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();