From 993f32e2bb28fca80a5aea3b4d37bc8c219e3fab Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 22 Feb 2021 13:06:15 +0100 Subject: [PATCH 01/16] Added SwapChain project and basic window setup --- ComputeSharp.sln | 11 + .../ComputeSharp.Sample.SwapChain.csproj | 16 ++ .../ComputeSharp.Sample.SwapChain/Program.cs | 35 +++ .../Win32ApplicationRunner.cs | 243 ++++++++++++++++++ 4 files changed, 305 insertions(+) create mode 100644 samples/ComputeSharp.Sample.SwapChain/ComputeSharp.Sample.SwapChain.csproj create mode 100644 samples/ComputeSharp.Sample.SwapChain/Program.cs create mode 100644 samples/ComputeSharp.Sample.SwapChain/Win32ApplicationRunner.cs diff --git a/ComputeSharp.sln b/ComputeSharp.sln index cccc08d6..7e4f1344 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -47,6 +47,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Tests.Internal EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Tests.NativeLibrariesResolver", "tests\ComputeSharp.Tests.NativeLibrariesResolver\ComputeSharp.Tests.NativeLibrariesResolver.csproj", "{BF52326F-E415-49E6-8595-62762216762B}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.Sample.SwapChain", "samples\ComputeSharp.Sample.SwapChain\ComputeSharp.Sample.SwapChain.csproj", "{E7C9247D-016B-4819-AF9F-0E9B3591E04B}" +EndProject Global GlobalSection(SharedMSBuildProjectFiles) = preSolution samples\ComputeSharp.Sample.Shared\ComputeSharp.Sample.Shared.projitems*{7048deea-0a6f-46a0-b951-b682a8f1cb75}*SharedItemsImports = 5 @@ -172,6 +174,14 @@ Global {BF52326F-E415-49E6-8595-62762216762B}.Release|Any CPU.Build.0 = Release|Any CPU {BF52326F-E415-49E6-8595-62762216762B}.Release|x64.ActiveCfg = Release|Any CPU {BF52326F-E415-49E6-8595-62762216762B}.Release|x64.Build.0 = Release|Any CPU + {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Debug|x64.ActiveCfg = Debug|Any CPU + {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Debug|x64.Build.0 = Debug|Any CPU + {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Release|Any CPU.Build.0 = Release|Any CPU + {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Release|x64.ActiveCfg = Release|Any CPU + {E7C9247D-016B-4819-AF9F-0E9B3591E04B}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -187,6 +197,7 @@ Global {8CEFC324-CA6C-4845-9AD9-70B92BD87057} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} {BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} {BF52326F-E415-49E6-8595-62762216762B} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} + {E7C9247D-016B-4819-AF9F-0E9B3591E04B} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC} diff --git a/samples/ComputeSharp.Sample.SwapChain/ComputeSharp.Sample.SwapChain.csproj b/samples/ComputeSharp.Sample.SwapChain/ComputeSharp.Sample.SwapChain.csproj new file mode 100644 index 00000000..44b2ad45 --- /dev/null +++ b/samples/ComputeSharp.Sample.SwapChain/ComputeSharp.Sample.SwapChain.csproj @@ -0,0 +1,16 @@ + + + + Exe + net5.0 + + + + + + + + diff --git a/samples/ComputeSharp.Sample.SwapChain/Program.cs b/samples/ComputeSharp.Sample.SwapChain/Program.cs new file mode 100644 index 00000000..bb263015 --- /dev/null +++ b/samples/ComputeSharp.Sample.SwapChain/Program.cs @@ -0,0 +1,35 @@ +using System; +using System.Drawing; +using TerraFX.Interop; + +namespace ComputeSharp.Sample.SwapChain +{ + class Program + { + static void Main(string[] args) + { + Win32ApplicationRunner.Run(); + } + } + + internal sealed class FractalTilesApplication : Win32Application + { + public override string Title => "Fractal tiles"; + + public override void Dispose() + { + } + + public override void OnInitialize(Size size, HWND hwnd) + { + } + + public override void OnResize(Size size) + { + } + + public override void OnUpdate(TimeSpan time) + { + } + } +} diff --git a/samples/ComputeSharp.Sample.SwapChain/Win32ApplicationRunner.cs b/samples/ComputeSharp.Sample.SwapChain/Win32ApplicationRunner.cs new file mode 100644 index 00000000..b33dac6f --- /dev/null +++ b/samples/ComputeSharp.Sample.SwapChain/Win32ApplicationRunner.cs @@ -0,0 +1,243 @@ +using System; +using System.Diagnostics; +using System.Drawing; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Threading; +using TerraFX.Interop; +using FX = TerraFX.Interop.Windows; + +namespace ComputeSharp.Sample.SwapChain +{ + internal abstract class Win32Application : IDisposable + { + public abstract string Title { get; } + + public abstract void OnInitialize(Size size, HWND hwnd); + + public abstract void OnResize(Size size); + + public abstract void OnUpdate(TimeSpan time); + + public abstract void Dispose(); + } + + /// + /// A helper class to manage the creation and execution of Win32 applications. + /// + internal unsafe static class Win32ApplicationRunner + { + private static bool isResizing = false; + private static bool isPaused = false; + private static HWND hwnd; + private static Size windowSize; + private static Stopwatch stopwatch = null!; + private static Win32Application application = null!; + private static long elapsedMillisecondsForLastTitleUpdate; + private static int elapsedFramesSinceLastTitleUpdate; + + public static int Run() + where T : Win32Application, new() + { + application = new T(); + + IntPtr hInstance = FX.GetModuleHandleW(null); + uint width = 1280; + uint height = 720; + + fixed (char* name = Assembly.GetExecutingAssembly().FullName) + fixed (char* windowTitle = application.Title) + { + // Initialize the window class + WNDCLASSEXW windowClassEx = new() + { + cbSize = (uint)sizeof(WNDCLASSEXW), + style = FX.CS_HREDRAW | FX.CS_VREDRAW, + lpfnWndProc = &WindowProc, + hInstance = hInstance, + hCursor = FX.LoadCursorW(IntPtr.Zero, FX.MAKEINTRESOURCE(32512)), + lpszClassName = (ushort*)name + }; + + // Register the window class + _ = FX.RegisterClassExW(&windowClassEx); + + Rectangle windowRect = new(0, 0, (int)width, (int)height); + + // Set the target window size + _ = FX.AdjustWindowRect((RECT*)&windowRect, FX.WS_OVERLAPPEDWINDOW, FX.FALSE); + + height = (uint)(windowRect.Bottom - windowRect.Top); + width = (uint)(windowRect.Right - windowRect.Left); + + // Create the window and store a handle to it + hwnd = FX.CreateWindowExW( + 0, + windowClassEx.lpszClassName, + (ushort*)windowTitle, + FX.WS_OVERLAPPEDWINDOW, + FX.CW_USEDEFAULT, + FX.CW_USEDEFAULT, + (int)width, + (int)height, + HWND.NULL, + HMENU.NULL, + hInstance, + (void*)GCHandle.ToIntPtr(GCHandle.Alloc(application)) + ); + } + + windowSize = new Size((int)height, (int)width); + + // Initialize the application + application.OnInitialize(windowSize, hwnd); + + // Display the window + _ = FX.ShowWindow(hwnd, FX.SW_SHOWDEFAULT); + + // Start the timer + stopwatch = Stopwatch.StartNew(); + + MSG msg = default; + + // Process any messages in the queue + while (msg.message != FX.WM_QUIT) + { + if (FX.PeekMessageW(&msg, HWND.NULL, 0, 0, FX.PM_REMOVE) != 0) + { + _ = FX.TranslateMessage(&msg); + _ = FX.DispatchMessageW(&msg); + } + else if (!isPaused || true) + { + RunApp(); + } + else + { + Thread.Sleep(100); + } + } + + application.Dispose(); + + // Return this part of the WM_QUIT message to Windows + return (int)msg.wParam; + } + + /// + /// The application state update method that is invoked within the main application loop. + /// + private static void RunApp() + { + // Update window title approx every second + if (stopwatch.ElapsedMilliseconds - elapsedMillisecondsForLastTitleUpdate >= 1000) + { + string title = isPaused switch + { + true => $"{application.Title} - Paused", + false => $"{application.Title} - FPS: {elapsedFramesSinceLastTitleUpdate}" + }; + + fixed (char* pTitle = title) + { + _ = FX.SetWindowTextW(hwnd, (ushort*)pTitle); + } + + elapsedMillisecondsForLastTitleUpdate = stopwatch.ElapsedMilliseconds; + elapsedFramesSinceLastTitleUpdate = 0; + } + + // Update the application state + application.OnUpdate(stopwatch.Elapsed); + } + + /// + /// 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 nint WindowProc(IntPtr hwnd, uint uMsg, nuint wParam, nint lParam) + { + switch (uMsg) + { + // Change the paused state on window activation + case FX.WM_ACTIVATE: + { + if (FX.LOWORD(wParam) == FX.WA_INACTIVE) + { + isPaused = true; + } + else + { + isPaused = false; + } + return 0; + } + + // Change the paused state when ESC is pressed + case FX.WM_KEYDOWN: + { + if ((ConsoleKey)wParam == ConsoleKey.Escape) + { + + if (isPaused) + { + FX.SetCapture(Win32ApplicationRunner.hwnd); + } + else + { + FX.ReleaseCapture(); + } + + isPaused = !isPaused; + } + + return 0; + } + + // Window resize started + case FX.WM_ENTERSIZEMOVE: + { + isResizing = true; + + return 0; + } + + // Window resize completed + case FX.WM_EXITSIZEMOVE: + { + isResizing = false; + application.OnResize(windowSize); + + return 0; + } + case FX.WM_SIZE: + { + uint size = (uint)lParam; + + windowSize = new Size(FX.LOWORD(size), FX.HIWORD(size)); + + if (!isResizing && wParam != FX.SIZE_MINIMIZED) + { + application.OnResize(windowSize); + } + + return 0; + } + + // Shutdown + case FX.WM_DESTROY: + { + FX.PostQuitMessage(0); + return 0; + } + } + + return FX.DefWindowProcW(hwnd, uMsg, wParam, lParam); + } + } +} \ No newline at end of file From 23791ee4efe1b4c89268b21197529eb5aebb657c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 22 Feb 2021 14:15:15 +0100 Subject: [PATCH 02/16] Added swap chain initialization code --- .../ComputeSharp.Sample.SwapChain/Program.cs | 123 +++++++++++++++++- .../Win32ApplicationRunner.cs | 44 ++++++- 2 files changed, 162 insertions(+), 5 deletions(-) diff --git a/samples/ComputeSharp.Sample.SwapChain/Program.cs b/samples/ComputeSharp.Sample.SwapChain/Program.cs index bb263015..66f488b5 100644 --- a/samples/ComputeSharp.Sample.SwapChain/Program.cs +++ b/samples/ComputeSharp.Sample.SwapChain/Program.cs @@ -1,6 +1,8 @@ using System; using System.Drawing; +using ComputeSharp.Interop; using TerraFX.Interop; +using FX = TerraFX.Interop.Windows; namespace ComputeSharp.Sample.SwapChain { @@ -14,14 +16,123 @@ namespace ComputeSharp.Sample.SwapChain internal sealed class FractalTilesApplication : Win32Application { + /// + /// 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 = 1; + + /// + /// The instance used to display content onto the target window. + /// + private ComPtr dxgiSwapChain1; + + /// + /// 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 uint currentBufferIndex; + public override string Title => "Fractal tiles"; - public override void Dispose() + public override unsafe void OnInitialize(Size size, HWND hwnd) { - } + // Get the underlying ID3D12Device in use + fixed (ID3D12Device** d3D12Device = this.d3D12Device) + { + _ = InteropServices.TryGetID3D12Device(Gpu.Default, FX.__uuidof(), (void**)d3D12Device); + } - public override void OnInitialize(Size size, HWND hwnd) - { + // 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; + + _ = d3D12Device.Get()->CreateCommandQueue( + &d3D12CommandQueueDesc, + FX.__uuidof(), + (void**)d3D12CommandQueue); + } + + // Create the direct fence + fixed (ID3D12Fence** d3D12Fence = this.d3D12Fence) + { + _ = this.d3D12Device.Get()->CreateFence( + 0, + D3D12_FENCE_FLAGS.D3D12_FENCE_FLAG_NONE, + FX.__uuidof(), + (void**)d3D12Fence); + } + + // Create the swap chain to display frames + fixed (IDXGISwapChain1** dxgiSwapChain1 = this.dxgiSwapChain1) + { + using ComPtr dxgiFactory2 = default; + + _ = FX.CreateDXGIFactory2(FX.DXGI_CREATE_FACTORY_DEBUG, FX.__uuidof(), (void**)dxgiFactory2.GetAddressOf()); + + DXGI_SWAP_CHAIN_DESC1 dxgiSwapChainDesc1 = default; + dxgiSwapChainDesc1.AlphaMode = DXGI_ALPHA_MODE.DXGI_ALPHA_MODE_IGNORE; + dxgiSwapChainDesc1.BufferCount = 2; + dxgiSwapChainDesc1.Flags = 0; + dxgiSwapChainDesc1.Format = DXGI_FORMAT.DXGI_FORMAT_B8G8R8A8_UNORM; + dxgiSwapChainDesc1.Width = 0; + dxgiSwapChainDesc1.Height = 0; + 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; + + _ = dxgiFactory2.Get()->CreateSwapChainForHwnd( + (IUnknown*)d3D12CommandQueue.Get(), + hwnd, + &dxgiSwapChainDesc1, + null, + null, + dxgiSwapChain1); + } + + // Retrieve the back buffers for the swap chain + fixed (ID3D12Resource** d3D12Resource0 = this.d3D12Resource0) + fixed (ID3D12Resource** d3D12Resource1 = this.d3D12Resource1) + { + _ = dxgiSwapChain1.Get()->GetBuffer(0, FX.__uuidof(), (void**)d3D12Resource0); + _ = dxgiSwapChain1.Get()->GetBuffer(1, FX.__uuidof(), (void**)d3D12Resource1); + } + + // Get the index of the current buffer + using ComPtr dxgiSwapChain3 = default; + + _ = this.dxgiSwapChain1.CopyTo(dxgiSwapChain3.GetAddressOf()); + + this.currentBufferIndex = dxgiSwapChain3.Get()->GetCurrentBackBufferIndex(); } public override void OnResize(Size size) @@ -31,5 +142,9 @@ namespace ComputeSharp.Sample.SwapChain public override void OnUpdate(TimeSpan time) { } + + public override void Dispose() + { + } } } diff --git a/samples/ComputeSharp.Sample.SwapChain/Win32ApplicationRunner.cs b/samples/ComputeSharp.Sample.SwapChain/Win32ApplicationRunner.cs index b33dac6f..a0ec1e0e 100644 --- a/samples/ComputeSharp.Sample.SwapChain/Win32ApplicationRunner.cs +++ b/samples/ComputeSharp.Sample.SwapChain/Win32ApplicationRunner.cs @@ -27,15 +27,55 @@ namespace ComputeSharp.Sample.SwapChain /// internal unsafe static 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 current size of the application window. + /// private static Size windowSize; + + /// + /// A instance used to track the elapsed time for the application. + /// private static Stopwatch stopwatch = null!; + + /// + /// The application being run. + /// private static Win32Application application = null!; + + /// + /// The number of elapsed milliseconds since the window title was last updated. + /// private static long elapsedMillisecondsForLastTitleUpdate; + + /// + /// The number of elapsed frames since the window title was last updated. + /// private static int elapsedFramesSinceLastTitleUpdate; + /// + /// Runs a specified application and starts the main loop to update its state. + /// This is the entry point for a given application of type , and it should be + /// called as soon as the process is launched, excluding any other additional initialization needed. + /// To launch an application, simply add this line to the project being used: + /// Win32ApplicationRunner.Run<MyApplication>(); + /// + /// The type of application being launched. + /// The exit code for the application. public static int Run() where T : Win32Application, new() { @@ -149,6 +189,8 @@ namespace ComputeSharp.Sample.SwapChain // Update the application state application.OnUpdate(stopwatch.Elapsed); + + elapsedFramesSinceLastTitleUpdate++; } /// @@ -186,7 +228,7 @@ namespace ComputeSharp.Sample.SwapChain if (isPaused) { - FX.SetCapture(Win32ApplicationRunner.hwnd); + FX.SetCapture(hwnd); } else { From 69f9c26565fd57e30245f9d13cfb32c575d79e5e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 22 Feb 2021 14:46:36 +0100 Subject: [PATCH 03/16] Fixed mip level when creating textures --- .../Extensions/ID3D12DeviceExtensions.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs b/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs index f7f1bd7e..bf11e1db 100644 --- a/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs +++ b/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs @@ -236,7 +236,7 @@ namespace ComputeSharp.Graphics.Extensions d3D12HeapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; } - D3D12_RESOURCE_DESC d3D12ResourceDescription = D3D12_RESOURCE_DESC.Tex2D(dxgiFormat, width, height, flags: d3D12ResourceFlags); + D3D12_RESOURCE_DESC d3D12ResourceDescription = D3D12_RESOURCE_DESC.Tex2D(dxgiFormat, width, height, mipLevels: 1, flags: d3D12ResourceFlags); d3D12Device.CreateCommittedResource( &d3D12HeapProperties, @@ -302,7 +302,7 @@ namespace ComputeSharp.Graphics.Extensions d3D12HeapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; } - D3D12_RESOURCE_DESC d3D12ResourceDescription = D3D12_RESOURCE_DESC.Tex3D(dxgiFormat, width, height, depth, flags: d3D12ResourceFlags); + D3D12_RESOURCE_DESC d3D12ResourceDescription = D3D12_RESOURCE_DESC.Tex3D(dxgiFormat, width, height, depth, mipLevels: 1, flags: d3D12ResourceFlags); d3D12Device.CreateCommittedResource( &d3D12HeapProperties, From a2a121407b3ad949855fb9486a2872b2aca2a057 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 22 Feb 2021 14:46:53 +0100 Subject: [PATCH 04/16] Implemented initial image rendering --- .../ComputeSharp.Sample.SwapChain/Program.cs | 107 +++++++++++++++++- 1 file changed, 106 insertions(+), 1 deletion(-) diff --git a/samples/ComputeSharp.Sample.SwapChain/Program.cs b/samples/ComputeSharp.Sample.SwapChain/Program.cs index 66f488b5..853bb58d 100644 --- a/samples/ComputeSharp.Sample.SwapChain/Program.cs +++ b/samples/ComputeSharp.Sample.SwapChain/Program.cs @@ -102,7 +102,7 @@ namespace ComputeSharp.Sample.SwapChain dxgiSwapChainDesc1.AlphaMode = DXGI_ALPHA_MODE.DXGI_ALPHA_MODE_IGNORE; dxgiSwapChainDesc1.BufferCount = 2; dxgiSwapChainDesc1.Flags = 0; - dxgiSwapChainDesc1.Format = DXGI_FORMAT.DXGI_FORMAT_B8G8R8A8_UNORM; + dxgiSwapChainDesc1.Format = DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_UNORM; dxgiSwapChainDesc1.Width = 0; dxgiSwapChainDesc1.Height = 0; dxgiSwapChainDesc1.SampleDesc = new DXGI_SAMPLE_DESC(count: 1, quality: 0); @@ -133,6 +133,76 @@ namespace ComputeSharp.Sample.SwapChain _ = this.dxgiSwapChain1.CopyTo(dxgiSwapChain3.GetAddressOf()); this.currentBufferIndex = dxgiSwapChain3.Get()->GetCurrentBackBufferIndex(); + + // ============== + // SAMPLE + // ============== + + var desc = this.d3D12Resource0.Get()->GetDesc(); + + int width = (int)desc.Width; + int height = (int)desc.Height; + + using ReadWriteTexture2D texture = Gpu.Default.AllocateReadWriteTexture2D(width, height); + + Gpu.Default.For(texture.Width, texture.Height, new FractalTiling(texture, 0)); + + ID3D12Resource* resource; + + _ = InteropServices.TryGetID3D12Resource(texture, FX.__uuidof(), (void**)&resource); + + using ComPtr d3D12CommandAllocator = default; + + this.d3D12Device.Get()->CreateCommandAllocator( + D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT, + FX.__uuidof(), + (void**)d3D12CommandAllocator.GetAddressOf()); + + using ComPtr d3D12GraphicsCommandList = default; + + this.d3D12Device.Get()->CreateCommandList( + 0, + D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT, + d3D12CommandAllocator, + null, + FX.__uuidof(), + (void**)d3D12GraphicsCommandList.GetAddressOf()); + + D3D12_RESOURCE_BARRIER d3D12ResourceBarrierBefore = D3D12_RESOURCE_BARRIER.InitTransition( + resource, + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_SOURCE); + + d3D12GraphicsCommandList.Get()->ResourceBarrier(1, &d3D12ResourceBarrierBefore); + + D3D12_RESOURCE_BARRIER d3D12ResourceBarrierBefore0 = D3D12_RESOURCE_BARRIER.InitTransition( + this.d3D12Resource0.Get(), + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_DEST); + + d3D12GraphicsCommandList.Get()->ResourceBarrier(1, &d3D12ResourceBarrierBefore0); + + d3D12GraphicsCommandList.Get()->CopyResource(this.d3D12Resource0.Get(), resource); + + D3D12_RESOURCE_BARRIER d3D12ResourceBarrierAfter = D3D12_RESOURCE_BARRIER.InitTransition( + resource, + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + + d3D12GraphicsCommandList.Get()->ResourceBarrier(1, &d3D12ResourceBarrierAfter); + + D3D12_RESOURCE_BARRIER d3D12ResourceBarrierAfter0 = D3D12_RESOURCE_BARRIER.InitTransition( + this.d3D12Resource0.Get(), + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COMMON); + + d3D12GraphicsCommandList.Get()->ResourceBarrier(1, &d3D12ResourceBarrierAfter0); + + d3D12GraphicsCommandList.Get()->Close(); + + this.d3D12CommandQueue.Get()->ExecuteCommandLists(1, (ID3D12CommandList**)d3D12GraphicsCommandList.GetAddressOf()); + + this.dxgiSwapChain1.Get()->Present(0, 0); } public override void OnResize(Size size) @@ -147,4 +217,39 @@ namespace ComputeSharp.Sample.SwapChain { } } + + [AutoConstructor] + internal readonly partial struct FractalTiling : IComputeShader + { + public readonly IReadWriteTexture2D texture; + public readonly float time; + + /// + public void Execute() + { + Float2 position = ((Float2)(256 * ThreadIds.XY)) / texture.Width + time; + Float4 color = 0; + + for (int i = 0; i < 6; i++) + { + Float2 a = Hlsl.Floor(position); + Float2 b = Hlsl.Frac(position); + Float4 w = Hlsl.Frac( + (Hlsl.Sin(a.X * 7 + 31.0f * a.Y + 0.01f * time) + + new Float4(0.035f, 0.01f, 0, 0.7f)) + * 13.545317f); + + color.XYZ += w.XYZ * + 2.0f * Hlsl.SmoothStep(0.45f, 0.55f, w.W) * + Hlsl.Sqrt(16.0f * b.X * b.Y * (1.0f - b.X) * (1.0f - b.Y)); + + position /= 2.0f; + color /= 2.0f; + } + + color.XYZ = Hlsl.Pow(color.XYZ, new Float3(0.7f, 0.8f, 0.5f)); + + texture[ThreadIds.XY] = color; + } + } } From e36afbfca6b95ce735e2f27366ea5e4099f1065b Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 22 Feb 2021 15:55:01 +0100 Subject: [PATCH 05/16] Implemented swap chain animation --- .../ComputeSharp.Sample.SwapChain/Program.cs | 189 +++++++++++------- 1 file changed, 117 insertions(+), 72 deletions(-) diff --git a/samples/ComputeSharp.Sample.SwapChain/Program.cs b/samples/ComputeSharp.Sample.SwapChain/Program.cs index 853bb58d..04f4b087 100644 --- a/samples/ComputeSharp.Sample.SwapChain/Program.cs +++ b/samples/ComputeSharp.Sample.SwapChain/Program.cs @@ -1,6 +1,7 @@ using System; using System.Drawing; using ComputeSharp.Interop; +using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; @@ -34,7 +35,17 @@ namespace ComputeSharp.Sample.SwapChain /// /// The next fence value for graphics operations using . /// - //private ulong nextD3D12FenceValue = 1; + private ulong nextD3D12FenceValue = 1; + + /// + /// The object to create command lists. + /// + private ComPtr d3D12CommandAllocator; + + /// + /// The instance used to copy data to the back buffers. + /// + private ComPtr d3D12GraphicsCommandList; /// /// The instance used to display content onto the target window. @@ -56,6 +67,11 @@ namespace ComputeSharp.Sample.SwapChain /// private uint currentBufferIndex; + /// + /// The instance used to prepare frames to display. + /// + private ReadWriteTexture2D texture = null!; + public override string Title => "Fractal tiles"; public override unsafe void OnInitialize(Size size, HWND hwnd) @@ -127,90 +143,119 @@ namespace ComputeSharp.Sample.SwapChain _ = dxgiSwapChain1.Get()->GetBuffer(1, FX.__uuidof(), (void**)d3D12Resource1); } - // Get the index of the current buffer - using ComPtr dxgiSwapChain3 = default; + // Get the index of the initial back buffer + using (ComPtr dxgiSwapChain3 = default) + { + _ = this.dxgiSwapChain1.CopyTo(dxgiSwapChain3.GetAddressOf()); - _ = this.dxgiSwapChain1.CopyTo(dxgiSwapChain3.GetAddressOf()); + this.currentBufferIndex = dxgiSwapChain3.Get()->GetCurrentBackBufferIndex(); + } - this.currentBufferIndex = dxgiSwapChain3.Get()->GetCurrentBackBufferIndex(); + D3D12_RESOURCE_DESC d3D12Resource0Description = this.d3D12Resource0.Get()->GetDesc(); - // ============== - // SAMPLE - // ============== + // Create the command allocator to use + fixed (ID3D12CommandAllocator** d3D12CommandAllocator = this.d3D12CommandAllocator) + { + this.d3D12Device.Get()->CreateCommandAllocator( + D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT, + FX.__uuidof(), + (void**)d3D12CommandAllocator); + } - var desc = this.d3D12Resource0.Get()->GetDesc(); + // 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, + d3D12CommandAllocator, + null, + FX.__uuidof(), + (void**)d3D12GraphicsCommandList); + } - int width = (int)desc.Width; - int height = (int)desc.Height; + // Close the command list to prepare it for future use + this.d3D12GraphicsCommandList.Get()->Close(); - using ReadWriteTexture2D texture = Gpu.Default.AllocateReadWriteTexture2D(width, height); - - Gpu.Default.For(texture.Width, texture.Height, new FractalTiling(texture, 0)); - - ID3D12Resource* resource; - - _ = InteropServices.TryGetID3D12Resource(texture, FX.__uuidof(), (void**)&resource); - - using ComPtr d3D12CommandAllocator = default; - - this.d3D12Device.Get()->CreateCommandAllocator( - D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT, - FX.__uuidof(), - (void**)d3D12CommandAllocator.GetAddressOf()); - - using ComPtr d3D12GraphicsCommandList = default; - - this.d3D12Device.Get()->CreateCommandList( - 0, - D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT, - d3D12CommandAllocator, - null, - FX.__uuidof(), - (void**)d3D12GraphicsCommandList.GetAddressOf()); - - D3D12_RESOURCE_BARRIER d3D12ResourceBarrierBefore = D3D12_RESOURCE_BARRIER.InitTransition( - resource, - D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_SOURCE); - - d3D12GraphicsCommandList.Get()->ResourceBarrier(1, &d3D12ResourceBarrierBefore); - - D3D12_RESOURCE_BARRIER d3D12ResourceBarrierBefore0 = D3D12_RESOURCE_BARRIER.InitTransition( - this.d3D12Resource0.Get(), - D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COMMON, - D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_DEST); - - d3D12GraphicsCommandList.Get()->ResourceBarrier(1, &d3D12ResourceBarrierBefore0); - - d3D12GraphicsCommandList.Get()->CopyResource(this.d3D12Resource0.Get(), resource); - - D3D12_RESOURCE_BARRIER d3D12ResourceBarrierAfter = D3D12_RESOURCE_BARRIER.InitTransition( - resource, - D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_SOURCE, - D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_UNORDERED_ACCESS); - - d3D12GraphicsCommandList.Get()->ResourceBarrier(1, &d3D12ResourceBarrierAfter); - - D3D12_RESOURCE_BARRIER d3D12ResourceBarrierAfter0 = D3D12_RESOURCE_BARRIER.InitTransition( - this.d3D12Resource0.Get(), - D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COMMON); - - d3D12GraphicsCommandList.Get()->ResourceBarrier(1, &d3D12ResourceBarrierAfter0); - - d3D12GraphicsCommandList.Get()->Close(); - - this.d3D12CommandQueue.Get()->ExecuteCommandLists(1, (ID3D12CommandList**)d3D12GraphicsCommandList.GetAddressOf()); - - this.dxgiSwapChain1.Get()->Present(0, 0); + // Create the 2D texture to use to generate frames to display + this.texture = Gpu.Default.AllocateReadWriteTexture2D( + (int)d3D12Resource0Description.Width, + (int)d3D12Resource0Description.Height); } public override void OnResize(Size size) { } - public override void OnUpdate(TimeSpan time) + public override unsafe void OnUpdate(TimeSpan time) { + // Generate the new frame + Gpu.Default.For(texture.Width, texture.Height, new FractalTiling(texture, (float)time.TotalSeconds)); + + using ComPtr d3D12Resource = default; + + // Get the underlying ID3D12Resource pointer for the texture + _ = InteropServices.TryGetID3D12Resource(texture, FX.__uuidof(), (void**)d3D12Resource.GetAddressOf()); + + // 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 to reuse + this.d3D12GraphicsCommandList.Get()->Reset(this.d3D12CommandAllocator.Get(), null); + + 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 + d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers); + + // Copy the generated frame to the target back buffer + 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 + d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers); + + d3D12GraphicsCommandList.Get()->Close(); + + // Execute the command list to perform the copy + this.d3D12CommandQueue.Get()->ExecuteCommandLists(1, (ID3D12CommandList**)d3D12GraphicsCommandList.GetAddressOf()); + this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), this.nextD3D12FenceValue); + + if (this.nextD3D12FenceValue > this.d3D12Fence.Get()->GetCompletedValue()) + { + this.d3D12Fence.Get()->SetEventOnCompletion(this.nextD3D12FenceValue, default); + } + + this.nextD3D12FenceValue++; + + // Present the new frame + this.dxgiSwapChain1.Get()->Present(0, 0); } public override void Dispose() From 456a687969269b7b3ba57eba9930ab16b33ecfda Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 22 Feb 2021 21:35:39 +0100 Subject: [PATCH 06/16] Fixed a memory leak in the swap chain render loop --- samples/ComputeSharp.Sample.SwapChain/Program.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/samples/ComputeSharp.Sample.SwapChain/Program.cs b/samples/ComputeSharp.Sample.SwapChain/Program.cs index 04f4b087..97f112a9 100644 --- a/samples/ComputeSharp.Sample.SwapChain/Program.cs +++ b/samples/ComputeSharp.Sample.SwapChain/Program.cs @@ -207,7 +207,8 @@ namespace ComputeSharp.Sample.SwapChain this.currentBufferIndex ^= 1; - // Reset the command list to reuse + // Reset the command list and command allocator + this.d3D12CommandAllocator.Get()->Reset(); this.d3D12GraphicsCommandList.Get()->Reset(this.d3D12CommandAllocator.Get(), null); D3D12_RESOURCE_BARRIER* d3D12ResourceBarriers = stackalloc D3D12_RESOURCE_BARRIER[] From cd4f11893c112ebf4940b83ed44cf34eaa750fd3 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 22 Feb 2021 21:48:52 +0100 Subject: [PATCH 07/16] Added resize logic for working texture --- .../ComputeSharp.Sample.SwapChain/Program.cs | 20 +++++++++---------- .../Win32ApplicationRunner.cs | 6 +----- 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/samples/ComputeSharp.Sample.SwapChain/Program.cs b/samples/ComputeSharp.Sample.SwapChain/Program.cs index 97f112a9..b8e2c34e 100644 --- a/samples/ComputeSharp.Sample.SwapChain/Program.cs +++ b/samples/ComputeSharp.Sample.SwapChain/Program.cs @@ -1,7 +1,6 @@ using System; using System.Drawing; using ComputeSharp.Interop; -using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; @@ -70,7 +69,7 @@ namespace ComputeSharp.Sample.SwapChain /// /// The instance used to prepare frames to display. /// - private ReadWriteTexture2D texture = null!; + private ReadWriteTexture2D? texture; public override string Title => "Fractal tiles"; @@ -176,6 +175,13 @@ namespace ComputeSharp.Sample.SwapChain // Close the command list to prepare it for future use this.d3D12GraphicsCommandList.Get()->Close(); + } + + public override unsafe void OnResize(Size size) + { + this.texture?.Dispose(); + + D3D12_RESOURCE_DESC d3D12Resource0Description = this.d3D12Resource0.Get()->GetDesc(); // Create the 2D texture to use to generate frames to display this.texture = Gpu.Default.AllocateReadWriteTexture2D( @@ -183,14 +189,10 @@ namespace ComputeSharp.Sample.SwapChain (int)d3D12Resource0Description.Height); } - public override void OnResize(Size size) - { - } - public override unsafe void OnUpdate(TimeSpan time) { // Generate the new frame - Gpu.Default.For(texture.Width, texture.Height, new FractalTiling(texture, (float)time.TotalSeconds)); + Gpu.Default.For(texture!.Width, texture.Height, new FractalTiling(texture, (float)time.TotalSeconds)); using ComPtr d3D12Resource = default; @@ -258,10 +260,6 @@ namespace ComputeSharp.Sample.SwapChain // Present the new frame this.dxgiSwapChain1.Get()->Present(0, 0); } - - public override void Dispose() - { - } } [AutoConstructor] diff --git a/samples/ComputeSharp.Sample.SwapChain/Win32ApplicationRunner.cs b/samples/ComputeSharp.Sample.SwapChain/Win32ApplicationRunner.cs index a0ec1e0e..bfdbda7d 100644 --- a/samples/ComputeSharp.Sample.SwapChain/Win32ApplicationRunner.cs +++ b/samples/ComputeSharp.Sample.SwapChain/Win32ApplicationRunner.cs @@ -9,7 +9,7 @@ using FX = TerraFX.Interop.Windows; namespace ComputeSharp.Sample.SwapChain { - internal abstract class Win32Application : IDisposable + internal abstract class Win32Application { public abstract string Title { get; } @@ -18,8 +18,6 @@ namespace ComputeSharp.Sample.SwapChain public abstract void OnResize(Size size); public abstract void OnUpdate(TimeSpan time); - - public abstract void Dispose(); } /// @@ -158,8 +156,6 @@ namespace ComputeSharp.Sample.SwapChain } } - application.Dispose(); - // Return this part of the WM_QUIT message to Windows return (int)msg.wParam; } From 2c92c1b8cefc8833cd1991ed5a164bfebfa7b202 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 22 Feb 2021 22:12:27 +0100 Subject: [PATCH 08/16] Code refactoring, improved samples modularity --- .../Backend/SwapChainApplication{T}.cs | 275 +++++++++++++++++ .../Backend/Win32Application.cs | 36 +++ .../{ => Backend}/Win32ApplicationRunner.cs | 18 +- .../ComputeSharp.Sample.SwapChain.csproj | 5 +- .../ComputeSharp.Sample.SwapChain/Program.cs | 292 +----------------- .../Shaders/FractalTiling.cs | 50 +++ 6 files changed, 368 insertions(+), 308 deletions(-) create mode 100644 samples/ComputeSharp.Sample.SwapChain/Backend/SwapChainApplication{T}.cs create mode 100644 samples/ComputeSharp.Sample.SwapChain/Backend/Win32Application.cs rename samples/ComputeSharp.Sample.SwapChain/{ => Backend}/Win32ApplicationRunner.cs (95%) create mode 100644 samples/ComputeSharp.Sample.SwapChain/Shaders/FractalTiling.cs diff --git a/samples/ComputeSharp.Sample.SwapChain/Backend/SwapChainApplication{T}.cs b/samples/ComputeSharp.Sample.SwapChain/Backend/SwapChainApplication{T}.cs new file mode 100644 index 00000000..192737c8 --- /dev/null +++ b/samples/ComputeSharp.Sample.SwapChain/Backend/SwapChainApplication{T}.cs @@ -0,0 +1,275 @@ +using System; +using System.Drawing; +using ComputeSharp.Interop; +using TerraFX.Interop; +using FX = TerraFX.Interop.Windows; + +namespace ComputeSharp.Sample.SwapChain.Backend +{ + internal sealed class SwapChainApplication : Win32Application + where T : struct, IComputeShader + { + /// + /// The instance used to create shaders to run. + /// + private readonly Func, TimeSpan, T> shaderFactory; + + /// + /// 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 = 1; + + /// + /// The object to create command lists. + /// + private ComPtr d3D12CommandAllocator; + + /// + /// The instance used to copy data to the back buffers. + /// + private ComPtr d3D12GraphicsCommandList; + + /// + /// The instance used to display content onto the target window. + /// + private ComPtr dxgiSwapChain1; + + /// + /// 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 uint currentBufferIndex; + + /// + /// The instance used to prepare frames to display. + /// + private ReadWriteTexture2D? texture; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance used to create shaders to run. + public SwapChainApplication(Func, TimeSpan, T> shaderFactory) + { + this.shaderFactory = shaderFactory; + } + + /// + public override string Title => default(T).ToString()!; + + /// + public override unsafe void OnInitialize(Size size, HWND hwnd) + { + // Get the underlying ID3D12Device in use + fixed (ID3D12Device** d3D12Device = this.d3D12Device) + { + _ = InteropServices.TryGetID3D12Device(Gpu.Default, FX.__uuidof(), (void**)d3D12Device); + } + + // 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; + + _ = d3D12Device.Get()->CreateCommandQueue( + &d3D12CommandQueueDesc, + FX.__uuidof(), + (void**)d3D12CommandQueue); + } + + // Create the direct fence + fixed (ID3D12Fence** d3D12Fence = this.d3D12Fence) + { + _ = this.d3D12Device.Get()->CreateFence( + 0, + D3D12_FENCE_FLAGS.D3D12_FENCE_FLAG_NONE, + FX.__uuidof(), + (void**)d3D12Fence); + } + + // Create the swap chain to display frames + fixed (IDXGISwapChain1** dxgiSwapChain1 = this.dxgiSwapChain1) + { + using ComPtr dxgiFactory2 = default; + + _ = FX.CreateDXGIFactory2(FX.DXGI_CREATE_FACTORY_DEBUG, FX.__uuidof(), (void**)dxgiFactory2.GetAddressOf()); + + DXGI_SWAP_CHAIN_DESC1 dxgiSwapChainDesc1 = default; + dxgiSwapChainDesc1.AlphaMode = DXGI_ALPHA_MODE.DXGI_ALPHA_MODE_IGNORE; + dxgiSwapChainDesc1.BufferCount = 2; + dxgiSwapChainDesc1.Flags = 0; + dxgiSwapChainDesc1.Format = DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_UNORM; + dxgiSwapChainDesc1.Width = 0; + dxgiSwapChainDesc1.Height = 0; + 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; + + _ = dxgiFactory2.Get()->CreateSwapChainForHwnd( + (IUnknown*)d3D12CommandQueue.Get(), + hwnd, + &dxgiSwapChainDesc1, + null, + null, + dxgiSwapChain1); + } + + // Retrieve the back buffers for the swap chain + fixed (ID3D12Resource** d3D12Resource0 = this.d3D12Resource0) + fixed (ID3D12Resource** d3D12Resource1 = this.d3D12Resource1) + { + _ = dxgiSwapChain1.Get()->GetBuffer(0, FX.__uuidof(), (void**)d3D12Resource0); + _ = dxgiSwapChain1.Get()->GetBuffer(1, FX.__uuidof(), (void**)d3D12Resource1); + } + + // Get the index of the initial back buffer + using (ComPtr dxgiSwapChain3 = default) + { + _ = this.dxgiSwapChain1.CopyTo(dxgiSwapChain3.GetAddressOf()); + + this.currentBufferIndex = dxgiSwapChain3.Get()->GetCurrentBackBufferIndex(); + } + + D3D12_RESOURCE_DESC d3D12Resource0Description = this.d3D12Resource0.Get()->GetDesc(); + + // Create the command allocator to use + fixed (ID3D12CommandAllocator** d3D12CommandAllocator = this.d3D12CommandAllocator) + { + this.d3D12Device.Get()->CreateCommandAllocator( + D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT, + FX.__uuidof(), + (void**)d3D12CommandAllocator); + } + + // 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, + d3D12CommandAllocator, + null, + FX.__uuidof(), + (void**)d3D12GraphicsCommandList); + } + + // Close the command list to prepare it for future use + this.d3D12GraphicsCommandList.Get()->Close(); + } + + /// + public override unsafe void OnResize(Size size) + { + this.texture?.Dispose(); + + D3D12_RESOURCE_DESC d3D12Resource0Description = this.d3D12Resource0.Get()->GetDesc(); + + // Create the 2D texture to use to generate frames to display + this.texture = Gpu.Default.AllocateReadWriteTexture2D( + (int)d3D12Resource0Description.Width, + (int)d3D12Resource0Description.Height); + } + + /// + public override unsafe void OnUpdate(TimeSpan time) + { + // Generate the new frame + Gpu.Default.For(this.texture!.Width, this.texture.Height, this.shaderFactory(this.texture, time)); + + using ComPtr d3D12Resource = default; + + // Get the underlying ID3D12Resource pointer for the texture + _ = InteropServices.TryGetID3D12Resource(this.texture, FX.__uuidof(), (void**)d3D12Resource.GetAddressOf()); + + // 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(); + this.d3D12GraphicsCommandList.Get()->Reset(this.d3D12CommandAllocator.Get(), null); + + 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 + d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers); + + // Copy the generated frame to the target back buffer + 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 + d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers); + + d3D12GraphicsCommandList.Get()->Close(); + + // Execute the command list to perform the copy + this.d3D12CommandQueue.Get()->ExecuteCommandLists(1, (ID3D12CommandList**)d3D12GraphicsCommandList.GetAddressOf()); + this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), this.nextD3D12FenceValue); + + if (this.nextD3D12FenceValue > this.d3D12Fence.Get()->GetCompletedValue()) + { + this.d3D12Fence.Get()->SetEventOnCompletion(this.nextD3D12FenceValue, default); + } + + this.nextD3D12FenceValue++; + + // Present the new frame + this.dxgiSwapChain1.Get()->Present(0, 0); + } + } +} diff --git a/samples/ComputeSharp.Sample.SwapChain/Backend/Win32Application.cs b/samples/ComputeSharp.Sample.SwapChain/Backend/Win32Application.cs new file mode 100644 index 00000000..b207f3e8 --- /dev/null +++ b/samples/ComputeSharp.Sample.SwapChain/Backend/Win32Application.cs @@ -0,0 +1,36 @@ +using System; +using System.Drawing; +using TerraFX.Interop; + +namespace ComputeSharp.Sample.SwapChain.Backend +{ + /// + /// A class representing a simple Win32 application. + /// + internal abstract class Win32Application + { + /// + /// Gets the title of the current application. + /// + public abstract string Title { get; } + + /// + /// Initializes the current application. + /// + /// The window size. + /// The handle for the window. + public abstract void OnInitialize(Size size, HWND hwnd); + + /// + /// Resizes the current application. + /// + /// The new window size. + public abstract void OnResize(Size size); + + /// + /// Updates the current application. + /// + /// The current time since the start of the application. + public abstract void OnUpdate(TimeSpan time); + } +} diff --git a/samples/ComputeSharp.Sample.SwapChain/Win32ApplicationRunner.cs b/samples/ComputeSharp.Sample.SwapChain/Backend/Win32ApplicationRunner.cs similarity index 95% rename from samples/ComputeSharp.Sample.SwapChain/Win32ApplicationRunner.cs rename to samples/ComputeSharp.Sample.SwapChain/Backend/Win32ApplicationRunner.cs index bfdbda7d..c101b362 100644 --- a/samples/ComputeSharp.Sample.SwapChain/Win32ApplicationRunner.cs +++ b/samples/ComputeSharp.Sample.SwapChain/Backend/Win32ApplicationRunner.cs @@ -7,19 +7,8 @@ using System.Threading; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; -namespace ComputeSharp.Sample.SwapChain +namespace ComputeSharp.Sample.SwapChain.Backend { - internal abstract class Win32Application - { - public abstract string Title { get; } - - public abstract void OnInitialize(Size size, HWND hwnd); - - public abstract void OnResize(Size size); - - public abstract void OnUpdate(TimeSpan time); - } - /// /// A helper class to manage the creation and execution of Win32 applications. /// @@ -74,10 +63,9 @@ namespace ComputeSharp.Sample.SwapChain /// /// The type of application being launched. /// The exit code for the application. - public static int Run() - where T : Win32Application, new() + public static int Run(Win32Application application) { - application = new T(); + Win32ApplicationRunner.application = application; IntPtr hInstance = FX.GetModuleHandleW(null); uint width = 1280; diff --git a/samples/ComputeSharp.Sample.SwapChain/ComputeSharp.Sample.SwapChain.csproj b/samples/ComputeSharp.Sample.SwapChain/ComputeSharp.Sample.SwapChain.csproj index 44b2ad45..333c078e 100644 --- a/samples/ComputeSharp.Sample.SwapChain/ComputeSharp.Sample.SwapChain.csproj +++ b/samples/ComputeSharp.Sample.SwapChain/ComputeSharp.Sample.SwapChain.csproj @@ -7,10 +7,7 @@ - + diff --git a/samples/ComputeSharp.Sample.SwapChain/Program.cs b/samples/ComputeSharp.Sample.SwapChain/Program.cs index b8e2c34e..f9030a45 100644 --- a/samples/ComputeSharp.Sample.SwapChain/Program.cs +++ b/samples/ComputeSharp.Sample.SwapChain/Program.cs @@ -1,8 +1,5 @@ -using System; -using System.Drawing; -using ComputeSharp.Interop; -using TerraFX.Interop; -using FX = TerraFX.Interop.Windows; +using ComputeSharp.Sample.SwapChain.Backend; +using ComputeSharp.Sample.SwapChain.Shaders; namespace ComputeSharp.Sample.SwapChain { @@ -10,290 +7,7 @@ namespace ComputeSharp.Sample.SwapChain { static void Main(string[] args) { - Win32ApplicationRunner.Run(); - } - } - - internal sealed class FractalTilesApplication : Win32Application - { - /// - /// 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 = 1; - - /// - /// The object to create command lists. - /// - private ComPtr d3D12CommandAllocator; - - /// - /// The instance used to copy data to the back buffers. - /// - private ComPtr d3D12GraphicsCommandList; - - /// - /// The instance used to display content onto the target window. - /// - private ComPtr dxgiSwapChain1; - - /// - /// 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 uint currentBufferIndex; - - /// - /// The instance used to prepare frames to display. - /// - private ReadWriteTexture2D? texture; - - public override string Title => "Fractal tiles"; - - public override unsafe void OnInitialize(Size size, HWND hwnd) - { - // Get the underlying ID3D12Device in use - fixed (ID3D12Device** d3D12Device = this.d3D12Device) - { - _ = InteropServices.TryGetID3D12Device(Gpu.Default, FX.__uuidof(), (void**)d3D12Device); - } - - // 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; - - _ = d3D12Device.Get()->CreateCommandQueue( - &d3D12CommandQueueDesc, - FX.__uuidof(), - (void**)d3D12CommandQueue); - } - - // Create the direct fence - fixed (ID3D12Fence** d3D12Fence = this.d3D12Fence) - { - _ = this.d3D12Device.Get()->CreateFence( - 0, - D3D12_FENCE_FLAGS.D3D12_FENCE_FLAG_NONE, - FX.__uuidof(), - (void**)d3D12Fence); - } - - // Create the swap chain to display frames - fixed (IDXGISwapChain1** dxgiSwapChain1 = this.dxgiSwapChain1) - { - using ComPtr dxgiFactory2 = default; - - _ = FX.CreateDXGIFactory2(FX.DXGI_CREATE_FACTORY_DEBUG, FX.__uuidof(), (void**)dxgiFactory2.GetAddressOf()); - - DXGI_SWAP_CHAIN_DESC1 dxgiSwapChainDesc1 = default; - dxgiSwapChainDesc1.AlphaMode = DXGI_ALPHA_MODE.DXGI_ALPHA_MODE_IGNORE; - dxgiSwapChainDesc1.BufferCount = 2; - dxgiSwapChainDesc1.Flags = 0; - dxgiSwapChainDesc1.Format = DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_UNORM; - dxgiSwapChainDesc1.Width = 0; - dxgiSwapChainDesc1.Height = 0; - 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; - - _ = dxgiFactory2.Get()->CreateSwapChainForHwnd( - (IUnknown*)d3D12CommandQueue.Get(), - hwnd, - &dxgiSwapChainDesc1, - null, - null, - dxgiSwapChain1); - } - - // Retrieve the back buffers for the swap chain - fixed (ID3D12Resource** d3D12Resource0 = this.d3D12Resource0) - fixed (ID3D12Resource** d3D12Resource1 = this.d3D12Resource1) - { - _ = dxgiSwapChain1.Get()->GetBuffer(0, FX.__uuidof(), (void**)d3D12Resource0); - _ = dxgiSwapChain1.Get()->GetBuffer(1, FX.__uuidof(), (void**)d3D12Resource1); - } - - // Get the index of the initial back buffer - using (ComPtr dxgiSwapChain3 = default) - { - _ = this.dxgiSwapChain1.CopyTo(dxgiSwapChain3.GetAddressOf()); - - this.currentBufferIndex = dxgiSwapChain3.Get()->GetCurrentBackBufferIndex(); - } - - D3D12_RESOURCE_DESC d3D12Resource0Description = this.d3D12Resource0.Get()->GetDesc(); - - // Create the command allocator to use - fixed (ID3D12CommandAllocator** d3D12CommandAllocator = this.d3D12CommandAllocator) - { - this.d3D12Device.Get()->CreateCommandAllocator( - D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT, - FX.__uuidof(), - (void**)d3D12CommandAllocator); - } - - // 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, - d3D12CommandAllocator, - null, - FX.__uuidof(), - (void**)d3D12GraphicsCommandList); - } - - // Close the command list to prepare it for future use - this.d3D12GraphicsCommandList.Get()->Close(); - } - - public override unsafe void OnResize(Size size) - { - this.texture?.Dispose(); - - D3D12_RESOURCE_DESC d3D12Resource0Description = this.d3D12Resource0.Get()->GetDesc(); - - // Create the 2D texture to use to generate frames to display - this.texture = Gpu.Default.AllocateReadWriteTexture2D( - (int)d3D12Resource0Description.Width, - (int)d3D12Resource0Description.Height); - } - - public override unsafe void OnUpdate(TimeSpan time) - { - // Generate the new frame - Gpu.Default.For(texture!.Width, texture.Height, new FractalTiling(texture, (float)time.TotalSeconds)); - - using ComPtr d3D12Resource = default; - - // Get the underlying ID3D12Resource pointer for the texture - _ = InteropServices.TryGetID3D12Resource(texture, FX.__uuidof(), (void**)d3D12Resource.GetAddressOf()); - - // 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(); - this.d3D12GraphicsCommandList.Get()->Reset(this.d3D12CommandAllocator.Get(), null); - - 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 - d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers); - - // Copy the generated frame to the target back buffer - 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 - d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers); - - d3D12GraphicsCommandList.Get()->Close(); - - // Execute the command list to perform the copy - this.d3D12CommandQueue.Get()->ExecuteCommandLists(1, (ID3D12CommandList**)d3D12GraphicsCommandList.GetAddressOf()); - this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), this.nextD3D12FenceValue); - - if (this.nextD3D12FenceValue > this.d3D12Fence.Get()->GetCompletedValue()) - { - this.d3D12Fence.Get()->SetEventOnCompletion(this.nextD3D12FenceValue, default); - } - - this.nextD3D12FenceValue++; - - // Present the new frame - this.dxgiSwapChain1.Get()->Present(0, 0); - } - } - - [AutoConstructor] - internal readonly partial struct FractalTiling : IComputeShader - { - public readonly IReadWriteTexture2D texture; - public readonly float time; - - /// - public void Execute() - { - Float2 position = ((Float2)(256 * ThreadIds.XY)) / texture.Width + time; - Float4 color = 0; - - for (int i = 0; i < 6; i++) - { - Float2 a = Hlsl.Floor(position); - Float2 b = Hlsl.Frac(position); - Float4 w = Hlsl.Frac( - (Hlsl.Sin(a.X * 7 + 31.0f * a.Y + 0.01f * time) + - new Float4(0.035f, 0.01f, 0, 0.7f)) - * 13.545317f); - - color.XYZ += w.XYZ * - 2.0f * Hlsl.SmoothStep(0.45f, 0.55f, w.W) * - Hlsl.Sqrt(16.0f * b.X * b.Y * (1.0f - b.X) * (1.0f - b.Y)); - - position /= 2.0f; - color /= 2.0f; - } - - color.XYZ = Hlsl.Pow(color.XYZ, new Float3(0.7f, 0.8f, 0.5f)); - - texture[ThreadIds.XY] = color; + Win32ApplicationRunner.Run(new SwapChainApplication(static (texture, time) => new FractalTiling(texture, (float)time.TotalSeconds))); } } } diff --git a/samples/ComputeSharp.Sample.SwapChain/Shaders/FractalTiling.cs b/samples/ComputeSharp.Sample.SwapChain/Shaders/FractalTiling.cs new file mode 100644 index 00000000..a5be7ef9 --- /dev/null +++ b/samples/ComputeSharp.Sample.SwapChain/Shaders/FractalTiling.cs @@ -0,0 +1,50 @@ +namespace ComputeSharp.Sample.SwapChain.Shaders +{ + /// + /// A shader creating a fractal tiling animation. + /// Ported from . + /// Created by Inigo Quilez. + /// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. + /// + [AutoConstructor] + internal readonly partial struct FractalTiling : IComputeShader + { + /// + /// The target texture. + /// + public readonly IReadWriteTexture2D texture; + + /// + /// The current time since the start of the application. + /// + public readonly float time; + + /// + public void Execute() + { + Float2 position = ((Float2)(256 * ThreadIds.XY)) / texture.Width + time; + Float4 color = 0; + + for (int i = 0; i < 6; i++) + { + Float2 a = Hlsl.Floor(position); + Float2 b = Hlsl.Frac(position); + Float4 w = Hlsl.Frac( + (Hlsl.Sin(a.X * 7 + 31.0f * a.Y + 0.01f * time) + + new Float4(0.035f, 0.01f, 0, 0.7f)) + * 13.545317f); + + color.XYZ += w.XYZ * + 2.0f * Hlsl.SmoothStep(0.45f, 0.55f, w.W) * + Hlsl.Sqrt(16.0f * b.X * b.Y * (1.0f - b.X) * (1.0f - b.Y)); + + position /= 2.0f; + color /= 2.0f; + } + + color.XYZ = Hlsl.Pow(color.XYZ, new Float3(0.7f, 0.8f, 0.5f)); + + texture[ThreadIds.XY] = color; + } + } +} From 11fa1ef8a61c05ea9df9e4bef02852f76d5daba5 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 23 Feb 2021 01:54:44 +0100 Subject: [PATCH 09/16] Fixed resize logic in swap chain setup --- .../Backend/SwapChainApplication{T}.cs | 54 +++++++++++-------- 1 file changed, 33 insertions(+), 21 deletions(-) diff --git a/samples/ComputeSharp.Sample.SwapChain/Backend/SwapChainApplication{T}.cs b/samples/ComputeSharp.Sample.SwapChain/Backend/SwapChainApplication{T}.cs index 192737c8..0cfc25da 100644 --- a/samples/ComputeSharp.Sample.SwapChain/Backend/SwapChainApplication{T}.cs +++ b/samples/ComputeSharp.Sample.SwapChain/Backend/SwapChainApplication{T}.cs @@ -143,24 +143,6 @@ namespace ComputeSharp.Sample.SwapChain.Backend dxgiSwapChain1); } - // Retrieve the back buffers for the swap chain - fixed (ID3D12Resource** d3D12Resource0 = this.d3D12Resource0) - fixed (ID3D12Resource** d3D12Resource1 = this.d3D12Resource1) - { - _ = dxgiSwapChain1.Get()->GetBuffer(0, FX.__uuidof(), (void**)d3D12Resource0); - _ = dxgiSwapChain1.Get()->GetBuffer(1, FX.__uuidof(), (void**)d3D12Resource1); - } - - // Get the index of the initial back buffer - using (ComPtr dxgiSwapChain3 = default) - { - _ = this.dxgiSwapChain1.CopyTo(dxgiSwapChain3.GetAddressOf()); - - this.currentBufferIndex = dxgiSwapChain3.Get()->GetCurrentBackBufferIndex(); - } - - D3D12_RESOURCE_DESC d3D12Resource0Description = this.d3D12Resource0.Get()->GetDesc(); - // Create the command allocator to use fixed (ID3D12CommandAllocator** d3D12CommandAllocator = this.d3D12CommandAllocator) { @@ -189,6 +171,36 @@ namespace ComputeSharp.Sample.SwapChain.Backend /// public override unsafe void OnResize(Size size) { + this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), this.nextD3D12FenceValue); + + // Wait for the fence again to ensure there are no pending operations + this.d3D12Fence.Get()->SetEventOnCompletion(this.nextD3D12FenceValue, default); + + this.nextD3D12FenceValue++; + + // Dispose the old buffers before resizing the buffer + this.d3D12Resource0.Dispose(); + this.d3D12Resource1.Dispose(); + + // Resize the swap chain buffers + this.dxgiSwapChain1.Get()->ResizeBuffers(0, 0, 0, DXGI_FORMAT.DXGI_FORMAT_UNKNOWN, 0); + + // Get the index of the initial back buffer + using (ComPtr dxgiSwapChain3 = default) + { + _ = this.dxgiSwapChain1.CopyTo(dxgiSwapChain3.GetAddressOf()); + + this.currentBufferIndex = dxgiSwapChain3.Get()->GetCurrentBackBufferIndex(); + } + + // Retrieve the back buffers for the swap chain + fixed (ID3D12Resource** d3D12Resource0 = this.d3D12Resource0) + fixed (ID3D12Resource** d3D12Resource1 = this.d3D12Resource1) + { + _ = dxgiSwapChain1.Get()->GetBuffer(0, FX.__uuidof(), (void**)d3D12Resource0); + _ = dxgiSwapChain1.Get()->GetBuffer(1, FX.__uuidof(), (void**)d3D12Resource1); + } + this.texture?.Dispose(); D3D12_RESOURCE_DESC d3D12Resource0Description = this.d3D12Resource0.Get()->GetDesc(); @@ -261,15 +273,15 @@ namespace ComputeSharp.Sample.SwapChain.Backend this.d3D12CommandQueue.Get()->ExecuteCommandLists(1, (ID3D12CommandList**)d3D12GraphicsCommandList.GetAddressOf()); this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), this.nextD3D12FenceValue); + // Present the new frame + this.dxgiSwapChain1.Get()->Present(0, 0); + if (this.nextD3D12FenceValue > this.d3D12Fence.Get()->GetCompletedValue()) { this.d3D12Fence.Get()->SetEventOnCompletion(this.nextD3D12FenceValue, default); } this.nextD3D12FenceValue++; - - // Present the new frame - this.dxgiSwapChain1.Get()->Present(0, 0); } } } From 97d023387d3701343851dc6b05abd0aaa09797ce Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 23 Feb 2021 02:04:28 +0100 Subject: [PATCH 10/16] Added missing length HLSL intrinsic methods --- src/ComputeSharp.Core/Intrinsics/Hlsl.cs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/ComputeSharp.Core/Intrinsics/Hlsl.cs b/src/ComputeSharp.Core/Intrinsics/Hlsl.cs index 3d757637..dc8e838c 100644 --- a/src/ComputeSharp.Core/Intrinsics/Hlsl.cs +++ b/src/ComputeSharp.Core/Intrinsics/Hlsl.cs @@ -1240,6 +1240,30 @@ namespace ComputeSharp [Pure] public static Float4 Ldexp(Float4 x, Float4 exp) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Ldexp)}({nameof(Float4)},{nameof(Float4)})"); + /// + /// Returns the length of the specified floating-point vector. + /// + /// The specified floating-point vector. + /// A floating-point scalar that represents the length of the x parameter. + [Pure] + public static float Length(Float2 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Length)}({nameof(Float2)})"); + + /// + /// Returns the length of the specified floating-point vector. + /// + /// The specified floating-point vector. + /// A floating-point scalar that represents the length of the x parameter. + [Pure] + public static float Length(Float3 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Length)}({nameof(Float3)})"); + + /// + /// Returns the length of the specified floating-point vector. + /// + /// The specified floating-point vector. + /// A floating-point scalar that represents the length of the x parameter. + [Pure] + public static float Length(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Length)}({nameof(Float4)})"); + /// /// Performs a linear interpolation. /// From ab430753510ac226a85dca9c04b32616a33a10e1 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 23 Feb 2021 02:16:36 +0100 Subject: [PATCH 11/16] Fixed type mapping for return types --- .../Extensions/SyntaxNodeExtensions.cs | 6 +++++ .../SyntaxRewriters/ShaderSourceRewriter.cs | 6 ++++- .../ComputeSharp.Tests/ShaderCompilerTests.cs | 22 +++++++++++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs index 86418169..3a29bc8d 100644 --- a/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs +++ b/src/ComputeSharp.SourceGenerators/Extensions/SyntaxNodeExtensions.cs @@ -58,6 +58,12 @@ namespace ComputeSharp.SourceGenerators.Extensions _ => semanticModel.GetTypeInfo(sourceType).Type! }; + // Do nothing if the type is just void + if (typeSymbol.SpecialType == SpecialType.System_Void) + { + return node; + } + string typeName = typeSymbol.ToDisplayString(ISymbolExtensions.FullyQualifiedWithoutGlobalFormat); discoveredTypes.Add((INamedTypeSymbol)typeSymbol); diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 38cf34f3..9c640fa4 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -153,7 +153,9 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { this.currentMethod = node; - var updatedNode = (MethodDeclarationSyntax?)base.Visit(node); + var updatedNode = (MethodDeclarationSyntax?)base.Visit(node)!; + + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, this.semanticModel, this.discoveredTypes); if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword))) { @@ -358,6 +360,8 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters .WithAttributeLists(List()) .WithIdentifier(Identifier($"__{this.currentMethod!.Identifier.Text}__{node.Identifier.Text}")); + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, this.semanticModel, this.discoveredTypes); + if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword))) { this.context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node); diff --git a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs index 3cf860e9..b490ce77 100644 --- a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs +++ b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs @@ -1,3 +1,4 @@ +using System.Threading; using ComputeSharp.Interop; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -27,5 +28,26 @@ namespace ComputeSharp.Tests row_major[ThreadIds.X] = log / dword; } } + + [TestMethod] + public void SpecialTypeAsReturnType() + { + ReflectionServices.GetShaderInfo(out _); + } + + [AutoConstructor] + public readonly partial struct FloatReturnType : IComputeShader + { + public readonly ReadWriteBuffer buffer; + + Float2 Foo(float x) => x; + + public void Execute() + { + static Float3 Bar(float x) => x; + + buffer[ThreadIds.X] = Foo(ThreadIds.X) + Bar(ThreadIds.X).XY; + } + } } } From 8bf828da6dca1b3c763253b0a0cfda4294d69b61 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 23 Feb 2021 02:26:11 +0100 Subject: [PATCH 12/16] Added two-tiled Truchet sample shader --- .../ComputeSharp.Sample.SwapChain/Program.cs | 2 +- .../Shaders/TwoTiledTruchet.cs | 153 ++++++++++++++++++ 2 files changed, 154 insertions(+), 1 deletion(-) create mode 100644 samples/ComputeSharp.Sample.SwapChain/Shaders/TwoTiledTruchet.cs diff --git a/samples/ComputeSharp.Sample.SwapChain/Program.cs b/samples/ComputeSharp.Sample.SwapChain/Program.cs index f9030a45..1bb260cd 100644 --- a/samples/ComputeSharp.Sample.SwapChain/Program.cs +++ b/samples/ComputeSharp.Sample.SwapChain/Program.cs @@ -7,7 +7,7 @@ namespace ComputeSharp.Sample.SwapChain { static void Main(string[] args) { - Win32ApplicationRunner.Run(new SwapChainApplication(static (texture, time) => new FractalTiling(texture, (float)time.TotalSeconds))); + Win32ApplicationRunner.Run(new SwapChainApplication(static (texture, time) => new(texture, (float)time.TotalSeconds))); } } } diff --git a/samples/ComputeSharp.Sample.SwapChain/Shaders/TwoTiledTruchet.cs b/samples/ComputeSharp.Sample.SwapChain/Shaders/TwoTiledTruchet.cs new file mode 100644 index 00000000..a9f7781a --- /dev/null +++ b/samples/ComputeSharp.Sample.SwapChain/Shaders/TwoTiledTruchet.cs @@ -0,0 +1,153 @@ +namespace ComputeSharp.Sample.SwapChain.Shaders +{ + /// + /// A shader creating an animated two-tiles Truchet arrangement. + /// Ported from . + /// Created by Shane. + /// + [AutoConstructor] + internal readonly partial struct TwoTiledTruchet : IComputeShader + { + /// + /// The target texture. + /// + public readonly IReadWriteTexture2D texture; + + /// + /// The current time since the start of the application. + /// + public readonly float time; + + // Fast hash for a pair of floats + private static float Hash21(Float2 p) + { + return Hlsl.Frac(Hlsl.Sin(Hlsl.Dot(p, new Float2(27.619f, 57.583f))) * 43758.5453f); + } + + // HLSL's port of the GLSL mod intrinsic + private static float Mod(float x, float y) + { + return x - y * Hlsl.Floor(x / y); + } + + /// + /// Calculates the Truchet distance field. + /// + /// The input value to compute the distance field for. + /// The resulting Truchet angle. + /// The distance field for the input value. + private Float2 DistanceField(Float2 p, out Float2 ang) + { + Float2 ip2 = Hlsl.Floor(p / 2.0f); + Float2 ip = Hlsl.Floor(p); + float rnd = Hash21(ip); + float rnd3 = Hash21(ip + 0.57f); + Float2 d = 1e5f; + + p -= ip + 0.5f; + + if (Mod(ip2.X + ip2.Y, 2.0f) < 0.5f) + { + d = Hlsl.Abs(p); + ang = p.YX; + + if (Mod(ip.X + 1.0f, 2.0f) < 0.5f) + { + ang.X *= -1.0f; + + } + + if (Mod(ip.Y + 1.0f, 2.0f) > 0.5f) + { + ang.Y *= -1.0f; + } + + if (rnd3 < .5) + { + d = d.YX; + ang = ang.YX; + } + + ang += 0.5f; + ang *= 3.0f; + + } + else + { + if (rnd < .5) + { + p = p.YX * new Float2(1, -1); + } + + d.X = Hlsl.Length(p - 0.5f) - 0.5f; + d.Y = Hlsl.Length(p + 0.5f) - 0.5f; + + d = Hlsl.Abs(d); + + ang = 0; + ang.X = -Hlsl.Atan((p.Y - 0.5f) / (p.X - 0.5f)); + ang.Y = -Hlsl.Atan((p.Y + 0.5f) / (p.X + 0.5f)); + + if (Mod(ip.X + ip.Y, 2.0f) < 0.5f) + { + ang *= -1.0f; + } + + if (rnd < 0.5f) + { + ang *= -1.0f; + } + + if (rnd3 < 0.5f) + { + d = d.YX; + ang = ang.YX; + } + + ang *= 4.0f / 6.2831853f; + ang *= 2.0f; + } + + ang = Hlsl.Frac(ang + time / 4.0f); + + return d; + } + + /// + public void Execute() + { + int width = texture.Width; + int height = texture.Height; + + Float2 uv = ((Float2)ThreadIds.XY - (Float2)(new Int2(width, height)) * 0.5f) / height; + + float gSc = 7.0f; + Float2 p = uv * gSc - new Float2(-1, -0.5f) * time / 2.0f; + float sf = 2.0f / height * gSc; + float lSc = 6.0f; + float lw = 1.0f / lSc / gSc; + Float2 d = DistanceField(p, out Float2 ang) - 2.5f / lSc; + Float3 col = new Float3(1.0f, 0.9f, 0.8f); + + for (int i = 0; i < 2; i++) + { + float di = d[i] - lw / 4.0f; + float tracks = Hlsl.Clamp(Hlsl.Sin(ang[i] * 6.2831f + time * 6.0f) * 4.0f, 0.0f, 1.0f); + float gap = 1.0f + lw; + + col = Hlsl.Lerp(col, 0, (1.0f - Hlsl.SmoothStep(0.0f, sf * 6.0f, di)) * 0.35f); + col = Hlsl.Lerp(col, 0, 1.0f - Hlsl.SmoothStep(0.0f, sf, di)); + col = Hlsl.Lerp(col, new(1.0f, 0.9f, 0.8f), 1.0f - Hlsl.SmoothStep(0.0f, sf, di + lw * 2.0f)); + col = Hlsl.Lerp(col, 0, 1.0f - Hlsl.SmoothStep(0.0f, sf, di + gap / lSc)); + col = Hlsl.Lerp(col, 1, 1.0f - Hlsl.SmoothStep(0.0f, sf, di + gap / lSc + lw)); + col = Hlsl.Lerp(col, 0, 1.0f - Hlsl.SmoothStep(0.0f, sf, di + 2.0f * gap / lSc)); + col = Hlsl.Lerp(col, 1 * tracks, 1.0f - Hlsl.SmoothStep(0.0f, sf, di + 2.0f * gap / lSc + lw)); + } + + Float3 rgb = Hlsl.Sqrt(Hlsl.Max(col, 0.0f)); + Float4 color = new(rgb.X, rgb.Y, rgb.Z, 1.0f); + + texture[ThreadIds.XY] = color; + } + } +} From 36f2512cf6449225e80bafc63836cf6704df6efd Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 23 Feb 2021 02:32:08 +0100 Subject: [PATCH 13/16] Fixed an issue with local functions in external methods --- .../Shaders/TwoTiledTruchet.cs | 24 +++++++------- .../IComputeShaderSourceGenerator.cs | 12 +++---- .../ComputeSharp.Tests/ShaderCompilerTests.cs | 32 ++++++++++++++++--- 3 files changed, 46 insertions(+), 22 deletions(-) diff --git a/samples/ComputeSharp.Sample.SwapChain/Shaders/TwoTiledTruchet.cs b/samples/ComputeSharp.Sample.SwapChain/Shaders/TwoTiledTruchet.cs index a9f7781a..14e5213b 100644 --- a/samples/ComputeSharp.Sample.SwapChain/Shaders/TwoTiledTruchet.cs +++ b/samples/ComputeSharp.Sample.SwapChain/Shaders/TwoTiledTruchet.cs @@ -18,18 +18,6 @@ /// public readonly float time; - // Fast hash for a pair of floats - private static float Hash21(Float2 p) - { - return Hlsl.Frac(Hlsl.Sin(Hlsl.Dot(p, new Float2(27.619f, 57.583f))) * 43758.5453f); - } - - // HLSL's port of the GLSL mod intrinsic - private static float Mod(float x, float y) - { - return x - y * Hlsl.Floor(x / y); - } - /// /// Calculates the Truchet distance field. /// @@ -38,6 +26,18 @@ /// The distance field for the input value. private Float2 DistanceField(Float2 p, out Float2 ang) { + // Fast hash for a pair of floats + static float Hash21(Float2 p) + { + return Hlsl.Frac(Hlsl.Sin(Hlsl.Dot(p, new Float2(27.619f, 57.583f))) * 43758.5453f); + } + + // HLSL's port of the GLSL mod intrinsic + static float Mod(float x, float y) + { + return x - y * Hlsl.Floor(x / y); + } + Float2 ip2 = Hlsl.Floor(p / 2.0f); Float2 ip = Hlsl.Floor(p); float rnd = Hash21(ip); diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index aebad7c3..b6c54421 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -251,6 +251,12 @@ namespace ComputeSharp.SourceGenerators // Rewrite the method syntax tree MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); + // Emit the extracted local functions first + foreach (var localFunction in shaderSourceRewriter.LocalFunctions) + { + methods.Add(localFunction.Value); + } + // If the method is the shader entry point, do additional processing if (isShaderEntryPoint) { @@ -259,12 +265,6 @@ namespace ComputeSharp.SourceGenerators entryPoint = processedMethod.NormalizeWhitespace().ToFullString(); } else methods.Add(processedMethod); - - // Emit the extracted local functions - foreach (var localFunction in shaderSourceRewriter.LocalFunctions) - { - methods.Add(localFunction.Value); - } } return (entryPoint!, methods); diff --git a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs index b490ce77..09faf240 100644 --- a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs +++ b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs @@ -11,11 +11,11 @@ namespace ComputeSharp.Tests [TestMethod] public void ReservedKeywords() { - ReflectionServices.GetShaderInfo(out _); + ReflectionServices.GetShaderInfo(out _); } [AutoConstructor] - public readonly partial struct SoftmaxActivation : IComputeShader + public readonly partial struct ReservedKeywords_Kernel : IComputeShader { public readonly ReadWriteBuffer row_major; public readonly float dword; @@ -32,11 +32,11 @@ namespace ComputeSharp.Tests [TestMethod] public void SpecialTypeAsReturnType() { - ReflectionServices.GetShaderInfo(out _); + ReflectionServices.GetShaderInfo(out _); } [AutoConstructor] - public readonly partial struct FloatReturnType : IComputeShader + public readonly partial struct SpecialTypeAsReturnType_Kernel : IComputeShader { public readonly ReadWriteBuffer buffer; @@ -49,5 +49,29 @@ namespace ComputeSharp.Tests buffer[ThreadIds.X] = Foo(ThreadIds.X) + Bar(ThreadIds.X).XY; } } + + [TestMethod] + public void LocalFunctionInExternalMethods() + { + ReflectionServices.GetShaderInfo(out _); + } + + [AutoConstructor] + public readonly partial struct LocalFunctionInExternalMethods_Kernel : IComputeShader + { + public readonly ReadWriteBuffer buffer; + + Float2 Foo(float x) + { + static Float2 Baz(float y) => y; + + return Baz(x); + } + + public void Execute() + { + buffer[ThreadIds.X] = Foo(ThreadIds.X); + } + } } } From be3216313c9edc0fb03e152ff649ac09621e4ce5 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 23 Feb 2021 02:55:03 +0100 Subject: [PATCH 14/16] Added colorful infinity sample shader --- .../ComputeSharp.Sample.SwapChain/Program.cs | 2 +- .../Shaders/ColorfulInfinity.cs | 79 +++++++++++++++++++ .../Shaders/TwoTiledTruchet.cs | 1 - 3 files changed, 80 insertions(+), 2 deletions(-) create mode 100644 samples/ComputeSharp.Sample.SwapChain/Shaders/ColorfulInfinity.cs diff --git a/samples/ComputeSharp.Sample.SwapChain/Program.cs b/samples/ComputeSharp.Sample.SwapChain/Program.cs index 1bb260cd..f28ae939 100644 --- a/samples/ComputeSharp.Sample.SwapChain/Program.cs +++ b/samples/ComputeSharp.Sample.SwapChain/Program.cs @@ -7,7 +7,7 @@ namespace ComputeSharp.Sample.SwapChain { static void Main(string[] args) { - Win32ApplicationRunner.Run(new SwapChainApplication(static (texture, time) => new(texture, (float)time.TotalSeconds))); + Win32ApplicationRunner.Run(new SwapChainApplication(static (texture, time) => new(texture, (float)time.TotalSeconds))); } } } diff --git a/samples/ComputeSharp.Sample.SwapChain/Shaders/ColorfulInfinity.cs b/samples/ComputeSharp.Sample.SwapChain/Shaders/ColorfulInfinity.cs new file mode 100644 index 00000000..f5566663 --- /dev/null +++ b/samples/ComputeSharp.Sample.SwapChain/Shaders/ColorfulInfinity.cs @@ -0,0 +1,79 @@ +namespace ComputeSharp.Sample.SwapChain.Shaders +{ + /// + /// A shader creating an abstract and colorful animation. + /// Ported from . + /// Created by Benoit Marini. + /// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. + /// + [AutoConstructor] + internal readonly partial struct ColorfulInfinity : IComputeShader + { + /// + /// The target texture. + /// + public readonly IReadWriteTexture2D texture; + + /// + /// The current time since the start of the application. + /// + public readonly float time; + + /// + /// The total number of layers for the final animation. + /// + private const float NumberOfLayers = 16.0f; + + /// + /// The number of iterations to calculate a texel value. + /// + private const int NumberOfIterations = 23; + + /// + /// Makes some magic happen. + /// + private Float4 Tex(Float3 p) + { + float t = time + 78.0f; + Float4 o = new(p.X, p.Y, p.Z, 3.0f * Hlsl.Sin(t * 0.1f)); + Float4 dec = + new Float4(1.0f, 0.9f, 0.1f, 0.15f) + + new Float4(0.06f * Hlsl.Cos(t * 0.1f), 0, 0, 0.14f * Hlsl.Cos(t * 0.23f)); + + for (int i = 0; i++ < NumberOfIterations;) + { + o.XZYW = Hlsl.Abs(o / Hlsl.Dot(o, o) - dec); + } + + return o; + } + + /// + public void Execute() + { + int width = texture.Width; + int height = texture.Height; + + Float2 uv = ((Float2)ThreadIds.XY - (Float2)(new Int2(width, height)) * 0.5f) / height; + Float3 col = 0; + float t = time * 0.3f; + + for (float i = 0.0f; i <= 1.0f; i += 1.0f / NumberOfLayers) + { + float d = Hlsl.Frac(i + t); + float s = Hlsl.Lerp(5.0f, 0.5f, d); + float f = d * Hlsl.SmoothStep(1.0f, 0.9f, d); + + col += Tex(new Float3(uv.X * s, uv.Y * s, i * 4.0f)).XYZ * f; + } + + col /= NumberOfLayers; + col *= new Float3(2, 1.0f, 2.0f); + col = Hlsl.Pow(col, 0.5f); + + Float4 color = new(col.X, col.Y, col.Z, 1.0f); + + texture[ThreadIds.XY] = color; + } + } +} diff --git a/samples/ComputeSharp.Sample.SwapChain/Shaders/TwoTiledTruchet.cs b/samples/ComputeSharp.Sample.SwapChain/Shaders/TwoTiledTruchet.cs index 14e5213b..176f330c 100644 --- a/samples/ComputeSharp.Sample.SwapChain/Shaders/TwoTiledTruchet.cs +++ b/samples/ComputeSharp.Sample.SwapChain/Shaders/TwoTiledTruchet.cs @@ -120,7 +120,6 @@ int height = texture.Height; Float2 uv = ((Float2)ThreadIds.XY - (Float2)(new Int2(width, height)) * 0.5f) / height; - float gSc = 7.0f; Float2 p = uv * gSc - new Float2(-1, -0.5f) * time / 2.0f; float sf = 2.0f / height * gSc; From f778abd94155a39338aa579de957fa81e374ad80 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 23 Feb 2021 03:28:12 +0100 Subject: [PATCH 15/16] Added sample selection --- .../ComputeSharp.Sample.SwapChain/Program.cs | 38 +++++++++++++++++-- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/samples/ComputeSharp.Sample.SwapChain/Program.cs b/samples/ComputeSharp.Sample.SwapChain/Program.cs index f28ae939..98d036cd 100644 --- a/samples/ComputeSharp.Sample.SwapChain/Program.cs +++ b/samples/ComputeSharp.Sample.SwapChain/Program.cs @@ -1,13 +1,45 @@ -using ComputeSharp.Sample.SwapChain.Backend; +using System; +using ComputeSharp.Sample.SwapChain.Backend; using ComputeSharp.Sample.SwapChain.Shaders; namespace ComputeSharp.Sample.SwapChain { class Program { - static void Main(string[] args) + /// + /// The mapping of available samples to choose from. + /// + private static readonly Win32Application[] Samples = new Win32Application[] { - Win32ApplicationRunner.Run(new SwapChainApplication(static (texture, time) => new(texture, (float)time.TotalSeconds))); + new SwapChainApplication(static (texture, time) => new(texture, (float)time.TotalSeconds)), + new SwapChainApplication(static (texture, time) => new(texture, (float)time.TotalSeconds)), + new SwapChainApplication(static (texture, time) => new(texture, (float)time.TotalSeconds)) + }; + + static void Main() + { + Console.WriteLine("Available samples:"); + Console.WriteLine(); + + for (int i = 0; i < Samples.Length; i++) + { + Console.WriteLine($"{i}: {Samples[i].GetType().GenericTypeArguments[0].Name}"); + } + + Console.WriteLine(); + + int index; + + do + { + Console.Write("Enter the index of the sample to run: "); + } + while (!int.TryParse(Console.ReadLine(), out index)); + + Console.WriteLine(); + Console.WriteLine($"Starting {Samples[index].GetType().GenericTypeArguments[0].Name}..."); + + Win32ApplicationRunner.Run(Samples[index]); } } } From 12e849d8cbd8234119135aacd9297da301e3a0d4 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 23 Feb 2021 04:10:02 +0100 Subject: [PATCH 16/16] Improved sample window style --- .../Backend/Win32ApplicationRunner.cs | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/samples/ComputeSharp.Sample.SwapChain/Backend/Win32ApplicationRunner.cs b/samples/ComputeSharp.Sample.SwapChain/Backend/Win32ApplicationRunner.cs index c101b362..047e0c65 100644 --- a/samples/ComputeSharp.Sample.SwapChain/Backend/Win32ApplicationRunner.cs +++ b/samples/ComputeSharp.Sample.SwapChain/Backend/Win32ApplicationRunner.cs @@ -111,6 +111,14 @@ namespace ComputeSharp.Sample.SwapChain.Backend hInstance, (void*)GCHandle.ToIntPtr(GCHandle.Alloc(application)) ); + + MARGINS margins = default; + margins.cxLeftWidth = -1; + margins.cxRightWidth = -1; + margins.cyTopHeight = -1; + margins.cyBottomHeight = -1; + + _ = FX.DwmExtendFrameIntoClientArea(hwnd, &margins); } windowSize = new Size((int)height, (int)width); @@ -241,6 +249,8 @@ namespace ComputeSharp.Sample.SwapChain.Backend return 0; } + + // Size update case FX.WM_SIZE: { uint size = (uint)lParam; @@ -255,6 +265,72 @@ namespace ComputeSharp.Sample.SwapChain.Backend return 0; } + // Size and position of the window (needed to enable the borderless mode) + case FX.WM_NCCALCSIZE: + { + return 0; + } + + // Enable dragging the window + case FX.WM_NCHITTEST: + { + POINT point; + RECT rect; + + _ = FX.GetCursorPos(&point); + _ = FX.GetWindowRect(hwnd, &rect); + + bool + isAtTop = Math.Abs(point.y - rect.top) < 12, + isAtRight = Math.Abs(point.x - rect.right) < 12, + isAtBottom = Math.Abs(point.y - rect.bottom) < 12, + isAtLeft = Math.Abs(point.x - rect.left) < 12; + + if (isAtTop) + { + if (isAtRight) return FX.HTTOPRIGHT; + if (isAtLeft) return FX.HTTOPLEFT; + return FX.HTTOP; + } + + if (isAtRight) + { + if (isAtTop) return FX.HTTOPRIGHT; + if (isAtBottom) return FX.HTBOTTOMRIGHT; + return FX.HTRIGHT; + } + + if (isAtBottom) + { + if (isAtRight) return FX.HTBOTTOMRIGHT; + if (isAtLeft) return FX.HTBOTTOMLEFT; + return FX.HTBOTTOM; + } + + if (isAtLeft) + { + if (isAtTop) return FX.HTTOPLEFT; + if (isAtBottom) return FX.HTBOTTOMLEFT; + return FX.HTLEFT; + } + + return FX.HTCAPTION; + } + + // Restore the drop shadow + case FX.WM_DWMCOMPOSITIONCHANGED: + { + MARGINS margins = default; + margins.cxLeftWidth = -1; + margins.cxRightWidth = -1; + margins.cyTopHeight = -1; + margins.cyBottomHeight = -1; + + _ = FX.DwmExtendFrameIntoClientArea(hwnd, &margins); + + return 0; + } + // Shutdown case FX.WM_DESTROY: {