Merge pull request #35 from Sergio0694/feature_captured-scopes

Captured scopes support
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2019-08-23 19:40:26 +02:00
コミット a03963667a
3ファイル変更
+162 -48

検索条件に一致するファイルはありません

+26 -24
ファイルの表示
@@ -79,40 +79,42 @@ namespace ComputeSharp.BokehBlur
for (int j = 0; j < diameter; j++)
kernel[i * diameter + j] /= ones;
// Apply the effect
Console.WriteLine(">> Applying effect");
using ReadOnlyBuffer<Vector4> image_gpu = Gpu.Default.AllocateReadOnlyBuffer(vectorArray);
using ReadOnlyBuffer<float> kernel_gpu = Gpu.Default.AllocateReadOnlyBuffer(kernel);
using ReadWriteBuffer<Vector4> result_gpu = Gpu.Default.AllocateReadWriteBuffer<Vector4>(vectorArray.Length);
Gpu.Default.For(height, width, id =>
using (ReadOnlyBuffer<Vector4> image_gpu = Gpu.Default.AllocateReadOnlyBuffer(vectorArray))
using (ReadOnlyBuffer<float> kernel_gpu = Gpu.Default.AllocateReadOnlyBuffer(kernel))
using (ReadWriteBuffer<Vector4> result_gpu = Gpu.Default.AllocateReadWriteBuffer<Vector4>(vectorArray.Length))
{
Vector4 total = Vector4.Zero;
for (int y = -Radius; y <= Radius; y++)
// Apply the effect
Gpu.Default.For(height, width, id =>
{
for (int x = -Radius; x <= Radius; x++)
Vector4 total = Vector4.Zero;
for (int y = -Radius; y <= Radius; y++)
{
int iy = (int)id.X + y;
int jx = (int)id.Y + x;
for (int x = -Radius; x <= Radius; x++)
{
int iy = (int)id.X + y;
int jx = (int)id.Y + x;
if (iy < 0) iy = -iy;
else if (iy > height) iy = 2 * height - iy;
if (jx < 0) jx = -jx;
else if (jx > width) jx = 2 * width - jx;
if (iy < 0) iy = -iy;
else if (iy > height) iy = 2 * height - iy;
if (jx < 0) jx = -jx;
else if (jx > width) jx = 2 * width - jx;
int ki = Radius - y;
int kj = Radius - x;
int ki = Radius - y;
int kj = Radius - x;
total += image_gpu[(uint)(iy * width + jx)] * kernel_gpu[(uint)(ki * diameter + kj)];
total += image_gpu[(uint)(iy * width + jx)] * kernel_gpu[(uint)(ki * diameter + kj)];
}
}
}
result_gpu[(uint)(id.X * width + id.Y)] = total;
});
result_gpu[(uint)(id.X * width + id.Y)] = total;
});
// Copy data back
Console.WriteLine(">> Copying data back");
result_gpu.GetData(vectorArray);
// Copy data back
Console.WriteLine(">> Copying data back");
result_gpu.GetData(vectorArray);
}
// Copy the modified image back
Console.WriteLine(">> Storing pixel data");
+91 -15
ファイルの表示
@@ -6,6 +6,7 @@ using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Text;
using System.Text.RegularExpressions;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.CSharp;
@@ -99,6 +100,25 @@ namespace ComputeSharp.Shaders.Translation
}
}
/// <summary>
/// Creates a new <see cref="CSharpDecompiler"/> instance targeting a given assembly
/// </summary>
/// <param name="assemblyPath">The path of the assembly to decompile</param>
/// <returns>A <see cref="CSharpDecompiler"/> instance that can be used on the targeted assembly</returns>
[Pure]
private static CSharpDecompiler CreateDecompiler(string assemblyPath)
{
DecompilerSettings decompilerSettings = new DecompilerSettings(ICSharpCode.Decompiler.CSharp.LanguageVersion.Latest)
{
ObjectOrCollectionInitializers = false,
UsingDeclarations = false,
CSharpFormattingOptions = { IndentationString = IndentedTextWriter.DefaultTabString }
};
UniversalAssemblyResolver resolver = new UniversalAssemblyResolver(assemblyPath, false, "netstandard");
return new CSharpDecompiler(assemblyPath, resolver, decompilerSettings);
}
/// <summary>
/// A <see cref="Regex"/> used to preprocess the closure type declarations for both lambda expressions and local methods
/// </summary>
@@ -149,8 +169,11 @@ namespace ComputeSharp.Shaders.Translation
methodFixedCode = methodFixedCode.Insert(lastClosedBracketsIndex, methodOnlyIndentedSourceCode);
}
// Unwrap the nested fields
string unwrappedCode = UnwrapSyntaxTree(methodFixedCode);
// Load the type syntax tree
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(methodFixedCode);
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(unwrappedCode);
// Get the root node to return
rootNode = syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First(node => node.GetLeadingTrivia().ToFullString().Contains(methodInfo.Name));
@@ -162,22 +185,75 @@ namespace ComputeSharp.Shaders.Translation
}
/// <summary>
/// Creates a new <see cref="CSharpDecompiler"/> instance targeting a given assembly
/// A <see cref="Regex"/> used to find fields that represent nested closure types
/// </summary>
/// <param name="assemblyPath">The path of the assembly to decompile</param>
/// <returns>A <see cref="CSharpDecompiler"/> instance that can be used on the targeted assembly</returns>
[Pure]
private static CSharpDecompiler CreateDecompiler(string assemblyPath)
{
DecompilerSettings decompilerSettings = new DecompilerSettings(ICSharpCode.Decompiler.CSharp.LanguageVersion.Latest)
{
ObjectOrCollectionInitializers = false,
UsingDeclarations = false,
CSharpFormattingOptions = { IndentationString = IndentedTextWriter.DefaultTabString }
};
private static readonly Regex NestedClosureFieldRegex = new Regex(@"(?<=public )((?:\w+\.)+<>[\w_]+) (CS\$<>[\w_]+)(?=;)", RegexOptions.Compiled);
UniversalAssemblyResolver resolver = new UniversalAssemblyResolver(assemblyPath, false, "netstandard");
return new CSharpDecompiler(assemblyPath, resolver, decompilerSettings);
/// <summary>
/// A <see cref="Regex"/> used to identify compiler generated fields
/// </summary>
private static readonly Regex CompilerGeneratedFieldRegex = new Regex(@"CS\$<>[\w_]+\.", RegexOptions.Compiled);
/// <summary>
/// Unwraps all the nested captured fields in the given source code, moving them to the top level
/// </summary>
/// <param name="source">The input source code to process</param>
[Pure]
private string UnwrapSyntaxTree(string source)
{
List<FieldDeclarationSyntax> parsedFields = new List<FieldDeclarationSyntax>();
// Local function to recursively extract all the nested fields
void ParseNestedFields(string source)
{
// Find the field declarations
Match match = NestedClosureFieldRegex.Match(source);
if (!match.Success) return;
// Load the nested closure type
string fullname = match.Groups[1].Value.Replace(".<>", "+<>"); // Fullname of a nested type
Type type = AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetType(fullname)).First(t => t != null);
// Decompile the type and get a readable source code
EntityHandle typeHandle = MetadataTokenHelpers.TryAsEntityHandle(type.MetadataToken) ?? throw new InvalidOperationException();
CSharpDecompiler decompiler = Decompilers[type.Assembly.Location];
string
sourceCode = decompiler.DecompileAsString(typeHandle),
typeFixedCode = ClosureTypeDeclarationRegex.Replace(sourceCode, "Scope");
// Load the syntax tree and retrieve the list of fields
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(typeFixedCode);
FieldDeclarationSyntax[] fields = syntaxTree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().First().ChildNodes().OfType<FieldDeclarationSyntax>().ToArray();
// Add the captured fields
foreach (FieldDeclarationSyntax field in fields)
if (!field.Declaration.Variables.ToFullString().StartsWith("CS$<>"))
parsedFields.Add(field);
// Explore the new decompiled type
ParseNestedFields(typeFixedCode);
}
ParseNestedFields(source);
if (parsedFields.Count > 0)
{
// Build the aggregated string with all the captured fields
StringBuilder builder = new StringBuilder();
foreach (FieldDeclarationSyntax field in parsedFields)
builder.AppendLine(field.ToFullString());
string fields = builder.ToString().TrimEnd(' ', '\r', '\n');
// Replace the field declarations
Match match = NestedClosureFieldRegex.Match(source);
source = source.Remove(match.Index - 11, match.Length + 12); // leading " public " and trailing ";"
source = source.Insert(match.Index - 11, fields);
// Adjust the method body to remove references to compiler generated fields
source = CompilerGeneratedFieldRegex.Replace(source, string.Empty);
}
return source;
}
}
}
+45 -9
ファイルの表示
@@ -72,24 +72,46 @@ namespace ComputeSharp.Shaders.Translation
/// <summary>
/// The <see cref="List{T}"/> of <see cref="ReadableMember"/> instances mapping the captured buffers in the current shader
/// </summary>
private readonly List<ReadableMember> _BufferMembers = new List<ReadableMember>();
private readonly List<(ReadableMember Member, IEnumerable<ReadableMember>? Parents)> _BufferMembers = new List<(ReadableMember, IEnumerable<ReadableMember>?)>();
/// <summary>
/// Gets the ordered collection of buffers used as fields in the current shader
/// </summary>
/// <param name="action">The <see cref="Action{T}"/> to use to build the shader</param>
public IEnumerable<(int Index, GraphicsResource Resource)> GetBuffers(Action<ThreadIds> action) => _BufferMembers.Select((field, i) => (i + 1, (GraphicsResource)field.GetValue(action.Target)));
public IEnumerable<(int Index, GraphicsResource Resource)> GetBuffers(Action<ThreadIds> action)
{
foreach (var (item, i) in _BufferMembers.Select((item, i) => (item, i)))
{
if (item.Parents == null) yield return (i + 1, (GraphicsResource)item.Member.GetValue(action.Target));
else
{
object target = item.Parents.Aggregate(action.Target, (obj, member) => member.GetValue(obj));
yield return (i + 1, (GraphicsResource)item.Member.GetValue(target));
}
}
}
/// <summary>
/// The <see cref="List{T}"/> of <see cref="ReadableMember"/> instances mapping the captured scalar/vector variables in the current shader
/// </summary>
private readonly List<ReadableMember> _VariableMembers = new List<ReadableMember>();
private readonly List<(ReadableMember Member, IEnumerable<ReadableMember>? Parents)> _VariableMembers = new List<(ReadableMember, IEnumerable<ReadableMember>?)>();
/// <summary>
/// Gets the collection of values of the captured fields for the current shader
/// </summary>
/// <param name="action">The <see cref="Action{T}"/> to use to build the shader</param>
public IEnumerable<object> GetVariables(Action<ThreadIds> action) => _VariableMembers.Select(field => field.GetValue(action.Target));
public IEnumerable<object> GetVariables(Action<ThreadIds> action)
{
foreach (var item in _VariableMembers)
{
if (item.Parents == null) yield return item.Member.GetValue(action.Target);
else
{
object target = item.Parents.Aggregate(action.Target, (obj, member) => member.GetValue(obj));
yield return item.Member.GetValue(target);
}
}
}
private readonly List<HlslBufferInfo> _BuffersList = new List<HlslBufferInfo>();
@@ -154,7 +176,8 @@ namespace ComputeSharp.Shaders.Translation
/// </summary>
/// <param name="memberInfo">The target <see cref="ReadableMember"/> to load</param>
/// <param name="name">The optional explicit name to use for the field</param>
private void LoadFieldInfo(ReadableMember memberInfo, string? name = null)
/// <param name="parents">The list of parent fields to reach the current <see cref="ReadableMember"/> from a given <see cref="Action{T}"/></param>
private void LoadFieldInfo(ReadableMember memberInfo, string? name = null, IReadOnlyList<ReadableMember>? parents = null)
{
Type fieldType = memberInfo.MemberType;
string fieldName = HlslKnownKeywords.GetMappedName(name ?? memberInfo.Name);
@@ -165,7 +188,7 @@ namespace ComputeSharp.Shaders.Translation
DescriptorRanges.Add(new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, _ConstantBuffersCount));
// Track the buffer field
_BufferMembers.Add(memberInfo);
_BufferMembers.Add((memberInfo, parents));
string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]);
_BuffersList.Add(new ConstantBufferFieldInfo(fieldType, typeName, fieldName, _ConstantBuffersCount++));
@@ -176,7 +199,7 @@ namespace ComputeSharp.Shaders.Translation
DescriptorRanges.Add(new DescriptorRange(DescriptorRangeType.ShaderResourceView, 1, _ReadOnlyBuffersCount));
// Track the buffer field
_BufferMembers.Add(memberInfo);
_BufferMembers.Add((memberInfo, parents));
string typeName = HlslKnownTypes.GetMappedName(fieldType);
_BuffersList.Add(new ReadOnlyBufferFieldInfo(fieldType, typeName, fieldName, _ReadOnlyBuffersCount++));
@@ -187,7 +210,7 @@ namespace ComputeSharp.Shaders.Translation
DescriptorRanges.Add(new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, _ReadWriteBuffersCount));
// Track the buffer field
_BufferMembers.Add(memberInfo);
_BufferMembers.Add((memberInfo, parents));
string typeName = HlslKnownTypes.GetMappedName(fieldType);
_BuffersList.Add(new ReadWriteBufferFieldInfo(fieldType, typeName, fieldName, _ReadWriteBuffersCount++));
@@ -195,10 +218,23 @@ namespace ComputeSharp.Shaders.Translation
else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType))
{
// Register the captured field
_VariableMembers.Add(memberInfo);
_VariableMembers.Add((memberInfo, parents));
string typeName = HlslKnownTypes.GetMappedName(fieldType);
_FieldsList.Add(new CapturedFieldInfo(fieldType, typeName, fieldName));
}
else if (fieldType.IsClass && fieldName.StartsWith("CS$<>"))
{
// Captured scope, update the parents list
List<ReadableMember> updatedParents = parents?.ToList() ?? new List<ReadableMember>();
updatedParents.Add(memberInfo);
// Recurse on the new compiler generated class
IReadOnlyList<FieldInfo> fields = fieldType.GetFields().ToArray();
foreach (FieldInfo fieldInfo in fields)
{
LoadFieldInfo(fieldInfo, null, updatedParents);
}
}
}
/// <summary>