diff --git a/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems b/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems index 5e1d264c..3d8e7be8 100644 --- a/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems +++ b/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems @@ -15,6 +15,7 @@ + @@ -22,6 +23,7 @@ + diff --git a/src/ComputeSharp.NetStandard/System/IO/StreamExtensions.cs b/src/ComputeSharp.NetStandard/System/IO/StreamExtensions.cs new file mode 100644 index 00000000..6e94d749 --- /dev/null +++ b/src/ComputeSharp.NetStandard/System/IO/StreamExtensions.cs @@ -0,0 +1,54 @@ +using System.Buffers; + +namespace System.IO; + +/// +/// A polyfill type with extensions for . +/// +internal static class StreamExtensions +{ + /// + /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. + /// + /// The input instance. + /// A region of memory. When this method returns, the contents of this region are replaced by the bytes read from the current source. + /// The total number of bytes read into the buffer. + public static int Read(this Stream stream, Span span) + { + if (span.IsEmpty) + { + return 0; + } + + byte[] array = ArrayPool.Shared.Rent(span.Length); + + int bytesRead = stream.Read(array, 0, span.Length); + + array.AsSpan(0, bytesRead).CopyTo(span); + + ArrayPool.Shared.Return(array); + + return bytesRead; + } + + /// + /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. + /// + /// The input instance. + /// A region of memory. This method copies the contents of this region to the current stream. + public static void Write(this Stream stream, ReadOnlySpan span) + { + if (span.IsEmpty) + { + return; + } + + byte[] array = ArrayPool.Shared.Rent(span.Length); + + span.CopyTo(array); + + stream.Write(array, 0, span.Length); + + ArrayPool.Shared.Return(array); + } +} diff --git a/src/ComputeSharp.NetStandard/System/Runtime/InteropServices/UnmanagedCallersOnlyAttribute.cs b/src/ComputeSharp.NetStandard/System/Runtime/InteropServices/UnmanagedCallersOnlyAttribute.cs new file mode 100644 index 00000000..c9cbc8f0 --- /dev/null +++ b/src/ComputeSharp.NetStandard/System/Runtime/InteropServices/UnmanagedCallersOnlyAttribute.cs @@ -0,0 +1,14 @@ +using System; + +namespace ComputeSharp.NetStandard.System.Runtime.InteropServices; + +/// +/// Any method marked with can be directly called from native code. +/// +/// +/// This polyfill is deliberately in the wrong namespace to avoid the C# compiler failing to build below .NET 5. +/// +[AttributeUsage(AttributeTargets.Method, Inherited = false)] +public sealed class UnmanagedCallersOnlyAttribute : Attribute +{ +} \ No newline at end of file diff --git a/src/ComputeSharp/Core/PixelTypes/Bgra32.cs b/src/ComputeSharp/Core/Imaging/Bgra32.cs similarity index 100% rename from src/ComputeSharp/Core/PixelTypes/Bgra32.cs rename to src/ComputeSharp/Core/Imaging/Bgra32.cs diff --git a/src/ComputeSharp/Core/Imaging/Formats/ImageFormat.cs b/src/ComputeSharp/Core/Imaging/Formats/ImageFormat.cs new file mode 100644 index 00000000..218957e5 --- /dev/null +++ b/src/ComputeSharp/Core/Imaging/Formats/ImageFormat.cs @@ -0,0 +1,37 @@ +namespace ComputeSharp; + +/// +/// An representing a supported image format. +/// +public enum ImageFormat +{ + /// + /// The BMP format. + /// + Bmp, + + /// + /// The PNG format. + /// + Png, + + /// + /// The JPEG format. + /// + Jpeg, + + /// + /// The WMP format (also used for .jxr, .hdp, .wdp and .wmp files). + /// + Wmp, + + /// + /// The TIFF format. + /// + Tiff, + + /// + /// The DDS format. + /// + Dds +} diff --git a/src/ComputeSharp/Core/PixelTypes/R16.cs b/src/ComputeSharp/Core/Imaging/R16.cs similarity index 100% rename from src/ComputeSharp/Core/PixelTypes/R16.cs rename to src/ComputeSharp/Core/Imaging/R16.cs diff --git a/src/ComputeSharp/Core/PixelTypes/R8.cs b/src/ComputeSharp/Core/Imaging/R8.cs similarity index 100% rename from src/ComputeSharp/Core/PixelTypes/R8.cs rename to src/ComputeSharp/Core/Imaging/R8.cs diff --git a/src/ComputeSharp/Core/PixelTypes/Rg16.cs b/src/ComputeSharp/Core/Imaging/Rg16.cs similarity index 100% rename from src/ComputeSharp/Core/PixelTypes/Rg16.cs rename to src/ComputeSharp/Core/Imaging/Rg16.cs diff --git a/src/ComputeSharp/Core/PixelTypes/Rg32.cs b/src/ComputeSharp/Core/Imaging/Rg32.cs similarity index 100% rename from src/ComputeSharp/Core/PixelTypes/Rg32.cs rename to src/ComputeSharp/Core/Imaging/Rg32.cs diff --git a/src/ComputeSharp/Core/PixelTypes/Rgba32.cs b/src/ComputeSharp/Core/Imaging/Rgba32.cs similarity index 100% rename from src/ComputeSharp/Core/PixelTypes/Rgba32.cs rename to src/ComputeSharp/Core/Imaging/Rgba32.cs diff --git a/src/ComputeSharp/Core/PixelTypes/Rgba64.cs b/src/ComputeSharp/Core/Imaging/Rgba64.cs similarity index 100% rename from src/ComputeSharp/Core/PixelTypes/Rgba64.cs rename to src/ComputeSharp/Core/Imaging/Rgba64.cs diff --git a/src/ComputeSharp/Core/PixelTypes/__Internals/IUnorm{TPixel}.cs b/src/ComputeSharp/Core/Imaging/__Internals/IUnorm{TPixel}.cs similarity index 100% rename from src/ComputeSharp/Core/PixelTypes/__Internals/IUnorm{TPixel}.cs rename to src/ComputeSharp/Core/Imaging/__Internals/IUnorm{TPixel}.cs diff --git a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Resources.cs b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Resources.cs index 18c54fb3..8220fc1a 100644 --- a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Resources.cs +++ b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Resources.cs @@ -1,5 +1,6 @@ using System; using System.Diagnostics.Contracts; +using System.IO; using ComputeSharp.__Internals; using ComputeSharp.Graphics.Helpers; using ComputeSharp.Resources; @@ -1133,6 +1134,30 @@ public static partial class GraphicsDeviceExtensions return texture; } + /// + /// Loads a new readonly 2D texture with the contents of the specified stream. + /// + /// 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 stream with the image data to load and decode into the texture. + /// A instance with the contents of the specified file. + [Pure] + public static ReadOnlyTexture2D LoadReadOnlyTexture2D(this GraphicsDevice device, Stream stream) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + Guard.IsNotNull(stream, nameof(stream)); + + using UploadTexture2D upload = WICHelper.Instance.LoadTexture(device, stream); + + ReadOnlyTexture2D texture = device.AllocateReadOnlyTexture2D(upload.Width, upload.Height); + + upload.CopyTo(texture); + + return texture; + } + /// /// Loads a new writeable 2D texture with the contents of the specified file. /// @@ -1194,4 +1219,28 @@ public static partial class GraphicsDeviceExtensions return texture; } + + /// + /// Loads a new writeable 2D texture with the contents of the specified stream. + /// + /// 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 stream with the image data to load and decode into the texture. + /// A instance with the contents of the specified file. + [Pure] + public static ReadWriteTexture2D LoadReadWriteTexture2D(this GraphicsDevice device, Stream stream) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + Guard.IsNotNull(stream, nameof(stream)); + + using UploadTexture2D upload = WICHelper.Instance.LoadTexture(device, stream); + + ReadWriteTexture2D texture = device.AllocateReadWriteTexture2D(upload.Width, upload.Height); + + upload.CopyTo(texture); + + return texture; + } } diff --git a/src/ComputeSharp/Graphics/Extensions/Interop/IWICStreamExtensions.STGM.cs b/src/ComputeSharp/Graphics/Extensions/Interop/IWICStreamExtensions.STGM.cs new file mode 100644 index 00000000..74c6c521 --- /dev/null +++ b/src/ComputeSharp/Graphics/Extensions/Interop/IWICStreamExtensions.STGM.cs @@ -0,0 +1,20 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/coml2api.h in the Windows SDK for Windows 10.0.20348.0 +// Original source is Copyright © Microsoft. All rights reserved. + +#if NET6_0_OR_GREATER + +namespace TerraFX.Interop.Windows; + +// TODO: remove this once TerraFX.Interop.Windows is updated +internal static partial class STGM +{ + public const int STGM_READ = 0x00000000; + + public const int STGM_WRITE = 0x00000001; + + public const int STGM_READWRITE = 0x00000002; +} + +#endif \ No newline at end of file diff --git a/src/ComputeSharp/Graphics/Extensions/Interop/IWICStreamExtensions.cs b/src/ComputeSharp/Graphics/Extensions/Interop/IWICStreamExtensions.cs new file mode 100644 index 00000000..b2e0c83f --- /dev/null +++ b/src/ComputeSharp/Graphics/Extensions/Interop/IWICStreamExtensions.cs @@ -0,0 +1,585 @@ +using System; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using Microsoft.Toolkit.Diagnostics; +using TerraFX.Interop.Windows; +using static TerraFX.Interop.Windows.E; +using static TerraFX.Interop.Windows.IID; +using static TerraFX.Interop.Windows.S; +using static TerraFX.Interop.Windows.STATFLAG; +using static TerraFX.Interop.Windows.STG; +using static TerraFX.Interop.Windows.STGM; +using static TerraFX.Interop.Windows.STGTY; +#if NET6_0_OR_GREATER +using RuntimeHelpers = System.Runtime.CompilerServices.RuntimeHelpers; +#else +using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute; +#endif + +namespace ComputeSharp.Graphics.Extensions; + +/// +/// A with extensions for the type. +/// +internal static unsafe class IWICStreamExtensions +{ + /// + /// Initializes an input wrapping a given instance. + /// + /// The target object to initialize. + /// The input instance to wrap. + /// An value indicating the operation result. + public static HRESULT InitializeFromStream(this ref IWICStream stream, Stream source) + { + using ComPtr streamWrapper = default; + + IStreamWrapper.Create(source, streamWrapper.GetAddressOf()); + + return stream.InitializeFromIStream((IStream*)streamWrapper.Get()); + } + + /// + /// A manual CCW implementation for an object wrapping a instance. + /// + internal unsafe partial struct IStreamWrapper +#if NET6_0_OR_GREATER + : IUnknown.Interface +#endif + { +#if !NET6_0_OR_GREATER + /// + private delegate int QueryInterfaceDelegate(IStreamWrapper* @this, Guid* riid, void** ppvObject); + + /// + private delegate uint AddRefDelegate(IStreamWrapper* @this); + + /// + private delegate uint ReleaseDelegate(IStreamWrapper* @this); + + /// + private delegate HRESULT ReadDelegate(IStreamWrapper* @this, void* pv, uint cb, uint* pcbRead); + + /// + private delegate HRESULT WriteDelegate(IStreamWrapper* @this, void* pv, uint cb, uint* pcbWritten); + + /// + private delegate HRESULT SeekDelegate(IStreamWrapper* @this, LARGE_INTEGER dlibMove, uint dwOrigin, ULARGE_INTEGER* plibNewPosition); + + /// + private delegate HRESULT SetSizeDelegate(IStreamWrapper* @this, ULARGE_INTEGER libNewSize); + + /// + private delegate HRESULT CopyToDelegate(IStreamWrapper* @this, IStream* pstm, ULARGE_INTEGER cb, ULARGE_INTEGER* pcbRead, ULARGE_INTEGER* pcbWritten); + + /// + private delegate HRESULT CommitDelegate(IStreamWrapper* @this, uint grfCommitFlags); + + /// + private delegate HRESULT RevertDelegate(IStreamWrapper* @this); + + /// + private delegate HRESULT LockRegionDelegate(IStreamWrapper* @this, ULARGE_INTEGER libOffset, ULARGE_INTEGER cb, uint dwLockType); + + /// + private delegate HRESULT UnlockRegionDelegate(IStreamWrapper* @this, ULARGE_INTEGER libOffset, ULARGE_INTEGER cb, uint dwLockType); + + /// + private delegate HRESULT StatDelegate(IStreamWrapper* @this, STATSTG* pstatstg, uint grfStatFlag); + + /// + private delegate HRESULT CloneDelegate(IStreamWrapper* @this, IStream** ppstm); + + /// + /// A cached instance wrapping . + /// + private static readonly QueryInterfaceDelegate QueryInterfaceWrapper = QueryInterface; + + /// + /// A cached instance wrapping . + /// + private static readonly AddRefDelegate AddRefWrapper = AddRef; + + /// + /// A cached instance wrapping . + /// + private static readonly ReleaseDelegate ReleaseWrapper = Release; + + /// + /// A cached instance wrapping . + /// + private static readonly ReadDelegate ReadWrapper = Read; + + /// + /// A cached instance wrapping . + /// + private static readonly WriteDelegate WriteWrapper = Write; + + /// + /// A cached instance wrapping . + /// + private static readonly SeekDelegate SeekWrapper = Seek; + + /// + /// A cached instance wrapping . + /// + private static readonly SetSizeDelegate SetSizeWrapper = SetSize; + + /// + /// A cached instance wrapping . + /// + private static readonly CopyToDelegate CopyToWrapper = CopyTo; + + /// + /// A cached instance wrapping . + /// + private static readonly CommitDelegate CommitWrapper = Commit; + + /// + /// A cached instance wrapping . + /// + private static readonly RevertDelegate RevertWrapper = Revert; + + /// + /// A cached instance wrapping . + /// + private static readonly LockRegionDelegate LockRegionWrapper = LockRegion; + + /// + /// A cached instance wrapping . + /// + private static readonly UnlockRegionDelegate UnlockRegionWrapper = UnlockRegion; + + /// + /// A cached instance wrapping . + /// + private static readonly StatDelegate StatWrapper = Stat; + + /// + /// A cached instance wrapping . + /// + private static readonly CloneDelegate CloneWrapper = Clone; +#endif + + /// + /// The shared vtable pointer for instances. + /// + private static readonly void** Vtbl = InitVtbl(); + + /// + /// Setups the vtable pointer for . + /// + /// The initialized vtable pointer for . + private static void** InitVtbl() + { + void** lpVtbl = (void**)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(IStreamWrapper), sizeof(void*) * 14); + +#if NET6_0_OR_GREATER + lpVtbl[0] = (delegate* unmanaged)&QueryInterface; + lpVtbl[1] = (delegate* unmanaged)&AddRef; + lpVtbl[2] = (delegate* unmanaged)&Release; + lpVtbl[3] = (delegate* unmanaged)&Read; + lpVtbl[4] = (delegate* unmanaged)&Write; + lpVtbl[5] = (delegate* unmanaged)&Seek; + lpVtbl[6] = (delegate* unmanaged)&SetSize; + lpVtbl[7] = (delegate* unmanaged)&CopyTo; + lpVtbl[8] = (delegate* unmanaged)&Commit; + lpVtbl[9] = (delegate* unmanaged)&Revert; + lpVtbl[10] = (delegate* unmanaged)&LockRegion; + lpVtbl[11] = (delegate* unmanaged)&UnlockRegion; + lpVtbl[12] = (delegate* unmanaged)&Stat; + lpVtbl[13] = (delegate* unmanaged)&Clone; +#else + lpVtbl[0] = (void*)Marshal.GetFunctionPointerForDelegate(QueryInterfaceWrapper); + lpVtbl[1] = (void*)Marshal.GetFunctionPointerForDelegate(AddRefWrapper); + lpVtbl[2] = (void*)Marshal.GetFunctionPointerForDelegate(ReleaseWrapper); + lpVtbl[3] = (void*)Marshal.GetFunctionPointerForDelegate(ReadWrapper); + lpVtbl[4] = (void*)Marshal.GetFunctionPointerForDelegate(WriteWrapper); + lpVtbl[5] = (void*)Marshal.GetFunctionPointerForDelegate(SeekWrapper); + lpVtbl[6] = (void*)Marshal.GetFunctionPointerForDelegate(SetSizeWrapper); + lpVtbl[7] = (void*)Marshal.GetFunctionPointerForDelegate(CopyToWrapper); + lpVtbl[8] = (void*)Marshal.GetFunctionPointerForDelegate(CommitWrapper); + lpVtbl[9] = (void*)Marshal.GetFunctionPointerForDelegate(RevertWrapper); + lpVtbl[10] = (void*)Marshal.GetFunctionPointerForDelegate(LockRegionWrapper); + lpVtbl[11] = (void*)Marshal.GetFunctionPointerForDelegate(UnlockRegionWrapper); + lpVtbl[12] = (void*)Marshal.GetFunctionPointerForDelegate(StatWrapper); + lpVtbl[13] = (void*)Marshal.GetFunctionPointerForDelegate(CloneWrapper); +#endif + + return lpVtbl; + } + + /// + /// The vtable pointer for the current instance. + /// + public void** lpVtbl; + + /// + /// The current reference count for the object (from IUnknown). + /// + public volatile int referenceCount; + + /// + /// The to the captured . + /// + public GCHandle streamHandle; + + /// + /// Creates and initializes a new instance. + /// + /// The input instance to wrap. + /// The target instance to initialize. + public static void Create(Stream stream, IStreamWrapper** streamWrapper) + { + IStreamWrapper* @this = (IStreamWrapper*)NativeMemory.Alloc((nuint)sizeof(IStreamWrapper)); + + @this->lpVtbl = Vtbl; + @this->referenceCount = 1; + @this->streamHandle = GCHandle.Alloc(stream); + + *streamWrapper = @this; + } + + /// + /// Gets the captured instance. + /// + /// The captured instance + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private Stream GetStream() + { + return Unsafe.As(this.streamHandle.Target!); + } + +#if NET6_0_OR_GREATER + /// + public HRESULT QueryInterface(Guid* riid, void** ppvObject) + { + return ((delegate* unmanaged)lpVtbl[0])((IStreamWrapper*)Unsafe.AsPointer(ref this), riid, ppvObject); + } + + /// + public uint AddRef() + { + return ((delegate* unmanaged)lpVtbl[1])((IStreamWrapper*)Unsafe.AsPointer(ref this)); + } + + /// + public uint Release() + { + return ((delegate* unmanaged)lpVtbl[2])((IStreamWrapper*)Unsafe.AsPointer(ref this)); + } +#endif + + /// + [UnmanagedCallersOnly] + private static int QueryInterface(IStreamWrapper* @this, Guid* riid, void** ppvObject) + { + if (ppvObject is null) + { + return E_POINTER; + } + + if (riid->Equals(IID_IUnknown) || + riid->Equals(IID_ISequentialStream) || + riid->Equals(IID_IStream)) + { + _ = Interlocked.Increment(ref @this->referenceCount); + + *ppvObject = @this; + + return S_OK; + } + + *ppvObject = null; + + return E_NOINTERFACE; + } + + /// + [UnmanagedCallersOnly] + private static uint AddRef(IStreamWrapper* @this) + { + return (uint)Interlocked.Increment(ref @this->referenceCount); + } + + /// + [UnmanagedCallersOnly] + private static uint Release(IStreamWrapper* @this) + { + uint referenceCount = (uint)Interlocked.Decrement(ref @this->referenceCount); + + if (referenceCount == 0) + { + @this->streamHandle.Free(); + + NativeMemory.Free(@this); + } + + return referenceCount; + } + + /// + [UnmanagedCallersOnly] + private static HRESULT Read(IStreamWrapper* @this, void* pv, uint cb, uint* pcbRead) + { + if (pv == null) + { + return E_POINTER; + } + + if (cb > int.MaxValue) + { + return E_INVALIDARG; + } + + if (pcbRead != null) + { + *pcbRead = 0; + } + + try + { + Span dst = new(pv, (int)cb); + + while (dst.Length > 0) + { + int bytesRead = @this->GetStream().Read(dst); + + if (bytesRead == 0) + { + return S_FALSE; + } + + if (pcbRead != null) + { + *pcbRead += (uint)bytesRead; + } + + dst = dst.Slice(bytesRead); + } + + return S_OK; + } + catch (Exception ex) + { + return ex.HResult; + } + } + + /// + [UnmanagedCallersOnly] + private static HRESULT Write(IStreamWrapper* @this, void* pv, uint cb, uint* pcbWritten) + { + if (pv == null) + { + return E_POINTER; + } + + if (cb > int.MaxValue) + { + return E_INVALIDARG; + } + + if (pcbWritten != null) + { + *pcbWritten = 0; + } + + try + { + @this->GetStream().Write(new ReadOnlySpan(pv, (int)cb)); + + if (pcbWritten != null) + { + *pcbWritten = cb; + } + + return S_OK; + } + catch (Exception ex) + { + return ex.HResult; + } + } + + /// + [UnmanagedCallersOnly] + private static HRESULT Seek(IStreamWrapper* @this, LARGE_INTEGER dlibMove, uint dwOrigin, ULARGE_INTEGER* plibNewPosition) + { + SeekOrigin origin = (SeekOrigin)dwOrigin; + + switch (origin) + { + case SeekOrigin.Begin: + case SeekOrigin.Current: + case SeekOrigin.End: + break; + default: + return E_INVALIDARG; + } + + if (plibNewPosition != null) + { + *plibNewPosition = default; + } + + try + { + long newPosition = @this->GetStream().Seek(dlibMove.QuadPart, origin); + + if (plibNewPosition != null) + { + plibNewPosition->QuadPart = (ulong)newPosition; + } + + return S_OK; + } + catch (Exception ex) + { + return ex.HResult; + } + } + + /// + [UnmanagedCallersOnly] + private static HRESULT SetSize(IStreamWrapper* @this, ULARGE_INTEGER libNewSize) + { + if (libNewSize.QuadPart > long.MaxValue) + { + return E_INVALIDARG; + } + + try + { + @this->GetStream().SetLength((long)libNewSize.QuadPart); + + return S_OK; + } + catch (Exception ex) + { + return ex.HResult; + } + } + + /// + [UnmanagedCallersOnly] + private static HRESULT CopyTo(IStreamWrapper* @this, IStream* pstm, ULARGE_INTEGER cb, ULARGE_INTEGER* pcbRead, ULARGE_INTEGER* pcbWritten) + { + return E_NOTIMPL; + } + + /// + [UnmanagedCallersOnly] + private static HRESULT Commit(IStreamWrapper* @this, uint grfCommitFlags) + { + try + { + @this->GetStream().Flush(); + + return S_OK; + } + catch (Exception ex) + { + return ex.HResult; + } + } + + /// + [UnmanagedCallersOnly] + private static HRESULT Revert(IStreamWrapper* @this) + { + return STG_E_INVALIDFUNCTION; + } + + /// + [UnmanagedCallersOnly] + private static HRESULT LockRegion(IStreamWrapper* @this, ULARGE_INTEGER libOffset, ULARGE_INTEGER cb, uint dwLockType) + { + return STG_E_INVALIDFUNCTION; + } + + /// + [UnmanagedCallersOnly] + private static HRESULT UnlockRegion(IStreamWrapper* @this, ULARGE_INTEGER libOffset, ULARGE_INTEGER cb, uint dwLockType) + { + return STG_E_INVALIDFUNCTION; + } + + /// + [UnmanagedCallersOnly] + private static HRESULT Stat(IStreamWrapper* @this, STATSTG* pstatstg, uint grfStatFlag) + { + if (pstatstg == null) + { + return E_POINTER; + } + + *pstatstg = default; + + STATFLAG statFlag = (STATFLAG)grfStatFlag; + + if ((statFlag & (STATFLAG_DEFAULT | STATFLAG_NONAME | STATFLAG_NOOPEN)) != statFlag) + { + return E_INVALIDARG; + } + + try + { + Stream stream = @this->GetStream(); + + if (!statFlag.HasFlag(STATFLAG_NONAME)) + { + if (stream is FileStream asFileStream) + { + pstatstg->pwcsName = (ushort*)Marshal.StringToCoTaskMemUni(asFileStream.Name); + } + } + + bool canRead = stream.CanRead; + bool canWrite = stream.CanWrite; + + if (canRead && !canWrite) + { + pstatstg->grfMode = STGM_READ; + } + else if (canRead && canWrite) + { + pstatstg->grfMode = STGM_READWRITE; + } + else if (!canRead && canWrite) + { + pstatstg->grfMode = STGM_WRITE; + } + else + { + ThrowHelper.ThrowNotSupportedException(); + } + + pstatstg->type = (uint)STGTY_STREAM; + pstatstg->cbSize.QuadPart = (ulong)stream.Length; + + return S_OK; + } + catch (Exception ex) + { + if (pstatstg->pwcsName != null) + { + Marshal.FreeCoTaskMem((IntPtr)pstatstg->pwcsName); + + pstatstg->pwcsName = null; + } + + return ex.HResult; + } + } + + /// + [UnmanagedCallersOnly] + private static HRESULT Clone(IStreamWrapper* @this, IStream** ppstm) + { + return STG_E_INVALIDFUNCTION; + } + } +} diff --git a/src/ComputeSharp/Graphics/Extensions/ReadBackTexture2DExtensions.cs b/src/ComputeSharp/Graphics/Extensions/ReadBackTexture2DExtensions.cs index 7a4b51cd..4cfc2758 100644 --- a/src/ComputeSharp/Graphics/Extensions/ReadBackTexture2DExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/ReadBackTexture2DExtensions.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using ComputeSharp.Graphics.Helpers; using ComputeSharp.Resources; using Microsoft.Toolkit.Diagnostics; @@ -81,4 +82,19 @@ public static class ReadBackTexture2DExtensions { WICHelper.Instance.SaveTexture(texture.View, filename); } + + /// + /// Saves a texture to a specified stream. + /// + /// The type of items to store in the texture. + /// The texture to save to an image. + /// The stream to save the image to. + /// The target image format to use. + public static void Save(this ReadBackTexture2D texture, Stream stream, ImageFormat format) + where T : unmanaged + { + Guard.IsNotNull(stream, nameof(stream)); + + WICHelper.Instance.SaveTexture(texture.View, stream, format); + } } diff --git a/src/ComputeSharp/Graphics/Extensions/Texture2DExtensions.cs b/src/ComputeSharp/Graphics/Extensions/Texture2DExtensions.cs index 887659dd..d365be74 100644 --- a/src/ComputeSharp/Graphics/Extensions/Texture2DExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/Texture2DExtensions.cs @@ -1,5 +1,6 @@ using System; using System.Diagnostics.Contracts; +using System.IO; using System.Runtime.InteropServices; using ComputeSharp.Graphics.Helpers; using ComputeSharp.Resources; @@ -564,4 +565,23 @@ public static class Texture2DExtensions WICHelper.Instance.SaveTexture(readback.View, filename); } + + /// + /// Saves a texture to a specified stream. + /// + /// The type of items to store in the texture. + /// The texture to save to an image. + /// The stream to save the image to. + /// The target image format to use. + public static void Save(this Texture2D texture, Stream stream, ImageFormat format) + where T : unmanaged + { + Guard.IsNotNull(stream, nameof(stream)); + + using ReadBackTexture2D readback = texture.GraphicsDevice.AllocateReadBackTexture2D(texture.Width, texture.Height); + + texture.CopyTo(readback); + + WICHelper.Instance.SaveTexture(readback.View, stream, format); + } } diff --git a/src/ComputeSharp/Graphics/Extensions/UploadTexture2DExtensions.cs b/src/ComputeSharp/Graphics/Extensions/UploadTexture2DExtensions.cs index 675aab5d..6b97447c 100644 --- a/src/ComputeSharp/Graphics/Extensions/UploadTexture2DExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/UploadTexture2DExtensions.cs @@ -1,4 +1,8 @@ -using ComputeSharp.Resources; +using System; +using System.IO; +using ComputeSharp.Graphics.Helpers; +using ComputeSharp.Resources; +using Microsoft.Toolkit.Diagnostics; namespace ComputeSharp; @@ -52,4 +56,57 @@ public static class UploadTexture2DExtensions { destination.CopyFrom(source, sourceOffsetX, sourceOffsetY, destinationOffsetX, destinationOffsetY, width, height); } + + /// + /// Loads a texture from a specified file. + /// + /// The type of items stored on the texture. + /// The texture to decode the image into. + /// The filename of the image file to load. + public static void Load(this UploadTexture2D texture, string filename) + where T : unmanaged + { + Guard.IsNotNull(filename, nameof(filename)); + + texture. Load(filename.AsSpan()); + } + + /// + /// Loads a texture from a specified file. + /// + /// The type of items stored on the texture. + /// The texture to decode the image into. + /// The filename of the image file to load. + public static void Load(this UploadTexture2D texture, ReadOnlySpan filename) + where T : unmanaged + { + WICHelper.Instance.LoadTexture(texture.View, filename); + } + + /// + /// LLoads a texture from a specified buffer. + /// + /// The type of items stored on the texture. + /// The texture to decode the image into. + /// The buffer with the image data to load and decode into the texture. + /// A instance with the contents of the specified file. + public static void Load(this UploadTexture2D texture, ReadOnlySpan span) + where T : unmanaged + { + WICHelper.Instance.LoadTexture(texture.View, span); + } + + /// + /// Loads a texture from a specified stream. + /// + /// The type of items stored on the texture. + /// The texture to decode the image into. + /// The stream to load the image from. + public static void Load(this UploadTexture2D texture, Stream stream) + where T : unmanaged + { + Guard.IsNotNull(stream, nameof(stream)); + + WICHelper.Instance.LoadTexture(texture.View, stream); + } } diff --git a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.IDXGIFactory6.cs b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.IDXGIFactory6.cs index efc66035..1c41b5e7 100644 --- a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.IDXGIFactory6.cs +++ b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.IDXGIFactory6.cs @@ -7,6 +7,7 @@ using TerraFX.Interop.Windows; using RuntimeHelpers = System.Runtime.CompilerServices.RuntimeHelpers; #else using RuntimeHelpers = ComputeSharp.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute; #endif #pragma warning disable CA1416 @@ -85,6 +86,32 @@ internal static partial class DeviceHelper /// private unsafe struct IDXGIFactory4As6Backcompat { +#if !NET6_0_OR_GREATER + /// + private delegate uint ReleaseDelegate(IDXGIFactory4As6Backcompat* @this); + + /// + private delegate int EnumWarpAdapterDelegate(IDXGIFactory4As6Backcompat* @this, Guid* riid, void** ppvAdapter); + + /// + private delegate int EnumAdapterByGpuPreferenceDelegate(IDXGIFactory4As6Backcompat* @this, uint Adapter, DXGI_GPU_PREFERENCE GpuPreference, Guid* riid, void** ppvAdapter); + + /// + /// A cached instance wrapping . + /// + private static readonly ReleaseDelegate ReleaseWrapper = Release; + + /// + /// A cached instance wrapping . + /// + private static readonly EnumWarpAdapterDelegate EnumWarpAdapterWrapper = EnumWarpAdapter; + + /// + /// A cached instance wrapping . + /// + private static readonly EnumAdapterByGpuPreferenceDelegate EnumAdapterByGpuPreferenceWrapper = EnumAdapterByGpuPreference; +#endif + /// /// The shared method table pointer for all instances. /// @@ -138,20 +165,8 @@ internal static partial class DeviceHelper *dxgiFactory6 = (IDXGIFactory6*)@this; } -#if !NET6_0_OR_GREATER - /// - private delegate uint ReleaseDelegate(IDXGIFactory4As6Backcompat* @this); - - /// - /// A cached instance wrapping . - /// - private static readonly ReleaseDelegate ReleaseWrapper = Release; -#endif - /// -#if NET6_0_OR_GREATER [UnmanagedCallersOnly] -#endif public static uint Release(IDXGIFactory4As6Backcompat* @this) { @this->dxgiFactory4->Release(); @@ -161,39 +176,15 @@ internal static partial class DeviceHelper return 0; } -#if !NET6_0_OR_GREATER - /// - private delegate int EnumWarpAdapterDelegate(IDXGIFactory4As6Backcompat* @this, Guid* riid, void** ppvAdapter); - - /// - /// A cached instance wrapping . - /// - private static readonly EnumWarpAdapterDelegate EnumWarpAdapterWrapper = EnumWarpAdapter; -#endif - /// -#if NET6_0_OR_GREATER [UnmanagedCallersOnly] -#endif public static int EnumWarpAdapter(IDXGIFactory4As6Backcompat* @this, Guid* riid, void** ppvAdapter) { return @this->dxgiFactory4->EnumWarpAdapter(riid, ppvAdapter); } -#if !NET6_0_OR_GREATER - /// - private delegate int EnumAdapterByGpuPreferenceDelegate(IDXGIFactory4As6Backcompat* @this, uint Adapter, DXGI_GPU_PREFERENCE GpuPreference, Guid* riid, void** ppvAdapter); - - /// - /// A cached instance wrapping . - /// - private static readonly EnumAdapterByGpuPreferenceDelegate EnumAdapterByGpuPreferenceWrapper = EnumAdapterByGpuPreference; -#endif - /// -#if NET6_0_OR_GREATER [UnmanagedCallersOnly] -#endif public static int EnumAdapterByGpuPreference(IDXGIFactory4As6Backcompat* @this, uint Adapter, DXGI_GPU_PREFERENCE GpuPreference, Guid* riid, void** ppvAdapter) { return @this->dxgiFactory4->EnumAdapters1(Adapter, (IDXGIAdapter1**)ppvAdapter); diff --git a/src/ComputeSharp/Graphics/Helpers/WICFormatHelper.cs b/src/ComputeSharp/Graphics/Helpers/WICFormatHelper.cs index 88d6ea2f..cbc95d3e 100644 --- a/src/ComputeSharp/Graphics/Helpers/WICFormatHelper.cs +++ b/src/ComputeSharp/Graphics/Helpers/WICFormatHelper.cs @@ -132,4 +132,25 @@ internal static class WICFormatHelper _ => ThrowHelper.ThrowArgumentException("Invalid filename"), }; } + + /// + /// Gets the appropriate WIC container format value for the input format. + /// + /// The target format to get the container format for. + /// The WIC format container value matching . + /// Thrown when the input format isn't valid. + [Pure] + public static Guid GetForFormat(ImageFormat format) + { + return format switch + { + ImageFormat.Bmp => GUID.GUID_ContainerFormatBmp, + ImageFormat.Png => GUID.GUID_ContainerFormatPng, + ImageFormat.Jpeg => GUID.GUID_ContainerFormatJpeg, + ImageFormat.Wmp => GUID.GUID_ContainerFormatWmp, + ImageFormat.Tiff => GUID.GUID_ContainerFormatTiff, + ImageFormat.Dds => GUID.GUID_ContainerFormatDds, + _ => ThrowHelper.ThrowArgumentException("Invalid format"), + }; + } } diff --git a/src/ComputeSharp/Graphics/Helpers/WICHelper.cs b/src/ComputeSharp/Graphics/Helpers/WICHelper.cs index 1090d5bb..d1d07e44 100644 --- a/src/ComputeSharp/Graphics/Helpers/WICHelper.cs +++ b/src/ComputeSharp/Graphics/Helpers/WICHelper.cs @@ -1,7 +1,10 @@ using System; using System.Diagnostics.Contracts; +using System.IO; using System.Runtime.CompilerServices; using ComputeSharp.Core.Extensions; +using ComputeSharp.Graphics.Extensions; +using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop.Windows; #pragma warning disable CA1416 @@ -107,103 +110,30 @@ internal sealed unsafe class WICHelper } /// - /// Saves a texture to a specified file. + /// Loads an from a specified stream. /// /// 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) + /// The instance to use to allocate the texture. + /// The stream 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, Stream stream) 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 wicBitmapDecoder = default; 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, - Windows.GENERIC_WRITE); - } + wicStream.Get()->InitializeFromStream(stream).Assert(); - // Initialize the encoder - wicBitmapEncoder.Get()->Initialize( + this.wicImagingFactory2.Get()->CreateDecoderFromStream( (IStream*)wicStream.Get(), - WICBitmapEncoderCacheOption.WICBitmapEncoderNoCache).Assert(); + null, + WICDecodeOptions.WICDecodeMetadataCacheOnDemand, + wicBitmapDecoder.GetAddressOf()).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(); + return LoadTexture(device, wicBitmapDecoder.Get()); } /// @@ -282,4 +212,295 @@ internal sealed unsafe class WICHelper return upload; } } + + /// + /// Loads an image from a specified file. + /// + /// The type of items to store in the texture. + /// The target instance to write data to. + /// The filename of the image file to load and decode into the texture. + [Pure] + public void LoadTexture(TextureView2D texture, ReadOnlySpan filename) + where T : unmanaged + { + using ComPtr wicBitmapDecoder = default; + + fixed (char* p = filename) + { + this.wicImagingFactory2.Get()->CreateDecoderFromFilename( + (ushort*)p, + null, + Windows.GENERIC_READ, + WICDecodeOptions.WICDecodeMetadataCacheOnDemand, + wicBitmapDecoder.GetAddressOf()).Assert(); + } + + LoadTexture(texture, wicBitmapDecoder.Get()); + } + + /// + /// Loads an image from a specified buffer. + /// + /// The type of items to store in the texture. + /// The target instance to write data to. + /// The buffer with the image data to load and decode into the texture. + [Pure] + public void LoadTexture(TextureView2D texture, 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(); + + LoadTexture(texture, wicBitmapDecoder.Get()); + } + } + + /// + /// Loads an image from a specified stream. + /// + /// The type of items to store in the texture. + /// The target instance to write data to. + /// The stream with the image data to load and decode into the texture. + [Pure] + public void LoadTexture(TextureView2D texture, Stream stream) + where T : unmanaged + { + using ComPtr wicBitmapDecoder = default; + using ComPtr wicStream = default; + + this.wicImagingFactory2.Get()->CreateStream(wicStream.GetAddressOf()).Assert(); + + wicStream.Get()->InitializeFromStream(stream).Assert(); + + this.wicImagingFactory2.Get()->CreateDecoderFromStream( + (IStream*)wicStream.Get(), + null, + WICDecodeOptions.WICDecodeMetadataCacheOnDemand, + wicBitmapDecoder.GetAddressOf()).Assert(); + + LoadTexture(texture, wicBitmapDecoder.Get()); + } + + /// + /// Loads image data from a specified object into a target texture. + /// + /// The type of items to store in the texture. + /// The target instance to write data to. + /// The object in use. + [Pure] + private void LoadTexture(TextureView2D texture, IWICBitmapDecoder* wicBitmapDecoder) + where T : unmanaged + { + using ComPtr wicBitmapFrameDecode = default; + + wicBitmapDecoder->GetFrame(0, wicBitmapFrameDecode.GetAddressOf()).Assert(); + + uint width; + uint height; + + // Extract the image size info + wicBitmapFrameDecode.Get()->GetSize(&width, &height).Assert(); + + // Validate the target texture has the right size + Guard.IsEqualTo((uint)texture.Width, width, nameof(texture.Width)); + Guard.IsEqualTo((uint)texture.Height, height, nameof(texture.Height)); + + Guid wicTargetPixelFormatGuid = WICFormatHelper.GetForType(); + Guid wicActualPixelFormatGuid; + + wicBitmapFrameDecode.Get()->GetPixelFormat(&wicActualPixelFormatGuid).Assert(); + + T* data = texture.DangerousGetAddressAndByteStride(out int strideInBytes); + + // Copy the decoded pixels directly from the loaded image + if (wicTargetPixelFormatGuid == wicActualPixelFormatGuid) + { + wicBitmapFrameDecode.Get()->CopyPixels( + prc: null, + cbStride: (uint)strideInBytes, + cbBufferSize: (uint)strideInBytes * height, + pbBuffer: (byte*)data).Assert(); + } + else + { + using ComPtr wicFormatConverter = default; + + this.wicImagingFactory2.Get()->CreateFormatConverter(wicFormatConverter.GetAddressOf()).Assert(); + + wicFormatConverter.Get()->Initialize( + (IWICBitmapSource*)wicBitmapFrameDecode.Get(), + &wicTargetPixelFormatGuid, + WICBitmapDitherType.WICBitmapDitherTypeNone, + null, + 0, + WICBitmapPaletteType.WICBitmapPaletteTypeMedianCut).Assert(); + + // Decode the pixel data into the upload buffer + wicFormatConverter.Get()->CopyPixels( + prc: null, + cbStride: (uint)strideInBytes, + cbBufferSize: (uint)strideInBytes * height, + pbBuffer: (byte*)data).Assert(); + } + } + + /// + /// 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, + Windows.GENERIC_WRITE); + } + + // Initialize the encoder + wicBitmapEncoder.Get()->Initialize( + (IStream*)wicStream.Get(), + WICBitmapEncoderCacheOption.WICBitmapEncoderNoCache).Assert(); + + SaveTexture(texture, wicBitmapEncoder.Get(), containerGuid); + } + + /// + /// Saves a texture to a specified stream. + /// + /// The type of items to store in the texture. + /// The texture data to save to a stream. + /// The target stream to write to. + /// The target image format to use. + public void SaveTexture(TextureView2D texture, Stream stream, ImageFormat format) + where T : unmanaged + { + using ComPtr wicBitmapEncoder = default; + Guid containerGuid = WICFormatHelper.GetForFormat(format); + + // Create the image encoder + this.wicImagingFactory2.Get()->CreateEncoder( + &containerGuid, + null, + wicBitmapEncoder.GetAddressOf()).Assert(); + + using ComPtr wicStream = default; + + // Create and initialize a stream + this.wicImagingFactory2.Get()->CreateStream(wicStream.GetAddressOf()).Assert(); + + wicStream.Get()->InitializeFromStream(stream); + + // Initialize the encoder + wicBitmapEncoder.Get()->Initialize( + (IStream*)wicStream.Get(), + WICBitmapEncoderCacheOption.WICBitmapEncoderNoCache).Assert(); + + SaveTexture(texture, wicBitmapEncoder.Get(), containerGuid); + } + + /// + /// Saves a texture to a specified object. + /// + /// The type of items to store in the texture. + /// The texture data to save to an image. + /// The object in use. + /// The identifying the target format. + private void SaveTexture(TextureView2D texture, IWICBitmapEncoder* wicBitmapEncoder, Guid format) + where T : unmanaged + { + using ComPtr wicBitmapFrameEncode = default; + + // Create the image frame and initialize it + wicBitmapEncoder->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(format, 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->Commit(); + } } diff --git a/src/TerraFX.Interop.Windows/TerraFX.Interop.Windows.projitems b/src/TerraFX.Interop.Windows/TerraFX.Interop.Windows.projitems index c5562388..af64755d 100644 --- a/src/TerraFX.Interop.Windows/TerraFX.Interop.Windows.projitems +++ b/src/TerraFX.Interop.Windows/TerraFX.Interop.Windows.projitems @@ -217,17 +217,25 @@ + + + + + + + + diff --git a/src/TerraFX.Interop.Windows/Windows/shared/minwindef/FILETIME.cs b/src/TerraFX.Interop.Windows/Windows/shared/minwindef/FILETIME.cs new file mode 100644 index 00000000..0f4ac886 --- /dev/null +++ b/src/TerraFX.Interop.Windows/Windows/shared/minwindef/FILETIME.cs @@ -0,0 +1,15 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from shared/minwindef.h in the Windows SDK for Windows 10.0.20348.0 +// Original source is Copyright © Microsoft. All rights reserved. + +namespace TerraFX.Interop.Windows; + +internal partial struct FILETIME +{ + [NativeTypeName("DWORD")] + public uint dwLowDateTime; + + [NativeTypeName("DWORD")] + public uint dwHighDateTime; +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows/Windows/shared/winerror/STG.cs b/src/TerraFX.Interop.Windows/Windows/shared/winerror/STG.cs new file mode 100644 index 00000000..80db6d81 --- /dev/null +++ b/src/TerraFX.Interop.Windows/Windows/shared/winerror/STG.cs @@ -0,0 +1,12 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from shared/winerror.h in the Windows SDK for Windows 10.0.20348.0 +// Original source is Copyright © Microsoft. All rights reserved. + +namespace TerraFX.Interop.Windows; + +internal static partial class STG +{ + [NativeTypeName("#define STG_E_INVALIDFUNCTION _HRESULT_TYPEDEF_(0x80030001L)")] + public const int STG_E_INVALIDFUNCTION = unchecked((int)(0x80030001)); +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows/Windows/shared/wtypes/STATFLAG.cs b/src/TerraFX.Interop.Windows/Windows/shared/wtypes/STATFLAG.cs new file mode 100644 index 00000000..9a1a5369 --- /dev/null +++ b/src/TerraFX.Interop.Windows/Windows/shared/wtypes/STATFLAG.cs @@ -0,0 +1,15 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from shared/wtypes.h in the Windows SDK for Windows 10.0.20348.0 +// Original source is Copyright © Microsoft. All rights reserved. + +namespace TerraFX.Interop.Windows; + +internal enum STATFLAG +{ + STATFLAG_DEFAULT = 0, + + STATFLAG_NONAME = 1, + + STATFLAG_NOOPEN = 2, +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows/Windows/um/Unknwnbase/IID.cs b/src/TerraFX.Interop.Windows/Windows/um/Unknwnbase/IID.cs new file mode 100644 index 00000000..e5f657bf --- /dev/null +++ b/src/TerraFX.Interop.Windows/Windows/um/Unknwnbase/IID.cs @@ -0,0 +1,37 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/Unknwnbase.h in the Windows SDK for Windows 10.0.20348.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace TerraFX.Interop.Windows; + +internal static partial class IID +{ + public static ref readonly Guid IID_IUnknown + { + get + { + ReadOnlySpan data = new byte[] { + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, + 0x00, 0x00, + 0xC0, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x46 + }; + + Debug.Assert(data.Length == Unsafe.SizeOf()); + return ref Unsafe.As(ref MemoryMarshal.GetReference(data)); + } + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows/Windows/um/coml2api/STGM.cs b/src/TerraFX.Interop.Windows/Windows/um/coml2api/STGM.cs new file mode 100644 index 00000000..8e541953 --- /dev/null +++ b/src/TerraFX.Interop.Windows/Windows/um/coml2api/STGM.cs @@ -0,0 +1,18 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/coml2api.h in the Windows SDK for Windows 10.0.20348.0 +// Original source is Copyright © Microsoft. All rights reserved. + +namespace TerraFX.Interop.Windows; + +internal static partial class STGM +{ + [NativeTypeName("#define STGM_READ 0x00000000L")] + public const int STGM_READ = 0x00000000; + + [NativeTypeName("#define STGM_WRITE 0x00000001L")] + public const int STGM_WRITE = 0x00000001; + + [NativeTypeName("#define STGM_READWRITE 0x00000002L")] + public const int STGM_READWRITE = 0x00000002; +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows/Windows/um/objidlbase/IID.cs b/src/TerraFX.Interop.Windows/Windows/um/objidlbase/IID.cs new file mode 100644 index 00000000..4475b9f7 --- /dev/null +++ b/src/TerraFX.Interop.Windows/Windows/um/objidlbase/IID.cs @@ -0,0 +1,60 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/objidlbase.h in the Windows SDK for Windows 10.0.20348.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace TerraFX.Interop.Windows; + +internal static partial class IID +{ + public static ref readonly Guid IID_ISequentialStream + { + get + { + ReadOnlySpan data = new byte[] { + 0x30, 0x3A, 0x73, 0x0C, + 0x1C, 0x2A, + 0xCE, 0x11, + 0xAD, + 0xE5, + 0x00, + 0xAA, + 0x00, + 0x44, + 0x77, + 0x3D + }; + + Debug.Assert(data.Length == Unsafe.SizeOf()); + return ref Unsafe.As(ref MemoryMarshal.GetReference(data)); + } + } + + public static ref readonly Guid IID_IStream + { + get + { + ReadOnlySpan data = new byte[] { + 0x0C, 0x00, 0x00, 0x00, + 0x00, 0x00, + 0x00, 0x00, + 0xC0, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x46 + }; + + Debug.Assert(data.Length == Unsafe.SizeOf()); + return ref Unsafe.As(ref MemoryMarshal.GetReference(data)); + } + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows/Windows/um/objidlbase/IStream.cs b/src/TerraFX.Interop.Windows/Windows/um/objidlbase/IStream.cs index 9481b8aa..637adbfc 100644 --- a/src/TerraFX.Interop.Windows/Windows/um/objidlbase/IStream.cs +++ b/src/TerraFX.Interop.Windows/Windows/um/objidlbase/IStream.cs @@ -102,6 +102,13 @@ namespace TerraFX.Interop.Windows return ((delegate* unmanaged[Stdcall])(lpVtbl[11]))((IStream*)Unsafe.AsPointer(ref this), libOffset, cb, dwLockType); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(12)] + public HRESULT Stat(STATSTG* pstatstg, [NativeTypeName("DWORD")] uint grfStatFlag) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[12]))((IStream*)Unsafe.AsPointer(ref this), pstatstg, grfStatFlag); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(13)] public HRESULT Clone(IStream** ppstm) diff --git a/src/TerraFX.Interop.Windows/Windows/um/objidlbase/STATSTG.cs b/src/TerraFX.Interop.Windows/Windows/um/objidlbase/STATSTG.cs new file mode 100644 index 00000000..1f843abb --- /dev/null +++ b/src/TerraFX.Interop.Windows/Windows/um/objidlbase/STATSTG.cs @@ -0,0 +1,40 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/objidlbase.h in the Windows SDK for Windows 10.0.20348.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; + +namespace TerraFX.Interop.Windows; + +internal unsafe partial struct STATSTG +{ + [NativeTypeName("LPOLESTR")] + public ushort* pwcsName; + + [NativeTypeName("DWORD")] + public uint type; + + public ULARGE_INTEGER cbSize; + + public FILETIME mtime; + + public FILETIME ctime; + + public FILETIME atime; + + [NativeTypeName("DWORD")] + public uint grfMode; + + [NativeTypeName("DWORD")] + public uint grfLocksSupported; + + [NativeTypeName("CLSID")] + public Guid clsid; + + [NativeTypeName("DWORD")] + public uint grfStateBits; + + [NativeTypeName("DWORD")] + public uint reserved; +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows/Windows/um/objidlbase/STGTY.cs b/src/TerraFX.Interop.Windows/Windows/um/objidlbase/STGTY.cs new file mode 100644 index 00000000..7fd183ca --- /dev/null +++ b/src/TerraFX.Interop.Windows/Windows/um/objidlbase/STGTY.cs @@ -0,0 +1,17 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/objidlbase.h in the Windows SDK for Windows 10.0.20348.0 +// Original source is Copyright © Microsoft. All rights reserved. + +namespace TerraFX.Interop.Windows; + +internal enum STGTY +{ + STGTY_STORAGE = 1, + + STGTY_STREAM = 2, + + STGTY_LOCKBYTES = 3, + + STGTY_PROPERTY = 4, +} \ No newline at end of file diff --git a/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs b/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs index 003cbbb3..3048450d 100644 --- a/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs +++ b/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs @@ -1,5 +1,6 @@ using System; using System.Diagnostics.Contracts; +using System.IO; using ComputeSharp.__Internals; using ComputeSharp.Resources; @@ -301,6 +302,30 @@ public static class GraphicsDeviceExtensions }; } + /// + /// Loads an image from a specific file into a target instance. + /// + /// The type of items to store in the texture. + /// The target instance. + /// The type of filepath to use. + /// The filename of the image file to load and decode into the texture. + [Pure] + public static void Load(this UploadTexture2D texture, Type inputType, string filename) + where T : unmanaged + { + switch (inputType) + { + case var _ when inputType == typeof(string): + texture.Load(filename); + break; + case var _ when inputType == typeof(ReadOnlySpan): + texture.Load(filename); + break; + default: + throw new ArgumentException($"Invalid input type: {inputType}", nameof(inputType)); + } + } + /// /// Loads a new readonly 2D texture with the contents of the specified file. /// @@ -335,14 +360,14 @@ public static class GraphicsDeviceExtensions } /// - /// Loads a new readonly 2D texture with the contents of the specified file. + /// Loads 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 type of texture to allocate. /// The buffer with the image data to load and decode into the texture. - /// A instance with the contents of the specified file. + /// A instance with the contents of the specified buffer. [Pure] public static Texture2D LoadTexture2D(this GraphicsDevice device, Type type, byte[] buffer) where T : unmanaged, IUnorm @@ -356,6 +381,28 @@ public static class GraphicsDeviceExtensions }; } + /// + /// Loads a new readonly 2D texture with the contents of the specified stream. + /// + /// 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 type of texture to allocate. + /// The stream with the image data to load and decode into the texture. + /// A instance with the contents of the specified stream. + [Pure] + public static Texture2D LoadTexture2D(this GraphicsDevice device, Type type, Stream stream) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + return type switch + { + _ when type == typeof(ReadOnlyTexture2D<,>) => device.LoadReadOnlyTexture2D(stream), + _ when type == typeof(ReadWriteTexture2D<,>) => device.LoadReadWriteTexture2D(stream), + _ => throw new ArgumentException($"Invalid type: {type}", nameof(type)) + }; + } + /// /// Saves a texture to a specified file. /// diff --git a/tests/ComputeSharp.Tests/ImagingTests.cs b/tests/ComputeSharp.Tests/ImagingTests.cs index dc42f0a7..216083bc 100644 --- a/tests/ComputeSharp.Tests/ImagingTests.cs +++ b/tests/ComputeSharp.Tests/ImagingTests.cs @@ -27,7 +27,7 @@ public class ImagingTests [Resource(typeof(ReadWriteTexture2D<,>))] [Data(typeof(string))] [Data(typeof(ReadOnlySpan))] - public void LoadAsRgba32FromFile(Device device, Type textureType, Type inputType) + public void LoadAsRgba32_FromFile(Device device, Type textureType, Type inputType) { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg"); @@ -39,13 +39,136 @@ public class ImagingTests TolerantImageComparer.AssertEqual(original, loaded, 0.0000032f); } + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture2D<>))] + [Resource(typeof(ReadWriteTexture2D<>))] + [Data(typeof(string))] + [Data(typeof(ReadOnlySpan))] + public void LoadAsRgba32_FromFile_WithUploadTexture(Device device, Type textureType, Type inputType) + { + string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg"); + + IImageInfo imageInfo = Image.Identify(path); + + using Texture2D texture = device.Get().AllocateTexture2D(textureType, imageInfo.Width, imageInfo.Height); + using UploadTexture2D upload = device.Get().AllocateUploadTexture2D(imageInfo.Width, imageInfo.Height); + + upload.Load(inputType, path); + upload.CopyTo(texture); + + using Image loaded = texture.ToImage(); + using Image original = Image.Load(path); + + TolerantImageComparer.AssertEqual(original, loaded, 0.0000032f); + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture2D<,>))] + [Resource(typeof(ReadWriteTexture2D<,>))] + public void LoadAsRgba32_FromBuffer(Device device, Type textureType) + { + string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg"); + + byte[] buffer = File.ReadAllBytes(path); + + using Texture2D texture = device.Get().LoadTexture2D(textureType, buffer); + + using Image loaded = texture.ToImage(); + using Image original = Image.Load(path); + + TolerantImageComparer.AssertEqual(original, loaded, 0.0000032f); + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture2D<>))] + [Resource(typeof(ReadWriteTexture2D<>))] + public void LoadAsRgba32_FromBuffer_WithUploadTexture(Device device, Type textureType) + { + string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg"); + + IImageInfo imageInfo = Image.Identify(path); + + using Texture2D texture = device.Get().AllocateTexture2D(textureType, imageInfo.Width, imageInfo.Height); + using UploadTexture2D upload = device.Get().AllocateUploadTexture2D(imageInfo.Width, imageInfo.Height); + + byte[] buffer = File.ReadAllBytes(path); + + upload.Load(buffer); + upload.CopyTo(texture); + + using Image loaded = texture.ToImage(); + using Image original = Image.Load(path); + + TolerantImageComparer.AssertEqual(original, loaded, 0.0000032f); + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture2D<,>))] + [Resource(typeof(ReadWriteTexture2D<,>))] + public void LoadAsRgba32_FromStream(Device device, Type textureType) + { + string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg"); + + using Stream stream = File.OpenRead(path); + + using Texture2D texture = device.Get().LoadTexture2D(textureType, stream); + + using Image loaded = texture.ToImage(); + using Image original = Image.Load(path); + + TolerantImageComparer.AssertEqual(original, loaded, 0.0000032f); + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture2D<>))] + [Resource(typeof(ReadWriteTexture2D<>))] + public void LoadAsRgba32_FromStream_WithUploadTexture(Device device, Type textureType) + { + string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg"); + + IImageInfo imageInfo = Image.Identify(path); + + using Texture2D texture = device.Get().AllocateTexture2D(textureType, imageInfo.Width, imageInfo.Height); + using UploadTexture2D upload = device.Get().AllocateUploadTexture2D(imageInfo.Width, imageInfo.Height); + + using Stream stream = File.OpenRead(path); + + upload.Load(stream); + upload.CopyTo(texture); + + using Image loaded = texture.ToImage(); + using Image original = Image.Load(path); + + TolerantImageComparer.AssertEqual(original, loaded, 0.0000032f); + } + + [CombinatorialTestMethod] + [AllDevices] + [Data(3840, 2562)] + [Data(3839, 2560)] + [Data(3844, 2564)] + [ExpectedException(typeof(ArgumentException))] + public void LoadAsRgba32_FromStream_WithUploadTexture_SizeMismatch(Device device, int width, int height) + { + string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg"); + + using UploadTexture2D upload = device.Get().AllocateUploadTexture2D(width, height); + + upload.Load(path); + } + [CombinatorialTestMethod] [AllDevices] [Resource(typeof(ReadOnlyTexture2D<,>))] [Resource(typeof(ReadWriteTexture2D<,>))] [Data(typeof(string))] [Data(typeof(ReadOnlySpan))] - public void LoadAsBgra32FromFile(Device device, Type textureType, Type inputType) + public void LoadAsBgra32_FromFile(Device device, Type textureType, Type inputType) { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg"); @@ -57,13 +180,31 @@ public class ImagingTests TolerantImageComparer.AssertEqual(original, loaded, 0.00000132f); } + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture2D<,>))] + [Resource(typeof(ReadWriteTexture2D<,>))] + public void LoadAsBgra32_FromStream(Device device, Type textureType) + { + string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg"); + + using Stream stream = File.OpenRead(path); + + using Texture2D texture = device.Get().LoadTexture2D(textureType, stream); + + using Image loaded = texture.ToImage(); + using Image original = Image.Load(path); + + TolerantImageComparer.AssertEqual(original, loaded, 0.00000132f); + } + [CombinatorialTestMethod] [AllDevices] [Resource(typeof(ReadOnlyTexture2D<,>))] [Resource(typeof(ReadWriteTexture2D<,>))] [Data(typeof(string))] [Data(typeof(ReadOnlySpan))] - public void LoadAsBgra32FromFileWithSameFormat(Device device, Type textureType, Type inputType) + public void LoadAsBgra32_FromFile_WithSameFormat(Device device, Type textureType, Type inputType) { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets", "CityAfter1024x1024Sampling.png"); @@ -75,13 +216,31 @@ public class ImagingTests TolerantImageComparer.AssertEqual(original, loaded, 0.00000132f); } + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture2D<,>))] + [Resource(typeof(ReadWriteTexture2D<,>))] + public void LoadAsBgra32_FromStream_WithSameFormat(Device device, Type textureType) + { + string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets", "CityAfter1024x1024Sampling.png"); + + using Stream stream = File.OpenRead(path); + + using Texture2D texture = device.Get().LoadTexture2D(textureType, stream); + + using Image loaded = texture.ToImage(); + using Image original = Image.Load(path); + + TolerantImageComparer.AssertEqual(original, loaded, 0.00000132f); + } + [CombinatorialTestMethod] [AllDevices] [Resource(typeof(ReadOnlyTexture2D<,>))] [Resource(typeof(ReadWriteTexture2D<,>))] [Data(typeof(string))] [Data(typeof(ReadOnlySpan))] - public void LoadAsR8FromFile(Device device, Type textureType, Type inputType) + public void LoadAsR8_FromFile(Device device, Type textureType, Type inputType) { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg"); @@ -97,18 +256,18 @@ public class ImagingTests [AllDevices] [Resource(typeof(ReadOnlyTexture2D<,>))] [Resource(typeof(ReadWriteTexture2D<,>))] - public void LoadAsRgba32FromBuffer(Device device, Type textureType) + public void LoadAsR8_FromFile(Device device, Type textureType) { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg"); - byte[] buffer = File.ReadAllBytes(path); + using Stream stream = File.OpenRead(path); - using Texture2D texture = device.Get().LoadTexture2D(textureType, buffer); + using Texture2D texture = device.Get().LoadTexture2D(textureType, stream); - using Image loaded = texture.ToImage(); - using Image original = Image.Load(path); + using Image loaded = texture.ToImage(); + using Image original = Image.Load(path); - TolerantImageComparer.AssertEqual(original, loaded, 0.0000032f); + TolerantImageComparer.AssertEqual(original, loaded, 0.000039f); } [CombinatorialTestMethod] @@ -121,13 +280,23 @@ public class ImagingTests using Texture2D texture = device.Get().LoadTexture2D(textureType, typeof(string), null!); } + [CombinatorialTestMethod] + [Device(Device.Warp)] + [Resource(typeof(ReadOnlyTexture2D<,>))] + [Resource(typeof(ReadWriteTexture2D<,>))] + [ExpectedException(typeof(ArgumentNullException))] + public void LoadAsRgba32_WithNullStream(Device device, Type textureType) + { + using Texture2D texture = device.Get().LoadTexture2D(textureType, (Stream)null!); + } + [CombinatorialTestMethod] [AllDevices] [Resource(typeof(ReadOnlyTexture2D<,>))] [Resource(typeof(ReadWriteTexture2D<,>))] [Data(typeof(string))] [Data(typeof(ReadOnlySpan))] - public void SaveRgba32AsJpeg(Device device, Type textureType, Type inputType) + public void SaveRgba32AsJpeg_ToFile(Device device, Type textureType, Type inputType) { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"); string expectedPath = Path.Combine(path, "city.jpg"); @@ -140,13 +309,33 @@ public class ImagingTests TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.00001023f); } + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture2D<,>))] + [Resource(typeof(ReadWriteTexture2D<,>))] + public void SaveRgba32AsJpeg_ToStream(Device device, Type textureType) + { + string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"); + string expectedPath = Path.Combine(path, "city.jpg"); + string actualPath = Path.Combine(path, "city_rgba32_saved.jpg"); + + using Texture2D texture = device.Get().LoadTexture2D(textureType, typeof(string), expectedPath); + + using (Stream stream = File.OpenWrite(actualPath)) + { + texture.Save(stream, ImageFormat.Jpeg); + } + + TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.00001023f); + } + [CombinatorialTestMethod] [AllDevices] [Resource(typeof(ReadOnlyTexture2D<,>))] [Resource(typeof(ReadWriteTexture2D<,>))] [Data(typeof(string))] [Data(typeof(ReadOnlySpan))] - public void SaveRgba32AsJpeg_WithReadBackTexture(Device device, Type textureType, Type inputType) + public void SaveRgba32AsJpeg_ToFile_WithReadBackTexture(Device device, Type textureType, Type inputType) { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"); string expectedPath = Path.Combine(path, "city.jpg"); @@ -162,12 +351,35 @@ public class ImagingTests TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.00001023f); } + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture2D<,>))] + [Resource(typeof(ReadWriteTexture2D<,>))] + public void SaveRgba32AsJpeg_ToStream_WithReadBackTexture(Device device, Type textureType) + { + string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"); + string expectedPath = Path.Combine(path, "city.jpg"); + string actualPath = Path.Combine(path, "city_rgba32_saved.jpg"); + + using Texture2D texture = device.Get().LoadTexture2D(textureType, typeof(string), expectedPath); + using ReadBackTexture2D readback = device.Get().AllocateReadBackTexture2D(texture.Width, texture.Height); + + texture.CopyTo(readback); + + using (Stream stream = File.OpenWrite(actualPath)) + { + readback.Save(stream, ImageFormat.Jpeg); + } + + TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.00001023f); + } + [CombinatorialTestMethod] [Device(Device.Warp)] [Resource(typeof(ReadOnlyTexture2D<,>))] [Resource(typeof(ReadWriteTexture2D<,>))] [ExpectedException(typeof(ArgumentNullException))] - public void SaveRgba32AsJpeg_WithReadBackTexture_WithNullPath(Device device, Type textureType) + public void SaveRgba32AsJpeg_ToFile_WithReadBackTexture_WithNullPath(Device device, Type textureType) { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg"); @@ -179,13 +391,30 @@ public class ImagingTests readback.Save(typeof(string), null!); } + [CombinatorialTestMethod] + [Device(Device.Warp)] + [Resource(typeof(ReadOnlyTexture2D<,>))] + [Resource(typeof(ReadWriteTexture2D<,>))] + [ExpectedException(typeof(ArgumentNullException))] + public void SaveRgba32AsJpeg_ToStream_WithReadBackTexture_WithNullStream(Device device, Type textureType) + { + string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg"); + + using Texture2D texture = device.Get().LoadTexture2D(textureType, typeof(string), path); + using ReadBackTexture2D readback = device.Get().AllocateReadBackTexture2D(texture.Width, texture.Height); + + texture.CopyTo(readback); + + readback.Save(null!, ImageFormat.Jpeg); + } + [CombinatorialTestMethod] [AllDevices] [Resource(typeof(ReadOnlyTexture2D<,>))] [Resource(typeof(ReadWriteTexture2D<,>))] [Data(typeof(string))] [Data(typeof(ReadOnlySpan))] - public void SaveBgra32AsJpeg(Device device, Type textureType, Type inputType) + public void SaveBgra32AsJpeg_ToFile(Device device, Type textureType, Type inputType) { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"); string expectedPath = Path.Combine(path, "city.jpg"); @@ -204,7 +433,7 @@ public class ImagingTests [Resource(typeof(ReadWriteTexture2D<,>))] [Data(typeof(string))] [Data(typeof(ReadOnlySpan))] - public void SaveR8AsJpeg(Device device, Type textureType, Type inputType) + public void SaveR8AsJpeg_ToFile(Device device, Type textureType, Type inputType) { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"); string sourcePath = Path.Combine(path, "city.jpg"); @@ -227,7 +456,7 @@ public class ImagingTests [Resource(typeof(ReadOnlyTexture2D<,>))] [Resource(typeof(ReadWriteTexture2D<,>))] [ExpectedException(typeof(ArgumentNullException))] - public void SaveRgba32AsJpeg_WithNullPath(Device device, Type textureType) + public void SaveRgba32AsJpeg_ToFile_WithNullPath(Device device, Type textureType) { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg");