diff --git a/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj b/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj index 9f8fe3d7..248e0cad 100644 --- a/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj +++ b/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj @@ -5,10 +5,6 @@ net5.0 - - - - image = Image.Load(filename); - - ReadOnlyTexture2D texture = Gpu.Default.AllocateReadOnlyTexture2D(image.Width, image.Height); - - image.TryGetSinglePixelSpan(out Span span); - - texture.CopyFrom(MemoryMarshal.Cast(span)); - - return texture; + return Gpu.Default.AllocateReadOnlyTexture2D(filename); } } } diff --git a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs index 57592daf..6d65673e 100644 --- a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs @@ -1,6 +1,7 @@ using System; using System.Diagnostics.Contracts; using ComputeSharp.__Internals; +using ComputeSharp.Graphics.Helpers; using ComputeSharp.Resources; using ComputeSharp.Shaders; @@ -239,7 +240,7 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The allocation mode to use for the new resource. - /// A zeroed instance of size [, ]. + /// A zeroed instance of size [, ]. [Pure] public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, int width, int height, AllocationMode allocationMode = AllocationMode.Default) where T : unmanaged, IUnorm @@ -257,7 +258,7 @@ namespace ComputeSharp /// 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. + /// A instance with the contents of the input array. [Pure] public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, T[] source, int width, int height) where T : unmanaged, IUnorm @@ -276,7 +277,7 @@ namespace ComputeSharp /// 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. + /// A instance with the contents of the input array. [Pure] public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, T[] source, int offset, int width, int height) where T : unmanaged, IUnorm @@ -292,7 +293,7 @@ namespace ComputeSharp /// 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. + /// A read write instance with the contents of the input array. [Pure] public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, T[,] source) where T : unmanaged, IUnorm @@ -314,7 +315,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 ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, ReadOnlySpan source, int width, int height) where T : unmanaged, IUnorm @@ -327,6 +328,50 @@ namespace ComputeSharp return texture; } + /// + /// Allocates a new readonly 2D texture with the contents of the specified file. + /// + /// 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 filename of the image file to load and decode into the texture. + /// A instance with the contents of the specified file. + [Pure] + public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, ReadOnlySpan filename) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + using UploadTexture2D upload = WICHelper.Instance.LoadTexture(device, filename); + + ReadOnlyTexture2D texture = device.AllocateReadOnlyTexture2D(upload.Width, upload.Height); + + upload.CopyTo(texture); + + return texture; + } + + /// + /// Allocates a new readonly 2D texture with the contents of the specified buffer. + /// + /// 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 buffer with the image data to load and decode into the texture. + /// A instance with the contents of the specified file. + [Pure] + public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, ReadOnlySpan span) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + using UploadTexture2D upload = WICHelper.Instance.LoadTexture(device, span); + + ReadOnlyTexture2D texture = device.AllocateReadOnlyTexture2D(upload.Width, upload.Height); + + upload.CopyTo(texture); + + return texture; + } + /// /// Allocates a new readonly 3D texture with the specified parameters. /// @@ -432,7 +477,7 @@ namespace ComputeSharp /// The height of the texture. /// The depth of the texture. /// The allocation mode to use for the new resource. - /// A zeroed instance of size [, , ]. + /// A zeroed instance of size [, , ]. [Pure] public static ReadOnlyTexture3D AllocateReadOnlyTexture3D(this GraphicsDevice device, int width, int height, int depth, AllocationMode allocationMode = AllocationMode.Default) where T : unmanaged, IUnorm @@ -451,7 +496,7 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The depth of the texture. - /// A instance with the contents of the input array. + /// A instance with the contents of the input array. [Pure] public static ReadOnlyTexture3D AllocateReadOnlyTexture3D(this GraphicsDevice device, T[] source, int width, int height, int depth) where T : unmanaged, IUnorm @@ -471,7 +516,7 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The depth of the texture. - /// A instance with the contents of the input array. + /// A instance with the contents of the input array. [Pure] public static ReadOnlyTexture3D AllocateReadOnlyTexture3D(this GraphicsDevice device, T[] source, int offset, int width, int height, int depth) where T : unmanaged, IUnorm @@ -487,7 +532,7 @@ namespace ComputeSharp /// 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. + /// 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]. @@ -514,7 +559,7 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The depth of the texture. - /// A instance with the contents of the input . + /// A instance with the contents of the input . [Pure] public static ReadOnlyTexture3D AllocateReadOnlyTexture3D(this GraphicsDevice device, ReadOnlySpan source, int width, int height, int depth) where T : unmanaged, IUnorm @@ -688,7 +733,7 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The allocation mode to use for the new resource. - /// A zeroed instance of size [, ]. + /// A zeroed instance of size [, ]. [Pure] public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, int width, int height, AllocationMode allocationMode = AllocationMode.Default) where T : unmanaged, IUnorm @@ -706,7 +751,7 @@ namespace ComputeSharp /// 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. + /// A instance with the contents of the input array. [Pure] public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, T[] source, int width, int height) where T : unmanaged, IUnorm @@ -725,7 +770,7 @@ namespace ComputeSharp /// 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. + /// A instance with the contents of the input array. [Pure] public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, T[] source, int offset, int width, int height) where T : unmanaged, IUnorm @@ -741,7 +786,7 @@ namespace ComputeSharp /// 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. + /// A read write instance with the contents of the input array. [Pure] public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, T[,] source) where T : unmanaged, IUnorm @@ -763,7 +808,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 source, int width, int height) where T : unmanaged, IUnorm @@ -776,6 +821,50 @@ namespace ComputeSharp return texture; } + /// + /// Allocates a new writeable 2D texture with the contents of the specified file. + /// + /// 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 filename of the image file to load and decode into the texture. + /// A instance with the contents of the specified file. + [Pure] + public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, ReadOnlySpan filename) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + using UploadTexture2D upload = WICHelper.Instance.LoadTexture(device, filename); + + ReadWriteTexture2D texture = device.AllocateReadWriteTexture2D(upload.Width, upload.Height); + + upload.CopyTo(texture); + + return texture; + } + + /// + /// Allocates a new writeable 2D texture with the contents of the specified buffer. + /// + /// 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 buffer with the image data to load and decode into the texture. + /// A instance with the contents of the specified file. + [Pure] + public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, ReadOnlySpan span) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + using UploadTexture2D upload = WICHelper.Instance.LoadTexture(device, span); + + ReadWriteTexture2D texture = device.AllocateReadWriteTexture2D(upload.Width, upload.Height); + + upload.CopyTo(texture); + + return texture; + } + /// /// Allocates a new writeable 3D texture with the specified parameters. /// @@ -881,7 +970,7 @@ namespace ComputeSharp /// The height of the texture. /// The depth of the texture. /// The allocation mode to use for the new resource. - /// A instance of size [, , ]. + /// A instance of size [, , ]. [Pure] public static ReadWriteTexture3D AllocateReadWriteTexture3D(this GraphicsDevice device, int width, int height, int depth, AllocationMode allocationMode = AllocationMode.Default) where T : unmanaged, IUnorm @@ -900,7 +989,7 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The depth of the texture. - /// A instance with the contents of the input array. + /// A instance with the contents of the input array. [Pure] public static ReadWriteTexture3D AllocateReadWriteTexture3D(this GraphicsDevice device, T[] source, int width, int height, int depth) where T : unmanaged, IUnorm @@ -920,7 +1009,7 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The depth of the texture. - /// A instance with the contents of the input array. + /// A instance with the contents of the input array. [Pure] public static ReadWriteTexture3D AllocateReadWriteTexture3D(this GraphicsDevice device, T[] source, int offset, int width, int height, int depth) where T : unmanaged, IUnorm @@ -936,7 +1025,7 @@ namespace ComputeSharp /// 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. + /// 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]. @@ -963,7 +1052,7 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The depth of the texture. - /// A instance with the contents of the input . + /// A instance with the contents of the input . [Pure] public static ReadWriteTexture3D AllocateReadWriteTexture3D(this GraphicsDevice device, ReadOnlySpan source, int width, int height, int depth) where T : unmanaged, IUnorm diff --git a/src/ComputeSharp/Graphics/Extensions/ReadBackTexture2DExtensions.cs b/src/ComputeSharp/Graphics/Extensions/ReadBackTexture2DExtensions.cs new file mode 100644 index 00000000..83b075cf --- /dev/null +++ b/src/ComputeSharp/Graphics/Extensions/ReadBackTexture2DExtensions.cs @@ -0,0 +1,23 @@ +using System; +using ComputeSharp.Graphics.Helpers; + +namespace ComputeSharp +{ + /// + /// A that contains extension methods for the type. + /// + public static class ReadBackTexture2DExtensions + { + /// + /// Saves a texture to a specified file. + /// + /// The type of items to store in the texture. + /// The texture to save to an image. + /// The filename of the image file to save. + public static void Save(this ReadBackTexture2D texture, ReadOnlySpan filename) + where T : unmanaged + { + WICHelper.Instance.SaveTexture(texture.View, filename); + } + } +} diff --git a/src/ComputeSharp/Graphics/Extensions/Texture2DExtensions.cs b/src/ComputeSharp/Graphics/Extensions/Texture2DExtensions.cs index db6722f8..e1e2b755 100644 --- a/src/ComputeSharp/Graphics/Extensions/Texture2DExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/Texture2DExtensions.cs @@ -1,6 +1,7 @@ using System; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; +using ComputeSharp.Graphics.Helpers; using ComputeSharp.Resources; using Microsoft.Toolkit.Diagnostics; @@ -338,5 +339,21 @@ namespace ComputeSharp { texture.CopyFrom(ref MemoryMarshal.GetReference(source), source.Length, x, y, width, height); } + + /// + /// Saves a texture to a specified file. + /// + /// The type of items to store in the texture. + /// The texture to save to an image. + /// The filename of the image file to save. + public static void Save(this Texture2D texture, ReadOnlySpan filename) + where T : unmanaged + { + using ReadBackTexture2D readback = texture.GraphicsDevice.AllocateReadBackTexture2D(texture.Width, texture.Height); + + texture.CopyTo(readback); + + WICHelper.Instance.SaveTexture(readback.View, filename); + } } } diff --git a/src/ComputeSharp/Graphics/Helpers/WICFormatHelper.cs b/src/ComputeSharp/Graphics/Helpers/WICFormatHelper.cs new file mode 100644 index 00000000..19b5716e --- /dev/null +++ b/src/ComputeSharp/Graphics/Helpers/WICFormatHelper.cs @@ -0,0 +1,132 @@ +using System; +using System.Diagnostics.Contracts; +using System.IO; +using System.Runtime.CompilerServices; +using Microsoft.Toolkit.Diagnostics; +using FX = TerraFX.Interop.Windows; + +namespace ComputeSharp.Graphics.Helpers +{ + /// + /// A helper type with utility methods for WIC formats. + /// + internal static class WICFormatHelper + { + /// + /// Gets the appropriate WIC format value for the input type argument. + /// + /// The input type argument to get the corresponding WIC format . + /// The WIC format value corresponding to . + /// Thrown when the input type is not supported. + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Guid GetForType() + where T : unmanaged + { + if (typeof(T) == typeof(Bgra32)) return FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(Rgba32)) return FX.GUID_WICPixelFormat32bppRGBA; + else if (typeof(T) == typeof(Rgba64)) return FX.GUID_WICPixelFormat64bppRGBA; + else if (typeof(T) == typeof(R8)) return FX.GUID_WICPixelFormat8bppGray; + else if (typeof(T) == typeof(R16)) return FX.GUID_WICPixelFormat16bppGray; + else return ThrowHelper.ThrowArgumentException("Invalid texture type"); + } + + /// + /// Gets the appropriate WIC format value for the input type argument. + /// + /// The input type argument to get the corresponding WIC format . + /// The WIC format value corresponding to . + /// Thrown when the input type is not supported. + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryGetIntermediateFormatForType(Guid containerFormat, out Guid intermediateFormat) + where T : unmanaged + { + if (containerFormat == FX.GUID_ContainerFormatBmp) + { + if (typeof(T) == typeof(Bgra32)) intermediateFormat = default; + else if (typeof(T) == typeof(Rgba32)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(Rgba64)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(R8)) intermediateFormat = FX.GUID_WICPixelFormat24bppBGR; + else if (typeof(T) == typeof(R16)) intermediateFormat = FX.GUID_WICPixelFormat24bppBGR; + else intermediateFormat = ThrowHelper.ThrowArgumentException("Invalid texture type"); + } + else if (containerFormat == FX.GUID_ContainerFormatPng) + { + if (typeof(T) == typeof(Bgra32)) intermediateFormat = default; + else if (typeof(T) == typeof(Rgba32)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(Rgba64)) intermediateFormat = default; + else if (typeof(T) == typeof(R8)) intermediateFormat = default; + else if (typeof(T) == typeof(R16)) intermediateFormat = FX.GUID_WICPixelFormat8bppGray; + else intermediateFormat = ThrowHelper.ThrowArgumentException("Invalid texture type"); + } + else if (containerFormat == FX.GUID_ContainerFormatJpeg) + { + if (typeof(T) == typeof(Bgra32)) intermediateFormat = FX.GUID_WICPixelFormat24bppBGR; + else if (typeof(T) == typeof(Rgba32)) intermediateFormat = FX.GUID_WICPixelFormat24bppBGR; + else if (typeof(T) == typeof(Rgba64)) intermediateFormat = FX.GUID_WICPixelFormat24bppBGR; + else if (typeof(T) == typeof(R8)) intermediateFormat = default; + else if (typeof(T) == typeof(R16)) intermediateFormat = FX.GUID_WICPixelFormat8bppGray; + else intermediateFormat = ThrowHelper.ThrowArgumentException("Invalid texture type"); + } + else if (containerFormat == FX.GUID_ContainerFormatWmp) + { + if (typeof(T) == typeof(Bgra32)) intermediateFormat = default; + else if (typeof(T) == typeof(Rgba32)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(Rgba64)) intermediateFormat = default; + else if (typeof(T) == typeof(R8)) intermediateFormat = default; + else if (typeof(T) == typeof(R16)) intermediateFormat = default; + else intermediateFormat = ThrowHelper.ThrowArgumentException("Invalid texture type"); + } + else if (containerFormat == FX.GUID_ContainerFormatTiff) + { + if (typeof(T) == typeof(Bgra32)) intermediateFormat = default; + else if (typeof(T) == typeof(Rgba32)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(Rgba64)) intermediateFormat = default; + else if (typeof(T) == typeof(R8)) intermediateFormat = default; + else if (typeof(T) == typeof(R16)) intermediateFormat = default; + else intermediateFormat = ThrowHelper.ThrowArgumentException("Invalid texture type"); + } + else if (containerFormat == FX.GUID_ContainerFormatDds) + { + if (typeof(T) == typeof(Bgra32)) intermediateFormat = default; + else if (typeof(T) == typeof(Rgba32)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(Rgba64)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(R8)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(R16)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else intermediateFormat = ThrowHelper.ThrowArgumentException("Invalid texture type"); + } + else + { + intermediateFormat = ThrowHelper.ThrowArgumentException("Invalid container format"); + } + + return intermediateFormat != default; + } + + /// + /// Gets the appropriate WIC container format value for the input filename. + /// + /// The target filename to get the container format for. + /// The WIC format container value matching . + /// Thrown when the input filename doesn't have a valid file extension. + [Pure] + public static Guid GetForFilename(ReadOnlySpan filename) + { + switch (Path.GetExtension(filename).ToString()) + { + case ".bmp": return FX.GUID_ContainerFormatBmp; + case ".png": return FX.GUID_ContainerFormatPng; + case ".jpg": + case ".jpeg": return FX.GUID_ContainerFormatJpeg; + case ".jxr": + case ".hdp": + case ".wdp": + case ".wmp": return FX.GUID_ContainerFormatWmp; + case ".tiff": return FX.GUID_ContainerFormatTiff; + case ".dds": return FX.GUID_ContainerFormatDds; + default: return ThrowHelper.ThrowArgumentException("Invalid filename"); + } + } + } +} diff --git a/src/ComputeSharp/Graphics/Helpers/WICHelper.cs b/src/ComputeSharp/Graphics/Helpers/WICHelper.cs new file mode 100644 index 00000000..7bde9bf5 --- /dev/null +++ b/src/ComputeSharp/Graphics/Helpers/WICHelper.cs @@ -0,0 +1,258 @@ +using System; +using System.Diagnostics.Contracts; +using ComputeSharp.Core.Extensions; +using TerraFX.Interop; +using FX = TerraFX.Interop.Windows; + +namespace ComputeSharp.Graphics.Helpers +{ + /// + /// A that uses the WIC APIs to load and decode images. + /// + internal sealed unsafe class WICHelper + { + /// + /// The instance to use to create decoders. + /// + private readonly ComPtr wicImagingFactory2; + + /// + /// Creates a new instance. + /// + private WICHelper() + { + using ComPtr wicImagingFactory2 = default; + Guid wicImagingFactor2Clsid = FX.CLSID_WICImagingFactory2; + + FX.CoCreateInstance( + &wicImagingFactor2Clsid, + null, + (uint)CLSCTX.CLSCTX_INPROC_SERVER, + FX.__uuidof(), + wicImagingFactory2.GetVoidAddressOf()).Assert(); + + this.wicImagingFactory2 = wicImagingFactory2.Move(); + } + + /// + /// Destroys the current instance. + /// + ~WICHelper() + { + this.wicImagingFactory2.Dispose(); + } + + /// + /// Gets a instance to use. + /// + public static WICHelper Instance { get; } = new(); + + /// + /// Loads an from a specified file. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The filename of the image file to load and decode into the texture. + /// An instance with the contents of the specified file. + [Pure] + public UploadTexture2D LoadTexture(GraphicsDevice device, ReadOnlySpan filename) + where T : unmanaged + { + using ComPtr wicBitmapDecoder = default; + + // Get the bitmap decoder for the target file + fixed (char* p = filename) + { + this.wicImagingFactory2.Get()->CreateDecoderFromFilename( + (ushort*)p, + null, + FX.GENERIC_READ, + WICDecodeOptions.WICDecodeMetadataCacheOnDemand, + wicBitmapDecoder.GetAddressOf()).Assert(); + } + + return LoadTexture(device, wicBitmapDecoder.Get()); + } + + /// + /// Loads an from a specified buffer. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The buffer with the image data to load and decode into the texture. + /// An instance with the contents of the specified file. + [Pure] + public UploadTexture2D LoadTexture(GraphicsDevice device, ReadOnlySpan span) + where T : unmanaged + { + using ComPtr wicBitmapDecoder = default; + using ComPtr wicStream = default; + + // Get the bitmap decoder for the target buffer + fixed (byte* p = span) + { + this.wicImagingFactory2.Get()->CreateStream(wicStream.GetAddressOf()).Assert(); + + wicStream.Get()->InitializeFromMemory(p, (uint)span.Length).Assert(); + + this.wicImagingFactory2.Get()->CreateDecoderFromStream( + (IStream*)wicStream.Get(), + null, + WICDecodeOptions.WICDecodeMetadataCacheOnDemand, + wicBitmapDecoder.GetAddressOf()).Assert(); + + return LoadTexture(device, wicBitmapDecoder.Get()); + } + } + + /// + /// Saves a texture to a specified file. + /// + /// The type of items to store in the texture. + /// The texture data to save to an image. + /// The filename of the image file to save. + public void SaveTexture(TextureView2D texture, ReadOnlySpan filename) + where T : unmanaged + { + using ComPtr wicBitmapEncoder = default; + Guid containerGuid = WICFormatHelper.GetForFilename(filename); + + // Create the image encoder + this.wicImagingFactory2.Get()->CreateEncoder( + &containerGuid, + null, + wicBitmapEncoder.GetAddressOf()).Assert(); + + using ComPtr wicStream = default; + + // Create and initialize a stream to the target file + this.wicImagingFactory2.Get()->CreateStream(wicStream.GetAddressOf()).Assert(); + + fixed (char* p = filename) + { + wicStream.Get()->InitializeFromFilename( + (ushort*)p, + FX.GENERIC_WRITE); + } + + // Initialize the encoder + wicBitmapEncoder.Get()->Initialize( + (IStream*)wicStream.Get(), + WICBitmapEncoderCacheOption.WICBitmapEncoderNoCache).Assert(); + + using ComPtr wicBitmapFrameEncode = default; + + // Create the image frame and initialize it + wicBitmapEncoder.Get()->CreateNewFrame(wicBitmapFrameEncode.GetAddressOf(), null).Assert(); + + wicBitmapFrameEncode.Get()->Initialize(null).Assert(); + wicBitmapFrameEncode.Get()->SetSize((uint)texture.Width, (uint)texture.Height).Assert(); + + // Depending on the target format and the current pixel type, we need to check whether + // an intermediate encoding step is necessary. This is because not all pixel formats + // are directly supported by the native image encoders present in Windows. + if (WICFormatHelper.TryGetIntermediateFormatForType(containerGuid, out Guid intermediateGuid)) + { + T* data = texture.DangerousGetAddressAndByteStride(out int strideInBytes); + + using ComPtr wicBitmap = default; + Guid initialGuid = WICFormatHelper.GetForType(); + + // Create a bitmap wrapping the input texture + this.wicImagingFactory2.Get()->CreateBitmapFromMemory( + (uint)texture.Width, + (uint)texture.Height, + &initialGuid, + (uint)strideInBytes, + (uint)(strideInBytes * texture.Height), + (byte*)data, + wicBitmap.GetAddressOf()).Assert(); + + using ComPtr wicFormatConverter = default; + + this.wicImagingFactory2.Get()->CreateFormatConverter(wicFormatConverter.GetAddressOf()).Assert(); + + // Get a format converter to encode the pixel data + wicFormatConverter.Get()->Initialize( + (IWICBitmapSource*)wicBitmap.Get(), + &intermediateGuid, + WICBitmapDitherType.WICBitmapDitherTypeNone, + null, + 0, + WICBitmapPaletteType.WICBitmapPaletteTypeMedianCut).Assert(); + + // Write the encoded image data to the frame + wicBitmapFrameEncode.Get()->SetPixelFormat(&intermediateGuid).Assert(); + wicBitmapFrameEncode.Get()->WriteSource( + (IWICBitmapSource*)wicBitmap.Get(), + null).Assert(); + } + else + { + T* data = texture.DangerousGetAddressAndByteStride(out int strideInBytes); + Guid initialGuid = WICFormatHelper.GetForType(); + + // Write the image data to the frame + wicBitmapFrameEncode.Get()->SetPixelFormat(&initialGuid).Assert(); + wicBitmapFrameEncode.Get()->WritePixels( + lineCount: (uint)texture.Height, + cbStride: (uint)strideInBytes, + cbBufferSize: (uint)(strideInBytes * texture.Height), + pbPixels: (byte*)data).Assert(); + } + + wicBitmapFrameEncode.Get()->Commit(); + wicBitmapEncoder.Get()->Commit(); + } + + /// + /// Loads an from a specified object. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The object in use. + /// An instance with the contents of the specified file. + [Pure] + private UploadTexture2D LoadTexture(GraphicsDevice device, IWICBitmapDecoder* wicBitmapDecoder) + where T : unmanaged + { + using ComPtr wicBitmapFrameDecode = default; + + // Get the first frame of the loaded image (if more are present, they will be ignored) + wicBitmapDecoder->GetFrame(0, wicBitmapFrameDecode.GetAddressOf()).Assert(); + + using ComPtr wicFormatConverter = default; + Guid wicPixelFormatGuid = WICFormatHelper.GetForType(); + + this.wicImagingFactory2.Get()->CreateFormatConverter(wicFormatConverter.GetAddressOf()).Assert(); + + // Get a format converter to decode the pixel data + wicFormatConverter.Get()->Initialize( + (IWICBitmapSource*)wicBitmapFrameDecode.Get(), + &wicPixelFormatGuid, + WICBitmapDitherType.WICBitmapDitherTypeNone, + null, + 0, + WICBitmapPaletteType.WICBitmapPaletteTypeMedianCut).Assert(); + + uint width, height; + + // Extract the image size info + wicFormatConverter.Get()->GetSize(&width, &height).Assert(); + + // Allocate an upload texture to transfer the decoded pixel data + UploadTexture2D upload = device.AllocateUploadTexture2D((int)width, (int)height); + + T* data = upload.View.DangerousGetAddressAndByteStride(out int strideInBytes); + + // Decode the pixel data into the upload buffer + wicFormatConverter.Get()->CopyPixels( + prc: null, + cbStride: (uint)strideInBytes, + cbBufferSize: (uint)strideInBytes * height, + pbBuffer: (byte*)data).Assert(); + + return upload; + } + } +} diff --git a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs index 42b5c06b..984ba086 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs @@ -22,7 +22,7 @@ namespace ComputeSharp where TPixel : unmanaged { /// - /// Creates a new instance with the specified parameters. + /// Creates a new instance with the specified parameters. /// /// The associated with the current instance. /// The width of the texture. diff --git a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs index 2871cfd0..f29774ce 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs @@ -22,7 +22,7 @@ namespace ComputeSharp where TPixel : unmanaged { /// - /// Creates a new instance with the specified parameters. + /// Creates a new instance with the specified parameters. /// /// The associated with the current instance. /// The width of the texture. diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs index 84acb879..caa6def5 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs @@ -22,7 +22,7 @@ namespace ComputeSharp where TPixel : unmanaged { /// - /// Creates a new instance with the specified parameters. + /// Creates a new instance with the specified parameters. /// /// The associated with the current instance. /// The width of the texture. diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs index cb452315..19d2fe45 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs @@ -22,7 +22,7 @@ namespace ComputeSharp where TPixel : unmanaged { /// - /// Creates a new instance with the specified parameters. + /// Creates a new instance with the specified parameters. /// /// The associated with the current instance. /// The width of the texture. diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 398a1fa7..91228da0 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -4,7 +4,7 @@ - + diff --git a/tests/ComputeSharp.Tests/Extensions/ImagingExtensions.cs b/tests/ComputeSharp.Tests/Extensions/ImagingExtensions.cs index 6994ab4c..ab357a2e 100644 --- a/tests/ComputeSharp.Tests/Extensions/ImagingExtensions.cs +++ b/tests/ComputeSharp.Tests/Extensions/ImagingExtensions.cs @@ -13,21 +13,22 @@ namespace ComputeSharp.Tests.Extensions public static class ImagingExtensions { /// - /// Allocates a new instance with the specified texture data. + /// Creates a new instance with the specified texture data. /// - /// The target instance to allocate the texture for. - /// The path of the texture to load. - /// A texture with the data from the image at the specified path. + /// The source instance to read data from. + /// An image with the data from the input texture. [Pure] - public static ReadOnlyTexture2D LoadTexture(this GraphicsDevice device, string path) + public static Image ToImage(this ReadOnlyTexture2D texture) { - using Image image = Image.Load(path); + Image image = new(texture.Width, texture.Height); Assert.IsTrue(image.TryGetSinglePixelSpan(out Span span)); Span pixels = MemoryMarshal.Cast(span); - return device.AllocateReadOnlyTexture2D(pixels, image.Width, image.Height); + texture.CopyTo(pixels); + + return image; } /// diff --git a/tests/ComputeSharp.Tests/ImageProcessingTests.cs b/tests/ComputeSharp.Tests/ImageProcessingTests.cs new file mode 100644 index 00000000..409ea4b0 --- /dev/null +++ b/tests/ComputeSharp.Tests/ImageProcessingTests.cs @@ -0,0 +1,63 @@ +using System.IO; +using System.Reflection; +using ComputeSharp.BokehBlur.Processors; +using ComputeSharp.Tests.Attributes; +using ComputeSharp.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Processing; +using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; + +namespace ComputeSharp.Tests +{ + [TestClass] + [TestCategory("ImageProcessing")] + public class ImageProcessingTests + { + [CombinatorialTestMethod] + [AllDevices] + public void BokehBlur(Device device) + { + // Early test to ensure the device is available. This saves time when running the + // unit test if the target device is not available, as we skip the preprocessing. + _ = device.Get(); + + string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"); + + using var original = Image.Load(Path.Combine(path, "city.jpg")); + using var cpu = original.Clone(c => c.BokehBlur(80, 2, 3)); + using var gpu = original.Clone(c => c.ApplyProcessor(new HlslBokehBlurProcessor(device.Get(), 80, 2))); + + string + expectedPath = Path.Combine(path, "city_bokeh_cpu.jpg"), + actualPath = Path.Combine(path, "city_bokeh_gpu.jpg"); + + cpu.Save(expectedPath); + gpu.Save(actualPath); + + ImagingTests.TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.000009f); + } + + [CombinatorialTestMethod] + [AllDevices] + public void GaussianBlur(Device device) + { + _ = device.Get(); + + string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"); + + using var original = Image.Load(Path.Combine(path, "city.jpg")); + using var cpu = original.Clone(c => c.GaussianBlur(30f)); + using var gpu = original.Clone(c => c.ApplyProcessor(new HlslGaussianBlurProcessor(device.Get(), 90))); + + string + expectedPath = Path.Combine(path, "city_gaussian_cpu.jpg"), + actualPath = Path.Combine(path, "city_gaussian_gpu.jpg"); + + cpu.Save(expectedPath); + gpu.Save(actualPath); + + ImagingTests.TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.000003f); + } + } +} diff --git a/tests/ComputeSharp.Tests/ImagingTests.cs b/tests/ComputeSharp.Tests/ImagingTests.cs index 97ffe400..6e0e7656 100644 --- a/tests/ComputeSharp.Tests/ImagingTests.cs +++ b/tests/ComputeSharp.Tests/ImagingTests.cs @@ -4,13 +4,12 @@ using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; -using ComputeSharp.BokehBlur.Processors; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; using SixLabors.ImageSharp; -using SixLabors.ImageSharp.Processing; using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; +using ImageSharpL8 = SixLabors.ImageSharp.PixelFormats.L8; namespace ComputeSharp.Tests { @@ -20,48 +19,85 @@ namespace ComputeSharp.Tests { [CombinatorialTestMethod] [AllDevices] - public void BokehBlur(Device device) + public void LoadAsRgba32FromFile(Device device) { - // Early test to ensure the device is available. This saves time when running the - // unit test if the target device is not available, as we skip the preprocessing. - _ = device.Get(); + string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg"); - string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"); + using ReadOnlyTexture2D texture = device.Get().AllocateReadOnlyTexture2D(path); - using var original = Image.Load(Path.Combine(path, "city.jpg")); - using var cpu = original.Clone(c => c.BokehBlur(80, 2, 3)); - using var gpu = original.Clone(c => c.ApplyProcessor(new HlslBokehBlurProcessor(device.Get(), 80, 2))); + using Image loaded = texture.ToImage(); + using Image original = Image.Load(path); - string - expectedPath = Path.Combine(path, "city_bokeh_cpu.jpg"), - actualPath = Path.Combine(path, "city_bokeh_gpu.jpg"); - - cpu.Save(expectedPath); - gpu.Save(actualPath); - - TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.000009f); + TolerantImageComparer.AssertEqual(original, loaded, 0.0000032f); } [CombinatorialTestMethod] [AllDevices] - public void GaussianBlur(Device device) + public void LoadAsRgba32FromBuffer(Device device) { - _ = device.Get(); + string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg"); - string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"); + byte[] buffer = File.ReadAllBytes(path); - using var original = Image.Load(Path.Combine(path, "city.jpg")); - using var cpu = original.Clone(c => c.GaussianBlur(30f)); - using var gpu = original.Clone(c => c.ApplyProcessor(new HlslGaussianBlurProcessor(device.Get(), 90))); + using ReadOnlyTexture2D texture = device.Get().AllocateReadOnlyTexture2D(buffer); + using Image loaded = texture.ToImage(); + using Image original = Image.Load(path); + + TolerantImageComparer.AssertEqual(original, loaded, 0.0000032f); + } + + [CombinatorialTestMethod] + [AllDevices] + public void SaveRgba32AsJpeg(Device device) + { string - expectedPath = Path.Combine(path, "city_gaussian_cpu.jpg"), - actualPath = Path.Combine(path, "city_gaussian_gpu.jpg"); + path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"), + expectedPath = Path.Combine(path, "city.jpg"), + actualPath = Path.Combine(path, "city_rgba32_saved.jpg"); - cpu.Save(expectedPath); - gpu.Save(actualPath); + using ReadOnlyTexture2D texture = device.Get().AllocateReadOnlyTexture2D(expectedPath); - TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.000003f); + texture.Save(actualPath); + + TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.00001023f); + } + + [CombinatorialTestMethod] + [AllDevices] + public void SaveBgra32AsJpeg(Device device) + { + string + path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"), + expectedPath = Path.Combine(path, "city.jpg"), + actualPath = Path.Combine(path, "city_bgra32_saved.jpg"); + + using ReadOnlyTexture2D texture = device.Get().AllocateReadOnlyTexture2D(expectedPath); + + texture.Save(actualPath); + + TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.00001023f); + } + + [CombinatorialTestMethod] + [AllDevices] + public void SaveR8AsJpeg(Device device) + { + string + path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"), + sourcePath = Path.Combine(path, "city.jpg"), + expectedPath = Path.Combine(path, "city_r8_reference.jpg"), + actualPath = Path.Combine(path, "city_r8_saved.jpg"); + + using ReadOnlyTexture2D texture = device.Get().AllocateReadOnlyTexture2D(sourcePath); + + texture.Save(actualPath); + + using Image original = Image.Load(sourcePath); + + original.Save(expectedPath); + + TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.00004037f); } /// diff --git a/tests/ComputeSharp.Tests/ShadersTests.cs b/tests/ComputeSharp.Tests/ShadersTests.cs index 075e7ffa..2a3bdf14 100644 --- a/tests/ComputeSharp.Tests/ShadersTests.cs +++ b/tests/ComputeSharp.Tests/ShadersTests.cs @@ -105,7 +105,7 @@ namespace ComputeSharp.Tests { string filename = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Shaders", "Textures", "RustyMetal.png"); - using ReadOnlyTexture2D background = device.Get().LoadTexture(filename); + using ReadOnlyTexture2D background = device.Get().AllocateReadOnlyTexture2D(filename); RunAndCompareShader( device, diff --git a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs index 294dd521..0c0fec91 100644 --- a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs +++ b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs @@ -76,14 +76,14 @@ namespace ComputeSharp.Tests using var sampled = Image.Load(Path.Combine(assetsPath, "CityAfter1024x1024Sampling.png")); - using ReadOnlyTexture2D source = device.Get().LoadTexture(Path.Combine(imagingPath, "city.jpg")); + using ReadOnlyTexture2D source = device.Get().AllocateReadOnlyTexture2D(Path.Combine(imagingPath, "city.jpg")); using ReadWriteTexture2D destination = device.Get().AllocateReadWriteTexture2D(sampled.Width, sampled.Height); device.Get().For(sampled.Width, sampled.Height, new SamplingComputeShader(source, destination)); using var processed = destination.ToImage(); - ImagingTests.TolerantImageComparer.AssertEqual(sampled, processed, 0.00000086f); + ImagingTests.TolerantImageComparer.AssertEqual(sampled, processed, 0.0000017f); } [AutoConstructor] @@ -109,14 +109,14 @@ namespace ComputeSharp.Tests using var sampled = Image.Load(Path.Combine(assetsPath, "CityAfter1024x1024Sampling.png")); - using ReadOnlyTexture2D source = device.Get().LoadTexture(Path.Combine(imagingPath, "city.jpg")); + using ReadOnlyTexture2D source = device.Get().AllocateReadOnlyTexture2D(Path.Combine(imagingPath, "city.jpg")); using ReadWriteTexture2D destination = device.Get().AllocateReadWriteTexture2D(sampled.Width, sampled.Height); device.Get().ForEach(destination, new SamplingPixelShader(source)); using var processed = destination.ToImage(); - ImagingTests.TolerantImageComparer.AssertEqual(sampled, processed, 0.00000086f); + ImagingTests.TolerantImageComparer.AssertEqual(sampled, processed, 0.0000017f); } [AutoConstructor]