From 6a7f56b1a76a85e9b3c6a5cb0cb8ee146bf2e0f3 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 30 Dec 2020 23:15:21 +0100 Subject: [PATCH 01/26] Added .ShareX sample, ported ShareX code --- ComputeSharp.sln | 13 +- .../ComputeSharp.ShareX.csproj | 14 ++ samples/ComputeSharp.ShareX/Cpu/ColorBgra.cs | 120 +++++++++++ .../Cpu/ConvolutionMatrix.cs | 66 ++++++ .../Cpu/ConvolutionMatrixManager.cs | 148 ++++++++++++++ .../ComputeSharp.ShareX/Cpu/MathHelpers.cs | 41 ++++ .../Cpu/NumberExtensions.cs | 39 ++++ .../ComputeSharp.ShareX/Cpu/UnsafeBitmap.cs | 192 ++++++++++++++++++ samples/ComputeSharp.ShareX/Program.cs | 12 ++ 9 files changed, 644 insertions(+), 1 deletion(-) create mode 100644 samples/ComputeSharp.ShareX/ComputeSharp.ShareX.csproj create mode 100644 samples/ComputeSharp.ShareX/Cpu/ColorBgra.cs create mode 100644 samples/ComputeSharp.ShareX/Cpu/ConvolutionMatrix.cs create mode 100644 samples/ComputeSharp.ShareX/Cpu/ConvolutionMatrixManager.cs create mode 100644 samples/ComputeSharp.ShareX/Cpu/MathHelpers.cs create mode 100644 samples/ComputeSharp.ShareX/Cpu/NumberExtensions.cs create mode 100644 samples/ComputeSharp.ShareX/Cpu/UnsafeBitmap.cs create mode 100644 samples/ComputeSharp.ShareX/Program.cs diff --git a/ComputeSharp.sln b/ComputeSharp.sln index 066d9426..2c84c1f5 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -45,7 +45,9 @@ Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "ComputeSharp.Sample.Shared" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Tests.Internals.SourceGenerators", "tests\ComputeSharp.Tests.Internals.SourceGenerators\ComputeSharp.Tests.Internals.SourceGenerators.csproj", "{BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.Tests.NativeLibrariesResolver", "tests\ComputeSharp.Tests.NativeLibrariesResolver\ComputeSharp.Tests.NativeLibrariesResolver.csproj", "{BF52326F-E415-49E6-8595-62762216762B}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Tests.NativeLibrariesResolver", "tests\ComputeSharp.Tests.NativeLibrariesResolver\ComputeSharp.Tests.NativeLibrariesResolver.csproj", "{BF52326F-E415-49E6-8595-62762216762B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.ShareX", "samples\ComputeSharp.ShareX\ComputeSharp.ShareX.csproj", "{E200B2A8-6BC4-4F50-9D4F-7BAF06F1813A}" EndProject Global GlobalSection(SharedMSBuildProjectFiles) = preSolution @@ -172,6 +174,14 @@ Global {BF52326F-E415-49E6-8595-62762216762B}.Release|Any CPU.Build.0 = Release|Any CPU {BF52326F-E415-49E6-8595-62762216762B}.Release|x64.ActiveCfg = Release|Any CPU {BF52326F-E415-49E6-8595-62762216762B}.Release|x64.Build.0 = Release|Any CPU + {E200B2A8-6BC4-4F50-9D4F-7BAF06F1813A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E200B2A8-6BC4-4F50-9D4F-7BAF06F1813A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E200B2A8-6BC4-4F50-9D4F-7BAF06F1813A}.Debug|x64.ActiveCfg = Debug|Any CPU + {E200B2A8-6BC4-4F50-9D4F-7BAF06F1813A}.Debug|x64.Build.0 = Debug|Any CPU + {E200B2A8-6BC4-4F50-9D4F-7BAF06F1813A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E200B2A8-6BC4-4F50-9D4F-7BAF06F1813A}.Release|Any CPU.Build.0 = Release|Any CPU + {E200B2A8-6BC4-4F50-9D4F-7BAF06F1813A}.Release|x64.ActiveCfg = Release|Any CPU + {E200B2A8-6BC4-4F50-9D4F-7BAF06F1813A}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -187,6 +197,7 @@ Global {8CEFC324-CA6C-4845-9AD9-70B92BD87057} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} {BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} {BF52326F-E415-49E6-8595-62762216762B} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} + {E200B2A8-6BC4-4F50-9D4F-7BAF06F1813A} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC} diff --git a/samples/ComputeSharp.ShareX/ComputeSharp.ShareX.csproj b/samples/ComputeSharp.ShareX/ComputeSharp.ShareX.csproj new file mode 100644 index 00000000..55f80df8 --- /dev/null +++ b/samples/ComputeSharp.ShareX/ComputeSharp.ShareX.csproj @@ -0,0 +1,14 @@ + + + + Exe + net5.0 + true + enable + + + + + + + diff --git a/samples/ComputeSharp.ShareX/Cpu/ColorBgra.cs b/samples/ComputeSharp.ShareX/Cpu/ColorBgra.cs new file mode 100644 index 00000000..70dff53d --- /dev/null +++ b/samples/ComputeSharp.ShareX/Cpu/ColorBgra.cs @@ -0,0 +1,120 @@ +#region License Information (GPL v3) + +/* + ShareX - A program that allows you to take screenshots and share any file type + Copyright (c) 2007-2020 ShareX Team + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + + Optionally you can also view the license at . +*/ + +#endregion License Information (GPL v3) + +// Source: https://github.com/ShareX/ShareX/blob/master/ShareX.HelpersLib/ColorBgra.cs + +using System.Drawing; +using System.Runtime.InteropServices; + +namespace ShareX.HelpersLib +{ + [StructLayout(LayoutKind.Explicit)] + public struct ColorBgra + { + [FieldOffset(0)] + public uint Bgra; + + [FieldOffset(0)] + public byte Blue; + [FieldOffset(1)] + public byte Green; + [FieldOffset(2)] + public byte Red; + [FieldOffset(3)] + public byte Alpha; + + public const byte SizeOf = 4; + + public ColorBgra(uint bgra) : this() + { + Bgra = bgra; + } + + public ColorBgra(byte b, byte g, byte r, byte a = 255) : this() + { + Blue = b; + Green = g; + Red = r; + Alpha = a; + } + + public ColorBgra(Color color) : this(color.B, color.G, color.R, color.A) + { + } + + public static bool operator ==(ColorBgra c1, ColorBgra c2) + { + return c1.Bgra == c2.Bgra; + } + + public static bool operator !=(ColorBgra c1, ColorBgra c2) + { + return c1.Bgra != c2.Bgra; + } + + public override bool Equals(object? obj) + { + return obj is ColorBgra && ((ColorBgra)obj).Bgra == Bgra; + } + + public override int GetHashCode() + { + unchecked + { + return (int)Bgra; + } + } + + public static implicit operator ColorBgra(uint color) + { + return new ColorBgra(color); + } + + public static implicit operator uint(ColorBgra color) + { + return color.Bgra; + } + + public Color ToColor() + { + return Color.FromArgb(Alpha, Red, Green, Blue); + } + + public override string ToString() + { + return string.Format("B: {0}, G: {1}, R: {2}, A: {3}", Blue, Green, Red, Alpha); + } + + public static uint BgraToUInt32(uint b, uint g, uint r, uint a) + { + return b + (g << 8) + (r << 16) + (a << 24); + } + + public static uint BgraToUInt32(byte b, byte g, byte r, byte a) + { + return b + ((uint)g << 8) + ((uint)r << 16) + ((uint)a << 24); + } + } +} \ No newline at end of file diff --git a/samples/ComputeSharp.ShareX/Cpu/ConvolutionMatrix.cs b/samples/ComputeSharp.ShareX/Cpu/ConvolutionMatrix.cs new file mode 100644 index 00000000..d6cbc103 --- /dev/null +++ b/samples/ComputeSharp.ShareX/Cpu/ConvolutionMatrix.cs @@ -0,0 +1,66 @@ +#region License Information (GPL v3) + +/* + ShareX - A program that allows you to take screenshots and share any file type + Copyright (c) 2007-2020 ShareX Team + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + + Optionally you can also view the license at . +*/ + +#endregion License Information (GPL v3) + +// Source: https://github.com/ShareX/ShareX/blob/master/ShareX.HelpersLib/ConvolutionMatrix.cs + +namespace ShareX.HelpersLib +{ + public class ConvolutionMatrix + { + private readonly double[,] matrix; + + public int Width => matrix.GetLength(1); + public int Height => matrix.GetLength(0); + public byte Offset { get; set; } + + public bool ConsiderAlpha { get; set; } + + public ConvolutionMatrix() : this(3) + { + } + + public ConvolutionMatrix(int size) : this(size, size) + { + } + + public ConvolutionMatrix(int height, int width) + { + matrix = new double[height, width]; + } + + public void SetAll(double value) + { + for (int y = 0; y < Height; y++) + { + for (int x = 0; x < Width; x++) + { + matrix[y, x] = value; + } + } + } + + public ref double this[int y, int x] => ref matrix[y, x]; + } +} \ No newline at end of file diff --git a/samples/ComputeSharp.ShareX/Cpu/ConvolutionMatrixManager.cs b/samples/ComputeSharp.ShareX/Cpu/ConvolutionMatrixManager.cs new file mode 100644 index 00000000..d74fa361 --- /dev/null +++ b/samples/ComputeSharp.ShareX/Cpu/ConvolutionMatrixManager.cs @@ -0,0 +1,148 @@ +#region License Information (GPL v3) + +/* + ShareX - A program that allows you to take screenshots and share any file type + Copyright (c) 2007-2020 ShareX Team + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + + Optionally you can also view the license at . +*/ + +#endregion License Information (GPL v3) + +// Source: https://github.com/ShareX/ShareX/blob/master/ShareX.HelpersLib/ConvolutionMatrixManager.cs +// Adapted from: https://stackoverflow.com/questions/33569396/correctly-implement-a-2-pass-gaussian-blur +// Filters: http://www.codeproject.com/Articles/2008/Image-Processing-for-Dummies-with-C-and-GDI-Part-2 + +using System; +using System.Drawing; +using System.Drawing.Imaging; +using System.Threading.Tasks; + +namespace ShareX.HelpersLib +{ + public static class ConvolutionMatrixManager + { + public static Bitmap Apply(this ConvolutionMatrix kernel, Bitmap bmp) + { + Bitmap bmpResult = (Bitmap)bmp.Clone(); + + using (UnsafeBitmap source = new UnsafeBitmap(bmp, true, ImageLockMode.ReadOnly)) + using (UnsafeBitmap dest = new UnsafeBitmap(bmpResult, true, ImageLockMode.WriteOnly)) + { + int originX = (kernel.Width - 1) / 2; + int originY = (kernel.Height - 1) / 2; + + Parallel.For(0, source.Height, y => + { + Parallel.For(0, source.Width, x => + { + double r = 0.0; + double g = 0.0; + double b = 0.0; + double a = 0.0; + + // Apply each matrix multiplier to the color components for each pixel. + for (int fy = 0; fy < kernel.Height; fy++) + { + int fyr = fy - originY; + int offsetY = y + fyr; + + offsetY = offsetY.Clamp(0, source.Height - 1); + + for (int fx = 0; fx < kernel.Width; fx++) + { + int fxr = fx - originX; + int offsetX = x + fxr; + + offsetX = offsetX.Clamp(0, source.Width - 1); + + ColorBgra currentColor = source.GetPixel(offsetX, offsetY); + + r += kernel[fy, fx] * currentColor.Red; + g += kernel[fy, fx] * currentColor.Green; + b += kernel[fy, fx] * currentColor.Blue; + if (kernel.ConsiderAlpha) + { + a += kernel[fy, fx] * currentColor.Alpha; + } + } + } + + r += kernel.Offset; + r = r.Clamp(0, 255); + + g += kernel.Offset; + g = g.Clamp(0, 255); + + b += kernel.Offset; + b = b.Clamp(0, 255); + + if (kernel.ConsiderAlpha) + { + a += kernel.Offset; + a = a.Clamp(0, 255); + } + + dest.SetPixel(x, y, new ColorBgra((byte)b, (byte)g, (byte)r, kernel.ConsiderAlpha ? (byte)a : source.GetPixel(x, y).Alpha)); + }); + }); + } + + return bmpResult; + } + + private static double GaussianFunction(double x, double sigma) + { + double left = 1.0 / (Math.Sqrt(2 * Math.PI) * sigma); + + double exponentNumerator = -x * x; + double exponentDenominator = 2 * Math.Pow(sigma, 2); + double right = Math.Exp(exponentNumerator / exponentDenominator); + + return left * right; + } + + public static ConvolutionMatrix GaussianBlur(int height, int width, double sigma) + { + ConvolutionMatrix cm = new ConvolutionMatrix(height, width); + cm.ConsiderAlpha = true; + + double sum = 0.0; + double midpointX = (width - 1) / 2.0; + double midpointY = (height - 1) / 2.0; + + for (int y = 0; y < height; y++) + { + for (int x = 0; x < width; x++) + { + sum += cm[y, x] = GaussianFunction(x - midpointX, sigma) * GaussianFunction(y - midpointY, sigma); + } + } + + // Normalise kernel so that the sum of all weights equals 1 + for (int y = 0; y < height; y++) + { + for (int x = 0; x < width; x++) + { + cm[y, x] /= sum; + } + } + + return cm; + } + } +} \ No newline at end of file diff --git a/samples/ComputeSharp.ShareX/Cpu/MathHelpers.cs b/samples/ComputeSharp.ShareX/Cpu/MathHelpers.cs new file mode 100644 index 00000000..c7c3f753 --- /dev/null +++ b/samples/ComputeSharp.ShareX/Cpu/MathHelpers.cs @@ -0,0 +1,41 @@ +#region License Information (GPL v3) + +/* + ShareX - A program that allows you to take screenshots and share any file type + Copyright (c) 2007-2020 ShareX Team + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + + Optionally you can also view the license at . +*/ + +#endregion License Information (GPL v3) + +// Source: https://github.com/ShareX/ShareX/blob/master/ShareX.HelpersLib/Helpers/MathHelpers.cs + +using System; + +namespace ShareX.HelpersLib +{ + public static class MathHelpers + { + public static T Clamp(T num, T min, T max) where T : IComparable + { + if (num.CompareTo(min) <= 0) return min; + if (num.CompareTo(max) >= 0) return max; + return num; + } + } +} \ No newline at end of file diff --git a/samples/ComputeSharp.ShareX/Cpu/NumberExtensions.cs b/samples/ComputeSharp.ShareX/Cpu/NumberExtensions.cs new file mode 100644 index 00000000..11a0cd20 --- /dev/null +++ b/samples/ComputeSharp.ShareX/Cpu/NumberExtensions.cs @@ -0,0 +1,39 @@ +#region License Information (GPL v3) + +/* + ShareX - A program that allows you to take screenshots and share any file type + Copyright (c) 2007-2020 ShareX Team + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + + Optionally you can also view the license at . +*/ + +#endregion License Information (GPL v3) + +// Source: https://github.com/ShareX/ShareX/blob/master/ShareX.HelpersLib/Extensions/NumberExtensions.cs + +using System; + +namespace ShareX.HelpersLib +{ + public static class NumberExtensions + { + public static T Clamp(this T num, T min, T max) where T : IComparable + { + return MathHelpers.Clamp(num, min, max); + } + } +} \ No newline at end of file diff --git a/samples/ComputeSharp.ShareX/Cpu/UnsafeBitmap.cs b/samples/ComputeSharp.ShareX/Cpu/UnsafeBitmap.cs new file mode 100644 index 00000000..64965d39 --- /dev/null +++ b/samples/ComputeSharp.ShareX/Cpu/UnsafeBitmap.cs @@ -0,0 +1,192 @@ +#region License Information (GPL v3) + +/* + ShareX - A program that allows you to take screenshots and share any file type + Copyright (c) 2007-2020 ShareX Team + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + + Optionally you can also view the license at . +*/ + +#endregion License Information (GPL v3) + +// Source: https://github.com/ShareX/ShareX/blob/master/ShareX.HelpersLib/UnsafeBitmap.cs + +using System; +using System.Drawing; +using System.Drawing.Imaging; + +namespace ShareX.HelpersLib +{ + public unsafe class UnsafeBitmap : IDisposable + { + public ColorBgra* Pointer { get; private set; } + public bool IsLocked { get; private set; } + public int Width { get; private set; } + public int Height { get; private set; } + + public int PixelCount => Width * Height; + + private Bitmap bitmap; + private BitmapData? bitmapData; + + public UnsafeBitmap(Bitmap bitmap, bool lockBitmap = false, ImageLockMode imageLockMode = ImageLockMode.ReadWrite) + { + this.bitmap = bitmap; + Width = bitmap.Width; + Height = bitmap.Height; + + if (lockBitmap) + { + Lock(imageLockMode); + } + } + + public void Lock(ImageLockMode imageLockMode = ImageLockMode.ReadWrite) + { + if (!IsLocked) + { + IsLocked = true; + bitmapData = bitmap.LockBits(new Rectangle(0, 0, Width, Height), imageLockMode, PixelFormat.Format32bppArgb); + Pointer = (ColorBgra*)bitmapData.Scan0.ToPointer(); + } + } + + public void Unlock() + { + if (IsLocked) + { + bitmap.UnlockBits(bitmapData!); + bitmapData = null; + Pointer = null; + IsLocked = false; + } + } + + public static bool operator ==(UnsafeBitmap bmp1, UnsafeBitmap bmp2) + { + return ReferenceEquals(bmp1, bmp2) || bmp1.Equals(bmp2); + } + + public static bool operator !=(UnsafeBitmap bmp1, UnsafeBitmap bmp2) + { + return !(bmp1 == bmp2); + } + + public override bool Equals(object? obj) + { + return obj is UnsafeBitmap && Compare((UnsafeBitmap)obj, this); + } + + public override int GetHashCode() + { + return PixelCount; + } + + public static bool Compare(UnsafeBitmap bmp1, UnsafeBitmap bmp2) + { + int pixelCount = bmp1.PixelCount; + + if (pixelCount != bmp2.PixelCount) + { + return false; + } + + bmp1.Lock(ImageLockMode.ReadOnly); + bmp2.Lock(ImageLockMode.ReadOnly); + + ColorBgra* pointer1 = bmp1.Pointer; + ColorBgra* pointer2 = bmp2.Pointer; + + for (int i = 0; i < pixelCount; i++) + { + if (pointer1->Bgra != pointer2->Bgra) + { + return false; + } + + pointer1++; + pointer2++; + } + + return true; + } + + public bool IsTransparent() + { + int pixelCount = PixelCount; + + ColorBgra* pointer = Pointer; + + for (int i = 0; i < pixelCount; i++) + { + if (pointer->Alpha < 255) + { + return true; + } + + pointer++; + } + + return false; + } + + public ColorBgra GetPixel(int i) + { + return Pointer[i]; + } + + public ColorBgra GetPixel(int x, int y) + { + return Pointer[x + (y * Width)]; + } + + public void SetPixel(int i, ColorBgra color) + { + Pointer[i] = color; + } + + public void SetPixel(int i, uint color) + { + Pointer[i] = color; + } + + public void SetPixel(int x, int y, ColorBgra color) + { + Pointer[x + (y * Width)] = color; + } + + public void SetPixel(int x, int y, uint color) + { + Pointer[x + (y * Width)] = color; + } + + public void ClearPixel(int i) + { + Pointer[i] = 0; + } + + public void ClearPixel(int x, int y) + { + Pointer[x + (y * Width)] = 0; + } + + public void Dispose() + { + Unlock(); + } + } +} \ No newline at end of file diff --git a/samples/ComputeSharp.ShareX/Program.cs b/samples/ComputeSharp.ShareX/Program.cs new file mode 100644 index 00000000..5eca73eb --- /dev/null +++ b/samples/ComputeSharp.ShareX/Program.cs @@ -0,0 +1,12 @@ +using System; + +namespace ComputeSharp.ShareX +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("Hello World!"); + } + } +} From 1861fe321808d84b6ef55d433c1137d6a67b134c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 31 Dec 2020 01:31:25 +0100 Subject: [PATCH 02/26] Added GPU accelerated blur implementation --- .../Gpu/HlslConvolutionManager.cs.cs | 257 ++++++++++++++++++ 1 file changed, 257 insertions(+) create mode 100644 samples/ComputeSharp.ShareX/Gpu/HlslConvolutionManager.cs.cs diff --git a/samples/ComputeSharp.ShareX/Gpu/HlslConvolutionManager.cs.cs b/samples/ComputeSharp.ShareX/Gpu/HlslConvolutionManager.cs.cs new file mode 100644 index 00000000..c3cf8bfa --- /dev/null +++ b/samples/ComputeSharp.ShareX/Gpu/HlslConvolutionManager.cs.cs @@ -0,0 +1,257 @@ +using System; +using System.Drawing; +using System.Drawing.Imaging; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.PixelFormats; +using Rectangle = System.Drawing.Rectangle; + +namespace ComputeSharp.ShareX +{ + /// + /// Applies Gaussian blur processing to an image. + /// + internal sealed partial class HlslConvolutionManager + { + /// + /// The 1D gaussian blur kernel to use. + /// + private readonly float[] kernel; + + /// + /// Creates a new instance for the specific kernel. + /// + /// The convolution kernel to use. + private HlslConvolutionManager(float[] kernel) + { + this.kernel = kernel; + } + + /// + /// Creates a new instance with the specified parameters. + /// + /// The size of the convolution kernel. + /// The sigma parameter for the gaussian blur. + /// An instance to use to blur images. + public static HlslConvolutionManager Create(int size, float sigma) + { + return new(CreateGaussianBlurKernel(size, sigma)); + } + + /// + /// Creates a 1 dimensional Gaussian kernel using the Gaussian G(x) function. + /// + private static float[] CreateGaussianBlurKernel(int size, float weight) + { + 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; + } + + 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; + } + + for (int i = 0; i < size; i++) + { + Unsafe.Add(ref rKernel, i) /= sum; + } + + return kernel; + } + + /// + /// Applies the current convolution to a give bitmap. + /// + /// The input instance to process. + /// A blurred copy of . + public unsafe Bitmap Apply(Bitmap source) + { + Rectangle bounds = new(0, 0, source.Width, source.Height); + Bitmap result = new(source.Width, source.Height); + BitmapData + sourceData = source.LockBits(bounds, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb), + resultData = result.LockBits(bounds, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); + Span + sourceSpan = new((Rgba32*)sourceData.Scan0.ToPointer(), bounds.Width * bounds.Height), + resultSpan = new((Rgba32*)resultData.Scan0.ToPointer(), sourceSpan.Length); + Span vector4Span = new((void*)Marshal.AllocHGlobal(sizeof(Vector4) * sourceSpan.Length), sourceSpan.Length); + + try + { + PixelOperations.Instance.ToVector4(Configuration.Default, sourceSpan, vector4Span); + + using ReadWriteBuffer leftBuffer = Gpu.Default.AllocateReadWriteBuffer(vector4Span); + using ReadWriteBuffer rightBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceSpan.Length); + using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(this.kernel); + + ApplyVerticalConvolution(leftBuffer, rightBuffer, kernelBuffer, source.Height, source.Width); + ApplyHorizontalConvolution(rightBuffer, leftBuffer, kernelBuffer, source.Height, source.Width); + + leftBuffer.GetData(vector4Span); + + PixelOperations.Instance.FromVector4Destructive(Configuration.Default, vector4Span, resultSpan); + } + finally + { + Marshal.FreeHGlobal((IntPtr)Unsafe.AsPointer(ref vector4Span.GetPinnableReference())); + + source.UnlockBits(sourceData); + result.UnlockBits(resultData); + } + + return result; + } + + /// + /// Performs a vertical 1D complex convolution with the specified parameters. + /// + /// The source to read data from. + /// The target to write the results to. + /// The with the values for the current complex kernel. + /// The height of the image to process. + /// The width of the image to process. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ApplyVerticalConvolution( + ReadWriteBuffer source, + ReadWriteBuffer target, + ReadOnlyBuffer kernel, + int height, + int width) + { + VerticalConvolutionProcessor shader = new( + width, + maxY: height - 1, + maxX: width - 1, + kernel.Length, + source, + target, + kernel); + + Gpu.Default.For(width, height, in shader); + } + + /// + /// Kernel for the vertical convolution pass. + /// + [AutoConstructor] + internal readonly partial struct VerticalConvolutionProcessor : IComputeShader + { + public readonly int width; + public readonly int maxY; + public readonly int maxX; + public readonly int kernelLength; + + public readonly ReadWriteBuffer source; + public readonly ReadWriteBuffer target; + public readonly ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) + { + Vector4 result = Vector4.Zero; + int radiusY = kernelLength >> 1; + int sourceOffsetColumnBase = ids.X; + + for (int i = 0; i < kernelLength; i++) + { + int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); + int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); + Vector4 color = source[offsetY * width + offsetX]; + + result += kernel[i] * color; + } + + int offsetXY = ids.Y * width + ids.X; + target[offsetXY] = result; + } + } + + /// + /// Performs an horizontal 1D complex convolution with the specified parameters. + /// + /// The source to read data from. + /// The target to write the results to. + /// The with the values for the current complex kernel. + /// The height of the image to process. + /// The width of the image to process. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ApplyHorizontalConvolution( + ReadWriteBuffer source, + ReadWriteBuffer target, + ReadOnlyBuffer kernel, + int height, + int width) + { + HorizontalConvolutionProcessor shader = new( + width, + maxY: height - 1, + maxX: width - 1, + kernel.Length, + source, + target, + kernel); + + Gpu.Default.For(width, height, in shader); + } + + /// + /// Kernel for the horizontal convolution pass. + /// + [AutoConstructor] + internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader + { + public readonly int width; + public readonly int maxY; + public readonly int maxX; + public readonly int kernelLength; + + public readonly ReadWriteBuffer source; + public readonly ReadWriteBuffer target; + public readonly ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) + { + Vector4 result = Vector4.Zero; + int radiusX = kernelLength >> 1; + int sourceOffsetColumnBase = ids.X; + int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); + int offsetXY; + + for (int i = 0; i < kernelLength; i++) + { + int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX); + offsetXY = offsetY * width + offsetX; + Vector4 color = source[offsetXY]; + + result += kernel[i] * color; + } + + offsetXY = ids.Y * width + ids.X; + target[offsetXY] = result; + } + } + } +} From 2dd0549eecefab4aa40bccb16e8f1c4b73f4dccc Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 31 Dec 2020 01:31:36 +0100 Subject: [PATCH 03/26] Implemented ShareX sample --- .../ComputeSharp.ShareX.csproj | 13 +++++++ samples/ComputeSharp.ShareX/Program.cs | 36 +++++++++++++++++-- 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/samples/ComputeSharp.ShareX/ComputeSharp.ShareX.csproj b/samples/ComputeSharp.ShareX/ComputeSharp.ShareX.csproj index 55f80df8..19f36cbb 100644 --- a/samples/ComputeSharp.ShareX/ComputeSharp.ShareX.csproj +++ b/samples/ComputeSharp.ShareX/ComputeSharp.ShareX.csproj @@ -8,7 +8,20 @@ + + + + + + + + + + diff --git a/samples/ComputeSharp.ShareX/Program.cs b/samples/ComputeSharp.ShareX/Program.cs index 5eca73eb..54abd493 100644 --- a/samples/ComputeSharp.ShareX/Program.cs +++ b/samples/ComputeSharp.ShareX/Program.cs @@ -1,12 +1,44 @@ using System; +using System.Drawing; +using System.IO; +using System.Reflection; +using ShareX.HelpersLib; namespace ComputeSharp.ShareX { class Program { - static void Main(string[] args) + static void Main() { - Console.WriteLine("Hello World!"); + Console.WriteLine(">> Loading image"); + + string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "city.jpg"); + + using Bitmap sourceBitmap = new(path); + + Console.WriteLine(">> Blurring on CPU"); + + using Bitmap resultBitmapCpu = ConvolutionMatrixManager.GaussianBlur(60, 60, 10).Apply(sourceBitmap); + + string resultPathCpu = Path.Combine( + Path.GetRelativePath(Path.GetDirectoryName(path)!, @"..\..\..\"), + $"{Path.GetFileNameWithoutExtension(path)}_cpu{Path.GetExtension(path)}"); + + Console.WriteLine(">> Saving image"); + + resultBitmapCpu.Save(resultPathCpu); + + Console.WriteLine(">> Blurring on GPU"); + + using Bitmap resultBitmapGpu = HlslConvolutionManager.Create(60, 10).Apply(sourceBitmap); + + string resultPathGpu = Path.Combine( + Path.GetRelativePath(Path.GetDirectoryName(path)!, @"..\..\..\"), + $"{Path.GetFileNameWithoutExtension(path)}_gpu{Path.GetExtension(path)}"); + + Console.WriteLine(">> Saving image"); + + resultBitmapGpu.Save(resultPathGpu); } } } From 050182367f6247cec137031439862017e90e8170 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 4 Jan 2021 16:29:15 +0100 Subject: [PATCH 04/26] Added Bgra32 type --- .../ComputeSharp.Core.csproj | 1 + src/ComputeSharp.Core/PixelTypes/Bgra32.cs | 119 ++++++++++++++++++ .../PixelTypes/__Internals/IUnorm{TPixel}.cs | 16 +++ 3 files changed, 136 insertions(+) create mode 100644 src/ComputeSharp.Core/PixelTypes/Bgra32.cs create mode 100644 src/ComputeSharp.Core/PixelTypes/__Internals/IUnorm{TPixel}.cs diff --git a/src/ComputeSharp.Core/ComputeSharp.Core.csproj b/src/ComputeSharp.Core/ComputeSharp.Core.csproj index 85cab145..e7c12eb8 100644 --- a/src/ComputeSharp.Core/ComputeSharp.Core.csproj +++ b/src/ComputeSharp.Core/ComputeSharp.Core.csproj @@ -8,6 +8,7 @@ + diff --git a/src/ComputeSharp.Core/PixelTypes/Bgra32.cs b/src/ComputeSharp.Core/PixelTypes/Bgra32.cs new file mode 100644 index 00000000..faa0f907 --- /dev/null +++ b/src/ComputeSharp.Core/PixelTypes/Bgra32.cs @@ -0,0 +1,119 @@ +using System; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.__Internals; + +#pragma warning disable CS0618 + +namespace ComputeSharp +{ + /// + /// Packed pixel type containing four 8-bit unsigned normalized values ranging from 0 to 255. + /// The color components are stored in blue, green, red, and alpha order (least significant to most significant byte). + /// The format is binary compatible with System.Drawing.Imaging.PixelFormat.Format32bppArgb. + /// + /// Ranges from [0, 0, 0, 0] to [1, 1, 1, 1] in vector form. + /// + /// + [StructLayout(LayoutKind.Sequential)] + public struct Bgra32 : IEquatable, IUnorm, IUnorm, IUnorm + { + /// + /// The blue component. + /// + public byte B; + + /// + /// The green component. + /// + public byte G; + + /// + /// The red component. + /// + public byte R; + + /// + /// The alpha component. + /// + public byte A; + + /// + /// Initializes a new instance of the struct. + /// + /// The red component. + /// The green component. + /// The blue component. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Bgra32(byte r, byte g, byte b) + { + R = r; + G = g; + B = b; + A = byte.MaxValue; + } + + /// + /// Initializes a new instance of the struct. + /// + /// The red component. + /// The green component. + /// The blue component. + /// The alpha component. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Bgra32(byte r, byte g, byte b, byte a) + { + R = r; + G = g; + B = b; + A = a; + } + + /// + /// Gets or sets the packed representation of the struct. + /// + public uint PackedValue + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + readonly get => Unsafe.As(ref Unsafe.AsRef(this)); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => Unsafe.As(ref this) = value; + } + + /// + /// Compares two objects for equality. + /// + /// The on the left side of the operand. + /// The on the right side of the operand. + /// + /// True if the parameter is equal to the parameter; otherwise, false. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator ==(Bgra32 left, Bgra32 right) => left.Equals(right); + + /// + /// Compares two objects for equality. + /// + /// The on the left side of the operand. + /// The on the right side of the operand. + /// + /// True if the parameter is not equal to the parameter; otherwise, false. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator !=(Bgra32 left, Bgra32 right) => !left.Equals(right); + + /// + public override readonly bool Equals(object? obj) => obj is Bgra32 other && Equals(other); + + /// + public readonly bool Equals(Bgra32 other) => PackedValue.Equals(other.PackedValue); + + /// + public override readonly int GetHashCode() => PackedValue.GetHashCode(); + + /// + public override readonly string ToString() => $"{nameof(Bgra32)}({this.B}, {this.G}, {this.R}, {this.A})"; + } +} diff --git a/src/ComputeSharp.Core/PixelTypes/__Internals/IUnorm{TPixel}.cs b/src/ComputeSharp.Core/PixelTypes/__Internals/IUnorm{TPixel}.cs new file mode 100644 index 00000000..4f138d99 --- /dev/null +++ b/src/ComputeSharp.Core/PixelTypes/__Internals/IUnorm{TPixel}.cs @@ -0,0 +1,16 @@ +using System; +using System.ComponentModel; + +namespace ComputeSharp.__Internals +{ + /// + /// Indicates the supported HLSL pixel types to represent a given normalized pixel type. + /// + /// The type of pixels used on the GPU side. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This interface is not intended to be used directly by user code")] + public interface IUnorm + where TPixel : unmanaged + { + } +} From aaf8b5cac44b18bbeda46995b84fba7b79dde051 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 4 Jan 2021 16:29:50 +0100 Subject: [PATCH 05/26] Added support for normalized 2D textures --- .../Buffers/ReadWriteTexture2D{T,TPixel}.cs | 56 +++++++++++++++++++ .../Helpers/DXGIFormatHelper.cs | 3 +- .../Translation/Mappings/HlslKnownTypes.cs | 1 + .../IComputeShaderSourceGenerator.cs | 3 +- .../Mappings/HlslKnownMembers.cs | 1 + .../Mappings/HlslKnownTypes.cs | 6 +- .../Extensions/GraphicsDeviceExtensions.cs | 25 +++++++++ 7 files changed, 92 insertions(+), 3 deletions(-) create mode 100644 src/ComputeSharp.Graphics/Buffers/ReadWriteTexture2D{T,TPixel}.cs diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteTexture2D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Buffers/ReadWriteTexture2D{T,TPixel}.cs new file mode 100644 index 00000000..a49e97ab --- /dev/null +++ b/src/ComputeSharp.Graphics/Buffers/ReadWriteTexture2D{T,TPixel}.cs @@ -0,0 +1,56 @@ +using System.Diagnostics; +using ComputeSharp.__Internals; +using ComputeSharp.Exceptions; +using ComputeSharp.Graphics; +using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Graphics.Buffers.Enums; +using ComputeSharp.Graphics.Buffers.Views; + +#pragma warning disable CS0618 + +namespace ComputeSharp +{ + /// + /// A representing a typed read write 2D texture stored on GPU memory. + /// + /// The type of items stored on the texture. + /// The type of pixels used on the GPU side. + [DebuggerTypeProxy(typeof(Texture2DDebugView<>))] + [DebuggerDisplay("{ToString(),raw}")] + public sealed class ReadWriteTexture2D : Texture2D + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + /// + /// Creates a new instance with the specified parameters. + /// + /// The associated with the current instance. + /// The width of the texture. + /// The height of the texture. + internal ReadWriteTexture2D(GraphicsDevice device, int width, int height) + : base(device, width, height, ResourceType.ReadWrite) + { + } + + /// + /// Gets a single value from the current writeable texture. + /// + /// The horizontal offset of the value to get. + /// The vertical offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public ref TPixel this[int x, int y] => throw new InvalidExecutionContextException($"{nameof(ReadWriteTexture2D)}[int,int]"); + + /// + /// Gets or sets a single value from the current writeable texture. + /// + /// The coordinates of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public ref TPixel this[Int2 xy] => throw new InvalidExecutionContextException($"{nameof(ReadWriteTexture2D)}[Int2]"); + + /// + public override string ToString() + { + return $"ComputeSharp.ReadWriteTexture2D<{typeof(T)},{typeof(TPixel)}>[{Width}, {Height}]"; + } + } +} diff --git a/src/ComputeSharp.Graphics/Helpers/DXGIFormatHelper.cs b/src/ComputeSharp.Graphics/Helpers/DXGIFormatHelper.cs index be8d5d21..6260d27e 100644 --- a/src/ComputeSharp.Graphics/Helpers/DXGIFormatHelper.cs +++ b/src/ComputeSharp.Graphics/Helpers/DXGIFormatHelper.cs @@ -2,8 +2,8 @@ using System.Numerics; using System.Runtime.CompilerServices; using Microsoft.Toolkit.Diagnostics; -using static TerraFX.Interop.DXGI_FORMAT; using TerraFX.Interop; +using static TerraFX.Interop.DXGI_FORMAT; namespace ComputeSharp.Graphics.Helpers { @@ -38,6 +38,7 @@ namespace ComputeSharp.Graphics.Helpers else if (typeof(T) == typeof(Vector2)) return DXGI_FORMAT_R32G32_FLOAT; else if (typeof(T) == typeof(Vector3)) return DXGI_FORMAT_R32G32B32_FLOAT; else if (typeof(T) == typeof(Vector4)) return DXGI_FORMAT_R32G32B32A32_FLOAT; + else if (typeof(T) == typeof(Bgra32)) return DXGI_FORMAT_B8G8R8A8_UNORM; else return ThrowHelper.ThrowArgumentException("Invalid texture type"); } } diff --git a/src/ComputeSharp.Shaders/Translation/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.Shaders/Translation/Mappings/HlslKnownTypes.cs index b3fe7b73..0e5c821b 100644 --- a/src/ComputeSharp.Shaders/Translation/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.Shaders/Translation/Mappings/HlslKnownTypes.cs @@ -95,6 +95,7 @@ namespace ComputeSharp.Shaders.Mappings return genericType == typeof(ReadWriteBuffer<>) || genericType == typeof(ReadWriteTexture2D<>) || + genericType == typeof(ReadWriteTexture2D<,>) || genericType == typeof(ReadWriteTexture3D<>); } } diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index a90ba55c..fa51f8ba 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -122,7 +122,8 @@ namespace ComputeSharp.SourceGenerators yield return new[] { fieldSymbol.Name, mapping ?? fieldSymbol.Name, typeName }; // Track the type of items in the current buffer - if (HlslKnownTypes.IsTypedResourceType(typeSymbol.GetFullMetadataName())) + if (HlslKnownTypes.IsTypedResourceType(typeSymbol.GetFullMetadataName()) && + typeSymbol.TypeArguments.Length == 1) { types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]); } diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs index 7a7df32b..a1212d69 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs @@ -19,6 +19,7 @@ namespace ComputeSharp.SourceGenerators.Mappings { [$"ComputeSharp.ReadOnlyTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", [$"ComputeSharp.ReadWriteTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", + [$"ComputeSharp.ReadWriteTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", [$"ComputeSharp.ReadOnlyTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", [$"ComputeSharp.ReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3" }; diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index 43ba20b4..68433561 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -1,6 +1,8 @@ using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Diagnostics.Contracts; +using System.Linq; using System.Numerics; using ComputeSharp.SourceGenerators.Extensions; using Microsoft.CodeAnalysis; @@ -71,6 +73,7 @@ namespace ComputeSharp.SourceGenerators.Mappings case "ComputeSharp.ReadWriteBuffer`1": case "ComputeSharp.ReadOnlyTexture2D`1": case "ComputeSharp.ReadWriteTexture2D`1": + case "ComputeSharp.ReadWriteTexture2D`2": case "ComputeSharp.ReadOnlyTexture3D`1": case "ComputeSharp.ReadWriteTexture3D`1": return true; @@ -107,7 +110,7 @@ namespace ComputeSharp.SourceGenerators.Mappings // Special case for the structured buffer types if (IsTypedResourceType(typeName)) { - string genericArgumentName = ((INamedTypeSymbol)typeSymbol.TypeArguments[0]).GetFullMetadataName(); + string genericArgumentName = ((INamedTypeSymbol)typeSymbol.TypeArguments.Last()).GetFullMetadataName(); // If the current type is a custom type, format it as needed if (!KnownTypes.TryGetValue(genericArgumentName, out string? mapped)) @@ -123,6 +126,7 @@ namespace ComputeSharp.SourceGenerators.Mappings "ComputeSharp.ReadWriteBuffer`1" => $"RWStructuredBuffer<{mapped}>", "ComputeSharp.ReadOnlyTexture2D`1" => $"Texture2D<{mapped}>", "ComputeSharp.ReadWriteTexture2D`1" => $"RWTexture2D<{mapped}>", + "ComputeSharp.ReadWriteTexture2D`2" => $"RWTexture2D", "ComputeSharp.ReadOnlyTexture3D`1" => $"Texture3D<{mapped}>", "ComputeSharp.ReadWriteTexture3D`1" => $"RWTexture3D<{mapped}>", _ => throw new ArgumentException() diff --git a/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs index e22ed529..4da8df60 100644 --- a/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs +++ b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs @@ -1,9 +1,12 @@ using System; using System.Diagnostics.Contracts; +using ComputeSharp.__Internals; using ComputeSharp.Graphics; using ComputeSharp.Graphics.Buffers.Abstract; using ComputeSharp.Shaders; +#pragma warning disable CS0618 + namespace ComputeSharp { /// @@ -469,6 +472,28 @@ namespace ComputeSharp return texture; } + /// + /// Allocates a new writeable 2D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input with the data to copy on the allocated texture. + /// The width of the texture. + /// The height of the texture. + /// A instance with the contents of the input . + [Pure] + public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, ReadOnlySpan span, int width, int height) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + ReadWriteTexture2D texture = new(device, width, height); + + texture.SetData(span); + + return texture; + } + /// /// Allocates a new writeable 3D texture with the specified parameters. /// From b54fb3c7dfaa6112064f8a9640f4bacf452e4d71 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 4 Jan 2021 16:37:51 +0100 Subject: [PATCH 06/26] Added missing normalized texture types --- .../Buffers/ReadOnlyTexture2D{T,TPixel}.cs | 56 ++++++++++++++++++ .../Buffers/ReadOnlyTexture3D{T,TPixel}.cs | 58 +++++++++++++++++++ .../Buffers/ReadWriteTexture3D{T,TPixel}.cs | 58 +++++++++++++++++++ .../Translation/Mappings/HlslKnownTypes.cs | 7 ++- .../Mappings/HlslKnownMembers.cs | 5 +- .../Mappings/HlslKnownTypes.cs | 7 ++- 6 files changed, 187 insertions(+), 4 deletions(-) create mode 100644 src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture2D{T,TPixel}.cs create mode 100644 src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture3D{T,TPixel}.cs create mode 100644 src/ComputeSharp.Graphics/Buffers/ReadWriteTexture3D{T,TPixel}.cs diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture2D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture2D{T,TPixel}.cs new file mode 100644 index 00000000..771fb853 --- /dev/null +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture2D{T,TPixel}.cs @@ -0,0 +1,56 @@ +using System.Diagnostics; +using ComputeSharp.__Internals; +using ComputeSharp.Exceptions; +using ComputeSharp.Graphics; +using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Graphics.Buffers.Enums; +using ComputeSharp.Graphics.Buffers.Views; + +#pragma warning disable CS0618 + +namespace ComputeSharp +{ + /// + /// A representing a typed readonly 2D texture stored on GPU memory. + /// + /// The type of items stored on the texture. + /// The type of pixels used on the GPU side. + [DebuggerTypeProxy(typeof(Texture2DDebugView<>))] + [DebuggerDisplay("{ToString(),raw}")] + public sealed class ReadOnlyTexture2D : Texture2D + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + /// + /// Creates a new instance with the specified parameters. + /// + /// The associated with the current instance. + /// The width of the texture. + /// The height of the texture. + internal ReadOnlyTexture2D(GraphicsDevice device, int width, int height) + : base(device, width, height, ResourceType.ReadOnly) + { + } + + /// + /// Gets a single value from the current readonly texture. + /// + /// The horizontal offset of the value to get. + /// The vertical offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public T this[int x, int y] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyTexture2D)}[int,int]"); + + /// + /// Gets a single value from the current readonly texture. + /// + /// The coordinates of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public T this[Int2 xy] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyTexture2D)}[Int2]"); + + /// + public override string ToString() + { + return $"ComputeSharp.ReadOnlyTexture2D<{typeof(T)},{typeof(TPixel)}>[{Width}, {Height}]"; + } + } +} diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture3D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture3D{T,TPixel}.cs new file mode 100644 index 00000000..e0eaedb0 --- /dev/null +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture3D{T,TPixel}.cs @@ -0,0 +1,58 @@ +using System.Diagnostics; +using ComputeSharp.__Internals; +using ComputeSharp.Exceptions; +using ComputeSharp.Graphics; +using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Graphics.Buffers.Enums; +using ComputeSharp.Graphics.Buffers.Views; + +#pragma warning disable CS0618 + +namespace ComputeSharp +{ + /// + /// A representing a typed readonly 3D texture stored on GPU memory. + /// + /// The type of items stored on the texture. + /// The type of pixels used on the GPU side. + [DebuggerTypeProxy(typeof(Texture3DDebugView<>))] + [DebuggerDisplay("{ToString(),raw}")] + public sealed class ReadOnlyTexture3D : Texture3D + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + /// + /// Creates a new instance with the specified parameters. + /// + /// The associated with the current instance. + /// The width of the texture. + /// The height of the texture. + /// The depth of the texture. + internal ReadOnlyTexture3D(GraphicsDevice device, int width, int height, int depth) + : base(device, width, height, depth, ResourceType.ReadOnly) + { + } + + /// + /// Gets a single value from the current readonly texture. + /// + /// The horizontal offset of the value to get. + /// The vertical offset of the value to get. + /// The depthwise offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public T this[int x, int y, int z] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyTexture3D)}[int,int,int]"); + + /// + /// Gets a single value from the current readonly texture. + /// + /// The coordinates of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public T this[Int3 xyz] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyTexture3D)}[Int3]"); + + /// + public override string ToString() + { + return $"ComputeSharp.ReadOnlyTexture3D<{typeof(T)},{nameof(TPixel)}>[{Width}, {Height}, {Depth}]"; + } + } +} diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteTexture3D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Buffers/ReadWriteTexture3D{T,TPixel}.cs new file mode 100644 index 00000000..2d44f219 --- /dev/null +++ b/src/ComputeSharp.Graphics/Buffers/ReadWriteTexture3D{T,TPixel}.cs @@ -0,0 +1,58 @@ +using System.Diagnostics; +using ComputeSharp.__Internals; +using ComputeSharp.Exceptions; +using ComputeSharp.Graphics; +using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Graphics.Buffers.Enums; +using ComputeSharp.Graphics.Buffers.Views; + +#pragma warning disable CS0618 + +namespace ComputeSharp +{ + /// + /// A representing a typed readonly 3D texture stored on GPU memory. + /// + /// The type of items stored on the texture. + /// The type of pixels used on the GPU side. + [DebuggerTypeProxy(typeof(Texture3DDebugView<>))] + [DebuggerDisplay("{ToString(),raw}")] + public sealed class ReadWriteTexture3D : Texture3D + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + /// + /// Creates a new instance with the specified parameters. + /// + /// The associated with the current instance. + /// The width of the texture. + /// The height of the texture. + /// The depth of the texture. + internal ReadWriteTexture3D(GraphicsDevice device, int width, int height, int depth) + : base(device, width, height, depth, ResourceType.ReadWrite) + { + } + + /// + /// Gets a single value from the current writeable texture. + /// + /// The horizontal offset of the value to get. + /// The vertical offset of the value to get. + /// The depthwise offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public ref T this[int x, int y, int z] => throw new InvalidExecutionContextException($"{nameof(ReadWriteTexture3D)}[int,int,int]"); + + /// + /// Gets a single value from the current writeable texture. + /// + /// The coordinates of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public ref T this[Int3 xyz] => throw new InvalidExecutionContextException($"{nameof(ReadWriteTexture3D)}[Int3]"); + + /// + public override string ToString() + { + return $"ComputeSharp.ReadWriteTexture3D<{typeof(T)},{nameof(TPixel)}>[{Width}, {Height}, {Depth}]"; + } + } +} diff --git a/src/ComputeSharp.Shaders/Translation/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.Shaders/Translation/Mappings/HlslKnownTypes.cs index 0e5c821b..b2c84d86 100644 --- a/src/ComputeSharp.Shaders/Translation/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.Shaders/Translation/Mappings/HlslKnownTypes.cs @@ -77,7 +77,9 @@ namespace ComputeSharp.Shaders.Mappings return genericType == typeof(ReadOnlyBuffer<>) || genericType == typeof(ReadOnlyTexture2D<>) || - genericType == typeof(ReadOnlyTexture3D<>); + genericType == typeof(ReadOnlyTexture2D<,>) || + genericType == typeof(ReadOnlyTexture3D<>) || + genericType == typeof(ReadOnlyTexture3D<,>); } /// @@ -96,7 +98,8 @@ namespace ComputeSharp.Shaders.Mappings genericType == typeof(ReadWriteBuffer<>) || genericType == typeof(ReadWriteTexture2D<>) || genericType == typeof(ReadWriteTexture2D<,>) || - genericType == typeof(ReadWriteTexture3D<>); + genericType == typeof(ReadWriteTexture3D<>) || + genericType == typeof(ReadWriteTexture3D<,>); } } } diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs index a1212d69..e3751ef4 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs @@ -18,10 +18,13 @@ namespace ComputeSharp.SourceGenerators.Mappings private static readonly IReadOnlyDictionary KnownIndexers = new Dictionary { [$"ComputeSharp.ReadOnlyTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", + [$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", [$"ComputeSharp.ReadWriteTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", [$"ComputeSharp.ReadWriteTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", [$"ComputeSharp.ReadOnlyTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", - [$"ComputeSharp.ReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3" + [$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", + [$"ComputeSharp.ReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", + [$"ComputeSharp.ReadWriteTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3" }; /// diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index 68433561..2bc27d99 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; using System.Numerics; @@ -72,10 +71,13 @@ namespace ComputeSharp.SourceGenerators.Mappings case "ComputeSharp.ReadOnlyBuffer`1": case "ComputeSharp.ReadWriteBuffer`1": case "ComputeSharp.ReadOnlyTexture2D`1": + case "ComputeSharp.ReadOnlyTexture2D`2": case "ComputeSharp.ReadWriteTexture2D`1": case "ComputeSharp.ReadWriteTexture2D`2": case "ComputeSharp.ReadOnlyTexture3D`1": + case "ComputeSharp.ReadOnlyTexture3D`2": case "ComputeSharp.ReadWriteTexture3D`1": + case "ComputeSharp.ReadWriteTexture3D`2": return true; default: return false; }; @@ -125,10 +127,13 @@ namespace ComputeSharp.SourceGenerators.Mappings "ComputeSharp.ReadOnlyBuffer`1" => $"StructuredBuffer<{mapped}>", "ComputeSharp.ReadWriteBuffer`1" => $"RWStructuredBuffer<{mapped}>", "ComputeSharp.ReadOnlyTexture2D`1" => $"Texture2D<{mapped}>", + "ComputeSharp.ReadOnlyTexture2D`2" => $"Texture2D", "ComputeSharp.ReadWriteTexture2D`1" => $"RWTexture2D<{mapped}>", "ComputeSharp.ReadWriteTexture2D`2" => $"RWTexture2D", "ComputeSharp.ReadOnlyTexture3D`1" => $"Texture3D<{mapped}>", + "ComputeSharp.ReadOnlyTexture3D`2" => $"Texture3D", "ComputeSharp.ReadWriteTexture3D`1" => $"RWTexture3D<{mapped}>", + "ComputeSharp.ReadWriteTexture3D`2" => $"RWTexture3D", _ => throw new ArgumentException() }; } From f68dd1222ade04539ae4dfa7eab4a9e330041ce1 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 4 Jan 2021 17:36:36 +0100 Subject: [PATCH 07/26] Added more 4-channel pixel types --- src/ComputeSharp.Core/PixelTypes/Bgra32.cs | 3 + src/ComputeSharp.Core/PixelTypes/Rgba32.cs | 121 ++++++++++++++++++ src/ComputeSharp.Core/PixelTypes/Rgba64.cs | 121 ++++++++++++++++++ .../Helpers/DXGIFormatHelper.cs | 2 + 4 files changed, 247 insertions(+) create mode 100644 src/ComputeSharp.Core/PixelTypes/Rgba32.cs create mode 100644 src/ComputeSharp.Core/PixelTypes/Rgba64.cs diff --git a/src/ComputeSharp.Core/PixelTypes/Bgra32.cs b/src/ComputeSharp.Core/PixelTypes/Bgra32.cs index faa0f907..1b3f7ea8 100644 --- a/src/ComputeSharp.Core/PixelTypes/Bgra32.cs +++ b/src/ComputeSharp.Core/PixelTypes/Bgra32.cs @@ -16,6 +16,7 @@ namespace ComputeSharp /// Ranges from [0, 0, 0, 0] to [1, 1, 1, 1] in vector form. /// /// + /// This struct is fully mutable. [StructLayout(LayoutKind.Sequential)] public struct Bgra32 : IEquatable, IUnorm, IUnorm, IUnorm { @@ -108,9 +109,11 @@ namespace ComputeSharp public override readonly bool Equals(object? obj) => obj is Bgra32 other && Equals(other); /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly bool Equals(Bgra32 other) => PackedValue.Equals(other.PackedValue); /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] public override readonly int GetHashCode() => PackedValue.GetHashCode(); /// diff --git a/src/ComputeSharp.Core/PixelTypes/Rgba32.cs b/src/ComputeSharp.Core/PixelTypes/Rgba32.cs new file mode 100644 index 00000000..a288d440 --- /dev/null +++ b/src/ComputeSharp.Core/PixelTypes/Rgba32.cs @@ -0,0 +1,121 @@ +using System; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.__Internals; + +#pragma warning disable CS0618 + +namespace ComputeSharp +{ + /// + /// Packed pixel type containing four 8-bit unsigned normalized values ranging from 0 to 255. + /// The color components are stored in red, green, blue, and alpha order (least significant to most significant byte). + /// + /// Ranges from [0, 0, 0, 0] to [1, 1, 1, 1] in vector form. + /// + /// + /// This struct is fully mutable. + [StructLayout(LayoutKind.Sequential)] + public struct Rgba32 : IEquatable, IUnorm, IUnorm, IUnorm + { + /// + /// The red component. + /// + public byte R; + + /// + /// The green component. + /// + public byte G; + + /// + /// The blue component. + /// + public byte B; + + /// + /// The alpha component. + /// + public byte A; + + /// + /// Initializes a new instance of the struct. + /// + /// The red component. + /// The green component. + /// The blue component. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Rgba32(byte r, byte g, byte b) + { + this.R = r; + this.G = g; + this.B = b; + this.A = byte.MaxValue; + } + + /// + /// Initializes a new instance of the struct. + /// + /// The red component. + /// The green component. + /// The blue component. + /// The alpha component. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Rgba32(byte r, byte g, byte b, byte a) + { + this.R = r; + this.G = g; + this.B = b; + this.A = a; + } + + /// + /// Gets or sets the packed representation of the Rgba32 struct. + /// + public uint PackedValue + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + readonly get => Unsafe.As(ref Unsafe.AsRef(this)); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => Unsafe.As(ref this) = value; + } + + /// + /// Compares two objects for equality. + /// + /// The on the left side of the operand. + /// The on the right side of the operand. + /// + /// True if the parameter is equal to the parameter; otherwise, false. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator ==(Rgba32 left, Rgba32 right) => left.Equals(right); + + /// + /// Compares two objects for equality. + /// + /// The on the left side of the operand. + /// The on the right side of the operand. + /// + /// True if the parameter is not equal to the parameter; otherwise, false. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator !=(Rgba32 left, Rgba32 right) => !left.Equals(right); + + /// + public override readonly bool Equals(object obj) => obj is Rgba32 rgba32 && Equals(rgba32); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool Equals(Rgba32 other) => PackedValue.Equals(other.PackedValue); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override readonly int GetHashCode() => PackedValue.GetHashCode(); + + /// + public override readonly string ToString() => $"{nameof(Rgba32)}({this.R}, {this.G}, {this.B}, {this.A})"; + } +} diff --git a/src/ComputeSharp.Core/PixelTypes/Rgba64.cs b/src/ComputeSharp.Core/PixelTypes/Rgba64.cs new file mode 100644 index 00000000..794b85da --- /dev/null +++ b/src/ComputeSharp.Core/PixelTypes/Rgba64.cs @@ -0,0 +1,121 @@ +using System; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.__Internals; + +#pragma warning disable CS0618 + +namespace ComputeSharp +{ + /// + /// Packed pixel type containing four 16-bit unsigned normalized values ranging from 0 to 255. + /// The color components are stored in red, green, blue, and alpha order (least significant to most significant byte). + /// + /// Ranges from [0, 0, 0, 0] to [1, 1, 1, 1] in vector form. + /// + /// + /// This struct is fully mutable. + [StructLayout(LayoutKind.Sequential)] + public struct Rgba64 : IEquatable, IUnorm, IUnorm, IUnorm + { + /// + /// The red component. + /// + public ushort R; + + /// + /// The green component. + /// + public ushort G; + + /// + /// The blue component. + /// + public ushort B; + + /// + /// The alpha component. + /// + public ushort A; + + /// + /// Initializes a new instance of the struct. + /// + /// The red component. + /// The green component. + /// The blue component. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Rgba64(ushort r, ushort g, ushort b) + { + this.R = r; + this.G = g; + this.B = b; + this.A = ushort.MaxValue; + } + + /// + /// Initializes a new instance of the struct. + /// + /// The red component. + /// The green component. + /// The blue component. + /// The alpha component. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Rgba64(ushort r, ushort g, ushort b, ushort a) + { + this.R = r; + this.G = g; + this.B = b; + this.A = a; + } + + /// + /// Gets or sets the packed representation of the Rgba64 struct. + /// + public ulong PackedValue + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + readonly get => Unsafe.As(ref Unsafe.AsRef(this)); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => Unsafe.As(ref this) = value; + } + + /// + /// Compares two objects for equality. + /// + /// The on the left side of the operand. + /// The on the right side of the operand. + /// + /// True if the parameter is equal to the parameter; otherwise, false. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator ==(Rgba64 left, Rgba64 right) => left.Equals(right); + + /// + /// Compares two objects for equality. + /// + /// The on the left side of the operand. + /// The on the right side of the operand. + /// + /// True if the parameter is not equal to the parameter; otherwise, false. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator !=(Rgba64 left, Rgba64 right) => !left.Equals(right); + + /// + public override readonly bool Equals(object obj) => obj is Rgba64 rgba32 && Equals(rgba32); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool Equals(Rgba64 other) => PackedValue.Equals(other.PackedValue); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override readonly int GetHashCode() => PackedValue.GetHashCode(); + + /// + public override readonly string ToString() => $"{nameof(Rgba64)}({this.R}, {this.G}, {this.B}, {this.A})"; + } +} diff --git a/src/ComputeSharp.Graphics/Helpers/DXGIFormatHelper.cs b/src/ComputeSharp.Graphics/Helpers/DXGIFormatHelper.cs index 6260d27e..87596774 100644 --- a/src/ComputeSharp.Graphics/Helpers/DXGIFormatHelper.cs +++ b/src/ComputeSharp.Graphics/Helpers/DXGIFormatHelper.cs @@ -39,6 +39,8 @@ namespace ComputeSharp.Graphics.Helpers else if (typeof(T) == typeof(Vector3)) return DXGI_FORMAT_R32G32B32_FLOAT; else if (typeof(T) == typeof(Vector4)) return DXGI_FORMAT_R32G32B32A32_FLOAT; else if (typeof(T) == typeof(Bgra32)) return DXGI_FORMAT_B8G8R8A8_UNORM; + else if (typeof(T) == typeof(Rgba32)) return DXGI_FORMAT_R8G8B8A8_UNORM; + else if (typeof(T) == typeof(Rgba64)) return DXGI_FORMAT_R16G16B16A16_UNORM; else return ThrowHelper.ThrowArgumentException("Invalid texture type"); } } From bead19fc87083966ec5e10f708ba525841b4f3a9 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 4 Jan 2021 17:48:50 +0100 Subject: [PATCH 08/26] Updated sample to use normalized textures --- .gitignore | 5 +- .../ComputeSharp.ShareX.csproj | 1 - .../Gpu/HlslConvolutionManager.cs.cs | 62 +++++++------------ samples/ComputeSharp.ShareX/Program.cs | 4 +- 4 files changed, 26 insertions(+), 46 deletions(-) diff --git a/.gitignore b/.gitignore index 23c39fe0..fd8f3e38 100644 --- a/.gitignore +++ b/.gitignore @@ -329,6 +329,5 @@ ASALocalRun/ # MFractors (Xamarin productivity tool) working folder .mfractor/ -# Sample bokeh blur image -**/*_bokeh.jpg -**/*_gaussian.jpg +# Sample images +**/city_*.jpg diff --git a/samples/ComputeSharp.ShareX/ComputeSharp.ShareX.csproj b/samples/ComputeSharp.ShareX/ComputeSharp.ShareX.csproj index 19f36cbb..00562633 100644 --- a/samples/ComputeSharp.ShareX/ComputeSharp.ShareX.csproj +++ b/samples/ComputeSharp.ShareX/ComputeSharp.ShareX.csproj @@ -12,7 +12,6 @@ - diff --git a/samples/ComputeSharp.ShareX/Gpu/HlslConvolutionManager.cs.cs b/samples/ComputeSharp.ShareX/Gpu/HlslConvolutionManager.cs.cs index c3cf8bfa..a02df046 100644 --- a/samples/ComputeSharp.ShareX/Gpu/HlslConvolutionManager.cs.cs +++ b/samples/ComputeSharp.ShareX/Gpu/HlslConvolutionManager.cs.cs @@ -3,9 +3,6 @@ using System.Drawing; using System.Drawing.Imaging; using System.Numerics; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using SixLabors.ImageSharp; -using SixLabors.ImageSharp.PixelFormats; using Rectangle = System.Drawing.Rectangle; namespace ComputeSharp.ShareX @@ -93,30 +90,23 @@ namespace ComputeSharp.ShareX BitmapData sourceData = source.LockBits(bounds, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb), resultData = result.LockBits(bounds, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); - Span - sourceSpan = new((Rgba32*)sourceData.Scan0.ToPointer(), bounds.Width * bounds.Height), - resultSpan = new((Rgba32*)resultData.Scan0.ToPointer(), sourceSpan.Length); - Span vector4Span = new((void*)Marshal.AllocHGlobal(sizeof(Vector4) * sourceSpan.Length), sourceSpan.Length); + Span + sourceSpan = new((Bgra32*)sourceData.Scan0.ToPointer(), bounds.Width * bounds.Height), + resultSpan = new((Bgra32*)resultData.Scan0.ToPointer(), sourceSpan.Length); try { - PixelOperations.Instance.ToVector4(Configuration.Default, sourceSpan, vector4Span); - - using ReadWriteBuffer leftBuffer = Gpu.Default.AllocateReadWriteBuffer(vector4Span); - using ReadWriteBuffer rightBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceSpan.Length); + using ReadWriteTexture2D leftBuffer = Gpu.Default.AllocateReadWriteTexture2D(sourceSpan, source.Width, source.Height); + using ReadWriteTexture2D rightBuffer = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(this.kernel); ApplyVerticalConvolution(leftBuffer, rightBuffer, kernelBuffer, source.Height, source.Width); ApplyHorizontalConvolution(rightBuffer, leftBuffer, kernelBuffer, source.Height, source.Width); - leftBuffer.GetData(vector4Span); - - PixelOperations.Instance.FromVector4Destructive(Configuration.Default, vector4Span, resultSpan); + leftBuffer.GetData(resultSpan); } finally { - Marshal.FreeHGlobal((IntPtr)Unsafe.AsPointer(ref vector4Span.GetPinnableReference())); - source.UnlockBits(sourceData); result.UnlockBits(resultData); } @@ -127,21 +117,20 @@ namespace ComputeSharp.ShareX /// /// Performs a vertical 1D complex convolution with the specified parameters. /// - /// The source to read data from. - /// The target to write the results to. + /// The source to read data from. + /// The target to write the results to. /// The with the values for the current complex kernel. /// The height of the image to process. /// The width of the image to process. [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ApplyVerticalConvolution( - ReadWriteBuffer source, - ReadWriteBuffer target, + ReadWriteTexture2D source, + ReadWriteTexture2D target, ReadOnlyBuffer kernel, int height, int width) { VerticalConvolutionProcessor shader = new( - width, maxY: height - 1, maxX: width - 1, kernel.Length, @@ -158,13 +147,12 @@ namespace ComputeSharp.ShareX [AutoConstructor] internal readonly partial struct VerticalConvolutionProcessor : IComputeShader { - public readonly int width; public readonly int maxY; public readonly int maxX; public readonly int kernelLength; - public readonly ReadWriteBuffer source; - public readonly ReadWriteBuffer target; + public readonly ReadWriteTexture2D source; + public readonly ReadWriteTexture2D target; public readonly ReadOnlyBuffer kernel; /// @@ -178,34 +166,32 @@ namespace ComputeSharp.ShareX { int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); - Vector4 color = source[offsetY * width + offsetX]; + Vector4 color = source[offsetX, offsetY]; result += kernel[i] * color; } - int offsetXY = ids.Y * width + ids.X; - target[offsetXY] = result; + target[ids.XY] = result; } } /// /// Performs an horizontal 1D complex convolution with the specified parameters. /// - /// The source to read data from. - /// The target to write the results to. + /// The source to read data from. + /// The target to write the results to. /// The with the values for the current complex kernel. /// The height of the image to process. /// The width of the image to process. [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ApplyHorizontalConvolution( - ReadWriteBuffer source, - ReadWriteBuffer target, + ReadWriteTexture2D source, + ReadWriteTexture2D target, ReadOnlyBuffer kernel, int height, int width) { HorizontalConvolutionProcessor shader = new( - width, maxY: height - 1, maxX: width - 1, kernel.Length, @@ -222,13 +208,12 @@ namespace ComputeSharp.ShareX [AutoConstructor] internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader { - public readonly int width; public readonly int maxY; public readonly int maxX; public readonly int kernelLength; - public readonly ReadWriteBuffer source; - public readonly ReadWriteBuffer target; + public readonly ReadWriteTexture2D source; + public readonly ReadWriteTexture2D target; public readonly ReadOnlyBuffer kernel; /// @@ -238,19 +223,16 @@ namespace ComputeSharp.ShareX int radiusX = kernelLength >> 1; int sourceOffsetColumnBase = ids.X; int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); - int offsetXY; for (int i = 0; i < kernelLength; i++) { int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX); - offsetXY = offsetY * width + offsetX; - Vector4 color = source[offsetXY]; + Vector4 color = source[offsetX, offsetY]; result += kernel[i] * color; } - offsetXY = ids.Y * width + ids.X; - target[offsetXY] = result; + target[ids.XY] = result; } } } diff --git a/samples/ComputeSharp.ShareX/Program.cs b/samples/ComputeSharp.ShareX/Program.cs index 54abd493..90241bc2 100644 --- a/samples/ComputeSharp.ShareX/Program.cs +++ b/samples/ComputeSharp.ShareX/Program.cs @@ -18,7 +18,7 @@ namespace ComputeSharp.ShareX Console.WriteLine(">> Blurring on CPU"); - using Bitmap resultBitmapCpu = ConvolutionMatrixManager.GaussianBlur(60, 60, 10).Apply(sourceBitmap); + using Bitmap resultBitmapCpu = ConvolutionMatrixManager.GaussianBlur(61, 61, 10).Apply(sourceBitmap); string resultPathCpu = Path.Combine( Path.GetRelativePath(Path.GetDirectoryName(path)!, @"..\..\..\"), @@ -30,7 +30,7 @@ namespace ComputeSharp.ShareX Console.WriteLine(">> Blurring on GPU"); - using Bitmap resultBitmapGpu = HlslConvolutionManager.Create(60, 10).Apply(sourceBitmap); + using Bitmap resultBitmapGpu = HlslConvolutionManager.Create(61, 10).Apply(sourceBitmap); string resultPathGpu = Path.Combine( Path.GetRelativePath(Path.GetDirectoryName(path)!, @"..\..\..\"), From c8af56cbc486e45fe22dae9f927fa5fcc7ea2dd0 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 4 Jan 2021 17:57:33 +0100 Subject: [PATCH 09/26] Added new GraphicsDevice extensions --- .../Extensions/GraphicsDeviceExtensions.cs | 380 +++++++++++++++++- 1 file changed, 379 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs index 4da8df60..c0533982 100644 --- a/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs +++ b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs @@ -228,6 +228,102 @@ namespace ComputeSharp return texture; } + /// + /// Allocates a new readonly 2D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The width of the texture. + /// The height of the texture. + /// A zeroed instance of size [, ]. + [Pure] + public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, int width, int height) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + return new(device, width, height); + } + + /// + /// Allocates a new readonly 2D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// The width of the texture. + /// The height of the texture. + /// A instance with the contents of the input array. + [Pure] + public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, T[] array, int width, int height) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + return device.AllocateReadOnlyTexture2D(array.AsSpan(), width, height); + } + + /// + /// Allocates a new readonly 2D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// The starting offset within to read data from. + /// The width of the texture. + /// The height of the texture. + /// A instance with the contents of the input array. + [Pure] + public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, T[] array, int offset, int width, int height) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + return device.AllocateReadOnlyTexture2D(array.AsSpan(offset), width, height); + } + + /// + /// Allocates a new readonly 2D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// A read write instance with the contents of the input array. + [Pure] + public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, T[,] array) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + ReadOnlyTexture2D texture = new(device, array.GetLength(1), array.GetLength(0)); + + texture.SetData(array); + + return texture; + } + + /// + /// Allocates a new readonly 2D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input with the data to copy on the allocated texture. + /// The width of the texture. + /// The height of the texture. + /// A instance with the contents of the input . + [Pure] + public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, ReadOnlySpan span, int width, int height) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + ReadOnlyTexture2D texture = new(device, width, height); + + texture.SetData(span); + + return texture; + } + /// /// Allocates a new readonly 3D texture with the specified parameters. /// @@ -322,6 +418,110 @@ namespace ComputeSharp return texture; } + /// + /// Allocates a new readonly 3D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The width of the texture. + /// The height of the texture. + /// The depth of the texture. + /// A zeroed instance of size [, , ]. + [Pure] + public static ReadOnlyTexture3D AllocateReadOnlyTexture3D(this GraphicsDevice device, int width, int height, int depth) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + return new(device, width, height, depth); + } + + /// + /// Allocates a new readonly 3D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// The width of the texture. + /// The height of the texture. + /// The depth of the texture. + /// A instance with the contents of the input array. + [Pure] + public static ReadOnlyTexture3D AllocateReadOnlyTexture3D(this GraphicsDevice device, T[] array, int width, int height, int depth) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + return device.AllocateReadOnlyTexture3D(array.AsSpan(), width, height, depth); + } + + /// + /// Allocates a new readonly 3D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// The starting offset within to read data from. + /// The width of the texture. + /// The height of the texture. + /// The depth of the texture. + /// A instance with the contents of the input array. + [Pure] + public static ReadOnlyTexture3D AllocateReadOnlyTexture3D(this GraphicsDevice device, T[] array, int offset, int width, int height, int depth) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + return device.AllocateReadOnlyTexture3D(array.AsSpan(offset), width, height, depth); + } + + /// + /// Allocates a new readonly 3D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// A read write instance with the contents of the input array. + /// + /// The source 3D array needs to have each 2D plane stacked on the depth axis. + /// That is, the expected layout of the input array has to be [depth, height, width]. + /// + [Pure] + public static ReadOnlyTexture3D AllocateReadOnlyTexture3D(this GraphicsDevice device, T[,,] array) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + ReadOnlyTexture3D texture = new(device, array.GetLength(2), array.GetLength(1), array.GetLength(0)); + + texture.SetData(array); + + return texture; + } + + /// + /// Allocates a new readonly 3D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input with the data to copy on the allocated texture. + /// The width of the texture. + /// The height of the texture. + /// The depth of the texture. + /// A instance with the contents of the input . + [Pure] + public static ReadOnlyTexture3D AllocateReadOnlyTexture3D(this GraphicsDevice device, ReadOnlySpan span, int width, int height, int depth) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + ReadOnlyTexture3D texture = new(device, width, height, depth); + + texture.SetData(span); + + return texture; + } + /// /// Allocates a new read write buffer with the specified parameters. /// @@ -472,6 +672,80 @@ namespace ComputeSharp return texture; } + /// + /// Allocates a new writeable 2D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The width of the texture. + /// The height of the texture. + /// A zeroed instance of size [, ]. + [Pure] + public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, int width, int height) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + return new(device, width, height); + } + + /// + /// Allocates a new writeable 2D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// The width of the texture. + /// The height of the texture. + /// A instance with the contents of the input array. + [Pure] + public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, T[] array, int width, int height) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + return device.AllocateReadWriteTexture2D(array.AsSpan(), width, height); + } + + /// + /// Allocates a new writeable 2D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// The starting offset within to read data from. + /// The width of the texture. + /// The height of the texture. + /// A instance with the contents of the input array. + [Pure] + public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, T[] array, int offset, int width, int height) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + return device.AllocateReadWriteTexture2D(array.AsSpan(offset), width, height); + } + + /// + /// Allocates a new writeable 2D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// A read write instance with the contents of the input array. + [Pure] + public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, T[,] array) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + ReadWriteTexture2D texture = new(device, array.GetLength(1), array.GetLength(0)); + + texture.SetData(array); + + return texture; + } + /// /// Allocates a new writeable 2D texture with the specified parameters. /// @@ -481,7 +755,7 @@ namespace ComputeSharp /// The input with the data to copy on the allocated texture. /// The width of the texture. /// The height of the texture. - /// A instance with the contents of the input . + /// A instance with the contents of the input . [Pure] public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, ReadOnlySpan span, int width, int height) where T : unmanaged, IUnorm @@ -588,6 +862,110 @@ namespace ComputeSharp return texture; } + /// + /// Allocates a new writeable 3D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The width of the texture. + /// The height of the texture. + /// The depth of the texture. + /// A zeroed instance of size [, ]. + [Pure] + public static ReadWriteTexture3D AllocateReadWriteTexture3D(this GraphicsDevice device, int width, int height, int depth) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + return new(device, width, height, depth); + } + + /// + /// Allocates a new writeable 3D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// The width of the texture. + /// The height of the texture. + /// The depth of the texture. + /// A instance with the contents of the input array. + [Pure] + public static ReadWriteTexture3D AllocateReadWriteTexture3D(this GraphicsDevice device, T[] array, int width, int height, int depth) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + return device.AllocateReadWriteTexture3D(array.AsSpan(), width, height, depth); + } + + /// + /// Allocates a new writeable 3D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// The starting offset within to read data from. + /// The width of the texture. + /// The height of the texture. + /// The depth of the texture. + /// A instance with the contents of the input array. + [Pure] + public static ReadWriteTexture3D AllocateReadWriteTexture3D(this GraphicsDevice device, T[] array, int offset, int width, int height, int depth) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + return device.AllocateReadWriteTexture3D(array.AsSpan(offset), width, height, depth); + } + + /// + /// Allocates a new writeable 3D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input array with the data to copy on the allocated texture. + /// A read write instance with the contents of the input array. + /// + /// The source 3D array needs to have each 2D plane stacked on the depth axis. + /// That is, the expected layout of the input array has to be [depth, height, width]. + /// + [Pure] + public static ReadWriteTexture3D AllocateReadWriteTexture3D(this GraphicsDevice device, T[,,] array) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + ReadWriteTexture3D texture = new(device, array.GetLength(2), array.GetLength(1), array.GetLength(0)); + + texture.SetData(array); + + return texture; + } + + /// + /// Allocates a new writeable 3D texture with the specified parameters. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The input with the data to copy on the allocated texture. + /// The width of the texture. + /// The height of the texture. + /// The depth of the texture. + /// A instance with the contents of the input . + [Pure] + public static ReadWriteTexture3D AllocateReadWriteTexture3D(this GraphicsDevice device, ReadOnlySpan span, int width, int height, int depth) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + ReadWriteTexture3D texture = new(device, width, height, depth); + + texture.SetData(span); + + return texture; + } + /// /// Compiles and runs the input shader on a target instance, with the specified parameters. /// From 92bc95b028431b3ecf040c3a96b5d8e6bf569acc Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 4 Jan 2021 18:23:45 +0100 Subject: [PATCH 10/26] Added more pixel types --- src/ComputeSharp.Core/PixelTypes/R8.cs | 81 +++++++++++++++++ src/ComputeSharp.Core/PixelTypes/Rg16.cs | 89 +++++++++++++++++++ src/ComputeSharp.Core/PixelTypes/Rg32.cs | 89 +++++++++++++++++++ .../Helpers/DXGIFormatHelper.cs | 3 + 4 files changed, 262 insertions(+) create mode 100644 src/ComputeSharp.Core/PixelTypes/R8.cs create mode 100644 src/ComputeSharp.Core/PixelTypes/Rg16.cs create mode 100644 src/ComputeSharp.Core/PixelTypes/Rg32.cs diff --git a/src/ComputeSharp.Core/PixelTypes/R8.cs b/src/ComputeSharp.Core/PixelTypes/R8.cs new file mode 100644 index 00000000..7403ab05 --- /dev/null +++ b/src/ComputeSharp.Core/PixelTypes/R8.cs @@ -0,0 +1,81 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.__Internals; + +#pragma warning disable CS0618 + +namespace ComputeSharp +{ + /// + /// Packed pixel type containing a single 8-bit unsigned normalized channel value. + /// + /// Ranges from [0, 0, 0, 0] to [1, 0, 0, 0] in vector form. + /// + /// + [StructLayout(LayoutKind.Sequential)] + public struct R8 : IEquatable, IUnorm, IUnorm + { + /// + /// The red component. + /// + public byte R; + + /// + /// Initializes a new instance of the struct. + /// + /// The red component. + public R8(byte r) + { + R = r; + } + + /// + /// Gets or sets the packed representation of the Rgba32 struct. + /// + public byte PackedValue + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + readonly get => Unsafe.As(ref Unsafe.AsRef(this)); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => Unsafe.As(ref this) = value; + } + + /// + /// Compares two objects for equality. + /// + /// The on the left side of the operand. + /// The on the right side of the operand. + /// + /// True if the parameter is equal to the parameter; otherwise, false. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator ==(R8 left, R8 right) => left.Equals(right); + + /// + /// Compares two objects for equality. + /// + /// The on the left side of the operand. + /// The on the right side of the operand. + /// + /// True if the parameter is not equal to the parameter; otherwise, false. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator !=(R8 left, R8 right) => !left.Equals(right); + + /// + public override readonly bool Equals(object obj) => obj is R8 R8 && Equals(R8); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool Equals(R8 other) => PackedValue.Equals(other.PackedValue); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override readonly int GetHashCode() => PackedValue.GetHashCode(); + + /// + public override readonly string ToString() => $"{nameof(R8)}({this.R})"; + } +} diff --git a/src/ComputeSharp.Core/PixelTypes/Rg16.cs b/src/ComputeSharp.Core/PixelTypes/Rg16.cs new file mode 100644 index 00000000..d81b2313 --- /dev/null +++ b/src/ComputeSharp.Core/PixelTypes/Rg16.cs @@ -0,0 +1,89 @@ +using System; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.__Internals; + +#pragma warning disable CS0618 + +namespace ComputeSharp +{ + /// + /// Packed pixel type containing two 8-bit unsigned normalized values ranging from 0 to 255. + /// + /// Ranges from [0, 0, 0, 0] to [1, 1, 0, 0] in vector form. + /// + /// + [StructLayout(LayoutKind.Sequential)] + public struct Rg16 : IEquatable, IUnorm, IUnorm, IUnorm + { + /// + /// The red component. + /// + public byte R; + + /// + /// The green component. + /// + public byte G; + + /// + /// Initializes a new instance of the struct. + /// + /// The x-component + /// The y-component + public Rg16(byte r, byte g) + { + R = r; + G = g; + } + + /// + /// Gets or sets the packed representation of the Rg16 struct. + /// + public ushort PackedValue + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + readonly get => Unsafe.As(ref Unsafe.AsRef(this)); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => Unsafe.As(ref this) = value; + } + + /// + /// Compares two objects for equality. + /// + /// The on the left side of the operand. + /// The on the right side of the operand. + /// + /// True if the parameter is equal to the parameter; otherwise, false. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator ==(Rg16 left, Rg16 right) => left.Equals(right); + + /// + /// Compares two objects for equality. + /// + /// The on the left side of the operand. + /// The on the right side of the operand. + /// + /// True if the parameter is not equal to the parameter; otherwise, false. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator !=(Rg16 left, Rg16 right) => !left.Equals(right); + + /// + public override readonly bool Equals(object obj) => obj is Rg16 rgba32 && Equals(rgba32); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool Equals(Rg16 other) => PackedValue.Equals(other.PackedValue); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override readonly int GetHashCode() => PackedValue.GetHashCode(); + + /// + public override readonly string ToString() => $"{nameof(Rg16)}({this.R}, {this.G})"; + } +} diff --git a/src/ComputeSharp.Core/PixelTypes/Rg32.cs b/src/ComputeSharp.Core/PixelTypes/Rg32.cs new file mode 100644 index 00000000..872f07e0 --- /dev/null +++ b/src/ComputeSharp.Core/PixelTypes/Rg32.cs @@ -0,0 +1,89 @@ +using System; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.__Internals; + +#pragma warning disable CS0618 + +namespace ComputeSharp +{ + /// + /// Packed pixel type containing two 16-bit unsigned normalized values ranging from 0 to 255. + /// + /// Ranges from [0, 0, 0, 0] to [1, 1, 0, 0] in vector form. + /// + /// + [StructLayout(LayoutKind.Sequential)] + public struct Rg32 : IEquatable, IUnorm, IUnorm, IUnorm + { + /// + /// The red component. + /// + public ushort R; + + /// + /// The green component. + /// + public ushort G; + + /// + /// Initializes a new instance of the struct. + /// + /// The x-component + /// The y-component + public Rg32(ushort r, ushort g) + { + R = r; + G = g; + } + + /// + /// Gets or sets the packed representation of the Rg32 struct. + /// + public uint PackedValue + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + readonly get => Unsafe.As(ref Unsafe.AsRef(this)); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => Unsafe.As(ref this) = value; + } + + /// + /// Compares two objects for equality. + /// + /// The on the left side of the operand. + /// The on the right side of the operand. + /// + /// True if the parameter is equal to the parameter; otherwise, false. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator ==(Rg32 left, Rg32 right) => left.Equals(right); + + /// + /// Compares two objects for equality. + /// + /// The on the left side of the operand. + /// The on the right side of the operand. + /// + /// True if the parameter is not equal to the parameter; otherwise, false. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator !=(Rg32 left, Rg32 right) => !left.Equals(right); + + /// + public override readonly bool Equals(object obj) => obj is Rg32 rgba32 && Equals(rgba32); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool Equals(Rg32 other) => PackedValue.Equals(other.PackedValue); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override readonly int GetHashCode() => PackedValue.GetHashCode(); + + /// + public override readonly string ToString() => $"{nameof(Rg32)}({this.R}, {this.G})"; + } +} diff --git a/src/ComputeSharp.Graphics/Helpers/DXGIFormatHelper.cs b/src/ComputeSharp.Graphics/Helpers/DXGIFormatHelper.cs index 87596774..6b7319d5 100644 --- a/src/ComputeSharp.Graphics/Helpers/DXGIFormatHelper.cs +++ b/src/ComputeSharp.Graphics/Helpers/DXGIFormatHelper.cs @@ -41,6 +41,9 @@ namespace ComputeSharp.Graphics.Helpers else if (typeof(T) == typeof(Bgra32)) return DXGI_FORMAT_B8G8R8A8_UNORM; else if (typeof(T) == typeof(Rgba32)) return DXGI_FORMAT_R8G8B8A8_UNORM; else if (typeof(T) == typeof(Rgba64)) return DXGI_FORMAT_R16G16B16A16_UNORM; + else if (typeof(T) == typeof(R8)) return DXGI_FORMAT_R8_UNORM; + else if (typeof(T) == typeof(Rg16)) return DXGI_FORMAT_R8G8_UNORM; + else if (typeof(T) == typeof(Rg32)) return DXGI_FORMAT_R16G16_UNORM; else return ThrowHelper.ThrowArgumentException("Invalid texture type"); } } From 1ac1f6afdd3b792d37e75cf3d032b714c1a47cb7 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 4 Jan 2021 19:35:11 +0100 Subject: [PATCH 11/26] Added R16 pixel type --- src/ComputeSharp.Core/PixelTypes/R16.cs | 81 +++++++++++++++++++ src/ComputeSharp.Core/PixelTypes/R8.cs | 2 +- src/ComputeSharp.Core/PixelTypes/Rg16.cs | 2 +- src/ComputeSharp.Core/PixelTypes/Rg32.cs | 2 +- src/ComputeSharp.Core/PixelTypes/Rgba32.cs | 2 +- src/ComputeSharp.Core/PixelTypes/Rgba64.cs | 2 +- .../Helpers/DXGIFormatHelper.cs | 1 + 7 files changed, 87 insertions(+), 5 deletions(-) create mode 100644 src/ComputeSharp.Core/PixelTypes/R16.cs diff --git a/src/ComputeSharp.Core/PixelTypes/R16.cs b/src/ComputeSharp.Core/PixelTypes/R16.cs new file mode 100644 index 00000000..a9fccb92 --- /dev/null +++ b/src/ComputeSharp.Core/PixelTypes/R16.cs @@ -0,0 +1,81 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.__Internals; + +#pragma warning disable CS0618 + +namespace ComputeSharp +{ + /// + /// Packed pixel type containing a single 16-bit unsigned normalized channel value. + /// + /// Ranges from [0, 0, 0, 0] to [1, 0, 0, 0] in vector form. + /// + /// + [StructLayout(LayoutKind.Sequential)] + public struct R16 : IEquatable, IUnorm, IUnorm + { + /// + /// The red component. + /// + public ushort R; + + /// + /// Initializes a new instance of the struct. + /// + /// The red component. + public R16(ushort r) + { + R = r; + } + + /// + /// Gets or sets the packed representation of the struct. + /// + public ushort PackedValue + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + readonly get => Unsafe.As(ref Unsafe.AsRef(this)); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => Unsafe.As(ref this) = value; + } + + /// + /// Compares two objects for equality. + /// + /// The on the left side of the operand. + /// The on the right side of the operand. + /// + /// True if the parameter is equal to the parameter; otherwise, false. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator ==(R16 left, R16 right) => left.Equals(right); + + /// + /// Compares two objects for equality. + /// + /// The on the left side of the operand. + /// The on the right side of the operand. + /// + /// True if the parameter is not equal to the parameter; otherwise, false. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator !=(R16 left, R16 right) => !left.Equals(right); + + /// + public override readonly bool Equals(object obj) => obj is R16 R16 && Equals(R16); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly bool Equals(R16 other) => PackedValue.Equals(other.PackedValue); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override readonly int GetHashCode() => PackedValue.GetHashCode(); + + /// + public override readonly string ToString() => $"{nameof(R16)}({this.R})"; + } +} diff --git a/src/ComputeSharp.Core/PixelTypes/R8.cs b/src/ComputeSharp.Core/PixelTypes/R8.cs index 7403ab05..044c34f1 100644 --- a/src/ComputeSharp.Core/PixelTypes/R8.cs +++ b/src/ComputeSharp.Core/PixelTypes/R8.cs @@ -31,7 +31,7 @@ namespace ComputeSharp } /// - /// Gets or sets the packed representation of the Rgba32 struct. + /// Gets or sets the packed representation of the struct. /// public byte PackedValue { diff --git a/src/ComputeSharp.Core/PixelTypes/Rg16.cs b/src/ComputeSharp.Core/PixelTypes/Rg16.cs index d81b2313..5d6887f6 100644 --- a/src/ComputeSharp.Core/PixelTypes/Rg16.cs +++ b/src/ComputeSharp.Core/PixelTypes/Rg16.cs @@ -39,7 +39,7 @@ namespace ComputeSharp } /// - /// Gets or sets the packed representation of the Rg16 struct. + /// Gets or sets the packed representation of the struct. /// public ushort PackedValue { diff --git a/src/ComputeSharp.Core/PixelTypes/Rg32.cs b/src/ComputeSharp.Core/PixelTypes/Rg32.cs index 872f07e0..36bba66f 100644 --- a/src/ComputeSharp.Core/PixelTypes/Rg32.cs +++ b/src/ComputeSharp.Core/PixelTypes/Rg32.cs @@ -39,7 +39,7 @@ namespace ComputeSharp } /// - /// Gets or sets the packed representation of the Rg32 struct. + /// Gets or sets the packed representation of the struct. /// public uint PackedValue { diff --git a/src/ComputeSharp.Core/PixelTypes/Rgba32.cs b/src/ComputeSharp.Core/PixelTypes/Rgba32.cs index a288d440..e8787029 100644 --- a/src/ComputeSharp.Core/PixelTypes/Rgba32.cs +++ b/src/ComputeSharp.Core/PixelTypes/Rgba32.cs @@ -71,7 +71,7 @@ namespace ComputeSharp } /// - /// Gets or sets the packed representation of the Rgba32 struct. + /// Gets or sets the packed representation of the struct. /// public uint PackedValue { diff --git a/src/ComputeSharp.Core/PixelTypes/Rgba64.cs b/src/ComputeSharp.Core/PixelTypes/Rgba64.cs index 794b85da..835e8c30 100644 --- a/src/ComputeSharp.Core/PixelTypes/Rgba64.cs +++ b/src/ComputeSharp.Core/PixelTypes/Rgba64.cs @@ -71,7 +71,7 @@ namespace ComputeSharp } /// - /// Gets or sets the packed representation of the Rgba64 struct. + /// Gets or sets the packed representation of the struct. /// public ulong PackedValue { diff --git a/src/ComputeSharp.Graphics/Helpers/DXGIFormatHelper.cs b/src/ComputeSharp.Graphics/Helpers/DXGIFormatHelper.cs index 6b7319d5..c12698ae 100644 --- a/src/ComputeSharp.Graphics/Helpers/DXGIFormatHelper.cs +++ b/src/ComputeSharp.Graphics/Helpers/DXGIFormatHelper.cs @@ -42,6 +42,7 @@ namespace ComputeSharp.Graphics.Helpers else if (typeof(T) == typeof(Rgba32)) return DXGI_FORMAT_R8G8B8A8_UNORM; else if (typeof(T) == typeof(Rgba64)) return DXGI_FORMAT_R16G16B16A16_UNORM; else if (typeof(T) == typeof(R8)) return DXGI_FORMAT_R8_UNORM; + else if (typeof(T) == typeof(R16)) return DXGI_FORMAT_R16_UNORM; else if (typeof(T) == typeof(Rg16)) return DXGI_FORMAT_R8G8_UNORM; else if (typeof(T) == typeof(Rg32)) return DXGI_FORMAT_R16G16_UNORM; else return ThrowHelper.ThrowArgumentException("Invalid texture type"); From 5d816d0e9952793237fb9fa77b633100aab73639 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Jan 2021 12:46:29 +0100 Subject: [PATCH 12/26] Added normalized pixel texture allocation tests --- .../Extensions/GraphicsDeviceExtensions.cs | 50 +++++++++++ .../Texture2DTests.Pixels.cs | 87 ++++++++++++++++++ .../Texture3DTests.Pixels.cs | 88 +++++++++++++++++++ 3 files changed, 225 insertions(+) create mode 100644 tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs create mode 100644 tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs diff --git a/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs b/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs index ff9ba47e..f4005f85 100644 --- a/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs +++ b/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs @@ -1,8 +1,11 @@ using System; using System.Diagnostics.Contracts; +using ComputeSharp.__Internals; using ComputeSharp.Graphics; using ComputeSharp.Graphics.Buffers.Abstract; +#pragma warning disable CS0618 + namespace ComputeSharp.Tests.Extensions { /// @@ -52,6 +55,29 @@ namespace ComputeSharp.Tests.Extensions }; } + /// + /// Allocates a new instance of the specified type. + /// + /// The type of items in the texture. + /// The type of pixels used on the GPU side. + /// The target instance to allocate the texture for. + /// The type of texture to allocate. + /// The width of the texture to create. + /// The height of the texture to create. + /// A instance of the requested size. + [Pure] + public static Texture2D AllocateTexture2D(this GraphicsDevice device, Type type, int width, int height) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + return type switch + { + _ when type == typeof(ReadOnlyTexture2D<,>) => device.AllocateReadOnlyTexture2D(width, height), + _ when type == typeof(ReadWriteTexture2D<,>) => device.AllocateReadWriteTexture2D(width, height), + _ => throw new ArgumentException($"Invalid type: {type}", nameof(type)) + }; + } + /// /// Allocates a new instance of the specified type. /// @@ -74,6 +100,30 @@ namespace ComputeSharp.Tests.Extensions }; } + /// + /// Allocates a new instance of the specified type. + /// + /// The type of items in the texture. + /// The type of pixels used on the GPU side. + /// The target instance to allocate the texture for. + /// The type of texture to allocate. + /// The width of the texture to create. + /// The height of the texture to create. + /// The depth of the texture to create. + /// A instance of the requested size. + [Pure] + public static Texture3D AllocateTexture3D(this GraphicsDevice device, Type type, int width, int height, int depth) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + return type switch + { + _ when type == typeof(ReadOnlyTexture3D<,>) => device.AllocateReadOnlyTexture3D(width, height, depth), + _ when type == typeof(ReadWriteTexture3D<,>) => device.AllocateReadWriteTexture3D(width, height, depth), + _ => throw new ArgumentException($"Invalid type: {type}", nameof(type)) + }; + } + /// /// Allocates a new instance of the specified type. /// diff --git a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs new file mode 100644 index 00000000..1b0e1fb0 --- /dev/null +++ b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs @@ -0,0 +1,87 @@ +using System; +using System.Numerics; +using System.Reflection; +using ComputeSharp.__Internals; +using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#pragma warning disable CS0618 + +namespace ComputeSharp.Tests +{ + public partial class Texture2DTests + { + [TestMethod] + [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Bgra32), typeof(Vector4))] + [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Bgra32), typeof(Float4))] + [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Bgra32), typeof(Double4))] + [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(R16), typeof(float))] + [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(R16), typeof(double))] + [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(R8), typeof(float))] + [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(R8), typeof(double))] + [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rg16), typeof(Vector2))] + [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rg16), typeof(Float2))] + [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rg16), typeof(Double2))] + [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rg32), typeof(Vector2))] + [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rg32), typeof(Float2))] + [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rg32), typeof(Double2))] + [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rgba32), typeof(Vector4))] + [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rgba32), typeof(Float4))] + [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rgba32), typeof(Double4))] + [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rgba64), typeof(Vector4))] + [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rgba64), typeof(Float4))] + [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rgba64), typeof(Double4))] + [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Bgra32), typeof(Vector4))] + [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Bgra32), typeof(Float4))] + [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Bgra32), typeof(Double4))] + [DataRow(typeof(ReadWriteTexture2D<,>), typeof(R16), typeof(float))] + [DataRow(typeof(ReadWriteTexture2D<,>), typeof(R16), typeof(double))] + [DataRow(typeof(ReadWriteTexture2D<,>), typeof(R8), typeof(float))] + [DataRow(typeof(ReadWriteTexture2D<,>), typeof(R8), typeof(double))] + [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rg16), typeof(Vector2))] + [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rg16), typeof(Float2))] + [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rg16), typeof(Double2))] + [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rg32), typeof(Vector2))] + [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rg32), typeof(Float2))] + [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rg32), typeof(Double2))] + [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rgba32), typeof(Vector4))] + [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rgba32), typeof(Float4))] + [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rgba32), typeof(Double4))] + [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rgba64), typeof(Vector4))] + [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rgba64), typeof(Float4))] + [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rgba64), typeof(Double4))] + public void Allocate_Uninitialized_Pixel_Ok(Type textureType, Type t, Type tPixel) + { + static void Test(Type textureType) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + using Texture2D texture = Gpu.Default.AllocateTexture2D(textureType, 128, 128); + + Assert.IsNotNull(texture); + Assert.AreEqual(texture.Width, 128); + Assert.AreEqual(texture.Height, 128); + Assert.AreSame(texture.GraphicsDevice, Gpu.Default); + + if (textureType == typeof(ReadOnlyTexture2D<,>)) + { + Assert.IsTrue(texture is ReadOnlyTexture2D); + } + else + { + Assert.IsTrue(texture is ReadWriteTexture2D); + } + } + + try + { + new Action(Test).Method.GetGenericMethodDefinition().MakeGenericMethod(t, tPixel).Invoke(null, new[] { textureType }); + } + catch (TargetInvocationException e) when (e.InnerException is not null) + { + throw e.InnerException; + } + } + } +} diff --git a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs new file mode 100644 index 00000000..0057e024 --- /dev/null +++ b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs @@ -0,0 +1,88 @@ +using System; +using System.Numerics; +using System.Reflection; +using ComputeSharp.__Internals; +using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#pragma warning disable CS0618 + +namespace ComputeSharp.Tests +{ + public partial class Texture3DTests + { + [TestMethod] + [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Bgra32), typeof(Vector4))] + [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Bgra32), typeof(Float4))] + [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Bgra32), typeof(Double4))] + [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(R16), typeof(float))] + [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(R16), typeof(double))] + [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(R8), typeof(float))] + [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(R8), typeof(double))] + [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rg16), typeof(Vector2))] + [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rg16), typeof(Float2))] + [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rg16), typeof(Double2))] + [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rg32), typeof(Vector2))] + [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rg32), typeof(Float2))] + [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rg32), typeof(Double2))] + [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rgba32), typeof(Vector4))] + [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rgba32), typeof(Float4))] + [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rgba32), typeof(Double4))] + [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rgba64), typeof(Vector4))] + [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rgba64), typeof(Float4))] + [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rgba64), typeof(Double4))] + [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Bgra32), typeof(Vector4))] + [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Bgra32), typeof(Float4))] + [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Bgra32), typeof(Double4))] + [DataRow(typeof(ReadWriteTexture3D<,>), typeof(R16), typeof(float))] + [DataRow(typeof(ReadWriteTexture3D<,>), typeof(R16), typeof(double))] + [DataRow(typeof(ReadWriteTexture3D<,>), typeof(R8), typeof(float))] + [DataRow(typeof(ReadWriteTexture3D<,>), typeof(R8), typeof(double))] + [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rg16), typeof(Vector2))] + [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rg16), typeof(Float2))] + [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rg16), typeof(Double2))] + [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rg32), typeof(Vector2))] + [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rg32), typeof(Float2))] + [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rg32), typeof(Double2))] + [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rgba32), typeof(Vector4))] + [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rgba32), typeof(Float4))] + [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rgba32), typeof(Double4))] + [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rgba64), typeof(Vector4))] + [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rgba64), typeof(Float4))] + [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rgba64), typeof(Double4))] + public void Allocate_Uninitialized_Pixel_Ok(Type textureType, Type t, Type tPixel) + { + static void Test(Type textureType) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + using Texture3D texture = Gpu.Default.AllocateTexture3D(textureType, 128, 128, 2); + + Assert.IsNotNull(texture); + Assert.AreEqual(texture.Width, 128); + Assert.AreEqual(texture.Height, 128); + Assert.AreEqual(texture.Depth, 2); + Assert.AreSame(texture.GraphicsDevice, Gpu.Default); + + if (textureType == typeof(ReadOnlyTexture3D<,>)) + { + Assert.IsTrue(texture is ReadOnlyTexture3D); + } + else + { + Assert.IsTrue(texture is ReadWriteTexture3D); + } + } + + try + { + new Action(Test).Method.GetGenericMethodDefinition().MakeGenericMethod(t, tPixel).Invoke(null, new[] { textureType }); + } + catch (TargetInvocationException e) when (e.InnerException is not null) + { + throw e.InnerException; + } + } + } +} From e33c7b927ad37b45a500e2c721a25fc35360697f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Jan 2021 13:24:06 +0100 Subject: [PATCH 13/26] Fixed normalized textures accessors --- .../Buffers/ReadOnlyTexture2D{T,TPixel}.cs | 8 ++++---- .../Buffers/ReadOnlyTexture3D{T,TPixel}.cs | 8 ++++---- .../Buffers/ReadWriteTexture2D{T,TPixel}.cs | 4 ++-- .../Buffers/ReadWriteTexture3D{T,TPixel}.cs | 8 ++++---- 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture2D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture2D{T,TPixel}.cs index 771fb853..ad66a8a2 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture2D{T,TPixel}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture2D{T,TPixel}.cs @@ -33,19 +33,19 @@ namespace ComputeSharp } /// - /// Gets a single value from the current readonly texture. + /// Gets a single value from the current readonly texture. /// /// The horizontal offset of the value to get. /// The vertical offset of the value to get. /// This API can only be used from a compute shader, and will always throw if used anywhere else. - public T this[int x, int y] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyTexture2D)}[int,int]"); + public TPixel this[int x, int y] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyTexture2D)}[int,int]"); /// - /// Gets a single value from the current readonly texture. + /// Gets a single value from the current readonly texture. /// /// The coordinates of the value to get. /// This API can only be used from a compute shader, and will always throw if used anywhere else. - public T this[Int2 xy] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyTexture2D)}[Int2]"); + public TPixel this[Int2 xy] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyTexture2D)}[Int2]"); /// public override string ToString() diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture3D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture3D{T,TPixel}.cs index e0eaedb0..35d64c8e 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture3D{T,TPixel}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture3D{T,TPixel}.cs @@ -34,20 +34,20 @@ namespace ComputeSharp } /// - /// Gets a single value from the current readonly texture. + /// Gets a single value from the current readonly texture. /// /// The horizontal offset of the value to get. /// The vertical offset of the value to get. /// The depthwise offset of the value to get. /// This API can only be used from a compute shader, and will always throw if used anywhere else. - public T this[int x, int y, int z] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyTexture3D)}[int,int,int]"); + public TPixel this[int x, int y, int z] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyTexture3D)}[int,int,int]"); /// - /// Gets a single value from the current readonly texture. + /// Gets a single value from the current readonly texture. /// /// The coordinates of the value to get. /// This API can only be used from a compute shader, and will always throw if used anywhere else. - public T this[Int3 xyz] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyTexture3D)}[Int3]"); + public TPixel this[Int3 xyz] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyTexture3D)}[Int3]"); /// public override string ToString() diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteTexture2D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Buffers/ReadWriteTexture2D{T,TPixel}.cs index a49e97ab..ca284d79 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadWriteTexture2D{T,TPixel}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadWriteTexture2D{T,TPixel}.cs @@ -33,7 +33,7 @@ namespace ComputeSharp } /// - /// Gets a single value from the current writeable texture. + /// Gets a single value from the current writeable texture. /// /// The horizontal offset of the value to get. /// The vertical offset of the value to get. @@ -41,7 +41,7 @@ namespace ComputeSharp public ref TPixel this[int x, int y] => throw new InvalidExecutionContextException($"{nameof(ReadWriteTexture2D)}[int,int]"); /// - /// Gets or sets a single value from the current writeable texture. + /// Gets or sets a single value from the current writeable texture. /// /// The coordinates of the value to get. /// This API can only be used from a compute shader, and will always throw if used anywhere else. diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteTexture3D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Buffers/ReadWriteTexture3D{T,TPixel}.cs index 2d44f219..32acd100 100644 --- a/src/ComputeSharp.Graphics/Buffers/ReadWriteTexture3D{T,TPixel}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ReadWriteTexture3D{T,TPixel}.cs @@ -34,20 +34,20 @@ namespace ComputeSharp } /// - /// Gets a single value from the current writeable texture. + /// Gets a single value from the current writeable texture. /// /// The horizontal offset of the value to get. /// The vertical offset of the value to get. /// The depthwise offset of the value to get. /// This API can only be used from a compute shader, and will always throw if used anywhere else. - public ref T this[int x, int y, int z] => throw new InvalidExecutionContextException($"{nameof(ReadWriteTexture3D)}[int,int,int]"); + public ref TPixel this[int x, int y, int z] => throw new InvalidExecutionContextException($"{nameof(ReadWriteTexture3D)}[int,int,int]"); /// - /// Gets a single value from the current writeable texture. + /// Gets a single value from the current writeable texture. /// /// The coordinates of the value to get. /// This API can only be used from a compute shader, and will always throw if used anywhere else. - public ref T this[Int3 xyz] => throw new InvalidExecutionContextException($"{nameof(ReadWriteTexture3D)}[Int3]"); + public ref TPixel this[Int3 xyz] => throw new InvalidExecutionContextException($"{nameof(ReadWriteTexture3D)}[Int3]"); /// public override string ToString() From 9e0b7404b1c8f7bca606e65d0aa23cb7de8991ef Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Jan 2021 13:40:50 +0100 Subject: [PATCH 14/26] Added T4 templates for normalized 2D texture tests --- .../ComputeSharp.Tests.csproj | 27 ++ .../Texture2DTests.Pixels.g.cs | 394 ++++++++++++++++++ .../Texture2DTests.Pixels.tt | 81 ++++ 3 files changed, 502 insertions(+) create mode 100644 tests/ComputeSharp.Tests/Texture2DTests.Pixels.g.cs create mode 100644 tests/ComputeSharp.Tests/Texture2DTests.Pixels.tt diff --git a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj index d4f1c821..92a907e5 100644 --- a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj +++ b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj @@ -5,6 +5,14 @@ false + + + True + True + Texture2DTests.Pixels.tt + + + @@ -20,4 +28,23 @@ PrivateAssets="contentfiles;build"/> + + + TextTemplatingFileGenerator + Texture2DTests.Pixels.g.cs + + + + + + + + + + True + True + Texture2DTests.Pixels.tt + + + diff --git a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.g.cs b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.g.cs new file mode 100644 index 00000000..607b2168 --- /dev/null +++ b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.g.cs @@ -0,0 +1,394 @@ +using System; +using System.Numerics; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.Tests +{ + public partial class Texture2DTests + { + [TestMethod] + [DataRow(typeof(Bgra32), typeof(Vector4))] + [DataRow(typeof(Bgra32), typeof(Float4))] + [DataRow(typeof(Bgra32), typeof(Double4))] + [DataRow(typeof(R16), typeof(float))] + [DataRow(typeof(R16), typeof(double))] + [DataRow(typeof(R8), typeof(float))] + [DataRow(typeof(R8), typeof(double))] + [DataRow(typeof(Rg16), typeof(Vector2))] + [DataRow(typeof(Rg16), typeof(Float2))] + [DataRow(typeof(Rg16), typeof(Double2))] + [DataRow(typeof(Rg32), typeof(Vector2))] + [DataRow(typeof(Rg32), typeof(Float2))] + [DataRow(typeof(Rg32), typeof(Double2))] + [DataRow(typeof(Rgba32), typeof(Vector4))] + [DataRow(typeof(Rgba32), typeof(Float4))] + [DataRow(typeof(Rgba32), typeof(Double4))] + [DataRow(typeof(Rgba64), typeof(Vector4))] + [DataRow(typeof(Rgba64), typeof(Float4))] + [DataRow(typeof(Rgba64), typeof(Double4))] + public void Dispatch_NormalizedTexture2D(Type t, Type tPixel) + { + if (t == typeof(Bgra32) && tPixel == typeof(Vector4)) + { + using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); + using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); + + Gpu.Default.For(128, 128, new Shader_Unorm_Bgra32_Vector4(source, destination)); + } + if (t == typeof(Bgra32) && tPixel == typeof(Float4)) + { + using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); + using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); + + Gpu.Default.For(128, 128, new Shader_Unorm_Bgra32_Float4(source, destination)); + } + if (t == typeof(Bgra32) && tPixel == typeof(Double4)) + { + using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); + using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); + + Gpu.Default.For(128, 128, new Shader_Unorm_Bgra32_Double4(source, destination)); + } + if (t == typeof(R16) && tPixel == typeof(float)) + { + using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); + using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); + + Gpu.Default.For(128, 128, new Shader_Unorm_R16_float(source, destination)); + } + if (t == typeof(R16) && tPixel == typeof(double)) + { + using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); + using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); + + Gpu.Default.For(128, 128, new Shader_Unorm_R16_double(source, destination)); + } + if (t == typeof(R8) && tPixel == typeof(float)) + { + using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); + using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); + + Gpu.Default.For(128, 128, new Shader_Unorm_R8_float(source, destination)); + } + if (t == typeof(R8) && tPixel == typeof(double)) + { + using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); + using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); + + Gpu.Default.For(128, 128, new Shader_Unorm_R8_double(source, destination)); + } + if (t == typeof(Rg16) && tPixel == typeof(Vector2)) + { + using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); + using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); + + Gpu.Default.For(128, 128, new Shader_Unorm_Rg16_Vector2(source, destination)); + } + if (t == typeof(Rg16) && tPixel == typeof(Float2)) + { + using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); + using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); + + Gpu.Default.For(128, 128, new Shader_Unorm_Rg16_Float2(source, destination)); + } + if (t == typeof(Rg16) && tPixel == typeof(Double2)) + { + using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); + using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); + + Gpu.Default.For(128, 128, new Shader_Unorm_Rg16_Double2(source, destination)); + } + if (t == typeof(Rg32) && tPixel == typeof(Vector2)) + { + using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); + using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); + + Gpu.Default.For(128, 128, new Shader_Unorm_Rg32_Vector2(source, destination)); + } + if (t == typeof(Rg32) && tPixel == typeof(Float2)) + { + using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); + using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); + + Gpu.Default.For(128, 128, new Shader_Unorm_Rg32_Float2(source, destination)); + } + if (t == typeof(Rg32) && tPixel == typeof(Double2)) + { + using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); + using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); + + Gpu.Default.For(128, 128, new Shader_Unorm_Rg32_Double2(source, destination)); + } + if (t == typeof(Rgba32) && tPixel == typeof(Vector4)) + { + using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); + using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); + + Gpu.Default.For(128, 128, new Shader_Unorm_Rgba32_Vector4(source, destination)); + } + if (t == typeof(Rgba32) && tPixel == typeof(Float4)) + { + using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); + using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); + + Gpu.Default.For(128, 128, new Shader_Unorm_Rgba32_Float4(source, destination)); + } + if (t == typeof(Rgba32) && tPixel == typeof(Double4)) + { + using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); + using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); + + Gpu.Default.For(128, 128, new Shader_Unorm_Rgba32_Double4(source, destination)); + } + if (t == typeof(Rgba64) && tPixel == typeof(Vector4)) + { + using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); + using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); + + Gpu.Default.For(128, 128, new Shader_Unorm_Rgba64_Vector4(source, destination)); + } + if (t == typeof(Rgba64) && tPixel == typeof(Float4)) + { + using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); + using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); + + Gpu.Default.For(128, 128, new Shader_Unorm_Rgba64_Float4(source, destination)); + } + if (t == typeof(Rgba64) && tPixel == typeof(Double4)) + { + using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); + using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); + + Gpu.Default.For(128, 128, new Shader_Unorm_Rgba64_Double4(source, destination)); + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Bgra32_Vector4 : IComputeShader + { + public readonly ReadOnlyTexture2D source; + public readonly ReadWriteTexture2D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Bgra32_Float4 : IComputeShader + { + public readonly ReadOnlyTexture2D source; + public readonly ReadWriteTexture2D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Bgra32_Double4 : IComputeShader + { + public readonly ReadOnlyTexture2D source; + public readonly ReadWriteTexture2D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_R16_float : IComputeShader + { + public readonly ReadOnlyTexture2D source; + public readonly ReadWriteTexture2D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_R16_double : IComputeShader + { + public readonly ReadOnlyTexture2D source; + public readonly ReadWriteTexture2D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_R8_float : IComputeShader + { + public readonly ReadOnlyTexture2D source; + public readonly ReadWriteTexture2D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_R8_double : IComputeShader + { + public readonly ReadOnlyTexture2D source; + public readonly ReadWriteTexture2D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rg16_Vector2 : IComputeShader + { + public readonly ReadOnlyTexture2D source; + public readonly ReadWriteTexture2D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rg16_Float2 : IComputeShader + { + public readonly ReadOnlyTexture2D source; + public readonly ReadWriteTexture2D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rg16_Double2 : IComputeShader + { + public readonly ReadOnlyTexture2D source; + public readonly ReadWriteTexture2D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rg32_Vector2 : IComputeShader + { + public readonly ReadOnlyTexture2D source; + public readonly ReadWriteTexture2D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rg32_Float2 : IComputeShader + { + public readonly ReadOnlyTexture2D source; + public readonly ReadWriteTexture2D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rg32_Double2 : IComputeShader + { + public readonly ReadOnlyTexture2D source; + public readonly ReadWriteTexture2D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rgba32_Vector4 : IComputeShader + { + public readonly ReadOnlyTexture2D source; + public readonly ReadWriteTexture2D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rgba32_Float4 : IComputeShader + { + public readonly ReadOnlyTexture2D source; + public readonly ReadWriteTexture2D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rgba32_Double4 : IComputeShader + { + public readonly ReadOnlyTexture2D source; + public readonly ReadWriteTexture2D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rgba64_Vector4 : IComputeShader + { + public readonly ReadOnlyTexture2D source; + public readonly ReadWriteTexture2D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rgba64_Float4 : IComputeShader + { + public readonly ReadOnlyTexture2D source; + public readonly ReadWriteTexture2D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rgba64_Double4 : IComputeShader + { + public readonly ReadOnlyTexture2D source; + public readonly ReadWriteTexture2D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + } + } + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.tt b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.tt new file mode 100644 index 00000000..a69d9e3b --- /dev/null +++ b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.tt @@ -0,0 +1,81 @@ +<#@ template debug="false" hostspecific="false" language="C#" #> +<#@ assembly name="System.Core" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.Text" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ output extension=".g.cs"#> +<# +var typesMap = new Dictionary +{ + ["Bgra32"] = new[] { "Vector4", "Float4", "Double4" }, + ["R16"] = new[] { "float", "double" }, + ["R8"] = new[] { "float", "double" }, + ["Rg16"] = new[] { "Vector2", "Float2", "Double2" }, + ["Rg32"] = new[] { "Vector2", "Float2", "Double2" }, + ["Rgba32"] = new[] { "Vector4", "Float4", "Double4" }, + ["Rgba64"] = new[] { "Vector4", "Float4", "Double4" } +}; + +IEnumerable<(string T, string TPixel)> EnumerateTypes() +{ + foreach (var pair in typesMap) + foreach (var tPixel in pair.Value) + yield return (pair.Key, tPixel); +} +#> +using System; +using System.Numerics; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.Tests +{ + public partial class Texture2DTests + { + [TestMethod] +<# +foreach (var (t, tPixel) in EnumerateTypes()) +{ +#> + [DataRow(typeof(<#=t#>), typeof(<#=tPixel#>))] +<# +} +#> + public void Dispatch_NormalizedTexture2D(Type t, Type tPixel) + { +<# +foreach (var (t, tPixel) in EnumerateTypes()) +{ +#> + if (t == typeof(<#=t#>) && tPixel == typeof(<#=tPixel#>)) + { + using ReadOnlyTexture2D<<#=t#>, <#=tPixel#>> source = Gpu.Default.AllocateReadOnlyTexture2D<<#=t#>, <#=tPixel#>>(128, 128); + using ReadWriteTexture2D<<#=t#>, <#=tPixel#>> destination = Gpu.Default.AllocateReadWriteTexture2D<<#=t#>, <#=tPixel#>>(128, 128); + + Gpu.Default.For(128, 128, new Shader_Unorm_<#=t#>_<#=tPixel#>(source, destination)); + } +<# +} +#> + } +<# + +foreach (var (t, tPixel) in EnumerateTypes()) +{ +#> + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_<#=t#>_<#=tPixel#> : IComputeShader + { + public readonly ReadOnlyTexture2D<<#=t#>, <#=tPixel#>> source; + public readonly ReadWriteTexture2D<<#=t#>, <#=tPixel#>> destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + } + } +<# +} +#> + } +} \ No newline at end of file From 763f7e61f455f67ece44b015d7a51573a5d4a829 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Jan 2021 13:48:37 +0100 Subject: [PATCH 15/26] Removed unorm Double[N] options --- src/ComputeSharp.Core/PixelTypes/Bgra32.cs | 2 +- src/ComputeSharp.Core/PixelTypes/R16.cs | 2 +- src/ComputeSharp.Core/PixelTypes/R8.cs | 2 +- src/ComputeSharp.Core/PixelTypes/Rg16.cs | 2 +- src/ComputeSharp.Core/PixelTypes/Rg32.cs | 2 +- src/ComputeSharp.Core/PixelTypes/Rgba32.cs | 2 +- src/ComputeSharp.Core/PixelTypes/Rgba64.cs | 2 +- .../Texture2DTests.Pixels.cs | 14 -- .../Texture2DTests.Pixels.g.cs | 140 ------------------ .../Texture2DTests.Pixels.tt | 14 +- .../Texture3DTests.Pixels.cs | 14 -- 11 files changed, 14 insertions(+), 182 deletions(-) diff --git a/src/ComputeSharp.Core/PixelTypes/Bgra32.cs b/src/ComputeSharp.Core/PixelTypes/Bgra32.cs index 1b3f7ea8..3a9172d2 100644 --- a/src/ComputeSharp.Core/PixelTypes/Bgra32.cs +++ b/src/ComputeSharp.Core/PixelTypes/Bgra32.cs @@ -18,7 +18,7 @@ namespace ComputeSharp /// /// This struct is fully mutable. [StructLayout(LayoutKind.Sequential)] - public struct Bgra32 : IEquatable, IUnorm, IUnorm, IUnorm + public struct Bgra32 : IEquatable, IUnorm, IUnorm { /// /// The blue component. diff --git a/src/ComputeSharp.Core/PixelTypes/R16.cs b/src/ComputeSharp.Core/PixelTypes/R16.cs index a9fccb92..1cf56e8d 100644 --- a/src/ComputeSharp.Core/PixelTypes/R16.cs +++ b/src/ComputeSharp.Core/PixelTypes/R16.cs @@ -14,7 +14,7 @@ namespace ComputeSharp /// /// [StructLayout(LayoutKind.Sequential)] - public struct R16 : IEquatable, IUnorm, IUnorm + public struct R16 : IEquatable, IUnorm { /// /// The red component. diff --git a/src/ComputeSharp.Core/PixelTypes/R8.cs b/src/ComputeSharp.Core/PixelTypes/R8.cs index 044c34f1..a5c4fbe1 100644 --- a/src/ComputeSharp.Core/PixelTypes/R8.cs +++ b/src/ComputeSharp.Core/PixelTypes/R8.cs @@ -14,7 +14,7 @@ namespace ComputeSharp /// /// [StructLayout(LayoutKind.Sequential)] - public struct R8 : IEquatable, IUnorm, IUnorm + public struct R8 : IEquatable, IUnorm { /// /// The red component. diff --git a/src/ComputeSharp.Core/PixelTypes/Rg16.cs b/src/ComputeSharp.Core/PixelTypes/Rg16.cs index 5d6887f6..cf294abb 100644 --- a/src/ComputeSharp.Core/PixelTypes/Rg16.cs +++ b/src/ComputeSharp.Core/PixelTypes/Rg16.cs @@ -15,7 +15,7 @@ namespace ComputeSharp /// /// [StructLayout(LayoutKind.Sequential)] - public struct Rg16 : IEquatable, IUnorm, IUnorm, IUnorm + public struct Rg16 : IEquatable, IUnorm, IUnorm { /// /// The red component. diff --git a/src/ComputeSharp.Core/PixelTypes/Rg32.cs b/src/ComputeSharp.Core/PixelTypes/Rg32.cs index 36bba66f..3ad82522 100644 --- a/src/ComputeSharp.Core/PixelTypes/Rg32.cs +++ b/src/ComputeSharp.Core/PixelTypes/Rg32.cs @@ -15,7 +15,7 @@ namespace ComputeSharp /// /// [StructLayout(LayoutKind.Sequential)] - public struct Rg32 : IEquatable, IUnorm, IUnorm, IUnorm + public struct Rg32 : IEquatable, IUnorm, IUnorm { /// /// The red component. diff --git a/src/ComputeSharp.Core/PixelTypes/Rgba32.cs b/src/ComputeSharp.Core/PixelTypes/Rgba32.cs index e8787029..75b25d60 100644 --- a/src/ComputeSharp.Core/PixelTypes/Rgba32.cs +++ b/src/ComputeSharp.Core/PixelTypes/Rgba32.cs @@ -17,7 +17,7 @@ namespace ComputeSharp /// /// This struct is fully mutable. [StructLayout(LayoutKind.Sequential)] - public struct Rgba32 : IEquatable, IUnorm, IUnorm, IUnorm + public struct Rgba32 : IEquatable, IUnorm, IUnorm { /// /// The red component. diff --git a/src/ComputeSharp.Core/PixelTypes/Rgba64.cs b/src/ComputeSharp.Core/PixelTypes/Rgba64.cs index 835e8c30..4fd444e1 100644 --- a/src/ComputeSharp.Core/PixelTypes/Rgba64.cs +++ b/src/ComputeSharp.Core/PixelTypes/Rgba64.cs @@ -17,7 +17,7 @@ namespace ComputeSharp /// /// This struct is fully mutable. [StructLayout(LayoutKind.Sequential)] - public struct Rgba64 : IEquatable, IUnorm, IUnorm, IUnorm + public struct Rgba64 : IEquatable, IUnorm, IUnorm { /// /// The red component. diff --git a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs index 1b0e1fb0..78efd8c9 100644 --- a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs +++ b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs @@ -15,42 +15,28 @@ namespace ComputeSharp.Tests [TestMethod] [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Bgra32), typeof(Vector4))] [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Bgra32), typeof(Float4))] - [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Bgra32), typeof(Double4))] [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(R16), typeof(float))] - [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(R16), typeof(double))] [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(R8), typeof(float))] - [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(R8), typeof(double))] [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rg16), typeof(Vector2))] [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rg16), typeof(Float2))] - [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rg16), typeof(Double2))] [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rg32), typeof(Vector2))] [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rg32), typeof(Float2))] - [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rg32), typeof(Double2))] [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rgba32), typeof(Vector4))] [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rgba32), typeof(Float4))] - [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rgba32), typeof(Double4))] [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rgba64), typeof(Vector4))] [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rgba64), typeof(Float4))] - [DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rgba64), typeof(Double4))] [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Bgra32), typeof(Vector4))] [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Bgra32), typeof(Float4))] - [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Bgra32), typeof(Double4))] [DataRow(typeof(ReadWriteTexture2D<,>), typeof(R16), typeof(float))] - [DataRow(typeof(ReadWriteTexture2D<,>), typeof(R16), typeof(double))] [DataRow(typeof(ReadWriteTexture2D<,>), typeof(R8), typeof(float))] - [DataRow(typeof(ReadWriteTexture2D<,>), typeof(R8), typeof(double))] [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rg16), typeof(Vector2))] [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rg16), typeof(Float2))] - [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rg16), typeof(Double2))] [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rg32), typeof(Vector2))] [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rg32), typeof(Float2))] - [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rg32), typeof(Double2))] [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rgba32), typeof(Vector4))] [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rgba32), typeof(Float4))] - [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rgba32), typeof(Double4))] [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rgba64), typeof(Vector4))] [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rgba64), typeof(Float4))] - [DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rgba64), typeof(Double4))] public void Allocate_Uninitialized_Pixel_Ok(Type textureType, Type t, Type tPixel) { static void Test(Type textureType) diff --git a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.g.cs b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.g.cs index 607b2168..08039596 100644 --- a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.g.cs +++ b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.g.cs @@ -9,23 +9,16 @@ namespace ComputeSharp.Tests [TestMethod] [DataRow(typeof(Bgra32), typeof(Vector4))] [DataRow(typeof(Bgra32), typeof(Float4))] - [DataRow(typeof(Bgra32), typeof(Double4))] [DataRow(typeof(R16), typeof(float))] - [DataRow(typeof(R16), typeof(double))] [DataRow(typeof(R8), typeof(float))] - [DataRow(typeof(R8), typeof(double))] [DataRow(typeof(Rg16), typeof(Vector2))] [DataRow(typeof(Rg16), typeof(Float2))] - [DataRow(typeof(Rg16), typeof(Double2))] [DataRow(typeof(Rg32), typeof(Vector2))] [DataRow(typeof(Rg32), typeof(Float2))] - [DataRow(typeof(Rg32), typeof(Double2))] [DataRow(typeof(Rgba32), typeof(Vector4))] [DataRow(typeof(Rgba32), typeof(Float4))] - [DataRow(typeof(Rgba32), typeof(Double4))] [DataRow(typeof(Rgba64), typeof(Vector4))] [DataRow(typeof(Rgba64), typeof(Float4))] - [DataRow(typeof(Rgba64), typeof(Double4))] public void Dispatch_NormalizedTexture2D(Type t, Type tPixel) { if (t == typeof(Bgra32) && tPixel == typeof(Vector4)) @@ -42,13 +35,6 @@ namespace ComputeSharp.Tests Gpu.Default.For(128, 128, new Shader_Unorm_Bgra32_Float4(source, destination)); } - if (t == typeof(Bgra32) && tPixel == typeof(Double4)) - { - using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); - using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); - - Gpu.Default.For(128, 128, new Shader_Unorm_Bgra32_Double4(source, destination)); - } if (t == typeof(R16) && tPixel == typeof(float)) { using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); @@ -56,13 +42,6 @@ namespace ComputeSharp.Tests Gpu.Default.For(128, 128, new Shader_Unorm_R16_float(source, destination)); } - if (t == typeof(R16) && tPixel == typeof(double)) - { - using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); - using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); - - Gpu.Default.For(128, 128, new Shader_Unorm_R16_double(source, destination)); - } if (t == typeof(R8) && tPixel == typeof(float)) { using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); @@ -70,13 +49,6 @@ namespace ComputeSharp.Tests Gpu.Default.For(128, 128, new Shader_Unorm_R8_float(source, destination)); } - if (t == typeof(R8) && tPixel == typeof(double)) - { - using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); - using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); - - Gpu.Default.For(128, 128, new Shader_Unorm_R8_double(source, destination)); - } if (t == typeof(Rg16) && tPixel == typeof(Vector2)) { using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); @@ -91,13 +63,6 @@ namespace ComputeSharp.Tests Gpu.Default.For(128, 128, new Shader_Unorm_Rg16_Float2(source, destination)); } - if (t == typeof(Rg16) && tPixel == typeof(Double2)) - { - using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); - using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); - - Gpu.Default.For(128, 128, new Shader_Unorm_Rg16_Double2(source, destination)); - } if (t == typeof(Rg32) && tPixel == typeof(Vector2)) { using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); @@ -112,13 +77,6 @@ namespace ComputeSharp.Tests Gpu.Default.For(128, 128, new Shader_Unorm_Rg32_Float2(source, destination)); } - if (t == typeof(Rg32) && tPixel == typeof(Double2)) - { - using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); - using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); - - Gpu.Default.For(128, 128, new Shader_Unorm_Rg32_Double2(source, destination)); - } if (t == typeof(Rgba32) && tPixel == typeof(Vector4)) { using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); @@ -133,13 +91,6 @@ namespace ComputeSharp.Tests Gpu.Default.For(128, 128, new Shader_Unorm_Rgba32_Float4(source, destination)); } - if (t == typeof(Rgba32) && tPixel == typeof(Double4)) - { - using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); - using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); - - Gpu.Default.For(128, 128, new Shader_Unorm_Rgba32_Double4(source, destination)); - } if (t == typeof(Rgba64) && tPixel == typeof(Vector4)) { using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); @@ -154,13 +105,6 @@ namespace ComputeSharp.Tests Gpu.Default.For(128, 128, new Shader_Unorm_Rgba64_Float4(source, destination)); } - if (t == typeof(Rgba64) && tPixel == typeof(Double4)) - { - using ReadOnlyTexture2D source = Gpu.Default.AllocateReadOnlyTexture2D(128, 128); - using ReadWriteTexture2D destination = Gpu.Default.AllocateReadWriteTexture2D(128, 128); - - Gpu.Default.For(128, 128, new Shader_Unorm_Rgba64_Double4(source, destination)); - } } [AutoConstructor] @@ -187,18 +131,6 @@ namespace ComputeSharp.Tests } } - [AutoConstructor] - internal readonly partial struct Shader_Unorm_Bgra32_Double4 : IComputeShader - { - public readonly ReadOnlyTexture2D source; - public readonly ReadWriteTexture2D destination; - - public void Execute(ThreadIds ids) - { - destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; - } - } - [AutoConstructor] internal readonly partial struct Shader_Unorm_R16_float : IComputeShader { @@ -211,18 +143,6 @@ namespace ComputeSharp.Tests } } - [AutoConstructor] - internal readonly partial struct Shader_Unorm_R16_double : IComputeShader - { - public readonly ReadOnlyTexture2D source; - public readonly ReadWriteTexture2D destination; - - public void Execute(ThreadIds ids) - { - destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; - } - } - [AutoConstructor] internal readonly partial struct Shader_Unorm_R8_float : IComputeShader { @@ -235,18 +155,6 @@ namespace ComputeSharp.Tests } } - [AutoConstructor] - internal readonly partial struct Shader_Unorm_R8_double : IComputeShader - { - public readonly ReadOnlyTexture2D source; - public readonly ReadWriteTexture2D destination; - - public void Execute(ThreadIds ids) - { - destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; - } - } - [AutoConstructor] internal readonly partial struct Shader_Unorm_Rg16_Vector2 : IComputeShader { @@ -271,18 +179,6 @@ namespace ComputeSharp.Tests } } - [AutoConstructor] - internal readonly partial struct Shader_Unorm_Rg16_Double2 : IComputeShader - { - public readonly ReadOnlyTexture2D source; - public readonly ReadWriteTexture2D destination; - - public void Execute(ThreadIds ids) - { - destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; - } - } - [AutoConstructor] internal readonly partial struct Shader_Unorm_Rg32_Vector2 : IComputeShader { @@ -307,18 +203,6 @@ namespace ComputeSharp.Tests } } - [AutoConstructor] - internal readonly partial struct Shader_Unorm_Rg32_Double2 : IComputeShader - { - public readonly ReadOnlyTexture2D source; - public readonly ReadWriteTexture2D destination; - - public void Execute(ThreadIds ids) - { - destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; - } - } - [AutoConstructor] internal readonly partial struct Shader_Unorm_Rgba32_Vector4 : IComputeShader { @@ -343,18 +227,6 @@ namespace ComputeSharp.Tests } } - [AutoConstructor] - internal readonly partial struct Shader_Unorm_Rgba32_Double4 : IComputeShader - { - public readonly ReadOnlyTexture2D source; - public readonly ReadWriteTexture2D destination; - - public void Execute(ThreadIds ids) - { - destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; - } - } - [AutoConstructor] internal readonly partial struct Shader_Unorm_Rgba64_Vector4 : IComputeShader { @@ -378,17 +250,5 @@ namespace ComputeSharp.Tests destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; } } - - [AutoConstructor] - internal readonly partial struct Shader_Unorm_Rgba64_Double4 : IComputeShader - { - public readonly ReadOnlyTexture2D source; - public readonly ReadWriteTexture2D destination; - - public void Execute(ThreadIds ids) - { - destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; - } - } } } \ No newline at end of file diff --git a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.tt b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.tt index a69d9e3b..33775291 100644 --- a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.tt +++ b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.tt @@ -7,13 +7,13 @@ <# var typesMap = new Dictionary { - ["Bgra32"] = new[] { "Vector4", "Float4", "Double4" }, - ["R16"] = new[] { "float", "double" }, - ["R8"] = new[] { "float", "double" }, - ["Rg16"] = new[] { "Vector2", "Float2", "Double2" }, - ["Rg32"] = new[] { "Vector2", "Float2", "Double2" }, - ["Rgba32"] = new[] { "Vector4", "Float4", "Double4" }, - ["Rgba64"] = new[] { "Vector4", "Float4", "Double4" } + ["Bgra32"] = new[] { "Vector4", "Float4" }, + ["R16"] = new[] { "float" }, + ["R8"] = new[] { "float" }, + ["Rg16"] = new[] { "Vector2", "Float2" }, + ["Rg32"] = new[] { "Vector2", "Float2" }, + ["Rgba32"] = new[] { "Vector4", "Float4" }, + ["Rgba64"] = new[] { "Vector4", "Float4" } }; IEnumerable<(string T, string TPixel)> EnumerateTypes() diff --git a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs index 0057e024..673f6f77 100644 --- a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs +++ b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs @@ -15,42 +15,28 @@ namespace ComputeSharp.Tests [TestMethod] [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Bgra32), typeof(Vector4))] [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Bgra32), typeof(Float4))] - [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Bgra32), typeof(Double4))] [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(R16), typeof(float))] - [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(R16), typeof(double))] [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(R8), typeof(float))] - [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(R8), typeof(double))] [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rg16), typeof(Vector2))] [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rg16), typeof(Float2))] - [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rg16), typeof(Double2))] [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rg32), typeof(Vector2))] [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rg32), typeof(Float2))] - [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rg32), typeof(Double2))] [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rgba32), typeof(Vector4))] [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rgba32), typeof(Float4))] - [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rgba32), typeof(Double4))] [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rgba64), typeof(Vector4))] [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rgba64), typeof(Float4))] - [DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rgba64), typeof(Double4))] [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Bgra32), typeof(Vector4))] [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Bgra32), typeof(Float4))] - [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Bgra32), typeof(Double4))] [DataRow(typeof(ReadWriteTexture3D<,>), typeof(R16), typeof(float))] - [DataRow(typeof(ReadWriteTexture3D<,>), typeof(R16), typeof(double))] [DataRow(typeof(ReadWriteTexture3D<,>), typeof(R8), typeof(float))] - [DataRow(typeof(ReadWriteTexture3D<,>), typeof(R8), typeof(double))] [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rg16), typeof(Vector2))] [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rg16), typeof(Float2))] - [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rg16), typeof(Double2))] [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rg32), typeof(Vector2))] [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rg32), typeof(Float2))] - [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rg32), typeof(Double2))] [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rgba32), typeof(Vector4))] [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rgba32), typeof(Float4))] - [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rgba32), typeof(Double4))] [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rgba64), typeof(Vector4))] [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rgba64), typeof(Float4))] - [DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rgba64), typeof(Double4))] public void Allocate_Uninitialized_Pixel_Ok(Type textureType, Type t, Type tPixel) { static void Test(Type textureType) From 66744990f253330c2159e89baf98941b2132cd57 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Jan 2021 13:51:06 +0100 Subject: [PATCH 16/26] Added T4 templates for normalized 3D texture tests --- .../ComputeSharp.Tests.csproj | 17 +- .../Texture3DTests.Pixels.g.cs | 254 ++++++++++++++++++ .../Texture3DTests.Pixels.tt | 81 ++++++ 3 files changed, 344 insertions(+), 8 deletions(-) create mode 100644 tests/ComputeSharp.Tests/Texture3DTests.Pixels.g.cs create mode 100644 tests/ComputeSharp.Tests/Texture3DTests.Pixels.tt diff --git a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj index 92a907e5..aae52469 100644 --- a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj +++ b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj @@ -5,14 +5,6 @@ false - - - True - True - Texture2DTests.Pixels.tt - - - @@ -33,6 +25,10 @@ TextTemplatingFileGenerator Texture2DTests.Pixels.g.cs + + TextTemplatingFileGenerator + Texture3DTests.Pixels.g.cs + @@ -45,6 +41,11 @@ True Texture2DTests.Pixels.tt + + True + True + Texture3DTests.Pixels.tt + diff --git a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.g.cs b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.g.cs new file mode 100644 index 00000000..3c1e4955 --- /dev/null +++ b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.g.cs @@ -0,0 +1,254 @@ +using System; +using System.Numerics; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.Tests +{ + public partial class Texture3DTests + { + [TestMethod] + [DataRow(typeof(Bgra32), typeof(Vector4))] + [DataRow(typeof(Bgra32), typeof(Float4))] + [DataRow(typeof(R16), typeof(float))] + [DataRow(typeof(R8), typeof(float))] + [DataRow(typeof(Rg16), typeof(Vector2))] + [DataRow(typeof(Rg16), typeof(Float2))] + [DataRow(typeof(Rg32), typeof(Vector2))] + [DataRow(typeof(Rg32), typeof(Float2))] + [DataRow(typeof(Rgba32), typeof(Vector4))] + [DataRow(typeof(Rgba32), typeof(Float4))] + [DataRow(typeof(Rgba64), typeof(Vector4))] + [DataRow(typeof(Rgba64), typeof(Float4))] + public void Dispatch_NormalizedTexture3D(Type t, Type tPixel) + { + if (t == typeof(Bgra32) && tPixel == typeof(Vector4)) + { + using ReadOnlyTexture3D source = Gpu.Default.AllocateReadOnlyTexture3D(128, 128, 2); + using ReadWriteTexture3D destination = Gpu.Default.AllocateReadWriteTexture3D(128, 128, 2); + + Gpu.Default.For(128, 128, 2, new Shader_Unorm_Bgra32_Vector4(source, destination)); + } + if (t == typeof(Bgra32) && tPixel == typeof(Float4)) + { + using ReadOnlyTexture3D source = Gpu.Default.AllocateReadOnlyTexture3D(128, 128, 2); + using ReadWriteTexture3D destination = Gpu.Default.AllocateReadWriteTexture3D(128, 128, 2); + + Gpu.Default.For(128, 128, 2, new Shader_Unorm_Bgra32_Float4(source, destination)); + } + if (t == typeof(R16) && tPixel == typeof(float)) + { + using ReadOnlyTexture3D source = Gpu.Default.AllocateReadOnlyTexture3D(128, 128, 2); + using ReadWriteTexture3D destination = Gpu.Default.AllocateReadWriteTexture3D(128, 128, 2); + + Gpu.Default.For(128, 128, 2, new Shader_Unorm_R16_float(source, destination)); + } + if (t == typeof(R8) && tPixel == typeof(float)) + { + using ReadOnlyTexture3D source = Gpu.Default.AllocateReadOnlyTexture3D(128, 128, 2); + using ReadWriteTexture3D destination = Gpu.Default.AllocateReadWriteTexture3D(128, 128, 2); + + Gpu.Default.For(128, 128, 2, new Shader_Unorm_R8_float(source, destination)); + } + if (t == typeof(Rg16) && tPixel == typeof(Vector2)) + { + using ReadOnlyTexture3D source = Gpu.Default.AllocateReadOnlyTexture3D(128, 128, 2); + using ReadWriteTexture3D destination = Gpu.Default.AllocateReadWriteTexture3D(128, 128, 2); + + Gpu.Default.For(128, 128, 2, new Shader_Unorm_Rg16_Vector2(source, destination)); + } + if (t == typeof(Rg16) && tPixel == typeof(Float2)) + { + using ReadOnlyTexture3D source = Gpu.Default.AllocateReadOnlyTexture3D(128, 128, 2); + using ReadWriteTexture3D destination = Gpu.Default.AllocateReadWriteTexture3D(128, 128, 2); + + Gpu.Default.For(128, 128, 2, new Shader_Unorm_Rg16_Float2(source, destination)); + } + if (t == typeof(Rg32) && tPixel == typeof(Vector2)) + { + using ReadOnlyTexture3D source = Gpu.Default.AllocateReadOnlyTexture3D(128, 128, 2); + using ReadWriteTexture3D destination = Gpu.Default.AllocateReadWriteTexture3D(128, 128, 2); + + Gpu.Default.For(128, 128, 2, new Shader_Unorm_Rg32_Vector2(source, destination)); + } + if (t == typeof(Rg32) && tPixel == typeof(Float2)) + { + using ReadOnlyTexture3D source = Gpu.Default.AllocateReadOnlyTexture3D(128, 128, 2); + using ReadWriteTexture3D destination = Gpu.Default.AllocateReadWriteTexture3D(128, 128, 2); + + Gpu.Default.For(128, 128, 2, new Shader_Unorm_Rg32_Float2(source, destination)); + } + if (t == typeof(Rgba32) && tPixel == typeof(Vector4)) + { + using ReadOnlyTexture3D source = Gpu.Default.AllocateReadOnlyTexture3D(128, 128, 2); + using ReadWriteTexture3D destination = Gpu.Default.AllocateReadWriteTexture3D(128, 128, 2); + + Gpu.Default.For(128, 128, 2, new Shader_Unorm_Rgba32_Vector4(source, destination)); + } + if (t == typeof(Rgba32) && tPixel == typeof(Float4)) + { + using ReadOnlyTexture3D source = Gpu.Default.AllocateReadOnlyTexture3D(128, 128, 2); + using ReadWriteTexture3D destination = Gpu.Default.AllocateReadWriteTexture3D(128, 128, 2); + + Gpu.Default.For(128, 128, 2, new Shader_Unorm_Rgba32_Float4(source, destination)); + } + if (t == typeof(Rgba64) && tPixel == typeof(Vector4)) + { + using ReadOnlyTexture3D source = Gpu.Default.AllocateReadOnlyTexture3D(128, 128, 2); + using ReadWriteTexture3D destination = Gpu.Default.AllocateReadWriteTexture3D(128, 128, 2); + + Gpu.Default.For(128, 128, 2, new Shader_Unorm_Rgba64_Vector4(source, destination)); + } + if (t == typeof(Rgba64) && tPixel == typeof(Float4)) + { + using ReadOnlyTexture3D source = Gpu.Default.AllocateReadOnlyTexture3D(128, 128, 2); + using ReadWriteTexture3D destination = Gpu.Default.AllocateReadWriteTexture3D(128, 128, 2); + + Gpu.Default.For(128, 128, 2, new Shader_Unorm_Rgba64_Float4(source, destination)); + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Bgra32_Vector4 : IComputeShader + { + public readonly ReadOnlyTexture3D source; + public readonly ReadWriteTexture3D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Bgra32_Float4 : IComputeShader + { + public readonly ReadOnlyTexture3D source; + public readonly ReadWriteTexture3D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_R16_float : IComputeShader + { + public readonly ReadOnlyTexture3D source; + public readonly ReadWriteTexture3D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_R8_float : IComputeShader + { + public readonly ReadOnlyTexture3D source; + public readonly ReadWriteTexture3D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rg16_Vector2 : IComputeShader + { + public readonly ReadOnlyTexture3D source; + public readonly ReadWriteTexture3D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rg16_Float2 : IComputeShader + { + public readonly ReadOnlyTexture3D source; + public readonly ReadWriteTexture3D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rg32_Vector2 : IComputeShader + { + public readonly ReadOnlyTexture3D source; + public readonly ReadWriteTexture3D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rg32_Float2 : IComputeShader + { + public readonly ReadOnlyTexture3D source; + public readonly ReadWriteTexture3D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rgba32_Vector4 : IComputeShader + { + public readonly ReadOnlyTexture3D source; + public readonly ReadWriteTexture3D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rgba32_Float4 : IComputeShader + { + public readonly ReadOnlyTexture3D source; + public readonly ReadWriteTexture3D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rgba64_Vector4 : IComputeShader + { + public readonly ReadOnlyTexture3D source; + public readonly ReadWriteTexture3D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + } + } + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_Rgba64_Float4 : IComputeShader + { + public readonly ReadOnlyTexture3D source; + public readonly ReadWriteTexture3D destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + } + } + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.tt b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.tt new file mode 100644 index 00000000..d72edd3c --- /dev/null +++ b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.tt @@ -0,0 +1,81 @@ +<#@ template debug="false" hostspecific="false" language="C#" #> +<#@ assembly name="System.Core" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.Text" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ output extension=".g.cs"#> +<# +var typesMap = new Dictionary +{ + ["Bgra32"] = new[] { "Vector4", "Float4" }, + ["R16"] = new[] { "float" }, + ["R8"] = new[] { "float" }, + ["Rg16"] = new[] { "Vector2", "Float2" }, + ["Rg32"] = new[] { "Vector2", "Float2" }, + ["Rgba32"] = new[] { "Vector4", "Float4" }, + ["Rgba64"] = new[] { "Vector4", "Float4" } +}; + +IEnumerable<(string T, string TPixel)> EnumerateTypes() +{ + foreach (var pair in typesMap) + foreach (var tPixel in pair.Value) + yield return (pair.Key, tPixel); +} +#> +using System; +using System.Numerics; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.Tests +{ + public partial class Texture3DTests + { + [TestMethod] +<# +foreach (var (t, tPixel) in EnumerateTypes()) +{ +#> + [DataRow(typeof(<#=t#>), typeof(<#=tPixel#>))] +<# +} +#> + public void Dispatch_NormalizedTexture3D(Type t, Type tPixel) + { +<# +foreach (var (t, tPixel) in EnumerateTypes()) +{ +#> + if (t == typeof(<#=t#>) && tPixel == typeof(<#=tPixel#>)) + { + using ReadOnlyTexture3D<<#=t#>, <#=tPixel#>> source = Gpu.Default.AllocateReadOnlyTexture3D<<#=t#>, <#=tPixel#>>(128, 128, 2); + using ReadWriteTexture3D<<#=t#>, <#=tPixel#>> destination = Gpu.Default.AllocateReadWriteTexture3D<<#=t#>, <#=tPixel#>>(128, 128, 2); + + Gpu.Default.For(128, 128, 2, new Shader_Unorm_<#=t#>_<#=tPixel#>(source, destination)); + } +<# +} +#> + } +<# + +foreach (var (t, tPixel) in EnumerateTypes()) +{ +#> + + [AutoConstructor] + internal readonly partial struct Shader_Unorm_<#=t#>_<#=tPixel#> : IComputeShader + { + public readonly ReadOnlyTexture3D<<#=t#>, <#=tPixel#>> source; + public readonly ReadWriteTexture3D<<#=t#>, <#=tPixel#>> destination; + + public void Execute(ThreadIds ids) + { + destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + } + } +<# +} +#> + } +} \ No newline at end of file From 32b3787b3c705f9df7c7eb13511c2357da239f83 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Jan 2021 16:29:39 +0100 Subject: [PATCH 17/26] Minor code refactoring --- .../{DnnBenchmark.cs => Blas/BlasBenchmark.cs} | 16 +++++++++++----- .../{Dnn.cs => Blas/BlasHelpers.cs} | 4 ++-- 2 files changed, 13 insertions(+), 7 deletions(-) rename samples/ComputeSharp.Benchmark/{DnnBenchmark.cs => Blas/BlasBenchmark.cs} (90%) rename samples/ComputeSharp.Benchmark/{Dnn.cs => Blas/BlasHelpers.cs} (98%) diff --git a/samples/ComputeSharp.Benchmark/DnnBenchmark.cs b/samples/ComputeSharp.Benchmark/Blas/BlasBenchmark.cs similarity index 90% rename from samples/ComputeSharp.Benchmark/DnnBenchmark.cs rename to samples/ComputeSharp.Benchmark/Blas/BlasBenchmark.cs index 186d119f..2f1e91ed 100644 --- a/samples/ComputeSharp.Benchmark/DnnBenchmark.cs +++ b/samples/ComputeSharp.Benchmark/Blas/BlasBenchmark.cs @@ -4,13 +4,13 @@ using System.Runtime.CompilerServices; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Engines; -namespace ComputeSharp.Benchmark +namespace ComputeSharp.Benchmark.Blas { /// /// A that benchmarks the APIs in the class, on both CPU and GPU. /// [SimpleJob(RunStrategy.Monitoring)] - public class DnnBenchmark : IDisposable + public class BlasBenchmark : IDisposable { /// /// The number of samples. @@ -128,13 +128,19 @@ namespace ComputeSharp.Benchmark /// Runs a fully connected forward operation on the CPU. /// [Benchmark(Baseline = true)] - public void Cpu() => Dnn.FullyConnectedForwardCpu(C, N, M, P, X, W, B, Y); + public void Cpu() + { + BlasHelpers.FullyConnectedForwardCpu(C, N, M, P, X, W, B, Y); + } /// /// Runs a fully connected forward operation on the GPU. /// [Benchmark] - public void GpuWithNoTemporaryBuffers() => Dnn.FullyConnectedForwardGpu(Gpu.Default, C, N, M, P, BufferX, BufferW, BufferB, BufferY); + 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. @@ -147,7 +153,7 @@ namespace ComputeSharp.Benchmark using ReadOnlyBuffer b = Gpu.Default.AllocateReadOnlyBuffer(B); using ReadWriteBuffer y = Gpu.Default.AllocateReadWriteBuffer(Y); - Dnn.FullyConnectedForwardGpu(Gpu.Default, C, N, M, P, x, w, b, y); + BlasHelpers.FullyConnectedForwardGpu(Gpu.Default, C, N, M, P, x, w, b, y); y.GetData(Y); } diff --git a/samples/ComputeSharp.Benchmark/Dnn.cs b/samples/ComputeSharp.Benchmark/Blas/BlasHelpers.cs similarity index 98% rename from samples/ComputeSharp.Benchmark/Dnn.cs rename to samples/ComputeSharp.Benchmark/Blas/BlasHelpers.cs index 3f8087ba..6634e708 100644 --- a/samples/ComputeSharp.Benchmark/Dnn.cs +++ b/samples/ComputeSharp.Benchmark/Blas/BlasHelpers.cs @@ -2,12 +2,12 @@ using System.Threading.Tasks; using ComputeSharp.Graphics; -namespace ComputeSharp.Benchmark +namespace ComputeSharp.Benchmark.Blas { /// /// A that contains primitives to run certain operations of a neural network. /// - internal static partial class Dnn + internal static partial class BlasHelpers { /// /// Executes the forward pass on a fully connected layer on the CPU. From 71ab1950e6feb71833bc0956940414b40ce62d1d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Jan 2021 16:51:49 +0100 Subject: [PATCH 18/26] Added image processing benchmark --- .../Blas/BlasBenchmark.cs | 10 +- .../ComputeSharp.Benchmark.csproj | 14 +++ .../Imaging/ImagingBenchmark.cs | 91 +++++++++++++++++++ 3 files changed, 111 insertions(+), 4 deletions(-) create mode 100644 samples/ComputeSharp.Benchmark/Imaging/ImagingBenchmark.cs diff --git a/samples/ComputeSharp.Benchmark/Blas/BlasBenchmark.cs b/samples/ComputeSharp.Benchmark/Blas/BlasBenchmark.cs index 2f1e91ed..870b1966 100644 --- a/samples/ComputeSharp.Benchmark/Blas/BlasBenchmark.cs +++ b/samples/ComputeSharp.Benchmark/Blas/BlasBenchmark.cs @@ -7,7 +7,7 @@ using BenchmarkDotNet.Engines; namespace ComputeSharp.Benchmark.Blas { /// - /// A that benchmarks the APIs in the class, on both CPU and GPU. + /// A that benchmarks the APIs in the class, on both CPU and GPU. /// [SimpleJob(RunStrategy.Monitoring)] public class BlasBenchmark : IDisposable @@ -105,11 +105,13 @@ namespace ComputeSharp.Benchmark.Blas BufferW = Gpu.Default.AllocateReadOnlyBuffer(W); BufferB = Gpu.Default.AllocateReadOnlyBuffer(B); BufferY = Gpu.Default.AllocateReadWriteBuffer(Y); + + Cpu(); + GpuWithNoTemporaryBuffers(); + GpuWithTemporaryBuffers(); } - /// - /// Clears the memory from the current session. - /// + /// [GlobalCleanup] public void Dispose() { diff --git a/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj index 06bb8291..e95049bf 100644 --- a/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj +++ b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj @@ -5,8 +5,22 @@ net5.0 + + + + + + + + + + + + + + diff --git a/samples/ComputeSharp.Benchmark/Imaging/ImagingBenchmark.cs b/samples/ComputeSharp.Benchmark/Imaging/ImagingBenchmark.cs new file mode 100644 index 00000000..aa4d4873 --- /dev/null +++ b/samples/ComputeSharp.Benchmark/Imaging/ImagingBenchmark.cs @@ -0,0 +1,91 @@ +using System; +using System.IO; +using System.Reflection; +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Configs; +using BenchmarkDotNet.Engines; +using ComputeSharp.BokehBlur.Processors; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Processing; +using SixLabors.ImageSharp.Processing.Processors.Convolution; +using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; + +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 + { + /// + /// The loaded image. + /// + private Image image; + + /// + /// 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); + + Bokeh_Cpu(); + Bokeh_Gpu(); + Gaussian_Cpu(); + Gaussian_Gpu(); + } + + /// + [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 GPU. + /// + [Benchmark] + [BenchmarkCategory("BOKEH")] + public void Bokeh_Gpu() + { + this.image.Mutate(c => c.ApplyProcessor(new HlslBokehBlurProcessor(80, 2, 3))); + } + + /// + /// 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))); + } + } +} From 82a6737ce2521d6a17f56b3e63f3ab353fa3a794 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Jan 2021 17:06:11 +0100 Subject: [PATCH 19/26] Switched gaussian blur to normalized 2D textures --- .../Processors/HlslGaussianBlurProcessor.cs | 21 +++---- .../HlslGaussianBlurProcessor{TPixel}.cs | 57 +++++++++---------- .../ComputeSharp.ImageProcessing/Program.cs | 3 +- 3 files changed, 36 insertions(+), 45 deletions(-) diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs index b0d22c81..8bdfa0ef 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs @@ -60,13 +60,12 @@ namespace ComputeSharp.BokehBlur.Processors [AutoConstructor] internal readonly partial struct VerticalConvolutionProcessor : IComputeShader { - public readonly int width; public readonly int maxY; public readonly int maxX; public readonly int kernelLength; - public readonly ReadWriteBuffer source; - public readonly ReadWriteBuffer target; + public readonly ReadWriteTexture2D source; + public readonly ReadWriteTexture2D target; public readonly ReadOnlyBuffer kernel; /// @@ -80,13 +79,12 @@ namespace ComputeSharp.BokehBlur.Processors { int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); - Vector4 color = source[offsetY * width + offsetX]; + Vector4 color = source[offsetX, offsetY]; result += kernel[i] * color; } - int offsetXY = ids.Y * width + ids.X; - target[offsetXY] = result; + target[ids.XY] = result; } } @@ -96,13 +94,12 @@ namespace ComputeSharp.BokehBlur.Processors [AutoConstructor] internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader { - public readonly int width; public readonly int maxY; public readonly int maxX; public readonly int kernelLength; - public readonly ReadWriteBuffer source; - public readonly ReadWriteBuffer target; + public readonly ReadWriteTexture2D source; + public readonly ReadWriteTexture2D target; public readonly ReadOnlyBuffer kernel; /// @@ -117,14 +114,12 @@ namespace ComputeSharp.BokehBlur.Processors for (int i = 0; i < kernelLength; i++) { int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX); - offsetXY = offsetY * width + offsetX; - Vector4 color = source[offsetXY]; + Vector4 color = source[offsetX, offsetY]; result += kernel[i] * color; } - offsetXY = ids.Y * width + ids.X; - target[offsetXY] = result; + target[ids.XY] = result; } } } diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs index 4ea8671c..f9529bf2 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs @@ -1,11 +1,12 @@ using System; -using System.Buffers; using System.Numerics; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Microsoft.Toolkit.Diagnostics; using SixLabors.ImageSharp; -using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; +using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; namespace ComputeSharp.BokehBlur.Processors { @@ -86,46 +87,41 @@ namespace ComputeSharp.BokehBlur.Processors /// protected override void OnFrameApply(ImageFrame source) { - foreach (Memory memory in source.GetPixelMemoryGroup()) + ImageFrame frame = (ImageFrame)(object)source; + + if (!frame.TryGetSinglePixelSpan(out Span pixelSpan)) { - Span spanTPixel = memory.Span; - - using IMemoryOwner group4 = Configuration.MemoryAllocator.Allocate(spanTPixel.Length); - - Span spanVector4 = group4.Memory.Span; - - PixelOperations.Instance.ToVector4(Configuration, spanTPixel, spanVector4); - - using ReadWriteBuffer sourceBuffer = Gpu.Default.AllocateReadWriteBuffer(spanVector4); - using ReadWriteBuffer firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Length); - using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(Kernel); - - ApplyVerticalConvolution(sourceBuffer, firstPassBuffer, kernelBuffer); - ApplyHorizontalConvolution(firstPassBuffer, sourceBuffer, kernelBuffer); - - sourceBuffer.GetData(spanVector4); - - PixelOperations.Instance.FromVector4Destructive(Configuration, spanVector4, spanTPixel); + ThrowHelper.ThrowInvalidOperationException("Cannot process image frames wrapping discontiguous memory"); } + + Span span = MemoryMarshal.Cast(pixelSpan); + + using ReadWriteTexture2D sourceTexture = Gpu.Default.AllocateReadWriteTexture2D(span, frame.Width, frame.Height); + using ReadWriteTexture2D firstPassTexture = Gpu.Default.AllocateReadWriteTexture2D(frame.Width, frame.Height); + using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(Kernel); + + ApplyVerticalConvolution(sourceTexture, firstPassTexture, kernelBuffer); + ApplyHorizontalConvolution(firstPassTexture, sourceTexture, kernelBuffer); + + sourceTexture.GetData(span); } /// /// Performs a vertical 1D complex convolution with the specified parameters. /// - /// The source to read data from. - /// The target to write the results to. + /// The source to read data from. + /// The target to write the results to. /// The with the values for the current complex kernel. [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ApplyVerticalConvolution( - ReadWriteBuffer source, - ReadWriteBuffer target, + ReadWriteTexture2D source, + ReadWriteTexture2D target, ReadOnlyBuffer kernel) { int height = Source.Height; int width = Source.Width; HlslGaussianBlurProcessor.VerticalConvolutionProcessor shader = new( - width, maxY: height - 1, maxX: width - 1, kernel.Length, @@ -139,20 +135,19 @@ namespace ComputeSharp.BokehBlur.Processors /// /// Performs an horizontal 1D complex convolution with the specified parameters. /// - /// The source to read data from. - /// The target to write the results to. + /// The source to read data from. + /// The target to write the results to. /// The with the values for the current complex kernel. [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ApplyHorizontalConvolution( - ReadWriteBuffer source, - ReadWriteBuffer target, + ReadWriteTexture2D source, + ReadWriteTexture2D target, ReadOnlyBuffer kernel) { int height = Source.Height; int width = Source.Width; HlslGaussianBlurProcessor.HorizontalConvolutionProcessor shader = new( - width, maxY: height - 1, maxX: width - 1, kernel.Length, diff --git a/samples/ComputeSharp.ImageProcessing/Program.cs b/samples/ComputeSharp.ImageProcessing/Program.cs index 91f52ca5..34af8cb3 100644 --- a/samples/ComputeSharp.ImageProcessing/Program.cs +++ b/samples/ComputeSharp.ImageProcessing/Program.cs @@ -5,6 +5,7 @@ using ComputeSharp.BokehBlur.Processors; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Processing; using SixLabors.ImageSharp.Processing.Processors; +using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; namespace ComputeSharp.ImageProcessing { @@ -14,7 +15,7 @@ namespace ComputeSharp.ImageProcessing { Console.WriteLine(">> Loading image"); string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "city.jpg"); - using Image image = Image.Load(path); + using Image image = Image.Load(path); // Apply a series of processors and save the results foreach (var effect in new (string Name, IImageProcessor Processor)[] From 20762e00896f1cc9b00628911444549e86572e18 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Jan 2021 18:22:02 +0100 Subject: [PATCH 20/26] Switched image processors to pixel-specific --- nuget.config | 1 + .../ComputeSharp.Benchmark.csproj | 4 +- .../Imaging/ImagingBenchmark.cs | 2 +- .../Processors/HlslBokehBlurProcessor.cs | 31 +- .../HlslBokehBlurProcessor{TPixel}.cs | 824 +++++++++--------- .../Processors/HlslGaussianBlurProcessor.cs | 74 +- .../HlslGaussianBlurProcessor{TPixel}.cs | 315 ++++--- .../ComputeSharp.ImageProcessing/Program.cs | 2 +- 8 files changed, 631 insertions(+), 622 deletions(-) diff --git a/nuget.config b/nuget.config index a06b48ea..e71007c9 100644 --- a/nuget.config +++ b/nuget.config @@ -4,5 +4,6 @@ + diff --git a/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj index e95049bf..4a6eded4 100644 --- a/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj +++ b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj @@ -19,8 +19,8 @@ - - + + diff --git a/samples/ComputeSharp.Benchmark/Imaging/ImagingBenchmark.cs b/samples/ComputeSharp.Benchmark/Imaging/ImagingBenchmark.cs index aa4d4873..e518da56 100644 --- a/samples/ComputeSharp.Benchmark/Imaging/ImagingBenchmark.cs +++ b/samples/ComputeSharp.Benchmark/Imaging/ImagingBenchmark.cs @@ -65,7 +65,7 @@ namespace ComputeSharp.Benchmark.Imaging [BenchmarkCategory("BOKEH")] public void Bokeh_Gpu() { - this.image.Mutate(c => c.ApplyProcessor(new HlslBokehBlurProcessor(80, 2, 3))); + this.image.Mutate(c => c.ApplyProcessor(new HlslBokehBlurProcessor(80, 2))); } /// diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs index 84e05a55..e9bd5cfe 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs @@ -1,7 +1,10 @@ using System.Numerics; +using System.Runtime.CompilerServices; +using Microsoft.Toolkit.Diagnostics; using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; +using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; namespace ComputeSharp.BokehBlur.Processors { @@ -20,27 +23,23 @@ namespace ComputeSharp.BokehBlur.Processors /// public const int DefaultComponents = 2; - /// - /// The default gamma used by the parameterless constructor. - /// - public const float DefaultGamma = 3f; - /// /// Initializes a new instance of the class. /// - public HlslBokehBlurProcessor() : this(DefaultRadius, DefaultComponents, DefaultGamma) { } + public HlslBokehBlurProcessor() + : this(DefaultRadius, DefaultComponents) + { + } /// /// 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. - /// The gamma highlight factor to use to further process the image. - public HlslBokehBlurProcessor(int radius, int components, float gamma) + public HlslBokehBlurProcessor(int radius, int components) { Radius = radius; Components = components; - Gamma = gamma; } /// @@ -53,16 +52,18 @@ namespace ComputeSharp.BokehBlur.Processors /// public int Components { get; } - /// - /// Gets the gamma highlight factor to use when applying the effect. - /// - public float Gamma { get; } - /// public IImageProcessor CreatePixelSpecificProcessor(Configuration configuration, Image source, Rectangle sourceRectangle) where TPixel : unmanaged, IPixel { - return new HlslBokehBlurProcessor(this, configuration, source, sourceRectangle); + 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); } /// diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs index bbc41abb..f35defb8 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs @@ -10,446 +10,446 @@ using SixLabors.ImageSharp; using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; +using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; namespace ComputeSharp.BokehBlur.Processors { - /// - /// Applies bokeh blur processing to the image. - /// - /// The pixel format. - /// This processor is based on the code from Mike Pound, see github.com/mikepound/convolve. - public sealed partial class HlslBokehBlurProcessor : ImageProcessor - where TPixel : unmanaged, IPixel + /// + public sealed partial class HlslBokehBlurProcessor { /// - /// The kernel radius. + /// Applies bokeh blur processing to the image. /// - private readonly int Radius; - - /// - /// The gamma highlight factor to use when applying the effect. - /// - private readonly float Gamma; - - /// - /// 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 HlslBokehBlurProcessor(HlslBokehBlurProcessor definition, Configuration configuration, Image source, Rectangle sourceRectangle) - : base(configuration, source, sourceRectangle) + /// This processor is based on the code from Mike Pound, see github.com/mikepound/convolve. + public sealed partial class Implementation : ImageProcessor { - Radius = definition.Radius; - KernelSize = Radius * 2 + 1; - ComponentsCount = definition.Components; - Gamma = definition.Gamma; + /// + /// The kernel radius. + /// + private readonly int Radius; - // Reuse the initialized values from the cache, if possible - var parameters = (Radius, ComponentsCount); - if (Cache.TryGetValue(parameters, out var info)) + /// + /// 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) { - 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(); + Radius = definition.Radius; + KernelSize = Radius * 2 + 1; + ComponentsCount = definition.Components; - // 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); - } - - 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++) + // Reuse the initialized values from the cache, if possible + var parameters = (Radius, ComponentsCount); + if (Cache.TryGetValue(parameters, out var info)) { - for (int k = 0; k < length; k++) + 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)); + } + } + + /// + /// 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); + } + + 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++) { - 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); + 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; } } } - // 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) - { - foreach (Memory memory in source.GetPixelMemoryGroup()) - { - // Preliminary gamma highlight pass - using IMemoryOwner source4 = GetExposedVector4Buffer(memory); - - using ReadOnlyBuffer sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(source4.Memory.Span); - using ReadWriteBuffer processingBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Length); - using ReadWriteBuffer firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Length); - using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(KernelSize); - - ref Vector4 param0 = ref KernelParameters[0]; // Avoid bounds check to access the kernel parameters - - // Perform two 1D convolutions for each component in the current instance - for (int j = 0; j < Kernels.Length; j++) - { - kernelBuffer.SetData(Kernels[j]); - Vector4 parameters = Unsafe.Add(ref param0, j); - - ApplyVerticalConvolution(sourceBuffer, firstPassBuffer, kernelBuffer); - ApplyHorizontalConvolutionAndAccumulatePartials(firstPassBuffer, processingBuffer, kernelBuffer, parameters.Z, parameters.W); - } - - // Apply the inverse gamma exposure pass - processingBuffer.GetData(source4.Memory.Span); - - // Write the final pixel data - ApplyInverseGammaExposure(source4.Memory, memory); - } - } - - /// - /// Performs a vertical 1D complex convolution with the specified parameters. - /// - /// The source to read data from. - /// The target to write the results to. - /// The with the values for the current complex kernel. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ApplyVerticalConvolution( - ReadOnlyBuffer source, - ReadWriteBuffer target, - ReadOnlyBuffer kernel) - { - int height = Source.Height; - int width = Source.Width; - - HlslBokehBlurProcessor.VerticalConvolutionProcessor shader = new( - width, - maxY: height - 1, - maxX: width - 1, - kernelLength: kernel.Length, - source, - target, - kernel); - - Gpu.Default.For(width, height, in shader); - } - - /// - /// Performs an horizontal 1D complex convolution with the specified parameters. - /// - /// The source to read data from. - /// The target to write the results to. - /// The with the values for the current complex kernel. - /// The weight factor for the real component of the complex pixel values. - /// The weight factor for the imaginary component of the complex pixel values. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ApplyHorizontalConvolutionAndAccumulatePartials( - ReadWriteBuffer source, - ReadWriteBuffer target, - ReadOnlyBuffer kernel, - float z, - float w) - { - int height = Source.Height; - int width = Source.Width; - - HlslBokehBlurProcessor.HorizontalConvolutionAndAccumulatePartialsProcessor shader = new( - width, - maxY: height - 1, - maxX: width - 1, - kernelLength: kernel.Length, - z, - w, - source, - target, - kernel); - - Gpu.Default.For(width, height, in shader); - } - - /// - /// Applies the gamma correction/highlight to the input pixel buffer and returns an instance with values. - /// - /// The source image. - [Pure] - private IMemoryOwner GetExposedVector4Buffer(Memory source) - { - IMemoryOwner target = Configuration.MemoryAllocator.Allocate(source.Length); - - float exp = Gamma; - int width = Source.Width; - int height = source.Length / width; - - ParallelRowIterator.IterateRows( - Configuration, - new Rectangle(0, 0, width, height), - new GetExposedVector4BufferProcessor(width, exp, source, target.Memory, Configuration)); - - return target; - } - - /// - /// The processor for . - /// - [AutoConstructor] - private readonly partial struct GetExposedVector4BufferProcessor : IRowOperation - { - private readonly int width; - private readonly float exp; - - private readonly Memory source; - private readonly Memory target; - private readonly Configuration configuration; - /// - public void Invoke(int y) + protected override void OnFrameApply(ImageFrame source) { - int offset = y * width; - - Span rowTPixel = source.Span.Slice(offset, width); - Span rowVector4 = target.Span.Slice(offset, width); - - PixelOperations.Instance.ToVector4(configuration, rowTPixel, rowVector4); - - foreach (ref Vector4 v in rowVector4) + foreach (Memory memory in source.GetPixelMemoryGroup()) { - v.X = MathF.Pow(v.X, exp); - v.Y = MathF.Pow(v.Y, exp); - v.Z = MathF.Pow(v.Z, exp); + // Preliminary gamma highlight pass + using IMemoryOwner source4 = GetExposedVector4Buffer(memory); + + using ReadOnlyBuffer sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(source4.Memory.Span); + using ReadWriteBuffer processingBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Length); + using ReadWriteBuffer firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Length); + using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(KernelSize); + + ref Vector4 param0 = ref KernelParameters[0]; // Avoid bounds check to access the kernel parameters + + // Perform two 1D convolutions for each component in the current instance + for (int j = 0; j < Kernels.Length; j++) + { + kernelBuffer.SetData(Kernels[j]); + Vector4 parameters = Unsafe.Add(ref param0, j); + + ApplyVerticalConvolution(sourceBuffer, firstPassBuffer, kernelBuffer); + ApplyHorizontalConvolutionAndAccumulatePartials(firstPassBuffer, processingBuffer, kernelBuffer, parameters.Z, parameters.W); + } + + // Apply the inverse gamma exposure pass + processingBuffer.GetData(source4.Memory.Span); + + // Write the final pixel data + ApplyInverseGammaExposure(source4.Memory, memory); } } - } - /// - /// Applies the inverse gamma exposure pass to compute the final pixel values for a target image. - /// - /// The source buffer to read from. - /// The target image. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ApplyInverseGammaExposure(Memory source, Memory target) - { - int width = Source.Width; - int height = source.Length / width; - float expGamma = 1 / Gamma; - - ParallelRowIterator.IterateRows( - Configuration, - new Rectangle(0, 0, width, height), - new ApplyInverseGammaExposureProcessor(width, expGamma, source, target, Configuration)); - } - - /// - /// The processor for . - /// - [AutoConstructor] - private readonly partial struct ApplyInverseGammaExposureProcessor : IRowOperation - { - private readonly int width; - private readonly float exp; - - private readonly Memory source; - private readonly Memory target; - private readonly Configuration configuration; - - /// - public void Invoke(int y) + /// + /// Performs a vertical 1D complex convolution with the specified parameters. + /// + /// The source to read data from. + /// The target to write the results to. + /// The with the values for the current complex kernel. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ApplyVerticalConvolution( + ReadOnlyBuffer source, + ReadWriteBuffer target, + ReadOnlyBuffer kernel) { - int offset = y * width; + int height = Source.Height; + int width = Source.Width; - Span rowVector4 = source.Span.Slice(offset, width); - Span rowTPixel = target.Span.Slice(offset, width); + VerticalConvolutionProcessor shader = new( + width, + maxY: height - 1, + maxX: width - 1, + kernelLength: kernel.Length, + source, + target, + kernel); - Vector4 low = Vector4.Zero; - var high = new Vector4(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); + Gpu.Default.For(width, height, in shader); + } - foreach (ref Vector4 v in rowVector4) + /// + /// Performs an horizontal 1D complex convolution with the specified parameters. + /// + /// The source to read data from. + /// The target to write the results to. + /// The with the values for the current complex kernel. + /// The weight factor for the real component of the complex pixel values. + /// The weight factor for the imaginary component of the complex pixel values. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ApplyHorizontalConvolutionAndAccumulatePartials( + ReadWriteBuffer source, + ReadWriteBuffer target, + ReadOnlyBuffer kernel, + float z, + float w) + { + int height = Source.Height; + int width = Source.Width; + + HorizontalConvolutionAndAccumulatePartialsProcessor shader = new( + width, + maxY: height - 1, + maxX: width - 1, + kernelLength: kernel.Length, + z, + w, + source, + target, + kernel); + + Gpu.Default.For(width, height, in shader); + } + + /// + /// Applies the gamma correction/highlight to the input pixel buffer and returns an instance with values. + /// + /// The source image. + [Pure] + private IMemoryOwner GetExposedVector4Buffer(Memory source) + { + IMemoryOwner target = Configuration.MemoryAllocator.Allocate(source.Length); + + int width = Source.Width; + int height = source.Length / width; + + ParallelRowIterator.IterateRows( + Configuration, + new Rectangle(0, 0, width, height), + new GetExposedVector4BufferProcessor(width, source, target.Memory, Configuration)); + + return target; + } + + /// + /// The processor for . + /// + [AutoConstructor] + private readonly partial struct GetExposedVector4BufferProcessor : IRowOperation + { + private readonly int width; + + private readonly Memory source; + private readonly Memory target; + private readonly Configuration configuration; + + /// + public void Invoke(int y) { - var clamp = Vector4.Clamp(v, low, high); - v.X = MathF.Pow(clamp.X, exp); - v.Y = MathF.Pow(clamp.Y, exp); - v.Z = MathF.Pow(clamp.Z, exp); - } + int offset = y * width; - PixelOperations.Instance.FromVector4Destructive(configuration, rowVector4, rowTPixel); + Span rowTPixel = source.Span.Slice(offset, width); + Span rowVector4 = target.Span.Slice(offset, width); + + PixelOperations.Instance.ToVector4(configuration, rowTPixel, rowVector4); + + foreach (ref Vector4 v in rowVector4) + { + Vector4 pixel = v; + float alpha = pixel.W; + + pixel = pixel * pixel * pixel; + pixel.W = alpha; + + v = pixel; + } + } + } + + /// + /// Applies the inverse gamma exposure pass to compute the final pixel values for a target image. + /// + /// The source buffer to read from. + /// The target image. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ApplyInverseGammaExposure(Memory source, Memory target) + { + int width = Source.Width; + int height = source.Length / width; + + ParallelRowIterator.IterateRows( + Configuration, + new Rectangle(0, 0, width, height), + new ApplyInverseGammaExposureProcessor(width, source, target, Configuration)); + } + + /// + /// The processor for . + /// + [AutoConstructor] + private readonly partial struct ApplyInverseGammaExposureProcessor : IRowOperation + { + private readonly int width; + + private readonly Memory source; + private readonly Memory target; + private readonly Configuration configuration; + + /// + public void Invoke(int y) + { + int offset = y * width; + + Span rowVector4 = source.Span.Slice(offset, width); + Span rowTPixel = target.Span.Slice(offset, width); + + Vector4 low = Vector4.Zero; + var high = new Vector4(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); + + foreach (ref Vector4 v in rowVector4) + { + var clamp = Vector4.Clamp(v, low, high); + + clamp.X = MathF.Pow(clamp.X, 1 / 3f); + clamp.Y = MathF.Pow(clamp.Y, 1 / 3f); + clamp.Z = MathF.Pow(clamp.Z, 1 / 3f); + + v = clamp; + } + + PixelOperations.Instance.FromVector4Destructive(configuration, rowVector4, rowTPixel); + } } } } diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs index 8bdfa0ef..962db9cf 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs @@ -1,7 +1,9 @@ -using System.Numerics; +using System.Runtime.CompilerServices; +using Microsoft.Toolkit.Diagnostics; using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; +using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; namespace ComputeSharp.BokehBlur.Processors { @@ -51,76 +53,14 @@ namespace ComputeSharp.BokehBlur.Processors public IImageProcessor CreatePixelSpecificProcessor(Configuration configuration, Image source, Rectangle sourceRectangle) where TPixel : unmanaged, IPixel { - return new HlslGaussianBlurProcessor(this, configuration, source, sourceRectangle); - } - - /// - /// Kernel for the vertical convolution pass. - /// - [AutoConstructor] - internal readonly partial struct VerticalConvolutionProcessor : IComputeShader - { - public readonly int maxY; - public readonly int maxX; - public readonly int kernelLength; - - public readonly ReadWriteTexture2D source; - public readonly ReadWriteTexture2D target; - public readonly ReadOnlyBuffer kernel; - - /// - public void Execute(ThreadIds ids) + if (typeof(TPixel) != typeof(ImageSharpRgba32)) { - Vector4 result = Vector4.Zero; - int radiusY = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; - - for (int i = 0; i < kernelLength; i++) - { - int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); - Vector4 color = source[offsetX, offsetY]; - - result += kernel[i] * color; - } - - target[ids.XY] = result; + ThrowHelper.ThrowInvalidOperationException("This processor only supports the RGBA32 pixel format"); } - } - /// - /// Kernel for the horizontal convolution pass. - /// - [AutoConstructor] - internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader - { - public readonly int maxY; - public readonly int maxX; - public readonly int kernelLength; + var processor = new Implementation(this, configuration, Unsafe.As>(source), sourceRectangle); - public readonly ReadWriteTexture2D source; - public readonly ReadWriteTexture2D target; - public readonly ReadOnlyBuffer kernel; - - /// - public void Execute(ThreadIds ids) - { - Vector4 result = Vector4.Zero; - int radiusX = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; - int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); - int offsetXY; - - for (int i = 0; i < kernelLength; i++) - { - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX); - Vector4 color = source[offsetX, offsetY]; - - result += kernel[i] * color; - } - - target[ids.XY] = result; - } + return Unsafe.As>(processor); } } } diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs index f9529bf2..5f1fa2f5 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs @@ -4,158 +4,225 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.Toolkit.Diagnostics; using SixLabors.ImageSharp; -using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; namespace ComputeSharp.BokehBlur.Processors { - /// - /// Applies Gaussian blur processing to an image. - /// - /// The pixel format. - internal sealed class HlslGaussianBlurProcessor : ImageProcessor - where TPixel : unmanaged, IPixel + /// + public sealed partial class HlslGaussianBlurProcessor { /// - /// The 1D kernel to apply. + /// Applies Gaussian blur processing to an image. /// - 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 HlslGaussianBlurProcessor(HlslGaussianBlurProcessor definition, Configuration configuration, Image source, Rectangle sourceRectangle) - : base(configuration, source, sourceRectangle) + internal sealed partial class Implementation : ImageProcessor { - int kernelSize = definition.Radius * 2 + 1; - Kernel = CreateGaussianBlurKernel(kernelSize, definition.Sigma); - } + /// + /// The 1D kernel to apply. + /// + private readonly float[] Kernel; - /// - /// 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++) + /// + /// 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) { - float x = i - midpoint; - float gx = Gaussian(x, weight); - sum += gx; - Unsafe.Add(ref rKernel, i) = gx; + int kernelSize = definition.Radius * 2 + 1; + Kernel = CreateGaussianBlurKernel(kernelSize, definition.Sigma); } - // Normalize kernel so that the sum of all weights equals 1 - for (int i = 0; i < size; i++) + /// + /// Creates a 1 dimensional Gaussian kernel using the Gaussian G(x) function. + /// + private static float[] CreateGaussianBlurKernel(int size, float weight) { - Unsafe.Add(ref rKernel, i) /= sum; + 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; } - 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) - { - ImageFrame frame = (ImageFrame)(object)source; - - if (!frame.TryGetSinglePixelSpan(out Span pixelSpan)) + /// + /// 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) { - ThrowHelper.ThrowInvalidOperationException("Cannot process image frames wrapping discontiguous memory"); + 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; } - Span span = MemoryMarshal.Cast(pixelSpan); + /// + protected override void OnFrameApply(ImageFrame source) + { + if (!source.TryGetSinglePixelSpan(out Span pixelSpan)) + { + ThrowHelper.ThrowInvalidOperationException("Cannot process image frames wrapping discontiguous memory"); + } - using ReadWriteTexture2D sourceTexture = Gpu.Default.AllocateReadWriteTexture2D(span, frame.Width, frame.Height); - using ReadWriteTexture2D firstPassTexture = Gpu.Default.AllocateReadWriteTexture2D(frame.Width, frame.Height); - using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(Kernel); + Span span = MemoryMarshal.Cast(pixelSpan); - ApplyVerticalConvolution(sourceTexture, firstPassTexture, kernelBuffer); - ApplyHorizontalConvolution(firstPassTexture, sourceTexture, kernelBuffer); + using ReadWriteTexture2D sourceTexture = Gpu.Default.AllocateReadWriteTexture2D(span, source.Width, source.Height); + using ReadWriteTexture2D firstPassTexture = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); + using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(Kernel); - sourceTexture.GetData(span); - } + ApplyVerticalConvolution(sourceTexture, firstPassTexture, kernelBuffer); + ApplyHorizontalConvolution(firstPassTexture, sourceTexture, kernelBuffer); - /// - /// Performs a vertical 1D complex convolution with the specified parameters. - /// - /// The source to read data from. - /// The target to write the results to. - /// The with the values for the current complex kernel. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ApplyVerticalConvolution( - ReadWriteTexture2D source, - ReadWriteTexture2D target, - ReadOnlyBuffer kernel) - { - int height = Source.Height; - int width = Source.Width; + sourceTexture.GetData(span); + } - HlslGaussianBlurProcessor.VerticalConvolutionProcessor shader = new( - maxY: height - 1, - maxX: width - 1, - kernel.Length, - source, - target, - kernel); + /// + /// Performs a vertical 1D complex convolution with the specified parameters. + /// + /// The source to read data from. + /// The target to write the results to. + /// The with the values for the current complex kernel. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ApplyVerticalConvolution( + ReadWriteTexture2D source, + ReadWriteTexture2D target, + ReadOnlyBuffer kernel) + { + int height = Source.Height; + int width = Source.Width; - Gpu.Default.For(width, height, in shader); - } + VerticalConvolutionProcessor shader = new( + maxY: height - 1, + maxX: width - 1, + kernel.Length, + source, + target, + kernel); - /// - /// Performs an horizontal 1D complex convolution with the specified parameters. - /// - /// The source to read data from. - /// The target to write the results to. - /// The with the values for the current complex kernel. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ApplyHorizontalConvolution( - ReadWriteTexture2D source, - ReadWriteTexture2D target, - ReadOnlyBuffer kernel) - { - int height = Source.Height; - int width = Source.Width; + Gpu.Default.For(width, height, in shader); + } - HlslGaussianBlurProcessor.HorizontalConvolutionProcessor shader = new( - maxY: height - 1, - maxX: width - 1, - kernel.Length, - source, - target, - kernel); + /// + /// Kernel for the vertical convolution pass. + /// + [AutoConstructor] + internal readonly partial struct VerticalConvolutionProcessor : IComputeShader + { + public readonly int maxY; + public readonly int maxX; + public readonly int kernelLength; - Gpu.Default.For(width, height, in shader); + public readonly ReadWriteTexture2D source; + public readonly ReadWriteTexture2D target; + public readonly ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) + { + Vector4 result = Vector4.Zero; + int radiusY = kernelLength >> 1; + int sourceOffsetColumnBase = ids.X; + + for (int i = 0; i < kernelLength; i++) + { + int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); + int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); + Vector4 color = source[offsetX, offsetY]; + + result += kernel[i] * color; + } + + target[ids.XY] = result; + } + } + + /// + /// Performs an horizontal 1D complex convolution with the specified parameters. + /// + /// The source to read data from. + /// The target to write the results to. + /// The with the values for the current complex kernel. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ApplyHorizontalConvolution( + ReadWriteTexture2D source, + ReadWriteTexture2D target, + ReadOnlyBuffer kernel) + { + int height = Source.Height; + int width = Source.Width; + + HorizontalConvolutionProcessor shader = new( + maxY: height - 1, + maxX: width - 1, + kernel.Length, + source, + target, + kernel); + + Gpu.Default.For(width, height, in shader); + } + + /// + /// Kernel for the horizontal convolution pass. + /// + [AutoConstructor] + internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader + { + public readonly int maxY; + public readonly int maxX; + public readonly int kernelLength; + + public readonly ReadWriteTexture2D source; + public readonly ReadWriteTexture2D target; + public readonly ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) + { + Vector4 result = Vector4.Zero; + int radiusX = kernelLength >> 1; + int sourceOffsetColumnBase = ids.X; + int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); + + for (int i = 0; i < kernelLength; i++) + { + int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX); + Vector4 color = source[offsetX, offsetY]; + + result += kernel[i] * color; + } + + target[ids.XY] = result; + } + } } } } diff --git a/samples/ComputeSharp.ImageProcessing/Program.cs b/samples/ComputeSharp.ImageProcessing/Program.cs index 34af8cb3..9924b200 100644 --- a/samples/ComputeSharp.ImageProcessing/Program.cs +++ b/samples/ComputeSharp.ImageProcessing/Program.cs @@ -20,7 +20,7 @@ namespace ComputeSharp.ImageProcessing // Apply a series of processors and save the results foreach (var effect in new (string Name, IImageProcessor Processor)[] { - ("bokeh", new HlslBokehBlurProcessor(80, 2, 3)), + ("bokeh", new HlslBokehBlurProcessor(80, 2)), ("gaussian", new HlslGaussianBlurProcessor(80)) }) { From 7a87cf1841d780e2bc06b02a6c83bdfc85264a2d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Jan 2021 18:38:02 +0100 Subject: [PATCH 21/26] Added implicit FloatN <-> VectorN conversions --- src/ComputeSharp.Core/Intrinsics/Hlsl.cs | 1240 ----------------- .../Primitives/Float/Float2.cs | 13 + .../Primitives/Float/Float3.cs | 13 + .../Primitives/Float/Float4.cs | 13 + .../ComputeSharp.SourceGenerators.csproj | 3 +- 5 files changed, 41 insertions(+), 1241 deletions(-) diff --git a/src/ComputeSharp.Core/Intrinsics/Hlsl.cs b/src/ComputeSharp.Core/Intrinsics/Hlsl.cs index 7e5e0fcb..c58a3301 100644 --- a/src/ComputeSharp.Core/Intrinsics/Hlsl.cs +++ b/src/ComputeSharp.Core/Intrinsics/Hlsl.cs @@ -1,5 +1,4 @@ using System.Diagnostics.Contracts; -using System.Numerics; using ComputeSharp.Core.Intrinsics.Attributes; using ComputeSharp.Exceptions; @@ -74,30 +73,6 @@ namespace ComputeSharp [Pure] public static Float4 Abs(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Abs)}({nameof(Float4)})"); - /// - /// Returns the absolute value of the specified value. - /// - /// The specified value. - /// The absolute value of the parameter. - [Pure] - public static Vector2 Abs(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Abs)}({nameof(Vector2)})"); - - /// - /// Returns the absolute value of the specified value. - /// - /// The specified value. - /// The absolute value of the parameter. - [Pure] - public static Vector3 Abs(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Abs)}({nameof(Vector3)})"); - - /// - /// Returns the absolute value of the specified value. - /// - /// The specified value. - /// The absolute value of the parameter. - [Pure] - public static Vector4 Abs(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Abs)}({nameof(Vector4)})"); - /// /// Returns the arccosine of the specified value. /// @@ -130,30 +105,6 @@ namespace ComputeSharp [Pure] public static Float3 Acos(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Acos)}({nameof(Float4)})"); - /// - /// Returns the arccosine of the specified value. - /// - /// The specified value, where each component should be within the range [-1 to 1] - /// The arccosine of the parameter. - [Pure] - public static Vector2 Acos(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Acos)}({nameof(Vector2)})"); - - /// - /// Returns the arccosine of the specified value. - /// - /// The specified value, where each component should be within the range [-1 to 1] - /// The arccosine of the parameter. - [Pure] - public static Vector3 Acos(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Acos)}({nameof(Vector3)})"); - - /// - /// Returns the arccosine of the specified value. - /// - /// The specified value, where each component should be within the range [-1 to 1] - /// The arccosine of the parameter. - [Pure] - public static Vector3 Acos(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Acos)}({nameof(Vector4)})"); - /// /// Determines if all components of the specified value are non-zero. /// @@ -202,30 +153,6 @@ namespace ComputeSharp [Pure] public static bool All(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(All)}({nameof(Float4)})"); - /// - /// Determines if all components of the specified value are non-zero. - /// - /// The specified value. - /// if all components of the parameter are non-zero; otherwise, . - [Pure] - public static bool All(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(All)}({nameof(Vector2)})"); - - /// - /// Determines if all components of the specified value are non-zero. - /// - /// The specified value. - /// if all components of the parameter are non-zero; otherwise, . - [Pure] - public static bool All(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(All)}({nameof(Vector3)})"); - - /// - /// Determines if all components of the specified value are non-zero. - /// - /// The specified value. - /// if all components of the parameter are non-zero; otherwise, . - [Pure] - public static bool All(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(All)}({nameof(Vector4)})"); - /// /// Determines if any components of the specified value are non-zero. /// @@ -274,30 +201,6 @@ namespace ComputeSharp [Pure] public static bool Any(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Any)}({nameof(Float4)})"); - /// - /// Determines if any components of the specified value are non-zero. - /// - /// The specified value. - /// if any components of the parameter are non-zero; otherwise, . - [Pure] - public static bool Any(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Any)}({nameof(Vector2)})"); - - /// - /// Determines if any components of the specified value are non-zero. - /// - /// The specified value. - /// if any components of the parameter are non-zero; otherwise, . - [Pure] - public static bool Any(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Any)}({nameof(Vector3)})"); - - /// - /// Determines if any components of the specified value are non-zero. - /// - /// The specified value. - /// if any components of the parameter are non-zero; otherwise, . - [Pure] - public static bool Any(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Any)}({nameof(Vector4)})"); - /// /// Reinterprets a cast value (two 32-bit values) into a . /// @@ -412,30 +315,6 @@ namespace ComputeSharp [Pure] public static Float3 Asin(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Asin)}({nameof(Float4)})"); - /// - /// Returns the arcsine of the specified value. - /// - /// The specified value, where each component should be within the range [-1 to 1] - /// The arcsine of the parameter. - [Pure] - public static Vector2 Asin(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Asin)}({nameof(Vector2)})"); - - /// - /// Returns the arcsine of the specified value. - /// - /// The specified value, where each component should be within the range [-1 to 1] - /// The arcsine of the parameter. - [Pure] - public static Vector3 Asin(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Asin)}({nameof(Vector3)})"); - - /// - /// Returns the arcsine of the specified value. - /// - /// The specified value, where each component should be within the range [-1 to 1] - /// The arcsine of the parameter. - [Pure] - public static Vector3 Asin(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Asin)}({nameof(Vector4)})"); - /// /// Returns the arctangent of the specified value. /// @@ -468,30 +347,6 @@ namespace ComputeSharp [Pure] public static Float3 Atan(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Atan)}({nameof(Float4)})"); - /// - /// Returns the arctangent of the specified value. - /// - /// The specified value. - /// The arctangent of the parameter. - [Pure] - public static Vector2 Atan(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Atan)}({nameof(Vector2)})"); - - /// - /// Returns the arctangent of the specified value. - /// - /// The specified value. - /// The arctangent of the parameter. - [Pure] - public static Vector3 Atan(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Atan)}({nameof(Vector3)})"); - - /// - /// Returns the arctangent of the specified value. - /// - /// The specified value. - /// The arctangent of the parameter. - [Pure] - public static Vector3 Atan(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Atan)}({nameof(Vector4)})"); - /// /// Returns the arctangent of two values (,) /// @@ -528,33 +383,6 @@ namespace ComputeSharp [Pure] public static Float3 Atan2(Float4 y, Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Atan2)}({nameof(Float4)},{nameof(Float4)})"); - /// - /// Returns the arctangent of two values (,) - /// - /// The value. - /// The value. - /// The arctangent of (,) - [Pure] - public static Vector2 Atan2(Vector2 y, Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Atan2)}({nameof(Vector2)},{nameof(Vector2)})"); - - /// - /// Returns the arctangent of two values (,) - /// - /// The value. - /// The value. - /// The arctangent of (,) - [Pure] - public static Vector3 Atan2(Vector3 y, Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Atan2)}({nameof(Vector3)},{nameof(Vector3)})"); - - /// - /// Returns the arctangent of two values (,) - /// - /// The value. - /// The value. - /// The arctangent of (,) - [Pure] - public static Vector3 Atan2(Vector4 y, Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Atan2)}({nameof(Vector4)},{nameof(Vector4)})"); - /// /// Returns the smallest integer value that is greater than or equal to the specified value. /// @@ -587,30 +415,6 @@ namespace ComputeSharp [Pure] public static Float3 Ceil(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Ceil)}({nameof(Float4)})"); - /// - /// Returns the smallest integer value that is greater than or equal to the specified value. - /// - /// The specified value. - /// The smallest integer value (returned as a floating-point type) that is greater than or equal to the parameter. - [Pure] - public static Vector2 Ceil(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Ceil)}({nameof(Vector2)})"); - - /// - /// Returns the smallest integer value that is greater than or equal to the specified value. - /// - /// The specified value. - /// The smallest integer value (returned as a floating-point type) that is greater than or equal to the parameter. - [Pure] - public static Vector3 Ceil(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Ceil)}({nameof(Vector3)})"); - - /// - /// Returns the smallest integer value that is greater than or equal to the specified value. - /// - /// The specified value. - /// The smallest integer value (returned as a floating-point type) that is greater than or equal to the parameter. - [Pure] - public static Vector3 Ceil(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Ceil)}({nameof(Vector4)})"); - /// /// Clamps the specified value to the specified minimum and maximum range. /// @@ -699,39 +503,6 @@ namespace ComputeSharp [Pure] public static Float4 Clamp(Float4 x, Float4 min, Float4 max) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Clamp)}({nameof(Float4)},{nameof(Float4)},{nameof(Float4)})"); - /// - /// Clamps the specified value to the specified minimum and maximum range. - /// - /// A value to clamp. - /// The specified minimum range. - /// The specified maximum range. - /// The clamped value for the x parameter. - /// For values of -INF or INF, clamp will behave as expected. However for values of NaN, the results are undefined. - [Pure] - public static Vector2 Clamp(Vector2 x, Vector2 min, Vector2 max) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Clamp)}({nameof(Vector2)},{nameof(Vector2)},{nameof(Vector2)})"); - - /// - /// Clamps the specified value to the specified minimum and maximum range. - /// - /// A value to clamp. - /// The specified minimum range. - /// The specified maximum range. - /// The clamped value for the x parameter. - /// For values of -INF or INF, clamp will behave as expected. However for values of NaN, the results are undefined. - [Pure] - public static Vector3 Clamp(Vector3 x, Vector3 min, Vector3 max) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Clamp)}({nameof(Vector3)},{nameof(Vector3)},{nameof(Vector3)})"); - - /// - /// Clamps the specified value to the specified minimum and maximum range. - /// - /// A value to clamp. - /// The specified minimum range. - /// The specified maximum range. - /// The clamped value for the x parameter. - /// For values of -INF or INF, clamp will behave as expected. However for values of NaN, the results are undefined. - [Pure] - public static Vector4 Clamp(Vector4 x, Vector4 min, Vector4 max) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Clamp)}({nameof(Vector4)},{nameof(Vector4)},{nameof(Vector4)})"); - /// /// Returns the cosine of the specified value. /// @@ -764,30 +535,6 @@ namespace ComputeSharp [Pure] public static Float3 Cos(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Cos)}({nameof(Float4)})"); - /// - /// Returns the cosine of the specified value. - /// - /// The specified value, radians. - /// The cosine of the parameter. - [Pure] - public static Vector2 Cos(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Cos)}({nameof(Vector2)})"); - - /// - /// Returns the cosine of the specified value. - /// - /// The specified value, radians. - /// The cosine of the parameter. - [Pure] - public static Vector3 Cos(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Cos)}({nameof(Vector3)})"); - - /// - /// Returns the cosine of the specified value. - /// - /// The specified value, radians. - /// The cosine of the parameter. - [Pure] - public static Vector3 Cos(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Cos)}({nameof(Vector4)})"); - /// /// Returns the hyperbolic cosine of the specified value. /// @@ -820,30 +567,6 @@ namespace ComputeSharp [Pure] public static Float3 Cosh(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Cosh)}({nameof(Float4)})"); - /// - /// Returns the hyperbolic cosine of the specified value. - /// - /// The specified value, radians. - /// The hyperbolic cosine of the parameter. - [Pure] - public static Vector2 Cosh(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Cosh)}({nameof(Vector2)})"); - - /// - /// Returns the hyperbolic cosine of the specified value. - /// - /// The specified value, radians. - /// The hyperbolic cosine of the parameter. - [Pure] - public static Vector3 Cosh(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Cosh)}({nameof(Vector3)})"); - - /// - /// Returns the hyperbolic cosine of the specified value. - /// - /// The specified value, radians. - /// The hyperbolic cosine of the parameter. - [Pure] - public static Vector3 Cosh(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Cosh)}({nameof(Vector4)})"); - /// /// Counts the number of bits in the input value. /// @@ -861,15 +584,6 @@ namespace ComputeSharp [Pure] public static Float3 Cross(Float3 x, Float3 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Cross)}({nameof(Float3)})"); - /// - /// Returns the cross product of two values. - /// - /// The first vector. - /// The second vector. - /// The cross product of the parameter and the parameter. - [Pure] - public static Vector3 Cross(Vector3 x, Vector3 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Cross)}({nameof(Vector3)})"); - /// /// Converts the specified value from radians to degrees. /// @@ -902,30 +616,6 @@ namespace ComputeSharp [Pure] public static Float3 Degrees(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Degrees)}({nameof(Float4)})"); - /// - /// Converts the specified value from radians to degrees. - /// - /// The specified value. - /// The result of converting the parameter from radians to degrees. - [Pure] - public static Vector2 Degrees(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Degrees)}({nameof(Vector2)})"); - - /// - /// Converts the specified value from radians to degrees. - /// - /// The specified value. - /// The result of converting the parameter from radians to degrees. - [Pure] - public static Vector3 Degrees(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Degrees)}({nameof(Vector3)})"); - - /// - /// Converts the specified value from radians to degrees. - /// - /// The specified value. - /// The result of converting the parameter from radians to degrees. - [Pure] - public static Vector3 Degrees(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Degrees)}({nameof(Vector4)})"); - /// /// Returns a distance scalar between two values. /// @@ -953,33 +643,6 @@ namespace ComputeSharp [Pure] public static float Distance(Float4 x, Float4 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Distance)}({nameof(Float4)},{nameof(Float4)})"); - /// - /// Returns a distance scalar between two values. - /// - /// The first value to compare. - /// The second value to compare. - /// A scalar value that represents the distance between the parameter and the parameter. - [Pure] - public static float Distance(Vector2 x, Vector2 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Distance)}({nameof(Vector2)},{nameof(Vector2)})"); - - /// - /// Returns a distance scalar between two values. - /// - /// The first value to compare. - /// The second value to compare. - /// A scalar value that represents the distance between the parameter and the parameter. - [Pure] - public static float Distance(Vector3 x, Vector3 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Distance)}({nameof(Vector3)},{nameof(Vector3)})"); - - /// - /// Returns a distance scalar between two values. - /// - /// The first value to compare. - /// The second value to compare. - /// A scalar value that represents the distance between the parameter and the parameter. - [Pure] - public static float Distance(Vector4 x, Vector4 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Distance)}({nameof(Vector4)},{nameof(Vector4)})"); - /// /// Returns the dot product of two values. /// @@ -1007,33 +670,6 @@ namespace ComputeSharp [Pure] public static float Dot(Float4 x, Float4 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Dot)}({nameof(Float4)},{nameof(Float4)})"); - /// - /// Returns the dot product of two values. - /// - /// The first vector. - /// The second vector. - /// The dot product of the parameter and the parameter. - [Pure] - public static float Dot(Vector2 x, Vector2 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Dot)}({nameof(Vector2)},{nameof(Vector2)})"); - - /// - /// Returns the dot product of two values. - /// - /// The first vector. - /// The second vector. - /// The dot product of the parameter and the parameter. - [Pure] - public static float Dot(Vector3 x, Vector3 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Dot)}({nameof(Vector3)},{nameof(Vector3)})"); - - /// - /// Returns the dot product of two values. - /// - /// The first vector. - /// The second vector. - /// The dot product of the parameter and the parameter. - [Pure] - public static float Dot(Vector4 x, Vector4 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Dot)}({nameof(Vector4)},{nameof(Vector4)})"); - /// /// Returns the base-e exponential of the specified value. /// @@ -1066,30 +702,6 @@ namespace ComputeSharp [Pure] public static Float4 Exp(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Exp)}({nameof(Float4)})"); - /// - /// Returns the base-e exponential of the specified value. - /// - /// The specified value. - /// The base-e exponential of the parameter. - [Pure] - public static Vector2 Exp(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Exp)}({nameof(Vector2)})"); - - /// - /// Returns the base-e exponential of the specified value. - /// - /// The specified value. - /// The base-e exponential of the parameter. - [Pure] - public static Vector3 Exp(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Exp)}({nameof(Vector3)})"); - - /// - /// Returns the base-e exponential of the specified value. - /// - /// The specified value. - /// The base-e exponential of the parameter. - [Pure] - public static Vector4 Exp(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Exp)}({nameof(Vector4)})"); - /// /// Returns the base-2 exponential of the specified value. /// @@ -1122,30 +734,6 @@ namespace ComputeSharp [Pure] public static Float4 Exp2(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Exp2)}({nameof(Float4)})"); - /// - /// Returns the base-2 exponential of the specified value. - /// - /// The specified value. - /// The base-2 exponential of the parameter. - [Pure] - public static Vector2 Exp2(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Exp2)}({nameof(Vector2)})"); - - /// - /// Returns the base-2 exponential of the specified value. - /// - /// The specified value. - /// The base-2 exponential of the parameter. - [Pure] - public static Vector3 Exp2(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Exp2)}({nameof(Vector3)})"); - - /// - /// Returns the base-2 exponential of the specified value. - /// - /// The specified value. - /// The base-2 exponential of the parameter. - [Pure] - public static Vector4 Exp2(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Exp2)}({nameof(Vector4)})"); - /// /// Returns the largest integer that is less than or equal to the specified value. /// @@ -1178,30 +766,6 @@ namespace ComputeSharp [Pure] public static Float4 Floor(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Floor)}({nameof(Float4)})"); - /// - /// Returns the largest integer that is less than or equal to the specified value. - /// - /// The specified value. - /// The largest integer value (returned as a floating-point type) that is less than or equal to the parameter. - [Pure] - public static Vector2 Floor(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Floor)}({nameof(Vector2)})"); - - /// - /// Returns the largest integer that is less than or equal to the specified value. - /// - /// The specified value. - /// The largest integer value (returned as a floating-point type) that is less than or equal to the parameter. - [Pure] - public static Vector3 Floor(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Floor)}({nameof(Vector3)})"); - - /// - /// Returns the largest integer that is less than or equal to the specified value. - /// - /// The specified value. - /// The largest integer value (returned as a floating-point type) that is less than or equal to the parameter. - [Pure] - public static Vector4 Floor(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Floor)}({nameof(Vector4)})"); - /// /// Returns the floating-point remainder of /. /// @@ -1238,33 +802,6 @@ namespace ComputeSharp [Pure] public static Float4 Fmod(Float4 x, Float4 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Fmod)}({nameof(Float4)},{nameof(Float4)})"); - /// - /// Returns the floating-point remainder of /. - /// - /// The divident. - /// The divisor. - /// The floating-point remainder of the parameter divided by the parameter. - [Pure] - public static Vector2 Fmod(Vector2 x, Vector2 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Fmod)}({nameof(Vector2)},{nameof(Vector2)})"); - - /// - /// Returns the floating-point remainder of /. - /// - /// The divident. - /// The divisor. - /// The floating-point remainder of the parameter divided by the parameter. - [Pure] - public static Vector3 Fmod(Vector3 x, Vector3 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Fmod)}({nameof(Vector3)},{nameof(Vector3)})"); - - /// - /// Returns the floating-point remainder of /. - /// - /// The divident. - /// The divisor. - /// The floating-point remainder of the parameter divided by the parameter. - [Pure] - public static Vector4 Fmod(Vector4 x, Vector4 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Fmod)}({nameof(Vector4)},{nameof(Vector4)})"); - /// /// Returns the fractional (or decimal) part of , which is greater than or equal to 0 and less than 1. /// @@ -1297,30 +834,6 @@ namespace ComputeSharp [Pure] public static Float4 Frac(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Frac)}({nameof(Float4)})"); - /// - /// Returns the fractional (or decimal) part of , which is greater than or equal to 0 and less than 1. - /// - /// The specified value. - /// The fractional part of the parameter. - [Pure] - public static Vector2 Frac(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Frac)}({nameof(Vector2)})"); - - /// - /// Returns the fractional (or decimal) part of , which is greater than or equal to 0 and less than 1. - /// - /// The specified value. - /// The fractional part of the parameter. - [Pure] - public static Vector3 Frac(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Frac)}({nameof(Vector3)})"); - - /// - /// Returns the fractional (or decimal) part of , which is greater than or equal to 0 and less than 1. - /// - /// The specified value. - /// The fractional part of the parameter. - [Pure] - public static Vector4 Frac(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Frac)}({nameof(Vector4)})"); - /// /// Returns the mantissa and exponent of the specified floating-point value. /// @@ -1357,33 +870,6 @@ namespace ComputeSharp [Pure] public static Float4 Frexp(Float4 x, out Float4 exp) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Frexp)}({nameof(Float4)},{nameof(Float4)})"); - /// - /// Returns the mantissa and exponent of the specified floating-point value. - /// - /// The specified floating-point value (if the x parameter is 0, this function returns 0 for both the mantissa and the exponent) - /// The returned exponent of the parameter. - /// The fractional part of the parameter. - [Pure] - public static Vector2 Frexp(Vector2 x, out Vector2 exp) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Frexp)}({nameof(Vector2)},{nameof(Vector2)})"); - - /// - /// Returns the mantissa and exponent of the specified floating-point value. - /// - /// The specified floating-point value (if the x parameter is 0, this function returns 0 for both the mantissa and the exponent) - /// The returned exponent of the parameter. - /// The fractional part of the parameter. - [Pure] - public static Vector3 Frexp(Vector3 x, out Vector3 exp) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Frexp)}({nameof(Vector3)},{nameof(Vector3)})"); - - /// - /// Returns the mantissa and exponent of the specified floating-point value. - /// - /// The specified floating-point value (if the x parameter is 0, this function returns 0 for both the mantissa and the exponent) - /// The returned exponent of the parameter. - /// The fractional part of the parameter. - [Pure] - public static Vector4 Frexp(Vector4 x, out Vector4 exp) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Frexp)}({nameof(Vector4)},{nameof(Vector4)})"); - /// /// Performs a guaranteed atomic add of a value to a destination. /// @@ -1708,33 +1194,6 @@ namespace ComputeSharp [Pure] public static Float4 Ldexp(Float4 x, Float4 exp) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Ldexp)}({nameof(Float4)},{nameof(Float4)})"); - /// - /// Returns the result of multiplying the specified value by two, raised to the power of the specified exponent. - /// - /// The specified value. - /// The specified exponent. - /// The result of multiplying the parameter by two, raised to the power of the parameter. - [Pure] - public static Vector2 Ldexp(Vector2 x, Vector2 exp) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Ldexp)}({nameof(Vector2)},{nameof(Vector2)})"); - - /// - /// Returns the result of multiplying the specified value by two, raised to the power of the specified exponent. - /// - /// The specified value. - /// The specified exponent. - /// The result of multiplying the parameter by two, raised to the power of the parameter. - [Pure] - public static Vector3 Ldexp(Vector3 x, Vector3 exp) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Ldexp)}({nameof(Vector3)},{nameof(Vector3)})"); - - /// - /// Returns the result of multiplying the specified value by two, raised to the power of the specified exponent. - /// - /// The specified value. - /// The specified exponent. - /// The result of multiplying the parameter by two, raised to the power of the parameter. - [Pure] - public static Vector4 Ldexp(Vector4 x, Vector4 exp) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Ldexp)}({nameof(Vector4)},{nameof(Vector4)})"); - /// /// Performs a linear interpolation. /// @@ -1775,36 +1234,6 @@ namespace ComputeSharp [Pure] public static Float2 Lerp(Float4 x, Float4 y, Float4 s) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Lerp)}({nameof(Float4)},{nameof(Float4)},{nameof(Float4)})"); - /// - /// Performs a linear interpolation. - /// - /// The first value. - /// The second value. - /// A value that linearly interpolates between the parameter and the parameter. - /// The result of the linear interpolation. - [Pure] - public static Vector2 Lerp(Vector2 x, Vector2 y, Vector2 s) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Lerp)}({nameof(Vector2)},{nameof(Vector2)},{nameof(Vector2)})"); - - /// - /// Performs a linear interpolation. - /// - /// The first value. - /// The second value. - /// A value that linearly interpolates between the parameter and the parameter. - /// The result of the linear interpolation. - [Pure] - public static Vector3 Lerp(Vector3 x, Vector3 y, Vector3 s) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Lerp)}({nameof(Vector3)},{nameof(Vector3)},{nameof(Vector3)})"); - - /// - /// Performs a linear interpolation. - /// - /// The first value. - /// The second value. - /// A value that linearly interpolates between the parameter and the parameter. - /// The result of the linear interpolation. - [Pure] - public static Vector2 Lerp(Vector4 x, Vector4 y, Vector4 s) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Lerp)}({nameof(Vector4)},{nameof(Vector4)},{nameof(Vector4)})"); - /// /// Returns the base-e logarithm of the specified value. /// @@ -1837,30 +1266,6 @@ namespace ComputeSharp [Pure] public static Float4 Log(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Log)}({nameof(Float4)})"); - /// - /// Returns the base-e logarithm of the specified value. - /// - /// The specified value. - /// The base-e logarithm of the parameter (if parameter is negative this function returns indefinite, and if is 0, this function returns -INF) - [Pure] - public static Vector2 Log(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Log)}({nameof(Vector2)})"); - - /// - /// Returns the base-e logarithm of the specified value. - /// - /// The specified value. - /// The base-e logarithm of the parameter (if parameter is negative this function returns indefinite, and if is 0, this function returns -INF) - [Pure] - public static Vector3 Log(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Log)}({nameof(Vector3)})"); - - /// - /// Returns the base-e logarithm of the specified value. - /// - /// The specified value. - /// The base-e logarithm of the parameter (if parameter is negative this function returns indefinite, and if is 0, this function returns -INF) - [Pure] - public static Vector4 Log(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Log)}({nameof(Vector4)})"); - /// /// Returns the base-10 logarithm of the specified value. /// @@ -1893,30 +1298,6 @@ namespace ComputeSharp [Pure] public static Float4 Log10(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Log10)}({nameof(Float4)})"); - /// - /// Returns the base-10 logarithm of the specified value. - /// - /// The specified value. - /// The base-10 logarithm of the parameter (if parameter is negative this function returns indefinite, and if is 0, this function returns -INF) - [Pure] - public static Vector2 Log10(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Log10)}({nameof(Vector2)})"); - - /// - /// Returns the base-10 logarithm of the specified value. - /// - /// The specified value. - /// The base-10 logarithm of the parameter (if parameter is negative this function returns indefinite, and if is 0, this function returns -INF) - [Pure] - public static Vector3 Log10(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Log10)}({nameof(Vector3)})"); - - /// - /// Returns the base-10 logarithm of the specified value. - /// - /// The specified value. - /// The base-10 logarithm of the parameter (if parameter is negative this function returns indefinite, and if is 0, this function returns -INF) - [Pure] - public static Vector4 Log10(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Log10)}({nameof(Vector4)})"); - /// /// Returns the base-2 logarithm of the specified value. /// @@ -1949,30 +1330,6 @@ namespace ComputeSharp [Pure] public static Float4 Log2(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Log2)}({nameof(Float4)})"); - /// - /// Returns the base-2 logarithm of the specified value. - /// - /// The specified value. - /// The base-2 logarithm of the parameter (if parameter is negative this function returns indefinite, and if is 0, this function returns -INF) - [Pure] - public static Vector2 Log2(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Log2)}({nameof(Vector2)})"); - - /// - /// Returns the base-2 logarithm of the specified value. - /// - /// The specified value. - /// The base-2 logarithm of the parameter (if parameter is negative this function returns indefinite, and if is 0, this function returns -INF) - [Pure] - public static Vector3 Log2(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Log2)}({nameof(Vector3)})"); - - /// - /// Returns the base-2 logarithm of the specified value. - /// - /// The specified value. - /// The base-2 logarithm of the parameter (if parameter is negative this function returns indefinite, and if is 0, this function returns -INF) - [Pure] - public static Vector4 Log2(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Log2)}({nameof(Vector4)})"); - /// /// Selects the greater of and . /// @@ -2023,36 +1380,6 @@ namespace ComputeSharp [Pure] public static Float4 Max(Float4 x, Float4 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Max)}({nameof(Float4)},{nameof(Float4)})"); - /// - /// Selects the greater of and . - /// - /// The first specified value. - /// The second specified exponent. - /// The or parameter, whichever is the largest value. - /// For values of -INF or INF, will behave as expected, but for for values of , the results are undefined. - [Pure] - public static Vector2 Max(Vector2 x, Vector2 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Max)}({nameof(Vector2)},{nameof(Vector2)})"); - - /// - /// Selects the greater of and . - /// - /// The first specified value. - /// The second specified exponent. - /// The or parameter, whichever is the largest value. - /// For values of -INF or INF, will behave as expected, but for for values of , the results are undefined. - [Pure] - public static Vector3 Max(Vector3 x, Vector3 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Max)}({nameof(Vector3)},{nameof(Vector3)})"); - - /// - /// Selects the greater of and . - /// - /// The first specified value. - /// The second specified exponent. - /// The or parameter, whichever is the largest value. - /// For values of -INF or INF, will behave as expected, but for for values of , the results are undefined. - [Pure] - public static Vector4 Max(Vector4 x, Vector4 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Max)}({nameof(Vector4)},{nameof(Vector4)})"); - /// /// Selects the lesser of and . /// @@ -2103,36 +1430,6 @@ namespace ComputeSharp [Pure] public static Float4 Min(Float4 x, Float4 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Min)}({nameof(Float4)},{nameof(Float4)})"); - /// - /// Selects the lesser of and . - /// - /// The first specified value. - /// The second specified exponent. - /// The or parameter, whichever is the smallest value. - /// For values of -INF or INF, will behave as expected, but for for values of , the results are undefined. - [Pure] - public static Vector2 Min(Vector2 x, Vector2 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Min)}({nameof(Vector2)},{nameof(Vector2)})"); - - /// - /// Selects the lesser of and . - /// - /// The first specified value. - /// The second specified exponent. - /// The or parameter, whichever is the smallest value. - /// For values of -INF or INF, will behave as expected, but for for values of , the results are undefined. - [Pure] - public static Vector3 Min(Vector3 x, Vector3 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Min)}({nameof(Vector3)},{nameof(Vector3)})"); - - /// - /// Selects the lesser of and . - /// - /// The first specified value. - /// The second specified exponent. - /// The or parameter, whichever is the smallest value. - /// For values of -INF or INF, will behave as expected, but for for values of , the results are undefined. - [Pure] - public static Vector4 Min(Vector4 x, Vector4 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Min)}({nameof(Vector4)},{nameof(Vector4)})"); - /// /// Splits the value into fractional and integer parts, each of which has the same sign as . /// @@ -2205,33 +1502,6 @@ namespace ComputeSharp [Pure] public static Float4 Modf(Float4 x, out Float4 ip) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Modf)}({nameof(Float4)},{nameof(Float4)})"); - /// - /// Splits the value into fractional and integer parts, each of which has the same sign as . - /// - /// The input value. - /// The integer portion of . - /// The signed-fractional portion of . - [Pure] - public static Vector2 Modf(Vector2 x, out Vector2 ip) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Modf)}({nameof(Vector2)},{nameof(Vector2)})"); - - /// - /// Splits the value into fractional and integer parts, each of which has the same sign as . - /// - /// The input value. - /// The integer portion of . - /// The signed-fractional portion of . - [Pure] - public static Vector3 Modf(Vector3 x, out Vector3 ip) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Modf)}({nameof(Vector3)},{nameof(Vector3)})"); - - /// - /// Splits the value into fractional and integer parts, each of which has the same sign as . - /// - /// The input value. - /// The integer portion of . - /// The signed-fractional portion of . - [Pure] - public static Vector4 Modf(Vector4 x, out Vector4 ip) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Modf)}({nameof(Vector4)},{nameof(Vector4)})"); - /// /// Multiplies and using matrix math. /// @@ -2259,33 +1529,6 @@ namespace ComputeSharp [Pure] public static Float3 Mul(float x, Float4 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Mul)}(float,{nameof(Float4)})"); - /// - /// Multiplies and using matrix math. - /// - /// The first input value (if is a vector, it treated as a row vector) - /// The second input value (if is a vector, it treated as a column vector) - /// The result of times . - [Pure] - public static Vector2 Mul(float x, Vector2 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Mul)}(float,{nameof(Vector2)})"); - - /// - /// Multiplies and using matrix math. - /// - /// The first input value (if is a vector, it treated as a row vector) - /// The second input value (if is a vector, it treated as a column vector) - /// The result of times . - [Pure] - public static Vector3 Mul(float x, Vector3 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Mul)}(float,{nameof(Vector3)})"); - - /// - /// Multiplies and using matrix math. - /// - /// The first input value (if is a vector, it treated as a row vector) - /// The second input value (if is a vector, it treated as a column vector) - /// The result of times . - [Pure] - public static Vector3 Mul(float x, Vector4 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Mul)}(float,{nameof(Vector4)})"); - /// /// Multiplies and using matrix math. /// @@ -2313,33 +1556,6 @@ namespace ComputeSharp [Pure] public static Float4 Mul(Float4 x, float y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Mul)}({nameof(Float4)},float)"); - /// - /// Multiplies and using matrix math. - /// - /// The first input value (if is a vector, it treated as a row vector) - /// The second input value (if is a vector, it treated as a column vector) - /// The result of times . - [Pure] - public static Vector2 Mul(Vector2 x, float y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Mul)}({nameof(Vector2)},float)"); - - /// - /// Multiplies and using matrix math. - /// - /// The first input value (if is a vector, it treated as a row vector) - /// The second input value (if is a vector, it treated as a column vector) - /// The result of times . - [Pure] - public static Vector3 Mul(Vector3 x, float y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Mul)}({nameof(Vector3)},float)"); - - /// - /// Multiplies and using matrix math. - /// - /// The first input value (if is a vector, it treated as a row vector) - /// The second input value (if is a vector, it treated as a column vector) - /// The result of times . - [Pure] - public static Vector4 Mul(Vector4 x, float y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Mul)}({nameof(Vector4)},float)"); - /// /// Multiplies and using matrix math. /// @@ -2367,33 +1583,6 @@ namespace ComputeSharp [Pure] public static float Mul(Float4 x, Float4 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Mul)}({nameof(Float4)},{nameof(Float4)})"); - /// - /// Multiplies and using matrix math. - /// - /// The first input value (if is a vector, it treated as a row vector) - /// The second input value (if is a vector, it treated as a column vector) - /// The result of times . - [Pure] - public static float Mul(Vector2 x, Vector2 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Mul)}({nameof(Vector2)},{nameof(Vector2)})"); - - /// - /// Multiplies and using matrix math. - /// - /// The first input value (if is a vector, it treated as a row vector) - /// The second input value (if is a vector, it treated as a column vector) - /// The result of times . - [Pure] - public static float Mul(Vector3 x, Vector3 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Mul)}({nameof(Vector3)},{nameof(Vector3)})"); - - /// - /// Multiplies and using matrix math. - /// - /// The first input value (if is a vector, it treated as a row vector) - /// The second input value (if is a vector, it treated as a column vector) - /// The result of times . - [Pure] - public static float Mul(Vector4 x, Vector4 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Mul)}({nameof(Vector4)},{nameof(Vector4)})"); - /// /// Normalizes the specified floating-point vector according to / length() /// @@ -2418,30 +1607,6 @@ namespace ComputeSharp [Pure] public static Float4 Normalize(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Normalize)}({nameof(Float4)})"); - /// - /// Normalizes the specified floating-point vector according to / length() - /// - /// The specified value. - /// The normalized parameter. - [Pure] - public static Vector2 Normalize(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Normalize)}({nameof(Vector2)})"); - - /// - /// Normalizes the specified floating-point vector according to / length() - /// - /// The specified value. - /// The normalized parameter. - [Pure] - public static Vector3 Normalize(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Normalize)}({nameof(Vector3)})"); - - /// - /// Normalizes the specified floating-point vector according to / length() - /// - /// The specified value. - /// The normalized parameter. - [Pure] - public static Vector4 Normalize(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Normalize)}({nameof(Vector4)})"); - /// /// Returns the specified value raised to the specified power. /// @@ -2482,36 +1647,6 @@ namespace ComputeSharp [Pure] public static Float4 Pow(Float4 x, Float4 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Pow)}({nameof(Float4)},{nameof(Float4)})"); - /// - /// Returns the specified value raised to the specified power. - /// - /// The specified value. - /// The specified power. - /// The parameter raised to the power of the parameter. - /// See for details on special cases. - [Pure] - public static Vector2 Pow(Vector2 x, Vector2 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Pow)}({nameof(Vector2)},{nameof(Vector2)})"); - - /// - /// Returns the specified value raised to the specified power. - /// - /// The specified value. - /// The specified power. - /// The parameter raised to the power of the parameter. - /// See for details on special cases. - [Pure] - public static Vector3 Pow(Vector3 x, Vector3 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Pow)}({nameof(Vector3)},{nameof(Vector3)})"); - - /// - /// Returns the specified value raised to the specified power. - /// - /// The specified value. - /// The specified power. - /// The parameter raised to the power of the parameter. - /// See for details on special cases. - [Pure] - public static Vector4 Pow(Vector4 x, Vector4 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Pow)}({nameof(Vector4)},{nameof(Vector4)})"); - /// /// Converts the specified value from degrees to radians. /// @@ -2544,30 +1679,6 @@ namespace ComputeSharp [Pure] public static Float4 Radians(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Radians)}({nameof(Float4)})"); - /// - /// Converts the specified value from degrees to radians. - /// - /// The specified value. - /// The parameter converted from degrees to radians. - [Pure] - public static Vector2 Radians(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Radians)}({nameof(Vector2)})"); - - /// - /// Converts the specified value from degrees to radians. - /// - /// The specified value. - /// The parameter converted from degrees to radians. - [Pure] - public static Vector3 Radians(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Radians)}({nameof(Vector3)})"); - - /// - /// Converts the specified value from degrees to radians. - /// - /// The specified value. - /// The parameter converted from degrees to radians. - [Pure] - public static Vector4 Radians(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Radians)}({nameof(Vector4)})"); - /// /// Calculates a fast, approximate reciprocal of a given value. /// @@ -2600,30 +1711,6 @@ namespace ComputeSharp [Pure] public static Float4 Rcp(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Rcp)}({nameof(Float4)})"); - /// - /// Calculates a fast, approximate, per-component reciprocal. - /// - /// The specified value. - /// The reciprocal of the parameter. - [Pure] - public static Vector2 Rcp(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Rcp)}({nameof(Vector2)})"); - - /// - /// Calculates a fast, approximate, per-component reciprocal. - /// - /// The specified value. - /// The reciprocal of the parameter. - [Pure] - public static Vector3 Rcp(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Rcp)}({nameof(Vector3)})"); - - /// - /// Calculates a fast, approximate, per-component reciprocal. - /// - /// The specified value. - /// The reciprocal of the parameter. - [Pure] - public static Vector4 Rcp(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Rcp)}({nameof(Vector4)})"); - /// /// Rounds the specified value to the nearest integer. /// @@ -2656,30 +1743,6 @@ namespace ComputeSharp [Pure] public static Float4 Round(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Round)}({nameof(Float4)})"); - /// - /// Rounds the specified value to the nearest integer. - /// - /// The specified value. - /// The parameter, rounded to the nearest integer within a floating-point type. - [Pure] - public static Vector2 Round(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Round)}({nameof(Vector2)})"); - - /// - /// Rounds the specified value to the nearest integer. - /// - /// The specified value. - /// The parameter, rounded to the nearest integer within a floating-point type. - [Pure] - public static Vector3 Round(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Round)}({nameof(Vector3)})"); - - /// - /// Rounds the specified value to the nearest integer. - /// - /// The specified value. - /// The parameter, rounded to the nearest integer within a floating-point type. - [Pure] - public static Vector4 Round(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Round)}({nameof(Vector4)})"); - /// /// Returns the reciprocal of the square root of the specified value. /// @@ -2716,33 +1779,6 @@ namespace ComputeSharp [Pure] public static Float4 Rsqrt(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Rsqrt)}({nameof(Float4)})"); - /// - /// Returns the reciprocal of the square root of the specified value. - /// - /// The specified value. - /// The reciprocal of the square root of the parameter. - /// This function uses the following formula: 1 / sqrt() - [Pure] - public static Vector2 Rsqrt(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Rsqrt)}({nameof(Vector2)})"); - - /// - /// Returns the reciprocal of the square root of the specified value. - /// - /// The specified value. - /// The reciprocal of the square root of the parameter. - /// This function uses the following formula: 1 / sqrt() - [Pure] - public static Vector3 Rsqrt(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Rsqrt)}({nameof(Vector3)})"); - - /// - /// Returns the reciprocal of the square root of the specified value. - /// - /// The specified value. - /// The reciprocal of the square root of the parameter. - /// This function uses the following formula: 1 / sqrt() - [Pure] - public static Vector4 Rsqrt(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Rsqrt)}({nameof(Vector4)})"); - /// /// Clamps the specified value within the range [0,1] /// @@ -2775,30 +1811,6 @@ namespace ComputeSharp [Pure] public static Float4 Saturate(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Saturate)}({nameof(Float4)})"); - /// - /// Clamps the specified value within the range [0,1] - /// - /// The specified value. - /// The parameter, clamped within the range [0,1] - [Pure] - public static Vector2 Saturate(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Saturate)}({nameof(Vector2)})"); - - /// - /// Clamps the specified value within the range [0,1] - /// - /// The specified value. - /// The parameter, clamped within the range [0,1] - [Pure] - public static Vector3 Saturate(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Saturate)}({nameof(Vector3)})"); - - /// - /// Clamps the specified value within the range [0,1] - /// - /// The specified value. - /// The parameter, clamped within the range [0,1] - [Pure] - public static Vector4 Saturate(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Saturate)}({nameof(Vector4)})"); - /// /// Returns the sign of . /// @@ -2831,30 +1843,6 @@ namespace ComputeSharp [Pure] public static Float4 Sign(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Sign)}({nameof(Float4)})"); - /// - /// Returns the sign of . - /// - /// The input value. - /// Returns -1 if is less than zero, 0 if equals zero and 1 if is greater than zero. - [Pure] - public static Vector2 Sign(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Sign)}({nameof(Vector2)})"); - - /// - /// Returns the sign of . - /// - /// The input value. - /// Returns -1 if is less than zero, 0 if equals zero and 1 if is greater than zero. - [Pure] - public static Vector3 Sign(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Sign)}({nameof(Vector3)})"); - - /// - /// Returns the sign of . - /// - /// The input value. - /// Returns -1 if is less than zero, 0 if equals zero and 1 if is greater than zero. - [Pure] - public static Vector4 Sign(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Sign)}({nameof(Vector4)})"); - /// /// Returns the sine of the specified value. /// @@ -2887,30 +1875,6 @@ namespace ComputeSharp [Pure] public static Float4 Sin(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Sin)}({nameof(Float4)})"); - /// - /// Returns the sine of the specified value. - /// - /// The specified value, radians. - /// The sine of the parameter. - [Pure] - public static Vector2 Sin(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Sin)}({nameof(Vector2)})"); - - /// - /// Returns the sine of the specified value. - /// - /// The specified value, radians. - /// The sine of the parameter. - [Pure] - public static Vector3 Sin(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Sin)}({nameof(Vector3)})"); - - /// - /// Returns the sine of the specified value. - /// - /// The specified value, radians. - /// The sine of the parameter. - [Pure] - public static Vector4 Sin(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Sin)}({nameof(Vector4)})"); - /// /// Returns the sine and cosine of . /// @@ -2943,30 +1907,6 @@ namespace ComputeSharp /// Returns the cosine of . public static void SinCos(Float4 x, out Float4 s, out Float4 c) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(SinCos)}({nameof(Float4)},{nameof(Float4)},{nameof(Float4)})"); - /// - /// Returns the sine and cosine of . - /// - /// The specified value, radians. - /// Returns the sine of . - /// Returns the cosine of . - public static void SinCos(Vector2 x, out Vector2 s, out Vector2 c) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(SinCos)}({nameof(Vector2)},{nameof(Vector2)},{nameof(Vector2)})"); - - /// - /// Returns the sine and cosine of . - /// - /// The specified value, radians. - /// Returns the sine of . - /// Returns the cosine of . - public static void SinCos(Vector3 x, out Vector3 s, out Vector3 c) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(SinCos)}({nameof(Vector3)},{nameof(Vector3)},{nameof(Vector3)})"); - - /// - /// Returns the sine and cosine of . - /// - /// The specified value, radians. - /// Returns the sine of . - /// Returns the cosine of . - public static void SinCos(Vector4 x, out Vector4 s, out Vector4 c) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(SinCos)}({nameof(Vector4)},{nameof(Vector4)},{nameof(Vector4)})"); - /// /// Returns the hyperbolic sine of the specified value. /// @@ -2999,30 +1939,6 @@ namespace ComputeSharp [Pure] public static Float4 Sinh(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Sinh)}({nameof(Float4)})"); - /// - /// Returns the hyperbolic sine of the specified value. - /// - /// The specified value, radians. - /// The hyperbolic sine of the parameter. - [Pure] - public static Vector2 Sinh(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Sinh)}({nameof(Vector2)})"); - - /// - /// Returns the hyperbolic sine of the specified value. - /// - /// The specified value, radians. - /// The hyperbolic sine of the parameter. - [Pure] - public static Vector3 Sinh(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Sinh)}({nameof(Vector3)})"); - - /// - /// Returns the hyperbolic sine of the specified value. - /// - /// The specified value, radians. - /// The hyperbolic sine of the parameter. - [Pure] - public static Vector4 Sinh(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Sinh)}({nameof(Vector4)})"); - /// /// Returns a smooth Hermite interpolation between 0 and 1, if is in the range [, ] /// @@ -3063,36 +1979,6 @@ namespace ComputeSharp [Pure] public static Float4 SmoothStep(Float4 min, Float4 max, Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(SmoothStep)}({nameof(Float4)},{nameof(Float4)},{nameof(Float4)})"); - /// - /// Returns a smooth Hermite interpolation between 0 and 1, if is in the range [, ] - /// - /// The minimum range of the parameter. - /// The maximum range of the parameter. - /// The specified value to be interpolated. - /// 0 if is less than , 1 if is greater than , otherwise a value between 0 and 1 if is in the range [, ] - [Pure] - public static Vector2 SmoothStep(Vector2 min, Vector2 max, Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(SmoothStep)}({nameof(Vector2)},{nameof(Vector2)},{nameof(Vector2)})"); - - /// - /// Returns a smooth Hermite interpolation between 0 and 1, if is in the range [, ] - /// - /// The minimum range of the parameter. - /// The maximum range of the parameter. - /// The specified value to be interpolated. - /// 0 if is less than , 1 if is greater than , otherwise a value between 0 and 1 if is in the range [, ] - [Pure] - public static Vector3 SmoothStep(Vector3 min, Vector3 max, Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(SmoothStep)}({nameof(Vector3)},{nameof(Vector3)},{nameof(Vector3)})"); - - /// - /// Returns a smooth Hermite interpolation between 0 and 1, if is in the range [, ] - /// - /// The minimum range of the parameter. - /// The maximum range of the parameter. - /// The specified value to be interpolated. - /// 0 if is less than , 1 if is greater than , otherwise a value between 0 and 1 if is in the range [, ] - [Pure] - public static Vector4 SmoothStep(Vector4 min, Vector4 max, Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(SmoothStep)}({nameof(Vector4)},{nameof(Vector4)},{nameof(Vector4)})"); - /// /// Returns the square root of the specified floating-point value. /// @@ -3125,30 +2011,6 @@ namespace ComputeSharp [Pure] public static Float4 Sqrt(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Sqrt)}({nameof(Float4)})"); - /// - /// Returns the square root of the specified floating-point value, per component. - /// - /// The specified value. - /// The square root of the parameter, per component. - [Pure] - public static Vector2 Sqrt(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Sqrt)}({nameof(Vector2)})"); - - /// - /// Returns the square root of the specified floating-point value, per component. - /// - /// The specified value. - /// The square root of the parameter, per component. - [Pure] - public static Vector3 Sqrt(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Sqrt)}({nameof(Vector3)})"); - - /// - /// Returns the square root of the specified floating-point value, per component. - /// - /// The specified value. - /// The square root of the parameter, per component. - [Pure] - public static Vector4 Sqrt(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Sqrt)}({nameof(Vector4)})"); - /// /// Compares two values, returning 0 or 1 based on which value is greater. /// @@ -3189,36 +2051,6 @@ namespace ComputeSharp [Pure] public static Float4 Step(Float4 x, Float4 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Step)}({nameof(Float4)},{nameof(Float4)})"); - /// - /// Compares two values, returning 0 or 1 based on which value is greater. - /// - /// The first specified value to compare. - /// The second specified value to compare. - /// 1 if the parameter is greater than or equal to the parameter, otherwise, 0. - /// This function uses the following formula: (x >= y) ? 1 : 0. - [Pure] - public static Vector2 Step(Vector2 x, Vector2 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Step)}({nameof(Vector2)},{nameof(Vector2)})"); - - /// - /// Compares two values, returning 0 or 1 based on which value is greater. - /// - /// The first specified value to compare. - /// The second specified value to compare. - /// 1 if the parameter is greater than or equal to the parameter, otherwise, 0. - /// This function uses the following formula: (x >= y) ? 1 : 0. - [Pure] - public static Vector3 Step(Vector3 x, Vector3 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Step)}({nameof(Vector3)},{nameof(Vector3)})"); - - /// - /// Compares two values, returning 0 or 1 based on which value is greater. - /// - /// The first specified value to compare. - /// The second specified value to compare. - /// 1 if the parameter is greater than or equal to the parameter, otherwise, 0. - /// This function uses the following formula: (x >= y) ? 1 : 0. - [Pure] - public static Vector4 Step(Vector4 x, Vector4 y) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Step)}({nameof(Vector4)},{nameof(Vector4)})"); - /// /// Returns the tangent of the specified value. /// @@ -3251,30 +2083,6 @@ namespace ComputeSharp [Pure] public static Float4 Tan(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Tan)}({nameof(Float4)})"); - /// - /// Returns the tangent of the specified value. - /// - /// The specified value, radians. - /// The tangent of the parameter. - [Pure] - public static Vector2 Tan(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Tan)}({nameof(Vector2)})"); - - /// - /// Returns the tangent of the specified value. - /// - /// The specified value, radians. - /// The tangent of the parameter. - [Pure] - public static Vector3 Tan(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Tan)}({nameof(Vector3)})"); - - /// - /// Returns the tangent of the specified value. - /// - /// The specified value, radians. - /// The tangent of the parameter. - [Pure] - public static Vector4 Tan(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Tan)}({nameof(Vector4)})"); - /// /// Returns the hyperbolic tangent of the specified value. /// @@ -3307,30 +2115,6 @@ namespace ComputeSharp [Pure] public static Float4 Tanh(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Tanh)}({nameof(Float4)})"); - /// - /// Returns the hyperbolic tangent of the specified value. - /// - /// The specified value, radians. - /// The hyperbolic tangent of the parameter. - [Pure] - public static Vector2 Tanh(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Tanh)}({nameof(Vector2)})"); - - /// - /// Returns the hyperbolic tangent of the specified value. - /// - /// The specified value, radians. - /// The hyperbolic tangent of the parameter. - [Pure] - public static Vector3 Tanh(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Tanh)}({nameof(Vector3)})"); - - /// - /// Returns the hyperbolic tangent of the specified value. - /// - /// The specified value, radians. - /// The hyperbolic tangent of the parameter. - [Pure] - public static Vector4 Tanh(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Tanh)}({nameof(Vector4)})"); - /// /// Truncates a floating-point value to the integer component. /// @@ -3362,29 +2146,5 @@ namespace ComputeSharp /// The parameter truncated to an integer component. [Pure] public static Float4 Trunc(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Trunc)}({nameof(Float4)})"); - - /// - /// Truncates a floating-point value to the integer component. - /// - /// The specified value, radians. - /// The parameter truncated to an integer component. - [Pure] - public static Vector2 Trunc(Vector2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Trunc)}({nameof(Vector2)})"); - - /// - /// Truncates a floating-point value to the integer component. - /// - /// The specified value, radians. - /// The parameter truncated to an integer component. - [Pure] - public static Vector3 Trunc(Vector3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Trunc)}({nameof(Vector3)})"); - - /// - /// Truncates a floating-point value to the integer component. - /// - /// The specified value, radians. - /// The parameter truncated to an integer component. - [Pure] - public static Vector4 Trunc(Vector4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Trunc)}({nameof(Vector4)})"); } } diff --git a/src/ComputeSharp.Core/Primitives/Float/Float2.cs b/src/ComputeSharp.Core/Primitives/Float/Float2.cs index 42067446..36168a1c 100644 --- a/src/ComputeSharp.Core/Primitives/Float/Float2.cs +++ b/src/ComputeSharp.Core/Primitives/Float/Float2.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Numerics; using System.Runtime.InteropServices; using ComputeSharp.Exceptions; @@ -142,6 +143,18 @@ namespace ComputeSharp /// The value to use for the components of the new instance. public static implicit operator Float2(float x) => new(x, x); + /// + /// Casts a value to a one. + /// + /// The input value to cast. + public static unsafe implicit operator Vector2(Float2 xy) => *(Vector2*)&xy; + + /// + /// Casts a value to a one. + /// + /// The input value to cast. + public static unsafe implicit operator Float2(Vector2 xy) => *(Float2*)&xy; + /// /// Casts a value to a one. /// diff --git a/src/ComputeSharp.Core/Primitives/Float/Float3.cs b/src/ComputeSharp.Core/Primitives/Float/Float3.cs index 30069e33..eeeea995 100644 --- a/src/ComputeSharp.Core/Primitives/Float/Float3.cs +++ b/src/ComputeSharp.Core/Primitives/Float/Float3.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Numerics; using System.Runtime.InteropServices; using ComputeSharp.Exceptions; @@ -563,6 +564,18 @@ namespace ComputeSharp /// The value to use for the components of the new instance. public static implicit operator Float3(float x) => new(x, x, x); + /// + /// Casts a value to a one. + /// + /// The input value to cast. + public static unsafe implicit operator Vector3(Float3 xyz) => *(Vector3*)&xyz; + + /// + /// Casts a value to a one. + /// + /// The input value to cast. + public static unsafe implicit operator Float3(Vector3 xyz) => *(Float3*)&xyz; + /// /// Casts a value to a one. /// diff --git a/src/ComputeSharp.Core/Primitives/Float/Float4.cs b/src/ComputeSharp.Core/Primitives/Float/Float4.cs index 944ec16e..5b7904a6 100644 --- a/src/ComputeSharp.Core/Primitives/Float/Float4.cs +++ b/src/ComputeSharp.Core/Primitives/Float/Float4.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Numerics; using System.Runtime.InteropServices; using ComputeSharp.Exceptions; @@ -3968,6 +3969,18 @@ namespace ComputeSharp /// The value to use for the components of the new instance. public static implicit operator Float4(float x) => new(x, x, x, x); + /// + /// Casts a value to a one. + /// + /// The input value to cast. + public static unsafe implicit operator Vector4(Float4 xyzw) => *(Vector4*)&xyzw; + + /// + /// Casts a value to a one. + /// + /// The input value to cast. + public static unsafe implicit operator Float4(Vector4 xyzw) => *(Float4*)&xyzw; + /// /// Casts a value to a one. /// diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 04f729f7..03fb352f 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -2,6 +2,7 @@ netstandard2.0 + true 9.0 @@ -12,7 +13,7 @@ + and to match members based on full name, so the types being in the generator assembly are not an issue.--> From e3775e842499342fa0c068a242b2cde3b0ef7ab9 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Jan 2021 18:38:15 +0100 Subject: [PATCH 22/26] Fixed warnings due to missing nullability annotations --- src/ComputeSharp.Core/PixelTypes/R16.cs | 2 +- src/ComputeSharp.Core/PixelTypes/R8.cs | 2 +- src/ComputeSharp.Core/PixelTypes/Rg32.cs | 2 +- src/ComputeSharp.Core/PixelTypes/Rgba32.cs | 2 +- src/ComputeSharp.Core/PixelTypes/Rgba64.cs | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/ComputeSharp.Core/PixelTypes/R16.cs b/src/ComputeSharp.Core/PixelTypes/R16.cs index 1cf56e8d..8e6a8951 100644 --- a/src/ComputeSharp.Core/PixelTypes/R16.cs +++ b/src/ComputeSharp.Core/PixelTypes/R16.cs @@ -65,7 +65,7 @@ namespace ComputeSharp public static bool operator !=(R16 left, R16 right) => !left.Equals(right); /// - public override readonly bool Equals(object obj) => obj is R16 R16 && Equals(R16); + public override readonly bool Equals(object? obj) => obj is R16 R16 && Equals(R16); /// [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/src/ComputeSharp.Core/PixelTypes/R8.cs b/src/ComputeSharp.Core/PixelTypes/R8.cs index a5c4fbe1..cb627b96 100644 --- a/src/ComputeSharp.Core/PixelTypes/R8.cs +++ b/src/ComputeSharp.Core/PixelTypes/R8.cs @@ -65,7 +65,7 @@ namespace ComputeSharp public static bool operator !=(R8 left, R8 right) => !left.Equals(right); /// - public override readonly bool Equals(object obj) => obj is R8 R8 && Equals(R8); + public override readonly bool Equals(object? obj) => obj is R8 R8 && Equals(R8); /// [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/src/ComputeSharp.Core/PixelTypes/Rg32.cs b/src/ComputeSharp.Core/PixelTypes/Rg32.cs index 3ad82522..10f5a7c1 100644 --- a/src/ComputeSharp.Core/PixelTypes/Rg32.cs +++ b/src/ComputeSharp.Core/PixelTypes/Rg32.cs @@ -73,7 +73,7 @@ namespace ComputeSharp public static bool operator !=(Rg32 left, Rg32 right) => !left.Equals(right); /// - public override readonly bool Equals(object obj) => obj is Rg32 rgba32 && Equals(rgba32); + public override readonly bool Equals(object? obj) => obj is Rg32 rgba32 && Equals(rgba32); /// [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/src/ComputeSharp.Core/PixelTypes/Rgba32.cs b/src/ComputeSharp.Core/PixelTypes/Rgba32.cs index 75b25d60..7e21c856 100644 --- a/src/ComputeSharp.Core/PixelTypes/Rgba32.cs +++ b/src/ComputeSharp.Core/PixelTypes/Rgba32.cs @@ -105,7 +105,7 @@ namespace ComputeSharp public static bool operator !=(Rgba32 left, Rgba32 right) => !left.Equals(right); /// - public override readonly bool Equals(object obj) => obj is Rgba32 rgba32 && Equals(rgba32); + public override readonly bool Equals(object? obj) => obj is Rgba32 rgba32 && Equals(rgba32); /// [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/src/ComputeSharp.Core/PixelTypes/Rgba64.cs b/src/ComputeSharp.Core/PixelTypes/Rgba64.cs index 4fd444e1..7d1c7eb1 100644 --- a/src/ComputeSharp.Core/PixelTypes/Rgba64.cs +++ b/src/ComputeSharp.Core/PixelTypes/Rgba64.cs @@ -105,7 +105,7 @@ namespace ComputeSharp public static bool operator !=(Rgba64 left, Rgba64 right) => !left.Equals(right); /// - public override readonly bool Equals(object obj) => obj is Rgba64 rgba32 && Equals(rgba32); + public override readonly bool Equals(object? obj) => obj is Rgba64 rgba32 && Equals(rgba32); /// [MethodImpl(MethodImplOptions.AggressiveInlining)] From df2301b78268e4be519fa05a06994831047e4f1f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Jan 2021 19:34:01 +0100 Subject: [PATCH 23/26] Switched bokeh blur effect to textures --- .../ComputeSharp.Benchmark.csproj | 1 - .../Primitives/ComplexVector4.cs | 23 ---- .../Processors/HlslBokehBlurProcessor.cs | 85 +------------ .../HlslBokehBlurProcessor{TPixel}.cs | 120 +++++++++++++++--- 4 files changed, 103 insertions(+), 126 deletions(-) delete mode 100644 samples/ComputeSharp.ImageProcessing/Primitives/ComplexVector4.cs diff --git a/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj index 4a6eded4..ccadcf15 100644 --- a/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj +++ b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj @@ -7,7 +7,6 @@ - diff --git a/samples/ComputeSharp.ImageProcessing/Primitives/ComplexVector4.cs b/samples/ComputeSharp.ImageProcessing/Primitives/ComplexVector4.cs deleted file mode 100644 index 1c24a7dd..00000000 --- a/samples/ComputeSharp.ImageProcessing/Primitives/ComplexVector4.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) Six Labors. -// Licensed under the Apache License, Version 2.0. - -using System.Numerics; - -namespace SixLabors.ImageSharp -{ - /// - /// A vector with a pair of representing a complex color. - /// - internal struct ComplexVector4 - { - /// - /// The real part of the complex vector. - /// - public Vector4 Real; - - /// - /// The imaginary part of the complex number. - /// - public Vector4 Imaginary; - } -} \ No newline at end of file diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs index e9bd5cfe..dd4ecb24 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs @@ -1,5 +1,4 @@ -using System.Numerics; -using System.Runtime.CompilerServices; +using System.Runtime.CompilerServices; using Microsoft.Toolkit.Diagnostics; using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; @@ -65,87 +64,5 @@ namespace ComputeSharp.BokehBlur.Processors return Unsafe.As>(processor); } - - /// - /// Kernel for the vertical convolution pass. - /// - [AutoConstructor] - internal partial struct VerticalConvolutionProcessor : IComputeShader - { - public int width; - public int maxY; - public int maxX; - public int kernelLength; - - public ReadOnlyBuffer source; - public ReadWriteBuffer target; - public ReadOnlyBuffer kernel; - - /// - public void Execute(ThreadIds ids) - { - Vector4 real = Vector4.Zero; - Vector4 imaginary = Vector4.Zero; - int radiusY = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; - - for (int i = 0; i < kernelLength; i++) - { - int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); - Vector4 color = source[offsetY * width + offsetX]; - Complex64 factors = kernel[i]; - - real += factors.Real * color; - imaginary += factors.Imaginary * color; - } - - int offsetXY = ids.Y * width + ids.X; - - target[offsetXY].Real = real; - target[offsetXY].Imaginary = imaginary; - } - } - - /// - /// Kernel for the horizontal convolution pass. - /// - [AutoConstructor] - internal partial struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader - { - public int width; - public int maxY; - public int maxX; - public int kernelLength; - public float z; - public float w; - - public ReadWriteBuffer source; - public ReadWriteBuffer target; - public ReadOnlyBuffer kernel; - - /// - public void Execute(ThreadIds ids) - { - Vector4 real = Vector4.Zero; - Vector4 imaginary = Vector4.Zero; - int radiusX = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; - int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); - - for (int i = 0; i < kernelLength; i++) - { - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX); - var offsetXY = offsetY * width + offsetX; - ComplexVector4 source4 = source[offsetXY]; - Complex64 factors = kernel[i]; - - real += factors.Real * source4.Real - factors.Imaginary * source4.Imaginary; - imaginary += factors.Real * source4.Imaginary + factors.Imaginary * source4.Real; - } - - target[ids.Y * width + ids.X] += real * z + imaginary * w; - } - } } } diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs index f35defb8..a9937447 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs @@ -257,9 +257,10 @@ namespace ComputeSharp.BokehBlur.Processors // Preliminary gamma highlight pass using IMemoryOwner source4 = GetExposedVector4Buffer(memory); - using ReadOnlyBuffer sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(source4.Memory.Span); - using ReadWriteBuffer processingBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Length); - using ReadWriteBuffer firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Length); + using ReadOnlyTexture2D sourceTexture = Gpu.Default.AllocateReadOnlyTexture2D(source4.Memory.Span, source.Width, source.Height); + using ReadWriteTexture2D processingTexture = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); + using ReadWriteTexture2D realTexture = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); + using ReadWriteTexture2D imaginaryTexture = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(KernelSize); ref Vector4 param0 = ref KernelParameters[0]; // Avoid bounds check to access the kernel parameters @@ -270,12 +271,12 @@ namespace ComputeSharp.BokehBlur.Processors kernelBuffer.SetData(Kernels[j]); Vector4 parameters = Unsafe.Add(ref param0, j); - ApplyVerticalConvolution(sourceBuffer, firstPassBuffer, kernelBuffer); - ApplyHorizontalConvolutionAndAccumulatePartials(firstPassBuffer, processingBuffer, kernelBuffer, parameters.Z, parameters.W); + ApplyVerticalConvolution(sourceTexture, realTexture, imaginaryTexture, kernelBuffer); + ApplyHorizontalConvolutionAndAccumulatePartials(realTexture, imaginaryTexture, processingTexture, kernelBuffer, parameters.Z, parameters.W); } // Apply the inverse gamma exposure pass - processingBuffer.GetData(source4.Memory.Span); + processingTexture.GetData(source4.Memory.Span); // Write the final pixel data ApplyInverseGammaExposure(source4.Memory, memory); @@ -285,42 +286,84 @@ namespace ComputeSharp.BokehBlur.Processors /// /// Performs a vertical 1D complex convolution with the specified parameters. /// - /// The source to read data from. - /// The target to write the results to. + /// The source to read data from. + /// The target to write the real results to. + /// The target to write the imaginary results to. /// The with the values for the current complex kernel. [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ApplyVerticalConvolution( - ReadOnlyBuffer source, - ReadWriteBuffer target, + ReadOnlyTexture2D source, + ReadWriteTexture2D reals, + ReadWriteTexture2D imaginaries, ReadOnlyBuffer kernel) { int height = Source.Height; int width = Source.Width; VerticalConvolutionProcessor shader = new( - width, maxY: height - 1, maxX: width - 1, kernelLength: kernel.Length, source, - target, + reals, + imaginaries, kernel); Gpu.Default.For(width, height, in shader); } + /// + /// Kernel for the vertical convolution pass. + /// + [AutoConstructor] + internal partial struct VerticalConvolutionProcessor : IComputeShader + { + public int maxY; + public int maxX; + public int kernelLength; + + public ReadOnlyTexture2D source; + public ReadWriteTexture2D reals; + public ReadWriteTexture2D imaginaries; + public ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) + { + Vector4 real = Vector4.Zero; + Vector4 imaginary = Vector4.Zero; + int radiusY = kernelLength >> 1; + int sourceOffsetColumnBase = ids.X; + + for (int i = 0; i < kernelLength; i++) + { + int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); + int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); + Vector4 color = source[offsetX, offsetY]; + Complex64 factors = kernel[i]; + + real += factors.Real * color; + imaginary += factors.Imaginary * color; + } + + reals[ids.XY] = real; + imaginaries[ids.XY] = imaginary; + } + } + /// /// Performs an horizontal 1D complex convolution with the specified parameters. /// - /// The source to read data from. - /// The target to write the results to. + /// The source to read the real results from. + /// The source to read the imaginary results from. /// The with the values for the current complex kernel. /// The weight factor for the real component of the complex pixel values. /// The weight factor for the imaginary component of the complex pixel values. [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ApplyHorizontalConvolutionAndAccumulatePartials( - ReadWriteBuffer source, - ReadWriteBuffer target, + ReadWriteTexture2D reals, + ReadWriteTexture2D imaginaries, + ReadWriteTexture2D target, ReadOnlyBuffer kernel, float z, float w) @@ -329,19 +372,60 @@ namespace ComputeSharp.BokehBlur.Processors int width = Source.Width; HorizontalConvolutionAndAccumulatePartialsProcessor shader = new( - width, maxY: height - 1, maxX: width - 1, kernelLength: kernel.Length, z, w, - source, + reals, + imaginaries, target, kernel); Gpu.Default.For(width, height, in shader); } + /// + /// Kernel for the horizontal convolution pass. + /// + [AutoConstructor] + internal partial struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader + { + public int maxY; + public int maxX; + public int kernelLength; + public float z; + public float w; + + public ReadWriteTexture2D reals; + public ReadWriteTexture2D imaginaries; + public ReadWriteTexture2D target; + public ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) + { + Vector4 real = Vector4.Zero; + Vector4 imaginary = Vector4.Zero; + int radiusX = kernelLength >> 1; + int sourceOffsetColumnBase = ids.X; + int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); + + for (int i = 0; i < kernelLength; i++) + { + int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX); + Vector4 sourceReal = reals[offsetX, offsetY]; + Vector4 sourceImaginary = imaginaries[offsetX, offsetY]; + Complex64 factors = kernel[i]; + + real += factors.Real * sourceReal - factors.Imaginary * sourceImaginary; + imaginary += factors.Real * sourceImaginary + factors.Imaginary * sourceReal; + } + + target[ids.XY] += real * z + imaginary * w; + } + } + /// /// Applies the gamma correction/highlight to the input pixel buffer and returns an instance with values. /// From e349eb78f4a252bdeb97aca18d031d71bb035409 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Jan 2021 20:17:41 +0100 Subject: [PATCH 24/26] Enabled GPU-side pixel format conversion in bokeh blur --- .../HlslBokehBlurProcessor{TPixel}.cs | 165 +++++++----------- 1 file changed, 65 insertions(+), 100 deletions(-) diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs index a9937447..0f175def 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs @@ -1,14 +1,12 @@ using System; -using System.Buffers; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using Microsoft.Toolkit.Diagnostics; using SixLabors.ImageSharp; -using SixLabors.ImageSharp.Advanced; -using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; @@ -252,35 +250,39 @@ namespace ComputeSharp.BokehBlur.Processors /// protected override void OnFrameApply(ImageFrame source) { - foreach (Memory memory in source.GetPixelMemoryGroup()) + if (!source.TryGetSinglePixelSpan(out Span pixelSpan)) { - // Preliminary gamma highlight pass - using IMemoryOwner source4 = GetExposedVector4Buffer(memory); - - using ReadOnlyTexture2D sourceTexture = Gpu.Default.AllocateReadOnlyTexture2D(source4.Memory.Span, source.Width, source.Height); - using ReadWriteTexture2D processingTexture = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); - using ReadWriteTexture2D realTexture = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); - using ReadWriteTexture2D imaginaryTexture = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); - using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(KernelSize); - - ref Vector4 param0 = ref KernelParameters[0]; // Avoid bounds check to access the kernel parameters - - // Perform two 1D convolutions for each component in the current instance - for (int j = 0; j < Kernels.Length; j++) - { - kernelBuffer.SetData(Kernels[j]); - Vector4 parameters = Unsafe.Add(ref param0, j); - - ApplyVerticalConvolution(sourceTexture, realTexture, imaginaryTexture, kernelBuffer); - ApplyHorizontalConvolutionAndAccumulatePartials(realTexture, imaginaryTexture, processingTexture, kernelBuffer, parameters.Z, parameters.W); - } - - // Apply the inverse gamma exposure pass - processingTexture.GetData(source4.Memory.Span); - - // Write the final pixel data - ApplyInverseGammaExposure(source4.Memory, memory); + ThrowHelper.ThrowInvalidOperationException("Cannot process image frames wrapping discontiguous memory"); } + + Span span = MemoryMarshal.Cast(pixelSpan); + + using ReadWriteTexture2D sourceTexture = Gpu.Default.AllocateReadWriteTexture2D(span, source.Width, source.Height); + using ReadWriteTexture2D processingTexture = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); + using ReadWriteTexture2D realTexture = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); + using ReadWriteTexture2D imaginaryTexture = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); + using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(KernelSize); + + // Preliminary gamma highlight pass + ApplyGammaHighlight(sourceTexture); + + ref Vector4 param0 = ref MemoryMarshal.GetArrayDataReference(KernelParameters); + + // Perform two 1D convolutions for each component in the current instance + for (int j = 0; j < Kernels.Length; j++) + { + kernelBuffer.SetData(Kernels[j]); + Vector4 parameters = Unsafe.Add(ref param0, j); + + ApplyVerticalConvolution(sourceTexture, realTexture, imaginaryTexture, kernelBuffer); + ApplyHorizontalConvolutionAndAccumulatePartials(realTexture, imaginaryTexture, processingTexture, kernelBuffer, parameters.Z, parameters.W); + } + + // Apply the inverse gamma exposure pass + ApplyInverseGammaExposure(processingTexture, sourceTexture); + + // Write the final pixel data + sourceTexture.GetData(span); } /// @@ -292,7 +294,7 @@ namespace ComputeSharp.BokehBlur.Processors /// The with the values for the current complex kernel. [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ApplyVerticalConvolution( - ReadOnlyTexture2D source, + ReadWriteTexture2D source, ReadWriteTexture2D reals, ReadWriteTexture2D imaginaries, ReadOnlyBuffer kernel) @@ -322,7 +324,7 @@ namespace ComputeSharp.BokehBlur.Processors public int maxX; public int kernelLength; - public ReadOnlyTexture2D source; + public ReadWriteTexture2D source; public ReadWriteTexture2D reals; public ReadWriteTexture2D imaginaries; public ReadOnlyBuffer kernel; @@ -427,112 +429,75 @@ namespace ComputeSharp.BokehBlur.Processors } /// - /// Applies the gamma correction/highlight to the input pixel buffer and returns an instance with values. + /// Applies the gamma highlight pass to compute the final pixel values for a target image. /// - /// The source image. + /// The source instance to modify. [Pure] - private IMemoryOwner GetExposedVector4Buffer(Memory source) + private void ApplyGammaHighlight(ReadWriteTexture2D source) { - IMemoryOwner target = Configuration.MemoryAllocator.Allocate(source.Length); - - int width = Source.Width; - int height = source.Length / width; - - ParallelRowIterator.IterateRows( - Configuration, - new Rectangle(0, 0, width, height), - new GetExposedVector4BufferProcessor(width, source, target.Memory, Configuration)); - - return target; + Gpu.Default.For(source.Height, new GammaHighlightProcessor(source.Width, source)); } /// - /// The processor for . + /// Kernel for the gamma highlight pass. /// [AutoConstructor] - private readonly partial struct GetExposedVector4BufferProcessor : IRowOperation + internal readonly partial struct GammaHighlightProcessor : IComputeShader { - private readonly int width; + public readonly int width; - private readonly Memory source; - private readonly Memory target; - private readonly Configuration configuration; + public readonly ReadWriteTexture2D source; /// - public void Invoke(int y) + public void Execute(ThreadIds ids) { - int offset = y * width; - - Span rowTPixel = source.Span.Slice(offset, width); - Span rowVector4 = target.Span.Slice(offset, width); - - PixelOperations.Instance.ToVector4(configuration, rowTPixel, rowVector4); - - foreach (ref Vector4 v in rowVector4) + for (int i = 0; i < width; i++) { - Vector4 pixel = v; - float alpha = pixel.W; + Float4 v = source[i, ids.X]; - pixel = pixel * pixel * pixel; - pixel.W = alpha; + v.XYZ = v.XYZ * v.XYZ * v.XYZ; - v = pixel; + source[i, ids.X] = v; } } } /// - /// Applies the inverse gamma exposure pass to compute the final pixel values for a target image. + /// Applies the inverse gamma highlight pass to compute the final pixel values for a target image. /// - /// The source buffer to read from. - /// The target image. + /// The source instance to read from. + /// The target instance to write to. [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ApplyInverseGammaExposure(Memory source, Memory target) + private void ApplyInverseGammaExposure( + ReadWriteTexture2D source, + ReadWriteTexture2D target) { - int width = Source.Width; - int height = source.Length / width; - - ParallelRowIterator.IterateRows( - Configuration, - new Rectangle(0, 0, width, height), - new ApplyInverseGammaExposureProcessor(width, source, target, Configuration)); + Gpu.Default.For(source.Height, new InverseGammaHighlightProcessor(source.Width, source, target)); } /// - /// The processor for . + /// Kernel for the inverse gamma highlight pass. /// [AutoConstructor] - private readonly partial struct ApplyInverseGammaExposureProcessor : IRowOperation + internal readonly partial struct InverseGammaHighlightProcessor : IComputeShader { - private readonly int width; + public readonly int width; - private readonly Memory source; - private readonly Memory target; - private readonly Configuration configuration; + public readonly ReadWriteTexture2D source; + public readonly ReadWriteTexture2D target; /// - public void Invoke(int y) + public void Execute(ThreadIds ids) { - int offset = y * width; - - Span rowVector4 = source.Span.Slice(offset, width); - Span rowTPixel = target.Span.Slice(offset, width); - - Vector4 low = Vector4.Zero; - var high = new Vector4(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); - - foreach (ref Vector4 v in rowVector4) + for (int i = 0; i < width; i++) { - var clamp = Vector4.Clamp(v, low, high); + Float4 v = source[i, ids.X]; - clamp.X = MathF.Pow(clamp.X, 1 / 3f); - clamp.Y = MathF.Pow(clamp.Y, 1 / 3f); - clamp.Z = MathF.Pow(clamp.Z, 1 / 3f); + v.XYZ = Hlsl.Clamp(v.XYZ, 0, float.MaxValue); + v.XYZ = Hlsl.Pow(v.XYZ, 0.333333343f); - v = clamp; + target[i, ids.X] = v; } - - PixelOperations.Instance.FromVector4Destructive(configuration, rowVector4, rowTPixel); } } } From d5992f0039673a15097af4c3681bf2ec4da7a1af Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Jan 2021 20:24:45 +0100 Subject: [PATCH 25/26] Fixed parsing issue with HLSL float literals --- .../Processors/HlslBokehBlurProcessor{TPixel}.cs | 2 +- .../SyntaxRewriters/ShaderSourceRewriter.cs | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs index 0f175def..25d0d23b 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs @@ -494,7 +494,7 @@ namespace ComputeSharp.BokehBlur.Processors Float4 v = source[i, ids.X]; v.XYZ = Hlsl.Clamp(v.XYZ, 0, float.MaxValue); - v.XYZ = Hlsl.Pow(v.XYZ, 0.333333343f); + v.XYZ = Hlsl.Pow(v.XYZ, 1 / 3f); target[i, ids.X] = v; } diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 2331d5ea..0f089902 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -218,11 +218,15 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters // in HLSL, we can remove the suffix entirely. As for 64 bit values, we simply use the 'L' suffix. if (type.GetFullMetadataName().Equals(typeof(float).FullName)) { - return updatedNode.WithToken(Literal(updatedNode.Token.ValueText, 0f)); + string literal = updatedNode.Token.ValueText; + + if (!literal.Contains('.')) literal += ".0"; + + return updatedNode.WithToken(Literal(literal, 0f)); } else if (type.GetFullMetadataName().Equals(typeof(double).FullName)) { - return updatedNode.WithToken(Literal($"{updatedNode.Token.ValueText}L", 0d)); + return updatedNode.WithToken(Literal(updatedNode.Token.ValueText + "L", 0d)); } } From f6a7e3f7f3aadb7c559a6938f72b33bee4e60067 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Jan 2021 20:34:59 +0100 Subject: [PATCH 26/26] Removed ShareX sample --- ComputeSharp.sln | 11 - .../ComputeSharp.ShareX.csproj | 26 -- samples/ComputeSharp.ShareX/Cpu/ColorBgra.cs | 120 --------- .../Cpu/ConvolutionMatrix.cs | 66 ----- .../Cpu/ConvolutionMatrixManager.cs | 148 ----------- .../ComputeSharp.ShareX/Cpu/MathHelpers.cs | 41 --- .../Cpu/NumberExtensions.cs | 39 --- .../ComputeSharp.ShareX/Cpu/UnsafeBitmap.cs | 192 -------------- .../Gpu/HlslConvolutionManager.cs.cs | 239 ------------------ samples/ComputeSharp.ShareX/Program.cs | 44 ---- 10 files changed, 926 deletions(-) delete mode 100644 samples/ComputeSharp.ShareX/ComputeSharp.ShareX.csproj delete mode 100644 samples/ComputeSharp.ShareX/Cpu/ColorBgra.cs delete mode 100644 samples/ComputeSharp.ShareX/Cpu/ConvolutionMatrix.cs delete mode 100644 samples/ComputeSharp.ShareX/Cpu/ConvolutionMatrixManager.cs delete mode 100644 samples/ComputeSharp.ShareX/Cpu/MathHelpers.cs delete mode 100644 samples/ComputeSharp.ShareX/Cpu/NumberExtensions.cs delete mode 100644 samples/ComputeSharp.ShareX/Cpu/UnsafeBitmap.cs delete mode 100644 samples/ComputeSharp.ShareX/Gpu/HlslConvolutionManager.cs.cs delete mode 100644 samples/ComputeSharp.ShareX/Program.cs diff --git a/ComputeSharp.sln b/ComputeSharp.sln index 2c84c1f5..cccc08d6 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -47,8 +47,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Tests.Internal EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Tests.NativeLibrariesResolver", "tests\ComputeSharp.Tests.NativeLibrariesResolver\ComputeSharp.Tests.NativeLibrariesResolver.csproj", "{BF52326F-E415-49E6-8595-62762216762B}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.ShareX", "samples\ComputeSharp.ShareX\ComputeSharp.ShareX.csproj", "{E200B2A8-6BC4-4F50-9D4F-7BAF06F1813A}" -EndProject Global GlobalSection(SharedMSBuildProjectFiles) = preSolution samples\ComputeSharp.Sample.Shared\ComputeSharp.Sample.Shared.projitems*{7048deea-0a6f-46a0-b951-b682a8f1cb75}*SharedItemsImports = 5 @@ -174,14 +172,6 @@ Global {BF52326F-E415-49E6-8595-62762216762B}.Release|Any CPU.Build.0 = Release|Any CPU {BF52326F-E415-49E6-8595-62762216762B}.Release|x64.ActiveCfg = Release|Any CPU {BF52326F-E415-49E6-8595-62762216762B}.Release|x64.Build.0 = Release|Any CPU - {E200B2A8-6BC4-4F50-9D4F-7BAF06F1813A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E200B2A8-6BC4-4F50-9D4F-7BAF06F1813A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E200B2A8-6BC4-4F50-9D4F-7BAF06F1813A}.Debug|x64.ActiveCfg = Debug|Any CPU - {E200B2A8-6BC4-4F50-9D4F-7BAF06F1813A}.Debug|x64.Build.0 = Debug|Any CPU - {E200B2A8-6BC4-4F50-9D4F-7BAF06F1813A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E200B2A8-6BC4-4F50-9D4F-7BAF06F1813A}.Release|Any CPU.Build.0 = Release|Any CPU - {E200B2A8-6BC4-4F50-9D4F-7BAF06F1813A}.Release|x64.ActiveCfg = Release|Any CPU - {E200B2A8-6BC4-4F50-9D4F-7BAF06F1813A}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -197,7 +187,6 @@ Global {8CEFC324-CA6C-4845-9AD9-70B92BD87057} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} {BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} {BF52326F-E415-49E6-8595-62762216762B} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} - {E200B2A8-6BC4-4F50-9D4F-7BAF06F1813A} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC} diff --git a/samples/ComputeSharp.ShareX/ComputeSharp.ShareX.csproj b/samples/ComputeSharp.ShareX/ComputeSharp.ShareX.csproj deleted file mode 100644 index 00562633..00000000 --- a/samples/ComputeSharp.ShareX/ComputeSharp.ShareX.csproj +++ /dev/null @@ -1,26 +0,0 @@ - - - - Exe - net5.0 - true - enable - - - - - - - - - - - - - - - - diff --git a/samples/ComputeSharp.ShareX/Cpu/ColorBgra.cs b/samples/ComputeSharp.ShareX/Cpu/ColorBgra.cs deleted file mode 100644 index 70dff53d..00000000 --- a/samples/ComputeSharp.ShareX/Cpu/ColorBgra.cs +++ /dev/null @@ -1,120 +0,0 @@ -#region License Information (GPL v3) - -/* - ShareX - A program that allows you to take screenshots and share any file type - Copyright (c) 2007-2020 ShareX Team - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - Optionally you can also view the license at . -*/ - -#endregion License Information (GPL v3) - -// Source: https://github.com/ShareX/ShareX/blob/master/ShareX.HelpersLib/ColorBgra.cs - -using System.Drawing; -using System.Runtime.InteropServices; - -namespace ShareX.HelpersLib -{ - [StructLayout(LayoutKind.Explicit)] - public struct ColorBgra - { - [FieldOffset(0)] - public uint Bgra; - - [FieldOffset(0)] - public byte Blue; - [FieldOffset(1)] - public byte Green; - [FieldOffset(2)] - public byte Red; - [FieldOffset(3)] - public byte Alpha; - - public const byte SizeOf = 4; - - public ColorBgra(uint bgra) : this() - { - Bgra = bgra; - } - - public ColorBgra(byte b, byte g, byte r, byte a = 255) : this() - { - Blue = b; - Green = g; - Red = r; - Alpha = a; - } - - public ColorBgra(Color color) : this(color.B, color.G, color.R, color.A) - { - } - - public static bool operator ==(ColorBgra c1, ColorBgra c2) - { - return c1.Bgra == c2.Bgra; - } - - public static bool operator !=(ColorBgra c1, ColorBgra c2) - { - return c1.Bgra != c2.Bgra; - } - - public override bool Equals(object? obj) - { - return obj is ColorBgra && ((ColorBgra)obj).Bgra == Bgra; - } - - public override int GetHashCode() - { - unchecked - { - return (int)Bgra; - } - } - - public static implicit operator ColorBgra(uint color) - { - return new ColorBgra(color); - } - - public static implicit operator uint(ColorBgra color) - { - return color.Bgra; - } - - public Color ToColor() - { - return Color.FromArgb(Alpha, Red, Green, Blue); - } - - public override string ToString() - { - return string.Format("B: {0}, G: {1}, R: {2}, A: {3}", Blue, Green, Red, Alpha); - } - - public static uint BgraToUInt32(uint b, uint g, uint r, uint a) - { - return b + (g << 8) + (r << 16) + (a << 24); - } - - public static uint BgraToUInt32(byte b, byte g, byte r, byte a) - { - return b + ((uint)g << 8) + ((uint)r << 16) + ((uint)a << 24); - } - } -} \ No newline at end of file diff --git a/samples/ComputeSharp.ShareX/Cpu/ConvolutionMatrix.cs b/samples/ComputeSharp.ShareX/Cpu/ConvolutionMatrix.cs deleted file mode 100644 index d6cbc103..00000000 --- a/samples/ComputeSharp.ShareX/Cpu/ConvolutionMatrix.cs +++ /dev/null @@ -1,66 +0,0 @@ -#region License Information (GPL v3) - -/* - ShareX - A program that allows you to take screenshots and share any file type - Copyright (c) 2007-2020 ShareX Team - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - Optionally you can also view the license at . -*/ - -#endregion License Information (GPL v3) - -// Source: https://github.com/ShareX/ShareX/blob/master/ShareX.HelpersLib/ConvolutionMatrix.cs - -namespace ShareX.HelpersLib -{ - public class ConvolutionMatrix - { - private readonly double[,] matrix; - - public int Width => matrix.GetLength(1); - public int Height => matrix.GetLength(0); - public byte Offset { get; set; } - - public bool ConsiderAlpha { get; set; } - - public ConvolutionMatrix() : this(3) - { - } - - public ConvolutionMatrix(int size) : this(size, size) - { - } - - public ConvolutionMatrix(int height, int width) - { - matrix = new double[height, width]; - } - - public void SetAll(double value) - { - for (int y = 0; y < Height; y++) - { - for (int x = 0; x < Width; x++) - { - matrix[y, x] = value; - } - } - } - - public ref double this[int y, int x] => ref matrix[y, x]; - } -} \ No newline at end of file diff --git a/samples/ComputeSharp.ShareX/Cpu/ConvolutionMatrixManager.cs b/samples/ComputeSharp.ShareX/Cpu/ConvolutionMatrixManager.cs deleted file mode 100644 index d74fa361..00000000 --- a/samples/ComputeSharp.ShareX/Cpu/ConvolutionMatrixManager.cs +++ /dev/null @@ -1,148 +0,0 @@ -#region License Information (GPL v3) - -/* - ShareX - A program that allows you to take screenshots and share any file type - Copyright (c) 2007-2020 ShareX Team - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - Optionally you can also view the license at . -*/ - -#endregion License Information (GPL v3) - -// Source: https://github.com/ShareX/ShareX/blob/master/ShareX.HelpersLib/ConvolutionMatrixManager.cs -// Adapted from: https://stackoverflow.com/questions/33569396/correctly-implement-a-2-pass-gaussian-blur -// Filters: http://www.codeproject.com/Articles/2008/Image-Processing-for-Dummies-with-C-and-GDI-Part-2 - -using System; -using System.Drawing; -using System.Drawing.Imaging; -using System.Threading.Tasks; - -namespace ShareX.HelpersLib -{ - public static class ConvolutionMatrixManager - { - public static Bitmap Apply(this ConvolutionMatrix kernel, Bitmap bmp) - { - Bitmap bmpResult = (Bitmap)bmp.Clone(); - - using (UnsafeBitmap source = new UnsafeBitmap(bmp, true, ImageLockMode.ReadOnly)) - using (UnsafeBitmap dest = new UnsafeBitmap(bmpResult, true, ImageLockMode.WriteOnly)) - { - int originX = (kernel.Width - 1) / 2; - int originY = (kernel.Height - 1) / 2; - - Parallel.For(0, source.Height, y => - { - Parallel.For(0, source.Width, x => - { - double r = 0.0; - double g = 0.0; - double b = 0.0; - double a = 0.0; - - // Apply each matrix multiplier to the color components for each pixel. - for (int fy = 0; fy < kernel.Height; fy++) - { - int fyr = fy - originY; - int offsetY = y + fyr; - - offsetY = offsetY.Clamp(0, source.Height - 1); - - for (int fx = 0; fx < kernel.Width; fx++) - { - int fxr = fx - originX; - int offsetX = x + fxr; - - offsetX = offsetX.Clamp(0, source.Width - 1); - - ColorBgra currentColor = source.GetPixel(offsetX, offsetY); - - r += kernel[fy, fx] * currentColor.Red; - g += kernel[fy, fx] * currentColor.Green; - b += kernel[fy, fx] * currentColor.Blue; - if (kernel.ConsiderAlpha) - { - a += kernel[fy, fx] * currentColor.Alpha; - } - } - } - - r += kernel.Offset; - r = r.Clamp(0, 255); - - g += kernel.Offset; - g = g.Clamp(0, 255); - - b += kernel.Offset; - b = b.Clamp(0, 255); - - if (kernel.ConsiderAlpha) - { - a += kernel.Offset; - a = a.Clamp(0, 255); - } - - dest.SetPixel(x, y, new ColorBgra((byte)b, (byte)g, (byte)r, kernel.ConsiderAlpha ? (byte)a : source.GetPixel(x, y).Alpha)); - }); - }); - } - - return bmpResult; - } - - private static double GaussianFunction(double x, double sigma) - { - double left = 1.0 / (Math.Sqrt(2 * Math.PI) * sigma); - - double exponentNumerator = -x * x; - double exponentDenominator = 2 * Math.Pow(sigma, 2); - double right = Math.Exp(exponentNumerator / exponentDenominator); - - return left * right; - } - - public static ConvolutionMatrix GaussianBlur(int height, int width, double sigma) - { - ConvolutionMatrix cm = new ConvolutionMatrix(height, width); - cm.ConsiderAlpha = true; - - double sum = 0.0; - double midpointX = (width - 1) / 2.0; - double midpointY = (height - 1) / 2.0; - - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - sum += cm[y, x] = GaussianFunction(x - midpointX, sigma) * GaussianFunction(y - midpointY, sigma); - } - } - - // Normalise kernel so that the sum of all weights equals 1 - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - cm[y, x] /= sum; - } - } - - return cm; - } - } -} \ No newline at end of file diff --git a/samples/ComputeSharp.ShareX/Cpu/MathHelpers.cs b/samples/ComputeSharp.ShareX/Cpu/MathHelpers.cs deleted file mode 100644 index c7c3f753..00000000 --- a/samples/ComputeSharp.ShareX/Cpu/MathHelpers.cs +++ /dev/null @@ -1,41 +0,0 @@ -#region License Information (GPL v3) - -/* - ShareX - A program that allows you to take screenshots and share any file type - Copyright (c) 2007-2020 ShareX Team - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - Optionally you can also view the license at . -*/ - -#endregion License Information (GPL v3) - -// Source: https://github.com/ShareX/ShareX/blob/master/ShareX.HelpersLib/Helpers/MathHelpers.cs - -using System; - -namespace ShareX.HelpersLib -{ - public static class MathHelpers - { - public static T Clamp(T num, T min, T max) where T : IComparable - { - if (num.CompareTo(min) <= 0) return min; - if (num.CompareTo(max) >= 0) return max; - return num; - } - } -} \ No newline at end of file diff --git a/samples/ComputeSharp.ShareX/Cpu/NumberExtensions.cs b/samples/ComputeSharp.ShareX/Cpu/NumberExtensions.cs deleted file mode 100644 index 11a0cd20..00000000 --- a/samples/ComputeSharp.ShareX/Cpu/NumberExtensions.cs +++ /dev/null @@ -1,39 +0,0 @@ -#region License Information (GPL v3) - -/* - ShareX - A program that allows you to take screenshots and share any file type - Copyright (c) 2007-2020 ShareX Team - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - Optionally you can also view the license at . -*/ - -#endregion License Information (GPL v3) - -// Source: https://github.com/ShareX/ShareX/blob/master/ShareX.HelpersLib/Extensions/NumberExtensions.cs - -using System; - -namespace ShareX.HelpersLib -{ - public static class NumberExtensions - { - public static T Clamp(this T num, T min, T max) where T : IComparable - { - return MathHelpers.Clamp(num, min, max); - } - } -} \ No newline at end of file diff --git a/samples/ComputeSharp.ShareX/Cpu/UnsafeBitmap.cs b/samples/ComputeSharp.ShareX/Cpu/UnsafeBitmap.cs deleted file mode 100644 index 64965d39..00000000 --- a/samples/ComputeSharp.ShareX/Cpu/UnsafeBitmap.cs +++ /dev/null @@ -1,192 +0,0 @@ -#region License Information (GPL v3) - -/* - ShareX - A program that allows you to take screenshots and share any file type - Copyright (c) 2007-2020 ShareX Team - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - Optionally you can also view the license at . -*/ - -#endregion License Information (GPL v3) - -// Source: https://github.com/ShareX/ShareX/blob/master/ShareX.HelpersLib/UnsafeBitmap.cs - -using System; -using System.Drawing; -using System.Drawing.Imaging; - -namespace ShareX.HelpersLib -{ - public unsafe class UnsafeBitmap : IDisposable - { - public ColorBgra* Pointer { get; private set; } - public bool IsLocked { get; private set; } - public int Width { get; private set; } - public int Height { get; private set; } - - public int PixelCount => Width * Height; - - private Bitmap bitmap; - private BitmapData? bitmapData; - - public UnsafeBitmap(Bitmap bitmap, bool lockBitmap = false, ImageLockMode imageLockMode = ImageLockMode.ReadWrite) - { - this.bitmap = bitmap; - Width = bitmap.Width; - Height = bitmap.Height; - - if (lockBitmap) - { - Lock(imageLockMode); - } - } - - public void Lock(ImageLockMode imageLockMode = ImageLockMode.ReadWrite) - { - if (!IsLocked) - { - IsLocked = true; - bitmapData = bitmap.LockBits(new Rectangle(0, 0, Width, Height), imageLockMode, PixelFormat.Format32bppArgb); - Pointer = (ColorBgra*)bitmapData.Scan0.ToPointer(); - } - } - - public void Unlock() - { - if (IsLocked) - { - bitmap.UnlockBits(bitmapData!); - bitmapData = null; - Pointer = null; - IsLocked = false; - } - } - - public static bool operator ==(UnsafeBitmap bmp1, UnsafeBitmap bmp2) - { - return ReferenceEquals(bmp1, bmp2) || bmp1.Equals(bmp2); - } - - public static bool operator !=(UnsafeBitmap bmp1, UnsafeBitmap bmp2) - { - return !(bmp1 == bmp2); - } - - public override bool Equals(object? obj) - { - return obj is UnsafeBitmap && Compare((UnsafeBitmap)obj, this); - } - - public override int GetHashCode() - { - return PixelCount; - } - - public static bool Compare(UnsafeBitmap bmp1, UnsafeBitmap bmp2) - { - int pixelCount = bmp1.PixelCount; - - if (pixelCount != bmp2.PixelCount) - { - return false; - } - - bmp1.Lock(ImageLockMode.ReadOnly); - bmp2.Lock(ImageLockMode.ReadOnly); - - ColorBgra* pointer1 = bmp1.Pointer; - ColorBgra* pointer2 = bmp2.Pointer; - - for (int i = 0; i < pixelCount; i++) - { - if (pointer1->Bgra != pointer2->Bgra) - { - return false; - } - - pointer1++; - pointer2++; - } - - return true; - } - - public bool IsTransparent() - { - int pixelCount = PixelCount; - - ColorBgra* pointer = Pointer; - - for (int i = 0; i < pixelCount; i++) - { - if (pointer->Alpha < 255) - { - return true; - } - - pointer++; - } - - return false; - } - - public ColorBgra GetPixel(int i) - { - return Pointer[i]; - } - - public ColorBgra GetPixel(int x, int y) - { - return Pointer[x + (y * Width)]; - } - - public void SetPixel(int i, ColorBgra color) - { - Pointer[i] = color; - } - - public void SetPixel(int i, uint color) - { - Pointer[i] = color; - } - - public void SetPixel(int x, int y, ColorBgra color) - { - Pointer[x + (y * Width)] = color; - } - - public void SetPixel(int x, int y, uint color) - { - Pointer[x + (y * Width)] = color; - } - - public void ClearPixel(int i) - { - Pointer[i] = 0; - } - - public void ClearPixel(int x, int y) - { - Pointer[x + (y * Width)] = 0; - } - - public void Dispose() - { - Unlock(); - } - } -} \ No newline at end of file diff --git a/samples/ComputeSharp.ShareX/Gpu/HlslConvolutionManager.cs.cs b/samples/ComputeSharp.ShareX/Gpu/HlslConvolutionManager.cs.cs deleted file mode 100644 index a02df046..00000000 --- a/samples/ComputeSharp.ShareX/Gpu/HlslConvolutionManager.cs.cs +++ /dev/null @@ -1,239 +0,0 @@ -using System; -using System.Drawing; -using System.Drawing.Imaging; -using System.Numerics; -using System.Runtime.CompilerServices; -using Rectangle = System.Drawing.Rectangle; - -namespace ComputeSharp.ShareX -{ - /// - /// Applies Gaussian blur processing to an image. - /// - internal sealed partial class HlslConvolutionManager - { - /// - /// The 1D gaussian blur kernel to use. - /// - private readonly float[] kernel; - - /// - /// Creates a new instance for the specific kernel. - /// - /// The convolution kernel to use. - private HlslConvolutionManager(float[] kernel) - { - this.kernel = kernel; - } - - /// - /// Creates a new instance with the specified parameters. - /// - /// The size of the convolution kernel. - /// The sigma parameter for the gaussian blur. - /// An instance to use to blur images. - public static HlslConvolutionManager Create(int size, float sigma) - { - return new(CreateGaussianBlurKernel(size, sigma)); - } - - /// - /// Creates a 1 dimensional Gaussian kernel using the Gaussian G(x) function. - /// - private static float[] CreateGaussianBlurKernel(int size, float weight) - { - 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; - } - - 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; - } - - for (int i = 0; i < size; i++) - { - Unsafe.Add(ref rKernel, i) /= sum; - } - - return kernel; - } - - /// - /// Applies the current convolution to a give bitmap. - /// - /// The input instance to process. - /// A blurred copy of . - public unsafe Bitmap Apply(Bitmap source) - { - Rectangle bounds = new(0, 0, source.Width, source.Height); - Bitmap result = new(source.Width, source.Height); - BitmapData - sourceData = source.LockBits(bounds, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb), - resultData = result.LockBits(bounds, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); - Span - sourceSpan = new((Bgra32*)sourceData.Scan0.ToPointer(), bounds.Width * bounds.Height), - resultSpan = new((Bgra32*)resultData.Scan0.ToPointer(), sourceSpan.Length); - - try - { - using ReadWriteTexture2D leftBuffer = Gpu.Default.AllocateReadWriteTexture2D(sourceSpan, source.Width, source.Height); - using ReadWriteTexture2D rightBuffer = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); - using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(this.kernel); - - ApplyVerticalConvolution(leftBuffer, rightBuffer, kernelBuffer, source.Height, source.Width); - ApplyHorizontalConvolution(rightBuffer, leftBuffer, kernelBuffer, source.Height, source.Width); - - leftBuffer.GetData(resultSpan); - } - finally - { - source.UnlockBits(sourceData); - result.UnlockBits(resultData); - } - - return result; - } - - /// - /// Performs a vertical 1D complex convolution with the specified parameters. - /// - /// The source to read data from. - /// The target to write the results to. - /// The with the values for the current complex kernel. - /// The height of the image to process. - /// The width of the image to process. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ApplyVerticalConvolution( - ReadWriteTexture2D source, - ReadWriteTexture2D target, - ReadOnlyBuffer kernel, - int height, - int width) - { - VerticalConvolutionProcessor shader = new( - maxY: height - 1, - maxX: width - 1, - kernel.Length, - source, - target, - kernel); - - Gpu.Default.For(width, height, in shader); - } - - /// - /// Kernel for the vertical convolution pass. - /// - [AutoConstructor] - internal readonly partial struct VerticalConvolutionProcessor : IComputeShader - { - public readonly int maxY; - public readonly int maxX; - public readonly int kernelLength; - - public readonly ReadWriteTexture2D source; - public readonly ReadWriteTexture2D target; - public readonly ReadOnlyBuffer kernel; - - /// - public void Execute(ThreadIds ids) - { - Vector4 result = Vector4.Zero; - int radiusY = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; - - for (int i = 0; i < kernelLength; i++) - { - int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); - Vector4 color = source[offsetX, offsetY]; - - result += kernel[i] * color; - } - - target[ids.XY] = result; - } - } - - /// - /// Performs an horizontal 1D complex convolution with the specified parameters. - /// - /// The source to read data from. - /// The target to write the results to. - /// The with the values for the current complex kernel. - /// The height of the image to process. - /// The width of the image to process. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ApplyHorizontalConvolution( - ReadWriteTexture2D source, - ReadWriteTexture2D target, - ReadOnlyBuffer kernel, - int height, - int width) - { - HorizontalConvolutionProcessor shader = new( - maxY: height - 1, - maxX: width - 1, - kernel.Length, - source, - target, - kernel); - - Gpu.Default.For(width, height, in shader); - } - - /// - /// Kernel for the horizontal convolution pass. - /// - [AutoConstructor] - internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader - { - public readonly int maxY; - public readonly int maxX; - public readonly int kernelLength; - - public readonly ReadWriteTexture2D source; - public readonly ReadWriteTexture2D target; - public readonly ReadOnlyBuffer kernel; - - /// - public void Execute(ThreadIds ids) - { - Vector4 result = Vector4.Zero; - int radiusX = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; - int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); - - for (int i = 0; i < kernelLength; i++) - { - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX); - Vector4 color = source[offsetX, offsetY]; - - result += kernel[i] * color; - } - - target[ids.XY] = result; - } - } - } -} diff --git a/samples/ComputeSharp.ShareX/Program.cs b/samples/ComputeSharp.ShareX/Program.cs deleted file mode 100644 index 90241bc2..00000000 --- a/samples/ComputeSharp.ShareX/Program.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.Drawing; -using System.IO; -using System.Reflection; -using ShareX.HelpersLib; - -namespace ComputeSharp.ShareX -{ - class Program - { - static void Main() - { - Console.WriteLine(">> Loading image"); - - string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "city.jpg"); - - using Bitmap sourceBitmap = new(path); - - Console.WriteLine(">> Blurring on CPU"); - - using Bitmap resultBitmapCpu = ConvolutionMatrixManager.GaussianBlur(61, 61, 10).Apply(sourceBitmap); - - string resultPathCpu = Path.Combine( - Path.GetRelativePath(Path.GetDirectoryName(path)!, @"..\..\..\"), - $"{Path.GetFileNameWithoutExtension(path)}_cpu{Path.GetExtension(path)}"); - - Console.WriteLine(">> Saving image"); - - resultBitmapCpu.Save(resultPathCpu); - - Console.WriteLine(">> Blurring on GPU"); - - using Bitmap resultBitmapGpu = HlslConvolutionManager.Create(61, 10).Apply(sourceBitmap); - - string resultPathGpu = Path.Combine( - Path.GetRelativePath(Path.GetDirectoryName(path)!, @"..\..\..\"), - $"{Path.GetFileNameWithoutExtension(path)}_gpu{Path.GetExtension(path)}"); - - Console.WriteLine(">> Saving image"); - - resultBitmapGpu.Save(resultPathGpu); - } - } -}