diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fb91940..772e5e9 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -70,6 +70,14 @@ jobs: if: runner.os == 'Windows' shell: pwsh run: dotnet run --project samples/ModernTriangle -c Debug -- --warp --resize-test --evidence=artifacts/triangle-resize + - name: WARP texture and depth samples + if: runner.os == 'Windows' + shell: pwsh + run: | + dotnet run --project samples/HelloTexture -c Debug -- --warp --frames=4 + if ($LASTEXITCODE -ne 0) { throw 'HelloTexture failed.' } + dotnet run --project samples/AdvancedSample -c Debug -- --warp --frames=4 + if ($LASTEXITCODE -ne 0) { throw 'AdvancedSample failed.' } - name: WARP compute and DirectML numerical qualification if: runner.os == 'Windows' shell: pwsh diff --git a/DXSharp.sln b/DXSharp.sln index 954f09b..980ec22 100644 --- a/DXSharp.sln +++ b/DXSharp.sln @@ -138,6 +138,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModernTriangle", "samples\M EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModernCompute", "samples\ModernCompute\ModernCompute.csproj", "{2BB6521A-B6BC-4BD3-AC2E-67E8042386E4}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DXSharp.Framework.Desktop", "src\DXSharp.Framework.Desktop\DXSharp.Framework.Desktop.csproj", "{2ABFBD91-D516-4267-88F3-F232D822D38B}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -302,6 +304,18 @@ Global {2BB6521A-B6BC-4BD3-AC2E-67E8042386E4}.Release|x64.Build.0 = Release|x64 {2BB6521A-B6BC-4BD3-AC2E-67E8042386E4}.Release|x86.ActiveCfg = Release|x86 {2BB6521A-B6BC-4BD3-AC2E-67E8042386E4}.Release|x86.Build.0 = Release|x86 + {2ABFBD91-D516-4267-88F3-F232D822D38B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2ABFBD91-D516-4267-88F3-F232D822D38B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2ABFBD91-D516-4267-88F3-F232D822D38B}.Debug|x64.ActiveCfg = Debug|x64 + {2ABFBD91-D516-4267-88F3-F232D822D38B}.Debug|x64.Build.0 = Debug|x64 + {2ABFBD91-D516-4267-88F3-F232D822D38B}.Debug|x86.ActiveCfg = Debug|x86 + {2ABFBD91-D516-4267-88F3-F232D822D38B}.Debug|x86.Build.0 = Debug|x86 + {2ABFBD91-D516-4267-88F3-F232D822D38B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2ABFBD91-D516-4267-88F3-F232D822D38B}.Release|Any CPU.Build.0 = Release|Any CPU + {2ABFBD91-D516-4267-88F3-F232D822D38B}.Release|x64.ActiveCfg = Release|x64 + {2ABFBD91-D516-4267-88F3-F232D822D38B}.Release|x64.Build.0 = Release|x64 + {2ABFBD91-D516-4267-88F3-F232D822D38B}.Release|x86.ActiveCfg = Release|x86 + {2ABFBD91-D516-4267-88F3-F232D822D38B}.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -333,12 +347,12 @@ Global {6D81F5A7-1D01-49DF-8D02-ECD9183FDF6F} = {4A52D278-0251-4FD5-BF3A-5C52C294480A} {AA296E18-E027-4E92-A7D7-42FC5086A052} = {AEE84FD5-7441-42CF-AA6C-5805B759E1F8} {2BB6521A-B6BC-4BD3-AC2E-67E8042386E4} = {AEE84FD5-7441-42CF-AA6C-5805B759E1F8} + {2ABFBD91-D516-4267-88F3-F232D822D38B} = {29411031-4490-4542-B2D1-02D223BFD605} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {7C4990EC-248E-49D5-A254-EA8AD214C338} EndGlobalSection GlobalSection(SharedMSBuildProjectFiles) = preSolution samples\shared\DXSharp.Samples.Shared\DXSharp.Samples.Shared.projitems*{29e67012-6798-43e1-befe-f9270f595779}*SharedItemsImports = 13 - samples\shared\DXSharp.Samples.Shared\DXSharp.Samples.Shared.projitems*{f3c57f0f-8540-4e97-b28d-a34091c53755}*SharedItemsImports = 5 EndGlobalSection EndGlobal diff --git a/build/VerifyPackages.ps1 b/build/VerifyPackages.ps1 index b7ec0c7..f70650b 100644 --- a/build/VerifyPackages.ps1 +++ b/build/VerifyPackages.ps1 @@ -16,7 +16,7 @@ try { if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($version)) { throw 'Unable to evaluate the package version.' } - foreach ($name in @('DXSharp', 'DXSharp.Dxc', 'DXSharp.Framework', 'DXSharp.Core', 'DXSharp.DirectML')) { + foreach ($name in @('DXSharp', 'DXSharp.Dxc', 'DXSharp.Framework', 'DXSharp.Framework.Desktop', 'DXSharp.Core', 'DXSharp.DirectML')) { if (-not (Test-Path (Join-Path $packageDirectory "$name.$version.nupkg"))) { throw "Missing package: $name.$version.nupkg" } @@ -34,6 +34,7 @@ try { + @@ -42,6 +43,7 @@ try { System.Console.WriteLine(typeof(DXSharp.Direct3D12.IDevice).Assembly.FullName); System.Console.WriteLine(typeof(DXSharp.Dxc.ShaderBuilder).Assembly.FullName); System.Console.WriteLine(typeof(DXSharp.Graphics.GraphicsDevice).Assembly.FullName); +System.Console.WriteLine(typeof(DXSharp.Framework.Desktop.DesktopGame).Assembly.FullName); System.Console.WriteLine(typeof(DXSharp.MachineLearning.DirectMlDevice).Assembly.FullName); '@ | Set-Content (Join-Path $consumerDirectory 'Program.cs') @" diff --git a/doc/Generated-Com-Foundation.md b/doc/Generated-Com-Foundation.md index a6e86af..ccea0b2 100644 --- a/doc/Generated-Com-Foundation.md +++ b/doc/Generated-Com-Foundation.md @@ -112,3 +112,15 @@ If Developer PowerShell selects an `x64` platform subdirectory, use the matching The launcher records the executable hash, arguments, OS, architecture and SDK/runtime inventory, and asks ProcDump to launch only that executable and capture a full dump on an unhandled exception. It does not change global crash settings. ModernTriangle also writes `diagnostics.json` and managed failures under its evidence directory. Next investigation requires the crashing native instruction, native/managed stacks, loaded-module versions and device-removal evidence from that exact run. Primary references: [source-generated COM](https://learn.microsoft.com/dotnet/standard/native-interop/comwrappers-source-generation), [unique ComObject.FinalRelease](https://learn.microsoft.com/dotnet/api/system.runtime.interopservices.marshalling.comobject.finalrelease), [DirectML binding](https://learn.microsoft.com/windows/ai/directml/dml-binding), [Microsoft's HelloDirectML](https://github.com/microsoft/DirectML/blob/master/Samples/HelloDirectML/main.cpp), [ProcDump](https://learn.microsoft.com/sysinternals/downloads/procdump). + +## Desktop samples + +`DXSharp.Framework.Desktop` hosts the WinForms window, frame timing, back buffers, resize, optional depth target, presentation, and shutdown. The caller owns its device, shaders, pipelines, and scene resources. The draw callback records into the frame's borrowed command list. The host currently uses one allocator and waits for each draw submission. + +- **ModernTriangle** exercises the shared host, including its existing `--resize-test`. +- **HelloTexture** ports the checkerboard triangle from [Microsoft's D3D12 Hello Texture](https://github.com/microsoft/DirectX-Graphics-Samples/tree/master/Samples/Desktop/D3D12HelloWorld/src/HelloTexture). It uploads a single-mip RGBA8 texture with row padding and samples it through an SRV and static sampler. +- **AdvancedSample** exercises per-frame matrices, lighting, and a D32 depth target with a rotating cube. See [the sample README](../samples/AdvancedSample/readme.md). + +Run either new sample with `--warp --frames=4` for the bounded Windows software-adapter check. With no arguments, the sample uses the hardware adapter and runs until its window closes. + +The next Microsoft port candidates are [Hello Frame Buffering](https://github.com/microsoft/DirectX-Graphics-Samples/tree/master/Samples/Desktop/D3D12HelloWorld/src/HelloFrameBuffering) for multiple frames in flight, [ExecuteIndirect](https://github.com/microsoft/DirectX-Graphics-Samples/tree/master/Samples/Desktop/D3D12ExecuteIndirect) for GPU-driven draws, and [D3D12 Multithreading](https://github.com/microsoft/DirectX-Graphics-Samples/tree/master/Samples/Desktop/D3D12Multithreading) for a shadow pass and parallel recording. diff --git a/samples/AdvancedSample/AdvancedSample.csproj b/samples/AdvancedSample/AdvancedSample.csproj index ea8b2fc..b01a163 100644 --- a/samples/AdvancedSample/AdvancedSample.csproj +++ b/samples/AdvancedSample/AdvancedSample.csproj @@ -1,71 +1,14 @@ - - - - false - Exe - WinExe - 0.1.0 - 0.1.0 - - Advanced DXSharp Sample - AdvancedDXS - Assets\DXSharp_ICON_256.ico - - $(TargetCPUs); - $(DotNetTargets) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Assets\Shaders\obj\%(Filename).blob - Assets\Shaders\obj\%(Filename).cso - 5_0 - vs;ps; - - - - - - - - - - - - - - - - ./app.manifest - PerMonitorV2 - - - + + Exe + $(DotNetTargets) + AdvancedDXS + Assets/DXSharp_ICON_256.ico + PerMonitorV2 + + + + + + diff --git a/samples/AdvancedSample/Program.cs b/samples/AdvancedSample/Program.cs index c2e27b2..906b337 100644 --- a/samples/AdvancedSample/Program.cs +++ b/samples/AdvancedSample/Program.cs @@ -1,41 +1,85 @@ -#region Using Directives -using System.Drawing ; +using System.Numerics; +using System.Runtime.InteropServices; +using DXSharp.Framework.Desktop; +using DXSharp.Graphics; +using DXSharp.Shaders; -using DXSharp ; -using DXSharp.Applications ; -using AdvancedDXS.Framework ; - -#if DEBUG || DEBUG_COM -using DXSharp.Framework.Debugging ; -using IDebugD3D = DXSharp.Direct3D12.IDebug6 ; -using IDebugDXGI = DXSharp.DXGI.Debugging.IDebug1 ; -#endif -#endregion - - -//! Create the app startup settings: -AppSettings Settings = new( "DXSharp: Advanced Sample", - (1920 , 1080), - new AppSettings.Style { - FontSize = 13, - FontName = "Consolas", - BackBufferColor = Color.Black, - ForegroundColor = Color.Black, - BackgroundColor = SystemColors.Window, - } ) ; +namespace AdvancedDXS; +internal static class Program { + private const string Shader = """ + cbuffer Scene : register(b0) { + row_major float4x4 WorldViewProjection; + row_major float4x4 World; + }; + struct Vertex { float4 position : SV_Position; float3 color : COLOR; }; + Vertex VS(uint id : SV_VertexID) { + const float3 corners[8] = { + float3(-1,-1,-1), float3(1,-1,-1), float3(1,1,-1), float3(-1,1,-1), + float3(-1,-1, 1), float3(1,-1, 1), float3(1,1, 1), float3(-1,1, 1) + }; + const uint indices[36] = { + 0,3,2, 0,2,1, 4,5,6, 4,6,7, 0,4,7, 0,7,3, + 1,2,6, 1,6,5, 3,7,6, 3,6,2, 0,1,5, 0,5,4 + }; + const float3 normals[6] = { + float3(0,0,-1), float3(0,0,1), float3(-1,0,0), + float3(1,0,0), float3(0,1,0), float3(0,-1,0) + }; + const float3 colors[6] = { + float3(0.18,0.7,0.92), float3(0.27,0.85,0.68), float3(0.25,0.4,0.82), + float3(0.97,0.55,0.22), float3(0.8,0.9,1), float3(0.62,0.34,0.88) + }; + uint face = id / 6; + float3 normal = mul(normals[face], (float3x3)World); + float light = 0.28 + 0.72 * saturate(dot(normal, normalize(float3(0.45, 0.8, 0.65)))); + Vertex output; + output.position = mul(float4(corners[indices[id]], 1), WorldViewProjection); + output.color = colors[face] * light; + return output; + } + float4 PS(Vertex input) : SV_Target { return float4(input.color, 1); } + """; -//! Enable the debug layer in debug mode: -#if DEBUG || DEBUG_COM -await using DebugSystem< IDebugD3D, IDebugDXGI > dbg = new( ) ; -dbg.Enable( ) ; + [STAThread] + public static int Main( string[] args ) { + Application.SetUnhandledExceptionMode( UnhandledExceptionMode.ThrowException ); + ApplicationConfiguration.Initialize( ); +#if DEBUG + const bool debugLayer = true; +#else + const bool debugLayer = false; #endif + int frameLimit = int.Parse( args.FirstOrDefault( x => x.StartsWith( "--frames=", StringComparison.Ordinal ) )?[9..] ?? "0" ); + using var device = GraphicsDevice.Create( new( ) { + UseWarp = args.Contains( "--warp" ), + UseAgility = !args.Contains( "--system-runtime" ), + EnableDebugLayer = debugLayer && !args.Contains( "--no-debug" ) + } ); + Console.WriteLine( device.AdapterName ); + using var compiler = new ShaderCompiler( ); + using var root = device.CreateGraphicsConstantsRootSignature( 32 ); + using var pipeline = device.CreateGraphicsPipeline( root, compiler.Compile( Shader, "VS", "vs_6_0" ), + compiler.Compile( Shader, "PS", "ps_6_0" ), PixelFormat.Rgba8Unorm, depthEnabled: true ); - - -// Initialize & run the app: -var app = new DXSApp( Settings ) - .Initialize( ) ; - -app.Run( ) ; -app?.Shutdown( ) ; \ No newline at end of file + var view = Matrix4x4.CreateLookAt( new Vector3( 0, 1.4f, 5.8f ), Vector3.Zero, Vector3.UnitY ); + float angle = 0.65f; + var result = DesktopGame.Run( device, new( ) { + Title = "DXSharp · Advanced Sample · Lit Cube", FrameLimit = frameLimit, EnableDepth = true + }, frame => { + angle += Math.Min( (float)frame.Elapsed.TotalSeconds, 0.1f ) * 0.9f; + var world = Matrix4x4.CreateRotationX( 0.45f ) * Matrix4x4.CreateRotationY( angle ); + var projection = Matrix4x4.CreatePerspectiveFieldOfView( MathF.PI / 3, (float)frame.Size.Width / frame.Size.Height, 0.1f, 100 ); + ReadOnlySpan matrices = [world * view * projection, world]; + frame.Commands.SetGraphicsPipeline( pipeline ); + frame.Commands.SetGraphicsConstants( MemoryMarshal.Cast( matrices ) ); + frame.Commands.Draw( 36 ); + } ); + var diagnostics = device.GetDiagnostics( ); + foreach ( string message in diagnostics.Messages ) Console.WriteLine( message ); + if ( diagnostics.DeviceRemovedReason < 0 || diagnostics.Messages.Any( x => x.Contains( "SEVERITY_ERROR" ) || x.Contains( "SEVERITY_CORRUPTION" ) ) ) return 1; + if ( frameLimit > 0 && result.Frames != frameLimit ) return 1; + Console.WriteLine( $"AdvancedSample closed cleanly after {result.Frames} frames." ); + return 0; + } +} diff --git a/samples/AdvancedSample/packages.lock.json b/samples/AdvancedSample/packages.lock.json index c79c7c1..15a81f9 100644 --- a/samples/AdvancedSample/packages.lock.json +++ b/samples/AdvancedSample/packages.lock.json @@ -2,21 +2,30 @@ "version": 2, "dependencies": { "net10.0-windows10.0.26100": { - "dxsharp": { - "type": "Project" - }, - "dxsharp.dxc": { + "dxsharp.core": { "type": "Project", "dependencies": { - "DXSharp": "[0.4.0-net10-preview.1, )" + "Microsoft.Direct3D.D3D12": "[1.620.1, 1.620.1]", + "Microsoft.Direct3D.DXC": "[1.9.2609.5, 1.9.2609.5]" } }, - "dxsharp.framework": { + "dxsharp.framework.desktop": { "type": "Project", "dependencies": { - "DXSharp": "[0.4.0-net10-preview.1, )", - "DXSharp.Dxc": "[0.4.0-net10-preview.1, )" + "DXSharp.Core": "[0.4.0-net10-preview.1, )" } + }, + "Microsoft.Direct3D.D3D12": { + "type": "CentralTransitive", + "requested": "[1.620.1, )", + "resolved": "1.620.1", + "contentHash": "oQCFTys3PZ0IHtS3I/u0/1IWgpuG7aQa+84AGiraqc8bMOCM8QpDLwLBshEbJ1J7LmuctZReXhF8c0eCiu2Xcw==" + }, + "Microsoft.Direct3D.DXC": { + "type": "CentralTransitive", + "requested": "[1.9.2609.5, )", + "resolved": "1.9.2609.5", + "contentHash": "jTWr7a2bMpqV+b0Uc7oxOo8ualplaUw3fsQ+p0kp9TwlWvvmREvt3SA4+Drl2Y0M31iscqZolrL3vpdnLoPpdg==" } } } diff --git a/samples/AdvancedSample/readme.md b/samples/AdvancedSample/readme.md index 84ccd68..466523e 100644 --- a/samples/AdvancedSample/readme.md +++ b/samples/AdvancedSample/readme.md @@ -1,65 +1,10 @@ -# DXSharp "Advanced Sample" +# DXSharp AdvancedSample ---- +AdvancedSample draws a lit, rotating cube using the desktop framework and the generated COM graphics API. It uploads world and world-view-projection matrices as root constants, uses a D32 depth buffer, and updates the projection and depth target when the window is resized. -## Introduction: -___ - - -### Important Notes: -In order to run this sample, it requires the following: - -- Windows 10.1 or later -- DirectX 12 compatible GPU -- Windows 10 SDK (10.0.22621.0+) or later - - - **Note:** You can lower the version number in the - `AdvancedSample.csproj` file to match your Windows SDK version. - - If you change the version number, you're responsible for the compatibility implications! - - Be careful what Direct3D, DXGI or other features you use and the versions that support it. - - Many interfaces and API functions are marked with `SupportedOSPlatform` attributes as guidance. - - These attributes give compiler warnings about method call sights and version numbers, but can't be relied on. - -### Project/Assembly Dependencies: -- #### **DXSharp**.dll - - Native DLLs: - - *D3D12Core.dll* - - *d3d12SDKLayers.dll* - ---- - -- #### **DXSharp.Dxc**.dll - - Native DLLs: - - *dxcompiler.dll* - - *dxil.dll* - ---- - -The sample includes a `PackageReference` for the `Microsoft.Direct3D.D3D12` package (aka, the DirectX "Agility SDK") and -for the `Microsoft.Direct3D.DXC` package (aka, the DirectX "Shader Compiler"). - -The new MSBuild script should now automatically copy the native NuGet dependencies for Agility SDK into the output directory. -So, the previous instructions about manually copying the Agility SDK binaries side-along with the assembly -should no longer be necessary. If you get errors about missing native DLLs, please make an issue and report it. -But manually copying the native Agility SDK *.dll files should fix it. You can also modify the Props and Targets -to do custom setups. - - * **NOTE:** DXSharp looks for `d3d12core.dll` and - `d3d12sdklayers.dll` in the same directory as the DXSharp assembly. Your project MSBuild script can grab all of these - things and put them wherever you want them to live in your solution tree. - * You can set `$(UsingAgilitySDK)` to `true` or `false` in your project file to enable/disable the Agility SDK - * If you disable Agility SDK, the default Windows SDK libraries are loaded. - * Native Dxc (DirectX Shader Compiler) binaries still need to accompany the `DXSharp.Dxc` assembly. - ---- - -## Sample Overview: - -The purpose of this sample is to provide a more "advanced" playground for DXSharp development, to act as a catalyst for -progress and provide a more "realistic" example and way to test and profile the DXSharp runtime. This project is -recommended for those who are more familiar with the DirectX SDK and are looking for a more "advanced" example of how to -use DXSharp to build things. - - -____________________________________________________________________________________________________________________ +```powershell +dotnet run --project samples/AdvancedSample -c Debug +dotnet run --project samples/AdvancedSample -c Debug -- --warp --frames=4 +``` +The earlier scene, camera and shadow-map experiments under `Framework/` and `Assets/` remain as reference source. The runnable project compiles the modern entry point. [Microsoft's D3D12 Multithreading sample](https://github.com/microsoft/DirectX-Graphics-Samples/tree/master/Samples/Desktop/D3D12Multithreading) is a reference for a later port with shadow passes and parallel command recording. diff --git a/samples/HelloTexture/BasicApp.cs b/samples/HelloTexture/BasicApp.cs deleted file mode 100644 index 65dd6f2..0000000 --- a/samples/HelloTexture/BasicApp.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Windows.Forms ; -using DXSharp.Applications ; -namespace HelloTexture ; - - -public class BasicApp: DXWinformApp { - public static BasicApp? Instance { get; private set ; } - GraphicsSettings _graphicsSettings ; - GraphicsPipeline? graphics ; - - public BasicApp( AppSettings settings ): base( settings ) { - if( Instance is not null ) - throw new InvalidOperationException( "Only one instance of BasicApp is allowed" ) ; - - Instance = this ; - _graphicsSettings = new( 2 ) ; - } - - public override BasicApp Initialize( ) { - base.Initialize( ) ; - Window!.SetSize( Settings.WindowSize ) ; - MainForm!.StartPosition = FormStartPosition.CenterScreen ; - - graphics = new( _graphicsSettings ) ; - graphics.LoadPipeline( ) ; - graphics.LoadAssets( ) ; - return this ; - } -} ; \ No newline at end of file diff --git a/samples/HelloTexture/DebugHelper.cs b/samples/HelloTexture/DebugHelper.cs deleted file mode 100644 index 6ea71ce..0000000 --- a/samples/HelloTexture/DebugHelper.cs +++ /dev/null @@ -1,77 +0,0 @@ -using System.Diagnostics ; -using DXSharp.Direct3D12 ; -using D3D12 = DXSharp.Direct3D12.D3D12 ; -using IDebug6 = DXSharp.Direct3D12.IDebug6 ; -namespace HelloTexture ; - - -public static class DebugHelper { - const string LOG_OUTPUT_PATH = @"\logs", - LOG_FILE_NAME = $"{nameof(DebugHelper)}-" ; - - static readonly Stack< string > InfoLogStack = new( ) ; - - public static IDebug6 Init( bool EnableGPUBasedValidation = true, - GPUBasedValidationFlags flags = - GPUBasedValidationFlags.None, - bool EnableAutoName = true ) { - LogInfo( $"Initializing debug layer ..." ) ; - var hr = D3D12.GetDebugInterface( out IDebug6? debug6 ) ; - hr.ThrowOnFailure( ) ; - ObjectDisposedException.ThrowIf( debug6 is null, typeof( IDebug6 ) ) ; - - //! Enable the debug layer: - hr = debug6.EnableDebugLayer( ) ; - LogInfo( $"Initialization Result: {hr} (0x{hr.Value:x}) - " + - $"{( hr.Succeeded ? "SUCCEEDED" : "FAILED" )}" ) ; - hr.ThrowOnFailure( ) ; - - if( EnableAutoName ) - debug6.SetEnableAutoName( EnableAutoName ) ; - LogInfo( $"AutoName is {( EnableAutoName ? "enabled" : "disabled" )}..." ) ; - - if ( EnableGPUBasedValidation ) { - debug6.SetGPUBasedValidationFlags( flags ) ; - debug6.SetEnableGPUBasedValidation( EnableGPUBasedValidation ) ; - } - LogInfo( $"GPU-based validation is {( EnableAutoName ? "enabled" : "disabled" )}..." ) ; - return debug6 ; - } - - - public static void LogInfo( params string[] messages ) { - foreach ( string msg in messages ) { - LogInfo( msg ) ; - } - } - public static void LogInfo( string message ) { - ArgumentException.ThrowIfNullOrEmpty( message, nameof( message ) ) ; - - Debug.WriteLine( message ) ; - Console.WriteLine( message ) ; - InfoLogStack.Push( message ) ; - } - - /// - /// Gets all of the info log text lines as an array of . - /// - /// All text from the info log stack as a array. - public static string[ ] GetInfoLogLines( ) => InfoLogStack.ToArray( ) ; - - public static async ValueTask SaveLogFileAsync( ) { - string[ ] lines = GetInfoLogLines( ) ; - if ( lines is { Length: < 1 } ) { - LogInfo( "No log lines to save." ) ; - } - string timestamp = DateTime.Now.ToString( "yyyy-MM-dd-HH-mm-ss" ) ; - string path = Path.Combine( Environment.CurrentDirectory, LOG_OUTPUT_PATH ) ; - - if ( !Directory.Exists(path) ) { - Directory.CreateDirectory( path ) ; - } - - string fileName = $"{LOG_FILE_NAME}{timestamp}.log" ; - path = Path.Combine( path, fileName ) ; - await File.WriteAllLinesAsync( path, lines ) ; - } -} ; \ No newline at end of file diff --git a/samples/HelloTexture/GraphicsPipeline.cs b/samples/HelloTexture/GraphicsPipeline.cs deleted file mode 100644 index 93a97a5..0000000 --- a/samples/HelloTexture/GraphicsPipeline.cs +++ /dev/null @@ -1,211 +0,0 @@ -#region Using Directives -using Windows.Win32.Foundation ; - -using DXSharp ; -using DXSharp.DXGI ; -using DXSharp.Windows ; -using DXSharp.Direct3D12 ; -using DXSharp.Windows.COM ; -using DXSharp.Applications ; -using DXSharp.Windows.Win32 ; -#endregion -namespace HelloTexture ; - - -public class GraphicsPipeline: DXGraphics { - #region Constant/ReadOnly Members - // ----------------------------------------------------- - // Constant & Read-Only Values: - // ----------------------------------------------------- - const int MAX_ADAPTERS = 0x10 ; - const FactoryCreateFlags FACTORY_FLAGS = -#if DEBUG - FactoryCreateFlags.Debug ; -#else - FactoryCreateFlags.None ; -#endif - // =================================================== - #endregion - - - // ----------------------------------------------------- - // Instance Fields: - // ----------------------------------------------------- - HWnd _wnd ; - BasicApp? _app ; - GraphicsSettings _settings ; - PCWSTR _DBGName_Factory = default, - _DBGName_Device = default ; - - IFactory7? _factory ; - IDevice10? _device ; - // ===================================================== - - - // ----------------------------------------------------------------------------------------------------------------- - - public GraphicsPipeline( GraphicsSettings? settings = null ) { - _DBGName_Factory = "DXSharp.DXGI.IFactory7" ; - _DBGName_Device = "DXSharp.Direct3D12.IDevice12" ; - Add( _DBGName_Factory ) ; - Add( _DBGName_Device ) ; - - _app = BasicApp.Instance ?? - throw new InvalidOperationException( "Application instance is not initialized!" ) ; - _settings = settings ?? GraphicsSettings.Default ; - - _wnd = _app.Window?.Handle ?? HWnd.Null ; - if( _wnd.IsNull ) throw new DXSharpException( "Window handle is null!" ) ; - } - - // ----------------------------------------------------------------------------------------------------------------- - - - public override void LoadPipeline( ) { - // Create the DXGI factory: - var hr = DXGIFunctions.CreateFactory2( IFactory7.IID, out var _f7, - FACTORY_FLAGS ) ; - _factory = (IFactory7) _f7 ; -#if DEBUG || DEBUG_COM || DEV_BUILD - hr.ThrowOnFailure( ) ; - if( _factory is null ) throw new DXSharpException($"Failed to create DXGI factory! (hr = {hr})") ; - _setDBGName( _DBGName_Factory, _factory ) ; -#endif - - // Get the best GPU: - using var adapter = _getBestGPU( _factory ) ; - - // Create the D3D12 device: - _device = D3D12.CreateDevice< IDevice10 >( adapter, FeatureLevel.D3D12_0 ) ; - if ( _device is null ) throw new DXSharpException( $"Failed to create {nameof(IDevice10)}!" ) ; - else Add( _device ) ; - - // Describe & create the command queue: - _device.CreateCommandQueue( CommandQueueDescription.Default, - ICommandQueue.IID, out ICommandQueue? cmdQueue ) ; - if( cmdQueue is null ) throw new DXSharpException( "Failed to create command queue!" ) ; - else Add( cmdQueue ) ; - - // Describe the swap chain: - var swapChainDesc = new SwapChainDescription1 { - BufferCount = _settings.BufferCount, - Width = 0, Height = 0, - Format = Format.R8G8B8A8_UNORM, - BufferUsage = Usage.RenderTargetOutput, - SwapEffect = SwapEffect.FlipDiscard, - SampleDesc = ( 1, 0 ), - } ; - var swapchainFSDesc = new SwapChainFullscreenDescription { - RefreshRate = new Rational( 60, 1 ), - Scaling = ScalingMode.Stretched, - Windowed = true, - } ; - - // Create the swapchain: - _factory.CreateSwapChainForHwnd( cmdQueue, _wnd, swapChainDesc, swapchainFSDesc, - null, out var swapChain1 ) ; - var swapChain = COMUtility.Cast< ISwapChain1, ISwapChain4 >( swapChain1 ) ; - if( swapChain is null ) throw new DXSharpException( "Failed to create swap chain!" ) ; - else Add( swapChain ) ; - swapChain1?.DisposeAsync( ) ; - - - // Set the window association flags: - _factory.MakeWindowAssociation( _wnd, WindowAssociation.NoAltEnter ) ; - - // Create the descriptor heaps: - uint frameCount = _settings.BufferCount ; - DescriptorHeapDescription rtvHeapDesc = new( DescriptorHeapType.RTV, frameCount ) ; - _device.CreateDescriptorHeap( rtvHeapDesc, IDescriptorHeap.IID, out IDescriptorHeap? rtvHeap ) ; - if( rtvHeap is null ) throw new DXSharpException( "Failed to create RTV descriptor heap!" ) ; - - DescriptorHeapDescription dsvHeapDesc = new( DescriptorHeapType.CBV_SRV_UAV, - 1, - DescriptorHeapFlags.ShaderVisible ) ; - _device.CreateDescriptorHeap( dsvHeapDesc, IDescriptorHeap.IID, out IDescriptorHeap? dsvHeap ) ; - - var rtvHandle = rtvHeap!.GetCPUDescriptorHandleForHeapStart( ) ; - var rtvDescSize = _device.GetDescriptorHandleIncrementSize( DescriptorHeapType.RTV ) ; - - // Create frame resources with a RTV for each frame: - for ( uint n = 0; n < frameCount; ++n ) { - swapChain.GetBuffer< IResource2 >( n, out var buffer ) ; - _device.CreateRenderTargetView( buffer, default, rtvHandle ) ; - rtvHandle.Offset( 1, rtvDescSize ) ; - } - - static IAdapter4? _getBestGPU( IFactory7 factory ) { - List< IAdapter1 > adapters = new( ) ; - IAdapter4? bestAdapter = null ; - ulong maxVRAM = 0 ; - - for( uint i = 0; i < MAX_ADAPTERS; ++i ) { - IAdapter1? _adapter = default ; - var hr = factory.EnumAdapters1( i, out _adapter ) ; - - //! Is this the last adapter? - if( hr == HResult.DXGI_ERROR_NOT_FOUND || _adapter is null ) break ; - else hr.ThrowOnFailure( ) ; - - adapters.Add( _adapter ) ; - var adapter = COMUtility.Cast< IAdapter1, IAdapter4 >( _adapter ) ; - if ( adapter is null ) { -#if DEBUG || DEBUG_COM || DEV_BUILD - throw new DXSharpException( $"Failed to cast " + - $"{nameof(IAdapter1)} to " + - $"{nameof(IAdapter4)}!" ) ; -#else - continue; -#endif - } - - adapter.GetDesc3( out var _desc ) ; - - // Skip software and remote adapters: - if( _desc.Flags.HasFlag( AdapterFlag3.Software ) - || _desc.Flags.HasFlag( AdapterFlag3.Remote ) ) continue ; - - ulong vram = (ulong)_desc.DedicatedVideoMemory ; - if( vram > maxVRAM ) { - maxVRAM = vram ; - bestAdapter = (IAdapter4)adapter ; - } - } - foreach ( var adapter in adapters ) adapter.Dispose( ) ; - return bestAdapter ; - } - } - - public override void LoadAssets( ) { } - - - // ----------------------------------------------------- - // Static Helper Methods: - // ----------------------------------------------------- - - static unsafe void _setDBGName( in PCWSTR name, in IDXCOMObject obj ) => - obj.SetPrivateData( COMUtility.WKPDID_D3DDebugObjectName, - (uint)name.Length * sizeof(char), (nint)name.Value ) ; - - static PCWSTR _setDBGName( string name, in IDXCOMObject obj ) { - unsafe { - PCWSTR _name = name ; - obj.SetPrivateData( COMUtility.WKPDID_D3DDebugObjectName, - (uint)name.Length * sizeof( char ), (nint)_name.Value ) ; - return _name ; - } - } - - // ================================================================================================================= -} ; - - - -/* - void _setDBGName( in string name, in IDXCOMObject? obj ) { - var pStr = Marshal.StringToCoTaskMemAuto( name ) ; - obj?.SetPrivateData< char >( COMUtility.WKPDID_D3DDebugObjectName, - (uint)name.Length * sizeof(char), (nint)pStr ) ; - } - - */ \ No newline at end of file diff --git a/samples/HelloTexture/GraphicsSettings.cs b/samples/HelloTexture/GraphicsSettings.cs deleted file mode 100644 index 72c54c5..0000000 --- a/samples/HelloTexture/GraphicsSettings.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace HelloTexture ; - -public class GraphicsSettings { - public static readonly GraphicsSettings Default = new( ) { - BufferCount = 2, - } ; - - public uint BufferCount { get; set ; } = 2 ; - - public GraphicsSettings( ) { } - public GraphicsSettings( uint bufferCount ) { - BufferCount = bufferCount ; - } -} \ No newline at end of file diff --git a/samples/HelloTexture/HelloTexture.csproj b/samples/HelloTexture/HelloTexture.csproj index 1a4c957..3e55a14 100644 --- a/samples/HelloTexture/HelloTexture.csproj +++ b/samples/HelloTexture/HelloTexture.csproj @@ -1,19 +1,9 @@ - - - Exe - WinExe - - $(TargetCPUs); - $(DotNetTargets) - - - - - - - - - - + + Exe + $(DotNetTargets) + + + + diff --git a/samples/HelloTexture/Program.cs b/samples/HelloTexture/Program.cs index 4a04847..a36fe4f 100644 --- a/samples/HelloTexture/Program.cs +++ b/samples/HelloTexture/Program.cs @@ -1,46 +1,74 @@ -#region Using Directives -using System.Drawing ; -using DXSharp.Applications ; -using DXSharp.Direct3D12 ; -using HelloTexture ; -#endregion +using DXSharp.Framework.Desktop; +using DXSharp.Graphics; +using DXSharp.Shaders; +namespace HelloTexture; -Console.WriteLine("\"Hello Texture\" sample started ...") ; -AppSettings Settings = new( "DXSharp: Hello Texture", - (1920, 1080), - new AppSettings.Style { - FontSize = 13, - FontName = "Consolas", - BackBufferColor = Color.Black, - ForegroundColor = Color.Black, - BackgroundColor = SystemColors.Window, - } ) ; +internal static class Program { + // Based on Microsoft's D3D12 Hello Texture sample. Vertex data is generated in HLSL. + private const string Shader = """ + Texture2D Checker : register(t0); + SamplerState PointClamp : register(s0); + struct Vertex { float4 position : SV_Position; float2 uv : TEXCOORD; }; + Vertex VS(uint id : SV_VertexID) { + const float2 positions[3] = { float2(0, 0.72), float2(0.68, -0.65), float2(-0.68, -0.65) }; + const float2 uvs[3] = { float2(0.5, 0), float2(1, 1), float2(0, 1) }; + Vertex output; + output.position = float4(positions[id], 0, 1); + output.uv = uvs[id]; + return output; + } + float4 PS(Vertex input) : SV_Target { return Checker.Sample(PointClamp, input.uv); } + """; - - -#if DEBUG || DEBUG_COM -//! Debug Settings -------------------------------------------------------------------- -const GPUBasedValidationFlags gpuBasedValidationFlags = GPUBasedValidationFlags.None ; -const bool EnableGPUBasedValidation = true ; -const bool EnableAutoName = true ; -// ------------------------------------------------------------------------------------ -var debug6 = DebugHelper.Init( EnableGPUBasedValidation, - gpuBasedValidationFlags, - EnableAutoName ) ; -// ------------------------------------------------------------------------------------ + [STAThread] + public static int Main( string[] args ) { + Application.SetUnhandledExceptionMode( UnhandledExceptionMode.ThrowException ); + ApplicationConfiguration.Initialize( ); +#if DEBUG + const bool debugLayer = true; +#else + const bool debugLayer = false; #endif + int frameLimit = int.Parse( args.FirstOrDefault( x => x.StartsWith( "--frames=", StringComparison.Ordinal ) )?[9..] ?? "0" ); + using var device = GraphicsDevice.Create( new( ) { + UseWarp = args.Contains( "--warp" ), + UseAgility = !args.Contains( "--system-runtime" ), + EnableDebugLayer = debugLayer && !args.Contains( "--no-debug" ) + } ); + Console.WriteLine( device.AdapterName ); + using var uploadQueue = device.CreateCommandQueue( ); + using var compiler = new ShaderCompiler( ); + using var root = device.CreateTextureRootSignature( ); + using var pipeline = device.CreateGraphicsPipeline( root, compiler.Compile( Shader, "VS", "vs_6_0" ), compiler.Compile( Shader, "PS", "ps_6_0" ) ); + const int size = 250; // Exercises row-pitch padding. + using var texture = device.CreateSampledTexture2D( uploadQueue, size, size, Checkerboard( size ) ); + var result = DesktopGame.Run( device, new( ) { Title = "DXSharp · Hello Texture", FrameLimit = frameLimit }, frame => { + frame.Commands.SetGraphicsPipeline( pipeline ); + frame.Commands.SetGraphicsTexture( texture ); + frame.Commands.Draw( 3 ); + } ); + var diagnostics = device.GetDiagnostics( ); + foreach ( string message in diagnostics.Messages ) Console.WriteLine( message ); + if ( diagnostics.DeviceRemovedReason < 0 || diagnostics.Messages.Any( x => x.Contains( "SEVERITY_ERROR" ) || x.Contains( "SEVERITY_CORRUPTION" ) ) ) return 1; + if ( frameLimit > 0 && result.Frames != frameLimit ) return 1; + Console.WriteLine( $"HelloTexture closed cleanly after {result.Frames} frames." ); + return 0; + } -// Initialize & run the app: -using IDXApp app = new BasicApp( Settings ) ; -app.Initialize( ) ; -app.Run( ) ; -app.Shutdown( ) ; - - -#if DEBUG || DEBUG_COM -//! Destroy the debug layer in debug mode: -debug6.DisableDebugLayer( ) ; -await debug6.DisposeAsync( ) ; -#endif \ No newline at end of file + private static byte[] Checkerboard( int size ) { + byte[] pixels = new byte[size * size * 4]; + for ( int y = 0; y < size; ++y ) { + for ( int x = 0; x < size; ++x ) { + int i = (y * size + x) * 4; + bool light = ((x * 8 / size ^ y * 8 / size) & 1) == 0; + pixels[i] = light ? (byte)239 : (byte)24; + pixels[i + 1] = light ? (byte)245 : (byte)107; + pixels[i + 2] = light ? (byte)231 : (byte)160; + pixels[i + 3] = 255; + } + } + return pixels; + } +} diff --git a/samples/HelloTexture/packages.lock.json b/samples/HelloTexture/packages.lock.json index 1edce93..15a81f9 100644 --- a/samples/HelloTexture/packages.lock.json +++ b/samples/HelloTexture/packages.lock.json @@ -2,8 +2,30 @@ "version": 2, "dependencies": { "net10.0-windows10.0.26100": { - "dxsharp": { - "type": "Project" + "dxsharp.core": { + "type": "Project", + "dependencies": { + "Microsoft.Direct3D.D3D12": "[1.620.1, 1.620.1]", + "Microsoft.Direct3D.DXC": "[1.9.2609.5, 1.9.2609.5]" + } + }, + "dxsharp.framework.desktop": { + "type": "Project", + "dependencies": { + "DXSharp.Core": "[0.4.0-net10-preview.1, )" + } + }, + "Microsoft.Direct3D.D3D12": { + "type": "CentralTransitive", + "requested": "[1.620.1, )", + "resolved": "1.620.1", + "contentHash": "oQCFTys3PZ0IHtS3I/u0/1IWgpuG7aQa+84AGiraqc8bMOCM8QpDLwLBshEbJ1J7LmuctZReXhF8c0eCiu2Xcw==" + }, + "Microsoft.Direct3D.DXC": { + "type": "CentralTransitive", + "requested": "[1.9.2609.5, )", + "resolved": "1.9.2609.5", + "contentHash": "jTWr7a2bMpqV+b0Uc7oxOo8ualplaUw3fsQ+p0kp9TwlWvvmREvt3SA4+Drl2Y0M31iscqZolrL3vpdnLoPpdg==" } } } diff --git a/samples/ModernTriangle/ModernTriangle.csproj b/samples/ModernTriangle/ModernTriangle.csproj index 79f8dcf..0c2672d 100644 --- a/samples/ModernTriangle/ModernTriangle.csproj +++ b/samples/ModernTriangle/ModernTriangle.csproj @@ -4,6 +4,6 @@ net10.0-windows10.0.26100.0 - + diff --git a/samples/ModernTriangle/Program.cs b/samples/ModernTriangle/Program.cs index 9f0b0f2..21d7755 100644 --- a/samples/ModernTriangle/Program.cs +++ b/samples/ModernTriangle/Program.cs @@ -1,5 +1,6 @@ using System.Text; using System.Text.Json; +using DXSharp.Framework.Desktop; using DXSharp.Graphics; using DXSharp.Shaders; @@ -45,38 +46,31 @@ public static int Main( string[] args ) { if ( !headless ) { Application.SetUnhandledExceptionMode( UnhandledExceptionMode.ThrowException ); ApplicationConfiguration.Initialize( ); - using var window = new Form { Text = "DXSharp · Generated COM · .NET 10", ClientSize = new( 1024, 720 ) }; - window.Show( ); - using var renderer = new Renderer( device, compiler, window ); - int frames = 0; - Size initialSize = window.ClientSize; - using var timer = new System.Windows.Forms.Timer { Interval = 1 }; - window.FormClosing += ( _, _ ) => timer.Stop( ); - timer.Tick += ( _, _ ) => { - if ( window.Disposing || !window.IsHandleCreated || window.WindowState == FormWindowState.Minimized ) return; - Size clientSize = window.ClientSize; - if ( clientSize.Width <= 0 || clientSize.Height <= 0 ) return; - // Native presentation can dispatch window messages. Do not render from a nested tick. - timer.Stop( ); - bool resized = renderer.Render( clientSize ); + using var root = device.CreateRootSignature( ); + using var pipeline = device.CreateGraphicsPipeline( root, compiler.Compile( Shader, "VS", "vs_6_0" ), compiler.Compile( Shader, "PS", "ps_6_0" ) ); + Size initialSize = default; + int previousResizes = 0; + bool stressGc = args.Contains( "--gc-stress" ); + var result = DesktopGame.Run( device, new( ) { Title = "DXSharp · Generated COM · .NET 10", FrameLimit = frameLimit }, frame => { + frame.Commands.SetGraphicsPipeline( pipeline ); + frame.Commands.Draw( 3 ); + }, ( window, progress ) => { if ( resizeTest ) { - if ( frames == 0 ) { - window.ClientSize = new Size( initialSize.Width + 64, initialSize.Height + 48 ); - } else if ( frames is 1 or 2 ) { - if ( !resized ) throw new InvalidOperationException( "The test window size change did not resize the swap chain." ); - if ( frames == 1 ) window.ClientSize = initialSize; + if ( progress.Frames == 1 ) { + initialSize = window.ClientSize; + window.ClientSize = new( initialSize.Width + 64, initialSize.Height + 48 ); + } else if ( progress.Frames is 2 or 3 ) { + if ( progress.Resizes == previousResizes ) + throw new InvalidOperationException( "The test window size change did not resize the swap chain." ); + if ( progress.Frames == 2 ) window.ClientSize = initialSize; else Console.WriteLine( "PASS: rendered and presented after both swap-chain resizes." ); } } - if ( args.Contains( "--gc-stress" ) && frames % 30 == 0 ) { GC.Collect( ); GC.WaitForPendingFinalizers( ); } - ++frames; - if ( frameLimit > 0 && frames >= frameLimit ) window.Close( ); - else if ( window.IsHandleCreated && !window.Disposing ) timer.Start( ); - }; - // Propagate rendering failures to the outer evidence handler. - timer.Start( ); Application.Run( window ); timer.Stop( ); - if ( resizeTest && frames < 3 ) throw new InvalidOperationException( "The window closed before the resize test completed." ); - Console.WriteLine( $"Rendered {frames} frames." ); + previousResizes = progress.Resizes; + if ( stressGc && (progress.Frames - 1) % 30 == 0 ) { GC.Collect( ); GC.WaitForPendingFinalizers( ); } + } ); + if ( resizeTest && result.Frames < 3 ) throw new InvalidOperationException( "The window closed before the resize test completed." ); + Console.WriteLine( $"Rendered {result.Frames} frames." ); } var diagnostics = WriteDiagnostics( device, evidence ); if ( diagnostics.DeviceRemovedReason < 0 || diagnostics.Messages.Any( x => x.Contains( "SEVERITY_ERROR" ) || x.Contains( "SEVERITY_CORRUPTION" ) ) ) @@ -129,62 +123,4 @@ private static void ComputeRoundTrip( GraphicsDevice device, ShaderCompiler comp Console.WriteLine( "PASS: compute/readback = 1234; native dependencies survived public disposal and GC." ); } - private sealed class Renderer : IDisposable { - private readonly GraphicsDevice _device; - private readonly CommandQueue _queue; - private readonly CommandAllocator _allocator; - private readonly GraphicsCommandList _commands; - private readonly SwapChain _swap; - private readonly DescriptorHeap _rtvHeap; - private readonly RootSignature _root; - private readonly PipelineState _pipeline; - private readonly GpuResource?[] _buffers = new GpuResource?[2]; - private readonly RenderTargetView[] _views = new RenderTargetView[2]; - private uint _width, _height; - internal Renderer( GraphicsDevice device, ShaderCompiler compiler, Form window ) { - _device = device; - _width = (uint)window.ClientSize.Width; _height = (uint)window.ClientSize.Height; - _queue = device.CreateCommandQueue( ); _allocator = device.CreateCommandAllocator( ); - _commands = device.CreateCommandList( _allocator ); _commands.Close( ); - _swap = device.CreateSwapChain( _queue, window.Handle, _width, _height ); - _rtvHeap = device.CreateRenderTargetHeap( 2 ); _root = device.CreateRootSignature( ); - _pipeline = device.CreateGraphicsPipeline( _root, compiler.Compile( Shader, "VS", "vs_6_0" ), compiler.Compile( Shader, "PS", "ps_6_0" ) ); - AcquireBuffers( ); - } - private void AcquireBuffers( ) { - for ( uint i = 0; i < 2; ++i ) { - _buffers[i] = _swap.AcquireBackBuffer( i ); - _views[i] = _device.CreateRenderTargetView( _buffers[i]!, _rtvHeap, i ); - } - } - internal bool Render( Size clientSize ) { - uint width = (uint)clientSize.Width, height = (uint)clientSize.Height; - bool resized = width != _width || height != _height; - if ( resized ) _queue.WaitIdle( ); - _allocator.Reset( ); - _commands.Reset( _allocator ); - if ( resized ) { - foreach ( var buffer in _buffers ) buffer?.Dispose( ); - Array.Clear( _buffers ); - Array.Clear( _views ); - Console.WriteLine( $"Resizing swap chain from {_width}x{_height} to {width}x{height}." ); - _swap.Resize( width, height ); - _width = width; - _height = height; - AcquireBuffers( ); - } - uint index = _swap.CurrentBackBufferIndex; - _commands.Transition( _buffers[index]!, ResourceState.Present, ResourceState.RenderTarget ); - _commands.SetViewport( _width, _height ); _commands.Clear( _views[index], 0.025f, 0.035f, 0.065f ); - _commands.SetRenderTarget( _views[index] ); _commands.SetGraphicsPipeline( _pipeline ); _commands.Draw( 3 ); - _commands.Transition( _buffers[index]!, ResourceState.RenderTarget, ResourceState.Present ); - _commands.Close( ); _queue.Wait( _queue.Submit( _commands ) ); _swap.Present( ); - return resized; - } - public void Dispose( ) { - _queue.WaitIdle( ); _commands.Dispose( ); - foreach ( var buffer in _buffers ) buffer?.Dispose( ); Array.Clear( _views ); - _pipeline.Dispose( ); _root.Dispose( ); _rtvHeap.Dispose( ); _swap.Dispose( ); _allocator.Dispose( ); _queue.Dispose( ); - } - } } diff --git a/samples/ModernTriangle/packages.lock.json b/samples/ModernTriangle/packages.lock.json index d0ee3eb..15a81f9 100644 --- a/samples/ModernTriangle/packages.lock.json +++ b/samples/ModernTriangle/packages.lock.json @@ -9,6 +9,12 @@ "Microsoft.Direct3D.DXC": "[1.9.2609.5, 1.9.2609.5]" } }, + "dxsharp.framework.desktop": { + "type": "Project", + "dependencies": { + "DXSharp.Core": "[0.4.0-net10-preview.1, )" + } + }, "Microsoft.Direct3D.D3D12": { "type": "CentralTransitive", "requested": "[1.620.1, )", diff --git a/src/DXSharp.Core/Graphics/Commands.cs b/src/DXSharp.Core/Graphics/Commands.cs index 31db923..2e25767 100644 --- a/src/DXSharp.Core/Graphics/Commands.cs +++ b/src/DXSharp.Core/Graphics/Commands.cs @@ -79,6 +79,35 @@ public void CopyBuffer( GpuResource source, GpuResource destination, ulong size, Track( source ); Track( destination ); Native.Interface.CopyBufferRegion( destination.Native.Interface, destinationOffset, source.Native.Interface, sourceOffset, size ); } + internal void CopyTextureFromUpload( GpuResource upload, GpuResource texture, D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint ) { + Recording( ); + Track( upload ); + Track( texture ); + using var uploadLease = upload.Native.Borrow( ); + using var textureLease = texture.Native.Borrow( ); + D3D12_TEXTURE_COPY_LOCATION source = new( ) { + pResource = (ID3D12Resource_unmanaged*)uploadLease.Pointer, + Type = D3D12_TEXTURE_COPY_TYPE.D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT + }; + source.Anonymous.PlacedFootprint = footprint; + D3D12_TEXTURE_COPY_LOCATION target = new( ) { + pResource = (ID3D12Resource_unmanaged*)textureLease.Pointer, + Type = D3D12_TEXTURE_COPY_TYPE.D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX + }; + Native.Interface.CopyTextureRegion( target, 0, 0, 0, source, null ); + } + + /// Binds t0 for a graphics pipeline created with a texture root signature. + /// This replaces the current shader-visible CBV/SRV/UAV heap. + public void SetGraphicsTexture( SampledTexture2D texture ) { + ArgumentNullException.ThrowIfNull( texture ); + Recording( ); + Track( texture.Resource ); + Track( texture.Heap ); + Native.Interface.SetDescriptorHeaps( 1, [texture.Heap.Native.Interface] ); + Native.Interface.SetGraphicsRootDescriptorTable( 0, texture.Heap.Native.Interface.GetGPUDescriptorHandleForHeapStart( ) ); + } + /// Sets a viewport and scissor rectangle. public void SetViewport( uint width, uint height ) { Recording( ); if ( width == 0 || height == 0 ) throw new ArgumentOutOfRangeException( nameof(width) ); @@ -98,6 +127,29 @@ public void SetRenderTarget( RenderTargetView target ) { var handle = target.Handle; Native.Interface.OMSetRenderTargets( 1, &handle, false, null ); } + /// Binds a color target and a D32 depth target, optionally clearing depth to 1. + public void SetRenderTarget( RenderTargetView target, DepthTarget depth, bool clearDepth = false ) { + ArgumentNullException.ThrowIfNull( depth ); + Recording( ); + Track( target.Heap ); + Track( target.Resource ); + Track( depth.Heap ); + Track( depth.Resource ); + var colorHandle = target.Handle; + var depthHandle = depth.Heap.CpuHandle( 0 ); + if ( clearDepth ) + Native.Interface.ClearDepthStencilView( depthHandle, D3D12_CLEAR_FLAGS.D3D12_CLEAR_FLAG_DEPTH, 1, 0, 0, null ); + Native.Interface.OMSetRenderTargets( 1, &colorHandle, false, &depthHandle ); + } + + /// Copies inline values to b0 for a graphics pipeline with a graphics constants root signature. + public void SetGraphicsConstants( ReadOnlySpan values ) { + Recording( ); + if ( values.Length is 0 or > 64 ) throw new ArgumentOutOfRangeException( nameof(values) ); + fixed ( uint* pointer = values ) + Native.Interface.SetGraphicsRoot32BitConstants( 0, (uint)values.Length, pointer, 0 ); + } + /// Binds a graphics root signature and pipeline. public void SetGraphicsPipeline( PipelineState pipeline ) { Recording( ); if ( pipeline.IsCompute ) throw new ArgumentException( "A graphics pipeline is required." ); diff --git a/src/DXSharp.Core/Graphics/DepthTarget.cs b/src/DXSharp.Core/Graphics/DepthTarget.cs new file mode 100644 index 0000000..55ddd5c --- /dev/null +++ b/src/DXSharp.Core/Graphics/DepthTarget.cs @@ -0,0 +1,60 @@ +using Windows.Win32.Graphics.Direct3D12; +using Windows.Win32.Graphics.Dxgi.Common; +using DXSharp.Interop; + +namespace DXSharp.Graphics; + +/// An owning D32 depth resource and its depth-stencil view. +public sealed class DepthTarget : IDisposable { + internal GpuResource Resource { get; } + internal DescriptorHeap Heap { get; } + internal DepthTarget( GpuResource resource, DescriptorHeap heap ) { Resource = resource; Heap = heap; } + + /// Releases the public owners. Recorded command lists retain their own references. + public void Dispose( ) { + Heap.Dispose( ); + Resource.Dispose( ); + } +} + +public sealed unsafe partial class GraphicsDevice { + /// Creates a D32_FLOAT depth target in the depth-write state, with a clear value of 1. + public DepthTarget CreateDepthTarget( uint width, uint height ) { + ArgumentOutOfRangeException.ThrowIfZero( width ); + ArgumentOutOfRangeException.ThrowIfZero( height ); + if ( width > 16384 || height > 16384 ) throw new ArgumentException( "Depth target dimensions exceed the D3D12 Texture2D limit." ); + var format = DXGI_FORMAT.DXGI_FORMAT_D32_FLOAT; + D3D12_RESOURCE_DESC description = new( ) { + Dimension = D3D12_RESOURCE_DIMENSION.D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width = width, Height = height, DepthOrArraySize = 1, MipLevels = 1, Format = format, + SampleDesc = new( ) { Count = 1 }, + Flags = D3D12_RESOURCE_FLAGS.D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAGS.D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE + }; + D3D12_HEAP_PROPERTIES memory = new( ) { Type = D3D12_HEAP_TYPE.D3D12_HEAP_TYPE_DEFAULT, CreationNodeMask = 1, VisibleNodeMask = 1 }; + D3D12_CLEAR_VALUE clear = new( ) { Format = format }; + clear.Anonymous.DepthStencil.Depth = 1; + Guid id = typeof(ID3D12Resource).GUID; + nint pointer = 0; + Results.Check( Native.Interface.CreateCommittedResource( &memory, 0, &description, + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_DEPTH_WRITE, &clear, &id, (void**)&pointer ), "CreateCommittedResource(Depth)" ); + var resource = new GpuResource( ComOwner.Adopt( pointer ), 0, BufferMemory.Default ) { DeviceIdentity = DeviceIdentity }; + try { + var type = D3D12_DESCRIPTOR_HEAP_TYPE.D3D12_DESCRIPTOR_HEAP_TYPE_DSV; + D3D12_DESCRIPTOR_HEAP_DESC heapDescription = new( ) { Type = type, NumDescriptors = 1 }; + id = typeof(ID3D12DescriptorHeap).GUID; + Results.Check( Native.Interface.CreateDescriptorHeap( &heapDescription, &id, out pointer ), "CreateDescriptorHeap(Depth)" ); + var heap = new DescriptorHeap( ComOwner.Adopt( pointer ), 1, + Native.Interface.GetDescriptorHandleIncrementSize( type ) ) { DeviceIdentity = DeviceIdentity }; + try { + Native.Interface.CreateDepthStencilView( resource.Native.Interface, null, heap.CpuHandle( 0 ) ); + return new( resource, heap ); + } catch { + heap.Dispose( ); + throw; + } + } catch { + resource.Dispose( ); + throw; + } + } +} diff --git a/src/DXSharp.Core/Graphics/GraphicsTypes.cs b/src/DXSharp.Core/Graphics/GraphicsTypes.cs index 32a7107..f17db76 100644 --- a/src/DXSharp.Core/Graphics/GraphicsTypes.cs +++ b/src/DXSharp.Core/Graphics/GraphicsTypes.cs @@ -8,7 +8,7 @@ public enum QueueKind { Direct = 0, Compute = 2, Copy = 3 } [Flags] public enum ResourceState : uint { Common = 0, Present = 0, VertexAndConstantBuffer = 1, RenderTarget = 4, UnorderedAccess = 8, - CopyDestination = 0x400, CopySource = 0x800, GenericRead = 0xac3 + PixelShaderResource = 0x80, CopyDestination = 0x400, CopySource = 0x800, GenericRead = 0xac3 } /// CPU/GPU buffer placement. public enum BufferMemory { Default = 1, Upload = 2, Readback = 3 } diff --git a/src/DXSharp.Core/Graphics/Pipelines.cs b/src/DXSharp.Core/Graphics/Pipelines.cs index 9e40422..e95f8db 100644 --- a/src/DXSharp.Core/Graphics/Pipelines.cs +++ b/src/DXSharp.Core/Graphics/Pipelines.cs @@ -48,24 +48,73 @@ public RootSignature CreateRootSignature( uint computeBufferCount = 0 ) { NumParameters = computeBufferCount, pParameters = pointer, Flags = computeBufferCount == 0 ? D3D12_ROOT_SIGNATURE_FLAGS.D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT : 0 }; - int hr = SerializeRoot( description, out nint blobPointer, out nint errorPointer ); - try { - Results.Check( hr, "SerializeVersionedRootSignature" ); - nint owned = blobPointer; blobPointer = 0; - using var blob = ComOwner.Adopt( owned ); - Guid id = typeof(ID3D12RootSignature).GUID; - Results.Check( Native.Interface.CreateRootSignature( 0, blob.Interface.GetBufferPointer( ), blob.Interface.GetBufferSize( ), &id, out nint rootPointer ), "CreateRootSignature" ); - return new( ComOwner.Adopt( rootPointer ) ) { DeviceIdentity = DeviceIdentity }; - } finally { - if ( blobPointer != 0 ) UnknownCalls.Release( blobPointer ); - if ( errorPointer != 0 ) UnknownCalls.Release( errorPointer ); - } + return CreateRootSignature( description ); + } + } + + /// Creates a graphics root signature with a pixel shader texture at t0 and a point-clamp sampler at s0. + public RootSignature CreateTextureRootSignature( ) { + D3D12_DESCRIPTOR_RANGE range = new( ) { RangeType = D3D12_DESCRIPTOR_RANGE_TYPE.D3D12_DESCRIPTOR_RANGE_TYPE_SRV, NumDescriptors = 1 }; + D3D12_ROOT_PARAMETER parameter = new( ) { + ParameterType = D3D12_ROOT_PARAMETER_TYPE.D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + ShaderVisibility = D3D12_SHADER_VISIBILITY.D3D12_SHADER_VISIBILITY_PIXEL + }; + parameter.Anonymous.DescriptorTable = new( ) { NumDescriptorRanges = 1, pDescriptorRanges = &range }; + var clamp = D3D12_TEXTURE_ADDRESS_MODE.D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + D3D12_STATIC_SAMPLER_DESC sampler = new( ) { + Filter = D3D12_FILTER.D3D12_FILTER_MIN_MAG_MIP_POINT, + AddressU = clamp, AddressV = clamp, AddressW = clamp, + MaxAnisotropy = 1, MaxLOD = float.MaxValue, + ComparisonFunc = D3D12_COMPARISON_FUNC.D3D12_COMPARISON_FUNC_ALWAYS, + ShaderVisibility = D3D12_SHADER_VISIBILITY.D3D12_SHADER_VISIBILITY_PIXEL + }; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC description = default; + description.Version = D3D_ROOT_SIGNATURE_VERSION.D3D_ROOT_SIGNATURE_VERSION_1_0; + description.Anonymous.Desc_1_0 = new( ) { + NumParameters = 1, pParameters = ¶meter, + NumStaticSamplers = 1, pStaticSamplers = &sampler + }; + return CreateRootSignature( description ); + } + + /// Creates a graphics root signature with up to 64 inline DWORDs at b0. + public RootSignature CreateGraphicsConstantsRootSignature( uint valueCount ) { + if ( valueCount is 0 or > 64 ) throw new ArgumentOutOfRangeException( nameof(valueCount) ); + D3D12_ROOT_PARAMETER parameter = new( ) { + ParameterType = D3D12_ROOT_PARAMETER_TYPE.D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS + }; + parameter.Anonymous.Constants.Num32BitValues = valueCount; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC description = default; + description.Version = D3D_ROOT_SIGNATURE_VERSION.D3D_ROOT_SIGNATURE_VERSION_1_0; + description.Anonymous.Desc_1_0 = new( ) { NumParameters = 1, pParameters = ¶meter }; + return CreateRootSignature( description ); + } + + private RootSignature CreateRootSignature( in D3D12_VERSIONED_ROOT_SIGNATURE_DESC description ) { + int hr = SerializeRoot( description, out nint blobPointer, out nint errorPointer ); + try { + Results.Check( hr, "SerializeVersionedRootSignature" ); + nint owned = blobPointer; + blobPointer = 0; + using var blob = ComOwner.Adopt( owned ); + Guid id = typeof(ID3D12RootSignature).GUID; + Results.Check( Native.Interface.CreateRootSignature( 0, blob.Interface.GetBufferPointer( ), + blob.Interface.GetBufferSize( ), &id, out nint rootPointer ), "CreateRootSignature" ); + return new( ComOwner.Adopt( rootPointer ) ) { DeviceIdentity = DeviceIdentity }; + } finally { + if ( blobPointer != 0 ) UnknownCalls.Release( blobPointer ); + if ( errorPointer != 0 ) UnknownCalls.Release( errorPointer ); } } /// Creates a triangle-list graphics pipeline for SV_VertexID-generated vertices. public PipelineState CreateGraphicsPipeline( RootSignature root, ShaderCompilation vertex, ShaderCompilation pixel, - PixelFormat targetFormat = PixelFormat.Rgba8Unorm ) { + PixelFormat targetFormat = PixelFormat.Rgba8Unorm ) => + CreateGraphicsPipeline( root, vertex, pixel, targetFormat, depthEnabled: false ); + + /// Creates a triangle-list graphics pipeline with optional D32_FLOAT depth testing and writes. + public PipelineState CreateGraphicsPipeline( RootSignature root, ShaderCompilation vertex, ShaderCompilation pixel, + PixelFormat targetFormat, bool depthEnabled ) { RequireSameDevice( root ); vertex.RequireSuccess( ); pixel.RequireSuccess( ); if ( vertex.Bytecode.IsEmpty || pixel.Bytecode.IsEmpty ) throw new ArgumentException( "Both compiled shader objects are required." ); @@ -85,6 +134,12 @@ public PipelineState CreateGraphicsPipeline( RootSignature root, ShaderCompilati LogicOp = D3D12_LOGIC_OP.D3D12_LOGIC_OP_NOOP, RenderTargetWriteMask = 15 }; description.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC.D3D12_COMPARISON_FUNC_ALWAYS; + if ( depthEnabled ) { + description.DSVFormat = DXGI_FORMAT.DXGI_FORMAT_D32_FLOAT; + description.DepthStencilState.DepthEnable = true; + description.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK.D3D12_DEPTH_WRITE_MASK_ALL; + description.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC.D3D12_COMPARISON_FUNC_LESS; + } description.DepthStencilState.StencilReadMask = byte.MaxValue; description.DepthStencilState.StencilWriteMask = byte.MaxValue; description.DepthStencilState.FrontFace = new( ) { diff --git a/src/DXSharp.Core/Graphics/Textures.cs b/src/DXSharp.Core/Graphics/Textures.cs new file mode 100644 index 0000000..e4f6918 --- /dev/null +++ b/src/DXSharp.Core/Graphics/Textures.cs @@ -0,0 +1,94 @@ +using Windows.Win32.Graphics.Direct3D12; +using Windows.Win32.Graphics.Dxgi.Common; +using DXSharp.Interop; + +namespace DXSharp.Graphics; + +/// An immutable RGBA8 texture and its shader-visible view. +public sealed class SampledTexture2D : IDisposable { + internal GpuResource Resource { get; } + internal DescriptorHeap Heap { get; } + /// Texture width in pixels. + public uint Width { get; } + /// Texture height in pixels. + public uint Height { get; } + + internal SampledTexture2D( GpuResource resource, DescriptorHeap heap, uint width, uint height ) { + Resource = resource; + Heap = heap; + Width = width; + Height = height; + } + + /// Releases the public owners. Recorded command lists retain their own references. + public void Dispose( ) { + Heap.Dispose( ); + Resource.Dispose( ); + } +} + +public sealed unsafe partial class GraphicsDevice { + /// Uploads tightly packed, single-mip RGBA8 pixels and waits until they can be sampled by a pixel shader. + /// Use a direct queue on this device. Row padding is supplied by the SDK. + public SampledTexture2D CreateSampledTexture2D( CommandQueue queue, uint width, uint height, ReadOnlySpan rgba ) { + RequireSameDevice( queue ); + if ( queue.Kind != QueueKind.Direct ) throw new ArgumentException( "Texture upload requires a direct queue.", nameof(queue) ); + ArgumentOutOfRangeException.ThrowIfZero( width ); + ArgumentOutOfRangeException.ThrowIfZero( height ); + if ( width > 16384 || height > 16384 ) throw new ArgumentException( "Texture dimensions exceed the D3D12 Texture2D limit." ); + int rowBytes = checked((int)width * 4); + if ( rgba.Length != checked(rowBytes * (int)height) ) + throw new ArgumentException( "Supply exactly four bytes per pixel.", nameof(rgba) ); + + D3D12_RESOURCE_DESC description = new( ) { + Dimension = D3D12_RESOURCE_DIMENSION.D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width = width, Height = height, DepthOrArraySize = 1, MipLevels = 1, + Format = DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc = new( ) { Count = 1 } + }; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint; + ulong bytes; + Native.Interface.GetCopyableFootprints( &description, 0, 1, 0, &footprint, null, null, &bytes ); + byte[] staging = new byte[checked((int)bytes)]; + for ( int y = 0; y < (int)height; ++y ) { + int offset = checked((int)(footprint.Offset + (ulong)y * footprint.Footprint.RowPitch)); + rgba.Slice( y * rowBytes, rowBytes ).CopyTo( staging.AsSpan( offset, rowBytes ) ); + } + + D3D12_HEAP_PROPERTIES memory = new( ) { Type = D3D12_HEAP_TYPE.D3D12_HEAP_TYPE_DEFAULT, CreationNodeMask = 1, VisibleNodeMask = 1 }; + Guid id = typeof(ID3D12Resource).GUID; + nint pointer = 0; + Results.Check( Native.Interface.CreateCommittedResource( &memory, 0, &description, + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_DEST, null, &id, (void**)&pointer ), "CreateCommittedResource(Texture2D)" ); + var texture = new GpuResource( ComOwner.Adopt( pointer ), 0, BufferMemory.Default ) { DeviceIdentity = DeviceIdentity }; + try { + using var upload = CreateBuffer( bytes, BufferMemory.Upload ); + upload.Write( staging ); + using var allocator = CreateCommandAllocator( ); + using var commands = CreateCommandList( allocator ); + commands.CopyTextureFromUpload( upload, texture, footprint ); + commands.Transition( texture, ResourceState.CopyDestination, ResourceState.PixelShaderResource ); + commands.Close( ); + queue.Wait( queue.Submit( commands ) ); + + var type = D3D12_DESCRIPTOR_HEAP_TYPE.D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + D3D12_DESCRIPTOR_HEAP_DESC heapDescription = new( ) { + Type = type, NumDescriptors = 1, Flags = D3D12_DESCRIPTOR_HEAP_FLAGS.D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE + }; + id = typeof(ID3D12DescriptorHeap).GUID; + Results.Check( Native.Interface.CreateDescriptorHeap( &heapDescription, &id, out pointer ), "CreateDescriptorHeap(Texture2D)" ); + var heap = new DescriptorHeap( ComOwner.Adopt( pointer ), 1, + Native.Interface.GetDescriptorHandleIncrementSize( type ) ) { DeviceIdentity = DeviceIdentity }; + try { + Native.Interface.CreateShaderResourceView( texture.Native.Interface, null, heap.CpuHandle( 0 ) ); + return new( texture, heap, width, height ); + } catch { + heap.Dispose( ); + throw; + } + } catch { + texture.Dispose( ); + throw; + } + } +} diff --git a/src/DXSharp.Framework.Desktop/DXSharp.Framework.Desktop.csproj b/src/DXSharp.Framework.Desktop/DXSharp.Framework.Desktop.csproj new file mode 100644 index 0000000..f7cb10f --- /dev/null +++ b/src/DXSharp.Framework.Desktop/DXSharp.Framework.Desktop.csproj @@ -0,0 +1,10 @@ + + + $(DotNetTargets) + true + WinForms desktop frame hosting for the modern DXSharp graphics API. + + + + + diff --git a/src/DXSharp.Framework.Desktop/DesktopGame.cs b/src/DXSharp.Framework.Desktop/DesktopGame.cs new file mode 100644 index 0000000..ad4c311 --- /dev/null +++ b/src/DXSharp.Framework.Desktop/DesktopGame.cs @@ -0,0 +1,128 @@ +using System.Diagnostics; +using System.Numerics; +using DXSharp.Graphics; + +namespace DXSharp.Framework.Desktop; + +/// Settings for a windowed Direct3D 12 application. +public sealed record DesktopGameOptions { + /// The initial window title. + public string Title { get; init; } = "DXSharp"; + /// The initial client area in pixels. + public Size ClientSize { get; init; } = new( 1024, 720 ); + /// The RGBA clear color. + public Vector4 ClearColor { get; init; } = new( 0.025f, 0.035f, 0.065f, 1 ); + /// Create and clear a D32_FLOAT depth target for each frame. + public bool EnableDepth { get; init; } + /// Close after this many presentations. Zero runs until the window closes. + public int FrameLimit { get; init; } +} + +/// A frame whose command list and render target are borrowed for the draw callback. +public readonly record struct DesktopFrame( GraphicsCommandList Commands, RenderTargetView Target, Size Size, TimeSpan Elapsed ); + +/// Totals from a desktop run. +public readonly record struct DesktopRunResult( int Frames, int Resizes ); + +/// Runs a synchronous WinForms frame loop with a single allocator and two back buffers. +public static class DesktopGame { + /// Runs on the calling STA thread. The host owns the window, submission and presentation. + /// The caller owns the device and scene resources. Record draw commands only during the draw callback. + public static DesktopRunResult Run( GraphicsDevice device, DesktopGameOptions options, Action draw, + Action? framePresented = null ) { + ArgumentNullException.ThrowIfNull( device ); + ArgumentNullException.ThrowIfNull( options ); + ArgumentNullException.ThrowIfNull( draw ); + if ( options.ClientSize.Width <= 0 || options.ClientSize.Height <= 0 || options.FrameLimit < 0 ) + throw new ArgumentOutOfRangeException( nameof(options) ); + if ( Thread.CurrentThread.GetApartmentState( ) != ApartmentState.STA ) + throw new InvalidOperationException( "The desktop game must run on an STA thread." ); + + using var window = new Form { Text = options.Title, ClientSize = options.ClientSize, StartPosition = FormStartPosition.CenterScreen }; + window.Show( ); + Size size = window.ClientSize; + using var queue = device.CreateCommandQueue( ); + using var allocator = device.CreateCommandAllocator( ); + using var commands = device.CreateCommandList( allocator ); + commands.Close( ); + using var swap = device.CreateSwapChain( queue, window.Handle, (uint)size.Width, (uint)size.Height ); + using var heap = device.CreateRenderTargetHeap( swap.BufferCount ); + using var timer = new System.Windows.Forms.Timer { Interval = 1 }; + var buffers = new GpuResource?[swap.BufferCount]; + var targets = new RenderTargetView[swap.BufferCount]; + DepthTarget? depth = null; + var clock = Stopwatch.StartNew( ); + int frames = 0, resizes = 0; + TimeSpan previous = TimeSpan.Zero; + + try { + AcquireBuffers( ); + window.FormClosing += ( _, _ ) => timer.Stop( ); + timer.Tick += ( _, _ ) => { + if ( window.Disposing || !window.IsHandleCreated || window.WindowState == FormWindowState.Minimized ) { + previous = clock.Elapsed; + return; + } + Size clientSize = window.ClientSize; + if ( clientSize.Width <= 0 || clientSize.Height <= 0 ) return; + // Native presentation can dispatch messages. Keep nested timer ticks out of the frame. + timer.Stop( ); + bool resized = clientSize != size; + if ( resized ) queue.WaitIdle( ); + allocator.Reset( ); + commands.Reset( allocator ); + if ( resized ) { + ReleaseBuffers( ); + swap.Resize( (uint)clientSize.Width, (uint)clientSize.Height ); + size = clientSize; + AcquireBuffers( ); + ++resizes; + } + uint index = swap.CurrentBackBufferIndex; + var buffer = buffers[index]!; + var target = targets[index]; + commands.Transition( buffer, ResourceState.Present, ResourceState.RenderTarget ); + commands.SetViewport( (uint)size.Width, (uint)size.Height ); + Vector4 clear = options.ClearColor; + commands.Clear( target, clear.X, clear.Y, clear.Z, clear.W ); + if ( depth is null ) commands.SetRenderTarget( target ); + else commands.SetRenderTarget( target, depth, clearDepth: true ); + TimeSpan now = clock.Elapsed; + draw( new( commands, target, size, now - previous ) ); + previous = now; + commands.Transition( buffer, ResourceState.RenderTarget, ResourceState.Present ); + commands.Close( ); + queue.Wait( queue.Submit( commands ) ); + swap.Present( ); + ++frames; + framePresented?.Invoke( window, new( frames, resizes ) ); + if ( window.IsDisposed || window.Disposing || !window.IsHandleCreated ) return; + if ( options.FrameLimit > 0 && frames >= options.FrameLimit ) window.Close( ); + else timer.Start( ); + }; + timer.Start( ); + Application.Run( window ); + return new( frames, resizes ); + } finally { + timer.Stop( ); + try { queue.WaitIdle( ); } + finally { ReleaseBuffers( ); } + } + + void AcquireBuffers( ) { + for ( uint i = 0; i < swap.BufferCount; ++i ) { + buffers[i] = swap.AcquireBackBuffer( i ); + targets[i] = device.CreateRenderTargetView( buffers[i]!, heap, i ); + } + if ( options.EnableDepth ) depth = device.CreateDepthTarget( (uint)size.Width, (uint)size.Height ); + } + + void ReleaseBuffers( ) { + depth?.Dispose( ); + depth = null; + foreach ( var buffer in buffers ) buffer?.Dispose( ); + Array.Clear( buffers ); + Array.Clear( targets ); + } + } +} diff --git a/src/DXSharp.Framework.Desktop/packages.lock.json b/src/DXSharp.Framework.Desktop/packages.lock.json new file mode 100644 index 0000000..d0ee3eb --- /dev/null +++ b/src/DXSharp.Framework.Desktop/packages.lock.json @@ -0,0 +1,26 @@ +{ + "version": 2, + "dependencies": { + "net10.0-windows10.0.26100": { + "dxsharp.core": { + "type": "Project", + "dependencies": { + "Microsoft.Direct3D.D3D12": "[1.620.1, 1.620.1]", + "Microsoft.Direct3D.DXC": "[1.9.2609.5, 1.9.2609.5]" + } + }, + "Microsoft.Direct3D.D3D12": { + "type": "CentralTransitive", + "requested": "[1.620.1, )", + "resolved": "1.620.1", + "contentHash": "oQCFTys3PZ0IHtS3I/u0/1IWgpuG7aQa+84AGiraqc8bMOCM8QpDLwLBshEbJ1J7LmuctZReXhF8c0eCiu2Xcw==" + }, + "Microsoft.Direct3D.DXC": { + "type": "CentralTransitive", + "requested": "[1.9.2609.5, )", + "resolved": "1.9.2609.5", + "contentHash": "jTWr7a2bMpqV+b0Uc7oxOo8ualplaUw3fsQ+p0kp9TwlWvvmREvt3SA4+Drl2Y0M31iscqZolrL3vpdnLoPpdg==" + } + } + } +} \ No newline at end of file