diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 630b714..18d0946 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -57,7 +57,6 @@ jobs:
artifacts/test-results/**
artifacts/api-coverage/**
artifacts/sample-packages/**
- artifacts/shader-build/**
artifacts/packages/**
if-no-files-found: warn
diff --git a/DXSharp.sln b/DXSharp.sln
index 6325683..b0774fe 100644
--- a/DXSharp.sln
+++ b/DXSharp.sln
@@ -160,8 +160,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BasicSample", "samples\Basi
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CharacterLab", "samples\CharacterLab\CharacterLab.csproj", "{BF80CE21-E7F9-4F5F-8D30-8595596B76B1}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CharacterLab.Native", "samples\CharacterLab.Native\CharacterLab.Native.csproj", "{3F26D680-7549-4ED0-B6E6-F940B2E2E8C1}"
-EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -173,29 +171,17 @@ Global
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{BF80CE21-E7F9-4F5F-8D30-8595596B76B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {3F26D680-7549-4ED0-B6E6-F940B2E2E8C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BF80CE21-E7F9-4F5F-8D30-8595596B76B1}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {3F26D680-7549-4ED0-B6E6-F940B2E2E8C1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BF80CE21-E7F9-4F5F-8D30-8595596B76B1}.Debug|x64.ActiveCfg = Debug|x64
- {3F26D680-7549-4ED0-B6E6-F940B2E2E8C1}.Debug|x64.ActiveCfg = Debug|x64
{BF80CE21-E7F9-4F5F-8D30-8595596B76B1}.Debug|x64.Build.0 = Debug|x64
- {3F26D680-7549-4ED0-B6E6-F940B2E2E8C1}.Debug|x64.Build.0 = Debug|x64
{BF80CE21-E7F9-4F5F-8D30-8595596B76B1}.Debug|x86.ActiveCfg = Debug|Any CPU
- {3F26D680-7549-4ED0-B6E6-F940B2E2E8C1}.Debug|x86.ActiveCfg = Debug|Any CPU
{BF80CE21-E7F9-4F5F-8D30-8595596B76B1}.Debug|x86.Build.0 = Debug|Any CPU
- {3F26D680-7549-4ED0-B6E6-F940B2E2E8C1}.Debug|x86.Build.0 = Debug|Any CPU
{BF80CE21-E7F9-4F5F-8D30-8595596B76B1}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {3F26D680-7549-4ED0-B6E6-F940B2E2E8C1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BF80CE21-E7F9-4F5F-8D30-8595596B76B1}.Release|Any CPU.Build.0 = Release|Any CPU
- {3F26D680-7549-4ED0-B6E6-F940B2E2E8C1}.Release|Any CPU.Build.0 = Release|Any CPU
{BF80CE21-E7F9-4F5F-8D30-8595596B76B1}.Release|x64.ActiveCfg = Release|x64
- {3F26D680-7549-4ED0-B6E6-F940B2E2E8C1}.Release|x64.ActiveCfg = Release|x64
{BF80CE21-E7F9-4F5F-8D30-8595596B76B1}.Release|x64.Build.0 = Release|x64
- {3F26D680-7549-4ED0-B6E6-F940B2E2E8C1}.Release|x64.Build.0 = Release|x64
{BF80CE21-E7F9-4F5F-8D30-8595596B76B1}.Release|x86.ActiveCfg = Release|Any CPU
- {3F26D680-7549-4ED0-B6E6-F940B2E2E8C1}.Release|x86.ActiveCfg = Release|Any CPU
{BF80CE21-E7F9-4F5F-8D30-8595596B76B1}.Release|x86.Build.0 = Release|Any CPU
- {3F26D680-7549-4ED0-B6E6-F940B2E2E8C1}.Release|x86.Build.0 = Release|Any CPU
{82FD3E3F-ECB1-4EA2-B538-E1561AE737EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{82FD3E3F-ECB1-4EA2-B538-E1561AE737EF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{82FD3E3F-ECB1-4EA2-B538-E1561AE737EF}.Debug|x64.ActiveCfg = Debug|x64
@@ -488,7 +474,6 @@ Global
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{BF80CE21-E7F9-4F5F-8D30-8595596B76B1} = {AEE84FD5-7441-42CF-AA6C-5805B759E1F8}
- {3F26D680-7549-4ED0-B6E6-F940B2E2E8C1} = {AEE84FD5-7441-42CF-AA6C-5805B759E1F8}
{82FD3E3F-ECB1-4EA2-B538-E1561AE737EF} = {29411031-4490-4542-B2D1-02D223BFD605}
{8A61B8EE-8D96-4AF1-9A7B-0026AA0AF498} = {4A52D278-0251-4FD5-BF3A-5C52C294480A}
{F3C57F0F-8540-4E97-B28D-A34091C53755} = {AEE84FD5-7441-42CF-AA6C-5805B759E1F8}
diff --git a/README.md b/README.md
index 4940827..25ec337 100644
--- a/README.md
+++ b/README.md
@@ -65,5 +65,3 @@ Aaron Carter started DXSharp to prove that C# could support a full Direct3D 12 w
For contributions, open an issue or a pull request with a small reproduction and the adapter, runtime, and validation details. DXSharp is [MIT licensed](LICENSE.md).
The higher-level game runtime and tooling direction, including the experimental Framework migration, is documented in [Framework vision](doc/Framework-Vision.md).
-
-The Preview 4 shader and native-window increment is documented in [Shader build and hosting](doc/Shader-Build-and-Hosting.md). It retains the WinForms API while sharing frame rendering with the native Win32 host and adds precompiled shader assets.
diff --git a/build.ps1 b/build.ps1
index 01fc49a..7979cd7 100644
--- a/build.ps1
+++ b/build.ps1
@@ -49,8 +49,6 @@ try {
Invoke-DotNet -Arguments @('pack', 'DXSharp.sln', '--configuration', $Configuration, '--no-build', '--no-restore', '-m:1')
foreach ($major in '10', '11') {
& (Join-Path $PSScriptRoot 'build/VerifyPackages.ps1') -Configuration $Configuration -RuntimeMajor $major
- & python (Join-Path $PSScriptRoot 'build/verify_shader_build.py') --configuration $Configuration --runtime-major $major
- if ($LASTEXITCODE -ne 0) { throw 'Shader build package qualification failed.' }
& (Join-Path $PSScriptRoot 'build/VerifySamplePackages.ps1') -Configuration $Configuration -RuntimeMajor $major
}
} finally {
diff --git a/build/VerifyPackages.ps1 b/build/VerifyPackages.ps1
index a2163ee..14729a7 100644
--- a/build/VerifyPackages.ps1
+++ b/build/VerifyPackages.ps1
@@ -46,12 +46,6 @@ try {
}
} finally { $archive.Dispose() }
}
- $toolArchive = [System.IO.Compression.ZipFile]::OpenRead((Join-Path $packageDirectory "DXSharp.Tools.Builds.$version.nupkg"))
- try {
- foreach ($entry in 'tasks/netstandard2.0/DXSharp.Tools.Builds.dll', 'buildTransitive/DXSharp.Tools.Builds.targets') {
- if ($null -eq $toolArchive.GetEntry($entry)) { throw "Missing shader build asset: $entry" }
- }
- } finally { $toolArchive.Dispose() }
@"
diff --git a/build/VerifySamples.ps1 b/build/VerifySamples.ps1
index e85f049..bc82999 100644
--- a/build/VerifySamples.ps1
+++ b/build/VerifySamples.ps1
@@ -19,7 +19,6 @@ try {
if ($LASTEXITCODE -ne 0) { throw "$Name failed with exit code $LASTEXITCODE." }
}
- Invoke-Sample 'CharacterLab-native' @('run', '--project', 'samples/CharacterLab.Native', '-c', 'Debug', '--', '--warp', '--frames=9', '--resize-test')
Invoke-Sample 'DepthStencil' @('run', '--project', 'samples/DepthStencil', '-c', 'Debug', '--', '--warp')
Invoke-Sample 'ModernTriangle' @('run', '--project', 'samples/ModernTriangle', '-c', 'Debug', '--',
diff --git a/build/msbuild/DXSharp.Shaders.targets b/build/msbuild/DXSharp.Shaders.targets
deleted file mode 100644
index b956542..0000000
--- a/build/msbuild/DXSharp.Shaders.targets
+++ /dev/null
@@ -1,31 +0,0 @@
-
-
- true
- true
- false
- false
- 1.9.2609.5
- $(NuGetPackageRoot)/microsoft.direct3d.dxc/$(DXSharpDxcVersion)/build/native/bin/x64/dxc.exe
- $(MSBuildThisFileDirectory)../tasks/netstandard2.0/DXSharp.Tools.Builds.dll
-
-
-
-
- <_DXSharpShader Include="@(DXSharpShader)">
- $(IntermediateOutputPath)shaders/%(DXSharpShader.Filename).%(DXSharpShader.EntryPoint).%(DXSharpShader.Profile).dxil
- Shaders.%(DXSharpShader.Filename).%(DXSharpShader.EntryPoint).dxil
- Shaders/%(DXSharpShader.Filename).%(DXSharpShader.EntryPoint).dxil
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/build/msbuild/NativeDependencies.targets b/build/msbuild/NativeDependencies.targets
index da1b85a..9ffae96 100644
--- a/build/msbuild/NativeDependencies.targets
+++ b/build/msbuild/NativeDependencies.targets
@@ -13,7 +13,7 @@
Condition="'$(Configuration)' == 'Debug'"
Link="D3D12/%(Filename)%(Extension)" Pack="false" ExcludeFromSingleFile="true" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="Never" />
-
+
diff --git a/build/release_packages.py b/build/release_packages.py
index 6da78ec..0e75549 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.Desktop", "DXSharp.Framework", "DXSharp.Tools.Builds")
+PACKAGE_IDS = ("DXSharp.Native", "DXSharp.Assets", "DXSharp.Core", "DXSharp.DirectML", "DXSharp.Framework.Desktop", "DXSharp.Framework")
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 38322a6..1fdd6f6 100644
--- a/build/verify_sample_packages.py
+++ b/build/verify_sample_packages.py
@@ -106,17 +106,7 @@ def qualify(configuration, runtime_major):
fleet = consumer / "samples/FleetBattler/bin" / configuration / framework / "FleetBattler.dll"
run([str(fleet), "--warp", "--mute", "--frames=14", "--view-test"], consumer, evidence / "fleet-runtime.log")
character = consumer / "samples/CharacterLab/bin" / configuration / framework / "CharacterLab.dll"
- run([str(character), "--warp", "--frames=9", "--close-test"], consumer, evidence / "character-runtime.log")
- native = consumer / "samples/CharacterLab.Native/bin" / configuration / framework / "CharacterLab.Native.dll"
- runtime = json.loads(native.with_suffix('.runtimeconfig.json').read_text())['runtimeOptions']
- runtime_frameworks = runtime.get('frameworks', [runtime.get('framework', {})])
- if any(x.get('name', '').startswith('Microsoft.WindowsDesktop') for x in runtime_frameworks):
- raise RuntimeError('Native sample requires the Windows Desktop runtime')
- for name in ('dxcompiler.dll', 'dxil.dll'):
- path = native.parent / name
- if path.exists():
- raise RuntimeError(f'Native precompiled consumer deployed {name}')
- run([str(native), "--warp", "--frames=9", "--resize-test"], consumer, evidence / "character-native-runtime.log")
+ run([str(character), "--warp", "--frames=9"], consumer, evidence / "character-runtime.log")
(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/build/verify_shader_build.py b/build/verify_shader_build.py
deleted file mode 100644
index 4eb37ef..0000000
--- a/build/verify_shader_build.py
+++ /dev/null
@@ -1,101 +0,0 @@
-"""Qualify real DXC compilation, incremental state, includes, diagnostics and isolated build-tool packaging."""
-import argparse
-import json
-import os
-from pathlib import Path
-import shutil
-import subprocess
-import tempfile
-import xml.etree.ElementTree as ET
-
-
-def main():
- parser = argparse.ArgumentParser()
- parser.add_argument('--configuration', default='Release')
- parser.add_argument('--runtime-major', default='10')
- parser.add_argument('--compiler')
- parser.add_argument('--source-task', action='store_true')
- args = parser.parse_args()
- root = Path(__file__).resolve().parent.parent
- version = subprocess.check_output(['dotnet', 'msbuild', str(root/'src/DXSharp.Core/DXSharp.Core.csproj'), '-getProperty:PackageVersion', '-nologo'], text=True).strip()
- with tempfile.TemporaryDirectory(prefix='dxsharp shader build ') as temporary:
- consumer = Path(temporary)
- shutil.copyfile(root/'global.json', consumer/'global.json')
- project = ET.Element('Project', Sdk='Microsoft.NET.Sdk')
- properties = ET.SubElement(project, 'PropertyGroup')
- for key, value in {'TargetFramework': f'net{args.runtime_major}.0', 'DXSharpEmbedShaders': 'false',
- 'DXSharpShaderDebug': 'false', 'NuGetAudit': 'false'}.items():
- ET.SubElement(properties, key).text = value
- if args.compiler:
- ET.SubElement(properties, 'DXSharpDxcToolPath').text = args.compiler
- if args.source_task:
- ET.SubElement(properties, 'DXSharpShaderTaskAssembly').text = str(root/f'artifacts/bin/DXSharp.Tools.Builds/{args.configuration}/netstandard2.0/DXSharp.Tools.Builds.dll')
- ET.SubElement(project, 'Import', Project=str(root/'build/msbuild/DXSharp.Shaders.targets'))
- else:
- group = ET.SubElement(project, 'ItemGroup')
- ET.SubElement(group, 'PackageReference', Include='DXSharp.Tools.Builds', Version=f'[{version}]', PrivateAssets='all')
- group = ET.SubElement(project, 'ItemGroup')
- for entry, profile in [('VS', 'vs_6_0'), ('PS', 'ps_6_0')]:
- ET.SubElement(group, 'DXSharpShader', Include='source with spaces/main.hlsl', EntryPoint=entry, Profile=profile,
- Defines='FACTOR=$(Factor)', IncludeDirectories='source with spaces')
- ET.SubElement(properties, 'Factor').text = '1'
- ET.ElementTree(project).write(consumer/'Test.csproj', encoding='utf-8')
- config = ET.Element('configuration'); sources = ET.SubElement(config, 'packageSources'); ET.SubElement(sources, 'clear')
- ET.SubElement(sources, 'add', key='local', value=str(root/f'artifacts/packages/{args.configuration}'))
- if not args.source_task:
- ET.SubElement(sources, 'add', key='nuget.org', value='https://api.nuget.org/v3/index.json')
- mapping = ET.SubElement(config, 'packageSourceMapping')
- 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')
- folder = consumer/'source with spaces'; (folder/'nested').mkdir(parents=True)
- (folder/'main.hlsl').write_text('#include "nested/outer.hlsli"\nfloat4 VS(uint id:SV_VertexID):SV_Position{return float4(id,0,0,1);}\nfloat4 PS():SV_Target{return Shade()*FACTOR;}\n')
- (folder/'nested/outer.hlsli').write_text('#include "../color.hlsli"\nfloat4 Shade(){return COLOR;}\n')
- include = folder/'color.hlsli'; valid = '#define COLOR float4(1,0,0,1)\n'; include.write_text(valid)
- logs = []
- def run(*arguments, success=True):
- result = subprocess.run(['dotnet', *arguments], cwd=consumer, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
- logs.append(result.stdout)
- if (result.returncode == 0) != success:
- raise RuntimeError(result.stdout)
- return result.stdout
- run('restore', 'Test.csproj', '--packages', str(consumer/'packages'))
- compiler_path = Path(run('msbuild', 'Test.csproj', '-getProperty:DXSharpDxcToolPath', '-nologo').strip())
- if not compiler_path.is_file():
- raise RuntimeError(f'Resolved compiler does not exist: {compiler_path}')
- def build(*extra, success=True):
- return run('build', 'Test.csproj', '--no-restore', '-c', args.configuration, '-p:UseSharedCompilation=false', '-nodeReuse:false', *extra, success=success)
- first = build(); containers = sorted((consumer/'obj').rglob('*.dxil'))
- if len(containers) != 2 or any(p.read_bytes()[:4] != b'DXBC' for p in containers):
- raise RuntimeError('Expected two real shader containers')
- first_times = [p.stat().st_mtime_ns for p in containers]
- second = build()
- if second.count('DXC up-to-date:') != 2 or first_times != [p.stat().st_mtime_ns for p in containers]:
- raise RuntimeError('Unchanged shaders were recompiled')
- include.write_text('#define COLOR float4(0,1,0,1)\n')
- if build().count('DXC compiled:') != 2:
- raise RuntimeError('Nested include modification did not invalidate both compilation units')
- if build('-p:Factor=2').count('DXC compiled:') != 2:
- raise RuntimeError('Define change did not invalidate compilation')
- include.write_text('#error intentional shader failure\n')
- failure = build(success=False)
- if 'intentional shader failure' not in failure or 'DXSHADER' not in failure:
- raise RuntimeError('Shader failure lost diagnostic information')
- include.unlink(); build(success=False)
- include.write_text(valid); build('-p:DXSharpShaderDebug=true')
- if len(list((consumer/'obj').rglob('*.dxil.pdb'))) != 2:
- raise RuntimeError('Missing debug PDBs')
- manifest = ET.parse(containers[0].with_name(containers[0].name+'.xml'))
- if not any(x.attrib['Path'].endswith('color.hlsli') for x in manifest.findall('Dependency')):
- raise RuntimeError('Transitive include missing from shader manifest')
- run('clean', 'Test.csproj', '-c', args.configuration)
- if any(p.exists() for p in containers):
- raise RuntimeError('Clean left shader intermediates behind')
- evidence = root/f'artifacts/shader-build/{args.configuration}/net{args.runtime_major}'
- evidence.mkdir(parents=True, exist_ok=True)
- (evidence/'qualification.log').write_text('\n'.join(logs))
- print('PASS: shader package; two entry points; paths with spaces; unchanged/define/transitive-include rebuilds; errors; deleted includes; PDBs; manifests; clean.')
-
-
-if __name__ == '__main__':
- main()
diff --git a/doc/API-Coverage.md b/doc/API-Coverage.md
index fe7e907..aac05dd 100644
--- a/doc/API-Coverage.md
+++ b/doc/API-Coverage.md
@@ -1,6 +1,6 @@
# DirectX API coverage
-The modern SDK exposes public native bindings through DXSharp.Native. Core builds its owned graphics API on the same declarations. Consumers can use the generated interfaces and NativeInterface without generating another set of DirectX types.
+The preview 3 candidate exposes public native bindings through DXSharp.Native. Core builds its owned graphics API on the same declarations. Consumers can use the generated interfaces and NativeInterface without generating another set of DirectX types.
The baseline is Microsoft.Windows.SDK.Win32Metadata 71.0.45-preview, CsWin32 0.3.371, Agility 1.620.2 D3D12 metadata, .NET 10/11, and Windows x64. The Windows metadata package supplies the non-D3D12 families; its modular D3D12 provider selects the pinned Agility WinMD. Exactly one D3D12 provider is selected. Native API names live under Windows.Win32. Entry points and constants use Windows.Win32.PInvoke. NativeInterface ownership helpers live under DXSharp.Interop.
@@ -31,9 +31,6 @@ ApiCoverage reads the pinned WinMD and built assembly with System.Reflection.Met
| DirectComposition | 62 / 62 | 294 / 294 |
| XInput | 16 / 16 | 117 / 117 |
| GameInput | 80 / 80 | 802 / 802 |
-| Window messages and HWND APIs | 198 / 198 | 3314 / 3314 |
-| High DPI | 7 / 7 | 56 / 56 |
-| Keyboard and mouse | 46 / 46 | 605 / 605 |
These counts measure the pinned metadata surface. They do not verify every overload, ABI layout, callback, native version, feature tier, or driver. In particular, interface generation through ID3D12Device16 does not imply that the selected runtime or adapter implements every interface. Query the required interface and check feature support before use.
diff --git a/doc/Framework-Vision.md b/doc/Framework-Vision.md
index 40d8a92..7406022 100644
--- a/doc/Framework-Vision.md
+++ b/doc/Framework-Vision.md
@@ -33,7 +33,3 @@ The frame-time display measures CPU recording and presentation cadence separatel
5. Deliver project templates, asset/animation inspection, shader reload, profiling, packaging and deployment as the initial Game Studio experience. Expand editor functionality from those working tools.
Acceptance remains workload-based: CPU/GPU deformation agreement; clear allocation and fence ownership; package-only consumption of the same samples; JIT and NativeAOT on .NET 10/11; lifecycle/presentation checks and separately recorded hardware performance. Maintain the Windows API parity backlog alongside the framework work.
-
-## Shader and host continuation
-
-The next working slice adds precompiled Framework shader resources, typed runtime compiler options and a packaged incremental DXC task. FrameRenderer now 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. WinUI/WPF adapters and the full application lifecycle remain continuation work.
diff --git a/doc/Generated-Com-Foundation.md b/doc/Generated-Com-Foundation.md
index 5994efa..7e94a14 100644
--- a/doc/Generated-Com-Foundation.md
+++ b/doc/Generated-Com-Foundation.md
@@ -1,5 +1,3 @@
-> Historical foundation notes. Current public bindings live in DXSharp.Native; current pins and coverage are in [API-Coverage.md](API-Coverage.md). The original private-projection and single-frame host descriptions below describe earlier increments. See [Framework-Vision.md](Framework-Vision.md) and [Shader-Build-and-Hosting.md](Shader-Build-and-Hosting.md) for the current framework/host contract.
-
# 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.
diff --git a/doc/Sample-Showcase-Plan.md b/doc/Sample-Showcase-Plan.md
deleted file mode 100644
index 22f680a..0000000
--- a/doc/Sample-Showcase-Plan.md
+++ /dev/null
@@ -1,44 +0,0 @@
-# Visual samples and optional UI hosts
-
-The sample lineup must demonstrate observable SDK behavior as coverage grows. Console readback fixtures remain correctness tests; they do not replace interactive graphics, media or streaming examples. This plan adds no completed-coverage claims for APIs that are still on the backlog.
-
-## Immediate visual polish
-
-- PlanarShadows: lower the directional light, lengthen the silhouettes, enlarge the receiving plane and adjust the camera. Increase receiver/shadow contrast and light rotating pyramid normals in world space with the same direction used for projection. Keep the simple opaque planar projection explicit; this is not a shadow-map or soft-shadow implementation.
-- LitCube: move lighting into the pixel shader, normalize interpolated normals, add a warm key with specular response, a restrained cool fill and hemispherical ambient light. Convert linear output to sRGB explicitly for the existing UNORM target. This is an analytic lighting example, not a PBR material renderer.
-- Keep the existing bounded WARP runs and debug-layer checks for both samples. Visual acceptance additionally needs an interactive hardware review; a successful smoke run alone does not establish appearance or frame pacing.
-
-## Optional host adapters
-
-Keep Core and Framework independent of WPF and Windows App SDK dependencies. Each reusable control belongs in an optional assembly in this repository and the normal Libraries solution group. Sample applications are separate executable projects. No copy of the graphics bindings or second rendering backend is needed.
-
-| Host | Proposed assembly / existing location | Presentation contract |
-| --- | --- | --- |
-| Native Win32 | Existing DXSharp.Framework | NativeGame and HWND FrameRenderer; no Windows Forms dependency |
-| Windows Forms | Existing DXSharp.Framework.Desktop | Existing DesktopGame adapter |
-| WPF | Proposed DXSharp.Framework.Wpf | HwndHost child HWND using the existing frame renderer; WPF dispatcher owns scheduling and teardown |
-| WinUI 3 | Proposed DXSharp.Framework.WinUI | Composition swap chain attached through Microsoft.UI.Xaml ISwapChainPanelNative; Windows App SDK dependency stays in this adapter |
-
-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.
-
-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.
-
-## Coverage-driven showcase work
-
-| Work item | Interactive demonstration | Required evidence |
-| --- | --- | --- |
-| Video and audio | Local licensed test clip decoded into a displayed texture with synchronized audio, play/pause/seek, volume/mute, format and hardware-decoding telemetry | Known color/time patterns, seek/end-of-stream, A/V clock drift, resize and teardown. Identify Media Foundation versus D3D video decode/processing paths explicitly; playing through a control is not proof of D3D12 video binding coverage. |
-| Spatial audio | XAudio2 voices with X3DAudio emitter/listener motion, distance attenuation and channel routing | Deterministic DSP coefficient checks plus audible hardware verification; expose channel layout and device changes. X3DAudio computes spatial DSP parameters and does not itself play audio. |
-| DirectStorage | Stream a prepared asset pack into a live scene; show queue state, read/decompression timings, bytes and active path | Compare decoded content hashes against the source, exercise missing/corrupt input and shutdown with pending requests. Distinguish file I/O, decompression and GPU visibility; report actual supported paths rather than silently presenting fallback as GPU decompression. Keep ordinary loading as a comparison. |
-| DXR visual scene | Windowed camera-controlled scene with meshes and ground, visible ray-traced shadows and reflections, and a moving instance | Reuse the acceleration-structure/shader-table groundwork from DxrHelloWorld; add output presentation, TLAS updates, resize, fenced resource lifetime and deterministic image checks. Query DXR support and explain an unsupported result clearly; do not relabel rasterization as ray tracing. |
-
-Order: optional WPF HWND and WinUI composition host slice; video/audio and spatial audio alongside their native coverage; DirectStorage alongside its native coverage; then a focused DXR visual showcase. Retain the general texture/DDS, pipeline configuration and cross-queue synchronization backlog as supporting SDK work. Full applications must consume public SDK APIs and join the same source/package qualification mechanism as existing samples.
-
-## Platform references
-
-- [WPF and Win32 interoperation](https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/wpf-and-win32-interoperation)
-- [WPF and Direct3D9 interoperation](https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/wpf-and-direct3d9-interoperation)
-- [WinUI 3 ISwapChainPanelNative::SetSwapChain](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)
-- [CreateSwapChainForComposition](https://learn.microsoft.com/en-us/windows/win32/api/dxgi1_2/nf-dxgi1_2-idxgifactory2-createswapchainforcomposition)
diff --git a/doc/Shader-Build-and-Hosting.md b/doc/Shader-Build-and-Hosting.md
deleted file mode 100644
index 980a3d5..0000000
--- a/doc/Shader-Build-and-Hosting.md
+++ /dev/null
@@ -1,59 +0,0 @@
-# Shader assets and window hosts
-
-This Preview 4 development increment adds a real DXC build task, precompiled shader containers, a shared frame renderer and a Win32 host. Preview 3 remains the published package version. DXSharp.Tools.Builds is a seventh package in the next candidate set; do not reference an unpublished preview from a standalone download.
-
-## Shader compilation
-
-DXSharp.Native exposes the main DXC metadata family; Core's ShaderCompiler uses generated COM. ShaderCompileOptions adds profiles, optional library entry points, source names, HLSL language version, optimization, definitions, include directories, debug information, warnings-as-errors and additional arguments. CompileFile resolves includes through a generated managed include callback backed by filesystem reads. A supplied callback still supports virtual shader sources.
-
-The build task uses the pinned Microsoft.Direct3D.DXC executable, independently of the application's runtime compiler. The old task returned success without compiling and processed only the first item. It and its obsolete task factory/inline definition have been replaced; the historical DxcTool.Build.targets/scripts are compatibility-era files, not the supported target below.
-
-For a package consumer of the next release:
-
-```xml
-
-
-
-
-
-```
-
-No shader profile whitelist prevents newer DXC stages or library profiles. Omit EntryPoint for a library profile. Use distinct outputs/logical names for permutations; OutputFile overrides the default `obj/.../shaders/...dxil`. The task rejects output collisions. AdditionalArguments metadata accepts semicolon-separated DXC argument tokens; output-path flags belong to the task.
-
-Shaders are embedded resources by default. Set DXSharpEmbedShaders=false to stage them as build/publish content, with optional TargetPath metadata. Debug configurations emit PDBs under obj; PDBs, state and manifests are not automatically published. The task's outputs participate in Clean. Compiler selection can be explicitly overridden with DXSharpDxcToolPath, including a native Linux executable for cross-compilation; the default pinned package path is Windows x64.
-
-DXC preprocessing performs actual transitive/macro include resolution on each build. The task hashes its result, compiler binaries and options to decide whether compilation is necessary. This handles include deletion and include-search shadowing as well as edits. It avoids fragile Makefile dependency parsing, including DXC paths containing spaces. Successful shader outputs have XML dependency/hash manifests and state files; missing/corrupt output or missing debug artifacts forces rebuilding. No-op compilation preserves output timestamps.
-
-Framework builds its skinning VS/PS with this task and embeds DXIL. Its default SkinnedModelRenderer constructor loads those shaders; the explicit ShaderCompiler constructor remains available for development. Framework can be compiled for portable CPU/COM-fixture work on Linux without a DXC executable, but that assembly cannot render the skinning workload without its shader resources and cannot be packed as a Framework release. Supply DXSharpDxcToolPath when cross-building a complete package.
-
-ShaderBytecode.Load/CopyFrom own the container storage and can create graphics/compute pipelines without invoking DXC. The container check recognizes a DXBC/DXIL header; it is not an exhaustive DXIL validator. The existing ShaderCompilation overloads remain source-compatible. Pipeline creation still invokes the graphics runtime/driver; build-time HLSL compilation does not precompile a portable driver PSO.
-
-DXSharpCopyDxcRuntime=false disables the SDK package's DXC DLL staging for consumers that exclusively load bytecode. Native declares DXC entry points but loads them only when called. This does not remove the Core NuGet dependency graph or prevent an application from explicitly compiling. CharacterLab.Native's isolated package check asserts no dxcompiler.dll/dxil.dll deployment and verifies no DXC compiler module was loaded.
-
-## Shared renderer and hosts
-
-FrameRenderer lives in Framework, with no Windows Forms dependency. It owns the direct queue, frame slots, HWND swap chain, targets, resizing and fence-based resource retirement. The caller owns the device and HWND. RenderFrame exposes borrowed resources and an already-retired frame-slot index. WindowRenderOptions describes physical size, clear/depth settings, frame slots and optional frame limit.
-
-Public renderer methods are single-threaded. BeginDrain starts queue completion on a worker; the host keeps pumping messages and keeps its HWND alive until that task completes, then disposes presentation resources before destroying the window. Disposal while recording is rejected. Raw device/resource callers retain the underlying SDK synchronization responsibilities.
-
-NativeGame runs a native window and message loop with no WinForms reference, tracks its instance through a rooted GCHandle and pointer-sized window data, catches managed exceptions at WNDPROC, handles DPI changes and mouse capture, skips minimized/zero-sized rendering, and pumps messages through queue drain. DPI awareness is scoped to the calling thread. NativeGameWindow's handle is borrowed: request close through its API rather than destroying the HWND externally. FrameRenderer and native window mutation/disposal belong to their creating thread.
-
-DesktopGame preserves its existing API and delegates rendering/presentation to FrameRenderer. Its WinForms adapter owns UI scheduling, focus/minimize observation and orderly close. The same renderer is therefore exercised by both hosts.
-
-CharacterLab and CharacterLab.Native compile the same Program/OrbitCamera source and use the same CC0 asset and Framework renderer. The native executable references Framework directly, disables UseWindowsForms and compiler-DLL staging, and prints its host/compiler mode. Run either with --warp --frames=9 for a bounded check; native also accepts --resize-test. No second scene/render implementation is maintained.
-
-## Qualification
-
-- verify_shader_build.py uses a fresh external consumer of the packed task; verifies two entry points, spaces, unchanged builds, transitive includes, changed definitions, errors, deleted includes, debug PDBs, dependency manifests and Clean.
-- The Windows COM fixture covers typed runtime compilation/includes, owned bytecode load/save and precompiled pipeline creation. The native-host fixture covers presentation, resize, frame reuse, render exceptions, close/drain and destroyed HWNDs under JIT/NativeAOT.
-- Package qualification builds all 14 runnable samples on .NET 10/11. Both CharacterLab hosts run from those packages, including native resize, compiler-free deployment checks and WinForms dispatch after renderer retirement.
-- The existing sample matrix continues to exercise the WinForms adapter and GPU/CPU skinning correctness. WindowsAndMessaging, HiDpi and KeyboardAndMouse declarations are now namespace roots and coverage-gated, alongside the prior native families.
-
-## Remaining work
-
-This is the HWND host slice, not completed WPF/WinUI adapters. Next add a composition presentation surface for WinUI 3 SwapChainPanel, then optional WinUI and WPF HwndHost adapters with explicit UI thread/DPI/input contracts. WPF HWND airspace remains a host limitation; D3DImage needs a separate surface interoperability path.
-
-DXC reflection object models, disassembly/validation/linking conveniences, shader reload/cache services, richer content cooking and optional compiler package decoupling remain continuation work. General Game/Application lifecycle, video, DirectStorage, X3DAudio and current GameInput remain active SDK/framework backlog items.
diff --git a/samples/CharacterLab.Native/CharacterLab.Native.csproj b/samples/CharacterLab.Native/CharacterLab.Native.csproj
deleted file mode 100644
index 620d133..0000000
--- a/samples/CharacterLab.Native/CharacterLab.Native.csproj
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
- Exe$(DotNetTargets)
- falsefalsetrue
- $(DefineConstants);NATIVE_HOST
-
-
-
-
-
-
-
-
diff --git a/samples/CharacterLab.Native/README.md b/samples/CharacterLab.Native/README.md
deleted file mode 100644
index 7ca36d2..0000000
--- a/samples/CharacterLab.Native/README.md
+++ /dev/null
@@ -1,3 +0,0 @@
-# CharacterLab — native Win32 host
-
-The same scene, camera, model and precompiled Framework shaders as CharacterLab, hosted without Windows Forms. Build/run this project normally, or use `--warp --frames=9 --resize-test` for a bounded software-rendering check. The existing keyboard/mouse controls are unchanged. No DXC compiler DLL is required at runtime. See [the shader/host contract](../../doc/Shader-Build-and-Hosting.md).
diff --git a/samples/CharacterLab.Native/packages.lock.json b/samples/CharacterLab.Native/packages.lock.json
deleted file mode 100644
index fd483f7..0000000
--- a/samples/CharacterLab.Native/packages.lock.json
+++ /dev/null
@@ -1,56 +0,0 @@
-{
- "version": 2,
- "dependencies": {
- "net10.0-windows10.0.26100": {
- "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=="
- }
- }
- }
-}
\ No newline at end of file
diff --git a/samples/CharacterLab.Native/packages.net11.lock.json b/samples/CharacterLab.Native/packages.net11.lock.json
deleted file mode 100644
index db2a9ce..0000000
--- a/samples/CharacterLab.Native/packages.net11.lock.json
+++ /dev/null
@@ -1,56 +0,0 @@
-{
- "version": 2,
- "dependencies": {
- "net11.0-windows10.0.26100": {
- "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=="
- }
- }
- }
-}
\ No newline at end of file
diff --git a/samples/CharacterLab/Program.cs b/samples/CharacterLab/Program.cs
index 92e18d0..2f16a75 100644
--- a/samples/CharacterLab/Program.cs
+++ b/samples/CharacterLab/Program.cs
@@ -2,10 +2,7 @@
using System.Numerics;
using DXSharp.Assets;
using DXSharp.Framework;
-using DXSharp.Framework.Hosting;
-#if !NATIVE_HOST
using DXSharp.Framework.Desktop;
-#endif
using DXSharp.Framework.Graphics;
using DXSharp.Graphics;
using DXSharp.Shaders;
@@ -16,10 +13,8 @@ internal static class Program {
[STAThread]
private static int Main(string[] args) {
try {
-#if !NATIVE_HOST
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
ApplicationConfiguration.Initialize();
-#endif
string modelPath=args.FirstOrDefault(a=>a.StartsWith("--model="))?[8..]??Path.Combine(AppContext.BaseDirectory,"Assets","animatedKnightInPlateArmour.glb");
int frameLimit=int.Parse(args.FirstOrDefault(a=>a.StartsWith("--frames="))?[9..]??"0");
var model=SkinnedModel.Load(modelPath);
@@ -30,8 +25,8 @@ private static int Main(string[] args) {
bool debug=false;
#endif
using var device=GraphicsDevice.Create(new(){UseWarp=args.Contains("--warp"),UseAgility=!args.Contains("--system-runtime"),EnableDebugLayer=debug});
- using var renderer=new SkinnedModelRenderer(device,model,2);
- Console.WriteLine("Precompiled DXIL; no runtime shader compilation.");
+ using var compiler=new ShaderCompiler();
+ using var renderer=new SkinnedModelRenderer(device,compiler,model,2);
int root=Array.FindIndex(model.Nodes,n=>n.Name.Equals("pelvis",StringComparison.OrdinalIgnoreCase));
var player=new AnimationPlayer(model,root);
var pose=new SkeletonPose(model.Nodes);var camera=new OrbitCamera();
@@ -39,7 +34,7 @@ private static int Main(string[] args) {
Console.WriteLine("Drag: orbit | +/-: zoom | 1-9: clip | Space: pause | R: idle | [ / ]: speed");
Console.WriteLine("Persistent GPU skinning; in-place horizontal root motion; four material maps; two fenced frame slots.");
double drawMilliseconds=0;long draws=0;double elapsed=0;
- void Draw(RenderFrame frame) {
+ var result=DesktopGame.Run(device,new(){Title="DXSharp · Character Lab — GPU Skinning",ClientSize=new(1280,800),EnableDepth=true,FramesInFlight=2,FrameLimit=frameLimit},frame=>{
long start=Stopwatch.GetTimestamp();
double dt=frame.Elapsed.TotalSeconds;camera.Update((float)dt);
for(int i=0;i{
- if(UpdateTitle(stats.Frames) is {} title)window.Title=title;
- if(args.Contains("--resize-test") && stats.Frames==2)window.ResizeClient(new(960,640));
+ },(window,stats)=>{
+ if(stats.Frames%60==0)window.Text=$"DXSharp · Character Lab | {player.CurrentClipName} | {60/Math.Max(elapsed,0.001):F0} FPS | CPU record {drawMilliseconds/Math.Max(draws,1):F2} ms";
+ if(stats.Frames%60==0)elapsed=0;
});
-#else
- var desktop=DesktopGame.Run(device,new(){Title="DXSharp · Character Lab — GPU Skinning",ClientSize=new(1280,800),EnableDepth=true,FramesInFlight=2,FrameLimit=frameLimit},
- frame=>Draw(new(frame.Commands,frame.Target,frame.Size,frame.Elapsed,frame.FrameSlotIndex)),(window,stats)=>{
- if(UpdateTitle(stats.Frames) is {} title)window.Text=title;
- if(args.Contains("--close-test") && stats.Frames==1) window.FormClosed+=(_,_)=>{
- // Exercise dispatch after renderer retirement; queued timers must be inert.
- Thread.Sleep(40);Application.DoEvents();
- };
- });
- var result=new RenderStatistics(desktop.Frames,desktop.Resizes);
-#endif
-#if NATIVE_HOST
- if(Process.GetCurrentProcess().Modules.Cast().Any(m=>m.ModuleName.Equals("dxcompiler.dll",StringComparison.OrdinalIgnoreCase)))
- throw new InvalidOperationException("The precompiled native sample loaded DXC at runtime.");
-#endif
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")))return 1;
if(frameLimit>0 && result.Frames!=frameLimit)return 1;
diff --git a/samples/LitCube/Program.cs b/samples/LitCube/Program.cs
index d51a665..70d4948 100644
--- a/samples/LitCube/Program.cs
+++ b/samples/LitCube/Program.cs
@@ -12,39 +12,17 @@ internal static class Program {
row_major float4x4 WorldViewProjection;
row_major float4x4 World;
};
- struct Vertex {
- float4 position : SV_Position;
- float3 worldPosition : WORLDPOS;
- float3 normal : NORMAL;
- float3 color : COLOR;
- };
+ struct Vertex { float4 position : SV_Position; float3 color : COLOR; };
struct VertexInput { float3 position : POSITION; float3 normal : NORMAL; float3 color : COLOR; };
Vertex VS(VertexInput input) {
+ float3 normal = mul(input.normal, (float3x3)World);
+ float light = 0.28 + 0.72 * saturate(dot(normal, normalize(float3(0.45, 0.8, 0.65))));
Vertex output;
output.position = mul(float4(input.position, 1), WorldViewProjection);
- output.worldPosition = mul(float4(input.position, 1), World).xyz;
- output.normal = mul(input.normal, (float3x3)World);
- output.color = input.color;
+ output.color = input.color * light;
return output;
}
- float4 PS(Vertex input) : SV_Target {
- float3 n = normalize(input.normal);
- float3 v = normalize(float3(0, 1.4, 5.8) - input.worldPosition);
- float3 l = normalize(float3(-3.5, 4.0, 4.0) - input.worldPosition);
- float ndotl = saturate(dot(n, l));
- float3 h = normalize(l + v);
- float specular = pow(saturate(dot(n, h)), 48) * ndotl;
- float fill = saturate(dot(n, normalize(float3(1, 0.25, -0.6))));
- float hemisphere = n.y * 0.5 + 0.5;
- float3 ambient = lerp(float3(0.025, 0.03, 0.05), float3(0.12, 0.16, 0.22), hemisphere);
- float3 linearColor = input.color * (ambient + float3(1.05, 0.9, 0.7) * ndotl
- + float3(0.1, 0.2, 0.34) * fill) + float3(1.0, 0.92, 0.8) * specular * 0.65;
- // The target is UNORM, so perform the linear-to-sRGB transfer here.
- linearColor = saturate(linearColor);
- float3 srgb = lerp(12.92 * linearColor, 1.055 * pow(linearColor, 1.0 / 2.4) - 0.055,
- step(0.0031308, linearColor));
- return float4(srgb, 1);
- }
+ float4 PS(Vertex input) : SV_Target { return float4(input.color, 1); }
""";
[StructLayout(LayoutKind.Sequential)]
diff --git a/samples/PlanarShadows/Program.cs b/samples/PlanarShadows/Program.cs
index 87f6f3f..bb28ac4 100644
--- a/samples/PlanarShadows/Program.cs
+++ b/samples/PlanarShadows/Program.cs
@@ -7,12 +7,10 @@
namespace PlanarShadows;
internal static class Program {
- // A low key light exposes the projected silhouette outside each pyramid's base.
- private static readonly Vector3 Light = Vector3.Normalize(new Vector3(-1, 0.65f, 0.55f));
+ private static readonly Vector3 Light = Vector3.Normalize(new Vector3(-0.6f, 1, 0.45f));
private const string Shader = """
cbuffer Scene : register(b0) {
row_major float4x4 transform;
- row_major float4x4 world;
float4 tint;
};
struct Vertex { float4 position : SV_Position; float3 local : LOCAL; float light : LIGHT; };
@@ -22,7 +20,7 @@ Vertex FloorVS(uint id : SV_VertexID) {
float2(-1,-1), float2(1,1), float2(1,-1)
};
Vertex v;
- v.local = float3(corners[id].x, 0, corners[id].y) * 6;
+ v.local = float3(corners[id].x, 0, corners[id].y) * 5;
v.position = mul(float4(v.local, 1), transform);
v.light = 1;
return v;
@@ -33,16 +31,11 @@ Vertex PyramidVS(uint id : SV_VertexID) {
float3(-1,0,1), float3(0,1.65,0)
};
const uint indices[12] = { 0,1,4, 1,2,4, 2,3,4, 3,0,4 };
- uint face = (id / 3) * 3;
- float3 a = corners[indices[face]];
- float3 b = corners[indices[face + 1]];
- float3 c = corners[indices[face + 2]];
- float3 normal = normalize(cross(c - a, b - a));
+ const float light[4] = { 0.6, 0.8, 1.0, 0.72 };
Vertex v;
v.local = corners[indices[id]];
v.position = mul(float4(v.local, 1), transform);
- normal = normalize(mul(normal, (float3x3)world));
- v.light = lerp(1, 0.3 + 0.7 * saturate(dot(normal, normalize(float3(-1, 0.65, 0.55)))), tint.a);
+ v.light = lerp(1, light[id / 3], tint.a);
return v;
}
float4 FloorPS(Vertex v) : SV_Target {
@@ -59,7 +52,7 @@ private static readonly (Vector3 Position, Vector4 Color, float Scale)[] Objects
];
[StructLayout(LayoutKind.Sequential)]
- private readonly record struct DrawConstants(Matrix4x4 Transform, Matrix4x4 World, Vector4 Tint);
+ private readonly record struct DrawConstants(Matrix4x4 Transform, Vector4 Tint);
[STAThread]
public static int Main(string[] args) {
@@ -78,7 +71,7 @@ public static int Main(string[] args) {
});
Console.WriteLine(device.AdapterName);
using var compiler = new ShaderCompiler();
- using var root = device.CreateGraphicsConstantsRootSignature(36);
+ using var root = device.CreateGraphicsConstantsRootSignature(20);
using var floor = CreatePipeline("FloorVS", "FloorPS");
using var pyramid = CreatePipeline("PyramidVS", "PyramidPS");
@@ -94,7 +87,7 @@ public static int Main(string[] args) {
}, frame => {
time += Math.Min((float)frame.Elapsed.TotalSeconds, 0.1f);
float orbit = 0.38f + time * 0.28f;
- var eye = new Vector3(10.2f * MathF.Sin(orbit), 7.2f, 10.2f * MathF.Cos(orbit));
+ var eye = new Vector3(8.5f * MathF.Sin(orbit), 5.8f, 8.5f * MathF.Cos(orbit));
var view = Matrix4x4.CreateLookAt(eye, Vector3.Zero, Vector3.UnitY);
var projection = Matrix4x4.CreatePerspectiveFieldOfView(
MathF.PI / 3, (float)frame.Size.Width / frame.Size.Height, 0.1f, 50);
@@ -107,11 +100,11 @@ public static int Main(string[] args) {
}
frame.Commands.SetGraphicsPipeline(floor);
- Draw(frame.Commands, viewProjection, Matrix4x4.Identity, new(0.36f, 0.42f, 0.5f, 1), 6);
+ Draw(frame.Commands, viewProjection, new(0.25f, 0.29f, 0.36f, 1), 6);
frame.Commands.SetGraphicsPipeline(pyramid);
- foreach (var world in worlds) Draw(frame.Commands, world * shadow * viewProjection, world, new(0.045f, 0.06f, 0.085f, 0), 12);
- for (int i = 0; i < worlds.Length; i++) Draw(frame.Commands, worlds[i] * viewProjection, worlds[i], Objects[i].Color, 12);
+ foreach (var world in worlds) Draw(frame.Commands, world * shadow * viewProjection, new(0.09f, 0.11f, 0.16f, 0), 12);
+ for (int i = 0; i < worlds.Length; i++) Draw(frame.Commands, worlds[i] * viewProjection, Objects[i].Color, 12);
});
var diagnostics = device.GetDiagnostics();
foreach (string message in diagnostics.Messages) Console.WriteLine(message);
@@ -125,8 +118,8 @@ PipelineState CreatePipeline(string vs, string ps) =>
compiler.Compile(Shader, ps, "ps_6_0"), PixelFormat.Rgba8Unorm, depthEnabled: true);
}
- private static void Draw(GraphicsCommandList commands, Matrix4x4 transform, Matrix4x4 world, Vector4 tint, uint vertices) {
- var constants = new DrawConstants(transform, world, tint);
+ private static void Draw(GraphicsCommandList commands, Matrix4x4 transform, Vector4 tint, uint vertices) {
+ var constants = new DrawConstants(transform, tint);
commands.SetGraphicsConstants(MemoryMarshal.Cast(MemoryMarshal.CreateReadOnlySpan(ref constants, 1)));
commands.Draw(vertices);
}
diff --git a/samples/README.md b/samples/README.md
index 523604f..125a734 100644
--- a/samples/README.md
+++ b/samples/README.md
@@ -9,10 +9,10 @@ Open `DXSharp.sln` or run a project with `dotnet run --project samples/ -c
| [ModernTriangle](ModernTriangle) | Minimal graphics pipeline and resize qualification |
| [HelloTexture](HelloTexture) | Texture upload, SRV and sampler |
| [InstancedGrid](InstancedGrid) | 256 animated quads in one instanced draw |
-| [LitCube](LitCube) | Indexed mesh upload, per-pixel diffuse/specular lighting, hemispherical ambient and D32 depth |
+| [LitCube](LitCube) | Indexed mesh upload, vertex input layouts, lighting and D32 depth |
| [StaticModelViewer](StaticModelViewer) | glTF and GLB import, shared geometry, node transforms, and directional lighting |
| [FleetBattler](FleetBattler) | Fleet skirmishes, box selection, planetary development, and compute-driven civilian traffic |
-| [PlanarShadows](PlanarShadows) | Low directional light, world-space face lighting and extended planar shadows |
+| [PlanarShadows](PlanarShadows) | Orbiting camera, multiple pipelines and projected shadows |
| [ModernCompute](ModernCompute) | DXC compute readback, DirectML Add, and matrix inference with fused ReLU |
| [NBodyGravity](NBodyGravity) | Ping-pong GPU simulation, instanced drawing, and a seeded CPU reference |
| [DxrHelloWorld](DxrHelloWorld) | DXR acceleration structures, shader table, and image readback |
@@ -20,7 +20,3 @@ Open `DXSharp.sln` or run a project with `dotnet run --project samples/ -c
Every runnable sample project is included in DXSharp.sln and consumes the current SDK through project references. AdvancedSample remains reference source without a project file.
CharacterLab adds persistent GPU skinning, animation playback and material maps; see [CharacterLab](CharacterLab/README.md).
-
-`CharacterLab.Native` runs the same GPU-skinned scene as CharacterLab through the native Win32 host, with precompiled Framework shaders and no Windows Forms reference. Both samples participate in source and package qualification.
-
-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.
diff --git a/src/DXSharp.Core/Graphics/PrecompiledPipelines.cs b/src/DXSharp.Core/Graphics/PrecompiledPipelines.cs
deleted file mode 100644
index 4e6c330..0000000
--- a/src/DXSharp.Core/Graphics/PrecompiledPipelines.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-using DXSharp.Shaders;
-
-namespace DXSharp.Graphics;
-
-public sealed unsafe partial class GraphicsDevice {
- /// Creates a graphics pipeline directly from precompiled shader containers.
- public PipelineState CreateGraphicsPipeline( RootSignature root, ShaderBytecode vertex, ShaderBytecode pixel,
- PixelFormat targetFormat = PixelFormat.Rgba8Unorm, bool depthEnabled = false ) =>
- CreateGraphicsPipeline( root, vertex, pixel, ReadOnlySpan.Empty, targetFormat, depthEnabled );
- /// Creates an indexed/instanced graphics pipeline from precompiled shader containers.
- public PipelineState CreateGraphicsPipeline( RootSignature root, ShaderBytecode vertex, ShaderBytecode pixel,
- ReadOnlySpan inputLayout, PixelFormat targetFormat = PixelFormat.Rgba8Unorm, bool depthEnabled = false ) {
- ArgumentNullException.ThrowIfNull( vertex ); ArgumentNullException.ThrowIfNull( pixel );
- return CreateGraphicsPipeline( root, vertex.AsCompilation( ), pixel.AsCompilation( ), inputLayout, targetFormat, depthEnabled );
- }
- /// Creates a compute pipeline from precompiled bytecode without invoking DXC.
- public PipelineState CreateComputePipeline( RootSignature root, ShaderBytecode shader ) {
- ArgumentNullException.ThrowIfNull( shader ); return CreateComputePipeline( root, shader.AsCompilation( ) );
- }
-}
diff --git a/src/DXSharp.Core/Shaders/ShaderBytecode.cs b/src/DXSharp.Core/Shaders/ShaderBytecode.cs
deleted file mode 100644
index dbecd2b..0000000
--- a/src/DXSharp.Core/Shaders/ShaderBytecode.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-namespace DXSharp.Shaders;
-
-/// An owned shader container that can be loaded without invoking DXC.
-public sealed class ShaderBytecode {
- private readonly byte[] _bytes;
- private ShaderBytecode( byte[] bytes ) {
- if ( bytes.Length < 32 || bytes[0] != 'D' || bytes[1] != 'X' || bytes[2] != 'B' || bytes[3] != 'C' )
- throw new ArgumentException( "Expected a DXBC/DXIL shader container.", nameof(bytes) );
- _bytes = bytes;
- }
- /// The owned container bytes. Pipeline creation reads them synchronously.
- public ReadOnlyMemory Bytes => _bytes;
- /// Copies a precompiled DXBC/DXIL container into owned storage.
- public static ShaderBytecode CopyFrom( ReadOnlySpan bytes ) => new( bytes.ToArray( ) );
- /// Loads an existing compiled shader. No compiler DLL is loaded.
- public static ShaderBytecode Load( string path ) => new( File.ReadAllBytes( path ) );
- /// Reads a compiled shader from the stream's current position, leaving the stream open.
- public static ShaderBytecode Load( Stream stream ) {
- ArgumentNullException.ThrowIfNull( stream );
- using var copy = new MemoryStream( ); stream.CopyTo( copy ); return new( copy.ToArray( ) );
- }
- /// Writes the shader container to a file.
- public void Save( string path ) => File.WriteAllBytes( path, _bytes );
- internal ShaderCompilation AsCompilation( ) => new( 0, _bytes, string.Empty, new Dictionary>( ) );
-}
diff --git a/src/DXSharp.Core/Shaders/ShaderCompileOptions.cs b/src/DXSharp.Core/Shaders/ShaderCompileOptions.cs
deleted file mode 100644
index f2e7bc0..0000000
--- a/src/DXSharp.Core/Shaders/ShaderCompileOptions.cs
+++ /dev/null
@@ -1,54 +0,0 @@
-namespace DXSharp.Shaders;
-
-/// Common DXC options with an unrestricted additional-argument path.
-public sealed record ShaderCompileOptions {
- /// DXC target profile, including mesh, amplification and library profiles.
- public string Profile { get; init; } = "vs_6_0";
- /// Entry point; null for a library profile.
- public string? EntryPoint { get; init; } = "main";
- /// Source identity reported in diagnostics and debug information.
- public string? SourceName { get; init; }
- /// HLSL language version.
- public string LanguageVersion { get; init; } = "2021";
- /// Optimization level 0 through 3.
- public int OptimizationLevel { get; init; } = 3;
- /// Emit debug information into the compiled container.
- public bool DebugInformation { get; init; }
- /// Treat warnings as errors.
- public bool WarningsAsErrors { get; init; }
- /// Preprocessor definitions, each in NAME or NAME=VALUE form.
- public IReadOnlyList Defines { get; init; } = Array.Empty( );
- /// Include search directories. Without a callback, the compiler resolves includes from the filesystem.
- public IReadOnlyList IncludeDirectories { get; init; } = Array.Empty( );
- /// Additional DXC arguments preserved in supplied order.
- public IReadOnlyList AdditionalArguments { get; init; } = Array.Empty( );
- internal List Arguments( ) {
- if ( OptimizationLevel is < 0 or > 3 ) throw new ArgumentOutOfRangeException( nameof(OptimizationLevel) );
- ArgumentException.ThrowIfNullOrWhiteSpace( LanguageVersion );
- ArgumentNullException.ThrowIfNull( Defines ); ArgumentNullException.ThrowIfNull( IncludeDirectories ); ArgumentNullException.ThrowIfNull( AdditionalArguments );
- var result = new List( );
- if ( SourceName is not null ) result.Add( SourceName );
- result.AddRange( ["-HV", LanguageVersion, "-O" + OptimizationLevel] );
- if ( DebugInformation ) result.AddRange( ["-Zi", "-Qembed_debug"] );
- if ( WarningsAsErrors ) result.Add( "-WX" );
- foreach ( string value in Defines ) { result.Add( "-D" ); result.Add( value ); }
- foreach ( string value in IncludeDirectories ) { result.Add( "-I" ); result.Add( value ); }
- result.AddRange( AdditionalArguments ); return result;
- }
-}
-
-public sealed unsafe partial class ShaderCompiler {
- /// Compiles a shader or library using typed options and optional virtual include resolution.
- public ShaderCompilation Compile( string source, ShaderCompileOptions options, Func>? includeResolver = null ) {
- ArgumentNullException.ThrowIfNull( options );
- return options.EntryPoint is null ? CompileLibrary( source, options.Profile, options.Arguments( ), includeResolver ) :
- Compile( source, options.EntryPoint, options.Profile, options.Arguments( ), includeResolver );
- }
- /// Compiles UTF-8 HLSL from disk, adding its directory to the include search path.
- public ShaderCompilation CompileFile( string path, ShaderCompileOptions options ) {
- ArgumentNullException.ThrowIfNull( options ); string fullPath = Path.GetFullPath( path );
- return Compile( File.ReadAllText( fullPath ), options with {
- SourceName = fullPath, IncludeDirectories = [Path.GetDirectoryName( fullPath )!, ..options.IncludeDirectories]
- } );
- }
-}
diff --git a/src/DXSharp.Core/Shaders/ShaderCompiler.cs b/src/DXSharp.Core/Shaders/ShaderCompiler.cs
index 57c4c81..fedb9ed 100644
--- a/src/DXSharp.Core/Shaders/ShaderCompiler.cs
+++ b/src/DXSharp.Core/Shaders/ShaderCompiler.cs
@@ -24,7 +24,7 @@ public ShaderCompilation RequireSuccess( ) {
}
/// A synchronous DXC compiler using generated COM, scoped source storage, and copied outputs.
-public sealed unsafe partial class ShaderCompiler : IDisposable {
+public sealed unsafe class ShaderCompiler : IDisposable {
private readonly ComOwner _compiler;
private readonly object _gate = new( );
/// Loads the packaged DXC compiler without depending on the working directory.
@@ -60,12 +60,12 @@ private ShaderCompilation CompileCore( string source, string? entryPoint, string
if ( options.Any( value => string.IsNullOrEmpty( value ) || value.Contains( '\0' ) ) ) throw new ArgumentException( "Compiler arguments cannot be empty or contain NUL." );
byte[] bytes = Encoding.UTF8.GetBytes( source );
using var nativeArguments = new Arguments( options );
- using var includes = new IncludeHandler( includeResolver ?? (name => File.ReadAllBytes( name )) );
+ using var includes = includeResolver is null ? null : new IncludeHandler( includeResolver );
lock ( _gate ) {
fixed ( byte* input = bytes ) fixed ( nint* args = nativeArguments.Values ) {
DxcBuffer buffer = new( ) { Ptr = input, Size = (nuint)bytes.Length, Encoding = 65001 };
Guid resultId = typeof(IDxcResult).GUID;
- Results.Check( _compiler.Interface.Compile( &buffer, (PCWSTR*)args, (uint)options.Count, includes, &resultId, out nint resultPointer ), "Compiler3.Compile" );
+ Results.Check( _compiler.Interface.Compile( &buffer, (PCWSTR*)args, (uint)options.Count, includes!, &resultId, out nint resultPointer ), "Compiler3.Compile" );
using var result = ComOwner.Adopt( resultPointer );
HRESULT status;
Results.Check( result.Interface.GetStatus( &status ), "DxcResult.GetStatus" );
diff --git a/src/DXSharp.Framework.Desktop/DesktopGame.cs b/src/DXSharp.Framework.Desktop/DesktopGame.cs
index 0b2311c..8874673 100644
--- a/src/DXSharp.Framework.Desktop/DesktopGame.cs
+++ b/src/DXSharp.Framework.Desktop/DesktopGame.cs
@@ -1,7 +1,6 @@
using System.Diagnostics;
using System.Numerics;
using DXSharp.Graphics;
-using DXSharp.Framework.Hosting;
using Windows.Win32;
using Windows.Win32.UI.WindowsAndMessaging;
@@ -38,51 +37,159 @@ public readonly record struct DesktopFrame( GraphicsCommandList Commands, Render
/// Number of back-buffer size changes after initialization.
public readonly record struct DesktopRunResult( int Frames, int Resizes );
-/// WinForms scheduling over the shared frame renderer.
+/// Runs a WinForms frame loop with two back buffers and one or two frame slots.
public static class DesktopGame {
- /// Runs on the calling STA thread. The device remains caller-owned.
+ /// Runs a windowed render loop on the calling STA thread until the window closes.
+ /// A caller-owned device that stays alive for the duration of the run.
+ /// Window dimensions, depth, presentation limit and number of frame slots.
+ /// Records scene commands into the borrowed frame before submission.
+ /// Optional callback on the calling thread after each present call.
+ /// Presentation and resize totals.
+ /// The calling thread is outside an STA.
public static DesktopRunResult Run( GraphicsDevice device, DesktopGameOptions options, Action draw,
Action
-
-
- false
- $(RepoRootPath)artifacts/bin/DXSharp.Tools.Builds/$(Configuration)/netstandard2.0/DXSharp.Tools.Builds.dll
-
-
-
-
-
-
-
-
-
diff --git a/src/DXSharp.Framework/Graphics/SkinnedModelRenderer.cs b/src/DXSharp.Framework/Graphics/SkinnedModelRenderer.cs
index b15409a..f57b6b8 100644
--- a/src/DXSharp.Framework/Graphics/SkinnedModelRenderer.cs
+++ b/src/DXSharp.Framework/Graphics/SkinnedModelRenderer.cs
@@ -50,18 +50,16 @@ public sealed unsafe class SkinnedModelRenderer : IDisposable {
private struct Joint { public Matrix4x4 Pose, Normal; }
[StructLayout(LayoutKind.Sequential)]
private struct Scene { public Matrix4x4 Wvp, World, Normal; public Vector4 Surface, Camera, BaseFactor, MaterialSettings; }
- /// Creates geometry/materials using the assembly's precompiled shaders. No compiler is invoked.
- public SkinnedModelRenderer(GraphicsDevice device, SkinnedModel model, int frameSlots=2)
- : this(device,model,LoadShader("VS"),LoadShader("PS"),frameSlots) { }
- /// Creates geometry/materials with explicitly supplied precompiled shaders.
- public SkinnedModelRenderer(GraphicsDevice device, SkinnedModel model, ShaderBytecode vertex, ShaderBytecode pixel, int frameSlots=2) {
- ArgumentNullException.ThrowIfNull(device); ArgumentNullException.ThrowIfNull(model);
+ /// Creates resident geometry and materials. Initialization performs one upload submission and wait.
+ public SkinnedModelRenderer(GraphicsDevice device, ShaderCompiler compiler, SkinnedModel model, int frameSlots=2) {
+ ArgumentNullException.ThrowIfNull(device); ArgumentNullException.ThrowIfNull(compiler); ArgumentNullException.ThrowIfNull(model);
if(frameSlots is <1 or >3) throw new ArgumentOutOfRangeException(nameof(frameSlots));
_model=model; _palette=new Matrix4x4[model.Skin.Joints.Length]; _joints=new Joint[_palette.Length+1]; _frames=new GpuResource[frameSlots];
_sceneOffset = ((ulong)_joints.Length*128+255)&~255UL;
try {
_root=Own(CreateSignature(device));
- _pipeline=Own(device.CreateGraphicsPipeline(_root,vertex,pixel,[
+ string shader=ReadShader();
+ _pipeline=Own(device.CreateGraphicsPipeline(_root,compiler.Compile(shader,"VS","vs_6_0"),compiler.Compile(shader,"PS","ps_6_0"),[
new("POSITION",VertexFormat.Float3,0),new("NORMAL",VertexFormat.Float3,12),new("TANGENT",VertexFormat.Float4,24),
new("TEXCOORD",VertexFormat.Float2,40),new("BLENDWEIGHT",VertexFormat.Float4,48),new("BLENDINDICES",VertexFormat.UInt4,64)
],depthEnabled:true));
@@ -84,17 +82,6 @@ public SkinnedModelRenderer(GraphicsDevice device, SkinnedModel model, ShaderByt
for(int i=0;i<_frames.Length;++i) _frames[i]=Own(device.CreateBuffer(checked(_sceneOffset+512),BufferMemory.Upload));
} catch { Dispose();throw; }
}
- /// Creates the renderer with explicit runtime compilation, for development and custom compiler configuration.
- public SkinnedModelRenderer(GraphicsDevice device, ShaderCompiler compiler, SkinnedModel model, int frameSlots=2)
- : this(device,model,Compile(compiler,"VS","vs_6_0"),Compile(compiler,"PS","ps_6_0"),frameSlots) { }
- private static ShaderBytecode Compile(ShaderCompiler compiler,string entry,string profile) {
- ArgumentNullException.ThrowIfNull(compiler);return ShaderBytecode.CopyFrom(compiler.Compile(ReadShader(),entry,profile).RequireSuccess().Bytecode.Span);
- }
- private static ShaderBytecode LoadShader(string entry) {
- using var stream=typeof(SkinnedModelRenderer).Assembly.GetManifestResourceStream("DXSharp.Framework.Graphics.Skinned."+entry+".dxil")
- ??throw new InvalidOperationException("Precompiled skinning shaders are missing. Build Framework with DXC before rendering.");
- return ShaderBytecode.Load(stream);
- }
/// Records a skinned model and optional reference grid using a completed frame slot. Matrices use System.Numerics row-vector conventions.
public void Draw(GraphicsCommandList commands,SkeletonPose pose,Matrix4x4 world,Matrix4x4 viewProjection,Vector3 camera,int frameSlot,bool drawGrid=true,float exposure=1) {
ObjectDisposedException.ThrowIf(_disposed,this);
diff --git a/src/DXSharp.Framework/Hosting/FrameRenderer.cs b/src/DXSharp.Framework/Hosting/FrameRenderer.cs
deleted file mode 100644
index f9a4eea..0000000
--- a/src/DXSharp.Framework/Hosting/FrameRenderer.cs
+++ /dev/null
@@ -1,132 +0,0 @@
-using System.Drawing;
-using System.Numerics;
-using DXSharp.Graphics;
-
-namespace DXSharp.Framework.Hosting;
-
-/// Settings shared by native and managed window hosts.
-public sealed record WindowRenderOptions {
- /// Initial window title.
- public string Title { get; init; } = "DXSharp";
- /// Initial physical client size.
- public Size ClientSize { get; init; } = new( 1024, 720 );
- /// Color used to clear the back buffer.
- public Vector4 ClearColor { get; init; } = new( .025f, .035f, .065f, 1 );
- /// Creates a depth buffer matching the presentation surface.
- public bool EnableDepth { get; init; }
- /// Frame slots. Reuse waits for the slot's previous submission.
- public int FramesInFlight { get; init; } = 2;
- /// Bounded presentation count, or zero for an interactive run.
- public int FrameLimit { get; init; }
-}
-
-/// Borrowed frame resources valid only during the render callback.
-public readonly record struct RenderFrame( GraphicsCommandList Commands, RenderTargetView Target, Size Size, TimeSpan Elapsed, int FrameSlotIndex );
-/// 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.
-public sealed class FrameRenderer : IDisposable {
- private readonly int _thread = Environment.CurrentManagedThreadId;
- private readonly GraphicsDevice _device;
- private readonly WindowRenderOptions _options;
- private readonly CommandQueue _queue;
- private readonly SwapChain _swap;
- private readonly DescriptorHeap _heap;
- private readonly FrameSlot[] _slots;
- private readonly GpuResource?[] _buffers;
- private readonly RenderTargetView[] _targets;
- private DepthTarget? _depth;
- private Size _size;
- private bool _rendering, _disposed;
- private Task? _drain;
- /// Current presentation totals.
- public RenderStatistics Statistics { get; private set; }
-
- /// Creates presentation resources for an externally owned live HWND.
- public FrameRenderer( GraphicsDevice device, nint window, WindowRenderOptions options ) {
- 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) );
- _device = device; _options = options; _size = options.ClientSize;
- _queue = device.CreateCommandQueue( );
- var owners = new List( );
- try {
- _swap = 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] ); }
- _buffers = new GpuResource?[_swap.BufferCount]; _targets = new RenderTargetView[_swap.BufferCount];
- AcquireBuffers( );
- } catch {
- _depth?.Dispose( );
- if ( _buffers is not null ) foreach ( var b in _buffers ) b?.Dispose( );
- for ( int i = owners.Count - 1; i >= 0; --i ) owners[i].Dispose( );
- _queue.Dispose( ); throw;
- }
- }
-
- /// Records and presents one frame. Zero-sized/minimized surfaces are skipped. Nested calls return false.
- public bool Render( Size size, TimeSpan elapsed, Action draw ) {
- CheckThread( ); ObjectDisposedException.ThrowIf( _disposed, this ); ArgumentNullException.ThrowIfNull( draw );
- if ( _drain is not null ) throw new InvalidOperationException( "Presentation is draining." );
- if ( _rendering || size.Width <= 0 || size.Height <= 0 ) return false;
- _rendering = true;
- try {
- if ( size != _size ) {
- _queue.WaitIdle( ); ReleaseBuffers( );
- _swap.Resize( (uint)size.Width, (uint)size.Height ); _size = size; AcquireBuffers( );
- Statistics = Statistics with { Resizes = Statistics.Resizes + 1 };
- }
- int slotIndex = Statistics.Frames % _slots.Length; var slot = _slots[slotIndex];
- if ( slot.Completion != 0 ) _queue.Wait( slot.Completion );
- var commands = slot.Begin( ); uint index = _swap.CurrentBackBufferIndex;
- var buffer = _buffers[index]!; var target = _targets[index];
- commands.Transition( buffer, ResourceState.Present, ResourceState.RenderTarget );
- commands.SetViewport( (uint)size.Width, (uint)size.Height );
- var c = _options.ClearColor; commands.Clear( target, c.X, c.Y, c.Z, c.W );
- if ( _depth is null ) commands.SetRenderTarget( target ); else commands.SetRenderTarget( target, _depth, clearDepth: true );
- draw( new( commands, target, size, elapsed, slotIndex ) );
- commands.Transition( buffer, ResourceState.RenderTarget, ResourceState.Present ); commands.Close( );
- slot.Completion = _queue.Submit( commands );
- if ( _slots.Length == 1 ) _queue.Wait( slot.Completion );
- _swap.Present( ); Statistics = Statistics with { Frames = Statistics.Frames + 1 }; return true;
- } finally { _rendering = false; }
- }
- /// Starts draining on a worker so the UI host can continue dispatching messages until completion.
- public Task BeginDrain( ) {
- CheckThread( ); ObjectDisposedException.ThrowIf( _disposed, this );
- if ( _rendering ) throw new InvalidOperationException( "Cannot drain during recording or presentation." );
- return _drain ??= Task.Run( _queue.WaitIdle );
- }
- private void CheckThread( ) { if ( Environment.CurrentManagedThreadId != _thread ) throw new InvalidOperationException( "The frame renderer is owned by another thread." ); }
- private void AcquireBuffers( ) {
- for ( uint i = 0; i < _swap.BufferCount; ++i ) {
- _buffers[i] = _swap.AcquireBackBuffer( i ); _targets[i] = _device.CreateRenderTargetView( _buffers[i]!, _heap, i );
- }
- if ( _options.EnableDepth ) _depth = _device.CreateDepthTarget( (uint)_size.Width, (uint)_size.Height );
- }
- private void ReleaseBuffers( ) {
- _depth?.Dispose( ); _depth = null;
- foreach ( var buffer in _buffers ) buffer?.Dispose( ); Array.Clear( _buffers ); Array.Clear( _targets );
- }
- /// Drains and releases presentation resources. The caller keeps the HWND alive during this operation.
- public void Dispose( ) {
- CheckThread( ); if ( _disposed ) return;
- BeginDrain( ).GetAwaiter( ).GetResult( );
- foreach ( var slot in _slots ) slot.Dispose( ); ReleaseBuffers( ); _swap.Dispose( ); _heap.Dispose( ); _queue.Dispose( ); _disposed = true;
- }
- private sealed class FrameSlot : IDisposable {
- private readonly CommandAllocator _allocator;
- private readonly GraphicsCommandList _commands;
- internal ulong Completion;
- internal FrameSlot( GraphicsDevice device ) {
- _allocator = device.CreateCommandAllocator( );
- try { _commands = device.CreateCommandList( _allocator ); try { _commands.Close( ); } catch { _commands.Dispose( ); throw; } }
- catch { _allocator.Dispose( ); throw; }
- }
- internal GraphicsCommandList Begin( ) { _allocator.Reset( ); _commands.Reset( _allocator ); return _commands; }
- public void Dispose( ) { _commands.Dispose( ); _allocator.Dispose( ); }
- }
-}
diff --git a/src/DXSharp.Framework/Hosting/NativeGame.cs b/src/DXSharp.Framework/Hosting/NativeGame.cs
deleted file mode 100644
index 1992304..0000000
--- a/src/DXSharp.Framework/Hosting/NativeGame.cs
+++ /dev/null
@@ -1,149 +0,0 @@
-using System.ComponentModel;
-using System.Diagnostics;
-using System.Drawing;
-using System.Runtime.CompilerServices;
-using System.Runtime.ExceptionServices;
-using System.Runtime.InteropServices;
-using DXSharp.Graphics;
-using Windows.Win32;
-using Windows.Win32.Foundation;
-using Windows.Win32.UI.HiDpi;
-using Windows.Win32.UI.WindowsAndMessaging;
-
-namespace DXSharp.Framework.Hosting;
-
-/// A thread-owned Win32 window without Windows Forms. Its handle is borrowed; close through RequestClose.
-public sealed unsafe class NativeGameWindow : IDisposable {
- private readonly int _thread = Environment.CurrentManagedThreadId;
- private readonly string _className = "DXSharp." + Guid.NewGuid( ).ToString( "N" );
- private readonly HINSTANCE _instance;
- private GCHandle _root;
- private HWND _window;
- private ushort _atom;
- private string _title;
- private Exception? _failure;
- private const WINDOW_STYLE Style = WINDOW_STYLE.WS_OVERLAPPEDWINDOW;
- /// Borrowed native handle, valid until disposal.
- public nint Handle => (nint)_window.Value;
- /// Whether the host should drain rendering and then destroy the window.
- public bool CloseRequested { get; private set; }
- /// Whether the window is minimized.
- public bool IsMinimized => PInvoke.IsIconic( _window );
- /// Current physical client size.
- public Size ClientSize {
- get { Check( PInvoke.GetClientRect( _window, out var rect ) ); return new( rect.right - rect.left, rect.bottom - rect.top ); }
- }
- /// Gets or sets the title on the creating thread.
- public string Title {
- get => _title;
- set { CheckThread( ); ArgumentNullException.ThrowIfNull( value ); Check( PInvoke.SetWindowTextW( _window, value ) ); _title = value; }
- }
- internal NativeGameWindow( WindowRenderOptions options ) {
- _title = options.Title;
- _instance = new HINSTANCE( NativeLibrary.GetMainProgramHandle( ) );
- _root = GCHandle.Alloc( this );
- try {
- fixed ( char* className = _className ) fixed ( char* title = _title ) {
- WNDCLASSEXW wc = new( ) { cbSize = (uint)sizeof(WNDCLASSEXW), lpfnWndProc = &WindowProc, hInstance = _instance,
- lpszClassName = new PCWSTR( className ), hCursor = PInvoke.LoadCursorW( default, new PCWSTR( (char*)32512 ) ) };
- _atom = PInvoke.RegisterClassExW( wc ); if ( _atom == 0 ) throw new Win32Exception( );
- RECT rect = new( ) { right = options.ClientSize.Width, bottom = options.ClientSize.Height };
- Check( PInvoke.AdjustWindowRectExForDpi( ref rect, Style, false, 0, PInvoke.GetDpiForSystem( ) ) );
- _window = PInvoke.CreateWindowExW( 0, new PCWSTR( className ), new PCWSTR( title ), Style,
- unchecked((int)0x80000000), unchecked((int)0x80000000), rect.right-rect.left, rect.bottom-rect.top,
- default, default, _instance, (void*)GCHandle.ToIntPtr( _root ) );
- if ( _window.IsNull ) throw new Win32Exception( );
- }
- PInvoke.ShowWindow( _window, SHOW_WINDOW_CMD.SW_SHOW );
- } catch { Dispose( ); throw; }
- }
- /// Requests orderly shutdown. The HWND remains alive until its renderer drains.
- public void RequestClose( ) { CheckThread( ); CloseRequested = true; }
- /// Changes the client size in physical pixels on the creating thread.
- public void ResizeClient( Size size ) {
- CheckThread( );
- if ( size.Width <= 0 || size.Height <= 0 ) throw new ArgumentOutOfRangeException( nameof(size) );
- RECT rect = new( ) { right = size.Width, bottom = size.Height };
- Check( PInvoke.AdjustWindowRectExForDpi( ref rect, Style, false, 0, PInvoke.GetDpiForWindow( _window ) ) );
- Check( PInvoke.SetWindowPos( _window, default, 0, 0, rect.right-rect.left, rect.bottom-rect.top,
- SET_WINDOW_POS_FLAGS.SWP_NOMOVE | SET_WINDOW_POS_FLAGS.SWP_NOZORDER | SET_WINDOW_POS_FLAGS.SWP_NOACTIVATE ) );
- }
- internal void Pump( bool reportErrors = true ) {
- while ( PInvoke.PeekMessageW( out var message, default, 0, 0, PEEK_MESSAGE_REMOVE_TYPE.PM_REMOVE ) ) {
- if ( message.message == 0x12 ) { RequestClose( ); continue; }
- PInvoke.TranslateMessage( message ); PInvoke.DispatchMessageW( message );
- }
- if ( reportErrors && _failure is not null ) ExceptionDispatchInfo.Capture( _failure ).Throw( );
- }
- internal static void WaitForMessages( ) => PInvoke.MsgWaitForMultipleObjectsEx( 0, null, 16, QUEUE_STATUS_FLAGS.QS_ALLINPUT, MSG_WAIT_FOR_MULTIPLE_OBJECTS_EX_FLAGS.MWMO_INPUTAVAILABLE );
- [UnmanagedCallersOnly( CallConvs = [typeof(CallConvStdcall)] )]
- private static LRESULT WindowProc( HWND hwnd, uint message, WPARAM wparam, LPARAM lparam ) {
- NativeGameWindow? window = null;
- try {
- if ( message == 0x81 ) {
- var create = (CREATESTRUCTW*)lparam.Value;
- PInvoke.SetWindowLongPtrW( hwnd, WINDOW_LONG_PTR_INDEX.GWLP_USERDATA, (nint)create->lpCreateParams );
- }
- nint token = PInvoke.GetWindowLongPtrW( hwnd, WINDOW_LONG_PTR_INDEX.GWLP_USERDATA );
- if ( token != 0 ) window = GCHandle.FromIntPtr( token ).Target as NativeGameWindow;
- switch ( message ) {
- case 0x10: window?.RequestClose( ); return default;
- case 0x14: return new LRESULT( 1 ); // The renderer owns the full client area.
- case 0x201: case 0x207: PInvoke.SetCapture( hwnd ); break;
- case 0x202: case 0x208: PInvoke.ReleaseCapture( ); break;
- case 0x2E0:
- var r = (RECT*)lparam.Value;
- PInvoke.SetWindowPos( hwnd, default, r->left, r->top, r->right-r->left, r->bottom-r->top,
- SET_WINDOW_POS_FLAGS.SWP_NOZORDER | SET_WINDOW_POS_FLAGS.SWP_NOACTIVATE ); return default;
- case 0x82: PInvoke.SetWindowLongPtrW( hwnd, WINDOW_LONG_PTR_INDEX.GWLP_USERDATA, 0 ); break;
- }
- return PInvoke.DefWindowProcW( hwnd, message, wparam, lparam );
- } catch ( Exception error ) {
- if ( window is not null ) { window._failure = error; window.RequestClose( ); }
- return default; // Never unwind a managed exception through USER32.
- }
- }
- private void CheckThread( ) { if ( Environment.CurrentManagedThreadId != _thread ) throw new InvalidOperationException( "The native window is owned by another thread." ); }
- private static void Check( BOOL success ) { if ( !success ) throw new Win32Exception( Marshal.GetLastPInvokeError( ) ); }
- /// Destroys the window after its presentation work has drained.
- public void Dispose( ) {
- CheckThread( );
- if ( !_window.IsNull ) { Check( PInvoke.DestroyWindow( _window ) ); _window = default; }
- if ( _atom != 0 ) { fixed ( char* name = _className ) PInvoke.UnregisterClassW( new PCWSTR( name ), _instance ); _atom = 0; }
- if ( _root.IsAllocated ) _root.Free( );
- }
-}
-
-/// Native Win32 scheduling over the same renderer used by the managed desktop host.
-public static class NativeGame {
- /// Runs a native HWND without WinForms. UI callbacks run on the caller's thread.
- public static RenderStatistics Run( GraphicsDevice device, WindowRenderOptions options, Action draw,
- Action? presented = null ) {
- ArgumentNullException.ThrowIfNull( device ); ArgumentNullException.ThrowIfNull( options ); ArgumentNullException.ThrowIfNull( draw );
- if ( options.ClientSize.Width <= 0 || options.ClientSize.Height <= 0 ) throw new ArgumentOutOfRangeException( nameof(options) );
- var previousDpi = PInvoke.SetThreadDpiAwarenessContext( new DPI_AWARENESS_CONTEXT( (nint)(-4) ) );
- try {
- using var window = new NativeGameWindow( options );
- using var renderer = new FrameRenderer( device, window.Handle, options with { ClientSize = window.ClientSize } );
- var clock = Stopwatch.StartNew( ); TimeSpan previous = clock.Elapsed;
- try {
- while ( !window.CloseRequested ) {
- window.Pump( );
- if ( window.CloseRequested ) break;
- TimeSpan now = clock.Elapsed;
- if ( window.IsMinimized ) { previous = now; NativeGameWindow.WaitForMessages( ); continue; }
- if ( renderer.Render( window.ClientSize, now - previous, draw ) ) {
- presented?.Invoke( window, renderer.Statistics );
- if ( options.FrameLimit > 0 && renderer.Statistics.Frames >= options.FrameLimit ) window.RequestClose( );
- } else NativeGameWindow.WaitForMessages( );
- previous = now;
- }
- return renderer.Statistics;
- } finally {
- var drain = renderer.BeginDrain( );
- while ( !drain.IsCompleted ) { window.Pump( false ); NativeGameWindow.WaitForMessages( ); }
- drain.GetAwaiter( ).GetResult( );
- }
- } finally { if ( !previousDpi.IsNull ) PInvoke.SetThreadDpiAwarenessContext( previousDpi ); }
- }
-}
diff --git a/src/DXSharp.Native/NativeMethods.txt b/src/DXSharp.Native/NativeMethods.txt
index 2cc4fbc..fef7c63 100644
--- a/src/DXSharp.Native/NativeMethods.txt
+++ b/src/DXSharp.Native/NativeMethods.txt
@@ -37,7 +37,3 @@ PeekMessage
GetAsyncKeyState
GetActiveWindow
GetCursorPos
-
-Windows.Win32.UI.WindowsAndMessaging
-Windows.Win32.UI.HiDpi
-Windows.Win32.UI.Input.KeyboardAndMouse
diff --git a/tests/InteropQualification/HostShaderQualification.cs b/tests/InteropQualification/HostShaderQualification.cs
deleted file mode 100644
index f68164a..0000000
--- a/tests/InteropQualification/HostShaderQualification.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-using DXSharp.Framework.Hosting;
-using DXSharp.Graphics;
-using DXSharp.Shaders;
-using Windows.Win32;
-using Windows.Win32.Foundation;
-
-namespace InteropQualification;
-
-internal static class HostShaderQualification {
- internal static void Run() {
- using var device = GraphicsDevice.Create(new() { UseWarp = true });
- string folder = Path.Combine(Path.GetTempPath(), "dxsharp include " + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(folder);
- try {
- string source = Path.Combine(folder, "test.hlsl");
- File.WriteAllText(Path.Combine(folder, "value.hlsli"), "#define VALUE 7\n");
- File.WriteAllText(source, "#include \"value.hlsli\"\nRWStructuredBuffer Data:register(u0);[numthreads(1,1,1)]void CS(){Data[0]=VALUE+EXTRA;}");
- using var compiler = new ShaderCompiler();
- var result = compiler.CompileFile(source, new() { Profile = "cs_6_0", EntryPoint = "CS", Defines = ["EXTRA=3"], DebugInformation = true }).RequireSuccess();
- var input = result.Bytecode.ToArray(); var bytecode = ShaderBytecode.CopyFrom(input); input[0] = 0;
- if (bytecode.Bytes.Span[0] != 'D') throw new InvalidOperationException("Shader bytecode did not own its input.");
- string saved = Path.Combine(folder, "shader.dxil"); bytecode.Save(saved);
- var loaded = ShaderBytecode.Load(saved);
- if (!loaded.Bytes.Span.SequenceEqual(bytecode.Bytes.Span)) throw new InvalidOperationException("Shader bytecode roundtrip failed.");
- using var root = device.CreateRootSignature(1); using var pipeline = device.CreateComputePipeline(root, loaded);
- try { ShaderBytecode.CopyFrom(new byte[32]); throw new InvalidOperationException("Invalid bytecode accepted."); } catch (ArgumentException) { }
- Console.WriteLine("PASS: typed DXC options, filesystem includes, owned shader bytecode, disk roundtrip and precompiled PSO.");
- } finally { Directory.Delete(folder, true); }
-
- nint handle = 0;
- var stats = NativeGame.Run(device, new() { ClientSize = new(320,240), FramesInFlight = 2, FrameLimit = 7 }, _ => { }, (window, value) => {
- handle = window.Handle;
- if (value.Frames == 2) window.ResizeClient(new(400,280));
- });
- if (stats.Frames != 7 || stats.Resizes < 1 || PInvoke.IsWindow(new HWND(handle))) throw new InvalidOperationException("Native presentation/resize/teardown failed.");
- bool propagated = false;
- try { NativeGame.Run(device, new() { ClientSize = new(160,120), FrameLimit = 2 }, _ => throw new ApplicationException("intentional render failure")); }
- catch (ApplicationException error) when (error.Message == "intentional render failure") { propagated = true; }
- if (!propagated) throw new InvalidOperationException("Native render exception was not propagated.");
- var closed = NativeGame.Run(device, new() { ClientSize = new(160,120) }, _ => { }, (window, _) => window.RequestClose());
- if (closed.Frames != 1) throw new InvalidOperationException("Native close/drain failed.");
- var diagnostics = device.GetDiagnostics();
- if (diagnostics.DeviceRemovedReason < 0 || diagnostics.Messages.Any(x => x.Contains("SEVERITY_ERROR") || x.Contains("SEVERITY_CORRUPTION")))
- throw new InvalidOperationException("Native host emitted device errors: " + string.Join(Environment.NewLine, diagnostics.Messages));
- Console.WriteLine("PASS: native Win32 presentation, resize, frame-slot reuse, render failure, close/drain and HWND teardown.");
- }
-}
diff --git a/tests/InteropQualification/Program.cs b/tests/InteropQualification/Program.cs
index e2df722..4decbf0 100644
--- a/tests/InteropQualification/Program.cs
+++ b/tests/InteropQualification/Program.cs
@@ -165,7 +165,7 @@ public static unsafe int Main( ) {
AssetQualification.Run( );
CharacterQualification.RunPortable();
FleetQualification.Run( );
- if ( OperatingSystem.IsWindows( ) ) { FeatureQueryQualification.Run(); HostShaderQualification.Run(); MeshQualification.Run( ); }
+ if ( OperatingSystem.IsWindows( ) ) { FeatureQueryQualification.Run(); MeshQualification.Run( ); }
Console.WriteLine( $"PASS: {_checks} checks; {Native.Destroyed( )} native objects destroyed; no live objects." );
return 0;
} catch ( Exception exception ) { Console.Error.WriteLine( exception ); return 1; }
diff --git a/tools/ApiCoverage/Program.cs b/tools/ApiCoverage/Program.cs
index e2ddff0..e58d12d 100644
--- a/tools/ApiCoverage/Program.cs
+++ b/tools/ApiCoverage/Program.cs
@@ -59,10 +59,7 @@
"Windows.Win32.Graphics.DirectComposition",
"Windows.Win32.UI.Input.XboxController",
"Windows.Win32.UI.Input.GameInput",
- "Windows.Win32.Storage.DirectStorage",
- "Windows.Win32.UI.WindowsAndMessaging",
- "Windows.Win32.UI.HiDpi",
- "Windows.Win32.UI.Input.KeyboardAndMouse"
+ "Windows.Win32.Storage.DirectStorage"
];
var exportedFunctions = new HashSet( StringComparer.Ordinal );
diff --git a/tools/DXSharp.Tools.Builds/DXSharp.Tools.Builds.csproj b/tools/DXSharp.Tools.Builds/DXSharp.Tools.Builds.csproj
index 50ef8d7..08a0266 100644
--- a/tools/DXSharp.Tools.Builds/DXSharp.Tools.Builds.csproj
+++ b/tools/DXSharp.Tools.Builds/DXSharp.Tools.Builds.csproj
@@ -1,21 +1,8 @@
-
+
netstandard2.0
-
- falsefalsefalse
- false
-
- $(NoWarn);NU5100;NU5128
- truefalse
- Incremental DXC shader compilation for SDK-style MSBuild projects.
-
-
-
-
-
-
diff --git a/tools/DXSharp.Tools.Builds/Shaders/DxcTaskFactory.cs b/tools/DXSharp.Tools.Builds/Shaders/DxcTaskFactory.cs
new file mode 100644
index 0000000..3e1b581
--- /dev/null
+++ b/tools/DXSharp.Tools.Builds/Shaders/DxcTaskFactory.cs
@@ -0,0 +1,54 @@
+using System ;
+using System.Linq ;
+using System.Collections.Generic ;
+using Microsoft.Build.Framework ;
+using Microsoft.Build.Utilities ;
+using MSBuildTask = Microsoft.Build.Utilities.Task ;
+
+namespace DXSharp.Tools.Builds.Shaders {
+
+ public class DxcTaskFactory: ITaskFactory2 {
+ IDictionary< string, TaskPropertyInfo > parameterGroup ;
+ IBuildEngine buildEngine ;
+ string taskBody ;
+
+ public string FactoryName => nameof( DxcTaskFactory ) ;
+ public Type TaskType => typeof( DxcTool ) ;
+
+ public bool Initialize( string taskName, IDictionary< string, TaskPropertyInfo > _parameterGroup,
+ string _taskBody, IBuildEngine taskFactoryLoggingHost ) {
+ this.parameterGroup = _parameterGroup;
+ this.taskBody = _taskBody;
+ this.buildEngine = taskFactoryLoggingHost;
+
+ return true;
+ }
+
+ public TaskPropertyInfo[ ] GetTaskParameters( ) {
+ return parameterGroup.Values.ToArray( ) ;
+ }
+
+ public ITask CreateTask( IBuildEngine taskFactoryLoggingHost ) {
+ return new DxcTool( ) ;
+ }
+
+ public void CleanupTask( ITask task ) {
+ // Custom cleanup logic goes here
+ }
+
+ public bool Initialize( string taskName, IDictionary< string, string > factoryIdentityParameters,
+ IDictionary< string, TaskPropertyInfo > _parameterGroup, string _taskBody,
+ IBuildEngine taskFactoryLoggingHost ) {
+ this.parameterGroup = _parameterGroup ;
+ this.taskBody = _taskBody ;
+ this.buildEngine = taskFactoryLoggingHost ;
+
+ return true;
+ }
+
+ public ITask CreateTask( IBuildEngine taskFactoryLoggingHost,
+ IDictionary< string, string > taskIdentityParameters) {
+ return new DxcTool( ) ;
+ }
+ }
+}
diff --git a/tools/DXSharp.Tools.Builds/Shaders/DxcTool.cs b/tools/DXSharp.Tools.Builds/Shaders/DxcTool.cs
index 92636fd..336d79f 100644
--- a/tools/DXSharp.Tools.Builds/Shaders/DxcTool.cs
+++ b/tools/DXSharp.Tools.Builds/Shaders/DxcTool.cs
@@ -1,140 +1,230 @@
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.IO;
-using System.Linq;
-using System.Security.Cryptography;
-using System.Text;
-using System.Text.RegularExpressions;
-using System.Xml.Linq;
-using Microsoft.Build.Framework;
-using Microsoft.Build.Utilities;
+using System ;
+using System.IO ;
+using System.Linq ;
+using System.Collections ;
+using System.Collections.Generic ;
+using System.Collections.ObjectModel ;
+using Microsoft.Build.Framework ;
+using Microsoft.Build.Utilities ;
+using MSBuildTask = Microsoft.Build.Utilities.Task ;
-namespace DXSharp.Tools.Builds.Shaders;
+namespace DXSharp.Tools.Builds.Shaders {
-/// Compiles every supplied shader using a pinned DXC executable and content-based incremental state.
-public sealed class DxcTool : Microsoft.Build.Utilities.Task {
- /// HLSL sources with Profile, EntryPoint, OutputFile, Defines and IncludeDirectories metadata.
- [Required] public ITaskItem[] ShaderFiles { get; set; } = Array.Empty();
- /// Absolute path to the selected compiler executable.
- [Required] public string CompilerPath { get; set; } = string.Empty;
- /// Project-relative paths are resolved against this directory.
- [Required] public string ProjectDirectory { get; set; } = string.Empty;
- /// Emit shader PDBs and disable optimization.
- public bool DebugShaders { get; set; }
- /// Promote compiler warnings to build errors.
- public bool WarningsAsErrors { get; set; }
- /// Successfully compiled or up-to-date output containers.
- [Output] public ITaskItem[] Outputs { get; private set; } = Array.Empty();
- private static readonly Regex Lines = new Regex("^#(?:line)?\\s+\\d+\\s+\"([^\"]+)\"", RegexOptions.Multiline);
+/* NOTES:
+ * The command-line arguments for dxc.exe take the form of:
+ * dxc.exe [options]
+ */
- ///
- public override bool Execute() {
- var outputs = new List();
- try {
- CompilerPath = Path.GetFullPath(CompilerPath);
- if (!File.Exists(CompilerPath)) throw new FileNotFoundException("The pinned DXC executable was not found: " + CompilerPath, CompilerPath);
- var compiler = new StringBuilder(HashFile(CompilerPath));
- foreach (var name in new[] { "dxcompiler.dll", "dxil.dll", "../lib/libdxcompiler.so", "../lib/libdxil.so" }) {
- string path = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(CompilerPath)!, name));
- if (File.Exists(path)) compiler.Append(HashFile(path));
- }
- var occupied = new HashSet(StringComparer.OrdinalIgnoreCase);
- foreach (var item in ShaderFiles) {
- string path = Absolute(item.GetMetadata("OutputFile"));
- if (!occupied.Add(path)) throw new InvalidOperationException("Multiple shader items have the same output: " + path);
- }
- foreach (var item in ShaderFiles) {
- try { outputs.Add(Compile(item, compiler.ToString())); }
- catch (Exception error) { Log.LogErrorFromException(error, false); }
- }
- } catch (Exception error) { Log.LogErrorFromException(error, false); }
- Outputs = outputs.ToArray(); return !Log.HasLoggedErrors;
- }
- private ITaskItem Compile(ITaskItem item, string compiler) {
- string source = Absolute(item.ItemSpec), output = Absolute(item.GetMetadata("OutputFile"));
- string profile = item.GetMetadata("Profile"), entry = item.GetMetadata("EntryPoint");
- if (string.IsNullOrWhiteSpace(profile)) throw new ArgumentException("Shader Profile is required: " + source);
- if (!profile.StartsWith("lib_", StringComparison.Ordinal) && string.IsNullOrWhiteSpace(entry)) throw new ArgumentException("Shader EntryPoint is required: " + source);
- Directory.CreateDirectory(Path.GetDirectoryName(output)!);
- var args = new List { source, "-T", profile, "-HV", "2021" };
- if (!string.IsNullOrWhiteSpace(entry)) { args.Add("-E"); args.Add(entry); }
- foreach (var value in Split(item.GetMetadata("Defines"))) { args.Add("-D"); args.Add(value); }
- foreach (var value in Split(item.GetMetadata("IncludeDirectories"))) { args.Add("-I"); args.Add(Absolute(value)); }
- args.AddRange(Split(item.GetMetadata("AdditionalArguments")));
- string temporary = output + ".tmp-" + Guid.NewGuid().ToString("N");
- string preprocess = temporary + ".hlsl", state = output + ".state", pdb = output + ".pdb", manifest = output + ".xml";
- try {
- // DXC performs include/macro resolution on every build. Hashing its preprocessed result also
- // catches macro includes, transitive edits, deletion and include-path shadowing, including spaces.
- Invoke(args.Concat(new[] { "-P", "-Fi", preprocess }));
- string text = File.ReadAllText(preprocess);
- string fingerprint = Hash(compiler + "\n" + string.Join("\n", args) + "\n" + DebugShaders + WarningsAsErrors + "\n" + text);
- string existing = File.Exists(state) ? File.ReadAllText(state) : string.Empty;
- bool current = File.Exists(output) && File.Exists(manifest) && (!DebugShaders || File.Exists(pdb)) &&
- existing == fingerprint + "\n" + HashFile(output);
- if (!current) {
- var compile = new List(args) { "-Fo", temporary };
- if (DebugShaders) compile.AddRange(new[] { "-Zi", "-Od", "-Fd", pdb }); else compile.Add("-O3");
- if (WarningsAsErrors) compile.Add("-WX");
- Invoke(compile);
- if (!File.Exists(temporary) || new FileInfo(temporary).Length < 32) throw new InvalidDataException("DXC produced no shader container: " + source);
- // Invalidate incremental state before replacing output. A failed build never becomes up-to-date.
- if (File.Exists(state)) File.Delete(state);
- File.Copy(temporary, output, true);
- var dependencies = new HashSet(StringComparer.OrdinalIgnoreCase) { source };
- foreach (Match match in Lines.Matches(text)) {
- string path = match.Groups[1].Value.Replace("\\\\", "\\");
- if (path.StartsWith("<", StringComparison.Ordinal)) continue;
- path = Absolute(path); if (File.Exists(path)) dependencies.Add(path);
- }
- new XDocument(new XElement("Shader", new XAttribute("Source", source), new XAttribute("Profile", profile),
- new XAttribute("EntryPoint", entry), new XAttribute("CompilerFingerprint", compiler), new XAttribute("Fingerprint", fingerprint),
- dependencies.OrderBy(x => x, StringComparer.Ordinal).Select(x => new XElement("Dependency", new XAttribute("Path", x), new XAttribute("Sha256", HashFile(x)))))).Save(manifest);
- File.WriteAllText(state, fingerprint + "\n" + HashFile(output));
- if (!DebugShaders && File.Exists(pdb)) File.Delete(pdb);
- Log.LogMessage(MessageImportance.High, "DXC compiled: {0} ({1}, {2})", source, entry, profile);
- } else Log.LogMessage(MessageImportance.High, "DXC up-to-date: {0} ({1}, {2})", source, entry, profile);
- var result = new TaskItem(output); result.SetMetadata("LogicalName", item.GetMetadata("LogicalName"));
- result.SetMetadata("TargetPath", item.GetMetadata("TargetPath")); return result;
- } finally {
- if (File.Exists(temporary)) File.Delete(temporary);
- if (File.Exists(preprocess)) File.Delete(preprocess);
- }
- }
- private void Invoke(IEnumerable args) {
- string command = string.Join(" ", args.Select(Quote));
- using (var process = new Process()) {
- process.StartInfo = new ProcessStartInfo(CompilerPath, command.ToString()) { UseShellExecute = false,
- RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true, WorkingDirectory = ProjectDirectory };
- process.Start(); var stdout = process.StandardOutput.ReadToEndAsync(); var stderr = process.StandardError.ReadToEndAsync();
- if (!process.WaitForExit(120000)) { process.Kill(); process.WaitForExit(); throw new TimeoutException("DXC exceeded two minutes."); }
- string text = stdout.GetAwaiter().GetResult() + stderr.GetAwaiter().GetResult();
- foreach (string line in text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)) {
- var match = Regex.Match(line, @"^(.*?):(\d+):(\d+):\s*(warning|error):\s*(.*)$");
- if (match.Success) {
- int row = int.Parse(match.Groups[2].Value), col = int.Parse(match.Groups[3].Value);
- if (match.Groups[4].Value == "error" || WarningsAsErrors) Log.LogError(null, "DXSHADER", null, match.Groups[1].Value, row, col, 0, 0, match.Groups[5].Value);
- else Log.LogWarning(null, "DXSHADER", null, match.Groups[1].Value, row, col, 0, 0, match.Groups[5].Value);
- } else Log.LogMessage(MessageImportance.Normal, line);
- }
- if (process.ExitCode != 0) throw new InvalidOperationException("DXC failed with exit code " + process.ExitCode + ": " + text);
- }
- }
- private static string Quote(string value) {
- if (value.Length != 0 && !value.Any(c => char.IsWhiteSpace(c) || c == '"')) return value;
- var result = new StringBuilder("\""); int slashes = 0;
- foreach (char c in value) {
- if (c == '\\') { ++slashes; continue; }
- result.Append('\\', c == '"' ? slashes * 2 + 1 : slashes); result.Append(c); slashes = 0;
- }
- result.Append('\\', slashes * 2); return result.Append('"').ToString();
- }
- private string Absolute(string path) {
- if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException("A shader path is empty.");
- return Path.GetFullPath(Path.IsPathRooted(path) ? path : Path.Combine(ProjectDirectory, path));
- }
- private static IEnumerable Split(string value) => value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).Where(x => x.Length != 0);
- private static string Hash(string value) { using (var sha = SHA256.Create()) return Convert.ToBase64String(sha.ComputeHash(Encoding.UTF8.GetBytes(value))); }
- private static string HashFile(string path) { using (var sha = SHA256.Create()) using (var stream = File.OpenRead(path)) return Convert.ToBase64String(sha.ComputeHash(stream)); }
-}
+public class DxcTool: MSBuildTask {
+ public static class ErrorCodes {
+ public const int Success = 0, InvalidArguments = -1, CompilationFailed = -2, InternalError = -3,
+ InvalidBytecode = -4, ValidationFailed = -5, InvalidOperation = -6,
+ OutOfMemory = -7, InvalidState = 8, InvalidFile = -9 ;
+ }
+
+
+ public static class Info {
+ public const string TOOLNAME = "dxc.exe" ;
+ public const string OVERVIEW = "HLSL Compiler" ;
+ static readonly string[ ] DLLs = { "dxcompiler.dll", //! As of 11/23/23: 1.5 - 10.0.19041.1
+ "dxil.dll" } ; //! As of 11/23/23: 1.5 - 10.0.19041.1
+ public static string[ ] DllNames => DLLs.ToArray( ) ;
+ public const string USAGE = "dxc.exe [options] " ;
+ static readonly string[ ] _profileStrings = {
+ "ps_6_0", "ps_6_1", "ps_6_2", "ps_6_3", "ps_6_4", "ps_6_5",
+ "vs_6_0", "vs_6_1", "vs_6_2", "vs_6_3", "vs_6_4", "vs_6_5",
+ "cs_6_0", "cs_6_1", "cs_6_2", "cs_6_3", "cs_6_4", "cs_6_5",
+ "gs_6_0", "gs_6_1", "gs_6_2", "gs_6_3", "gs_6_4", "gs_6_5",
+ "ds_6_0", "ds_6_1", "ds_6_2", "ds_6_3", "ds_6_4", "ds_6_5",
+ "hs_6_0", "hs_6_1", "hs_6_2", "hs_6_3", "hs_6_4", "hs_6_5",
+ "lib_6_3", "lib_6_4", "lib_6_5", "ms_6_5", "as_6_5",
+ } ;
+ public static readonly ReadOnlyDictionary< string, string > CommonOptions =
+ new( new Dictionary< string, string >( ) {
+ { "-help", "Display available options" },
+ { "-nologo", "Suppress copyright message" },
+ { "-Qunused-arguments", "Don't emit warning for unused driver arguments" },
+ } );
+ public static readonly ReadOnlyDictionary< string, string > OptimizationOptions =
+ new( new Dictionary< string, string >( ) {
+ { "-O0", "Optimization Level 0" },
+ { "-O1", "Optimization Level 1" },
+ { "-O2", "Optimization Level 2" },
+ { "-O3", "Optimization Level 3 (Default)" },
+ } );
+ public static readonly ReadOnlyDictionary< string, string > UtilityOptions =
+ new( new Dictionary< string, string >( ) {
+ { "-dumpbin", "Load a binary file rather than compiling" },
+ { "-extractrootsignature", "Extract root signature from shader bytecode (must be used with /Fo )" },
+ { "-getprivate ", "Save private data from shader blob" },
+ { "-P ", "Preprocess to file (must be used alone)" },
+ { "-Qembed_debug", "Embed PDB in shader container (must be used with /Zi)" },
+ { "-Qstrip_debug", "Strip debug information from 4_0+ shader bytecode (must be used with /Fo )" },
+ { "-Qstrip_priv", "Strip private data from shader bytecode (must be used with /Fo )" },
+ { "-Qstrip_reflect", "Strip reflection data from shader bytecode (must be used with /Fo )" },
+ { "-Qstrip_rootsignature", "Strip root signature data from shader bytecode (must be used with /Fo )" },
+ { "-setprivate ", "Private data to add to compiled shader blob" },
+ { "-setrootsignature ", "Attach root signature to shader bytecode" },
+ { "-verifyrootsignature ", "Verify shader bytecode with root signature" },
+ } );
+ public static readonly ReadOnlyDictionary< string, string > SPIRVCodeGenerationOptions = new(
+ new Dictionary< string, string >( ) {
+ { "-fspv-debug=", "Specify whitelist of debug info category (file -> source -> line, tool)" },
+ { "-fspv-extension=", "Specify SPIR-V extension permitted to use" },
+ { "-fspv-flatten-resource-arrays", "Flatten arrays of resources so each array element takes one binding number" },
+ { "-fspv-reflect", "Emit additional SPIR-V instructions to aid reflection" },
+ { "-fspv-target-env=", "Specify the target environment: vulkan1.0 (default) or vulkan1.1" },
+ { "-fvk-b-shift ", "Specify Vulkan binding number shift for b-type register" },
+ { "-fvk-bind-globals ", "Specify Vulkan binding number and set number for the $Globals cbuffer" },
+ { "-fvk-bind-register ", "Specify Vulkan descriptor set and binding for a specific register" },
+ { "-fvk-invert-y", "Negate SV_Position.y before writing to stage output in VS/DS/GS to accommodate Vulkan's coordinate system" },
+ { "-fvk-s-shift ", "Specify Vulkan binding number shift for s-type register" },
+ { "-fvk-t-shift ", "Specify Vulkan binding number shift for t-type register" },
+ { "-fvk-u-shift ", "Specify Vulkan binding number shift for u-type register" },
+ { "-fvk-use-dx-layout", "Use DirectX memory layout for Vulkan resources" },
+ { "-fvk-use-dx-position-w", "Reciprocate SV_Position.w after reading from stage input in PS to accommodate the difference between Vulkan and DirectX" },
+ { "-fvk-use-gl-layout", "Use strict OpenGL std140/std430 memory layout for Vulkan resources" },
+ { "-fvk-use-scalar-layout", "Use scalar memory layout for Vulkan resources" },
+ { "-Oconfig=", "Specify a comma-separated list of SPIRV-Tools passes to customize optimization configuration (see http://khr.io/hlsl2spirv#optimization)" },
+ { "-spirv", "Generate SPIR-V code" },
+ } ) ;
+ public static readonly ReadOnlyDictionary< string, string > CompilationOptions = new (
+ new Dictionary< string, string >( ) {
+ { "-all_resources_bound", "Enables agressive flattening" },
+ { "-auto-binding-space ", "Set auto binding space - enables auto resource binding in libraries" },
+ { "-Cc", "Output color coded assembly listings" },
+ { "-default-linkage ", "Set default linkage for non-shader functions when compiling or linking to a library target (internal, external)" },
+ { "-denorm ", "Select denormal value options (any, preserve, ftz). any is the default." },
+ // Previous items...
+ { "-D ", "Define macro" },
+ { "-enable-16bit-types", "Enable 16bit types and disable min precision types. Available in HLSL 2018 and shader model 6.2" },
+ { "-export-shaders-only", "Only export shaders when compiling a library" },
+ { "-exports ", "Specify exports when compiling a library: export1[[,export1_clone,...]=internal_name][;...]" },
+ { "-E ", "Entry point name" },
+ { "-Fc ", "Output assembly code listing file" },
+ { "-Fd ", "Write debug information to the given file, or automatically named file in directory when ending in '\\'" },
+ // Previous items...
+ { "-Fe ", "Output warnings and errors to the given file" },
+ { "-Fh ", "Output header file containing object code" },
+ { "-flegacy-macro-expansion", "Expand the operands before performing token-pasting operation (fxc behavior)" },
+ { "-flegacy-resource-reservation", "Reserve unused explicit register assignments for compatibility with shader model 5.0 and below" },
+ { "-force_rootsig_ver ", "force root signature version (rootsig_1_1 if omitted)" },
+ { "-Fo ", "Output object file" },
+ { "-Gec", "Enable backward compatibility mode" },
+ { "-Ges", "Enable strict mode" },
+ { "-Gfa", "Avoid flow control constructs" },
+ { "-Gfp", "Prefer flow control constructs" },
+ { "-Gis", "Force IEEE strictness" },
+ { "-HV ", "HLSL version (2016, 2017, 2018). Default is 2018" },
+ { "-H", "Show header includes and nesting depth" },
+ { "-ignore-line-directives", "Ignore line directives" },
+ { "-I ", "Add directory to include search path" },
+ { "-Lx", "Output hexadecimal literals" },
+ { "-Ni", "Output instruction numbers in assembly listings" },
+ { "-no-warnings", "Suppress warnings" },
+ { "-not_use_legacy_cbuf_load", "Do not use legacy cbuffer load" },
+ { "-No", "Output instruction byte offsets in assembly listings" },
+ { "-Odump", "Print the optimizer commands." },
+ { "-Od", "Disable optimizations" },
+ { "-pack_optimized", "Optimize signature packing assuming identical signature provided for each connecting stage" },
+ { "-pack_prefix_stable", "(default) Pack signatures preserving prefix-stable property - appended elements will not disturb placement of prior elements" },
+ { "-recompile", "Recompile from DXIL container with Debug Info or Debug Info bitcode file" },
+ { "-res_may_alias", "Assume that UAVs/SRVs may alias (Allows resources to alias the same register space)" },
+ { "-rootsig-define ", "Read root signature from a #define" },
+ { "-T ", "Set target profile." },
+ { "", @"""ps_6_0, ps_6_1, ps_6_2, ps_6_3, ps_6_4, ps_6_5,
+ vs_6_0, vs_6_1, vs_6_2, vs_6_3, vs_6_4, vs_6_5,
+ cs_6_0, cs_6_1, cs_6_2, cs_6_3, cs_6_4, cs_6_5,
+ gs_6_0, gs_6_1, gs_6_2, gs_6_3, gs_6_4, gs_6_5,
+ ds_6_0, ds_6_1, ds_6_2, ds_6_3, ds_6_4, ds_6_5,
+ hs_6_0, hs_6_1, hs_6_2, hs_6_3, hs_6_4, hs_6_5,
+ lib_6_3, lib_6_4, lib_6_5, ms_6_5, as_6_5
+""" },
+ { "-Vd", "Disable validation" },
+ { "-Vi", "Display details about the include process" },
+ { "-Vn ", "Use as variable name in header file" },
+ { "-WX", "Warnings are errors" },
+ { "-Zi", "Enable debug information" },
+ { "-Zpc", "Pack matrices in column-major order" },
+ { "-Zpr", "Pack matrices in row-major order" },
+ { "-Zsb", "Build debug name considering only output binary" },
+ { "-Zss", "Build debug name considering source information" },
+ } );
+
+ public static int LogLevel { get; set; } = 3 ;
+ public static int LogLevels( string str ) => str.ToLowerInvariant( ) switch {
+ "none" => 0, "min" => 1, "low" => 2, "normal" or "default" => 3, "high" => 4, "debug" => 5, _ => 3,
+ } ;
+ }
+ const string _LOGPREFIX = nameof(DxcTool) + " ::" ;
+ const string DEFAULT_OUT_DIR = ".\fxbin", DEFAULT_OUT_FILE = "shader_bytecode",
+ DEFAULT_SHADER_MODEL = "vs_6_0", DEFAULT_ENTRY_POINT = "main" ;
+ public const string DxSharpShaderType = "dxsharp", VertexShaderType = "vertex", PixelShaderType = "pixel",
+ GeometryShaderType = "geometry", HullShaderType = "hull", DomainShaderType = "domain",
+ ComputeShaderType = "compute" ;
+ static readonly string[ ] _shaderTypes = { DxSharpShaderType, VertexShaderType, PixelShaderType,
+ GeometryShaderType, HullShaderType, DomainShaderType,
+ ComputeShaderType, } ;
+
+
+ //! List of hlsl files to compile:
+ [Required] public ITaskItem[ ] ShaderFiles { get; set; }
+
+ public string EntryPoint { get; set; }
+ [Required] public string ShaderType { get; set; }
+ public string ShaderModel { get; set; }
+ public string AssemblerOutDir { get; set; }
+ public string AssemblerOutputFile { get; set; }
+ public bool EnableDebuggingInfo { get; set; }
+ public bool DisableOptimizations { get; set; }
+ public string[ ] PreprocessorDefinitions { get; set; }
+ public string[ ] AdditionalIncludeDirectories { get; set; }
+
+
+ // Helper methods
+ bool isValidShaderType( string str ) =>
+ _shaderTypes.Contains( ShaderType.ToLowerInvariant( ) ) ;
+
+
+
+ public override bool Execute( ) {
+ foreach ( var item in ShaderFiles ) {
+ string shaderType = item.GetMetadata( "ShaderType" ) ;
+ return shaderType switch {
+ "vertex" => ( CompileVertexShader( item ) is 0 ),
+ "pixel" => ( CompilePixelShader( item ) is 0 ),
+ "dxsharp" => throw new Exception( "DXSharp shader type is not supported yet!" ),
+ _ => throw new Exception( $"Unknown shader type: {ShaderType}" ),
+ } ;
+ }
+ return false ;
+ }
+
+ public int CompileVertexShader( ITaskItem item ) {
+ if ( item is null ) {
+ Log.LogError( $"{_LOGPREFIX} :: TaskItem is null/empty!", -1 ) ;
+ return -1 ;
+ }
+ var itemSpec = item.ItemSpec ?? throw new ArgumentNullException( nameof(item) ) ;
+ var shaderName = item.GetMetadata( "ShaderName" ) ?? Path.GetFileNameWithoutExtension( itemSpec ) ;
+ var entryPoint = item.GetMetadata( "EntryPoint" ) ?? DEFAULT_ENTRY_POINT ;
+ var shaderModel = item.GetMetadata( "ShaderModel" ) ?? DEFAULT_SHADER_MODEL ;
+ var assemblerOutDir = item.GetMetadata( "AssemblerOutDir" ) ?? DEFAULT_OUT_DIR ;
+
+ var assemblerOutputFile = item.GetMetadata( "AssemblerOutputFile" ) ?? DEFAULT_OUT_FILE ;
+
+ bool enableDebugParsed = bool.TryParse( item.GetMetadata( "EnableDebuggingInfo" )
+ ?? "false", out var _enableDebuggingInfo ) ;
+ bool disableOptimizationsParsed = bool.TryParse( item.GetMetadata( "DisableOptimizations" )
+ ?? "false", out var _disableOptimizations ) ;
+
+ Log.LogMessage( MessageImportance.High, $"Compiling vertex shader: {item.GetMetadata( "EntryPoint" )}" ) ;
+
+ return 0 ;
+ }
+
+ public int CompilePixelShader( ITaskItem item ) {
+ return 0 ;
+ }
+} ;
+}
\ No newline at end of file
diff --git a/tools/DXSharp.Tools.Builds/Shaders/DxcTool.targets b/tools/DXSharp.Tools.Builds/Shaders/DxcTool.targets
new file mode 100644
index 0000000..d3a8d8e
--- /dev/null
+++ b/tools/DXSharp.Tools.Builds/Shaders/DxcTool.targets
@@ -0,0 +1,212 @@
+
+
+
+ $(ShaderOutDir)
+ %(Filename)_%(ShaderModel)_%(ShaderType)_%(EntryPoint)
+ %(Name).%(Extension)
+ $(ShaderOutDir)
+ %(OutputType)
+ %(ShaderProfile)
+ %(ShaderModel)
+ %(ShaderModel)
+ %(Extension)
+ %(ShaderType)
+
+
+
+ %(ShaderDebug)
+ %(ShaderTypes)
+ %(ShaderModels)
+ %(ShaderProfiles)
+ %(ShaderFilters)
+
+
+
+ CodeTaskFactory
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ $(PrepInputFilesDependsOn);
+ DxcGenerateShader;
+ DxcCompileShader;
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ DxShader
+ 5_0
+
+
+ Vertex
+ 5_0
+
+
+ Pixel
+ 5_0
+
+
+ Geometry
+ 5_0
+
+
+ Hull
+ 5_0
+
+
+ Domain
+ 5_0
+
+
+ Compute
+ 5_0
+
+
+ Texture
+ 5_0
+
+
+
+
+
+ $([System.IO.Path]::GetDirectoryName(%(SrcFiles.TargetPath)))
+ $(IntermediateOutputPath)$([System.IO.Path]::ChangeExtension(%(SrcFiles.TargetPath), '.cso'))
+ true
+ main
+ $(ShaderModel)
+
+
+
+
+ %(SrcFiles.TargetDirectory)\
+
+
+
+
+
+
+ $(DxcCompileShaderDependsOn);AssignItemsFxCompile;
+ $(AssignTargetPathsDependsOn);AssignItemsFxCompile
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/tools/DXSharp.Tools.Builds/packages.lock.json b/tools/DXSharp.Tools.Builds/packages.lock.json
index a138d73..5219a50 100644
--- a/tools/DXSharp.Tools.Builds/packages.lock.json
+++ b/tools/DXSharp.Tools.Builds/packages.lock.json
@@ -21,12 +21,6 @@
"System.Text.Encoding.CodePages": "9.0.0"
}
},
- "Microsoft.Direct3D.DXC": {
- "type": "Direct",
- "requested": "[1.9.2609.5, 1.9.2609.5]",
- "resolved": "1.9.2609.5",
- "contentHash": "jTWr7a2bMpqV+b0Uc7oxOo8ualplaUw3fsQ+p0kp9TwlWvvmREvt3SA4+Drl2Y0M31iscqZolrL3vpdnLoPpdg=="
- },
"NETStandard.Library": {
"type": "Direct",
"requested": "[2.0.3, )",