From 9a0c27b71e8ce19f9f4e200cfc3f9a6e878a4275 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 1 Jan 2022 15:39:18 +0100 Subject: [PATCH 01/12] Fix frame latency management, improve rendering performance --- .../Controls/ComputeShaderPanel.Rendering.cs | 38 +++++++++++-------- .../DirectX/shared/dxgi1_4/IDXGISwapChain3.cs | 7 ++++ 2 files changed, 30 insertions(+), 15 deletions(-) diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Rendering.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Rendering.cs index 855c3223..9dd2fbc3 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Rendering.cs +++ b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Rendering.cs @@ -231,6 +231,10 @@ public sealed partial class ComputeShaderPanel } } + // Set the maximum frame latency to 2 to improve rendering performance. This is fine in this scenario, as we're not + // dealing with a real-time game or something that absolutely needs the least amount of frame latency as possible. + this.dxgiSwapChain3.Get()->SetMaximumFrameLatency(2).Assert(); + // Get the awaitable object to synchronizize present calls this.frameLatencyWaitableObject = this.dxgiSwapChain3.Get()->GetFrameLatencyWaitableObject(); @@ -348,10 +352,10 @@ public sealed partial class ComputeShaderPanel } /// - /// Updates the render resolution, if needed, and renders a new frame. + /// Updates the render resolution, if needed, and renders and presents a new frame. /// /// The current time since the start of the application. - private unsafe void OnUpdate(TimeSpan time) + private unsafe bool OnUpdate(TimeSpan time) { if (this.isResizePending) { @@ -363,11 +367,19 @@ public sealed partial class ComputeShaderPanel // Skip if no factory is available if (this.shaderRunner is null) { - return; + return false; } + // Wait for the swap chain to finish presenting + _ = Win32.WaitForSingleObjectEx(frameLatencyWaitableObject, 1000, true); + // Generate the new frame this.shaderRunner.Execute(this.texture!, time); + + // Present the new frame + OnPresent(); + + return true; } /// @@ -375,8 +387,6 @@ public sealed partial class ComputeShaderPanel /// private unsafe void OnPresent() { - _ = Win32.WaitForSingleObjectEx(frameLatencyWaitableObject, 1000, 1); - using ComPtr d3D12Resource = default; // Get the underlying ID3D12Resource pointer for the texture @@ -462,13 +472,13 @@ public sealed partial class ComputeShaderPanel // Start the initial frame separately, before the timer starts. This ensures that // resuming after a pause correctly renders the first frame at the right time. - @this.OnUpdate(renderStopwatch.Elapsed); - @this.OnPresent(); + while (!@this.OnUpdate(renderStopwatch.Elapsed) && + !@this.isCancellationRequested) + { + } renderStopwatch.Start(); - const long targetFrameTimeInTicksFor61fps = 163934; - // Main render loop, until cancellation is requested while (!@this.isCancellationRequested) { @@ -494,14 +504,12 @@ public sealed partial class ComputeShaderPanel @this.isResizePending = true; } - while (frameStopwatch.ElapsedTicks < targetFrameTimeInTicksFor61fps) - { - } - frameStopwatch.Restart(); - @this.OnUpdate(renderStopwatch.Elapsed); - @this.OnPresent(); + while (!@this.OnUpdate(renderStopwatch.Elapsed) && + !@this.isCancellationRequested) + { + } } renderStopwatch.Stop(); diff --git a/src/TerraFX.Interop.Windows/DirectX/shared/dxgi1_4/IDXGISwapChain3.cs b/src/TerraFX.Interop.Windows/DirectX/shared/dxgi1_4/IDXGISwapChain3.cs index 358cbf3d..4b6b04e8 100644 --- a/src/TerraFX.Interop.Windows/DirectX/shared/dxgi1_4/IDXGISwapChain3.cs +++ b/src/TerraFX.Interop.Windows/DirectX/shared/dxgi1_4/IDXGISwapChain3.cs @@ -63,6 +63,13 @@ namespace TerraFX.Interop.DirectX return ((delegate* unmanaged[Stdcall])(lpVtbl[13]))((IDXGISwapChain3*)Unsafe.AsPointer(ref this), BufferCount, Width, Height, NewFormat, SwapChainFlags); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(31)] + public HRESULT SetMaximumFrameLatency(uint MaxLatency) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[31]))((IDXGISwapChain3*)Unsafe.AsPointer(ref this), MaxLatency); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(33)] public HANDLE GetFrameLatencyWaitableObject() From 9205b38de79d40427f8e1aa56a29553f5f428e88 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 1 Jan 2022 17:50:34 +0100 Subject: [PATCH 02/12] Add [SkipLocalsInit] to UWP sample app --- .../ComputeSharp.SwapChain.Uwp.csproj | 1 + .../Properties/AssemblyInfo.cs | 5 ++++- .../Properties/SkipLocalsInitAttribute.cs | 16 ++++++++++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 samples/ComputeSharp.SwapChain.Uwp/Properties/SkipLocalsInitAttribute.cs diff --git a/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj b/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj index c183283c..477be62b 100644 --- a/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj +++ b/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj @@ -123,6 +123,7 @@ App.xaml + MainView.xaml diff --git a/samples/ComputeSharp.SwapChain.Uwp/Properties/AssemblyInfo.cs b/samples/ComputeSharp.SwapChain.Uwp/Properties/AssemblyInfo.cs index c199ce78..0ed0ddff 100644 --- a/samples/ComputeSharp.SwapChain.Uwp/Properties/AssemblyInfo.cs +++ b/samples/ComputeSharp.SwapChain.Uwp/Properties/AssemblyInfo.cs @@ -1,4 +1,5 @@ using System.Reflection; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -25,4 +26,6 @@ using System.Runtime.InteropServices; // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] -[assembly: ComVisible(false)] \ No newline at end of file +[assembly: ComVisible(false)] + +[module: SkipLocalsInit] \ No newline at end of file diff --git a/samples/ComputeSharp.SwapChain.Uwp/Properties/SkipLocalsInitAttribute.cs b/samples/ComputeSharp.SwapChain.Uwp/Properties/SkipLocalsInitAttribute.cs new file mode 100644 index 00000000..894d04db --- /dev/null +++ b/samples/ComputeSharp.SwapChain.Uwp/Properties/SkipLocalsInitAttribute.cs @@ -0,0 +1,16 @@ +namespace System.Runtime.CompilerServices; + +/// +/// Used to indicate to the compiler that the .locals init flag should not be set in method headers. +/// +[AttributeUsage(AttributeTargets.Module + | AttributeTargets.Class + | AttributeTargets.Struct + | AttributeTargets.Interface + | AttributeTargets.Constructor + | AttributeTargets.Method + | AttributeTargets.Property + | AttributeTargets.Event, Inherited = false)] +internal sealed class SkipLocalsInitAttribute : Attribute +{ +} \ No newline at end of file From b3338be7dddd67ecf6c2c109813048e4b385c616 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 2 Jan 2022 13:31:35 +0100 Subject: [PATCH 03/12] Revert multiple frames latency --- .../Controls/ComputeShaderPanel.Properties.cs | 2 +- .../Controls/ComputeShaderPanel.Rendering.cs | 35 ++++++------------- .../Controls/ComputeShaderPanel.cs | 2 +- .../DirectX/shared/dxgi1_4/IDXGISwapChain3.cs | 7 ---- 4 files changed, 13 insertions(+), 33 deletions(-) diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs index 73e49028..818f753e 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs +++ b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs @@ -10,7 +10,7 @@ namespace ComputeSharp.WinUI; #endif /// -public sealed unsafe partial class ComputeShaderPanel +partial class ComputeShaderPanel { /// /// Gets or sets the instance to use to render content. diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Rendering.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Rendering.cs index 9dd2fbc3..510266b6 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Rendering.cs +++ b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Rendering.cs @@ -29,7 +29,7 @@ namespace ComputeSharp.WinUI; #endif /// -public sealed partial class ComputeShaderPanel +partial class ComputeShaderPanel { /// /// The render thread in use, if any. @@ -231,10 +231,6 @@ public sealed partial class ComputeShaderPanel } } - // Set the maximum frame latency to 2 to improve rendering performance. This is fine in this scenario, as we're not - // dealing with a real-time game or something that absolutely needs the least amount of frame latency as possible. - this.dxgiSwapChain3.Get()->SetMaximumFrameLatency(2).Assert(); - // Get the awaitable object to synchronizize present calls this.frameLatencyWaitableObject = this.dxgiSwapChain3.Get()->GetFrameLatencyWaitableObject(); @@ -352,10 +348,10 @@ public sealed partial class ComputeShaderPanel } /// - /// Updates the render resolution, if needed, and renders and presents a new frame. + /// Updates the render resolution, if needed, and renders a new frame. /// /// The current time since the start of the application. - private unsafe bool OnUpdate(TimeSpan time) + private void OnUpdate(TimeSpan time) { if (this.isResizePending) { @@ -367,19 +363,11 @@ public sealed partial class ComputeShaderPanel // Skip if no factory is available if (this.shaderRunner is null) { - return false; + return; } - // Wait for the swap chain to finish presenting - _ = Win32.WaitForSingleObjectEx(frameLatencyWaitableObject, 1000, true); - // Generate the new frame this.shaderRunner.Execute(this.texture!, time); - - // Present the new frame - OnPresent(); - - return true; } /// @@ -387,6 +375,9 @@ public sealed partial class ComputeShaderPanel /// private unsafe void OnPresent() { + // Wait for the swap chain to be ready for presenting + _ = Win32.WaitForSingleObjectEx(frameLatencyWaitableObject, 1000, true); + using ComPtr d3D12Resource = default; // Get the underlying ID3D12Resource pointer for the texture @@ -472,10 +463,8 @@ public sealed partial class ComputeShaderPanel // Start the initial frame separately, before the timer starts. This ensures that // resuming after a pause correctly renders the first frame at the right time. - while (!@this.OnUpdate(renderStopwatch.Elapsed) && - !@this.isCancellationRequested) - { - } + @this.OnUpdate(renderStopwatch.Elapsed); + @this.OnPresent(); renderStopwatch.Start(); @@ -506,10 +495,8 @@ public sealed partial class ComputeShaderPanel frameStopwatch.Restart(); - while (!@this.OnUpdate(renderStopwatch.Elapsed) && - !@this.isCancellationRequested) - { - } + @this.OnUpdate(renderStopwatch.Elapsed); + @this.OnPresent(); } renderStopwatch.Stop(); diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs index 70d86b9d..9b0f15d7 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs +++ b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs @@ -14,7 +14,7 @@ namespace ComputeSharp.WinUI; /// A custom that can be used to render animated backgrounds. /// It is powered by ComputeSharp and leverages compute shaders to create frames to display. /// -public sealed unsafe partial class ComputeShaderPanel : SwapChainPanel +public sealed partial class ComputeShaderPanel : SwapChainPanel { /// /// Creates a new instance. diff --git a/src/TerraFX.Interop.Windows/DirectX/shared/dxgi1_4/IDXGISwapChain3.cs b/src/TerraFX.Interop.Windows/DirectX/shared/dxgi1_4/IDXGISwapChain3.cs index 4b6b04e8..358cbf3d 100644 --- a/src/TerraFX.Interop.Windows/DirectX/shared/dxgi1_4/IDXGISwapChain3.cs +++ b/src/TerraFX.Interop.Windows/DirectX/shared/dxgi1_4/IDXGISwapChain3.cs @@ -63,13 +63,6 @@ namespace TerraFX.Interop.DirectX return ((delegate* unmanaged[Stdcall])(lpVtbl[13]))((IDXGISwapChain3*)Unsafe.AsPointer(ref this), BufferCount, Width, Height, NewFormat, SwapChainFlags); } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - [VtblIndex(31)] - public HRESULT SetMaximumFrameLatency(uint MaxLatency) - { - return ((delegate* unmanaged[Stdcall])(lpVtbl[31]))((IDXGISwapChain3*)Unsafe.AsPointer(ref this), MaxLatency); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(33)] public HANDLE GetFrameLatencyWaitableObject() From 6e0a6d0796a1ac66d4b94bcbf9292471f6c8da02 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 2 Jan 2022 14:51:36 +0100 Subject: [PATCH 04/12] Move swap chain rendering code to SwapChainManager type --- src/ComputeSharp.UI/ComputeSharp.UI.projitems | 2 +- .../Controls/ComputeShaderPanel.Properties.cs | 47 ++- .../Controls/ComputeShaderPanel.cs | 63 ++-- .../SwapChainManager.cs} | 297 ++++++++++-------- 4 files changed, 234 insertions(+), 175 deletions(-) rename src/ComputeSharp.UI/{Controls/ComputeShaderPanel.Rendering.cs => Helpers/SwapChainManager.cs} (75%) diff --git a/src/ComputeSharp.UI/ComputeSharp.UI.projitems b/src/ComputeSharp.UI/ComputeSharp.UI.projitems index e081e8cc..571ddce3 100644 --- a/src/ComputeSharp.UI/ComputeSharp.UI.projitems +++ b/src/ComputeSharp.UI/ComputeSharp.UI.projitems @@ -11,7 +11,7 @@ - + diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs index 818f753e..f7c134fb 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs +++ b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs @@ -1,11 +1,13 @@ using System; #if WINDOWS_UWP using Windows.UI.Xaml; +#else +using Microsoft.UI.Xaml; +#endif +#if WINDOWS_UWP namespace ComputeSharp.Uwp; #else - -using Microsoft.UI.Xaml; namespace ComputeSharp.WinUI; #endif @@ -17,18 +19,35 @@ partial class ComputeShaderPanel /// public IShaderRunner? ShaderRunner { - get => (IShaderRunner?)GetValue(ShaderFactoryProperty); - set => SetValue(ShaderFactoryProperty, value); + get => (IShaderRunner?)GetValue(ShaderRunnerProperty); + set => SetValue(ShaderRunnerProperty, value); } /// /// The backing . /// - public static readonly DependencyProperty ShaderFactoryProperty = DependencyProperty.Register( + public static readonly DependencyProperty ShaderRunnerProperty = DependencyProperty.Register( nameof(ShaderRunner), typeof(IShaderRunner), typeof(ComputeShaderPanel), - new PropertyMetadata(null, static (d, e) => ((ComputeShaderPanel)d).shaderRunner = (IShaderRunner?)e.NewValue)); + new PropertyMetadata(null, OnShaderRunnerPropertyChanged)); + + /// + private static void OnShaderRunnerPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var @this = (ComputeShaderPanel)d; + var shaderRunner = (IShaderRunner?)e.NewValue; + + if (shaderRunner is null) + { + @this.swapChainManager.StopRenderLoop(); + } + else if (@this.IsLoaded && + !@this.IsPaused) + { + @this.swapChainManager.StartRenderLoop(shaderRunner); + } + } /// /// Gets or sets the resolution scale to be used to render frames. @@ -56,12 +75,7 @@ partial class ComputeShaderPanel var @this = (ComputeShaderPanel)d; var resolutionScale = (double)e.NewValue; - @this.targetResolutionScale = (float)resolutionScale; - - if (!@this.isDynamicResolutionEnabled) - { - @this.OnResize(); - } + @this.swapChainManager.QueueResolutionScaleChange(resolutionScale); } /// @@ -89,8 +103,6 @@ partial class ComputeShaderPanel { var @this = (ComputeShaderPanel)d; var isDynamicResolutionEnabled = (bool)e.NewValue; - - @this.isDynamicResolutionEnabled = isDynamicResolutionEnabled; } /// @@ -119,11 +131,12 @@ partial class ComputeShaderPanel if (isPaused) { - @this.OnStopRenderLoop(); + @this.swapChainManager.StopRenderLoop(); } - else + else if (@this.IsLoaded && + @this.ShaderRunner is IShaderRunner shaderRunner) { - @this.OnStartRenderLoop(); + @this.swapChainManager.StartRenderLoop(shaderRunner); } } } diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs index 9b0f15d7..6ba8eff5 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs +++ b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs @@ -1,12 +1,20 @@ #if WINDOWS_UWP +using System.Runtime.InteropServices; +using ComputeSharp.Uwp.Helpers; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; - -namespace ComputeSharp.Uwp; +using TerraFX.Interop.Windows; #else +using ComputeSharp.WinUI.Helpers; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; +using TerraFX.Interop.Windows; +using WinRT; +#endif +#if WINDOWS_UWP +namespace ComputeSharp.Uwp; +#else namespace ComputeSharp.WinUI; #endif @@ -16,61 +24,58 @@ namespace ComputeSharp.WinUI; /// public sealed partial class ComputeShaderPanel : SwapChainPanel { + /// + /// The instance handling rendering. + /// + private readonly SwapChainManager swapChainManager; + /// /// Creates a new instance. /// - public ComputeShaderPanel() + public unsafe ComputeShaderPanel() { +#if WINDOWS_UWP + IUnknown* swapChainPanel = (IUnknown*)Marshal.GetIUnknownForObject(this); +#else + IUnknown* swapChainPanel = (IUnknown*)((IWinRTObject)this).NativeObject.ThisPtr; +#endif + + this.swapChainManager = new SwapChainManager(swapChainPanel); + this.Loaded += ComputeShaderPanel_Loaded; this.Unloaded += ComputeShaderPanel_Unloaded; this.SizeChanged += ComputeShaderPanel_SizeChanged; this.CompositionScaleChanged += ComputeShaderPanel_CompositionScaleChanged; } - /// - /// Finalizes the current instance and releases all resources. - /// - ~ComputeShaderPanel() - { - OnDisposed(); - } - // Initializes the swap chain and starts the render thread private void ComputeShaderPanel_Loaded(object sender, RoutedEventArgs e) { - this.width = (float)ActualWidth; - this.height = (float)ActualHeight; - this.compositionScaleX = CompositionScaleX; - this.compositionScaleY = CompositionScaleY; - this.resolutionScale = (float)ResolutionScale; - this.targetResolutionScale = 1.0f; - this.isDynamicResolutionEnabled = true; + this.swapChainManager.QueueResize(ActualWidth, ActualHeight); + this.swapChainManager.QueueCompositionScaleChange(CompositionScaleX, CompositionScaleY); + this.swapChainManager.QueueResolutionScaleChange(ResolutionScale); - OnInitialize(); - OnStartRenderLoop(); + if (ShaderRunner is IShaderRunner shaderRunner) + { + this.swapChainManager.StartRenderLoop(shaderRunner); + } } // Requests a cancellation for the render thread private void ComputeShaderPanel_Unloaded(object sender, RoutedEventArgs e) { - OnStopRenderLoop(); + this.swapChainManager.StopRenderLoop(); } // Updates the background store for the frame size factors used by the render thread private void ComputeShaderPanel_SizeChanged(object sender, SizeChangedEventArgs e) { - this.width = (float)e.NewSize.Width; - this.height = (float)e.NewSize.Height; - - OnResize(); + this.swapChainManager.QueueResize(e.NewSize.Width, e.NewSize.Height); } // Updates the background store for the composition scale factors used by the render thread private void ComputeShaderPanel_CompositionScaleChanged(SwapChainPanel sender, object args) { - this.compositionScaleX = CompositionScaleX; - this.compositionScaleY = CompositionScaleY; - - OnResize(); + this.swapChainManager.QueueCompositionScaleChange(CompositionScaleX, CompositionScaleY); } } diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Rendering.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs similarity index 75% rename from src/ComputeSharp.UI/Controls/ComputeShaderPanel.Rendering.cs rename to src/ComputeSharp.UI/Helpers/SwapChainManager.cs index 510266b6..5ecc8383 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Rendering.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs @@ -1,45 +1,32 @@ using System; using System.Diagnostics; -#if WINDOWS_UWP -using System.Runtime.InteropServices; -#endif using System.Threading; using ComputeSharp.Core.Extensions; using ComputeSharp.Graphics.Helpers; using ComputeSharp.Interop; -#if WINDOWS_UWP -using ComputeSharp.Uwp.Helpers; -#else -using ComputeSharp.WinUI.Helpers; -#endif +using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using TerraFX.Interop.WinRT; -#if !WINDOWS_UWP -using WinRT; -#endif using Win32 = TerraFX.Interop.Windows.Windows; #pragma warning disable CS0420 #if WINDOWS_UWP -namespace ComputeSharp.Uwp; +namespace ComputeSharp.Uwp.Helpers; #else -namespace ComputeSharp.WinUI; +namespace ComputeSharp.WinUI.Helpers; #endif -/// -partial class ComputeShaderPanel +/// +/// A type managing rendering on a target swap chain object. +/// +internal sealed unsafe class SwapChainManager : NativeObject { /// - /// The render thread in use, if any. + /// A lock object for the render loops. /// - private Thread? renderThread; - - /// - /// The instance used to create shaders to run. - /// - private IShaderRunner? shaderRunner; + private readonly object renderLock = new(); /// /// The pointer for the device currently in use. @@ -94,12 +81,27 @@ partial class ComputeShaderPanel /// /// The index of the next buffer that can be used to present content. /// - private uint currentBufferIndex; + private volatile uint currentBufferIndex; + + /// + /// The render thread in use, if any. + /// + private volatile Thread? renderThread; + + /// + /// The to use for . + /// + private volatile CancellationTokenSource? renderCancellationTokenSource; + + /// + /// The instance used to create shaders to run. + /// + private volatile IShaderRunner? shaderRunner; /// /// The instance used to prepare frames to display. /// - private ReadWriteTexture2D? texture; + private volatile ReadWriteTexture2D? texture; /// /// Whether or not the window has been resized and requires the buffers to be updated. @@ -141,37 +143,37 @@ partial class ComputeShaderPanel /// private volatile bool isDynamicResolutionEnabled; - /// - /// Indicates whether or not the rendering has been canceled. - /// - private volatile bool isCancellationRequested; - /// /// The instance tracking time since the first rendered frame. /// - private Stopwatch? renderStopwatch; + private volatile Stopwatch? renderStopwatch; /// - /// Indicates whether or not has already been called. + /// Initializes a new instance of the type. /// - private bool isInitialized; - - /// - /// Initializes the current application. - /// - private unsafe void OnInitialize() + /// The input swap chain object being used. + public SwapChainManager(IUnknown* swapChainPanel) { - if (this.isInitialized) - { - return; - } + // Extract the ISwapChainPanelNative reference from the current panel, then query the + // IDXGISwapChain reference just created and set that as the swap chain panel to use. + using ComPtr swapChainPanelNative = default; - this.isInitialized = true; +#if WINDOWS_UWP + swapChainPanel->QueryInterface( + Win32.__uuidof(), + (void**)&swapChainPanelNative).Assert(); +#else + Guid iSwapChainPanelNativeUuid = new(0x63AAD0B8, 0x7C24, 0x40FF, 0x85, 0xA8, 0x64, 0x0D, 0x94, 0x4C, 0xC3, 0x25); + + swapChainPanel->QueryInterface( + &iSwapChainPanelNativeUuid, + (void**)&swapChainPanelNative).Assert(); +#endif // Get the underlying ID3D12Device in use fixed (ID3D12Device** d3D12Device = this.d3D12Device) { - InteropServices.TryGetID3D12Device(GraphicsDevice.Default, Win32.__uuidof(), (void**)d3D12Device).Assert(); + GraphicsDevice.Default.D3D12Device->QueryInterface(Win32.__uuidof(), (void**)d3D12Device).Assert(); } // Create the direct command queue to use @@ -258,25 +260,6 @@ partial class ComputeShaderPanel // Close the command list to prepare it for future use this.d3D12GraphicsCommandList.Get()->Close().Assert(); - // Extract the ISwapChainPanelNative reference from the current panel, then query the - // IDXGISwapChain reference just created and set that as the swap chain panel to use. - using ComPtr swapChainPanelNative = default; - -#if WINDOWS_UWP - IUnknown* swapChainPanel = (IUnknown*)Marshal.GetIUnknownForObject(this); - - swapChainPanel->QueryInterface( - Win32.__uuidof(), - (void**)&swapChainPanelNative).Assert(); -#else - IUnknown* swapChainPanel = (IUnknown*)((IWinRTObject)this).NativeObject.ThisPtr; - Guid iSwapChainPanelNativeUuid = new(0x63AAD0B8, 0x7C24, 0x40FF, 0x85, 0xA8, 0x64, 0x0D, 0x94, 0x4C, 0xC3, 0x25); - - swapChainPanel->QueryInterface( - &iSwapChainPanelNativeUuid, - (void**)&swapChainPanelNative).Assert(); -#endif - using (ComPtr idxgiSwapChain = default) { this.dxgiSwapChain3.CopyTo(&idxgiSwapChain).Assert(); @@ -287,14 +270,6 @@ partial class ComputeShaderPanel GC.KeepAlive(this); } - /// - /// Resizes the current application. - /// - private void OnResize() - { - this.isResizePending = true; - } - /// /// Applies the actual resize logic that was scheduled from . /// @@ -348,10 +323,9 @@ partial class ComputeShaderPanel } /// - /// Updates the render resolution, if needed, and renders a new frame. + /// Resizes the current application, if needed. /// - /// The current time since the start of the application. - private void OnUpdate(TimeSpan time) + private void OnResize() { if (this.isResizePending) { @@ -359,7 +333,14 @@ partial class ComputeShaderPanel this.isResizePending = false; } + } + /// + /// Updates the render resolution, if needed, and renders a new frame. + /// + /// The current time since the start of the application. + private void OnUpdate(TimeSpan time) + { // Skip if no factory is available if (this.shaderRunner is null) { @@ -381,7 +362,7 @@ partial class ComputeShaderPanel using ComPtr d3D12Resource = default; // Get the underlying ID3D12Resource pointer for the texture - InteropServices.TryGetID3D12Resource(this.texture!, Win32.__uuidof(), (void**)d3D12Resource.GetAddressOf()).Assert(); + this.texture!.D3D12Resource->QueryInterface(Win32.__uuidof(), (void**)d3D12Resource.GetAddressOf()).Assert(); // Get the target back buffer to update ID3D12Resource* d3D12ResourceBackBuffer = this.currentBufferIndex switch @@ -446,86 +427,146 @@ partial class ComputeShaderPanel } /// - /// Executes the render loop for the current panel. + /// The core render loop. /// - /// This method assumes to be invoked from a background thread. - private void OnStartRenderLoop() + private void RenderLoop() { - static void ExecuteRenderLoop(ComputeShaderPanel @this) + Stopwatch renderStopwatch = this.renderStopwatch ??= new(); + Stopwatch frameStopwatch = Stopwatch.StartNew(); + CancellationToken cancellationToken = this.renderCancellationTokenSource!.Token; + + DynamicResolutionManager.Create(out DynamicResolutionManager frameTimeWatcher); + + bool isDynamicResolutionEnabled = this.isDynamicResolutionEnabled; + + // Start the initial frame separately, before the timer starts. This ensures that + // resuming after a pause correctly renders the first frame at the right time. + this.OnResize(); + this.OnUpdate(renderStopwatch.Elapsed); + this.OnPresent(); + + renderStopwatch.Start(); + + // Main render loop, until cancellation is requested + while (!cancellationToken.IsCancellationRequested) { - Stopwatch - renderStopwatch = @this.renderStopwatch ??= new(), - frameStopwatch = Stopwatch.StartNew(); - - DynamicResolutionManager.Create(out DynamicResolutionManager frameTimeWatcher); - - bool isDynamicResolutionEnabled = @this.isDynamicResolutionEnabled; - - // Start the initial frame separately, before the timer starts. This ensures that - // resuming after a pause correctly renders the first frame at the right time. - @this.OnUpdate(renderStopwatch.Elapsed); - @this.OnPresent(); - - renderStopwatch.Start(); - - // Main render loop, until cancellation is requested - while (!@this.isCancellationRequested) + // Update the resolution mode, if needed + if (isDynamicResolutionEnabled != this.isDynamicResolutionEnabled) { - // Update the resolution mode, if needed - if (isDynamicResolutionEnabled != @this.isDynamicResolutionEnabled) + isDynamicResolutionEnabled = !isDynamicResolutionEnabled; + + if (isDynamicResolutionEnabled) { - isDynamicResolutionEnabled = !isDynamicResolutionEnabled; - - if (isDynamicResolutionEnabled) - { - DynamicResolutionManager.Create(out frameTimeWatcher); - } - else - { - @this.targetResolutionScale = @this.resolutionScale; - } + DynamicResolutionManager.Create(out frameTimeWatcher); } - - // Evaluate the dynamic resolution frame time step, if the mode is enabled - if (isDynamicResolutionEnabled && - frameTimeWatcher.Advance(frameStopwatch.ElapsedTicks, ref @this.targetResolutionScale)) + else { - @this.isResizePending = true; + this.targetResolutionScale = this.resolutionScale; } - - frameStopwatch.Restart(); - - @this.OnUpdate(renderStopwatch.Elapsed); - @this.OnPresent(); } - renderStopwatch.Stop(); + // Evaluate the dynamic resolution frame time step, if the mode is enabled + if (isDynamicResolutionEnabled && + frameTimeWatcher.Advance(frameStopwatch.ElapsedTicks, ref this.targetResolutionScale)) + { + this.isResizePending = true; + } + + frameStopwatch.Restart(); + + this.OnResize(); + this.OnUpdate(renderStopwatch.Elapsed); + this.OnPresent(); } - this.isCancellationRequested = false; - this.renderThread = new Thread(static args => ExecuteRenderLoop((ComputeShaderPanel)args!)); - this.renderThread.Start(this); + renderStopwatch.Stop(); + } + + /// + /// Starts the current render loop. + /// + public void StartRenderLoop(IShaderRunner shaderRunner) + { + this.isDynamicResolutionEnabled = false; + + ThrowIfDisposed(); + + Guard.IsNotNull(shaderRunner, nameof(shaderRunner)); + + lock (this.renderLock) + { + this.renderCancellationTokenSource?.Cancel(); + this.renderThread?.Join(); + + Thread newRenderThread = new(static args => ((SwapChainManager)args!).RenderLoop()); + + this.shaderRunner = shaderRunner; + this.renderCancellationTokenSource = new CancellationTokenSource(); + this.renderThread = newRenderThread; + + newRenderThread.Start(this); + } } /// /// Stops the current render loop, if one is running. /// - private void OnStopRenderLoop() + public void StopRenderLoop() { - this.isCancellationRequested = true; + ThrowIfDisposed(); + + lock (this.renderLock) + { + this.renderCancellationTokenSource?.Cancel(); + } } /// - /// Stops the current render loop, and releases all resources. + /// Queues a resize operation. /// - private void OnDisposed() + /// The width of the render resolution. + /// The height of the render resolution. + public void QueueResize(double width, double height) { - this.isCancellationRequested = true; + this.width = (float)width; + this.height = (float)height; + this.isResizePending = true; + } + + /// + /// Queues a change in the composition scale factors. + /// + /// The composition scale on the X axis. + /// The composition scale on the Y axis + public void QueueCompositionScaleChange(double compositionScaleX, double compositionScaleY) + { + this.compositionScaleX = (float)compositionScaleX; + this.compositionScaleY = (float)compositionScaleY; + + this.isResizePending = true; + } + + /// + /// Queues a change in the resolution scale factor. + /// + /// The resolution scale factor to use. + public void QueueResolutionScaleChange(double resolutionScale) + { + this.resolutionScale = (float)resolutionScale; + this.targetResolutionScale = (float)resolutionScale; + + this.isResizePending = true; + } + + /// + protected override void OnDispose() + { // Ensure the rendering has stopped - if (this.renderThread is Thread renderThread) + lock (this.renderLock) { - renderThread.Join(); + this.renderCancellationTokenSource?.Cancel(); + this.renderThread?.Join(); } this.d3D12Device.Dispose(); From e831cac33b9b504b39f92e979f35709818cfecee Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 2 Jan 2022 15:04:49 +0100 Subject: [PATCH 05/12] Fix incorrect signaling during presenting --- .../Helpers/SwapChainManager.cs | 23 +++++++++++-------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs index 5ecc8383..64ef76d0 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs @@ -46,7 +46,7 @@ internal sealed unsafe class SwapChainManager : NativeObject /// /// The next fence value for graphics operations using . /// - private ulong nextD3D12FenceValue = 1; + private ulong nextD3D12FenceValue; /// /// The object to create command lists. @@ -275,12 +275,12 @@ internal sealed unsafe class SwapChainManager : NativeObject /// private unsafe void ApplyResize() { - this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), this.nextD3D12FenceValue).Assert(); + ulong updatedFenceValue = ++this.nextD3D12FenceValue; + + this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), updatedFenceValue).Assert(); // Wait for the fence again to ensure there are no pending operations - this.d3D12Fence.Get()->SetEventOnCompletion(this.nextD3D12FenceValue, default).Assert(); - - this.nextD3D12FenceValue++; + this.d3D12Fence.Get()->SetEventOnCompletion(updatedFenceValue, default).Assert(); // Dispose the old buffers before resizing the buffer this.d3D12Resource0.Dispose(); @@ -413,17 +413,20 @@ internal sealed unsafe class SwapChainManager : NativeObject // Execute the command list to perform the copy this.d3D12CommandQueue.Get()->ExecuteCommandLists(1, (ID3D12CommandList**)this.d3D12GraphicsCommandList.GetAddressOf()); - this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), this.nextD3D12FenceValue).Assert(); + + // Increment the fence value and signal the fence. Just like with normal dispatches, + // the increment must be done after executing the command list and before signaling. + ulong updatedFenceValue = ++this.nextD3D12FenceValue; + + this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), updatedFenceValue).Assert(); // Present the new frame this.dxgiSwapChain3.Get()->Present(0, 0).Assert(); - if (this.nextD3D12FenceValue > this.d3D12Fence.Get()->GetCompletedValue()) + if (updatedFenceValue > this.d3D12Fence.Get()->GetCompletedValue()) { - this.d3D12Fence.Get()->SetEventOnCompletion(this.nextD3D12FenceValue, default).Assert(); + this.d3D12Fence.Get()->SetEventOnCompletion(updatedFenceValue, default).Assert(); } - - this.nextD3D12FenceValue++; } /// From daf126d50eb86c8bc4b4ffbbd6b785d42b6fd854 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 2 Jan 2022 18:51:17 +0100 Subject: [PATCH 06/12] Separate support for dynamic resolution --- .../Controls/ComputeShaderPanel.Properties.cs | 2 + .../Controls/ComputeShaderPanel.cs | 1 + .../Helpers/DynamicResolutionManager.cs | 7 +- .../Helpers/SwapChainManager.cs | 117 ++++++++++++++---- 4 files changed, 96 insertions(+), 31 deletions(-) diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs index f7c134fb..01ea621d 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs +++ b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs @@ -103,6 +103,8 @@ partial class ComputeShaderPanel { var @this = (ComputeShaderPanel)d; var isDynamicResolutionEnabled = (bool)e.NewValue; + + @this.swapChainManager.QueueDynamicResolutionModeChange(isDynamicResolutionEnabled); } /// diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs index 6ba8eff5..9b2ebb8f 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs +++ b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs @@ -54,6 +54,7 @@ public sealed partial class ComputeShaderPanel : SwapChainPanel this.swapChainManager.QueueResize(ActualWidth, ActualHeight); this.swapChainManager.QueueCompositionScaleChange(CompositionScaleX, CompositionScaleY); this.swapChainManager.QueueResolutionScaleChange(ResolutionScale); + this.swapChainManager.QueueDynamicResolutionModeChange(IsDynamicResolutionEnabled); if (ShaderRunner is IShaderRunner shaderRunner) { diff --git a/src/ComputeSharp.UI/Helpers/DynamicResolutionManager.cs b/src/ComputeSharp.UI/Helpers/DynamicResolutionManager.cs index 26b9004e..cfbbc869 100644 --- a/src/ComputeSharp.UI/Helpers/DynamicResolutionManager.cs +++ b/src/ComputeSharp.UI/Helpers/DynamicResolutionManager.cs @@ -118,10 +118,9 @@ internal unsafe ref struct DynamicResolutionManager if (averageFrameTimeInTicks is < LowerFrameTimeThresholdInTicksFor60fps or > UpperFrameTimeThresholdInTicksFor60fps) { - float - frameTimeDelta = (TargetFrameTimeInTicksFor60fps - averageFrameTimeInTicks) / (float)averageFrameTimeInTicks, - scaleFactorDelta = scaleFactor * frameTimeDelta * ScaleFactorDeltaK, - updatedScaleFactor = Math.Clamp(scaleFactor + scaleFactorDelta, 0.10f, 1.0f); + float frameTimeDelta = (TargetFrameTimeInTicksFor60fps - averageFrameTimeInTicks) / (float)averageFrameTimeInTicks; + float scaleFactorDelta = scaleFactor * frameTimeDelta * ScaleFactorDeltaK; + float updatedScaleFactor = Math.Clamp(scaleFactor + scaleFactorDelta, 0.10f, 1.0f); // Apply the scale factor update if the target scale has changed enough. This helps to avoid // too frequence resolution changes if the scale factor only changes very little every time. diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs index 64ef76d0..ae019d43 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs @@ -429,19 +429,33 @@ internal sealed unsafe class SwapChainManager : NativeObject } } + /// + /// Selects the right render loop to start. + /// + private void SwitchAndStartRenderLoop() + { + if (this.isDynamicResolutionEnabled) + { + this.targetResolutionScale = 1.0f; + + RenderLoopWithDynamicResolution(); + } + else + { + this.targetResolutionScale = this.resolutionScale; + + RenderLoop(); + } + } + /// /// The core render loop. /// private void RenderLoop() { Stopwatch renderStopwatch = this.renderStopwatch ??= new(); - Stopwatch frameStopwatch = Stopwatch.StartNew(); CancellationToken cancellationToken = this.renderCancellationTokenSource!.Token; - DynamicResolutionManager.Create(out DynamicResolutionManager frameTimeWatcher); - - bool isDynamicResolutionEnabled = this.isDynamicResolutionEnabled; - // Start the initial frame separately, before the timer starts. This ensures that // resuming after a pause correctly renders the first frame at the right time. this.OnResize(); @@ -453,24 +467,38 @@ internal sealed unsafe class SwapChainManager : NativeObject // Main render loop, until cancellation is requested while (!cancellationToken.IsCancellationRequested) { - // Update the resolution mode, if needed - if (isDynamicResolutionEnabled != this.isDynamicResolutionEnabled) - { - isDynamicResolutionEnabled = !isDynamicResolutionEnabled; + this.OnResize(); + this.OnUpdate(renderStopwatch.Elapsed); + this.OnPresent(); + } - if (isDynamicResolutionEnabled) - { - DynamicResolutionManager.Create(out frameTimeWatcher); - } - else - { - this.targetResolutionScale = this.resolutionScale; - } - } + renderStopwatch.Stop(); + } + /// + /// The core render loop with dynamic resolution. + /// + private void RenderLoopWithDynamicResolution() + { + Stopwatch renderStopwatch = this.renderStopwatch ??= new(); + Stopwatch frameStopwatch = Stopwatch.StartNew(); + CancellationToken cancellationToken = this.renderCancellationTokenSource!.Token; + + DynamicResolutionManager.Create(out DynamicResolutionManager frameTimeWatcher); + + // Start the initial frame separately, before the timer starts. This ensures that + // resuming after a pause correctly renders the first frame at the right time. + this.OnResize(); + this.OnUpdate(renderStopwatch.Elapsed); + this.OnPresent(); + + renderStopwatch.Start(); + + // Main render loop, until cancellation is requested + while (!cancellationToken.IsCancellationRequested) + { // Evaluate the dynamic resolution frame time step, if the mode is enabled - if (isDynamicResolutionEnabled && - frameTimeWatcher.Advance(frameStopwatch.ElapsedTicks, ref this.targetResolutionScale)) + if (frameTimeWatcher.Advance(frameStopwatch.ElapsedTicks, ref this.targetResolutionScale)) { this.isResizePending = true; } @@ -488,10 +516,9 @@ internal sealed unsafe class SwapChainManager : NativeObject /// /// Starts the current render loop. /// + /// The instance to use to render frames. public void StartRenderLoop(IShaderRunner shaderRunner) { - this.isDynamicResolutionEnabled = false; - ThrowIfDisposed(); Guard.IsNotNull(shaderRunner, nameof(shaderRunner)); @@ -501,7 +528,7 @@ internal sealed unsafe class SwapChainManager : NativeObject this.renderCancellationTokenSource?.Cancel(); this.renderThread?.Join(); - Thread newRenderThread = new(static args => ((SwapChainManager)args!).RenderLoop()); + Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop()); this.shaderRunner = shaderRunner; this.renderCancellationTokenSource = new CancellationTokenSource(); @@ -512,15 +539,33 @@ internal sealed unsafe class SwapChainManager : NativeObject } /// - /// Stops the current render loop, if one is running. + /// Queues a change in the dynamic resolution mode. /// - public void StopRenderLoop() + /// Whether or not to use dynamic resolution. + public void QueueDynamicResolutionModeChange(bool isDynamicResolutionEnabled) { ThrowIfDisposed(); lock (this.renderLock) { - this.renderCancellationTokenSource?.Cancel(); + // If there is a render thread currently running, stop it and restart it + if (this.renderCancellationTokenSource?.IsCancellationRequested == false) + { + this.renderCancellationTokenSource?.Cancel(); + this.renderThread?.Join(); + + Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop()); + + this.renderCancellationTokenSource = new CancellationTokenSource(); + this.renderThread = newRenderThread; + this.isDynamicResolutionEnabled = isDynamicResolutionEnabled; + + newRenderThread.Start(this); + } + else + { + this.isDynamicResolutionEnabled = isDynamicResolutionEnabled; + } } } @@ -531,6 +576,8 @@ internal sealed unsafe class SwapChainManager : NativeObject /// The height of the render resolution. public void QueueResize(double width, double height) { + ThrowIfDisposed(); + this.width = (float)width; this.height = (float)height; @@ -544,6 +591,8 @@ internal sealed unsafe class SwapChainManager : NativeObject /// The composition scale on the Y axis public void QueueCompositionScaleChange(double compositionScaleX, double compositionScaleY) { + ThrowIfDisposed(); + this.compositionScaleX = (float)compositionScaleX; this.compositionScaleY = (float)compositionScaleY; @@ -556,12 +605,26 @@ internal sealed unsafe class SwapChainManager : NativeObject /// The resolution scale factor to use. public void QueueResolutionScaleChange(double resolutionScale) { + ThrowIfDisposed(); + this.resolutionScale = (float)resolutionScale; - this.targetResolutionScale = (float)resolutionScale; this.isResizePending = true; } + /// + /// Stops the current render loop, if one is running. + /// + public void StopRenderLoop() + { + ThrowIfDisposed(); + + lock (this.renderLock) + { + this.renderCancellationTokenSource?.Cancel(); + } + } + /// protected override void OnDispose() { From 056e50d89941809161b1332b03130889286a7e75 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 2 Jan 2022 19:03:46 +0100 Subject: [PATCH 07/12] Code refactoring to SwapChainManager --- src/ComputeSharp.UI/ComputeSharp.UI.projitems | 1 + .../Helpers/SwapChainManager.Rendering.cs | 254 ++++++++++++++++++ .../Helpers/SwapChainManager.cs | 243 +---------------- 3 files changed, 259 insertions(+), 239 deletions(-) create mode 100644 src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs diff --git a/src/ComputeSharp.UI/ComputeSharp.UI.projitems b/src/ComputeSharp.UI/ComputeSharp.UI.projitems index 571ddce3..c990a06c 100644 --- a/src/ComputeSharp.UI/ComputeSharp.UI.projitems +++ b/src/ComputeSharp.UI/ComputeSharp.UI.projitems @@ -11,6 +11,7 @@ + diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs new file mode 100644 index 00000000..a66a70e9 --- /dev/null +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs @@ -0,0 +1,254 @@ +using System; +using System.Diagnostics; +using System.Threading; +using Microsoft.Toolkit.Diagnostics; + +#pragma warning disable CS0420 + +#if WINDOWS_UWP +namespace ComputeSharp.Uwp.Helpers; +#else +namespace ComputeSharp.WinUI.Helpers; +#endif + +/// +partial class SwapChainManager +{ + /// + /// Starts the current render loop. + /// + /// The instance to use to render frames. + public void StartRenderLoop(IShaderRunner shaderRunner) + { + ThrowIfDisposed(); + + Guard.IsNotNull(shaderRunner, nameof(shaderRunner)); + + lock (this.renderLock) + { + this.renderCancellationTokenSource?.Cancel(); + this.renderThread?.Join(); + + Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop()); + + this.shaderRunner = shaderRunner; + this.renderCancellationTokenSource = new CancellationTokenSource(); + this.renderThread = newRenderThread; + + newRenderThread.Start(this); + } + } + + /// + /// Stops the current render loop, if one is running. + /// + public void StopRenderLoop() + { + ThrowIfDisposed(); + + lock (this.renderLock) + { + this.renderCancellationTokenSource?.Cancel(); + this.renderThread?.Join(); + } + } + + /// + /// Queues a change in the dynamic resolution mode. + /// + /// Whether or not to use dynamic resolution. + public void QueueDynamicResolutionModeChange(bool isDynamicResolutionEnabled) + { + ThrowIfDisposed(); + + lock (this.renderLock) + { + // If there is a render thread currently running, stop it and restart it + if (this.renderCancellationTokenSource?.IsCancellationRequested == false) + { + this.renderCancellationTokenSource?.Cancel(); + this.renderThread?.Join(); + + Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop()); + + this.renderCancellationTokenSource = new CancellationTokenSource(); + this.renderThread = newRenderThread; + this.isDynamicResolutionEnabled = isDynamicResolutionEnabled; + + newRenderThread.Start(this); + } + else + { + this.isDynamicResolutionEnabled = isDynamicResolutionEnabled; + } + } + } + + /// + /// Queues a resize operation. + /// + /// The width of the render resolution. + /// The height of the render resolution. + public void QueueResize(double width, double height) + { + ThrowIfDisposed(); + + this.width = (float)width; + this.height = (float)height; + + this.isResizePending = true; + } + + /// + /// Queues a change in the composition scale factors. + /// + /// The composition scale on the X axis. + /// The composition scale on the Y axis + public void QueueCompositionScaleChange(double compositionScaleX, double compositionScaleY) + { + ThrowIfDisposed(); + + this.compositionScaleX = (float)compositionScaleX; + this.compositionScaleY = (float)compositionScaleY; + + this.isResizePending = true; + } + + /// + /// Queues a change in the resolution scale factor. + /// + /// The resolution scale factor to use. + public void QueueResolutionScaleChange(double resolutionScale) + { + ThrowIfDisposed(); + + this.resolutionScale = (float)resolutionScale; + + this.isResizePending = true; + } + + /// + /// Selects the right render loop to start. + /// + private void SwitchAndStartRenderLoop() + { + if (this.isDynamicResolutionEnabled) + { + this.targetResolutionScale = 1.0f; + + RenderLoopWithDynamicResolution(); + } + else + { + this.targetResolutionScale = this.resolutionScale; + + RenderLoop(); + } + } + + /// + /// The core render loop. + /// + private void RenderLoop() + { + Stopwatch renderStopwatch = this.renderStopwatch ??= new(); + CancellationToken cancellationToken = this.renderCancellationTokenSource!.Token; + + // Start the initial frame separately, before the timer starts. This ensures that + // resuming after a pause correctly renders the first frame at the right time. + this.OnResize(); + this.OnUpdate(renderStopwatch.Elapsed); + this.OnPresent(); + + renderStopwatch.Start(); + + // Main render loop, until cancellation is requested + while (!cancellationToken.IsCancellationRequested) + { + this.OnResize(); + this.OnUpdate(renderStopwatch.Elapsed); + this.OnPresent(); + } + + renderStopwatch.Stop(); + } + + /// + /// The core render loop with dynamic resolution. + /// + private void RenderLoopWithDynamicResolution() + { + Stopwatch renderStopwatch = this.renderStopwatch ??= new(); + Stopwatch frameStopwatch = Stopwatch.StartNew(); + CancellationToken cancellationToken = this.renderCancellationTokenSource!.Token; + + DynamicResolutionManager.Create(out DynamicResolutionManager frameTimeWatcher); + + // Start the initial frame separately, before the timer starts. This ensures that + // resuming after a pause correctly renders the first frame at the right time. + this.OnResize(); + this.OnUpdate(renderStopwatch.Elapsed); + this.OnPresent(); + + renderStopwatch.Start(); + + // Main render loop, until cancellation is requested + while (!cancellationToken.IsCancellationRequested) + { + // Evaluate the dynamic resolution frame time step, if the mode is enabled + if (frameTimeWatcher.Advance(frameStopwatch.ElapsedTicks, ref this.targetResolutionScale)) + { + this.isResizePending = true; + } + + frameStopwatch.Restart(); + + this.OnResize(); + this.OnUpdate(renderStopwatch.Elapsed); + this.OnPresent(); + } + + renderStopwatch.Stop(); + } + + /// + /// Resizes the current application, if needed. + /// + private void OnResize() + { + if (this.isResizePending) + { + ApplyResize(); + + this.isResizePending = false; + } + } + + /// + /// Updates the render resolution, if needed, and renders a new frame. + /// + /// The current time since the start of the application. + private void OnUpdate(TimeSpan time) + { + this.shaderRunner!.Execute(this.texture!, time); + } + + /// + /// Presents the last rendered frame for the current application. + /// + private unsafe partial void OnPresent(); + + /// + /// Stops the current render loop, if one is running, and waits for it. + /// + /// This method doesn't check for disposal. + private void UnsafeStopRenderLoopAndWait() + { + ThrowIfDisposed(); + + lock (this.renderLock) + { + this.renderCancellationTokenSource?.Cancel(); + } + } +} diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs index ae019d43..8e2a3ea4 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs @@ -4,14 +4,11 @@ using System.Threading; using ComputeSharp.Core.Extensions; using ComputeSharp.Graphics.Helpers; using ComputeSharp.Interop; -using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using TerraFX.Interop.WinRT; using Win32 = TerraFX.Interop.Windows.Windows; -#pragma warning disable CS0420 - #if WINDOWS_UWP namespace ComputeSharp.Uwp.Helpers; #else @@ -21,7 +18,7 @@ namespace ComputeSharp.WinUI.Helpers; /// /// A type managing rendering on a target swap chain object. /// -internal sealed unsafe class SwapChainManager : NativeObject +internal sealed unsafe partial class SwapChainManager : NativeObject { /// /// A lock object for the render loops. @@ -322,39 +319,8 @@ internal sealed unsafe class SwapChainManager : NativeObject (int)d3D12Resource0Description.Height); } - /// - /// Resizes the current application, if needed. - /// - private void OnResize() - { - if (this.isResizePending) - { - ApplyResize(); - - this.isResizePending = false; - } - } - - /// - /// Updates the render resolution, if needed, and renders a new frame. - /// - /// The current time since the start of the application. - private void OnUpdate(TimeSpan time) - { - // Skip if no factory is available - if (this.shaderRunner is null) - { - return; - } - - // Generate the new frame - this.shaderRunner.Execute(this.texture!, time); - } - - /// - /// Presents the last rendered frame for the current application. - /// - private unsafe void OnPresent() + /// + private unsafe partial void OnPresent() { // Wait for the swap chain to be ready for presenting _ = Win32.WaitForSingleObjectEx(frameLatencyWaitableObject, 1000, true); @@ -429,211 +395,10 @@ internal sealed unsafe class SwapChainManager : NativeObject } } - /// - /// Selects the right render loop to start. - /// - private void SwitchAndStartRenderLoop() - { - if (this.isDynamicResolutionEnabled) - { - this.targetResolutionScale = 1.0f; - - RenderLoopWithDynamicResolution(); - } - else - { - this.targetResolutionScale = this.resolutionScale; - - RenderLoop(); - } - } - - /// - /// The core render loop. - /// - private void RenderLoop() - { - Stopwatch renderStopwatch = this.renderStopwatch ??= new(); - CancellationToken cancellationToken = this.renderCancellationTokenSource!.Token; - - // Start the initial frame separately, before the timer starts. This ensures that - // resuming after a pause correctly renders the first frame at the right time. - this.OnResize(); - this.OnUpdate(renderStopwatch.Elapsed); - this.OnPresent(); - - renderStopwatch.Start(); - - // Main render loop, until cancellation is requested - while (!cancellationToken.IsCancellationRequested) - { - this.OnResize(); - this.OnUpdate(renderStopwatch.Elapsed); - this.OnPresent(); - } - - renderStopwatch.Stop(); - } - - /// - /// The core render loop with dynamic resolution. - /// - private void RenderLoopWithDynamicResolution() - { - Stopwatch renderStopwatch = this.renderStopwatch ??= new(); - Stopwatch frameStopwatch = Stopwatch.StartNew(); - CancellationToken cancellationToken = this.renderCancellationTokenSource!.Token; - - DynamicResolutionManager.Create(out DynamicResolutionManager frameTimeWatcher); - - // Start the initial frame separately, before the timer starts. This ensures that - // resuming after a pause correctly renders the first frame at the right time. - this.OnResize(); - this.OnUpdate(renderStopwatch.Elapsed); - this.OnPresent(); - - renderStopwatch.Start(); - - // Main render loop, until cancellation is requested - while (!cancellationToken.IsCancellationRequested) - { - // Evaluate the dynamic resolution frame time step, if the mode is enabled - if (frameTimeWatcher.Advance(frameStopwatch.ElapsedTicks, ref this.targetResolutionScale)) - { - this.isResizePending = true; - } - - frameStopwatch.Restart(); - - this.OnResize(); - this.OnUpdate(renderStopwatch.Elapsed); - this.OnPresent(); - } - - renderStopwatch.Stop(); - } - - /// - /// Starts the current render loop. - /// - /// The instance to use to render frames. - public void StartRenderLoop(IShaderRunner shaderRunner) - { - ThrowIfDisposed(); - - Guard.IsNotNull(shaderRunner, nameof(shaderRunner)); - - lock (this.renderLock) - { - this.renderCancellationTokenSource?.Cancel(); - this.renderThread?.Join(); - - Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop()); - - this.shaderRunner = shaderRunner; - this.renderCancellationTokenSource = new CancellationTokenSource(); - this.renderThread = newRenderThread; - - newRenderThread.Start(this); - } - } - - /// - /// Queues a change in the dynamic resolution mode. - /// - /// Whether or not to use dynamic resolution. - public void QueueDynamicResolutionModeChange(bool isDynamicResolutionEnabled) - { - ThrowIfDisposed(); - - lock (this.renderLock) - { - // If there is a render thread currently running, stop it and restart it - if (this.renderCancellationTokenSource?.IsCancellationRequested == false) - { - this.renderCancellationTokenSource?.Cancel(); - this.renderThread?.Join(); - - Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop()); - - this.renderCancellationTokenSource = new CancellationTokenSource(); - this.renderThread = newRenderThread; - this.isDynamicResolutionEnabled = isDynamicResolutionEnabled; - - newRenderThread.Start(this); - } - else - { - this.isDynamicResolutionEnabled = isDynamicResolutionEnabled; - } - } - } - - /// - /// Queues a resize operation. - /// - /// The width of the render resolution. - /// The height of the render resolution. - public void QueueResize(double width, double height) - { - ThrowIfDisposed(); - - this.width = (float)width; - this.height = (float)height; - - this.isResizePending = true; - } - - /// - /// Queues a change in the composition scale factors. - /// - /// The composition scale on the X axis. - /// The composition scale on the Y axis - public void QueueCompositionScaleChange(double compositionScaleX, double compositionScaleY) - { - ThrowIfDisposed(); - - this.compositionScaleX = (float)compositionScaleX; - this.compositionScaleY = (float)compositionScaleY; - - this.isResizePending = true; - } - - /// - /// Queues a change in the resolution scale factor. - /// - /// The resolution scale factor to use. - public void QueueResolutionScaleChange(double resolutionScale) - { - ThrowIfDisposed(); - - this.resolutionScale = (float)resolutionScale; - - this.isResizePending = true; - } - - /// - /// Stops the current render loop, if one is running. - /// - public void StopRenderLoop() - { - ThrowIfDisposed(); - - lock (this.renderLock) - { - this.renderCancellationTokenSource?.Cancel(); - } - } - /// protected override void OnDispose() { - // Ensure the rendering has stopped - lock (this.renderLock) - { - this.renderCancellationTokenSource?.Cancel(); - this.renderThread?.Join(); - } + UnsafeStopRenderLoopAndWait(); this.d3D12Device.Dispose(); this.d3D12CommandQueue.Dispose(); From 28a4ad3b4829ebfacca6cf492c8b08dde8f0f628 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 2 Jan 2022 19:22:03 +0100 Subject: [PATCH 08/12] Add parameter to IShaderRunner --- .../Shaders/Runners/ContouredLayersRunner.cs | 2 +- .../Helpers/SwapChainManager.Rendering.cs | 2 +- src/ComputeSharp.UI/IShaderRunner.cs | 3 +- src/ComputeSharp.UI/ShaderRunner{T}.cs | 39 +++++++++++++++---- 4 files changed, 36 insertions(+), 10 deletions(-) diff --git a/samples/ComputeSharp.SwapChain.Core.Shared/Shaders/Runners/ContouredLayersRunner.cs b/samples/ComputeSharp.SwapChain.Core.Shared/Shaders/Runners/ContouredLayersRunner.cs index a3d18eb4..2aa1a353 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 void Execute(IReadWriteTexture2D texture, TimeSpan timespan) + public void Execute(IReadWriteTexture2D texture, TimeSpan timespan, object? parameter) { if (this.texture is null) { diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs index a66a70e9..f8b75f6d 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs @@ -230,7 +230,7 @@ partial class SwapChainManager /// The current time since the start of the application. private void OnUpdate(TimeSpan time) { - this.shaderRunner!.Execute(this.texture!, time); + this.shaderRunner!.Execute(this.texture!, time, null); } /// diff --git a/src/ComputeSharp.UI/IShaderRunner.cs b/src/ComputeSharp.UI/IShaderRunner.cs index c681b68b..a3c5aca3 100644 --- a/src/ComputeSharp.UI/IShaderRunner.cs +++ b/src/ComputeSharp.UI/IShaderRunner.cs @@ -16,5 +16,6 @@ public interface IShaderRunner /// /// The target texture to render the frame to. /// The timespan for the current frame. - public void Execute(IReadWriteTexture2D texture, TimeSpan timespan); + /// The input parameter for the frame being rendered. + void Execute(IReadWriteTexture2D texture, TimeSpan timespan, object? parameter); } diff --git a/src/ComputeSharp.UI/ShaderRunner{T}.cs b/src/ComputeSharp.UI/ShaderRunner{T}.cs index 370089d6..e1d43722 100644 --- a/src/ComputeSharp.UI/ShaderRunner{T}.cs +++ b/src/ComputeSharp.UI/ShaderRunner{T}.cs @@ -1,4 +1,5 @@ using System; +using Microsoft.Toolkit.Diagnostics; #if WINDOWS_UWP namespace ComputeSharp.Uwp; @@ -14,9 +15,14 @@ public sealed class ShaderRunner : IShaderRunner where T : struct, IPixelShader { /// - /// The instance used to create shaders to run. + /// The instance used to create shaders to run. /// - private readonly Func shaderFactory; + private readonly Func? shaderFactory; + + /// + /// The instance used to create shaders to run. + /// + private readonly Func? statefulShaderFactory; /// /// Creates a new instance that will create shader instances with @@ -25,21 +31,40 @@ public sealed class ShaderRunner : IShaderRunner /// public ShaderRunner() { - this.shaderFactory = static _ => default; } /// /// Creates a new instance. /// - /// The instance used to create shaders to run. + /// The instance used to create shaders to run. public ShaderRunner(Func shaderFactory) { + Guard.IsNotNull(shaderFactory, nameof(shaderFactory)); + this.shaderFactory = shaderFactory; } - /// - public void Execute(IReadWriteTexture2D texture, TimeSpan time) + /// + /// Creates a new instance. + /// + /// The instance used to create shaders to run. + public ShaderRunner(Func shaderFactory) { - GraphicsDevice.Default.ForEach(texture, this.shaderFactory(time)); + Guard.IsNotNull(shaderFactory, nameof(shaderFactory)); + + this.statefulShaderFactory = shaderFactory; + } + + /// + public void Execute(IReadWriteTexture2D texture, TimeSpan time, object? parameter) + { + if (this.shaderFactory is Func shaderFactory) + { + GraphicsDevice.Default.ForEach(texture, this.shaderFactory(time)); + } + else + { + GraphicsDevice.Default.ForEach(texture, this.statefulShaderFactory!(time, parameter)); + } } } From 22d429d101d59b9a970610fbe249193e61343190 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 2 Jan 2022 19:35:20 +0100 Subject: [PATCH 09/12] Add initial version of IFrameRequestQueue --- src/ComputeSharp.UI/ComputeSharp.UI.projitems | 1 + .../Controls/ComputeShaderPanel.Properties.cs | 36 ++++++- .../Controls/ComputeShaderPanel.cs | 2 +- .../Helpers/SwapChainManager.Rendering.cs | 96 +++++++++++++++---- .../Helpers/SwapChainManager.cs | 5 + src/ComputeSharp.UI/IFrameRequestQueue.cs | 20 ++++ 6 files changed, 138 insertions(+), 22 deletions(-) create mode 100644 src/ComputeSharp.UI/IFrameRequestQueue.cs diff --git a/src/ComputeSharp.UI/ComputeSharp.UI.projitems b/src/ComputeSharp.UI/ComputeSharp.UI.projitems index c990a06c..200af187 100644 --- a/src/ComputeSharp.UI/ComputeSharp.UI.projitems +++ b/src/ComputeSharp.UI/ComputeSharp.UI.projitems @@ -14,6 +14,7 @@ + diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs index 01ea621d..04939c0d 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs +++ b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs @@ -14,6 +14,38 @@ namespace ComputeSharp.WinUI; /// partial class ComputeShaderPanel { + /// + /// Gets or sets the instance to use to request new frames. + /// + public IFrameRequestQueue? FrameRequestQueue + { + get => (IFrameRequestQueue)GetValue(FrameRequestQueueProperty); + set => SetValue(FrameRequestQueueProperty, value); + } + + /// + /// The backing . + /// + public static readonly DependencyProperty FrameRequestQueueProperty = DependencyProperty.Register( + nameof(FrameRequestQueue), + typeof(IFrameRequestQueue), + typeof(ComputeShaderPanel), + new PropertyMetadata(null, OnFrameRequestQueueChanged)); + + /// + private static void OnFrameRequestQueueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var @this = (ComputeShaderPanel)d; + var frameRequestQueue = (IFrameRequestQueue?)e.NewValue; + + if (@this.IsLoaded && + !@this.IsPaused && + @this.ShaderRunner is IShaderRunner shaderRunner) + { + @this.swapChainManager.StartRenderLoop(frameRequestQueue, shaderRunner); + } + } + /// /// Gets or sets the instance to use to render content. /// @@ -45,7 +77,7 @@ partial class ComputeShaderPanel else if (@this.IsLoaded && !@this.IsPaused) { - @this.swapChainManager.StartRenderLoop(shaderRunner); + @this.swapChainManager.StartRenderLoop(@this.FrameRequestQueue, shaderRunner); } } @@ -138,7 +170,7 @@ partial class ComputeShaderPanel else if (@this.IsLoaded && @this.ShaderRunner is IShaderRunner shaderRunner) { - @this.swapChainManager.StartRenderLoop(shaderRunner); + @this.swapChainManager.StartRenderLoop(@this.FrameRequestQueue, shaderRunner); } } } diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs index 9b2ebb8f..13bc5a40 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs +++ b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs @@ -58,7 +58,7 @@ public sealed partial class ComputeShaderPanel : SwapChainPanel if (ShaderRunner is IShaderRunner shaderRunner) { - this.swapChainManager.StartRenderLoop(shaderRunner); + this.swapChainManager.StartRenderLoop(FrameRequestQueue, shaderRunner); } } diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs index f8b75f6d..fd265119 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs @@ -1,5 +1,6 @@ using System; using System.Diagnostics; +using System.Runtime.CompilerServices; using System.Threading; using Microsoft.Toolkit.Diagnostics; @@ -17,8 +18,9 @@ partial class SwapChainManager /// /// Starts the current render loop. /// + /// The instance to use, if available. /// The instance to use to render frames. - public void StartRenderLoop(IShaderRunner shaderRunner) + public void StartRenderLoop(IFrameRequestQueue? frameRequestQueue, IShaderRunner shaderRunner) { ThrowIfDisposed(); @@ -31,6 +33,7 @@ partial class SwapChainManager Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop()); + this.frameRequestQueue = frameRequestQueue; this.shaderRunner = shaderRunner; this.renderCancellationTokenSource = new CancellationTokenSource(); this.renderThread = newRenderThread; @@ -154,20 +157,30 @@ partial class SwapChainManager Stopwatch renderStopwatch = this.renderStopwatch ??= new(); CancellationToken cancellationToken = this.renderCancellationTokenSource!.Token; + if (!OnFrameRequest(out object? parameter, cancellationToken)) + { + return; + } + // Start the initial frame separately, before the timer starts. This ensures that // resuming after a pause correctly renders the first frame at the right time. - this.OnResize(); - this.OnUpdate(renderStopwatch.Elapsed); - this.OnPresent(); + OnResize(); + OnUpdate(renderStopwatch.Elapsed, parameter); + OnPresent(); renderStopwatch.Start(); // Main render loop, until cancellation is requested while (!cancellationToken.IsCancellationRequested) { - this.OnResize(); - this.OnUpdate(renderStopwatch.Elapsed); - this.OnPresent(); + if (!OnFrameRequest(out parameter, cancellationToken)) + { + return; + } + + OnResize(); + OnUpdate(renderStopwatch.Elapsed, parameter); + OnPresent(); } renderStopwatch.Stop(); @@ -179,20 +192,23 @@ partial class SwapChainManager private void RenderLoopWithDynamicResolution() { Stopwatch renderStopwatch = this.renderStopwatch ??= new(); - Stopwatch frameStopwatch = Stopwatch.StartNew(); CancellationToken cancellationToken = this.renderCancellationTokenSource!.Token; DynamicResolutionManager.Create(out DynamicResolutionManager frameTimeWatcher); + + if (!OnFrameRequest(out object? parameter, cancellationToken)) + { + return; + } - // Start the initial frame separately, before the timer starts. This ensures that - // resuming after a pause correctly renders the first frame at the right time. - this.OnResize(); - this.OnUpdate(renderStopwatch.Elapsed); - this.OnPresent(); + Stopwatch frameStopwatch = Stopwatch.StartNew(); + + OnResize(); + OnUpdate(renderStopwatch.Elapsed, parameter); + OnPresent(); renderStopwatch.Start(); - // Main render loop, until cancellation is requested while (!cancellationToken.IsCancellationRequested) { // Evaluate the dynamic resolution frame time step, if the mode is enabled @@ -201,16 +217,57 @@ partial class SwapChainManager this.isResizePending = true; } + if (!OnFrameRequest(out parameter, cancellationToken)) + { + return; + } + frameStopwatch.Restart(); - this.OnResize(); - this.OnUpdate(renderStopwatch.Elapsed); - this.OnPresent(); + OnResize(); + OnUpdate(renderStopwatch.Elapsed, parameter); + OnPresent(); } renderStopwatch.Stop(); } + /// + /// Waits for a new frame request and retrieves its parameter. + /// + /// The input parameter for the frame to render. + /// A token to cancel waiting for a new frame. + /// Whether the operation was canceled. + private bool OnFrameRequest(out object? parameter, CancellationToken token) + { + if (this.frameRequestQueue is IFrameRequestQueue frameRequestQueue) + { + [MethodImpl(MethodImplOptions.NoInlining)] + static bool WaitForFrameRequest(IFrameRequestQueue frameRequestQueue, out object? parameter, CancellationToken token) + { + try + { + // Wait for a new frame request + frameRequestQueue.Dequeue(out parameter, token); + + return true; + } + catch (OperationCanceledException) + { + parameter = null; + + return false; + } + } + + return WaitForFrameRequest(frameRequestQueue, out parameter, token); + } + + parameter = null; + + return true; + } + /// /// Resizes the current application, if needed. /// @@ -228,9 +285,10 @@ partial class SwapChainManager /// Updates the render resolution, if needed, and renders a new frame. /// /// The current time since the start of the application. - private void OnUpdate(TimeSpan time) + /// The input parameter for the frame being rendered. + private void OnUpdate(TimeSpan time, object? parameter) { - this.shaderRunner!.Execute(this.texture!, time, null); + this.shaderRunner!.Execute(this.texture!, time, parameter); } /// diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs index 8e2a3ea4..80533ead 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs @@ -90,6 +90,11 @@ internal sealed unsafe partial class SwapChainManager : NativeObject /// private volatile CancellationTokenSource? renderCancellationTokenSource; + /// + /// The instance used to get frame requests and parameters. + /// + private volatile IFrameRequestQueue? frameRequestQueue; + /// /// The instance used to create shaders to run. /// diff --git a/src/ComputeSharp.UI/IFrameRequestQueue.cs b/src/ComputeSharp.UI/IFrameRequestQueue.cs new file mode 100644 index 00000000..41a1e719 --- /dev/null +++ b/src/ComputeSharp.UI/IFrameRequestQueue.cs @@ -0,0 +1,20 @@ +using System.Threading; + +#if WINDOWS_UWP +namespace ComputeSharp.Uwp; +#else +namespace ComputeSharp.WinUI; +#endif + +/// +/// An interface for a shader runner to be used with . +/// +public interface IFrameRequestQueue +{ + /// + /// Waits for a new frame request to be available, retrieving its parameter, if any. + /// + /// The input parameter for the frame to render. + /// A token to cancel waiting for a new frame. + void Dequeue(out object? parameter, CancellationToken token); +} From d11f524ade5673235a41e419030444d31673eab6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 2 Jan 2022 20:16:14 +0100 Subject: [PATCH 10/12] Add AnimatedComputeShaderPanel control --- .../Views/MainView.xaml | 4 +- .../Views/MainWindow.xaml | 4 +- src/ComputeSharp.UI/ComputeSharp.UI.projitems | 2 + .../AnimatedComputeShaderPanel.Properties.cs | 144 ++++++++++++++++++ .../Controls/AnimatedComputeShaderPanel.cs | 88 +++++++++++ .../Controls/ComputeShaderPanel.Properties.cs | 56 ++----- .../Controls/ComputeShaderPanel.cs | 10 +- 7 files changed, 258 insertions(+), 50 deletions(-) create mode 100644 src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.Properties.cs create mode 100644 src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs diff --git a/samples/ComputeSharp.SwapChain.Uwp/Views/MainView.xaml b/samples/ComputeSharp.SwapChain.Uwp/Views/MainView.xaml index fe94efd1..5b07b170 100644 --- a/samples/ComputeSharp.SwapChain.Uwp/Views/MainView.xaml +++ b/samples/ComputeSharp.SwapChain.Uwp/Views/MainView.xaml @@ -125,7 +125,7 @@ - + - - + - ComputeSharp.UI + + diff --git a/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.Properties.cs b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.Properties.cs new file mode 100644 index 00000000..9899e75f --- /dev/null +++ b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.Properties.cs @@ -0,0 +1,144 @@ +using System; +#if WINDOWS_UWP +using Windows.UI.Xaml; +#else +using Microsoft.UI.Xaml; +#endif + +#if WINDOWS_UWP +namespace ComputeSharp.Uwp; +#else +namespace ComputeSharp.WinUI; +#endif + +/// +partial class AnimatedComputeShaderPanel +{ + /// + /// Gets or sets the instance to use to render content. + /// + public IShaderRunner? ShaderRunner + { + get => (IShaderRunner?)GetValue(ShaderRunnerProperty); + set => SetValue(ShaderRunnerProperty, value); + } + + /// + /// The backing . + /// + public static readonly DependencyProperty ShaderRunnerProperty = DependencyProperty.Register( + nameof(ShaderRunner), + typeof(IShaderRunner), + typeof(AnimatedComputeShaderPanel), + new PropertyMetadata(null, OnShaderRunnerPropertyChanged)); + + /// + private static void OnShaderRunnerPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var @this = (AnimatedComputeShaderPanel)d; + + if (@this.IsLoaded && + !@this.IsPaused && + e.NewValue is IShaderRunner shaderRunner) + { + @this.swapChainManager.StartRenderLoop(null, shaderRunner); + } + else + { + @this.swapChainManager.StopRenderLoop(); + } + } + + /// + /// Gets or sets the resolution scale to be used to render frames. + /// This can help achieve higher framerates with more complex shaders. + /// + /// The accepted range is [0.1 and 1] (default is 1, exceeding values will be clamped). + public double ResolutionScale + { + get => (double)GetValue(ResolutionScaleProperty); + set => SetValue(ResolutionScaleProperty, Math.Clamp(value, 0.1, 1.0)); + } + + /// + /// The backing . + /// + public static readonly DependencyProperty ResolutionScaleProperty = DependencyProperty.Register( + nameof(ResolutionScale), + typeof(double), + typeof(AnimatedComputeShaderPanel), + new PropertyMetadata(1.0, OnResolutionScalePropertyChanged)); + + /// + private static void OnResolutionScalePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var @this = (AnimatedComputeShaderPanel)d; + var resolutionScale = (double)e.NewValue; + + @this.swapChainManager.QueueResolutionScaleChange(resolutionScale); + } + + /// + /// Gets or sets whether dynamic resolution is enabled. If it is, the internal render + /// resolution of the shader being run will be automatically adjusted to reach 60fps. + /// The default value for this property is . + /// + public bool IsDynamicResolutionEnabled + { + get => (bool)GetValue(IsDynamicResolutionEnabledProperty); + set => SetValue(IsDynamicResolutionEnabledProperty, value); + } + + /// + /// The backing . + /// + public static readonly DependencyProperty IsDynamicResolutionEnabledProperty = DependencyProperty.Register( + nameof(IsDynamicResolutionEnabled), + typeof(bool), + typeof(AnimatedComputeShaderPanel), + new PropertyMetadata(true, OnIsDynamicResolutionEnabledPropertyChanged)); + + /// + private static void OnIsDynamicResolutionEnabledPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var @this = (AnimatedComputeShaderPanel)d; + var isDynamicResolutionEnabled = (bool)e.NewValue; + + @this.swapChainManager.QueueDynamicResolutionModeChange(isDynamicResolutionEnabled); + } + + /// + /// Gets or sets whether or not the rendering is paused. + /// + public bool IsPaused + { + get => (bool)GetValue(IsPausedProperty); + set => SetValue(IsPausedProperty, value); + } + + /// + /// The backing . + /// + public static readonly DependencyProperty IsPausedProperty = DependencyProperty.Register( + nameof(IsPaused), + typeof(bool), + typeof(AnimatedComputeShaderPanel), + new PropertyMetadata(false, OnIsPausedPropertyChanged)); + + /// + private static void OnIsPausedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var @this = (AnimatedComputeShaderPanel)d; + + if (@this.IsLoaded && + (bool)e.NewValue is false && + @this.ShaderRunner is IShaderRunner shaderRunner) + { + @this.swapChainManager.StartRenderLoop(null, shaderRunner); + } + else + { + @this.swapChainManager.StopRenderLoop(); + } + } +} diff --git a/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs new file mode 100644 index 00000000..85c00936 --- /dev/null +++ b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs @@ -0,0 +1,88 @@ +#if WINDOWS_UWP +using System.Runtime.InteropServices; +using ComputeSharp.Uwp.Helpers; +using Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; +using TerraFX.Interop.Windows; +#else +using ComputeSharp.WinUI.Helpers; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using TerraFX.Interop.Windows; +using WinRT; +#endif + +#if WINDOWS_UWP +namespace ComputeSharp.Uwp; +#else +namespace ComputeSharp.WinUI; +#endif + +/// +/// +/// A custom that can be used to render animated backgrounds. +/// It is powered by ComputeSharp and leverages compute shaders to create frames to display. +/// +/// +/// This panel will always render new frames at the current display refresh rate, automatically. +/// +/// +public sealed partial class AnimatedComputeShaderPanel : SwapChainPanel +{ + /// + /// The instance handling rendering. + /// + private readonly SwapChainManager swapChainManager; + + /// + /// Creates a new instance. + /// + public unsafe AnimatedComputeShaderPanel() + { +#if WINDOWS_UWP + IUnknown* swapChainPanel = (IUnknown*)Marshal.GetIUnknownForObject(this); +#else + IUnknown* swapChainPanel = (IUnknown*)((IWinRTObject)this).NativeObject.ThisPtr; +#endif + + this.swapChainManager = new SwapChainManager(swapChainPanel); + + this.Loaded += AnimatedComputeShaderPanel_Loaded; + this.Unloaded += AnimatedComputeShaderPanel_Unloaded; + this.SizeChanged += AnimatedComputeShaderPanel_SizeChanged; + this.CompositionScaleChanged += AnimatedComputeShaderPanel_CompositionScaleChanged; + } + + // Initializes the swap chain and starts the render thread + private void AnimatedComputeShaderPanel_Loaded(object sender, RoutedEventArgs e) + { + this.swapChainManager.QueueResize(ActualWidth, ActualHeight); + this.swapChainManager.QueueCompositionScaleChange(CompositionScaleX, CompositionScaleY); + this.swapChainManager.QueueResolutionScaleChange(ResolutionScale); + this.swapChainManager.QueueDynamicResolutionModeChange(IsDynamicResolutionEnabled); + + if (!IsPaused && + ShaderRunner is IShaderRunner shaderRunner) + { + this.swapChainManager.StartRenderLoop(null, shaderRunner); + } + } + + // Requests a cancellation for the render thread + private void AnimatedComputeShaderPanel_Unloaded(object sender, RoutedEventArgs e) + { + this.swapChainManager.StopRenderLoop(); + } + + // Updates the background store for the frame size factors used by the render thread + private void AnimatedComputeShaderPanel_SizeChanged(object sender, SizeChangedEventArgs e) + { + this.swapChainManager.QueueResize(e.NewSize.Width, e.NewSize.Height); + } + + // Updates the background store for the composition scale factors used by the render thread + private void AnimatedComputeShaderPanel_CompositionScaleChanged(SwapChainPanel sender, object args) + { + this.swapChainManager.QueueCompositionScaleChange(CompositionScaleX, CompositionScaleY); + } +} diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs index 04939c0d..3372bb85 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs +++ b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs @@ -36,14 +36,17 @@ partial class ComputeShaderPanel private static void OnFrameRequestQueueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var @this = (ComputeShaderPanel)d; - var frameRequestQueue = (IFrameRequestQueue?)e.NewValue; if (@this.IsLoaded && - !@this.IsPaused && + e.NewValue is IFrameRequestQueue frameRequestQueue && @this.ShaderRunner is IShaderRunner shaderRunner) { @this.swapChainManager.StartRenderLoop(frameRequestQueue, shaderRunner); } + else + { + @this.swapChainManager.StopRenderLoop(); + } } /// @@ -68,17 +71,17 @@ partial class ComputeShaderPanel private static void OnShaderRunnerPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var @this = (ComputeShaderPanel)d; - var shaderRunner = (IShaderRunner?)e.NewValue; - if (shaderRunner is null) + if (@this.IsLoaded && + @this.FrameRequestQueue is IFrameRequestQueue frameRequestQueue && + e.NewValue is IShaderRunner shaderRunner) + { + @this.swapChainManager.StartRenderLoop(frameRequestQueue, shaderRunner); + } + else { @this.swapChainManager.StopRenderLoop(); } - else if (@this.IsLoaded && - !@this.IsPaused) - { - @this.swapChainManager.StartRenderLoop(@this.FrameRequestQueue, shaderRunner); - } } /// @@ -138,39 +141,4 @@ partial class ComputeShaderPanel @this.swapChainManager.QueueDynamicResolutionModeChange(isDynamicResolutionEnabled); } - - /// - /// Gets or sets whether or not the rendering is paused. - /// - public bool IsPaused - { - get => (bool)GetValue(IsPausedProperty); - set => SetValue(IsPausedProperty, value); - } - - /// - /// The backing . - /// - public static readonly DependencyProperty IsPausedProperty = DependencyProperty.Register( - nameof(IsPaused), - typeof(bool), - typeof(ComputeShaderPanel), - new PropertyMetadata(false, OnIsPausedPropertyChanged)); - - /// - private static void OnIsPausedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) - { - var @this = (ComputeShaderPanel)d; - var isPaused = (bool)e.NewValue; - - if (isPaused) - { - @this.swapChainManager.StopRenderLoop(); - } - else if (@this.IsLoaded && - @this.ShaderRunner is IShaderRunner shaderRunner) - { - @this.swapChainManager.StartRenderLoop(@this.FrameRequestQueue, shaderRunner); - } - } } diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs index 13bc5a40..9be6d942 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs +++ b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs @@ -19,8 +19,13 @@ namespace ComputeSharp.WinUI; #endif /// +/// /// A custom that can be used to render animated backgrounds. /// It is powered by ComputeSharp and leverages compute shaders to create frames to display. +/// +/// +/// This panel accepts a custom instance to customize frame requests. +/// /// public sealed partial class ComputeShaderPanel : SwapChainPanel { @@ -56,9 +61,10 @@ public sealed partial class ComputeShaderPanel : SwapChainPanel this.swapChainManager.QueueResolutionScaleChange(ResolutionScale); this.swapChainManager.QueueDynamicResolutionModeChange(IsDynamicResolutionEnabled); - if (ShaderRunner is IShaderRunner shaderRunner) + if (FrameRequestQueue is IFrameRequestQueue frameRequestQueue && + ShaderRunner is IShaderRunner shaderRunner) { - this.swapChainManager.StartRenderLoop(FrameRequestQueue, shaderRunner); + this.swapChainManager.StartRenderLoop(frameRequestQueue, shaderRunner); } } From 49c5690ff8ce1e4df664bd9decf95bed7f9c2df7 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 3 Jan 2022 10:23:14 +0100 Subject: [PATCH 11/12] Avoid blocking on UI thread in shader panels --- src/ComputeSharp.UI/ComputeSharp.UI.projitems | 1 + .../Extensions/SemaphoreSlimExtensions.cs | 56 +++++++++++++++++++ .../Helpers/SwapChainManager.Rendering.cs | 55 +++++++++++------- .../Helpers/SwapChainManager.cs | 34 +++++++---- 4 files changed, 114 insertions(+), 32 deletions(-) create mode 100644 src/ComputeSharp.UI/Extensions/SemaphoreSlimExtensions.cs diff --git a/src/ComputeSharp.UI/ComputeSharp.UI.projitems b/src/ComputeSharp.UI/ComputeSharp.UI.projitems index 694e6245..2f58b838 100644 --- a/src/ComputeSharp.UI/ComputeSharp.UI.projitems +++ b/src/ComputeSharp.UI/ComputeSharp.UI.projitems @@ -13,6 +13,7 @@ + diff --git a/src/ComputeSharp.UI/Extensions/SemaphoreSlimExtensions.cs b/src/ComputeSharp.UI/Extensions/SemaphoreSlimExtensions.cs new file mode 100644 index 00000000..fd2ab3d0 --- /dev/null +++ b/src/ComputeSharp.UI/Extensions/SemaphoreSlimExtensions.cs @@ -0,0 +1,56 @@ +using System; +using System.ComponentModel; +using System.Threading; +using System.Threading.Tasks; + +#pragma warning disable CS0618 + +#if WINDOWS_UWP +namespace ComputeSharp.Uwp.Extensions; +#else +namespace ComputeSharp.WinUI.Extensions; +#endif + +/// +/// A helper type for . +/// +internal static class SemaphoreSlimExtensions +{ + /// + /// Acquires a lock for the current instance, that is automatically released outside the block. + /// + public static async ValueTask LockAsync(this SemaphoreSlim semaphore) + { + await semaphore.WaitAsync().ConfigureAwait(false); + + return new(semaphore); + } + + /// + /// Private class that implements the automatic release of the semaphore + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public readonly struct Lock : IDisposable + { + /// + /// The underlying semaphore used by this instance. + /// + private readonly SemaphoreSlim semaphore; + + /// + /// Creates a new instance. + /// + /// The instance to wrap. + [Obsolete("Use AsyncMutex.LockAsync instead.")] + public Lock(SemaphoreSlim semaphore) + { + this.semaphore = semaphore; + } + + /// + public void Dispose() + { + this.semaphore.Release(); + } + } +} diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs index fd265119..a9344b05 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs @@ -2,6 +2,11 @@ using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading; +#if WINDOWS_UWP +using ComputeSharp.Uwp.Extensions; +#else +using ComputeSharp.WinUI.Extensions; +#endif using Microsoft.Toolkit.Diagnostics; #pragma warning disable CS0420 @@ -20,16 +25,17 @@ partial class SwapChainManager /// /// The instance to use, if available. /// The instance to use to render frames. - public void StartRenderLoop(IFrameRequestQueue? frameRequestQueue, IShaderRunner shaderRunner) + public async void StartRenderLoop(IFrameRequestQueue? frameRequestQueue, IShaderRunner shaderRunner) { ThrowIfDisposed(); Guard.IsNotNull(shaderRunner, nameof(shaderRunner)); - lock (this.renderLock) + using (await this.setupSemaphore.LockAsync()) { this.renderCancellationTokenSource?.Cancel(); - this.renderThread?.Join(); + + await this.renderSemaphore.WaitAsync(); Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop()); @@ -37,6 +43,7 @@ partial class SwapChainManager this.shaderRunner = shaderRunner; this.renderCancellationTokenSource = new CancellationTokenSource(); this.renderThread = newRenderThread; + this.renderSemaphore = new SemaphoreSlim(0, 1); newRenderThread.Start(this); } @@ -45,14 +52,13 @@ partial class SwapChainManager /// /// Stops the current render loop, if one is running. /// - public void StopRenderLoop() + public async void StopRenderLoop() { ThrowIfDisposed(); - lock (this.renderLock) + using (await this.setupSemaphore.LockAsync()) { this.renderCancellationTokenSource?.Cancel(); - this.renderThread?.Join(); } } @@ -60,22 +66,24 @@ partial class SwapChainManager /// Queues a change in the dynamic resolution mode. /// /// Whether or not to use dynamic resolution. - public void QueueDynamicResolutionModeChange(bool isDynamicResolutionEnabled) + public async void QueueDynamicResolutionModeChange(bool isDynamicResolutionEnabled) { ThrowIfDisposed(); - lock (this.renderLock) + using (await this.setupSemaphore.LockAsync()) { // If there is a render thread currently running, stop it and restart it if (this.renderCancellationTokenSource?.IsCancellationRequested == false) { this.renderCancellationTokenSource?.Cancel(); - this.renderThread?.Join(); + + await this.renderSemaphore.WaitAsync(); Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop()); this.renderCancellationTokenSource = new CancellationTokenSource(); this.renderThread = newRenderThread; + this.renderSemaphore = new SemaphoreSlim(0, 1); this.isDynamicResolutionEnabled = isDynamicResolutionEnabled; newRenderThread.Start(this); @@ -135,17 +143,24 @@ partial class SwapChainManager /// private void SwitchAndStartRenderLoop() { - if (this.isDynamicResolutionEnabled) + try { - this.targetResolutionScale = 1.0f; + if (this.isDynamicResolutionEnabled) + { + this.targetResolutionScale = 1.0f; - RenderLoopWithDynamicResolution(); + RenderLoopWithDynamicResolution(); + } + else + { + this.targetResolutionScale = this.resolutionScale; + + RenderLoop(); + } } - else + finally { - this.targetResolutionScale = this.resolutionScale; - - RenderLoop(); + this.renderSemaphore.Release(); } } @@ -304,9 +319,9 @@ partial class SwapChainManager { ThrowIfDisposed(); - lock (this.renderLock) - { - this.renderCancellationTokenSource?.Cancel(); - } + this.setupSemaphore.Wait(); + + this.renderCancellationTokenSource?.Cancel(); + this.renderSemaphore.Wait(); } } diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs index 80533ead..b4ec17e2 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs @@ -21,9 +21,9 @@ namespace ComputeSharp.WinUI.Helpers; internal sealed unsafe partial class SwapChainManager : NativeObject { /// - /// A lock object for the render loops. + /// An object for the render loop management. /// - private readonly object renderLock = new(); + private readonly SemaphoreSlim setupSemaphore = new(1, 1); /// /// The pointer for the device currently in use. @@ -85,6 +85,11 @@ internal sealed unsafe partial class SwapChainManager : NativeObject /// private volatile Thread? renderThread; + /// + /// The used to wait for render threads to complete. + /// + private volatile SemaphoreSlim renderSemaphore = new(1, 1); + /// /// The to use for . /// @@ -403,16 +408,21 @@ internal sealed unsafe partial class SwapChainManager : NativeObject /// protected override void OnDispose() { - UnsafeStopRenderLoopAndWait(); + ThreadPool.UnsafeQueueUserWorkItem(static state => + { + SwapChainManager @this = (SwapChainManager)state!; - this.d3D12Device.Dispose(); - this.d3D12CommandQueue.Dispose(); - this.d3D12Fence.Dispose(); - this.d3D12CommandAllocator.Dispose(); - this.d3D12GraphicsCommandList.Dispose(); - this.dxgiSwapChain3.Dispose(); - this.d3D12Resource0.Dispose(); - this.d3D12Resource1.Dispose(); - this.texture?.Dispose(); + @this.UnsafeStopRenderLoopAndWait(); + + @this.d3D12Device.Dispose(); + @this.d3D12CommandQueue.Dispose(); + @this.d3D12Fence.Dispose(); + @this.d3D12CommandAllocator.Dispose(); + @this.d3D12GraphicsCommandList.Dispose(); + @this.dxgiSwapChain3.Dispose(); + @this.d3D12Resource0.Dispose(); + @this.d3D12Resource1.Dispose(); + @this.texture?.Dispose(); + }, this); } } From 10f2663cad3fcae08652b26b7b612a4c9b2516d5 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 3 Jan 2022 11:17:42 +0100 Subject: [PATCH 12/12] Add rendering events to shader panels --- .../AnimatedComputeShaderPanel.Properties.cs | 28 ++++++++++ .../Controls/AnimatedComputeShaderPanel.cs | 16 +----- .../Controls/ComputeShaderPanel.Properties.cs | 28 ++++++++++ .../Controls/ComputeShaderPanel.cs | 16 +----- .../Helpers/SwapChainManager.Rendering.cs | 39 ++++++++++++- .../Helpers/SwapChainManager.cs | 55 +++++++++++++++++-- 6 files changed, 148 insertions(+), 34 deletions(-) diff --git a/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.Properties.cs b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.Properties.cs index 9899e75f..6e5bc36e 100644 --- a/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.Properties.cs +++ b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.Properties.cs @@ -4,6 +4,7 @@ using Windows.UI.Xaml; #else using Microsoft.UI.Xaml; #endif +using Windows.Foundation; #if WINDOWS_UWP namespace ComputeSharp.Uwp; @@ -14,6 +15,33 @@ namespace ComputeSharp.WinUI; /// partial class AnimatedComputeShaderPanel { + /// + /// Raised whenever rendering starts. + /// + public event TypedEventHandler? RenderingStarted + { + add => this.swapChainManager.RenderingStarted += value; + remove => this.swapChainManager.RenderingStarted -= value; + } + + /// + /// Raised whenever rendering stops. + /// + public event TypedEventHandler? RenderingStopped + { + add => this.swapChainManager.RenderingStopped += value; + remove => this.swapChainManager.RenderingStopped -= value; + } + + /// + /// Raised whenever rendering fails. + /// + public event TypedEventHandler? RenderingFailed + { + add => this.swapChainManager.RenderingFailed += value; + remove => this.swapChainManager.RenderingFailed -= value; + } + /// /// Gets or sets the instance to use to render content. /// diff --git a/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs index 85c00936..27b77bc1 100644 --- a/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs +++ b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs @@ -1,15 +1,11 @@ #if WINDOWS_UWP -using System.Runtime.InteropServices; using ComputeSharp.Uwp.Helpers; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; -using TerraFX.Interop.Windows; #else using ComputeSharp.WinUI.Helpers; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; -using TerraFX.Interop.Windows; -using WinRT; #endif #if WINDOWS_UWP @@ -30,22 +26,16 @@ namespace ComputeSharp.WinUI; public sealed partial class AnimatedComputeShaderPanel : SwapChainPanel { /// - /// The instance handling rendering. + /// The instance handling rendering. /// - private readonly SwapChainManager swapChainManager; + private readonly SwapChainManager swapChainManager; /// /// Creates a new instance. /// public unsafe AnimatedComputeShaderPanel() { -#if WINDOWS_UWP - IUnknown* swapChainPanel = (IUnknown*)Marshal.GetIUnknownForObject(this); -#else - IUnknown* swapChainPanel = (IUnknown*)((IWinRTObject)this).NativeObject.ThisPtr; -#endif - - this.swapChainManager = new SwapChainManager(swapChainPanel); + this.swapChainManager = new SwapChainManager(this); this.Loaded += AnimatedComputeShaderPanel_Loaded; this.Unloaded += AnimatedComputeShaderPanel_Unloaded; diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs index 3372bb85..7e351bc0 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs +++ b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs @@ -4,6 +4,7 @@ using Windows.UI.Xaml; #else using Microsoft.UI.Xaml; #endif +using Windows.Foundation; #if WINDOWS_UWP namespace ComputeSharp.Uwp; @@ -14,6 +15,33 @@ namespace ComputeSharp.WinUI; /// partial class ComputeShaderPanel { + /// + /// Raised whenever rendering starts. + /// + public event TypedEventHandler? RenderingStarted + { + add => this.swapChainManager.RenderingStarted += value; + remove => this.swapChainManager.RenderingStarted -= value; + } + + /// + /// Raised whenever rendering stops. + /// + public event TypedEventHandler? RenderingStopped + { + add => this.swapChainManager.RenderingStopped += value; + remove => this.swapChainManager.RenderingStopped -= value; + } + + /// + /// Raised whenever rendering fails. + /// + public event TypedEventHandler? RenderingFailed + { + add => this.swapChainManager.RenderingFailed += value; + remove => this.swapChainManager.RenderingFailed -= value; + } + /// /// Gets or sets the instance to use to request new frames. /// diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs index 9be6d942..8750e3dc 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs +++ b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs @@ -1,15 +1,11 @@ #if WINDOWS_UWP -using System.Runtime.InteropServices; using ComputeSharp.Uwp.Helpers; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; -using TerraFX.Interop.Windows; #else using ComputeSharp.WinUI.Helpers; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; -using TerraFX.Interop.Windows; -using WinRT; #endif #if WINDOWS_UWP @@ -30,22 +26,16 @@ namespace ComputeSharp.WinUI; public sealed partial class ComputeShaderPanel : SwapChainPanel { /// - /// The instance handling rendering. + /// The instance handling rendering. /// - private readonly SwapChainManager swapChainManager; + private readonly SwapChainManager swapChainManager; /// /// Creates a new instance. /// public unsafe ComputeShaderPanel() { -#if WINDOWS_UWP - IUnknown* swapChainPanel = (IUnknown*)Marshal.GetIUnknownForObject(this); -#else - IUnknown* swapChainPanel = (IUnknown*)((IWinRTObject)this).NativeObject.ThisPtr; -#endif - - this.swapChainManager = new SwapChainManager(swapChainPanel); + this.swapChainManager = new SwapChainManager(this); this.Loaded += ComputeShaderPanel_Loaded; this.Unloaded += ComputeShaderPanel_Unloaded; diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs index a9344b05..ef540584 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs @@ -18,7 +18,7 @@ namespace ComputeSharp.WinUI.Helpers; #endif /// -partial class SwapChainManager +partial class SwapChainManager { /// /// Starts the current render loop. @@ -37,7 +37,7 @@ partial class SwapChainManager await this.renderSemaphore.WaitAsync(); - Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop()); + Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop()); this.frameRequestQueue = frameRequestQueue; this.shaderRunner = shaderRunner; @@ -79,7 +79,7 @@ partial class SwapChainManager await this.renderSemaphore.WaitAsync(); - Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop()); + Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop()); this.renderCancellationTokenSource = new CancellationTokenSource(); this.renderThread = newRenderThread; @@ -145,6 +145,8 @@ partial class SwapChainManager { try { + OnRenderingStarted(); + if (this.isDynamicResolutionEnabled) { this.targetResolutionScale = 1.0f; @@ -157,6 +159,12 @@ partial class SwapChainManager RenderLoop(); } + + OnRenderingStopped(); + } + catch (Exception e) + { + OnRenderingFailed(e); } finally { @@ -311,6 +319,31 @@ partial class SwapChainManager /// private unsafe partial void OnPresent(); + /// + /// Raises . + /// + private void OnRenderingStarted() + { + _ = this.dispatcherQueue.TryEnqueue(() => RenderingStarted?.Invoke(this.owner, EventArgs.Empty)); + } + + /// + /// Raises . + /// + private void OnRenderingStopped() + { + _ = this.dispatcherQueue.TryEnqueue(() => RenderingStopped?.Invoke(this.owner, EventArgs.Empty)); + } + + /// + /// Raises . + /// + /// The being thrown that caused rendering to stop. + private void OnRenderingFailed(Exception e) + { + _ = this.dispatcherQueue.TryEnqueue(() => RenderingFailed?.Invoke(this.owner, e)); + } + /// /// Stops the current render loop, if one is running, and waits for it. /// diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs index b4ec17e2..babdc16c 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs @@ -4,9 +4,22 @@ using System.Threading; using ComputeSharp.Core.Extensions; using ComputeSharp.Graphics.Helpers; using ComputeSharp.Interop; +#if !WINDOWS_UWP +using Microsoft.UI.Dispatching; +using Microsoft.UI.Xaml.Controls; +#endif using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using TerraFX.Interop.WinRT; +#if WINDOWS_UWP +using System.Runtime.InteropServices; +using Windows.Foundation; +using Windows.UI.Xaml.Controls; +using Windows.System; +#else +using Windows.Foundation; +using WinRT; +#endif using Win32 = TerraFX.Interop.Windows.Windows; #if WINDOWS_UWP @@ -18,8 +31,20 @@ namespace ComputeSharp.WinUI.Helpers; /// /// A type managing rendering on a target swap chain object. /// -internal sealed unsafe partial class SwapChainManager : NativeObject +/// The type of the owner instance. +internal sealed unsafe partial class SwapChainManager : NativeObject + where TOwner : SwapChainPanel { + /// + /// The owning instance. + /// + private readonly TOwner owner; + + /// + /// The captured for the current instance. + /// + private readonly DispatcherQueue dispatcherQueue = DispatcherQueue.GetForCurrentThread(); + /// /// An object for the render loop management. /// @@ -156,20 +181,40 @@ internal sealed unsafe partial class SwapChainManager : NativeObject private volatile Stopwatch? renderStopwatch; /// - /// Initializes a new instance of the type. + /// Raised whenever rendering starts. /// - /// The input swap chain object being used. - public SwapChainManager(IUnknown* swapChainPanel) + public event TypedEventHandler? RenderingStarted; + + /// + /// Raised whenever rendering stops. + /// + public event TypedEventHandler? RenderingStopped; + + /// + /// Raised whenever rendering fails. + /// + public event TypedEventHandler? RenderingFailed; + + /// + /// Initializes a new instance of the type. + /// + /// The input swap chain instance being used. + public SwapChainManager(TOwner owner) { + this.owner = owner; + // Extract the ISwapChainPanelNative reference from the current panel, then query the // IDXGISwapChain reference just created and set that as the swap chain panel to use. using ComPtr swapChainPanelNative = default; #if WINDOWS_UWP + IUnknown* swapChainPanel = (IUnknown*)Marshal.GetIUnknownForObject(owner); + swapChainPanel->QueryInterface( Win32.__uuidof(), (void**)&swapChainPanelNative).Assert(); #else + IUnknown* swapChainPanel = (IUnknown*)((IWinRTObject)owner).NativeObject.ThisPtr; Guid iSwapChainPanelNativeUuid = new(0x63AAD0B8, 0x7C24, 0x40FF, 0x85, 0xA8, 0x64, 0x0D, 0x94, 0x4C, 0xC3, 0x25); swapChainPanel->QueryInterface( @@ -410,7 +455,7 @@ internal sealed unsafe partial class SwapChainManager : NativeObject { ThreadPool.UnsafeQueueUserWorkItem(static state => { - SwapChainManager @this = (SwapChainManager)state!; + SwapChainManager @this = (SwapChainManager)state!; @this.UnsafeStopRenderLoopAndWait();