diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml
index eaa46939..d1b18b54 100644
--- a/.github/workflows/dotnet.yml
+++ b/.github/workflows/dotnet.yml
@@ -134,6 +134,8 @@ jobs:
steps:
- name: Git checkout
uses: actions/checkout@v3
+ - name: Add msbuild to PATH
+ uses: microsoft/setup-msbuild@v1.1
- name: Build and run ComputeSharp.Sample
run: >
dotnet build samples\ComputeSharp.Sample\ComputeSharp.Sample.csproj -c Release -f ${{matrix.framework}} -r win-x64 --no-self-contained -p:Platform=x64 -v n;
@@ -147,7 +149,7 @@ jobs:
dotnet build samples\ComputeSharp.ImageProcessing\ComputeSharp.ImageProcessing.csproj -c Release -f ${{matrix.framework}} -r win-x64 --no-self-contained -p:Platform=x64 -v n;
samples\ComputeSharp.ImageProcessing\bin\x64\Release\${{matrix.framework}}\win-x64\ComputeSharp.ImageProcessing.exe
- # Also publish the NativeAOT test when .NET 7 is used
+ # Publish the NativeAOT test when .NET 7 is used
- if: matrix.framework == 'net7.0'
name: Publish ComputeSharp.SwapChain.Cli with NativeAOT
run: >
@@ -169,6 +171,21 @@ jobs:
path: samples\ComputeSharp.SwapChain.Cli\bin\Release\net7.0\win-x64\publish\computesharp.cli.exe
if-no-files-found: error
+ # Also publish the Win2D sample on .NET 7 (without NativeAOT, see https://github.com/dotnet/runtime/issues/84908)
+ - if: matrix.framework == 'net7.0'
+ name: Publish ComputeSharp.SwapChain.D2D1.Cli
+ run: >
+ msbuild samples\ComputeSharp.SwapChain.D2D1.Cli\ComputeSharp.SwapChain.D2D1.Cli.csproj -t:restore,publish /p:Configuration=Release
+ /p:Platform=x64 /p:RuntimeIdentifier=win10-x64 /p:PublishSingleFile=True /p:SelfContained=True /p:PublishTrimmed=True
+ - if: matrix.framework == 'net7.0'
+ name: Run ComputeSharp.SwapChain.D2D1.Cli
+ run: >
+ $process = (Start-Process samples\ComputeSharp.SwapChain.D2D1.Cli\bin\x64\Release\net7.0-windows10.0.22621\win10-x64\publish\computesharp.d2d1.cli.exe -PassThru);
+ sleep -Seconds 2;
+ $process.CloseMainWindow() | Out-Null;
+ $process.WaitForExit();
+ $process.ExitCode
+
# Download the NuGet packages generated in the previous job and use them
# to build and run the sample project referencing them. This is used as
# a test to ensure the NuGet packages work in a consuming project.
diff --git a/ComputeSharp.sln b/ComputeSharp.sln
index 7b49c5d0..37e36f64 100644
--- a/ComputeSharp.sln
+++ b/ComputeSharp.sln
@@ -1,5 +1,4 @@
-
-Microsoft Visual Studio Solution File, Format Version 12.00
+Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31825.309
MinimumVisualStudioVersion = 10.0.40219.1
@@ -153,6 +152,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{B54B6DCA
tests\Directory.Build.targets = tests\Directory.Build.targets
EndProjectSection
EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.SwapChain.D2D1.Cli", "samples\ComputeSharp.SwapChain.D2D1.Cli\ComputeSharp.SwapChain.D2D1.Cli.csproj", "{9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
@@ -409,6 +410,14 @@ Global
{BD9E6556-357E-4C20-BFCD-FB131F9372FA}.Release|ARM64.Build.0 = Release|ARM64
{BD9E6556-357E-4C20-BFCD-FB131F9372FA}.Release|x64.ActiveCfg = Release|x64
{BD9E6556-357E-4C20-BFCD-FB131F9372FA}.Release|x64.Build.0 = Release|x64
+ {9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}.Debug|ARM64.ActiveCfg = Debug|ARM64
+ {9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}.Debug|ARM64.Build.0 = Debug|ARM64
+ {9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}.Debug|x64.ActiveCfg = Debug|x64
+ {9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}.Debug|x64.Build.0 = Debug|x64
+ {9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}.Release|ARM64.ActiveCfg = Release|ARM64
+ {9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}.Release|ARM64.Build.0 = Release|ARM64
+ {9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}.Release|x64.ActiveCfg = Release|x64
+ {9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -445,6 +454,7 @@ Global
{F8BF7666-7CCF-4FE4-B055-2EBA4BCD4564} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1}
{568E7009-5C13-4153-9C94-0AC7A3E6883C} = {1A9C4108-F61A-4ABE-B5CF-F524521EAE2D}
{B54B6DCA-6EAB-46A8-83D3-15154659F47F} = {1A9C4108-F61A-4ABE-B5CF-F524521EAE2D}
+ {9EA5AE9D-C39A-4F43-B03E-0A848EA2558A} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC}
@@ -467,6 +477,7 @@ Global
src\ComputeSharp.D2D1.UI\ComputeSharp.D2D1.UI.projitems*{902d7b44-2c6c-4fcd-840b-ebcae811ee63}*SharedItemsImports = 13
src\ComputeSharp.SourceGeneration.Hlsl\ComputeSharp.SourceGeneration.Hlsl.projitems*{9ac496a3-bbf0-4c8f-a50d-a20bf01c5e05}*SharedItemsImports = 13
src\TerraFX.Interop.Windows.D2D1\TerraFX.Interop.Windows.D2D1.projitems*{9da1da9f-f8b2-4b25-be80-c21f773029e3}*SharedItemsImports = 13
+ samples\ComputeSharp.SwapChain.Shaders.D2D1.Shared\ComputeSharp.SwapChain.Shaders.D2D1.Shared.projitems*{9ea5ae9d-c39a-4f43-b03e-0a848ea2558a}*SharedItemsImports = 5
src\ComputeSharp.NetStandard\ComputeSharp.NetStandard.projitems*{a5997814-d8d2-4541-87ac-c3e53caa67c0}*SharedItemsImports = 13
src\ComputeSharp.UI\ComputeSharp.UI.projitems*{afaafdc9-be42-45d4-8c79-0ee8c8edbf52}*SharedItemsImports = 5
src\ComputeSharp.D2D1.UI\ComputeSharp.D2D1.UI.projitems*{bd9e6556-357e-4c20-bfcd-fb131f9372fa}*SharedItemsImports = 5
diff --git a/samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/ABI.Microsoft.Graphics.Canvas/ICanvasFactoryNative.cs b/samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/ABI.Microsoft.Graphics.Canvas/ICanvasFactoryNative.cs
new file mode 100644
index 00000000..c5bd740f
--- /dev/null
+++ b/samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/ABI.Microsoft.Graphics.Canvas/ICanvasFactoryNative.cs
@@ -0,0 +1,103 @@
+using System;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using TerraFX.Interop.Windows;
+using TerraFX.Interop;
+using WinRT;
+using WinRT.Interop;
+
+#pragma warning disable CS0649, IDE1006
+
+namespace ABI.Microsoft.Graphics.Canvas;
+
+///
+/// Raw bindings for the interop interface for the activation factory.
+///
+[Guid("695C440D-04B3-4EDD-BFD9-63E51E9F7202")]
+internal unsafe struct ICanvasFactoryNative : IUnknown.Interface
+{
+ public void** lpVtbl;
+
+ ///
+ static Guid* INativeGuid.NativeGuid
+ {
+ get
+ {
+ ReadOnlySpan 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));
+ }
+ }
+
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public HRESULT QueryInterface(Guid* riid, void** ppvObject)
+ {
+ return ((delegate* unmanaged)this.lpVtbl[0])((ICanvasFactoryNative*)Unsafe.AsPointer(ref this), riid, ppvObject);
+ }
+
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public uint AddRef()
+ {
+ return ((delegate* unmanaged)this.lpVtbl[1])((ICanvasFactoryNative*)Unsafe.AsPointer(ref this));
+ }
+
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public uint Release()
+ {
+ return ((delegate* unmanaged)this.lpVtbl[2])((ICanvasFactoryNative*)Unsafe.AsPointer(ref this));
+ }
+
+ ///
+ /// Gets or creates an IInspectable Win2D wrapper for a given native D2D resource.
+ ///
+ /// The input canvas device (as a marshalled ).
+ /// The input native resource to create a wrapper for.
+ /// The realization DPIs for
+ /// The resulting wrapper for .
+ /// The HRESULT for the operation.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public HRESULT GetOrCreate(IUnknown* device, IUnknown* resource, float dpi, void** wrapper)
+ {
+ return ((delegate* unmanaged)this.lpVtbl[6])(
+ (ICanvasFactoryNative*)Unsafe.AsPointer(ref this),
+ device,
+ resource,
+ dpi,
+ wrapper);
+ }
+
+ ///
+ /// The managed interface for .
+ ///
+ [Guid("695C440D-04B3-4EDD-BFD9-63E51E9F7202")]
+ [WindowsRuntimeType]
+ [WindowsRuntimeHelperType(typeof(Interface))]
+ public interface Interface
+ {
+ ///
+ /// The vtable type for .
+ ///
+ [Guid("695C440D-04B3-4EDD-BFD9-63E51E9F7202")]
+ public readonly struct Vftbl
+ {
+ ///
+ /// Allows CsWinRT to retrieve a pointer to the projection vtable (the name is hardcoded by convention).
+ ///
+ public static readonly IntPtr AbiToProjectionVftablePtr = IUnknownVftbl.AbiToProjectionVftblPtr;
+ }
+ }
+}
\ No newline at end of file
diff --git a/samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/PixelShaderEffect.cs b/samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/PixelShaderEffect.cs
new file mode 100644
index 00000000..44175d6a
--- /dev/null
+++ b/samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/PixelShaderEffect.cs
@@ -0,0 +1,115 @@
+using System;
+using ComputeSharp.D2D1;
+using ComputeSharp.D2D1.WinUI;
+using Microsoft.Graphics.Canvas;
+
+namespace ComputeSharp.SwapChain.D2D1.Backend;
+
+///
+/// An base effect for an animated pixel shader.
+///
+internal abstract class PixelShaderEffect : CanvasEffect
+{
+ ///
+ /// The current elapsed time.
+ ///
+ private TimeSpan elapsedTime;
+
+ ///
+ /// The current screen width in raw pixels.
+ ///
+ private int screenWidth;
+
+ ///
+ /// The current screen height in raw pixels.
+ ///
+ private int screenHeight;
+
+ ///
+ /// Gets or sets the total elapsed time.
+ ///
+ public TimeSpan ElapsedTime
+ {
+ get => this.elapsedTime;
+ set => SetAndInvalidateEffectGraph(ref this.elapsedTime, value);
+ }
+
+ ///
+ /// Gets or sets the screen width in raw pixels.
+ ///
+ public int ScreenWidth
+ {
+ get => this.screenWidth;
+ set => SetAndInvalidateEffectGraph(ref this.screenWidth, value);
+ }
+
+ ///
+ /// Gets or sets the screen height in raw pixels.
+ ///
+ public int ScreenHeight
+ {
+ get => this.screenHeight;
+ set => SetAndInvalidateEffectGraph(ref this.screenHeight, value);
+ }
+
+ ///
+ /// An effect for an animated pixel shader.
+ ///
+ /// The type of pixel shader to render.
+ public sealed class For : PixelShaderEffect
+ where T : unmanaged, ID2D1PixelShader
+ {
+ ///
+ /// The factory to use.
+ ///
+ private readonly Factory factory;
+
+ ///
+ /// The instance in use.
+ ///
+ private PixelShaderEffect? effect;
+
+ ///
+ /// Creates a new instance with the specified parameters.
+ ///
+ /// The input factory.
+ public For(Factory factory)
+ {
+ this.factory = factory;
+ }
+
+ ///
+ protected override ICanvasImage BuildEffectGraph()
+ {
+ this.effect = new PixelShaderEffect();
+
+ return this.effect;
+ }
+
+ ///
+ protected override void ConfigureEffectGraph()
+ {
+ this.effect!.ConstantBuffer = this.factory(ElapsedTime, ScreenWidth, ScreenHeight);
+ }
+
+ ///
+ protected override void Dispose(bool disposing)
+ {
+ base.Dispose(disposing);
+
+ if (disposing)
+ {
+ this.effect?.Dispose();
+ }
+ }
+
+ ///
+ /// A factory of a given shader instance.
+ ///
+ /// The total elapsed time.
+ /// The screen width in raw pixels.
+ /// The screen height in raw pixels.
+ /// A shader instance to render.
+ public delegate T Factory(TimeSpan elapsedTime, int screenWidth, int screenHeight);
+ }
+}
diff --git a/samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/Win32Application.cs b/samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/Win32Application.cs
new file mode 100644
index 00000000..18378ed5
--- /dev/null
+++ b/samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/Win32Application.cs
@@ -0,0 +1,231 @@
+using System;
+using System.Diagnostics.CodeAnalysis;
+using ABI.Microsoft.Graphics.Canvas;
+using TerraFX.Interop.DirectX;
+using TerraFX.Interop.Windows;
+using TerraFX.Interop.WinRT;
+using Windows.Graphics.DirectX;
+using Windows.Graphics.Imaging;
+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;
+
+///
+/// A simple Win32 application handling a D2D swapchain.
+///
+internal sealed class Win32Application
+{
+ ///
+ /// The instance to use.
+ ///
+ private CanvasDevice? canvasDevice;
+
+ ///
+ /// The instance to use to render frames.
+ ///
+ private CanvasSwapChain? canvasSwapChain;
+
+ ///
+ /// Whether or not the window has been resized and requires the buffers to be updated.
+ ///
+ private volatile bool isResizePending;
+
+ ///
+ /// The current screen width in raw pixels.
+ ///
+ private uint screenWidth;
+
+ ///
+ /// The current screen height in raw pixels.
+ ///
+ private uint screenHeight;
+
+ ///
+ /// Raised whenever a draw operation can be performed.
+ ///
+ public event EventHandler? Draw;
+
+ ///
+ /// Initializes the current application.
+ ///
+ /// The handle for the window.
+ [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 direct3DDeviceUnknown = default)
+ using (ComPtr dxgiFactory2 = default)
+ using (ComPtr dxgiSwapChain1 = default)
+ {
+ HRESULT hresult;
+
+ // Extract the underlying Direct3D device from the canvas device.
+ // This is needed for CreateSwapChainForHwnd, as the owning device.
+ using (ComPtr canvasDeviceUnknown = default)
+ using (ComPtr direct3DDxgiInterfaceAccess = default)
+ {
+ canvasDeviceUnknown.Attach((IUnknown*)MarshalInspectable.FromManaged(canvasDevice));
+
+ hresult = canvasDeviceUnknown.CopyTo(direct3DDxgiInterfaceAccess.GetAddressOf());
+
+ ExceptionHelpers.ThrowExceptionForHR(hresult);
+
+ hresult = direct3DDxgiInterfaceAccess.Get()->GetInterface(Windows.__uuidof(), (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(), (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 = this.screenWidth = 1;
+ dxgiSwapChainDesc1.Height = this.screenHeight = 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 canvasFactoryNative = default;
+
+ // Get the activation factory for CanvasDevice
+ using (ComPtr canvasFactoryNativeUnknown = default)
+ {
+ ICanvasFactoryNative.Interface canvasDeviceActivationFactory = CanvasDevice.As();
+
+ canvasFactoryNativeUnknown.Attach((IUnknown*)MarshalInterface.FromManaged(canvasDeviceActivationFactory));
+
+ hresult = canvasFactoryNativeUnknown.CopyTo(canvasFactoryNative.GetAddressOf());
+
+ ExceptionHelpers.ThrowExceptionForHR(hresult);
+ }
+
+ // Create a Win2D wrapper for the swapchain
+ using (ComPtr canvasDeviceUnknown = default)
+ using (ComPtr canvasSwapChainUnknown = default)
+ {
+ canvasDeviceUnknown.Attach((IUnknown*)MarshalInspectable.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.FromAbi((IntPtr)canvasSwapChainUnknown.Get());
+ }
+ }
+
+ // Save the Win2D objects for later use
+ this.canvasDevice = canvasDevice;
+ this.canvasSwapChain = canvasSwapChain;
+ }
+
+ ///
+ /// Resizes the current application.
+ ///
+ public void OnResize()
+ {
+ this.isResizePending = true;
+ }
+
+ ///
+ /// Updates the current application.
+ ///
+ /// The current time since the start of the application.
+ 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);
+
+ BitmapSize bitmapSize = this.canvasSwapChain!.SizeInPixels;
+
+ this.screenWidth = bitmapSize.Width;
+ this.screenHeight = bitmapSize.Height;
+
+ this.isResizePending = false;
+ }
+
+ // Create the drawing session and invoke all registered draw handler
+ using (CanvasDrawingSession canvasDrawingSession = this.canvasSwapChain!.CreateDrawingSession(default))
+ {
+ Draw?.Invoke(this, new DrawEventArgs
+ {
+ ScreenWidth = this.screenWidth,
+ ScreenHeight = this.screenHeight,
+ TotalTime = time,
+ DrawingSession = canvasDrawingSession
+ });
+ }
+
+ // Wait for v-sync
+ this.canvasSwapChain.WaitForVerticalBlank();
+
+ // Present the new frame
+ this.canvasSwapChain.Present(syncInterval: 1);
+ }
+
+ ///
+ /// Arguments for .
+ ///
+ public sealed class DrawEventArgs : EventArgs
+ {
+ ///
+ /// Gets the screen width in raw pixels.
+ ///
+ public required uint ScreenWidth { get; init; }
+
+ ///
+ /// Gets the screen height in raw pixels.
+ ///
+ public required uint ScreenHeight { get; init; }
+
+ ///
+ /// Gets the total time for the rendering loop.
+ ///
+ public required TimeSpan TotalTime { get; init; }
+
+ ///
+ /// Gets the instance to use.
+ ///
+ public required CanvasDrawingSession DrawingSession { get; init; }
+ }
+}
diff --git a/samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/Win32ApplicationRunner.cs b/samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/Win32ApplicationRunner.cs
new file mode 100644
index 00000000..557cb7e0
--- /dev/null
+++ b/samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/Win32ApplicationRunner.cs
@@ -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;
+
+///
+/// A helper class to manage the creation and execution of Win32 applications.
+///
+internal static unsafe class Win32ApplicationRunner
+{
+ ///
+ /// Whether or not a resize operation is in progress.
+ ///
+ private static bool isResizing = false;
+
+ ///
+ /// Whether or not the application is currently paused.
+ ///
+ private static bool isPaused = false;
+
+ ///
+ /// The for the application window.
+ ///
+ private static HWND hwnd;
+
+ ///
+ /// The application being run.
+ ///
+ private static Win32Application application = null!;
+
+ ///
+ /// The thread running the render loop.
+ ///
+ private static Thread renderThread = null!;
+
+ ///
+ /// 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.
+ ///
+ /// The input application instance to run.
+ /// Name of the input application instance to run.
+ /// The title to use for the window being opened.
+ /// The exit code for the application.
+ 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;
+ }
+
+ ///
+ /// Processes incoming messages for a window.
+ ///
+ /// A handle to the window.
+ /// The message.
+ /// Additional message information (the contents depend on the value of ).
+ /// Additional message information (the contents depend on the value of ).
+ /// The result of the message processing for the input message.
+ [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);
+ }
+}
\ No newline at end of file
diff --git a/samples/ComputeSharp.SwapChain.D2D1.Cli/ComputeSharp.SwapChain.D2D1.Cli.csproj b/samples/ComputeSharp.SwapChain.D2D1.Cli/ComputeSharp.SwapChain.D2D1.Cli.csproj
new file mode 100644
index 00000000..5e9b56f4
--- /dev/null
+++ b/samples/ComputeSharp.SwapChain.D2D1.Cli/ComputeSharp.SwapChain.D2D1.Cli.csproj
@@ -0,0 +1,48 @@
+
+
+
+ Exe
+ WinExe
+ net7.0-windows10.0.22621
+ app.manifest
+ x64;ARM64
+ $(NoWarn);IDE0065
+ computesharp.d2d1.cli
+ ..\ComputeSharp.SwapChain.Cli\icon.ico
+
+
+
+
+
+ $(NoWarn);IL2104;IL2026
+
+
+
+
+ true
+ true
+ true
+ Speed
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/ComputeSharp.SwapChain.D2D1.Cli/Program.cs b/samples/ComputeSharp.SwapChain.D2D1.Cli/Program.cs
new file mode 100644
index 00000000..25467b03
--- /dev/null
+++ b/samples/ComputeSharp.SwapChain.D2D1.Cli/Program.cs
@@ -0,0 +1,74 @@
+using System;
+using ComputeSharp.SwapChain.D2D1.Backend;
+using ComputeSharp.SwapChain.Shaders.D2D1;
+using TerraFX.Interop.Windows;
+
+// Accepted inputs:
+// - []
+// - []
+if (args is [] or [_])
+{
+ // If there are no args, just run the default shader
+ if (args is not [string shaderName])
+ {
+ shaderName = nameof(ColorfulInfinity);
+ }
+
+ // Get the requested shader, if possible
+ PixelShaderEffect? effect = shaderName.ToLowerInvariant() switch
+ {
+ "helloworld" => new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))),
+ "colorfulinfinity" => new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))),
+ "fractaltiling" => new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))),
+ "twotiledtruchet" => new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))),
+ "mengerjourney" => new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))),
+ "octagrams" => new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))),
+ "proteanclouds" => new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))),
+ "pyramidpattern" => new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))),
+ "trianglegridcontouring" => new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))),
+ "terracedhills" => new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))),
+ _ => null
+ };
+
+ // If a shader is found, run it
+ if (effect is not null)
+ {
+ Win32Application win32Application = new();
+
+ win32Application.Draw += (_, e) =>
+ {
+ // Set the effect properties
+ effect.ElapsedTime = e.TotalTime;
+ effect.ScreenWidth = (int)e.ScreenWidth;
+ effect.ScreenHeight = (int)e.ScreenHeight;
+
+ // Draw the effect
+ e.DrawingSession.DrawImage(effect);
+ };
+
+ return Win32ApplicationRunner.Run(win32Application, "ComputeSharp.D2D1", "ComputeSharp.D2D1");
+ }
+
+ // If no shader matches, check if help was requested
+ if (shaderName is "-h")
+ {
+ Console.WriteLine($"""
+ Available shaders:
+
+ - {nameof(HelloWorld)}
+ - {nameof(ColorfulInfinity)}
+ - {nameof(FractalTiling)}
+ - {nameof(TwoTiledTruchet)}
+ - {nameof(MengerJourney)}
+ - {nameof(Octagrams)}
+ - {nameof(ProteanClouds)}
+ - {nameof(PyramidPattern)}
+ - {nameof(TriangleGridContouring)}
+ - {nameof(TerracedHills)}
+ """);
+
+ return S.S_OK;
+ }
+}
+
+return E.E_INVALIDARG;
\ No newline at end of file
diff --git a/samples/ComputeSharp.SwapChain.D2D1.Cli/Properties/Default.rd.xml b/samples/ComputeSharp.SwapChain.D2D1.Cli/Properties/Default.rd.xml
new file mode 100644
index 00000000..95116ed6
--- /dev/null
+++ b/samples/ComputeSharp.SwapChain.D2D1.Cli/Properties/Default.rd.xml
@@ -0,0 +1,15 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/samples/ComputeSharp.SwapChain.D2D1.Cli/app.manifest b/samples/ComputeSharp.SwapChain.D2D1.Cli/app.manifest
new file mode 100644
index 00000000..526a6e63
--- /dev/null
+++ b/samples/ComputeSharp.SwapChain.D2D1.Cli/app.manifest
@@ -0,0 +1,9 @@
+
+
+
+
+ true
+ PerMonitorV2
+
+
+
diff --git a/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs b/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs
index 41713dbe..d4d15aec 100644
--- a/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs
+++ b/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs
@@ -71,7 +71,7 @@ internal sealed class SwapChainApplication : Win32Application
///
/// Whether or not the window has been resized and requires the buffers to be updated.
///
- private bool isResizePending;
+ private volatile bool isResizePending;
///
/// Creates a new instance with the specified parameters.
diff --git a/samples/ComputeSharp.SwapChain/Backend/Win32ApplicationRunner.cs b/samples/ComputeSharp.SwapChain/Backend/Win32ApplicationRunner.cs
index e6dd3c90..d7445763 100644
--- a/samples/ComputeSharp.SwapChain/Backend/Win32ApplicationRunner.cs
+++ b/samples/ComputeSharp.SwapChain/Backend/Win32ApplicationRunner.cs
@@ -340,6 +340,7 @@ internal static unsafe class Win32ApplicationRunner
case WM.WM_DESTROY:
{
Windows.PostQuitMessage(0);
+
return 0;
}
}