diff --git a/README.md b/README.md index db63fbfa..646df712 100644 --- a/README.md +++ b/README.md @@ -252,7 +252,7 @@ With the compute shader being like this: [AutoConstructor] public readonly partial struct GrayscaleEffect : IComputeShader { - public readonly IReadWriteTexture2D texture; + public readonly IReadWriteNormalizedTexture2D texture; // Other captured resources or values here... diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs index e8d3318b..5a4847bc 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs @@ -315,7 +315,7 @@ public sealed partial class HlslBokehBlurProcessor [AutoConstructor] internal partial struct VerticalConvolutionProcessor : IComputeShader { - public IReadWriteTexture2D source; + public IReadWriteNormalizedTexture2D source; public ReadWriteTexture2D reals; public ReadWriteTexture2D imaginaries; public ReadOnlyBuffer kernel; @@ -392,7 +392,7 @@ public sealed partial class HlslBokehBlurProcessor [AutoConstructor] internal readonly partial struct GammaHighlightProcessor : IComputeShader { - public readonly IReadWriteTexture2D source; + public readonly IReadWriteNormalizedTexture2D source; /// public void Execute() @@ -417,7 +417,7 @@ public sealed partial class HlslBokehBlurProcessor internal readonly partial struct InverseGammaHighlightProcessor : IComputeShader { public readonly ReadWriteTexture2D source; - public readonly IReadWriteTexture2D target; + public readonly IReadWriteNormalizedTexture2D target; /// public void Execute() diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs index 0079ac2f..06832d3a 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs @@ -121,8 +121,8 @@ public sealed partial class HlslGaussianBlurProcessor [AutoConstructor] internal readonly partial struct VerticalConvolutionProcessor : IComputeShader { - public readonly IReadWriteTexture2D source; - public readonly IReadWriteTexture2D target; + public readonly IReadWriteNormalizedTexture2D source; + public readonly IReadWriteNormalizedTexture2D target; public readonly ReadOnlyBuffer kernel; /// @@ -153,8 +153,8 @@ public sealed partial class HlslGaussianBlurProcessor [AutoConstructor] internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader { - public readonly IReadWriteTexture2D source; - public readonly IReadWriteTexture2D target; + public readonly IReadWriteNormalizedTexture2D source; + public readonly IReadWriteNormalizedTexture2D target; public readonly ReadOnlyBuffer kernel; /// diff --git a/samples/ComputeSharp.SwapChain.Core.Shared/Shaders/Runners/ContouredLayersRunner.cs b/samples/ComputeSharp.SwapChain.Core.Shared/Shaders/Runners/ContouredLayersRunner.cs index 74480aa4..09804b6b 100644 --- a/samples/ComputeSharp.SwapChain.Core.Shared/Shaders/Runners/ContouredLayersRunner.cs +++ b/samples/ComputeSharp.SwapChain.Core.Shared/Shaders/Runners/ContouredLayersRunner.cs @@ -23,7 +23,7 @@ public sealed class ContouredLayersRunner : IShaderRunner private ReadOnlyTexture2D? texture; /// - public bool TryExecute(IReadWriteTexture2D texture, TimeSpan timespan, object? parameter) + public bool TryExecute(IReadWriteNormalizedTexture2D texture, TimeSpan timespan, object? parameter) { if (this.texture is null || this.texture.GraphicsDevice != texture.GraphicsDevice) diff --git a/samples/ComputeSharp.SwapChain.Shaders.Shared/ContouredLayers.cs b/samples/ComputeSharp.SwapChain.Shaders.Shared/ContouredLayers.cs index 90b878f8..7fa460ef 100644 --- a/samples/ComputeSharp.SwapChain.Shaders.Shared/ContouredLayers.cs +++ b/samples/ComputeSharp.SwapChain.Shaders.Shared/ContouredLayers.cs @@ -19,7 +19,7 @@ internal readonly partial struct ContouredLayers : IPixelShader /// /// The background texture to sample. /// - public readonly IReadOnlyTexture2D texture; + public readonly IReadOnlyNormalizedTexture2D texture; // float3 to float hash. private static float Hash21(float2 p) diff --git a/samples/ComputeSharp.SwapChain/Program.cs b/samples/ComputeSharp.SwapChain/Program.cs index 3f775af6..0601b382 100644 --- a/samples/ComputeSharp.SwapChain/Program.cs +++ b/samples/ComputeSharp.SwapChain/Program.cs @@ -12,7 +12,7 @@ class Program /// /// A texture for \Textures\RustyMetal.png. /// - private static readonly IReadOnlyTexture2D RustyMetal = LoadTexture(); + private static readonly IReadOnlyNormalizedTexture2D RustyMetal = LoadTexture(); /// /// The mapping of available samples to choose from. diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs index 05adcd0d..a3d99549 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs @@ -24,12 +24,16 @@ internal static class HlslKnownMembers [$"ComputeSharp.ReadWriteTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", [$"ComputeSharp.IReadWriteTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", + [$"ComputeSharp.IReadOnlyNormalizedTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", + [$"ComputeSharp.IReadWriteNormalizedTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", [$"ComputeSharp.ReadOnlyTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", [$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", [$"ComputeSharp.ReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", [$"ComputeSharp.ReadWriteTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", [$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", - [$"ComputeSharp.IReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3" + [$"ComputeSharp.IReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", + [$"ComputeSharp.IReadOnlyNormalizedTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", + [$"ComputeSharp.IReadWriteNormalizedTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3" }; /// @@ -41,10 +45,14 @@ internal static class HlslKnownMembers [$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(Float2).FullName}]"] = null, [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2", [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(Float2).FullName}]"] = null, + [$"ComputeSharp.IReadOnlyNormalizedTexture2D`1.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2", + [$"ComputeSharp.IReadOnlyNormalizedTexture2D`1.this[{typeof(Float2).FullName}]"] = null, [$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3", [$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(Float3).FullName}]"] = null, [$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3", - [$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(Float3).FullName}]"] = null + [$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(Float3).FullName}]"] = null, + [$"ComputeSharp.IReadOnlyNormalizedTexture3D`1.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3", + [$"ComputeSharp.IReadOnlyNormalizedTexture3D`1.this[{typeof(Float3).FullName}]"] = null }; /// @@ -63,11 +71,16 @@ internal static class HlslKnownMembers ["ComputeSharp.IReadOnlyTexture3D`1.Width"] = (3, 0), ["ComputeSharp.IReadOnlyTexture3D`1.Height"] = (3, 1), ["ComputeSharp.IReadOnlyTexture3D`1.Depth"] = (3, 2), - ["ComputeSharp.IReadWriteTexture2D`1.Width"] = (2, 0), - ["ComputeSharp.IReadWriteTexture2D`1.Height"] = (2, 1), - ["ComputeSharp.IReadWriteTexture3D`1.Width"] = (3, 0), - ["ComputeSharp.IReadWriteTexture3D`1.Height"] = (3, 1), - ["ComputeSharp.IReadWriteTexture3D`1.Depth"] = (3, 2) + ["ComputeSharp.IReadOnlyNormalizedTexture2D`1.Width"] = (2, 0), + ["ComputeSharp.IReadOnlyNormalizedTexture2D`1.Height"] = (2, 1), + ["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Width"] = (3, 0), + ["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Height"] = (3, 1), + ["ComputeSharp.IReadOnlyNormalizedTexture3D`1.Depth"] = (3, 2), + ["ComputeSharp.IReadWriteNormalizedTexture2D`1.Width"] = (2, 0), + ["ComputeSharp.IReadWriteNormalizedTexture2D`1.Height"] = (2, 1), + ["ComputeSharp.IReadWriteNormalizedTexture3D`1.Width"] = (3, 0), + ["ComputeSharp.IReadWriteNormalizedTexture3D`1.Height"] = (3, 1), + ["ComputeSharp.IReadWriteNormalizedTexture3D`1.Depth"] = (3, 2) }; /// diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index 3a5de54c..2625d3f7 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -143,6 +143,8 @@ internal static class HlslKnownTypes "ComputeSharp.ReadOnlyTexture3D`2" or "ComputeSharp.IReadOnlyTexture2D`1" or "ComputeSharp.IReadOnlyTexture3D`1" => true, + "ComputeSharp.IReadOnlyNormalizedTexture2D`1" or + "ComputeSharp.IReadOnlyNormalizedTexture3D`1" => true, _ => false, }; } @@ -161,8 +163,8 @@ internal static class HlslKnownTypes "ComputeSharp.ReadWriteTexture2D`2" or "ComputeSharp.ReadWriteTexture3D`1" or "ComputeSharp.ReadWriteTexture3D`2" or - "ComputeSharp.IReadWriteTexture2D`1" or - "ComputeSharp.IReadWriteTexture3D`1" => true, + "ComputeSharp.IReadWriteNormalizedTexture2D`1" or + "ComputeSharp.IReadWriteNormalizedTexture3D`1" => true, _ => false, }; } @@ -188,9 +190,11 @@ internal static class HlslKnownTypes "ComputeSharp.ReadWriteTexture3D`1" or "ComputeSharp.ReadWriteTexture3D`2" or "ComputeSharp.IReadOnlyTexture2D`1" or - "ComputeSharp.IReadWriteTexture2D`1" or "ComputeSharp.IReadOnlyTexture3D`1" or - "ComputeSharp.IReadWriteTexture3D`1" => true, + "ComputeSharp.IReadOnlyNormalizedTexture2D`1" or + "ComputeSharp.IReadWriteNormalizedTexture2D`1" or + "ComputeSharp.IReadOnlyNormalizedTexture3D`1" or + "ComputeSharp.IReadWriteNormalizedTexture3D`1" => true, _ => false, }; } @@ -294,10 +298,12 @@ internal static class HlslKnownTypes "ComputeSharp.ReadOnlyTexture3D`2" => $"Texture3D", "ComputeSharp.ReadWriteTexture3D`1" => $"RWTexture3D<{mappedElementType}>", "ComputeSharp.ReadWriteTexture3D`2" => $"RWTexture3D", - "ComputeSharp.IReadOnlyTexture2D`1" => $"Texture2D", - "ComputeSharp.IReadWriteTexture2D`1" => $"RWTexture2D", - "ComputeSharp.IReadOnlyTexture3D`1" => $"Texture3D", - "ComputeSharp.IReadWriteTexture3D`1" => $"RWTexture3D", + "ComputeSharp.IReadOnlyTexture2D`1" => $"Texture2D<{mappedElementType}>", + "ComputeSharp.IReadOnlyTexture3D`1" => $"Texture3D<{mappedElementType}>", + "ComputeSharp.IReadOnlyNormalizedTexture2D`1" => $"Texture2D", + "ComputeSharp.IReadWriteNormalizedTexture2D`1" => $"RWTexture2D", + "ComputeSharp.IReadOnlyNormalizedTexture3D`1" => $"Texture3D", + "ComputeSharp.IReadWriteNormalizedTexture3D`1" => $"RWTexture3D", _ => throw new ArgumentException() }; } diff --git a/src/ComputeSharp.UI/IShaderRunner.cs b/src/ComputeSharp.UI/IShaderRunner.cs index fbf5c96f..b6ebaf23 100644 --- a/src/ComputeSharp.UI/IShaderRunner.cs +++ b/src/ComputeSharp.UI/IShaderRunner.cs @@ -22,5 +22,5 @@ public interface IShaderRunner /// Any exceptions thrown by the runner will result in /// or to be raised. /// - bool TryExecute(IReadWriteTexture2D texture, TimeSpan timespan, object? parameter); + bool TryExecute(IReadWriteNormalizedTexture2D texture, TimeSpan timespan, object? parameter); } diff --git a/src/ComputeSharp.UI/ShaderRunner{T}.cs b/src/ComputeSharp.UI/ShaderRunner{T}.cs index 967e8713..cad093ef 100644 --- a/src/ComputeSharp.UI/ShaderRunner{T}.cs +++ b/src/ComputeSharp.UI/ShaderRunner{T}.cs @@ -57,7 +57,7 @@ public sealed class ShaderRunner : IShaderRunner } /// - public bool TryExecute(IReadWriteTexture2D texture, TimeSpan time, object? parameter) + public bool TryExecute(IReadWriteNormalizedTexture2D texture, TimeSpan time, object? parameter) { if (this.shaderFactory is Func shaderFactory) { diff --git a/src/ComputeSharp/Core/Dispatch/DispatchAxis.cs b/src/ComputeSharp/Core/Dispatch/DispatchAxis.cs index b31e9184..8dbe1294 100644 --- a/src/ComputeSharp/Core/Dispatch/DispatchAxis.cs +++ b/src/ComputeSharp/Core/Dispatch/DispatchAxis.cs @@ -35,9 +35,9 @@ public enum DispatchAxis /// Indicates a shader dispatch along the X and Y axes. /// /// - /// This applies to using , , - /// , , - /// or . + /// This applies to using , , + /// , , + /// or . /// XY, diff --git a/src/ComputeSharp/Core/Imaging/Interfaces/IPixel{T,TPixel}.cs b/src/ComputeSharp/Core/Imaging/Interfaces/IPixel{T,TPixel}.cs index 4c32dba5..4a047881 100644 --- a/src/ComputeSharp/Core/Imaging/Interfaces/IPixel{T,TPixel}.cs +++ b/src/ComputeSharp/Core/Imaging/Interfaces/IPixel{T,TPixel}.cs @@ -15,8 +15,8 @@ public interface IPixel /// The representation for the current value. /// /// This method is primarily meant to be used to support - /// - /// and . + /// + /// and . /// TPixel ToPixel(); } diff --git a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs index 32465be7..c097058a 100644 --- a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs +++ b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs @@ -75,7 +75,7 @@ public static partial class GraphicsDeviceExtensions /// The type of pixels being processed by the shader. /// The to use to run the shader. /// The target texture to apply the pixel shader to. - public static void ForEach(this GraphicsDevice device, IReadWriteTexture2D texture) + public static void ForEach(this GraphicsDevice device, IReadWriteNormalizedTexture2D texture) where T : struct, IPixelShader where TPixel : unmanaged { @@ -90,7 +90,7 @@ public static partial class GraphicsDeviceExtensions /// The to use to run the shader. /// The target texture to apply the pixel shader to. /// The input instance representing the pixel shader to run. - public static void ForEach(this GraphicsDevice device, IReadWriteTexture2D texture, in T shader) + public static void ForEach(this GraphicsDevice device, IReadWriteNormalizedTexture2D texture, in T shader) where T : struct, IPixelShader where TPixel : unmanaged { diff --git a/src/ComputeSharp/Graphics/Extensions/ReadWriteTexture2DExtensions.cs b/src/ComputeSharp/Graphics/Extensions/ReadWriteTexture2DExtensions.cs new file mode 100644 index 00000000..7b9f48dc --- /dev/null +++ b/src/ComputeSharp/Graphics/Extensions/ReadWriteTexture2DExtensions.cs @@ -0,0 +1,133 @@ +using System; + +namespace ComputeSharp; + +/// +/// A that contains extension methods for the and types. +/// +public static class ReadWriteTexture2DExtensions +{ + /// + /// Retrieves a wrapping instance for the input resource. + /// + /// The input instance to create a wrapper for. + /// An instance wrapping the current resource. + /// + /// The returned instance can be used in a shader to enable texture sampling. + /// + /// This is an advanced API that can only be used after the current instance has been transitioned to be in a readonly state. To do so, + /// use , + /// and specify . After that, this method can be used to get a readonly wrapper for + /// the current texture to use in a shader. This instance should not be cached or reused, but just passed directly to a shader + /// being dispatched through that same , as it will not work if the texture changes state later on. + /// Before the end of that list of operations, the texture also needs to be transitioned back to writeable state, using the same + /// API as before but specifying . Failing to do so results in undefined behavior. + /// + /// + /// Thrown if the current instance or its associated device are disposed. + /// Thrown if the current instance is not in a readonly state. + public static IReadOnlyTexture2D AsReadOnly(this ReadWriteTexture2D texture) + { + return texture.AsReadOnly(); + } + + /// + /// Retrieves a wrapping instance for the input resource. + /// + /// The input instance to create a wrapper for. + /// An instance wrapping the current resource. + /// + /// The returned instance can be used in a shader to enable texture sampling. + /// + /// This is an advanced API that can only be used after the current instance has been transitioned to be in a readonly state. To do so, + /// use , + /// and specify . After that, this method can be used to get a readonly wrapper for + /// the current texture to use in a shader. This instance should not be cached or reused, but just passed directly to a shader + /// being dispatched through that same , as it will not work if the texture changes state later on. + /// Before the end of that list of operations, the texture also needs to be transitioned back to writeable state, using the same + /// API as before but specifying . Failing to do so results in undefined behavior. + /// + /// + /// Thrown if the current instance or its associated device are disposed. + /// Thrown if the current instance is not in a readonly state. + public static IReadOnlyTexture2D AsReadOnly(this ReadWriteTexture2D texture) + { + return texture.AsReadOnly(); + } + + /// + /// Retrieves a wrapping instance for the input resource. + /// + /// The input instance to create a wrapper for. + /// An instance wrapping the current resource. + /// + /// The returned instance can be used in a shader to enable texture sampling. + /// + /// This is an advanced API that can only be used after the current instance has been transitioned to be in a readonly state. To do so, + /// use , + /// and specify . After that, this method can be used to get a readonly wrapper for + /// the current texture to use in a shader. This instance should not be cached or reused, but just passed directly to a shader + /// being dispatched through that same , as it will not work if the texture changes state later on. + /// Before the end of that list of operations, the texture also needs to be transitioned back to writeable state, using the same + /// API as before but specifying . Failing to do so results in undefined behavior. + /// + /// + /// Thrown if the current instance or its associated device are disposed. + /// Thrown if the current instance is not in a readonly state. + public static IReadOnlyTexture2D AsReadOnly(this ReadWriteTexture2D texture) + { + return texture.AsReadOnly(); + } + + /// + /// Retrieves a wrapping instance for the input resource. + /// + /// The input instance to create a wrapper for. + /// An instance wrapping the current resource. + /// + /// The returned instance can be used in a shader to enable texture sampling. + /// + /// This is an advanced API that can only be used after the current instance has been transitioned to be in a readonly state. To do so, + /// use , + /// and specify . After that, this method can be used to get a readonly wrapper for + /// the current texture to use in a shader. This instance should not be cached or reused, but just passed directly to a shader + /// being dispatched through that same , as it will not work if the texture changes state later on. + /// Before the end of that list of operations, the texture also needs to be transitioned back to writeable state, using the same + /// API as before but specifying . Failing to do so results in undefined behavior. + /// + /// + /// Thrown if the current instance or its associated device are disposed. + /// Thrown if the current instance is not in a readonly state. + public static IReadOnlyTexture2D AsReadOnly(this ReadWriteTexture2D texture) + { + return texture.AsReadOnly(); + } + + /// + /// Retrieves a wrapping instance for the input resource. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The input instance to create a wrapper for. + /// An instance wrapping the current resource. + /// + /// The returned instance can be used in a shader to enable texture sampling. + /// + /// This is an advanced API that can only be used after the current instance has been transitioned to be in a readonly state. To do so, + /// use , + /// and specify . After that, this method can be used to get a readonly wrapper for + /// the current texture to use in a shader. This instance should not be cached or reused, but just passed directly to a shader + /// being dispatched through that same , as it will not work if the texture changes state later on. + /// Before the end of that list of operations, the texture also needs to be transitioned back to writeable state, using the same + /// API as before but specifying . Failing to do so results in undefined behavior. + /// + /// + /// Thrown if the current instance or its associated device are disposed. + /// Thrown if the current instance is not in a readonly state. + public static IReadOnlyNormalizedTexture2D AsReadOnly(this ReadWriteTexture2D texture) + where T : unmanaged, IPixel + where TPixel : unmanaged + { + return texture.AsReadOnly(); + } +} diff --git a/src/ComputeSharp/Graphics/Extensions/ReadWriteTexture3DExtensions.cs b/src/ComputeSharp/Graphics/Extensions/ReadWriteTexture3DExtensions.cs new file mode 100644 index 00000000..fd2f9657 --- /dev/null +++ b/src/ComputeSharp/Graphics/Extensions/ReadWriteTexture3DExtensions.cs @@ -0,0 +1,133 @@ +using System; + +namespace ComputeSharp; + +/// +/// A that contains extension methods for the and types. +/// +public static class ReadWriteTexture3DExtensions +{ + /// + /// Retrieves a wrapping instance for the input resource. + /// + /// The input instance to create a wrapper for. + /// An instance wrapping the current resource. + /// + /// The returned instance can be used in a shader to enable texture sampling. + /// + /// This is an advanced API that can only be used after the current instance has been transitioned to be in a readonly state. To do so, + /// use , + /// and specify . After that, this method can be used to get a readonly wrapper for + /// the current texture to use in a shader. This instance should not be cached or reused, but just passed directly to a shader + /// being dispatched through that same , as it will not work if the texture changes state later on. + /// Before the end of that list of operations, the texture also needs to be transitioned back to writeable state, using the same + /// API as before but specifying . Failing to do so results in undefined behavior. + /// + /// + /// Thrown if the current instance or its associated device are disposed. + /// Thrown if the current instance is not in a readonly state. + public static IReadOnlyTexture3D AsReadOnly(this ReadWriteTexture3D texture) + { + return texture.AsReadOnly(); + } + + /// + /// Retrieves a wrapping instance for the input resource. + /// + /// The input instance to create a wrapper for. + /// An instance wrapping the current resource. + /// + /// The returned instance can be used in a shader to enable texture sampling. + /// + /// This is an advanced API that can only be used after the current instance has been transitioned to be in a readonly state. To do so, + /// use , + /// and specify . After that, this method can be used to get a readonly wrapper for + /// the current texture to use in a shader. This instance should not be cached or reused, but just passed directly to a shader + /// being dispatched through that same , as it will not work if the texture changes state later on. + /// Before the end of that list of operations, the texture also needs to be transitioned back to writeable state, using the same + /// API as before but specifying . Failing to do so results in undefined behavior. + /// + /// + /// Thrown if the current instance or its associated device are disposed. + /// Thrown if the current instance is not in a readonly state. + public static IReadOnlyTexture3D AsReadOnly(this ReadWriteTexture3D texture) + { + return texture.AsReadOnly(); + } + + /// + /// Retrieves a wrapping instance for the input resource. + /// + /// The input instance to create a wrapper for. + /// An instance wrapping the current resource. + /// + /// The returned instance can be used in a shader to enable texture sampling. + /// + /// This is an advanced API that can only be used after the current instance has been transitioned to be in a readonly state. To do so, + /// use , + /// and specify . After that, this method can be used to get a readonly wrapper for + /// the current texture to use in a shader. This instance should not be cached or reused, but just passed directly to a shader + /// being dispatched through that same , as it will not work if the texture changes state later on. + /// Before the end of that list of operations, the texture also needs to be transitioned back to writeable state, using the same + /// API as before but specifying . Failing to do so results in undefined behavior. + /// + /// + /// Thrown if the current instance or its associated device are disposed. + /// Thrown if the current instance is not in a readonly state. + public static IReadOnlyTexture3D AsReadOnly(this ReadWriteTexture3D texture) + { + return texture.AsReadOnly(); + } + + /// + /// Retrieves a wrapping instance for the input resource. + /// + /// The input instance to create a wrapper for. + /// An instance wrapping the current resource. + /// + /// The returned instance can be used in a shader to enable texture sampling. + /// + /// This is an advanced API that can only be used after the current instance has been transitioned to be in a readonly state. To do so, + /// use , + /// and specify . After that, this method can be used to get a readonly wrapper for + /// the current texture to use in a shader. This instance should not be cached or reused, but just passed directly to a shader + /// being dispatched through that same , as it will not work if the texture changes state later on. + /// Before the end of that list of operations, the texture also needs to be transitioned back to writeable state, using the same + /// API as before but specifying . Failing to do so results in undefined behavior. + /// + /// + /// Thrown if the current instance or its associated device are disposed. + /// Thrown if the current instance is not in a readonly state. + public static IReadOnlyTexture3D AsReadOnly(this ReadWriteTexture3D texture) + { + return texture.AsReadOnly(); + } + + /// + /// Retrieves a wrapping instance for the input resource. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The input instance to create a wrapper for. + /// An instance wrapping the current resource. + /// + /// The returned instance can be used in a shader to enable texture sampling. + /// + /// This is an advanced API that can only be used after the current instance has been transitioned to be in a readonly state. To do so, + /// use , + /// and specify . After that, this method can be used to get a readonly wrapper for + /// the current texture to use in a shader. This instance should not be cached or reused, but just passed directly to a shader + /// being dispatched through that same , as it will not work if the texture changes state later on. + /// Before the end of that list of operations, the texture also needs to be transitioned back to writeable state, using the same + /// API as before but specifying . Failing to do so results in undefined behavior. + /// + /// + /// Thrown if the current instance or its associated device are disposed. + /// Thrown if the current instance is not in a readonly state. + public static IReadOnlyNormalizedTexture3D AsReadOnly(this ReadWriteTexture3D texture) + where T : unmanaged, IPixel + where TPixel : unmanaged + { + return texture.AsReadOnly(); + } +} diff --git a/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs b/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs index bc80a50a..b1a846f6 100644 --- a/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs +++ b/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs @@ -111,12 +111,33 @@ public static class GraphicsResourceHelper /// /// Validates the given texture for usage with a specified device, and retrieves its GPU descriptor handle. /// - /// The type of normalized values stored in the input texture. - /// The input instance to check. + /// The type of values stored in the input texture. + /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the texture. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadOnlyTexture2D texture, GraphicsDevice device) + public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadOnlyTexture2D texture, GraphicsDevice device) + where T : unmanaged + { + if (texture is IGraphicsResource resource) + { + D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = resource.ValidateAndGetGpuDescriptorHandle(device); + + return *(ulong*)&d3D12GpuDescriptorHandle; + } + + return ThrowHelper.ThrowArgumentException("The input texture is not a valid instance"); + } + + /// + /// Validates the given texture for usage with a specified device, and retrieves its GPU descriptor handle. + /// + /// The type of normalized values stored in the input texture. + /// The input instance to check. + /// The target instance in use. + /// The GPU descriptor handle for the texture. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadOnlyNormalizedTexture2D texture, GraphicsDevice device) where TPixel : unmanaged { if (texture is IGraphicsResource resource) @@ -133,11 +154,11 @@ public static class GraphicsResourceHelper /// Validates the given texture for usage with a specified device, and retrieves its GPU descriptor handle. /// /// The type of normalized values stored in the input texture. - /// The input instance to check. + /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the texture. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadWriteTexture2D texture, GraphicsDevice device) + public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadWriteNormalizedTexture2D texture, GraphicsDevice device) where TPixel : unmanaged { if (texture is IGraphicsResource resource) @@ -191,12 +212,33 @@ public static class GraphicsResourceHelper /// /// Validates the given texture for usage with a specified device, and retrieves its GPU descriptor handle. /// - /// The type of normalized values stored in the input texture. - /// The input instance to check. + /// The type of values stored in the input texture. + /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the texture. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadOnlyTexture3D texture, GraphicsDevice device) + public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadOnlyTexture3D texture, GraphicsDevice device) + where T : unmanaged + { + if (texture is IGraphicsResource resource) + { + D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = resource.ValidateAndGetGpuDescriptorHandle(device); + + return *(ulong*)&d3D12GpuDescriptorHandle; + } + + return ThrowHelper.ThrowArgumentException("The input texture is not a valid instance"); + } + + /// + /// Validates the given texture for usage with a specified device, and retrieves its GPU descriptor handle. + /// + /// The type of normalized values stored in the input texture. + /// The input instance to check. + /// The target instance in use. + /// The GPU descriptor handle for the texture. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadOnlyNormalizedTexture3D texture, GraphicsDevice device) where TPixel : unmanaged { if (texture is IGraphicsResource resource) @@ -213,11 +255,11 @@ public static class GraphicsResourceHelper /// Validates the given texture for usage with a specified device, and retrieves its GPU descriptor handle. /// /// The type of normalized values stored in the input texture. - /// The input instance to check. + /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the texture. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadWriteTexture3D texture, GraphicsDevice device) + public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadWriteNormalizedTexture3D texture, GraphicsDevice device) where TPixel : unmanaged { if (texture is IGraphicsResource resource) diff --git a/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture2D{TPixel}.cs b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyNormalizedTexture2D{TPixel}.cs similarity index 96% rename from src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture2D{TPixel}.cs rename to src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyNormalizedTexture2D{TPixel}.cs index 39fa80da..89e461b7 100644 --- a/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture2D{TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyNormalizedTexture2D{TPixel}.cs @@ -5,7 +5,7 @@ /// This interface can only be used to wrap instances. /// /// The type of normalized pixels used on the GPU side. -public interface IReadOnlyTexture2D : IGraphicsResource +public interface IReadOnlyNormalizedTexture2D : IGraphicsResource where TPixel : unmanaged { /// diff --git a/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture3D{TPixel}.cs b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyNormalizedTexture3D{TPixel}.cs similarity index 97% rename from src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture3D{TPixel}.cs rename to src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyNormalizedTexture3D{TPixel}.cs index 625cd1f8..9faa16f0 100644 --- a/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture3D{TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyNormalizedTexture3D{TPixel}.cs @@ -5,7 +5,7 @@ /// This interface can only be used to wrap instances. /// /// The type of normalized pixels used on the GPU side. -public interface IReadOnlyTexture3D : IGraphicsResource +public interface IReadOnlyNormalizedTexture3D : IGraphicsResource where TPixel : unmanaged { /// diff --git a/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture2D{T}.cs new file mode 100644 index 00000000..578542f4 --- /dev/null +++ b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture2D{T}.cs @@ -0,0 +1,50 @@ +namespace ComputeSharp; + +/// +/// An interface representing a typed readonly 2D texture containing raw data stored on GPU memory. +/// This interface can only be used to wrap instances. +/// +/// The type of raw data used on the GPU side. +public interface IReadOnlyTexture2D : IGraphicsResource + where T : unmanaged +{ + /// + /// Gets the width of the current texture. + /// + int Width { get; } + + /// + /// Gets the height of the current texture. + /// + int Height { get; } + + /// + /// Gets a single value from the current readonly texture. + /// + /// The horizontal offset of the value to get. + /// The vertical offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + ref readonly T this[int x, int y] { get; } + + /// + /// Gets a single value from the current readonly texture. + /// + /// The coordinates of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + ref readonly T this[Int2 xy] { get; } + + /// + /// Gets a single value from the current readonly texture with linear sampling. + /// + /// The horizontal normalized offset of the value to get. + /// The vertical normalized offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + ref readonly T this[float u, float v] { get; } + + /// + /// Gets a single value from the current readonly texture with linear sampling. + /// + /// The normalized coordinates of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + ref readonly T this[Float2 uv] { get; } +} diff --git a/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture3D{T}.cs b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture3D{T}.cs new file mode 100644 index 00000000..822e9dea --- /dev/null +++ b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture3D{T}.cs @@ -0,0 +1,57 @@ +namespace ComputeSharp; + +/// +/// An interface representing a typed readonly 3D texture containing raw data stored on GPU memory. +/// This interface can only be used to wrap instances. +/// +/// The type of raw data used on the GPU side. +public interface IReadOnlyTexture3D : IGraphicsResource + where T : unmanaged +{ + /// + /// Gets the width of the current texture. + /// + int Width { get; } + + /// + /// Gets the height of the current texture. + /// + int Height { get; } + + /// + /// Gets the depth of the current texture. + /// + int Depth { get; } + + /// + /// Gets a single value from the current readonly texture. + /// + /// The horizontal offset of the value to get. + /// The vertical offset of the value to get. + /// The depthwise offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + ref readonly T this[int x, int y, int z] { get; } + + /// + /// Gets a single value from the current readonly texture. + /// + /// The coordinates of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + ref readonly T this[Int3 xyz] { get; } + + /// + /// Gets a single value from the current readonly texture with linear sampling. + /// + /// The horizontal normalized offset of the value to get. + /// The vertical normalized offset of the value to get. + /// The depthwise normalized offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + ref readonly T this[float u, float v, float w] { get; } + + /// + /// Gets a single value from the current readonly texture with linear sampling. + /// + /// The normalized coordinates of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + ref readonly T this[Float3 uvw] { get; } +} diff --git a/src/ComputeSharp/Graphics/Resources/Interfaces/IReadWriteTexture2D{TPixel}.cs b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadWriteNormalizedTexture2D{TPixel}.cs similarity index 95% rename from src/ComputeSharp/Graphics/Resources/Interfaces/IReadWriteTexture2D{TPixel}.cs rename to src/ComputeSharp/Graphics/Resources/Interfaces/IReadWriteNormalizedTexture2D{TPixel}.cs index e9938395..3c9255bd 100644 --- a/src/ComputeSharp/Graphics/Resources/Interfaces/IReadWriteTexture2D{TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadWriteNormalizedTexture2D{TPixel}.cs @@ -5,7 +5,7 @@ /// This interface can only be used to wrap instances. /// /// The type of normalized pixels used on the GPU side. -public interface IReadWriteTexture2D : IGraphicsResource +public interface IReadWriteNormalizedTexture2D : IGraphicsResource where TPixel : unmanaged { /// diff --git a/src/ComputeSharp/Graphics/Resources/Interfaces/IReadWriteTexture3D{TPixel}.cs b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadWriteNormalizedTexture3D{TPixel}.cs similarity index 95% rename from src/ComputeSharp/Graphics/Resources/Interfaces/IReadWriteTexture3D{TPixel}.cs rename to src/ComputeSharp/Graphics/Resources/Interfaces/IReadWriteNormalizedTexture3D{TPixel}.cs index 746fec0d..9ddb39ad 100644 --- a/src/ComputeSharp/Graphics/Resources/Interfaces/IReadWriteTexture3D{TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadWriteNormalizedTexture3D{TPixel}.cs @@ -5,7 +5,7 @@ /// This interface can only be used to wrap instances. /// /// The type of normalized pixels used on the GPU side. -public interface IReadWriteTexture3D : IGraphicsResource +public interface IReadWriteNormalizedTexture3D : IGraphicsResource where TPixel : unmanaged { /// diff --git a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs index 8ad822a1..befbf989 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs @@ -14,7 +14,7 @@ namespace ComputeSharp; /// The type of pixels used on the GPU side. [DebuggerTypeProxy(typeof(Texture2DDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] -public sealed class ReadOnlyTexture2D : Texture2D, IReadOnlyTexture2D +public sealed class ReadOnlyTexture2D : Texture2D, IReadOnlyNormalizedTexture2D where T : unmanaged, IPixel where TPixel : unmanaged { diff --git a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs index 7f0ca4bd..20982a21 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs @@ -14,7 +14,7 @@ namespace ComputeSharp; /// The type of pixels used on the GPU side. [DebuggerTypeProxy(typeof(Texture3DDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] -public sealed class ReadOnlyTexture3D : Texture3D, IReadOnlyTexture3D +public sealed class ReadOnlyTexture3D : Texture3D, IReadOnlyNormalizedTexture3D where T : unmanaged, IPixel where TPixel : unmanaged { diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs index 33924345..55cb5933 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.ReadOnly.cs @@ -21,25 +21,8 @@ partial class ReadWriteTexture2D /// private ReadOnly? readOnlyWrapper; - /// - /// Retrieves a wrapping instance for the current resource. - /// - /// An instance wrapping the current resource. - /// - /// The returned instance can be used in a shader to enable texture sampling. - /// - /// This is an advanced API that can only be used after the current instance has been transitioned to be in a readonly state. To do so, - /// use , - /// and specify . After that, can be used to get a readonly wrapper for - /// the current texture to use in a shader. This instance should not be cached or reused, but just passed directly to a shader - /// being dispatched through that same , as it will not work if the texture changes state later on. - /// Before the end of that list of operations, the texture also needs to be transitioned back to writeable state, using the same - /// API as before but specifying . Failing to do so results in undefined behavior. - /// - /// - /// Thrown if the current instance or its associated device are disposed. - /// Thrown if the current instance is not in a readonly state. - public IReadOnlyTexture2D AsReadOnly() + /// + internal IReadOnlyNormalizedTexture2D AsReadOnly() { GraphicsDevice.ThrowIfDisposed(); @@ -53,9 +36,6 @@ partial class ReadWriteTexture2D return readOnlyWrapper; } - // The wrapper initialization is moved to a non inlined helper to keep the codegen of this method - // as compact as possible. If the current wrapper is not initialized, control goes directly to the - // helper that will initialize and return it, which translates to a single jump. [MethodImpl(MethodImplOptions.NoInlining)] static ReadOnly InitializeWrapper(ReadWriteTexture2D texture) { @@ -76,7 +56,7 @@ partial class ReadWriteTexture2D /// /// A wrapper for a resource that has been temporarily transitioned to readonly. /// - private sealed unsafe class ReadOnly : NativeObject, IReadOnlyTexture2D, GraphicsResourceHelper.IGraphicsResource + private sealed unsafe class ReadOnly : NativeObject, IReadOnlyNormalizedTexture2D, GraphicsResourceHelper.IGraphicsResource { /// /// The owning instance being wrapped. diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs index 4647cace..fecb9603 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs @@ -14,7 +14,7 @@ namespace ComputeSharp; /// The type of pixels used on the GPU side. [DebuggerTypeProxy(typeof(Texture2DDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] -public sealed partial class ReadWriteTexture2D : Texture2D, IReadWriteTexture2D +public sealed partial class ReadWriteTexture2D : Texture2D, IReadWriteNormalizedTexture2D where T : unmanaged, IPixel where TPixel : unmanaged { diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs new file mode 100644 index 00000000..fdb58dd9 --- /dev/null +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.ReadOnly.cs @@ -0,0 +1,151 @@ +using System; +using System.Runtime.CompilerServices; +using ComputeSharp.__Internals; +using ComputeSharp.Exceptions; +using ComputeSharp.Graphics.Commands.Interop; +using ComputeSharp.Graphics.Extensions; +using ComputeSharp.Graphics.Helpers; +using ComputeSharp.Interop; +using TerraFX.Interop.DirectX; +using static TerraFX.Interop.DirectX.D3D12_SRV_DIMENSION; + +#pragma warning disable CS0618 + +namespace ComputeSharp; + +/// +partial class ReadWriteTexture2D +{ + /// + /// The wrapping instance, if available. + /// + private ReadOnly? readOnlyWrapper; + + /// + public IReadOnlyTexture2D AsReadOnly() + { + GraphicsDevice.ThrowIfDisposed(); + + ThrowIfDisposed(); + ThrowIfIsNotInReadOnlyState(); + + ReadOnly? readOnlyWrapper = this.readOnlyWrapper; + + if (readOnlyWrapper is not null) + { + return readOnlyWrapper; + } + + // The wrapper initialization is moved to a non inlined helper to keep the codegen of this method + // as compact as possible. If the current wrapper is not initialized, control goes directly to the + // helper that will initialize and return it, which translates to a single jump. + [MethodImpl(MethodImplOptions.NoInlining)] + static ReadOnly InitializeWrapper(ReadWriteTexture2D texture) + { + return texture.readOnlyWrapper = new(texture); + } + + return InitializeWrapper(this); + } + + /// + protected override void OnDispose() + { + base.OnDispose(); + + this.readOnlyWrapper?.Dispose(); + } + + /// + /// A wrapper for a resource that has been temporarily transitioned to readonly. + /// + private sealed unsafe class ReadOnly : NativeObject, IReadOnlyTexture2D, GraphicsResourceHelper.IGraphicsResource + { + /// + /// The owning instance being wrapped. + /// + private readonly ReadWriteTexture2D owner; + + /// + /// The instance for the current resource. + /// + private readonly ID3D12ResourceDescriptorHandles d3D12ResourceDescriptorHandles; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The owning instance to wrap. + public ReadOnly(ReadWriteTexture2D owner) + { + this.owner = owner; + + owner.GraphicsDevice.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); + + owner.GraphicsDevice.D3D12Device->CreateShaderResourceView(owner.D3D12Resource, DXGIFormatHelper.GetForType(), D3D12_SRV_DIMENSION_TEXTURE2D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + } + + /// + public ref readonly T this[int x, int y] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture2D.ReadOnly)}[{typeof(int)}, {typeof(int)}]"); + + /// + public ref readonly T this[Int2 xy] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture2D.ReadOnly)}[{typeof(Int2)}]"); + + /// + public ref readonly T this[float u, float v] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture2D.ReadOnly)}[{typeof(float)}, {typeof(float)}]"); + + /// + public ref readonly T this[Float2 uv] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture2D.ReadOnly)}[{typeof(Float2)}]"); + + /// + public int Width => this.owner.Width; + + /// + public int Height => this.owner.Height; + + /// + public GraphicsDevice GraphicsDevice => this.owner.GraphicsDevice; + + /// + D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) + { + ThrowIfDisposed(); + + this.owner.ThrowIfDisposed(); + this.owner.ThrowIfDeviceMismatch(device); + + return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; + } + + /// + (D3D12_GPU_DESCRIPTOR_HANDLE, D3D12_CPU_DESCRIPTOR_HANDLE) GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuAndCpuDescriptorHandlesForClear(GraphicsDevice device, out bool isNormalized) + { + throw new NotSupportedException("This operation cannot be performaned on a readonly wrapper."); + } + + /// + ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) + { + ThrowIfDisposed(); + + this.owner.ThrowIfDisposed(); + this.owner.ThrowIfDeviceMismatch(device); + + return this.owner.D3D12Resource; + } + + /// + (D3D12_RESOURCE_STATES, D3D12_RESOURCE_STATES) GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource) + { + throw new NotSupportedException("This operation cannot be performaned on a readonly wrapper."); + } + + /// + protected override void OnDispose() + { + if (this.owner.GraphicsDevice is GraphicsDevice device) + { + device.ReturnShaderResourceViewDescriptorHandles(in this.d3D12ResourceDescriptorHandles); + } + } + } +} diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.cs index f341e786..d4e055ff 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T}.cs @@ -13,7 +13,7 @@ namespace ComputeSharp; /// The type of items stored on the texture. [DebuggerTypeProxy(typeof(Texture2DDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] -public sealed class ReadWriteTexture2D : Texture2D +public sealed partial class ReadWriteTexture2D : Texture2D where T : unmanaged { /// diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs index 8bc206b8..270c7135 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.ReadOnly.cs @@ -21,25 +21,8 @@ partial class ReadWriteTexture3D /// private ReadOnly? readOnlyWrapper; - /// - /// Retrieves a wrapping instance for the current resource. - /// - /// An instance wrapping the current resource. - /// - /// The returned instance can be used in a shader to enable texture sampling. - /// - /// This is an advanced API that can only be used after the current instance has been transitioned to be in a readonly state. To do so, - /// use , - /// and specify . After that, can be used to get a readonly wrapper for - /// the current texture to use in a shader. This instance should not be cached or reused, but just passed directly to a shader - /// being dispatched through that same , as it will not work if the texture changes state later on. - /// Before the end of that list of operations, the texture also needs to be transitioned back to writeable state, using the same - /// API as before but specifying . Failing to do so results in undefined behavior. - /// - /// - /// Thrown if the current instance or its associated device are disposed. - /// Thrown if the current instance is not in a readonly state. - public IReadOnlyTexture3D AsReadOnly() + /// + public IReadOnlyNormalizedTexture3D AsReadOnly() { GraphicsDevice.ThrowIfDisposed(); @@ -73,7 +56,7 @@ partial class ReadWriteTexture3D /// /// A wrapper for a resource that has been temporarily transitioned to readonly. /// - private sealed unsafe class ReadOnly : NativeObject, IReadOnlyTexture3D, GraphicsResourceHelper.IGraphicsResource + private sealed unsafe class ReadOnly : NativeObject, IReadOnlyNormalizedTexture3D, GraphicsResourceHelper.IGraphicsResource { /// /// The owning instance being wrapped. diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs index 492c6fd6..d7f68197 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs @@ -14,7 +14,7 @@ namespace ComputeSharp; /// The type of pixels used on the GPU side. [DebuggerTypeProxy(typeof(Texture3DDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] -public sealed partial class ReadWriteTexture3D : Texture3D, IReadWriteTexture3D +public sealed partial class ReadWriteTexture3D : Texture3D, IReadWriteNormalizedTexture3D where T : unmanaged, IPixel where TPixel : unmanaged { diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs new file mode 100644 index 00000000..5d38517d --- /dev/null +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.ReadOnly.cs @@ -0,0 +1,151 @@ +using System; +using System.Runtime.CompilerServices; +using ComputeSharp.__Internals; +using ComputeSharp.Exceptions; +using ComputeSharp.Graphics.Commands.Interop; +using ComputeSharp.Graphics.Extensions; +using ComputeSharp.Graphics.Helpers; +using ComputeSharp.Interop; +using TerraFX.Interop.DirectX; +using static TerraFX.Interop.DirectX.D3D12_SRV_DIMENSION; + +#pragma warning disable CS0618 + +namespace ComputeSharp; + +/// +partial class ReadWriteTexture3D +{ + /// + /// The wrapping instance, if available. + /// + private ReadOnly? readOnlyWrapper; + + /// + public IReadOnlyTexture3D AsReadOnly() + { + GraphicsDevice.ThrowIfDisposed(); + + ThrowIfDisposed(); + ThrowIfIsNotInReadOnlyState(); + + ReadOnly? readOnlyWrapper = this.readOnlyWrapper; + + if (readOnlyWrapper is not null) + { + return readOnlyWrapper; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static ReadOnly InitializeWrapper(ReadWriteTexture3D texture) + { + return texture.readOnlyWrapper = new(texture); + } + + return InitializeWrapper(this); + } + + /// + protected override void OnDispose() + { + base.OnDispose(); + + this.readOnlyWrapper?.Dispose(); + } + + /// + /// A wrapper for a resource that has been temporarily transitioned to readonly. + /// + private sealed unsafe class ReadOnly : NativeObject, IReadOnlyTexture3D, GraphicsResourceHelper.IGraphicsResource + { + /// + /// The owning instance being wrapped. + /// + private readonly ReadWriteTexture3D owner; + + /// + /// The instance for the current resource. + /// + private readonly ID3D12ResourceDescriptorHandles d3D12ResourceDescriptorHandles; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The owning instance to wrap. + public ReadOnly(ReadWriteTexture3D owner) + { + this.owner = owner; + + owner.GraphicsDevice.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); + + owner.GraphicsDevice.D3D12Device->CreateShaderResourceView(owner.D3D12Resource, DXGIFormatHelper.GetForType(), D3D12_SRV_DIMENSION_TEXTURE3D, this.d3D12ResourceDescriptorHandles.D3D12CpuDescriptorHandle); + } + + /// + public ref readonly T this[int x, int y, int z] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture3D.ReadOnly)}[{typeof(int)}, {typeof(int)}, {typeof(int)}]"); + + /// + public ref readonly T this[Int3 xyz] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture3D.ReadOnly)}[{typeof(Int3)}]"); + + /// + public ref readonly T this[float u, float v, float w] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture3D.ReadOnly)}[{typeof(float)}, {typeof(float)}, {typeof(float)}]"); + + /// + public ref readonly T this[Float3 uvw] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture3D.ReadOnly)}[{typeof(Float3)}]"); + + /// + public int Width => this.owner.Width; + + /// + public int Height => this.owner.Height; + + /// + public int Depth => this.owner.Depth; + + /// + public GraphicsDevice GraphicsDevice => this.owner.GraphicsDevice; + + /// + D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) + { + ThrowIfDisposed(); + + this.owner.ThrowIfDisposed(); + this.owner.ThrowIfDeviceMismatch(device); + + return this.d3D12ResourceDescriptorHandles.D3D12GpuDescriptorHandle; + } + + /// + (D3D12_GPU_DESCRIPTOR_HANDLE, D3D12_CPU_DESCRIPTOR_HANDLE) GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuAndCpuDescriptorHandlesForClear(GraphicsDevice device, out bool isNormalized) + { + throw new NotSupportedException("This operation cannot be performaned on a readonly wrapper."); + } + + /// + ID3D12Resource* GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12Resource(GraphicsDevice device) + { + ThrowIfDisposed(); + + this.owner.ThrowIfDisposed(); + this.owner.ThrowIfDeviceMismatch(device); + + return this.owner.D3D12Resource; + } + + /// + (D3D12_RESOURCE_STATES, D3D12_RESOURCE_STATES) GraphicsResourceHelper.IGraphicsResource.ValidateAndGetID3D12ResourceAndTransitionStates(GraphicsDevice device, ResourceState resourceState, out ID3D12Resource* d3D12Resource) + { + throw new NotSupportedException("This operation cannot be performaned on a readonly wrapper."); + } + + /// + protected override void OnDispose() + { + if (this.owner.GraphicsDevice is GraphicsDevice device) + { + device.ReturnShaderResourceViewDescriptorHandles(in this.d3D12ResourceDescriptorHandles); + } + } + } +} diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.cs index 1e5e6f89..28f3e10f 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T}.cs @@ -13,7 +13,7 @@ namespace ComputeSharp; /// The type of items stored on the texture. [DebuggerTypeProxy(typeof(Texture3DDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] -public sealed class ReadWriteTexture3D : Texture3D +public sealed partial class ReadWriteTexture3D : Texture3D where T : unmanaged { /// diff --git a/src/ComputeSharp/Shaders/ComputeContext.cs b/src/ComputeSharp/Shaders/ComputeContext.cs index 304ca785..63a16507 100644 --- a/src/ComputeSharp/Shaders/ComputeContext.cs +++ b/src/ComputeSharp/Shaders/ComputeContext.cs @@ -218,7 +218,7 @@ public struct ComputeContext : IDisposable, IAsyncDisposable /// The type of pixel to work on. /// The target texture to invoke the pixel shader upon. /// The input instance representing the pixel shader to run. - internal readonly unsafe void Run(IReadWriteTexture2D texture, ref T shader) + internal readonly unsafe void Run(IReadWriteNormalizedTexture2D texture, ref T shader) where T : struct, IPixelShader where TPixel : unmanaged { diff --git a/src/ComputeSharp/Shaders/Extensions/ComputeContextExtensions.cs b/src/ComputeSharp/Shaders/Extensions/ComputeContextExtensions.cs index 0ef89976..ffe0449b 100644 --- a/src/ComputeSharp/Shaders/Extensions/ComputeContextExtensions.cs +++ b/src/ComputeSharp/Shaders/Extensions/ComputeContextExtensions.cs @@ -81,8 +81,8 @@ public static class ComputeContextExtensions /// /// The type of pixels stored on the texture. /// The to use to insert the resource barrier. - /// The input instance to insert the barrier for. - public static unsafe void Barrier(this in ComputeContext context, IReadWriteTexture2D texture) + /// The input instance to insert the barrier for. + public static unsafe void Barrier(this in ComputeContext context, IReadWriteNormalizedTexture2D texture) where TPixel : unmanaged { context.Barrier(((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetID3D12Resource(context.GraphicsDevice)); @@ -93,8 +93,8 @@ public static class ComputeContextExtensions /// /// The type of pixels stored on the texture. /// The to use to insert the resource barrier. - /// The input instance to insert the barrier for. - public static unsafe void Barrier(this in ComputeContext context, IReadWriteTexture3D texture) + /// The input instance to insert the barrier for. + public static unsafe void Barrier(this in ComputeContext context, IReadWriteNormalizedTexture3D texture) where TPixel : unmanaged { context.Barrier(((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetID3D12Resource(context.GraphicsDevice)); @@ -179,8 +179,8 @@ public static class ComputeContextExtensions /// /// The type of pixels stored on the texture. /// The to use to clear the resource. - /// The input instance to clear. - public static unsafe void Clear(this in ComputeContext context, IReadWriteTexture2D texture) + /// The input instance to clear. + public static unsafe void Clear(this in ComputeContext context, IReadWriteNormalizedTexture2D texture) where TPixel : unmanaged { var handles = ((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetGpuAndCpuDescriptorHandlesForClear(context.GraphicsDevice, out _); @@ -193,8 +193,8 @@ public static class ComputeContextExtensions /// /// The type of pixels stored on the texture. /// The to use to clear the resource. - /// The input instance to clear. - public static unsafe void Clear(this in ComputeContext context, IReadWriteTexture3D texture) + /// The input instance to clear. + public static unsafe void Clear(this in ComputeContext context, IReadWriteNormalizedTexture3D texture) where TPixel : unmanaged { var handles = ((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetGpuAndCpuDescriptorHandlesForClear(context.GraphicsDevice, out _); @@ -241,9 +241,9 @@ public static class ComputeContextExtensions /// /// The type of pixels stored on the texture. /// The to use to fill the resource. - /// The input instance to fill. + /// The input instance to fill. /// The value to use to fill . - public static unsafe void Fill(this in ComputeContext context, IReadWriteTexture2D texture, TPixel value) + public static unsafe void Fill(this in ComputeContext context, IReadWriteNormalizedTexture2D texture, TPixel value) where TPixel : unmanaged { var handles = ((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetGpuAndCpuDescriptorHandlesForClear(context.GraphicsDevice, out _); @@ -260,9 +260,9 @@ public static class ComputeContextExtensions /// /// The type of pixels stored on the texture. /// The to use to fill the resource. - /// The input instance to fill. + /// The input instance to fill. /// The value to use to fill . - public static unsafe void Fill(this in ComputeContext context, IReadWriteTexture3D texture, TPixel value) + public static unsafe void Fill(this in ComputeContext context, IReadWriteNormalizedTexture3D texture, TPixel value) where TPixel : unmanaged { var handles = ((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetGpuAndCpuDescriptorHandlesForClear(context.GraphicsDevice, out _); @@ -341,7 +341,7 @@ public static class ComputeContextExtensions /// The type of pixels being processed by the shader. /// The to use to run the shader. /// The target texture to apply the pixel shader to. - public static void ForEach(this in ComputeContext context, IReadWriteTexture2D texture) + public static void ForEach(this in ComputeContext context, IReadWriteNormalizedTexture2D texture) where T : struct, IPixelShader where TPixel : unmanaged { @@ -356,13 +356,65 @@ public static class ComputeContextExtensions /// The to use to run the shader. /// The target texture to apply the pixel shader to. /// The input instance representing the pixel shader to run. - public static void ForEach(this in ComputeContext context, IReadWriteTexture2D texture, in T shader) + public static void ForEach(this in ComputeContext context, IReadWriteNormalizedTexture2D texture, in T shader) where T : struct, IPixelShader where TPixel : unmanaged { context.Run(texture, ref Unsafe.AsRef(in shader)); } + /// + /// Transitions the state of a specific resource. + /// + /// The to use to transition the resource. + /// The input instance to transition. + /// The state to transition the input resource to. + public static unsafe void Transition(this in ComputeContext context, ReadWriteTexture2D texture, ResourceState resourceState) + { + var states = texture.ValidateAndGetID3D12ResourceAndTransitionStates(context.GraphicsDevice, resourceState, out ID3D12Resource* d3D12Resource); + + context.Transition(d3D12Resource, states.Before, states.After); + } + + /// + /// Transitions the state of a specific resource. + /// + /// The to use to transition the resource. + /// The input instance to transition. + /// The state to transition the input resource to. + public static unsafe void Transition(this in ComputeContext context, ReadWriteTexture2D texture, ResourceState resourceState) + { + var states = texture.ValidateAndGetID3D12ResourceAndTransitionStates(context.GraphicsDevice, resourceState, out ID3D12Resource* d3D12Resource); + + context.Transition(d3D12Resource, states.Before, states.After); + } + + /// + /// Transitions the state of a specific resource. + /// + /// The to use to transition the resource. + /// The input instance to transition. + /// The state to transition the input resource to. + public static unsafe void Transition(this in ComputeContext context, ReadWriteTexture2D texture, ResourceState resourceState) + { + var states = texture.ValidateAndGetID3D12ResourceAndTransitionStates(context.GraphicsDevice, resourceState, out ID3D12Resource* d3D12Resource); + + context.Transition(d3D12Resource, states.Before, states.After); + } + + /// + /// Transitions the state of a specific resource. + /// + /// The to use to transition the resource. + /// The input instance to transition. + /// The state to transition the input resource to. + public static unsafe void Transition(this in ComputeContext context, ReadWriteTexture2D texture, ResourceState resourceState) + { + var states = texture.ValidateAndGetID3D12ResourceAndTransitionStates(context.GraphicsDevice, resourceState, out ID3D12Resource* d3D12Resource); + + context.Transition(d3D12Resource, states.Before, states.After); + } + /// /// Transitions the state of a specific resource. /// @@ -380,6 +432,58 @@ public static class ComputeContextExtensions context.Transition(d3D12Resource, states.Before, states.After); } + /// + /// Transitions the state of a specific resource. + /// + /// The to use to transition the resource. + /// The input instance to transition. + /// The state to transition the input resource to. + public static unsafe void Transition(this in ComputeContext context, ReadWriteTexture3D texture, ResourceState resourceState) + { + var states = texture.ValidateAndGetID3D12ResourceAndTransitionStates(context.GraphicsDevice, resourceState, out ID3D12Resource* d3D12Resource); + + context.Transition(d3D12Resource, states.Before, states.After); + } + + /// + /// Transitions the state of a specific resource. + /// + /// The to use to transition the resource. + /// The input instance to transition. + /// The state to transition the input resource to. + public static unsafe void Transition(this in ComputeContext context, ReadWriteTexture3D texture, ResourceState resourceState) + { + var states = texture.ValidateAndGetID3D12ResourceAndTransitionStates(context.GraphicsDevice, resourceState, out ID3D12Resource* d3D12Resource); + + context.Transition(d3D12Resource, states.Before, states.After); + } + + /// + /// Transitions the state of a specific resource. + /// + /// The to use to transition the resource. + /// The input instance to transition. + /// The state to transition the input resource to. + public static unsafe void Transition(this in ComputeContext context, ReadWriteTexture3D texture, ResourceState resourceState) + { + var states = texture.ValidateAndGetID3D12ResourceAndTransitionStates(context.GraphicsDevice, resourceState, out ID3D12Resource* d3D12Resource); + + context.Transition(d3D12Resource, states.Before, states.After); + } + + /// + /// Transitions the state of a specific resource. + /// + /// The to use to transition the resource. + /// The input instance to transition. + /// The state to transition the input resource to. + public static unsafe void Transition(this in ComputeContext context, ReadWriteTexture3D texture, ResourceState resourceState) + { + var states = texture.ValidateAndGetID3D12ResourceAndTransitionStates(context.GraphicsDevice, resourceState, out ID3D12Resource* d3D12Resource); + + context.Transition(d3D12Resource, states.Before, states.After); + } + /// /// Transitions the state of a specific resource. /// diff --git a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs index 97a5b575..0327f1d4 100644 --- a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs @@ -145,7 +145,7 @@ internal static class ShaderRunner /// The to use to run the shader. /// The target texture to invoke the pixel shader upon. /// The input instance representing the pixel shader to run. - public static unsafe void Run(GraphicsDevice device, IReadWriteTexture2D texture, ref T shader) + public static unsafe void Run(GraphicsDevice device, IReadWriteNormalizedTexture2D texture, ref T shader) where TPixel : unmanaged { device.ThrowIfDisposed(); diff --git a/tests/ComputeSharp.Tests/ComputeContextTests.cs b/tests/ComputeSharp.Tests/ComputeContextTests.cs index 9ba08e37..d4fffa3b 100644 --- a/tests/ComputeSharp.Tests/ComputeContextTests.cs +++ b/tests/ComputeSharp.Tests/ComputeContextTests.cs @@ -283,7 +283,7 @@ public partial class ComputeContextTests using (ComputeContext context = device.Get().CreateComputeContext()) { - context.Clear((IReadWriteTexture2D)texture); + context.Clear((IReadWriteNormalizedTexture2D)texture); } texture.CopyTo(array); @@ -325,7 +325,7 @@ public partial class ComputeContextTests using (ComputeContext context = device.Get().CreateComputeContext()) { - context.Clear((IReadWriteTexture3D)texture); + context.Clear((IReadWriteNormalizedTexture3D)texture); } texture.CopyTo(array); @@ -491,7 +491,7 @@ public partial class ComputeContextTests using (ComputeContext context = device.Get().CreateComputeContext()) { - context.Fill((IReadWriteTexture2D)texture, color.ToPixel()); + context.Fill((IReadWriteNormalizedTexture2D)texture, color.ToPixel()); } T[,] result = texture.ToArray(); @@ -531,7 +531,7 @@ public partial class ComputeContextTests using (ComputeContext context = device.Get().CreateComputeContext()) { - context.Fill((IReadWriteTexture3D)texture, color.ToPixel()); + context.Fill((IReadWriteNormalizedTexture3D)texture, color.ToPixel()); } T[,,] result = texture.ToArray(); @@ -898,13 +898,41 @@ public partial class ComputeContextTests using var sampled = Image.Load(Path.Combine(assetsPath, "CityAfter1024x1024Sampling.png")); + using ReadOnlyTexture2D source = device.Get().LoadReadOnlyTexture2D(Path.Combine(imagingPath, "city.jpg")); + using ReadWriteTexture2D sourceAsFloat4 = device.Get().AllocateReadWriteTexture2D(source.Width, source.Height); + using ReadWriteTexture2D destination = device.Get().AllocateReadWriteTexture2D(sampled.Width, sampled.Height); + + using (var context = device.Get().CreateComputeContext()) + { + context.For(source.Width, source.Height, new ConvertToNonNormalized2DShader(source, sourceAsFloat4)); + context.Transition(sourceAsFloat4, ResourceState.ReadOnly); + context.ForEach(destination, new LinearSampling2DPixelShader(sourceAsFloat4.AsReadOnly())); + context.Transition(sourceAsFloat4, ResourceState.ReadWrite); + } + + using var processed = destination.ToImage(); + + ImagingTests.TolerantImageComparer.AssertEqual(sampled, processed, 0.00000174f); + } + + [CombinatorialTestMethod] + [AllDevices] + public void Transition_ReadWriteTexture2D_Normalized(Device device) + { + _ = device.Get(); + + string imagingPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"); + string assetsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets"); + + using var sampled = Image.Load(Path.Combine(assetsPath, "CityAfter1024x1024Sampling.png")); + using ReadWriteTexture2D source = device.Get().LoadReadWriteTexture2D(Path.Combine(imagingPath, "city.jpg")); using ReadWriteTexture2D destination = device.Get().AllocateReadWriteTexture2D(sampled.Width, sampled.Height); using (var context = device.Get().CreateComputeContext()) { context.Transition(source, ResourceState.ReadOnly); - context.ForEach(destination, new LinearSampling2DPixelShader(source.AsReadOnly())); + context.ForEach(destination, new LinearSamplingFromNormalized2DPixelShader(source.AsReadOnly())); context.Transition(source, ResourceState.ReadWrite); } @@ -927,6 +955,58 @@ public partial class ComputeContextTests using var sampled = Image.Load(Path.Combine(assetsPath, sampledPath)); + using ReadWriteTexture3D sourceAsFloat4 = device.Get().AllocateReadWriteTexture3D(imageInfo.Width, imageInfo.Height, 3); + + using (UploadTexture2D upload2D = device.Get().LoadUploadTexture2D(originalPath)) + using (UploadTexture3D upload3D = device.Get().AllocateUploadTexture3D(upload2D.Width, upload2D.Height, 2)) + { + for (int z = 0; z < upload3D.Depth; z++) + { + TextureView2D layer = upload3D.View.GetDepthView(z); + + for (int y = 0; y < layer.Height; y++) + { + for (int x = 0; x < layer.Width; x++) + { + layer[x, y] = upload2D.View[x, y].ToPixel(); + } + } + } + + upload3D.CopyTo(sourceAsFloat4); + } + + using ReadWriteTexture3D destination = device.Get().AllocateReadWriteTexture3D(sampled.Width, sampled.Height, 2); + + using (var context = device.Get().CreateComputeContext()) + { + context.Transition(sourceAsFloat4, ResourceState.ReadOnly); + context.For(destination.Width, destination.Height, destination.Depth, new LinearSampling3DComputeShader(sourceAsFloat4.AsReadOnly(), destination)); + context.Transition(sourceAsFloat4, ResourceState.ReadWrite); + } + + for (int z = 0; z < destination.Depth; z++) + { + using var processed = destination.ToImage(depth: z); + + ImagingTests.TolerantImageComparer.AssertEqual(sampled, processed, 0.000012f); + } + } + + [CombinatorialTestMethod] + [AllDevices] + public void Transition_ReadWriteTexture3D_Normalized(Device device) + { + _ = device.Get(); + + string assetsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets"); + string originalPath = Path.Combine(assetsPath, "CityWith1920x1280Resizing.png"); + string sampledPath = Path.Combine(assetsPath, "CityAfter1024x1024Sampling.png"); + + var imageInfo = Image.Identify(originalPath); + + using var sampled = Image.Load(Path.Combine(assetsPath, sampledPath)); + using ReadWriteTexture3D source = device.Get().AllocateReadWriteTexture3D(imageInfo.Width, imageInfo.Height, 3); using (UploadTexture2D upload2D = device.Get().LoadUploadTexture2D(originalPath)) @@ -945,7 +1025,7 @@ public partial class ComputeContextTests using (var context = device.Get().CreateComputeContext()) { context.Transition(source, ResourceState.ReadOnly); - context.For(destination.Width, destination.Height, destination.Depth, new LinearSampling3DComputeShader(source.AsReadOnly(), destination)); + context.For(destination.Width, destination.Height, destination.Depth, new LinearSamplingFromNormalized3DComputeShader(source.AsReadOnly(), destination)); context.Transition(source, ResourceState.ReadWrite); } @@ -959,7 +1039,7 @@ public partial class ComputeContextTests [CombinatorialTestMethod] [AllDevices] - public void TransitionAndWrites_ReadWriteTexture2D(Device device) + public void TransitionAndWrites_ReadWriteTexture2D_Normalized(Device device) { _ = device.Get(); @@ -975,7 +1055,7 @@ public partial class ComputeContextTests { context.For(source.Width, source.Height, new Dotted2DPixelShader(source)); context.Transition(source, ResourceState.ReadOnly); - context.ForEach(destination, new LinearSampling2DPixelShader(source.AsReadOnly())); + context.ForEach(destination, new LinearSamplingFromNormalized2DPixelShader(source.AsReadOnly())); context.Transition(source, ResourceState.ReadWrite); context.Fill(source, new Rgba32(0xFF, 0x6A, 0x00, 0x00)); } @@ -994,7 +1074,7 @@ public partial class ComputeContextTests [CombinatorialTestMethod] [AllDevices] - public void TransitionAndWrites_ReadWriteTexture3D(Device device) + public void TransitionAndWrites_ReadWriteTexture3D_Normalized(Device device) { _ = device.Get(); @@ -1025,7 +1105,7 @@ public partial class ComputeContextTests { context.For(source.Width, source.Height, source.Depth, new Dotted3DPixelShader(source)); context.Transition(source, ResourceState.ReadOnly); - context.For(destination.Width, destination.Height, destination.Depth, new LinearSampling3DComputeShader(source.AsReadOnly(), destination)); + context.For(destination.Width, destination.Height, destination.Depth, new LinearSamplingFromNormalized3DComputeShader(source.AsReadOnly(), destination)); context.Transition(source, ResourceState.ReadWrite); context.Fill(source, new Rgba32(0xFF, 0x6A, 0x00, 0x00)); } @@ -1216,7 +1296,32 @@ public partial class ComputeContextTests internal readonly partial struct LinearSampling3DComputeShader : IComputeShader { public readonly IReadOnlyTexture3D source; - public readonly IReadWriteTexture3D destination; + public readonly IReadWriteNormalizedTexture3D destination; + + /// + public void Execute() + { + destination[ThreadIds.XYZ] = source[ThreadIds.Normalized.XYZ]; + } + } + + [AutoConstructor] + internal readonly partial struct LinearSamplingFromNormalized2DPixelShader : IPixelShader + { + public readonly IReadOnlyNormalizedTexture2D source; + + /// + public float4 Execute() + { + return source[ThreadIds.Normalized.XY]; + } + } + + [AutoConstructor] + internal readonly partial struct LinearSamplingFromNormalized3DComputeShader : IComputeShader + { + public readonly IReadOnlyNormalizedTexture3D source; + public readonly IReadWriteNormalizedTexture3D destination; /// public void Execute() @@ -1228,7 +1333,7 @@ public partial class ComputeContextTests [AutoConstructor] internal readonly partial struct Dotted2DPixelShader : IComputeShader { - public readonly IReadWriteTexture2D source; + public readonly IReadWriteNormalizedTexture2D source; /// public void Execute() @@ -1256,7 +1361,7 @@ public partial class ComputeContextTests [AutoConstructor] internal readonly partial struct Dotted3DPixelShader : IComputeShader { - public readonly IReadWriteTexture3D source; + public readonly IReadWriteNormalizedTexture3D source; /// public void Execute() @@ -1280,4 +1385,17 @@ public partial class ComputeContextTests } } } + + [AutoConstructor] + internal readonly partial struct ConvertToNonNormalized2DShader : IComputeShader + { + public readonly IReadOnlyNormalizedTexture2D source; + public readonly ReadWriteTexture2D destination; + + /// + public void Execute() + { + destination[ThreadIds.XY] = source[ThreadIds.XY]; + } + } } diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/ColorfulInfinity.cs b/tests/ComputeSharp.Tests/Shaders/Compute/ColorfulInfinity.cs index 166a29c4..2d70a855 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/ColorfulInfinity.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/ColorfulInfinity.cs @@ -12,7 +12,7 @@ internal readonly partial struct ColorfulInfinity : IComputeShader /// /// The target texture. /// - public readonly IReadWriteTexture2D texture; + public readonly IReadWriteNormalizedTexture2D texture; /// /// The current time since the start of the application. diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/ContouredLayers.cs b/tests/ComputeSharp.Tests/Shaders/Compute/ContouredLayers.cs index 0748d2e5..b982f561 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/ContouredLayers.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/ContouredLayers.cs @@ -11,7 +11,7 @@ internal readonly partial struct ContouredLayers : IComputeShader /// /// The target texture. /// - public readonly IReadWriteTexture2D destination; + public readonly IReadWriteNormalizedTexture2D destination; /// /// The current time Hlsl.Since the start of the application. @@ -21,7 +21,7 @@ internal readonly partial struct ContouredLayers : IComputeShader /// /// The sampling texture. /// - public readonly IReadOnlyTexture2D texture; + public readonly IReadOnlyNormalizedTexture2D texture; // float3 to float hash. private static float Hash21(float2 p) diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/ExtrudedTruchetPattern.cs b/tests/ComputeSharp.Tests/Shaders/Compute/ExtrudedTruchetPattern.cs index fbe09034..308b3c65 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/ExtrudedTruchetPattern.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/ExtrudedTruchetPattern.cs @@ -11,7 +11,7 @@ internal readonly partial struct ExtrudedTruchetPattern : IComputeShader /// /// The target texture. /// - public readonly IReadWriteTexture2D texture; + public readonly IReadWriteNormalizedTexture2D texture; /// /// The current time since the start of the application. diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/FourColorGradient.cs b/tests/ComputeSharp.Tests/Shaders/Compute/FourColorGradient.cs index db346e4c..91309eea 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/FourColorGradient.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/FourColorGradient.cs @@ -12,7 +12,7 @@ internal readonly partial struct FourColorGradient : IComputeShader /// /// The target texture. /// - public readonly IReadWriteTexture2D texture; + public readonly IReadWriteNormalizedTexture2D texture; /// /// The current time since the start of the application. diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/FractalTiling.cs b/tests/ComputeSharp.Tests/Shaders/Compute/FractalTiling.cs index 6ee58518..c61fe0c0 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/FractalTiling.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/FractalTiling.cs @@ -12,7 +12,7 @@ internal readonly partial struct FractalTiling : IComputeShader /// /// The target texture. /// - public readonly IReadWriteTexture2D texture; + public readonly IReadWriteNormalizedTexture2D texture; /// /// The current time since the start of the application. diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/MengerJourney.cs b/tests/ComputeSharp.Tests/Shaders/Compute/MengerJourney.cs index bc54d018..83f97d10 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/MengerJourney.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/MengerJourney.cs @@ -11,7 +11,7 @@ internal readonly partial struct MengerJourney : IComputeShader /// /// The target texture. /// - public readonly IReadWriteTexture2D texture; + public readonly IReadWriteNormalizedTexture2D texture; /// /// The current time since the start of the application. diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/Octagrams.cs b/tests/ComputeSharp.Tests/Shaders/Compute/Octagrams.cs index 9901a7f0..9c37ce7b 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/Octagrams.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/Octagrams.cs @@ -11,7 +11,7 @@ internal readonly partial struct Octagrams : IComputeShader /// /// The target texture. /// - public readonly IReadWriteTexture2D texture; + public readonly IReadWriteNormalizedTexture2D texture; /// /// The current time since the start of the application. diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/ProteanClouds.cs b/tests/ComputeSharp.Tests/Shaders/Compute/ProteanClouds.cs index 079f600c..030ffdb3 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/ProteanClouds.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/ProteanClouds.cs @@ -12,7 +12,7 @@ internal readonly partial struct ProteanClouds : IComputeShader /// /// The target texture. /// - public readonly IReadWriteTexture2D texture; + public readonly IReadWriteNormalizedTexture2D texture; /// /// The current time Hlsl.Since the start of the application. diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/PyramidPattern.cs b/tests/ComputeSharp.Tests/Shaders/Compute/PyramidPattern.cs index adb0a1be..778d3442 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/PyramidPattern.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/PyramidPattern.cs @@ -12,7 +12,7 @@ internal readonly partial struct PyramidPattern : IComputeShader /// /// The target texture. /// - public readonly IReadWriteTexture2D texture; + public readonly IReadWriteNormalizedTexture2D texture; /// /// The current time Hlsl.Since the start of the application. diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/TriangleGridContouring.cs b/tests/ComputeSharp.Tests/Shaders/Compute/TriangleGridContouring.cs index 66e59609..3457d626 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/TriangleGridContouring.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/TriangleGridContouring.cs @@ -11,7 +11,7 @@ internal readonly partial struct TriangleGridContouring : IComputeShader /// /// The target texture. /// - public readonly IReadWriteTexture2D texture; + public readonly IReadWriteNormalizedTexture2D texture; /// /// The current time Hlsl.Since the start of the application. diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/TwoTiledTruchet.cs b/tests/ComputeSharp.Tests/Shaders/Compute/TwoTiledTruchet.cs index 878f54a7..8d31b400 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/TwoTiledTruchet.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/TwoTiledTruchet.cs @@ -11,7 +11,7 @@ internal readonly partial struct TwoTiledTruchet : IComputeShader /// /// The target texture. /// - public readonly IReadWriteTexture2D texture; + public readonly IReadWriteNormalizedTexture2D texture; /// /// The current time since the start of the application. diff --git a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs index b779e9db..30ef0a3c 100644 --- a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs +++ b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs @@ -74,8 +74,8 @@ public partial class Texture2DTests [AutoConstructor] public readonly partial struct SamplingComputeShader : IComputeShader { - public readonly IReadOnlyTexture2D source; - public readonly IReadWriteTexture2D destination; + public readonly IReadOnlyNormalizedTexture2D source; + public readonly IReadWriteNormalizedTexture2D destination; public void Execute() { @@ -107,7 +107,7 @@ public partial class Texture2DTests [AutoConstructor] public readonly partial struct SamplingPixelShader : IPixelShader { - public readonly IReadOnlyTexture2D texture; + public readonly IReadOnlyNormalizedTexture2D texture; public float4 Execute() { @@ -136,11 +136,11 @@ public partial class Texture2DTests { context.Transition(texture, ResourceState.ReadOnly); - IReadOnlyTexture2D wrapper1 = texture.AsReadOnly(); + IReadOnlyNormalizedTexture2D wrapper1 = texture.AsReadOnly(); Assert.IsNotNull(wrapper1); - IReadOnlyTexture2D wrapper2 = texture.AsReadOnly(); + IReadOnlyNormalizedTexture2D wrapper2 = texture.AsReadOnly(); Assert.IsNotNull(wrapper2); Assert.AreSame(wrapper1, wrapper2); diff --git a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs index 7a75234b..d8b6c18f 100644 --- a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs +++ b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs @@ -69,11 +69,11 @@ public partial class Texture3DTests { context.Transition(texture, ResourceState.ReadOnly); - IReadOnlyTexture3D wrapper1 = texture.AsReadOnly(); + IReadOnlyNormalizedTexture3D wrapper1 = texture.AsReadOnly(); Assert.IsNotNull(wrapper1); - IReadOnlyTexture3D wrapper2 = texture.AsReadOnly(); + IReadOnlyNormalizedTexture3D wrapper2 = texture.AsReadOnly(); Assert.IsNotNull(wrapper2); Assert.AreSame(wrapper1, wrapper2);