Add basic WASDK sample setup and render loop

このコミットが含まれているのは:
Sergio Pedri committed 2023-04-22 01:23:41 +02:00
1 親 1bd588500e
コミット 6b330d1973
6ファイル変更
+629 -1

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

@@ -0,0 +1,90 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using TerraFX.Interop.Windows;
using TerraFX.Interop;
using System;
#pragma warning disable CS0649, IDE1006
namespace ABI.Microsoft.Graphics.Canvas;
/// <summary>
/// Raw bindings for the interop interface for the <see cref="CanvasDevice"/> activation factory.
/// </summary>
[Guid("695C440D-04B3-4EDD-BFD9-63E51E9F7202")]
internal unsafe struct ICanvasFactoryNative : IUnknown.Interface
{
public void** lpVtbl;
/// <inheritdoc/>
static Guid* INativeGuid.NativeGuid
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0x0D, 0x44, 0x5C, 0x69,
0xB3, 0x04,
0xDD, 0x4E,
0xBF, 0xD9,
0x63,
0xE5,
0x1E,
0x9F,
0x72,
0x02
};
return (Guid*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(data));
}
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public HRESULT QueryInterface(Guid* riid, void** ppvObject)
{
return ((delegate* unmanaged<ICanvasFactoryNative*, Guid*, void**, int>)this.lpVtbl[0])((ICanvasFactoryNative*)Unsafe.AsPointer(ref this), riid, ppvObject);
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public uint AddRef()
{
return ((delegate* unmanaged<ICanvasFactoryNative*, uint>)this.lpVtbl[1])((ICanvasFactoryNative*)Unsafe.AsPointer(ref this));
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public uint Release()
{
return ((delegate* unmanaged<ICanvasFactoryNative*, uint>)this.lpVtbl[2])((ICanvasFactoryNative*)Unsafe.AsPointer(ref this));
}
/// <summary>
/// Gets or creates an <c>IInspectable</c> Win2D wrapper for a given native D2D resource.
/// </summary>
/// <param name="device">The input canvas device (as a marshalled <see cref="global::Microsoft.Graphics.Canvas.CanvasDevice"/>).</param>
/// <param name="resource">The input native resource to create a wrapper for.</param>
/// <param name="dpi">The realization DPIs for <paramref name="resource"/></param>
/// <param name="wrapper">The resulting wrapper for <paramref name="resource"/>.</param>
/// <returns>The <see cref="HRESULT"/> for the operation.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public HRESULT GetOrCreate(IUnknown* device, IUnknown* resource, float dpi, void** wrapper)
{
return ((delegate* unmanaged<ICanvasFactoryNative*, IUnknown*, IUnknown*, float, void**, int>)this.lpVtbl[6])(
(ICanvasFactoryNative*)Unsafe.AsPointer(ref this),
device,
resource,
dpi,
wrapper);
}
/// <summary>
/// The COM import interface for <see cref="ICanvasFactoryNative"/>.
/// </summary>
[Guid("695C440D-04B3-4EDD-BFD9-63E51E9F7202")]
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface Interface
{
}
}
+184
ファイルの表示
@@ -0,0 +1,184 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using ABI.Microsoft.Graphics.Canvas;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
using TerraFX.Interop.WinRT;
using Windows.Graphics.DirectX;
using WinRT;
namespace ComputeSharp.SwapChain.D2D1.Backend;
using CanvasDevice = Microsoft.Graphics.Canvas.CanvasDevice;
using CanvasDrawingSession = Microsoft.Graphics.Canvas.CanvasDrawingSession;
using CanvasSwapChain = Microsoft.Graphics.Canvas.CanvasSwapChain;
using Windows = TerraFX.Interop.Windows.Windows;
/// <summary>
/// A simple Win32 application handling a D2D swapchain.
/// </summary>
internal sealed class Win32Application
{
/// <summary>
/// The <see cref="CanvasDevice"/> instance to use.
/// </summary>
private CanvasDevice? canvasDevice;
/// <summary>
/// The <see cref="CanvasSwapChain"/> instance to use to render frames.
/// </summary>
private CanvasSwapChain? canvasSwapChain;
/// <summary>
/// Whether or not the window has been resized and requires the buffers to be updated.
/// </summary>
private bool isResizePending;
/// <summary>
/// Raised whenever a draw operation can be performed.
/// </summary>
public event EventHandler<CanvasDrawingSession>? Draw;
/// <summary>
/// Initializes the current application.
/// </summary>
/// <param name="hwnd">The handle for the window.</param>
[MemberNotNull(nameof(canvasDevice))]
[MemberNotNull(nameof(canvasSwapChain))]
public unsafe void OnInitialize(HWND hwnd)
{
// Create a new canvas device, which will handle DX11/D2D initialization
CanvasDevice canvasDevice = new();
CanvasSwapChain canvasSwapChain;
// Create the swap chain to display frames
using (ComPtr<IUnknown> direct3DDeviceUnknown = default)
using (ComPtr<IDXGIFactory2> dxgiFactory2 = default)
using (ComPtr<IDXGISwapChain1> dxgiSwapChain1 = default)
{
HRESULT hresult;
// Extract the underlying Direct3D device from the canvas device.
// This is needed for CreateSwapChainForHwnd, as the owning device.
using (ComPtr<IUnknown> canvasDeviceUnknown = default)
using (ComPtr<IDirect3DDxgiInterfaceAccess> direct3DDxgiInterfaceAccess = default)
{
canvasDeviceUnknown.Attach((IUnknown*)MarshalInspectable<CanvasDevice>.FromManaged(canvasDevice));
hresult = canvasDeviceUnknown.CopyTo(direct3DDxgiInterfaceAccess.GetAddressOf());
ExceptionHelpers.ThrowExceptionForHR(hresult);
hresult = direct3DDxgiInterfaceAccess.Get()->GetInterface(Windows.__uuidof<IUnknown>(), (void**)direct3DDeviceUnknown.GetAddressOf());
ExceptionHelpers.ThrowExceptionForHR(hresult);
}
// Create the DXGIFactory2 instance to create the swapchain with
hresult = DirectX.CreateDXGIFactory2(DXGI.DXGI_CREATE_FACTORY_DEBUG, Windows.__uuidof<IDXGIFactory2>(), (void**)dxgiFactory2.GetAddressOf());
ExceptionHelpers.ThrowExceptionForHR(hresult);
DXGI_SWAP_CHAIN_DESC1 dxgiSwapChainDesc1 = default;
dxgiSwapChainDesc1.AlphaMode = DXGI_ALPHA_MODE.DXGI_ALPHA_MODE_IGNORE;
dxgiSwapChainDesc1.BufferCount = 2;
dxgiSwapChainDesc1.BufferUsage = DXGI.DXGI_USAGE_RENDER_TARGET_OUTPUT;
dxgiSwapChainDesc1.Flags = 0;
dxgiSwapChainDesc1.Format = DXGI_FORMAT.DXGI_FORMAT_B8G8R8A8_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;
// Create the native DXGI swapchain object to wrap
hresult = dxgiFactory2.Get()->CreateSwapChainForHwnd(
direct3DDeviceUnknown.Get(),
hwnd,
&dxgiSwapChainDesc1,
null,
null,
dxgiSwapChain1.GetAddressOf());
ExceptionHelpers.ThrowExceptionForHR(hresult);
using ComPtr<ICanvasFactoryNative> canvasFactoryNative = default;
// Get the activation factory for CanvasDevice
using (ComPtr<IUnknown> canvasFactoryNativeUnknown = default)
{
ICanvasFactoryNative.Interface canvasDeviceActivationFactory = CanvasDevice.As<ICanvasFactoryNative.Interface>();
canvasFactoryNativeUnknown.Attach((IUnknown*)Marshal.GetIUnknownForObject(canvasDeviceActivationFactory));
hresult = canvasFactoryNativeUnknown.CopyTo(canvasFactoryNative.GetAddressOf());
ExceptionHelpers.ThrowExceptionForHR(hresult);
}
// Create a Win2D wrapper for the swapchain
using (ComPtr<IUnknown> canvasDeviceUnknown = default)
using (ComPtr<IUnknown> canvasSwapChainUnknown = default)
{
canvasDeviceUnknown.Attach((IUnknown*)MarshalInspectable<CanvasDevice>.FromManaged(canvasDevice));
hresult = canvasFactoryNative.Get()->GetOrCreate(
device: canvasDeviceUnknown.Get(),
resource: (IUnknown*)dxgiSwapChain1.Get(),
dpi: 96.0f,
wrapper: (void**)canvasSwapChainUnknown.GetAddressOf());
ExceptionHelpers.ThrowExceptionForHR(hresult);
// Marshal to a WinRT managed object
canvasSwapChain = MarshalInspectable<CanvasSwapChain>.FromAbi((IntPtr)canvasSwapChainUnknown.Get());
}
}
// Save the Win2D objects for later use
this.canvasDevice = canvasDevice;
this.canvasSwapChain = canvasSwapChain;
}
/// <summary>
/// Resizes the current application.
/// </summary>
public void OnResize()
{
this.isResizePending = true;
}
/// <summary>
/// Updates the current application.
/// </summary>
/// <param name="time">The current time since the start of the application.</param>
public void OnUpdate(TimeSpan time)
{
if (this.isResizePending)
{
// Resize the swapchain if needed (the size is calculated automatically)
this.canvasSwapChain!.ResizeBuffers(
newWidth: 0,
newHeight: 0,
newDpi: 96.0f,
newFormat: DirectXPixelFormat.Unknown,
bufferCount: 0);
this.isResizePending = false;
}
// Create the drawing session and invoke all registered draw handler
using (CanvasDrawingSession canvasDrawingSession = this.canvasSwapChain!.CreateDrawingSession(default))
{
Draw?.Invoke(this, canvasDrawingSession);
}
// Wait for v-sync
this.canvasSwapChain.WaitForVerticalBlank();
// Present the new frame
this.canvasSwapChain.Present(syncInterval: 1);
}
}
+344
ファイルの表示
@@ -0,0 +1,344 @@
using System;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Threading;
using TerraFX.Interop.Windows;
namespace ComputeSharp.SwapChain.D2D1.Backend;
using Windows = TerraFX.Interop.Windows.Windows;
/// <summary>
/// A helper class to manage the creation and execution of Win32 applications.
/// </summary>
internal static unsafe class Win32ApplicationRunner
{
/// <summary>
/// Whether or not a resize operation is in progress.
/// </summary>
private static bool isResizing = false;
/// <summary>
/// Whether or not the application is currently paused.
/// </summary>
private static bool isPaused = false;
/// <summary>
/// The <see cref="HWND"/> for the application window.
/// </summary>
private static HWND hwnd;
/// <summary>
/// The application being run.
/// </summary>
private static Win32Application application = null!;
/// <summary>
/// The thread running the render loop.
/// </summary>
private static Thread renderThread = null!;
/// <summary>
/// Runs a specified application and starts the main loop to update its state. This is the entry point for a given application,
/// and it should be called as soon as the process is launched, excluding any other additional initialization needed.
/// </summary>
/// <param name="application">The input application instance to run.</param>
/// <param name="applicationName">Name of the input application instance to run.</param>
/// <param name="windowTitle">The title to use for the window being opened.</param>
/// <returns>The exit code for the application.</returns>
public static int Run(Win32Application application, string applicationName, string windowTitle)
{
Win32ApplicationRunner.application = application;
HMODULE hInstance = Windows.GetModuleHandleW(null);
fixed (char* name = applicationName)
fixed (char* title = windowTitle)
{
// Initialize the window class
WNDCLASSEXW windowClassEx = new()
{
cbSize = (uint)sizeof(WNDCLASSEXW),
style = CS.CS_HREDRAW | CS.CS_VREDRAW,
lpfnWndProc = &WindowProc,
hInstance = hInstance,
hCursor = Windows.LoadCursorW(HINSTANCE.NULL, IDC.IDC_ARROW),
lpszClassName = (ushort*)name
};
// Register the window class
_ = Windows.RegisterClassExW(&windowClassEx);
Rectangle windowRect = new(0, 0, 1280, 720);
// Set the target window size
_ = Windows.AdjustWindowRect((RECT*)&windowRect, WS.WS_OVERLAPPEDWINDOW, Windows.FALSE);
uint height = (uint)(windowRect.Bottom - windowRect.Top);
uint width = (uint)(windowRect.Right - windowRect.Left);
// Create the window and store a handle to it
hwnd = Windows.CreateWindowExW(
0,
windowClassEx.lpszClassName,
(ushort*)title,
WS.WS_OVERLAPPEDWINDOW,
Windows.CW_USEDEFAULT,
Windows.CW_USEDEFAULT,
(int)width,
(int)height,
HWND.NULL,
HMENU.NULL,
hInstance,
(void*)GCHandle.ToIntPtr(GCHandle.Alloc(application))
);
MARGINS margins = default;
margins.cxLeftWidth = -1;
margins.cxRightWidth = -1;
margins.cyTopHeight = -1;
margins.cyBottomHeight = -1;
_ = Windows.DwmExtendFrameIntoClientArea(hwnd, &margins);
}
// Initialize the application
application.OnInitialize(hwnd);
// Display the window
_ = Windows.ShowWindow(hwnd, SW.SW_SHOWDEFAULT);
MSG msg = default;
// Setup the render thread that enables smooth resizing of the window
renderThread = new Thread(static args =>
{
(Win32Application application, CancellationToken token) = ((Win32Application, CancellationToken))args!;
Stopwatch stopwatch = Stopwatch.StartNew();
while (!token.IsCancellationRequested)
{
application.OnUpdate(stopwatch.Elapsed);
}
});
CancellationTokenSource tokenSource = new();
renderThread.Start((application, tokenSource.Token));
// Process any messages in the queue
while (msg.message != WM.WM_QUIT)
{
if (Windows.PeekMessageW(&msg, HWND.NULL, 0, 0, PM.PM_REMOVE) != 0)
{
_ = Windows.TranslateMessage(&msg);
_ = Windows.DispatchMessageW(&msg);
}
else if (isPaused)
{
Thread.Sleep(100);
}
// Also listen to Escape and 'Q' to quit
if (msg.message == WM.WM_KEYUP && (msg.wParam == (WPARAM)VK.VK_ESCAPE || msg.wParam == 'Q'))
{
_ = Windows.DestroyWindow(hwnd);
}
}
tokenSource.Cancel();
renderThread.Join();
// Return this part of the WM_QUIT message to Windows
return (int)msg.wParam;
}
/// <summary>
/// Processes incoming messages for a window.
/// </summary>
/// <param name="hwnd">A handle to the window.</param>
/// <param name="uMsg">The message.</param>
/// <param name="wParam">Additional message information (the contents depend on the value of <paramref name="uMsg"/>).</param>
/// <param name="lParam">Additional message information (the contents depend on the value of <paramref name="uMsg"/>).</param>
/// <returns>The result of the message processing for the input message.</returns>
[UnmanagedCallersOnly]
private static LRESULT WindowProc(HWND hwnd, uint uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
// Change the paused state on window activation
case WM.WM_ACTIVATE:
{
if (Windows.LOWORD(wParam) == Windows.WA_INACTIVE)
{
isPaused = true;
}
else
{
isPaused = false;
}
return 0;
}
// Change the paused state when ESC is pressed
case WM.WM_KEYDOWN:
{
if (wParam == (byte)ConsoleKey.Escape)
{
if (isPaused)
{
_ = Windows.SetCapture(hwnd);
}
else
{
_ = Windows.ReleaseCapture();
}
isPaused = !isPaused;
}
return 0;
}
// Window resize started
case WM.WM_ENTERSIZEMOVE:
{
isResizing = true;
return 0;
}
// Window resize completed
case WM.WM_EXITSIZEMOVE:
{
isResizing = false;
application.OnResize();
return 0;
}
// Size update
case WM.WM_SIZE:
{
if (!isResizing && wParam != Windows.SIZE_MINIMIZED)
{
application.OnResize();
}
return 0;
}
// Size and position of the window (needed to enable the borderless mode)
case WM.WM_NCCALCSIZE:
{
return 0;
}
// Enable dragging the window
case WM.WM_NCHITTEST:
{
POINT point;
RECT rect;
_ = Windows.GetCursorPos(&point);
_ = Windows.GetWindowRect(hwnd, &rect);
bool isAtTop = Math.Abs(point.y - rect.top) < 12;
bool isAtRight = Math.Abs(point.x - rect.right) < 12;
bool isAtBottom = Math.Abs(point.y - rect.bottom) < 12;
bool isAtLeft = Math.Abs(point.x - rect.left) < 12;
if (isAtTop)
{
if (isAtRight)
{
return Windows.HTTOPRIGHT;
}
if (isAtLeft)
{
return Windows.HTTOPLEFT;
}
return Windows.HTTOP;
}
if (isAtRight)
{
if (isAtTop)
{
return Windows.HTTOPRIGHT;
}
if (isAtBottom)
{
return Windows.HTBOTTOMRIGHT;
}
return Windows.HTRIGHT;
}
if (isAtBottom)
{
if (isAtRight)
{
return Windows.HTBOTTOMRIGHT;
}
if (isAtLeft)
{
return Windows.HTBOTTOMLEFT;
}
return Windows.HTBOTTOM;
}
if (isAtLeft)
{
if (isAtTop)
{
return Windows.HTTOPLEFT;
}
if (isAtBottom)
{
return Windows.HTBOTTOMLEFT;
}
return Windows.HTLEFT;
}
return Windows.HTCAPTION;
}
// Restore the drop shadow
case WM.WM_DWMCOMPOSITIONCHANGED:
{
MARGINS margins = default;
margins.cxLeftWidth = -1;
margins.cxRightWidth = -1;
margins.cyTopHeight = -1;
margins.cyBottomHeight = -1;
_ = Windows.DwmExtendFrameIntoClientArea(hwnd, &margins);
return 0;
}
// Shutdown
case WM.WM_DESTROY:
{
Windows.PostQuitMessage(0);
return 0;
}
}
return Windows.DefWindowProcW(hwnd, uMsg, wParam, lParam);
}
}
+7 -1
ファイルの表示
@@ -2,8 +2,14 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net6.0-windows10.0.22621</TargetFramework>
<Platforms>x64;ARM64</Platforms>
<NoWarn>$(NoWarn);IDE0065</NoWarn>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Graphics.Win2D" Version="1.1.0-preview1" />
<PackageReference Include="TerraFX.Interop.Windows" Version="10.0.22621.1" />
</ItemGroup>
</Project>
+3
ファイルの表示
@@ -0,0 +1,3 @@
using ComputeSharp.SwapChain.D2D1.Backend;
return Win32ApplicationRunner.Run(new Win32Application(), "ComputeSharp.SwapChain.D2D1", "test");
+1
ファイルの表示
@@ -340,6 +340,7 @@ internal static unsafe class Win32ApplicationRunner
case WM.WM_DESTROY:
{
Windows.PostQuitMessage(0);
return 0;
}
}