using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
#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.Extensions;
#else
using ComputeSharp.WinUI.Extensions;
#endif
#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 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
namespace ComputeSharp.Uwp.Helpers;
#else
namespace ComputeSharp.WinUI.Helpers;
#endif
///
/// A type managing rendering on a target swap chain object.
///
/// The type of the owner instance.
internal sealed unsafe partial class SwapChainManager : NativeObject
where TOwner : SwapChainPanel
{
///
/// The owning instance.
///
private readonly TOwner owner;
///
/// The instance in use.
///
private readonly GraphicsDevice device;
///
/// The captured for the current instance.
///
private readonly DispatcherQueue dispatcherQueue = DispatcherQueue.GetForCurrentThread();
///
/// An object for the render loop management.
///
private readonly SemaphoreSlim setupSemaphore = new(1, 1);
///
/// The pointer for the device currently in use.
///
private ComPtr d3D12Device;
///
/// The instance to use for graphics operations.
///
private ComPtr d3D12CommandQueue;
///
/// The instance used for graphics operations.
///
private ComPtr d3D12Fence;
///
/// The next fence value for graphics operations using .
///
private ulong nextD3D12FenceValue;
///
/// The object to create command lists.
///
private ComPtr d3D12CommandAllocator;
///
/// The instance used to copy data to the back buffers.
///
private ComPtr d3D12GraphicsCommandList;
///
/// The instance for the underlying object wrapped by the target control.
///
///
/// This is needed to call with
/// when the panel is destroyed, so the additional implicit references to the swap chain an native device can be released.
///
private ComPtr swapChainPanelNative;
///
/// The instance used to display content onto the target window.
///
private ComPtr dxgiSwapChain3;
///
/// The awaitable object for calls.
///
private HANDLE frameLatencyWaitableObject;
///
/// The first buffer within .
///
private ComPtr d3D12Resource0;
///
/// The second buffer within .
///
private ComPtr d3D12Resource1;
///
/// The index of the next buffer that can be used to present content.
///
private volatile uint currentBufferIndex;
///
/// The render thread in use, if any.
///
private volatile Thread? renderThread;
///
/// The used to wait for render threads to complete.
///
private volatile SemaphoreSlim renderSemaphore = new(1, 1);
///
/// The to use for .
///
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.
///
private volatile IShaderRunner? shaderRunner;
///
/// The instance used to prepare frames to display.
///
private volatile ReadWriteTexture2D? texture;
///
/// Whether or not the window has been resized and requires the buffers to be updated.
///
private volatile bool isResizePending;
///
/// The backing store for the actual width for the render thread.
///
private volatile float width;
///
/// The backing store for the actual height for the render thread.
///
private volatile float height;
///
/// The backing store for the current composition scale on the X axis for the render thread.
///
private volatile float compositionScaleX;
///
/// The backing store for the current composition scale on the Y axis for the render thread.
///
private volatile float compositionScaleY;
///
/// The resolution scale used to render frames when explicitly controlled by the user.
///
private volatile float resolutionScale;
///
/// The dynamic resolution scale used to render frames.
///
private volatile float dynamicResolutionScale;
///
/// Whether dynamic resolution is currently enabled.
///
private volatile bool isDynamicResolutionEnabled;
///
/// The flags to enable or disable vertical sync.
///
private volatile uint syncInterval;
///
/// The instance tracking time since the first rendered frame.
///
private volatile Stopwatch? renderStopwatch;
///
/// Raised whenever rendering starts.
///
public event TypedEventHandler? RenderingStarted;
///
/// Raised whenever rendering stops.
///
public event TypedEventHandler? RenderingStopped;
///
/// Raised whenever rendering fails.
///
public event TypedEventHandler? RenderingFailed;
///
/// Raised whenever the parent control is disposed and all underlying resources are released.
///
public event TypedEventHandler? Disposed;
///
/// Initializes a new instance of the type.
///
/// The input swap chain instance being used.
/// The instance to use to render frames.
public SwapChainManager(TOwner owner, GraphicsDevice device)
{
this.owner = owner;
this.device = device;
// 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.
fixed (ISwapChainPanelNative** swapChainPanelNative = this.swapChainPanelNative)
{
using (ComPtr swapChainPanel = default)
{
#if WINDOWS_UWP
swapChainPanel.Attach((IUnknown*)Marshal.GetIUnknownForObject(owner));
swapChainPanel.CopyTo(swapChainPanelNative).Assert();
#else
swapChainPanel.Attach((IUnknown*)((IWinRTObject)owner).NativeObject.GetRef());
swapChainPanel.CopyTo(
(Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(new Guid(0x63AAD0B8, 0x7C24, 0x40FF, 0x85, 0xA8, 0x64, 0x0D, 0x94, 0x4C, 0xC3, 0x25))),
(void**)swapChainPanelNative).Assert();
#endif
}
}
// Get the underlying ID3D12Device in use
fixed (ID3D12Device** d3D12Device = this.d3D12Device)
{
this.device.D3D12Device->QueryInterface(Win32.__uuidof(), (void**)d3D12Device).Assert();
}
// Create the direct command queue to use
fixed (ID3D12CommandQueue** d3D12CommandQueue = this.d3D12CommandQueue)
{
D3D12_COMMAND_QUEUE_DESC d3D12CommandQueueDesc;
d3D12CommandQueueDesc.Type = D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT;
d3D12CommandQueueDesc.Priority = (int)D3D12_COMMAND_QUEUE_PRIORITY.D3D12_COMMAND_QUEUE_PRIORITY_NORMAL;
d3D12CommandQueueDesc.Flags = D3D12_COMMAND_QUEUE_FLAGS.D3D12_COMMAND_QUEUE_FLAG_NONE;
d3D12CommandQueueDesc.NodeMask = 0;
this.d3D12Device.Get()->CreateCommandQueue(
&d3D12CommandQueueDesc,
Win32.__uuidof(),
(void**)d3D12CommandQueue).Assert();
}
// Create the direct fence
fixed (ID3D12Fence** d3D12Fence = this.d3D12Fence)
{
this.d3D12Device.Get()->CreateFence(
0,
D3D12_FENCE_FLAGS.D3D12_FENCE_FLAG_NONE,
Win32.__uuidof(),
(void**)d3D12Fence).Assert();
}
// Create the swap chain to display frames
using (ComPtr dxgiFactory6 = default)
{
DeviceHelper.CreateDXGIFactory6(dxgiFactory6.GetAddressOf());
DXGI_SWAP_CHAIN_DESC1 dxgiSwapChainDesc1 = default;
dxgiSwapChainDesc1.AlphaMode = DXGI_ALPHA_MODE.DXGI_ALPHA_MODE_IGNORE;
dxgiSwapChainDesc1.BufferCount = 2;
dxgiSwapChainDesc1.Flags = (uint)DXGI_SWAP_CHAIN_FLAG.DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
dxgiSwapChainDesc1.Format = DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_UNORM;
dxgiSwapChainDesc1.Width = 1;
dxgiSwapChainDesc1.Height = 1;
dxgiSwapChainDesc1.SampleDesc = new DXGI_SAMPLE_DESC(count: 1, quality: 0);
dxgiSwapChainDesc1.Scaling = DXGI_SCALING.DXGI_SCALING_STRETCH;
dxgiSwapChainDesc1.Stereo = 0;
dxgiSwapChainDesc1.SwapEffect = DXGI_SWAP_EFFECT.DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
dxgiSwapChainDesc1.BufferUsage = DXGI.DXGI_USAGE_RENDER_TARGET_OUTPUT;
using ComPtr dxgiSwapChain1 = default;
dxgiFactory6.Get()->CreateSwapChainForComposition(
(IUnknown*)this.d3D12CommandQueue.Get(),
&dxgiSwapChainDesc1,
null,
(IDXGISwapChain1**)&dxgiSwapChain1).Assert();
fixed (IDXGISwapChain3** dxgiSwapChain3 = this.dxgiSwapChain3)
{
dxgiSwapChain1.CopyTo(dxgiSwapChain3).Assert();
}
}
// Get the awaitable object to synchronizize present calls
this.frameLatencyWaitableObject = this.dxgiSwapChain3.Get()->GetFrameLatencyWaitableObject();
// Create the command allocator to use
fixed (ID3D12CommandAllocator** d3D12CommandAllocator = this.d3D12CommandAllocator)
{
this.d3D12Device.Get()->CreateCommandAllocator(
D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT,
Win32.__uuidof(),
(void**)d3D12CommandAllocator).Assert();
}
// Create the reusable command list to copy data to the back buffers
fixed (ID3D12GraphicsCommandList** d3D12GraphicsCommandList = this.d3D12GraphicsCommandList)
{
this.d3D12Device.Get()->CreateCommandList(
0,
D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT,
this.d3D12CommandAllocator,
null,
Win32.__uuidof(),
(void**)d3D12GraphicsCommandList).Assert();
}
// Close the command list to prepare it for future use
this.d3D12GraphicsCommandList.Get()->Close().Assert();
using (ComPtr idxgiSwapChain = default)
{
this.dxgiSwapChain3.CopyTo(&idxgiSwapChain).Assert();
this.swapChainPanelNative.Get()->SetSwapChain(idxgiSwapChain.Get()).Assert();
}
GC.KeepAlive(this);
}
///
/// Applies the actual resize logic that was scheduled from , if needed.
///
private unsafe void ApplyResize()
{
// The target resolution scale is either the dynamic resolution scale, being updated by the render thread,
// or the fixed resolution scale set by the user. If dynamic resolution is enabled, the latter is ignored.
float targetResolutionScale = this.isDynamicResolutionEnabled
? this.dynamicResolutionScale
: this.resolutionScale;
uint resizedWidth = (uint)Math.Max(Math.Ceiling(this.width * this.compositionScaleX * targetResolutionScale), 1.0);
uint resizeHeight = (uint)Math.Max(Math.Ceiling(this.height * this.compositionScaleY * targetResolutionScale), 1.0);
if (this.texture is null ||
this.texture.Width != resizedWidth ||
this.texture.Height != resizeHeight)
{
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(updatedFenceValue, default).Assert();
// Dispose the old buffers before resizing the buffer
this.d3D12Resource0.Dispose();
this.d3D12Resource1.Dispose();
// Resize the swap chain buffers
this.dxgiSwapChain3.Get()->ResizeBuffers(
2,
resizedWidth,
resizeHeight,
DXGI_FORMAT.DXGI_FORMAT_UNKNOWN,
(uint)DXGI_SWAP_CHAIN_FLAG.DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT).Assert();
// Apply the necessary scale transform
DXGI_MATRIX_3X2_F transformMatrix = default;
transformMatrix._11 = (1 / this.compositionScaleX) * (1 / targetResolutionScale);
transformMatrix._22 = (1 / this.compositionScaleY) * (1 / targetResolutionScale);
this.dxgiSwapChain3.Get()->SetMatrixTransform(&transformMatrix).Assert();
// Retrieve the back buffers for the swap chain
fixed (ID3D12Resource** d3D12Resource0 = this.d3D12Resource0)
fixed (ID3D12Resource** d3D12Resource1 = this.d3D12Resource1)
{
this.dxgiSwapChain3.Get()->GetBuffer(0, Win32.__uuidof(), (void**)d3D12Resource0).Assert();
this.dxgiSwapChain3.Get()->GetBuffer(1, Win32.__uuidof(), (void**)d3D12Resource1).Assert();
}
// Get the index of the initial back buffer
this.currentBufferIndex = this.dxgiSwapChain3.Get()->GetCurrentBackBufferIndex();
// Dispose the previous texture, if present, and create the new 2D texture to use to generate frames to display
this.texture?.Dispose();
this.texture = this.device.AllocateReadWriteTexture2D((int)resizedWidth, (int)resizeHeight);
}
}
///
private unsafe partial void OnWaitForPresent()
{
_ = Win32.WaitForSingleObjectEx(frameLatencyWaitableObject, Win32.INFINITE, true);
}
///
private unsafe partial void OnPresent()
{
using ComPtr d3D12Resource = default;
// Get the underlying ID3D12Resource pointer for the texture
this.texture!.D3D12Resource->QueryInterface(Win32.__uuidof(), (void**)d3D12Resource.GetAddressOf()).Assert();
// Get the target back buffer to update
ID3D12Resource* d3D12ResourceBackBuffer = this.currentBufferIndex switch
{
0 => this.d3D12Resource0.Get(),
1 => this.d3D12Resource1.Get(),
_ => null
};
this.currentBufferIndex ^= 1;
// Reset the command list and command allocator
this.d3D12CommandAllocator.Get()->Reset().Assert();
this.d3D12GraphicsCommandList.Get()->Reset(this.d3D12CommandAllocator.Get(), null).Assert();
D3D12_RESOURCE_BARRIER* d3D12ResourceBarriers = stackalloc D3D12_RESOURCE_BARRIER[]
{
D3D12_RESOURCE_BARRIER.InitTransition(
d3D12Resource.Get(),
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_SOURCE),
D3D12_RESOURCE_BARRIER.InitTransition(
d3D12ResourceBackBuffer,
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_DEST)
};
// Transition the resources to COPY_DEST and COPY_SOURCE respectively
this.d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers);
// Copy the generated frame to the target back buffer
this.d3D12GraphicsCommandList.Get()->CopyResource(d3D12ResourceBackBuffer, d3D12Resource.Get());
d3D12ResourceBarriers[0] = D3D12_RESOURCE_BARRIER.InitTransition(
d3D12Resource.Get(),
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_SOURCE,
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
d3D12ResourceBarriers[1] = D3D12_RESOURCE_BARRIER.InitTransition(
d3D12ResourceBackBuffer,
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COMMON);
// Transition the resources back to COMMON and UNORDERED_ACCESS respectively
this.d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers);
this.d3D12GraphicsCommandList.Get()->Close().Assert();
// Execute the command list to perform the copy
fixed (ID3D12GraphicsCommandList** d3D12GraphicsCommandList = this.d3D12GraphicsCommandList)
{
this.d3D12CommandQueue.Get()->ExecuteCommandLists(1, (ID3D12CommandList**)d3D12GraphicsCommandList);
}
// 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(SyncInterval: this.syncInterval, 0).Assert();
if (updatedFenceValue > this.d3D12Fence.Get()->GetCompletedValue())
{
this.d3D12Fence.Get()->SetEventOnCompletion(updatedFenceValue, default).Assert();
}
}
///
private unsafe partial void OnGetDynamicResolutionManager(out DynamicResolutionManager resolutionManager)
{
using ComPtr dxgiFactory6 = default;
DeviceHelper.CreateDXGIFactory6(dxgiFactory6.GetAddressOf());
using ComPtr dxgiAdapter = default;
dxgiFactory6.Get()->EnumAdapters(0, dxgiAdapter.GetAddressOf()).Assert();
int targetFramerate = dxgiAdapter.Get()->GetCompositionRefreshRate(DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_UNORM);
resolutionManager = new DynamicResolutionManager(targetFramerate);
}
///
private protected override void OnDispose()
{
static void OnDisposeOnDispatcherQueueThread(SwapChainManager @this)
{
// Even while rendering is still running, we need to properly release all implicit references
// that have been added when connecting the swap chain panel that was used. To do that, the
// same ISwapChainPanelNative::SetSwapChain API has to be called, but passing null as the
// target swap chain. This is handled correctly in the implementation, and all the additional
// references to the swap chain we passed during initialization will be dropped. Once that
// is done, we can then dispose our reference to the underlying swap chain panel for the control.
// This API has to be called on the UI thread, and it can be called just fine even if rendering
// is still running, so we can just call it immediately before moving to a thread to stop rendering.
@this.swapChainPanelNative.Get()->SetSwapChain(null).Assert();
@this.swapChainPanelNative.Dispose();
_ = ThreadPool.UnsafeQueueUserWorkItem(static state =>
{
SwapChainManager @this = (SwapChainManager)state!;
@this.UnsafeStopRenderLoopAndWait();
ulong updatedFenceValue = @this.nextD3D12FenceValue + 1;
@this.d3D12CommandQueue.Get()->Signal(@this.d3D12Fence.Get(), updatedFenceValue).Assert();
// Just like in the resize logic, signal and wait to make sure no operations are pending. This
// is needed to avoid a crash when disposing resources when disposing after stopping rendering.
@this.d3D12Fence.Get()->SetEventOnCompletion(updatedFenceValue, default).Assert();
_ = Win32.CloseHandle(@this.frameLatencyWaitableObject);
@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.OnDisposed();
}, @this);
}
// Check whether the current thread is the one associated with the dispatcher queue. If so, the dispose
// logic can be called directly, otherwise an extra dispatch is needed. This is because the start of
// the dispose logic requires UI thread access to interact with the swap chain panel.
if (this.dispatcherQueue.HasThreadAccess)
{
OnDisposeOnDispatcherQueueThread(this);
}
else
{
[MethodImpl(MethodImplOptions.NoInlining)]
static void OnDisposeOnThreadPoolThread(SwapChainManager @this)
{
_ = @this.dispatcherQueue.TryEnqueue(() => OnDisposeOnDispatcherQueueThread(@this));
}
// Move to a separate queue to skip the closure when lowering this method, if not needed
OnDisposeOnThreadPoolThread(this);
}
}
}