Merge pull request #69 from Sergio0694/feature/shader-structs

Shader structs, minor optimizations
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2020-06-14 17:53:30 +02:00
コミット ef8d18ece6
48ファイル変更
+1725 -965

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

+52 -14
ファイルの表示
@@ -31,11 +31,27 @@ More details available [here](https://www.nuget.org/packages/ComputeSharp/).
The following sample shows how to allocate a writeable buffer, populate it with a compute shader, and read it back.
```C#
// Define a simple shader
public readonly struct MyShader : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
public MyShader(ReadWriteBuffer<float> buffer)
{
this.buffer = buffer;
}
public void Execute(ThreadIds ids)
{
buffer[ids.X] = ids.X;
}
}
// Allocate a writeable buffer on the GPU, with the contents of the array
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1000);
// Run the shader
Gpu.Default.For(1000, id => buffer[id.X] = id.X);
Gpu.Default.For(1000, new MyShader(buffer));
// Get the data back
float[] array = buffer.GetData();
@@ -69,9 +85,41 @@ There are a number of extension APIs for the `GraphicsDevice` class that can be
## Advanced usage
**ComputeSharp** lets you dispatch compute shaders over thread groups from 1 to 3 dimensions, includes supports for constant and readonly buffers, and more. The shader body can both be declared inline, as a separate `Action<ThreadIds>` or as a local method. Additionally, most of the [HLSL intrinsic functions](https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-intrinsic-functions) are available through the `Hlsl` class. Here is a more advanced sample showcasing all these features.
**ComputeSharp** lets you dispatch compute shaders over thread groups from 1 to 3 dimensions, includes supports for constant and readonly buffers, and more. Additionally, most of the [HLSL intrinsic functions](https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-intrinsic-functions) are available through the `Hlsl` class. Here is a more advanced sample showcasing all these features.
```C#
// Define a class with some utility static functions
public static class Activations
{
public static float Sigmoid(float x) => 1 / (1 + Hlsl.Exp(-x));
}
// Define the shader
public readonly struct ActivationShader : IComputeShader
{
private readonly int width;
public readonly ReadOnlyBuffer<float> x;
public readonly ReadWriteBuffer<float> y;
public ActivationShader(
int width,
ReadOnlyBuffer<float> x,
ReadWriteBuffer<float> y)
{
this.width = width;
this.x = x;
this.y = y;
}
public void Execute(ThreadIds ids)
{
int offset = ids.X + ids.Y * width;
float pow = Hlsl.Pow(x[offset], 2);
y[offset] = Activations.Sigmoid(pow);
}
}
int height = 10, width = 10;
float[] x = new float[height * width]; // Array to sum to y
float[] y = new float[height * width]; // Result array (assume both had some values)
@@ -79,18 +127,8 @@ float[] y = new float[height * width]; // Result array (assume both had some val
using ReadOnlyBuffer<float> xBuffer = Gpu.Default.AllocateReadOnlyBuffer(x);
using ReadWriteBuffer<float> yBuffer = Gpu.Default.AllocateReadWriteBuffer(y);
static float Sigmoid(float x) => 1 / (1 + Hlsl.Exp(-x));
// Shader body
void Kernel(ThreadIds id)
{
int offset = id.X + id.Y * width;
float pow = Hlsl.Pow(xBuffer[offset], 2);
yBuffer[offset] = Sigmoid(pow);
}
// Run the shader
Gpu.Default.For(width, height, Kernel);
Gpu.Default.For(width, height, new ActivationShader(width, xBuffer, yBuffer));
// Get the data back and write it to the y array
yBuffer.GetData(y);
@@ -102,7 +140,7 @@ The **ComputeSharp** library requires .NET Standard 2.1 support, and it is avail
- .NET Core >= 3.0
- Windows (x86 or x64)
Additionally, you need an IDE with .NET Core 3.0 and C# 8.0 support to compile the library and samples on your PC.
Additionally, you need an IDE with .NET Core 3.1 and C# 8.0 support to compile the library and samples on your PC.
# Special thanks
+2 -2
ファイルの表示
@@ -2,11 +2,11 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.11.5" />
<PackageReference Include="BenchmarkDotNet" Version="0.12.1" />
</ItemGroup>
<ItemGroup>
+43 -7
ファイルの表示
@@ -61,24 +61,60 @@ namespace ComputeSharp.Benchmark
/// <param name="w">The weights tensor</param>
/// <param name="b">The bias tensor</param>
/// <param name="y">The result tensor</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void FullyConnectedForwardGpu(
int c, int n, int m, int p,
ReadOnlyBuffer<float> x, ReadOnlyBuffer<float> w, ReadOnlyBuffer<float> b, ReadWriteBuffer<float> y)
{
void Kernel(ThreadIds id)
Gpu.Default.For(c, n, p, new FullyConnectedForwardKernel(n, m, p, x, w, b, y));
}
/// <summary>
/// Kernel for <see cref="FullyConnectedForwardGpu"/>
/// </summary>
private readonly struct FullyConnectedForwardKernel : IComputeShader
{
private readonly int n;
private readonly int m;
private readonly int p;
private readonly ReadOnlyBuffer<float> x;
private readonly ReadOnlyBuffer<float> w;
private readonly ReadOnlyBuffer<float> b;
private readonly ReadWriteBuffer<float> y;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public FullyConnectedForwardKernel(
int n,
int m,
int p,
ReadOnlyBuffer<float> x,
ReadOnlyBuffer<float> w,
ReadOnlyBuffer<float> b,
ReadWriteBuffer<float> y)
{
int x_offset = id.X * n * p + id.Y * m;
this.n = n;
this.m = m;
this.p = p;
this.x = x;
this.w = w;
this.b = b;
this.y = y;
}
/// <inheritdoc/>
public void Execute(ThreadIds ids)
{
int x_offset = ids.X * n * p + ids.Y * m;
float result = 0f;
for (int k = 0; k < m; k++)
{
result += x[x_offset + k] * w[k * p + id.Z];
result += x[x_offset + k] * w[k * p + ids.Z];
}
y[id.X * n * p + id.Y * p + id.Z] = result + b[id.Z];
};
Gpu.Default.For(c, n, p, Kernel);
y[ids.X * n * p + ids.Y * p + ids.Z] = result + b[ids.Z];
}
}
}
}
+1 -1
ファイルの表示
@@ -130,7 +130,7 @@ namespace ComputeSharp.Benchmark
/// <summary>
/// Runs a fully connected forward operation on the CPU
/// </summary>
[Benchmark]
[Benchmark(Baseline = true)]
public void Cpu() => Dnn.FullyConnectedForwardCpu(C, N, M, P, X, W, B, Y);
/// <summary>
+2 -2
ファイルの表示
@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
@@ -16,7 +16,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="SixLabors.ImageSharp" Version="1.0.0-beta0007" />
<PackageReference Include="SixLabors.ImageSharp" Version="1.0.0-rc0002" />
</ItemGroup>
<ItemGroup>
+3 -3
ファイルの表示
@@ -1,7 +1,6 @@
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing.Processors;
using SixLabors.Primitives;
namespace ComputeSharp.BokehBlur.Processors
{
@@ -59,9 +58,10 @@ namespace ComputeSharp.BokehBlur.Processors
public float Gamma { get; }
/// <inheritdoc/>
public IImageProcessor<TPixel> CreatePixelSpecificProcessor<TPixel>(Image<TPixel> source, Rectangle sourceRectangle) where TPixel : struct, IPixel<TPixel>
public IImageProcessor<TPixel> CreatePixelSpecificProcessor<TPixel>(Configuration configuration, Image<TPixel> source, Rectangle sourceRectangle)
where TPixel : unmanaged, IPixel<TPixel>
{
return new HlslBokehBlurProcessor<TPixel>(this, source, sourceRectangle);
return new HlslBokehBlurProcessor<TPixel>(this, configuration, source, sourceRectangle);
}
}
}
+203 -75
ファイルの表示
@@ -6,12 +6,10 @@ using System.Diagnostics.Contracts;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Advanced;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing.Processors;
using SixLabors.Primitives;
namespace ComputeSharp.BokehBlur.Processors
{
@@ -20,7 +18,8 @@ namespace ComputeSharp.BokehBlur.Processors
/// </summary>
/// <typeparam name="TPixel">The pixel format</typeparam>
/// <remarks>This processor is based on the code from Mike Pound, see <a href="https://github.com/mikepound/convolve">github.com/mikepound/convolve</a></remarks>
public sealed class HlslBokehBlurProcessor<TPixel> : IImageProcessor<TPixel> where TPixel : struct, IPixel<TPixel>
public sealed class HlslBokehBlurProcessor<TPixel> : ImageProcessor<TPixel>
where TPixel : unmanaged, IPixel<TPixel>
{
/// <summary>
/// The kernel radius
@@ -62,24 +61,20 @@ namespace ComputeSharp.BokehBlur.Processors
/// </summary>
private static readonly ConcurrentDictionary<(int Radius, int ComponentsCount), (Vector4[] Parameters, float Scale, Vector2[][] Kernels)> Cache = new ConcurrentDictionary<(int, int), (Vector4[], float, Vector2[][])>();
/// <summary>
/// The source <see cref="Image{TPixel}"/> instance to modify
/// </summary>
private readonly Image<TPixel> Source;
/// <summary>
/// Initializes a new instance of the <see cref="HlslBokehBlurProcessor{TPixel}"/> class
/// </summary>
/// <param name="definition">The <see cref="HlslBokehBlurProcessor"/> defining the processor parameters</param>
/// <param name="configuration">The configuration which allows altering default behaviour or extending the library</param>
/// <param name="source">The source <see cref="Image{TPixel}"/> instance to modify</param>
/// <param name="sourceRectangle">The source <see cref="Rectangle"/> that indicates the area to edit</param>
public HlslBokehBlurProcessor(HlslBokehBlurProcessor definition, Image<TPixel> source, Rectangle sourceRectangle)
public HlslBokehBlurProcessor(HlslBokehBlurProcessor definition, Configuration configuration, Image<TPixel> source, Rectangle sourceRectangle)
: base(configuration, source, sourceRectangle)
{
Radius = definition.Radius;
KernelSize = Radius * 2 + 1;
ComponentsCount = definition.Components;
Gamma = definition.Gamma;
Source = source;
// Reuse the initialized values from the cache, if possible
var parameters = (Radius, ComponentsCount);
@@ -259,31 +254,36 @@ namespace ComputeSharp.BokehBlur.Processors
}
/// <inheritdoc/>
public void Apply()
protected override void OnFrameApply(ImageFrame<TPixel> source)
{
// Preliminary gamma highlight pass
using IMemoryOwner<Vector4> source4 = GetExposedVector4Buffer();
using ReadOnlyBuffer<Vector4> sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(source4.Memory.Span);
using ReadWriteBuffer<Vector4> processingBuffer = Gpu.Default.AllocateReadWriteBuffer<Vector4>(sourceBuffer.Size);
using ReadWriteBuffer<Vector4> firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer<Vector4>(sourceBuffer.Size * 2);
using ReadOnlyBuffer<Vector2> kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer<Vector2>(KernelSize);
ref Vector4 param0 = ref KernelParameters[0]; // Avoid bounds check to access the kernel parameters
// Perform two 1D convolutions for each component in the current instance
for (int i = 0; i < Kernels.Length; i++)
foreach (Memory<TPixel> memory in source.GetPixelMemoryGroup())
{
kernelBuffer.SetData(Kernels[i]);
Vector4 parameters = Unsafe.Add(ref param0, i);
// Preliminary gamma highlight pass
using IMemoryOwner<Vector4> source4 = GetExposedVector4Buffer(memory);
ApplyVerticalConvolution(sourceBuffer, firstPassBuffer, kernelBuffer);
ApplyHorizontalConvolutionAndAccumulatePartials(firstPassBuffer, processingBuffer, kernelBuffer, parameters.Z, parameters.W);
using ReadOnlyBuffer<Vector4> sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(source4.Memory.Span);
using ReadWriteBuffer<Vector4> processingBuffer = Gpu.Default.AllocateReadWriteBuffer<Vector4>(sourceBuffer.Size);
using ReadWriteBuffer<Vector4> firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer<Vector4>(sourceBuffer.Size * 2);
using ReadOnlyBuffer<Vector2> kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer<Vector2>(KernelSize);
ref Vector4 param0 = ref KernelParameters[0]; // Avoid bounds check to access the kernel parameters
// 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);
ApplyVerticalConvolution(sourceBuffer, firstPassBuffer, kernelBuffer);
ApplyHorizontalConvolutionAndAccumulatePartials(firstPassBuffer, processingBuffer, kernelBuffer, parameters.Z, parameters.W);
}
// Apply the inverse gamma exposure pass
processingBuffer.GetData(source4.Memory.Span);
// Write the final pixel data
ApplyInverseGammaExposure(source4.Memory, memory);
}
// Apply the inverse gamma exposure pass, and write the final pixel data
processingBuffer.GetData(source4.Memory.Span);
ApplyInverseGammaExposure(source4);
}
/// <summary>
@@ -292,6 +292,7 @@ namespace ComputeSharp.BokehBlur.Processors
/// <param name="source">The source <see cref="ReadOnlyBuffer{T}"/> to read data from</param>
/// <param name="target">The target <see cref="ReadWriteBuffer{T}"/> to write the results to</param>
/// <param name="kernel">The <see cref="ReadOnlyBuffer{T}"/> with the values for the current complex kernel</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyVerticalConvolution(
ReadOnlyBuffer<Vector4> source,
ReadWriteBuffer<Vector4> target,
@@ -299,20 +300,44 @@ namespace ComputeSharp.BokehBlur.Processors
{
int height = Source.Height;
int width = Source.Width;
int maxY = height - 1;
int maxX = width - 1;
int kernelLength = kernel.Size;
Gpu.Default.For(width, height, id =>
Gpu.Default.For(width, height, new VerticalConvolutionProcessor
{
width = width,
maxY = height - 1,
maxX = width - 1,
kernelLength = kernel.Size,
source = source,
target = target,
kernel = kernel
});
}
/// <summary>
/// Kernel for <see cref="ApplyVerticalConvolution"/>
/// </summary>
private struct VerticalConvolutionProcessor : IComputeShader
{
public int width;
public int maxY;
public int maxX;
public int kernelLength;
public ReadOnlyBuffer<Vector4> source;
public ReadWriteBuffer<Vector4> target;
public ReadOnlyBuffer<Vector2> kernel;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
{
Vector4 real = Vector4.Zero;
Vector4 imaginary = Vector4.Zero;
int radiusY = kernelLength >> 1;
int sourceOffsetColumnBase = id.X;
int sourceOffsetColumnBase = ids.X;
for (int i = 0; i < kernelLength; i++)
{
int offsetY = Hlsl.Clamp(id.Y + i - radiusY, 0, maxY);
int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY);
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX);
Vector4 color = source[offsetY * width + offsetX];
Vector2 factors = kernel[i];
@@ -321,10 +346,10 @@ namespace ComputeSharp.BokehBlur.Processors
imaginary += factors.Y * color;
}
int offsetXY = id.Y * width * 2 + id.X * 2;
int offsetXY = ids.Y * width * 2 + ids.X * 2;
target[offsetXY] = real;
target[offsetXY + 1] = imaginary;
});
}
}
/// <summary>
@@ -335,6 +360,7 @@ namespace ComputeSharp.BokehBlur.Processors
/// <param name="kernel">The <see cref="ReadOnlyBuffer{T}"/> with the values for the current complex kernel</param>
/// <param name="z">The weight factor for the real component of the complex pixel values</param>
/// <param name="w">The weight factor for the imaginary component of the complex pixel values</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyHorizontalConvolutionAndAccumulatePartials(
ReadWriteBuffer<Vector4> source,
ReadWriteBuffer<Vector4> target,
@@ -344,17 +370,45 @@ namespace ComputeSharp.BokehBlur.Processors
{
int height = Source.Height;
int width = Source.Width;
int maxY = height - 1;
int maxX = width - 1;
int kernelLength = kernel.Size;
Gpu.Default.For(width, height, id =>
Gpu.Default.For(width, height, new HorizontalConvolutionAndAccumulatePartialsProcessor
{
width = width,
maxY = height - 1,
maxX = width - 1,
kernelLength = kernel.Size,
z = z,
w = w,
source = source,
target = target,
kernel = kernel
});
}
/// <summary>
/// Kernel for <see cref="ApplyHorizontalConvolutionAndAccumulatePartials"/>
/// </summary>
private struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader
{
public int width;
public int maxY;
public int maxX;
public int kernelLength;
public float z;
public float w;
public ReadWriteBuffer<Vector4> source;
public ReadWriteBuffer<Vector4> target;
public ReadOnlyBuffer<Vector2> kernel;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
{
Vector4 real = Vector4.Zero;
Vector4 imaginary = Vector4.Zero;
int radiusX = kernelLength >> 1;
int sourceOffsetColumnBase = id.X;
int offsetY = Hlsl.Clamp(id.Y, 0, maxY);
int sourceOffsetColumnBase = ids.X;
int offsetY = Hlsl.Clamp(ids.Y, 0, maxY);
for (int i = 0; i < kernelLength; i++)
{
@@ -368,69 +422,143 @@ namespace ComputeSharp.BokehBlur.Processors
imaginary += factors.X * sourceImaginary + factors.Y * sourceReal;
}
target[id.Y * width + id.X] += real * z + imaginary * w;
});
target[ids.Y * width + ids.X] += real * z + imaginary * w;
}
}
/// <summary>
/// Applies the gamma correction/highlight to the input pixel buffer and returns an <see cref="IMemoryOwner{T}"/> instance with <see cref="Vector4"/> values.
/// </summary>
/// <param name="source">The source image</param>
[Pure]
private IMemoryOwner<Vector4> GetExposedVector4Buffer()
private IMemoryOwner<Vector4> GetExposedVector4Buffer(Memory<TPixel> source)
{
IMemoryOwner<Vector4> source4 = Source.GetConfiguration().MemoryAllocator.Allocate<Vector4>(Source.Width * Source.Height);
IMemoryOwner<Vector4> target = Configuration.MemoryAllocator.Allocate<Vector4>(source.Length);
float exp = Gamma;
int width = Source.Width;
int height = source.Length / width;
Parallel.For(0, Source.Height, y =>
ParallelRowIterator.IterateRows(
Configuration,
new Rectangle(0, 0, width, height),
new GetExposedVector4BufferProcessor(width, exp, source, target.Memory, Configuration));
return target;
}
/// <summary>
/// The processor for <see cref="GetExposedVector4Buffer"/>
/// </summary>
private readonly struct GetExposedVector4BufferProcessor : IRowOperation
{
private readonly int width;
private readonly float exp;
private readonly Memory<TPixel> source;
private readonly Memory<Vector4> target;
private readonly Configuration configuration;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public GetExposedVector4BufferProcessor(
int width,
float exp,
Memory<TPixel> source,
Memory<Vector4> target,
Configuration configuration)
{
ref TPixel rPixel = ref Source.GetPixelRowSpan(y).GetPinnableReference();
ref Vector4 r4 = ref source4.Memory.Span.Slice(y * width).GetPinnableReference();
this.width = width;
this.exp = exp;
this.source = source;
this.target = target;
this.configuration = configuration;
}
for (int x = 0; x < width; x++)
/// <inheritdoc/>
public void Invoke(int y)
{
int offset = y * width;
Span<TPixel> rowTPixel = source.Span.Slice(offset, width);
Span<Vector4> rowVector4 = target.Span.Slice(offset, width);
PixelOperations<TPixel>.Instance.ToVector4(configuration, rowTPixel, rowVector4);
foreach (ref Vector4 v in rowVector4)
{
ref Vector4 v = ref Unsafe.Add(ref r4, x);
v = Unsafe.Add(ref rPixel, x).ToVector4();
v.X = MathF.Pow(v.X, exp);
v.Y = MathF.Pow(v.Y, exp);
v.Z = MathF.Pow(v.Z, exp);
}
});
return source4;
}
}
/// <summary>
/// Applies the inverse gamma exposure pass to compute the final pixel values for a target image
/// </summary>
/// <param name="sourceValues">The source <see cref="Vector4"/> buffer to read from</param>
private void ApplyInverseGammaExposure(IMemoryOwner<Vector4> sourceValues)
/// <param name="source">The source <see cref="Vector4"/> buffer to read from</param>
/// <param name="target">The target image</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyInverseGammaExposure(Memory<Vector4> source, Memory<TPixel> target)
{
int width = Source.Width;
int height = source.Length / width;
float expGamma = 1 / Gamma;
Parallel.For(0, Source.Height, y =>
ParallelRowIterator.IterateRows(
Configuration,
new Rectangle(0, 0, width, height),
new ApplyInverseGammaExposureProcessor(width, expGamma, source, target, Configuration));
}
/// <summary>
/// The processor for <see cref="ApplyInverseGammaExposure"/>
/// </summary>
private readonly struct ApplyInverseGammaExposureProcessor : IRowOperation
{
private readonly int width;
private readonly float exp;
private readonly Memory<Vector4> source;
private readonly Memory<TPixel> target;
private readonly Configuration configuration;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ApplyInverseGammaExposureProcessor(
int width,
float exp,
Memory<Vector4> source,
Memory<TPixel> target,
Configuration configuration)
{
this.width = width;
this.exp = exp;
this.source = source;
this.target = target;
this.configuration = configuration;
}
/// <inheritdoc/>
public void Invoke(int y)
{
int offset = y * width;
Span<Vector4> rowVector4 = source.Span.Slice(offset, width);
Span<TPixel> rowTPixel = target.Span.Slice(offset, width);
Vector4 low = Vector4.Zero;
var high = new Vector4(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
ref TPixel rPixel = ref Source.GetPixelRowSpan(y).GetPinnableReference();
ref Vector4 r4 = ref sourceValues.Memory.Span.Slice(y * width).GetPinnableReference();
for (int x = 0; x < width; x++)
foreach (ref Vector4 v in rowVector4)
{
Vector4 v = Unsafe.Add(ref r4, x);
var clamp = Vector4.Clamp(v, low, high);
v.X = MathF.Pow(clamp.X, expGamma);
v.Y = MathF.Pow(clamp.Y, expGamma);
v.Z = MathF.Pow(clamp.Z, expGamma);
Unsafe.Add(ref rPixel, x).FromVector4(v);
v.X = MathF.Pow(clamp.X, exp);
v.Y = MathF.Pow(clamp.Y, exp);
v.Z = MathF.Pow(clamp.Z, exp);
}
});
}
/// <inheritdoc/>
public void Dispose() { }
PixelOperations<TPixel>.Instance.FromVector4Destructive(configuration, rowVector4, rowTPixel);
}
}
}
}
+3 -3
ファイルの表示
@@ -1,7 +1,6 @@
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing.Processors;
using SixLabors.Primitives;
namespace ComputeSharp.BokehBlur.Processors
{
@@ -48,9 +47,10 @@ namespace ComputeSharp.BokehBlur.Processors
public int Radius { get; }
/// <inheritdoc />
public IImageProcessor<TPixel> CreatePixelSpecificProcessor<TPixel>(Image<TPixel> source, Rectangle sourceRectangle) where TPixel : struct, IPixel<TPixel>
public IImageProcessor<TPixel> CreatePixelSpecificProcessor<TPixel>(Configuration configuration, Image<TPixel> source, Rectangle sourceRectangle)
where TPixel : unmanaged, IPixel<TPixel>
{
return new HlslGaussianBlurProcessor<TPixel>(this, source, sourceRectangle);
return new HlslGaussianBlurProcessor<TPixel>(this, configuration, source, sourceRectangle);
}
}
}
+91 -60
ファイルの表示
@@ -1,13 +1,11 @@
using System;
using System.Buffers;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Advanced;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing.Processors;
using SixLabors.Primitives;
namespace ComputeSharp.BokehBlur.Processors
{
@@ -15,29 +13,26 @@ namespace ComputeSharp.BokehBlur.Processors
/// Applies Gaussian blur processing to an image.
/// </summary>
/// <typeparam name="TPixel">The pixel format.</typeparam>
internal class HlslGaussianBlurProcessor<TPixel> : IImageProcessor<TPixel> where TPixel : struct, IPixel<TPixel>
internal class HlslGaussianBlurProcessor<TPixel> : ImageProcessor<TPixel>
where TPixel : unmanaged, IPixel<TPixel>
{
/// <summary>
/// The 1D kernel to apply
/// </summary>
private readonly float[] Kernel;
/// <summary>
/// The source <see cref="Image{TPixel}"/> instance to modify
/// </summary>
private readonly Image<TPixel> Source;
/// <summary>
/// Initializes a new instance of the <see cref="HlslGaussianBlurProcessor"/> class
/// </summary>
/// <param name="definition">The <see cref="HlslGaussianBlurProcessor"/> defining the processor parameters</param>
/// <param name="configuration">The configuration which allows altering default behaviour or extending the library</param>
/// <param name="source">The source <see cref="Image{TPixel}"/> for the current processor instance</param>
/// <param name="sourceRectangle">The source area to process for the current processor instance</param>
public HlslGaussianBlurProcessor(HlslGaussianBlurProcessor definition, Image<TPixel> source, Rectangle sourceRectangle)
public HlslGaussianBlurProcessor(HlslGaussianBlurProcessor definition, Configuration configuration, Image<TPixel> source, Rectangle sourceRectangle)
: base(configuration, source, sourceRectangle)
{
int kernelSize = definition.Radius * 2 + 1;
Kernel = CreateGaussianBlurKernel(kernelSize, definition.Sigma);
Source = source;
}
/// <summary>
@@ -89,20 +84,29 @@ namespace ComputeSharp.BokehBlur.Processors
}
/// <inheritdoc/>
public void Apply()
protected override void OnFrameApply(ImageFrame<TPixel> source)
{
using Image<RgbaVector> source = Source.CloneAs<RgbaVector>();
Span<Vector4> sourceSpan = MemoryMarshal.Cast<RgbaVector, Vector4>(source.GetPixelSpan());
foreach (Memory<TPixel> memory in source.GetPixelMemoryGroup())
{
Span<TPixel> spanTPixel = memory.Span;
using ReadWriteBuffer<Vector4> sourceBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceSpan);
using ReadWriteBuffer<Vector4> firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer<Vector4>(sourceBuffer.Size);
using ReadOnlyBuffer<float> kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(Kernel);
using IMemoryOwner<Vector4> group4 = Configuration.MemoryAllocator.Allocate<Vector4>(spanTPixel.Length);
ApplyVerticalConvolution(sourceBuffer, firstPassBuffer, kernelBuffer);
ApplyHorizontalConvolution(firstPassBuffer, sourceBuffer, kernelBuffer);
Span<Vector4> spanVector4 = group4.Memory.Span;
sourceBuffer.GetData(sourceSpan);
WriteResultData(source);
PixelOperations<TPixel>.Instance.ToVector4(Configuration, spanTPixel, spanVector4);
using ReadWriteBuffer<Vector4> sourceBuffer = Gpu.Default.AllocateReadWriteBuffer(spanVector4);
using ReadWriteBuffer<Vector4> firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer<Vector4>(sourceBuffer.Size);
using ReadOnlyBuffer<float> kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(Kernel);
ApplyVerticalConvolution(sourceBuffer, firstPassBuffer, kernelBuffer);
ApplyHorizontalConvolution(firstPassBuffer, sourceBuffer, kernelBuffer);
sourceBuffer.GetData(spanVector4);
PixelOperations<TPixel>.Instance.FromVector4Destructive(Configuration, spanVector4, spanTPixel);
}
}
/// <summary>
@@ -111,6 +115,7 @@ namespace ComputeSharp.BokehBlur.Processors
/// <param name="source">The source <see cref="ReadWriteBuffer{T}"/> to read data from</param>
/// <param name="target">The target <see cref="ReadWriteBuffer{T}"/> to write the results to</param>
/// <param name="kernel">The <see cref="ReadOnlyBuffer{T}"/> with the values for the current complex kernel</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyVerticalConvolution(
ReadWriteBuffer<Vector4> source,
ReadWriteBuffer<Vector4> target,
@@ -118,28 +123,52 @@ namespace ComputeSharp.BokehBlur.Processors
{
int height = Source.Height;
int width = Source.Width;
int maxY = height - 1;
int maxX = width - 1;
int kernelLength = kernel.Size;
Gpu.Default.For(width, height, id =>
Gpu.Default.For(width, height, new VerticalConvolutionProcessor
{
width = width,
maxY = height - 1,
maxX = width - 1,
kernelLength = kernel.Size,
source = source,
target = target,
kernel = kernel
});
}
/// <summary>
/// Kernel for <see cref="ApplyVerticalConvolution"/>
/// </summary>
private struct VerticalConvolutionProcessor : IComputeShader
{
public int width;
public int maxY;
public int maxX;
public int kernelLength;
public ReadWriteBuffer<Vector4> source;
public ReadWriteBuffer<Vector4> target;
public ReadOnlyBuffer<float> kernel;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
{
Vector4 result = Vector4.Zero;
int radiusY = kernelLength >> 1;
int sourceOffsetColumnBase = id.X;
int sourceOffsetColumnBase = ids.X;
for (int i = 0; i < kernelLength; i++)
{
int offsetY = Hlsl.Clamp(id.Y + i - radiusY, 0, maxY);
int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY);
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX);
Vector4 color = source[offsetY * width + offsetX];
result += kernel[i] * color;
}
int offsetXY = id.Y * width + id.X;
int offsetXY = ids.Y * width + ids.X;
target[offsetXY] = result;
});
}
}
/// <summary>
@@ -148,6 +177,7 @@ namespace ComputeSharp.BokehBlur.Processors
/// <param name="source">The source <see cref="ReadWriteBuffer{T}"/> to read data from</param>
/// <param name="target">The target <see cref="ReadWriteBuffer{T}"/> to write the results to</param>
/// <param name="kernel">The <see cref="ReadOnlyBuffer{T}"/> with the values for the current complex kernel</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyHorizontalConvolution(
ReadWriteBuffer<Vector4> source,
ReadWriteBuffer<Vector4> target,
@@ -155,16 +185,40 @@ namespace ComputeSharp.BokehBlur.Processors
{
int height = Source.Height;
int width = Source.Width;
int maxY = height - 1;
int maxX = width - 1;
int kernelLength = kernel.Size;
Gpu.Default.For(width, height, id =>
Gpu.Default.For(width, height, new HorizontalConvolutionProcessor
{
width = width,
maxY = height - 1,
maxX = width - 1,
kernelLength = kernel.Size,
source = source,
target = target,
kernel = kernel
});
}
/// <summary>
/// Kernel for <see cref="ApplyHorizontalConvolution"/>
/// </summary>
private struct HorizontalConvolutionProcessor : IComputeShader
{
public int width;
public int maxY;
public int maxX;
public int kernelLength;
public ReadWriteBuffer<Vector4> source;
public ReadWriteBuffer<Vector4> target;
public ReadOnlyBuffer<float> kernel;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
{
Vector4 result = Vector4.Zero;
int radiusX = kernelLength >> 1;
int sourceOffsetColumnBase = id.X;
int offsetY = Hlsl.Clamp(id.Y, 0, maxY);
int sourceOffsetColumnBase = ids.X;
int offsetY = Hlsl.Clamp(ids.Y, 0, maxY);
int offsetXY;
for (int i = 0; i < kernelLength; i++)
@@ -176,32 +230,9 @@ namespace ComputeSharp.BokehBlur.Processors
result += kernel[i] * color;
}
offsetXY = id.Y * width + id.X;
offsetXY = ids.Y * width + ids.X;
target[offsetXY] = result;
});
}
}
/// <summary>
/// Writes the final data to the source image
/// </summary>
/// <param name="image">The source <see cref="Image{TPixel}"/> to read from</param>
private void WriteResultData(Image<RgbaVector> image)
{
int width = Source.Width;
Parallel.For(0, Source.Height, y =>
{
ref TPixel rPixel = ref Source.GetPixelRowSpan(y).GetPinnableReference();
ref Vector4 r4 = ref MemoryMarshal.Cast<RgbaVector, Vector4>(image.GetPixelRowSpan(y)).GetPinnableReference();
for (int x = 0; x < width; x++)
{
Unsafe.Add(ref rPixel, x).FromVector4(Unsafe.Add(ref r4, x));
}
});
}
/// <inheritdoc/>
public void Dispose() { }
}
}
+2 -4
ファイルの表示
@@ -3,7 +3,6 @@ using System.IO;
using System.Reflection;
using ComputeSharp.BokehBlur.Processors;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Processing.Processors;
@@ -15,7 +14,7 @@ namespace ComputeSharp.ImageProcessing
{
Console.WriteLine(">> Loading image");
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "city.jpg");
using Image<Rgb24> image = Image.Load<Rgb24>(path);
using Image image = Image.Load(path);
// Apply a series of processors and save the results
foreach (var effect in new (string Name, IImageProcessor Processor)[]
@@ -25,8 +24,7 @@ namespace ComputeSharp.ImageProcessing
})
{
Console.WriteLine($">> Applying {effect.Name}");
using Image<Rgb24> copy = image.Clone();
copy.Mutate(c => c.ApplyProcessor(effect.Processor));
using Image copy = image.Clone(c => c.ApplyProcessor(effect.Processor));
Console.WriteLine($">> Saving {effect.Name} to disk");
string targetPath = Path.Combine(
+1 -1
ファイルの表示
@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
+25 -5
ファイルの表示
@@ -27,11 +27,7 @@ namespace ComputeSharp.Sample
using ReadWriteBuffer<float> gpuBuffer = Gpu.Default.AllocateReadWriteBuffer(array);
// Run the shader
Gpu.Default.For(100, id =>
{
int offset = id.X + id.Y * width;
gpuBuffer[offset] *= 2;
});
Gpu.Default.For(100, new MainKernel(width, gpuBuffer));
// Get the data back
gpuBuffer.GetData(array);
@@ -42,6 +38,30 @@ namespace ComputeSharp.Sample
Console.WriteLine("==================================================");
}
/// <summary>
/// Kernel for <see cref="Main"/>
/// </summary>
private readonly struct MainKernel : IComputeShader
{
private readonly int width;
private readonly ReadWriteBuffer<float> buffer;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public MainKernel(int width, ReadWriteBuffer<float> buffer)
{
this.width = width;
this.buffer = buffer;
}
/// <inheritdoc/>
public void Execute(ThreadIds ids)
{
int offset = ids.X + ids.Y * width;
buffer[offset] *= 2;
}
}
/// <summary>
/// Prints a matrix in a properly formatted way
/// </summary>
+14
ファイルの表示
@@ -0,0 +1,14 @@
namespace ComputeSharp
{
/// <summary>
/// An <see langword="interface"/> representing a compute shader.
/// </summary>
public interface IComputeShader
{
/// <summary>
/// Executes the current compute shader.
/// </summary>
/// <param name="ids">The <see cref="ThreadIds"/> value with the current execution indices.</param>
void Execute(ThreadIds ids);
}
}
+40 -18
ファイルの表示
@@ -1,4 +1,5 @@
using System;
using System.Runtime.CompilerServices;
using Vortice.Direct3D12;
namespace ComputeSharp.Graphics.Buffers.Abstract
@@ -22,11 +23,6 @@ namespace ComputeSharp.Graphics.Buffers.Abstract
/// </summary>
public GraphicsDevice GraphicsDevice { get; }
/// <summary>
/// Gets the <see cref="IntPtr"/> associated to the currently mapped resource
/// </summary>
internal IntPtr MappedResource { get; private set; }
/// <summary>
/// Gets the <see cref="ID3D12Resource"/> object currently mapped
/// </summary>
@@ -45,24 +41,50 @@ namespace ComputeSharp.Graphics.Buffers.Abstract
/// <summary>
/// Maps the current resource to a specified subresource
/// </summary>
/// <returns>An <see cref="IntPtr"/> for the newly mapped resource</returns>
internal IntPtr Map()
/// <returns>A <see cref="MappedResource"/> instance representing the mapped resource</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal MappedResource MapResource()
{
IntPtr mappedResource = NativeResource?.Map(0) ?? throw new InvalidOperationException("Missing resource");
MappedResource = mappedResource;
return mappedResource;
}
var resource = NativeResource ?? throw new InvalidOperationException("Missing resource");
/// <summary>
/// Unmaps a subresource specified by a given index
/// </summary>
internal void Unmap()
{
NativeResource?.Unmap(0);
MappedResource = IntPtr.Zero;
return new MappedResource(resource);
}
/// <inheritdoc/>
public virtual void Dispose() => NativeResource?.Dispose();
/// <summary>
/// A type representing a mapped memory resource
/// </summary>
internal readonly ref struct MappedResource
{
/// <summary>
/// The target <see cref="ID3D12Resource"/> to map
/// </summary>
private readonly ID3D12Resource Resource;
/// <summary>
/// The pointer to the mapped resource
/// </summary>
public readonly IntPtr Pointer;
/// <summary>
/// Creates a new <see cref="MappedResource"/> instance for a given <see cref="ID3D12Resource"/> value
/// </summary>
/// <param name="resource">The input <see cref="ID3D12Resource"/> instance to map</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public MappedResource(ID3D12Resource resource)
{
Resource = resource;
Pointer = resource.Map(0);
}
/// <inheritdoc cref="IDisposable.Dispose"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
Resource.Unmap(0);
}
}
}
}
+6 -6
ファイルの表示
@@ -71,18 +71,18 @@ namespace ComputeSharp.Graphics.Buffers.Abstract
public void SetData(T[] array, int offset, int count) => SetData(array.AsSpan(), offset, count);
/// <summary>
/// Writes the contents of a given <see cref="Span{T}"/> to the current <see cref="HlslBuffer{T}"/> instance
/// Writes the contents of a given <see cref="ReadOnlySpan{T}"/> to the current <see cref="HlslBuffer{T}"/> instance
/// </summary>
/// <param name="span">The input <see cref="Span{T}"/> to read data from</param>
public void SetData(Span<T> span) => SetData(span, 0, Size);
/// <param name="span">The input <see cref="ReadOnlySpan{T}"/> to read data from</param>
public void SetData(ReadOnlySpan<T> span) => SetData(span, 0, Size);
/// <summary>
/// Writes the contents of a given <see cref="Span{T}"/> to a specified area of the current <see cref="HlslBuffer{T}"/> instance
/// Writes the contents of a given <see cref="ReadOnlySpan{T}"/> to a specified area of the current <see cref="HlslBuffer{T}"/> instance
/// </summary>
/// <param name="span">The input <see cref="Span{T}"/> to read data from</param>
/// <param name="span">The input <see cref="ReadOnlySpan{T}"/> to read data from</param>
/// <param name="offset">The offset to start writing data to</param>
/// <param name="count">The number of items to write</param>
public abstract void SetData(Span<T> span, int offset, int count);
public abstract void SetData(ReadOnlySpan<T> span, int offset, int count);
/// <summary>
/// Writes the contents of a given <see cref="HlslBuffer{T}"/> to the current <see cref="HlslBuffer{T}"/> instance
+12 -12
ファイルの表示
@@ -25,29 +25,30 @@ namespace ComputeSharp.Graphics.Buffers.Abstract
public override void GetData(Span<T> span, int offset, int count)
{
using Buffer<T> transferBuffer = new Buffer<T>(GraphicsDevice, count, count * ElementSizeInBytes, BufferType.ReadBack);
using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy);
copyCommandList.CopyBufferRegion(this, offset * ElementSizeInBytes, transferBuffer, 0, count * ElementSizeInBytes);
copyCommandList.Flush();
using (CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy))
{
copyCommandList.CopyBufferRegion(this, offset * ElementSizeInBytes, transferBuffer, 0, count * ElementSizeInBytes);
}
transferBuffer.Map();
MemoryHelper.Copy(transferBuffer.MappedResource, 0, span, 0, count);
transferBuffer.Unmap();
using MappedResource resource = transferBuffer.MapResource();
MemoryHelper.Copy(resource.Pointer, 0, span, 0, count);
}
/// <inheritdoc/>
public override void SetData(Span<T> span, int offset, int count)
public override void SetData(ReadOnlySpan<T> span, int offset, int count)
{
using Buffer<T> transferBuffer = new Buffer<T>(GraphicsDevice, count, count * ElementSizeInBytes, BufferType.Transfer);
transferBuffer.Map();
MemoryHelper.Copy(span, 0, transferBuffer.MappedResource, 0, count);
transferBuffer.Unmap();
using (MappedResource resource = transferBuffer.MapResource())
{
MemoryHelper.Copy(span, resource.Pointer, 0, count);
}
using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy);
copyCommandList.CopyBufferRegion(transferBuffer, 0, this, offset * ElementSizeInBytes, count * ElementSizeInBytes);
copyCommandList.Flush();
}
/// <inheritdoc/>
@@ -59,7 +60,6 @@ namespace ComputeSharp.Graphics.Buffers.Abstract
using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy);
copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes);
copyCommandList.Flush();
}
else SetDataWithCpuBuffer(buffer);
}
+30 -52
ファイルの表示
@@ -1,7 +1,7 @@
using System;
using System.Buffers;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.Exceptions;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Buffers.Abstract;
@@ -23,16 +23,18 @@ namespace ComputeSharp
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance</param>
/// <param name="size">The number of items to store in the current buffer</param>
internal ConstantBuffer(GraphicsDevice device, int size) : base(device, size, size * GetPaddedSize() * 16, BufferType.Constant) { }
internal ConstantBuffer(GraphicsDevice device, int size) : base(device, size, size * GetPaddedSize(), BufferType.Constant) { }
/// <summary>
/// Gets the right padded size for <typeparamref name="T"/> elements to store in the current instance
/// </summary>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetPaddedSize()
{
int size = Unsafe.SizeOf<T>();
return size % 16 == 0 ? 1 : size / 16 + 1;
return (size + 15) & ~15;
}
/// <summary>
@@ -43,72 +45,49 @@ namespace ComputeSharp
public T this[int i] => throw new InvalidExecutionContextException($"{nameof(ConstantBuffer<T>)}<T>[int]");
/// <inheritdoc/>
public override void GetData(Span<T> span, int offset, int count)
public override unsafe void GetData(Span<T> span, int offset, int count)
{
using MappedResource resource = MapResource();
if (IsPaddingPresent)
{
// Create the temporary array
byte[] temporaryArray = ArrayPool<byte>.Shared.Rent(count * PaddedElementSizeInBytes);
Span<byte> temporarySpan = temporaryArray.AsSpan(0, count * PaddedElementSizeInBytes);
ref T spanRef = ref MemoryMarshal.GetReference(span);
ref byte resourceRef = ref Unsafe.AsRef<byte>((void*)resource.Pointer);
// Copy the padded data to the temporary array
Map();
MemoryHelper.Copy(MappedResource, offset * PaddedElementSizeInBytes, temporarySpan, 0, count * PaddedElementSizeInBytes);
Unmap();
// Move to the initial ref
resourceRef = ref Unsafe.Add(ref resourceRef, offset * GetPaddedSize());
ref byte tin = ref temporarySpan.GetPinnableReference();
ref T tout = ref span.GetPinnableReference();
// Copy the padded data to the target span, removing the padding
for (int i = 0; i < count; i++)
for (var i = 0; i < count; i++)
{
ref byte rsource = ref Unsafe.Add(ref tin, i * PaddedElementSizeInBytes);
Unsafe.Add(ref tout, i) = Unsafe.As<byte, T>(ref rsource);
}
ref byte targetRef = ref Unsafe.Add(ref resourceRef, i * GetPaddedSize());
ArrayPool<byte>.Shared.Return(temporaryArray);
}
else
{
// Directly copy the data back if there is no padding
Map();
MemoryHelper.Copy(MappedResource, offset, span, 0, count);
Unmap();
Unsafe.Add(ref spanRef, i) = Unsafe.As<byte, T>(ref targetRef);
}
}
else MemoryHelper.Copy(resource.Pointer, offset, span, 0, count);
}
/// <inheritdoc/>
public override void SetData(Span<T> span, int offset, int count)
public override unsafe void SetData(ReadOnlySpan<T> span, int offset, int count)
{
using MappedResource resource = MapResource();
if (IsPaddingPresent)
{
// Create the temporary array
byte[] temporaryArray = ArrayPool<byte>.Shared.Rent(count * PaddedElementSizeInBytes);
Span<byte> temporarySpan = temporaryArray.AsSpan(0, count * PaddedElementSizeInBytes); // Array pool arrays can be longer
ref T tin = ref span.GetPinnableReference();
ref byte tout = ref temporarySpan.GetPinnableReference();
ref T spanRef = ref MemoryMarshal.GetReference(span);
ref byte resourceRef = ref Unsafe.AsRef<byte>((void*)resource.Pointer);
// Copy the input data to the temporary array and add the padding
for (int i = 0; i < count; i++)
// Move to the initial offset
resourceRef = ref Unsafe.Add(ref resourceRef, offset * GetPaddedSize());
for (var i = 0; i < count; i++)
{
ref byte rtarget = ref Unsafe.Add(ref tout, i * PaddedElementSizeInBytes);
Unsafe.As<byte, T>(ref rtarget) = Unsafe.Add(ref tin, i);
ref byte targetRef = ref Unsafe.Add(ref resourceRef, i * GetPaddedSize());
Unsafe.As<byte, T>(ref targetRef) = Unsafe.Add(ref spanRef, i);
}
// Copy the padded data to the GPU
Map();
MemoryHelper.Copy(temporarySpan, 0, MappedResource, offset * PaddedElementSizeInBytes, count * PaddedElementSizeInBytes);
Unmap();
ArrayPool<byte>.Shared.Return(temporaryArray);
}
else
{
// Directly copy the input span if there is no padding
Map();
MemoryHelper.Copy(span, 0, MappedResource, offset, count);
Unmap();
}
else MemoryHelper.Copy(span, resource.Pointer, offset, count);
}
/// <inheritdoc/>
@@ -120,7 +99,6 @@ namespace ComputeSharp
using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy);
copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes);
copyCommandList.Flush();
}
else SetDataWithCpuBuffer(buffer);
}
+4 -14
ファイルの表示
@@ -88,23 +88,13 @@ namespace ComputeSharp.Graphics.Commands
NativeCommandList.Dispatch(threadGroupCountX, threadGroupCountY, threadGroupCountZ);
}
/// <summary>
/// Executes the pending operations and waits for them to be completed
/// </summary>
public void Flush()
{
Close();
GraphicsDevice.ExecuteCommandList(this);
}
/// <summary>
/// Closes the current native command list
/// </summary>
public void Close() => NativeCommandList.Close();
/// <inheritdoc/>
public override void Dispose()
{
NativeCommandList.Close();
GraphicsDevice.ExecuteCommandList(this);
switch (CommandListType)
{
case CommandListType.Direct:
+2 -2
ファイルの表示
@@ -8,8 +8,8 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="4.6.0" />
<PackageReference Include="Vortice.Direct3D12" Version="1.3.0" />
<PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="4.7.1" />
<PackageReference Include="Vortice.Direct3D12" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
+7 -19
ファイルの表示
@@ -2,9 +2,9 @@
using System.Threading;
using ComputeSharp.Graphics.Commands;
using Vortice.Direct3D12;
using Vortice.DirectX.Direct3D;
using Vortice.DXGI;
using CommandList = ComputeSharp.Graphics.Commands.CommandList;
using Direct3DFeatureLevel = Vortice.Direct3D.FeatureLevel;
namespace ComputeSharp.Graphics
{
@@ -16,12 +16,7 @@ namespace ComputeSharp.Graphics
/// <summary>
/// Gets the <see cref="FeatureLevel"/> value that needs to be supported by GPUs mapped to a <see cref="GraphicsDevice"/> instance
/// </summary>
public const FeatureLevel FeatureLevel = Vortice.DirectX.Direct3D.FeatureLevel.Level_12_1;
/// <summary>
/// The <see cref="System.Threading.AutoResetEvent"/> instance used to wait for completion when executing commands
/// </summary>
private readonly AutoResetEvent AutoResetEvent = new AutoResetEvent(false);
public const Direct3DFeatureLevel FeatureLevel = Direct3DFeatureLevel.Level_12_1;
/// <summary>
/// The <see cref="ID3D12CommandQueue"/> instance to use for compute operations
@@ -126,11 +121,6 @@ namespace ComputeSharp.Graphics
/// </summary>
internal ID3D12Fence NativeDirectFence { get; }
/// <summary>
/// The <see cref="object"/> used to lock command list executions
/// </summary>
private readonly object Lock = new object();
/// <summary>
/// Gets the next fence value for compute operations
/// </summary>
@@ -174,11 +164,11 @@ namespace ComputeSharp.Graphics
if (fenceValue <= fence.CompletedValue) return;
lock (Lock)
{
fence.SetEventOnCompletion(fenceValue, AutoResetEvent.SafeWaitHandle.DangerousGetHandle());
AutoResetEvent.WaitOne();
}
using ManualResetEvent fenceEvent = new ManualResetEvent(false);
fence.SetEventOnCompletion(fenceValue, fenceEvent);
fenceEvent.WaitOne();
}
/// <summary>
@@ -244,8 +234,6 @@ namespace ComputeSharp.Graphics
NativeDirectFence.Dispose();
NativeDevice.Dispose();
AutoResetEvent.Dispose();
}
}
}
+2 -2
ファイルの表示
@@ -1,7 +1,7 @@
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using Vortice.Direct3D;
using Vortice.Direct3D12;
using Vortice.DirectX.Direct3D;
using Vortice.DXGI;
namespace ComputeSharp.Graphics.Helpers
@@ -23,7 +23,7 @@ namespace ComputeSharp.Graphics.Helpers
{
List<(ID3D12Device, AdapterDescription)> devices = new List<(ID3D12Device, AdapterDescription)>();
foreach (IDXGIAdapter1 adapter in factory.EnumAdapters1())
foreach (IDXGIAdapter1 adapter in factory.Adapters1)
{
if (adapter.Description.DedicatedVideoMemory == 0) continue;
if (D3D12.D3D12CreateDevice(adapter, FeatureLevel.Level_12_0, out ID3D12Device device).Success)
+8 -8
ファイルの表示
@@ -9,19 +9,19 @@ namespace ComputeSharp.Graphics.Helpers
internal static class MemoryHelper
{
/// <summary>
/// Copies the content of a <see cref="Span{T}"/> to the area pointed by an input <see cref="IntPtr"/> value
/// Copies the content of a <see cref="ReadOnlySpan{T}"/> to the area pointed by an input <see cref="IntPtr"/> value
/// </summary>
/// <typeparam name="T">The type of values in the input <see cref="Span{T}"/></typeparam>
/// <param name="source">The source <see cref="Span{T}"/> to read</param>
/// <param name="sourceOffset">The source offset to start reading data from</param>
/// <typeparam name="T">The type of values in the input <see cref="ReadOnlySpan{T}"/></typeparam>
/// <param name="source">The source <see cref="ReadOnlySpan{T}"/> to read</param>
/// <param name="destination">The <see cref="IntPtr"/> for the destination memory area</param>
/// <param name="destinationOffset">The destination offset to start writing data to</param>
/// <param name="count">The total number of items to copy</param>
public static unsafe void Copy<T>(Span<T> source, int sourceOffset, IntPtr destination, int destinationOffset, int count) where T : unmanaged
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void Copy<T>(ReadOnlySpan<T> source, IntPtr destination, int destinationOffset, int count) where T : unmanaged
{
ref T rout = ref Unsafe.AsRef<T>(destination.ToPointer());
void* target = Unsafe.AsPointer(ref Unsafe.Add(ref rout, destinationOffset));
source.Slice(sourceOffset, count).CopyTo(new Span<T>(target, count));
T* p = (T*)destination.ToPointer() + destinationOffset;
source.CopyTo(new Span<T>(p, count));
}
/// <summary>
+5 -4
ファイルの表示
@@ -7,10 +7,11 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ICSharpCode.Decompiler" Version="5.0.1.5145" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.3.1" />
<PackageReference Include="Stubble.Core" Version="1.4.12" />
<PackageReference Include="Vortice.Dxc" Version="1.3.0" />
<PackageReference Include="ICSharpCode.Decompiler" Version="5.0.2.5153" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.5.0" />
<PackageReference Include="Microsoft.Experimental.Collections" Version="1.0.6-e190117-3" />
<PackageReference Include="Stubble.Core" Version="1.7.2" />
<PackageReference Include="Vortice.Dxc" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
+15 -15
ファイルの表示
@@ -1,11 +1,11 @@
using System;
using System.Collections.Generic;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Shaders.Renderer;
using ComputeSharp.Shaders.Renderer.Models;
using ComputeSharp.Shaders.Translation;
using ComputeSharp.Shaders.Translation.Models;
using Microsoft.Collections.Extensions;
using Vortice.Direct3D12;
using CommandList = ComputeSharp.Graphics.Commands.CommandList;
using PipelineState = ComputeSharp.Graphics.Commands.PipelineState;
@@ -15,7 +15,9 @@ namespace ComputeSharp.Shaders
/// <summary>
/// A <see langword="class"/> responsible for performing all the necessary operations to compile and run a compute shader
/// </summary>
internal static class ShaderRunner
/// <typeparam name="T">The type of compute shader to run</typeparam>
internal static class ShaderRunner<T>
where T : struct, IComputeShader
{
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
@@ -24,8 +26,8 @@ namespace ComputeSharp.Shaders
/// <param name="x">The number of iterations to run on the X axis</param>
/// <param name="y">The number of iterations to run on the Y axis</param>
/// <param name="z">The number of iterations to run on the Z axis</param>
/// <param name="action">The input <see cref="Action{T}"/> representing the compute shader to run</param>
public static void Run(GraphicsDevice device, int x, int y, int z, Action<ThreadIds> action)
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run</param>
public static void Run(GraphicsDevice device, int x, int y, int z, in T shader)
{
// Calculate the optimized thread num values
int threadsX, threadsY = 1, threadsZ = 1;
@@ -33,13 +35,13 @@ namespace ComputeSharp.Shaders
else if (z == 1) threadsX = threadsY = 8;
else threadsX = threadsY = threadsZ = 4;
Run(device, x, y, z, threadsX, threadsY, threadsZ, action);
Run(device, x, y, z, threadsX, threadsY, threadsZ, shader);
}
/// <summary>
/// The mapping used to cache and reuse compiled shaders
/// </summary>
private static readonly Dictionary<(int Id, int ThreadsX, int ThreadsY, int ThreadsZ), CachedShader> ShadersCache = new Dictionary<(int, int, int, int), CachedShader>();
private static readonly DictionarySlim<ShaderKey, CachedShader<T>> ShadersCache = new DictionarySlim<ShaderKey, CachedShader<T>>();
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
@@ -51,22 +53,22 @@ namespace ComputeSharp.Shaders
/// <param name="threadsX">The number of threads in each thread group for the X axis</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis</param>
/// <param name="action">The input <see cref="Action{T}"/> representing the compute shader to run</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run</param>
public static void Run(
GraphicsDevice device,
int x, int y, int z,
int threadsX, int threadsY, int threadsZ,
Action<ThreadIds> action)
in T shader)
{
// Try to get the cache shader
CachedShader shaderData;
CachedShader<T> shaderData;
lock (ShadersCache)
{
var key = (ShaderHashCodeProvider.GetHashCode(action), threadsX, threadsY, threadsZ);
var key = new ShaderKey(ShaderHashCodeProvider.GetHashCode(shader), threadsX, threadsY, threadsZ);
if (!ShadersCache.TryGetValue(key, out shaderData))
{
// Load the input shader
ShaderLoader shaderLoader = ShaderLoader.Load(action);
ShaderLoader<T> shaderLoader = ShaderLoader<T>.Load(shader);
// Render the loaded shader
ShaderInfo shaderInfo = new ShaderInfo
@@ -87,8 +89,7 @@ namespace ComputeSharp.Shaders
ShaderBytecode shaderBytecode = ShaderCompiler.CompileShader(shaderSource);
// Cache for later use
shaderData = new CachedShader(shaderLoader, shaderBytecode);
ShadersCache.Add(key, shaderData);
ShadersCache.GetOrAddValueRef(key) = shaderData = new CachedShader<T>(shaderLoader, shaderBytecode);
}
}
@@ -102,7 +103,7 @@ namespace ComputeSharp.Shaders
commandList.SetPipelineState(pipelineState);
// Extract the dispatch data for the shader invocation
using DispatchData dispatchData = shaderData.Loader.GetDispatchData(action, x, y, z);
using DispatchData dispatchData = shaderData.Loader.GetDispatchData(shader, x, y, z);
// Load the captured buffers
Span<GraphicsResource> resources = dispatchData.Resources;
@@ -124,7 +125,6 @@ namespace ComputeSharp.Shaders
// Dispatch and wait for completion
commandList.Dispatch(groupsX, groupsY, groupsZ);
commandList.Flush();
}
}
}
+2 -2
ファイルの表示
@@ -6,9 +6,9 @@
internal enum MethodType
{
/// <summary>
/// An instance method that belongs to a closure class
/// The instance <see cref="IComputeShader.Execute"/> method on some shader type
/// </summary>
Closure,
Execute,
/// <summary>
/// A standalone, static method
+27 -110
ファイルの表示
@@ -6,7 +6,6 @@ using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Text;
using System.Text.RegularExpressions;
using ComputeSharp.Shaders.Mappings;
using ComputeSharp.Shaders.Translation.Enums;
@@ -138,7 +137,7 @@ namespace ComputeSharp.Shaders.Translation
{
string sourceCode = methodType switch
{
MethodType.Closure => GetSyntaxTreeForClosureMethod(methodInfo),
MethodType.Execute => GetSyntaxTreeForExecuteMethod(methodInfo),
MethodType.Static => GetSyntaxTreeForStaticMethod(methodInfo),
_ => throw new ArgumentOutOfRangeException(nameof(methodType), $"Invalid method type: {methodType}")
};
@@ -147,7 +146,12 @@ namespace ComputeSharp.Shaders.Translation
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sourceCode);
// Get the root node to return
rootNode = syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First(node => node.GetLeadingTrivia().ToFullString().Contains(methodInfo.Name));
rootNode = syntaxTree
.GetRoot()
.DescendantNodes()
.OfType<MethodDeclarationSyntax>()
.First(node => node.Identifier.ToString().Equals(methodInfo.Name) ||
node.GetLeadingTrivia().ToFullString().Contains(methodInfo.Name));
// Update the incremental compilation and retrieve the syntax tree for the method
Compilation compilation = _Compilation.AddSyntaxTrees(syntaxTree);
@@ -159,31 +163,13 @@ namespace ComputeSharp.Shaders.Translation
/// </summary>
/// <param name="methodInfo">The input <see cref="MethodInfo"/> to inspect</param>
[Pure]
private string GetSyntaxTreeForClosureMethod(MethodInfo methodInfo)
private string GetSyntaxTreeForExecuteMethod(MethodInfo methodInfo)
{
// Decompile the method source and fix the method declaration for local methods converted to lambdas
string
sourceCode = DecompileMethodOrDeclaringType(methodInfo),
typeFixedCode = ClosureTypeDeclarationRegex.Replace(sourceCode, "Shader"),
methodFixedCode = LambdaMethodDeclarationRegex.Replace(typeFixedCode, m => $"// {m.Value}{Environment.NewLine} internal void Main");
// Workaround for some local methods not being decompiled correctly
if (!methodFixedCode.Contains("internal void Main"))
{
string
methodOnlySourceCode = DecompileMethodOrDeclaringType(methodInfo, true),
methodOnlyFixedSourceCode = LambdaMethodDeclarationRegex.Replace(methodOnlySourceCode, m => $"// {m.Value}{Environment.NewLine} internal void Main"),
methodOnlyIndentedSourceCode = $" {methodOnlyFixedSourceCode.Replace(Environment.NewLine, $"{Environment.NewLine} ")}";
int lastClosedBracketsIndex = methodFixedCode.LastIndexOf('}');
methodFixedCode = methodFixedCode.Insert(lastClosedBracketsIndex, methodOnlyIndentedSourceCode);
}
// Unwrap the nested fields
string unwrappedSourceCode = UnwrapSyntaxTree(methodFixedCode);
// Decompile the method source
string sourceCode = DecompileMethodOrDeclaringType(methodInfo);
// Remove the in keyword from the source
string inFixedSourceCode = Regex.Replace(unwrappedSourceCode, @"(?<!\w)in ", string.Empty);
string inFixedSourceCode = Regex.Replace(sourceCode, @"(?<!\w)in ", string.Empty);
// Tweak the out declarations
string outFixedSourceCode = RefactorInlineOutDeclarations(inFixedSourceCode, methodInfo.Name);
@@ -201,8 +187,16 @@ namespace ComputeSharp.Shaders.Translation
string
sourceCode = DecompileMethodOrDeclaringType(methodInfo, true),
methodFixedCode = sourceCode.Replace(methodInfo.Name, Regex.Replace(methodInfo.Name, "[<>|]", "_")),
prototype = methodFixedCode.Split(Environment.NewLine)[0],
commentedSourceCode = $"// {methodInfo.Name}{Environment.NewLine}{methodFixedCode}",
methodWithoutAttributes = CSharpSyntaxTree
.ParseText(methodFixedCode)
.GetRoot()
.DescendantNodes()
.OfType<MethodDeclarationSyntax>()
.First()
.WithAttributeLists(default)
.ToString(),
prototype = methodWithoutAttributes.Split(Environment.NewLine)[0],
commentedSourceCode = $"// {methodInfo.Name}{Environment.NewLine}{methodWithoutAttributes}",
inFixedSourceCode = Regex.Replace(commentedSourceCode, @"(?<!\w)in ", string.Empty),
outFixedSourceCode = RefactorInlineOutDeclarations(inFixedSourceCode, methodInfo.Name);
@@ -213,88 +207,6 @@ namespace ComputeSharp.Shaders.Translation
return $"// {methodInfo.Name}{Environment.NewLine}{prototype}{Environment.NewLine}{block.ToFullString()}";
}
/// <summary>
/// A <see cref="Regex"/> used to preprocess the closure type declarations for both lambda expressions and local methods
/// </summary>
private static readonly Regex ClosureTypeDeclarationRegex = new Regex(@"(?<=private sealed class )<\w*>[\w_]+", RegexOptions.Compiled);
/// <summary>
/// A <see cref="Regex"/> used to preprocess the entry point declaration for both lambda expressions and local methods
/// </summary>
private static readonly Regex LambdaMethodDeclarationRegex = new Regex(@"(?:private|internal) void <\w+>[\w_|]+(?=\()", RegexOptions.Compiled);
/// <summary>
/// A <see cref="Regex"/> used to find fields that represent nested closure types
/// </summary>
private static readonly Regex NestedClosureFieldRegex = new Regex(@"(?<=public )((?:\w+\.)+<>[\w_]+) (CS\$<>[\w_]+)(?=;)", RegexOptions.Compiled);
/// <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 typeSource)
{
// Find the field declarations
Match match = NestedClosureFieldRegex.Match(typeSource);
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;
}
/// <summary>
/// Refactors all the inline out expressions with a variable declaration
/// </summary>
@@ -308,7 +220,12 @@ namespace ComputeSharp.Shaders.Translation
// Load the syntax tree and the entry node
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source);
MethodDeclarationSyntax rootNode = syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First(node => node.GetLeadingTrivia().ToFullString().Contains(entryPoint));
MethodDeclarationSyntax rootNode = syntaxTree
.GetRoot()
.DescendantNodes()
.OfType<MethodDeclarationSyntax>()
.First(node => node.Identifier.ToString().Equals(entryPoint) ||
node.GetLeadingTrivia().ToFullString().Contains(entryPoint));
// Get the out declarations to replace
var outs = (
@@ -5,12 +5,14 @@ namespace ComputeSharp.Shaders.Translation.Models
/// <summary>
/// A <see langword="struct"/> that contains info on a cached shader
/// </summary>
internal readonly struct CachedShader
/// <typeparam name="T">The type of compute shader in use</typeparam>
internal readonly struct CachedShader<T>
where T : struct, IComputeShader
{
/// <summary>
/// The <see cref="ShaderLoader"/> instance with the shader metadata
/// </summary>
public readonly ShaderLoader Loader;
public readonly ShaderLoader<T> Loader;
/// <summary>
/// The compiled shader bytecode
@@ -22,7 +24,7 @@ namespace ComputeSharp.Shaders.Translation.Models
/// </summary>
/// <param name="loader">The <see cref="ShaderLoader"/> instance with the shader metadata</param>
/// <param name="bytecode">The compiled shader bytecode</param>
public CachedShader(ShaderLoader loader, ShaderBytecode bytecode)
public CachedShader(ShaderLoader<T> loader, ShaderBytecode bytecode)
{
Loader = loader;
Bytecode = bytecode;
+85
ファイルの表示
@@ -0,0 +1,85 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace ComputeSharp.Shaders.Translation.Models
{
/// <summary>
/// A <see langword="struct"/> representing a key for a given shader
/// </summary>
[StructLayout(LayoutKind.Explicit)]
internal readonly struct ShaderKey : IEquatable<ShaderKey>
{
/// <summary>
/// The hashcode of the current shader type
/// </summary>
[FieldOffset(0)]
private readonly int Id;
/// <summary>
/// The number of iterations to run on the X axis
/// </summary>
[FieldOffset(4)]
private readonly int ThreadsX;
/// <summary>
/// The number of iterations to run on the Y axis
/// </summary>
[FieldOffset(8)]
private readonly int ThreadsY;
/// <summary>
/// The number of iterations to run on the Z axis
/// </summary>
[FieldOffset(12)]
private readonly int ThreadsZ;
/// <summary>
/// Creates a new <see cref="ShaderKey"/> instance with the specified parameters
/// </summary>
/// <param name="id">The hashcode of the current shader type</param>
/// <param name="threadsX">The number of iterations to run on the X axis</param>
/// <param name="threadsY">The number of iterations to run on the Y axis</param>
/// <param name="threadsZ">The number of iterations to run on the Z axis</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ShaderKey(int id, int threadsX, int threadsY, int threadsZ)
{
Id = id;
ThreadsX = threadsX;
ThreadsY = threadsY;
ThreadsZ = threadsZ;
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Equals(ShaderKey other)
{
return
Unsafe.As<int, ulong>(ref Unsafe.AsRef(Id))
== Unsafe.As<int, ulong>(ref Unsafe.AsRef(other.Id)) &&
Unsafe.As<int, ulong>(ref Unsafe.AsRef(ThreadsY))
== Unsafe.As<int, ulong>(ref Unsafe.AsRef(other.ThreadsY));
}
/// <inheritdoc/>
public override bool Equals(object? obj)
{
return obj is ShaderKey other && Equals(other);
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int GetHashCode()
{
ulong ul0 = Unsafe.As<int, ulong>(ref Unsafe.AsRef(Id));
int hash = unchecked((int)ul0) ^ (int)(ul0 >> 32);
ulong ul1 = Unsafe.As<int, ulong>(ref Unsafe.AsRef(ThreadsY));
hash = (hash << 5) + hash + unchecked((int)ul1) ^ ((int)(ul1 >> 32));
return hash;
}
}
}
+62 -73
ファイルの表示
@@ -5,7 +5,6 @@ using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using ComputeSharp.Shaders.Mappings;
namespace ComputeSharp.Shaders.Translation
{
@@ -15,99 +14,102 @@ namespace ComputeSharp.Shaders.Translation
internal static class ShaderHashCodeProvider
{
/// <summary>
/// The mapping of hashcodes to aggregate hashing functions
/// A type containing static info for a given shader type <typeparamref name="T"/>
/// </summary>
private static readonly Dictionary<int, Hasher?> HasherMapping = new Dictionary<int, Hasher?>();
/// <summary>
/// Gets a unique hashcode for the input shader closure
/// </summary>
/// <param name="action">The input <see cref="Action{T}"/> representing the shader to run</param>
[Pure]
public static int GetHashCode(Action<ThreadIds> action)
/// <typeparam name="T">The type of compute shader currently in use</typeparam>
private static class TypeInfo<T>
where T : struct, IComputeShader
{
// Get the delegate hashcode
MethodInfo methodInfo = action.Method;
int hash = methodInfo.GetHashCode();
/// <summary>
/// The id of the compute shader type in use
/// </summary>
public static readonly int Id;
if (!HasherMapping.TryGetValue(hash, out Hasher? hasher))
/// <summary>
/// The optional <see cref="Hasher{T}"/> instance, if needed
/// </summary>
public static readonly Hasher<T>? Hasher;
/// <summary>
/// Initializes the static members of the <see cref="TypeInfo{T}"/> type
/// </summary>
static TypeInfo()
{
// Get the candidate fields for delegate checking
Id = HashCode.Combine(typeof(T));
// Get the valid delegates for delegate checking
FieldInfo[] delegateFieldInfos = (
from fieldInfo in methodInfo.DeclaringType.GetFields()
where fieldInfo.FieldType.IsDelegate() &&
fieldInfo.FieldType.GenericTypeArguments.All(type => HlslKnownTypes.IsKnownScalarType(type) || HlslKnownTypes.IsKnownVectorType(type))
from fieldInfo in typeof(T).GetFields()
where fieldInfo.FieldType.IsDelegate()
select fieldInfo).ToArray();
// If at least one captured delegate is present, build the hasher method
hasher = delegateFieldInfos.Length == 0 ? null : BuildDynamicHasher(action.Method.DeclaringType, delegateFieldInfos);
HasherMapping.Add(hash, hasher);
// If at least one delegate is present, build the hasher method
if (delegateFieldInfos.Length > 0)
{
Hasher = BuildDynamicHasher<T>(delegateFieldInfos);
}
}
}
// Aggregate the hash of the captured delegates, if needed
if (hasher != null) hash = hasher(hash, action.Target);
/// <summary>
/// Gets a unique hashcode for the input compute shader instance
/// </summary>
/// <typeparam name="T">The type of compute shader currently in use</typeparam>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the shader to run</param>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int GetHashCode<T>(in T shader)
where T : struct, IComputeShader
{
int hash = TypeInfo<T>.Id;
Hasher<T>? hasher = TypeInfo<T>.Hasher;
if (hasher != null) hash = hasher(hash, shader);
return hash;
}
/// <summary>
/// A <see langword="delegate"/> that represents an aggregate hash function for a given instance
/// A <see langword="delegate"/> that represents an aggregate hash function for a given <typeparamref name="T"/> instance
/// </summary>
/// <typeparam name="T">The type of compute shader currently in use</typeparam>
/// <param name="hash">The initial hash value</param>
/// <param name="instance">The closure instance to use to compute the final hash value</param>
/// <param name="shader">The compute shader instance to use to compute the final hash value</param>
/// <returns>The final hash value for the input closure</returns>
private delegate int Hasher(int hash, object instance);
private delegate int Hasher<T>(int hash, in T shader)
where T : struct, IComputeShader;
/// <summary>
/// Builds a new <see cref="Hasher"/> instance for the target <see cref="Type"/> and sequence of <see cref="FieldInfo"/> values
/// Builds a new <see cref="Hasher{T}"/> instance for the target <see cref="Type"/> and sequence of <see cref="FieldInfo"/> values
/// </summary>
/// <param name="declaringType">The declaring <see cref="Type"/> to analyze</param>
/// <typeparam name="T">The type of compute shader currently in use</typeparam>
/// <param name="fieldInfos">The list of captured fields to inspect</param>
[Pure]
private static Hasher BuildDynamicHasher(Type declaringType, IReadOnlyCollection<FieldInfo> fieldInfos)
private static Hasher<T> BuildDynamicHasher<T>(IReadOnlyCollection<FieldInfo> fieldInfos)
where T : struct, IComputeShader
{
return DynamicMethod<Hasher>.New(il =>
return DynamicMethod<Hasher<T>>.New(il =>
{
// Declare the local variable to store the target instance
il.DeclareLocal(declaringType);
// Load the argument (the object instance)
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Castclass, declaringType);
il.Emit(OpCodes.Stloc_0);
// Unroll the member access
MethodInfo
validateDelegateInfo = typeof(ShaderHashCodeProvider).GetMethod(nameof(ValidateDelegate), BindingFlags.NonPublic | BindingFlags.Static),
getMethodInfo = typeof(Delegate).GetProperty(nameof(Delegate.Method)).GetMethod,
getHashCodeInfo = typeof(object).GetMethod(nameof(GetHashCode));
getHashCodeInfo = typeof(object).GetMethod(nameof(object.GetHashCode));
foreach (FieldInfo fieldInfo in fieldInfos)
{
Label label = il.DefineLabel();
// if (fieldInfo.GetValue(obj) != null) {
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ldfld, fieldInfo);
il.Emit(OpCodes.Brfalse_S, label);
// if (ValidateDelegate(field)) {
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ldfld, fieldInfo);
il.EmitCall(OpCodes.Call, validateDelegateInfo, null);
il.Emit(OpCodes.Brfalse_S, label);
// hash = hash * 17 + field.Method.GetHashCode();
// (hashcode << 5) + hashcode
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldc_I4_S, (byte)17);
il.Emit(OpCodes.Mul);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ldc_I4_5);
il.Emit(OpCodes.Shl);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Add);
// hashcode += shader.Function[#].Method.GetHashCode();
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldfld, fieldInfo);
il.EmitCall(OpCodes.Callvirt, getMethodInfo, null);
il.EmitCall(OpCodes.Callvirt, getHashCodeInfo, null);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Starg_S, (byte)0);
il.MarkLabel(label);
}
// Return the computed hash
@@ -115,18 +117,5 @@ namespace ComputeSharp.Shaders.Translation
il.Emit(OpCodes.Ret);
});
}
/// <summary>
/// A method that checks whether an input <see cref="Delegate"/> is supported in HLSL
/// </summary>
/// <param name="candidate">The input <see cref="Delegate"/> instance to check</param>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool ValidateDelegate(Delegate candidate)
{
MethodInfo methodInfo = candidate.Method;
return (methodInfo.IsStatic || methodInfo.DeclaringType.IsStatelessDelegateContainer()) &&
(HlslKnownTypes.IsKnownScalarType(methodInfo.ReturnType) || HlslKnownTypes.IsKnownVectorType(methodInfo.ReturnType));
}
}
}
@@ -2,7 +2,6 @@
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
@@ -12,8 +11,8 @@ using ComputeSharp.Shaders.Translation.Models;
namespace ComputeSharp.Shaders.Translation
{
/// <inheritdoc cref="ShaderLoader"/>
internal sealed partial class ShaderLoader
/// <inheritdoc cref="ShaderLoader{T}"/>
internal sealed partial class ShaderLoader<T>
{
/// <summary>
/// The number of captured graphics resources (buffers)
@@ -34,22 +33,22 @@ namespace ComputeSharp.Shaders.Translation
private readonly List<ReadableMember> _CapturedMembers = new List<ReadableMember>();
/// <summary>
/// A <see langword="delegate"/> that loads all the captured members from a shader closure
/// A <see langword="delegate"/> that loads all the captured members from a shader instance
/// </summary>
/// <param name="obj">The shader closure instance to load the data from</param>
/// <param name="shader">The shader instance to load the data from</param>
/// <param name="r0">A reference to the buffer with all the captured <see cref="GraphicsResource"/> instances</param>
/// <param name="r1">A reference to the buffer to use to store all the captured value types</param>
private delegate void DispatchDataLoader(object obj, ref GraphicsResource r0, ref byte r1);
private delegate void DispatchDataLoader(in T shader, ref GraphicsResource r0, ref byte r1);
/// <summary>
/// Gets a new <see cref="DispatchData"/> instance with all the captured data for the current shader instance
/// </summary>
/// <param name="action">The input <see cref="Action{T}"/> representing the compute shader to run</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run</param>
/// <param name="x">The number of iterations to run on the X axis</param>
/// <param name="y">The number of iterations to run on the Y axis</param>
/// <param name="z">The number of iterations to run on the Z axis</param>
[Pure]
public DispatchData GetDispatchData(Action<ThreadIds> action, int x, int y, int z)
public DispatchData GetDispatchData(in T shader, int x, int y, int z)
{
// Resources and variables buffers
GraphicsResource[] resources = ArrayPool<GraphicsResource>.Shared.Rent(_ResourcesCount);
@@ -63,7 +62,7 @@ namespace ComputeSharp.Shaders.Translation
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 2) = z;
// Invoke the dynamic method to extract the captured data
_DispatchDataLoader!(action.Target, ref r0, ref r1);
_DispatchDataLoader!(shader, ref r0, ref r1);
return new DispatchData(resources, _ResourcesCount, variables, _VariablesByteSize);
}
@@ -73,66 +72,8 @@ namespace ComputeSharp.Shaders.Translation
/// </summary>
private void BuildDispatchDataLoader()
{
// Mapping of parent members to index of the relative local variable
var map =
_CapturedMembers
.Where(m => !m.IsStatic && m.Parents != null)
.SelectMany(m => m.Parents)
.Distinct()
.Select((m, i) => (Member: m, Index: i))
.ToDictionary(p => (object)p.Member, p => p.Index + 1);
object root = new object(); // Placeholder
map.Add(root, 0);
// Set of indices of the loaded parent members
HashSet<int> loaded = new HashSet<int>(new[] { 0 });
// Build the dynamic IL method
_DispatchDataLoader = DynamicMethod<DispatchDataLoader>.New(il =>
{
// Loads a given member on the top of the execution stack
void LoadMember(ReadableMember member)
{
if (!member.IsStatic)
{
// Load the parent instance on the execution stack if the member isn't static
int index = map[member.Parents?.Last() ?? root];
if (loaded.Contains(index)) il.EmitLoadLocal(index);
else
{
// Seek upwards to find the most in depth loaded parent
int i = member.Parents!.Count - 1;
while (i > 0 && !loaded.Contains(map[member.Parents[i]])) i--;
// Load the local variables for all the parents of the current member
il.EmitLoadLocal(i);
for (; i < member.Parents.Count; i++)
{
index = map[member.Parents[i]];
il.Emit(OpCodes.Ldfld, member.Parents[i]);
il.EmitStoreLocal(index);
il.EmitLoadLocal(index);
loaded.Add(index);
}
}
}
il.EmitReadMember(member);
}
// Declare the local variables
il.DeclareLocal(ShaderType);
foreach (ReadableMember member in map.OrderBy(p => p.Value).Skip(1).Select(p => p.Key))
{
il.DeclareLocal(member.MemberType);
}
// Cast the closure instance and assign it to the local variable
il.Emit(OpCodes.Ldarg_0);
il.EmitCastOrUnbox(ShaderType);
il.Emit(OpCodes.Stloc_0);
// Handle all the captured members, both resources and variables
foreach (ReadableMember member in _CapturedMembers)
{
if (HlslKnownTypes.IsKnownBufferType(member.MemberType))
@@ -155,11 +96,11 @@ namespace ComputeSharp.Shaders.Translation
}
else throw new InvalidOperationException($"Invalid captured member of type {member.MemberType}");
/* Load the current member accordingly.
* When this method returns, the value of the current
* member will be at the top of the execution stack */
LoadMember(member);
// Load the reference to the input delegate if the member is not static
if (!member.IsStatic) il.Emit(OpCodes.Ldarg_0);
// Read the current member and store it to the target address
il.EmitReadMember(member);
il.EmitStoreToAddress(member.MemberType);
}
@@ -21,24 +21,16 @@ using ParameterInfo = ComputeSharp.Shaders.Renderer.Models.Functions.ParameterIn
namespace ComputeSharp.Shaders.Translation
{
/// <summary>
/// A <see langword="class"/> responsible for loading and processing <see cref="Action{T}"/> instances
/// A <see langword="class"/> responsible for loading and processing shaders of a given type
/// </summary>
internal sealed partial class ShaderLoader
/// <typeparam name="T">The type of compute shader currently in use</typeparam>
internal sealed partial class ShaderLoader<T>
where T : struct, IComputeShader
{
/// <summary>
/// The <see cref="Action{T}"/> that represents the shader to load
/// Creates a new <see cref="ShaderLoader{T}"/> instance
/// </summary>
private readonly Action<ThreadIds> Action;
/// <summary>
/// Creates a new <see cref="ShaderLoader"/> with the specified parameters
/// </summary>
/// <param name="action">The <see cref="Action{T}"/> to use to build the shader</param>
private ShaderLoader(Action<ThreadIds> action)
{
Action = action;
ShaderType = action.Method.DeclaringType;
}
private ShaderLoader() { }
/// <summary>
/// The number of constant buffers to define in the shader
@@ -55,17 +47,12 @@ namespace ComputeSharp.Shaders.Translation
/// </summary>
private int _ReadWriteBuffersCount;
/// <summary>
/// Gets the closure <see cref="Type"/> for the <see cref="Action"/> field
/// </summary>
public Type ShaderType { get; }
/// <summary>
/// The <see cref="List{T}"/> of <see cref="DescriptorRange1"/> items that are required to load the captured values
/// </summary>
private readonly List<DescriptorRange1> DescriptorRanges = new List<DescriptorRange1>();
private RootParameter1[] _RootParameters;
private RootParameter1[]? _RootParameters;
/// <summary>
/// Gets the <see cref="RootParameter1"/> array for the current shader
@@ -111,17 +98,22 @@ namespace ComputeSharp.Shaders.Translation
public IReadOnlyList<LocalFunctionInfo> LocalFunctionsList => _LocalFunctionsList;
/// <summary>
/// Loads and processes an input <see cref="Action{T}"/>
/// Loads and processes an input<typeparamref name="T"/> shadeer
/// </summary>
/// <param name="action">The <see cref="Action{T}"/> to use to build the shader</param>
/// <param name="shader">The <typeparamref name="T"/> instance to use to build the shader</param>
/// <returns>A new <see cref="ShaderLoader"/> instance representing the input shader</returns>
[Pure]
public static ShaderLoader Load(Action<ThreadIds> action)
public static ShaderLoader<T> Load(in T shader)
{
ShaderLoader @this = new ShaderLoader(action);
ShaderLoader<T> @this = new ShaderLoader<T>();
@this.LoadFieldsInfo();
@this.LoadMethodSource();
/* Reading members through reflection requires an object parameter,
* so here we're just boxing the input shader once to avoid allocating
* it multiple times in the managed heap while processing the shader. */
object box = shader;
@this.LoadFieldsInfo(box);
@this.LoadMethodSource(box);
@this.BuildDispatchDataLoader();
return @this;
@@ -130,10 +122,16 @@ namespace ComputeSharp.Shaders.Translation
/// <summary>
/// Loads the fields info for the current shader being loaded
/// </summary>
private void LoadFieldsInfo()
/// <param name="shader">The boxed <typeparamref name="T"/> instance to use to build the shader</param>
private void LoadFieldsInfo(object shader)
{
IReadOnlyList<FieldInfo> shaderFields = ShaderType.GetFields().ToArray();
if (shaderFields.Any(fieldInfo => fieldInfo.IsStatic)) throw new InvalidOperationException("Empty shader body");
IReadOnlyList<FieldInfo> shaderFields = typeof(T).GetFields(
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic).ToArray();
if (shaderFields.Count == 0) throw new InvalidOperationException("Empty shader body");
// Descriptor for the buffer for captured scalar/vector variables
DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.ConstantBufferView, 1, _ConstantBuffersCount++));
@@ -141,17 +139,17 @@ namespace ComputeSharp.Shaders.Translation
// Inspect the captured fields
foreach (FieldInfo fieldInfo in shaderFields)
{
LoadFieldInfo(fieldInfo);
LoadFieldInfo(shader, fieldInfo);
}
}
/// <summary>
/// Loads a specified <see cref="ReadableMember"/> and adds it to the shader model
/// </summary>
/// <param name="shader">The boxed <typeparamref name="T"/> instance to use to build the shader</param>
/// <param name="memberInfo">The target <see cref="ReadableMember"/> to load</param>
/// <param name="name">The optional explicit name to use for the field</param>
/// <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)
private void LoadFieldInfo(object shader, ReadableMember memberInfo, string? name = null)
{
Type fieldType = memberInfo.MemberType;
string fieldName = HlslKnownKeywords.GetMappedName(name ?? memberInfo.Name);
@@ -161,8 +159,6 @@ namespace ComputeSharp.Shaders.Translation
{
DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.ConstantBufferView, 1, _ConstantBuffersCount));
// Track the buffer field
memberInfo.Parents = parents;
_CapturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]);
@@ -173,8 +169,6 @@ namespace ComputeSharp.Shaders.Translation
// Root parameter for a readonly buffer
DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.ShaderResourceView, 1, _ReadOnlyBuffersCount));
// Track the buffer field
memberInfo.Parents = parents;
_CapturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType);
@@ -185,8 +179,6 @@ namespace ComputeSharp.Shaders.Translation
// Root parameter for a read write buffer
DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.UnorderedAccessView, 1, _ReadWriteBuffersCount));
// Track the buffer field
memberInfo.Parents = parents;
_CapturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType);
@@ -194,48 +186,36 @@ namespace ComputeSharp.Shaders.Translation
}
else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType))
{
// Register the captured field
memberInfo.Parents = parents;
_CapturedMembers.Add(memberInfo);
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);
}
}
else if (fieldType.IsDelegate() &&
memberInfo.GetValue(Action.Target) is Delegate func &&
memberInfo.GetValue(shader) is Delegate func &&
(func.Method.IsStatic || func.Method.DeclaringType.IsStatelessDelegateContainer()) &&
(HlslKnownTypes.IsKnownScalarType(func.Method.ReturnType) || HlslKnownTypes.IsKnownVectorType(func.Method.ReturnType)) &&
fieldType.GenericTypeArguments.All(type => HlslKnownTypes.IsKnownScalarType(type) ||
HlslKnownTypes.IsKnownVectorType(type)))
{
// Captured static delegates with a return type
LoadStaticMethodSource(fieldName, func.Method);
LoadStaticMethodSource(shader, fieldName, func.Method);
}
else throw new ArgumentException($"Invalid captured variable of type {fieldType} with name \"{memberInfo.Name}\"");
}
/// <summary>
/// Loads the entry method for the current shader being loaded
/// </summary>
private void LoadMethodSource()
/// <param name="shader">The boxed <typeparamref name="T"/> instance to use to build the shader</param>
private void LoadMethodSource(object shader)
{
// Decompile the shader method
MethodDecompiler.Instance.GetSyntaxTree(Action.Method, MethodType.Closure, out MethodDeclarationSyntax root, out SemanticModel semanticModel);
MethodInfo methodInfo = typeof(T).GetMethod(nameof(IComputeShader.Execute));
MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Execute, out MethodDeclarationSyntax root, out SemanticModel semanticModel);
// Rewrite the shader method (eg. to fix the type declarations)
ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, ShaderType);
ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, typeof(T));
root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root);
// Extract the implicit local functions
@@ -253,18 +233,18 @@ namespace ComputeSharp.Shaders.Translation
// Register the captured static members
foreach (var member in syntaxRewriter.StaticMembers)
{
LoadFieldInfo(member.Value, member.Key);
LoadFieldInfo(shader, member.Value, member.Key);
}
// Register the captured static methods
foreach (var method in syntaxRewriter.StaticMethods)
{
LoadStaticMethodSource(method.Key, method.Value);
LoadStaticMethodSource(shader, method.Key, method.Value);
}
// Get the thread ids identifier name and shader method body
ThreadsIdsVariableName = root.ParameterList.Parameters.First().Identifier.Text;
MethodBody = root.Body.ToFullString();
MethodBody = root.Body!.ToFullString();
// Additional preprocessing
MethodBody = Regex.Replace(MethodBody, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value);
@@ -275,9 +255,10 @@ namespace ComputeSharp.Shaders.Translation
/// <summary>
/// Loads additional static methods used by the shader
/// </summary>
/// <param name="shader">The boxed <typeparamref name="T"/> instance to use to build the shader</param>
/// <param name="name">The HLSL name of the new method to load</param>
/// <param name="methodInfo">The <see cref="MethodInfo"/> instance for the method to load</param>
private void LoadStaticMethodSource(string name, MethodInfo methodInfo)
private void LoadStaticMethodSource(object shader, string name, MethodInfo methodInfo)
{
// Decompile the target method
MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Static, out MethodDeclarationSyntax root, out SemanticModel semanticModel);
@@ -289,26 +270,26 @@ namespace ComputeSharp.Shaders.Translation
// Register the captured static members
foreach (var member in syntaxRewriter.StaticMembers)
{
LoadFieldInfo(member.Value, member.Key);
LoadFieldInfo(shader, member.Value, member.Key);
}
// Register the captured static methods
foreach (var method in syntaxRewriter.StaticMethods)
{
LoadStaticMethodSource(method.Key, method.Value);
LoadStaticMethodSource(shader, method.Key, method.Value);
}
// Get the function parameters
IReadOnlyList<ParameterInfo> parameters = (
from parameter in root.ParameterList.Parameters.Select((p, i) => (Node: p, Index: i))
let modifiers = parameter.Node.Modifiers
let type = parameter.Node.Type.ToFullString()
let type = parameter.Node.Type!.ToFullString()
let parameterName = parameter.Node.Identifier.ToFullString()
let last = parameter.Index == root.ParameterList.Parameters.Count - 1
select new ParameterInfo(modifiers, type, parameterName, last)).ToArray();
// Get the function body
string body = root.Body.ToFullString();
string body = root.Body!.ToFullString();
body = Regex.Replace(body, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value);
body = body.TrimEnd('\n', '\r', ' ');
body = HlslKnownKeywords.GetMappedText(body);
+9 -8
ファイルの表示
@@ -2,7 +2,7 @@
<package >
<metadata>
<id>ComputeSharp</id>
<version>1.3.1</version>
<version>2.0.0</version>
<title>ComputeSharp</title>
<authors>Sergio Pedri</authors>
<owners>Sergio Pedri</owners>
@@ -12,17 +12,18 @@
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>A .NET Standard 2.1 library to run C# code in parallel on the GPU through DX12 and dynamically generated HLSL compute shaders</description>
<releaseNotes>Bug fixes, NuGet updates</releaseNotes>
<copyright>Copyright (c) 2019 Sergio Pedri</copyright>
<copyright>Copyright (c) 2020 Sergio Pedri</copyright>
<tags>dotnet net netcore netstandard csharp library graphics shader hlsl compute gpu</tags>
<repository type="git" url="https://github.com/Sergio0694/ComputeSharp.git" branch="master" />
<dependencies>
<dependency id="Microsoft.Windows.SDK.Contracts" version="10.0.18362.2005" />
<dependency id="System.Runtime.CompilerServices.Unsafe" version="4.6.0" />
<dependency id="Vortice.Direct3D12" version="1.3.0" />
<dependency id="ICSharpCode.Decompiler" version="5.0.1.5145" />
<dependency id="Microsoft.CodeAnalysis.CSharp" version="3.3.1" />
<dependency id="Stubble.Core" version="1.4.12" />
<dependency id="Vortice.Dxc" version="1.3.0" />
<dependency id="System.Runtime.CompilerServices.Unsafe" version="4.7.1" />
<dependency id="Vortice.Direct3D12" version="1.6.0" />
<dependency id="ICSharpCode.Decompiler" version="5.0.2.5153" />
<dependency id="Microsoft.CodeAnalysis.CSharp" version="3.5.0" />
<dependency id="Microsoft.Experimental.Collections" version="1.0.6-e190117-3" />
<dependency id="Stubble.Core" version="1.7.2" />
<dependency id="Vortice.Dxc" version="1.6.0" />
</dependencies>
</metadata>
</package>
+30 -11
ファイルの表示
@@ -1,5 +1,4 @@
using System;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics;
using ComputeSharp.Shaders;
namespace ComputeSharp
@@ -12,33 +11,49 @@ namespace ComputeSharp
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
/// </summary>
/// <typeparam name="T">The type of compute shader to run</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader</param>
/// <param name="x">The number of iterations to run on the X axis</param>
/// <param name="action">The input <see cref="Action{T}"/> representing the compute shader to run</param>
public static void For(this GraphicsDevice device, int x, Action<ThreadIds> action) => ShaderRunner.Run(device, x, 1, 1, action);
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run</param>
public static void For<T>(this GraphicsDevice device, int x, in T shader)
where T : struct, IComputeShader
{
ShaderRunner<T>.Run(device, x, 1, 1, shader);
}
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
/// </summary>
/// <typeparam name="T">The type of compute shader to run</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader</param>
/// <param name="x">The number of iterations to run on the X axis</param>
/// <param name="y">The number of iterations to run on the Y axis</param>
/// <param name="action">The input <see cref="Action{T}"/> representing the compute shader to run</param>
public static void For(this GraphicsDevice device, int x, int y, Action<ThreadIds> action) => ShaderRunner.Run(device, x, y, 1, action);
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run</param>
public static void For<T>(this GraphicsDevice device, int x, int y, in T shader)
where T : struct, IComputeShader
{
ShaderRunner<T>.Run(device, x, y, 1, shader);
}
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
/// </summary>
/// <typeparam name="T">The type of compute shader to run</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader</param>
/// <param name="x">The number of iterations to run on the X axis</param>
/// <param name="y">The number of iterations to run on the Y axis</param>
/// <param name="z">The number of iterations to run on the Z axis</param>
/// <param name="action">The input <see cref="Action{T}"/> representing the compute shader to run</param>
public static void For(this GraphicsDevice device, int x, int y, int z, Action<ThreadIds> action) => ShaderRunner.Run(device, x, y, z, action);
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run</param>
public static void For<T>(this GraphicsDevice device, int x, int y, int z, in T shader)
where T : struct, IComputeShader
{
ShaderRunner<T>.Run(device, x, y, z, shader);
}
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
/// </summary>
/// <typeparam name="T">The type of compute shader to run</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader</param>
/// <param name="x">The number of iterations to run on the X axis</param>
/// <param name="y">The number of iterations to run on the Y axis</param>
@@ -46,11 +61,15 @@ namespace ComputeSharp
/// <param name="threadsX">The number of threads in each thread group for the X axis</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis</param>
/// <param name="action">The input <see cref="Action{T}"/> representing the compute shader to run</param>
public static void For(
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run</param>
public static void For<T>(
this GraphicsDevice device,
int x, int y, int z,
int threadsX, int threadsY, int threadsZ,
Action<ThreadIds> action) => ShaderRunner.Run(device, x, y, z, threadsX, threadsY, threadsZ, action);
in T shader)
where T : struct, IComputeShader
{
ShaderRunner<T>.Run(device, x, y, z, threadsX, threadsY, threadsZ, shader);
}
}
}
+11 -14
ファイルの表示
@@ -21,6 +21,11 @@ namespace ComputeSharp
{
Devices = DeviceHelper.QueryAllSupportedDevices();
IsSupported = Devices.Any();
if (IsSupported)
{
_Default = new GraphicsDevice(Devices[0].Device, Devices[0].Description);
}
}
/// <summary>
@@ -28,25 +33,17 @@ namespace ComputeSharp
/// </summary>
private static readonly IReadOnlyList<(ID3D12Device Device, AdapterDescription Description)> Devices;
/// <summary>
/// Gets whether or not the <see cref="Gpu"/> APIs can be used on the current machine (ie. if there is at least a supported GPU device)
/// </summary>
public static bool IsSupported { get; }
private static GraphicsDevice? _Default;
private static readonly GraphicsDevice? _Default;
/// <summary>
/// Gets the default <see cref="GraphicsDevice"/> instance for the current machine
/// </summary>
public static GraphicsDevice Default
{
get
{
if (!IsSupported) throw new NotSupportedException("There isn't a supported GPU device on the current machine");
public static GraphicsDevice Default => _Default ?? throw new NotSupportedException("There isn't a supported GPU device on the current machine");
return _Default ??= new GraphicsDevice(Devices[0].Device, Devices[0].Description);
}
}
/// <summary>
/// Gets whether or not the <see cref="Gpu"/> APIs can be used on the current machine (ie. if there is at least a supported GPU device)
/// </summary>
public static bool IsSupported { get; }
/// <summary>
/// Enumerates all the available <see cref="GraphicsDevice"/> objects on the current machine
+4 -4
ファイルの表示
@@ -1,15 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<TargetFramework>netcoreapp3.1</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.3.0" />
<PackageReference Include="MSTest.TestAdapter" Version="2.0.0" />
<PackageReference Include="MSTest.TestFramework" Version="2.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
<PackageReference Include="MSTest.TestAdapter" Version="2.1.1" />
<PackageReference Include="MSTest.TestFramework" Version="2.1.1" />
</ItemGroup>
<ItemGroup>
+35 -10
ファイルの表示
@@ -8,25 +8,48 @@ namespace ComputeSharp.Tests.Internals
[TestCategory("ShaderHashCodes")]
public class ShaderHashCodeTests
{
public struct Shader1 : IComputeShader
{
public float A;
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[0] = A;
}
}
[TestMethod]
public void ShaderWithNoCapturedDelegates()
{
float value = 10;
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Action<ThreadIds> action1 = id => buffer[0] = value;
Shader1 shader1 = new Shader1 { A = value, B = buffer };
int
hash1 = ShaderHashCodeProvider.GetHashCode(action1),
hash2 = ShaderHashCodeProvider.GetHashCode(action1);
hash1 = ShaderHashCodeProvider.GetHashCode(shader1),
hash2 = ShaderHashCodeProvider.GetHashCode(shader1);
Assert.IsTrue(hash1 == hash2);
Action<ThreadIds> action2 = id => buffer[0] = value;
Shader1 shader2 = new Shader1 { A = value, B = buffer };
int hash3 = ShaderHashCodeProvider.GetHashCode(action2);
int hash3 = ShaderHashCodeProvider.GetHashCode(shader2);
Assert.IsFalse(hash1 == hash3);
Assert.IsTrue(hash1 == hash3);
}
public struct Shader2 : IComputeShader
{
public float A;
public ReadWriteBuffer<float> B;
public Func<float, float> F;
public void Execute(ThreadIds ids)
{
B[0] = F(A);
}
}
[TestMethod]
@@ -36,17 +59,19 @@ namespace ComputeSharp.Tests.Internals
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Action<ThreadIds> action = id => buffer[0] = f(2);
Shader2 shader1 = new Shader2 { A = 1, B = buffer, F = f };
int
hash1 = ShaderHashCodeProvider.GetHashCode(action),
hash2 = ShaderHashCodeProvider.GetHashCode(action);
hash1 = ShaderHashCodeProvider.GetHashCode(shader1),
hash2 = ShaderHashCodeProvider.GetHashCode(shader1);
Assert.IsTrue(hash1 == hash2);
f = x => x + 1;
int hash3 = ShaderHashCodeProvider.GetHashCode(action);
Shader2 shader2 = new Shader2 { A = 1, B = buffer, F = f };
int hash3 = ShaderHashCodeProvider.GetHashCode(shader2);
Assert.IsFalse(hash1 == hash3);
}
+4 -4
ファイルの表示
@@ -1,15 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<TargetFramework>netcoreapp3.1</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.3.0" />
<PackageReference Include="MSTest.TestAdapter" Version="2.0.0" />
<PackageReference Include="MSTest.TestFramework" Version="2.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
<PackageReference Include="MSTest.TestAdapter" Version="2.1.1" />
<PackageReference Include="MSTest.TestFramework" Version="2.1.1" />
</ItemGroup>
<ItemGroup>
+77 -17
ファイルの表示
@@ -7,18 +7,50 @@ namespace ComputeSharp.Tests
[TestCategory("HlslVectorTypes")]
public class HlslVectorTypesTests
{
private struct SequentialCompilation_Shader_1 : IComputeShader
{
public Float2 F2;
public ReadWriteBuffer<Float2> B;
public void Execute(ThreadIds ids)
{
B[0] = F2.XY;
}
}
private struct SequentialCompilation_Shader_2 : IComputeShader
{
public Float2 F2;
public ReadWriteBuffer<Float2> B;
public void Execute(ThreadIds ids)
{
B[1] = F2.XY;
}
}
[TestMethod]
public void SequentialCompilation()
{
Float2 f2 = new Float2(1, 2);
using ReadWriteBuffer<Float2> buffer = Gpu.Default.AllocateReadWriteBuffer<Float2>(2);
Action<ThreadIds> action1 = id => buffer[0] = f2.YX;
var shader1 = new SequentialCompilation_Shader_1 { F2 = f2, B = buffer };
var shader2 = new SequentialCompilation_Shader_2 { F2 = f2, B = buffer };
Action<ThreadIds> action2 = id => buffer[1] = f2.YX;
Gpu.Default.For(1, shader1);
Gpu.Default.For(1, shader2);
}
Gpu.Default.For(1, action1);
Gpu.Default.For(1, action2);
private struct LocalFloatAssignToFloat2Buffer_Shader : IComputeShader
{
public Float2 F2;
public ReadWriteBuffer<Float2> B;
public void Execute(ThreadIds ids)
{
B[0] = F2.YX;
}
}
[TestMethod]
@@ -27,9 +59,9 @@ namespace ComputeSharp.Tests
Float2 f2 = new Float2(1, 2);
using ReadWriteBuffer<Float2> buffer = Gpu.Default.AllocateReadWriteBuffer<Float2>(1);
Action<ThreadIds> action = id => buffer[0] = f2.YX;
var shader = new LocalFloatAssignToFloat2Buffer_Shader { F2 = f2, B = buffer };
Gpu.Default.For(1, action);
Gpu.Default.For(1, shader);
Float2[] result = buffer.GetData();
@@ -37,29 +69,50 @@ namespace ComputeSharp.Tests
Assert.IsTrue(MathF.Abs(result[0].Y - f2.X) < 0.0001f);
}
private struct Int2Properties_Shader : IComputeShader
{
public ReadWriteBuffer<Int2> B;
public void Execute(ThreadIds ids)
{
B[0] = 1;
}
}
[TestMethod]
public void Int2Properties()
{
using ReadWriteBuffer<Int2> buffer = Gpu.Default.AllocateReadWriteBuffer<Int2>(1);
Action<ThreadIds> action = id => buffer[0].X = 1;
var shader = new Int2Properties_Shader { B = buffer };
Gpu.Default.For(1, action);
Gpu.Default.For(1, shader);
Int2[] result = buffer.GetData();
Assert.IsTrue(result[0].X == 1);
}
private struct LocalBoolAssignToBool2Buffer_Shader : IComputeShader
{
public Bool2 B2;
public ReadWriteBuffer<Bool2> B;
public void Execute(ThreadIds ids)
{
B[0] = B2;
}
}
[TestMethod]
public void LocalBoolAssignToBool2Buffer()
{
Bool2 b2 = Bool2.TrueY;
using ReadWriteBuffer<Bool2> buffer = Gpu.Default.AllocateReadWriteBuffer<Bool2>(1);
Action<ThreadIds> action = id => buffer[0] = b2;
var shader = new LocalBoolAssignToBool2Buffer_Shader { B2 = b2, B = buffer };
Gpu.Default.For(1, action);
Gpu.Default.For(1, shader);
Bool2[] result = buffer.GetData();
@@ -67,19 +120,26 @@ namespace ComputeSharp.Tests
Assert.IsTrue(result[0].Y == b2.Y);
}
private struct Bool3Operations_Shader : IComputeShader
{
public ReadWriteBuffer<Bool3> B;
public void Execute(ThreadIds ids)
{
B[0] = Bool3.TrueX;
B[1] = Bool3.True;
B[2].YZ = Bool2.True;
}
}
[TestMethod]
public void Bool3Operations()
{
using ReadWriteBuffer<Bool3> buffer = Gpu.Default.AllocateReadWriteBuffer<Bool3>(3);
Action<ThreadIds> action = id =>
{
buffer[0] = Bool3.TrueX;
buffer[1] = Bool3.True;
buffer[2].YZ = Bool2.True;
};
var shader = new Bool3Operations_Shader { B = buffer };
Gpu.Default.For(1, action);
Gpu.Default.For(1, shader);
Bool3[] result = buffer.GetData();
+12 -2
ファイルの表示
@@ -17,6 +17,16 @@ namespace ComputeSharp.Tests
else Assert.ThrowsException<NotSupportedException>(() => Gpu.Default);
}
private struct RunShaderOnAllDevicesShader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[ids.X] = ids.X;
}
}
[TestMethod]
public void RunShaderOnAllDevices()
{
@@ -24,9 +34,9 @@ namespace ComputeSharp.Tests
{
using (ReadWriteBuffer<float> buffer = gpu.AllocateReadWriteBuffer<float>(100))
{
Action<ThreadIds> action = id => buffer[id.X] = id.X;
var shader = new RunShaderOnAllDevicesShader { B = buffer };
gpu.For(100, action);
gpu.For(100, shader);
float[] array = buffer.GetData();
float[] expected = Enumerable.Range(0, 100).Select(i => (float)i).ToArray();
+75 -24
ファイルの表示
@@ -39,60 +39,97 @@ namespace ComputeSharp.Tests
[TestCategory("StaticFields")]
public class InternalStaticMembersTests
{
private struct StaticReadonlyScalarFieldAssignToBuffer_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[0] = StaticMembersContainer.ReadonlyFloat;
}
}
[TestMethod]
public void StaticReadonlyScalarFieldAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Action<ThreadIds> action = id => buffer[0] = StaticMembersContainer.ReadonlyFloat;
var shader = new StaticReadonlyScalarFieldAssignToBuffer_Shader { B = buffer };
Gpu.Default.For(1, action);
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - StaticMembersContainer.ReadonlyFloat) < 0.0001f);
}
private struct StaticScalarFieldAssignToBuffer_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[0] = StaticMembersContainer.StaticFloat;
}
}
[TestMethod]
public void StaticScalarFieldAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Action<ThreadIds> action = id => buffer[0] = StaticMembersContainer.StaticFloat;
var shader = new StaticScalarFieldAssignToBuffer_Shader { B = buffer };
Gpu.Default.For(1, action);
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - StaticMembersContainer.StaticFloat) < 0.0001f);
}
private struct StaticScalarFieldRepeatedAssignToBuffer_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[0] = StaticMembersContainer.StaticFloat + StaticMembersContainer.StaticFloat;
}
}
[TestMethod]
public void StaticScalarFieldRepeatedAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Action<ThreadIds> action = id => buffer[0] = StaticMembersContainer.StaticFloat + StaticMembersContainer.StaticFloat;
var shader = new StaticScalarFieldRepeatedAssignToBuffer_Shader { B = buffer };
Gpu.Default.For(1, action);
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - StaticMembersContainer.StaticFloat * 2) < 0.0001f);
}
private struct StaticReadonlyVectorFieldAssignToBuffer_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
if (ids.X == 0) B[0] = StaticMembersContainer.ReadonlyVector2.X;
else B[1] = StaticMembersContainer.ReadonlyVector2.Y;
}
}
[TestMethod]
public void StaticReadonlyVectorFieldAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(2);
Action<ThreadIds> action = id =>
{
if (id.X == 0) buffer[0] = StaticMembersContainer.ReadonlyVector2.X;
else buffer[1] = StaticMembersContainer.ReadonlyVector2.Y;
};
var shader = new StaticReadonlyVectorFieldAssignToBuffer_Shader { B = buffer };
Gpu.Default.For(2, action);
Gpu.Default.For(2, shader);
float[] result = buffer.GetData();
@@ -100,18 +137,25 @@ namespace ComputeSharp.Tests
Assert.IsTrue(MathF.Abs(result[1] - StaticMembersContainer.ReadonlyVector2.Y) < 0.0001f);
}
private struct StaticVectorFieldAssignToBuffer_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
if (ids.X == 0) B[0] = StaticMembersContainer.StaticVector2.X;
else B[1] = StaticMembersContainer.StaticVector2.Y;
}
}
[TestMethod]
public void StaticVectorFieldAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(2);
Action<ThreadIds> action = id =>
{
if (id.X == 0) buffer[0] = StaticMembersContainer.StaticVector2.X;
else buffer[1] = StaticMembersContainer.StaticVector2.Y;
};
var shader = new StaticVectorFieldAssignToBuffer_Shader { B = buffer };
Gpu.Default.For(2, action);
Gpu.Default.For(2, shader);
float[] result = buffer.GetData();
@@ -119,18 +163,25 @@ namespace ComputeSharp.Tests
Assert.IsTrue(MathF.Abs(result[1] - StaticMembersContainer.StaticVector2.Y) < 0.0001f);
}
private struct StaticReadOnlyBufferFieldAssignToBuffer_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
if (ids.X == 0) B[0] = StaticMembersContainer.StaticBuffer[0];
else B[1] = StaticMembersContainer.StaticBuffer[1];
}
}
[TestMethod]
public void StaticReadOnlyBufferFieldAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(2);
Action<ThreadIds> action = id =>
{
if (id.X == 0) buffer[0] = StaticMembersContainer.StaticBuffer[0];
else buffer[1] = StaticMembersContainer.StaticBuffer[1];
};
var shader = new StaticReadOnlyBufferFieldAssignToBuffer_Shader { B = buffer };
Gpu.Default.For(2, action);
Gpu.Default.For(2, shader);
float[] result = buffer.GetData();
float[] expected = StaticMembersContainer.StaticBuffer.GetData();
+47 -23
ファイルの表示
@@ -7,22 +7,30 @@ namespace ComputeSharp.Tests
[TestCategory("Intrinsics")]
public class IntrinsicTests
{
private struct IntrinsicWithInlineOutParamater_Shader : IComputeShader
{
public float A;
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[0] = Hlsl.Sin(A);
B[1] = Hlsl.Cos(A);
Hlsl.SinCos(A, out float sine, out float cosine);
B[2] = sine;
B[3] = cosine;
}
}
[TestMethod]
public void IntrinsicWithInlineOutParamater()
{
float angle = 80;
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(4);
Action<ThreadIds> action = id =>
{
buffer[0] = Hlsl.Sin(angle);
buffer[1] = Hlsl.Cos(angle);
Hlsl.SinCos(angle, out float sine, out float cosine);
buffer[2] = sine;
buffer[3] = cosine;
};
var shader = new IntrinsicWithInlineOutParamater_Shader { A = angle, B = buffer };
Gpu.Default.For(1, action);
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
@@ -30,40 +38,56 @@ namespace ComputeSharp.Tests
Assert.IsTrue(MathF.Abs(result[1] - result[3]) < 0.0001f);
}
private struct IntrinsicWithInlineOutParamaterAndDiscard_Shader : IComputeShader
{
public float A;
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[0] = Hlsl.Sin(A);
Hlsl.SinCos(A, out float sine, out _);
B[1] = sine;
}
}
[TestMethod]
public void IntrinsicWithInlineOutParamaterAndDiscard()
{
float angle = 80;
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(2);
Action<ThreadIds> action = id =>
{
buffer[0] = Hlsl.Sin(angle);
Hlsl.SinCos(angle, out float sine, out _);
buffer[1] = sine;
};
var shader = new IntrinsicWithInlineOutParamaterAndDiscard_Shader { A = angle, B = buffer };
Gpu.Default.For(1, action);
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - result[1]) < 0.0001f);
}
private struct IntrinsicWithOutParamaters_Shader : IComputeShader
{
public float A;
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[0] = Hlsl.Sin(A);
B[1] = Hlsl.Cos(A);
Hlsl.SinCos(A, out B[2], out B[3]);
}
}
[TestMethod]
public void IntrinsicWithOutParamaters()
{
float angle = 80;
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(4);
Action<ThreadIds> action = id =>
{
buffer[0] = Hlsl.Sin(angle);
buffer[1] = Hlsl.Cos(angle);
Hlsl.SinCos(angle, out buffer[2], out buffer[3]);
};
var shader = new IntrinsicWithOutParamaters_Shader { A = angle, B = buffer };
Gpu.Default.For(1, action);
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
+24 -7
ファイルの表示
@@ -10,24 +10,41 @@ namespace ComputeSharp.Tests
[TestCategory("InvalidShader")]
public class InvalidShaderTests
{
[TestMethod]
public void EmptyShaderCompileError()
private struct EmptyShaderCompileError_Shader : IComputeShader
{
Action<ThreadIds> action = id => { };
Assert.ThrowsException<InvalidOperationException>(() => Gpu.Default.For(10, action));
public void Execute(ThreadIds ids) { }
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void EmptyShaderCompileError()
{
var shader = default(EmptyShaderCompileError_Shader);
Gpu.Default.For(10, shader);
}
private struct DeviceMismatchException_Shader : IComputeShader
{
public ReadWriteBuffer<int> B;
public void Execute(ThreadIds ids)
{
B[0] = 1;
}
}
[TestMethod]
[ExpectedException(typeof(GraphicsDeviceMismatchException))]
public void DeviceMismatchException()
{
ReadWriteBuffer<int> buffer = Gpu.Default.AllocateReadWriteBuffer<int>(1);
GraphicsDevice device = Gpu.EnumerateDevices().First();
Action<ThreadIds> action = id => buffer[0] = 1;
var shader = new DeviceMismatchException_Shader { B = buffer };
Assert.ThrowsException<GraphicsDeviceMismatchException>(() => device.For(1, action));
device.For(1, shader);
}
}
}
+83 -97
ファイルの表示
@@ -10,19 +10,33 @@ namespace ComputeSharp.Tests
[TestCategory("ShaderClosure")]
public class ShaderClosureTests
{
private struct LocalScalarAssignToBuffer_Shader<T> : IComputeShader where T : unmanaged
{
public T Value;
public T Zero;
public ReadWriteBuffer<T> B;
public void Execute(ThreadIds ids)
{
if (ids.X % 2 == 0) B[ids.X] = Value;
else B[ids.X] = Zero;
}
}
private static void LocalScalarAssignToBuffer<T>(T value, Func<T, T, bool> equals) where T : unmanaged
{
using ReadWriteBuffer<T> buffer = Gpu.Default.AllocateReadWriteBuffer<T>(4);
T zero = default;
Action<ThreadIds> action = id =>
var shader = new LocalScalarAssignToBuffer_Shader<T>
{
if (id.X % 2 == 0) buffer[id.X] = value;
else buffer[id.X] = zero;
Value = value,
Zero = zero,
B = buffer
};
Gpu.Default.For(4, action);
Gpu.Default.For(4, shader);
T[] result = buffer.GetData();
@@ -41,19 +55,27 @@ namespace ComputeSharp.Tests
LocalScalarAssignToBuffer<Bool>(true, (a, b) => a == b);
}
private struct ShaderWithBoolType_Shader : IComputeShader
{
public ReadWriteBuffer<Bool> B;
public ReadWriteBuffer<int> I;
public void Execute(ThreadIds ids)
{
if (B[ids.X]) I[ids.X] = ids.X + 1;
B[ids.X] = (ids.X % 2) == 0;
}
}
[TestMethod]
public void ShaderWithBoolType()
{
using ReadWriteBuffer<Bool> bools = Gpu.Default.AllocateReadWriteBuffer(new Bool[] { true, false, true, true });
using ReadWriteBuffer<int> ints = Gpu.Default.AllocateReadWriteBuffer<int>(4);
void Foo(ThreadIds id)
{
if (bools[id.X]) ints[id.X] = id.X + 1;
bools[id.X] = (id.X % 2) == 0;
}
var shader = new ShaderWithBoolType_Shader { B = bools, I = ints };
Gpu.Default.For(4, Foo);
Gpu.Default.For(4, shader);
Bool[] boolResults = bools.GetData();
@@ -70,19 +92,18 @@ namespace ComputeSharp.Tests
Assert.IsTrue(intResults[3] == 4);
}
[TestMethod]
public void LocalScalarAssignToBufferWithinLocalMethod()
private struct LocalKnownVectorAssignToBuffer_Shader : IComputeShader
{
float value = 10;
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
public Vector4 V4;
public ReadWriteBuffer<float> B;
void Foo(ThreadIds id) => buffer[0] = value;
Gpu.Default.For(1, Foo);
float[] result = buffer.GetData();
Assert.IsTrue((int)result[0] == (int)value);
public void Execute(ThreadIds ids)
{
if (ids.X == 0) B[0] = V4.X;
else if (ids.X == 1) B[1] = V4.Y;
else if (ids.X == 2) B[2] = V4.Z;
else if (ids.X == 3) B[3] = V4.W;
}
}
[TestMethod]
@@ -91,15 +112,9 @@ namespace ComputeSharp.Tests
Vector4 vector4 = new Vector4(1, 2, 3, 4);
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(4);
Action<ThreadIds> action = id =>
{
if (id.X == 0) buffer[0] = vector4.X;
else if (id.X == 1) buffer[1] = vector4.Y;
else if (id.X == 2) buffer[2] = vector4.Z;
else if (id.X == 3) buffer[3] = vector4.W;
};
var shader = new LocalKnownVectorAssignToBuffer_Shader { V4 = vector4, B = buffer };
Gpu.Default.For(4, action);
Gpu.Default.For(4, shader);
float[] result = buffer.GetData();
float[] expected = { 1, 2, 3, 4 };
@@ -107,6 +122,17 @@ namespace ComputeSharp.Tests
Assert.IsTrue(result.AsSpan().ContentEquals(expected));
}
private struct CopyBetweenConstantAndWriteableBuffers_Shader : IComputeShader
{
public ConstantBuffer<float> C;
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[ids.X] = C[ids.X];
}
}
[TestMethod]
public void CopyBetweenConstantAndWriteableBuffers()
{
@@ -115,15 +141,26 @@ namespace ComputeSharp.Tests
using ConstantBuffer<float> input = Gpu.Default.AllocateConstantBuffer(source);
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(source.Length);
Action<ThreadIds> action = id => buffer[id.X] = input[id.X];
var shader = new CopyBetweenConstantAndWriteableBuffers_Shader { C = input, B = buffer };
Gpu.Default.For(source.Length, action);
Gpu.Default.For(source.Length, shader);
float[] result = buffer.GetData();
Assert.IsTrue(result.AsSpan().ContentEquals(source));
}
private struct CopyBetweenReadOnlyAndWriteableBuffers_Shader : IComputeShader
{
public ReadOnlyBuffer<float> IN;
public ReadWriteBuffer<float> OUT;
public void Execute(ThreadIds ids)
{
OUT[ids.X] = IN[ids.X];
}
}
[TestMethod]
public void CopyBetweenReadOnlyAndWriteableBuffers()
{
@@ -132,15 +169,26 @@ namespace ComputeSharp.Tests
using ReadOnlyBuffer<float> input = Gpu.Default.AllocateReadOnlyBuffer(source);
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(source.Length);
Action<ThreadIds> action = id => buffer[id.X] = input[id.X];
var shader = new CopyBetweenReadOnlyAndWriteableBuffers_Shader { IN = input, OUT = buffer };
Gpu.Default.For(source.Length, action);
Gpu.Default.For(source.Length, shader);
float[] result = buffer.GetData();
Assert.IsTrue(result.AsSpan().ContentEquals(source));
}
private struct CopyBetweenWriteableBuffers_Shader : IComputeShader
{
public ReadWriteBuffer<float> IN;
public ReadWriteBuffer<float> OUT;
public void Execute(ThreadIds ids)
{
OUT[ids.X] = IN[ids.X];
}
}
[TestMethod]
public void CopyBetweenWriteableBuffers()
{
@@ -149,75 +197,13 @@ namespace ComputeSharp.Tests
using ReadWriteBuffer<float> input = Gpu.Default.AllocateReadWriteBuffer(source);
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(source.Length);
Action<ThreadIds> action = id => buffer[id.X] = input[id.X];
var shader = new CopyBetweenWriteableBuffers_Shader { IN = input, OUT = buffer };
Gpu.Default.For(source.Length, action);
Gpu.Default.For(source.Length, shader);
float[] result = buffer.GetData();
Assert.IsTrue(result.AsSpan().ContentEquals(source));
}
[TestMethod]
public void CopyBetweenNestedClosuresEasy()
{
int value1 = 1;
using (ReadWriteBuffer<int> buffer1 = Gpu.Default.AllocateReadWriteBuffer<int>(1))
{
int value2 = 2;
Action<ThreadIds> action = id =>
{
int sum = value1 + value2;
buffer1[0] = sum;
};
Gpu.Default.For(1, action);
int[] result1 = buffer1.GetData();
Assert.IsTrue(result1[0] == value1 + value2);
}
}
[TestMethod]
public void CopyBetweenNestedClosuresHard()
{
int value1 = 1, value2 = 55, value3 = 77;
using (ReadWriteBuffer<int> buffer1 = Gpu.Default.AllocateReadWriteBuffer<int>(1))
{
int value4 = 2, value5 = 24, value6 = 99;
using (ReadWriteBuffer<int> buffer2 = Gpu.Default.AllocateReadWriteBuffer<int>(1))
{
int value7 = 3, value8 = 12, value9 = 333;
using (ReadWriteBuffer<int> buffer3 = Gpu.Default.AllocateReadWriteBuffer<int>(1))
{
int value10 = 4, value11 = 22;
Action<ThreadIds> action = id =>
{
int sum_gpu =
value1 + value2 + value3 + value4 +
value5 + value6 + value7 + value8 +
value9 + value10 + value11;
buffer1[0] = buffer2[0] = buffer3[0] = sum_gpu;
};
Gpu.Default.For(1, action);
int[] result1 = buffer1.GetData();
int[] result2 = buffer2.GetData();
int[] result3 = buffer3.GetData();
int sum_cpu =
value1 + value2 + value3 + value4 +
value5 + value6 + value7 + value8 +
value9 + value10 + value11;
Assert.IsTrue(result1[0] == sum_cpu);
Assert.IsTrue(result2[0] == sum_cpu);
Assert.IsTrue(result3[0] == sum_cpu);
}
}
}
}
}
}
+40 -10
ファイルの表示
@@ -9,14 +9,24 @@ namespace ComputeSharp.Tests
[TestCategory("ShaderDispatch")]
public class ShaderDispatch
{
private struct WriteToReadWriteBufferDispatch1D_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[ids.X] = ids.X;
}
}
[TestMethod]
public void WriteToReadWriteBufferDispatch1D()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(100);
Action<ThreadIds> action = id => buffer[id.X] = id.X;
var shader = new WriteToReadWriteBufferDispatch1D_Shader { B = buffer };
Gpu.Default.For(100, action);
Gpu.Default.For(100, shader);
float[] array = buffer.GetData();
float[] expected = Enumerable.Range(0, 100).Select(i => (float)i).ToArray();
@@ -29,9 +39,9 @@ namespace ComputeSharp.Tests
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(100);
Action<ThreadIds> action = id => buffer[id.X] = id.X;
var shader = new WriteToReadWriteBufferDispatch1D_Shader { B = buffer };
Gpu.Default.For(100, 1, 1, 64, 1, 1, action);
Gpu.Default.For(100, 1, 1, 64, 1, 1, shader);
float[] array = buffer.GetData();
float[] expected = Enumerable.Range(0, 100).Select(i => (float)i).ToArray();
@@ -39,14 +49,24 @@ namespace ComputeSharp.Tests
Assert.IsTrue(array.AsSpan().ContentEquals(expected));
}
private struct WriteToReadWriteBufferDispatch2D_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[ids.X + ids.Y * 10] = ids.X + ids.Y * 10;
}
}
[TestMethod]
public void WriteToReadWriteBufferDispatch2D()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(100);
Action<ThreadIds> action = id => buffer[id.X + id.Y * 10] = id.X + id.Y * 10;
var shader = new WriteToReadWriteBufferDispatch2D_Shader { B = buffer };
Gpu.Default.For(10, 10, action);
Gpu.Default.For(10, 10, shader);
float[] array = buffer.GetData();
float[] expected = Enumerable.Range(0, 100).Select(i => (float)i).ToArray();
@@ -54,14 +74,24 @@ namespace ComputeSharp.Tests
Assert.IsTrue(array.AsSpan().ContentEquals(expected));
}
private struct WriteToReadWriteBufferDispatch3D_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[ids.X + ids.Y * 10 + ids.Z * 100] = ids.X + ids.Y * 10 + ids.Z * 100;
}
}
[TestMethod]
public void WriteToReadWriteBufferDispatch3D()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1000);
Action<ThreadIds> action = id => buffer[id.X + id.Y * 10 + id.Z * 100] = id.X + id.Y * 10 + id.Z * 100;
var shader = new WriteToReadWriteBufferDispatch3D_Shader { B = buffer };
Gpu.Default.For(10, 10, 10, action);
Gpu.Default.For(10, 10, 10, shader);
float[] array = buffer.GetData();
float[] expected = Enumerable.Range(0, 1000).Select(i => (float)i).ToArray();
@@ -74,9 +104,9 @@ namespace ComputeSharp.Tests
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1000);
Action<ThreadIds> action = id => buffer[id.X + id.Y * 10 + id.Z * 100] = id.X + id.Y * 10 + id.Z * 100;
var shader = new WriteToReadWriteBufferDispatch3D_Shader { B = buffer };
Gpu.Default.For(10, 10, 10, 4, 4, 4, action);
Gpu.Default.For(10, 10, 10, 4, 4, 4, shader);
float[] array = buffer.GetData();
float[] expected = Enumerable.Range(0, 1000).Select(i => (float)i).ToArray();
+75 -24
ファイルの表示
@@ -39,60 +39,97 @@ namespace ComputeSharp.Tests
[TestCategory("StaticFields")]
public class StaticFieldsTests
{
private struct StaticReadonlyScalarFieldAssignToBuffer_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[0] = StaticFieldsContainer.ReadonlyFloat;
}
}
[TestMethod]
public void StaticReadonlyScalarFieldAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Action<ThreadIds> action = id => buffer[0] = StaticFieldsContainer.ReadonlyFloat;
var shader = new StaticReadonlyScalarFieldAssignToBuffer_Shader { B = buffer };
Gpu.Default.For(1, action);
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - StaticFieldsContainer.ReadonlyFloat) < 0.0001f);
}
private struct StaticScalarFieldAssignToBuffer_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[0] = StaticFieldsContainer.StaticFloat;
}
}
[TestMethod]
public void StaticScalarFieldAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Action<ThreadIds> action = id => buffer[0] = StaticFieldsContainer.StaticFloat;
var shader = new StaticScalarFieldAssignToBuffer_Shader { B = buffer };
Gpu.Default.For(1, action);
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - StaticFieldsContainer.StaticFloat) < 0.0001f);
}
private struct StaticScalarFieldRepeatedAssignToBuffer_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[0] = StaticFieldsContainer.StaticFloat + StaticFieldsContainer.StaticFloat;
}
}
[TestMethod]
public void StaticScalarFieldRepeatedAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Action<ThreadIds> action = id => buffer[0] = StaticFieldsContainer.StaticFloat + StaticFieldsContainer.StaticFloat;
var shader = new StaticScalarFieldRepeatedAssignToBuffer_Shader { B = buffer };
Gpu.Default.For(1, action);
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - StaticFieldsContainer.StaticFloat * 2) < 0.0001f);
}
private struct StaticReadonlyVectorFieldAssignToBuffer_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
if (ids.X == 0) B[0] = StaticFieldsContainer.ReadonlyVector2.X;
else B[1] = StaticFieldsContainer.ReadonlyVector2.Y;
}
}
[TestMethod]
public void StaticReadonlyVectorFieldAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(2);
Action<ThreadIds> action = id =>
{
if (id.X == 0) buffer[0] = StaticFieldsContainer.ReadonlyVector2.X;
else buffer[1] = StaticFieldsContainer.ReadonlyVector2.Y;
};
var shader = new StaticReadonlyVectorFieldAssignToBuffer_Shader { B = buffer };
Gpu.Default.For(2, action);
Gpu.Default.For(2, shader);
float[] result = buffer.GetData();
@@ -100,18 +137,25 @@ namespace ComputeSharp.Tests
Assert.IsTrue(MathF.Abs(result[1] - StaticFieldsContainer.ReadonlyVector2.Y) < 0.0001f);
}
private struct StaticVectorFieldAssignToBuffer_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
if (ids.X == 0) B[0] = StaticFieldsContainer.StaticVector2.X;
else B[1] = StaticFieldsContainer.StaticVector2.Y;
}
}
[TestMethod]
public void StaticVectorFieldAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(2);
Action<ThreadIds> action = id =>
{
if (id.X == 0) buffer[0] = StaticFieldsContainer.StaticVector2.X;
else buffer[1] = StaticFieldsContainer.StaticVector2.Y;
};
var shader = new StaticVectorFieldAssignToBuffer_Shader { B = buffer };
Gpu.Default.For(2, action);
Gpu.Default.For(2, shader);
float[] result = buffer.GetData();
@@ -119,18 +163,25 @@ namespace ComputeSharp.Tests
Assert.IsTrue(MathF.Abs(result[1] - StaticFieldsContainer.StaticVector2.Y) < 0.0001f);
}
private struct StaticReadOnlyBufferFieldAssignToBuffer_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
if (ids.X == 0) B[0] = StaticFieldsContainer.StaticBuffer[0];
else B[1] = StaticFieldsContainer.StaticBuffer[1];
}
}
[TestMethod]
public void StaticReadOnlyBufferFieldAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(2);
Action<ThreadIds> action = id =>
{
if (id.X == 0) buffer[0] = StaticFieldsContainer.StaticBuffer[0];
else buffer[1] = StaticFieldsContainer.StaticBuffer[1];
};
var shader = new StaticReadOnlyBufferFieldAssignToBuffer_Shader { B = buffer };
Gpu.Default.For(2, action);
Gpu.Default.For(2, shader);
float[] result = buffer.GetData();
float[] expected = StaticFieldsContainer.StaticBuffer.GetData();
+214 -24
ファイルの表示
@@ -7,14 +7,77 @@ namespace ComputeSharp.Tests
[TestCategory("StaticFunctions")]
public class StaticFunctionsTests
{
private struct ExternalStaticFunctionDirect_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[0] = StaticMethodsContainer.Square(4);
}
}
[TestMethod]
public void ExternalStaticFunctionDirect()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
var shader = new ExternalStaticFunctionDirect_Shader { B = buffer };
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - 16) < 0.0001f);
}
private struct ExternalStaticFunctionWithAttributesDirect_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[0] = StaticMethodsContainer.SquareWithAttributes(4);
}
}
[TestMethod]
public void ExternalStaticFunctionWithAttributesDirect()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
var shader = new ExternalStaticFunctionWithAttributesDirect_Shader { B = buffer };
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - 16) < 0.0001f);
}
private struct FloatToFloatFunc_Shader : IComputeShader
{
public Func<float, float> F;
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[0] = F(3);
}
}
[TestMethod]
public void FloatToFloatFunc()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Func<float, float> square = StaticMethodsContainer.Square;
var shader = new FloatToFloatFunc_Shader
{
F = StaticMethodsContainer.Square,
B = buffer
};
Gpu.Default.For(1, id => buffer[0] = square(3));
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
@@ -28,7 +91,13 @@ namespace ComputeSharp.Tests
Func<float, float> square = StaticMethodsContainer.InternalSquare;
Gpu.Default.For(1, id => buffer[0] = square(3));
var shader = new FloatToFloatFunc_Shader
{
F = square,
B = buffer
};
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
@@ -40,23 +109,39 @@ namespace ComputeSharp.Tests
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Func<float, float> func = StaticMethodsContainer.Square;
var shader = new FloatToFloatFunc_Shader
{
F = StaticMethodsContainer.Square,
B = buffer
};
Gpu.Default.For(1, id => buffer[0] = func(3));
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f);
func = StaticMethodsContainer.Negate;
shader.F = StaticMethodsContainer.Negate;
Gpu.Default.For(1, id => buffer[0] = func(3));
Gpu.Default.For(1, shader);
result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] + 3) < 0.0001f);
}
private struct ChangingFuncsFromExternalMethod_Shader : IComputeShader
{
public Func<float, float> F;
public ReadWriteBuffer<float> B;
public float I;
public void Execute(ThreadIds ids)
{
B[0] = F(I);
}
}
[TestMethod]
public void ChangingFuncsFromExternalMethod()
{
@@ -69,7 +154,14 @@ namespace ComputeSharp.Tests
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Gpu.Default.For(1, id => buffer[0] = func(input));
var shader = new ChangingFuncsFromExternalMethod_Shader
{
F = func,
B = buffer,
I = input
};
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
@@ -78,6 +170,17 @@ namespace ComputeSharp.Tests
public delegate float Squarer(float x);
private struct CustomStaticDelegate_Shader : IComputeShader
{
public Squarer F;
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[0] = F(3);
}
}
[TestMethod]
public void CustomStaticDelegate()
{
@@ -85,7 +188,13 @@ namespace ComputeSharp.Tests
Squarer square = StaticMethodsContainer.Square;
Gpu.Default.For(1, id => buffer[0] = square(3));
var shader = new CustomStaticDelegate_Shader
{
F = square,
B = buffer
};
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
@@ -99,7 +208,13 @@ namespace ComputeSharp.Tests
Func<float, float> f = x => x * x;
Gpu.Default.For(1, id => buffer[0] = f(3));
var shader = new FloatToFloatFunc_Shader
{
F = f,
B = buffer
};
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
@@ -115,7 +230,33 @@ namespace ComputeSharp.Tests
Func<float, float> f = Func;
Gpu.Default.For(1, id => buffer[0] = f(3));
var shader = new FloatToFloatFunc_Shader
{
F = f,
B = buffer
};
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f);
}
[TestMethod]
public void StaticLocalFunction()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
static float f(float x) => x * x;
var shader = new FloatToFloatFunc_Shader
{
F = f,
B = buffer
};
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
@@ -129,7 +270,13 @@ namespace ComputeSharp.Tests
float f(float x) => x * x;
Gpu.Default.For(1, id => buffer[0] = f(3));
var shader = new FloatToFloatFunc_Shader
{
F = f,
B = buffer
};
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
@@ -138,12 +285,24 @@ namespace ComputeSharp.Tests
public static float Square(float x) => x * x;
private struct StaticMethodInSameClass_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[0] = Square(3);
}
}
[TestMethod]
public void StaticMethodInSameClass()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Gpu.Default.For(1, id => buffer[0] = Square(3));
var shader = new StaticMethodInSameClass_Shader { B = buffer };
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
@@ -152,46 +311,77 @@ namespace ComputeSharp.Tests
public static Func<float, float> SquareFunc { get; } = x => x * x;
private struct StaticFunctionInSameClass_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[0] = SquareFunc(3);
}
}
[TestMethod]
public void StaticFunctionInSameClass()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Gpu.Default.For(1, id => buffer[0] = SquareFunc(3));
var shader = new StaticFunctionInSameClass_Shader { B = buffer };
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f);
}
private struct StaticFunctionInExternalClass_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[0] = StaticPropertiesContainer.SquareFunc(3);
}
}
[TestMethod]
public void StaticFunctionInExternalClass()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Gpu.Default.For(1, id => buffer[0] = StaticPropertiesContainer.SquareFunc(3));
var shader = new StaticFunctionInExternalClass_Shader { B = buffer };
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f);
}
private static float Sigmoid(float x) => 1 / (1 + Hlsl.Exp(-x));
private struct ReadmeSample_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
int offset = ids.X + ids.Y * 1;
float pow = Hlsl.Pow(B[offset], 2); // 9
B[offset] = Sigmoid(pow); // 0.9998766
}
}
[TestMethod]
public void ReadmeSample()
{
float[] buffer = { 3 };
using ReadWriteBuffer<float> xBuffer = Gpu.Default.AllocateReadWriteBuffer(buffer);
static float Sigmoid(float x) => 1 / (1 + Hlsl.Exp(-x));
var shader = new ReadmeSample_Shader { B = xBuffer };
void Kernel(ThreadIds id)
{
int offset = id.X + id.Y * 1;
float pow = Hlsl.Pow(xBuffer[offset], 2); // 9
xBuffer[offset] = Sigmoid(pow); // 0.9998766
}
Gpu.Default.For(1, Kernel);
Gpu.Default.For(1, shader);
float[] result = xBuffer.GetData();
+85 -6
ファイルの表示
@@ -1,5 +1,7 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ComputeSharp.Tests
@@ -12,6 +14,11 @@ namespace ComputeSharp.Tests
[Pure]
public static float Square(float x) => x * x;
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NotNull]
public static float SquareWithAttributes(float x) => x * x;
[Pure]
public static float Negate(float x) => -x;
@@ -33,36 +40,72 @@ namespace ComputeSharp.Tests
[TestCategory("StaticMethods")]
public class StaticMethodsTests
{
private struct FloatToFloatFunc_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[0] = StaticMethodsContainer.Square(3);
}
}
[TestMethod]
public void FloatToFloatFunc()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Gpu.Default.For(1, id => buffer[0] = StaticMethodsContainer.Square(3));
var shader = new FloatToFloatFunc_Shader { B = buffer };
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f);
}
private struct InternalFloatToFloatFunc_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[0] = StaticMethodsContainer.InternalSquare(3);
}
}
[TestMethod]
public void InternalFloatToFloatFunc()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Gpu.Default.For(1, id => buffer[0] = StaticMethodsContainer.InternalSquare(3));
var shader = new InternalFloatToFloatFunc_Shader { B = buffer };
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f);
}
private struct FloatToFloat4Func_Shader : IComputeShader
{
public ReadWriteBuffer<Float4> B;
public void Execute(ThreadIds ids)
{
B[0] = StaticMethodsContainer.Range(3);
}
}
[TestMethod]
public void FloatToFloat4Func()
{
using ReadWriteBuffer<Float4> buffer = Gpu.Default.AllocateReadWriteBuffer<Float4>(1);
Gpu.Default.For(1, id => buffer[0] = StaticMethodsContainer.Range(3));
var shader = new FloatToFloat4Func_Shader { B = buffer };
Gpu.Default.For(1, shader);
Float4[] result = buffer.GetData();
@@ -72,37 +115,73 @@ namespace ComputeSharp.Tests
Assert.IsTrue(MathF.Abs(result[0].W - 6) < 0.0001f);
}
private struct Float4ToIntFunc_Shader : IComputeShader
{
public ReadWriteBuffer<int> B;
public void Execute(ThreadIds ids)
{
B[0] = StaticMethodsContainer.Sum(new Float4(1, 2, 3, 14));
}
}
[TestMethod]
public void Float4ToIntFunc()
{
using ReadWriteBuffer<int> buffer = Gpu.Default.AllocateReadWriteBuffer<int>(1);
Gpu.Default.For(1, id => buffer[0] = StaticMethodsContainer.Sum(new Float4(1, 2, 3, 14)));
var shader = new Float4ToIntFunc_Shader { B = buffer };
Gpu.Default.For(1, shader);
int[] result = buffer.GetData();
Assert.IsTrue(result[0] == 20);
}
private struct IntToOutIntFunc_Shader : IComputeShader
{
public ReadWriteBuffer<int> B;
public void Execute(ThreadIds ids)
{
StaticMethodsContainer.Assign(7, out B[0]);
}
}
[TestMethod]
public void IntToOutIntFunc()
{
using ReadWriteBuffer<int> buffer = Gpu.Default.AllocateReadWriteBuffer<int>(1);
Gpu.Default.For(1, id => StaticMethodsContainer.Assign(7, out buffer[0]));
var shader = new IntToOutIntFunc_Shader { B = buffer };
Gpu.Default.For(1, shader);
int[] result = buffer.GetData();
Assert.IsTrue(result[0] == 7);
}
private struct IntToRefIntFunc_Shader : IComputeShader
{
public ReadWriteBuffer<int> B;
public void Execute(ThreadIds ids)
{
StaticMethodsContainer.ReadAndSquare(ref B[0]);
}
}
[TestMethod]
public void IntToRefIntFunc()
{
int[] data = { 3 };
using ReadWriteBuffer<int> buffer = Gpu.Default.AllocateReadWriteBuffer(data);
Gpu.Default.For(1, id => StaticMethodsContainer.ReadAndSquare(ref buffer[0]));
var shader = new IntToRefIntFunc_Shader { B = buffer };
Gpu.Default.For(1, shader);
buffer.GetData(data);
+87 -26
ファイルの表示
@@ -44,60 +44,97 @@ namespace ComputeSharp.Tests
[TestCategory("StaticProperties")]
public class StaticPropertiesTests
{
private struct StaticReadonlyScalarPropertyAssignToBuffer_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[0] = StaticPropertiesContainer.ReadonlyFloat;
}
}
[TestMethod]
public void StaticReadonlyScalarPropertyAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Action<ThreadIds> action = id => buffer[0] = StaticPropertiesContainer.ReadonlyFloat;
var shader = new StaticReadonlyScalarPropertyAssignToBuffer_Shader { B = buffer };
Gpu.Default.For(1, action);
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - StaticPropertiesContainer.ReadonlyFloat) < 0.0001f);
}
private struct StaticScalarPropertyAssignToBuffer_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[0] = StaticPropertiesContainer.StaticFloat;
}
}
[TestMethod]
public void StaticScalarPropertyAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Action<ThreadIds> action = id => buffer[0] = StaticPropertiesContainer.StaticFloat;
var shader = new StaticScalarPropertyAssignToBuffer_Shader { B = buffer };
Gpu.Default.For(1, action);
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - StaticPropertiesContainer.StaticFloat) < 0.0001f);
}
private struct StaticScalarPropertyRepeatedAssignToBuffer_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
B[0] = StaticPropertiesContainer.StaticFloat + StaticPropertiesContainer.StaticFloat;
}
}
[TestMethod]
public void StaticScalarPropertyRepeatedAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
Action<ThreadIds> action = id => buffer[0] = StaticPropertiesContainer.StaticFloat + StaticPropertiesContainer.StaticFloat;
var shader = new StaticScalarPropertyRepeatedAssignToBuffer_Shader { B = buffer };
Gpu.Default.For(1, action);
Gpu.Default.For(1, shader);
float[] result = buffer.GetData();
Assert.IsTrue(MathF.Abs(result[0] - StaticPropertiesContainer.StaticFloat * 2) < 0.0001f);
}
private struct StaticReadonlyVectorPropertyAssignToBuffer_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
if (ids.X == 0) B[0] = StaticPropertiesContainer.ReadonlyVector2.X;
else B[1] = StaticPropertiesContainer.ReadonlyVector2.Y;
}
}
[TestMethod]
public void StaticReadonlyVectorPropertyAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(2);
Action<ThreadIds> action = id =>
{
if (id.X == 0) buffer[0] = StaticPropertiesContainer.ReadonlyVector2.X;
else buffer[1] = StaticPropertiesContainer.ReadonlyVector2.Y;
};
var shader = new StaticReadonlyVectorPropertyAssignToBuffer_Shader { B = buffer };
Gpu.Default.For(2, action);
Gpu.Default.For(2, shader);
float[] result = buffer.GetData();
@@ -105,18 +142,25 @@ namespace ComputeSharp.Tests
Assert.IsTrue(MathF.Abs(result[1] - StaticPropertiesContainer.ReadonlyVector2.Y) < 0.0001f);
}
private struct StaticVectorPropertyAssignToBuffer_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
if (ids.X == 0) B[0] = StaticPropertiesContainer.StaticVector2.X;
else B[1] = StaticPropertiesContainer.StaticVector2.Y;
}
}
[TestMethod]
public void StaticVectorPropertyAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(2);
Action<ThreadIds> action = id =>
{
if (id.X == 0) buffer[0] = StaticPropertiesContainer.StaticVector2.X;
else buffer[1] = StaticPropertiesContainer.StaticVector2.Y;
};
var shader = new StaticVectorPropertyAssignToBuffer_Shader { B = buffer };
Gpu.Default.For(2, action);
Gpu.Default.For(2, shader);
float[] result = buffer.GetData();
@@ -124,18 +168,25 @@ namespace ComputeSharp.Tests
Assert.IsTrue(MathF.Abs(result[1] - StaticPropertiesContainer.StaticVector2.Y) < 0.0001f);
}
private struct StaticReadOnlyBufferPropertyAssignToBuffer_Shader : IComputeShader
{
public ReadWriteBuffer<float> B;
public void Execute(ThreadIds ids)
{
if (ids.X == 0) B[0] = StaticPropertiesContainer.StaticBuffer[0];
else B[1] = StaticPropertiesContainer.StaticBuffer[1];
}
}
[TestMethod]
public void StaticReadOnlyBufferPropertyAssignToBuffer()
{
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(2);
Action<ThreadIds> action = id =>
{
if (id.X == 0) buffer[0] = StaticPropertiesContainer.StaticBuffer[0];
else buffer[1] = StaticPropertiesContainer.StaticBuffer[1];
};
var shader = new StaticReadOnlyBufferPropertyAssignToBuffer_Shader { B = buffer };
Gpu.Default.For(2, action);
Gpu.Default.For(2, shader);
float[] result = buffer.GetData();
float[] expected = StaticPropertiesContainer.StaticBuffer.GetData();
@@ -146,14 +197,24 @@ namespace ComputeSharp.Tests
public static int SomeNumber = 7;
private struct StaticLocalScalarFieldAssignToBuffer_Shader : IComputeShader
{
public ReadWriteBuffer<int> B;
public void Execute(ThreadIds ids)
{
B[0] = SomeNumber;
}
}
[TestMethod]
public void StaticLocalScalarFieldAssignToBuffer()
{
using ReadWriteBuffer<int> buffer = Gpu.Default.AllocateReadWriteBuffer<int>(1);
Action<ThreadIds> action = id => buffer[0] = SomeNumber;
var shader = new StaticLocalScalarFieldAssignToBuffer_Shader { B = buffer };
Gpu.Default.For(1, action);
Gpu.Default.For(1, shader);
int[] result = buffer.GetData();