From 35e21eadbd289106a7271b69795fe93a96d79563 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 30 Jul 2024 23:07:04 -0700 Subject: [PATCH] Refactor render code into 'CoreApplication' helpers --- .../Program.cs | 6 +- .../App.cs | 46 ++---- .../Backend/CoreWindowApplication.cs | 145 ++++++++++++++++++ .../Backend/CoreWindowApplicationRunner.cs | 53 +++++++ .../Backend/PixelShaderEffect.cs | 89 +++++++++++ 5 files changed, 302 insertions(+), 37 deletions(-) create mode 100644 samples/ComputeSharp.SwapChain.D2D1.CoreWindow/Backend/CoreWindowApplication.cs create mode 100644 samples/ComputeSharp.SwapChain.D2D1.CoreWindow/Backend/CoreWindowApplicationRunner.cs create mode 100644 samples/ComputeSharp.SwapChain.D2D1.CoreWindow/Backend/PixelShaderEffect.cs diff --git a/samples/ComputeSharp.SwapChain.D2D1.Cli/Program.cs b/samples/ComputeSharp.SwapChain.D2D1.Cli/Program.cs index fddaba8f..629eea49 100644 --- a/samples/ComputeSharp.SwapChain.D2D1.Cli/Program.cs +++ b/samples/ComputeSharp.SwapChain.D2D1.Cli/Program.cs @@ -33,9 +33,9 @@ if (args is [] or [_]) // If a shader is found, run it if (effect is not null) { - Win32Application win32Application = new(); + Win32Application application = new(); - win32Application.Draw += (_, e) => + application.Draw += (_, e) => { // Set the effect properties effect.ElapsedTime = e.TotalTime; @@ -46,7 +46,7 @@ if (args is [] or [_]) e.DrawingSession.DrawImage(effect); }; - Win32ApplicationRunner.Run(win32Application, "ComputeSharp.D2D1"); + Win32ApplicationRunner.Run(application, "ComputeSharp.D2D1"); return S.S_OK; } diff --git a/samples/ComputeSharp.SwapChain.D2D1.CoreWindow/App.cs b/samples/ComputeSharp.SwapChain.D2D1.CoreWindow/App.cs index d1af0c69..c6b7d5d0 100644 --- a/samples/ComputeSharp.SwapChain.D2D1.CoreWindow/App.cs +++ b/samples/ComputeSharp.SwapChain.D2D1.CoreWindow/App.cs @@ -1,14 +1,8 @@ -using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -using System.Threading; -using ComputeSharp.D2D1.Uwp; +using ComputeSharp.SwapChain.D2D1.Backend; using ComputeSharp.SwapChain.D2D1.Extensions; using ComputeSharp.SwapChain.Shaders.D2D1; -using Microsoft.Graphics.Canvas; -using Microsoft.Graphics.Canvas.Effects; using Windows.ApplicationModel.Core; -using Windows.Graphics.Display; -using Windows.UI; using Windows.UI.Core; using Windows.UI.ViewManagement; @@ -69,38 +63,22 @@ public sealed partial class App : IFrameworkViewSource, IFrameworkView ApplicationView.GetForCurrentView().TitleBar.StyleTitleBarForExtendedIntoViewMode(); - CanvasSwapChain swapChain = CanvasSwapChain.CreateForCoreWindow( - CanvasDevice.GetSharedDevice(), - this.window, - DisplayInformation.GetForCurrentView().LogicalDpi); + PixelShaderEffect effect = new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))); - int2 sizeInPixels = new((int)swapChain.SizeInPixels.Width, (int)swapChain.SizeInPixels.Height); - CancellationTokenSource cancellationTokenSource = new(); - Stopwatch stopwatch = Stopwatch.StartNew(); + CoreWindowApplication application = new(); - Thread thread = new(() => + application.Draw += (s, e) => { - PixelShaderEffect shader = new(); - PremultiplyEffect premultiply = new() { Source = shader }; + // Set the effect properties + effect.ElapsedTime = e.TotalTime; + effect.ScreenWidth = (int)e.ScreenWidth; + effect.ScreenHeight = (int)e.ScreenHeight; - while (!cancellationTokenSource.IsCancellationRequested) - { - using (CanvasDrawingSession session = swapChain.CreateDrawingSession(Colors.Transparent)) - { - shader.ConstantBuffer = new ColorfulInfinity((float)stopwatch.Elapsed.TotalSeconds, sizeInPixels); + // Draw the effect + e.DrawingSession.DrawImage(effect); + }; - session.DrawImage(premultiply); - } - - swapChain.Present(syncInterval: 1); - } - }); - - thread.Start(); - - this.window!.Activate(); - - this.window.Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessUntilQuit); + CoreWindowApplicationRunner.Run(application, this.window!); } /// diff --git a/samples/ComputeSharp.SwapChain.D2D1.CoreWindow/Backend/CoreWindowApplication.cs b/samples/ComputeSharp.SwapChain.D2D1.CoreWindow/Backend/CoreWindowApplication.cs new file mode 100644 index 00000000..725c97bb --- /dev/null +++ b/samples/ComputeSharp.SwapChain.D2D1.CoreWindow/Backend/CoreWindowApplication.cs @@ -0,0 +1,145 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using Microsoft.Graphics.Canvas; +using Windows.Graphics.Display; +using Windows.Graphics.Imaging; +using Windows.UI.Core; + +namespace ComputeSharp.SwapChain.D2D1.Backend; + +/// +/// A simple application handling a D2D swapchain. +/// +internal sealed class CoreWindowApplication +{ + /// + /// 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 instance. + [MemberNotNull(nameof(canvasDevice))] + [MemberNotNull(nameof(canvasSwapChain))] + public unsafe void OnInitialize(CoreWindow window) + { + // Create a new canvas device, which will handle DX11/D2D initialization + CanvasDevice canvasDevice = new(); + + // Create the swapchain for rendering (it is automatically tied to the window) + CanvasSwapChain canvasSwapChain = CanvasSwapChain.CreateForCoreWindow( + resourceCreator: canvasDevice, + coreWindow: window, + dpi: DisplayInformation.GetForCurrentView().LogicalDpi); + + // Save the Win2D objects for later use + this.canvasDevice = canvasDevice; + this.canvasSwapChain = canvasSwapChain; + + // Store the initial size of the screen + this.screenWidth = canvasSwapChain.SizeInPixels.Width; + this.screenHeight = canvasSwapChain.SizeInPixels.Height; + } + + /// + /// 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: DisplayInformation.GetForCurrentView().LogicalDpi); + + 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; } + } +} \ No newline at end of file diff --git a/samples/ComputeSharp.SwapChain.D2D1.CoreWindow/Backend/CoreWindowApplicationRunner.cs b/samples/ComputeSharp.SwapChain.D2D1.CoreWindow/Backend/CoreWindowApplicationRunner.cs new file mode 100644 index 00000000..20772756 --- /dev/null +++ b/samples/ComputeSharp.SwapChain.D2D1.CoreWindow/Backend/CoreWindowApplicationRunner.cs @@ -0,0 +1,53 @@ +using System.Diagnostics; +using System.Threading; +using Windows.UI.Core; + +namespace ComputeSharp.SwapChain.D2D1.Backend; + +/// +/// A helper class to manage the creation and execution of applications. +/// +internal static class CoreWindowApplicationRunner +{ + /// + /// 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. + /// The instance. + public static void Run(CoreWindowApplication application, CoreWindow window) + { + // Initialize the application + application.OnInitialize(window); + + // Setup the render thread that enables smooth resizing of the window + Thread renderThread = new(static args => + { + (CoreWindowApplication application, CancellationToken token) = ((CoreWindowApplication, CancellationToken))args!; + + Stopwatch stopwatch = Stopwatch.StartNew(); + + while (!token.IsCancellationRequested) + { + application.OnUpdate(stopwatch.Elapsed); + } + }); + + CancellationTokenSource tokenSource = new(); + + // Start the render thread before activating the window. + // This allows the app to show up while already drawing. + renderThread.Start((application, tokenSource.Token)); + + // Activate the window + window.Activate(); + + // Process any messages in the queue + window.Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessUntilQuit); + + tokenSource.Cancel(); + + // Wait for the render thread to stop before terminating + renderThread.Join(); + } +} \ No newline at end of file diff --git a/samples/ComputeSharp.SwapChain.D2D1.CoreWindow/Backend/PixelShaderEffect.cs b/samples/ComputeSharp.SwapChain.D2D1.CoreWindow/Backend/PixelShaderEffect.cs new file mode 100644 index 00000000..dd97480f --- /dev/null +++ b/samples/ComputeSharp.SwapChain.D2D1.CoreWindow/Backend/PixelShaderEffect.cs @@ -0,0 +1,89 @@ +using System; +using ComputeSharp.D2D1; +using ComputeSharp.D2D1.Descriptors; +using ComputeSharp.D2D1.Uwp; + +namespace ComputeSharp.SwapChain.D2D1.Backend; + +/// +/// An base effect for an animated pixel shader. +/// +internal abstract partial 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. + /// The input factory. + public sealed partial class For(For.Factory factory) : PixelShaderEffect + where T : unmanaged, ID2D1PixelShader, ID2D1PixelShaderDescriptor + { + /// + /// The node in use. + /// + private static readonly CanvasEffectNode> Effect = new(); + + /// + protected override void BuildEffectGraph(CanvasEffectGraph effectGraph) + { + effectGraph.RegisterOutputNode(Effect, new PixelShaderEffect()); + } + + /// + protected override void ConfigureEffectGraph(CanvasEffectGraph effectGraph) + { + effectGraph.GetNode(Effect).ConstantBuffer = factory(ElapsedTime, ScreenWidth, ScreenHeight); + } + + /// + /// 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); + } +} \ No newline at end of file