From 7001b54a222aeb7d55fa7ed2f658354bd78ab43a Mon Sep 17 00:00:00 2001
From: Aaron Carter <89698828+atcarter714@users.noreply.github.com>
Date: Thu, 5 Nov 2026 00:20:02 -0600
Subject: [PATCH 1/6] Introduce generated COM graphics, shader and DirectML
foundation
---
.github/workflows/build.yml | 46 +++-
DXSharp.sln | 77 ++++++
Directory.Packages.props | 1 +
README.md | 2 +
build.ps1 | 1 +
build/CaptureCrash.ps1 | 26 ++
build/VerifyInterop.ps1 | 43 ++++
build/VerifyPackages.ps1 | 33 ++-
build/msbuild/DXSharp.Core.targets | 8 +
build/msbuild/DXSharp.DirectML.targets | 15 ++
build/msbuild/NativeDependencies.targets | 13 +-
doc/Generated-Com-Foundation.md | 108 ++++++++
samples/ModernCompute/ModernCompute.csproj | 9 +
samples/ModernCompute/Program.cs | 62 +++++
samples/ModernCompute/packages.lock.json | 39 +++
samples/ModernTriangle/ModernTriangle.csproj | 9 +
samples/ModernTriangle/Program.cs | 156 +++++++++++
samples/ModernTriangle/packages.lock.json | 26 ++
src/DXSharp.Core/DXSharp.Core.csproj | 20 ++
src/DXSharp.Core/Graphics/Commands.cs | 243 ++++++++++++++++++
src/DXSharp.Core/Graphics/GraphicsDevice.cs | 127 +++++++++
src/DXSharp.Core/Graphics/GraphicsTypes.cs | 50 ++++
src/DXSharp.Core/Graphics/Pipelines.cs | 125 +++++++++
src/DXSharp.Core/Graphics/Resources.cs | 120 +++++++++
src/DXSharp.Core/Graphics/SwapChain.cs | 67 +++++
src/DXSharp.Core/Interop/ComOwner.cs | 109 ++++++++
src/DXSharp.Core/Interop/Factory2Raw.cs | 17 ++
src/DXSharp.Core/Interop/GraphicsException.cs | 16 ++
src/DXSharp.Core/Interop/NativeRuntime.cs | 31 +++
src/DXSharp.Core/NativeMethods.json | 12 +
src/DXSharp.Core/NativeMethods.txt | 41 +++
src/DXSharp.Core/Shaders/ShaderCompiler.cs | 126 +++++++++
src/DXSharp.Core/packages.lock.json | 49 ++++
src/DXSharp.DirectML/DXSharp.DirectML.csproj | 12 +
src/DXSharp.DirectML/DirectMlDevice.cs | 49 ++++
src/DXSharp.DirectML/TensorAddOperator.cs | 115 +++++++++
src/DXSharp.DirectML/TensorShape.cs | 25 ++
src/DXSharp.DirectML/packages.lock.json | 32 +++
.../InteropQualification.csproj | 13 +
tests/InteropQualification/Program.cs | 159 ++++++++++++
tests/InteropQualification/native/fixture.cpp | 101 ++++++++
tests/InteropQualification/packages.lock.json | 39 +++
42 files changed, 2366 insertions(+), 6 deletions(-)
create mode 100644 build/CaptureCrash.ps1
create mode 100644 build/VerifyInterop.ps1
create mode 100644 build/msbuild/DXSharp.Core.targets
create mode 100644 build/msbuild/DXSharp.DirectML.targets
create mode 100644 doc/Generated-Com-Foundation.md
create mode 100644 samples/ModernCompute/ModernCompute.csproj
create mode 100644 samples/ModernCompute/Program.cs
create mode 100644 samples/ModernCompute/packages.lock.json
create mode 100644 samples/ModernTriangle/ModernTriangle.csproj
create mode 100644 samples/ModernTriangle/Program.cs
create mode 100644 samples/ModernTriangle/packages.lock.json
create mode 100644 src/DXSharp.Core/DXSharp.Core.csproj
create mode 100644 src/DXSharp.Core/Graphics/Commands.cs
create mode 100644 src/DXSharp.Core/Graphics/GraphicsDevice.cs
create mode 100644 src/DXSharp.Core/Graphics/GraphicsTypes.cs
create mode 100644 src/DXSharp.Core/Graphics/Pipelines.cs
create mode 100644 src/DXSharp.Core/Graphics/Resources.cs
create mode 100644 src/DXSharp.Core/Graphics/SwapChain.cs
create mode 100644 src/DXSharp.Core/Interop/ComOwner.cs
create mode 100644 src/DXSharp.Core/Interop/Factory2Raw.cs
create mode 100644 src/DXSharp.Core/Interop/GraphicsException.cs
create mode 100644 src/DXSharp.Core/Interop/NativeRuntime.cs
create mode 100644 src/DXSharp.Core/NativeMethods.json
create mode 100644 src/DXSharp.Core/NativeMethods.txt
create mode 100644 src/DXSharp.Core/Shaders/ShaderCompiler.cs
create mode 100644 src/DXSharp.Core/packages.lock.json
create mode 100644 src/DXSharp.DirectML/DXSharp.DirectML.csproj
create mode 100644 src/DXSharp.DirectML/DirectMlDevice.cs
create mode 100644 src/DXSharp.DirectML/TensorAddOperator.cs
create mode 100644 src/DXSharp.DirectML/TensorShape.cs
create mode 100644 src/DXSharp.DirectML/packages.lock.json
create mode 100644 tests/InteropQualification/InteropQualification.csproj
create mode 100644 tests/InteropQualification/Program.cs
create mode 100644 tests/InteropQualification/native/fixture.cpp
create mode 100644 tests/InteropQualification/packages.lock.json
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index b641f46..f16713a 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -1,4 +1,4 @@
-name: .NET 10 build baseline
+name: .NET 10 SDK qualification
on:
push:
@@ -29,7 +29,10 @@ jobs:
global-json-file: global.json
cache: true
cache-dependency-path: '**/packages.lock.json'
- - name: Restore, build, baseline tests, pack, and consume packages
+ - uses: ilammy/msvc-dev-cmd@v1
+ with:
+ arch: x64
+ - name: Restore, build, ABI tests, pack, and consume packages
shell: pwsh
run: ./build.ps1 -Configuration ${{ matrix.configuration }}
- name: Upload build evidence
@@ -42,3 +45,42 @@ jobs:
artifacts/test-results/**
artifacts/packages/**
if-no-files-found: warn
+
+ interop-aot:
+ name: Native COM JIT and AOT (${{ matrix.os }})
+ runs-on: ${{ matrix.os }}
+ timeout-minutes: 25
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-24.04, windows-2025]
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-dotnet@v4
+ with:
+ global-json-file: global.json
+ - uses: ilammy/msvc-dev-cmd@v1
+ if: runner.os == 'Windows'
+ with:
+ arch: x64
+ - name: Native fixture and managed/AOT ownership qualification
+ shell: pwsh
+ run: ./build/VerifyInterop.ps1 -Configuration Release -PublishAot
+ - name: WARP compute and DirectML numerical qualification
+ if: runner.os == 'Windows'
+ shell: pwsh
+ run: |
+ dotnet run --project samples/ModernCompute -c Release -- --warp --directml
+ if ($LASTEXITCODE -ne 0) { throw 'JIT numerical qualification failed.' }
+ dotnet publish samples/ModernCompute -c Release -r win-x64 -p:PublishAot=true -o artifacts/modern-compute-aot
+ if ($LASTEXITCODE -ne 0) { throw 'NativeAOT compute publish failed.' }
+ & ./artifacts/modern-compute-aot/ModernCompute.exe --warp --directml --no-debug
+ if ($LASTEXITCODE -ne 0) { throw 'NativeAOT numerical qualification failed.' }
+ - uses: actions/upload-artifact@v4
+ if: always()
+ with:
+ name: interop-${{ matrix.os }}
+ path: |
+ artifacts/qualification-aot/**
+ artifacts/modern-compute-aot/**
+ if-no-files-found: warn
diff --git a/DXSharp.sln b/DXSharp.sln
index 0f5951f..954f09b 100644
--- a/DXSharp.sln
+++ b/DXSharp.sln
@@ -126,6 +126,18 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "inc", "inc", "{301D517A-385
devops\pipelines\inc\global-varz.yml = devops\pipelines\inc\global-varz.yml
EndProjectSection
EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DXSharp.Core", "src\DXSharp.Core\DXSharp.Core.csproj", "{95C699FE-92C8-4296-BC32-D250258EA40D}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DXSharp.DirectML", "src\DXSharp.DirectML\DXSharp.DirectML.csproj", "{28A906D9-4254-467D-9238-8C60C49E2E21}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InteropQualification", "tests\InteropQualification\InteropQualification.csproj", "{6D81F5A7-1D01-49DF-8D02-ECD9183FDF6F}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModernTriangle", "samples\ModernTriangle\ModernTriangle.csproj", "{AA296E18-E027-4E92-A7D7-42FC5086A052}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModernCompute", "samples\ModernCompute\ModernCompute.csproj", "{2BB6521A-B6BC-4BD3-AC2E-67E8042386E4}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -230,6 +242,66 @@ Global
{2362EB4B-6F3D-4274-A836-C5394A9660FC}.Release|x64.Build.0 = Release|Any CPU
{2362EB4B-6F3D-4274-A836-C5394A9660FC}.Release|x86.ActiveCfg = Release|Any CPU
{2362EB4B-6F3D-4274-A836-C5394A9660FC}.Release|x86.Build.0 = Release|Any CPU
+ {95C699FE-92C8-4296-BC32-D250258EA40D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {95C699FE-92C8-4296-BC32-D250258EA40D}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {95C699FE-92C8-4296-BC32-D250258EA40D}.Debug|x64.ActiveCfg = Debug|x64
+ {95C699FE-92C8-4296-BC32-D250258EA40D}.Debug|x64.Build.0 = Debug|x64
+ {95C699FE-92C8-4296-BC32-D250258EA40D}.Debug|x86.ActiveCfg = Debug|x86
+ {95C699FE-92C8-4296-BC32-D250258EA40D}.Debug|x86.Build.0 = Debug|x86
+ {95C699FE-92C8-4296-BC32-D250258EA40D}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {95C699FE-92C8-4296-BC32-D250258EA40D}.Release|Any CPU.Build.0 = Release|Any CPU
+ {95C699FE-92C8-4296-BC32-D250258EA40D}.Release|x64.ActiveCfg = Release|x64
+ {95C699FE-92C8-4296-BC32-D250258EA40D}.Release|x64.Build.0 = Release|x64
+ {95C699FE-92C8-4296-BC32-D250258EA40D}.Release|x86.ActiveCfg = Release|x86
+ {95C699FE-92C8-4296-BC32-D250258EA40D}.Release|x86.Build.0 = Release|x86
+ {28A906D9-4254-467D-9238-8C60C49E2E21}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {28A906D9-4254-467D-9238-8C60C49E2E21}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {28A906D9-4254-467D-9238-8C60C49E2E21}.Debug|x64.ActiveCfg = Debug|x64
+ {28A906D9-4254-467D-9238-8C60C49E2E21}.Debug|x64.Build.0 = Debug|x64
+ {28A906D9-4254-467D-9238-8C60C49E2E21}.Debug|x86.ActiveCfg = Debug|x86
+ {28A906D9-4254-467D-9238-8C60C49E2E21}.Debug|x86.Build.0 = Debug|x86
+ {28A906D9-4254-467D-9238-8C60C49E2E21}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {28A906D9-4254-467D-9238-8C60C49E2E21}.Release|Any CPU.Build.0 = Release|Any CPU
+ {28A906D9-4254-467D-9238-8C60C49E2E21}.Release|x64.ActiveCfg = Release|x64
+ {28A906D9-4254-467D-9238-8C60C49E2E21}.Release|x64.Build.0 = Release|x64
+ {28A906D9-4254-467D-9238-8C60C49E2E21}.Release|x86.ActiveCfg = Release|x86
+ {28A906D9-4254-467D-9238-8C60C49E2E21}.Release|x86.Build.0 = Release|x86
+ {6D81F5A7-1D01-49DF-8D02-ECD9183FDF6F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {6D81F5A7-1D01-49DF-8D02-ECD9183FDF6F}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {6D81F5A7-1D01-49DF-8D02-ECD9183FDF6F}.Debug|x64.ActiveCfg = Debug|x64
+ {6D81F5A7-1D01-49DF-8D02-ECD9183FDF6F}.Debug|x64.Build.0 = Debug|x64
+ {6D81F5A7-1D01-49DF-8D02-ECD9183FDF6F}.Debug|x86.ActiveCfg = Debug|x86
+ {6D81F5A7-1D01-49DF-8D02-ECD9183FDF6F}.Debug|x86.Build.0 = Debug|x86
+ {6D81F5A7-1D01-49DF-8D02-ECD9183FDF6F}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {6D81F5A7-1D01-49DF-8D02-ECD9183FDF6F}.Release|Any CPU.Build.0 = Release|Any CPU
+ {6D81F5A7-1D01-49DF-8D02-ECD9183FDF6F}.Release|x64.ActiveCfg = Release|x64
+ {6D81F5A7-1D01-49DF-8D02-ECD9183FDF6F}.Release|x64.Build.0 = Release|x64
+ {6D81F5A7-1D01-49DF-8D02-ECD9183FDF6F}.Release|x86.ActiveCfg = Release|x86
+ {6D81F5A7-1D01-49DF-8D02-ECD9183FDF6F}.Release|x86.Build.0 = Release|x86
+ {AA296E18-E027-4E92-A7D7-42FC5086A052}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {AA296E18-E027-4E92-A7D7-42FC5086A052}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {AA296E18-E027-4E92-A7D7-42FC5086A052}.Debug|x64.ActiveCfg = Debug|x64
+ {AA296E18-E027-4E92-A7D7-42FC5086A052}.Debug|x64.Build.0 = Debug|x64
+ {AA296E18-E027-4E92-A7D7-42FC5086A052}.Debug|x86.ActiveCfg = Debug|x86
+ {AA296E18-E027-4E92-A7D7-42FC5086A052}.Debug|x86.Build.0 = Debug|x86
+ {AA296E18-E027-4E92-A7D7-42FC5086A052}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {AA296E18-E027-4E92-A7D7-42FC5086A052}.Release|Any CPU.Build.0 = Release|Any CPU
+ {AA296E18-E027-4E92-A7D7-42FC5086A052}.Release|x64.ActiveCfg = Release|x64
+ {AA296E18-E027-4E92-A7D7-42FC5086A052}.Release|x64.Build.0 = Release|x64
+ {AA296E18-E027-4E92-A7D7-42FC5086A052}.Release|x86.ActiveCfg = Release|x86
+ {AA296E18-E027-4E92-A7D7-42FC5086A052}.Release|x86.Build.0 = Release|x86
+ {2BB6521A-B6BC-4BD3-AC2E-67E8042386E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {2BB6521A-B6BC-4BD3-AC2E-67E8042386E4}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {2BB6521A-B6BC-4BD3-AC2E-67E8042386E4}.Debug|x64.ActiveCfg = Debug|x64
+ {2BB6521A-B6BC-4BD3-AC2E-67E8042386E4}.Debug|x64.Build.0 = Debug|x64
+ {2BB6521A-B6BC-4BD3-AC2E-67E8042386E4}.Debug|x86.ActiveCfg = Debug|x86
+ {2BB6521A-B6BC-4BD3-AC2E-67E8042386E4}.Debug|x86.Build.0 = Debug|x86
+ {2BB6521A-B6BC-4BD3-AC2E-67E8042386E4}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {2BB6521A-B6BC-4BD3-AC2E-67E8042386E4}.Release|Any CPU.Build.0 = Release|Any CPU
+ {2BB6521A-B6BC-4BD3-AC2E-67E8042386E4}.Release|x64.ActiveCfg = Release|x64
+ {2BB6521A-B6BC-4BD3-AC2E-67E8042386E4}.Release|x64.Build.0 = Release|x64
+ {2BB6521A-B6BC-4BD3-AC2E-67E8042386E4}.Release|x86.ActiveCfg = Release|x86
+ {2BB6521A-B6BC-4BD3-AC2E-67E8042386E4}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -256,6 +328,11 @@ Global
{9AA76EA1-7D92-40CF-A170-B38DEEB87396} = {AF35E6EE-C244-4E1F-84A6-DED8F9BD0EC7}
{3FEFFBFD-24AE-4B98-AF02-1A2EA87F9245} = {60DAF7CD-8C68-4BDF-9940-5ACBF49620D3}
{301D517A-3852-4BEC-911A-EAF7F421F3EB} = {60DAF7CD-8C68-4BDF-9940-5ACBF49620D3}
+ {95C699FE-92C8-4296-BC32-D250258EA40D} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
+ {28A906D9-4254-467D-9238-8C60C49E2E21} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
+ {6D81F5A7-1D01-49DF-8D02-ECD9183FDF6F} = {4A52D278-0251-4FD5-BF3A-5C52C294480A}
+ {AA296E18-E027-4E92-A7D7-42FC5086A052} = {AEE84FD5-7441-42CF-AA6C-5805B759E1F8}
+ {2BB6521A-B6BC-4BD3-AC2E-67E8042386E4} = {AEE84FD5-7441-42CF-AA6C-5805B759E1F8}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {7C4990EC-248E-49D5-A254-EA8AD214C338}
diff --git a/Directory.Packages.props b/Directory.Packages.props
index e5055fb..5ca097c 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -8,6 +8,7 @@
+
diff --git a/README.md b/README.md
index 8ce09c7..a3d83aa 100644
--- a/README.md
+++ b/README.md
@@ -55,6 +55,8 @@
See [the .NET 10 build baseline](doc/NET10-Build-Baseline.md) for Release builds, locked dependencies, test scope, package checks, and current limitations. The original proof-of-concept architecture described below is being migrated incrementally; compilation does not establish production readiness.
+The [generated COM foundation](doc/Generated-Com-Foundation.md) adds the modern `DXSharp.Core` and optional `DXSharp.DirectML` path, native ownership qualification, DXC compilation, and bounded graphics/compute samples. The coverage matrix distinguishes working implementations from the remaining port and records what has actually been executed.
+
## Roadmap ๐ค๏ธ
- [x] Initial DirectX 12 support
diff --git a/build.ps1 b/build.ps1
index 7b21717..3d753ea 100644
--- a/build.ps1
+++ b/build.ps1
@@ -38,6 +38,7 @@ try {
if ([int] $trx.TestRun.ResultSummary.Counters.executed -lt 1) {
throw 'The baseline test filter executed no tests.'
}
+ & (Join-Path $PSScriptRoot 'build/VerifyInterop.ps1') -Configuration $Configuration
if ($RunGraphicsTests) {
Invoke-DotNet -Arguments @('test', 'tests/BasicTests/BasicTests.csproj', '--configuration', $Configuration,
'--no-build', '--no-restore', '--filter', 'TestCategory!=BuildBaseline',
diff --git a/build/CaptureCrash.ps1 b/build/CaptureCrash.ps1
new file mode 100644
index 0000000..243bda2
--- /dev/null
+++ b/build/CaptureCrash.ps1
@@ -0,0 +1,26 @@
+[CmdletBinding()]
+param(
+ [Parameter(Mandatory)] [string] $Executable,
+ [Parameter(Mandatory)] [string] $ProcDumpPath,
+ [string[]] $Arguments = @(),
+ [string] $OutputDirectory = (Join-Path (Split-Path $PSScriptRoot -Parent) 'artifacts/crashes')
+)
+$ErrorActionPreference = 'Stop'
+if (-not $IsWindows) { throw 'Crash capture requires Windows.' }
+$executablePath = (Resolve-Path $Executable).Path
+$procDump = (Resolve-Path $ProcDumpPath).Path
+$directory = [System.IO.Path]::GetFullPath($OutputDirectory)
+New-Item -ItemType Directory -Force $directory | Out-Null
+@{
+ Executable = $executablePath
+ Arguments = $Arguments
+ StartedUtc = [DateTime]::UtcNow.ToString('O')
+ OS = [System.Runtime.InteropServices.RuntimeInformation]::OSDescription
+ Architecture = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString()
+ SHA256 = (Get-FileHash $executablePath -Algorithm SHA256).Hash
+ DotNet = (& dotnet --info | Out-String)
+} | ConvertTo-Json -Depth 4 | Set-Content (Join-Path $directory 'session.json')
+# Full dump on an unhandled exception, launching this executable only. ProcDump
+# handles its own first-run license prompt. No machine-wide crash settings change.
+& $procDump -ma -e -x $directory $executablePath @Arguments 2>&1 | Tee-Object (Join-Path $directory 'procdump.log')
+if ($LASTEXITCODE -ne 0) { throw "ProcDump exited with code $LASTEXITCODE. See $directory." }
diff --git a/build/VerifyInterop.ps1 b/build/VerifyInterop.ps1
new file mode 100644
index 0000000..d766fc1
--- /dev/null
+++ b/build/VerifyInterop.ps1
@@ -0,0 +1,43 @@
+[CmdletBinding()]
+param(
+ [ValidateSet('Debug', 'Release')] [string] $Configuration = 'Debug',
+ [ValidateSet('x64')] [string] $Architecture = 'x64',
+ [switch] $PublishAot
+)
+$ErrorActionPreference = 'Stop'
+Set-StrictMode -Version Latest
+$repoRoot = Split-Path $PSScriptRoot -Parent
+function Invoke-Checked([string] $Command, [string[]] $Arguments) {
+ & $Command @Arguments
+ if ($LASTEXITCODE -ne 0) { throw "$Command failed with exit code $LASTEXITCODE." }
+}
+Push-Location $repoRoot
+try {
+ $nativeDirectory = Join-Path $repoRoot "artifacts/native/$Architecture"
+ New-Item -ItemType Directory -Force $nativeDirectory | Out-Null
+ $source = Join-Path $repoRoot 'tests/InteropQualification/native/fixture.cpp'
+ if ($IsWindows) {
+ # Run from a Developer PowerShell, with cl.exe configured for Architecture.
+ $fixture = Join-Path $nativeDirectory 'dxsharp_abi.dll'
+ Invoke-Checked 'cl.exe' @('/nologo', '/std:c++17', '/EHsc', '/LD', '/O2', $source,
+ "/Fo$nativeDirectory/fixture.obj", '/link', "/OUT:$fixture", "/IMPLIB:$nativeDirectory/dxsharp_abi.lib")
+ $rid = "win-$Architecture"
+ } elseif ($IsLinux -and $Architecture -eq 'x64') {
+ $fixture = Join-Path $nativeDirectory 'libdxsharp_abi.so'
+ Invoke-Checked 'g++' @('-std=c++17', '-shared', '-fPIC', '-O2', $source, '-o', $fixture)
+ $rid = 'linux-x64'
+ } else { throw 'This script qualifies Windows x64/x86/ARM64 and Linux x64.' }
+ $project = 'tests/InteropQualification/InteropQualification.csproj'
+ Invoke-Checked 'dotnet' @('restore', $project, '--locked-mode', '-m:1')
+ Invoke-Checked 'dotnet' @('build', $project, '-c', $Configuration, '--no-restore', '-m:1', "-p:DXSharpNativeFixture=$fixture")
+ $managed = Join-Path $repoRoot "artifacts/bin/InteropQualification/$Configuration/net10.0-windows10.0.26100.0/InteropQualification.dll"
+ Invoke-Checked 'dotnet' @($managed)
+ if ($PublishAot) {
+ $publish = Join-Path $repoRoot "artifacts/qualification-aot/$rid"
+ Invoke-Checked 'dotnet' @('publish', $project, '-m:1', '-c', $Configuration, '-r', $rid, '-p:PublishAot=true',
+ "-p:DXSharpNativeFixture=$fixture", '-o', $publish)
+ Copy-Item $fixture $publish -Force
+ $executable = Join-Path $publish $(if ($IsWindows) { 'InteropQualification.exe' } else { 'InteropQualification' })
+ Invoke-Checked $executable @()
+ }
+} finally { Pop-Location }
diff --git a/build/VerifyPackages.ps1 b/build/VerifyPackages.ps1
index 2a45414..4e95a7b 100644
--- a/build/VerifyPackages.ps1
+++ b/build/VerifyPackages.ps1
@@ -16,7 +16,7 @@ try {
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($version)) {
throw 'Unable to evaluate the package version.'
}
- foreach ($name in @('DXSharp', 'DXSharp.Dxc', 'DXSharp.Framework')) {
+ foreach ($name in @('DXSharp', 'DXSharp.Dxc', 'DXSharp.Framework', 'DXSharp.Core', 'DXSharp.DirectML')) {
if (-not (Test-Path (Join-Path $packageDirectory "$name.$version.nupkg"))) {
throw "Missing package: $name.$version.nupkg"
}
@@ -28,15 +28,21 @@ try {
net10.0-windows10.0.26100.0
true
true
+ win-x64
+ false
+ true
+
"@ | Set-Content (Join-Path $consumerDirectory 'Consumer.csproj')
@'
System.Console.WriteLine(typeof(DXSharp.Direct3D12.IDevice).Assembly.FullName);
System.Console.WriteLine(typeof(DXSharp.Dxc.ShaderBuilder).Assembly.FullName);
+System.Console.WriteLine(typeof(DXSharp.Graphics.GraphicsDevice).Assembly.FullName);
+System.Console.WriteLine(typeof(DXSharp.MachineLearning.DirectMlDevice).Assembly.FullName);
'@ | Set-Content (Join-Path $consumerDirectory 'Program.cs')
@"
@@ -54,6 +60,31 @@ System.Console.WriteLine(typeof(DXSharp.Dxc.ShaderBuilder).Assembly.FullName);
if ($LASTEXITCODE -ne 0) { throw 'Package consumer restore failed.' }
& dotnet build Consumer.csproj --configuration $Configuration --no-restore
if ($LASTEXITCODE -ne 0) { throw 'Package consumer build failed.' }
+ $output = Join-Path $consumerDirectory "bin/$Configuration/net10.0-windows10.0.26100.0/win-x64"
+ $native = @{
+ 'D3D12/D3D12Core.dll' = 'microsoft.direct3d.d3d12/1.620.1/build/native/bin/x64/D3D12Core.dll'
+ 'D3D12/D3D12StateObjectCompiler.dll' = 'microsoft.direct3d.d3d12/1.620.1/build/native/bin/x64/D3D12StateObjectCompiler.dll'
+ 'dxcompiler.dll' = 'microsoft.direct3d.dxc/1.9.2609.5/build/native/bin/x64/dxcompiler.dll'
+ 'dxil.dll' = 'microsoft.direct3d.dxc/1.9.2609.5/build/native/bin/x64/dxil.dll'
+ 'DirectML.dll' = 'microsoft.ai.directml/1.15.4/bin/x64-win/DirectML.dll'
+ }
+ function Test-NativeOutput([string] $Directory) {
+ foreach ($relative in $native.Keys) {
+ $actual = Join-Path $Directory $relative
+ $expected = Join-Path $consumerDirectory "packages/$($native[$relative])"
+ if (-not (Test-Path $actual) -or (Get-FileHash $actual).Hash -ne (Get-FileHash $expected).Hash) {
+ throw "Missing or incorrect native package asset: $actual"
+ }
+ }
+ }
+ Test-NativeOutput $output
+ $publish = Join-Path $consumerDirectory 'publish'
+ & dotnet publish Consumer.csproj --configuration $Configuration --no-restore --output $publish
+ if ($LASTEXITCODE -ne 0) { throw 'Package consumer single-file publish failed.' }
+ Test-NativeOutput $publish
+ foreach ($debugLayer in @('D3D12/d3d12SDKLayers.dll', 'DirectML.Debug.dll')) {
+ if (Test-Path (Join-Path $publish $debugLayer)) { throw "Debug layer leaked into publish: $debugLayer" }
+ }
} finally {
Pop-Location
}
diff --git a/build/msbuild/DXSharp.Core.targets b/build/msbuild/DXSharp.Core.targets
new file mode 100644
index 0000000..84dd8b2
--- /dev/null
+++ b/build/msbuild/DXSharp.Core.targets
@@ -0,0 +1,8 @@
+
+
+
+ $(NuGetPackageRoot)/microsoft.direct3d.d3d12/1.620.1
+ $(NuGetPackageRoot)/microsoft.direct3d.dxc/1.9.2609.5
+
+
+
diff --git a/build/msbuild/DXSharp.DirectML.targets b/build/msbuild/DXSharp.DirectML.targets
new file mode 100644
index 0000000..b028c23
--- /dev/null
+++ b/build/msbuild/DXSharp.DirectML.targets
@@ -0,0 +1,15 @@
+
+
+ $(NuGetPackageRoot)/microsoft.ai.directml/1.15.4
+ x64
+ x86
+ arm64
+
+
+
+
+
+
diff --git a/build/msbuild/NativeDependencies.targets b/build/msbuild/NativeDependencies.targets
index 1842fac..9ffae96 100644
--- a/build/msbuild/NativeDependencies.targets
+++ b/build/msbuild/NativeDependencies.targets
@@ -8,13 +8,20 @@
+ Link="D3D12/%(Filename)%(Extension)" Pack="false" ExcludeFromSingleFile="true" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
+ Link="D3D12/%(Filename)%(Extension)" Pack="false" ExcludeFromSingleFile="true" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="Never" />
+ Link="%(Filename)%(Extension)" Pack="false" ExcludeFromSingleFile="true" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
+
+
+
+
diff --git a/doc/Generated-Com-Foundation.md b/doc/Generated-Com-Foundation.md
new file mode 100644
index 0000000..3452bef
--- /dev/null
+++ b/doc/Generated-Com-Foundation.md
@@ -0,0 +1,108 @@
+# Generated COM foundation
+
+This slice establishes a second, independently usable path through DXSharp: generated native projections, deterministic C# owners, explicit command recording, shader compilation, presentation, and DirectML tensor execution. It builds on the .NET 10 baseline. The original SDK and its samples remain available while their public surface is ported.
+
+The architectural direction follows the README's self-assessment: preserve DirectX semantics and direct access, make the managed layer idiomatic, and remove the duplicated public-interface/implementation hierarchy. The optional application framework remains separate from the graphics SDK.
+
+## Assemblies and dependency direction
+
+| Assembly | Responsibility | Depends on |
+| --- | --- | --- |
+| `DXSharp.Core` | Private generated DXGI/D3D12/DXC/DirectML declarations; native activation; ownership; public graphics and shader APIs | Native Agility and DXC SDK packages |
+| `DXSharp.DirectML` | Public tensor shape, DirectML device, compiled dense Float32 addition, initialization/binding/execution | `DXSharp.Core`, native DirectML package |
+| Existing `DXSharp`, `DXSharp.Dxc`, `DXSharp.Framework` | Existing proof-of-concept API during the port | Existing frozen projection |
+
+The migration target is to promote the modern implementation into the main DXSharp package after API and runtime parity gates pass, then port the framework and retire the legacy lifetime machinery. The two implementations are a transition boundary, not a permanent duplication strategy. The modern samples depend only on the new path.
+
+The generated declarations are implementation details. A signed friend relationship lets the DirectML component reuse the same declarations and ownership rules without a second native projection. Public graphics types are sealed owners; they do not mirror each native interface with another public interface and implementation pair. `GraphicsObject.QueryNativeInterface` supplies an independently owned `SafeHandle` for deliberate native integration.
+
+Core uses CsWin32 **0.3.367**, Win32Metadata **71.0.37-preview**, `GeneratedComInterface`, `GeneratedComClass`, and `LibraryImport`. Runtime marshalling is disabled in the modern assemblies. CsWin32 runs as a build task; generated output lives under `artifacts/obj`, outside source globs. The legacy projects retain their previous generator pins. These are intentional per-project overrides, not a solution-wide projection replacement.
+
+## Ownership contract
+
+`ComOwner.Adopt` consumes exactly one returned native interface reference. It creates a private `UniqueInstance` generated projection, which owns its own queried references. Disposal calls `ComObject.FinalRelease` on that unique projection and disposes the original native reference exactly once. Projection failure releases the consumed output. `Clone` obtains independent ownership. No public method returns a shared runtime RCW that the caller must manually release.
+
+The only handwritten vtable calls are the invariant IUnknown slots: QueryInterface, AddRef and Release. A narrow source-generated `IFactory2Raw` declaration adapts DXGI's typed swap-chain output to a raw owning output; it inherits its preceding slots from metadata-generated `IDXGIFactory1`. This avoids mixing the default shared output projection with deterministic unique ownership. No graphics call uses handwritten vtable offsets.
+
+Internal stack-scoped borrows use `SafeHandle.DangerousAddRef/DangerousRelease` and cannot escape to the heap. Borrow values must not be copied. The owner and native lease remain distinct; disposal of the public owner does not invalidate an active borrow or a separately retained submission reference. Callers synchronize disposal with CPU method calls on the same owner. DXC compilation and queue operations have their own locks; command-list recording and allocator management are single-threaded per object.
+
+### GPU lifetime
+
+Recording captures independent native references to resources, descriptor heaps, pipeline state, root signatures and the allocator. Submitting transfers those references to a queue completion record. The queue also retains the native command list. Fence completion releases that record and makes allocator/list reuse legal. Public wrappers can therefore be disposed after their final recording use, before submission, without releasing the native objects required by that submission.
+
+Pending submissions root their queue independently of application references. A nonblocking completion poll retires finished records, so dropping the last managed queue reference cannot finalize an in-flight resource. Explicit `Wait` retires immediately. The poll does not turn a timeout or signal failure into success; unresolved work stays rooted. A removed device permits retiring all records because its execution has stopped. Queue disposal drains its work; a timeout throws and leaves the owner live for another wait/disposal attempt.
+
+The caller still manages resource states, cross-queue synchronization, descriptor overwrites and concurrent use. A fence value from another queue is not interchangeable with this queue's completion token. Each queue owns a private fence. Objects from different device identities are rejected before recording or binding. This is a thin SDK contract, not an implicit render graph or a full D3D12 hazard validator.
+
+## Native activation and distribution
+
+Agility 1.620.1 is selected through `ID3D12SDKConfiguration1.CreateDeviceFactory(620, absoluteSdkPath)`. Debug configuration is applied to that local factory before device creation. This avoids the old module initializer, developer-mode SDK override and process-global SDK selection. `DeviceOptions.UseAgility = false` explicitly selects the system runtime.
+
+System D3D12/DXGI load from the Windows system directory. DXC and DirectML load from `AppContext.BaseDirectory`; Agility resides under `D3D12/`. Successful module loads are cached for process lifetime so callbacks and finalizers cannot call into an unloaded module. Missing app-local dependencies fail with the expected absolute path.
+
+Modern NuGet packages depend on the official native SDK packages and include `buildTransitive` copy targets. Build and publish copy the selected architecture's files to those same paths, including for a framework-dependent single-file consumer. DLLs remain outside the single-file executable. Debug layers are copied for Debug builds and excluded from publish. The separate DirectML package brings DirectML 1.15.4 only when that component is referenced. Native files are consumed from their original packages, with their original licenses.
+
+Set `RuntimeIdentifier` to `win-x64`, `win-x86`, or `win-arm64` for deployment. Architecture selection otherwise defaults to x64; an arbitrary AnyCPU executable is not a portable native deployment. x64 is the qualification target in this slice. x86/ARM64 copy mappings are present but their ABI execution is not yet qualified. When updating native versions, update both `Directory.Packages.props` and the pinned package paths in `build/msbuild/DXSharp.*.targets`, then rerun the isolated consumer test.
+
+## Implemented surface and remaining port
+
+| Area | Implemented in the modern path | Subsequent work |
+| --- | --- | --- |
+| DXGI | Adapter preference/WARP selection; flip HWND swap chain; acquire/present/resize | Adapter enumeration and selection API, HDR/color space, tearing, fullscreen policy |
+| D3D12 | Device/local factory; direct/compute/copy queues; allocators/lists; completion; buffer map/copy/barriers; RTV heaps; graphics/compute roots and PSOs | General textures/views, upload footprints, descriptor allocation/tables, samplers, stream PSOs, bundles, render passes, enhanced barriers |
+| Shaders | DXC Compiler3/Result; UTF-8 source; arguments; generated include/blob callbacks; status and warnings; copied object/reflection/PDB/hash/root-signature/disassembly outputs | Structured reflection API, container/linker tooling, cache, cancellation through worker isolation |
+| DirectML | Immutable dense Float32 shape; device; compiled equal-shape Add; initializer; descriptors; temporary/persistent allocations; binding; dispatch | General binding/execution sessions, reusable initialization/storage, GEMM/convolution/activations, graphs, broadcasting/strides/dtypes, feature queries |
+| Diagnostics | Bounded InfoQueue snapshot, device-removed HRESULT, operation-preserving exceptions, sample evidence, ProcDump launcher | DRED setup and breadcrumb/page-fault decoding; live-object regression gates; device-recovery policy |
+| Samples | ModernTriangle with resize, bounded frames and GC stress; ModernCompute with numerical DXC and optional DirectML checks | Texture, async upload, multi-frame synchronization, mesh/raytracing, richer DirectML workloads |
+
+Declaring newer native interfaces in the generation manifest does not mean their friendly APIs or runtime paths have been qualified. General API completeness, zero-allocation hot paths and performance parity still require measured gates. `IsAotCompatible` is deliberately not advertised on the packages before the Windows execution matrix passes. The WinForms triangle itself is not an AOT sample; ModernCompute is the console candidate.
+
+## Build and qualification
+
+Use an x64 Developer PowerShell with the C++ build tools available for the standard Windows build:
+
+```powershell
+./build.ps1 -Configuration Debug
+./build.ps1 -Configuration Release
+./build/VerifyInterop.ps1 -Configuration Release -PublishAot
+
+dotnet run --project samples/ModernTriangle -c Debug -- --frames=600 --gc-stress
+dotnet run --project samples/ModernTriangle -c Debug -- --headless --warp
+dotnet run --project samples/ModernCompute -c Debug -- --directml
+dotnet run --project samples/ModernCompute -c Release -- --warp --directml
+```
+
+ModernTriangle compiles shaders, checks failed DXC diagnostics and include callbacks, dispatches a known compute result, and renders only when headless mode is absent. It uses a fully synchronized frame path to isolate ABI/lifetime correctness before introducing multiple frames in flight. ModernCompute verifies `1234` from a compiled compute shader and, with `--directml`, `[11, 22, 33, 44]` from a native DirectML Add. Both exercise disposal of public owners before submission while native leases remain live. `--no-debug` disables validation when deliberately comparing a retail run. `--system-runtime` bypasses Agility.
+
+The native C++ fixture checks actual vtables, inherited methods, 16-byte structure returns, buffer lengths, failed QI/projection cleanup, independent clones, disposal and scoped borrows, forgotten-owner finalization, repeated GC stress, native-held callbacks, and the actual generated DXC include/blob callback types. It does not need a GPU or the Windows DLLs. The tensor tests verify copied shapes, invalid dimensions and checked byte counts; binding and tensor descriptor sizes are compared with the platform C++ definitions (Windows SDK types on Windows). Include resolver exceptions are checked across the native HRESULT boundary. `VerifyInterop.ps1` builds the fixture with MSVC on Windows or g++ on Linux, executes the managed suite, and optionally publishes/runs its NativeAOT counterpart.
+
+CI adds Windows/Linux JIT and AOT native-fixture runs, Windows WARP compute/DirectML checks, and a published AOT ModernCompute run. The isolated package consumer restores into a private cache, builds, publishes a single-file executable, compares deployed native file hashes to the selected official SDK package files, and rejects debug layers in publish output. CI configuration is an execution gate, not evidence that a workflow has already passed.
+
+### Evidence from this development host
+
+- Linux x64, SDK 10.0.403: full solution Debug and Release builds passed; new modern projects compiled without warnings. Existing legacy warnings remain visible.
+- Native fixture JIT and Linux NativeAOT: **2,288 checks passed per run**, **2,004 native fixture objects destroyed per run**, **zero remaining native fixture objects**. This includes the generated DXC include/blob callback path, not actual DXC compilation on Linux.
+- Linux NativeAOT publishing required a development-host workaround for MSB4216: an external, uncommitted MSBuild import ran the ILLink tasks in process instead of the failing out-of-process task host. The resulting native ELF executable passed the same suite. No workaround or warning suppression is shipped in the repository.
+- Debug and Release packing and isolated consumer build/single-file publish passed, including deployed native hashes and debug-layer exclusion.
+- Windows presentation, DXC compilation, DirectML numerical execution, Windows structure-return ABI, and Windows AOT remain pending execution of their corresponding gates. The earlier baseline sample's Windows success was reported by the maintainer; the later CLR crash remains undiagnosed.
+
+## Crash investigation
+
+The original BasicSample remains useful as a reproduction. Keep its exact binaries and PDBs with the dump; do not infer the failure from a managed exception alone. A CLR access violation can originate at an incorrect ABI boundary, a released native object, or unrelated native code. This foundation removes several lifetime mechanisms from the new path, but is not proof of the original crash's cause or a verified fix.
+
+With Sysinternals ProcDump available, launch either sample under full-dump capture:
+
+```powershell
+./build/CaptureCrash.ps1 `
+ -Executable ./artifacts/bin/BasicSample/Debug/net10.0-windows10.0.26100.0/BasicSample.exe `
+ -ProcDumpPath C:/Tools/ProcDump/procdump64.exe
+
+./build/CaptureCrash.ps1 `
+ -Executable ./artifacts/bin/ModernTriangle/Debug/net10.0-windows10.0.26100.0/ModernTriangle.exe `
+ -ProcDumpPath C:/Tools/ProcDump/procdump64.exe `
+ -Arguments @('--frames=100000', '--gc-stress')
+```
+
+The launcher records the executable hash, arguments, OS, architecture and SDK/runtime inventory, and asks ProcDump to launch only that executable and capture a full dump on an unhandled exception. It does not change global crash settings. ModernTriangle also writes `diagnostics.json` and managed failures under its evidence directory. Next investigation requires the crashing native instruction, native/managed stacks, loaded-module versions and device-removal evidence from that exact run.
+
+Primary references: [source-generated COM](https://learn.microsoft.com/dotnet/standard/native-interop/comwrappers-source-generation), [unique ComObject.FinalRelease](https://learn.microsoft.com/dotnet/api/system.runtime.interopservices.marshalling.comobject.finalrelease), [DirectML binding](https://learn.microsoft.com/windows/ai/directml/dml-binding), [Microsoft's HelloDirectML](https://github.com/microsoft/DirectML/blob/master/Samples/HelloDirectML/main.cpp), [ProcDump](https://learn.microsoft.com/sysinternals/downloads/procdump).
diff --git a/samples/ModernCompute/ModernCompute.csproj b/samples/ModernCompute/ModernCompute.csproj
new file mode 100644
index 0000000..6a73b40
--- /dev/null
+++ b/samples/ModernCompute/ModernCompute.csproj
@@ -0,0 +1,9 @@
+
+
+ Exe
+ net10.0-windows10.0.26100.0
+ false
+ true
+
+
+
diff --git a/samples/ModernCompute/Program.cs b/samples/ModernCompute/Program.cs
new file mode 100644
index 0000000..e29c57a
--- /dev/null
+++ b/samples/ModernCompute/Program.cs
@@ -0,0 +1,62 @@
+using DXSharp.Graphics;
+using DXSharp.MachineLearning;
+using DXSharp.Shaders;
+
+using var device = GraphicsDevice.Create( new( ) {
+ UseWarp = args.Contains( "--warp" ), UseAgility = !args.Contains( "--system-runtime" ), EnableDebugLayer = !args.Contains( "--no-debug" )
+} );
+Console.WriteLine( device.AdapterName );
+try {
+ ShaderRoundTrip( );
+ if ( args.Contains( "--directml" ) ) DirectMlRoundTrip( );
+ var diagnostics = device.GetDiagnostics( );
+ foreach ( string message in diagnostics.Messages ) Console.WriteLine( message );
+ if ( diagnostics.DeviceRemovedReason < 0 || diagnostics.Messages.Any( x => x.Contains( "SEVERITY_ERROR" ) || x.Contains( "SEVERITY_CORRUPTION" ) ) )
+ throw new InvalidOperationException( "Graphics validation failed." );
+ Console.WriteLine( "PASS: requested numerical qualifications completed." ); return 0;
+} catch ( Exception error ) {
+ Console.Error.WriteLine( error );
+ foreach ( string message in device.GetDiagnostics( ).Messages ) Console.Error.WriteLine( message );
+ return 1;
+}
+
+void ShaderRoundTrip( ) {
+ using var compiler = new ShaderCompiler( );
+ var shader = compiler.Compile( "RWStructuredBuffer values : register(u0); [numthreads(1,1,1)] void Main() { values[0] = 1234; }", "Main", "cs_6_0" ).RequireSuccess( );
+ using var queue = device.CreateCommandQueue( QueueKind.Compute ); using var allocator = device.CreateCommandAllocator( QueueKind.Compute );
+ using var commands = device.CreateCommandList( allocator ); using var root = device.CreateRootSignature( 1 );
+ using var pipeline = device.CreateComputePipeline( root, shader );
+ using var output = device.CreateBuffer( 4, initialState: ResourceState.UnorderedAccess, unorderedAccess: true );
+ using var readback = device.CreateBuffer( 4, BufferMemory.Readback );
+ commands.SetComputePipeline( pipeline ); commands.SetComputeBuffer( 0, output ); commands.Dispatch( 1 );
+ commands.UavBarrier( output ); commands.Transition( output, ResourceState.UnorderedAccess, ResourceState.CopySource );
+ commands.CopyBuffer( output, readback, 4 ); commands.Close( );
+ root.Dispose( ); pipeline.Dispose( ); output.Dispose( ); GC.Collect( ); GC.WaitForPendingFinalizers( );
+ queue.Wait( queue.Submit( commands ) );
+ Span value = stackalloc uint[1]; readback.Read( value );
+ if ( value[0] != 1234 ) throw new InvalidOperationException( $"Shader readback mismatch: {value[0]}." );
+ Console.WriteLine( "PASS: DXC -> compute -> readback = 1234, after early owner disposal and GC." );
+}
+void DirectMlRoundTrip( ) {
+ using var ml = DirectMlDevice.Create( device ); using var add = ml.CompileAdd( new TensorShape( 1, 1, 1, 4 ) );
+ using var queue = device.CreateCommandQueue( ); using var allocator = device.CreateCommandAllocator( );
+ using var commands = device.CreateCommandList( allocator );
+ using var left = device.CreateBuffer( 16, initialState: ResourceState.CopyDestination, unorderedAccess: true );
+ using var right = device.CreateBuffer( 16, initialState: ResourceState.CopyDestination, unorderedAccess: true );
+ using var output = device.CreateBuffer( 16, initialState: ResourceState.UnorderedAccess, unorderedAccess: true );
+ using var upload = device.CreateBuffer( 32, BufferMemory.Upload );
+ using var readback = device.CreateBuffer( 16, BufferMemory.Readback );
+ upload.Write( [1, 2, 3, 4, 10, 20, 30, 40] );
+ commands.CopyBuffer( upload, left, 16 ); commands.CopyBuffer( upload, right, 16, sourceOffset: 16 );
+ commands.Transition( left, ResourceState.CopyDestination, ResourceState.UnorderedAccess );
+ commands.Transition( right, ResourceState.CopyDestination, ResourceState.UnorderedAccess );
+ commands.Close( ); upload.Dispose( ); GC.Collect( ); queue.Wait( queue.Submit( commands ) );
+ // The operator owns its DirectML and graphics references independently of this facade.
+ ml.Dispose( ); add.Execute( queue, left, right, output );
+ allocator.Reset( ); commands.Reset( allocator );
+ commands.Transition( output, ResourceState.UnorderedAccess, ResourceState.CopySource );
+ commands.CopyBuffer( output, readback, 16 ); commands.Close( ); queue.Wait( queue.Submit( commands ) );
+ Span values = stackalloc float[4]; readback.Read( values );
+ if ( !values.SequenceEqual( [11f, 22f, 33f, 44f] ) ) throw new InvalidOperationException( $"DirectML mismatch: {string.Join( ", ", values.ToArray( ) )}." );
+ Console.WriteLine( "PASS: DirectML Add = [11, 22, 33, 44]." );
+}
diff --git a/samples/ModernCompute/packages.lock.json b/samples/ModernCompute/packages.lock.json
new file mode 100644
index 0000000..92072c3
--- /dev/null
+++ b/samples/ModernCompute/packages.lock.json
@@ -0,0 +1,39 @@
+{
+ "version": 2,
+ "dependencies": {
+ "net10.0-windows10.0.26100": {
+ "dxsharp.core": {
+ "type": "Project",
+ "dependencies": {
+ "Microsoft.Direct3D.D3D12": "[1.620.1, 1.620.1]",
+ "Microsoft.Direct3D.DXC": "[1.9.2609.5, 1.9.2609.5]"
+ }
+ },
+ "dxsharp.directml": {
+ "type": "Project",
+ "dependencies": {
+ "DXSharp.Core": "[0.4.0-net10-preview.1, )",
+ "Microsoft.AI.DirectML": "[1.15.4, 1.15.4]"
+ }
+ },
+ "Microsoft.AI.DirectML": {
+ "type": "CentralTransitive",
+ "requested": "[1.15.4, )",
+ "resolved": "1.15.4",
+ "contentHash": "UblWBtQxcXcxwcn+jh0pfbq4zv2b6w7ThJ35qUV9gd8niGofrFWzVqZ6yqYDMiE+IJf8LRpG+H1cZpswceOeiA=="
+ },
+ "Microsoft.Direct3D.D3D12": {
+ "type": "CentralTransitive",
+ "requested": "[1.620.1, )",
+ "resolved": "1.620.1",
+ "contentHash": "oQCFTys3PZ0IHtS3I/u0/1IWgpuG7aQa+84AGiraqc8bMOCM8QpDLwLBshEbJ1J7LmuctZReXhF8c0eCiu2Xcw=="
+ },
+ "Microsoft.Direct3D.DXC": {
+ "type": "CentralTransitive",
+ "requested": "[1.9.2609.5, )",
+ "resolved": "1.9.2609.5",
+ "contentHash": "jTWr7a2bMpqV+b0Uc7oxOo8ualplaUw3fsQ+p0kp9TwlWvvmREvt3SA4+Drl2Y0M31iscqZolrL3vpdnLoPpdg=="
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/samples/ModernTriangle/ModernTriangle.csproj b/samples/ModernTriangle/ModernTriangle.csproj
new file mode 100644
index 0000000..79f8dcf
--- /dev/null
+++ b/samples/ModernTriangle/ModernTriangle.csproj
@@ -0,0 +1,9 @@
+
+
+ Exe
+ net10.0-windows10.0.26100.0
+
+
+
+
+
diff --git a/samples/ModernTriangle/Program.cs b/samples/ModernTriangle/Program.cs
new file mode 100644
index 0000000..0a60996
--- /dev/null
+++ b/samples/ModernTriangle/Program.cs
@@ -0,0 +1,156 @@
+using System.Text;
+using System.Text.Json;
+using DXSharp.Graphics;
+using DXSharp.Shaders;
+
+namespace ModernTriangle;
+
+internal static class Program {
+ private const string Shader = """
+ struct Vertex { float4 position : SV_Position; float3 color : COLOR; };
+ Vertex VS(uint id : SV_VertexID) {
+ float2 positions[3] = { float2(0, 0.65), float2(0.65, -0.65), float2(-0.65, -0.65) };
+ float3 colors[3] = { float3(1, 0.2, 0.3), float3(0.2, 1, 0.3), float3(0.2, 0.3, 1) };
+ Vertex value; value.position = float4(positions[id], 0, 1); value.color = colors[id]; return value;
+ }
+ float4 PS(Vertex value) : SV_Target { return float4(value.color, 1); }
+ """;
+
+ [STAThread]
+ public static int Main( string[] args ) {
+ GraphicsDevice? device = null;
+ string evidence = Path.GetFullPath( GetOption( args, "--evidence=" ) ?? "artifacts/modern-triangle" );
+ Directory.CreateDirectory( evidence );
+ try {
+ int frameLimit = int.Parse( GetOption( args, "--frames=" ) ?? "0" );
+ if ( frameLimit < 0 ) throw new ArgumentOutOfRangeException( nameof(frameLimit) );
+ device = GraphicsDevice.Create( new( ) {
+ UseWarp = args.Contains( "--warp" ), UseAgility = !args.Contains( "--system-runtime" ),
+ EnableDebugLayer = !args.Contains( "--no-debug" )
+ } );
+ Console.WriteLine( device.AdapterName );
+ WriteDiagnostics( device, evidence );
+ using var compiler = new ShaderCompiler( );
+ QualifyCompiler( compiler );
+ ComputeRoundTrip( device, compiler );
+ if ( !args.Contains( "--headless" ) ) {
+ Application.SetUnhandledExceptionMode( UnhandledExceptionMode.ThrowException );
+ ApplicationConfiguration.Initialize( );
+ using var window = new Form { Text = "DXSharp ยท Generated COM ยท .NET 10", ClientSize = new( 1024, 720 ) };
+ window.Show( );
+ using var renderer = new Renderer( device, compiler, window );
+ int frames = 0;
+ using var timer = new System.Windows.Forms.Timer { Interval = 1 };
+ timer.Tick += ( _, _ ) => {
+ if ( window.WindowState == FormWindowState.Minimized ) return;
+ renderer.Render( );
+ if ( args.Contains( "--gc-stress" ) && frames % 30 == 0 ) { GC.Collect( ); GC.WaitForPendingFinalizers( ); }
+ ++frames;
+ if ( frameLimit > 0 && frames >= frameLimit ) window.Close( );
+ };
+ // Propagate rendering failures to the outer evidence handler.
+ timer.Start( ); Application.Run( window ); timer.Stop( );
+ Console.WriteLine( $"Rendered {frames} frames." );
+ }
+ var diagnostics = WriteDiagnostics( device, evidence );
+ if ( diagnostics.DeviceRemovedReason < 0 || diagnostics.Messages.Any( x => x.Contains( "SEVERITY_ERROR" ) || x.Contains( "SEVERITY_CORRUPTION" ) ) )
+ throw new InvalidOperationException( "The graphics validation layer reported errors; see diagnostics.json." );
+ Console.WriteLine( "PASS: DXC, include callbacks, compute/readback, and requested rendering completed." );
+ return 0;
+ } catch ( Exception error ) {
+ File.WriteAllText( Path.Combine( evidence, "failure.txt" ), error.ToString( ) );
+ Console.Error.WriteLine( error );
+ if ( device is not null ) { try { WriteDiagnostics( device, evidence ); } catch ( Exception diagnosticError ) { Console.Error.WriteLine( diagnosticError ); } }
+ return 1;
+ } finally { device?.Dispose( ); }
+ }
+
+ private static string? GetOption( string[] args, string prefix ) => args.FirstOrDefault( x => x.StartsWith( prefix, StringComparison.Ordinal ) )?[prefix.Length..];
+ private static GraphicsDiagnostics WriteDiagnostics( GraphicsDevice device, string directory ) {
+ var value = device.GetDiagnostics( );
+ File.WriteAllText( Path.Combine( directory, "diagnostics.json" ), JsonSerializer.Serialize( value, new JsonSerializerOptions { WriteIndented = true } ) );
+ return value;
+ }
+ private static void QualifyCompiler( ShaderCompiler compiler ) {
+ var failed = compiler.Compile( "not valid HLSL", "Main", "cs_6_0" );
+ if ( failed.Succeeded || string.IsNullOrWhiteSpace( failed.Diagnostics ) ) throw new InvalidOperationException( "DXC failure diagnostics were lost." );
+ int calls = 0;
+ var valid = compiler.Compile( "#include \"constant.hlsli\"\nRWStructuredBuffer output : register(u0); [numthreads(1,1,1)] void Main() { output[0] = VALUE; }",
+ "Main", "cs_6_0", includeResolver: name => {
+ if ( !name.EndsWith( "constant.hlsli", StringComparison.Ordinal ) ) throw new FileNotFoundException( name );
+ ++calls; GC.Collect( ); return Encoding.UTF8.GetBytes( "#define VALUE 1234\n" );
+ } ).RequireSuccess( );
+ if ( calls == 0 || valid.Bytecode.IsEmpty ) throw new InvalidOperationException( "The managed include callback did not produce bytecode." );
+ }
+ private static void ComputeRoundTrip( GraphicsDevice device, ShaderCompiler compiler ) {
+ using var queue = device.CreateCommandQueue( QueueKind.Compute );
+ using var allocator = device.CreateCommandAllocator( QueueKind.Compute );
+ using var commands = device.CreateCommandList( allocator );
+ using var root = device.CreateRootSignature( 1 );
+ var shader = compiler.Compile( "RWStructuredBuffer output : register(u0); [numthreads(1,1,1)] void Main() { output[0] = 1234; }", "Main", "cs_6_0" ).RequireSuccess( );
+ using var pipeline = device.CreateComputePipeline( root, shader );
+ using var output = device.CreateBuffer( 4, initialState: ResourceState.UnorderedAccess, unorderedAccess: true );
+ using var readback = device.CreateBuffer( 4, BufferMemory.Readback );
+ commands.SetComputePipeline( pipeline ); commands.SetComputeBuffer( 0, output ); commands.Dispatch( 1 );
+ commands.UavBarrier( output ); commands.Transition( output, ResourceState.UnorderedAccess, ResourceState.CopySource );
+ commands.CopyBuffer( output, readback, 4 ); commands.Close( );
+ // Recording leases survive disposal of the public owners, before submission.
+ root.Dispose( ); pipeline.Dispose( ); output.Dispose( );
+ GC.Collect( ); GC.WaitForPendingFinalizers( );
+ queue.Wait( queue.Submit( commands ) );
+ Span result = stackalloc uint[1]; readback.Read( result );
+ if ( result[0] != 1234 ) throw new InvalidOperationException( $"Compute readback: expected 1234, got {result[0]}." );
+ Console.WriteLine( "PASS: compute/readback = 1234; native dependencies survived public disposal and GC." );
+ }
+
+ private sealed class Renderer : IDisposable {
+ private readonly Form _window;
+ private readonly GraphicsDevice _device;
+ private readonly CommandQueue _queue;
+ private readonly CommandAllocator _allocator;
+ private readonly GraphicsCommandList _commands;
+ private readonly SwapChain _swap;
+ private readonly DescriptorHeap _rtvHeap;
+ private readonly RootSignature _root;
+ private readonly PipelineState _pipeline;
+ private readonly GpuResource?[] _buffers = new GpuResource?[2];
+ private readonly RenderTargetView[] _views = new RenderTargetView[2];
+ private uint _width, _height;
+ internal Renderer( GraphicsDevice device, ShaderCompiler compiler, Form window ) {
+ _window = window; _device = device;
+ _width = (uint)window.ClientSize.Width; _height = (uint)window.ClientSize.Height;
+ _queue = device.CreateCommandQueue( ); _allocator = device.CreateCommandAllocator( );
+ _commands = device.CreateCommandList( _allocator ); _commands.Close( );
+ _swap = device.CreateSwapChain( _queue, window.Handle, _width, _height );
+ _rtvHeap = device.CreateRenderTargetHeap( 2 ); _root = device.CreateRootSignature( );
+ _pipeline = device.CreateGraphicsPipeline( _root, compiler.Compile( Shader, "VS", "vs_6_0" ), compiler.Compile( Shader, "PS", "ps_6_0" ) );
+ AcquireBuffers( );
+ }
+ private void AcquireBuffers( ) {
+ for ( uint i = 0; i < 2; ++i ) {
+ _buffers[i] = _swap.AcquireBackBuffer( i );
+ _views[i] = _device.CreateRenderTargetView( _buffers[i]!, _rtvHeap, i );
+ }
+ }
+ internal void Render( ) {
+ uint width = (uint)Math.Max( _window.ClientSize.Width, 1 ), height = (uint)Math.Max( _window.ClientSize.Height, 1 );
+ _queue.WaitIdle( );
+ if ( width != _width || height != _height ) {
+ foreach ( var buffer in _buffers ) buffer?.Dispose( ); Array.Clear( _buffers ); Array.Clear( _views );
+ _swap.Resize( width, height ); _width = width; _height = height; AcquireBuffers( );
+ }
+ _allocator.Reset( ); _commands.Reset( _allocator );
+ uint index = _swap.CurrentBackBufferIndex;
+ _commands.Transition( _buffers[index]!, ResourceState.Present, ResourceState.RenderTarget );
+ _commands.SetViewport( _width, _height ); _commands.Clear( _views[index], 0.025f, 0.035f, 0.065f );
+ _commands.SetRenderTarget( _views[index] ); _commands.SetGraphicsPipeline( _pipeline ); _commands.Draw( 3 );
+ _commands.Transition( _buffers[index]!, ResourceState.RenderTarget, ResourceState.Present );
+ _commands.Close( ); _queue.Wait( _queue.Submit( _commands ) ); _swap.Present( );
+ }
+ public void Dispose( ) {
+ _queue.WaitIdle( ); _commands.Dispose( );
+ foreach ( var buffer in _buffers ) buffer?.Dispose( ); Array.Clear( _views );
+ _pipeline.Dispose( ); _root.Dispose( ); _rtvHeap.Dispose( ); _swap.Dispose( ); _allocator.Dispose( ); _queue.Dispose( );
+ }
+ }
+}
diff --git a/samples/ModernTriangle/packages.lock.json b/samples/ModernTriangle/packages.lock.json
new file mode 100644
index 0000000..d0ee3eb
--- /dev/null
+++ b/samples/ModernTriangle/packages.lock.json
@@ -0,0 +1,26 @@
+{
+ "version": 2,
+ "dependencies": {
+ "net10.0-windows10.0.26100": {
+ "dxsharp.core": {
+ "type": "Project",
+ "dependencies": {
+ "Microsoft.Direct3D.D3D12": "[1.620.1, 1.620.1]",
+ "Microsoft.Direct3D.DXC": "[1.9.2609.5, 1.9.2609.5]"
+ }
+ },
+ "Microsoft.Direct3D.D3D12": {
+ "type": "CentralTransitive",
+ "requested": "[1.620.1, )",
+ "resolved": "1.620.1",
+ "contentHash": "oQCFTys3PZ0IHtS3I/u0/1IWgpuG7aQa+84AGiraqc8bMOCM8QpDLwLBshEbJ1J7LmuctZReXhF8c0eCiu2Xcw=="
+ },
+ "Microsoft.Direct3D.DXC": {
+ "type": "CentralTransitive",
+ "requested": "[1.9.2609.5, )",
+ "resolved": "1.9.2609.5",
+ "contentHash": "jTWr7a2bMpqV+b0Uc7oxOo8ualplaUw3fsQ+p0kp9TwlWvvmREvt3SA4+Drl2Y0M31iscqZolrL3vpdnLoPpdg=="
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/DXSharp.Core/DXSharp.Core.csproj b/src/DXSharp.Core/DXSharp.Core.csproj
new file mode 100644
index 0000000..89dd10e
--- /dev/null
+++ b/src/DXSharp.Core/DXSharp.Core.csproj
@@ -0,0 +1,20 @@
+
+
+ net10.0-windows10.0.26100.0
+ true
+ true
+ true
+ $(BaseIntermediateOutputPath)$(Configuration)/generated
+ Source-generated DirectX foundation and deterministic ownership for DXSharp.
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/DXSharp.Core/Graphics/Commands.cs b/src/DXSharp.Core/Graphics/Commands.cs
new file mode 100644
index 0000000..c5f08ec
--- /dev/null
+++ b/src/DXSharp.Core/Graphics/Commands.cs
@@ -0,0 +1,243 @@
+using Windows.Win32.Graphics.Direct3D;
+using Windows.Win32.Graphics.Direct3D12;
+using Windows.Win32.Foundation;
+using DXSharp.Interop;
+
+namespace DXSharp.Graphics;
+
+/// A command-memory allocator with explicit pending-submission tracking.
+public sealed class CommandAllocator : GraphicsObject {
+ internal readonly ComOwner Native;
+ internal int Pending;
+ /// The command-list type this allocator serves.
+ public QueueKind Kind { get; }
+ internal CommandAllocator( ComOwner owner, QueueKind kind ) : base( owner ) { Native = owner; Kind = kind; }
+ internal override ComReference Retain( ) => Native.Retain( );
+ /// Reclaims command memory after all associated submissions complete.
+ public void Reset( ) {
+ if ( Volatile.Read( ref Pending ) != 0 ) throw new InvalidOperationException( "The allocator still has GPU work pending." );
+ Results.Check( Native.Interface.Reset( ), "CommandAllocator.Reset" );
+ }
+}
+
+/// A generated-COM command list. Recording is single-threaded per list; independent lists share no scratch state.
+public sealed unsafe class GraphicsCommandList : GraphicsObject {
+ internal readonly ComOwner Native;
+ internal CommandAllocator Allocator;
+ internal QueueKind Kind => Allocator.Kind;
+ private Dictionary