Move swap chain rendering code to SwapChainManager type

このコミットが含まれているのは:
Sergio Pedri committed 2022-01-02 20:32:39 +01:00
1 親 b3338be7dd
コミット 6e0a6d0796
4ファイル変更
+234 -175

検索条件に一致するファイルはありません

+1 -1
ファイルの表示
@@ -11,7 +11,7 @@
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)Controls\ComputeShaderPanel.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Controls\ComputeShaderPanel.Properties.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Controls\ComputeShaderPanel.Rendering.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\SwapChainManager.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\DynamicResolutionManager.cs" />
<Compile Include="$(MSBuildThisFileDirectory)IShaderRunner.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ShaderRunner{T}.cs" />
+30 -17
ファイルの表示
@@ -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
/// </summary>
public IShaderRunner? ShaderRunner
{
get => (IShaderRunner?)GetValue(ShaderFactoryProperty);
set => SetValue(ShaderFactoryProperty, value);
get => (IShaderRunner?)GetValue(ShaderRunnerProperty);
set => SetValue(ShaderRunnerProperty, value);
}
/// <summary>
/// The <see cref="DependencyProperty"/> backing <see cref="ShaderRunner"/>.
/// </summary>
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));
/// <inheritdoc cref="DependencyPropertyChangedCallback"/>
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);
}
}
/// <summary>
/// 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);
}
/// <summary>
@@ -89,8 +103,6 @@ partial class ComputeShaderPanel
{
var @this = (ComputeShaderPanel)d;
var isDynamicResolutionEnabled = (bool)e.NewValue;
@this.isDynamicResolutionEnabled = isDynamicResolutionEnabled;
}
/// <summary>
@@ -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);
}
}
}
+34 -29
ファイルの表示
@@ -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;
/// </summary>
public sealed partial class ComputeShaderPanel : SwapChainPanel
{
/// <summary>
/// The <see cref="SwapChainManager"/> instance handling rendering.
/// </summary>
private readonly SwapChainManager swapChainManager;
/// <summary>
/// Creates a new <see cref="ComputeShaderPanel"/> instance.
/// </summary>
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;
}
/// <summary>
/// Finalizes the current <see cref="ComputeShaderPanel"/> instance and releases all resources.
/// </summary>
~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);
}
}
@@ -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
/// <inheritdoc cref="ComputeShaderPanel"/>
partial class ComputeShaderPanel
/// <summary>
/// A type managing rendering on a target swap chain object.
/// </summary>
internal sealed unsafe class SwapChainManager : NativeObject
{
/// <summary>
/// The render thread in use, if any.
/// A lock object for the render loops.
/// </summary>
private Thread? renderThread;
/// <summary>
/// The <see cref="IShaderRunner"/> instance used to create shaders to run.
/// </summary>
private IShaderRunner? shaderRunner;
private readonly object renderLock = new();
/// <summary>
/// The <see cref="ID3D12Device"/> pointer for the device currently in use.
@@ -94,12 +81,27 @@ partial class ComputeShaderPanel
/// <summary>
/// The index of the next buffer that can be used to present content.
/// </summary>
private uint currentBufferIndex;
private volatile uint currentBufferIndex;
/// <summary>
/// The render thread in use, if any.
/// </summary>
private volatile Thread? renderThread;
/// <summary>
/// The <see cref="CancellationTokenSource"/> to use for <see cref="renderThread"/>.
/// </summary>
private volatile CancellationTokenSource? renderCancellationTokenSource;
/// <summary>
/// The <see cref="IShaderRunner"/> instance used to create shaders to run.
/// </summary>
private volatile IShaderRunner? shaderRunner;
/// <summary>
/// The <see cref="ReadWriteTexture2D{T, TPixel}"/> instance used to prepare frames to display.
/// </summary>
private ReadWriteTexture2D<Rgba32, Float4>? texture;
private volatile ReadWriteTexture2D<Rgba32, Float4>? texture;
/// <summary>
/// Whether or not the window has been resized and requires the buffers to be updated.
@@ -141,37 +143,37 @@ partial class ComputeShaderPanel
/// </summary>
private volatile bool isDynamicResolutionEnabled;
/// <summary>
/// Indicates whether or not the rendering has been canceled.
/// </summary>
private volatile bool isCancellationRequested;
/// <summary>
/// The <see cref="Stopwatch"/> instance tracking time since the first rendered frame.
/// </summary>
private Stopwatch? renderStopwatch;
private volatile Stopwatch? renderStopwatch;
/// <summary>
/// Indicates whether or not <see cref="OnInitialize"/> has already been called.
/// Initializes a new instance of the <see cref="SwapChainManager"/> type.
/// </summary>
private bool isInitialized;
/// <summary>
/// Initializes the current application.
/// </summary>
private unsafe void OnInitialize()
/// <param name="swapChainPanel">The input swap chain object being used.</param>
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<ISwapChainPanelNative> swapChainPanelNative = default;
this.isInitialized = true;
#if WINDOWS_UWP
swapChainPanel->QueryInterface(
Win32.__uuidof<ISwapChainPanelNative>(),
(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<ID3D12Device>(), (void**)d3D12Device).Assert();
GraphicsDevice.Default.D3D12Device->QueryInterface(Win32.__uuidof<ID3D12Device>(), (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<ISwapChainPanelNative> swapChainPanelNative = default;
#if WINDOWS_UWP
IUnknown* swapChainPanel = (IUnknown*)Marshal.GetIUnknownForObject(this);
swapChainPanel->QueryInterface(
Win32.__uuidof<ISwapChainPanelNative>(),
(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> idxgiSwapChain = default)
{
this.dxgiSwapChain3.CopyTo(&idxgiSwapChain).Assert();
@@ -287,14 +270,6 @@ partial class ComputeShaderPanel
GC.KeepAlive(this);
}
/// <summary>
/// Resizes the current application.
/// </summary>
private void OnResize()
{
this.isResizePending = true;
}
/// <summary>
/// Applies the actual resize logic that was scheduled from <see cref="OnResize"/>.
/// </summary>
@@ -348,10 +323,9 @@ partial class ComputeShaderPanel
}
/// <summary>
/// Updates the render resolution, if needed, and renders a new frame.
/// Resizes the current application, if needed.
/// </summary>
/// <param name="time">The current time since the start of the application.</param>
private void OnUpdate(TimeSpan time)
private void OnResize()
{
if (this.isResizePending)
{
@@ -359,7 +333,14 @@ partial class ComputeShaderPanel
this.isResizePending = false;
}
}
/// <summary>
/// Updates the render resolution, if needed, and renders a new frame.
/// </summary>
/// <param name="time">The current time since the start of the application.</param>
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<ID3D12Resource> d3D12Resource = default;
// Get the underlying ID3D12Resource pointer for the texture
InteropServices.TryGetID3D12Resource(this.texture!, Win32.__uuidof<ID3D12Resource>(), (void**)d3D12Resource.GetAddressOf()).Assert();
this.texture!.D3D12Resource->QueryInterface(Win32.__uuidof<ID3D12Resource>(), (void**)d3D12Resource.GetAddressOf()).Assert();
// Get the target back buffer to update
ID3D12Resource* d3D12ResourceBackBuffer = this.currentBufferIndex switch
@@ -446,86 +427,146 @@ partial class ComputeShaderPanel
}
/// <summary>
/// Executes the render loop for the current panel.
/// The core render loop.
/// </summary>
/// <remarks>This method assumes to be invoked from a background thread.</remarks>
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();
}
/// <summary>
/// Starts the current render loop.
/// </summary>
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);
}
}
/// <summary>
/// Stops the current render loop, if one is running.
/// </summary>
private void OnStopRenderLoop()
public void StopRenderLoop()
{
this.isCancellationRequested = true;
ThrowIfDisposed();
lock (this.renderLock)
{
this.renderCancellationTokenSource?.Cancel();
}
}
/// <summary>
/// Stops the current render loop, and releases all resources.
/// Queues a resize operation.
/// </summary>
private void OnDisposed()
/// <param name="width">The width of the render resolution.</param>
/// <param name="height">The height of the render resolution.</param>
public void QueueResize(double width, double height)
{
this.isCancellationRequested = true;
this.width = (float)width;
this.height = (float)height;
this.isResizePending = true;
}
/// <summary>
/// Queues a change in the composition scale factors.
/// </summary>
/// <param name="compositionScaleX">The composition scale on the X axis.</param>
/// <param name="compositionScaleY">The composition scale on the Y axis</param>
public void QueueCompositionScaleChange(double compositionScaleX, double compositionScaleY)
{
this.compositionScaleX = (float)compositionScaleX;
this.compositionScaleY = (float)compositionScaleY;
this.isResizePending = true;
}
/// <summary>
/// Queues a change in the resolution scale factor.
/// </summary>
/// <param name="resolutionScale">The resolution scale factor to use.</param>
public void QueueResolutionScaleChange(double resolutionScale)
{
this.resolutionScale = (float)resolutionScale;
this.targetResolutionScale = (float)resolutionScale;
this.isResizePending = true;
}
/// <inheritdoc/>
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();