diff --git a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj index 66a98d68..3b059c63 100644 --- a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj +++ b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj @@ -8,17 +8,10 @@ - - - - Never - - - diff --git a/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs new file mode 100644 index 00000000..822c95d2 --- /dev/null +++ b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs @@ -0,0 +1,245 @@ +using System; +using System.Buffers; +using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; +using ComputeSharp.Shaders.Renderer.Models; +using ComputeSharp.Shaders.Renderer.Models.Fields; + +namespace ComputeSharp.Shaders.Renderer +{ + /// + /// A type that renders an HLSL template from the previously loaded shader data. + /// + internal static class HlslShaderRenderer + { + /// + /// Renders a new HLSL shader source with the given parameters + /// + /// The input instance with the shader information + /// The source code for the new HLSL shader + [Pure] + public static ArrayPoolStringBuilder Render(ShaderInfo info) + { + var builder = ArrayPoolStringBuilder.Create(); + + // Header + builder.AppendLine("// ================================================"); + builder.AppendLine("// AUTO GENERATED"); + builder.AppendLine("// ================================================"); + builder.AppendLine("// This shader was created by ComputeSharp."); + builder.AppendLine("// See: https://github.com/Sergio0694/ComputeSharp."); + builder.AppendLine(); + + // Captured variables + builder.AppendLine("cbuffer _ : register(b0)"); + builder.AppendLine('{'); + builder.AppendLine(" uint __x;"); + builder.AppendLine(" uint __y;"); + builder.AppendLine(" uint __z;"); + + foreach (var local in info.FieldsList) + { + builder.Append(" "); + builder.Append(local.FieldType); + builder.Append(' '); + builder.AppendLine(local.FieldName); + } + + builder.AppendLine('}'); + + // Buffers + foreach (var buffer in info.BuffersList) + { + builder.AppendLine(); + + switch (buffer) + { + // Constant buffer go to cbuffer fields with a dummy local + case ConstantBufferFieldInfo _: + builder.Append("cbuffer _"); + builder.Append(buffer.FieldName); + builder.Append(" : register(b"); + builder.Append(buffer.BufferIndex.ToString()); + builder.AppendLine(')'); + builder.AppendLine('{'); + builder.Append(" "); + builder.Append(buffer.FieldType); + builder.Append(' '); + builder.Append(buffer.FieldName); + builder.Append("[2];"); + builder.AppendLine('}'); + break; + + // Structured buffer have the same syntax but different id + case ReadOnlyBufferFieldInfo _: + char registerId = 't'; + goto StructuredBuffer; + case ReadWriteBufferFieldInfo _: + registerId = 'u'; + StructuredBuffer: + builder.Append(buffer.FieldType); + builder.Append(' '); + builder.Append(buffer.FieldName); + builder.Append(" : register("); + builder.Append(registerId); + builder.Append(buffer.BufferIndex.ToString()); + builder.AppendLine(");"); + break; + } + } + + // Entry point + builder.AppendLine(); + builder.Append("[NumThreads("); + builder.Append(info.NumThreadsX.ToString()); + builder.Append(", "); + builder.Append(info.NumThreadsY.ToString()); + builder.Append(", "); + builder.Append(info.NumThreadsZ.ToString()); + builder.AppendLine(")]"); + builder.AppendLine(info.EntryPoint); + + return builder; + } + + /// + /// A helper type that implements a pooled buffer writer for values. + /// + public ref struct ArrayPoolStringBuilder + { + /// + /// The underlying array. + /// + private char[] array; + + /// + /// The starting offset within . + /// + private int index; + + /// + /// Creates a new instance ready to use. + /// + /// A new instance with default values. + [Pure] + public static ArrayPoolStringBuilder Create() + { + ArrayPoolStringBuilder builder; + + builder.array = ArrayPool.Shared.Rent(1024); + builder.index = 0; + + return builder; + } + + /// + public ReadOnlySpan WrittenSpan + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new(this.array, 0, this.index); + } + + /// + /// Appends the input sequence of characters to the current buffer. + /// + /// The input characters to write. + public void Append(ReadOnlySpan value) + { + EnsureCapacity(value.Length); + + value.CopyTo(this.array.AsSpan(this.index)); + + this.index += value.Length; + } + + /// + /// Appends a character to the current buffer. + /// + public void Append(char character) + { + EnsureCapacity(1); + + this.array[this.index++] = character; + } + + /// + /// Appends the input sequence of characters to the current buffer, with a trailing new line. + /// + /// The input characters to write. + public void AppendLine(ReadOnlySpan value) + { + EnsureCapacity(value.Length + 1); + + value.CopyTo(this.array.AsSpan(this.index)); + + this.index += value.Length; + + this.array[this.index++] = '\n'; + } + + /// + /// Appends a character and a new line to the current buffer. + /// + public void AppendLine(char character) + { + EnsureCapacity(2); + + this.array[this.index++] = character; + this.array[this.index++] = '\n'; + } + + /// + /// Appends a new line to the current buffer. + /// + public void AppendLine() + { + EnsureCapacity(1); + + this.array[this.index++] = '\n'; + } + + /// + /// Ensures that has enough free space to contain a given number of new items. + /// + /// The minimum number of items to ensure space for in . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void EnsureCapacity(int requestedSize) + { + if (requestedSize > this.array.Length - this.index) + { + ResizeBuffer(requestedSize); + } + } + + /// + /// Resizes to ensure it can fit the specified number of new items. + /// + /// The minimum number of items to ensure space for in . + [MethodImpl(MethodImplOptions.NoInlining)] + private void ResizeBuffer(int sizeHint) + { + int minimumSize = this.index + sizeHint; + + // Rent a new array with the specified size, and copy as many items from the current array + // as possible to the new array. This mirrors the behavior of the Array.Resize API from + // the BCL: if the new size is greater than the length of the current array, copy all the + // items from the original array into the new one. Otherwise, copy as many items as possible, + // until the new array is completely filled, and ignore the remaining items in the first array. + char[] newArray = ArrayPool.Shared.Rent(minimumSize); + int itemsToCopy = Math.Min(this.array.Length, minimumSize); + + Array.Copy(this.array, 0, newArray, 0, itemsToCopy); + + ArrayPool.Shared.Return(array); + + this.array = newArray; + } + + /// + public void Dispose() + { + ArrayPool.Shared.Return(this.array); + } + } + } +} diff --git a/src/ComputeSharp.Shaders/Renderer/ShaderRenderer.cs b/src/ComputeSharp.Shaders/Renderer/ShaderRenderer.cs deleted file mode 100644 index e7a5df56..00000000 --- a/src/ComputeSharp.Shaders/Renderer/ShaderRenderer.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System.Diagnostics.Contracts; -using System.IO; -using System.Linq; -using System.Reflection; -using ComputeSharp.Shaders.Renderer.Models; -using Stubble.Core; - -namespace ComputeSharp.Shaders.Renderer -{ - /// - /// A that uses the mustache templating system to render HLSL shaders - /// - internal sealed class ShaderRenderer - { - /// - /// Gets the singleton instance to use - /// - public static ShaderRenderer Instance { get; } = new ShaderRenderer(); - - /// - /// Creates a new instance and loads the mustache template to use - /// - private ShaderRenderer() - { - Assembly assembly = Assembly.GetExecutingAssembly(); - string filename = assembly.GetManifestResourceNames().First(name => name.EndsWith("ShaderTemplate.mustache")); - - using Stream stream = assembly.GetManifestResourceStream(filename)!; - using StreamReader reader = new StreamReader(stream); - - Template = reader.ReadToEnd(); - } - - /// - /// Gets the mustache template used by the shader renderer - /// - public string Template { get; } - - /// - /// Renders a new HLSL shader source with the given parameters - /// - /// The input instance with the shader information - /// The source code for the new HLSL shader - [Pure] - public string Render(ShaderInfo info) => StaticStubbleRenderer.Render(Template, info); - } -} diff --git a/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache b/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache deleted file mode 100644 index 499ced69..00000000 --- a/src/ComputeSharp.Shaders/Renderer/Templates/ShaderTemplate.mustache +++ /dev/null @@ -1,53 +0,0 @@ -// ================================================ -// AUTO GENERATED -// ================================================ -// This shader was created by ComputeSharp. -// See: https://github.com/Sergio0694/ComputeSharp. - -{{!Captured variables buffer}} -cbuffer _ : register(b0) -{ - uint __x; - uint __y; - uint __z; -{{#FieldsList}} - {{&FieldType}} {{FieldName}}; -{{/FieldsList}} -} -{{#BuffersList}} -{{#IsConstantBuffer}} - -{{!Constant buffer}} -cbuffer _{{FieldName}} : register(b{{BufferIndex}}) -{ - {{&FieldType}} {{FieldName}}[2]; -} -{{/IsConstantBuffer}} -{{#IsReadOnlyBuffer}} - -{{!Readonly buffer}} -{{&FieldType}} {{FieldName}} : register(t{{BufferIndex}}); -{{/IsReadOnlyBuffer}} -{{#IsReadWriteBuffer}} - -{{!Read write buffer}} -{{&FieldType}} {{FieldName}} : register(u{{BufferIndex}}); -{{/IsReadWriteBuffer}} -{{/BuffersList}} -{{#FunctionsList}} - -{{!Shader private functions}} -// {{FunctionCsharpReturnType}} {{&FunctionFullName}}({{FunctionCsharpParameters}}) -{{ReturnType}} {{FunctionName}}({{#ParametersList}}{{ParameterModifier}} {{ParameterType}} {{ParameterName}}{{^IsLastParameter}}, {{/IsLastParameter}}{{/ParametersList}}) -{{FunctionBody}} -{{/FunctionsList}} -{{#LocalFunctionsList}} - -{{!Shader implicit functions}} -// {{FunctionPrototype}} -{{FunctionDeclaration}} -{{/LocalFunctionsList}} - -{{!Shader entry point}} -[NumThreads({{NumThreadsX}}, {{NumThreadsY}}, {{NumThreadsZ}})] -{{&EntryPoint}}