diff --git a/DXSharp.sln b/DXSharp.sln index 036d79b..f1b38c7 100644 --- a/DXSharp.sln +++ b/DXSharp.sln @@ -166,6 +166,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CharacterLab.Wpf", "samples EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DXSharp.Framework.Wpf", "src\DXSharp.Framework.Wpf\DXSharp.Framework.Wpf.csproj", "{CA095DE4-9BC3-49E4-A764-D4406AA4D795}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DXSharp.Framework.WinUI", "src\DXSharp.Framework.WinUI\DXSharp.Framework.WinUI.csproj", "{A466B395-6AE2-4EA8-8AE7-576F60182FC0}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CharacterLab.WinUI", "samples\CharacterLab.WinUI\CharacterLab.WinUI.csproj", "{0BE7F2F5-66C9-4F48-B0EA-412BC17FC649}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -510,6 +514,30 @@ Global {CA095DE4-9BC3-49E4-A764-D4406AA4D795}.Release|x64.Build.0 = Release|x64 {CA095DE4-9BC3-49E4-A764-D4406AA4D795}.Release|x86.ActiveCfg = Release|x86 {CA095DE4-9BC3-49E4-A764-D4406AA4D795}.Release|x86.Build.0 = Release|x86 + {A466B395-6AE2-4EA8-8AE7-576F60182FC0}.Debug|Any CPU.ActiveCfg = Debug|x64 + {A466B395-6AE2-4EA8-8AE7-576F60182FC0}.Debug|Any CPU.Build.0 = Debug|x64 + {A466B395-6AE2-4EA8-8AE7-576F60182FC0}.Debug|x64.ActiveCfg = Debug|x64 + {A466B395-6AE2-4EA8-8AE7-576F60182FC0}.Debug|x64.Build.0 = Debug|x64 + {A466B395-6AE2-4EA8-8AE7-576F60182FC0}.Debug|x86.ActiveCfg = Debug|x64 + {A466B395-6AE2-4EA8-8AE7-576F60182FC0}.Debug|x86.Build.0 = Debug|x64 + {A466B395-6AE2-4EA8-8AE7-576F60182FC0}.Release|Any CPU.ActiveCfg = Release|x64 + {A466B395-6AE2-4EA8-8AE7-576F60182FC0}.Release|Any CPU.Build.0 = Release|x64 + {A466B395-6AE2-4EA8-8AE7-576F60182FC0}.Release|x64.ActiveCfg = Release|x64 + {A466B395-6AE2-4EA8-8AE7-576F60182FC0}.Release|x64.Build.0 = Release|x64 + {A466B395-6AE2-4EA8-8AE7-576F60182FC0}.Release|x86.ActiveCfg = Release|x64 + {A466B395-6AE2-4EA8-8AE7-576F60182FC0}.Release|x86.Build.0 = Release|x64 + {0BE7F2F5-66C9-4F48-B0EA-412BC17FC649}.Debug|Any CPU.ActiveCfg = Debug|x64 + {0BE7F2F5-66C9-4F48-B0EA-412BC17FC649}.Debug|Any CPU.Build.0 = Debug|x64 + {0BE7F2F5-66C9-4F48-B0EA-412BC17FC649}.Debug|x64.ActiveCfg = Debug|x64 + {0BE7F2F5-66C9-4F48-B0EA-412BC17FC649}.Debug|x64.Build.0 = Debug|x64 + {0BE7F2F5-66C9-4F48-B0EA-412BC17FC649}.Debug|x86.ActiveCfg = Debug|x64 + {0BE7F2F5-66C9-4F48-B0EA-412BC17FC649}.Debug|x86.Build.0 = Debug|x64 + {0BE7F2F5-66C9-4F48-B0EA-412BC17FC649}.Release|Any CPU.ActiveCfg = Release|x64 + {0BE7F2F5-66C9-4F48-B0EA-412BC17FC649}.Release|Any CPU.Build.0 = Release|x64 + {0BE7F2F5-66C9-4F48-B0EA-412BC17FC649}.Release|x64.ActiveCfg = Release|x64 + {0BE7F2F5-66C9-4F48-B0EA-412BC17FC649}.Release|x64.Build.0 = Release|x64 + {0BE7F2F5-66C9-4F48-B0EA-412BC17FC649}.Release|x86.ActiveCfg = Release|x64 + {0BE7F2F5-66C9-4F48-B0EA-412BC17FC649}.Release|x86.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -556,6 +584,8 @@ Global {F2B18F42-2A58-413A-921F-71648DB0C250} = {AEE84FD5-7441-42CF-AA6C-5805B759E1F8} {AEDF6FCA-CFF8-47EB-9DF1-D62C776BE151} = {AEE84FD5-7441-42CF-AA6C-5805B759E1F8} {CA095DE4-9BC3-49E4-A764-D4406AA4D795} = {29411031-4490-4542-B2D1-02D223BFD605} + {A466B395-6AE2-4EA8-8AE7-576F60182FC0} = {29411031-4490-4542-B2D1-02D223BFD605} + {0BE7F2F5-66C9-4F48-B0EA-412BC17FC649} = {AEE84FD5-7441-42CF-AA6C-5805B759E1F8} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {7C4990EC-248E-49D5-A254-EA8AD214C338} diff --git a/Directory.Packages.props b/Directory.Packages.props index 5f71dfa..6e9644f 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -18,5 +18,6 @@ + diff --git a/README.md b/README.md index fe48ad1..a18c399 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ The first command presents four frames and exits. The second verifies GPU comput | `DXSharp.Assets` | Static glTF/GLB models, materials, transforms, and decoded textures | | `DXSharp.Core` | D3D12, DXGI, DXC, and generated COM interop | | `DXSharp.Framework.Desktop` | WinForms presentation loop, swap-chain resize, and frame-slot retirement | +| `DXSharp.Framework.WinUI` | Optional WinUI 3 composition viewport and XAML overlays; [hosting contract](doc/WinUI-Hosting.md) | | `DXSharp.Framework.Wpf` | Optional WPF child-HWND viewport using the shared frame renderer; [hosting contract](doc/Wpf-Hosting.md) | | `DXSharp.DirectML` | Device and operator ownership, tensor binding, and DirectML execution | | `DXSharp`, `DXSharp.Framework`, `DXSharp.Dxc` | Compatibility packages for the original RCW-based SDK | diff --git a/build/VerifyPackages.ps1 b/build/VerifyPackages.ps1 index b4c201f..28fd3ee 100644 --- a/build/VerifyPackages.ps1 +++ b/build/VerifyPackages.ps1 @@ -17,7 +17,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.Framework.Desktop', 'DXSharp.Framework.Wpf', 'DXSharp.Native', 'DXSharp.Assets', 'DXSharp.Core', 'DXSharp.DirectML')) { + foreach ($name in @('DXSharp', 'DXSharp.Dxc', 'DXSharp.Framework', 'DXSharp.Framework.Desktop', 'DXSharp.Framework.Wpf', 'DXSharp.Framework.WinUI', 'DXSharp.Native', 'DXSharp.Assets', 'DXSharp.Core', 'DXSharp.DirectML')) { $path = Join-Path $packageDirectory "$name.$version.nupkg" if (-not (Test-Path $path)) { throw "Missing package: $path" } $archive = [System.IO.Compression.ZipFile]::OpenRead($path) @@ -25,6 +25,9 @@ try { $reader = [System.IO.StreamReader]::new($archive.GetEntry("$name.nuspec").Open()) try { [xml] $metadata = $reader.ReadToEnd() } finally { $reader.Dispose() } $frameworkReferences = @($metadata.SelectNodes("//*[local-name()='frameworkReference']") | ForEach-Object { $_.GetAttribute('name') }) + $winuiDependencies = @($metadata.SelectNodes("//*[local-name()='dependency']") | Where-Object { $_.GetAttribute('id') -like 'Microsoft.WindowsAppSDK*' }) + if ($name -ne 'DXSharp.Framework.WinUI' -and $winuiDependencies.Count -gt 0) { throw "Optional WinUI dependency leaked into $name." } + if ($name -eq 'DXSharp.Framework.WinUI' -and $winuiDependencies.Count -eq 0) { throw 'The WinUI adapter lost its pinned Windows App SDK dependency.' } if ($name -eq 'DXSharp.Framework.Wpf' -and ('Microsoft.WindowsDesktop.App.WPF' -notin $frameworkReferences -or 'Microsoft.WindowsDesktop.App.WindowsForms' -in $frameworkReferences)) { throw 'The WPF package must declare WPF without acquiring Windows Forms.' @@ -35,7 +38,7 @@ try { } $assemblies = @($archive.Entries | Where-Object FullName -CLike "lib/*/$name.dll") if ($assemblies.Count -eq 0) { throw "No library assembly found in $path" } - if ($name -in @('DXSharp.Native', 'DXSharp.Core', 'DXSharp.DirectML', 'DXSharp.Framework.Desktop', 'DXSharp.Framework.Wpf', 'DXSharp.Assets', 'DXSharp.Framework')) { + if ($name -in @('DXSharp.Native', 'DXSharp.Core', 'DXSharp.DirectML', 'DXSharp.Framework.Desktop', 'DXSharp.Framework.Wpf', 'DXSharp.Framework.WinUI', 'DXSharp.Assets', 'DXSharp.Framework')) { foreach ($major in '10', '11') { # NuGet normalizes the trailing zero of the Windows platform version. $framework = if ($name -eq 'DXSharp.Assets') { "net$major.0" } else { "net$major.0-windows10.0.26100" } diff --git a/build/VerifySamples.ps1 b/build/VerifySamples.ps1 index 92dab50..5f8dc62 100644 --- a/build/VerifySamples.ps1 +++ b/build/VerifySamples.ps1 @@ -22,6 +22,8 @@ try { Invoke-Sample 'CharacterLab-native' @('run', '--project', 'samples/CharacterLab.Native', '-c', 'Debug', '--', '--warp', '--frames=9', '--resize-test') Invoke-Sample 'CharacterLab-wpf' @('run', '--project', 'samples/CharacterLab.Wpf', '-c', 'Debug', '--', '--warp', '--frames=9') Invoke-Sample 'CharacterLab-wpf-host' @('run', '--project', 'samples/CharacterLab.Wpf', '-c', 'Debug', '--', '--warp', '--host-test') + Invoke-Sample 'CharacterLab-winui' @('run', '--project', 'samples/CharacterLab.WinUI', '-c', 'Debug', '--', '--warp', '--frames=9') + Invoke-Sample 'CharacterLab-winui-host' @('run', '--project', 'samples/CharacterLab.WinUI', '-c', 'Debug', '--', '--warp', '--host-test') Invoke-Sample 'DepthStencil' @('run', '--project', 'samples/DepthStencil', '-c', 'Debug', '--', '--warp') Invoke-Sample 'ModernTriangle' @('run', '--project', 'samples/ModernTriangle', '-c', 'Debug', '--', diff --git a/build/release_packages.py b/build/release_packages.py index 72b3fb2..993e07f 100644 --- a/build/release_packages.py +++ b/build/release_packages.py @@ -9,7 +9,7 @@ import xml.etree.ElementTree as ET from zipfile import ZipFile -PACKAGE_IDS = ("DXSharp.Native", "DXSharp.Assets", "DXSharp.Core", "DXSharp.DirectML", "DXSharp.Framework", "DXSharp.Framework.Desktop", "DXSharp.Framework.Wpf", "DXSharp.Tools.Builds") +PACKAGE_IDS = ("DXSharp.Native", "DXSharp.Assets", "DXSharp.Core", "DXSharp.DirectML", "DXSharp.Framework", "DXSharp.Framework.Desktop", "DXSharp.Framework.Wpf", "DXSharp.Framework.WinUI", "DXSharp.Tools.Builds") PREVIEW = re.compile(r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)-(?:net10-)?preview\.[1-9][0-9]*") diff --git a/build/verify_sample_packages.py b/build/verify_sample_packages.py index 93630b8..7e80029 100644 --- a/build/verify_sample_packages.py +++ b/build/verify_sample_packages.py @@ -9,14 +9,16 @@ import tempfile import xml.etree.ElementTree as ET -SDK_PACKAGES = ("DXSharp.Native", "DXSharp.Core", "DXSharp.DirectML", "DXSharp.Framework.Desktop", "DXSharp.Framework.Wpf", "DXSharp.Assets", "DXSharp.Framework") +SDK_PACKAGES = ("DXSharp.Native", "DXSharp.Core", "DXSharp.DirectML", "DXSharp.Framework.Desktop", "DXSharp.Framework.Wpf", "DXSharp.Framework.WinUI", "DXSharp.Assets", "DXSharp.Framework") EXCLUDED = {"bin", "obj", "artifacts", ".vs"} -def run(arguments, directory, log): +def run(arguments, directory, log, executable=False): + # Isolated package caches must not remain loaded in reusable MSBuild nodes. + environment = {**os.environ, "MSBUILDDISABLENODEREUSE": "1", "DOTNET_CLI_USE_MSBUILD_SERVER": "0"} with log.open("w", encoding="utf-8") as output: - process = subprocess.Popen(["dotnet", *arguments], cwd=directory, stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace") + process = subprocess.Popen(arguments if executable else ["dotnet", *arguments], cwd=directory, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace", env=environment) for line in process.stdout: print(line, end="", flush=True) output.write(line) @@ -99,8 +101,8 @@ def qualify(configuration, runtime_major): for key, pattern in (("local", "DXSharp.*"), ("nuget.org", "*")): ET.SubElement(ET.SubElement(mapping, "packageSource", key=key), "package", pattern=pattern) ET.ElementTree(config).write(consumer / "NuGet.Config", encoding="utf-8", xml_declaration=True) - run(["restore", "Samples.slnx", "--packages", str(consumer / "packages"), "-m:1", "-p:Platform=Any CPU"], consumer, evidence / "restore.log") - run(["build", "Samples.slnx", "-c", configuration, "--no-restore", "-m:1", "-p:Platform=Any CPU"], consumer, evidence / "build.log") + run(["restore", "Samples.slnx", "--packages", str(consumer / "packages"), "-m:1", "-nr:false", "-p:Platform=Any CPU"], consumer, evidence / "restore.log") + run(["build", "Samples.slnx", "-c", configuration, "--no-restore", "-m:1", "-nr:false", "-p:UseSharedCompilation=false", "-p:Platform=Any CPU"], consumer, evidence / "build.log") if os.name == "nt": # The developer shell's Platform variable must not change the built output path. fleet = consumer / "samples/FleetBattler/bin" / configuration / framework / "FleetBattler.dll" @@ -123,6 +125,15 @@ def qualify(configuration, runtime_major): raise RuntimeError(f'WPF precompiled consumer deployed {name}') run([str(wpf), "--warp", "--frames=9"], consumer, evidence / "character-wpf-runtime.log") run([str(wpf), "--warp", "--host-test"], consumer, evidence / "character-wpf-host.log") + winui_project = consumer / 'samples/CharacterLab.WinUI/CharacterLab.WinUI.csproj' + winui = Path(subprocess.check_output(['dotnet', 'msbuild', str(winui_project), f'-p:Configuration={configuration}', '-p:Platform=Any CPU', '-getProperty:TargetPath', '-nologo'], cwd=consumer, text=True).strip()).with_suffix('.exe') + if not winui.is_file(): + raise RuntimeError(f'Missing WinUI apphost: {winui}') + for name in ('dxcompiler.dll', 'dxil.dll'): + if (winui.parent / name).exists(): + raise RuntimeError(f'WinUI precompiled consumer deployed {name}') + run([str(winui), '--warp', '--frames=9'], consumer, evidence / 'character-winui-runtime.log', executable=True) + run([str(winui), '--warp', '--host-test'], consumer, evidence / 'character-winui-host.log', executable=True) (evidence / "samples.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") print(f"PASS: all {len(manifest)} runnable samples consume packaged SDK {version} outside the checkout.") diff --git a/doc/Framework-Vision.md b/doc/Framework-Vision.md index 0e8da9c..d3e124a 100644 --- a/doc/Framework-Vision.md +++ b/doc/Framework-Vision.md @@ -38,4 +38,4 @@ Acceptance remains workload-based: CPU/GPU deformation agreement; clear allocati The shader/host slice adds precompiled Framework shader resources, typed runtime compiler options and a packaged incremental DXC task. FrameRenderer separates frame slots/presentation from UI scheduling; DesktopGame keeps its API and NativeGame supplies an independent Win32 host. CharacterLab.Native shares the existing scene and has no WinForms reference. See [the shader/host contract](Shader-Build-and-Hosting.md) for packaging, cross-compilation limits and qualification. -The optional `DXSharp.Framework.Wpf` adapter now hosts the shared CharacterLab scene with dispatcher scheduling, physical-pixel resize and explicit stop/drain ownership. See [WPF hosting](Wpf-Hosting.md). WinUI composition and the full Game/Application lifecycle remain continuation work; WPF/BAML NativeAOT is not inferred from the separate native interop gates. +The optional `DXSharp.Framework.Wpf` adapter now hosts the shared CharacterLab scene with dispatcher scheduling, physical-pixel resize and explicit stop/drain ownership. See [WPF hosting](Wpf-Hosting.md). The optional `DXSharp.Framework.WinUI` adapter adds a composition viewport with ordinary XAML overlays ([contract](WinUI-Hosting.md)). The full Game/Application lifecycle remains continuation work; WPF/BAML NativeAOT is not inferred from the separate native interop gates. diff --git a/doc/Publishing-Previews.md b/doc/Publishing-Previews.md index 40b3fce..f4aa81e 100644 --- a/doc/Publishing-Previews.md +++ b/doc/Publishing-Previews.md @@ -1,6 +1,6 @@ # Publishing DXSharp previews -Preview 3 shipped five modern package IDs. Preview 4 development adds Framework, the DXC build tool and the optional WPF host. The candidate set is defined in `build/release_packages.py`: `DXSharp.Native`, `DXSharp.Assets`, `DXSharp.Core`, `DXSharp.DirectML`, `DXSharp.Framework.Desktop`, `DXSharp.Framework`, `DXSharp.Framework.Wpf` and `DXSharp.Tools.Builds`. Library assets target .NET 10/11 for Windows x64 (Assets is portable; the build tool targets netstandard2.0). Legacy compatibility projects remain independently buildable CI artifacts. Published versions remain immutable. +Preview 3 shipped five modern package IDs. Preview 4 development adds Framework, the DXC build tool and the optional WPF and WinUI hosts. The candidate set is defined in `build/release_packages.py`: `DXSharp.Native`, `DXSharp.Assets`, `DXSharp.Core`, `DXSharp.DirectML`, `DXSharp.Framework.Desktop`, `DXSharp.Framework`, `DXSharp.Framework.Wpf`, `DXSharp.Framework.WinUI` and `DXSharp.Tools.Builds`. Library assets target .NET 10/11 for Windows x64 (Assets is portable; the build tool targets netstandard2.0). Legacy compatibility projects remain independently buildable CI artifacts. Published versions remain immutable. ## One-time configuration diff --git a/doc/SDK-Architecture.md b/doc/SDK-Architecture.md index b934004..5822457 100644 --- a/doc/SDK-Architecture.md +++ b/doc/SDK-Architecture.md @@ -28,6 +28,7 @@ flowchart TD | `DXSharp.Core` | Device and queue ownership, buffers and resource states, descriptors, pipelines, HWND swap chains, DXC, and a bounded DXR surface | | `DXSharp.DirectML` | Same-device tensor binding and synchronous compiled Add and GEMM execution with optional fused ReLU | | `DXSharp.Framework.Desktop` | A WinForms-owned STA loop, one or two fenced frame slots, resize, depth target, and presentation | +| `DXSharp.Framework.WinUI` | Optional WinUI 3 SwapChainPanel composition over the shared frame renderer | | `DXSharp.Framework.Wpf` | Optional WPF dispatcher scheduling and a child-HWND viewport over the shared frame renderer | | `DXSharp`, `DXSharp.Dxc`, `DXSharp.Framework` | Compatibility types, RCWs, older wrappers and framework. The compatibility tests still exercise this path. BasicSample uses the current desktop host. | @@ -89,7 +90,7 @@ Split frame-slot management and presentation from the WinForms message loop. Def | Avalonia | A Windows sample using `NativeControlHost` and a child HWND | | Headless | The same renderer into offscreen targets with readback and no UI dispatcher | -Qualify resize, DPI changes, host teardown, and device removal in each adapter. Embedded WinUI composition is a separate surface kind from the HWND swap chain available today. [WinUI SwapChainPanel](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.swapchainpanel) · [WPF HWND hosting](https://learn.microsoft.com/dotnet/desktop/wpf/advanced/hosting-win32-content-in-wpf) · [Avalonia native Windows controls](https://docs.avaloniaui.net/docs/platform-specific-guides/windows) +Qualify resize, DPI changes, host teardown, and device removal in each adapter. The optional WinUI adapter uses the shared composition surface; the WPF adapter uses the HWND surface. See the [WinUI contract](WinUI-Hosting.md) and [WPF contract](Wpf-Hosting.md). [WinUI SwapChainPanel](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.swapchainpanel) · [WPF HWND hosting](https://learn.microsoft.com/dotnet/desktop/wpf/advanced/hosting-win32-content-in-wpf) · [Avalonia native Windows controls](https://docs.avaloniaui.net/docs/platform-specific-guides/windows) ### NoesisGUI adapter diff --git a/doc/Sample-Showcase-Plan.md b/doc/Sample-Showcase-Plan.md index 16fed8b..850790e 100644 --- a/doc/Sample-Showcase-Plan.md +++ b/doc/Sample-Showcase-Plan.md @@ -17,11 +17,11 @@ Keep Core and Framework independent of WPF and Windows App SDK dependencies. Eac | Native Win32 | Existing DXSharp.Framework | NativeGame and HWND FrameRenderer; no Windows Forms dependency | | Windows Forms | Existing DXSharp.Framework.Desktop | Existing DesktopGame adapter | | WPF | DXSharp.Framework.Wpf | D3D12Viewport child HWND and shared CharacterLab.Wpf scene; dispatcher scheduling and fenced teardown; see [contract](Wpf-Hosting.md) | -| WinUI 3 | Proposed DXSharp.Framework.WinUI | Composition swap chain attached through Microsoft.UI.Xaml ISwapChainPanelNative; Windows App SDK dependency stays in this adapter | +| WinUI 3 | DXSharp.Framework.WinUI | D3D12Viewport composition and shared CharacterLab.WinUI scene; XAML overlays, inverse scale and drained teardown; see [contract](WinUI-Hosting.md) | WPF's child HWND has airspace restrictions: WPF elements cannot freely overlap or transform it as ordinary composed content. D3DImage is a different path requiring a Direct3D9 surface bridge and synchronization; it is not a direct D3D12 swap-chain target. Start with an honest HwndHost sample and assess a composed surface bridge separately if editor overlays require it. -WinUI needs a composition presentation surface in Framework before the adapter can reuse frame-slot retirement. For D3D12, CreateSwapChainForComposition receives the direct command queue. Use the WinUI 3 interop interface from microsoft.ui.xaml.media.dxinterop.h, not the similarly named UWP interface. Attach/detach on the UI thread and handle composition scale, pixel size, unloading and outstanding GPU work explicitly. +WinUI uses the composition presentation surface in Framework and reuses frame-slot retirement. For D3D12, CreateSwapChainForComposition receives the direct command queue. Use the WinUI 3 interop interface from microsoft.ui.xaml.media.dxinterop.h, not the similarly named UWP interface. Attach/detach on the UI thread and handle composition scale, pixel size, unloading and outstanding GPU work explicitly. Acceptance: share the CharacterLab scene/rendering code; exercise repeated resizing, DPI/scale changes, minimize/restore or unload/reload, input focus, close during GPU work and device-loss reporting. Confirm consumers only acquire their chosen UI framework. Pin and qualify the Windows App SDK version when implementing WinUI; the native and WPF hosts must not require its runtime. A WinUI sample can be unpackaged; an MSIX packaging project is a deployment choice, not a requirement imposed by DirectX hosting. diff --git a/doc/Support-Matrix.md b/doc/Support-Matrix.md index 6d50476..5fb8b75 100644 --- a/doc/Support-Matrix.md +++ b/doc/Support-Matrix.md @@ -14,7 +14,7 @@ This matrix distinguishes declarations, managed workflows and runtime qualificat | Native runtime dependencies | Agility 1.620.2, DXC 1.9.2609.5, optional DirectML 1.15.4 | | Native declarations | CsWin32 0.3.371, Win32Metadata 71.0.45-preview, Agility 1.620.2 WinMD | | Compatibility packages | Existing RCW surface remains separate; modern AOT promises do not apply to it | -| Desktop hosts | Native Win32 and WinForms HWND presentation; optional WPF child-HWND viewport ([contract](Wpf-Hosting.md)); WinUI composition remains planned | +| Desktop hosts | Native Win32 and WinForms HWND presentation; optional WPF child-HWND viewport ([contract](Wpf-Hosting.md)); optional WinUI 3 composition viewport ([contract](WinUI-Hosting.md)) | | Linux | Portable native COM fixture only; no D3D12 renderer support | Samples default to .NET 10. Select the newer runtime with `-p:DXSharpRuntimeMajor=11` or the qualification scripts' `-RuntimeMajor 11` option. Each runtime has its own JIT/NativeAOT CI jobs and evidence. Building the checkout requires the pinned SDK; consuming the net10 package assets does not require changing an application's target to net11. diff --git a/doc/WinUI-Hosting.md b/doc/WinUI-Hosting.md new file mode 100644 index 0000000..b494397 --- /dev/null +++ b/doc/WinUI-Hosting.md @@ -0,0 +1,37 @@ +# WinUI 3 composition hosting + +`DXSharp.Framework.WinUI` is an optional Preview 4 adapter. Its `D3D12Viewport` is a WinUI `UserControl` containing a `SwapChainPanel`; it uses Framework's existing frame slots, depth targets, fences and resize handling. Core and Framework do not reference Windows App SDK. WPF and native Win32 consumers do not acquire it transitively. + +The adapter pins the stable `Microsoft.WindowsAppSDK.WinUI` component to 2.7.0. It uses the WinUI 3 `ISwapChainPanelNative` IID from that package's `microsoft.ui.xaml.media.dxinterop.h`, distinct from the similarly named UWP interface. The composition factory receives the D3D12 direct command queue and uses flip-sequential/STRETCH presentation. Factory outputs are queried for the required swap-chain interface, with independent owning references for renderer and panel attachment. + +## Using the control + +Reference `DXSharp.Framework.WinUI` and enable `UseWinUI` in a Windows x64 application. Add the control to your XAML layout or construct it in code: + +```csharp +var viewport = new DXSharp.Framework.WinUI.D3D12Viewport( ); +sceneGrid.Children.Add( viewport ); +viewport.Start( device, new WindowRenderOptions { + EnableDepth = true, FramesInFlight = 2 +}, frame => scene.Draw( frame ), owner: window ); +``` + +The device and scene remain caller-owned. `Start` may precede loading. Calls, rendering callbacks, panel attachment and disposal belong to the creating UI thread, with the normal WinUI dispatcher synchronization context. Pass the owning window to pause presentation while minimized; use `IsSuspended` for other application visibility policies. Loading schedules frames through `CompositionTarget.Rendering`. Unloading drains and detaches presentation resources; reloading resumes the active session. + +Panel layout is in XAML units. Back buffers use `ceil(ActualWidth * CompositionScaleX)` and the corresponding height. `RenderFrame.Size` and `PixelSize` are physical pixels. The swap-chain matrix applies the inverse composition scale, including after resizing, so scaling is applied once. `Panel` exposes the underlying panel for layout/transform configuration; callers must not replace its swap chain. Ordinary XAML overlays can appear above it, unlike the WPF child-HWND adapter. Overlays that should pass pointer input through must set `IsHitTestVisible=false`. + +Clicking the viewport focuses and captures it. `HasInputFocus` and `AcceptsPointerInput` let shared input code avoid consuming text-editor actions; `WheelScrolled` reports wheel input. Tab navigation enters and leaves the viewport. Logical XAML focus alone does not authorize keyboard polling while the owning window is inactive. Applications own action mapping and text/IME behavior; this host does not replace GameInput. + +Await `StopAsync` before disposing the viewport, scene resources or device. It detaches scheduling, drains outstanding queue work, calls `SetSwapChain(null)` and releases both native interface leases. Cancel the first window close, await stopping, dispose the viewport, then close the window. `CharacterWindow.CloseOrderly` implements this sequence. Use `FramePresented` for post-recording shutdown; do not stop or dispose inside the draw callback. `RenderFailed` reports stopped/drained rendering and `Failure` retains the exception. A new session can start after the stop completes. Device recreation remains the caller's responsibility. + +## Sample and qualification + +Run `dotnet run --project samples/CharacterLab.WinUI -c Release`. The sample uses an unpackaged x64 apphost and bundles the Windows App SDK runtime with `WindowsAppSDKSelfContained=true`; it still requires the selected .NET runtime. An MSIX packaging project is unnecessary. Launch the generated executable when deploying; invoking its DLL with `dotnet` bypasses the apphost's embedded activation manifest. + +The code-created application explicitly provides WinUI XAML type metadata and initializes control resources before creating its window. Normal markup-based WinUI applications receive that metadata from the XAML compiler. Explicit dispatcher shutdown keeps the UI thread alive until post-close checks and GPU resource disposal finish; an incomplete qualification cannot return a successful exit code. + +The same CharacterScene and OrbitCamera sources serve WinForms, native Win32, WPF and WinUI. WinUI playback controls, a text editor and an overlaid XAML badge demonstrate composition without a second renderer. Shaders remain precompiled, and runtime DXC binaries are excluded. + +`--warp --frames=9` bounds presentation. `--warp --host-test` exercises physical resize, nonuniform XAML scale, focus, tab navigation and window activation isolation, suspension, minimize/restore, unload/reload, intentional render failure, restart and close from a presentation callback. Source and isolated package consumers join Windows CI on .NET 10 and 11. The qualification target is Windows x64 JIT; the separate native COM NativeAOT fixture does not establish WinUI NativeAOT support. Hardware pacing and monitor-to-monitor DPI transitions need interactive hardware review. + +References: [composition swap-chain creation](https://learn.microsoft.com/en-us/windows/win32/api/dxgi1_2/nf-dxgi1_2-idxgifactory2-createswapchainforcomposition), [WinUI native panel attachment](https://learn.microsoft.com/en-us/windows/windows-app-sdk/api/win32/microsoft.ui.xaml.media.dxinterop/nf-microsoft-ui-xaml-media-dxinterop-iswapchainpanelnative-setswapchain), [SwapChainPanel](https://learn.microsoft.com/en-us/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.swapchainpanel), and [self-contained Windows App SDK deployment](https://learn.microsoft.com/en-us/windows/apps/package-and-deploy/self-contained-deploy/deploy-self-contained-apps). diff --git a/doc/Wpf-Hosting.md b/doc/Wpf-Hosting.md index 2e3f3bb..bf601d8 100644 --- a/doc/Wpf-Hosting.md +++ b/doc/Wpf-Hosting.md @@ -33,6 +33,6 @@ Run `dotnet run --project samples/CharacterLab.Wpf`; use `--warp --frames=9` for The Windows gate runs resize and current-DPI pixel-size checks, focus transfer and tab entry/exit, minimize/restore, visibility suspension, unload/reload, intentional render failure, restart, close from a presentation callback and native-handle teardown. Both runtime versions also build and execute the same sample from isolated fresh packages in Debug/Release. Physical monitor-to-monitor DPI transitions and hardware frame pacing require separate interactive hardware review; these checks do not simulate a second monitor. The standalone sample rejects a loaded Windows Forms assembly and deployed runtime DXC binaries. -WPF HWND airspace restrictions apply: arbitrary WPF overlays, opacity and transforms over the native viewport are not supported. Adjacent WPF panels and separate popup windows are suitable. A `D3DImage` composed-surface bridge would be a separate Direct3D9 interop design, not this D3D12 swap-chain host. WinUI composition remains an independent next adapter. +WPF HWND airspace restrictions apply: arbitrary WPF overlays, opacity and transforms over the native viewport are not supported. Adjacent WPF panels and separate popup windows are suitable. A `D3DImage` composed-surface bridge would be a separate Direct3D9 interop design, not this D3D12 swap-chain host. The separate [WinUI composition adapter](WinUI-Hosting.md) supports ordinary XAML overlays without this HWND airspace limitation. References: [WPF/Win32 interoperation](https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/wpf-and-win32-interoperation), [hosting Win32 content](https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/hosting-win32-content-in-wpf), and [composition rendering](https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.compositiontarget.rendering). diff --git a/samples/CharacterLab.WinUI/CharacterLab.WinUI.csproj b/samples/CharacterLab.WinUI/CharacterLab.WinUI.csproj new file mode 100644 index 0000000..478665e --- /dev/null +++ b/samples/CharacterLab.WinUI/CharacterLab.WinUI.csproj @@ -0,0 +1,15 @@ + + + Exe$(DotNetTargets) + truefalse + Nonetrue + x64x64win-x64false + app.manifestfalse + + + + + + + + diff --git a/samples/CharacterLab.WinUI/CharacterWindow.cs b/samples/CharacterLab.WinUI/CharacterWindow.cs new file mode 100644 index 0000000..506ec1e --- /dev/null +++ b/samples/CharacterLab.WinUI/CharacterWindow.cs @@ -0,0 +1,86 @@ +using DXSharp.Framework.Hosting; +using DXSharp.Framework.WinUI; +using DXSharp.Graphics; +using Microsoft.UI; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media; +using Windows.Graphics; + +namespace DXSharp.CharacterLab.WinUI; + +internal sealed class CharacterWindow : Window { + private readonly TaskCompletionSource _completion = new( TaskCreationOptions.RunContinuationsAsynchronously ); + private readonly CharacterScene _scene; + private readonly GraphicsDevice _device; + private readonly int _limit; + private bool _closing, _closed, _ready; + internal D3D12Viewport Viewport { get; } = new( ); + internal Grid SceneArea { get; } = new( ); + internal TextBox Editor { get; } = new( ) { Text = "Edit character notes here", Margin = new( 0, 12, 0, 0 ) }; + internal Task Completion => _completion.Task; + internal Exception? Failure { get; private set; } + internal RenderStatistics Statistics => Viewport.Statistics; + + internal CharacterWindow( GraphicsDevice device, CharacterScene scene, int limit, bool testing = false ) { + _device = device; _scene = scene; _limit = limit; + Title = "DXSharp · Character Lab — WinUI 3 Composition"; + var root = new Grid { Padding = new( 18 ), Background = Brush( 0x0B, 0x11, 0x1D ), RequestedTheme = ElementTheme.Dark }; + root.RowDefinitions.Add( new( ) { Height = GridLength.Auto } ); root.RowDefinitions.Add( new( ) ); root.RowDefinitions.Add( new( ) { Height = GridLength.Auto } ); + var header = new StackPanel { Margin = new( 0, 0, 0, 16 ) }; + header.Children.Add( new TextBlock { Text = "ARKAEN / DXSHARP", Foreground = Brush( 0x64, 0xD8, 0xCD ), FontSize = 12 } ); + header.Children.Add( new TextBlock { Text = "CHARACTER LAB · WINUI 3", FontSize = 28 } ); root.Children.Add( header ); + var body = new Grid { ColumnSpacing = 16 }; + body.ColumnDefinitions.Add( new( ) { Width = new( 240 ) } ); body.ColumnDefinitions.Add( new( ) ); Grid.SetRow( body, 1 ); root.Children.Add( body ); + var controls = new StackPanel { Spacing = 12 }; + controls.Children.Add( new TextBlock { Text = "PLAYBACK", Foreground = Brush( 0x64, 0xD8, 0xCD ) } ); + controls.Children.Add( new TextBlock { Text = $"{scene.Model.SourceVertices.Length:N0} vertices\n{scene.Model.Skin.Joints.Length} joints · {scene.Model.Animations.Length} clips" } ); + var clips = new ComboBox { ItemsSource = scene.Model.Animations.Select( a => a.Name ).ToArray( ), SelectedIndex = scene.Model.FindAnimation( "Idle" ), HorizontalAlignment = HorizontalAlignment.Stretch }; + clips.SelectionChanged += ( _, _ ) => { if ( _ready && clips.SelectedIndex >= 0 ) scene.Player.Play( clips.SelectedIndex ); }; controls.Children.Add( clips ); + var pause = new CheckBox { Content = "Pause animation" }; + pause.Checked += ( _, _ ) => scene.Player.Paused = true; pause.Unchecked += ( _, _ ) => scene.Player.Paused = false; controls.Children.Add( pause ); + controls.Children.Add( new TextBlock { Text = "Playback speed" } ); + var speed = new Slider { Minimum = .1, Maximum = 2.5, Value = 1 }; + speed.ValueChanged += ( _, args ) => scene.Player.Speed = (float)args.NewValue; controls.Children.Add( speed ); + var reset = new Button { Content = "Reset camera", HorizontalAlignment = HorizontalAlignment.Stretch }; + reset.Click += ( _, _ ) => scene.Camera.Reset( ); controls.Children.Add( reset ); + controls.Children.Add( new TextBlock { Text = "Drag the scene to orbit; wheel or +/− to zoom. 1–9 changes clip; Space pauses. Editing below retains keyboard input.", TextWrapping = TextWrapping.Wrap } ); + controls.Children.Add( Editor ); body.Children.Add( controls ); + Grid.SetColumn( SceneArea, 1 ); body.Children.Add( SceneArea ); SceneArea.Children.Add( Viewport ); + var overlay = new Border { Background = Brush( 0x10, 0x27, 0x36 ), Padding = new( 12 ), Margin = new( 16 ), + HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top, IsHitTestVisible = false, + Child = new TextBlock { Text = "LIVE COMPOSITION\nXAML overlay over a D3D12 swap chain", Foreground = Brush( 0x64, 0xD8, 0xCD ) } }; + SceneArea.Children.Add( overlay ); + var status = new TextBlock { Margin = new( 0, 12, 0, 0 ), Text = "Direct3D 12 · WinUI SwapChainPanel · precompiled shaders" }; Grid.SetRow( status, 2 ); root.Children.Add( status ); + Content = root; AppWindow.Resize( new SizeInt32( 1280, 820 ) ); + scene.Camera.InputEnabled = ( ) => Viewport.HasInputFocus; + scene.Camera.PointerEnabled = ( ) => Viewport.AcceptsPointerInput; + Viewport.WheelScrolled += delta => scene.Camera.Zoom( -delta / 120f * .3f ); + Viewport.RenderFailed += error => { Failure = error; if ( !testing ) CloseOrderly( ); }; + Viewport.FramePresented += statistics => { + if ( scene.UpdateTitle( statistics.Frames ) is { } title ) Title = title; + if ( statistics.Frames == 1 || statistics.Frames % 30 == 0 ) { + var p = Viewport.PixelSize; var s = Viewport.CompositionScale; + status.Text = $"{scene.Player.CurrentClipName} · {p.Width} × {p.Height} px · scale {s.X:F2}/{s.Y:F2} · CPU record {scene.MeanRecordingMilliseconds:F2} ms"; + } + if ( _limit > 0 && statistics.Frames >= _limit ) CloseOrderly( ); + }; + AppWindow.Closing += ( _, args ) => { if ( !_closed ) { args.Cancel = true; CloseOrderly( ); } }; + Closed += ( _, _ ) => _completion.TrySetResult( ); + VisibilityChanged += ( _, args ) => Viewport.IsSuspended = !args.Visible; + _ready = true; + Restart( ); + } + internal void Restart( Action? draw = null ) { + Failure = null; Viewport.Start( _device, new( ) { EnableDepth = true, FramesInFlight = 2 }, draw ?? _scene.Draw, this ); + } + internal async Task StopAsync( ) { await Viewport.StopAsync( ); Viewport.Dispose( ); } + internal async void CloseOrderly( ) { + if ( _closing ) return; + _closing = true; + try { await Viewport.StopAsync( ); Viewport.Dispose( ); } + catch ( Exception error ) { Failure ??= error; } + finally { _closed = true; Close( ); _completion.TrySetResult( ); } + } + private static SolidColorBrush Brush( byte r, byte g, byte b ) => new( Windows.UI.Color.FromArgb( 255, r, g, b ) ); +} diff --git a/samples/CharacterLab.WinUI/Program.cs b/samples/CharacterLab.WinUI/Program.cs new file mode 100644 index 0000000..74e06bb --- /dev/null +++ b/samples/CharacterLab.WinUI/Program.cs @@ -0,0 +1,75 @@ +using Microsoft.UI.Dispatching; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Markup; +using Microsoft.UI.Xaml.XamlTypeInfo; +using DXSharp.Graphics; + +namespace DXSharp.CharacterLab.WinUI; + +internal static class Program { + internal static int ExitCode = 1; + internal static bool HadUnhandledException; + [STAThread] + private static int Main( string[] args ) { + try { + Console.WriteLine( "Host: WinUI 3 composition; unpackaged apphost." ); + WinRT.ComWrappersSupport.InitializeComWrappers( ); + Application.Start( parameters => { + SynchronizationContext.SetSynchronizationContext( new DispatcherQueueSynchronizationContext( DispatcherQueue.GetForCurrentThread( ) ) ); + _ = new CharacterApplication( args ); + } ); + return ExitCode; + } catch ( Exception error ) { Console.Error.WriteLine( error ); return 1; } + } +} + +internal sealed class CharacterApplication : Application, IXamlMetadataProvider { + private XamlControlsXamlMetaDataProvider? _metadata; + private XamlControlsXamlMetaDataProvider Metadata => _metadata ??= new( ); + IXamlType IXamlMetadataProvider.GetXamlType( Type type ) => Metadata.GetXamlType( type ); + IXamlType IXamlMetadataProvider.GetXamlType( string name ) => Metadata.GetXamlType( name ); + XmlnsDefinition[] IXamlMetadataProvider.GetXmlnsDefinitions( ) => Metadata.GetXmlnsDefinitions( ); + private readonly string[] _arguments; + private CharacterWindow? _window; + internal CharacterApplication( string[] arguments ) { + _arguments = arguments; + this.DispatcherShutdownMode = Microsoft.UI.Xaml.DispatcherShutdownMode.OnExplicitShutdown; + UnhandledException += ( _, args ) => { Console.Error.WriteLine( args.Exception ); Program.ExitCode = 1; Program.HadUnhandledException = true; args.Handled = true; _window?.CloseOrderly( ); }; + } + protected override async void OnLaunched( LaunchActivatedEventArgs args ) { + GraphicsDevice? device = null; + CharacterScene? scene = null; + try { + XamlControlsXamlMetaDataProvider.Initialize( ); + Resources.MergedDictionaries.Add( new Microsoft.UI.Xaml.Controls.XamlControlsResources( ) ); + int limit = int.Parse( _arguments.FirstOrDefault( a => a.StartsWith( "--frames=" ) )?[9..] ?? "0" ); + string model = _arguments.FirstOrDefault( a => a.StartsWith( "--model=" ) )?[8..] ?? System.IO.Path.Combine( AppContext.BaseDirectory, "Assets", "animatedKnightInPlateArmour.glb" ); +#if DEBUG + bool debug = !_arguments.Contains( "--no-debug" ); +#else + bool debug = false; +#endif + device = GraphicsDevice.Create( new( ) { UseWarp = _arguments.Contains( "--warp" ), UseAgility = !_arguments.Contains( "--system-runtime" ), EnableDebugLayer = debug } ); + scene = new( device, model, limit > 0 || _arguments.Contains( "--host-test" ) ); + _window = new( device, scene, limit, _arguments.Contains( "--host-test" ) ); _window.Activate( ); + if ( _arguments.Contains( "--host-test" ) ) await WinUIHostQualification.Run( _window, device, scene ); + await _window.Completion; + if ( _window.Failure is { } failure ) throw new InvalidOperationException( "WinUI rendering stopped.", failure ); + if ( limit > 0 && _window.Statistics.Frames != limit ) throw new InvalidOperationException( "WinUI frame limit was not reached." ); + var diagnostics = device.GetDiagnostics( ); + foreach ( var message in diagnostics.Messages ) Console.WriteLine( message ); + if ( diagnostics.DeviceRemovedReason < 0 || diagnostics.Messages.Any( m => m.Contains( "SEVERITY_ERROR" ) || m.Contains( "SEVERITY_CORRUPTION" ) ) || Program.HadUnhandledException ) throw new InvalidOperationException( "WinUI qualification reported a device or unhandled UI failure." ); + if ( AppDomain.CurrentDomain.GetAssemblies( ).Any( a => a.GetName( ).Name is "System.Windows.Forms" or "PresentationFramework" ) ) + throw new InvalidOperationException( "WinUI sample loaded another desktop UI framework." ); + Console.WriteLine( $"PASS: WinUI CharacterLab presented {scene.Frames} GPU-skinned frames through composition; mean CPU recording {scene.MeanRecordingMilliseconds:F2} ms." ); + Program.ExitCode = 0; + } catch ( Exception error ) { Console.Error.WriteLine( error ); Program.ExitCode = 1; } + finally { + try { + try { if ( _window is not null ) await _window.StopAsync( ); } + finally { try { scene?.Dispose( ); } finally { device?.Dispose( ); } } + } catch ( Exception error ) { Console.Error.WriteLine( error ); Program.ExitCode = 1; } + finally { Exit( ); } + } + } +} diff --git a/samples/CharacterLab.WinUI/WinUIHostQualification.cs b/samples/CharacterLab.WinUI/WinUIHostQualification.cs new file mode 100644 index 0000000..3aa4450 --- /dev/null +++ b/samples/CharacterLab.WinUI/WinUIHostQualification.cs @@ -0,0 +1,89 @@ +using DXSharp.Graphics; +using DXSharp.Framework.Hosting; +using DXSharp.Framework.WinUI; +using Microsoft.UI.Windowing; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Input; +using Microsoft.UI.Xaml.Media; +using Windows.Graphics; + +namespace DXSharp.CharacterLab.WinUI; + +internal static class WinUIHostQualification { + internal static async Task Run( CharacterWindow window, GraphicsDevice device, CharacterScene scene ) { + var viewport = window.Viewport; + await Frames( viewport, 3 ); + await viewport.StopAsync( ); + System.Drawing.Size rendered = default; + window.Restart( frame => { rendered = frame.Size; scene.Draw( frame ); } ); + await Frames( viewport, 3 ); + var original = viewport.PixelSize; + window.AppWindow.Resize( new SizeInt32( 1000, 700 ) ); + await Frames( viewport, viewport.Statistics.Frames + 3 ); + Require( viewport.PixelSize != original && viewport.Statistics.Resizes > 0 && rendered == viewport.PixelSize, "WinUI resize did not reach the physical back buffers." ); + Require( viewport.Focus( FocusState.Programmatic ) && viewport.HasInputFocus, "Cannot focus the WinUI viewport." ); + window.Editor.Focus( FocusState.Programmatic ); + Require( !viewport.HasInputFocus && Equals( FocusManager.GetFocusedElement( viewport.XamlRoot ), window.Editor ), "Viewport stole text editor focus." ); + var navigation = new FindNextElementOptions { SearchRoot = window.Content }; + Require( FocusManager.TryMoveFocus( FocusNavigationDirection.Next, navigation ) && viewport.HasInputFocus, "Tab entry did not reach the viewport." ); + Require( FocusManager.TryMoveFocus( FocusNavigationDirection.Previous, navigation ) && !viewport.HasInputFocus, "Tab exit did not leave the viewport." ); + + viewport.Focus( FocusState.Programmatic ); + var other = new Window { Content = new Microsoft.UI.Xaml.Controls.TextBox { Text = "Other active window" } }; + try { + other.Activate( ); await Task.Delay( 120 ); + Require( !viewport.HasInputFocus, "Inactive viewport continued accepting keyboard input." ); + } finally { other.Close( ); window.Activate( ); } + viewport.Focus( FocusState.Programmatic ); + await Frames( viewport, viewport.Statistics.Frames + 2 ); + + var scale = viewport.CompositionScale; + viewport.Panel.RenderTransform = new ScaleTransform { ScaleX = 1.25, ScaleY = 1.5 }; + await Frames( viewport, viewport.Statistics.Frames + 4 ); + Require( viewport.CompositionScale != scale && rendered == viewport.PixelSize, "Composition scale did not resize the back buffers." ); + viewport.Panel.RenderTransform = null; + await Frames( viewport, viewport.Statistics.Frames + 3 ); + + viewport.IsSuspended = true; + int paused = viewport.Statistics.Frames; await Task.Delay( 120 ); + Require( viewport.Statistics.Frames == paused, "Suspended WinUI host kept presenting." ); + viewport.IsSuspended = false; await Frames( viewport, paused + 2 ); + var presenter = (OverlappedPresenter)window.AppWindow.Presenter; + presenter.Minimize( ); await Task.Delay( 80 ); + paused = viewport.Statistics.Frames; await Task.Delay( 120 ); + Require( viewport.Statistics.Frames == paused, "Minimized WinUI host kept presenting." ); + presenter.Restore( ); window.Activate( ); await Frames( viewport, paused + 2 ); + + window.SceneArea.Children.Remove( viewport ); await Task.Delay( 100 ); + paused = viewport.Statistics.Frames; await Task.Delay( 120 ); + Require( viewport.Statistics.Frames == paused, "Unloaded WinUI host kept presenting." ); + window.SceneArea.Children.Insert( 0, viewport ); await Frames( viewport, paused + 3 ); + Console.WriteLine( "PASS: WinUI composition presentation, physical resize, XAML scale, text focus, tab entry/exit, activation isolation, suspension, minimize/restore and unload/reload." ); + + await viewport.StopAsync( ); + var failed = new TaskCompletionSource( TaskCreationOptions.RunContinuationsAsynchronously ); + void OnFailed( Exception error ) => failed.TrySetResult( error ); + viewport.RenderFailed += OnFailed; + window.Restart( _ => throw new ApplicationException( "intentional WinUI render failure" ) ); + var error = await failed.Task.WaitAsync( TimeSpan.FromSeconds( 40 ) ); + viewport.RenderFailed -= OnFailed; + Require( error is ApplicationException && viewport.Failure == error, "WinUI render failure was lost." ); + await viewport.StopAsync( ); window.Restart( ); await Frames( viewport, 3 ); + Require( viewport.Failure is null && window.Failure is null, "Restart did not clear the intentional failure." ); + viewport.FramePresented += statistics => { if ( statistics.Frames >= 4 ) window.CloseOrderly( ); }; + await window.Completion.WaitAsync( TimeSpan.FromSeconds( 40 ) ); + paused = viewport.Statistics.Frames; await Task.Delay( 100 ); + Require( viewport.Statistics.Frames == paused, "Closed WinUI host retained a rendering callback." ); + Console.WriteLine( "PASS: WinUI render failure, drained restart, close during presentation, panel detach and inert callbacks." ); + } + private static async Task Frames( D3D12Viewport viewport, int frames ) { + if ( viewport.Statistics.Frames >= frames ) return; + var completion = new TaskCompletionSource( TaskCreationOptions.RunContinuationsAsynchronously ); + void Presented( RenderStatistics statistics ) { if ( statistics.Frames >= frames ) completion.TrySetResult( ); } + void Failed( Exception error ) => completion.TrySetException( error ); + viewport.FramePresented += Presented; viewport.RenderFailed += Failed; + try { await completion.Task.WaitAsync( TimeSpan.FromSeconds( 40 ) ); } + finally { viewport.FramePresented -= Presented; viewport.RenderFailed -= Failed; } + } + private static void Require( bool condition, string message ) { if ( !condition ) throw new InvalidOperationException( message ); } +} diff --git a/samples/CharacterLab.WinUI/app.manifest b/samples/CharacterLab.WinUI/app.manifest new file mode 100644 index 0000000..4ab17df --- /dev/null +++ b/samples/CharacterLab.WinUI/app.manifest @@ -0,0 +1,11 @@ + + + + + PerMonitorV2 + true + + + + + diff --git a/samples/CharacterLab.WinUI/packages.lock.json b/samples/CharacterLab.WinUI/packages.lock.json new file mode 100644 index 0000000..da24f4a --- /dev/null +++ b/samples/CharacterLab.WinUI/packages.lock.json @@ -0,0 +1,132 @@ +{ + "version": 2, + "dependencies": { + "net10.0-windows10.0.26100": { + "Microsoft.Web.WebView2": { + "type": "Transitive", + "resolved": "1.0.3719.77", + "contentHash": "t+ucyKw5NTwMjsUrDF6R9Lk40lpcKQD1/HgyGFxl49tdA4h9dKlsj6FYGEmDRpFNfnTpENuTypMcdbrlkqBdDA==" + }, + "Microsoft.Windows.SDK.BuildTools": { + "type": "Transitive", + "resolved": "10.0.26100.4654", + "contentHash": "2mgcOlj/t2RfSyyw+pVESfO+Tk1RkfQzto9Vrq42M1lUQIfQEwbi8QLha9GXWIOj+TFzeHIEJckIoF25mgiM8A==" + }, + "Microsoft.Windows.SDK.BuildTools.MSIX": { + "type": "Transitive", + "resolved": "1.7.251221100", + "contentHash": "f4aIZJ0NUth2403oxrpR+9rxVzZVI6dabqB21u8ncnk8eJAKCs9m77E4iYAnvP1YwrRe4axz3f8+yUcttNSfEA==" + }, + "Microsoft.WindowsAppSDK.Base": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "pz1xzq2mady89xuPbpsLrgVuB0v+bLZp8T4MJQu8d3HSimrrPPghEJmE6rqxvhAlk62iVjPhMZ9rVnhomCPmHQ==", + "dependencies": { + "Microsoft.Windows.SDK.BuildTools": "10.0.26100.4654", + "Microsoft.Windows.SDK.BuildTools.MSIX": "1.7.251221100" + } + }, + "Microsoft.WindowsAppSDK.Foundation": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "20RAdyrhDL5i5T1kHaIWzDf8oDQ8SiKSCuAVje0Y4zFKLO/OSlxoTl2omjl43CEvEbRm7A+T6CxxfjUtj6rTjA==", + "dependencies": { + "Microsoft.WindowsAppSDK.Base": "[2.7.0, 3.0.0)", + "Microsoft.WindowsAppSDK.InteractiveExperiences": "[2.7.0, 3.0.0)" + } + }, + "Microsoft.WindowsAppSDK.InteractiveExperiences": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "J3RehOxm689NHJlmjAhCFmGZF6REyxU/gxFkKBJEeGxTLZ4uhTW3AG5oRH4QcA/zM5UUp8Al0wiqFYaBnqvvLw==", + "dependencies": { + "Microsoft.WindowsAppSDK.Base": "2.7.0" + } + }, + "dxsharp.assets": { + "type": "Project", + "dependencies": { + "SharpGLTF.Core": "[1.0.7, 1.0.7]", + "StbImageSharp": "[2.30.16, 2.30.16]" + } + }, + "dxsharp.core": { + "type": "Project", + "dependencies": { + "DXSharp.Native": "[0.4.0-preview.4, )", + "Microsoft.Direct3D.D3D12": "[1.620.2, 1.620.2]", + "Microsoft.Direct3D.DXC": "[1.9.2609.5, 1.9.2609.5]" + } + }, + "dxsharp.framework": { + "type": "Project", + "dependencies": { + "DXSharp.Assets": "[0.4.0-preview.4, )", + "DXSharp.Core": "[0.4.0-preview.4, )" + } + }, + "dxsharp.framework.winui": { + "type": "Project", + "dependencies": { + "DXSharp.Framework": "[0.4.0-preview.4, )", + "Microsoft.WindowsAppSDK.WinUI": "[2.7.0, 2.7.0]" + } + }, + "dxsharp.native": { + "type": "Project" + }, + "Microsoft.Direct3D.D3D12": { + "type": "CentralTransitive", + "requested": "[1.620.2, )", + "resolved": "1.620.2", + "contentHash": "qSho5Lzlw6UjIHa/nEVwWK/gE2Mt7q7N2bixymflJ5QcvCWRqpatUuhkXWyW7AHex8K6yZyaEHyqx9xmXL5KLA==" + }, + "Microsoft.Direct3D.DXC": { + "type": "CentralTransitive", + "requested": "[1.9.2609.5, )", + "resolved": "1.9.2609.5", + "contentHash": "jTWr7a2bMpqV+b0Uc7oxOo8ualplaUw3fsQ+p0kp9TwlWvvmREvt3SA4+Drl2Y0M31iscqZolrL3vpdnLoPpdg==" + }, + "Microsoft.WindowsAppSDK.WinUI": { + "type": "CentralTransitive", + "requested": "[2.7.0, 2.7.0]", + "resolved": "2.7.0", + "contentHash": "6Pit9KmeSKLpLlUUR8TSWIRdos4V8ilsz7eaOf8o9H2555lTBtQgQyQR4LjXf1EDcAe4EYocQ+YDipe0pbQrpA==", + "dependencies": { + "Microsoft.Web.WebView2": "1.0.3719.77", + "Microsoft.WindowsAppSDK.Base": "2.7.0", + "Microsoft.WindowsAppSDK.Foundation": "2.7.0", + "Microsoft.WindowsAppSDK.InteractiveExperiences": "2.7.0" + } + }, + "SharpGLTF.Core": { + "type": "CentralTransitive", + "requested": "[1.0.7, 1.0.7]", + "resolved": "1.0.7", + "contentHash": "dZHCUl2jH1ViiLbAwyYbVfZnFqsF1e/9OhZAfLBoggOpqnsbgKQghldK3LnobmtNRp6GNZMyaNkPceqERkqmsQ==" + }, + "StbImageSharp": { + "type": "CentralTransitive", + "requested": "[2.30.16, 2.30.16]", + "resolved": "2.30.16", + "contentHash": "qg1i+NHihXVKLKYacGKrauhSQIGL31eBWcTC4Vc7jnGmBFj87LkRuCdXB5aDZisWMRnB6x2mcfwYXQxMWEG/lw==" + } + }, + "net10.0-windows10.0.26100/win-x64": { + "Microsoft.Web.WebView2": { + "type": "Transitive", + "resolved": "1.0.3719.77", + "contentHash": "t+ucyKw5NTwMjsUrDF6R9Lk40lpcKQD1/HgyGFxl49tdA4h9dKlsj6FYGEmDRpFNfnTpENuTypMcdbrlkqBdDA==" + }, + "Microsoft.WindowsAppSDK.Foundation": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "20RAdyrhDL5i5T1kHaIWzDf8oDQ8SiKSCuAVje0Y4zFKLO/OSlxoTl2omjl43CEvEbRm7A+T6CxxfjUtj6rTjA==", + "dependencies": { + "Microsoft.WindowsAppSDK.Base": "[2.7.0, 3.0.0)", + "Microsoft.WindowsAppSDK.InteractiveExperiences": "[2.7.0, 3.0.0)" + } + } + } + } +} \ No newline at end of file diff --git a/samples/CharacterLab.WinUI/packages.net11.lock.json b/samples/CharacterLab.WinUI/packages.net11.lock.json new file mode 100644 index 0000000..9868094 --- /dev/null +++ b/samples/CharacterLab.WinUI/packages.net11.lock.json @@ -0,0 +1,132 @@ +{ + "version": 2, + "dependencies": { + "net11.0-windows10.0.26100": { + "Microsoft.Web.WebView2": { + "type": "Transitive", + "resolved": "1.0.3719.77", + "contentHash": "t+ucyKw5NTwMjsUrDF6R9Lk40lpcKQD1/HgyGFxl49tdA4h9dKlsj6FYGEmDRpFNfnTpENuTypMcdbrlkqBdDA==" + }, + "Microsoft.Windows.SDK.BuildTools": { + "type": "Transitive", + "resolved": "10.0.26100.4654", + "contentHash": "2mgcOlj/t2RfSyyw+pVESfO+Tk1RkfQzto9Vrq42M1lUQIfQEwbi8QLha9GXWIOj+TFzeHIEJckIoF25mgiM8A==" + }, + "Microsoft.Windows.SDK.BuildTools.MSIX": { + "type": "Transitive", + "resolved": "1.7.251221100", + "contentHash": "f4aIZJ0NUth2403oxrpR+9rxVzZVI6dabqB21u8ncnk8eJAKCs9m77E4iYAnvP1YwrRe4axz3f8+yUcttNSfEA==" + }, + "Microsoft.WindowsAppSDK.Base": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "pz1xzq2mady89xuPbpsLrgVuB0v+bLZp8T4MJQu8d3HSimrrPPghEJmE6rqxvhAlk62iVjPhMZ9rVnhomCPmHQ==", + "dependencies": { + "Microsoft.Windows.SDK.BuildTools": "10.0.26100.4654", + "Microsoft.Windows.SDK.BuildTools.MSIX": "1.7.251221100" + } + }, + "Microsoft.WindowsAppSDK.Foundation": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "20RAdyrhDL5i5T1kHaIWzDf8oDQ8SiKSCuAVje0Y4zFKLO/OSlxoTl2omjl43CEvEbRm7A+T6CxxfjUtj6rTjA==", + "dependencies": { + "Microsoft.WindowsAppSDK.Base": "[2.7.0, 3.0.0)", + "Microsoft.WindowsAppSDK.InteractiveExperiences": "[2.7.0, 3.0.0)" + } + }, + "Microsoft.WindowsAppSDK.InteractiveExperiences": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "J3RehOxm689NHJlmjAhCFmGZF6REyxU/gxFkKBJEeGxTLZ4uhTW3AG5oRH4QcA/zM5UUp8Al0wiqFYaBnqvvLw==", + "dependencies": { + "Microsoft.WindowsAppSDK.Base": "2.7.0" + } + }, + "dxsharp.assets": { + "type": "Project", + "dependencies": { + "SharpGLTF.Core": "[1.0.7, 1.0.7]", + "StbImageSharp": "[2.30.16, 2.30.16]" + } + }, + "dxsharp.core": { + "type": "Project", + "dependencies": { + "DXSharp.Native": "[0.4.0-preview.4, )", + "Microsoft.Direct3D.D3D12": "[1.620.2, 1.620.2]", + "Microsoft.Direct3D.DXC": "[1.9.2609.5, 1.9.2609.5]" + } + }, + "dxsharp.framework": { + "type": "Project", + "dependencies": { + "DXSharp.Assets": "[0.4.0-preview.4, )", + "DXSharp.Core": "[0.4.0-preview.4, )" + } + }, + "dxsharp.framework.winui": { + "type": "Project", + "dependencies": { + "DXSharp.Framework": "[0.4.0-preview.4, )", + "Microsoft.WindowsAppSDK.WinUI": "[2.7.0, 2.7.0]" + } + }, + "dxsharp.native": { + "type": "Project" + }, + "Microsoft.Direct3D.D3D12": { + "type": "CentralTransitive", + "requested": "[1.620.2, )", + "resolved": "1.620.2", + "contentHash": "qSho5Lzlw6UjIHa/nEVwWK/gE2Mt7q7N2bixymflJ5QcvCWRqpatUuhkXWyW7AHex8K6yZyaEHyqx9xmXL5KLA==" + }, + "Microsoft.Direct3D.DXC": { + "type": "CentralTransitive", + "requested": "[1.9.2609.5, )", + "resolved": "1.9.2609.5", + "contentHash": "jTWr7a2bMpqV+b0Uc7oxOo8ualplaUw3fsQ+p0kp9TwlWvvmREvt3SA4+Drl2Y0M31iscqZolrL3vpdnLoPpdg==" + }, + "Microsoft.WindowsAppSDK.WinUI": { + "type": "CentralTransitive", + "requested": "[2.7.0, 2.7.0]", + "resolved": "2.7.0", + "contentHash": "6Pit9KmeSKLpLlUUR8TSWIRdos4V8ilsz7eaOf8o9H2555lTBtQgQyQR4LjXf1EDcAe4EYocQ+YDipe0pbQrpA==", + "dependencies": { + "Microsoft.Web.WebView2": "1.0.3719.77", + "Microsoft.WindowsAppSDK.Base": "2.7.0", + "Microsoft.WindowsAppSDK.Foundation": "2.7.0", + "Microsoft.WindowsAppSDK.InteractiveExperiences": "2.7.0" + } + }, + "SharpGLTF.Core": { + "type": "CentralTransitive", + "requested": "[1.0.7, 1.0.7]", + "resolved": "1.0.7", + "contentHash": "dZHCUl2jH1ViiLbAwyYbVfZnFqsF1e/9OhZAfLBoggOpqnsbgKQghldK3LnobmtNRp6GNZMyaNkPceqERkqmsQ==" + }, + "StbImageSharp": { + "type": "CentralTransitive", + "requested": "[2.30.16, 2.30.16]", + "resolved": "2.30.16", + "contentHash": "qg1i+NHihXVKLKYacGKrauhSQIGL31eBWcTC4Vc7jnGmBFj87LkRuCdXB5aDZisWMRnB6x2mcfwYXQxMWEG/lw==" + } + }, + "net11.0-windows10.0.26100/win-x64": { + "Microsoft.Web.WebView2": { + "type": "Transitive", + "resolved": "1.0.3719.77", + "contentHash": "t+ucyKw5NTwMjsUrDF6R9Lk40lpcKQD1/HgyGFxl49tdA4h9dKlsj6FYGEmDRpFNfnTpENuTypMcdbrlkqBdDA==" + }, + "Microsoft.WindowsAppSDK.Foundation": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "20RAdyrhDL5i5T1kHaIWzDf8oDQ8SiKSCuAVje0Y4zFKLO/OSlxoTl2omjl43CEvEbRm7A+T6CxxfjUtj6rTjA==", + "dependencies": { + "Microsoft.WindowsAppSDK.Base": "[2.7.0, 3.0.0)", + "Microsoft.WindowsAppSDK.InteractiveExperiences": "[2.7.0, 3.0.0)" + } + } + } + } +} \ No newline at end of file diff --git a/samples/CharacterLab/OrbitCamera.cs b/samples/CharacterLab/OrbitCamera.cs index 2e83070..fdf2b0f 100644 --- a/samples/CharacterLab/OrbitCamera.cs +++ b/samples/CharacterLab/OrbitCamera.cs @@ -15,6 +15,7 @@ sealed class OrbitCamera internal Func? InputEnabled { get; set; } internal Func? PointerEnabled { get; set; } internal void Reset() { _yaw = 0.35f; _pitch = 0.12f; _distance = 4; _wasDragging = false; _lastKeyState.Clear(); } + internal void Zoom(float amount) => _distance = Math.Clamp(_distance + amount, 2, 9); public Vector3 Eye { diff --git a/samples/Directory.Build.props b/samples/Directory.Build.props index e7aff40..4fec25d 100644 --- a/samples/Directory.Build.props +++ b/samples/Directory.Build.props @@ -8,6 +8,7 @@ DXSharp - $(MSBuildProjectName) DXSharp Samples Copyright (c) Arkaen Solutions and DXSharp contributors + GPU-skinned CharacterLab hosted in a WinUI 3 composition panel. Advanced DXSharp graphics techniques. A minimal Direct3D 12 renderer built with DXSharp. Depth/stencil rendering, native interop and readback validation. diff --git a/samples/README.md b/samples/README.md index 9e0d8cc..8234c15 100644 --- a/samples/README.md +++ b/samples/README.md @@ -25,4 +25,6 @@ CharacterLab adds persistent GPU skinning, animation playback and material maps; `CharacterLab.Wpf` shares that scene through the optional WPF viewport, with WPF playback controls and a focus-isolated text editor. `--warp --host-test` exercises resize, current-DPI sizing, minimize/restore, unload/reload, render failure, restart and close/teardown. It joins the same source and isolated package gates. See [WPF hosting](../doc/Wpf-Hosting.md). -See the [visual showcase and optional UI host plan](../doc/Sample-Showcase-Plan.md) for WPF/WinUI adapters and the upcoming media, spatial audio, DirectStorage and interactive DXR samples. These planned samples are not yet implemented. +`CharacterLab.WinUI` shares the scene through the optional WinUI 3 composition viewport, with playback controls, independent text input and a genuine XAML overlay. The unpackaged app bundles its Windows App SDK runtime. `--warp --host-test` checks scale, resize, focus, suspension, unload/reload, restart and teardown. See [WinUI hosting](../doc/WinUI-Hosting.md). + +See the [visual showcase and optional UI host plan](../doc/Sample-Showcase-Plan.md) for WPF/WinUI adapters and the upcoming media, spatial audio, DirectStorage and interactive DXR samples. The media, storage and interactive DXR showcases remain planned. diff --git a/src/DXSharp.Core/Graphics/SwapChain.cs b/src/DXSharp.Core/Graphics/SwapChain.cs index baf3c2f..be79b30 100644 --- a/src/DXSharp.Core/Graphics/SwapChain.cs +++ b/src/DXSharp.Core/Graphics/SwapChain.cs @@ -7,14 +7,19 @@ namespace DXSharp.Graphics; -/// An owning flip-model HWND swap chain. +/// An owning flip-model HWND or composition swap chain. public sealed unsafe class SwapChain : GraphicsObject { private readonly ComOwner _native; + private float _scaleX = 1, _scaleY = 1; /// The number of back buffers. public uint BufferCount { get; } /// The presentation format. public PixelFormat Format { get; } - internal SwapChain( ComOwner owner, uint count, PixelFormat format ) : base( owner ) { _native = owner; BufferCount = count; Format = format; } + /// Whether this chain targets a composition surface rather than an HWND. + public bool IsComposition { get; } + internal SwapChain( ComOwner owner, uint count, PixelFormat format, bool composition = false ) : base( owner ) { + _native = owner; BufferCount = count; Format = format; IsComposition = composition; + } internal override ComReference Retain( ) => _native.Retain( ); /// The current back-buffer index. public uint CurrentBackBufferIndex => _native.Interface.GetCurrentBackBufferIndex( ); @@ -35,6 +40,17 @@ public int Present( uint syncInterval = 1 ) { public void Resize( uint width, uint height ) { if ( width == 0 || height == 0 ) throw new ArgumentOutOfRangeException( nameof(width) ); Results.Check( _native.Interface.ResizeBuffers( BufferCount, width, height, (DXGI_FORMAT)Format, 0 ), "SwapChain.ResizeBuffers" ); + if ( IsComposition ) SetCompositionScale( _scaleX, _scaleY ); + } + /// Sets the inverse composition scale after sizing buffers in physical pixels. This requires a composition chain. + public void SetCompositionScale( float scaleX, float scaleY ) { + ObjectDisposedException.ThrowIf( IsDisposed, this ); + if ( !IsComposition ) throw new InvalidOperationException( "Composition scaling requires a composition swap chain." ); + if ( !float.IsFinite( scaleX ) || !float.IsFinite( scaleY ) || scaleX <= 0 || scaleY <= 0 || + !float.IsFinite( 1 / scaleX ) || !float.IsFinite( 1 / scaleY ) ) throw new ArgumentOutOfRangeException( nameof(scaleX) ); + DXGI_MATRIX_3X2_F matrix = new( ) { _11 = 1 / scaleX, _22 = 1 / scaleY }; + Results.Check( _native.Interface.SetMatrixTransform( &matrix ), "SwapChain.SetMatrixTransform" ); + _scaleX = scaleX; _scaleY = scaleY; } } @@ -59,10 +75,36 @@ public SwapChain CreateSwapChain( CommandQueue queue, nint window, uint width, u using var raw = rawFactory ?? throw new NotSupportedException( "DXGI 1.2 is required." ); using var queueLease = queue.Native.Borrow( ); Results.Check( raw.Interface.CreateSwapChainForHwnd( queueLease.Pointer, new HWND( window ), description, null, 0, out nint swapPointer ), "CreateSwapChainForHwnd" ); - var swap = ComOwner.Adopt( swapPointer ); + using var created = ComOwner.Adopt( swapPointer ); + created.TryQuery( typeof(IDXGISwapChain4).GUID, out var queried ); + var swap = queried ?? throw new NotSupportedException( "DXGI swap-chain interface 4 is required." ); try { Results.Check( factory.Interface.MakeWindowAssociation( new HWND( window ), DXGI_MWA_FLAGS.DXGI_MWA_NO_ALT_ENTER ), "MakeWindowAssociation" ); return new( swap, bufferCount, format ) { DeviceIdentity = DeviceIdentity }; } catch { swap.Dispose( ); throw; } } + + /// Creates an opaque composition swap chain on a direct queue. Attach it to a composition host before presenting. + public SwapChain CreateCompositionSwapChain( CommandQueue queue, uint width, uint height, + PixelFormat format = PixelFormat.Rgba8Unorm, uint bufferCount = 2 ) { + RequireSameDevice( queue ); + if ( queue.Kind != QueueKind.Direct ) throw new ArgumentException( "Presentation requires a direct queue.", nameof(queue) ); + if ( width == 0 || height == 0 || bufferCount < 2 || bufferCount > 16 ) throw new ArgumentOutOfRangeException( nameof(width) ); + Guid id = typeof(IDXGIFactory7).GUID; + Results.Check( PInvoke.CreateDXGIFactory2( 0, &id, out nint pointer ), "CreateDXGIFactory2" ); + using var factory = ComOwner.Adopt( pointer ); + factory.TryQuery( typeof(IFactory2Raw).GUID, out var queriedFactory ); + using var raw = queriedFactory ?? throw new NotSupportedException( "DXGI 1.2 is required." ); + DXGI_SWAP_CHAIN_DESC1 description = new( ) { + Width = width, Height = height, Format = (DXGI_FORMAT)format, + SampleDesc = new( ) { Count = 1 }, BufferUsage = DXGI_USAGE.DXGI_USAGE_RENDER_TARGET_OUTPUT, + BufferCount = bufferCount, SwapEffect = DXGI_SWAP_EFFECT.DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL, + Scaling = DXGI_SCALING.DXGI_SCALING_STRETCH, AlphaMode = DXGI_ALPHA_MODE.DXGI_ALPHA_MODE_IGNORE + }; + using var queueLease = queue.Native.Borrow( ); + Results.Check( raw.Interface.CreateSwapChainForComposition( queueLease.Pointer, description, 0, out nint swapPointer ), "CreateSwapChainForComposition" ); + using var created = ComOwner.Adopt( swapPointer ); + created.TryQuery( typeof(IDXGISwapChain4).GUID, out var queriedSwap ); + return new( queriedSwap ?? throw new NotSupportedException( "DXGI swap-chain interface 4 is required." ), bufferCount, format, composition: true ) { DeviceIdentity = DeviceIdentity }; + } } diff --git a/src/DXSharp.Framework.WinUI/D3D12Viewport.cs b/src/DXSharp.Framework.WinUI/D3D12Viewport.cs new file mode 100644 index 0000000..051f06d --- /dev/null +++ b/src/DXSharp.Framework.WinUI/D3D12Viewport.cs @@ -0,0 +1,196 @@ +using System.Diagnostics; +using System.Drawing; +using System.Numerics; +using System.Runtime.InteropServices; +using DXSharp.Framework.Hosting; +using DXSharp.Graphics; +using DXSharp.Interop; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Input; +using Microsoft.UI.Xaml.Media; +using Windows.Win32; +using Windows.Win32.Foundation; +using Windows.Win32.Graphics.Dxgi; + +namespace DXSharp.Framework.WinUI; + +/// A UI-thread-owned WinUI 3 composition viewport using the shared fenced frame renderer. +/// The caller owns the device and scene and stops/disposes the viewport before releasing either. +/// Windows App SDK dependencies are confined to this optional assembly and its consumers. +public sealed class D3D12Viewport : UserControl, IDisposable { + private readonly int _thread = Environment.CurrentManagedThreadId; + private readonly SwapChainPanel _panel = new( ); + private readonly Stopwatch _clock = new( ); + private GraphicsDevice? _device; + private WindowRenderOptions? _options; + private Action? _draw; + private FrameRenderer? _renderer; + private NativeInterface? _panelNative; + private NativeInterface? _chainNative; + private Task? _stop; + private RenderStatistics _retired; + private TimeSpan _previous; + private Vector2 _appliedScale; + private nint _ownerWindow; + private bool _started, _subscribed, _drawing, _disposed, _inside, _captured, _suspended; + + /// Creates a viewport usable as ordinary composed WinUI content. + public D3D12Viewport( ) { + Content = _panel; IsTabStop = true; + Loaded += OnLoaded; Unloaded += OnUnloaded; + PointerEntered += ( _, _ ) => _inside = true; + PointerExited += ( _, _ ) => _inside = false; + PointerPressed += OnPointerPressed; + PointerReleased += ( _, _ ) => ReleasePointer( ); + PointerCaptureLost += ( _, _ ) => _captured = false; + LostFocus += ( _, _ ) => ReleasePointer( ); + PointerWheelChanged += ( _, args ) => { + if ( HasInputFocus ) { WheelScrolled?.Invoke( args.GetCurrentPoint( _panel ).Properties.MouseWheelDelta ); args.Handled = true; } + }; + } + /// The native composition panel, exposed for layout/transform configuration. Do not replace its swap chain. + public SwapChainPanel Panel => _panel; + /// Current composition scale, including XAML and monitor scale. + public Vector2 CompositionScale => new( _panel.CompositionScaleX, _panel.CompositionScaleY ); + /// The requested physical back-buffer size, rounded up from panel layout and composition scale. + public Size PixelSize { + get { + CheckThread( ); var scale = CompositionScale; + if ( !double.IsFinite( _panel.ActualWidth ) || !double.IsFinite( _panel.ActualHeight ) || + !float.IsFinite( scale.X ) || !float.IsFinite( scale.Y ) || scale.X <= 0 || scale.Y <= 0 ) return Size.Empty; + return new( checked((int)Math.Ceiling( _panel.ActualWidth * scale.X )), checked((int)Math.Ceiling( _panel.ActualHeight * scale.Y )) ); + } + } + /// Whether the viewport, rather than a WinUI editor/control, owns keyboard focus. + public bool HasInputFocus { + get { + CheckThread( ); var active = PInvoke.GetActiveWindow( ); + return FocusState != Microsoft.UI.Xaml.FocusState.Unfocused && !active.IsNull && + (_ownerWindow == 0 || active == new HWND( _ownerWindow )); + } + } + /// Whether pointer polling belongs to the viewport or its captured drag. + public bool AcceptsPointerInput => HasInputFocus && (_inside || _captured); + /// Host-driven suspension, for example when an owning view is inactive. + public bool IsSuspended { get => _suspended; set { CheckThread( ); _suspended = value; _previous = _clock.Elapsed; } } + /// Totals accumulated through unload/reload in the current session. + public RenderStatistics Statistics { + get { CheckThread( ); var s = _renderer?.Statistics ?? default; return new( _retired.Frames + s.Frames, _retired.Resizes + s.Resizes ); } + } + /// The last failure, cleared by Start. + public Exception? Failure { get; private set; } + /// Raised on the UI thread after presentation. Stopping/closing here is allowed. + public event Action? FramePresented; + /// Raised on the UI thread when rendering fails. Failure retains the exception. + public event Action? RenderFailed; + /// Mouse wheel input from the focused viewport, in Win32 wheel-delta units. + public event Action? WheelScrolled; + + /// Starts rendering on load. Supply an owning window to suspend presentation while it is minimized. + public void Start( GraphicsDevice device, WindowRenderOptions options, Action draw, Window? owner = null ) { + CheckThread( ); ObjectDisposedException.ThrowIf( _disposed, this ); + ArgumentNullException.ThrowIfNull( device ); ArgumentNullException.ThrowIfNull( options ); ArgumentNullException.ThrowIfNull( draw ); + if ( _drawing || _started || _stop is { IsCompleted: false } ) throw new InvalidOperationException( "Stop and await the current session before starting another." ); + if ( options.FramesInFlight is < 1 or > 3 || options.FrameLimit < 0 ) throw new ArgumentOutOfRangeException( nameof(options) ); + _device = device; _options = options; _draw = draw; _retired = default; Failure = null; _stop = null; + _ownerWindow = owner is null ? 0 : WinRT.Interop.WindowNative.GetWindowHandle( owner ); + _started = true; _previous = TimeSpan.Zero; _clock.Restart( ); + if ( IsLoaded ) Attach( ); + } + /// Stops scheduling, drains outstanding GPU work, detaches the panel and releases presentation resources. + public Task StopAsync( ) { + CheckThread( ); + if ( _disposed ) return Task.CompletedTask; + if ( _drawing ) throw new InvalidOperationException( "Stop after recording, for example in FramePresented." ); + _started = false; Detach( ); ReleasePointer( ); + return _stop ??= RetireAsync( ); + } + private void CheckThread( ) { if ( Environment.CurrentManagedThreadId != _thread ) throw new InvalidOperationException( "The WinUI viewport belongs to another thread." ); } + private void OnLoaded( object sender, RoutedEventArgs args ) { if ( _started ) Attach( ); } + private async void OnUnloaded( object sender, RoutedEventArgs args ) { + Detach( ); ReleasePointer( ); + try { await (_stop ??= RetireAsync( )); } + catch ( Exception error ) { Report( error ); } + finally { _stop = null; if ( _started && IsLoaded && !_disposed ) Attach( ); } + } + private void Attach( ) { + if ( _subscribed || _disposed ) return; + _previous = _clock.Elapsed; CompositionTarget.Rendering += OnRendering; _subscribed = true; + } + private void Detach( ) { + if ( !_subscribed ) return; + CompositionTarget.Rendering -= OnRendering; _subscribed = false; + } + private void OnPointerPressed( object sender, PointerRoutedEventArgs args ) { + if ( !args.GetCurrentPoint( _panel ).Properties.IsLeftButtonPressed ) return; + Focus( Microsoft.UI.Xaml.FocusState.Pointer ); _captured = CapturePointer( args.Pointer ); args.Handled = true; + } + private void ReleasePointer( ) { ReleasePointerCaptures( ); _captured = false; } + private void CreateRenderer( Size size ) { + var renderer = FrameRenderer.CreateForComposition( _device!, _options! with { ClientSize = size } ); + NativeInterface? panel = null; + NativeInterface? chain = null; + try { + nint inspectable = WinRT.MarshalInspectable.FromManaged( _panel ); + try { + Guid id = typeof(ISwapChainPanelNative).GUID; + Marshal.ThrowExceptionForHR( Marshal.QueryInterface( inspectable, in id, out nint pointer ) ); + panel = NativeInterface.Adopt( pointer ); + } finally { WinRT.MarshalInspectable.DisposeAbi( inspectable ); } + chain = renderer.QuerySwapChainInterface( ); + var scale = CompositionScale; renderer.SetCompositionScale( scale.X, scale.Y ); + Marshal.ThrowExceptionForHR( panel.Interface.SetSwapChain( chain.Pointer ) ); + _renderer = renderer; _panelNative = panel; _chainNative = chain; _appliedScale = scale; + } catch { + if ( panel is not null ) panel.Interface.SetSwapChain( 0 ); + chain?.Dispose( ); panel?.Dispose( ); renderer.Dispose( ); throw; + } + } + private void OnRendering( object? sender, object args ) { + if ( !_started || _disposed || _drawing || _stop is { IsCompleted: false } ) return; + var now = _clock.Elapsed; + if ( _suspended || !IsLoaded || Visibility != Visibility.Visible || + (_ownerWindow != 0 && PInvoke.IsIconic( new HWND( _ownerWindow ) )) ) { _previous = now; return; } + try { + var size = PixelSize; + if ( size.Width <= 0 || size.Height <= 0 ) { _previous = now; return; } + if ( _renderer is null ) CreateRenderer( size ); + var scale = CompositionScale; + if ( scale != _appliedScale ) { _renderer!.SetCompositionScale( scale.X, scale.Y ); _appliedScale = scale; } + bool presented; + _drawing = true; + try { presented = _renderer!.Render( size, now - _previous, _draw! ); } + finally { _drawing = false; } + _previous = now; + if ( presented ) { + var statistics = Statistics; FramePresented?.Invoke( statistics ); + if ( _options!.FrameLimit > 0 && statistics.Frames >= _options.FrameLimit ) _ = FinishAsync( ); + } + } catch ( Exception error ) { Failure = error; _ = FinishAsync( error ); } + } + private async Task FinishAsync( Exception? error = null ) { + try { await StopAsync( ); } + catch ( Exception stopError ) { error = error is null ? stopError : new AggregateException( error, stopError ); } + if ( error is not null ) Report( error ); + } + private void Report( Exception error ) { Failure = error; _started = false; Detach( ); RenderFailed?.Invoke( error ); } + private async Task RetireAsync( ) { + var renderer = _renderer; + if ( renderer is null ) return; + _retired = Statistics; _renderer = null; + try { await renderer.BeginDrain( ); } + finally { + try { if ( _panelNative is not null ) Marshal.ThrowExceptionForHR( _panelNative.Interface.SetSwapChain( 0 ) ); } + finally { _chainNative?.Dispose( ); _chainNative = null; _panelNative?.Dispose( ); _panelNative = null; renderer.Dispose( ); } + } + } + /// Disposes after a completed StopAsync. Async draining must finish while WinUI still dispatches messages. + public void Dispose( ) { + CheckThread( ); if ( _disposed ) return; + if ( _drawing || _renderer is not null || _stop is { IsCompleted: false } ) + throw new InvalidOperationException( "Await StopAsync before disposing the WinUI viewport." ); + _disposed = true; _started = false; Detach( ); ReleasePointer( ); + Loaded -= OnLoaded; Unloaded -= OnUnloaded; _draw = null; _device = null; _clock.Stop( ); + } +} diff --git a/src/DXSharp.Framework.WinUI/DXSharp.Framework.WinUI.csproj b/src/DXSharp.Framework.WinUI/DXSharp.Framework.WinUI.csproj new file mode 100644 index 0000000..24d471c --- /dev/null +++ b/src/DXSharp.Framework.WinUI/DXSharp.Framework.WinUI.csproj @@ -0,0 +1,14 @@ + + + $(DXSharpTargetFrameworks) + trueNone + x64x64win-x64 + false + Optional WinUI 3 composition hosting for the modern DXSharp graphics framework. + $(WarningsAsErrors);CS1591 + + + + + + diff --git a/src/DXSharp.Framework.WinUI/SwapChainPanelNative.cs b/src/DXSharp.Framework.WinUI/SwapChainPanelNative.cs new file mode 100644 index 0000000..0c9bfa4 --- /dev/null +++ b/src/DXSharp.Framework.WinUI/SwapChainPanelNative.cs @@ -0,0 +1,12 @@ +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.Marshalling; + +namespace DXSharp.Framework.WinUI; + +// Pinned Windows App SDK 2.7.0 include/microsoft.ui.xaml.media.dxinterop.h. +// This is WinUI's interface, distinct from the similarly named UWP interface. +[GeneratedComInterface( Options = ComInterfaceOptions.ComObjectWrapper )] +[Guid( "63aad0b8-7c24-40ff-85a8-640d944cc325" )] +internal partial interface ISwapChainPanelNative { + [PreserveSig] int SetSwapChain( nint swapChain ); +} diff --git a/src/DXSharp.Framework.WinUI/packages.lock.json b/src/DXSharp.Framework.WinUI/packages.lock.json new file mode 100644 index 0000000..3860c3a --- /dev/null +++ b/src/DXSharp.Framework.WinUI/packages.lock.json @@ -0,0 +1,245 @@ +{ + "version": 2, + "dependencies": { + "net10.0-windows10.0.26100": { + "Microsoft.WindowsAppSDK.WinUI": { + "type": "Direct", + "requested": "[2.7.0, 2.7.0]", + "resolved": "2.7.0", + "contentHash": "6Pit9KmeSKLpLlUUR8TSWIRdos4V8ilsz7eaOf8o9H2555lTBtQgQyQR4LjXf1EDcAe4EYocQ+YDipe0pbQrpA==", + "dependencies": { + "Microsoft.Web.WebView2": "1.0.3719.77", + "Microsoft.WindowsAppSDK.Base": "2.7.0", + "Microsoft.WindowsAppSDK.Foundation": "2.7.0", + "Microsoft.WindowsAppSDK.InteractiveExperiences": "2.7.0" + } + }, + "Microsoft.Web.WebView2": { + "type": "Transitive", + "resolved": "1.0.3719.77", + "contentHash": "t+ucyKw5NTwMjsUrDF6R9Lk40lpcKQD1/HgyGFxl49tdA4h9dKlsj6FYGEmDRpFNfnTpENuTypMcdbrlkqBdDA==" + }, + "Microsoft.Windows.SDK.BuildTools": { + "type": "Transitive", + "resolved": "10.0.26100.4654", + "contentHash": "2mgcOlj/t2RfSyyw+pVESfO+Tk1RkfQzto9Vrq42M1lUQIfQEwbi8QLha9GXWIOj+TFzeHIEJckIoF25mgiM8A==" + }, + "Microsoft.Windows.SDK.BuildTools.MSIX": { + "type": "Transitive", + "resolved": "1.7.251221100", + "contentHash": "f4aIZJ0NUth2403oxrpR+9rxVzZVI6dabqB21u8ncnk8eJAKCs9m77E4iYAnvP1YwrRe4axz3f8+yUcttNSfEA==" + }, + "Microsoft.WindowsAppSDK.Base": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "pz1xzq2mady89xuPbpsLrgVuB0v+bLZp8T4MJQu8d3HSimrrPPghEJmE6rqxvhAlk62iVjPhMZ9rVnhomCPmHQ==", + "dependencies": { + "Microsoft.Windows.SDK.BuildTools": "10.0.26100.4654", + "Microsoft.Windows.SDK.BuildTools.MSIX": "1.7.251221100" + } + }, + "Microsoft.WindowsAppSDK.Foundation": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "20RAdyrhDL5i5T1kHaIWzDf8oDQ8SiKSCuAVje0Y4zFKLO/OSlxoTl2omjl43CEvEbRm7A+T6CxxfjUtj6rTjA==", + "dependencies": { + "Microsoft.WindowsAppSDK.Base": "[2.7.0, 3.0.0)", + "Microsoft.WindowsAppSDK.InteractiveExperiences": "[2.7.0, 3.0.0)" + } + }, + "Microsoft.WindowsAppSDK.InteractiveExperiences": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "J3RehOxm689NHJlmjAhCFmGZF6REyxU/gxFkKBJEeGxTLZ4uhTW3AG5oRH4QcA/zM5UUp8Al0wiqFYaBnqvvLw==", + "dependencies": { + "Microsoft.WindowsAppSDK.Base": "2.7.0" + } + }, + "dxsharp.assets": { + "type": "Project", + "dependencies": { + "SharpGLTF.Core": "[1.0.7, 1.0.7]", + "StbImageSharp": "[2.30.16, 2.30.16]" + } + }, + "dxsharp.core": { + "type": "Project", + "dependencies": { + "DXSharp.Native": "[0.4.0-preview.4, )", + "Microsoft.Direct3D.D3D12": "[1.620.2, 1.620.2]", + "Microsoft.Direct3D.DXC": "[1.9.2609.5, 1.9.2609.5]" + } + }, + "dxsharp.framework": { + "type": "Project", + "dependencies": { + "DXSharp.Assets": "[0.4.0-preview.4, )", + "DXSharp.Core": "[0.4.0-preview.4, )" + } + }, + "dxsharp.native": { + "type": "Project" + }, + "Microsoft.Direct3D.D3D12": { + "type": "CentralTransitive", + "requested": "[1.620.2, )", + "resolved": "1.620.2", + "contentHash": "qSho5Lzlw6UjIHa/nEVwWK/gE2Mt7q7N2bixymflJ5QcvCWRqpatUuhkXWyW7AHex8K6yZyaEHyqx9xmXL5KLA==" + }, + "Microsoft.Direct3D.DXC": { + "type": "CentralTransitive", + "requested": "[1.9.2609.5, )", + "resolved": "1.9.2609.5", + "contentHash": "jTWr7a2bMpqV+b0Uc7oxOo8ualplaUw3fsQ+p0kp9TwlWvvmREvt3SA4+Drl2Y0M31iscqZolrL3vpdnLoPpdg==" + }, + "SharpGLTF.Core": { + "type": "CentralTransitive", + "requested": "[1.0.7, 1.0.7]", + "resolved": "1.0.7", + "contentHash": "dZHCUl2jH1ViiLbAwyYbVfZnFqsF1e/9OhZAfLBoggOpqnsbgKQghldK3LnobmtNRp6GNZMyaNkPceqERkqmsQ==" + }, + "StbImageSharp": { + "type": "CentralTransitive", + "requested": "[2.30.16, 2.30.16]", + "resolved": "2.30.16", + "contentHash": "qg1i+NHihXVKLKYacGKrauhSQIGL31eBWcTC4Vc7jnGmBFj87LkRuCdXB5aDZisWMRnB6x2mcfwYXQxMWEG/lw==" + } + }, + "net10.0-windows10.0.26100/win-x64": { + "Microsoft.Web.WebView2": { + "type": "Transitive", + "resolved": "1.0.3719.77", + "contentHash": "t+ucyKw5NTwMjsUrDF6R9Lk40lpcKQD1/HgyGFxl49tdA4h9dKlsj6FYGEmDRpFNfnTpENuTypMcdbrlkqBdDA==" + }, + "Microsoft.WindowsAppSDK.Foundation": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "20RAdyrhDL5i5T1kHaIWzDf8oDQ8SiKSCuAVje0Y4zFKLO/OSlxoTl2omjl43CEvEbRm7A+T6CxxfjUtj6rTjA==", + "dependencies": { + "Microsoft.WindowsAppSDK.Base": "[2.7.0, 3.0.0)", + "Microsoft.WindowsAppSDK.InteractiveExperiences": "[2.7.0, 3.0.0)" + } + } + }, + "net11.0-windows10.0.26100": { + "Microsoft.WindowsAppSDK.WinUI": { + "type": "Direct", + "requested": "[2.7.0, 2.7.0]", + "resolved": "2.7.0", + "contentHash": "6Pit9KmeSKLpLlUUR8TSWIRdos4V8ilsz7eaOf8o9H2555lTBtQgQyQR4LjXf1EDcAe4EYocQ+YDipe0pbQrpA==", + "dependencies": { + "Microsoft.Web.WebView2": "1.0.3719.77", + "Microsoft.WindowsAppSDK.Base": "2.7.0", + "Microsoft.WindowsAppSDK.Foundation": "2.7.0", + "Microsoft.WindowsAppSDK.InteractiveExperiences": "2.7.0" + } + }, + "Microsoft.Web.WebView2": { + "type": "Transitive", + "resolved": "1.0.3719.77", + "contentHash": "t+ucyKw5NTwMjsUrDF6R9Lk40lpcKQD1/HgyGFxl49tdA4h9dKlsj6FYGEmDRpFNfnTpENuTypMcdbrlkqBdDA==" + }, + "Microsoft.Windows.SDK.BuildTools": { + "type": "Transitive", + "resolved": "10.0.26100.4654", + "contentHash": "2mgcOlj/t2RfSyyw+pVESfO+Tk1RkfQzto9Vrq42M1lUQIfQEwbi8QLha9GXWIOj+TFzeHIEJckIoF25mgiM8A==" + }, + "Microsoft.Windows.SDK.BuildTools.MSIX": { + "type": "Transitive", + "resolved": "1.7.251221100", + "contentHash": "f4aIZJ0NUth2403oxrpR+9rxVzZVI6dabqB21u8ncnk8eJAKCs9m77E4iYAnvP1YwrRe4axz3f8+yUcttNSfEA==" + }, + "Microsoft.WindowsAppSDK.Base": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "pz1xzq2mady89xuPbpsLrgVuB0v+bLZp8T4MJQu8d3HSimrrPPghEJmE6rqxvhAlk62iVjPhMZ9rVnhomCPmHQ==", + "dependencies": { + "Microsoft.Windows.SDK.BuildTools": "10.0.26100.4654", + "Microsoft.Windows.SDK.BuildTools.MSIX": "1.7.251221100" + } + }, + "Microsoft.WindowsAppSDK.Foundation": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "20RAdyrhDL5i5T1kHaIWzDf8oDQ8SiKSCuAVje0Y4zFKLO/OSlxoTl2omjl43CEvEbRm7A+T6CxxfjUtj6rTjA==", + "dependencies": { + "Microsoft.WindowsAppSDK.Base": "[2.7.0, 3.0.0)", + "Microsoft.WindowsAppSDK.InteractiveExperiences": "[2.7.0, 3.0.0)" + } + }, + "Microsoft.WindowsAppSDK.InteractiveExperiences": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "J3RehOxm689NHJlmjAhCFmGZF6REyxU/gxFkKBJEeGxTLZ4uhTW3AG5oRH4QcA/zM5UUp8Al0wiqFYaBnqvvLw==", + "dependencies": { + "Microsoft.WindowsAppSDK.Base": "2.7.0" + } + }, + "dxsharp.assets": { + "type": "Project", + "dependencies": { + "SharpGLTF.Core": "[1.0.7, 1.0.7]", + "StbImageSharp": "[2.30.16, 2.30.16]" + } + }, + "dxsharp.core": { + "type": "Project", + "dependencies": { + "DXSharp.Native": "[0.4.0-preview.4, )", + "Microsoft.Direct3D.D3D12": "[1.620.2, 1.620.2]", + "Microsoft.Direct3D.DXC": "[1.9.2609.5, 1.9.2609.5]" + } + }, + "dxsharp.framework": { + "type": "Project", + "dependencies": { + "DXSharp.Assets": "[0.4.0-preview.4, )", + "DXSharp.Core": "[0.4.0-preview.4, )" + } + }, + "dxsharp.native": { + "type": "Project" + }, + "Microsoft.Direct3D.D3D12": { + "type": "CentralTransitive", + "requested": "[1.620.2, )", + "resolved": "1.620.2", + "contentHash": "qSho5Lzlw6UjIHa/nEVwWK/gE2Mt7q7N2bixymflJ5QcvCWRqpatUuhkXWyW7AHex8K6yZyaEHyqx9xmXL5KLA==" + }, + "Microsoft.Direct3D.DXC": { + "type": "CentralTransitive", + "requested": "[1.9.2609.5, )", + "resolved": "1.9.2609.5", + "contentHash": "jTWr7a2bMpqV+b0Uc7oxOo8ualplaUw3fsQ+p0kp9TwlWvvmREvt3SA4+Drl2Y0M31iscqZolrL3vpdnLoPpdg==" + }, + "SharpGLTF.Core": { + "type": "CentralTransitive", + "requested": "[1.0.7, 1.0.7]", + "resolved": "1.0.7", + "contentHash": "dZHCUl2jH1ViiLbAwyYbVfZnFqsF1e/9OhZAfLBoggOpqnsbgKQghldK3LnobmtNRp6GNZMyaNkPceqERkqmsQ==" + }, + "StbImageSharp": { + "type": "CentralTransitive", + "requested": "[2.30.16, 2.30.16]", + "resolved": "2.30.16", + "contentHash": "qg1i+NHihXVKLKYacGKrauhSQIGL31eBWcTC4Vc7jnGmBFj87LkRuCdXB5aDZisWMRnB6x2mcfwYXQxMWEG/lw==" + } + }, + "net11.0-windows10.0.26100/win-x64": { + "Microsoft.Web.WebView2": { + "type": "Transitive", + "resolved": "1.0.3719.77", + "contentHash": "t+ucyKw5NTwMjsUrDF6R9Lk40lpcKQD1/HgyGFxl49tdA4h9dKlsj6FYGEmDRpFNfnTpENuTypMcdbrlkqBdDA==" + }, + "Microsoft.WindowsAppSDK.Foundation": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "20RAdyrhDL5i5T1kHaIWzDf8oDQ8SiKSCuAVje0Y4zFKLO/OSlxoTl2omjl43CEvEbRm7A+T6CxxfjUtj6rTjA==", + "dependencies": { + "Microsoft.WindowsAppSDK.Base": "[2.7.0, 3.0.0)", + "Microsoft.WindowsAppSDK.InteractiveExperiences": "[2.7.0, 3.0.0)" + } + } + } + } +} \ No newline at end of file diff --git a/src/DXSharp.Framework/Hosting/FrameRenderer.cs b/src/DXSharp.Framework/Hosting/FrameRenderer.cs index f9a4eea..fe3fd3a 100644 --- a/src/DXSharp.Framework/Hosting/FrameRenderer.cs +++ b/src/DXSharp.Framework/Hosting/FrameRenderer.cs @@ -25,8 +25,8 @@ public sealed record WindowRenderOptions { /// Completed presentations and surface resizes. public readonly record struct RenderStatistics( int Frames, int Resizes ); -/// Window-system-independent frame slots and HWND presentation. Public methods run on the creating thread; drain work runs on a worker. -/// The host owns the HWND and must keep it alive until Drain completes. The device remains caller-owned. +/// Window-system-independent frame slots with HWND or composition presentation. Public methods run on the creating thread; drain work runs on a worker. +/// The host owns its presentation surface and keeps it alive until drain completes. The device remains caller-owned. public sealed class FrameRenderer : IDisposable { private readonly int _thread = Environment.CurrentManagedThreadId; private readonly GraphicsDevice _device; @@ -45,7 +45,16 @@ public sealed class FrameRenderer : IDisposable { public RenderStatistics Statistics { get; private set; } /// Creates presentation resources for an externally owned live HWND. - public FrameRenderer( GraphicsDevice device, nint window, WindowRenderOptions options ) { + public FrameRenderer( GraphicsDevice device, nint window, WindowRenderOptions options ) : this( device, window, options, false ) { } + /// Creates composition presentation resources. The caller attaches the queried native swap chain to its UI surface. + public static FrameRenderer CreateForComposition( GraphicsDevice device, WindowRenderOptions options ) => new( device, 0, options, true ); + /// Queries an independently owned native view of the presentation chain. Detach the host and dispose this view before renderer disposal. + public DXSharp.Interop.NativeInterface QuerySwapChainInterface( ) where T : class { + CheckThread( ); ObjectDisposedException.ThrowIf( _disposed, this ); return _swap.QueryNativeInterface( ); + } + /// Applies composition scale on the creating thread. HWND renderers reject this operation. + public void SetCompositionScale( float scaleX, float scaleY ) { CheckThread( ); ObjectDisposedException.ThrowIf( _disposed, this ); _swap.SetCompositionScale( scaleX, scaleY ); } + private FrameRenderer( GraphicsDevice device, nint window, WindowRenderOptions options, bool composition ) { ArgumentNullException.ThrowIfNull( device ); ArgumentNullException.ThrowIfNull( options ); if ( options.ClientSize.Width <= 0 || options.ClientSize.Height <= 0 || options.FramesInFlight is < 1 or > 3 || options.FrameLimit < 0 ) throw new ArgumentOutOfRangeException( nameof(options) ); @@ -53,7 +62,8 @@ public FrameRenderer( GraphicsDevice device, nint window, WindowRenderOptions op _queue = device.CreateCommandQueue( ); var owners = new List( ); try { - _swap = device.CreateSwapChain( _queue, window, (uint)_size.Width, (uint)_size.Height ); owners.Add( _swap ); + _swap = composition ? device.CreateCompositionSwapChain( _queue, (uint)_size.Width, (uint)_size.Height ) : + device.CreateSwapChain( _queue, window, (uint)_size.Width, (uint)_size.Height ); owners.Add( _swap ); _heap = device.CreateRenderTargetHeap( _swap.BufferCount ); owners.Add( _heap ); _slots = new FrameSlot[options.FramesInFlight]; for ( int i = 0; i < _slots.Length; ++i ) { _slots[i] = new( device ); owners.Add( _slots[i] ); } diff --git a/src/DXSharp.Native/Factory2Raw.cs b/src/DXSharp.Native/Factory2Raw.cs index b6f247a..73de049 100644 --- a/src/DXSharp.Native/Factory2Raw.cs +++ b/src/DXSharp.Native/Factory2Raw.cs @@ -14,4 +14,13 @@ internal unsafe partial interface IFactory2Raw : IDXGIFactory1 { [PreserveSig] BOOL IsWindowedStereoEnabled( ); [PreserveSig] int CreateSwapChainForHwnd( nint device, HWND window, in DXGI_SWAP_CHAIN_DESC1 description, DXGI_SWAP_CHAIN_FULLSCREEN_DESC* fullscreen, nint output, out nint swapChain ); + [PreserveSig] int CreateSwapChainForCoreWindow( nint device, nint window, in DXGI_SWAP_CHAIN_DESC1 description, nint output, out nint swapChain ); + [PreserveSig] int GetSharedResourceAdapterLuid( HANDLE resource, out LUID luid ); + [PreserveSig] int RegisterStereoStatusWindow( HWND window, uint message, out uint cookie ); + [PreserveSig] int RegisterStereoStatusEvent( HANDLE signal, out uint cookie ); + [PreserveSig] void UnregisterStereoStatus( uint cookie ); + [PreserveSig] int RegisterOcclusionStatusWindow( HWND window, uint message, out uint cookie ); + [PreserveSig] int RegisterOcclusionStatusEvent( HANDLE signal, out uint cookie ); + [PreserveSig] void UnregisterOcclusionStatus( uint cookie ); + [PreserveSig] int CreateSwapChainForComposition( nint device, in DXGI_SWAP_CHAIN_DESC1 description, nint output, out nint swapChain ); } diff --git a/tests/InteropQualification/HostShaderQualification.cs b/tests/InteropQualification/HostShaderQualification.cs index f68164a..c71a694 100644 --- a/tests/InteropQualification/HostShaderQualification.cs +++ b/tests/InteropQualification/HostShaderQualification.cs @@ -3,12 +3,38 @@ using DXSharp.Shaders; using Windows.Win32; using Windows.Win32.Foundation; +using Windows.Win32.Graphics.Dxgi; namespace InteropQualification; internal static class HostShaderQualification { internal static void Run() { using var device = GraphicsDevice.Create(new() { UseWarp = true }); + using (var queue = device.CreateCommandQueue()) { + using var chain = device.CreateCompositionSwapChain(queue, 64, 48); + if (!chain.IsComposition || chain.BufferCount != 2) throw new InvalidOperationException("Composition swap-chain identity failed."); + using (var buffer = chain.AcquireBackBuffer(0)) { } + chain.SetCompositionScale(1.25f, 1.5f); + queue.WaitIdle(); chain.Resize(80, 72); + using var native = chain.QueryNativeInterface(); + unsafe { + DXGI_SWAP_CHAIN_DESC1 description; + System.Runtime.InteropServices.Marshal.ThrowExceptionForHR((int)native.Interface.GetDesc1(&description)); + DXGI_MATRIX_3X2_F matrix; + System.Runtime.InteropServices.Marshal.ThrowExceptionForHR((int)native.Interface.GetMatrixTransform(&matrix)); + if (description.Width != 80 || description.Height != 72 || + Math.Abs(matrix._11 - .8f) > .00001f || Math.Abs(matrix._22 - 1f/1.5f) > .00001f) + throw new InvalidOperationException("Composition description or inverse scale did not survive resize."); + } + bool rejected = false; + try { chain.SetCompositionScale(float.NaN, 1); } catch (ArgumentOutOfRangeException) { rejected = true; } + if (!rejected) throw new InvalidOperationException("Non-finite composition scale accepted."); + using var compute = device.CreateCommandQueue(QueueKind.Compute); + rejected = false; + try { using var invalid = device.CreateCompositionSwapChain(compute, 64, 48); } catch (ArgumentException) { rejected = true; } + if (!rejected) throw new InvalidOperationException("Composition accepted a non-direct queue."); + } + Console.WriteLine("PASS: composition factory ABI, owned interface query, buffers, resize, inverse scale and invalid input guards."); string folder = Path.Combine(Path.GetTempPath(), "dxsharp include " + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(folder); try { string source = Path.Combine(folder, "test.hlsl");