using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using CommunityToolkit.Diagnostics;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing.Processors;
using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
namespace ComputeSharp.BokehBlur.Processors;
///
public sealed partial class HlslGaussianBlurProcessor
{
///
/// Applies Gaussian blur processing to an image.
///
internal sealed partial class Implementation : ImageProcessor
{
///
/// The instance in use.
///
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)
{
int kernelSize = (definition.Radius * 2) + 1;
this.graphicsDevice = definition.graphicsDevice;
this.kernel = CreateGaussianBlurKernel(kernelSize, definition.Sigma);
}
///
/// 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++)
{
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;
}
///
/// 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 = (float)(Math.Sqrt(2 * Math.PI) * sigma);
float exponentNumerator = -x * x;
float exponentDenominator = 2 * sigma * sigma;
float left = Numerator / denominator;
float right = (float)Math.Exp(exponentNumerator / exponentDenominator);
return left * right;
}
///
protected override void OnFrameApply(ImageFrame source)
{
if (!source.DangerousTryGetSinglePixelMemory(out Memory pixelMemory))
{
ThrowHelper.ThrowInvalidOperationException("Cannot process image frames wrapping discontiguous memory.");
}
Span span = MemoryMarshal.Cast(pixelMemory.Span);
using ReadWriteTexture2D sourceTexture = this.graphicsDevice.AllocateReadWriteTexture2D(span, source.Width, source.Height);
using ReadWriteTexture2D firstPassTexture = this.graphicsDevice.AllocateReadWriteTexture2D(source.Width, source.Height);
using ReadOnlyBuffer kernelBuffer = this.graphicsDevice.AllocateReadOnlyBuffer(this.kernel);
using (ComputeContext context = this.graphicsDevice.CreateComputeContext())
{
context.For(source.Width, source.Height, new(sourceTexture, firstPassTexture, kernelBuffer));
context.Barrier(firstPassTexture);
context.For(source.Width, source.Height, new(firstPassTexture, sourceTexture, kernelBuffer));
}
sourceTexture.CopyTo(span);
}
///
/// Kernel for the vertical convolution pass.
///
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct VerticalConvolutionProcessor : IComputeShader
{
private readonly IReadWriteNormalizedTexture2D source;
private readonly IReadWriteNormalizedTexture2D target;
private readonly ReadOnlyBuffer kernel;
///
public void Execute()
{
float4 result = float4.Zero;
int maxY = this.source.Height - 1;
int maxX = this.source.Width - 1;
int kernelLength = this.kernel.Length;
int radiusY = kernelLength >> 1;
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);
float4 color = this.source[offsetX, offsetY];
result += this.kernel[i] * color;
}
this.target[ThreadIds.XY] = result;
}
}
///
/// Kernel for the horizontal convolution pass.
///
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader
{
private readonly IReadWriteNormalizedTexture2D source;
private readonly IReadWriteNormalizedTexture2D target;
private readonly ReadOnlyBuffer kernel;
///
public void Execute()
{
float4 result = float4.Zero;
int maxY = this.source.Height - 1;
int maxX = this.source.Width - 1;
int kernelLength = this.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);
float4 color = this.source[offsetX, offsetY];
result += this.kernel[i] * color;
}
this.target[ThreadIds.XY] = result;
}
}
}
}