From deae3e57bec9a568d3175e38f25dcc65388d9125 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 9 Jan 2021 00:10:11 +0100 Subject: [PATCH 1/5] Minor code tweaks --- .../IComputeShaderSourceGenerator.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index fa51f8ba..88c6e92c 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -78,7 +78,7 @@ namespace ComputeSharp.SourceGenerators var processedMembers = GetProcessedMembers(structDeclarationSymbol, discoveredTypes).ToArray(); var (entryPoint, localFunctions) = GetProcessedMethods(structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods); var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); - var processedMethods = localFunctions.Concat(staticMethods.Values.Select(static method => method.ToFullString())).ToArray(); + var processedMethods = localFunctions.Concat(staticMethods.Values).Select(static method => method.ToFullString()).ToArray(); // Create the compilation unit with the source attribute var source = @@ -140,7 +140,7 @@ namespace ComputeSharp.SourceGenerators /// The set of discovered and processed static methods. /// A sequence of processed methods in , and the entry point. [Pure] - private static (string EntryPoint, IEnumerable Methods) GetProcessedMethods( + private static (string EntryPoint, IEnumerable Methods) GetProcessedMethods( StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, SemanticModel semanticModel, @@ -154,7 +154,7 @@ namespace ComputeSharp.SourceGenerators select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); string? entryPoint = null; - List methods = new(); + List methods = new(); foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) { @@ -177,12 +177,12 @@ namespace ComputeSharp.SourceGenerators entryPoint = processedMethod.NormalizeWhitespace().ToFullString(); } - else methods.Add(processedMethod.NormalizeWhitespace().ToFullString()); + else methods.Add(processedMethod); // Emit the extracted local functions foreach (var localFunction in shaderSourceRewriter.LocalFunctions) { - methods.Add(localFunction.Value.NormalizeWhitespace().ToFullString()); + methods.Add(localFunction.Value); } } From b26fda5e8fbfd8baddeb9fee98d5383b48d3b3a1 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 9 Jan 2021 18:22:08 +0100 Subject: [PATCH 2/5] Added template method for GetDimensions(...) --- .../IComputeShaderSourceGenerator.cs | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index 88c6e92c..fb7f8dcb 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -226,6 +226,48 @@ namespace ComputeSharp.SourceGenerators .ToFullString(); } } + + /// + /// Creates a method to get a specific dimension size for a specified resource type. + /// + /// The input resource type (without generic parameters). + /// The type of items in the input resource. + /// The rank of the resource (must be 2 for structured buffers). + /// The target axis to get the dimension for. + /// A instance with the requested tree. + internal static MethodDeclarationSyntax CreateResourceDimensionAccessorMethod(string resourceType, string itemType, int rank, int axis) + { + // Create a static method to get a specified dimension for a target resource type. + // The method will automatically create the necessary number of temporary variables + // depending on the rank of the input resource (eg. 2 for Texture2D resources). + // For instance, this code will generate the following tree for Texture2D.Width: + // + // static int __get_Dimension0(Texture2D texture) + // { + // uint a, b; + // texture.GetDimensions(a, b); + // + // return a; + // } + return + MethodDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), $"__get_Dimension{axis}") + .AddModifiers(Token(SyntaxKind.StaticKeyword)) + .AddParameterListParameters( + Parameter(Identifier("resource")) + .WithType(GenericName(Identifier(resourceType)) + .AddTypeArgumentListArguments(IdentifierName(itemType)))) + .WithBody(Block( + LocalDeclarationStatement( + VariableDeclaration(PredefinedType(Token(SyntaxKind.UIntKeyword))) + .AddVariables(Enumerable.Range(0, rank).Select(static i => VariableDeclarator(Identifier(('a' + i).ToString()))).ToArray())), + ExpressionStatement( + InvocationExpression(MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("resource"), + IdentifierName("GetDimensions"))) + .AddArgumentListArguments(Enumerable.Range(0, rank).Select(static i => Argument(IdentifierName(('a' + i).ToString()))).ToArray())), + ReturnStatement(IdentifierName(('a' + axis).ToString())))); + } } } From e67d1161f3fc129c2f0c2246436bead4c256ed2c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 9 Jan 2021 19:38:27 +0100 Subject: [PATCH 3/5] Implemented support for GetDimensions properties --- .../IComputeShaderSourceGenerator.cs | 44 +------------- .../Mappings/HlslKnownMembers.cs | 44 ++++++++++++++ .../SyntaxRewriters/ShaderSourceRewriter.cs | 58 ++++++++++++++++++- 3 files changed, 102 insertions(+), 44 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index fb7f8dcb..3aa284ea 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -78,7 +78,7 @@ namespace ComputeSharp.SourceGenerators var processedMembers = GetProcessedMembers(structDeclarationSymbol, discoveredTypes).ToArray(); var (entryPoint, localFunctions) = GetProcessedMethods(structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods); var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); - var processedMethods = localFunctions.Concat(staticMethods.Values).Select(static method => method.ToFullString()).ToArray(); + var processedMethods = localFunctions.Concat(staticMethods.Values).Select(static method => method.NormalizeWhitespace().ToFullString()).ToArray(); // Create the compilation unit with the source attribute var source = @@ -226,48 +226,6 @@ namespace ComputeSharp.SourceGenerators .ToFullString(); } } - - /// - /// Creates a method to get a specific dimension size for a specified resource type. - /// - /// The input resource type (without generic parameters). - /// The type of items in the input resource. - /// The rank of the resource (must be 2 for structured buffers). - /// The target axis to get the dimension for. - /// A instance with the requested tree. - internal static MethodDeclarationSyntax CreateResourceDimensionAccessorMethod(string resourceType, string itemType, int rank, int axis) - { - // Create a static method to get a specified dimension for a target resource type. - // The method will automatically create the necessary number of temporary variables - // depending on the rank of the input resource (eg. 2 for Texture2D resources). - // For instance, this code will generate the following tree for Texture2D.Width: - // - // static int __get_Dimension0(Texture2D texture) - // { - // uint a, b; - // texture.GetDimensions(a, b); - // - // return a; - // } - return - MethodDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), $"__get_Dimension{axis}") - .AddModifiers(Token(SyntaxKind.StaticKeyword)) - .AddParameterListParameters( - Parameter(Identifier("resource")) - .WithType(GenericName(Identifier(resourceType)) - .AddTypeArgumentListArguments(IdentifierName(itemType)))) - .WithBody(Block( - LocalDeclarationStatement( - VariableDeclaration(PredefinedType(Token(SyntaxKind.UIntKeyword))) - .AddVariables(Enumerable.Range(0, rank).Select(static i => VariableDeclarator(Identifier(('a' + i).ToString()))).ToArray())), - ExpressionStatement( - InvocationExpression(MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("resource"), - IdentifierName("GetDimensions"))) - .AddArgumentListArguments(Enumerable.Range(0, rank).Select(static i => Argument(IdentifierName(('a' + i).ToString()))).ToArray())), - ReturnStatement(IdentifierName(('a' + axis).ToString())))); - } } } diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs index 45200de1..c2c58e37 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs @@ -31,6 +31,29 @@ namespace ComputeSharp.SourceGenerators.Mappings [$"ComputeSharp.IReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3" }; + /// + /// The mapping of supported known size accessors for HLSL resource types. + /// + private static readonly IReadOnlyDictionary KnownSizeAccessors = new Dictionary + { + ["ComputeSharp.Resources.Buffer`1.Length"] = (2, 0), + ["ComputeSharp.Resources.Texture2D`1.Width"] = (2, 0), + ["ComputeSharp.Resources.Texture2D`1.Height"] = (2, 1), + ["ComputeSharp.Resources.Texture3D`1.Width"] = (3, 0), + ["ComputeSharp.Resources.Texture3D`1.Height"] = (3, 1), + ["ComputeSharp.Resources.Texture3D`1.Depth"] = (3, 2), + ["ComputeSharp.IReadOnlyTexture2D`1.Width"] = (2, 0), + ["ComputeSharp.IReadOnlyTexture2D`1.Height"] = (2, 1), + ["ComputeSharp.IReadOnlyTexture3D`1.Width"] = (3, 0), + ["ComputeSharp.IReadOnlyTexture3D`1.Height"] = (3, 1), + ["ComputeSharp.IReadOnlyTexture3D`1.Depth"] = (3, 2), + ["ComputeSharp.IReadWriteTexture2D`1.Width"] = (2, 0), + ["ComputeSharp.IReadWriteTexture2D`1.Height"] = (2, 1), + ["ComputeSharp.IReadWriteTexture3D`1.Width"] = (3, 0), + ["ComputeSharp.IReadWriteTexture3D`1.Height"] = (3, 1), + ["ComputeSharp.IReadWriteTexture3D`1.Depth"] = (3, 2) + }; + /// /// The mapping of supported known members to HLSL names. /// @@ -193,5 +216,26 @@ namespace ComputeSharp.SourceGenerators.Mappings { return KnownIndexers.TryGetValue(name, out mapped); } + + /// + /// Tries to get the mapped HLSL-compatible indexer vector type name for the input indexer name. + /// + /// The input fully qualified indexer name. + /// The mapped type name, if one is found. + /// The HLSL-compatible type name that can be used in an HLSL shader for the given indexer. + [Pure] + public static bool TryGetAccessorRankAndAxis(string name, out int rank, out int axis) + { + if (KnownSizeAccessors.TryGetValue(name, out var info)) + { + (rank, axis) = info; + + return true; + } + + (rank, axis) = default((int, int)); + + return false; + } } } diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 0f089902..0c2e392d 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -306,7 +306,23 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters true => ParseExpression(mapping!), false => updatedNode.WithName(IdentifierName(mapping!)) }; - } + } + + // If the current member access is an access to any of the size properties in the available + // resource types (either buffer or texture types), then rewrite the subtree to transform the + // property access into an invocation of an autogenerated static helper method to get the target + // dimension for the buffer in use. The helper method is added to the list of static helpers. + if (operation is IPropertyReferenceOperation propertyOperation && + HlslKnownMembers.TryGetAccessorRankAndAxis(propertyOperation.Property.GetFullMetadataName(), out int rank, out int axis)) + { + INamedTypeSymbol resourceType = (INamedTypeSymbol)this.semanticModel.GetTypeInfo(node.Expression).Type!; + string resourceName = HlslKnownTypes.GetMappedName(resourceType); + MethodDeclarationSyntax methodSyntax = CreateResourceDimensionAccessorMethod(resourceName, rank, axis); + + this.staticMethods.Add(propertyOperation.Property.GetMethod!, methodSyntax); + + return InvocationExpression(IdentifierName(methodSyntax.Identifier)).AddArgumentListArguments(Argument(updatedNode.Expression)); + } } return updatedNode; @@ -416,5 +432,45 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters return updatedToken.WithoutTrivia(); } + + /// + /// Creates a method to get a specific dimension size for a specified resource type. + /// + /// The input resource type. + /// The rank of the resource (must be 2 for structured buffers). + /// The target axis to get the dimension for. + /// A instance with the requested tree. + private static MethodDeclarationSyntax CreateResourceDimensionAccessorMethod(string resourceType, int rank, int axis) + { + // Create a static method to get a specified dimension for a target resource type. + // The method will automatically create the necessary number of temporary variables + // depending on the rank of the input resource (eg. 2 for Texture2D resources). + // For instance, this code will generate the following tree for Texture2D.Width: + // + // static int __get_Dimension0(Texture2D texture) + // { + // uint _0, _1; + // texture.GetDimensions(_0, _1); + // + // return _0; + // } + return + MethodDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), $"__get_Dimension{axis}") + .AddModifiers(Token(SyntaxKind.StaticKeyword)) + .AddParameterListParameters( + Parameter(Identifier("resource")) + .WithType(IdentifierName(resourceType))) + .WithBody(Block( + LocalDeclarationStatement( + VariableDeclaration(PredefinedType(Token(SyntaxKind.UIntKeyword))) + .AddVariables(Enumerable.Range(0, rank).Select(static i => VariableDeclarator(Identifier("_" + i))).ToArray())), + ExpressionStatement( + InvocationExpression(MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("resource"), + IdentifierName("GetDimensions"))) + .AddArgumentListArguments(Enumerable.Range(0, rank).Select(static i => Argument(IdentifierName("_" + i))).ToArray())), + ReturnStatement(IdentifierName("_" + axis)))); + } } } From 81d04db13c46d5cd6747d91fc29a42931479c844 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 9 Jan 2021 19:43:48 +0100 Subject: [PATCH 4/5] Minor code refactoring, skipped repeated initialization --- .../SyntaxRewriters/ShaderSourceRewriter.cs | 82 +++++++++---------- 1 file changed, 38 insertions(+), 44 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 0c2e392d..d110eb45 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -315,11 +315,45 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters if (operation is IPropertyReferenceOperation propertyOperation && HlslKnownMembers.TryGetAccessorRankAndAxis(propertyOperation.Property.GetFullMetadataName(), out int rank, out int axis)) { - INamedTypeSymbol resourceType = (INamedTypeSymbol)this.semanticModel.GetTypeInfo(node.Expression).Type!; - string resourceName = HlslKnownTypes.GetMappedName(resourceType); - MethodDeclarationSyntax methodSyntax = CreateResourceDimensionAccessorMethod(resourceName, rank, axis); + IMethodSymbol key = propertyOperation.Property.GetMethod!; - this.staticMethods.Add(propertyOperation.Property.GetMethod!, methodSyntax); + if (!this.staticMethods.TryGetValue(key, out MethodDeclarationSyntax? methodSyntax)) + { + INamedTypeSymbol resourceType = (INamedTypeSymbol)this.semanticModel.GetTypeInfo(node.Expression).Type!; + string resourceName = HlslKnownTypes.GetMappedName(resourceType); + + // Create a static method to get a specified dimension for a target resource type. + // The method will automatically create the necessary number of temporary variables + // depending on the rank of the input resource (eg. 2 for Texture2D resources). + // For instance, this code will generate the following tree for Texture2D.Width: + // + // static int __get_Dimension0(Texture2D texture) + // { + // uint _0, _1; + // texture.GetDimensions(_0, _1); + // + // return _0; + // } + methodSyntax = + MethodDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), $"__get_Dimension{axis}") + .AddModifiers(Token(SyntaxKind.StaticKeyword)) + .AddParameterListParameters( + Parameter(Identifier("resource")) + .WithType(IdentifierName(resourceName))) + .WithBody(Block( + LocalDeclarationStatement( + VariableDeclaration(PredefinedType(Token(SyntaxKind.UIntKeyword))) + .AddVariables(Enumerable.Range(0, rank).Select(static i => VariableDeclarator(Identifier("_" + i))).ToArray())), + ExpressionStatement( + InvocationExpression(MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("resource"), + IdentifierName("GetDimensions"))) + .AddArgumentListArguments(Enumerable.Range(0, rank).Select(static i => Argument(IdentifierName("_" + i))).ToArray())), + ReturnStatement(IdentifierName("_" + axis)))); + + this.staticMethods.Add(key, methodSyntax); + } return InvocationExpression(IdentifierName(methodSyntax.Identifier)).AddArgumentListArguments(Argument(updatedNode.Expression)); } @@ -432,45 +466,5 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters return updatedToken.WithoutTrivia(); } - - /// - /// Creates a method to get a specific dimension size for a specified resource type. - /// - /// The input resource type. - /// The rank of the resource (must be 2 for structured buffers). - /// The target axis to get the dimension for. - /// A instance with the requested tree. - private static MethodDeclarationSyntax CreateResourceDimensionAccessorMethod(string resourceType, int rank, int axis) - { - // Create a static method to get a specified dimension for a target resource type. - // The method will automatically create the necessary number of temporary variables - // depending on the rank of the input resource (eg. 2 for Texture2D resources). - // For instance, this code will generate the following tree for Texture2D.Width: - // - // static int __get_Dimension0(Texture2D texture) - // { - // uint _0, _1; - // texture.GetDimensions(_0, _1); - // - // return _0; - // } - return - MethodDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), $"__get_Dimension{axis}") - .AddModifiers(Token(SyntaxKind.StaticKeyword)) - .AddParameterListParameters( - Parameter(Identifier("resource")) - .WithType(IdentifierName(resourceType))) - .WithBody(Block( - LocalDeclarationStatement( - VariableDeclaration(PredefinedType(Token(SyntaxKind.UIntKeyword))) - .AddVariables(Enumerable.Range(0, rank).Select(static i => VariableDeclarator(Identifier("_" + i))).ToArray())), - ExpressionStatement( - InvocationExpression(MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("resource"), - IdentifierName("GetDimensions"))) - .AddArgumentListArguments(Enumerable.Range(0, rank).Select(static i => Argument(IdentifierName("_" + i))).ToArray())), - ReturnStatement(IdentifierName("_" + axis)))); - } } } From 97722027e4cc606b7f72424b2c91ffa7a681014f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 9 Jan 2021 20:05:54 +0100 Subject: [PATCH 5/5] Code refactorings to image processing sample --- .../HlslBokehBlurProcessor{TPixel}.cs | 148 ++++-------------- .../HlslGaussianBlurProcessor{TPixel}.cs | 76 ++------- 2 files changed, 42 insertions(+), 182 deletions(-) diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs index 7fb37dd0..5ac36156 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; -using System.Diagnostics.Contracts; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -257,61 +256,38 @@ namespace ComputeSharp.BokehBlur.Processors Span span = MemoryMarshal.Cast(pixelSpan); - using ReadWriteTexture2D sourceTexture = Gpu.Default.AllocateReadWriteTexture2D(span, source.Width, source.Height); - using ReadWriteTexture2D processingTexture = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); - using ReadWriteTexture2D realTexture = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); - using ReadWriteTexture2D imaginaryTexture = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); - using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(KernelSize); + using ReadWriteTexture2D texture = Gpu.Default.AllocateReadWriteTexture2D(span, source.Width, source.Height); + using ReadWriteTexture2D temporary = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); + using ReadWriteTexture2D reals = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); + using ReadWriteTexture2D imaginaries = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); + using ReadOnlyBuffer kernel = Gpu.Default.AllocateReadOnlyBuffer(KernelSize); // Preliminary gamma highlight pass - ApplyGammaHighlight(sourceTexture); - - ref Vector4 param0 = ref MemoryMarshal.GetArrayDataReference(KernelParameters); + Gpu.Default.For(source.Height, new(texture)); // Perform two 1D convolutions for each component in the current instance for (int j = 0; j < Kernels.Length; j++) { - kernelBuffer.SetData(Kernels[j]); - Vector4 parameters = Unsafe.Add(ref param0, j); + Vector4 parameters = KernelParameters[j]; - ApplyVerticalConvolution(sourceTexture, realTexture, imaginaryTexture, kernelBuffer); - ApplyHorizontalConvolutionAndAccumulatePartials(realTexture, imaginaryTexture, processingTexture, kernelBuffer, parameters.Z, parameters.W); + kernel.SetData(Kernels[j]); + + Gpu.Default.For( + source.Width, + source.Height, + new(texture, reals, imaginaries, kernel)); + + Gpu.Default.For( + source.Width, + source.Height, + new(parameters.Z, parameters.W, reals, imaginaries, temporary, kernel)); } // Apply the inverse gamma exposure pass - ApplyInverseGammaExposure(processingTexture, sourceTexture); + Gpu.Default.For(source.Height, new(temporary, texture)); // Write the final pixel data - sourceTexture.GetData(span); - } - - /// - /// Performs a vertical 1D complex convolution with the specified parameters. - /// - /// The source to read data from. - /// The target to write the real results to. - /// The target to write the imaginary results to. - /// The with the values for the current complex kernel. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ApplyVerticalConvolution( - IReadWriteTexture2D source, - ReadWriteTexture2D reals, - ReadWriteTexture2D imaginaries, - ReadOnlyBuffer kernel) - { - int height = Source.Height; - int width = Source.Width; - - VerticalConvolutionProcessor shader = new( - maxY: height - 1, - maxX: width - 1, - kernelLength: kernel.Length, - source, - reals, - imaginaries, - kernel); - - Gpu.Default.For(width, height, in shader); + texture.GetData(span); } /// @@ -320,10 +296,6 @@ namespace ComputeSharp.BokehBlur.Processors [AutoConstructor] internal partial struct VerticalConvolutionProcessor : IComputeShader { - public int maxY; - public int maxX; - public int kernelLength; - public IReadWriteTexture2D source; public ReadWriteTexture2D reals; public ReadWriteTexture2D imaginaries; @@ -334,13 +306,15 @@ namespace ComputeSharp.BokehBlur.Processors { Vector4 real = Vector4.Zero; Vector4 imaginary = Vector4.Zero; + int maxY = source.Height; + int maxX = source.Width; + int kernelLength = kernel.Length; int radiusY = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; for (int i = 0; i < kernelLength; i++) { int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); + int offsetX = Hlsl.Clamp(ids.X, 0, maxX); Vector4 color = source[offsetX, offsetY]; Complex64 factors = kernel[i]; @@ -353,49 +327,12 @@ namespace ComputeSharp.BokehBlur.Processors } } - /// - /// Performs an horizontal 1D complex convolution with the specified parameters. - /// - /// The source to read the real results from. - /// The source to read the imaginary results from. - /// The with the values for the current complex kernel. - /// The weight factor for the real component of the complex pixel values. - /// The weight factor for the imaginary component of the complex pixel values. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ApplyHorizontalConvolutionAndAccumulatePartials( - ReadWriteTexture2D reals, - ReadWriteTexture2D imaginaries, - ReadWriteTexture2D target, - ReadOnlyBuffer kernel, - float z, - float w) - { - int height = Source.Height; - int width = Source.Width; - - HorizontalConvolutionAndAccumulatePartialsProcessor shader = new( - maxY: height - 1, - maxX: width - 1, - kernelLength: kernel.Length, - z, - w, - reals, - imaginaries, - target, - kernel); - - Gpu.Default.For(width, height, in shader); - } - /// /// Kernel for the horizontal convolution pass. /// [AutoConstructor] internal partial struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader { - public int maxY; - public int maxX; - public int kernelLength; public float z; public float w; @@ -409,13 +346,15 @@ namespace ComputeSharp.BokehBlur.Processors { Vector4 real = Vector4.Zero; Vector4 imaginary = Vector4.Zero; + int maxY = target.Height; + int maxX = target.Width; + int kernelLength = kernel.Length; int radiusX = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); for (int i = 0; i < kernelLength; i++) { - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX); + int offsetX = Hlsl.Clamp(ids.X + i - radiusX, 0, maxX); Vector4 sourceReal = reals[offsetX, offsetY]; Vector4 sourceImaginary = imaginaries[offsetX, offsetY]; Complex64 factors = kernel[i]; @@ -428,29 +367,19 @@ namespace ComputeSharp.BokehBlur.Processors } } - /// - /// Applies the gamma highlight pass to compute the final pixel values for a target image. - /// - /// The source instance to modify. - [Pure] - private void ApplyGammaHighlight(IReadWriteTexture2D source) - { - Gpu.Default.For(source.Height, new GammaHighlightProcessor(source.Width, source)); - } - /// /// Kernel for the gamma highlight pass. /// [AutoConstructor] internal readonly partial struct GammaHighlightProcessor : IComputeShader { - public readonly int width; - public readonly IReadWriteTexture2D source; /// public void Execute(ThreadIds ids) { + int width = source.Width; + for (int i = 0; i < width; i++) { Float4 v = source[i, ids.X]; @@ -462,33 +391,20 @@ namespace ComputeSharp.BokehBlur.Processors } } - /// - /// Applies the inverse gamma highlight pass to compute the final pixel values for a target image. - /// - /// The source instance to read from. - /// The target instance to write to. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ApplyInverseGammaExposure( - ReadWriteTexture2D source, - IReadWriteTexture2D target) - { - Gpu.Default.For(source.Height, new InverseGammaHighlightProcessor(source.Width, source, target)); - } - /// /// Kernel for the inverse gamma highlight pass. /// [AutoConstructor] internal readonly partial struct InverseGammaHighlightProcessor : IComputeShader { - public readonly int width; - public readonly ReadWriteTexture2D source; public readonly IReadWriteTexture2D target; /// public void Execute(ThreadIds ids) { + int width = source.Width; + for (int i = 0; i < width; i++) { Float4 v = source[i, ids.X]; diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs index bc72a6a8..0aad185e 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs @@ -98,48 +98,18 @@ namespace ComputeSharp.BokehBlur.Processors using ReadWriteTexture2D firstPassTexture = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(Kernel); - ApplyVerticalConvolution(sourceTexture, firstPassTexture, kernelBuffer); - ApplyHorizontalConvolution(firstPassTexture, sourceTexture, kernelBuffer); + Gpu.Default.For(source.Width, source.Height, new(sourceTexture, firstPassTexture, kernelBuffer)); + Gpu.Default.For(source.Width, source.Height, new(firstPassTexture, sourceTexture, kernelBuffer)); sourceTexture.GetData(span); } - /// - /// Performs a vertical 1D complex convolution with the specified parameters. - /// - /// The source to read data from. - /// The target to write the results to. - /// The with the values for the current complex kernel. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ApplyVerticalConvolution( - IReadWriteTexture2D source, - ReadWriteTexture2D target, - ReadOnlyBuffer kernel) - { - int height = Source.Height; - int width = Source.Width; - - VerticalConvolutionProcessor shader = new( - maxY: height - 1, - maxX: width - 1, - kernel.Length, - source, - target, - kernel); - - Gpu.Default.For(width, height, in shader); - } - /// /// Kernel for the vertical convolution pass. /// [AutoConstructor] internal readonly partial struct VerticalConvolutionProcessor : IComputeShader { - public readonly int maxY; - public readonly int maxX; - public readonly int kernelLength; - public readonly IReadWriteTexture2D source; public readonly ReadWriteTexture2D target; public readonly ReadOnlyBuffer kernel; @@ -148,13 +118,15 @@ namespace ComputeSharp.BokehBlur.Processors public void Execute(ThreadIds ids) { Vector4 result = Vector4.Zero; + int maxY = source.Height - 1; + int maxX = source.Width - 1; + int kernelLength = kernel.Length; int radiusY = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; for (int i = 0; i < kernelLength; i++) { int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); + int offsetX = Hlsl.Clamp(ids.X, 0, maxX); Vector4 color = source[offsetX, offsetY]; result += kernel[i] * color; @@ -164,42 +136,12 @@ namespace ComputeSharp.BokehBlur.Processors } } - /// - /// Performs an horizontal 1D complex convolution with the specified parameters. - /// - /// The source to read data from. - /// The target to write the results to. - /// The with the values for the current complex kernel. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ApplyHorizontalConvolution( - ReadWriteTexture2D source, - IReadWriteTexture2D target, - ReadOnlyBuffer kernel) - { - int height = Source.Height; - int width = Source.Width; - - HorizontalConvolutionProcessor shader = new( - maxY: height - 1, - maxX: width - 1, - kernel.Length, - source, - target, - kernel); - - Gpu.Default.For(width, height, in shader); - } - /// /// Kernel for the horizontal convolution pass. /// [AutoConstructor] internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader { - public readonly int maxY; - public readonly int maxX; - public readonly int kernelLength; - public readonly ReadWriteTexture2D source; public readonly IReadWriteTexture2D target; public readonly ReadOnlyBuffer kernel; @@ -208,13 +150,15 @@ namespace ComputeSharp.BokehBlur.Processors public void Execute(ThreadIds ids) { Vector4 result = Vector4.Zero; + int maxY = source.Height - 1; + int maxX = source.Width - 1; + int kernelLength = kernel.Length; int radiusX = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); for (int i = 0; i < kernelLength; i++) { - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX); + int offsetX = Hlsl.Clamp(ids.X + i - radiusX, 0, maxX); Vector4 color = source[offsetX, offsetY]; result += kernel[i] * color;