diff --git a/samples/ComputeSharp.Benchmark/Blas/BlasBenchmark.cs b/samples/ComputeSharp.Benchmark/Blas/BlasBenchmark.cs
index 5282758b..f58bdece 100644
--- a/samples/ComputeSharp.Benchmark/Blas/BlasBenchmark.cs
+++ b/samples/ComputeSharp.Benchmark/Blas/BlasBenchmark.cs
@@ -3,160 +3,159 @@ using System.Buffers;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Engines;
-namespace ComputeSharp.Benchmark.Blas
+namespace ComputeSharp.Benchmark.Blas;
+
+///
+/// A that benchmarks the APIs in the class, on both CPU and GPU.
+///
+[SimpleJob(RunStrategy.Monitoring)]
+public class BlasBenchmark : IDisposable
{
///
- /// A that benchmarks the APIs in the class, on both CPU and GPU.
+ /// The number of samples.
///
- [SimpleJob(RunStrategy.Monitoring)]
- public class BlasBenchmark : IDisposable
+ private const int C = 128;
+
+ ///
+ /// The nummber of rows in the matrix.
+ ///
+ private const int N = 512;
+
+ ///
+ /// The number of columns in the matrix (same as the number of rows in the matrix)
+ ///
+ private const int M = 512;
+
+ ///
+ /// The number of columns in the matrix.
+ ///
+ private const int P = 256;
+
+ ///
+ /// The input tensor.
+ ///
+ private float[]? X;
+
+ ///
+ /// The weights tensor.
+ ///
+ private float[]? W;
+
+ ///
+ /// The bias tensor.
+ ///
+ private float[]? B;
+
+ ///
+ /// The result tensor.
+ ///
+ private float[]? Y;
+
+ ///
+ /// The input tensor (GPU).
+ ///
+ private ReadOnlyBuffer? BufferX;
+
+ ///
+ /// The weights tensor (GPU).
+ ///
+ private ReadOnlyBuffer? BufferW;
+
+ ///
+ /// The bias tensor (GPU).
+ ///
+ private ReadOnlyBuffer? BufferB;
+
+ ///
+ /// The result tensor (GPU).
+ ///
+ private ReadWriteBuffer? BufferY;
+
+ ///
+ /// A instance to initialize the tensors.
+ ///
+ private readonly Random Random = new Random();
+
+ ///
+ /// Initial setup for a benchmarking session.
+ ///
+ [GlobalSetup]
+ public void Setup()
{
- ///
- /// The number of samples.
- ///
- private const int C = 128;
-
- ///
- /// The nummber of rows in the matrix.
- ///
- private const int N = 512;
-
- ///
- /// The number of columns in the matrix (same as the number of rows in the matrix)
- ///
- private const int M = 512;
-
- ///
- /// The number of columns in the matrix.
- ///
- private const int P = 256;
-
- ///
- /// The input tensor.
- ///
- private float[]? X;
-
- ///
- /// The weights tensor.
- ///
- private float[]? W;
-
- ///
- /// The bias tensor.
- ///
- private float[]? B;
-
- ///
- /// The result tensor.
- ///
- private float[]? Y;
-
- ///
- /// The input tensor (GPU).
- ///
- private ReadOnlyBuffer? BufferX;
-
- ///
- /// The weights tensor (GPU).
- ///
- private ReadOnlyBuffer? BufferW;
-
- ///
- /// The bias tensor (GPU).
- ///
- private ReadOnlyBuffer? BufferB;
-
- ///
- /// The result tensor (GPU).
- ///
- private ReadWriteBuffer? BufferY;
-
- ///
- /// A instance to initialize the tensors.
- ///
- private readonly Random Random = new Random();
-
- ///
- /// Initial setup for a benchmarking session.
- ///
- [GlobalSetup]
- public void Setup()
+ // Creates a new random normalized float[] array of a given size
+ float[] CreateRandomArray(int size)
{
- // Creates a new random normalized float[] array of a given size
- float[] CreateRandomArray(int size)
+ float[] array = ArrayPool.Shared.Rent(size);
+
+ foreach (ref float x in array.AsSpan())
{
- float[] array = ArrayPool.Shared.Rent(size);
-
- foreach (ref float x in array.AsSpan())
- {
- x = (float)Random.NextDouble();
- }
-
- return array;
+ x = (float)Random.NextDouble();
}
- X = CreateRandomArray(C * N * M);
- W = CreateRandomArray(M * P);
- B = CreateRandomArray(P);
- Y = CreateRandomArray(C * N * P);
-
- BufferX = Gpu.Default.AllocateReadOnlyBuffer(X);
- BufferW = Gpu.Default.AllocateReadOnlyBuffer(W);
- BufferB = Gpu.Default.AllocateReadOnlyBuffer(B);
- BufferY = Gpu.Default.AllocateReadWriteBuffer(Y);
-
- Cpu();
- GpuWithNoTemporaryBuffers();
- GpuWithTemporaryBuffers();
+ return array;
}
- ///
- [GlobalCleanup]
- public void Dispose()
- {
- ArrayPool.Shared.Return(X!);
- ArrayPool.Shared.Return(W!);
- ArrayPool.Shared.Return(B!);
- ArrayPool.Shared.Return(Y!);
+ X = CreateRandomArray(C * N * M);
+ W = CreateRandomArray(M * P);
+ B = CreateRandomArray(P);
+ Y = CreateRandomArray(C * N * P);
- BufferX!.Dispose();
- BufferW!.Dispose();
- BufferB!.Dispose();
- BufferY!.Dispose();
- }
+ BufferX = Gpu.Default.AllocateReadOnlyBuffer(X);
+ BufferW = Gpu.Default.AllocateReadOnlyBuffer(W);
+ BufferB = Gpu.Default.AllocateReadOnlyBuffer(B);
+ BufferY = Gpu.Default.AllocateReadWriteBuffer(Y);
- ///
- /// Runs a fully connected forward operation on the CPU.
- ///
- [Benchmark(Baseline = true)]
- public void Cpu()
- {
- BlasHelpers.FullyConnectedForwardCpu(C, N, M, P, X!, W!, B!, Y!);
- }
+ Cpu();
+ GpuWithNoTemporaryBuffers();
+ GpuWithTemporaryBuffers();
+ }
- ///
- /// Runs a fully connected forward operation on the GPU.
- ///
- [Benchmark]
- public void GpuWithNoTemporaryBuffers()
- {
- BlasHelpers.FullyConnectedForwardGpu(Gpu.Default, C, N, M, P, BufferX!, BufferW!, BufferB!, BufferY!);
- }
+ ///
+ [GlobalCleanup]
+ public void Dispose()
+ {
+ ArrayPool.Shared.Return(X!);
+ ArrayPool.Shared.Return(W!);
+ ArrayPool.Shared.Return(B!);
+ ArrayPool.Shared.Return(Y!);
- ///
- /// Runs a fully connected forward operation on the GPU, creating temporary GPU buffers to perform the operations.
- ///
- [Benchmark]
- public void GpuWithTemporaryBuffers()
- {
- using ReadOnlyBuffer x = Gpu.Default.AllocateReadOnlyBuffer(X!);
- using ReadOnlyBuffer w = Gpu.Default.AllocateReadOnlyBuffer(W!);
- using ReadOnlyBuffer b = Gpu.Default.AllocateReadOnlyBuffer(B!);
- using ReadWriteBuffer y = Gpu.Default.AllocateReadWriteBuffer(Y!.Length);
+ BufferX!.Dispose();
+ BufferW!.Dispose();
+ BufferB!.Dispose();
+ BufferY!.Dispose();
+ }
- BlasHelpers.FullyConnectedForwardGpu(Gpu.Default, C, N, M, P, x, w, b, y);
+ ///
+ /// Runs a fully connected forward operation on the CPU.
+ ///
+ [Benchmark(Baseline = true)]
+ public void Cpu()
+ {
+ BlasHelpers.FullyConnectedForwardCpu(C, N, M, P, X!, W!, B!, Y!);
+ }
- y.CopyTo(Y);
- }
+ ///
+ /// Runs a fully connected forward operation on the GPU.
+ ///
+ [Benchmark]
+ public void GpuWithNoTemporaryBuffers()
+ {
+ BlasHelpers.FullyConnectedForwardGpu(Gpu.Default, C, N, M, P, BufferX!, BufferW!, BufferB!, BufferY!);
+ }
+
+ ///
+ /// Runs a fully connected forward operation on the GPU, creating temporary GPU buffers to perform the operations.
+ ///
+ [Benchmark]
+ public void GpuWithTemporaryBuffers()
+ {
+ using ReadOnlyBuffer x = Gpu.Default.AllocateReadOnlyBuffer(X!);
+ using ReadOnlyBuffer w = Gpu.Default.AllocateReadOnlyBuffer(W!);
+ using ReadOnlyBuffer b = Gpu.Default.AllocateReadOnlyBuffer(B!);
+ using ReadWriteBuffer y = Gpu.Default.AllocateReadWriteBuffer(Y!.Length);
+
+ BlasHelpers.FullyConnectedForwardGpu(Gpu.Default, C, N, M, P, x, w, b, y);
+
+ y.CopyTo(Y);
}
}
diff --git a/samples/ComputeSharp.Benchmark/Blas/BlasHelpers.cs b/samples/ComputeSharp.Benchmark/Blas/BlasHelpers.cs
index d1e3df0a..b58acb8e 100644
--- a/samples/ComputeSharp.Benchmark/Blas/BlasHelpers.cs
+++ b/samples/ComputeSharp.Benchmark/Blas/BlasHelpers.cs
@@ -1,109 +1,108 @@
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
-namespace ComputeSharp.Benchmark.Blas
+namespace ComputeSharp.Benchmark.Blas;
+
+///
+/// A that contains primitives to run certain operations of a neural network.
+///
+internal static partial class BlasHelpers
{
///
- /// A that contains primitives to run certain operations of a neural network.
+ /// Executes the forward pass on a fully connected layer on the CPU.
///
- internal static partial class BlasHelpers
+ /// The number of samples in the input tensor.
+ /// The number of rows in the input matrix.
+ /// The number of columns in the input matrix.
+ /// The number of columns in the output matrix.
+ /// The input tensor.
+ /// The weights tensor.
+ /// The bias tensor.
+ /// The result tensor.
+ public static void FullyConnectedForwardCpu(int c, int n, int m, int p, float[] x, float[] w, float[] b, float[] y)
{
- ///
- /// Executes the forward pass on a fully connected layer on the CPU.
- ///
- /// The number of samples in the input tensor.
- /// The number of rows in the input matrix.
- /// The number of columns in the input matrix.
- /// The number of columns in the output matrix.
- /// The input tensor.
- /// The weights tensor.
- /// The bias tensor.
- /// The result tensor.
- public static void FullyConnectedForwardCpu(int c, int n, int m, int p, float[] x, float[] w, float[] b, float[] y)
+ void Kernel(int s)
{
- void Kernel(int s)
+ ref float rx = ref x[s * n * m];
+ ref float rw = ref w[0];
+ ref float rb = ref b[0];
+ ref float ry = ref y[s * n * p];
+
+ for (int i = 0; i < n; i++)
{
- ref float rx = ref x[s * n * m];
- ref float rw = ref w[0];
- ref float rb = ref b[0];
- ref float ry = ref y[s * n * p];
+ int x_offset = i * m;
+ int y_offset = i * p;
- for (int i = 0; i < n; i++)
+ for (int j = 0; j < p; j++)
{
- int x_offset = i * m;
- int y_offset = i * p;
+ float result = 0f;
- for (int j = 0; j < p; j++)
+ for (int k = 0; k < m; k++)
{
- float result = 0f;
-
- for (int k = 0; k < m; k++)
- {
- result += Unsafe.Add(ref rx, x_offset + k) * Unsafe.Add(ref rw, k * p + j);
- }
-
- Unsafe.Add(ref ry, y_offset + j) = result + Unsafe.Add(ref rb, j);
+ result += Unsafe.Add(ref rx, x_offset + k) * Unsafe.Add(ref rw, k * p + j);
}
+
+ Unsafe.Add(ref ry, y_offset + j) = result + Unsafe.Add(ref rb, j);
}
}
-
- Parallel.For(0, c, Kernel);
}
- ///
- /// Executes the forward pass on a fully connected layer on the GPU.
- ///
- /// The device to run the computation on.
- /// The number of samples in the input tensor.
- /// The number of rows in the input matrix.
- /// The number of columns in the input matrix.
- /// The number of columns in the output matrix.
- /// The input tensor.
- /// The weights tensor.
- /// The bias tensor.
- /// The result tensor.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static void FullyConnectedForwardGpu(
- GraphicsDevice device,
- int c,
- int n,
- int m,
- int p,
- ReadOnlyBuffer x,
- ReadOnlyBuffer w,
- ReadOnlyBuffer b,
- ReadWriteBuffer y)
- {
- device.For(c, n, p, new FullyConnectedForwardKernel(n, m, p, x, w, b, y));
- }
+ Parallel.For(0, c, Kernel);
+ }
- ///
- /// Kernel for .
- ///
- [AutoConstructor]
- public readonly partial struct FullyConnectedForwardKernel : IComputeShader
- {
- public readonly int n;
- public readonly int m;
- public readonly int p;
- public readonly ReadOnlyBuffer x;
- public readonly ReadOnlyBuffer w;
- public readonly ReadOnlyBuffer b;
- public readonly ReadWriteBuffer y;
+ ///
+ /// Executes the forward pass on a fully connected layer on the GPU.
+ ///
+ /// The device to run the computation on.
+ /// The number of samples in the input tensor.
+ /// The number of rows in the input matrix.
+ /// The number of columns in the input matrix.
+ /// The number of columns in the output matrix.
+ /// The input tensor.
+ /// The weights tensor.
+ /// The bias tensor.
+ /// The result tensor.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static void FullyConnectedForwardGpu(
+ GraphicsDevice device,
+ int c,
+ int n,
+ int m,
+ int p,
+ ReadOnlyBuffer x,
+ ReadOnlyBuffer w,
+ ReadOnlyBuffer b,
+ ReadWriteBuffer y)
+ {
+ device.For(c, n, p, new FullyConnectedForwardKernel(n, m, p, x, w, b, y));
+ }
- ///
- public void Execute()
+ ///
+ /// Kernel for .
+ ///
+ [AutoConstructor]
+ public readonly partial struct FullyConnectedForwardKernel : IComputeShader
+ {
+ public readonly int n;
+ public readonly int m;
+ public readonly int p;
+ public readonly ReadOnlyBuffer x;
+ public readonly ReadOnlyBuffer w;
+ public readonly ReadOnlyBuffer b;
+ public readonly ReadWriteBuffer y;
+
+ ///
+ public void Execute()
+ {
+ int x_offset = ThreadIds.X * n * p + ThreadIds.Y * m;
+ float result = 0f;
+
+ for (int k = 0; k < m; k++)
{
- int x_offset = ThreadIds.X * n * p + ThreadIds.Y * m;
- float result = 0f;
-
- for (int k = 0; k < m; k++)
- {
- result += x[x_offset + k] * w[k * p + ThreadIds.Z];
- }
-
- y[ThreadIds.X * n * p + ThreadIds.Y * p + ThreadIds.Z] = result + b[ThreadIds.Z];
+ result += x[x_offset + k] * w[k * p + ThreadIds.Z];
}
+
+ y[ThreadIds.X * n * p + ThreadIds.Y * p + ThreadIds.Z] = result + b[ThreadIds.Z];
}
}
}
diff --git a/samples/ComputeSharp.Benchmark/Imaging/ImagingBenchmark.cs b/samples/ComputeSharp.Benchmark/Imaging/ImagingBenchmark.cs
index ef208625..72f57439 100644
--- a/samples/ComputeSharp.Benchmark/Imaging/ImagingBenchmark.cs
+++ b/samples/ComputeSharp.Benchmark/Imaging/ImagingBenchmark.cs
@@ -10,82 +10,81 @@ using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Processing.Processors.Convolution;
using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
-namespace ComputeSharp.Benchmark.Imaging
+namespace ComputeSharp.Benchmark.Imaging;
+
+///
+/// A that benchmarks the image processors against the reference in ImageSharp.
+///
+[SimpleJob(RunStrategy.Monitoring)]
+[CategoriesColumn]
+[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
+public class ImagingBenchmark : IDisposable
{
///
- /// A that benchmarks the image processors against the reference in ImageSharp.
+ /// The loaded image.
///
- [SimpleJob(RunStrategy.Monitoring)]
- [CategoriesColumn]
- [GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
- public class ImagingBenchmark : IDisposable
+ private Image? image;
+
+ ///
+ /// Initial setup for a benchmarking session.
+ ///
+ [GlobalSetup]
+ public void Setup()
{
- ///
- /// The loaded image.
- ///
- private Image? image;
+ string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg");
- ///
- /// Initial setup for a benchmarking session.
- ///
- [GlobalSetup]
- public void Setup()
- {
- string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg");
+ this.image = Image.Load(path);
- this.image = Image.Load(path);
+ Bokeh_Cpu();
+ Bokeh_Gpu();
+ Gaussian_Cpu();
+ Gaussian_Gpu();
+ }
- Bokeh_Cpu();
- Bokeh_Gpu();
- Gaussian_Cpu();
- Gaussian_Gpu();
- }
+ ///
+ [GlobalCleanup]
+ public void Dispose()
+ {
+ this.image!.Dispose();
+ }
- ///
- [GlobalCleanup]
- public void Dispose()
- {
- this.image!.Dispose();
- }
+ ///
+ /// Runs a bokeh blur effect on the CPU.
+ ///
+ [Benchmark(Baseline = true)]
+ [BenchmarkCategory("BOKEH")]
+ public void Bokeh_Cpu()
+ {
+ this.image!.Mutate(c => c.ApplyProcessor(new BokehBlurProcessor(80, 2, 3)));
+ }
- ///
- /// Runs a bokeh blur effect on the CPU.
- ///
- [Benchmark(Baseline = true)]
- [BenchmarkCategory("BOKEH")]
- public void Bokeh_Cpu()
- {
- this.image!.Mutate(c => c.ApplyProcessor(new BokehBlurProcessor(80, 2, 3)));
- }
+ ///
+ /// Runs a bokeh blur effect on the GPU.
+ ///
+ [Benchmark]
+ [BenchmarkCategory("BOKEH")]
+ public void Bokeh_Gpu()
+ {
+ this.image!.Mutate(c => c.ApplyProcessor(new HlslBokehBlurProcessor(80, 2)));
+ }
- ///
- /// Runs a bokeh blur effect on the GPU.
- ///
- [Benchmark]
- [BenchmarkCategory("BOKEH")]
- public void Bokeh_Gpu()
- {
- this.image!.Mutate(c => c.ApplyProcessor(new HlslBokehBlurProcessor(80, 2)));
- }
+ ///
+ /// Runs a gaussian blur effect on the CPU.
+ ///
+ [Benchmark(Baseline = true)]
+ [BenchmarkCategory("GAUSSIAN")]
+ public void Gaussian_Cpu()
+ {
+ this.image!.Mutate(c => c.ApplyProcessor(new GaussianBlurProcessor(80)));
+ }
- ///
- /// Runs a gaussian blur effect on the CPU.
- ///
- [Benchmark(Baseline = true)]
- [BenchmarkCategory("GAUSSIAN")]
- public void Gaussian_Cpu()
- {
- this.image!.Mutate(c => c.ApplyProcessor(new GaussianBlurProcessor(80)));
- }
-
- ///
- /// Runs a gaussian blur effect on the GPU.
- ///
- [Benchmark]
- [BenchmarkCategory("GAUSSIAN")]
- public void Gaussian_Gpu()
- {
- this.image!.Mutate(c => c.ApplyProcessor(new HlslGaussianBlurProcessor(80)));
- }
+ ///
+ /// Runs a gaussian blur effect on the GPU.
+ ///
+ [Benchmark]
+ [BenchmarkCategory("GAUSSIAN")]
+ public void Gaussian_Gpu()
+ {
+ this.image!.Mutate(c => c.ApplyProcessor(new HlslGaussianBlurProcessor(80)));
}
}
diff --git a/samples/ComputeSharp.ImageProcessing/Primitives/Complex64.cs b/samples/ComputeSharp.ImageProcessing/Primitives/Complex64.cs
index e14516c1..37aeea99 100644
--- a/samples/ComputeSharp.ImageProcessing/Primitives/Complex64.cs
+++ b/samples/ComputeSharp.ImageProcessing/Primitives/Complex64.cs
@@ -3,44 +3,43 @@
using System.Runtime.CompilerServices;
-namespace SixLabors.ImageSharp
+namespace SixLabors.ImageSharp;
+
+///
+/// Represents a complex number, where the real and imaginary parts are stored as values.
+///
+///
+/// This is a more efficient version of the type.
+///
+internal readonly struct Complex64
{
///
- /// Represents a complex number, where the real and imaginary parts are stored as values.
+ /// The real part of the complex number.
///
- ///
- /// This is a more efficient version of the type.
- ///
- internal readonly struct Complex64
+ public readonly float Real;
+
+ ///
+ /// The imaginary part of the complex number.
+ ///
+ public readonly float Imaginary;
+
+ ///
+ /// Initializes a new instance of the struct.
+ ///
+ /// The real part in the complex number.
+ /// The imaginary part in the complex number.
+ public Complex64(float real, float imaginary)
{
- ///
- /// The real part of the complex number.
- ///
- public readonly float Real;
-
- ///
- /// The imaginary part of the complex number.
- ///
- public readonly float Imaginary;
-
- ///
- /// Initializes a new instance of the struct.
- ///
- /// The real part in the complex number.
- /// The imaginary part in the complex number.
- public Complex64(float real, float imaginary)
- {
- this.Real = real;
- this.Imaginary = imaginary;
- }
-
- ///
- /// Performs the multiplication operation between a instance and a scalar.
- ///
- /// The value to multiply.
- /// The scalar to use to multiply the value.
- /// The result.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static Complex64 operator *(Complex64 value, float scalar) => new Complex64(value.Real * scalar, value.Imaginary * scalar);
+ this.Real = real;
+ this.Imaginary = imaginary;
}
-}
\ No newline at end of file
+
+ ///
+ /// Performs the multiplication operation between a instance and a scalar.
+ ///
+ /// The value to multiply.
+ /// The scalar to use to multiply the value.
+ /// The result.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static Complex64 operator *(Complex64 value, float scalar) => new Complex64(value.Real * scalar, value.Imaginary * scalar);
+}
diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs
index 25e9dfc9..75c601bd 100644
--- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs
+++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs
@@ -5,81 +5,80 @@ using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing.Processors;
using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
-namespace ComputeSharp.BokehBlur.Processors
+namespace ComputeSharp.BokehBlur.Processors;
+
+///
+/// Applies bokeh blur processing to the image.
+///
+public sealed partial class HlslBokehBlurProcessor : IImageProcessor
{
///
- /// Applies bokeh blur processing to the image.
+ /// The default radius used by the parameterless constructor.
///
- public sealed partial class HlslBokehBlurProcessor : IImageProcessor
+ public const int DefaultRadius = 32;
+
+ ///
+ /// The default component count used by the parameterless constructor.
+ ///
+ public const int DefaultComponents = 2;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public HlslBokehBlurProcessor()
+ : this(Gpu.Default, DefaultRadius, DefaultComponents)
{
- ///
- /// The default radius used by the parameterless constructor.
- ///
- public const int DefaultRadius = 32;
+ }
- ///
- /// The default component count used by the parameterless constructor.
- ///
- public const int DefaultComponents = 2;
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The size of the area to sample.
+ /// The number of components to use to approximate the original 2D bokeh blur convolution kernel.
+ public HlslBokehBlurProcessor(int radius, int components)
+ : this(Gpu.Default, radius, components)
+ {
+ }
- ///
- /// Initializes a new instance of the class.
- ///
- public HlslBokehBlurProcessor()
- : this(Gpu.Default, DefaultRadius, DefaultComponents)
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The associated with the current instance.
+ /// The size of the area to sample.
+ /// The number of components to use to approximate the original 2D bokeh blur convolution kernel.
+ public HlslBokehBlurProcessor(GraphicsDevice device, int radius, int components)
+ {
+ GraphicsDevice = device;
+ Radius = radius;
+ Components = components;
+ }
+
+ ///
+ /// Gets the associated with the current instance.
+ ///
+ public GraphicsDevice GraphicsDevice { get; }
+
+ ///
+ /// Gets the radius.
+ ///
+ public int Radius { get; }
+
+ ///
+ /// Gets the number of components.
+ ///
+ public int Components { get; }
+
+ ///
+ public IImageProcessor CreatePixelSpecificProcessor(Configuration configuration, Image source, Rectangle sourceRectangle)
+ where TPixel : unmanaged, IPixel
+ {
+ if (typeof(TPixel) != typeof(ImageSharpRgba32))
{
+ ThrowHelper.ThrowInvalidOperationException("This processor only supports the RGBA32 pixel format");
}
- ///
- /// Initializes a new instance of the class.
- ///
- /// The size of the area to sample.
- /// The number of components to use to approximate the original 2D bokeh blur convolution kernel.
- public HlslBokehBlurProcessor(int radius, int components)
- : this(Gpu.Default, radius, components)
- {
- }
+ var processor = new Implementation(this, configuration, Unsafe.As>(source), sourceRectangle);
- ///
- /// Initializes a new instance of the class.
- ///
- /// The associated with the current instance.
- /// The size of the area to sample.
- /// The number of components to use to approximate the original 2D bokeh blur convolution kernel.
- public HlslBokehBlurProcessor(GraphicsDevice device, int radius, int components)
- {
- GraphicsDevice = device;
- Radius = radius;
- Components = components;
- }
-
- ///
- /// Gets the associated with the current instance.
- ///
- public GraphicsDevice GraphicsDevice { get; }
-
- ///
- /// Gets the radius.
- ///
- public int Radius { get; }
-
- ///
- /// Gets the number of components.
- ///
- public int Components { get; }
-
- ///
- public IImageProcessor CreatePixelSpecificProcessor(Configuration configuration, Image source, Rectangle sourceRectangle)
- where TPixel : unmanaged, IPixel
- {
- if (typeof(TPixel) != typeof(ImageSharpRgba32))
- {
- ThrowHelper.ThrowInvalidOperationException("This processor only supports the RGBA32 pixel format");
- }
-
- var processor = new Implementation(this, configuration, Unsafe.As>(source), sourceRectangle);
-
- return Unsafe.As>(processor);
- }
+ return Unsafe.As>(processor);
}
}
diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs
index 11f87db4..9bc7c664 100644
--- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs
+++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs
@@ -9,417 +9,416 @@ using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing.Processors;
using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
-namespace ComputeSharp.BokehBlur.Processors
+namespace ComputeSharp.BokehBlur.Processors;
+
+///
+public sealed partial class HlslBokehBlurProcessor
{
- ///
- public sealed partial class HlslBokehBlurProcessor
+ ///
+ /// Applies bokeh blur processing to the image.
+ ///
+ /// This processor is based on the code from Mike Pound, see github.com/mikepound/convolve.
+ public sealed partial class Implementation : ImageProcessor
{
///
- /// Applies bokeh blur processing to the image.
+ /// The instance in use.
///
- /// This processor is based on the code from Mike Pound, see github.com/mikepound/convolve.
- public sealed partial class Implementation : ImageProcessor
+ private readonly GraphicsDevice GraphicsDevice;
+
+ ///
+ /// The kernel radius.
+ ///
+ private readonly int Radius;
+
+ ///
+ /// The maximum size of the kernel in either direction.
+ ///
+ private readonly int KernelSize;
+
+ ///
+ /// The number of components to use when applying the bokeh blur.
+ ///
+ private readonly int ComponentsCount;
+
+ ///
+ /// The kernel parameters to use for the current instance (a: X, b: Y, A: Z, B: W)
+ ///
+ private readonly Vector4[] KernelParameters;
+
+ ///
+ /// The kernel components for the current instance.
+ ///
+ private readonly Complex64[][] Kernels;
+
+ ///
+ /// The scaling factor for kernel values.
+ ///
+ private readonly float KernelsScale;
+
+ ///
+ /// The mapping of initialized complex kernels and parameters, to speed up the initialization of new instances.
+ ///
+ private static readonly ConcurrentDictionary<(int Radius, int ComponentsCount), (Vector4[] Parameters, float Scale, Complex64[][] Kernels)> Cache = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The defining the processor parameters.
+ /// The configuration which allows altering default behaviour or extending the library.
+ /// The source instance to modify.
+ /// The source that indicates the area to edit.
+ public Implementation(HlslBokehBlurProcessor definition, Configuration configuration, Image source, Rectangle sourceRectangle)
+ : base(configuration, source, sourceRectangle)
{
- ///
- /// The instance in use.
- ///
- private readonly GraphicsDevice GraphicsDevice;
+ GraphicsDevice = definition.GraphicsDevice;
+ Radius = definition.Radius;
+ KernelSize = Radius * 2 + 1;
+ ComponentsCount = definition.Components;
- ///
- /// The kernel radius.
- ///
- private readonly int Radius;
-
- ///
- /// The maximum size of the kernel in either direction.
- ///
- private readonly int KernelSize;
-
- ///
- /// The number of components to use when applying the bokeh blur.
- ///
- private readonly int ComponentsCount;
-
- ///
- /// The kernel parameters to use for the current instance (a: X, b: Y, A: Z, B: W)
- ///
- private readonly Vector4[] KernelParameters;
-
- ///
- /// The kernel components for the current instance.
- ///
- private readonly Complex64[][] Kernels;
-
- ///
- /// The scaling factor for kernel values.
- ///
- private readonly float KernelsScale;
-
- ///
- /// The mapping of initialized complex kernels and parameters, to speed up the initialization of new instances.
- ///
- private static readonly ConcurrentDictionary<(int Radius, int ComponentsCount), (Vector4[] Parameters, float Scale, Complex64[][] Kernels)> Cache = new();
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The defining the processor parameters.
- /// The configuration which allows altering default behaviour or extending the library.
- /// The source instance to modify.
- /// The source that indicates the area to edit.
- public Implementation(HlslBokehBlurProcessor definition, Configuration configuration, Image source, Rectangle sourceRectangle)
- : base(configuration, source, sourceRectangle)
+ // Reuse the initialized values from the cache, if possible
+ var parameters = (Radius, ComponentsCount);
+ if (Cache.TryGetValue(parameters, out var info))
{
- GraphicsDevice = definition.GraphicsDevice;
- Radius = definition.Radius;
- KernelSize = Radius * 2 + 1;
- ComponentsCount = definition.Components;
+ KernelParameters = info.Parameters;
+ KernelsScale = info.Scale;
+ Kernels = info.Kernels;
+ }
+ else
+ {
+ // Initialize the complex kernels and parameters with the current arguments
+ (KernelParameters, KernelsScale) = GetParameters();
+ Kernels = CreateComplexKernels();
+ NormalizeKernels();
- // Reuse the initialized values from the cache, if possible
- var parameters = (Radius, ComponentsCount);
- if (Cache.TryGetValue(parameters, out var info))
- {
- KernelParameters = info.Parameters;
- KernelsScale = info.Scale;
- Kernels = info.Kernels;
- }
- else
- {
- // Initialize the complex kernels and parameters with the current arguments
- (KernelParameters, KernelsScale) = GetParameters();
- Kernels = CreateComplexKernels();
- NormalizeKernels();
+ // Store them in the cache for future use
+ Cache.TryAdd(parameters, (KernelParameters, KernelsScale, Kernels));
+ }
+ }
- // Store them in the cache for future use
- Cache.TryAdd(parameters, (KernelParameters, KernelsScale, Kernels));
- }
+ ///
+ /// Gets the kernel scales to adjust the component values in each kernel.
+ ///
+ private static IReadOnlyList KernelScales { get; } = new[] { 1.4f, 1.2f, 1.2f, 1.2f, 1.2f, 1.2f };
+
+ ///
+ /// Gets the available bokeh blur kernel parameters.
+ ///
+ private static IReadOnlyList KernelComponents { get; } = new[]
+ {
+ // 1 component
+ new[] { new Vector4(0.862325f, 1.624835f, 0.767583f, 1.862321f) },
+
+ // 2 components
+ new[]
+ {
+ new Vector4(0.886528f, 5.268909f, 0.411259f, -0.548794f),
+ new Vector4(1.960518f, 1.558213f, 0.513282f, 4.56111f)
+ },
+
+ // 3 components
+ new[]
+ {
+ new Vector4(2.17649f, 5.043495f, 1.621035f, -2.105439f),
+ new Vector4(1.019306f, 9.027613f, -0.28086f, -0.162882f),
+ new Vector4(2.81511f, 1.597273f, -0.366471f, 10.300301f)
+ },
+
+ // 4 components
+ new[]
+ {
+ new Vector4(4.338459f, 1.553635f, -5.767909f, 46.164397f),
+ new Vector4(3.839993f, 4.693183f, 9.795391f, -15.227561f),
+ new Vector4(2.791880f, 8.178137f, -3.048324f, 0.302959f),
+ new Vector4(1.342190f, 12.328289f, 0.010001f, 0.244650f)
+ },
+
+ // 5 components
+ new[]
+ {
+ new Vector4(4.892608f, 1.685979f, -22.356787f, 85.91246f),
+ new Vector4(4.71187f, 4.998496f, 35.918936f, -28.875618f),
+ new Vector4(4.052795f, 8.244168f, -13.212253f, -1.578428f),
+ new Vector4(2.929212f, 11.900859f, 0.507991f, 1.816328f),
+ new Vector4(1.512961f, 16.116382f, 0.138051f, -0.01f)
+ },
+
+ // 6 components
+ new[]
+ {
+ new Vector4(5.143778f, 2.079813f, -82.326596f, 111.231024f),
+ new Vector4(5.612426f, 6.153387f, 113.878661f, 58.004879f),
+ new Vector4(5.982921f, 9.802895f, 39.479083f, -162.028887f),
+ new Vector4(6.505167f, 11.059237f, -71.286026f, 95.027069f),
+ new Vector4(3.869579f, 14.81052f, 1.405746f, -3.704914f),
+ new Vector4(2.201904f, 19.032909f, -0.152784f, -0.107988f)
+ }
+ };
+
+ ///
+ /// Gets the kernel parameters and scaling factor for the current count value in the current instance.
+ ///
+ private (Vector4[] Parameters, float Scale) GetParameters()
+ {
+ // Prepare the kernel components
+ int index = Math.Max(0, Math.Min(ComponentsCount - 1, KernelComponents.Count));
+ return (KernelComponents[index], KernelScales[index]);
+ }
+
+ ///
+ /// Creates the collection of complex 1D kernels with the specified parameters.
+ ///
+ private Complex64[][] CreateComplexKernels()
+ {
+ var kernels = new Complex64[KernelParameters.Length][];
+ ref Vector4 baseRef = ref MemoryMarshal.GetReference(KernelParameters.AsSpan());
+ for (int i = 0; i < KernelParameters.Length; i++)
+ {
+ ref Vector4 paramsRef = ref Unsafe.Add(ref baseRef, i);
+ kernels[i] = CreateComplex1DKernel(paramsRef.X, paramsRef.Y);
}
- ///
- /// Gets the kernel scales to adjust the component values in each kernel.
- ///
- private static IReadOnlyList KernelScales { get; } = new[] { 1.4f, 1.2f, 1.2f, 1.2f, 1.2f, 1.2f };
+ return kernels;
+ }
- ///
- /// Gets the available bokeh blur kernel parameters.
- ///
- private static IReadOnlyList KernelComponents { get; } = new[]
+ ///
+ /// Creates a complex 1D kernel with the specified parameters.
+ ///
+ /// The exponential parameter for each complex component.
+ /// The angle component for each complex component.
+ private Complex64[] CreateComplex1DKernel(float a, float b)
+ {
+ var kernel = new Complex64[KernelSize];
+ ref Complex64 baseRef = ref MemoryMarshal.GetReference(kernel.AsSpan());
+ int r = Radius, n = -r;
+
+ for (int i = 0; i < KernelSize; i++, n++)
{
- // 1 component
- new[] { new Vector4(0.862325f, 1.624835f, 0.767583f, 1.862321f) },
+ // Incrementally compute the range values
+ float value = n * KernelsScale * (1f / r);
+ value *= value;
- // 2 components
- new[]
- {
- new Vector4(0.886528f, 5.268909f, 0.411259f, -0.548794f),
- new Vector4(1.960518f, 1.558213f, 0.513282f, 4.56111f)
- },
-
- // 3 components
- new[]
- {
- new Vector4(2.17649f, 5.043495f, 1.621035f, -2.105439f),
- new Vector4(1.019306f, 9.027613f, -0.28086f, -0.162882f),
- new Vector4(2.81511f, 1.597273f, -0.366471f, 10.300301f)
- },
-
- // 4 components
- new[]
- {
- new Vector4(4.338459f, 1.553635f, -5.767909f, 46.164397f),
- new Vector4(3.839993f, 4.693183f, 9.795391f, -15.227561f),
- new Vector4(2.791880f, 8.178137f, -3.048324f, 0.302959f),
- new Vector4(1.342190f, 12.328289f, 0.010001f, 0.244650f)
- },
-
- // 5 components
- new[]
- {
- new Vector4(4.892608f, 1.685979f, -22.356787f, 85.91246f),
- new Vector4(4.71187f, 4.998496f, 35.918936f, -28.875618f),
- new Vector4(4.052795f, 8.244168f, -13.212253f, -1.578428f),
- new Vector4(2.929212f, 11.900859f, 0.507991f, 1.816328f),
- new Vector4(1.512961f, 16.116382f, 0.138051f, -0.01f)
- },
-
- // 6 components
- new[]
- {
- new Vector4(5.143778f, 2.079813f, -82.326596f, 111.231024f),
- new Vector4(5.612426f, 6.153387f, 113.878661f, 58.004879f),
- new Vector4(5.982921f, 9.802895f, 39.479083f, -162.028887f),
- new Vector4(6.505167f, 11.059237f, -71.286026f, 95.027069f),
- new Vector4(3.869579f, 14.81052f, 1.405746f, -3.704914f),
- new Vector4(2.201904f, 19.032909f, -0.152784f, -0.107988f)
- }
- };
-
- ///
- /// Gets the kernel parameters and scaling factor for the current count value in the current instance.
- ///
- private (Vector4[] Parameters, float Scale) GetParameters()
- {
- // Prepare the kernel components
- int index = Math.Max(0, Math.Min(ComponentsCount - 1, KernelComponents.Count));
- return (KernelComponents[index], KernelScales[index]);
+ // Fill in the complex kernel values
+ Unsafe.Add(ref baseRef, i) = new Complex64(
+ MathF.Exp(-a * value) * MathF.Cos(b * value),
+ MathF.Exp(-a * value) * MathF.Sin(b * value));
}
- ///
- /// Creates the collection of complex 1D kernels with the specified parameters.
- ///
- private Complex64[][] CreateComplexKernels()
+ return kernel;
+ }
+
+ ///
+ /// Normalizes the kernels with respect to A * real + B * imaginary.
+ ///
+ private void NormalizeKernels()
+ {
+ // Calculate the complex weighted sum
+ float total = 0;
+ Span kernelsSpan = Kernels.AsSpan();
+ ref Complex64[] baseKernelsRef = ref MemoryMarshal.GetReference(kernelsSpan);
+ ref Vector4 baseParamsRef = ref MemoryMarshal.GetReference(KernelParameters.AsSpan());
+
+ for (int i = 0; i < KernelParameters.Length; i++)
{
- var kernels = new Complex64[KernelParameters.Length][];
- ref Vector4 baseRef = ref MemoryMarshal.GetReference(KernelParameters.AsSpan());
- for (int i = 0; i < KernelParameters.Length; i++)
+ ref Complex64[] kernelRef = ref Unsafe.Add(ref baseKernelsRef, i);
+ int length = kernelRef.Length;
+ ref Complex64 valueRef = ref kernelRef[0];
+ ref Vector4 paramsRef = ref Unsafe.Add(ref baseParamsRef, i);
+
+ for (int j = 0; j < length; j++)
{
- ref Vector4 paramsRef = ref Unsafe.Add(ref baseRef, i);
- kernels[i] = CreateComplex1DKernel(paramsRef.X, paramsRef.Y);
- }
-
- return kernels;
- }
-
- ///
- /// Creates a complex 1D kernel with the specified parameters.
- ///
- /// The exponential parameter for each complex component.
- /// The angle component for each complex component.
- private Complex64[] CreateComplex1DKernel(float a, float b)
- {
- var kernel = new Complex64[KernelSize];
- ref Complex64 baseRef = ref MemoryMarshal.GetReference(kernel.AsSpan());
- int r = Radius, n = -r;
-
- for (int i = 0; i < KernelSize; i++, n++)
- {
- // Incrementally compute the range values
- float value = n * KernelsScale * (1f / r);
- value *= value;
-
- // Fill in the complex kernel values
- Unsafe.Add(ref baseRef, i) = new Complex64(
- MathF.Exp(-a * value) * MathF.Cos(b * value),
- MathF.Exp(-a * value) * MathF.Sin(b * value));
- }
-
- return kernel;
- }
-
- ///
- /// Normalizes the kernels with respect to A * real + B * imaginary.
- ///
- private void NormalizeKernels()
- {
- // Calculate the complex weighted sum
- float total = 0;
- Span kernelsSpan = Kernels.AsSpan();
- ref Complex64[] baseKernelsRef = ref MemoryMarshal.GetReference(kernelsSpan);
- ref Vector4 baseParamsRef = ref MemoryMarshal.GetReference(KernelParameters.AsSpan());
-
- for (int i = 0; i < KernelParameters.Length; i++)
- {
- ref Complex64[] kernelRef = ref Unsafe.Add(ref baseKernelsRef, i);
- int length = kernelRef.Length;
- ref Complex64 valueRef = ref kernelRef[0];
- ref Vector4 paramsRef = ref Unsafe.Add(ref baseParamsRef, i);
-
- for (int j = 0; j < length; j++)
+ for (int k = 0; k < length; k++)
{
- for (int k = 0; k < length; k++)
- {
- ref Complex64 jRef = ref Unsafe.Add(ref valueRef, j);
- ref Complex64 kRef = ref Unsafe.Add(ref valueRef, k);
- total +=
- paramsRef.Z * (jRef.Real * kRef.Real - jRef.Imaginary * kRef.Imaginary)
- + paramsRef.W * (jRef.Real * kRef.Imaginary + jRef.Imaginary * kRef.Real);
- }
- }
- }
-
- // Normalize the kernels
- float scalar = 1f / MathF.Sqrt(total);
- for (int i = 0; i < kernelsSpan.Length; i++)
- {
- ref Complex64[] kernelsRef = ref Unsafe.Add(ref baseKernelsRef, i);
- int length = kernelsRef.Length;
- ref Complex64 valueRef = ref kernelsRef[0];
-
- for (int j = 0; j < length; j++)
- {
- Unsafe.Add(ref valueRef, j) *= scalar;
+ ref Complex64 jRef = ref Unsafe.Add(ref valueRef, j);
+ ref Complex64 kRef = ref Unsafe.Add(ref valueRef, k);
+ total +=
+ paramsRef.Z * (jRef.Real * kRef.Real - jRef.Imaginary * kRef.Imaginary)
+ + paramsRef.W * (jRef.Real * kRef.Imaginary + jRef.Imaginary * kRef.Real);
}
}
}
+ // Normalize the kernels
+ float scalar = 1f / MathF.Sqrt(total);
+ for (int i = 0; i < kernelsSpan.Length; i++)
+ {
+ ref Complex64[] kernelsRef = ref Unsafe.Add(ref baseKernelsRef, i);
+ int length = kernelsRef.Length;
+ ref Complex64 valueRef = ref kernelsRef[0];
+
+ for (int j = 0; j < length; j++)
+ {
+ Unsafe.Add(ref valueRef, j) *= scalar;
+ }
+ }
+ }
+
+ ///
+ protected override void OnFrameApply(ImageFrame source)
+ {
+ if (!source.TryGetSinglePixelSpan(out Span pixelSpan))
+ {
+ ThrowHelper.ThrowInvalidOperationException("Cannot process image frames wrapping discontiguous memory");
+ }
+
+ Span span = MemoryMarshal.Cast(pixelSpan);
+
+ using ReadWriteTexture2D texture = GraphicsDevice.AllocateReadWriteTexture2D(span, source.Width, source.Height);
+ using ReadWriteTexture2D temporary = GraphicsDevice.AllocateReadWriteTexture2D(source.Width, source.Height, AllocationMode.Clear);
+ using ReadWriteTexture2D reals = GraphicsDevice.AllocateReadWriteTexture2D(source.Width, source.Height);
+ using ReadWriteTexture2D imaginaries = GraphicsDevice.AllocateReadWriteTexture2D(source.Width, source.Height);
+ using ReadOnlyBuffer kernel = GraphicsDevice.AllocateReadOnlyBuffer(KernelSize);
+
+ // Preliminary gamma highlight pass
+ GraphicsDevice.For(source.Height, new(texture));
+
+ // Perform two 1D convolutions for each component in the current instance
+ for (int j = 0; j < Kernels.Length; j++)
+ {
+ Vector4 parameters = KernelParameters[j];
+
+ kernel.CopyFrom(Kernels[j]);
+
+ GraphicsDevice.For(
+ source.Width,
+ source.Height,
+ new(texture, reals, imaginaries, kernel));
+
+ GraphicsDevice.For(
+ source.Width,
+ source.Height,
+ new(parameters.Z, parameters.W, reals, imaginaries, temporary, kernel));
+ }
+
+ // Apply the inverse gamma exposure pass
+ GraphicsDevice.For(source.Height, new(temporary, texture));
+
+ // Write the final pixel data
+ texture.CopyTo(span);
+ }
+
+ ///
+ /// Kernel for the vertical convolution pass.
+ ///
+ [AutoConstructor]
+ internal partial struct VerticalConvolutionProcessor : IComputeShader
+ {
+ public IReadWriteTexture2D source;
+ public ReadWriteTexture2D reals;
+ public ReadWriteTexture2D imaginaries;
+ public ReadOnlyBuffer kernel;
+
///
- protected override void OnFrameApply(ImageFrame source)
+ public void Execute()
{
- if (!source.TryGetSinglePixelSpan(out Span pixelSpan))
+ Vector4 real = Vector4.Zero;
+ Vector4 imaginary = Vector4.Zero;
+ int maxY = source.Height;
+ int maxX = source.Width;
+ int kernelLength = kernel.Length;
+ int radiusY = kernelLength >> 1;
+
+ for (int i = 0; i < kernelLength; i++)
{
- ThrowHelper.ThrowInvalidOperationException("Cannot process image frames wrapping discontiguous memory");
+ int offsetY = Hlsl.Clamp(ThreadIds.Y + i - radiusY, 0, maxY);
+ int offsetX = Hlsl.Clamp(ThreadIds.X, 0, maxX);
+ Vector4 color = source[offsetX, offsetY];
+ Complex64 factors = kernel[i];
+
+ real += factors.Real * color;
+ imaginary += factors.Imaginary * color;
}
- Span span = MemoryMarshal.Cast(pixelSpan);
-
- using ReadWriteTexture2D texture = GraphicsDevice.AllocateReadWriteTexture2D(span, source.Width, source.Height);
- using ReadWriteTexture2D temporary = GraphicsDevice.AllocateReadWriteTexture2D(source.Width, source.Height, AllocationMode.Clear);
- using ReadWriteTexture2D reals = GraphicsDevice.AllocateReadWriteTexture2D(source.Width, source.Height);
- using ReadWriteTexture2D imaginaries = GraphicsDevice.AllocateReadWriteTexture2D(source.Width, source.Height);
- using ReadOnlyBuffer kernel = GraphicsDevice.AllocateReadOnlyBuffer(KernelSize);
-
- // Preliminary gamma highlight pass
- GraphicsDevice.For(source.Height, new(texture));
-
- // Perform two 1D convolutions for each component in the current instance
- for (int j = 0; j < Kernels.Length; j++)
- {
- Vector4 parameters = KernelParameters[j];
-
- kernel.CopyFrom(Kernels[j]);
-
- GraphicsDevice.For(
- source.Width,
- source.Height,
- new(texture, reals, imaginaries, kernel));
-
- GraphicsDevice.For(
- source.Width,
- source.Height,
- new(parameters.Z, parameters.W, reals, imaginaries, temporary, kernel));
- }
-
- // Apply the inverse gamma exposure pass
- GraphicsDevice.For(source.Height, new(temporary, texture));
-
- // Write the final pixel data
- texture.CopyTo(span);
+ reals[ThreadIds.XY] = real;
+ imaginaries[ThreadIds.XY] = imaginary;
}
+ }
- ///
- /// Kernel for the vertical convolution pass.
- ///
- [AutoConstructor]
- internal partial struct VerticalConvolutionProcessor : IComputeShader
+ ///
+ /// Kernel for the horizontal convolution pass.
+ ///
+ [AutoConstructor]
+ internal partial struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader
+ {
+ public float z;
+ public float w;
+
+ public ReadWriteTexture2D reals;
+ public ReadWriteTexture2D imaginaries;
+ public ReadWriteTexture2D target;
+ public ReadOnlyBuffer kernel;
+
+ ///
+ public void Execute()
{
- public IReadWriteTexture2D source;
- public ReadWriteTexture2D reals;
- public ReadWriteTexture2D imaginaries;
- public ReadOnlyBuffer kernel;
+ Vector4 real = Vector4.Zero;
+ Vector4 imaginary = Vector4.Zero;
+ int maxY = target.Height;
+ int maxX = target.Width;
+ int kernelLength = kernel.Length;
+ int radiusX = kernelLength >> 1;
+ int offsetY = Hlsl.Clamp(ThreadIds.Y, 0, maxY);
- ///
- public void Execute()
+ for (int i = 0; i < kernelLength; i++)
{
- Vector4 real = Vector4.Zero;
- Vector4 imaginary = Vector4.Zero;
- int maxY = source.Height;
- int maxX = source.Width;
- int kernelLength = kernel.Length;
- int radiusY = kernelLength >> 1;
+ int offsetX = Hlsl.Clamp(ThreadIds.X + i - radiusX, 0, maxX);
+ Vector4 sourceReal = reals[offsetX, offsetY];
+ Vector4 sourceImaginary = imaginaries[offsetX, offsetY];
+ Complex64 factors = kernel[i];
- for (int i = 0; i < kernelLength; i++)
- {
- int offsetY = Hlsl.Clamp(ThreadIds.Y + i - radiusY, 0, maxY);
- int offsetX = Hlsl.Clamp(ThreadIds.X, 0, maxX);
- Vector4 color = source[offsetX, offsetY];
- Complex64 factors = kernel[i];
+ real += factors.Real * sourceReal - factors.Imaginary * sourceImaginary;
+ imaginary += factors.Real * sourceImaginary + factors.Imaginary * sourceReal;
+ }
- real += factors.Real * color;
- imaginary += factors.Imaginary * color;
- }
+ target[ThreadIds.XY] += real * z + imaginary * w;
+ }
+ }
- reals[ThreadIds.XY] = real;
- imaginaries[ThreadIds.XY] = imaginary;
+ ///
+ /// Kernel for the gamma highlight pass.
+ ///
+ [AutoConstructor]
+ internal readonly partial struct GammaHighlightProcessor : IComputeShader
+ {
+ public readonly IReadWriteTexture2D source;
+
+ ///
+ public void Execute()
+ {
+ int width = source.Width;
+
+ for (int i = 0; i < width; i++)
+ {
+ float4 v = source[i, ThreadIds.X];
+
+ v.XYZ = v.XYZ * v.XYZ * v.XYZ;
+
+ source[i, ThreadIds.X] = v;
}
}
+ }
- ///
- /// Kernel for the horizontal convolution pass.
- ///
- [AutoConstructor]
- internal partial struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader
+ ///
+ /// Kernel for the inverse gamma highlight pass.
+ ///
+ [AutoConstructor]
+ internal readonly partial struct InverseGammaHighlightProcessor : IComputeShader
+ {
+ public readonly ReadWriteTexture2D source;
+ public readonly IReadWriteTexture2D target;
+
+ ///
+ public void Execute()
{
- public float z;
- public float w;
+ int width = source.Width;
- public ReadWriteTexture2D reals;
- public ReadWriteTexture2D imaginaries;
- public ReadWriteTexture2D target;
- public ReadOnlyBuffer kernel;
-
- ///
- public void Execute()
+ for (int i = 0; i < width; i++)
{
- Vector4 real = Vector4.Zero;
- Vector4 imaginary = Vector4.Zero;
- int maxY = target.Height;
- int maxX = target.Width;
- int kernelLength = kernel.Length;
- int radiusX = kernelLength >> 1;
- int offsetY = Hlsl.Clamp(ThreadIds.Y, 0, maxY);
+ float4 v = source[i, ThreadIds.X];
- for (int i = 0; i < kernelLength; i++)
- {
- int offsetX = Hlsl.Clamp(ThreadIds.X + i - radiusX, 0, maxX);
- Vector4 sourceReal = reals[offsetX, offsetY];
- Vector4 sourceImaginary = imaginaries[offsetX, offsetY];
- Complex64 factors = kernel[i];
+ v = Hlsl.Clamp(v, 0, float.MaxValue);
+ v.XYZ = Hlsl.Pow(v.XYZ, 1 / 3f);
- real += factors.Real * sourceReal - factors.Imaginary * sourceImaginary;
- imaginary += factors.Real * sourceImaginary + factors.Imaginary * sourceReal;
- }
-
- target[ThreadIds.XY] += real * z + imaginary * w;
- }
- }
-
- ///
- /// Kernel for the gamma highlight pass.
- ///
- [AutoConstructor]
- internal readonly partial struct GammaHighlightProcessor : IComputeShader
- {
- public readonly IReadWriteTexture2D source;
-
- ///
- public void Execute()
- {
- int width = source.Width;
-
- for (int i = 0; i < width; i++)
- {
- float4 v = source[i, ThreadIds.X];
-
- v.XYZ = v.XYZ * v.XYZ * v.XYZ;
-
- source[i, ThreadIds.X] = v;
- }
- }
- }
-
- ///
- /// Kernel for the inverse gamma highlight pass.
- ///
- [AutoConstructor]
- internal readonly partial struct InverseGammaHighlightProcessor : IComputeShader
- {
- public readonly ReadWriteTexture2D source;
- public readonly IReadWriteTexture2D target;
-
- ///
- public void Execute()
- {
- int width = source.Width;
-
- for (int i = 0; i < width; i++)
- {
- float4 v = source[i, ThreadIds.X];
-
- v = Hlsl.Clamp(v, 0, float.MaxValue);
- v.XYZ = Hlsl.Pow(v.XYZ, 1 / 3f);
-
- target[i, ThreadIds.X] = v;
- }
+ target[i, ThreadIds.X] = v;
}
}
}
diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs
index 159e1965..545c3e48 100644
--- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs
+++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs
@@ -5,85 +5,84 @@ using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing.Processors;
using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
-namespace ComputeSharp.BokehBlur.Processors
+namespace ComputeSharp.BokehBlur.Processors;
+
+///
+/// Defines Gaussian blur by a (Sigma, Radius) pair.
+///
+public sealed partial class HlslGaussianBlurProcessor : IImageProcessor
{
///
- /// Defines Gaussian blur by a (Sigma, Radius) pair.
+ /// The default value for .
///
- public sealed partial class HlslGaussianBlurProcessor : IImageProcessor
+ public const float DefaultSigma = 3f;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public HlslGaussianBlurProcessor()
+ : this(Gpu.Default, DefaultSigma, 9)
{
- ///
- /// The default value for .
- ///
- public const float DefaultSigma = 3f;
+ }
- ///
- /// Initializes a new instance of the class.
- ///
- public HlslGaussianBlurProcessor()
- : this(Gpu.Default, DefaultSigma, 9)
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The radius value representing the size of the area to sample.
+ public HlslGaussianBlurProcessor(int radius)
+ : this(Gpu.Default, radius / 3F, radius)
+ {
+ }
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The associated with the current instance.
+ /// The radius value representing the size of the area to sample.
+ public HlslGaussianBlurProcessor(GraphicsDevice device, int radius)
+ : this(device, radius / 3F, radius)
+ {
+ }
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The associated with the current instance.
+ /// The sigma value representing the weight of the blur.
+ /// The radius value representing the size of the area to sample (this should be at least twice the sigma value)
+ public HlslGaussianBlurProcessor(GraphicsDevice device, float sigma, int radius)
+ {
+ GraphicsDevice = device;
+ Sigma = sigma;
+ Radius = radius;
+ }
+
+ ///
+ /// The instance in use.
+ ///
+ private readonly GraphicsDevice GraphicsDevice;
+
+ ///
+ /// Gets the sigma value representing the weight of the blur.
+ ///
+ public float Sigma { get; }
+
+ ///
+ /// Gets the radius defining the size of the area to sample.
+ ///
+ public int Radius { get; }
+
+ ///
+ public IImageProcessor CreatePixelSpecificProcessor(Configuration configuration, Image source, Rectangle sourceRectangle)
+ where TPixel : unmanaged, IPixel
+ {
+ if (typeof(TPixel) != typeof(ImageSharpRgba32))
{
+ ThrowHelper.ThrowInvalidOperationException("This processor only supports the RGBA32 pixel format");
}
- ///
- /// Initializes a new instance of the class.
- ///
- /// The radius value representing the size of the area to sample.
- public HlslGaussianBlurProcessor(int radius)
- : this(Gpu.Default, radius / 3F, radius)
- {
- }
+ var processor = new Implementation(this, configuration, Unsafe.As>(source), sourceRectangle);
- ///
- /// Initializes a new instance of the class.
- ///
- /// The associated with the current instance.
- /// The radius value representing the size of the area to sample.
- public HlslGaussianBlurProcessor(GraphicsDevice device, int radius)
- : this(device, radius / 3F, radius)
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The associated with the current instance.
- /// The sigma value representing the weight of the blur.
- /// The radius value representing the size of the area to sample (this should be at least twice the sigma value)
- public HlslGaussianBlurProcessor(GraphicsDevice device, float sigma, int radius)
- {
- GraphicsDevice = device;
- Sigma = sigma;
- Radius = radius;
- }
-
- ///
- /// The instance in use.
- ///
- private readonly GraphicsDevice GraphicsDevice;
-
- ///
- /// Gets the sigma value representing the weight of the blur.
- ///
- public float Sigma { get; }
-
- ///
- /// Gets the radius defining the size of the area to sample.
- ///
- public int Radius { get; }
-
- ///
- public IImageProcessor CreatePixelSpecificProcessor(Configuration configuration, Image source, Rectangle sourceRectangle)
- where TPixel : unmanaged, IPixel
- {
- if (typeof(TPixel) != typeof(ImageSharpRgba32))
- {
- ThrowHelper.ThrowInvalidOperationException("This processor only supports the RGBA32 pixel format");
- }
-
- var processor = new Implementation(this, configuration, Unsafe.As>(source), sourceRectangle);
-
- return Unsafe.As>(processor);
- }
+ return Unsafe.As>(processor);
}
}
diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs
index e3b5a7c4..5176edea 100644
--- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs
+++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs
@@ -7,172 +7,171 @@ using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing.Processors;
using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
-namespace ComputeSharp.BokehBlur.Processors
+namespace ComputeSharp.BokehBlur.Processors;
+
+///
+public sealed partial class HlslGaussianBlurProcessor
{
- ///
- public sealed partial class HlslGaussianBlurProcessor
+ ///
+ /// Applies Gaussian blur processing to an image.
+ ///
+ internal sealed partial class Implementation : ImageProcessor
{
///
- /// Applies Gaussian blur processing to an image.
+ /// The instance in use.
///
- internal sealed partial class Implementation : ImageProcessor
+ private readonly GraphicsDevice GraphicsDevice;
+
+ ///
+ /// The 1D kernel to apply.
+ ///
+ private readonly float[] Kernel;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The defining the processor parameters.
+ /// The configuration which allows altering default behaviour or extending the library.
+ /// The source for the current processor instance.
+ /// The source area to process for the current processor instance.
+ public Implementation(HlslGaussianBlurProcessor definition, Configuration configuration, Image source, Rectangle sourceRectangle)
+ : base(configuration, source, sourceRectangle)
{
- ///
- /// The instance in use.
- ///
- private readonly GraphicsDevice GraphicsDevice;
+ int kernelSize = definition.Radius * 2 + 1;
- ///
- /// The 1D kernel to apply.
- ///
- private readonly float[] Kernel;
+ GraphicsDevice = definition.GraphicsDevice;
+ Kernel = CreateGaussianBlurKernel(kernelSize, definition.Sigma);
+ }
- ///
- /// Initializes a new instance of the class.
- ///
- /// The defining the processor parameters.
- /// The configuration which allows altering default behaviour or extending the library.
- /// The source for the current processor instance.
- /// The source area to process for the current processor instance.
- public Implementation(HlslGaussianBlurProcessor definition, Configuration configuration, Image source, Rectangle sourceRectangle)
- : base(configuration, source, sourceRectangle)
+ ///
+ /// Creates a 1 dimensional Gaussian kernel using the Gaussian G(x) function.
+ ///
+ private static float[] CreateGaussianBlurKernel(int size, float weight)
+ {
+ float[] kernel = new float[size];
+ ref float rKernel = ref kernel[0];
+
+ float sum = 0F;
+ float midpoint = (size - 1) / 2F;
+
+ for (int i = 0; i < size; i++)
{
- int kernelSize = definition.Radius * 2 + 1;
-
- GraphicsDevice = definition.GraphicsDevice;
- Kernel = CreateGaussianBlurKernel(kernelSize, definition.Sigma);
+ float x = i - midpoint;
+ float gx = Gaussian(x, weight);
+ sum += gx;
+ Unsafe.Add(ref rKernel, i) = gx;
}
- ///
- /// Creates a 1 dimensional Gaussian kernel using the Gaussian G(x) function.
- ///
- private static float[] CreateGaussianBlurKernel(int size, float weight)
+ // Normalize kernel so that the sum of all weights equals 1
+ for (int i = 0; i < size; i++)
{
- float[] kernel = new float[size];
- ref float rKernel = ref kernel[0];
-
- float sum = 0F;
- float midpoint = (size - 1) / 2F;
-
- for (int i = 0; i < size; i++)
- {
- float x = i - midpoint;
- float gx = Gaussian(x, weight);
- sum += gx;
- Unsafe.Add(ref rKernel, i) = gx;
- }
-
- // Normalize kernel so that the sum of all weights equals 1
- for (int i = 0; i < size; i++)
- {
- Unsafe.Add(ref rKernel, i) /= sum;
- }
-
- return kernel;
+ Unsafe.Add(ref rKernel, i) /= sum;
}
- ///
- /// Implementation of 1D Gaussian G(x) function.
- ///
- /// The x provided to G(x)
- /// The spread of the blur.
- /// The Gaussian G(x)
- private static float Gaussian(float x, float sigma)
+ return kernel;
+ }
+
+ ///
+ /// Implementation of 1D Gaussian G(x) function.
+ ///
+ /// The x provided to G(x)
+ /// The spread of the blur.
+ /// The Gaussian G(x)
+ private static float Gaussian(float x, float sigma)
+ {
+ const float Numerator = 1.0f;
+ float denominator = MathF.Sqrt(2 * MathF.PI) * sigma;
+
+ float exponentNumerator = -x * x;
+ float exponentDenominator = 2 * sigma * sigma;
+
+ float left = Numerator / denominator;
+ float right = MathF.Exp(exponentNumerator / exponentDenominator);
+
+ return left * right;
+ }
+
+ ///
+ protected override void OnFrameApply(ImageFrame source)
+ {
+ if (!source.TryGetSinglePixelSpan(out Span pixelSpan))
{
- const float Numerator = 1.0f;
- float denominator = MathF.Sqrt(2 * MathF.PI) * sigma;
-
- float exponentNumerator = -x * x;
- float exponentDenominator = 2 * sigma * sigma;
-
- float left = Numerator / denominator;
- float right = MathF.Exp(exponentNumerator / exponentDenominator);
-
- return left * right;
+ ThrowHelper.ThrowInvalidOperationException("Cannot process image frames wrapping discontiguous memory");
}
+ Span span = MemoryMarshal.Cast(pixelSpan);
+
+ using ReadWriteTexture2D sourceTexture = GraphicsDevice.AllocateReadWriteTexture2D(span, source.Width, source.Height);
+ using ReadWriteTexture2D firstPassTexture = GraphicsDevice.AllocateReadWriteTexture2D(source.Width, source.Height);
+ using ReadOnlyBuffer kernelBuffer = GraphicsDevice.AllocateReadOnlyBuffer(Kernel);
+
+ GraphicsDevice.For(source.Width, source.Height, new(sourceTexture, firstPassTexture, kernelBuffer));
+ GraphicsDevice.For(source.Width, source.Height, new(firstPassTexture, sourceTexture, kernelBuffer));
+
+ sourceTexture.CopyTo(span);
+ }
+
+ ///
+ /// Kernel for the vertical convolution pass.
+ ///
+ [AutoConstructor]
+ internal readonly partial struct VerticalConvolutionProcessor : IComputeShader
+ {
+ public readonly IReadWriteTexture2D source;
+ public readonly IReadWriteTexture2D target;
+ public readonly ReadOnlyBuffer kernel;
+
///
- protected override void OnFrameApply(ImageFrame source)
+ public void Execute()
{
- if (!source.TryGetSinglePixelSpan(out Span pixelSpan))
+ Vector4 result = Vector4.Zero;
+ int maxY = source.Height - 1;
+ int maxX = source.Width - 1;
+ int kernelLength = kernel.Length;
+ int radiusY = kernelLength >> 1;
+
+ for (int i = 0; i < kernelLength; i++)
{
- ThrowHelper.ThrowInvalidOperationException("Cannot process image frames wrapping discontiguous memory");
+ int offsetY = Hlsl.Clamp(ThreadIds.Y + i - radiusY, 0, maxY);
+ int offsetX = Hlsl.Clamp(ThreadIds.X, 0, maxX);
+ Vector4 color = source[offsetX, offsetY];
+
+ result += kernel[i] * color;
}
- Span span = MemoryMarshal.Cast(pixelSpan);
-
- using ReadWriteTexture2D sourceTexture = GraphicsDevice.AllocateReadWriteTexture2D(span, source.Width, source.Height);
- using ReadWriteTexture2D firstPassTexture = GraphicsDevice.AllocateReadWriteTexture2D(source.Width, source.Height);
- using ReadOnlyBuffer kernelBuffer = GraphicsDevice.AllocateReadOnlyBuffer(Kernel);
-
- GraphicsDevice.For(source.Width, source.Height, new(sourceTexture, firstPassTexture, kernelBuffer));
- GraphicsDevice.For(source.Width, source.Height, new(firstPassTexture, sourceTexture, kernelBuffer));
-
- sourceTexture.CopyTo(span);
+ target[ThreadIds.XY] = result;
}
+ }
- ///
- /// Kernel for the vertical convolution pass.
- ///
- [AutoConstructor]
- internal readonly partial struct VerticalConvolutionProcessor : IComputeShader
+ ///
+ /// Kernel for the horizontal convolution pass.
+ ///
+ [AutoConstructor]
+ internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader
+ {
+ public readonly IReadWriteTexture2D source;
+ public readonly IReadWriteTexture2D target;
+ public readonly ReadOnlyBuffer kernel;
+
+ ///
+ public void Execute()
{
- public readonly IReadWriteTexture2D source;
- public readonly IReadWriteTexture2D target;
- public readonly ReadOnlyBuffer kernel;
+ Vector4 result = Vector4.Zero;
+ int maxY = source.Height - 1;
+ int maxX = source.Width - 1;
+ int kernelLength = kernel.Length;
+ int radiusX = kernelLength >> 1;
+ int offsetY = Hlsl.Clamp(ThreadIds.Y, 0, maxY);
- ///
- public void Execute()
+ for (int i = 0; i < kernelLength; i++)
{
- Vector4 result = Vector4.Zero;
- int maxY = source.Height - 1;
- int maxX = source.Width - 1;
- int kernelLength = kernel.Length;
- int radiusY = kernelLength >> 1;
+ int offsetX = Hlsl.Clamp(ThreadIds.X + i - radiusX, 0, maxX);
+ Vector4 color = source[offsetX, offsetY];
- for (int i = 0; i < kernelLength; i++)
- {
- int offsetY = Hlsl.Clamp(ThreadIds.Y + i - radiusY, 0, maxY);
- int offsetX = Hlsl.Clamp(ThreadIds.X, 0, maxX);
- Vector4 color = source[offsetX, offsetY];
-
- result += kernel[i] * color;
- }
-
- target[ThreadIds.XY] = result;
+ result += kernel[i] * color;
}
- }
- ///
- /// Kernel for the horizontal convolution pass.
- ///
- [AutoConstructor]
- internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader
- {
- public readonly IReadWriteTexture2D source;
- public readonly IReadWriteTexture2D target;
- public readonly ReadOnlyBuffer kernel;
-
- ///
- public void Execute()
- {
- Vector4 result = Vector4.Zero;
- int maxY = source.Height - 1;
- int maxX = source.Width - 1;
- int kernelLength = kernel.Length;
- int radiusX = kernelLength >> 1;
- int offsetY = Hlsl.Clamp(ThreadIds.Y, 0, maxY);
-
- for (int i = 0; i < kernelLength; i++)
- {
- int offsetX = Hlsl.Clamp(ThreadIds.X + i - radiusX, 0, maxX);
- Vector4 color = source[offsetX, offsetY];
-
- result += kernel[i] * color;
- }
-
- target[ThreadIds.XY] = result;
- }
+ target[ThreadIds.XY] = result;
}
}
}
diff --git a/samples/ComputeSharp.ImageProcessing/Program.cs b/samples/ComputeSharp.ImageProcessing/Program.cs
index ded812cd..2487916f 100644
--- a/samples/ComputeSharp.ImageProcessing/Program.cs
+++ b/samples/ComputeSharp.ImageProcessing/Program.cs
@@ -7,32 +7,31 @@ using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Processing.Processors;
using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
-namespace ComputeSharp.ImageProcessing
+namespace ComputeSharp.ImageProcessing;
+
+class Program
{
- class Program
+ static void Main()
{
- static void Main()
+ Console.WriteLine(">> Loading image");
+ string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "city.jpg");
+ using Image image = Image.Load(path);
+
+ // Apply a series of processors and save the results
+ foreach (var effect in new (string Name, IImageProcessor Processor)[]
{
- Console.WriteLine(">> Loading image");
- string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "city.jpg");
- using Image image = Image.Load(path);
+ ("bokeh", new HlslBokehBlurProcessor(80, 2)),
+ ("gaussian", new HlslGaussianBlurProcessor(80))
+ })
+ {
+ Console.WriteLine($">> Applying {effect.Name}");
+ using Image copy = image.Clone(c => c.ApplyProcessor(effect.Processor));
- // Apply a series of processors and save the results
- foreach (var effect in new (string Name, IImageProcessor Processor)[]
- {
- ("bokeh", new HlslBokehBlurProcessor(80, 2)),
- ("gaussian", new HlslGaussianBlurProcessor(80))
- })
- {
- Console.WriteLine($">> Applying {effect.Name}");
- using Image copy = image.Clone(c => c.ApplyProcessor(effect.Processor));
-
- Console.WriteLine($">> Saving {effect.Name} to disk");
- string targetPath = Path.Combine(
- Path.GetRelativePath(Path.GetDirectoryName(path)!, @"..\..\..\"),
- $"{Path.GetFileNameWithoutExtension(path)}_{effect.Name}{Path.GetExtension(path)}");
- copy.Save(targetPath);
- }
+ Console.WriteLine($">> Saving {effect.Name} to disk");
+ string targetPath = Path.Combine(
+ Path.GetRelativePath(Path.GetDirectoryName(path)!, @"..\..\..\"),
+ $"{Path.GetFileNameWithoutExtension(path)}_{effect.Name}{Path.GetExtension(path)}");
+ copy.Save(targetPath);
}
}
}
diff --git a/samples/ComputeSharp.Sample.FSharp.Shaders/MultiplyByTwo.cs b/samples/ComputeSharp.Sample.FSharp.Shaders/MultiplyByTwo.cs
index 747bd11b..4d20dfb6 100644
--- a/samples/ComputeSharp.Sample.FSharp.Shaders/MultiplyByTwo.cs
+++ b/samples/ComputeSharp.Sample.FSharp.Shaders/MultiplyByTwo.cs
@@ -1,17 +1,16 @@
-namespace ComputeSharp.Sample.FSharp.Shaders
-{
- ///
- /// A sample shader thaat just multiplies items in a buffer by two.
- ///
- [AutoConstructor]
- public readonly partial struct MultiplyByTwo : IComputeShader
- {
- public readonly ReadWriteBuffer buffer;
+namespace ComputeSharp.Sample.FSharp.Shaders;
- ///
- public void Execute()
- {
- buffer[ThreadIds.X] *= 2;
- }
+///
+/// A sample shader thaat just multiplies items in a buffer by two.
+///
+[AutoConstructor]
+public readonly partial struct MultiplyByTwo : IComputeShader
+{
+ public readonly ReadWriteBuffer buffer;
+
+ ///
+ public void Execute()
+ {
+ buffer[ThreadIds.X] *= 2;
}
}
diff --git a/samples/ComputeSharp.Sample.Shared/Program.cs b/samples/ComputeSharp.Sample.Shared/Program.cs
index f87c1678..3fc4ead9 100644
--- a/samples/ComputeSharp.Sample.Shared/Program.cs
+++ b/samples/ComputeSharp.Sample.Shared/Program.cs
@@ -2,71 +2,69 @@
using System.Globalization;
using System.Linq;
-namespace ComputeSharp.Sample
+namespace ComputeSharp.Sample;
+
+partial class Program
{
- partial class Program
+ static void Main()
{
- static void Main()
+ float[] array = Enumerable.Range(1, 100).Select(static i => (float)i).ToArray();
+
+ // Create the graphics buffer
+ using ReadWriteBuffer gpuBuffer = Gpu.Default.AllocateReadWriteBuffer(array);
+
+ // Run the shader
+ Gpu.Default.For(100, new MainKernel(gpuBuffer));
+
+ // Print the initial matrix
+ PrintMatrix(array, 10, 10, "BEFORE");
+
+ // Get the data back
+ gpuBuffer.CopyTo(array);
+
+ // Print the updated matrix
+ PrintMatrix(array, 10, 10, "AFTER");
+ }
+
+ ///
+ /// Kernel for .
+ ///
+ [AutoConstructor]
+ internal readonly partial struct MainKernel : IComputeShader
+ {
+ public readonly ReadWriteBuffer buffer;
+
+ ///
+ public void Execute()
{
- float[] array = Enumerable.Range(1, 100).Select(static i => (float)i).ToArray();
-
- // Create the graphics buffer
- using ReadWriteBuffer gpuBuffer = Gpu.Default.AllocateReadWriteBuffer(array);
-
- // Run the shader
- Gpu.Default.For(100, new MainKernel(gpuBuffer));
-
- // Print the initial matrix
- PrintMatrix(array, 10, 10, "BEFORE");
-
- // Get the data back
- gpuBuffer.CopyTo(array);
-
- // Print the updated matrix
- PrintMatrix(array, 10, 10, "AFTER");
- }
-
- ///
- /// Kernel for .
- ///
- [AutoConstructor]
- internal readonly partial struct MainKernel : IComputeShader
- {
- public readonly ReadWriteBuffer buffer;
-
- ///
- public void Execute()
- {
- buffer[ThreadIds.X] *= 2;
- }
- }
-
- ///
- /// Prints a matrix in a properly formatted way.
- ///
- /// The input array representing the matrix to print.
- /// The width of the array to print.
- /// The height of the array to print.
- /// The name of the matrix to print.
- private static void PrintMatrix(float[] array, int width, int height, string name)
- {
- int pad = 48 - name.Length;
- string title = $"{new string('=', pad / 2)} {name} {new string('=', (pad + 1) / 2)}";
-
- Console.WriteLine(title);
-
- int numberWidth = Math.Max(array.Max().ToString(CultureInfo.InvariantCulture).Length, 4);
-
- for (int i = 0; i < height; i++)
- {
- var row = array[(i * width)..((i + 1) * width)];
- var text = string.Join(",", row.Select(x => x.ToString(CultureInfo.InvariantCulture).PadLeft(numberWidth)));
-
- Console.WriteLine(text);
- }
-
- Console.WriteLine(new string('=', 50));
+ buffer[ThreadIds.X] *= 2;
}
}
-}
+ ///
+ /// Prints a matrix in a properly formatted way.
+ ///
+ /// The input array representing the matrix to print.
+ /// The width of the array to print.
+ /// The height of the array to print.
+ /// The name of the matrix to print.
+ private static void PrintMatrix(float[] array, int width, int height, string name)
+ {
+ int pad = 48 - name.Length;
+ string title = $"{new string('=', pad / 2)} {name} {new string('=', (pad + 1) / 2)}";
+
+ Console.WriteLine(title);
+
+ int numberWidth = Math.Max(array.Max().ToString(CultureInfo.InvariantCulture).Length, 4);
+
+ for (int i = 0; i < height; i++)
+ {
+ var row = array[(i * width)..((i + 1) * width)];
+ var text = string.Join(",", row.Select(x => x.ToString(CultureInfo.InvariantCulture).PadLeft(numberWidth)));
+
+ Console.WriteLine(text);
+ }
+
+ Console.WriteLine(new string('=', 50));
+ }
+}
diff --git a/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs b/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs
index 93c3c2ea..26ddb260 100644
--- a/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs
+++ b/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs
@@ -3,301 +3,300 @@ using ComputeSharp.Interop;
using TerraFX.Interop;
using FX = TerraFX.Interop.Windows;
-namespace ComputeSharp.SwapChain.Backend
+namespace ComputeSharp.SwapChain.Backend;
+
+internal sealed class SwapChainApplication : Win32Application
+ where T : struct, IPixelShader
{
- internal sealed class SwapChainApplication : Win32Application
- where T : struct, IPixelShader
+ ///
+ /// The instance used to create shaders to run.
+ ///
+ private readonly Func shaderFactory;
+
+ ///
+ /// The pointer for the device currently in use.
+ ///
+ private ComPtr d3D12Device;
+
+ ///
+ /// The instance to use for graphics operations.
+ ///
+ private ComPtr d3D12CommandQueue;
+
+ ///
+ /// The instance used for graphics operations.
+ ///
+ private ComPtr d3D12Fence;
+
+ ///
+ /// The next fence value for graphics operations using .
+ ///
+ private ulong nextD3D12FenceValue = 1;
+
+ ///
+ /// The object to create command lists.
+ ///
+ private ComPtr d3D12CommandAllocator;
+
+ ///
+ /// The instance used to copy data to the back buffers.
+ ///
+ private ComPtr d3D12GraphicsCommandList;
+
+ ///
+ /// The instance used to display content onto the target window.
+ ///
+ private ComPtr dxgiSwapChain1;
+
+ ///
+ /// The first buffer within .
+ ///
+ private ComPtr d3D12Resource0;
+
+ ///
+ /// The second buffer within .
+ ///
+ private ComPtr d3D12Resource1;
+
+ ///
+ /// The index of the next buffer that can be used to present content.
+ ///
+ private uint currentBufferIndex;
+
+ ///
+ /// The instance used to prepare frames to display.
+ ///
+ private ReadWriteTexture2D? texture;
+
+ ///
+ /// Whether or not the window has been resized and requires the buffers to be updated.
+ ///
+ private bool isResizePending;
+
+ ///
+ /// Creates a new instance with the specified parameters.
+ ///
+ /// The instance used to create shaders to run.
+ public SwapChainApplication(Func shaderFactory)
{
- ///
- /// The instance used to create shaders to run.
- ///
- private readonly Func shaderFactory;
+ this.shaderFactory = shaderFactory;
+ }
- ///
- /// The pointer for the device currently in use.
- ///
- private ComPtr d3D12Device;
-
- ///
- /// The instance to use for graphics operations.
- ///
- private ComPtr d3D12CommandQueue;
-
- ///
- /// The instance used for graphics operations.
- ///
- private ComPtr d3D12Fence;
-
- ///
- /// The next fence value for graphics operations using .
- ///
- private ulong nextD3D12FenceValue = 1;
-
- ///
- /// The object to create command lists.
- ///
- private ComPtr d3D12CommandAllocator;
-
- ///
- /// The instance used to copy data to the back buffers.
- ///
- private ComPtr d3D12GraphicsCommandList;
-
- ///
- /// The instance used to display content onto the target window.
- ///
- private ComPtr dxgiSwapChain1;
-
- ///
- /// The first buffer within .
- ///
- private ComPtr d3D12Resource0;
-
- ///
- /// The second buffer within .
- ///
- private ComPtr d3D12Resource1;
-
- ///
- /// The index of the next buffer that can be used to present content.
- ///
- private uint currentBufferIndex;
-
- ///
- /// The instance used to prepare frames to display.
- ///
- private ReadWriteTexture2D? texture;
-
- ///
- /// Whether or not the window has been resized and requires the buffers to be updated.
- ///
- private bool isResizePending;
-
- ///
- /// Creates a new instance with the specified parameters.
- ///
- /// The instance used to create shaders to run.
- public SwapChainApplication(Func shaderFactory)
+ ///
+ public override unsafe void OnInitialize(HWND hwnd)
+ {
+ // Get the underlying ID3D12Device in use
+ fixed (ID3D12Device** d3D12Device = this.d3D12Device)
{
- this.shaderFactory = shaderFactory;
+ _ = InteropServices.TryGetID3D12Device(Gpu.Default, FX.__uuidof(), (void**)d3D12Device);
}
- ///
- public override unsafe void OnInitialize(HWND hwnd)
+ // Create the direct command queue to use
+ fixed (ID3D12CommandQueue** d3D12CommandQueue = this.d3D12CommandQueue)
{
- // Get the underlying ID3D12Device in use
- fixed (ID3D12Device** d3D12Device = this.d3D12Device)
- {
- _ = InteropServices.TryGetID3D12Device(Gpu.Default, FX.__uuidof(), (void**)d3D12Device);
- }
+ D3D12_COMMAND_QUEUE_DESC d3D12CommandQueueDesc;
+ d3D12CommandQueueDesc.Type = D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT;
+ d3D12CommandQueueDesc.Priority = (int)D3D12_COMMAND_QUEUE_PRIORITY.D3D12_COMMAND_QUEUE_PRIORITY_NORMAL;
+ d3D12CommandQueueDesc.Flags = D3D12_COMMAND_QUEUE_FLAGS.D3D12_COMMAND_QUEUE_FLAG_NONE;
+ d3D12CommandQueueDesc.NodeMask = 0;
- // Create the direct command queue to use
- fixed (ID3D12CommandQueue** d3D12CommandQueue = this.d3D12CommandQueue)
- {
- D3D12_COMMAND_QUEUE_DESC d3D12CommandQueueDesc;
- d3D12CommandQueueDesc.Type = D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT;
- d3D12CommandQueueDesc.Priority = (int)D3D12_COMMAND_QUEUE_PRIORITY.D3D12_COMMAND_QUEUE_PRIORITY_NORMAL;
- d3D12CommandQueueDesc.Flags = D3D12_COMMAND_QUEUE_FLAGS.D3D12_COMMAND_QUEUE_FLAG_NONE;
- d3D12CommandQueueDesc.NodeMask = 0;
-
- _ = d3D12Device.Get()->CreateCommandQueue(
- &d3D12CommandQueueDesc,
- FX.__uuidof(),
- (void**)d3D12CommandQueue);
- }
-
- // Create the direct fence
- fixed (ID3D12Fence** d3D12Fence = this.d3D12Fence)
- {
- _ = this.d3D12Device.Get()->CreateFence(
- 0,
- D3D12_FENCE_FLAGS.D3D12_FENCE_FLAG_NONE,
- FX.__uuidof(),
- (void**)d3D12Fence);
- }
-
- // Create the swap chain to display frames
- fixed (IDXGISwapChain1** dxgiSwapChain1 = this.dxgiSwapChain1)
- {
- using ComPtr dxgiFactory2 = default;
-
- _ = FX.CreateDXGIFactory2(FX.DXGI_CREATE_FACTORY_DEBUG, FX.__uuidof(), (void**)dxgiFactory2.GetAddressOf());
-
- DXGI_SWAP_CHAIN_DESC1 dxgiSwapChainDesc1 = default;
- dxgiSwapChainDesc1.AlphaMode = DXGI_ALPHA_MODE.DXGI_ALPHA_MODE_IGNORE;
- dxgiSwapChainDesc1.BufferCount = 2;
- dxgiSwapChainDesc1.Flags = 0;
- dxgiSwapChainDesc1.Format = DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_UNORM;
- dxgiSwapChainDesc1.Width = 0;
- dxgiSwapChainDesc1.Height = 0;
- dxgiSwapChainDesc1.SampleDesc = new DXGI_SAMPLE_DESC(count: 1, quality: 0);
- dxgiSwapChainDesc1.Scaling = DXGI_SCALING.DXGI_SCALING_STRETCH;
- dxgiSwapChainDesc1.Stereo = 0;
- dxgiSwapChainDesc1.SwapEffect = DXGI_SWAP_EFFECT.DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
-
- _ = dxgiFactory2.Get()->CreateSwapChainForHwnd(
- (IUnknown*)d3D12CommandQueue.Get(),
- hwnd,
- &dxgiSwapChainDesc1,
- null,
- null,
- dxgiSwapChain1);
- }
-
- // Create the command allocator to use
- fixed (ID3D12CommandAllocator** d3D12CommandAllocator = this.d3D12CommandAllocator)
- {
- this.d3D12Device.Get()->CreateCommandAllocator(
- D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT,
- FX.__uuidof(),
- (void**)d3D12CommandAllocator);
- }
-
- // Create the reusable command list to copy data to the back buffers
- fixed (ID3D12GraphicsCommandList** d3D12GraphicsCommandList = this.d3D12GraphicsCommandList)
- {
- this.d3D12Device.Get()->CreateCommandList(
- 0,
- D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT,
- d3D12CommandAllocator,
- null,
- FX.__uuidof(),
- (void**)d3D12GraphicsCommandList);
- }
-
- // Close the command list to prepare it for future use
- this.d3D12GraphicsCommandList.Get()->Close();
+ _ = d3D12Device.Get()->CreateCommandQueue(
+ &d3D12CommandQueueDesc,
+ FX.__uuidof(),
+ (void**)d3D12CommandQueue);
}
- ///
- public override unsafe void OnResize()
+ // Create the direct fence
+ fixed (ID3D12Fence** d3D12Fence = this.d3D12Fence)
{
- this.isResizePending = true;
+ _ = this.d3D12Device.Get()->CreateFence(
+ 0,
+ D3D12_FENCE_FLAGS.D3D12_FENCE_FLAG_NONE,
+ FX.__uuidof(),
+ (void**)d3D12Fence);
}
- ///
- /// Applies the actual resize logic that was scheduled from .
- ///
- private unsafe void ApplyResize()
+ // Create the swap chain to display frames
+ fixed (IDXGISwapChain1** dxgiSwapChain1 = this.dxgiSwapChain1)
{
- this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), this.nextD3D12FenceValue);
+ using ComPtr dxgiFactory2 = default;
- // Wait for the fence again to ensure there are no pending operations
- this.d3D12Fence.Get()->SetEventOnCompletion(this.nextD3D12FenceValue, default);
+ _ = FX.CreateDXGIFactory2(FX.DXGI_CREATE_FACTORY_DEBUG, FX.__uuidof(), (void**)dxgiFactory2.GetAddressOf());
- this.nextD3D12FenceValue++;
+ DXGI_SWAP_CHAIN_DESC1 dxgiSwapChainDesc1 = default;
+ dxgiSwapChainDesc1.AlphaMode = DXGI_ALPHA_MODE.DXGI_ALPHA_MODE_IGNORE;
+ dxgiSwapChainDesc1.BufferCount = 2;
+ dxgiSwapChainDesc1.Flags = 0;
+ dxgiSwapChainDesc1.Format = DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_UNORM;
+ dxgiSwapChainDesc1.Width = 0;
+ dxgiSwapChainDesc1.Height = 0;
+ dxgiSwapChainDesc1.SampleDesc = new DXGI_SAMPLE_DESC(count: 1, quality: 0);
+ dxgiSwapChainDesc1.Scaling = DXGI_SCALING.DXGI_SCALING_STRETCH;
+ dxgiSwapChainDesc1.Stereo = 0;
+ dxgiSwapChainDesc1.SwapEffect = DXGI_SWAP_EFFECT.DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
- // Dispose the old buffers before resizing the buffer
- this.d3D12Resource0.Dispose();
- this.d3D12Resource1.Dispose();
-
- // Resize the swap chain buffers
- this.dxgiSwapChain1.Get()->ResizeBuffers(0, 0, 0, DXGI_FORMAT.DXGI_FORMAT_UNKNOWN, 0);
-
- // Get the index of the initial back buffer
- using (ComPtr dxgiSwapChain3 = default)
- {
- _ = this.dxgiSwapChain1.CopyTo(dxgiSwapChain3.GetAddressOf());
-
- this.currentBufferIndex = dxgiSwapChain3.Get()->GetCurrentBackBufferIndex();
- }
-
- // Retrieve the back buffers for the swap chain
- fixed (ID3D12Resource** d3D12Resource0 = this.d3D12Resource0)
- fixed (ID3D12Resource** d3D12Resource1 = this.d3D12Resource1)
- {
- _ = dxgiSwapChain1.Get()->GetBuffer(0, FX.__uuidof(), (void**)d3D12Resource0);
- _ = dxgiSwapChain1.Get()->GetBuffer(1, FX.__uuidof(), (void**)d3D12Resource1);
- }
-
- this.texture?.Dispose();
-
- D3D12_RESOURCE_DESC d3D12Resource0Description = this.d3D12Resource0.Get()->GetDesc();
-
- // Create the 2D texture to use to generate frames to display
- this.texture = Gpu.Default.AllocateReadWriteTexture2D(
- (int)d3D12Resource0Description.Width,
- (int)d3D12Resource0Description.Height);
+ _ = dxgiFactory2.Get()->CreateSwapChainForHwnd(
+ (IUnknown*)d3D12CommandQueue.Get(),
+ hwnd,
+ &dxgiSwapChainDesc1,
+ null,
+ null,
+ dxgiSwapChain1);
}
- ///
- public override unsafe void OnUpdate(TimeSpan time)
+ // Create the command allocator to use
+ fixed (ID3D12CommandAllocator** d3D12CommandAllocator = this.d3D12CommandAllocator)
{
- if (this.isResizePending)
- {
- ApplyResize();
+ this.d3D12Device.Get()->CreateCommandAllocator(
+ D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT,
+ FX.__uuidof(),
+ (void**)d3D12CommandAllocator);
+ }
- this.isResizePending = false;
- }
+ // Create the reusable command list to copy data to the back buffers
+ fixed (ID3D12GraphicsCommandList** d3D12GraphicsCommandList = this.d3D12GraphicsCommandList)
+ {
+ this.d3D12Device.Get()->CreateCommandList(
+ 0,
+ D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT,
+ d3D12CommandAllocator,
+ null,
+ FX.__uuidof(),
+ (void**)d3D12GraphicsCommandList);
+ }
- // Generate the new frame
- Gpu.Default.ForEach(this.texture!, this.shaderFactory(time));
+ // Close the command list to prepare it for future use
+ this.d3D12GraphicsCommandList.Get()->Close();
+ }
- using ComPtr d3D12Resource = default;
+ ///
+ public override unsafe void OnResize()
+ {
+ this.isResizePending = true;
+ }
- // Get the underlying ID3D12Resource pointer for the texture
- _ = InteropServices.TryGetID3D12Resource(this.texture!, FX.__uuidof(), (void**)d3D12Resource.GetAddressOf());
+ ///
+ /// Applies the actual resize logic that was scheduled from .
+ ///
+ private unsafe void ApplyResize()
+ {
+ this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), this.nextD3D12FenceValue);
- // Get the target back buffer to update
- ID3D12Resource* d3D12ResourceBackBuffer = this.currentBufferIndex switch
- {
- 0 => this.d3D12Resource0.Get(),
- 1 => this.d3D12Resource1.Get(),
- _ => null
- };
+ // Wait for the fence again to ensure there are no pending operations
+ this.d3D12Fence.Get()->SetEventOnCompletion(this.nextD3D12FenceValue, default);
- this.currentBufferIndex ^= 1;
+ this.nextD3D12FenceValue++;
- // Reset the command list and command allocator
- this.d3D12CommandAllocator.Get()->Reset();
- this.d3D12GraphicsCommandList.Get()->Reset(this.d3D12CommandAllocator.Get(), null);
+ // Dispose the old buffers before resizing the buffer
+ this.d3D12Resource0.Dispose();
+ this.d3D12Resource1.Dispose();
- D3D12_RESOURCE_BARRIER* d3D12ResourceBarriers = stackalloc D3D12_RESOURCE_BARRIER[]
- {
- D3D12_RESOURCE_BARRIER.InitTransition(
- d3D12Resource.Get(),
- D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
- D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_SOURCE),
- D3D12_RESOURCE_BARRIER.InitTransition(
- d3D12ResourceBackBuffer,
- D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COMMON,
- D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_DEST)
- };
+ // Resize the swap chain buffers
+ this.dxgiSwapChain1.Get()->ResizeBuffers(0, 0, 0, DXGI_FORMAT.DXGI_FORMAT_UNKNOWN, 0);
- // Transition the resources to COPY_DEST and COPY_SOURCE respectively
- d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers);
+ // Get the index of the initial back buffer
+ using (ComPtr dxgiSwapChain3 = default)
+ {
+ _ = this.dxgiSwapChain1.CopyTo(dxgiSwapChain3.GetAddressOf());
- // Copy the generated frame to the target back buffer
- d3D12GraphicsCommandList.Get()->CopyResource(d3D12ResourceBackBuffer, d3D12Resource.Get());
+ this.currentBufferIndex = dxgiSwapChain3.Get()->GetCurrentBackBufferIndex();
+ }
- d3D12ResourceBarriers[0] = D3D12_RESOURCE_BARRIER.InitTransition(
+ // Retrieve the back buffers for the swap chain
+ fixed (ID3D12Resource** d3D12Resource0 = this.d3D12Resource0)
+ fixed (ID3D12Resource** d3D12Resource1 = this.d3D12Resource1)
+ {
+ _ = dxgiSwapChain1.Get()->GetBuffer(0, FX.__uuidof(), (void**)d3D12Resource0);
+ _ = dxgiSwapChain1.Get()->GetBuffer(1, FX.__uuidof(), (void**)d3D12Resource1);
+ }
+
+ this.texture?.Dispose();
+
+ D3D12_RESOURCE_DESC d3D12Resource0Description = this.d3D12Resource0.Get()->GetDesc();
+
+ // Create the 2D texture to use to generate frames to display
+ this.texture = Gpu.Default.AllocateReadWriteTexture2D(
+ (int)d3D12Resource0Description.Width,
+ (int)d3D12Resource0Description.Height);
+ }
+
+ ///
+ public override unsafe void OnUpdate(TimeSpan time)
+ {
+ if (this.isResizePending)
+ {
+ ApplyResize();
+
+ this.isResizePending = false;
+ }
+
+ // Generate the new frame
+ Gpu.Default.ForEach(this.texture!, this.shaderFactory(time));
+
+ using ComPtr d3D12Resource = default;
+
+ // Get the underlying ID3D12Resource pointer for the texture
+ _ = InteropServices.TryGetID3D12Resource(this.texture!, FX.__uuidof(), (void**)d3D12Resource.GetAddressOf());
+
+ // Get the target back buffer to update
+ ID3D12Resource* d3D12ResourceBackBuffer = this.currentBufferIndex switch
+ {
+ 0 => this.d3D12Resource0.Get(),
+ 1 => this.d3D12Resource1.Get(),
+ _ => null
+ };
+
+ this.currentBufferIndex ^= 1;
+
+ // Reset the command list and command allocator
+ this.d3D12CommandAllocator.Get()->Reset();
+ this.d3D12GraphicsCommandList.Get()->Reset(this.d3D12CommandAllocator.Get(), null);
+
+ D3D12_RESOURCE_BARRIER* d3D12ResourceBarriers = stackalloc D3D12_RESOURCE_BARRIER[]
+ {
+ D3D12_RESOURCE_BARRIER.InitTransition(
d3D12Resource.Get(),
- D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_SOURCE,
- D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
-
- d3D12ResourceBarriers[1] = D3D12_RESOURCE_BARRIER.InitTransition(
+ D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
+ D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_SOURCE),
+ D3D12_RESOURCE_BARRIER.InitTransition(
d3D12ResourceBackBuffer,
- D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_DEST,
- D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COMMON);
+ D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COMMON,
+ D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_DEST)
+ };
- // Transition the resources back to COMMON and UNORDERED_ACCESS respectively
- d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers);
+ // Transition the resources to COPY_DEST and COPY_SOURCE respectively
+ d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers);
- d3D12GraphicsCommandList.Get()->Close();
+ // Copy the generated frame to the target back buffer
+ d3D12GraphicsCommandList.Get()->CopyResource(d3D12ResourceBackBuffer, d3D12Resource.Get());
- // Execute the command list to perform the copy
- this.d3D12CommandQueue.Get()->ExecuteCommandLists(1, (ID3D12CommandList**)d3D12GraphicsCommandList.GetAddressOf());
- this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), this.nextD3D12FenceValue);
+ d3D12ResourceBarriers[0] = D3D12_RESOURCE_BARRIER.InitTransition(
+ d3D12Resource.Get(),
+ D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_SOURCE,
+ D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
- // Present the new frame
- this.dxgiSwapChain1.Get()->Present(0, 0);
+ d3D12ResourceBarriers[1] = D3D12_RESOURCE_BARRIER.InitTransition(
+ d3D12ResourceBackBuffer,
+ D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_DEST,
+ D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COMMON);
- if (this.nextD3D12FenceValue > this.d3D12Fence.Get()->GetCompletedValue())
- {
- this.d3D12Fence.Get()->SetEventOnCompletion(this.nextD3D12FenceValue, default);
- }
+ // Transition the resources back to COMMON and UNORDERED_ACCESS respectively
+ d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers);
- this.nextD3D12FenceValue++;
+ d3D12GraphicsCommandList.Get()->Close();
+
+ // Execute the command list to perform the copy
+ this.d3D12CommandQueue.Get()->ExecuteCommandLists(1, (ID3D12CommandList**)d3D12GraphicsCommandList.GetAddressOf());
+ this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), this.nextD3D12FenceValue);
+
+ // Present the new frame
+ this.dxgiSwapChain1.Get()->Present(0, 0);
+
+ if (this.nextD3D12FenceValue > this.d3D12Fence.Get()->GetCompletedValue())
+ {
+ this.d3D12Fence.Get()->SetEventOnCompletion(this.nextD3D12FenceValue, default);
}
+
+ this.nextD3D12FenceValue++;
}
}
diff --git a/samples/ComputeSharp.SwapChain/Backend/Win32Application.cs b/samples/ComputeSharp.SwapChain/Backend/Win32Application.cs
index af15cf6b..2dfe60da 100644
--- a/samples/ComputeSharp.SwapChain/Backend/Win32Application.cs
+++ b/samples/ComputeSharp.SwapChain/Backend/Win32Application.cs
@@ -1,28 +1,27 @@
using System;
using TerraFX.Interop;
-namespace ComputeSharp.SwapChain.Backend
+namespace ComputeSharp.SwapChain.Backend;
+
+///
+/// A class representing a simple Win32 application.
+///
+internal abstract class Win32Application
{
///
- /// A class representing a simple Win32 application.
+ /// Initializes the current application.
///
- internal abstract class Win32Application
- {
- ///
- /// Initializes the current application.
- ///
- /// The handle for the window.
- public abstract void OnInitialize(HWND hwnd);
+ /// The handle for the window.
+ public abstract void OnInitialize(HWND hwnd);
- ///
- /// Resizes the current application.
- ///
- public abstract void OnResize();
+ ///
+ /// Resizes the current application.
+ ///
+ public abstract void OnResize();
- ///
- /// Updates the current application.
- ///
- /// The current time since the start of the application.
- public abstract void OnUpdate(TimeSpan time);
- }
+ ///
+ /// Updates the current application.
+ ///
+ /// The current time since the start of the application.
+ public abstract void OnUpdate(TimeSpan time);
}
diff --git a/samples/ComputeSharp.SwapChain/Backend/Win32ApplicationRunner.cs b/samples/ComputeSharp.SwapChain/Backend/Win32ApplicationRunner.cs
index 4cb84dac..3b002576 100644
--- a/samples/ComputeSharp.SwapChain/Backend/Win32ApplicationRunner.cs
+++ b/samples/ComputeSharp.SwapChain/Backend/Win32ApplicationRunner.cs
@@ -7,95 +7,291 @@ using System.Threading;
using TerraFX.Interop;
using FX = TerraFX.Interop.Windows;
-namespace ComputeSharp.SwapChain.Backend
+namespace ComputeSharp.SwapChain.Backend;
+
+///
+/// A helper class to manage the creation and execution of Win32 applications.
+///
+internal unsafe static class Win32ApplicationRunner
{
///
- /// A helper class to manage the creation and execution of Win32 applications.
+ /// Whether or not a resize operation is in progress.
///
- internal unsafe static class Win32ApplicationRunner
+ private static bool isResizing = false;
+
+ ///
+ /// Whether or not the application is currently paused.
+ ///
+ private static bool isPaused = false;
+
+ ///
+ /// The for the application window.
+ ///
+ private static HWND hwnd;
+
+ ///
+ /// The application being run.
+ ///
+ private static Win32Application application = null!;
+
+ ///
+ /// The thread running the render loop.
+ ///
+ private static Thread renderThread = null!;
+
+ ///
+ /// Runs a specified application and starts the main loop to update its state.
+ /// This is the entry point for a given application of type , and it should be
+ /// called as soon as the process is launched, excluding any other additional initialization needed.
+ /// To launch an application, simply add this line to the project being used:
+ /// Win32ApplicationRunner.Run<MyApplication>();
+ ///
+ /// The type of application being launched.
+ /// The exit code for the application.
+ public static int Run(Win32Application application)
{
- ///
- /// Whether or not a resize operation is in progress.
- ///
- private static bool isResizing = false;
+ Win32ApplicationRunner.application = application;
- ///
- /// Whether or not the application is currently paused.
- ///
- private static bool isPaused = false;
+ IntPtr hInstance = FX.GetModuleHandleW(null);
- ///
- /// The for the application window.
- ///
- private static HWND hwnd;
-
- ///
- /// The application being run.
- ///
- private static Win32Application application = null!;
-
- ///
- /// The thread running the render loop.
- ///
- private static Thread renderThread = null!;
-
- ///
- /// Runs a specified application and starts the main loop to update its state.
- /// This is the entry point for a given application of type , and it should be
- /// called as soon as the process is launched, excluding any other additional initialization needed.
- /// To launch an application, simply add this line to the project being used:
- /// Win32ApplicationRunner.Run<MyApplication>();
- ///
- /// The type of application being launched.
- /// The exit code for the application.
- public static int Run(Win32Application application)
+ fixed (char* name = Assembly.GetExecutingAssembly().FullName)
+ fixed (char* windowTitle = application.GetType().ToString())
{
- Win32ApplicationRunner.application = application;
-
- IntPtr hInstance = FX.GetModuleHandleW(null);
-
- fixed (char* name = Assembly.GetExecutingAssembly().FullName)
- fixed (char* windowTitle = application.GetType().ToString())
+ // Initialize the window class
+ WNDCLASSEXW windowClassEx = new()
{
- // Initialize the window class
- WNDCLASSEXW windowClassEx = new()
+ cbSize = (uint)sizeof(WNDCLASSEXW),
+ style = FX.CS_HREDRAW | FX.CS_VREDRAW,
+ lpfnWndProc = &WindowProc,
+ hInstance = hInstance,
+ hCursor = FX.LoadCursorW(IntPtr.Zero, FX.MAKEINTRESOURCE(32512)),
+ lpszClassName = (ushort*)name
+ };
+
+ // Register the window class
+ _ = FX.RegisterClassExW(&windowClassEx);
+
+ Rectangle windowRect = new(0, 0, 1280, 720);
+
+ // Set the target window size
+ _ = FX.AdjustWindowRect((RECT*)&windowRect, FX.WS_OVERLAPPEDWINDOW, FX.FALSE);
+
+ uint
+ height = (uint)(windowRect.Bottom - windowRect.Top),
+ width = (uint)(windowRect.Right - windowRect.Left);
+
+ // Create the window and store a handle to it
+ hwnd = FX.CreateWindowExW(
+ 0,
+ windowClassEx.lpszClassName,
+ (ushort*)windowTitle,
+ FX.WS_OVERLAPPEDWINDOW,
+ FX.CW_USEDEFAULT,
+ FX.CW_USEDEFAULT,
+ (int)width,
+ (int)height,
+ HWND.NULL,
+ HMENU.NULL,
+ hInstance,
+ (void*)GCHandle.ToIntPtr(GCHandle.Alloc(application))
+ );
+
+ MARGINS margins = default;
+ margins.cxLeftWidth = -1;
+ margins.cxRightWidth = -1;
+ margins.cyTopHeight = -1;
+ margins.cyBottomHeight = -1;
+
+ _ = FX.DwmExtendFrameIntoClientArea(hwnd, &margins);
+ }
+
+ // Initialize the application
+ application.OnInitialize(hwnd);
+
+ // Display the window
+ _ = FX.ShowWindow(hwnd, FX.SW_SHOWDEFAULT);
+
+ MSG msg = default;
+
+ // Setup the render thread that enables smooth resizing of the window
+ renderThread = new Thread(static args =>
+ {
+ (Win32Application application, CancellationToken token) = ((Win32Application, CancellationToken))args!;
+
+ Stopwatch
+ startStopwatch = Stopwatch.StartNew(),
+ frameStopwatch = Stopwatch.StartNew();
+
+ const long targetFrameTimeInTicksFor60fps = 166666;
+
+ while (!token.IsCancellationRequested)
+ {
+ if (frameStopwatch.ElapsedTicks >= targetFrameTimeInTicksFor60fps)
{
- cbSize = (uint)sizeof(WNDCLASSEXW),
- style = FX.CS_HREDRAW | FX.CS_VREDRAW,
- lpfnWndProc = &WindowProc,
- hInstance = hInstance,
- hCursor = FX.LoadCursorW(IntPtr.Zero, FX.MAKEINTRESOURCE(32512)),
- lpszClassName = (ushort*)name
- };
+ frameStopwatch.Restart();
- // Register the window class
- _ = FX.RegisterClassExW(&windowClassEx);
+ application.OnUpdate(startStopwatch.Elapsed);
+ }
+ }
+ });
- Rectangle windowRect = new(0, 0, 1280, 720);
+ CancellationTokenSource tokenSource = new();
- // Set the target window size
- _ = FX.AdjustWindowRect((RECT*)&windowRect, FX.WS_OVERLAPPEDWINDOW, FX.FALSE);
+ renderThread.Start((application, tokenSource.Token));
- uint
- height = (uint)(windowRect.Bottom - windowRect.Top),
- width = (uint)(windowRect.Right - windowRect.Left);
+ // Process any messages in the queue
+ while (msg.message != FX.WM_QUIT)
+ {
+ if (FX.PeekMessageW(&msg, HWND.NULL, 0, 0, FX.PM_REMOVE) != 0)
+ {
+ _ = FX.TranslateMessage(&msg);
+ _ = FX.DispatchMessageW(&msg);
+ }
+ else if (isPaused)
+ {
+ Thread.Sleep(100);
+ }
+ }
- // Create the window and store a handle to it
- hwnd = FX.CreateWindowExW(
- 0,
- windowClassEx.lpszClassName,
- (ushort*)windowTitle,
- FX.WS_OVERLAPPEDWINDOW,
- FX.CW_USEDEFAULT,
- FX.CW_USEDEFAULT,
- (int)width,
- (int)height,
- HWND.NULL,
- HMENU.NULL,
- hInstance,
- (void*)GCHandle.ToIntPtr(GCHandle.Alloc(application))
- );
+ tokenSource.Cancel();
+ renderThread.Join();
+
+ // Return this part of the WM_QUIT message to Windows
+ return (int)msg.wParam;
+ }
+
+ ///
+ /// Processes incoming messages for a window.
+ ///
+ /// A handle to the window.
+ /// The message.
+ /// Additional message information (the contents depend on the value of ).
+ /// Additional message information (the contents depend on the value of ).
+ /// The result of the message processing for the input message.
+ [UnmanagedCallersOnly]
+ private static nint WindowProc(IntPtr hwnd, uint uMsg, nuint wParam, nint lParam)
+ {
+ switch (uMsg)
+ {
+ // Change the paused state on window activation
+ case FX.WM_ACTIVATE:
+ {
+ if (FX.LOWORD(wParam) == FX.WA_INACTIVE)
+ {
+ isPaused = true;
+ }
+ else
+ {
+ isPaused = false;
+ }
+ return 0;
+ }
+
+ // Change the paused state when ESC is pressed
+ case FX.WM_KEYDOWN:
+ {
+ if ((ConsoleKey)wParam == ConsoleKey.Escape)
+ {
+
+ if (isPaused)
+ {
+ FX.SetCapture(hwnd);
+ }
+ else
+ {
+ FX.ReleaseCapture();
+ }
+
+ isPaused = !isPaused;
+ }
+
+ return 0;
+ }
+
+ // Window resize started
+ case FX.WM_ENTERSIZEMOVE:
+ {
+ isResizing = true;
+
+ return 0;
+ }
+
+ // Window resize completed
+ case FX.WM_EXITSIZEMOVE:
+ {
+ isResizing = false;
+ application.OnResize();
+
+ return 0;
+ }
+
+ // Size update
+ case FX.WM_SIZE:
+ {
+ if (!isResizing && wParam != FX.SIZE_MINIMIZED)
+ {
+ application.OnResize();
+ }
+
+ return 0;
+ }
+
+ // Size and position of the window (needed to enable the borderless mode)
+ case FX.WM_NCCALCSIZE:
+ {
+ return 0;
+ }
+
+ // Enable dragging the window
+ case FX.WM_NCHITTEST:
+ {
+ POINT point;
+ RECT rect;
+
+ _ = FX.GetCursorPos(&point);
+ _ = FX.GetWindowRect(hwnd, &rect);
+
+ bool
+ isAtTop = Math.Abs(point.y - rect.top) < 12,
+ isAtRight = Math.Abs(point.x - rect.right) < 12,
+ isAtBottom = Math.Abs(point.y - rect.bottom) < 12,
+ isAtLeft = Math.Abs(point.x - rect.left) < 12;
+
+ if (isAtTop)
+ {
+ if (isAtRight) return FX.HTTOPRIGHT;
+ if (isAtLeft) return FX.HTTOPLEFT;
+ return FX.HTTOP;
+ }
+
+ if (isAtRight)
+ {
+ if (isAtTop) return FX.HTTOPRIGHT;
+ if (isAtBottom) return FX.HTBOTTOMRIGHT;
+ return FX.HTRIGHT;
+ }
+
+ if (isAtBottom)
+ {
+ if (isAtRight) return FX.HTBOTTOMRIGHT;
+ if (isAtLeft) return FX.HTBOTTOMLEFT;
+ return FX.HTBOTTOM;
+ }
+
+ if (isAtLeft)
+ {
+ if (isAtTop) return FX.HTTOPLEFT;
+ if (isAtBottom) return FX.HTBOTTOMLEFT;
+ return FX.HTLEFT;
+ }
+
+ return FX.HTCAPTION;
+ }
+
+ // Restore the drop shadow
+ case FX.WM_DWMCOMPOSITIONCHANGED:
+ {
MARGINS margins = default;
margins.cxLeftWidth = -1;
margins.cxRightWidth = -1;
@@ -103,215 +299,18 @@ namespace ComputeSharp.SwapChain.Backend
margins.cyBottomHeight = -1;
_ = FX.DwmExtendFrameIntoClientArea(hwnd, &margins);
+
+ return 0;
}
- // Initialize the application
- application.OnInitialize(hwnd);
-
- // Display the window
- _ = FX.ShowWindow(hwnd, FX.SW_SHOWDEFAULT);
-
- MSG msg = default;
-
- // Setup the render thread that enables smooth resizing of the window
- renderThread = new Thread(static args =>
+ // Shutdown
+ case FX.WM_DESTROY:
{
- (Win32Application application, CancellationToken token) = ((Win32Application, CancellationToken))args!;
-
- Stopwatch
- startStopwatch = Stopwatch.StartNew(),
- frameStopwatch = Stopwatch.StartNew();
-
- const long targetFrameTimeInTicksFor60fps = 166666;
-
- while (!token.IsCancellationRequested)
- {
- if (frameStopwatch.ElapsedTicks >= targetFrameTimeInTicksFor60fps)
- {
- frameStopwatch.Restart();
-
- application.OnUpdate(startStopwatch.Elapsed);
- }
- }
- });
-
- CancellationTokenSource tokenSource = new();
-
- renderThread.Start((application, tokenSource.Token));
-
- // Process any messages in the queue
- while (msg.message != FX.WM_QUIT)
- {
- if (FX.PeekMessageW(&msg, HWND.NULL, 0, 0, FX.PM_REMOVE) != 0)
- {
- _ = FX.TranslateMessage(&msg);
- _ = FX.DispatchMessageW(&msg);
- }
- else if (isPaused)
- {
- Thread.Sleep(100);
- }
+ FX.PostQuitMessage(0);
+ return 0;
}
-
- tokenSource.Cancel();
-
- renderThread.Join();
-
- // Return this part of the WM_QUIT message to Windows
- return (int)msg.wParam;
}
- ///
- /// Processes incoming messages for a window.
- ///
- /// A handle to the window.
- /// The message.
- /// Additional message information (the contents depend on the value of ).
- /// Additional message information (the contents depend on the value of ).
- /// The result of the message processing for the input message.
- [UnmanagedCallersOnly]
- private static nint WindowProc(IntPtr hwnd, uint uMsg, nuint wParam, nint lParam)
- {
- switch (uMsg)
- {
- // Change the paused state on window activation
- case FX.WM_ACTIVATE:
- {
- if (FX.LOWORD(wParam) == FX.WA_INACTIVE)
- {
- isPaused = true;
- }
- else
- {
- isPaused = false;
- }
- return 0;
- }
-
- // Change the paused state when ESC is pressed
- case FX.WM_KEYDOWN:
- {
- if ((ConsoleKey)wParam == ConsoleKey.Escape)
- {
-
- if (isPaused)
- {
- FX.SetCapture(hwnd);
- }
- else
- {
- FX.ReleaseCapture();
- }
-
- isPaused = !isPaused;
- }
-
- return 0;
- }
-
- // Window resize started
- case FX.WM_ENTERSIZEMOVE:
- {
- isResizing = true;
-
- return 0;
- }
-
- // Window resize completed
- case FX.WM_EXITSIZEMOVE:
- {
- isResizing = false;
- application.OnResize();
-
- return 0;
- }
-
- // Size update
- case FX.WM_SIZE:
- {
- if (!isResizing && wParam != FX.SIZE_MINIMIZED)
- {
- application.OnResize();
- }
-
- return 0;
- }
-
- // Size and position of the window (needed to enable the borderless mode)
- case FX.WM_NCCALCSIZE:
- {
- return 0;
- }
-
- // Enable dragging the window
- case FX.WM_NCHITTEST:
- {
- POINT point;
- RECT rect;
-
- _ = FX.GetCursorPos(&point);
- _ = FX.GetWindowRect(hwnd, &rect);
-
- bool
- isAtTop = Math.Abs(point.y - rect.top) < 12,
- isAtRight = Math.Abs(point.x - rect.right) < 12,
- isAtBottom = Math.Abs(point.y - rect.bottom) < 12,
- isAtLeft = Math.Abs(point.x - rect.left) < 12;
-
- if (isAtTop)
- {
- if (isAtRight) return FX.HTTOPRIGHT;
- if (isAtLeft) return FX.HTTOPLEFT;
- return FX.HTTOP;
- }
-
- if (isAtRight)
- {
- if (isAtTop) return FX.HTTOPRIGHT;
- if (isAtBottom) return FX.HTBOTTOMRIGHT;
- return FX.HTRIGHT;
- }
-
- if (isAtBottom)
- {
- if (isAtRight) return FX.HTBOTTOMRIGHT;
- if (isAtLeft) return FX.HTBOTTOMLEFT;
- return FX.HTBOTTOM;
- }
-
- if (isAtLeft)
- {
- if (isAtTop) return FX.HTTOPLEFT;
- if (isAtBottom) return FX.HTBOTTOMLEFT;
- return FX.HTLEFT;
- }
-
- return FX.HTCAPTION;
- }
-
- // Restore the drop shadow
- case FX.WM_DWMCOMPOSITIONCHANGED:
- {
- MARGINS margins = default;
- margins.cxLeftWidth = -1;
- margins.cxRightWidth = -1;
- margins.cyTopHeight = -1;
- margins.cyBottomHeight = -1;
-
- _ = FX.DwmExtendFrameIntoClientArea(hwnd, &margins);
-
- return 0;
- }
-
- // Shutdown
- case FX.WM_DESTROY:
- {
- FX.PostQuitMessage(0);
- return 0;
- }
- }
-
- return FX.DefWindowProcW(hwnd, uMsg, wParam, lParam);
- }
+ return FX.DefWindowProcW(hwnd, uMsg, wParam, lParam);
}
-}
\ No newline at end of file
+}
diff --git a/samples/ComputeSharp.SwapChain/Program.cs b/samples/ComputeSharp.SwapChain/Program.cs
index 3019f673..a680b0f5 100644
--- a/samples/ComputeSharp.SwapChain/Program.cs
+++ b/samples/ComputeSharp.SwapChain/Program.cs
@@ -6,70 +6,69 @@ using System.Runtime.CompilerServices;
using ComputeSharp.SwapChain.Backend;
using ComputeSharp.SwapChain.Shaders;
-namespace ComputeSharp.SwapChain
+namespace ComputeSharp.SwapChain;
+
+class Program
{
- class Program
+ ///
+ /// A texture for \Textures\RustyMetal.png.
+ ///
+ private static readonly IReadOnlyTexture2D RustyMetal = LoadTexture();
+
+ ///
+ /// The mapping of available samples to choose from.
+ ///
+ private static readonly Win32Application[] Samples = new Win32Application[]
{
- ///
- /// A texture for \Textures\RustyMetal.png.
- ///
- private static readonly IReadOnlyTexture2D RustyMetal = LoadTexture();
+ new SwapChainApplication(static time => new((float)time.TotalSeconds)),
+ new SwapChainApplication(static time => new((float)time.TotalSeconds)),
+ new SwapChainApplication(static time => new((float)time.TotalSeconds)),
+ new SwapChainApplication(static time => new((float)time.TotalSeconds)),
+ new SwapChainApplication(static time => new((float)time.TotalSeconds)),
+ new SwapChainApplication(static time => new((float)time.TotalSeconds)),
+ new SwapChainApplication(static time => new((float)time.TotalSeconds)),
+ new SwapChainApplication(static time => new((float)time.TotalSeconds)),
+ new SwapChainApplication(static time => new((float)time.TotalSeconds)),
+ new SwapChainApplication(static time => new((float)time.TotalSeconds)),
+ new SwapChainApplication(static time => new((float)time.TotalSeconds, RustyMetal))
+ };
- ///
- /// The mapping of available samples to choose from.
- ///
- private static readonly Win32Application[] Samples = new Win32Application[]
+ static void Main()
+ {
+ Console.WriteLine("Available samples:");
+ Console.WriteLine();
+
+ for (int i = 0; i < Samples.Length; i++)
{
- new SwapChainApplication(static time => new((float)time.TotalSeconds)),
- new SwapChainApplication