mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-12-01 10:42:28 +00:00
Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
713e2d72db | ||
|
|
c6bb82a6a8 | ||
|
|
95b1b154fa | ||
|
|
bc2b0add5d | ||
|
|
28041c38a3 | ||
|
|
bb21c4da3c | ||
|
|
32f7bf2be1 | ||
|
|
19c9667b5a | ||
|
|
dcb9e434c6 | ||
|
|
a94888d1c7 | ||
|
|
a5f6dadc6f | ||
|
|
2420c52ee5 | ||
|
|
ecee277cfa | ||
|
|
b92cfa8047 | ||
|
|
bf468e8c48 | ||
|
|
d08aaa0e33 | ||
|
|
1351925f40 | ||
|
|
663c8597ad | ||
|
|
cb4683b688 | ||
|
|
837129f9d2 |
No files matched your search
@@ -0,0 +1,81 @@
|
||||
name: Build open-source DXC (dxcompiler.dll)
|
||||
|
||||
# Builds x64 Release dxcompiler.dll from the pinned microsoft/DirectXShaderCompiler
|
||||
# tag on a Windows runner so BetterXen does not redistribute Microsoft's prebuilt
|
||||
# release zip or stage the GDK's dxcompiler.dll (#757).
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: DirectXShaderCompiler release tag to build
|
||||
required: true
|
||||
default: v1.9.2609
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: dxc-build-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
build-dxcompiler:
|
||||
name: Build dxcompiler.dll (x64 Release)
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- name: Checkout DirectXShaderCompiler
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
repository: microsoft/DirectXShaderCompiler
|
||||
ref: ${{ inputs.tag }}
|
||||
path: dxc
|
||||
submodules: recursive
|
||||
persist-credentials: false
|
||||
|
||||
- name: Configure CMake (x64)
|
||||
run: >
|
||||
cmake -B build -S dxc -A x64
|
||||
-C dxc/cmake/caches/PredefinedParams.cmake
|
||||
-DHLSL_INCLUDE_TESTS=OFF
|
||||
-DENABLE_SPIRV_CODEGEN=OFF
|
||||
|
||||
- name: Build dxcompiler (Release)
|
||||
run: cmake --build build --config Release --target dxcompiler --parallel
|
||||
|
||||
- name: Verify DxcCreateInstance export and collect artifact
|
||||
shell: pwsh
|
||||
run: |
|
||||
$dll = Get-ChildItem -Path build -Recurse -Filter dxcompiler.dll |
|
||||
Where-Object { $_.FullName -match '\\Release\\' } |
|
||||
Select-Object -First 1
|
||||
if (-not $dll) {
|
||||
throw "dxcompiler.dll not found under build/**/Release/"
|
||||
}
|
||||
$bytes = [System.IO.File]::ReadAllBytes($dll.FullName)
|
||||
$marker = [System.Text.Encoding]::ASCII.GetBytes("DxcCreateInstance`0")
|
||||
$found = $false
|
||||
for ($i = 0; $i -le $bytes.Length - $marker.Length; $i++) {
|
||||
$match = $true
|
||||
for ($j = 0; $j -lt $marker.Length; $j++) {
|
||||
if ($bytes[$i + $j] -ne $marker[$j]) { $match = $false; break }
|
||||
}
|
||||
if ($match) { $found = $true; break }
|
||||
}
|
||||
if (-not $found) {
|
||||
throw "DxcCreateInstance export string not found in $($dll.FullName)"
|
||||
}
|
||||
New-Item -ItemType Directory -Force -Path dist | Out-Null
|
||||
Copy-Item $dll.FullName dist/dxcompiler.dll
|
||||
$hash = (Get-FileHash dist/dxcompiler.dll -Algorithm SHA256).Hash
|
||||
Write-Host "Built $($dll.FullName)"
|
||||
Write-Host "SHA-256: $hash"
|
||||
|
||||
- name: Upload dxcompiler.dll artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: dxcompiler-${{ inputs.tag }}-win64-release
|
||||
path: dist/dxcompiler.dll
|
||||
if-no-files-found: error
|
||||
@@ -9,7 +9,17 @@ exact revision and known limitations.
|
||||
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
|
||||
remains unsupported.
|
||||
|
||||
### Fixed
|
||||
- **`gfx10-translate`: scan all `XBCH` candidates and support version 2/3 payloads** (#721). `container_code` previously stopped at the first `b"XBCH"` byte sequence in a container, so incidental `b"XBCH"` bytes earlier in the blob (for example in `STAT` or `DXIL` bitcode) caused it to read garbage sizes and fail with `XBCH record: compressed size past the end`. It now scans all `b"XBCH"` occurrences, validates the 24-byte header, bounds, version (`2` uncompressed `FSSM`, `1` and `3` zlib-compressed `FSSM`), and `FSSM` magic, and skips non-matching candidates. Covered by synthetic unit tests in `gfx10_translate::container::tests`.
|
||||
|
||||
### Changed
|
||||
- **Open-source DXC (`dxcompiler.dll`) replaces the GDK's shader compiler as the primary source** (#757, ADR 0010).
|
||||
- `.github/workflows/dxc-build.yml` builds x64 Release `dxcompiler.dll` from `microsoft/DirectXShaderCompiler` at pinned tag `v1.9.2609` on a Windows runner and uploads it as a workflow artifact.
|
||||
- `bx-cli setup --dxc-dir <dir>` (and `BX_DXC_DIR`) records the local open-source DXC folder in `local.conf` (`dxc_dir`).
|
||||
- `bx-cli run` (`gdk_libs::resolve`) stages `dxcompiler.dll` from `dxc_dir` first, falling back to the GDK's `dxcompiler.dll` only if no open-source build is configured. `dxcompiler.dll` is recognised by name and the `DxcCreateInstance` export, and `dxil.dll` is no longer staged.
|
||||
- ADR 0010, `docs/research/upstream-registry.md`, and `docs/research/component-reuse-matrix.md` record the source build and its `LICENSE.TXT` / per-file licence check.
|
||||
- **`docs/roadmap.md`, Picture stage, corrected to what was built.** The translator item said "GFX10-to-DXIL"; it produces HLSL, and `d3d12_xs` compiles that with the GDK's `dxcompiler.dll` at first draw. The item also said each rule is checked against the console compiler's output; it now says how rules are checked today (public assembler encodings and the instruction's definition) and where the console compiler has been used (the root-data layout). Dated state notes record that the capability checks were not done first, what is translated at run time, and what is open (#744, #745, #746). ADR 0010's title now names the shader compiler it has covered since #734; its file name is unchanged.
|
||||
- **`README.md` rewritten for the current state** (2026-11-30). It described the M0–M6 milestone plan with M2 active and listed as unimplemented several things that exist. It now gives the stage (Picture) and what the target build does today, the stages from `docs/roadmap.md`, an architecture diagram with the run-time shader translation and the GDK libraries, the current repository layout and `bx-cli` commands, the hard requirements for contributing, and a section that separates what the repository's tests verify from what was observed on the target build and from what is not claimed. `docs/architecture/parallel-tracks.md` is revised the same way: it listed the M0–M6 milestones and an issue-claiming protocol that `AGENTS.md` has replaced; it now gives the current directory table and points to `AGENTS.md` and the roadmap for the rules and the stages.
|
||||
- **Current stage: Picture** (`docs/roadmap.md`), by the repository owner's decision on 2026-11-30. Boot is marked as left without its ten-run gate having been run under the run protocol. The first frames and the menus are reached, and the open work is translation, textures and stability. The new pinned ladder issue carries the live status. The repository owner also accepted the LLVM-generated opcode table and test vectors of `gfx10-translate` (`docs/research/upstream-registry.md`).
|
||||
- **`CONTRIBUTING.md` is a short entry point for new members, consistent with AGENTS.md.** It covers the hard requirements (the target build, the GDK and the Ghidra results, distributed among members), setup (`setup --find`, `preflight`), the current way of working (pick order, checking for existing work, draft pull request claims with the 3-day rule, tests, Section 8), and running the target build with its diagnostic switches. The outdated workflow is removed: issue-comment claims, the 7-day rule and the Wave 1 backlog. The licensing, sign-off and merge sections are unchanged.
|
||||
- **Check for existing work before investigating any problem the game shows** (AGENTS.md Section 0 Step 3 and Section 7, `docs/process/working-method.md`). Every problem met while running the game, not only the picked blocker, is searched for in open and merged pull requests and open issues by its log event, stub symbol, error code and files. An open pull request that covers it is checked out and worked on, never duplicated. Prompted by a duplicate fix for physical-page DirectStorage requests made alongside #707.
|
||||
@@ -31,6 +41,13 @@ remains unsupported.
|
||||
- `dxbc-accc` no longer classifies `DXIL` chunks whose bitcode payload starts with the `NOBC` header-only placeholder as executable DXIL (Track D prerequisite from ADR 0008 / `docs/roadmap.md`). `inspect_dxbc` and `bx_shader_inspect` still report the container's `dxil_chunk_size`, stage, and shader model, but leave `kind` as `Unknown` (or `AcccOnly` when paired with an `ACCC` chunk) instead of `Dxil` or `DualDxilAndAccc`, and `bx_shader_prepare_for_d3dmetal` returns `BX_SHADER_ERR_UNSUPPORTED` rather than passing a bitcode-less container through. Covered by synthetic `NOBC`, mixed-chunk, and bounds-safety unit tests in `dxbc-accc`; live CrossOver execution is unchanged.
|
||||
|
||||
### Added
|
||||
- **`docs/research/console-shader-abi.md`: directly indexed descriptor heaps** (SM 6.6 `ResourceDescriptorHeap` / `SamplerDescriptorHeap`). Measured with probes of our own compiled by `xdxc`: the heap pointers follow the root data (resource heap, then sampler heap), as 32-bit pointers, with 32-byte resource and 16-byte sampler descriptors. The target build's pixel shaders with `SAMPLER_HEAP_DIRECTLY_INDEXED` take their sampler that way; the translator does not model it yet.
|
||||
- **Root signature layouts reach the translator at run time** (#715, #720; with `BX_CONSOLE_SHADERS=1`).
|
||||
- `bx_shader_bridge.dll` exports `bx_shader_translate_pair_rooted` (contract #741): the translation given the root parameter list and the signature's flags. `bx_shader_translate_pair` is the same call with no layout. The export list has 118 names across the 17 DLLs.
|
||||
- `d3d12_xs.dll` keeps each root signature's parameter list with its host object and passes it when a console pipeline is first drawn. With an older bridge it falls back to the table-only translation.
|
||||
- `SetGraphicsRootShaderResourceView` and `SetGraphicsRootConstantBufferView` give an address in plain title memory a host buffer, copied at submission. A root buffer has no size, so what is readable there is copied, up to 256 KiB for an SRV and 64 KiB for a CBV; a shader that reads further sees zeros.
|
||||
- Tests: `test_d3d12_console_pipeline_first_draw` gains a root SRV case, a vertex shader that pulls its positions by vertex index, drawn from an upload buffer and from plain process memory (46 checks); `tests/translate_pair.rs` covers the export, including inconsistent layouts.
|
||||
- On the target build every vertex/pixel pair it draws with in its first two minutes now translates; none is refused. The picture is unchanged (the menu's bars).
|
||||
- **`gfx10-translate`: root signature layouts** (#715; the rules are measured in `docs/research/console-shader-abi.md`). `translate_pair_rooted` and `translate_blobs_rooted` take the pipeline's root parameter list (`RootLayout`).
|
||||
- Each packed root value is mapped to its parameter: a table pointer is one value, a root CBV, SRV or UAV two, a constant one each. Both forms are read: registers from `s8`, and root data in memory through `s0` and the low byte of `s1` (`memory_based`).
|
||||
- A descriptor table is the parameter its pointer belongs to, no longer its register's position.
|
||||
@@ -180,6 +197,7 @@ remains unsupported.
|
||||
- `d3d12_xs.dll!D3D12ConfigureVirtualMemoryX` now decodes the Xbox virtual-memory configuration (`D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION`) alongside the existing `BXVM` contract. Layout and behaviour follow the authorized GDK documentation of the function and structure: no flags, a GPU page-table size in 4 MB units clamped to 33, a frame-buffer preserve size (0, -1 for the legacy size, or bytes clamped to 64 MiB), and two output addresses, the minimum always 2 GiB and the maximum 159.375 GiB at the default 5 pages. The call fails with `E_FAIL` once a D3D12 device exists. Call-site observation of a project-authorized target build agrees with the documented layout. Inferred, and marked as such: the maximum for other page-table sizes scales linearly (`max_estimated=1` in the log), and a page-table size of 0, an unreadable configuration or unwritable outputs fail with `E_INVALIDARG`. The host sizes no GPU page tables and keeps no cross-process frame buffer, so the path records both (`vmem_config_recorded`, `applied=0 recorded_only=1`), leaves the `BXVM` record and cached backing heap untouched, and still emits `BX_STUB_LOG`. `tests/conformance/test_d3d12_vmem_xbox/` checks the documented outputs, clamps and post-device `E_FAIL`, the refused cases, and that a cached `BXVM` backing heap survives.
|
||||
|
||||
### Fixed
|
||||
- **`d3d12_xs.dll`: a translated pipeline that reads a root constants or root descriptor parameter is no longer refused or mistaken for a table read** (#744). The shim read the translator's `USE ROOT <parameter>` layout line as `USE CB <entry>`: as a constant-buffer read of entry `<parameter>` of root parameter 0's table. With a parameter index of 8 or more the pipeline was refused ("reads table entry 8, beyond the 8 widened ones") and drew nothing; below 8 each submission looked up a table entry the shader never reads and logged it as an unresolved descriptor, which was most of the `console_descriptor` warnings on the target build's first screens and hid the real ones. Only `USE CB` and `USE TEX` lines now name table entries; other kinds are ignored, as `abi/include/bx_shader_bridge.h` says. `test_d3d12_console_root_constants` draws with a vertex shader that reads root parameter 8.
|
||||
- **Two causes of the target build's menu crashes are fixed** (#722). Before, most runs ended with exit status 5 within a few minutes.
|
||||
- **`d3d12_xs.dll`: `CopyTextureRegionX` is implemented**, as `CopyTextureRegion`; its `D3D12XBOX_COPY_FLAGS` steer console compression metadata the host does not have. As a stub it left a copy undone, the title's frame never completed, and its hang watchdog ended the process 30 s later (every watchdog crash followed its first call by 32–41 s). Test: `test_d3d12_copy_texture_region_x`, a box copy and a whole-texture copy through slot 85, read back. On the previous shim no pixel is copied.
|
||||
- **`bx_runtime_veh.dll`: a title fault on a page being remapped is retried.** xmem replaces part of a mapped run by unmapping the whole view and mapping the rest back, so other pages of the run briefly disappear; on the console that update is atomic. A fault in the title's own code on an inaccessible address now waits for any remap in progress (the remap guard) and retries if the address has become accessible. Each retry is logged (`remap_window_retry`). Genuine faults still reach the title. Test: `test_veh_remap_window`, four unguarded readers of one page while two pages of its run are remapped for four seconds. It crashes 4 of 4 times without the retry. A rarer silent case, a read that sees other data without faulting, remains (#729).
|
||||
|
||||
@@ -2,236 +2,250 @@
|
||||
|
||||
# BetterXen
|
||||
|
||||
**Modular Xbox Series (`Scarlett`) compatibility layer for Apple Silicon macOS — built on CrossOver, Rosetta 2, and D3DMetal 3.0.**
|
||||
**An Xbox Series (`Scarlett`) compatibility layer for Apple Silicon Macs, built on CrossOver, Rosetta 2 and D3DMetal 3.0.**
|
||||
|
||||
[](https://github.com/MacosPorters/betterxen/actions/workflows/hybrid-ci.yml)
|
||||
[](https://github.com/MacosPorters/betterxen/actions/workflows/hygiene.yml)
|
||||
-1f6feb?logo=apple&logoColor=white)
|
||||

|
||||

|
||||
-0969da)
|
||||

|
||||

|
||||
|
||||
</div>
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Experimental status.** BetterXen is an active, open-source compatibility engineering project with **Milestone M0 and Milestone M1 verified complete** on synthetic PE32+ workloads under CrossOver 26.3 + Rosetta 2, and **Milestone M2** (`First Rendered Frame & Shader Format Gate`) currently active. **Commercial Xbox game execution is not yet supported.** CrossOver, Rosetta 2, and D3DMetal are externally installed dependencies and are never bundled or redistributed.
|
||||
> **Experimental.** The goal is one project-authorized target build, fully playable on Apple Silicon Macs with 16 GB of memory. Today that build boots, reaches its frame loop and its first menus, and translates its own shaders at run time, but it shows almost no picture yet. CrossOver, Rosetta 2 and D3DMetal are installed separately and are never bundled or redistributed.
|
||||
|
||||
BetterXen builds the missing Xbox Game OS layer around **CrossOver 26.3+**, **Rosetta 2**, and **D3DMetal 3.0** on Apple Silicon:
|
||||
- **Native ARM64 macOS tooling** (`launcher/`, Rust) for host diagnostics, PE32+ static probing, CrossOver bottle orchestration, and structured trace aggregation.
|
||||
- **Cross-compiled x86-64 Windows PE32+ shim DLLs** (`shims/`, C++20 via `mingw-w64`) implementing Xbox runtime APIs (`xmem`, `XCRDAPI`, `d3d12_xs`, `xg_xs`, `xgameruntime`, `GameInput`, `AcpHal`/`xapu`/`chad`, Win32/PSM forwarders, and a `clwb` Vectored Exception Handler).
|
||||
- **Shader pipeline** (`shader-transpiler/`, Rust) for classifying `DXBC` containers (`DXIL` vs. `ACCC`/`FSPX` RDNA 2 machine code) and handling console shader translation where required.
|
||||
## Where it stands
|
||||
|
||||
> [!CAUTION]
|
||||
> **Provenance and anti-piracy policy.** BetterXen strictly opposes piracy and does not distribute copyrighted game files, firmware, decryption keys, or DRM circumvention tooling. Zero proprietary binaries, assets, or leaked materials are permitted in this repository or its Git history. All in-repo tests use independently authored synthetic PE32+ workloads.
|
||||
*As of 2026-11-30, on `main`. The live status is on the pinned issue labelled [`ladder`](https://github.com/MacosPorters/betterxen/issues?q=is%3Aissue+is%3Aopen+label%3Aladder).*
|
||||
|
||||
---
|
||||
The current stage is **Picture**: the target build should show its first non-black screen, correctly.
|
||||
|
||||
## Progress Tracker
|
||||
| | State |
|
||||
| --- | --- |
|
||||
| **Boot** | The target build starts, creates its Xbox-layout D3D12 device, loads through DirectStorage, and presents frames. |
|
||||
| **Menus reached** | With scripted input it goes through its first-run setup screens. A hang watchdog in the build still ends most runs after a few minutes ([#722](https://github.com/MacosPorters/betterxen/issues/722)). |
|
||||
| **Shaders** | The build ships console (RDNA 2) code only. BetterXen's own translator turns a vertex/pixel pair into HLSL when a pipeline is first drawn; the result is compiled and cached on disk. Every vertex/pixel pipeline the build draws with in its first two minutes translates and runs. Opt-in: `BX_CONSOLE_SHADERS=1`. |
|
||||
| **Picture** | Only the menu's background bars appear, in a few frames. The rest is open work: [#744](https://github.com/MacosPorters/betterxen/issues/744) (why only the bars), [#745](https://github.com/MacosPorters/betterxen/issues/745) (texture contents), [#746](https://github.com/MacosPorters/betterxen/issues/746) (compute shaders). |
|
||||
| **Translator coverage** | 1,538 of 4,331 vertex and pixel shaders in one member's dump of the build translate offline (35.5%). That means "produces HLSL that compiles", not "verified against the console". |
|
||||
| **Sound, saves, gameplay, performance** | Not started as stages. Audio and save shims answer the build's calls so that it runs; nothing is audible. |
|
||||
|
||||
> *Tracks engineering milestones and synthetic conformance progress only — not commercial game compatibility percentages.*
|
||||
Without `BX_CONSOLE_SHADERS=1` the window stays black: pipelines with console shaders are refused and their draws are skipped.
|
||||
|
||||
### Stages
|
||||
|
||||
From the Boot stage on, progress is measured by how far the target build gets in repeated, recorded runs, not by subsystems. Each stage has one exit gate: ten runs out of ten on a 16 GB Mac.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
M0["M0: Foundation & Shims\n(Verified Complete)"]:::done
|
||||
M1["M1: Boot to D3D12\n(Verified Complete — 16/16)"]:::done
|
||||
M2["M2: First Frame &\nShader Gate\n(Active — Milestone #18)"]:::active
|
||||
M3["M3: Shaders &\nTexture Tiling"]:::planned
|
||||
M4["M4: 3D, DXR/BVH\n& Input"]:::planned
|
||||
M5["M5: Audio, Saves\n& Stability"]:::planned
|
||||
M6["M6: Cache & 16 GB\nOptimization"]:::planned
|
||||
F["Foundation\nM0–M2, synthetic"]:::done
|
||||
B["Boot"]:::done
|
||||
P["Picture\n(current)"]:::active
|
||||
M["Menus"]:::planned
|
||||
W["World"]:::planned
|
||||
Fi["Fidelity"]:::planned
|
||||
Pl["Playable"]:::planned
|
||||
|
||||
M0 --> M1 --> M2 --> M3 --> M4 --> M5 --> M6
|
||||
F --> B --> P --> M --> W --> Fi --> Pl
|
||||
|
||||
classDef done fill:#dafbe1,stroke:#1a7f37,color:#0f5323,stroke-width:2px
|
||||
classDef active fill:#ddf4ff,stroke:#0969da,color:#0a3069,stroke-width:2px
|
||||
classDef planned fill:#f6f8fa,stroke:#8c959f,color:#57606a
|
||||
```
|
||||
|
||||
Legend: 🟢 **Done / Merged** · 🔵 **Active Milestone** · ⚪ **Planned**
|
||||
|
||||
### Active Milestone — [M2: First Rendered Frame & Shader Format Gate](https://github.com/MacosPorters/betterxen/milestone/18)
|
||||
|
||||
| Track | Focus | Visual Status | Live Issues |
|
||||
| --- | --- | --- | --- |
|
||||
| **Track A** | `system32` shim staging (`#457` / PR `#458` merged), AMD-only VEH emulation (`#451`), Track A/F runner integration (`#407`) | `🟩🟨🟨` *(#458 merged; #451, #407 active)* | [View Track A](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+A%22) |
|
||||
| **Track B** | `XCRDAPI.dll` DirectStorage GPU-buffer & batch transfers (`#467`) | `⬜` *(1 ready)* | [View Track B](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+B%22) |
|
||||
| **Track C** | `d3d12_xs` `D3D12ConfigureVirtualMemoryX` + placed resources (`#464`), `PresentX` swapchain bridge (`#465`), D3D workload fixes (`#450`) | `⬜⬜⬜` *(3 ready)* | [View Track C](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+C%22) |
|
||||
| **Track D** | `dxbc-accc` Windows guest bridge (`#445`), M2 Shader Format Gate ADR & PSO hook (`#466`) | `⬜⬜` *(2 ready)* | [View Track D](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+D%22) |
|
||||
| **Track E** | Public GDK COM `QueryApiImpl` dispatch (`#456` / PR `#462` merged), offline `XGameSave` + `XPackage` COM dispatch (`#468`) | `🟩⬜` *(#462 merged, 1 ready)* | [View Track E](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+E%22) |
|
||||
| **Track F** | D3DMetal GPU limits fixture (`#453` / PR #455), M2 first-frame + shader-gate exit fixture (`#469`) | `🟨⬜` *(PR #455 approved, 1 ready)* | [View Track F](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+F%22) |
|
||||
|
||||
`🟩` Merged & verified · `🟨` PR open / in review · `⬜` Open & ready to claim
|
||||
|
||||
### Milestone Roadmap (M0 → M6)
|
||||
|
||||
| Milestone | Scope | Status |
|
||||
| Stage | The target build… | Status |
|
||||
| --- | --- | --- |
|
||||
| **M0 — Repo, ABI & Cross-Build** | 6-track layout, frozen `abi/`, ARM64 `bx-cli`, 16 mingw-w64 C++ PE32+ shims plus the Rust `bx_shader_bridge.dll` (17 verified DLLs), live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb`, `test_shim_exports`) | 🟢 **Verified complete (`#406`)** |
|
||||
| **M1 — Boot to `D3D12XboxCreateDevice`** | Full startup shim coverage (`xmem` physical/scatter pages, `XCRDAPI` async file reads, `d3d12_xs` auto-logging COM proxy, offline `xgameruntime` + dynamic loader exports, audio queue stubs, supervised `bx-cli run`, ADR 0007, `test_integration_boot` 19 pass / 2 pending / 0 fail) | 🟢 **Verified complete ([Milestone #17](https://github.com/MacosPorters/betterxen/milestone/17))** |
|
||||
| **M2 — First Frame & Shader Gate** | Reversible `system32` staging, public GDK COM `QueryApiImpl` dispatch, `PresentX` → `IDXGISwapChain3::Present` via D3DMetal 3.0, `dxbc-accc` Windows bridge, D3DMetal GPU limits, and Shader Format Gate ADR | 🔵 **Active ([Milestone #18](https://github.com/MacosPorters/betterxen/milestone/18))** |
|
||||
| **M3 — Shaders, Streaming & Textures** | DirectStorage decompression, RDNA 2 `xg_xs` texture deswizzling, full shader pipeline | ⚪ Planned |
|
||||
| **M4 — 3D Rendering, DXR/BVH & Input** | BVH4 rehydration → live D3DMetal 3.0 DXR rebuild, PC FidelityFX/MetalFX upscaling shim, full `GameInput` | ⚪ Planned |
|
||||
| **M5 — Audio, Saves & Stability** | Software audio/DSP decoding (`AcpHal`/`xapu`/`chad`), `PersistentLocalStorage`, multi-hour soak stability | ⚪ Planned |
|
||||
| **M6 — Cache, 16 GB Tuning & Polish** | Persistent PSO/shader disk cache, Lockhart 16 GB unified memory optimization, Metal System Trace tuning | ⚪ Planned |
|
||||
| **Foundation** | (synthetic tests only) repository, frozen ABI, cross-built shims, a synthetic first frame, the shader format decision | Done |
|
||||
| **Boot** | starts, reaches its frame loop and stays there | Left on 2026-11-30 by the repository owner's decision; its ten-run gate was not run |
|
||||
| **Picture** | shows its first non-black screen, correctly | **Current** |
|
||||
| **Menus** | plays its opening sequence and menus with sound and input | Planned |
|
||||
| **World** | loads into gameplay and keeps running | Planned |
|
||||
| **Fidelity** | draws its 3D scenes as the console does | Planned |
|
||||
| **Playable** | is playable start to finish on every supported Mac | Planned |
|
||||
|
||||
See [docs/architecture/parallel-tracks.md](docs/architecture/parallel-tracks.md) and [docs/roadmap.md](docs/roadmap.md) for full details.
|
||||
[docs/roadmap.md](docs/roadmap.md) is the single authoritative roadmap, with each gate's exact wording. [docs/process/working-method.md](docs/process/working-method.md) explains how runs are made and recorded.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
## How it works
|
||||
|
||||
Rosetta 2 executes x86-64 CPU code (including AVX/AVX2/FMA/F16C/BMI1/BMI2/128-bit VAES when launched with `ROSETTA_ADVERTISE_AVX=1`), CrossOver/Wine provides Win32/NT/CRT/XAudio2/WinHTTP, and D3DMetal 3.0 translates Direct3D 12 + DXR onto Metal. BetterXen supplies the modular Xbox Game OS shims, `clwb` exception handling, shader bridge, and ARM64 orchestration around that stack.
|
||||
Rosetta 2 executes the build's x86-64 code. CrossOver/Wine provides Win32. D3DMetal 3.0 translates Direct3D 12 to Metal. BetterXen supplies what is missing between an Xbox title and that stack:
|
||||
|
||||
- **Xbox Game OS shims** (`shims/`): x86-64 Windows DLLs, cross-compiled on macOS, that implement the Xbox runtime the title imports: memory, DirectStorage, the Xbox flavour of Direct3D 12, the GDK runtime, input and audio.
|
||||
- **A shader translator** (`shader-transpiler/`): console shaders are AMD RDNA 2 machine code. The translator turns them into HLSL, one rule per instruction, and the Direct3D shim compiles and caches the result.
|
||||
- **A native launcher** (`launcher/`): `bx-cli` checks the host, runs a program in an isolated CrossOver environment, and turns the shims' logs into a run report.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Guest["Scarlett x86-64 PE32+ Executable"]
|
||||
Guest["Xbox Series title (x86-64 PE32+)"]
|
||||
|
||||
subgraph Shims["BetterXen x86-64 Wine Shims (Cross-Compiled on macOS)"]
|
||||
VEH["bx_runtime_veh.dll (clwb VEH trap, JSONL trace, Lockhart cap)"]
|
||||
XMem["xmem.dll (Physical/Virtual/Scatter Allocator)"]
|
||||
DS["XCRDAPI.dll (DirectStorage Async I/O)"]
|
||||
D3DX["d3d12_xs.dll + xg_xs.dll (Xbox D3D12 COM Proxy & RDNA2 Tiling)"]
|
||||
XGR["xgameruntime.dll + GameInput.dll + Audio/DSP"]
|
||||
Bridge["PSM AppNotify & ntuser Win32 Forwarders"]
|
||||
subgraph Shims["BetterXen shims (x86-64 DLLs, built on macOS)"]
|
||||
VEH["bx_runtime_veh.dll\ninstruction traps, logging, fault diagnostics"]
|
||||
XMem["xmem.dll\nvirtual and physical page mapping"]
|
||||
DS["XCRDAPI.dll\nDirectStorage queues, zlib, BCPack"]
|
||||
D3DX["d3d12_xs.dll\nXbox-layout D3D12 over the host's D3D12"]
|
||||
XGR["xgameruntime.dll, GameInput.dll, audio DLLs"]
|
||||
Bridge["bx_shader_bridge.dll (Rust)\nshader classifier and translator"]
|
||||
end
|
||||
|
||||
subgraph Shaders["Shader & DXR Bridge"]
|
||||
DXIL["DXIL Fast Path (SM 6.5/6.6)"]
|
||||
ACCC["ACCC / FSPX RDNA2 Transpiler"]
|
||||
subgraph GDK["From the member's own GDK, staged at run time, never shipped"]
|
||||
XG["xg_xs.dll (texture layouts)\nBCPack.dll"]
|
||||
DXC["dxcompiler.dll (HLSL to DXIL)"]
|
||||
end
|
||||
|
||||
subgraph External["External Foundation (User-Installed)"]
|
||||
Wine["CrossOver 26.3 / Wine (Win32, CRT, XAudio2, WinHTTP)"]
|
||||
Rosetta["Rosetta 2 (ROSETTA_ADVERTISE_AVX=1)"]
|
||||
D3DM["D3DMetal 3.0 (D3D12 + DXR on Apple Silicon Metal)"]
|
||||
subgraph External["External foundation (installed by the user)"]
|
||||
Wine["CrossOver 26.3+ / Wine"]
|
||||
Rosetta["Rosetta 2"]
|
||||
D3DM["D3DMetal 3.0"]
|
||||
end
|
||||
|
||||
CLI["bx-cli (Native ARM64 macOS Launcher, Probe & Telemetry)"]
|
||||
CLI["bx-cli (native ARM64)\nsetup, preflight, run, report"]
|
||||
|
||||
Guest --> Shims
|
||||
D3DX --> DXIL --> D3DM
|
||||
D3DX --> ACCC --> D3DM
|
||||
D3DX -->|"console shaders, at first draw"| Bridge
|
||||
Bridge -->|"HLSL"| DXC
|
||||
DXC -->|"DXIL, cached on disk"| D3DX
|
||||
D3DX --> D3DM
|
||||
D3DX --> XG
|
||||
XMem --> Wine
|
||||
DS --> Wine
|
||||
XGR --> Wine
|
||||
Bridge --> Wine
|
||||
VEH --> Rosetta
|
||||
Wine --> Rosetta
|
||||
CLI -.->|"Launches, sets overrides, summarizes traces"| External
|
||||
CLI -.->|"launches, isolates, stages, reports"| External
|
||||
```
|
||||
|
||||
Design decisions are recorded as ADRs in [docs/adr/](docs/adr/): the CrossOver-based direction (0005), the shader format gate (0008), Xbox-layout Direct3D objects (0009), and using the GDK's own texture libraries and compiler at run time (0010).
|
||||
|
||||
---
|
||||
|
||||
## Repository Layout
|
||||
## Repository layout
|
||||
|
||||
The repository is organized into disjoint track directories around a single frozen `abi/` contract so **5–8+ contributors (and coding agents)** can work concurrently with minimal merge conflicts.
|
||||
Work is split into tracks with their own directories, around one frozen `abi/` contract, so several contributors and coding agents can work at once ([docs/architecture/parallel-tracks.md](docs/architecture/parallel-tracks.md)).
|
||||
|
||||
| Directory | Track | Stack | Contents |
|
||||
| --- | --- | --- | --- |
|
||||
| [`abi/`](abi/README.md) | Shared (frozen) | C headers + `.def` | Versioned cross-DLL headers (`bx_config.h`, `bx_log.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical export tables for all 17 shim DLLs (16 mingw-w64 C++ shims plus the Rust `bx_shader_bridge.dll`) |
|
||||
| `launcher/` | Track A | Rust (`arm64`) | `bx-cli` (`doctor`, `probe`, `shader`, `trace`, `run`), `bx-probe` (PE32+ import classifier), `bx-telemetry` (JSONL trace aggregator) |
|
||||
| `shims/runtime_veh/` | Track A | C++20 (`x86_64` PE) | `bx_runtime_veh.dll`: `clwb` VEH trap, `adcx`/`adox` tripwire, Lockhart/Anaconda memory profile config, structured JSONL logging |
|
||||
| `shims/win32_bridge/` | Track A | C++20 (`x86_64` PE) | `api-ms-win-core-psm-appnotify-l1-1-0/1.dll` stubs and `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders; CrossOver answers these API-set names itself for static imports, so the files are not loaded that way ([ADR 0007](docs/adr/0007-api-set-shims-under-crossover.md)) |
|
||||
| `shims/xmem/`, `shims/xcrdapi/` | Track B | C++20 (`x86_64` PE) | `xmem.dll` (13 Xbox memory APIs + internal region stats) and `XCRDAPI.dll` (`DStorageGetFactory` async I/O) |
|
||||
| `shims/d3d12_xs/`, `shims/xg_xs/`, `shims/ffx_bvh_hooks/` | Track C | C++20 (`x86_64` PE) | Xbox D3D12 COM proxy over D3DMetal 3.0, RDNA 2 texture tiling (`XG`), and future FidelityFX/BVH4 hooks |
|
||||
| `shader-transpiler/` | Track D | Rust (`arm64`) | `dxbc-accc` (`DXBC`/`DXIL`/`ACCC`/`FSPX` classifier), future RDNA 2 transpiler & `d3dmetal-native` isolation harness |
|
||||
| `shims/xgameruntime/`, `shims/gameinput/`, `shims/audio/` | Track E | C++20 (`x86_64` PE) | Offline GDK runtime (`xgameruntime.dll`), `GameInput.dll` (`@1`), and `AcpHal.dll`/`xapu.dll`/`chad.dll` |
|
||||
| [`tests/conformance/`](tests/conformance/README.md) | Track F | C++20 (`x86_64` PE) | Auto-discovered clean-room synthetic PE32+ test binaries (`test_*/CMakeLists.txt`) |
|
||||
| [`abi/`](abi/README.md) | ABI gate | C headers, `.def` | Cross-DLL headers and the canonical export table of every shim DLL (17 DLLs, 118 exports) |
|
||||
| `launcher/` | A | Rust (`arm64`) | `bx-cli`, `bx-probe` (PE32+ import classifier), `bx-telemetry` (JSONL trace aggregator) |
|
||||
| `shims/runtime_veh/`, `shims/win32_bridge/` | A | C++20 (x86-64 PE) | `bx_runtime_veh.dll` (traps for instructions Rosetta 2 lacks, structured logging, fault diagnostics) and API-set forwarders ([ADR 0007](docs/adr/0007-api-set-shims-under-crossover.md)) |
|
||||
| `shims/xmem/`, `shims/xcrdapi/` | B | C++20 (x86-64 PE) | `xmem.dll` (Xbox memory APIs, physical page mapping) and `XCRDAPI.dll` (DirectStorage) |
|
||||
| `shims/d3d12_xs/`, `shims/xg_xs/`, `shims/ffx_bvh_hooks/` | C | C++20 (x86-64 PE) | The Xbox-layout Direct3D 12 layer, `PresentX`, console pipelines translated at first draw, title-memory resources, and the texture-layout shim |
|
||||
| `shader-transpiler/` | D | Rust | `gfx10-translate` (RDNA 2 decoder and translator to HLSL), `dxbc-accc` (container classifier; built for Windows as `bx_shader_bridge.dll`), `d3dmetal-harness` |
|
||||
| `shims/xgameruntime/`, `shims/gameinput/`, `shims/audio/` | E | C++20 (x86-64 PE) | Offline GDK runtime, `GameInput.dll`, and `AcpHal.dll` / `xapu.dll` / `chad.dll` |
|
||||
| [`tests/conformance/`](tests/conformance/README.md), `docs/` | F | C++20 (x86-64 PE), Markdown | 54 synthetic test programs, auto-discovered from `test_*/CMakeLists.txt`, and the documentation |
|
||||
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
## Quick start
|
||||
|
||||
### Requirements
|
||||
### Building and running the synthetic tests
|
||||
|
||||
- **Apple Silicon Mac** running native ARM64 macOS with **Rosetta 2** and **CrossOver 26.3+** (external install).
|
||||
- **Rust toolchain** (`aarch64-apple-darwin`, Rust 1.85+ / 1.100.0).
|
||||
- **`mingw-w64` & `cmake`** (`brew install mingw-w64 cmake`) for cross-compiling x86-64 Windows PE32+ shims on macOS.
|
||||
- **Python 3.11+** for export verification and repository hygiene checks.
|
||||
This needs no game and no GDK:
|
||||
|
||||
### Build & Verify
|
||||
- an **Apple Silicon Mac** with **Rosetta 2** and **CrossOver 26.3+** (licensed separately);
|
||||
- **Rust** 1.85 or later, **Python** 3.11 or later;
|
||||
- `brew install mingw-w64 cmake`.
|
||||
|
||||
```sh
|
||||
git clone https://github.com/MacosPorters/betterxen.git
|
||||
cd betterxen
|
||||
|
||||
# 1. Build & test the native ARM64 Rust workspace (launcher + shader-transpiler)
|
||||
# 1. The native ARM64 Rust workspace (launcher and shader translator)
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo test --workspace
|
||||
cargo build -p bx-cli
|
||||
cargo clippy --locked --workspace --all-targets -- -D warnings
|
||||
cargo test --locked --workspace
|
||||
cargo build --locked -p bx-cli
|
||||
|
||||
# 2. Check host Apple Silicon, Rosetta 2, CrossOver, D3DMetal, and mingw-w64 readiness
|
||||
# 2. Host readiness: Apple Silicon, Rosetta 2, CrossOver, D3DMetal, mingw-w64
|
||||
target/debug/bx-cli doctor
|
||||
|
||||
# 3. Cross-compile the 16 x86-64 PE32+ mingw-w64 shim DLLs, build the Rust
|
||||
# bx_shader_bridge.dll with cargo, and build the conformance binaries
|
||||
# (automatically verifies every abi/defs/*.def export across all 17 DLLs and zero MinGW runtime DLL deps)
|
||||
# 3. Cross-compile the 16 C++ shim DLLs, build the Rust bx_shader_bridge.dll and the
|
||||
# conformance programs; verifies every export of all 17 DLLs against abi/defs/*.def
|
||||
scripts/build-shims.sh
|
||||
|
||||
# 4. Run live synthetic PE32+ conformance tests inside CrossOver + Rosetta 2
|
||||
# 4. Two synthetic tests inside CrossOver and Rosetta 2
|
||||
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_veh_clwb.exe
|
||||
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_shim_exports.exe
|
||||
target/debug/bx-cli trace /tmp/bx-test.jsonl
|
||||
|
||||
# 5. Check Markdown links & repository hygiene
|
||||
# 5. Markdown links and repository hygiene
|
||||
python3 scripts/audit/docs_hygiene.py
|
||||
```
|
||||
|
||||
### `bx-cli` Commands
|
||||
The graphics tests need a CrossOver bottle with D3DMetal (`--bottle <name> --backend d3dmetal`); in a plain prefix they skip.
|
||||
|
||||
### Working on the project
|
||||
|
||||
Contributing needs three more things, and they are a **hard requirement**: the **project-authorized target build**, the **GDK** under the project's authorization, and the **Ghidra results** of the target build. They are distributed among members only. Nothing from them (files, names, hashes, paths, bytes) is ever committed or posted.
|
||||
|
||||
```sh
|
||||
target/debug/bx-cli setup --find # finds the build, the GDK and the Ghidra results on this machine
|
||||
target/debug/bx-cli preflight # must print: Ready to work.
|
||||
```
|
||||
|
||||
Then point a coding agent at the repository and say **"work"**, or follow the same steps by hand. [CONTRIBUTING.md](CONTRIBUTING.md) explains what you need and how work is organised; [AGENTS.md](AGENTS.md) (also `CLAUDE.md`) holds the full rules, including how one item is picked, claimed with a draft pull request, tested and proven.
|
||||
|
||||
### `bx-cli` commands
|
||||
|
||||
| Command | Purpose |
|
||||
| --- | --- |
|
||||
| `bx-cli doctor` | Inspects Apple Silicon host, RAM (recommends `lockhart` on 16 GB Macs or `anaconda` on 32 GB+), Rosetta 2, CrossOver, D3DMetal, and `mingw-w64` |
|
||||
| `bx-cli probe <pe32+>` | Static PE32+ import scanner that classifies every imported DLL into Tracks A–E or Wine built-ins |
|
||||
| `bx-cli shader <blob>` | Classifies a `DXBC` shader container (`DXIL` vs. legacy `SHDR`/`SHEX` vs. `ACCC`/`FSPX`) |
|
||||
| `bx-cli run --exe <path> ...` | Launches a PE32+ binary under CrossOver/Wine with `env_clear()` host isolation (`--inherit-env` opt-in), `ROSETTA_ADVERTISE_AVX=1`, `WINEDLLOVERRIDES`, `BX_PROFILE`, and JSONL trace capture |
|
||||
| `bx-cli trace <log.jsonl>` | Aggregates `bx_runtime_veh.dll` logs (unimplemented API counts, COM vtable misses, `clwb` VEH traps, ADX tripwires) |
|
||||
| `bx-cli doctor` | Inspects the host: chip, memory, Rosetta 2, CrossOver, D3DMetal, `mingw-w64` |
|
||||
| `bx-cli setup [--find]` | Remembers where the target build, the GDK and the Ghidra results are on this machine, outside the repository |
|
||||
| `bx-cli preflight` | Checks everything work needs; fails if anything is missing |
|
||||
| `bx-cli run --exe <path> ...` | Runs a program under CrossOver with a cleared environment, the shim overrides and a JSONL log. For the target build it stages the GDK's libraries beside the shims |
|
||||
| `bx-cli report <log.jsonl>...` | One run report per log, then a summary with blocker signatures |
|
||||
| `bx-cli trace <log.jsonl>` | Summarises a log: unimplemented calls, trapped instructions, shader-gate decisions |
|
||||
| `bx-cli probe <pe32+>` | Classifies a program's imports by track |
|
||||
| `bx-cli shader <blob>` | Classifies a shader container (DXIL, legacy, or console code) |
|
||||
| `bx-cli shader translate <vs> <ps> --out <dir> [--root <layout>]` | Translates a console vertex/pixel pair to HLSL |
|
||||
| `bx-cli shader coverage <dir>` | Counts how many shaders in a folder translate and ranks what blocks the rest |
|
||||
|
||||
---
|
||||
|
||||
## Contributing with Humans & Coding Agents
|
||||
## What is verified, and what is not
|
||||
|
||||
BetterXen is built for **parallel work across 5–8+ contributors and coding agents** (`AGENTS.md` — symlinked as `CLAUDE.md` — holds the full ruleset):
|
||||
**Verified by tests in this repository** (synthetic programs of the project's own, on Apple Silicon with CrossOver 26.3 and Rosetta 2):
|
||||
|
||||
1. **Pick a track & claim an issue** from [docs/issues/wave-1-backlog.md](docs/issues/wave-1-backlog.md) (or GitHub Issues using `.github/ISSUE_TEMPLATE/track-handoff.yml`). Reply `Claiming — branch: track-<a..f>/<issue>-<slug>` before coding.
|
||||
2. **Isolate your branch or worktree:** `git worktree add ../wt-<issue> -b track-<a..f>/<issue>-<slug> origin/main`.
|
||||
3. **Stay inside your issue's exclusive file scope:** Never edit another track's directory inside a feature PR. Need a new cross-DLL helper? Open a small `[ABI]` PR touching only `abi/` first.
|
||||
4. **Add a conflict-free conformance test:** Drop `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` — CMake auto-discovers `test_*` directories with zero edits to shared files.
|
||||
5. **Run the verification commands above**, update [CHANGELOG.md](CHANGELOG.md) under `[Unreleased]`, sign off commits (DCO `Signed-off-by`), and open a PR with `Closes #<issue>`.
|
||||
- All 17 shim DLLs build, and their export tables match `abi/defs/*.def` exactly (118 exports, no extras, no MinGW runtime dependency).
|
||||
- 54 conformance programs cover the shims' contracts: memory mapping, DirectStorage, the Xbox-layout Direct3D objects, `PresentX`, rectangle lists, console formats, the shader gate, and console pipelines translated at first draw.
|
||||
- The translator's output matches a reference translator on its golden pairs, and its instruction decoder matches LLVM's on its test vectors.
|
||||
|
||||
See [AGENTS.md](AGENTS.md), [CONTRIBUTING.md](CONTRIBUTING.md), [docs/architecture/parallel-tracks.md](docs/architecture/parallel-tracks.md), and [docs/README.md](docs/README.md).
|
||||
A conformance test shows that a shim matches the contract the project recorded. It does not show that the recorded contract is what a console does.
|
||||
|
||||
**Observed on the target build, on members' machines** (recorded in pull requests and issues, not reproducible without the build): the states in "Where it stands" above.
|
||||
|
||||
**Not claimed:**
|
||||
|
||||
- Nothing is verified on Xbox hardware. The project has none.
|
||||
- No commercial game is supported or playable.
|
||||
- Translated shaders are not checked against console output yet; most have never been drawn.
|
||||
- Performance has not been measured.
|
||||
|
||||
Evidence classes are defined in [docs/claims.toml](docs/claims.toml).
|
||||
|
||||
---
|
||||
|
||||
## Current Verified Scope & Limitations
|
||||
## Provenance and legal boundaries
|
||||
|
||||
- **Verified (local Apple M5, macOS 27.2.1, CrossOver 26.3, Rosetta 2):**
|
||||
- Native ARM64 `bx-cli`, `bx-probe`, `bx-telemetry`, and `dxbc-accc` unit tests.
|
||||
- All 17 x86-64 PE32+ shim DLLs — the 16 mingw-w64 C++ shims plus the Rust-built `bx_shader_bridge.dll` — pass strict PE Export Directory verification (111 exact names, ordinals, forwarders, 0 extra exports) and carry zero dynamic MinGW runtime dependencies. `scripts/build-shims.sh` cross-compiles the 16 C++ shims with CMake/mingw-w64 and builds `bx_shader_bridge.dll` with `cargo` for `x86_64-pc-windows-gnu`.
|
||||
- `test_veh_clwb.exe` executes AVX2+FMA, traps and skips `clwb` via `bx_runtime_veh.dll`, and exercises starter `XMemAlloc`/`XMemTransferMemory` under CrossOver/Wine.
|
||||
- `test_shim_exports.exe` loads all 16 mingw-w64 C++ shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine.
|
||||
- **Not yet verified at runtime (built and export-verified locally, not run under CrossOver):**
|
||||
- The build of `test_shim_exports.exe` on this revision also loads the Rust-built `bx_shader_bridge.dll` and resolves its three frozen exports (`bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal`, `bx_shader_free_buffer`), so the table covers 17 DLLs / 28 checks. The fixture compiles and links and `scripts/build-shims.sh` confirms the bridge's three exports statically, but the 28-check run across 17 DLLs under CrossOver/Wine has **not** been executed on this revision — the previous 16-DLL / 25-check pass was. Compiling, linking and export agreement do not establish that `LoadLibraryA` / `GetProcAddress` succeed for the bridge. This remains a load-and-resolve check in any case: it does not show the bridge *works*; `test_shader_gate.exe` exercises it functionally.
|
||||
- **Not yet implemented (M1–M6):**
|
||||
- `d3d12_xs.dll` COM device/command-list/PSO proxy and `PresentX` swapchain presentation.
|
||||
- `xmem.dll` physical/scatter page mapping and `XCRDAPI.dll` async DirectStorage queues.
|
||||
- `xg_xs.dll` RDNA 2 texture tiling/deswizzling and DXR/BVH4 rehydration interception.
|
||||
- Console `ACCC`/`FSPX` RDNA 2 → DXIL/MSL shader transpilation (gated on M2).
|
||||
- Real software audio/DSP decoding behind `AcpHal`/`xapu`/`chad` and full `GameInput` polling.
|
||||
- Commercial Xbox game execution.
|
||||
> [!CAUTION]
|
||||
> BetterXen opposes piracy. The repository contains no game files, firmware, keys, DRM circumvention, GDK files or compiler outputs, and none may be added to it or to its history.
|
||||
|
||||
- Contracts that have no public documentation are established from the authorized GDK, from the project-authorized target build (call sites and run-time diagnostics), and from compilers run on the project's own shaders. Each implemented contract gets a synthetic conformance test.
|
||||
- The GDK's own libraries (`xg_xs.dll`, `BCPack.dll`, `dxcompiler.dll`) are loaded at run time from each member's GDK. They are not reimplemented, committed or shipped ([ADR 0010](docs/adr/0010-gdk-texture-libraries.md)).
|
||||
- See [docs/legal.md](docs/legal.md), [docs/licenses.md](docs/licenses.md) and [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
|
||||
|
||||
---
|
||||
|
||||
## Historical Native-First Research
|
||||
## History
|
||||
|
||||
The earlier paused native-first implementation (independent x86-64 interpreter/ARM64 DBT, bounded `gfx1030` RDNA 2 → MSL translator, native Metal backend, and Swift app) was retired from `main` per [ADR 0006](docs/adr/0006-retire-in-tree-native-workspace.md) and remains preserved permanently in Git history at tag `native-first-final`.
|
||||
The earlier native-first implementation (an x86-64 interpreter and ARM64 translator, a native Metal backend and a Swift app) was retired from `main` by [ADR 0006](docs/adr/0006-retire-in-tree-native-workspace.md). It is preserved at the Git tag `native-first-final`.
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
BetterXen is licensed under the [GNU General Public License v3 or later](LICENSE). See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) and [docs/legal.md](docs/legal.md) for attribution and legal scope.
|
||||
BetterXen is licensed under the [GNU General Public License v3 or later](LICENSE).
|
||||
|
||||
BetterXen is an independent open-source project and is not affiliated with Microsoft, Xbox, Apple, CodeWeavers, or any game publisher.
|
||||
BetterXen is an independent open-source project and is not affiliated with Microsoft, Xbox, Apple, CodeWeavers, AMD or any game publisher.
|
||||
@@ -5,3 +5,4 @@ EXPORTS
|
||||
bx_shader_free_buffer
|
||||
bx_shader_translate_pair
|
||||
bx_shader_free_pair_translation
|
||||
bx_shader_translate_pair_rooted
|
||||
@@ -81,9 +81,11 @@ void bx_shader_free_buffer(uint8_t* ptr, size_t len);
|
||||
*
|
||||
* The inputs are the two stages as the title hands them to a pipeline: RDNA 2 code in the
|
||||
* console's shader container, or the bare code. d3d12_xs calls this when such a pipeline is
|
||||
* first drawn, compiles the HLSL with the public DXC (entry point `main`, profiles `vs_6_0` and
|
||||
* `ps_6_0`) and keeps the result on disk under `<vs_key>_<ps_key>` (16 lower-case hex digits
|
||||
* each).
|
||||
* first drawn and compiles the HLSL with a DXC library (entry point `main`, profiles `vs_6_0`
|
||||
* and `ps_6_0`). The two keys identify the pair, in logs and wherever a caller wants a name for
|
||||
* it (`<vs_key>_<ps_key>`, 16 lower-case hex digits each). How compiled shaders are cached is the
|
||||
* caller's business: d3d12_xs names them by a hash of the HLSL, so that a change of the
|
||||
* translator can never reuse an old result.
|
||||
*
|
||||
* All text is UTF-8 without a terminator. A buffer that is not NULL belongs to the caller, who
|
||||
* frees it with bx_shader_free_buffer(ptr, len); bx_shader_free_pair_translation frees all of
|
||||
@@ -123,7 +125,9 @@ typedef struct bx_shader_pair_translation {
|
||||
/*
|
||||
* BX_SHADER_OK: translated. BX_SHADER_ERR_UNSUPPORTED: an input uses something not modelled
|
||||
* (`reason` says what); the pipeline then stays untranslated. BX_SHADER_ERR_INVALID_BLOB: a NULL
|
||||
* or empty input, a NULL `out`, or an input that is not console shader code.
|
||||
* or empty input, a NULL `out`, or an input in a `DXBC` container that holds no console code.
|
||||
* Bare code has no magic to check: bytes that are not shader code are decoded as code and come
|
||||
* back BX_SHADER_ERR_UNSUPPORTED (an unknown or unmodelled instruction), not invalid.
|
||||
* BX_SHADER_ERR_TRANSLATE: an internal failure. `*out` is cleared first in every case.
|
||||
* Thread-safe; holds no state between calls.
|
||||
*/
|
||||
|
||||
+2
-2
@@ -5,7 +5,7 @@
|
||||
- [Project README](../README.md) — Overview, quick start, `bx-cli` commands, and verified scope.
|
||||
- [Roadmap](roadmap.md) — Single authoritative plan: the foundation milestones (M0–M2) and the stages the target build reaches (Boot, Picture, Menus, World, Fidelity, Playable), with exit gates and decision gates.
|
||||
- [Working Method](process/working-method.md) — What an agent does when told "work" — the blocker queue, run protocol, source ranks, pull-request shape and the starting queue.
|
||||
- [Parallel Track Architecture](architecture/parallel-tracks.md) — 6-track directory ownership, ABI freeze rule, and multi-agent Git workflow.
|
||||
- [Parallel Track Architecture](architecture/parallel-tracks.md) — Which track owns which directories, and how the tracks stay apart (one blocker per pull request, ABI first, self-contained tests). The rules themselves are in `AGENTS.md`.
|
||||
- [Wave 1 Parallel Backlog](issues/wave-1-backlog.md) — Non-overlapping starter issues across Tracks A–F.
|
||||
- [Frozen ABI Contracts](../abi/README.md) — Cross-DLL C headers (`abi/include/`) and canonical `.def` export tables (`abi/defs/`).
|
||||
- [Synthetic Conformance Suite](../tests/conformance/README.md) — Auto-discovered PE32+ conformance binaries.
|
||||
@@ -17,7 +17,7 @@
|
||||
- [ADR 0006: Retire in-tree native-first workspace](adr/0006-retire-in-tree-native-workspace.md) — Retirement of paused native code/scripts/docs from `main` (preserved at Git tag `native-first-final`).
|
||||
- [ADR 0007: API-set win32_bridge shims under CrossOver](adr/0007-api-set-shims-under-crossover.md) — Accepted: CrossOver answers the six API-set import names itself, so the shims are not loaded for static imports.
|
||||
- [ADR 0008: M2 Shader Format Gate](adr/0008-m2-shader-format-gate.md) — Proposed: Branch D1 (DXIL through D3DMetal, with the measured wave64 and 64-bit-atomic gaps as M3 work); ACCC-only containers refused with `E_NOTIMPL` until a lawful format source exists.
|
||||
- [ADR 0010: The GDK's texture libraries at run time](adr/0010-gdk-texture-libraries.md) — Accepted: console texture layouts and BCPack come from the GDK's own PC libraries (`xg_xs.dll`, `BCPack.dll`), staged by `bx-cli run` for the target build from each machine's GDK; never reimplemented, committed or shipped.
|
||||
- [ADR 0010: The GDK's own libraries at run time](adr/0010-gdk-texture-libraries.md) — Accepted: console texture layouts and BCPack come from the GDK's own PC libraries (`xg_xs.dll`, `BCPack.dll`), and translated shaders are compiled with its PC `dxcompiler.dll`; all are staged by `bx-cli run` for the target build from each machine's GDK, and never reimplemented, committed or shipped.
|
||||
- [ADR 0009: Xbox-layout D3D12 objects](adr/0009-xbox-layout-d3d12-objects.md) — Proposed: `d3d12_xs` gives titles objects with the Xbox object layout and function-table order (generated from the Xbox header), hosting the PC proxies; Phase 1 covers the device chain and the objects it creates.
|
||||
|
||||
## Research, Testing & Licensing
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# ADR 0010: The GDK's texture libraries at run time
|
||||
# ADR 0010: The GDK's own libraries at run time (textures and the shader compiler)
|
||||
|
||||
Status: **Accepted** (2026-11-30, by the repository owner). The evidence is from local Apple Silicon runs by the implementer.
|
||||
|
||||
@@ -19,8 +19,8 @@ Reimplementing either would mean deriving the console's tiling rules and the BCP
|
||||
2. **From each machine's own GDK.** The libraries come from the GDK configured by `bx-cli setup`, which preflight already requires. They are found by their exports, not their place in the GDK.
|
||||
3. **Never committed or shipped**, unless the project records an authorization that covers redistributing them. Commits name only the documented interfaces (`XGCreateTextureComputer`, `BCPackDecompress`, ...), as with every other GDK contract.
|
||||
4. **Only for the target build.** Conformance tests check BetterXen's own shims, so the GDK's libraries are staged only when the executable is the configured target build, or with `--gdk-libraries`. `--no-gdk-libraries` turns them off.
|
||||
5. **The GDK's PC shader compiler is staged the same way** (added 2026-11-30, #720). `d3d12_xs` compiles the HLSL of translated console shaders with `dxcompiler.dll`, and the GDK carries a PC build of it with `dxil.dll` beside it. `bx-cli run` stages both with the texture libraries, under the same rules: recognised by name and export (`DxcCreateInstance`), never committed or shipped, and only for the target build or with `--gdk-libraries`.
|
||||
5. **BetterXen's `xg_xs` shim stays** as the fallback (and for CI, which has no GDK). Without the GDK's XG, console textures are sized linearly, and the run log says so (`gdk_xg`).
|
||||
5. **The shader compiler is open-source DXC, with the GDK as fallback** (added 2026-11-30, #720; revised #757). `d3d12_xs` compiles the HLSL of translated console shaders with `dxcompiler.dll`. Because Microsoft's prebuilt DXC release zip carries closed-source licence terms (`LICENSE-MS.txt`) and the GDK's `dxcompiler.dll` cannot be redistributed, BetterXen builds `dxcompiler.dll` (x64 Release) from the open-source `microsoft/DirectXShaderCompiler` repository (pinned tag `v1.9.2609`) via `.github/workflows/dxc-build.yml`. `bx-cli run` stages `dxcompiler.dll` from the configured open-source DXC folder (`bx-cli setup --dxc-dir <dir>` / `BX_DXC_DIR`) first, falling back to the GDK's PC `dxcompiler.dll` only when no open-source build is configured. `dxcompiler.dll` is recognised by name and export (`DxcCreateInstance`), never committed to the repository, and `dxil.dll` is not needed (`dxcompiler.dll` alone validates and signs DXIL).
|
||||
6. **BetterXen's `xg_xs` shim stays** as the fallback (and for CI, which has no GDK). Without the GDK's XG, console textures are sized linearly, and the run log says so (`gdk_xg`).
|
||||
|
||||
## Consequences
|
||||
|
||||
|
||||
@@ -1,46 +1,41 @@
|
||||
# Parallel Track Architecture & Contributor Handoff Guide
|
||||
# Parallel Track Architecture
|
||||
|
||||
BetterXen is organized so **5 to 8+ contributors** can develop the CrossOver-based Apple Silicon compatibility stack concurrently via Git and GitHub Issues without merge conflicts.
|
||||
BetterXen is organized so several contributors and coding agents can work at the same time without merge conflicts: the code is split into tracks, each with its own directories, around one frozen `abi/` contract.
|
||||
|
||||
## Repository Layout
|
||||
This page describes the layout. The rules themselves are in [AGENTS.md](../../AGENTS.md) (Sections 0, 2 and 7), and [docs/process/working-method.md](../process/working-method.md) explains the method behind them. Where this page and those disagree, they are right.
|
||||
|
||||
| Directory | Track | Language / Build | Purpose |
|
||||
## Tracks and directories
|
||||
|
||||
| Directory | Track | Language / build | Purpose |
|
||||
| --- | --- | --- | --- |
|
||||
| `abi/` | Shared (frozen) | C headers + `.def` | Cross-DLL contracts (`bx_log.h`, `bx_config.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical DLL export lists |
|
||||
| `launcher/` | Track A | Rust (`aarch64-apple-darwin`) | Native ARM64 macOS CLI (`bx-cli`), PE32+ static probe (`bx-probe`), JSONL trace aggregator (`bx-telemetry`) |
|
||||
| `shims/runtime_veh/` | Track A | C++20 (`mingw-w64`) | `bx_runtime_veh.dll`: `clwb` VEH handler, `adcx`/`adox` tripwire, Lockhart/Anaconda config, JSONL trace logger |
|
||||
| `shims/win32_bridge/` | Track A | C++20 (`mingw-w64`) | PSM AppNotify stubs + `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders; not loaded for static imports under CrossOver ([ADR 0007](../adr/0007-api-set-shims-under-crossover.md)) |
|
||||
| `shims/xmem/` | Track B | C++20 (`mingw-w64`) | `xmem.dll`: physical/virtual/scatter memory allocator, `__XMemAllocationHooks__`, 16 GB Lockhart cap |
|
||||
| `shims/xcrdapi/` | Track B | C++20 (`mingw-w64`) | `XCRDAPI.dll`: DirectStorage async I/O factory, queues, and decompression |
|
||||
| `shims/d3d12_xs/` | Track C1 | C++20 (`mingw-w64`) | `d3d12_xs.dll`: Xbox D3D12 COM proxy over Wine `d3d12.dll` (D3DMetal 3.0), `PresentX`, placed resources |
|
||||
| `shims/xg_xs/` | Track C2 | C++20 (`mingw-w64`) | `xg_xs.dll`: RDNA 2 texture tile addressing & swizzle layout computer |
|
||||
| `shims/ffx_bvh_hooks/` | Track C3 | C++20 (`mingw-w64`) | Optional PC FidelityFX/MetalFX upscaler shim & BVH4 rehydration → DXR live rebuild bridge |
|
||||
| `shader-transpiler/` | Track D | Rust (`aarch64` / C ABI) | `DXBC`/`DXIL`/`ACCC`/`FSPX` shader classifier, RDNA 2 → DXIL/MSL transpiler (M2 gate), shader cache, `d3dmetal-native` harness |
|
||||
| `shims/xgameruntime/` | Track E1 | C++20 (`mingw-w64`) | `xgameruntime.dll`: offline GDK runtime (`XTaskQueue`, `XAsync`, `XUser`, `XStore`, `XSystem`, `XPersistentLocalStorage`) |
|
||||
| `shims/gameinput/`, `shims/audio/` | Track E2 | C++20 (`mingw-w64`) | `GameInput.dll` ordinal 1 adapter + `AcpHal.dll`, `xapu.dll`, `chad.dll` audio/DSP shims |
|
||||
| `tests/conformance/` | Track F | C++20 (`mingw-w64`) | Clean-room synthetic PE32+ test executables verifying each shim under CrossOver/Wine |
|
||||
| `abi/` | ABI gate | C headers, `.def` | Cross-DLL contracts (`bx_log.h`, `bx_config.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and the canonical export list of every shim DLL |
|
||||
| `launcher/` | A | Rust (`aarch64-apple-darwin`) | `bx-cli` (setup, preflight, run, report), `bx-probe` (PE32+ import classifier), `bx-telemetry` (JSONL trace aggregator) |
|
||||
| `shims/runtime_veh/` | A | C++20 (`mingw-w64`) | `bx_runtime_veh.dll`: traps for instructions Rosetta 2 lacks, structured logging, fault diagnostics, the retry for faults on pages being remapped |
|
||||
| `shims/win32_bridge/` | A | C++20 (`mingw-w64`) | PSM AppNotify stubs and `ext-ms-win-rtcore-ntuser-*` forwarders; not loaded for static imports under CrossOver ([ADR 0007](../adr/0007-api-set-shims-under-crossover.md)) |
|
||||
| `shims/xmem/` | B | C++20 (`mingw-w64`) | `xmem.dll`: Xbox virtual and physical memory APIs, physical page mapping, the Lockhart memory budget |
|
||||
| `shims/xcrdapi/` | B | C++20 (`mingw-w64`) | `XCRDAPI.dll`: DirectStorage factory, queues, zlib and BCPack requests |
|
||||
| `shims/d3d12_xs/` | C | C++20 (`mingw-w64`) | `d3d12_xs.dll`: Xbox-layout Direct3D 12 objects over the host's Direct3D 12 ([ADR 0009](../adr/0009-xbox-layout-d3d12-objects.md)), `PresentX`, resources in title memory, console pipelines translated at first draw |
|
||||
| `shims/xg_xs/` | C | C++20 (`mingw-w64`) | `xg_xs.dll`: BetterXen's texture-layout shim. For the target build `bx-cli run` stages the GDK's own library in its place ([ADR 0010](../adr/0010-gdk-texture-libraries.md)) |
|
||||
| `shims/ffx_bvh_hooks/` | C | C++20 (`mingw-w64`) | Reserved for upscaler and BVH work |
|
||||
| `shader-transpiler/` | D | Rust | `gfx10-translate` (RDNA 2 decoder and translator to HLSL), `dxbc-accc` (container classifier and the C interface, built for Windows as `bx_shader_bridge.dll`), `d3dmetal-harness` |
|
||||
| `shims/xgameruntime/` | E | C++20 (`mingw-w64`) | `xgameruntime.dll`: offline GDK runtime (task queues, async, users, saves, packages) |
|
||||
| `shims/gameinput/`, `shims/audio/` | E | C++20 (`mingw-w64`) | `GameInput.dll`, and `AcpHal.dll`, `xapu.dll`, `chad.dll` |
|
||||
| `tests/conformance/`, `docs/` | F | C++20 (`mingw-w64`), Markdown | Synthetic test programs, one folder each (`test_<name>/`), discovered automatically; documentation |
|
||||
|
||||
*(The earlier native-first research workspace was retired from `main` per [ADR 0006](../adr/0006-retire-in-tree-native-workspace.md) and remains permanently accessible at Git tag `native-first-final`.)*
|
||||
The earlier native-first workspace was retired from `main` by [ADR 0006](../adr/0006-retire-in-tree-native-workspace.md) and is preserved at the Git tag `native-first-final`.
|
||||
|
||||
## Milestones (M0 → M6)
|
||||
## How the tracks stay apart
|
||||
|
||||
1. **M0 — Repo, ABI & Cross-Build:** One-command ARM64 + x86-64 PE32+ build, export verification, and `test_veh_clwb.exe` passing under CrossOver + Rosetta 2 (`ROSETTA_ADVERTISE_AVX=1`).
|
||||
2. **M1 — Boot to `D3D12XboxCreateDevice`:** Zero missing imports; all 17 shim DLLs (16 mingw-w64 C++ shims plus the Rust `bx_shader_bridge.dll`) load cleanly; auto-logging COM proxy captures startup call traces.
|
||||
3. **M2 — First Frame & Shader Format Gate:** Present real frames through D3DMetal 3.0 (`PresentX` → `IDXGISwapChain3::Present`) and classify runtime shaders (`DXIL` fast path vs. `ACCC`/`FSPX` RDNA 2 transpilation).
|
||||
4. **M3 — Full Shaders, Streaming & Texture Correctness:** Async DirectStorage decompression, accurate RDNA 2 `xg_xs` tiling/deswizzling, full shader pipeline.
|
||||
5. **M4 — 3D World, Ray Tracing & Input:** BVH4 rehydration → live D3DMetal 3.0 DXR build, FidelityFX/MetalFX upscaling shim, full `GameInput` controller/KB/M mapping.
|
||||
6. **M5 — Real Audio, Saves & Stability:** Software audio/DSP decoding behind `AcpHal`/`xapu`/`chad`, `PersistentLocalStorage` saves, multi-hour soak testing.
|
||||
7. **M6 — Shader Cache, 16 GB Optimization & Polish:** Persistent disk PSO/shader cache, Lockhart 16 GB unified memory tuning, Metal System Trace optimization, Swift launcher UI.
|
||||
- **One blocker, one pull request.** Work is found by running the target build and taking the first thing it stops on. A draft pull request titled with the blocker's signature is the claim; open pull requests are checked first, and a pull request that already covers the problem is worked on, not duplicated.
|
||||
- **Stay in the track's directories.** A fix touches only the directories its blocker needs. Maintainer-directed startup and compatibility work may cross tracks, without overlapping anyone's open claim.
|
||||
- **ABI first.** A new cross-DLL helper or export starts as a small `[ABI]` pull request that touches only `abi/`, so the provider and the consumer can be written in parallel. The header carries the contract; the `.def` line arrives with the implementation, because the build verifies every export.
|
||||
- **Tests never collide.** A conformance test is its own folder, `tests/conformance/test_<name>/` with a `CMakeLists.txt` and a `main.cpp`. Nothing shared is edited to add one.
|
||||
- **Branches.** `track-<a..f>/<slug>` from `origin/main`, in the contributor's own worktree and their own CrossOver bottle.
|
||||
|
||||
## Zero-Conflict Git & Issue Protocol
|
||||
## Stages, not milestones
|
||||
|
||||
- **ABI-first:** Any cross-track header or `.def` change lands first in a small `[ABI]` PR touching only `abi/`.
|
||||
- **Branch naming:** `track-<a..f>/<issue>-<slug>` off `main`, squash-merged daily.
|
||||
- **Exclusive file scope:** Every issue lists the exact directories it may edit (using `.github/ISSUE_TEMPLATE/track-handoff.yml`). Never edit another track's folder in a feature PR.
|
||||
- **Local verification:**
|
||||
```sh
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo test --workspace
|
||||
scripts/build-shims.sh
|
||||
```
|
||||
The first three milestones (M0 to M2) were defined by subsystems and synthetic tests, and are history. Since then progress is measured in stages of what the target build does: Boot, Picture, Menus, World, Fidelity, Playable. [docs/roadmap.md](../roadmap.md) is the single authoritative roadmap and names the current stage.
|
||||
|
||||
## Verification before a pull request
|
||||
|
||||
The commands are in [AGENTS.md](../../AGENTS.md) Section 8: the Rust checks, `scripts/build-shims.sh` (which also verifies every DLL's exports), the live conformance tests under CrossOver, and the documentation check.
|
||||
@@ -11,6 +11,7 @@ Companion to the [upstream registry](upstream-registry.md); same evidence limits
|
||||
| Direct3D 12 to Metal | D3DMetal | **Evaluate as external**, subject to license | Not in CodeWeavers' FOSS list; terms and availability to verify (#349, #354). Not redistributable until proven. |
|
||||
| D3D12 on D3DMetal outside Wine (fault isolation) | utmapp/d3dmetal-native | **Adopt as external, opt-in test dependency** (#417) | MIT; built and run at `af1ee17` (see the registry's M1-D2 section). The user builds it; BetterXen copies none of it, and only the x86_64 probe links it. It forces an x86_64 process under Rosetta 2 because D3DMetal is x86_64-only. BetterXen's arm64 tools drive that process instead of loading the framework. Never use its D3DMetal binary patcher. |
|
||||
| Shader compilation for BetterXen's own test kernels | DirectX Shader Compiler (official release) | **Use as external tool** (#417) | Run under CrossOver Wine because there is no macOS release. Only compiler output of BetterXen's own HLSL is committed, with version and hashes recorded. The package's Microsoft licence terms cover its closed-source parts, which are never redistributed. |
|
||||
| Run-time HLSL compilation for translated console shaders (`dxcompiler.dll`) | DirectX Shader Compiler (source build at `v1.9.2609`) | **Build from source in CI and stage as external binary** (#757) | University of Illinois/NCSA Open Source License (`LICENSE.TXT`, permissive and GPL-3.0-compatible; per-file check recorded in `upstream-registry.md`). Built x64 Release by `.github/workflows/dxc-build.yml` and staged by `bx-cli run` via `--dxc-dir` / `BX_DXC_DIR` ahead of any GDK fallback. No binary is committed to `main`. |
|
||||
| Direct3D 11/10 to Metal | DXMT | **Evaluate** as external binary or build | LGPL 2.1-or-later; usable as a separate process or library under LGPL terms; linking or copying needs legal review (#354). |
|
||||
| Direct3D to Vulkan | DXVK | **Evaluate** only together with MoltenVK | zlib/libpng is permissive and GPL-compatible. Value on macOS unknown. |
|
||||
| Direct3D 12 to Vulkan | VKD3D-Proton | **Evaluate**; blocked on a Vulkan 1.3 provider | Depends on MoltenVK feature coverage, unknown. |
|
||||
|
||||
@@ -92,6 +92,25 @@ Recorded 2026-11-30, for the translator's root-signature layout (#715). Unlike t
|
||||
|
||||
**Inferred:** the layout is a function of the root parameter list alone: each parameter has a root dword index, read from `s(8 + d)` or, in the memory-based form, from byte `4 * d` of the root data. A translator that is given the list (type and number of 32-bit values per parameter) can tell which parameter a shader reads. Not probed: root UAVs in graphics stages, more root data than fits in registers without the flag, what the upper bits of `s1` hold, and the other graphics stages.
|
||||
|
||||
## Directly indexed descriptor heaps (SM 6.6, ACO path)
|
||||
|
||||
Recorded 2026-11-30, from pixel shaders of the target build that index the sampler heap. Their root signature has the flag `0x800`, `D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED`, and their code reads a register past the root data. Probes of the project's own, compiled with `xdxc -T ps_6_6` and read with `cargo run -p gfx10-translate --example listing`:
|
||||
|
||||
| Probe | Root signature | What the code reads |
|
||||
| --- | --- | --- |
|
||||
| s0 | `DescriptorTable(SRV(t0)), RootConstants(2, b0), DescriptorTable(Sampler(s0, numDescriptors=8))` | texture descriptor from the SRV table `s8`; sampler `samplers[idx]` from the sampler table `s11`, at `idx << 4` (`idx` = constant `s9`) |
|
||||
| s2 | `RootFlags(SAMPLER_HEAP_DIRECTLY_INDEXED), DescriptorTable(SRV(t2, space=1)), RootConstants(2, b500)` | texture descriptor from the table `s8`; `SamplerDescriptorHeap[idx]` from `s11`, at `idx << 4` |
|
||||
| s3 | `RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED \| SAMPLER_HEAP_DIRECTLY_INDEXED), RootConstants(2, b500)` | `ResourceDescriptorHeap[other]` from `s10` at `other << 5`; `SamplerDescriptorHeap[idx]` from `s11` at `idx << 4`; `m0` from `s12` |
|
||||
|
||||
**Measured:**
|
||||
- **Heap pointers follow the root data**, one register each: the resource heap (`CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED`, `0x400`) first, then the sampler heap (`SAMPLER_HEAP_DIRECTLY_INDEXED`, `0x800`). With the root data of s2 (`s8`, `s9`, `s10`) the sampler heap is `s11`; with that of s3 (`s8`, `s9`) the resource heap is `s10` and the sampler heap `s11`. A pixel shader's `m0` value follows them (`s12` in s3).
|
||||
- They are **32-bit pointers**, like table pointers: the shader writes 0 to the next register and loads through the pair (`s_mov_b32 s11, 0` then `s_load_dwordx8 s[0:7], s[10:11], s0`), or copies the pointer away first (`s14 = s11`, `s15 = 0`).
|
||||
- **Strides:** a resource descriptor is 32 bytes (`s_lshl_b32 s0, s9, 5`, then `s_load_dwordx8`), a sampler descriptor 16 bytes (`s_lshl_b32 ..., 4`, then `s_load_dwordx4`), the same sizes as table entries.
|
||||
- The target build's shaders with this flag have exactly s2's code at their start (the sampler from `s11` at a root constant times 16), so this is the form ACCC containers carry for `SamplerDescriptorHeap[i]`.
|
||||
- With a sampler table instead of the flag (s0), the code is the same; only what `s11` points at differs.
|
||||
|
||||
**Not probed:** the memory-based form with these flags, vertex shaders, compute (where root data starts at `s4`), and whether a heap pointer can be absent from user data when a stage does not index that heap.
|
||||
|
||||
## Open
|
||||
|
||||
- **Graphics stages:** root data is probed above; vertex and pixel inputs and exports are not.
|
||||
|
||||
@@ -25,7 +25,8 @@ Unlike the table above, these entries were cloned at the stated pin, built and r
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| d3dmetal-native | [utmapp/d3dmetal-native](https://github.com/utmapp/d3dmetal-native) | `af1ee1710711fadff41dead87960d0f1336c1047` (2026-10-26) | Repository `LICENSE`: MIT, © 2026 Turing Software LLC. 34 of 37 `src/` files and the public header carry `SPDX-License-Identifier: MIT`. `src/dmn_dxil_reflect.{cpp,h}`, `src/exports.symbols`, `scripts/` and about half of `tests/` have no per-file notice, so only the repository `LICENSE` covers them. `include/native/` holds WIDL-generated MinGW-w64/Wine headers under LGPL-2.1-or-later (`include/native/directx/README.md`, `COPYING.MinGW-w64.txt`). | External, opt-in, built by the user. It hosts a user-supplied `D3DMetal.framework` outside Wine for the M1-D2 harness. No source is copied into BetterXen. | It builds only as x86_64, because `meson.build` rejects other targets and D3DMetal is x86_64-only. Consumers must therefore be x86_64 processes under Rosetta 2. It loads the framework from an explicit path, `$D3DMETAL_FRAMEWORK_PATH`, or locations next to the dylib. Its optional `scripts/patch_d3dmetal_imports.py` rewrites the D3DMetal binary for App Store builds; BetterXen must not use it, and the harness works with an unpatched framework. Against CrossOver 26.3's D3DMetal 3.0, its `dmn-smoke` and `dmn-device-test` passed, while `d3d12-atomic64-test` read back zeros (not diagnosed). |
|
||||
| directx-native | [osy/directx-native](https://github.com/osy/directx-native) | `7258be1c56cdbf1e55c56b1bc4a866169c8ca0da` (pinned by d3dmetal-native's `subprojects/directx-native.wrap`) | Apache-2.0: repository `LICENSE`, plus `SPDX-License-Identifier: Apache-2.0` in 22 of its 25 files | Build dependency of d3dmetal-native, statically linked into the dylib; nothing is copied into BetterXen | Supplies the shared-resource and embedder headers that `d3dmetal_native.h` includes. Apache-2.0 is compatible with GPL-3.0, not GPL-2.0. |
|
||||
| DirectX Shader Compiler | [microsoft/DirectXShaderCompiler](https://github.com/microsoft/DirectXShaderCompiler/releases/tag/v1.9.2609) | Release `v1.9.2609`, `dxc_2026_09_29.zip`, SHA-256 `ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1` | The package ships the LLVM Release License, an MIT licence and Microsoft Software License Terms (`LICENSE-MS.txt`, covering the closed-source parts of the package) | External tool, used once to compile BetterXen's own HLSL kernel. Only its output (`fill_cs66.h`) is committed. | There is no macOS release, so `bin/x64/dxc.exe` was run under CrossOver 26.3 Wine. It reported `dxcompiler.dll 1.9.2609.5 (01b62ad47)`. |
|
||||
| DirectX Shader Compiler | [microsoft/DirectXShaderCompiler](https://github.com/microsoft/DirectXShaderCompiler/releases/tag/v1.9.2609) | Release `v1.9.2609`, `dxc_2026_09_29.zip`, SHA-256 `ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1` | The prebuilt zip ships the LLVM Release License, an MIT licence and Microsoft Software License Terms (`LICENSE-MS.txt`, covering the closed-source parts of the package) | External tool, used once to compile BetterXen's own HLSL kernel. Only its output (`fill_cs66.h`) is committed. | There is no macOS release, so `bin/x64/dxc.exe` was run under CrossOver 26.3 Wine. It reported `dxcompiler.dll 1.9.2609.5 (01b62ad47)`. |
|
||||
| DirectX Shader Compiler (source build for `dxcompiler.dll`) | [microsoft/DirectXShaderCompiler](https://github.com/microsoft/DirectXShaderCompiler/tree/v1.9.2609) | Tag `v1.9.2609` | Repository `LICENSE.TXT` is the University of Illinois/NCSA Open Source License (LLVM Release License), with third-party notices in `LICENSE.TXT` for `lib/Miniz/*` (MIT / Unlicense), `lib/Support/*` (Henry Spencer), and `include/llvm/Support/ConvertUTF.h` (Unicode). Source files inspected (e.g. `tools/clang/tools/dxcompiler/DXCompiler.cpp`) carry the University of Illinois Open Source License header. No `LICENSE-MS.txt` is present in the source tree. | Run-time HLSL compiler (`dxcompiler.dll`, x64 Release) built from source by `.github/workflows/dxc-build.yml` and staged by `bx-cli run` (#757). | Built from source on Windows to avoid both the GDK's non-redistributable `dxcompiler.dll` and the prebuilt zip's `LICENSE-MS.txt`. `dxcompiler.dll` alone validates and signs DXIL (`dxil.dll` is not needed). |
|
||||
|
||||
## Interface facts for XGameSave and XPackage (#468, #492)
|
||||
|
||||
|
||||
+5
-1
@@ -82,10 +82,14 @@ Every gate below is measured the same way ([working method](process/working-meth
|
||||
This is where the shader translator becomes the critical path, and where the D3DMetal route is tested for real. The risk checks come **first**, before feature work depends on them.
|
||||
|
||||
1. **Capability checks on D3DMetal (first).** Synthetic tests, one each, for what translated shaders need: direct descriptor-heap indexing (SM 6.6), 64-lane compute behaviour through the translator's emulation, 64-bit atomics on typed resources, mesh and amplification shaders. Each ends in *runs correctly*, *can be worked around in the translator*, or *blocked*. A *blocked* result opens an ADR on the back end, marked `needs-human`, before anything else in this stage continues.
|
||||
2. **The translator.** BetterXen writes its own GFX10-to-DXIL translator in `shader-transpiler/` and exposes it through `bx_shader_bridge.dll`; the upstream emulator's translator is not used (repository owner's decision, 2026-11-29). The design is mechanical: one rule per instruction, registers as variables, and control flow as numbered blocks in a dispatch loop, so no structure has to be reconstructed. Each rule is checked against the console compiler's output for a shader of our own (source rank 2). A prototype on branch `experiment/visible-frame` translates the four pipelines of the build's first screen and is the reference for that screen.
|
||||
*State (2026-11-30): not done in this order.* The translator and its run-time path were built first, on the vertex and pixel shaders of the build's first screens, which need none of these capabilities. The checks still come before compute shaders (64-lane behaviour, 64-bit atomics) and before anything that indexes descriptor heaps directly.
|
||||
2. **The translator.** BetterXen writes its own translator in `shader-transpiler/` (`gfx10-translate`) and exposes it through `bx_shader_bridge.dll`; the upstream emulator's translator is not used (repository owner's decision, 2026-11-29). It turns GFX10 code into **HLSL**, not DXIL directly: `d3d12_xs` compiles the HLSL to DXIL with the GDK's PC `dxcompiler.dll` when a pipeline is first drawn, and keeps the result on disk ([ADR 0010](adr/0010-gdk-texture-libraries.md)). The design is mechanical: one rule per instruction, registers as variables, and control flow as numbered blocks in a dispatch loop, so no structure has to be reconstructed.
|
||||
*How rules are checked today:* each rule has a test whose instruction words come from the public LLVM assembler and whose expected HLSL is written from the instruction's definition. Checking against the console compiler's output for a shader of our own (source rank 2) is the standard this item set; so far it has been done for the root-data layout ([docs/research/console-shader-abi.md](research/console-shader-abi.md)) and not rule by rule. The Python prototype on branch `experiment/visible-frame` is kept as a reference; the Rust translator matched its output on the pairs both translate.
|
||||
3. **Translator verification.** Extend the known-source corpus (#650) so every instruction class the first screens use is checked against a reference result. A translator bug is found with a ten-line shader, not in a broken frame.
|
||||
4. **The first pipelines.** The clear pipeline, the display-mapping compute shader, and whatever the first reference screen draws with, created on the host on first use.
|
||||
*State (2026-11-30):* vertex/pixel pipelines are translated at first draw (opt-in, `BX_CONSOLE_SHADERS=1`), and every one the build draws with in its first two minutes translates. Compute pipelines are not translated; their dispatches are skipped (#746).
|
||||
5. **Descriptors and memory the shaders read.** The descriptor model the translated shaders expect; contents of textures placed in title memory (today a logged stub); title-written constant and vertex data reaching the GPU.
|
||||
*State (2026-11-30):* descriptors the title copies itself are followed, and root signature layouts are passed to the translator. Open: texture contents (#745), and why the first screen shows only its background bars (#744). Two known simplifications: every translated shader samples with one fixed sampler (#750), and a descriptor table is widened for its first 8 entries only (#751).
|
||||
|
||||
### Menus to Playable — known work and unknowns
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! The GDK's own texture libraries, staged for runs of the target build (ADR 0010).
|
||||
//! Runtime texture and shader-compiler libraries staged for runs of the target build (ADR 0010).
|
||||
//!
|
||||
//! Console textures use tiled layouts and BCPack compression. BetterXen does not reimplement
|
||||
//! either: a run of the target build loads Microsoft's PC builds of the GDK's XG library
|
||||
@@ -12,10 +12,11 @@
|
||||
//! `BCPackDecompress`. Conformance tests keep BetterXen's own shim: the GDK's are staged only
|
||||
//! for the configured target build, or with `--gdk-libraries`.
|
||||
//!
|
||||
//! The same staging brings the GDK's PC shader compiler (#720): `dxcompiler.dll` and, when
|
||||
//! present, the `dxil.dll` beside it. `d3d12_xs` compiles the HLSL of translated console shaders
|
||||
//! with it. They are x86-64 PE32+ files with exactly those names that export
|
||||
//! `DxcCreateInstance`; the console compilers in the GDK have other names.
|
||||
//! `d3d12_xs` compiles the HLSL of translated console shaders with `dxcompiler.dll` (#720, #757).
|
||||
//! `dxcompiler.dll` is taken first from the configured BetterXen-built open-source DXC folder
|
||||
//! (`--dxc-dir` / `BX_DXC_DIR`), falling back to the GDK's PC `dxcompiler.dll` only if no
|
||||
//! open-source build is configured. It is recognised as an x86-64 PE32+ file named
|
||||
//! `dxcompiler.dll` that exports `DxcCreateInstance`; `dxil.dll` is not needed.
|
||||
|
||||
use std::fs;
|
||||
use std::io;
|
||||
@@ -27,10 +28,8 @@ use bx_probe::probe_pe32_plus;
|
||||
pub struct GdkLibraries {
|
||||
pub xg: Option<PathBuf>,
|
||||
pub bcpack: Option<PathBuf>,
|
||||
/// The PC `dxcompiler.dll`.
|
||||
/// The PC `dxcompiler.dll` (open-source DXC first, GDK fallback).
|
||||
pub dxc: Option<PathBuf>,
|
||||
/// The `dxil.dll` in the same folder as `dxc`, when there is one.
|
||||
pub dxil: Option<PathBuf>,
|
||||
}
|
||||
|
||||
fn contains(bytes: &[u8], needle: &[u8]) -> bool {
|
||||
@@ -55,11 +54,43 @@ pub fn is_bcpack(bytes: &[u8]) -> bool {
|
||||
probe_pe32_plus(bytes).is_ok() && contains(bytes, b"BCPackDecompress\0")
|
||||
}
|
||||
|
||||
/// Whether `bytes` are a PC DXC library (`dxcompiler.dll` or `dxil.dll`).
|
||||
/// Whether `bytes` are a PC `dxcompiler.dll` (x86-64 PE32+ exporting `DxcCreateInstance`).
|
||||
pub fn is_dxc(bytes: &[u8]) -> bool {
|
||||
probe_pe32_plus(bytes).is_ok() && contains(bytes, b"DxcCreateInstance\0")
|
||||
}
|
||||
|
||||
/// Finds `dxcompiler.dll` under `dir` (bounded depth), recognised by name and `DxcCreateInstance`.
|
||||
pub fn find_dxc(dir: &Path) -> Option<PathBuf> {
|
||||
let mut dxc = Vec::new();
|
||||
let mut stack = vec![(dir.to_path_buf(), 0usize)];
|
||||
while let Some((cur, depth)) = stack.pop() {
|
||||
let Ok(entries) = fs::read_dir(&cur) else {
|
||||
continue;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
let Ok(kind) = entry.file_type() else {
|
||||
continue;
|
||||
};
|
||||
if kind.is_dir() {
|
||||
if depth < 14 {
|
||||
stack.push((path, depth + 1));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let name = entry.file_name().to_string_lossy().to_ascii_lowercase();
|
||||
if name != "dxcompiler.dll" {
|
||||
continue;
|
||||
}
|
||||
if fs::read(&path).is_ok_and(|bytes| is_dxc(&bytes)) {
|
||||
dxc.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
dxc.sort();
|
||||
dxc.into_iter().next()
|
||||
}
|
||||
|
||||
/// Finds the libraries under `root` (bounded depth). When the GDK holds several builds,
|
||||
/// the first by path order is used, so the choice is the same on every run.
|
||||
pub fn find(root: &Path) -> GdkLibraries {
|
||||
@@ -101,23 +132,26 @@ pub fn find(root: &Path) -> GdkLibraries {
|
||||
xg.sort();
|
||||
bcpack.sort();
|
||||
dxc.sort();
|
||||
let dxc = dxc.into_iter().next();
|
||||
let dxil = dxc
|
||||
.as_ref()
|
||||
.and_then(|d| d.parent())
|
||||
.map(|dir| dir.join("dxil.dll"))
|
||||
.filter(|p| fs::read(p).is_ok_and(|bytes| is_dxc(&bytes)));
|
||||
GdkLibraries {
|
||||
xg: xg.into_iter().next(),
|
||||
bcpack: bcpack.into_iter().next(),
|
||||
dxc,
|
||||
dxil,
|
||||
dxc: dxc.into_iter().next(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds `out` as a copy of the shim folder's files with the GDK's libraries added: its
|
||||
/// `xg_xs.dll` replaces BetterXen's shim, and `BCPack.dll` sits beside it. Returns the path of
|
||||
/// the staged `BCPack.dll`, when there is one.
|
||||
/// Resolves runtime libraries, preferring BetterXen-built open-source `dxcompiler.dll` under
|
||||
/// `dxc_dir` and falling back to the GDK's `dxcompiler.dll` under `gdk_root` only if needed.
|
||||
pub fn resolve(dxc_dir: Option<&Path>, gdk_root: Option<&Path>) -> GdkLibraries {
|
||||
let mut libs = gdk_root.map(find).unwrap_or_default();
|
||||
if let Some(dxc) = dxc_dir.and_then(find_dxc) {
|
||||
libs.dxc = Some(dxc);
|
||||
}
|
||||
libs
|
||||
}
|
||||
|
||||
/// Builds `out` as a copy of the shim folder's files with the runtime libraries added: the
|
||||
/// GDK's `xg_xs.dll` replaces BetterXen's shim, `dxcompiler.dll` is staged beside it, and
|
||||
/// `BCPack.dll` sits beside it. Returns the path of the staged `BCPack.dll`, when there is one.
|
||||
pub fn merge_shims(shims: &Path, libs: &GdkLibraries, out: &Path) -> io::Result<Option<PathBuf>> {
|
||||
fs::create_dir_all(out)?;
|
||||
for entry in fs::read_dir(shims)? {
|
||||
@@ -132,9 +166,6 @@ pub fn merge_shims(shims: &Path, libs: &GdkLibraries, out: &Path) -> io::Result<
|
||||
if let Some(dxc) = &libs.dxc {
|
||||
fs::copy(dxc, out.join("dxcompiler.dll"))?;
|
||||
}
|
||||
if let Some(dxil) = &libs.dxil {
|
||||
fs::copy(dxil, out.join("dxil.dll"))?;
|
||||
}
|
||||
match &libs.bcpack {
|
||||
Some(bcpack) => {
|
||||
let staged = out.join("BCPack.dll");
|
||||
@@ -197,15 +228,12 @@ mod tests {
|
||||
.unwrap();
|
||||
fs::write(gdk.join("c/xg_xs.dll"), pe(b"XGCreateTextureComputer\0")).unwrap(); // not the PC library
|
||||
fs::write(gdk.join("c/BCPack.dll"), pe(b"BCPackDecompress\0")).unwrap();
|
||||
// The PC compiler and the dxil.dll beside it; a console compiler has another name, and
|
||||
// a dxil.dll elsewhere is not taken.
|
||||
// The PC compiler; a console compiler has another name, and dxil.dll is not needed.
|
||||
fs::write(gdk.join("a/dxcompiler.dll"), pe(b"DxcCreateInstance\0")).unwrap();
|
||||
fs::write(gdk.join("a/dxil.dll"), pe(b"DxcCreateInstance\0dxil")).unwrap();
|
||||
fs::write(gdk.join("c/dxcompiler_xs.dll"), pe(b"DxcCreateInstance\0")).unwrap();
|
||||
fs::write(gdk.join("c/dxil.dll"), pe(b"DxcCreateInstance\0other")).unwrap();
|
||||
let libs = find(&gdk);
|
||||
assert_eq!(libs.dxc, Some(gdk.join("a/dxcompiler.dll")));
|
||||
assert_eq!(libs.dxil, Some(gdk.join("a/dxil.dll")));
|
||||
assert_eq!(libs.xg, Some(gdk.join("a/b/xg_xs.dll")));
|
||||
assert_eq!(libs.bcpack, Some(gdk.join("c/BCPack.dll")));
|
||||
|
||||
@@ -226,11 +254,53 @@ mod tests {
|
||||
fs::read(out.join("dxcompiler.dll")).unwrap(),
|
||||
fs::read(gdk.join("a/dxcompiler.dll")).unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read(out.join("dxil.dll")).unwrap(),
|
||||
fs::read(gdk.join("a/dxil.dll")).unwrap()
|
||||
);
|
||||
assert!(!out.join("dxil.dll").exists());
|
||||
assert!(!out.join("dxcompiler_xs.dll").exists());
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_source_dxc_takes_precedence_over_gdk_fallback() {
|
||||
let root = std::env::temp_dir().join(format!("bx-dxc-prec-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
let gdk = root.join("gdk");
|
||||
let dxc_dir = root.join("open-source-dxc");
|
||||
let empty_dir = root.join("empty");
|
||||
fs::create_dir_all(&gdk).unwrap();
|
||||
fs::create_dir_all(&dxc_dir).unwrap();
|
||||
fs::create_dir_all(&empty_dir).unwrap();
|
||||
|
||||
fs::write(
|
||||
gdk.join("xg_xs.dll"),
|
||||
pe(b"XGCreateTextureComputer\0XGComputeTexture2DLayout\0"),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(gdk.join("dxcompiler.dll"), pe(b"DxcCreateInstance\0gdk")).unwrap();
|
||||
fs::write(
|
||||
dxc_dir.join("dxcompiler.dll"),
|
||||
pe(b"DxcCreateInstance\0oss"),
|
||||
)
|
||||
.unwrap();
|
||||
// A file without DxcCreateInstance is ignored.
|
||||
fs::write(empty_dir.join("dxcompiler.dll"), pe(b"NotDxc\0")).unwrap();
|
||||
|
||||
// Open-source DXC wins over GDK fallback.
|
||||
let libs = resolve(Some(&dxc_dir), Some(&gdk));
|
||||
assert_eq!(libs.dxc, Some(dxc_dir.join("dxcompiler.dll")));
|
||||
assert_eq!(libs.xg, Some(gdk.join("xg_xs.dll")));
|
||||
|
||||
// Without dxc_dir (or with an invalid one), GDK dxcompiler.dll is used as fallback.
|
||||
let fallback = resolve(None, Some(&gdk));
|
||||
assert_eq!(fallback.dxc, Some(gdk.join("dxcompiler.dll")));
|
||||
let invalid_dxc = resolve(Some(&empty_dir), Some(&gdk));
|
||||
assert_eq!(invalid_dxc.dxc, Some(gdk.join("dxcompiler.dll")));
|
||||
|
||||
// Open-source DXC works even without a GDK.
|
||||
let oss_only = resolve(Some(&dxc_dir), None);
|
||||
assert_eq!(oss_only.dxc, Some(dxc_dir.join("dxcompiler.dll")));
|
||||
assert_eq!(oss_only.xg, None);
|
||||
assert_eq!(oss_only.bcpack, None);
|
||||
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
@@ -74,7 +74,7 @@ fn usage_text() -> &'static str {
|
||||
bx-cli shader <dxbc_blob_path> Classify a DXBC shader container (DXIL vs ACCC/FSPX)\n\
|
||||
bx-cli shader translate <vs> <ps> --out <dir> [--root <layout>] Translate a console VS/PS pair to HLSL (gfx10-translate); <layout> is the root signature's parameters, e.g. T,S:0:0,C2:1:0,B:2:0[,mem]\n\
|
||||
bx-cli shader coverage <dir> Rank what blocks translation across a folder of *_VS.* / *_PS.* shaders\n\
|
||||
bx-cli setup [--find] [--target-exe <path>] [--gdk-root <dir>] [--ghidra-results <dir>] Remember where the target build, the GDK and the target build's Ghidra results are on this machine (saved outside the repository); --find searches the home folder for them\n\
|
||||
bx-cli setup [--find] [--target-exe <path>] [--gdk-root <dir>] [--ghidra-results <dir>] [--dxc-dir <dir>] Remember where the target build, the GDK, the target build's Ghidra results and open-source DXC are on this machine (saved outside the repository); --find searches the home folder for them\n\
|
||||
bx-cli preflight Check everything work needs: host, CrossOver, the target build, the GDK, the Ghidra results, disk space. Fails if anything is missing\n\
|
||||
bx-cli trace <log.jsonl> Summarize bx_runtime_veh JSONL diagnostics\n\
|
||||
bx-cli report <log.jsonl>... Run report per log (one log = one run), then a summary with blocker signatures\n\
|
||||
@@ -245,6 +245,7 @@ fn local_setting(env_name: &str, key: &str, config: &BTreeMap<String, String>) -
|
||||
const TARGET_EXE_KEY: &str = "target_exe";
|
||||
const GDK_ROOT_KEY: &str = "gdk_root";
|
||||
const GHIDRA_RESULTS_KEY: &str = "ghidra_results";
|
||||
const DXC_DIR_KEY: &str = "dxc_dir";
|
||||
|
||||
/// The static-analysis results of the target build, recognised by structure: a folder with the
|
||||
/// run's `RUN_REPORT.md`, a `decompiled/` folder, and `exports/<program>/` folders each holding a
|
||||
@@ -580,6 +581,7 @@ fn cmd_setup(args: &[String]) -> ExitCode {
|
||||
"--target-exe" => (TARGET_EXE_KEY, check_target_exe),
|
||||
"--gdk-root" => (GDK_ROOT_KEY, check_gdk_root),
|
||||
"--ghidra-results" => (GHIDRA_RESULTS_KEY, check_ghidra_results),
|
||||
"--dxc-dir" => (DXC_DIR_KEY, check_dxc_dir),
|
||||
other => {
|
||||
eprintln!("error: unknown argument: {other}");
|
||||
return ExitCode::FAILURE;
|
||||
@@ -624,6 +626,7 @@ fn cmd_setup(args: &[String]) -> ExitCode {
|
||||
" Ghidra results: {}",
|
||||
state(GHIDRA_RESULTS_KEY, check_ghidra_results)
|
||||
);
|
||||
println!(" DXC : {}", state(DXC_DIR_KEY, check_dxc_dir));
|
||||
println!("They are kept outside the repository. Run `bx-cli preflight` to check everything.");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
@@ -669,6 +672,22 @@ fn check_ghidra_for_target(results: Option<&str>, target: Option<&str>) -> Resul
|
||||
}
|
||||
}
|
||||
|
||||
/// Open-source DXC: the setting must be a folder that contains a PC `dxcompiler.dll`
|
||||
/// exporting `DxcCreateInstance`.
|
||||
fn check_dxc_dir(value: Option<&str>) -> Result<String, String> {
|
||||
let dir = value.filter(|v| !v.is_empty()).ok_or(
|
||||
"not set (optional; GDK dxcompiler.dll used as fallback, or run `bx-cli setup --dxc-dir <folder with dxcompiler.dll>`)",
|
||||
)?;
|
||||
let path = Path::new(dir);
|
||||
if !path.is_dir() {
|
||||
return Err("the saved path is not a folder".to_owned());
|
||||
}
|
||||
match gdk_libs::find_dxc(path) {
|
||||
Some(_) => Ok("present (dxcompiler.dll found)".to_owned()),
|
||||
None => Err("no PC dxcompiler.dll exporting DxcCreateInstance under it".to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The GDK: the setting must be a folder that contains the GDK's `d3d12_xs.h`.
|
||||
fn check_gdk_root(value: Option<&str>) -> Result<String, String> {
|
||||
let root = value
|
||||
@@ -1623,8 +1642,9 @@ fn cmd_run(args: &[String]) -> ExitCode {
|
||||
let mut abs_shims = fs::canonicalize(&shims_dir).unwrap_or(shims_dir);
|
||||
let abs_exe = fs::canonicalize(&exe).unwrap_or(exe);
|
||||
|
||||
// The GDK's texture libraries (gdk_libs.rs, ADR 0010): staged for the configured target
|
||||
// build, or with --gdk-libraries, from the GDK configured on this machine.
|
||||
// Runtime texture and shader-compiler libraries (gdk_libs.rs, ADR 0010): staged for the
|
||||
// configured target build, or with --gdk-libraries. Open-source DXC (`--dxc-dir` /
|
||||
// `BX_DXC_DIR`) takes precedence for `dxcompiler.dll`, with the GDK as fallback.
|
||||
let config = local_config_path()
|
||||
.map(|p| read_local_config(&p))
|
||||
.unwrap_or_default();
|
||||
@@ -1634,31 +1654,45 @@ fn cmd_run(args: &[String]) -> ExitCode {
|
||||
let mut staged_bcpack: Option<PathBuf> = None;
|
||||
let mut gdk_shims_dir: Option<PathBuf> = None;
|
||||
if gdk_libraries.unwrap_or(is_target) {
|
||||
match local_setting("BX_GDK_ROOT", GDK_ROOT_KEY, &config) {
|
||||
Some(root) => {
|
||||
let libs = gdk_libs::find(Path::new(&root));
|
||||
let out = env::temp_dir().join(format!("bx-gdk-shims-{}", std::process::id()));
|
||||
match gdk_libs::merge_shims(&abs_shims, &libs, &out) {
|
||||
Ok(bcpack) => {
|
||||
let state = |found: bool| if found { "staged" } else { "not found" };
|
||||
diag(format_args!(
|
||||
"bx-cli: GDK libraries: XG {}, BCPack {}, DXC {}",
|
||||
state(libs.xg.is_some()),
|
||||
state(bcpack.is_some()),
|
||||
state(libs.dxc.is_some())
|
||||
));
|
||||
staged_bcpack = bcpack;
|
||||
abs_shims = out.clone();
|
||||
gdk_shims_dir = Some(out);
|
||||
}
|
||||
Err(e) => diag(format_args!(
|
||||
"warning: GDK texture libraries not staged: {e}"
|
||||
)),
|
||||
let dxc_dir = local_setting("BX_DXC_DIR", DXC_DIR_KEY, &config);
|
||||
let gdk_root = local_setting("BX_GDK_ROOT", GDK_ROOT_KEY, &config);
|
||||
if dxc_dir.is_none() && gdk_root.is_none() {
|
||||
diag(
|
||||
"warning: GDK texture libraries and DXC not staged: neither GDK nor DXC configured (bx-cli setup --find / --dxc-dir)",
|
||||
);
|
||||
} else {
|
||||
let libs = gdk_libs::resolve(
|
||||
dxc_dir.as_deref().map(Path::new),
|
||||
gdk_root.as_deref().map(Path::new),
|
||||
);
|
||||
let dxc_from_oss = dxc_dir
|
||||
.as_deref()
|
||||
.is_some_and(|dir| libs.dxc.as_ref().is_some_and(|p| p.starts_with(dir)));
|
||||
let out = env::temp_dir().join(format!("bx-gdk-shims-{}", std::process::id()));
|
||||
match gdk_libs::merge_shims(&abs_shims, &libs, &out) {
|
||||
Ok(bcpack) => {
|
||||
let state = |found: bool| if found { "staged" } else { "not found" };
|
||||
let dxc_state = if libs.dxc.is_none() {
|
||||
"not found"
|
||||
} else if dxc_from_oss {
|
||||
"staged (open-source)"
|
||||
} else {
|
||||
"staged (GDK fallback)"
|
||||
};
|
||||
diag(format_args!(
|
||||
"bx-cli: runtime libraries: XG {}, BCPack {}, DXC {}",
|
||||
state(libs.xg.is_some()),
|
||||
state(bcpack.is_some()),
|
||||
dxc_state
|
||||
));
|
||||
staged_bcpack = bcpack;
|
||||
abs_shims = out.clone();
|
||||
gdk_shims_dir = Some(out);
|
||||
}
|
||||
Err(e) => diag(format_args!(
|
||||
"warning: GDK texture libraries not staged: {e}"
|
||||
)),
|
||||
}
|
||||
None => diag(
|
||||
"warning: GDK texture libraries not staged: no GDK configured (bx-cli setup --find)",
|
||||
),
|
||||
}
|
||||
}
|
||||
struct RemoveOnDrop(Option<PathBuf>);
|
||||
@@ -3085,15 +3119,49 @@ sub setup_bottle_wineprefix {
|
||||
"free space is measurable for an existing folder"
|
||||
);
|
||||
|
||||
// Open-source DXC: unset, not a folder, folder without dxcompiler.dll, folder with valid PE32+ dxcompiler.dll.
|
||||
assert!(check_dxc_dir(None).unwrap_err().contains("not set"));
|
||||
assert!(
|
||||
check_dxc_dir(pe.to_str())
|
||||
.unwrap_err()
|
||||
.contains("not a folder")
|
||||
);
|
||||
let dxc_dir = dir.join("dxc");
|
||||
fs::create_dir_all(&dxc_dir).unwrap();
|
||||
assert!(
|
||||
check_dxc_dir(dxc_dir.to_str())
|
||||
.unwrap_err()
|
||||
.contains("no PC dxcompiler.dll")
|
||||
);
|
||||
let mut fake_dxc = vec![0u8; 0x200];
|
||||
fake_dxc[0..2].copy_from_slice(b"MZ");
|
||||
fake_dxc[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
|
||||
fake_dxc[0x40..0x44].copy_from_slice(b"PE\0\0");
|
||||
fake_dxc[0x44..0x46].copy_from_slice(&0x8664u16.to_le_bytes());
|
||||
fake_dxc[0x54..0x56].copy_from_slice(&240u16.to_le_bytes());
|
||||
fake_dxc[0x58..0x5A].copy_from_slice(&0x020Bu16.to_le_bytes());
|
||||
fake_dxc[0x58 + 108..0x58 + 112].copy_from_slice(&16u32.to_le_bytes());
|
||||
fake_dxc.extend_from_slice(b"DxcCreateInstance\0");
|
||||
fs::write(dxc_dir.join("dxcompiler.dll"), &fake_dxc).unwrap();
|
||||
assert!(check_dxc_dir(dxc_dir.to_str()).unwrap().contains("found"));
|
||||
|
||||
// Local settings: written, read back, unknown keys kept, comments ignored; the
|
||||
// environment variable wins over the saved value.
|
||||
let conf = dir.join("conf/local.conf");
|
||||
let mut values = BTreeMap::new();
|
||||
values.insert(TARGET_EXE_KEY.to_owned(), pe.to_string_lossy().into_owned());
|
||||
values.insert(
|
||||
DXC_DIR_KEY.to_owned(),
|
||||
dxc_dir.to_string_lossy().into_owned(),
|
||||
);
|
||||
values.insert("future_key".to_owned(), "kept".to_owned());
|
||||
write_local_config(&conf, &values).unwrap();
|
||||
let read = read_local_config(&conf);
|
||||
assert_eq!(read, values);
|
||||
assert_eq!(
|
||||
local_setting("BX_TEST_UNSET_VARIABLE_FOR_PREFLIGHT", DXC_DIR_KEY, &read).as_deref(),
|
||||
dxc_dir.to_str()
|
||||
);
|
||||
assert!(
|
||||
fs::read_to_string(&conf)
|
||||
.unwrap()
|
||||
|
||||
@@ -482,7 +482,77 @@ fn publish(text: &str, buffer: &mut *mut u8, len: &mut usize) -> Result<(), ()>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn translate_pair_status(vs: &[u8], ps: &[u8], out: &mut BxShaderPairTranslation) -> i32 {
|
||||
/// Mirror of `bx_shader_root_parameter_t`.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct BxShaderRootParameter {
|
||||
pub r#type: u32,
|
||||
pub num_32bit_values: u32,
|
||||
pub shader_register: u32,
|
||||
pub register_space: u32,
|
||||
}
|
||||
|
||||
/// Mirror of `bx_shader_root_layout_t`.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct BxShaderRootLayout {
|
||||
pub parameters: *const BxShaderRootParameter,
|
||||
pub parameter_count: u32,
|
||||
pub flags: u32,
|
||||
}
|
||||
|
||||
/// D3D12XBOX_ROOT_SIGNATURE_FLAG_FORCE_MEMORY_BASED_ABI.
|
||||
const ROOT_FLAG_MEMORY_BASED: u32 = 0x0100_0000;
|
||||
/// More parameters than a root signature can have (its cost limit is 64 values).
|
||||
const MAX_ROOT_PARAMETERS: u32 = 64;
|
||||
|
||||
/// The translator's layout for a C layout; None when it is inconsistent.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `layout.parameters` must be readable for `parameter_count` entries when it is non-null.
|
||||
unsafe fn root_layout(layout: &BxShaderRootLayout) -> Option<gfx10_translate::RootLayout> {
|
||||
use gfx10_translate::{RootKind, RootParameter};
|
||||
if layout.parameter_count > MAX_ROOT_PARAMETERS
|
||||
|| (layout.parameters.is_null() && layout.parameter_count != 0)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let parameters: &[BxShaderRootParameter] = if layout.parameter_count == 0 {
|
||||
&[]
|
||||
} else {
|
||||
// SAFETY: non-null, and the caller guarantees `parameter_count` readable entries.
|
||||
unsafe { std::slice::from_raw_parts(layout.parameters, layout.parameter_count as usize) }
|
||||
};
|
||||
let mut out = gfx10_translate::RootLayout {
|
||||
parameters: Vec::with_capacity(parameters.len()),
|
||||
memory_based: layout.flags & ROOT_FLAG_MEMORY_BASED != 0,
|
||||
};
|
||||
for p in parameters {
|
||||
let kind = match p.r#type {
|
||||
0 => RootKind::Table,
|
||||
1 => RootKind::Constants,
|
||||
2 => RootKind::Cbv,
|
||||
3 => RootKind::Srv,
|
||||
4 => RootKind::Uav,
|
||||
_ => return None,
|
||||
};
|
||||
out.parameters.push(RootParameter {
|
||||
kind,
|
||||
values: p.num_32bit_values,
|
||||
register: p.shader_register,
|
||||
space: p.register_space,
|
||||
});
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn translate_pair_status(
|
||||
vs: &[u8],
|
||||
ps: &[u8],
|
||||
root: Option<&gfx10_translate::RootLayout>,
|
||||
out: &mut BxShaderPairTranslation,
|
||||
) -> i32 {
|
||||
if vs.is_empty() || ps.is_empty() {
|
||||
return BX_SHADER_ERR_INVALID_BLOB;
|
||||
}
|
||||
@@ -495,7 +565,11 @@ fn translate_pair_status(vs: &[u8], ps: &[u8], out: &mut BxShaderPairTranslation
|
||||
{
|
||||
return BX_SHADER_ERR_INVALID_BLOB;
|
||||
}
|
||||
match gfx10_translate::translate_blobs(vs, ps) {
|
||||
let translated = match root {
|
||||
Some(layout) => gfx10_translate::translate_blobs_rooted(vs, ps, layout),
|
||||
None => gfx10_translate::translate_blobs(vs, ps),
|
||||
};
|
||||
match translated {
|
||||
Ok(t) => {
|
||||
let published = publish(&t.vs_hlsl, &mut out.vs_hlsl, &mut out.vs_hlsl_len)
|
||||
.and_then(|()| publish(&t.ps_hlsl, &mut out.ps_hlsl, &mut out.ps_hlsl_len))
|
||||
@@ -527,6 +601,27 @@ pub unsafe extern "C" fn bx_shader_translate_pair(
|
||||
ps_bytes: *const u8,
|
||||
ps_len: usize,
|
||||
out: *mut BxShaderPairTranslation,
|
||||
) -> i32 {
|
||||
// SAFETY: the caller's guarantees are those of the rooted form with no layout.
|
||||
unsafe { bx_shader_translate_pair_rooted(vs_bytes, vs_len, ps_bytes, ps_len, ptr::null(), out) }
|
||||
}
|
||||
|
||||
/// Translate a console vertex/pixel shader pair given the layout of the pipeline's root
|
||||
/// signature (see `bx_shader_translate_pair_rooted` in abi/include/bx_shader_bridge.h). A null
|
||||
/// `layout` gives `bx_shader_translate_pair`.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// As [`bx_shader_translate_pair`]. `layout` must be null or point to a readable
|
||||
/// `bx_shader_root_layout_t` whose `parameters` is readable for `parameter_count` entries.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn bx_shader_translate_pair_rooted(
|
||||
vs_bytes: *const u8,
|
||||
vs_len: usize,
|
||||
ps_bytes: *const u8,
|
||||
ps_len: usize,
|
||||
layout: *const BxShaderRootLayout,
|
||||
out: *mut BxShaderPairTranslation,
|
||||
) -> i32 {
|
||||
if out.is_null() {
|
||||
return BX_SHADER_ERR_INVALID_BLOB;
|
||||
@@ -536,7 +631,17 @@ pub unsafe extern "C" fn bx_shader_translate_pair(
|
||||
let mut result = BxShaderPairTranslation::EMPTY;
|
||||
let status = match catch_unwind(AssertUnwindSafe(|| {
|
||||
match (input_bytes(vs_bytes, vs_len), input_bytes(ps_bytes, ps_len)) {
|
||||
(Some(vs), Some(ps)) => translate_pair_status(vs, ps, &mut result),
|
||||
(Some(vs), Some(ps)) => {
|
||||
if layout.is_null() {
|
||||
translate_pair_status(vs, ps, None, &mut result)
|
||||
} else {
|
||||
// SAFETY: non-null, and the caller guarantees the layout is readable.
|
||||
match unsafe { root_layout(&*layout) } {
|
||||
Some(root) => translate_pair_status(vs, ps, Some(&root), &mut result),
|
||||
None => BX_SHADER_ERR_INVALID_BLOB,
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => BX_SHADER_ERR_INVALID_BLOB,
|
||||
}
|
||||
})) {
|
||||
|
||||
@@ -49,8 +49,9 @@ use std::fmt;
|
||||
pub use c_abi::{
|
||||
BX_SHADER_ERR_INVALID_BLOB, BX_SHADER_ERR_OOM, BX_SHADER_ERR_TRANSLATE,
|
||||
BX_SHADER_ERR_UNSUPPORTED, BX_SHADER_OK, BxShaderInspection, BxShaderPairTranslation,
|
||||
bx_shader_free_buffer, bx_shader_free_pair_translation, bx_shader_inspect,
|
||||
bx_shader_prepare_for_d3dmetal, bx_shader_translate_pair,
|
||||
BxShaderRootLayout, BxShaderRootParameter, bx_shader_free_buffer,
|
||||
bx_shader_free_pair_translation, bx_shader_inspect, bx_shader_prepare_for_d3dmetal,
|
||||
bx_shader_translate_pair, bx_shader_translate_pair_rooted,
|
||||
};
|
||||
pub use fspx::{FSPX_MAX_SECTIONS, FspxCodeBounds, FspxInfo, FspxSection, FspxStageConfig};
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ use dxbc_accc::{
|
||||
BX_SHADER_ERR_INVALID_BLOB, BX_SHADER_ERR_UNSUPPORTED, BX_SHADER_OK, BxShaderPairTranslation,
|
||||
bx_shader_free_pair_translation, bx_shader_translate_pair,
|
||||
};
|
||||
use dxbc_accc::{BxShaderRootLayout, BxShaderRootParameter, bx_shader_translate_pair_rooted};
|
||||
|
||||
const VS_HEX: &str = include_str!("../../gfx10-translate/tests/goldens/textured.vs.hex");
|
||||
const PS_HEX: &str = include_str!("../../gfx10-translate/tests/goldens/textured.ps.hex");
|
||||
@@ -131,3 +132,110 @@ fn unreadable_inputs_are_invalid() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// One root SRV at t5: s0 = s8 ; s1 = s9 | (1 << 16) ; s2 = -1 ; s3 = 0x11014fac ; v1 = v0 + v0 ;
|
||||
// buffer_load_dwordx3 v[1:3], v1, s[0:3], 8 offen offset:4 ; v4 = 1.0 ; exp pos0 ; s_endpgm
|
||||
// (our own assembly through llvm-mc; the same program as gfx10-translate's root-buffer test).
|
||||
const ROOT_SRV_VS: &str = "be800308 8801ff09 00010000 be8203c1 be8303ff 11014fac 4a020100 e03c1004 88000101 7e0802f2 f80008cf 04030201 bf810000";
|
||||
/// v_mov_b32 v0, 1.0 ; exp mrt0 v0, v0, v0, v0 done vm ; s_endpgm
|
||||
const FLAT_PS: &str = "7e0002f2 f800180f 00000000 bf810000";
|
||||
|
||||
fn translate_rooted(
|
||||
vs: &[u8],
|
||||
ps: &[u8],
|
||||
layout: *const BxShaderRootLayout,
|
||||
) -> (i32, BxShaderPairTranslation) {
|
||||
let mut out = std::mem::MaybeUninit::<BxShaderPairTranslation>::uninit();
|
||||
// SAFETY: the inputs are readable slices, `layout` is null or valid, `out` is writable.
|
||||
let status = unsafe {
|
||||
bx_shader_translate_pair_rooted(
|
||||
vs.as_ptr(),
|
||||
vs.len(),
|
||||
ps.as_ptr(),
|
||||
ps.len(),
|
||||
layout,
|
||||
out.as_mut_ptr(),
|
||||
)
|
||||
};
|
||||
// SAFETY: the bridge fills `out` in every case.
|
||||
(status, unsafe { out.assume_init() })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_root_layout_changes_what_the_registers_mean() {
|
||||
let (vs, ps) = (code(ROOT_SRV_VS), code(FLAT_PS));
|
||||
// Without a layout s8 is taken for a table pointer, and building a buffer from it is refused.
|
||||
let (status, mut t) = translate_rooted(&vs, &ps, std::ptr::null());
|
||||
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
|
||||
unsafe { bx_shader_free_pair_translation(&mut t) };
|
||||
// With the layout "one root SRV at t5, space 3" it is that parameter's buffer.
|
||||
let parameters = [BxShaderRootParameter {
|
||||
r#type: 3,
|
||||
num_32bit_values: 0,
|
||||
shader_register: 5,
|
||||
register_space: 3,
|
||||
}];
|
||||
let layout = BxShaderRootLayout {
|
||||
parameters: parameters.as_ptr(),
|
||||
parameter_count: 1,
|
||||
flags: 0,
|
||||
};
|
||||
let (status, mut t) = translate_rooted(&vs, &ps, &layout);
|
||||
assert_eq!(status, BX_SHADER_OK);
|
||||
let hlsl = text(t.vs_hlsl, t.vs_hlsl_len);
|
||||
assert!(
|
||||
hlsl.contains("ByteAddressBuffer rootbuf0 : register(t5, space3);"),
|
||||
"{hlsl}"
|
||||
);
|
||||
assert!(hlsl.contains("uint vertex_id : SV_VertexID"), "{hlsl}");
|
||||
assert_eq!(text(t.layout, t.layout_len), "USE ROOT 0\n");
|
||||
unsafe { bx_shader_free_pair_translation(&mut t) };
|
||||
// The memory-based flag changes where root data is read: this register-form shader then
|
||||
// reads nothing the layout accounts for and is refused.
|
||||
let memory = BxShaderRootLayout {
|
||||
flags: 0x0100_0000,
|
||||
..layout
|
||||
};
|
||||
let (status, mut t) = translate_rooted(&vs, &ps, &memory);
|
||||
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
|
||||
unsafe { bx_shader_free_pair_translation(&mut t) };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inconsistent_layouts_are_invalid() {
|
||||
let (vs, ps) = (code(ROOT_SRV_VS), code(FLAT_PS));
|
||||
// A count without parameters.
|
||||
let missing = BxShaderRootLayout {
|
||||
parameters: std::ptr::null(),
|
||||
parameter_count: 2,
|
||||
flags: 0,
|
||||
};
|
||||
let (status, t) = translate_rooted(&vs, &ps, &missing);
|
||||
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
|
||||
assert!(t.vs_hlsl.is_null() && t.reason.is_null());
|
||||
// A parameter type Direct3D 12 does not have.
|
||||
let parameters = [BxShaderRootParameter {
|
||||
r#type: 9,
|
||||
num_32bit_values: 0,
|
||||
shader_register: 0,
|
||||
register_space: 0,
|
||||
}];
|
||||
let unknown = BxShaderRootLayout {
|
||||
parameters: parameters.as_ptr(),
|
||||
parameter_count: 1,
|
||||
flags: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
translate_rooted(&vs, &ps, &unknown).0,
|
||||
BX_SHADER_ERR_INVALID_BLOB
|
||||
);
|
||||
// An empty signature is a layout like any other: the shader reads past it and is refused.
|
||||
let empty = BxShaderRootLayout {
|
||||
parameters: std::ptr::null(),
|
||||
parameter_count: 0,
|
||||
flags: 0,
|
||||
};
|
||||
let (status, mut t) = translate_rooted(&vs, &ps, &empty);
|
||||
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
|
||||
unsafe { bx_shader_free_pair_translation(&mut t) };
|
||||
}
|
||||
@@ -1,15 +1,28 @@
|
||||
//! The GPU code of one stage from a console shader container.
|
||||
//!
|
||||
//! A console container is a DXBC file whose DXIL part carries no bitcode. The console code is in
|
||||
//! an `XBCH` record: magic, version, compressed size (u64), uncompressed size (u64), then a zlib
|
||||
//! stream. It inflates to an `FSSM` block: a 16-byte header (magic, version, size), then offsets
|
||||
//! relative to the end of that header. One of the per-stage slots at 0x18..0x78 is not
|
||||
//! 0xDEADBEEF filler and locates the stage record, whose first two u64 fields are the code offset
|
||||
//! and size. The code starts with 12-byte header records (a VOP3 word whose top half is 0xD580,
|
||||
//! `v_nop` with a literal) before the first instruction.
|
||||
//! A console container is a DXBC file whose DXIL part carries no bitcode (or carries an `XDAT`
|
||||
//! section after the bitcode/`NOBC` placeholder). The console code is in an `XBCH` record:
|
||||
//! - `+0..+4`: magic `b"XBCH"`
|
||||
//! - `+4..+8`: version (`u32`, low byte checked: `2` = uncompressed `FSSM` payload of `csize`
|
||||
//! bytes at `+24`; `3` = zlib-compressed `FSSM` stream of `csize` bytes at `+24` inflating to
|
||||
//! `usize` bytes; synthetic conformance tests also use `1` for zlib-compressed)
|
||||
//! - `+8..+16`: `csize` (`u64`), payload/compressed stream size in bytes
|
||||
//! - `+16..+24`: `usize` (`u64`), uncompressed size in bytes (used for zlib-compressed records)
|
||||
//! - `+24..+24+csize`: payload (`FSSM` block or zlib stream)
|
||||
//!
|
||||
//! These are inferences from containers of the project-authorized target build (AGENTS.md
|
||||
//! section 6), checked by the synthetic container in the tests below.
|
||||
//! It inflates (or decodes directly for version 2) to an `FSSM` block: a 16-byte header (magic,
|
||||
//! version, size), then offsets relative to the end of that header. One of the per-stage slots
|
||||
//! at 0x18..0x78 is not 0xDEADBEEF filler and locates the stage record, whose first two u64 fields
|
||||
//! are the code offset and size. The code starts with 12-byte header records (a VOP3 word whose
|
||||
//! top half is 0xD580, `v_nop` with a literal) before the first instruction.
|
||||
//!
|
||||
//! Because the 4-byte sequence `b"XBCH"` can also appear incidentally in earlier chunks (such as
|
||||
//! `STAT` or `DXIL` bitcode) before the real `XBCH` record, [`container_code`] scans all `b"XBCH"`
|
||||
//! occurrences and validates each candidate's header, bounds, version, and `FSSM` magic rather than
|
||||
//! stopping at the first match.
|
||||
//!
|
||||
//! These are inferences from containers of the project-authorized target build and the GDK
|
||||
//! compiler (`AGENTS.md` section 6), checked by the synthetic containers in the tests below.
|
||||
|
||||
use crate::inflate::zlib_inflate;
|
||||
use std::fmt;
|
||||
@@ -47,31 +60,49 @@ fn u64_at(b: &[u8], at: usize) -> Option<u64> {
|
||||
Some(u64::from_le_bytes(b.get(at..at + 8)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
/// The stage code inside a console container, header records included.
|
||||
pub fn container_code(blob: &[u8]) -> Result<Vec<u8>, ContainerError> {
|
||||
let at = blob
|
||||
.windows(4)
|
||||
.position(|w| w == b"XBCH")
|
||||
.ok_or(ContainerError::NoXbch)?;
|
||||
let csize = u64_at(blob, at + 8).ok_or(ContainerError::BadXbch("truncated header"))? as usize;
|
||||
let usize_ = u64_at(blob, at + 16).ok_or(ContainerError::BadXbch("truncated header"))? as usize;
|
||||
let stream = blob
|
||||
.get(at + 24..at.saturating_add(24).saturating_add(csize))
|
||||
fn try_xbch_at(blob: &[u8], at: usize) -> Result<Vec<u8>, ContainerError> {
|
||||
let ver = u32_at(blob, at + 4).ok_or(ContainerError::BadXbch("truncated header"))? & 0xff;
|
||||
let csize_u64 = u64_at(blob, at + 8).ok_or(ContainerError::BadXbch("truncated header"))?;
|
||||
let usize_u64 = u64_at(blob, at + 16).ok_or(ContainerError::BadXbch("truncated header"))?;
|
||||
let csize = usize::try_from(csize_u64)
|
||||
.map_err(|_| ContainerError::BadXbch("compressed size past the end"))?;
|
||||
let end = at
|
||||
.checked_add(24)
|
||||
.and_then(|start| start.checked_add(csize))
|
||||
.filter(|&end| end <= blob.len())
|
||||
.ok_or(ContainerError::BadXbch("compressed size past the end"))?;
|
||||
let fssm = zlib_inflate(stream, usize_.min(MAX_FSSM))
|
||||
.map_err(|_| ContainerError::BadXbch("zlib stream"))?;
|
||||
if fssm.len() != usize_ || fssm.get(..4) != Some(b"FSSM") {
|
||||
return Err(ContainerError::BadXbch("does not inflate to an FSSM block"));
|
||||
let payload = &blob[at + 24..end];
|
||||
match ver {
|
||||
2 => {
|
||||
if payload.get(..4) != Some(b"FSSM") {
|
||||
return Err(ContainerError::BadXbch("does not inflate to an FSSM block"));
|
||||
}
|
||||
Ok(payload.to_vec())
|
||||
}
|
||||
1 | 3 => {
|
||||
let usize_ = usize::try_from(usize_u64)
|
||||
.map_err(|_| ContainerError::BadXbch("does not inflate to an FSSM block"))?;
|
||||
let fssm = zlib_inflate(payload, usize_.min(MAX_FSSM))
|
||||
.map_err(|_| ContainerError::BadXbch("zlib stream"))?;
|
||||
if fssm.len() != usize_ || fssm.get(..4) != Some(b"FSSM") {
|
||||
return Err(ContainerError::BadXbch("does not inflate to an FSSM block"));
|
||||
}
|
||||
Ok(fssm)
|
||||
}
|
||||
_ => Err(ContainerError::BadXbch("unsupported version")),
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_fssm_code(fssm: &[u8]) -> Result<Vec<u8>, ContainerError> {
|
||||
const BASE: usize = 16;
|
||||
let record = (0x18..0x78)
|
||||
.step_by(8)
|
||||
.filter_map(|slot| u64_at(&fssm, slot))
|
||||
.filter_map(|slot| u64_at(fssm, slot))
|
||||
.find(|&v| v != FILLER)
|
||||
.ok_or(ContainerError::NoStageRecord)? as usize
|
||||
+ BASE;
|
||||
let offset = u64_at(&fssm, record).ok_or(ContainerError::NoStageRecord)? as usize;
|
||||
let size = u64_at(&fssm, record + 8).ok_or(ContainerError::NoStageRecord)? as usize;
|
||||
let offset = u64_at(fssm, record).ok_or(ContainerError::NoStageRecord)? as usize;
|
||||
let size = u64_at(fssm, record + 8).ok_or(ContainerError::NoStageRecord)? as usize;
|
||||
let code = fssm
|
||||
.get(BASE + offset..BASE + offset + size)
|
||||
.ok_or(ContainerError::BadCode("outside the FSSM block"))?;
|
||||
@@ -83,6 +114,21 @@ pub fn container_code(blob: &[u8]) -> Result<Vec<u8>, ContainerError> {
|
||||
Ok(code.to_vec())
|
||||
}
|
||||
|
||||
/// The stage code inside a console container, header records included.
|
||||
pub fn container_code(blob: &[u8]) -> Result<Vec<u8>, ContainerError> {
|
||||
let mut last_err = None;
|
||||
for (at, w) in blob.windows(4).enumerate() {
|
||||
if w != b"XBCH" {
|
||||
continue;
|
||||
}
|
||||
match try_xbch_at(blob, at) {
|
||||
Ok(fssm) => return extract_fssm_code(&fssm),
|
||||
Err(e) => last_err = Some(e),
|
||||
}
|
||||
}
|
||||
Err(last_err.unwrap_or(ContainerError::NoXbch))
|
||||
}
|
||||
|
||||
/// The instruction words of a stage: from a console container (`DXBC` magic) or a raw code blob,
|
||||
/// with the leading 12-byte header records skipped.
|
||||
pub fn code_words(blob: &[u8]) -> Result<Vec<u32>, ContainerError> {
|
||||
@@ -125,9 +171,7 @@ mod tests {
|
||||
s
|
||||
}
|
||||
|
||||
/// A container laid out as the module comment describes: one header record, then two
|
||||
/// instruction words, the stage record in slot 0x30.
|
||||
fn container(code_words_after_header: &[u32]) -> Vec<u8> {
|
||||
fn build_fssm(code_words_after_header: &[u32]) -> Vec<u8> {
|
||||
let mut code = Vec::new();
|
||||
code.extend_from_slice(&0xD580_0000u32.to_le_bytes());
|
||||
code.extend_from_slice(&[0u8; 8]);
|
||||
@@ -146,17 +190,33 @@ mod tests {
|
||||
fssm[16 + record + 8..16 + record + 16].copy_from_slice(&(code.len() as u64).to_le_bytes());
|
||||
fssm.resize(16 + code_offset as usize, 0);
|
||||
fssm.extend_from_slice(&code);
|
||||
let stream = stored(&fssm);
|
||||
fssm
|
||||
}
|
||||
|
||||
fn container_with_version(code_words_after_header: &[u32], version: u32) -> Vec<u8> {
|
||||
let fssm = build_fssm(code_words_after_header);
|
||||
let (payload, usize_) = if (version & 0xff) == 2 {
|
||||
(fssm, 0u64)
|
||||
} else {
|
||||
let usize_ = fssm.len() as u64;
|
||||
(stored(&fssm), usize_)
|
||||
};
|
||||
let mut blob = b"DXBC".to_vec();
|
||||
blob.extend_from_slice(&[0u8; 28]);
|
||||
blob.extend_from_slice(b"XBCH");
|
||||
blob.extend_from_slice(&1u32.to_le_bytes());
|
||||
blob.extend_from_slice(&(stream.len() as u64).to_le_bytes());
|
||||
blob.extend_from_slice(&(fssm.len() as u64).to_le_bytes());
|
||||
blob.extend_from_slice(&stream);
|
||||
blob.extend_from_slice(&version.to_le_bytes());
|
||||
blob.extend_from_slice(&(payload.len() as u64).to_le_bytes());
|
||||
blob.extend_from_slice(&usize_.to_le_bytes());
|
||||
blob.extend_from_slice(&payload);
|
||||
blob
|
||||
}
|
||||
|
||||
/// A container laid out as the module comment describes: one header record, then two
|
||||
/// instruction words, the stage record in slot 0x30.
|
||||
fn container(code_words_after_header: &[u32]) -> Vec<u8> {
|
||||
container_with_version(code_words_after_header, 1)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_the_stage_code_and_skips_header_records() {
|
||||
let blob = container(&[0xBF81_0000, 0x1234_5678]);
|
||||
@@ -171,6 +231,24 @@ mod tests {
|
||||
assert_eq!(code_words(&raw).unwrap(), vec![0xBF81_0000]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_incidental_xbch_bytes_before_the_record() {
|
||||
let mut blob = container_with_version(&[0xBF81_0000, 0x1234_5678], 3);
|
||||
// Simulate an incidental "XBCH" sequence in an earlier chunk (e.g. STAT or DXIL bitcode)
|
||||
// whose +8 bytes look like a compressed size past the end of the container.
|
||||
blob[8..12].copy_from_slice(b"XBCH");
|
||||
blob[16..24].copy_from_slice(&u64::MAX.to_le_bytes());
|
||||
assert_eq!(code_words(&blob).unwrap(), vec![0xBF81_0000, 0x1234_5678]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supports_uncompressed_version_2_and_compressed_version_3() {
|
||||
let v2 = container_with_version(&[0xBF81_0000], 2);
|
||||
assert_eq!(code_words(&v2).unwrap(), vec![0xBF81_0000]);
|
||||
let v3 = container_with_version(&[0xBF81_0000], 3);
|
||||
assert_eq!(code_words(&v3).unwrap(), vec![0xBF81_0000]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_what_is_missing() {
|
||||
assert_eq!(
|
||||
@@ -181,5 +259,11 @@ mod tests {
|
||||
let at = blob.windows(4).position(|w| w == b"XBCH").unwrap();
|
||||
blob[at + 24] = 0; // break the zlib header
|
||||
assert!(matches!(code_words(&blob), Err(ContainerError::BadXbch(_))));
|
||||
|
||||
let v4 = container_with_version(&[0xBF81_0000], 4);
|
||||
assert_eq!(
|
||||
code_words(&v4),
|
||||
Err(ContainerError::BadXbch("unsupported version"))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,13 @@
|
||||
* static sampler. That sampler is linear and wrapping whatever the title asked for: the console
|
||||
* sampler a shader names is not decoded yet.
|
||||
*
|
||||
* Root signature layouts (#715). A console shader's root arguments are packed values in
|
||||
* root-parameter order, so which register holds which parameter depends on the parameter list
|
||||
* (docs/research/console-shader-abi.md). Each root signature's list is kept with its host object
|
||||
* and handed to the translator (bx_shader_translate_pair_rooted). Root CBVs, SRVs, UAVs and
|
||||
* constants are then declared at the title's own registers, which the root signature already
|
||||
* has; only descriptor tables need the widening above.
|
||||
*
|
||||
* Not handled here, and logged when met: pipelines with other stages, stream output or view
|
||||
* instancing; table entries beyond the widened range.
|
||||
*/
|
||||
@@ -38,6 +45,7 @@
|
||||
#include <dxcapi.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
@@ -99,9 +107,12 @@ HMODULE load_beside(const wchar_t* name) {
|
||||
|
||||
using TranslateFn = bx_shader_status_t (*)(const uint8_t*, size_t, const uint8_t*, size_t, bx_shader_pair_translation_t*);
|
||||
using FreeTranslationFn = void (*)(bx_shader_pair_translation_t*);
|
||||
using TranslateRootedFn = bx_shader_status_t (*)(const uint8_t*, size_t, const uint8_t*, size_t, const bx_shader_root_layout_t*,
|
||||
bx_shader_pair_translation_t*);
|
||||
|
||||
struct Tools {
|
||||
TranslateFn translate = nullptr;
|
||||
TranslateRootedFn translate_rooted = nullptr; // absent in an older bridge: every parameter is then taken for a table
|
||||
FreeTranslationFn release = nullptr;
|
||||
DxcCreateInstanceProc dxc = nullptr;
|
||||
};
|
||||
@@ -113,6 +124,8 @@ const Tools& tools() {
|
||||
t.translate = reinterpret_cast<TranslateFn>(reinterpret_cast<void*>(GetProcAddress(bridge, "bx_shader_translate_pair")));
|
||||
t.release = reinterpret_cast<FreeTranslationFn>(
|
||||
reinterpret_cast<void*>(GetProcAddress(bridge, "bx_shader_free_pair_translation")));
|
||||
t.translate_rooted = reinterpret_cast<TranslateRootedFn>(
|
||||
reinterpret_cast<void*>(GetProcAddress(bridge, "bx_shader_translate_pair_rooted")));
|
||||
}
|
||||
if (HMODULE dxc = load_beside(L"dxcompiler.dll")) {
|
||||
t.dxc = reinterpret_cast<DxcCreateInstanceProc>(reinterpret_cast<void*>(GetProcAddress(dxc, "DxcCreateInstance")));
|
||||
@@ -265,6 +278,47 @@ Fn host_d3d12(const char* name) {
|
||||
return d3d12 ? reinterpret_cast<Fn>(reinterpret_cast<void*>(GetProcAddress(d3d12, name))) : nullptr;
|
||||
}
|
||||
|
||||
/* What the translator needs to know about a root signature: its parameters and flags. */
|
||||
struct RootLayout {
|
||||
std::vector<bx_shader_root_parameter_t> parameters;
|
||||
UINT flags = 0;
|
||||
};
|
||||
|
||||
std::mutex g_root_lock;
|
||||
std::unordered_map<const void*, std::shared_ptr<RootLayout>> g_root_layouts; // by host root signature
|
||||
|
||||
/* The layout of a serialized root signature, or nullptr when it cannot be read. */
|
||||
std::shared_ptr<RootLayout> read_layout(const void* blob, size_t size) {
|
||||
static const DeserializerFn deserialize = host_d3d12<DeserializerFn>("D3D12CreateVersionedRootSignatureDeserializer");
|
||||
if (!deserialize || !blob || !size) return nullptr;
|
||||
ID3D12VersionedRootSignatureDeserializer* d = nullptr;
|
||||
if (FAILED(deserialize(blob, size, __uuidof(ID3D12VersionedRootSignatureDeserializer), reinterpret_cast<void**>(&d))) || !d) {
|
||||
return nullptr;
|
||||
}
|
||||
std::shared_ptr<RootLayout> layout;
|
||||
const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* v = nullptr;
|
||||
if (SUCCEEDED(d->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &v)) && v) {
|
||||
layout = std::make_shared<RootLayout>();
|
||||
layout->flags = static_cast<UINT>(v->Desc_1_1.Flags);
|
||||
for (UINT i = 0; i < v->Desc_1_1.NumParameters; ++i) {
|
||||
const D3D12_ROOT_PARAMETER1& p = v->Desc_1_1.pParameters[i];
|
||||
bx_shader_root_parameter_t out{};
|
||||
out.type = static_cast<uint32_t>(p.ParameterType);
|
||||
if (p.ParameterType == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS) {
|
||||
out.num_32bit_values = p.Constants.Num32BitValues;
|
||||
out.shader_register = p.Constants.ShaderRegister;
|
||||
out.register_space = p.Constants.RegisterSpace;
|
||||
} else if (p.ParameterType != D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) {
|
||||
out.shader_register = p.Descriptor.ShaderRegister;
|
||||
out.register_space = p.Descriptor.RegisterSpace;
|
||||
}
|
||||
layout->parameters.push_back(out);
|
||||
}
|
||||
}
|
||||
d->Release();
|
||||
return layout;
|
||||
}
|
||||
|
||||
/* The title's root signature with the translated shaders' ranges and sampler added, or nullptr. */
|
||||
ID3DBlob* widen(const void* blob, size_t size) {
|
||||
static const DeserializerFn deserialize = host_d3d12<DeserializerFn>("D3D12CreateVersionedRootSignatureDeserializer");
|
||||
@@ -334,6 +388,19 @@ bool bx_console_shaders_enabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
namespace {
|
||||
/* Keeps the layout of the title's blob with the host root signature just created from it. */
|
||||
void remember_layout(void* host_root, const void* blob, size_t size) {
|
||||
std::shared_ptr<RootLayout> layout = read_layout(blob, size);
|
||||
std::lock_guard<std::mutex> guard(g_root_lock);
|
||||
if (layout) {
|
||||
g_root_layouts[host_root] = std::move(layout);
|
||||
} else {
|
||||
g_root_layouts.erase(host_root); // an address reused by a signature that cannot be read
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
HRESULT bx_console_create_root_signature(ID3D12Device* device, UINT node_mask, const void* blob, SIZE_T size, REFIID riid,
|
||||
void** ppv) {
|
||||
if (bx_console_shaders_enabled() && blob && size) {
|
||||
@@ -342,7 +409,10 @@ HRESULT bx_console_create_root_signature(ID3D12Device* device, UINT node_mask, c
|
||||
if (wide) {
|
||||
const HRESULT hr = device->CreateRootSignature(node_mask, wide->GetBufferPointer(), wide->GetBufferSize(), riid, ppv);
|
||||
wide->Release();
|
||||
if (SUCCEEDED(hr)) return hr;
|
||||
if (SUCCEEDED(hr)) {
|
||||
remember_layout(*ppv, blob, size);
|
||||
return hr;
|
||||
}
|
||||
}
|
||||
uint64_t total = 0;
|
||||
if (sampled(refused, &total)) {
|
||||
@@ -350,6 +420,9 @@ HRESULT bx_console_create_root_signature(ID3D12Device* device, UINT node_mask, c
|
||||
"a root signature could not be widened for translated shaders (%s); the title's own is used; total=%llu",
|
||||
wide ? "the host refused the widened form" : "it could not be read or serialized", static_cast<unsigned long long>(total));
|
||||
}
|
||||
const HRESULT hr = device->CreateRootSignature(node_mask, blob, size, riid, ppv);
|
||||
if (SUCCEEDED(hr)) remember_layout(*ppv, blob, size);
|
||||
return hr;
|
||||
}
|
||||
return device->CreateRootSignature(node_mask, blob, size, riid, ppv);
|
||||
}
|
||||
@@ -478,7 +551,20 @@ void prepare(BxConsolePipeline* p) {
|
||||
if (!t.translate || !t.release) return;
|
||||
const ULONGLONG started = GetTickCount64();
|
||||
bx_shader_pair_translation_t out{};
|
||||
const bx_shader_status_t status = t.translate(p->vs_code.data(), p->vs_code.size(), p->ps_code.data(), p->ps_code.size(), &out);
|
||||
// With the root signature's layout when both sides have it; otherwise as a signature of tables.
|
||||
std::shared_ptr<RootLayout> root;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_root_lock);
|
||||
auto it = g_root_layouts.find(p->root);
|
||||
if (it != g_root_layouts.end()) root = it->second;
|
||||
}
|
||||
bx_shader_status_t status;
|
||||
if (root && t.translate_rooted) {
|
||||
const bx_shader_root_layout_t layout{root->parameters.data(), static_cast<uint32_t>(root->parameters.size()), root->flags};
|
||||
status = t.translate_rooted(p->vs_code.data(), p->vs_code.size(), p->ps_code.data(), p->ps_code.size(), &layout, &out);
|
||||
} else {
|
||||
status = t.translate(p->vs_code.data(), p->vs_code.size(), p->ps_code.data(), p->ps_code.size(), &out);
|
||||
}
|
||||
std::string why;
|
||||
if (status == BX_SHADER_OK) {
|
||||
const std::string layout(reinterpret_cast<const char*>(out.layout), out.layout_len);
|
||||
@@ -504,7 +590,11 @@ void prepare(BxConsolePipeline* p) {
|
||||
e.AlignedByteOffset = d;
|
||||
e.InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA;
|
||||
p->elements.push_back(e);
|
||||
} else if (std::sscanf(line.c_str(), "USE %7s %u %u", kind, &a, &b) >= 2) {
|
||||
} else if (std::sscanf(line.c_str(), "USE %7s %u %u", kind, &a, &b) >= 2 &&
|
||||
(std::strcmp(kind, "CB") == 0 || std::strcmp(kind, "TEX") == 0)) {
|
||||
// Only CB and TEX lines name descriptor-table entries. `USE ROOT <parameter>` is a
|
||||
// root constants or root descriptor parameter, which the host root signature binds
|
||||
// as it is (abi/include/bx_shader_bridge.h); other kinds are ignored.
|
||||
const int numbers = std::sscanf(line.c_str(), "USE %7s %u %u", kind, &a, &b) - 1;
|
||||
const unsigned entry = numbers == 2 ? b : a;
|
||||
p->uses.push_back({std::strcmp(kind, "TEX") == 0, numbers == 2 ? a : 0, entry});
|
||||
|
||||
@@ -270,6 +270,74 @@ void note_unbacked(const char* what, D3D12_GPU_VIRTUAL_ADDRESS address, UINT siz
|
||||
|
||||
} // namespace
|
||||
|
||||
namespace {
|
||||
|
||||
/* How much of the title memory at `address` is readable, up to `limit` bytes. */
|
||||
UINT64 readable_extent(D3D12_GPU_VIRTUAL_ADDRESS address, UINT64 limit) {
|
||||
MEMORY_BASIC_INFORMATION info{};
|
||||
if (!VirtualQuery(reinterpret_cast<const void*>(address), &info, sizeof(info))) return 0;
|
||||
if (info.State != MEM_COMMIT || (info.Protect & (PAGE_NOACCESS | PAGE_GUARD))) return 0;
|
||||
const UINT64 end = reinterpret_cast<UINT64>(info.BaseAddress) + info.RegionSize;
|
||||
return end - address < limit ? end - address : limit;
|
||||
}
|
||||
|
||||
/* A root CBV or SRV. A root buffer has no size (a console shader reads it unchecked), so plain
|
||||
* title memory behind one gets a host buffer of what is readable there, up to `limit`, copied
|
||||
* when the list is submitted: a shader that reads further sees zeros. Only with translated
|
||||
* console shaders enabled, the only ones that read such buffers; otherwise the address is
|
||||
* translated as before. Returns false when the binding must be left empty. */
|
||||
bool root_buffer_address(ID3D12GraphicsCommandList* list, D3D12_GPU_VIRTUAL_ADDRESS address, UINT64 limit, const char* what,
|
||||
const char* stub, D3D12_GPU_VIRTUAL_ADDRESS* host) {
|
||||
*host = address;
|
||||
if (!address || bx_xbox_try_host_gpu_va(address, host)) return true;
|
||||
if (!bx_console_shaders_enabled()) {
|
||||
*host = bx_xbox_host_gpu_va(address);
|
||||
return true;
|
||||
}
|
||||
const UINT64 size = readable_extent(address, limit);
|
||||
if (size && bx_xbox_bind_title_memory(list, address, size, host)) {
|
||||
static std::atomic<uint64_t> bound{0};
|
||||
const uint64_t n = ++bound;
|
||||
if ((n & (n - 1)) == 0) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "%s at 0x%llx: %llu bytes of title memory get a host buffer; total=%llu", what,
|
||||
static_cast<unsigned long long>(address), static_cast<unsigned long long>(size),
|
||||
static_cast<unsigned long long>(n));
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "root_buffer", detail);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
note_unbacked(what, address, static_cast<UINT>(size), stub);
|
||||
return false;
|
||||
}
|
||||
|
||||
constexpr UINT64 kRootSrvBytes = 256 * 1024; // copied per submission: a prefix of the buffer
|
||||
constexpr UINT64 kRootCbvBytes = 64 * 1024; // the largest constant buffer
|
||||
|
||||
} // namespace
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_set_graphics_root_shader_resource_view(void* self, UINT param,
|
||||
D3D12_GPU_VIRTUAL_ADDRESS address) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetGraphicsRootShaderResourceView");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
D3D12_GPU_VIRTUAL_ADDRESS host = 0;
|
||||
if (root_buffer_address(list, address, kRootSrvBytes, "root SRV", "SetGraphicsRootShaderResourceView(title memory without a host buffer)",
|
||||
&host)) {
|
||||
list->SetGraphicsRootShaderResourceView(param, host);
|
||||
}
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_set_graphics_root_constant_buffer_view(void* self, UINT param,
|
||||
D3D12_GPU_VIRTUAL_ADDRESS address) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetGraphicsRootConstantBufferView");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
D3D12_GPU_VIRTUAL_ADDRESS host = 0;
|
||||
if (root_buffer_address(list, address, kRootCbvBytes, "root CBV", "SetGraphicsRootConstantBufferView(title memory without a host buffer)",
|
||||
&host)) {
|
||||
list->SetGraphicsRootConstantBufferView(param, host);
|
||||
}
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_ia_set_vertex_buffers(void* self, UINT start, UINT count,
|
||||
const D3D12_VERTEX_BUFFER_VIEW* views) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "IASetVertexBuffers");
|
||||
|
||||
@@ -112,6 +112,8 @@ CUSTOM = {
|
||||
"IASetVertexBuffers": "bx_xbox_list_ia_set_vertex_buffers",
|
||||
"IASetPrimitiveTopology": "bx_xbox_list_ia_set_primitive_topology",
|
||||
"SetGraphicsRootDescriptorTable": "bx_xbox_list_set_graphics_root_descriptor_table",
|
||||
"SetGraphicsRootShaderResourceView": "bx_xbox_list_set_graphics_root_shader_resource_view",
|
||||
"SetGraphicsRootConstantBufferView": "bx_xbox_list_set_graphics_root_constant_buffer_view",
|
||||
"IASetIndexBuffer": "bx_xbox_list_ia_set_index_buffer",
|
||||
"SetPipelineState": "bx_xbox_list_set_pipeline_state",
|
||||
"Reset": "bx_xbox_list_reset",
|
||||
|
||||
@@ -280,6 +280,10 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_signature(void* self, co
|
||||
/* True when [address, address + 32 * count) lies in the title-visible storage of a
|
||||
CBV/SRV/UAV descriptor heap (descriptor_heaps.cpp). */
|
||||
bool bx_xbox_title_descriptors(uint64_t address, UINT count);
|
||||
/* descriptor_heaps.cpp: root buffers. An address in plain title memory gets a host buffer when
|
||||
translated console shaders are enabled; otherwise it is translated as before. */
|
||||
void STDMETHODCALLTYPE bx_xbox_list_set_graphics_root_shader_resource_view(void* self, UINT param, D3D12_GPU_VIRTUAL_ADDRESS address);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_set_graphics_root_constant_buffer_view(void* self, UINT param, D3D12_GPU_VIRTUAL_ADDRESS address);
|
||||
/* pipelines.cpp: the table handle is noted for translated console draws, then bound. */
|
||||
void STDMETHODCALLTYPE bx_xbox_list_set_graphics_root_descriptor_table(void* self, UINT param, D3D12_GPU_DESCRIPTOR_HANDLE base);
|
||||
/* pipelines.cpp: root signatures, widened for translated console shaders when those are enabled. */
|
||||
|
||||
@@ -1362,18 +1362,10 @@ static void STDMETHODCALLTYPE x_GraphicsCommandList_41(void* self, UINT a0, D3D1
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetComputeRootConstantBufferView");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetComputeRootConstantBufferView(a0, bx_xbox_host_gpu_va(a1));
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_42(void* self, UINT a0, D3D12_GPU_VIRTUAL_ADDRESS a1) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetGraphicsRootConstantBufferView");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetGraphicsRootConstantBufferView(a0, bx_xbox_host_gpu_va(a1));
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_43(void* self, UINT a0, D3D12_GPU_VIRTUAL_ADDRESS a1) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetComputeRootShaderResourceView");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetComputeRootShaderResourceView(a0, bx_xbox_host_gpu_va(a1));
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_44(void* self, UINT a0, D3D12_GPU_VIRTUAL_ADDRESS a1) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetGraphicsRootShaderResourceView");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetGraphicsRootShaderResourceView(a0, bx_xbox_host_gpu_va(a1));
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_45(void* self, UINT a0, D3D12_GPU_VIRTUAL_ADDRESS a1) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetComputeRootUnorderedAccessView");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetComputeRootUnorderedAccessView(a0, bx_xbox_host_gpu_va(a1));
|
||||
@@ -1668,9 +1660,9 @@ const void* const kGraphicsCommandListTable[] = {
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_39),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_40),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_41),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_42),
|
||||
reinterpret_cast<const void*>(&bx_xbox_list_set_graphics_root_constant_buffer_view),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_43),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_44),
|
||||
reinterpret_cast<const void*>(&bx_xbox_list_set_graphics_root_shader_resource_view),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_45),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_46),
|
||||
reinterpret_cast<const void*>(&bx_xbox_list_ia_set_index_buffer),
|
||||
@@ -1793,7 +1785,7 @@ const IID kGraphicsCommandListIids[] = {
|
||||
{0xc4fec28f, 0x7966, 0x4e95, {0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8}}, /* ID3D12Object */
|
||||
};
|
||||
|
||||
/* ID3D12GraphicsCommandList8: 150 slots (64 forwarded, 27 shared, 59 stubs); hosted on ID3D12GraphicsCommandList7. */
|
||||
/* ID3D12GraphicsCommandList8: 150 slots (62 forwarded, 29 shared, 59 stubs); hosted on ID3D12GraphicsCommandList7. */
|
||||
const IID kHostGraphicsCommandList = __uuidof(ID3D12GraphicsCommandList7);
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -41,6 +41,13 @@
|
||||
* four floats from entry 0 of root parameter 0's table and computes
|
||||
* position = (c0 * x, c1 * y + c3, 0, 1), parameter 0 = (z, w, 0, 1). With c = (0.5, 0.5,
|
||||
* 0, 0) a full-target quad covers exactly the centre half, in the colour (z, w, 0).
|
||||
* 7. a root signature that is not made of tables reaches the translator (#715). The root
|
||||
* signature is one root SRV. A console shader gets its 64-bit address in s8, s9, where a
|
||||
* table pointer would take s8 alone, builds the buffer descriptor itself and reads element
|
||||
* `vertex index` from it (docs/research/console-shader-abi.md). The vertex shader below does
|
||||
* exactly that for its position and exports the colour (1, 0, 1). Two draws: positions in
|
||||
* an upload buffer covering the left half, and positions in plain process memory (what a
|
||||
* title's own allocation is to Direct3D) covering the top-right quarter.
|
||||
*
|
||||
* Slots (Xbox-layout tables, ADR 0009): 2 Release; device 9 CreateCommandAllocator,
|
||||
* 14 CreateDescriptorHeap, 16 CreateRootSignature, 17 CreateConstantBufferView, 20 CreateRenderTargetView,
|
||||
@@ -50,7 +57,7 @@
|
||||
* GetCPUDescriptorHandleForHeapStart; command list 9 Close, 12 DrawInstanced,
|
||||
* 16 CopyTextureRegion, 20 IASetPrimitiveTopology, 21 RSSetViewports, 22 RSSetScissorRects,
|
||||
* 25 SetPipelineState, 26 ResourceBarrier, 32 SetDescriptorHeaps, 34 SetGraphicsRootSignature,
|
||||
* 36 SetGraphicsRootDescriptorTable, 48 IASetVertexBuffers,
|
||||
* 36 SetGraphicsRootDescriptorTable, 44 SetGraphicsRootShaderResourceView, 48 IASetVertexBuffers,
|
||||
* 50 OMSetRenderTargets, 52 ClearRenderTargetView; queue 10 ExecuteCommandLists, 16 Signal;
|
||||
* fence 9 SetEventOnCompletion.
|
||||
*/
|
||||
@@ -80,6 +87,7 @@ constexpr int kListSetPipelineState = 25, kListResourceBarrier = 26, kListSetGra
|
||||
constexpr int kListIASetVertexBuffers = 48, kListOMSetRenderTargets = 50, kListClearRenderTargetView = 52;
|
||||
constexpr int kQueueExecuteCommandLists = 10, kQueueSignal = 16, kFenceSetEventOnCompletion = 9;
|
||||
constexpr int kDevCopyDescriptorsSimple = 24;
|
||||
constexpr int kListSetGraphicsRootShaderResourceView = 44;
|
||||
constexpr int kDevCreateConstantBufferView = 17, kListSetDescriptorHeaps = 32, kListSetGraphicsRootDescriptorTable = 36;
|
||||
|
||||
constexpr UINT kSize = 128;
|
||||
@@ -93,6 +101,11 @@ const uint32_t kPs[] = {0xbefc0302, 0xc8080000, 0xc8090001, 0xc80c0100, 0xc80d01
|
||||
* exp pos0, v0, v1, v2, v3 done ; exp param0, v6, v7, v2, v3 ; s_endpgm */
|
||||
const uint32_t kTableVs[] = {0xbe842104, 0xf4080304, 0xfa000000, 0xbf8cc07f, 0xf4280406, 0xfa000000, 0xbf8cc07f, 0x10000810, 0xd54b0001,
|
||||
0x004e0a11, 0x7e040280, 0x7e0602f2, 0xf80008cf, 0x03020100, 0xf800020f, 0x03020706, 0xbf810000};
|
||||
/* s0 = s8 ; s1 = s9 | (16 << 16) ; s2 = -1 ; s3 = 0x11014fac the root SRV's descriptor
|
||||
* buffer_load_dwordx4 v[0:3], v0, s[0:3], 0 idxen element v0: the vertex index
|
||||
* v4 = 1.0 ; v5 = 0 ; exp pos0, v0, v1, v2, v3 done ; exp param0, v4, v5, v4, v4 ; s_endpgm */
|
||||
const uint32_t kPullVs[] = {0xbe800308, 0x8801ff09, 0x00100000, 0xbe8203c1, 0xbe8303ff, 0x11014fac, 0xe0382000, 0x80000000,
|
||||
0x7e0802f2, 0x7e0a0280, 0xf80008cf, 0x03020100, 0xf800020f, 0x04040504, 0xbf810000};
|
||||
/* image_store v0, v[1:2], s[20:27] dmask:0x1 dim:2D ; s_endpgm: no rule in the translator. */
|
||||
const uint32_t kStorePs[] = {0xf0200108, 0x00050001, 0xbf810000};
|
||||
|
||||
@@ -159,6 +172,7 @@ using CreateCbvFn = void(STDMETHODCALLTYPE*)(void*, const D3D12_CONSTANT_BUFFER_
|
||||
using CopySimpleFn = void(STDMETHODCALLTYPE*)(void*, UINT, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_CPU_DESCRIPTOR_HANDLE,
|
||||
D3D12_DESCRIPTOR_HEAP_TYPE);
|
||||
using SetHeapsFn = void(STDMETHODCALLTYPE*)(void*, UINT, void* const*);
|
||||
using SetRootVaFn = void(STDMETHODCALLTYPE*)(void*, UINT, D3D12_GPU_VIRTUAL_ADDRESS);
|
||||
using SetTableFn = void(STDMETHODCALLTYPE*)(void*, UINT, D3D12_GPU_DESCRIPTOR_HANDLE);
|
||||
using SerializeRootFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**);
|
||||
|
||||
@@ -442,6 +456,48 @@ int main() {
|
||||
}
|
||||
CHECK(hr == S_OK && table_pipeline, "CreatePipelineState(console pair reading a table) hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
|
||||
// Case 7: a root signature of one root SRV (t0), and the vertex-pulling pipeline. No input
|
||||
// layout: the shader fetches its own data.
|
||||
D3D12_ROOT_PARAMETER pull_param{};
|
||||
pull_param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV;
|
||||
pull_param.Descriptor = {0, 0};
|
||||
pull_param.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
|
||||
D3D12_VERSIONED_ROOT_SIGNATURE_DESC pull_root_desc{};
|
||||
pull_root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
|
||||
pull_root_desc.Desc_1_0.NumParameters = 1;
|
||||
pull_root_desc.Desc_1_0.pParameters = &pull_param;
|
||||
ID3DBlob* pull_root_blob = nullptr;
|
||||
hr = serialize(&pull_root_desc, &pull_root_blob, nullptr);
|
||||
void* pull_root = nullptr;
|
||||
if (SUCCEEDED(hr) && pull_root_blob) {
|
||||
hr = slot<CreateRootFn>(dev, kDevCreateRootSignature)(dev, 0, pull_root_blob->GetBufferPointer(), pull_root_blob->GetBufferSize(),
|
||||
__uuidof(ID3D12RootSignature), &pull_root);
|
||||
}
|
||||
CHECK(hr == S_OK && pull_root, "CreateRootSignature(one root SRV) hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
const std::vector<uint8_t> pull_vs = console_container(kPullVs, sizeof(kPullVs) / 4, 2);
|
||||
void* pull_pipeline = nullptr;
|
||||
{
|
||||
Stream s;
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, static_cast<ID3D12RootSignature*>(pull_root));
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, D3D12_SHADER_BYTECODE{pull_vs.data(), pull_vs.size()});
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, D3D12_SHADER_BYTECODE{ps.data(), ps.size()});
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE);
|
||||
D3D12_RT_FORMAT_ARRAY formats{};
|
||||
formats.NumRenderTargets = 1;
|
||||
formats.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, formats);
|
||||
D3D12_RASTERIZER_DESC raster{};
|
||||
raster.FillMode = D3D12_FILL_MODE_SOLID;
|
||||
raster.CullMode = D3D12_CULL_MODE_NONE;
|
||||
raster.DepthClipEnable = TRUE;
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, raster);
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, D3D12_DEPTH_STENCIL_DESC{});
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, DXGI_SAMPLE_DESC{1, 0});
|
||||
const D3D12_PIPELINE_STATE_STREAM_DESC desc{s.bytes.size(), s.bytes.data()};
|
||||
hr = slot<CreateStreamFn>(dev, kDevCreatePipelineState)(dev, &desc, __uuidof(ID3D12PipelineState), &pull_pipeline);
|
||||
}
|
||||
CHECK(hr == S_OK && pull_pipeline, "CreatePipelineState(console pair with a root SRV) hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
|
||||
// Two render targets of different formats, their views, readback buffers, the vertex buffer.
|
||||
D3D12_HEAP_PROPERTIES default_heap{}, upload_heap{}, readback_heap{};
|
||||
default_heap.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
@@ -462,8 +518,9 @@ int main() {
|
||||
buffer_desc.MipLevels = 1;
|
||||
buffer_desc.SampleDesc.Count = 1;
|
||||
buffer_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
constexpr int kTargets = 3; // 0, 1: the ramp in two formats; 2: the table case
|
||||
const DXGI_FORMAT target_formats[kTargets] = {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM};
|
||||
constexpr int kTargets = 4; // 0, 1: the ramp in two formats; 2: the table case; 3: the root SRV case
|
||||
const DXGI_FORMAT target_formats[kTargets] = {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM,
|
||||
DXGI_FORMAT_R8G8B8A8_UNORM};
|
||||
void* targets[kTargets] = {};
|
||||
void* readbacks[kTargets] = {};
|
||||
void* vertices = nullptr;
|
||||
@@ -502,8 +559,8 @@ int main() {
|
||||
hr = slot<CreateHeapFn>(dev, kDevCreateDescriptorHeap)(dev, &view_heap_desc, __uuidof(ID3D12DescriptorHeap), &view_heap);
|
||||
CHECK(hr == S_OK && view_heap, "CBV/SRV heap hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (!queue || !allocator || !list || !fence || !root || !pipeline || !same_pair || !untranslatable || !targets[0] ||
|
||||
!targets[1] || !targets[2] || !readbacks[0] || !readbacks[1] || !readbacks[2] || !vertices || !rtv_heap || !table_root ||
|
||||
!table_pipeline || !constants || !view_heap) {
|
||||
!targets[1] || !targets[2] || !targets[3] || !readbacks[0] || !readbacks[1] || !readbacks[2] || !readbacks[3] || !vertices ||
|
||||
!rtv_heap || !table_root || !table_pipeline || !constants || !view_heap || !pull_root || !pull_pipeline) {
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_console_pipeline_first_draw: setup\n");
|
||||
return 1;
|
||||
}
|
||||
@@ -549,6 +606,17 @@ int main() {
|
||||
std::memcpy(reinterpret_cast<void*>(view_start.ptr + 2 * 32), reinterpret_cast<const void*>(view_start.ptr + 4 * 32), 32);
|
||||
const D3D12_GPU_DESCRIPTOR_HANDLE table{view_start.ptr + 2 * 32};
|
||||
|
||||
// Case 7: positions for the left half at offset 8192 of the upload buffer, and positions for
|
||||
// the top-right quarter in plain memory of this process.
|
||||
const float left_half[] = {-1, 1, 0, 1, 0, 1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, 0, 1, 0, 1, 0, -1, 0, 1};
|
||||
const float top_right[] = {0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1};
|
||||
std::memcpy(static_cast<uint8_t*>(mapped) + 8192, left_half, sizeof(left_half));
|
||||
const D3D12_GPU_VIRTUAL_ADDRESS left_half_va = vbv.BufferLocation + 8192;
|
||||
void* plain = VirtualAlloc(nullptr, 64 * 1024, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
||||
CHECK(plain != nullptr, "VirtualAlloc for the plain-memory positions");
|
||||
if (!plain) return 1;
|
||||
std::memcpy(plain, top_right, sizeof(top_right));
|
||||
|
||||
const D3D12_VIEWPORT viewport{0, 0, static_cast<float>(kSize), static_cast<float>(kSize), 0, 1};
|
||||
const D3D12_RECT scissor{0, 0, static_cast<LONG>(kSize), static_cast<LONG>(kSize)};
|
||||
const FLOAT green[4] = {0, 1, 0, 1};
|
||||
@@ -584,6 +652,16 @@ int main() {
|
||||
slot<SetObjectFn>(list, kListSetPipelineState)(list, table_pipeline);
|
||||
slot<DrawFn>(list, kListDrawInstanced)(list, 6, 1, 0, 0);
|
||||
|
||||
// Target 3: the root SRV case. A root SRV address is the title's own address.
|
||||
slot<SetObjectFn>(list, kListSetGraphicsRootSignature)(list, pull_root);
|
||||
slot<SetTargetsFn>(list, kListOMSetRenderTargets)(list, 1, &rtvs[3], FALSE, nullptr);
|
||||
slot<ClearFn>(list, kListClearRenderTargetView)(list, rtvs[3], green, 0, nullptr);
|
||||
slot<SetObjectFn>(list, kListSetPipelineState)(list, pull_pipeline);
|
||||
slot<SetRootVaFn>(list, kListSetGraphicsRootShaderResourceView)(list, 0, left_half_va);
|
||||
slot<DrawFn>(list, kListDrawInstanced)(list, 6, 1, 0, 0);
|
||||
slot<SetRootVaFn>(list, kListSetGraphicsRootShaderResourceView)(list, 0, reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(plain));
|
||||
slot<DrawFn>(list, kListDrawInstanced)(list, 6, 1, 0, 0);
|
||||
|
||||
for (int i = 0; i < kTargets; ++i) {
|
||||
D3D12_RESOURCE_BARRIER to_copy{};
|
||||
to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
@@ -613,6 +691,35 @@ int main() {
|
||||
|
||||
const int red_byte[2] = {0, 2}, blue_byte[2] = {2, 0}; // R8G8B8A8, then B8G8R8A8
|
||||
const char* names[2] = {"the declared format (R8G8B8A8)", "another format (B8G8R8A8)"};
|
||||
{
|
||||
// Case 7: magenta (255, 0, 255) in the left half and the top-right quarter, the clear
|
||||
// colour in the bottom-right quarter.
|
||||
void* result = nullptr;
|
||||
hr = slot<MapFn>(readbacks[3], kResMap)(readbacks[3], 0, nullptr, &result);
|
||||
CHECK(hr == S_OK && result, "readback 3 Map hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (!result) return 1;
|
||||
const auto* pixels = static_cast<const uint8_t*>(result);
|
||||
unsigned left_wrong = 0, plain_wrong = 0, rest_wrong = 0;
|
||||
for (UINT y = 2; y < kSize; y += 7) {
|
||||
for (UINT x = 2; x < kSize; x += 7) {
|
||||
const uint8_t* q = pixels + static_cast<size_t>(y) * kRowPitch + static_cast<size_t>(x) * 4;
|
||||
const bool magenta = q[0] > 250 && q[1] < 5 && q[2] > 250;
|
||||
const bool clear = q[0] < 5 && q[1] > 250 && q[2] < 5;
|
||||
if (x < 62) {
|
||||
left_wrong += magenta ? 0 : 1;
|
||||
} else if (x >= 66 && y < 62) {
|
||||
plain_wrong += magenta ? 0 : 1;
|
||||
} else if (x >= 66 && y >= 66) {
|
||||
rest_wrong += clear ? 0 : 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
CHECK(left_wrong == 0, "positions pulled from a root SRV in an upload buffer cover the left half: %u sampled pixel(s) differ",
|
||||
left_wrong);
|
||||
CHECK(plain_wrong == 0, "positions pulled from a root SRV in plain memory cover the top-right quarter: %u sampled pixel(s) differ",
|
||||
plain_wrong);
|
||||
CHECK(rest_wrong == 0, "nothing is drawn in the bottom-right quarter: %u sampled pixel(s) differ", rest_wrong);
|
||||
}
|
||||
for (int i = 0; i < 2; ++i) { // the two ramp targets
|
||||
void* result = nullptr;
|
||||
hr = slot<MapFn>(readbacks[i], kResMap)(readbacks[i], 0, nullptr, &result);
|
||||
@@ -646,9 +753,14 @@ int main() {
|
||||
const std::string log = read_log();
|
||||
if (!log.empty()) {
|
||||
const std::string mine = log.substr(before.size() <= log.size() ? before.size() : 0);
|
||||
CHECK(count_of(mine, "kept for translation at first draw") == 4, "four pipelines are kept for translation (%zu)",
|
||||
CHECK(count_of(mine, "kept for translation at first draw") == 5, "five pipelines are kept for translation (%zu)",
|
||||
count_of(mine, "kept for translation at first draw"));
|
||||
CHECK(count_of(mine, "ms (compiled)") == 1, "the first pipeline's shaders are compiled (%zu)", count_of(mine, "ms (compiled)"));
|
||||
// Translations are logged at the 1st, 2nd and 4th: the first pipeline (compiled), the
|
||||
// same pair again (cached), and the root SRV pipeline (compiled).
|
||||
CHECK(count_of(mine, "ms (compiled)") == 2, "the first and the root SRV pipeline's shaders are compiled (%zu)",
|
||||
count_of(mine, "ms (compiled)"));
|
||||
CHECK(count_of(mine, "\"event\":\"root_buffer\"") == 1 && mine.find("root SRV at") != std::string::npos,
|
||||
"the plain-memory root SRV gets a host buffer, logged once (%zu)", count_of(mine, "\"event\":\"root_buffer\""));
|
||||
CHECK(count_of(mine, "console_descriptor") == 0, "every table entry read was found through its marker");
|
||||
CHECK(count_of(mine, "ms (shaders from the disk cache)") == 1, "the second pipeline's shaders come from the disk cache (%zu)",
|
||||
count_of(mine, "ms (shaders from the disk cache)"));
|
||||
@@ -659,8 +771,8 @@ int main() {
|
||||
std::printf("note: no BX_LOG_FILE; the log checks did not run\n");
|
||||
}
|
||||
|
||||
for (void* object : {view_heap, constants, table_pipeline, table_root, rtv_heap, vertices, readbacks[2], readbacks[1], readbacks[0],
|
||||
targets[2], targets[1], targets[0], untranslatable, same_pair, pipeline, root, fence, list, allocator, queue, dev}) {
|
||||
for (void* object : {pull_pipeline, pull_root, view_heap, constants, table_pipeline, table_root, rtv_heap, vertices, readbacks[3],
|
||||
readbacks[2], readbacks[1], readbacks[0], targets[3], targets[2], targets[1], targets[0], untranslatable, same_pair, pipeline, root, fence, list, allocator, queue, dev}) {
|
||||
slot<ReleaseFn>(object, kRelease)(object);
|
||||
}
|
||||
std::printf("%s: test_d3d12_console_pipeline_first_draw (%d of %d checks passed)\n", g_failed ? "FAIL" : "PASS",
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
# A console pipeline reading a root-constants parameter is drawn (#744). Needs D3DMetal,
|
||||
# bx_shader_bridge.dll and the GDK's PC dxcompiler.dll beside the shims (bx-cli run
|
||||
# --gdk-libraries); skips without them.
|
||||
add_executable(test_d3d12_console_root_constants main.cpp)
|
||||
target_compile_definitions(test_d3d12_console_root_constants PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
|
||||
target_link_libraries(test_d3d12_console_root_constants PRIVATE d3d12_xs kernel32 uuid)
|
||||
@@ -0,0 +1,467 @@
|
||||
/*
|
||||
* Conformance test: a console pipeline that reads a root-constants parameter is drawn, whatever the
|
||||
* parameter's index (#744).
|
||||
*
|
||||
* With a root signature, the translator names each root constants or root descriptor parameter a
|
||||
* shader reads in a layout line `USE ROOT <root parameter>` (abi/include/bx_shader_bridge.h). Only
|
||||
* `USE CB` and `USE TEX` lines name descriptor-table entries; the host root signature binds a
|
||||
* `USE ROOT` parameter as it is, and unknown lines are to be ignored. Read as a table entry,
|
||||
* `USE ROOT 8` is entry 8 of root parameter 0, beyond the eight widened entries, and the pipeline
|
||||
* is refused: its draws do nothing.
|
||||
*
|
||||
* The root signature here is nine 32-bit-constants parameters (b0..b8, one value each). A console
|
||||
* shader gets root value d in user-data register s(8 + d) (docs/research/console-shader-abi.md), so
|
||||
* parameter 8 is s16. The vertex shader (GFX10.3 assembly of our own, assembled with the public
|
||||
* LLVM assembler, gfx1030):
|
||||
* s_swappc_b64 s[4:5], s[4:5] ; the console vertex-fetch call: element 0 in v[4:7]
|
||||
* v_mov_b32 v2, 0
|
||||
* v_mov_b32 v3, 1.0
|
||||
* exp pos0, v4, v5, v2, v3 done ; position = (element 0 .xy, 0, 1)
|
||||
* v_mov_b32 v8, s16 ; root parameter 8
|
||||
* exp param0, v8, v2, v2, v3 ; parameter 0 = (root parameter 8, 0, 0, 1)
|
||||
* s_endpgm
|
||||
* and the pixel shader of test_d3d12_console_pipeline_first_draw exports parameter 0 .xyz with
|
||||
* alpha 1. With 0.5 in parameter 8 and every other parameter 0, a full-target quad is (128, 0, 0).
|
||||
* The expectation is from the program, not from the translator.
|
||||
*
|
||||
* Checked: the draw shows the colour; the pipeline is not refused (log); no table entry is looked
|
||||
* up for it (no `console_descriptor` line).
|
||||
*
|
||||
* Slots (Xbox-layout tables, ADR 0009): 2 Release; device 9 CreateCommandAllocator,
|
||||
* 14 CreateDescriptorHeap, 16 CreateRootSignature, 20 CreateRenderTargetView,
|
||||
* 27 CreateCommittedResource, 36 CreateFence, 48 CreateCommandQueueX, 73 CreateCommandListX,
|
||||
* 86 CreatePipelineState; resource 8 Map, 11 GetGPUVirtualAddress; descriptor heap 9
|
||||
* GetCPUDescriptorHandleForHeapStart; command list 9 Close, 12 DrawInstanced, 16 CopyTextureRegion,
|
||||
* 20 IASetPrimitiveTopology, 21 RSSetViewports, 22 RSSetScissorRects, 25 SetPipelineState,
|
||||
* 26 ResourceBarrier, 34 SetGraphicsRootSignature, 38 SetGraphicsRoot32BitConstant,
|
||||
* 48 IASetVertexBuffers, 50 OMSetRenderTargets, 52 ClearRenderTargetView; queue 10
|
||||
* ExecuteCommandLists, 16 Signal; fence 9 SetEventOnCompletion.
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
|
||||
void** ppv);
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kRelease = 2;
|
||||
constexpr int kDevCreateCommandAllocator = 9, kDevCreateDescriptorHeap = 14, kDevCreateRootSignature = 16;
|
||||
constexpr int kDevCreateRenderTargetView = 20, kDevCreateCommittedResource = 27, kDevCreateFence = 36;
|
||||
constexpr int kDevCreateCommandQueueX = 48, kDevCreateCommandListX = 73, kDevCreatePipelineState = 86;
|
||||
constexpr int kResMap = 8, kResGetGpuVirtualAddress = 11, kHeapGetCpuStart = 9;
|
||||
constexpr int kListClose = 9, kListDrawInstanced = 12, kListCopyTextureRegion = 16;
|
||||
constexpr int kListIASetPrimitiveTopology = 20, kListRSSetViewports = 21, kListRSSetScissorRects = 22;
|
||||
constexpr int kListSetPipelineState = 25, kListResourceBarrier = 26, kListSetGraphicsRootSignature = 34;
|
||||
constexpr int kListSetGraphicsRoot32BitConstant = 38;
|
||||
constexpr int kListIASetVertexBuffers = 48, kListOMSetRenderTargets = 50, kListClearRenderTargetView = 52;
|
||||
constexpr int kQueueExecuteCommandLists = 10, kQueueSignal = 16, kFenceSetEventOnCompletion = 9;
|
||||
|
||||
constexpr UINT kSize = 64;
|
||||
constexpr UINT kRowPitch = 256;
|
||||
constexpr UINT kParams = 9; // root parameters 0..8, one 32-bit constant each
|
||||
|
||||
const uint32_t kRootVs[] = {0xbe842104, 0x7e040280, 0x7e0602f2, 0xf80008cf, 0x03020504, 0x7e100210, 0xf800020f, 0x03020208, 0xbf810000};
|
||||
const uint32_t kPs[] = {0xbefc0302, 0xc8080000, 0xc8090001, 0xc80c0100, 0xc80d0101, 0xc8100200,
|
||||
0xc8110201, 0x7e0a02f2, 0xf800180f, 0x05040302, 0xbf810000};
|
||||
|
||||
int g_checks = 0;
|
||||
int g_failed = 0;
|
||||
|
||||
#define CHECK(cond, ...) \
|
||||
do { \
|
||||
++g_checks; \
|
||||
if (!(cond)) { \
|
||||
++g_failed; \
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_console_root_constants:%d: ", __LINE__); \
|
||||
std::fprintf(stderr, __VA_ARGS__); \
|
||||
std::fprintf(stderr, "\n"); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
template <typename Fn>
|
||||
Fn slot(void* object, int index) {
|
||||
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
|
||||
}
|
||||
|
||||
struct QueueDescX {
|
||||
D3D12_COMMAND_LIST_TYPE Type;
|
||||
UINT Flags, EngineOrPipeIndex, QueueIndex;
|
||||
};
|
||||
struct ListDescX {
|
||||
D3D12_COMMAND_LIST_TYPE Type;
|
||||
UINT Flags, NodeMask, ResourceBarrierBatchSize;
|
||||
};
|
||||
|
||||
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
|
||||
using CreateQueueXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const QueueDescX*, REFIID, void**);
|
||||
using CreateAllocatorFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_COMMAND_LIST_TYPE, REFIID, void**);
|
||||
using CreateListXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const ListDescX*, void*, void*, REFIID, void**);
|
||||
using CreateCommittedFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
|
||||
const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
|
||||
const D3D12_CLEAR_VALUE*, REFIID, void**);
|
||||
using CreateFenceFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, D3D12_FENCE_FLAGS, REFIID, void**);
|
||||
using CreateHeapFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_DESCRIPTOR_HEAP_DESC*, REFIID, void**);
|
||||
using HeapStartFn = D3D12_CPU_DESCRIPTOR_HANDLE(STDMETHODCALLTYPE*)(void*);
|
||||
using CreateRootFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, const void*, SIZE_T, REFIID, void**);
|
||||
using CreateRtvFn = void(STDMETHODCALLTYPE*)(void*, void*, const D3D12_RENDER_TARGET_VIEW_DESC*, D3D12_CPU_DESCRIPTOR_HANDLE);
|
||||
using CreateStreamFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_PIPELINE_STATE_STREAM_DESC*, REFIID, void**);
|
||||
using MapFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RANGE*, void**);
|
||||
using GetGpuVaFn = D3D12_GPU_VIRTUAL_ADDRESS(STDMETHODCALLTYPE*)(void*);
|
||||
using CloseFn = HRESULT(STDMETHODCALLTYPE*)(void*);
|
||||
using DrawFn = void(STDMETHODCALLTYPE*)(void*, UINT, UINT, UINT, UINT);
|
||||
using CopyTextureFn = void(STDMETHODCALLTYPE*)(void*, const D3D12_TEXTURE_COPY_LOCATION*, UINT, UINT, UINT,
|
||||
const D3D12_TEXTURE_COPY_LOCATION*, const D3D12_BOX*);
|
||||
using TopologyFn = void(STDMETHODCALLTYPE*)(void*, D3D12_PRIMITIVE_TOPOLOGY);
|
||||
using ViewportsFn = void(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_VIEWPORT*);
|
||||
using ScissorsFn = void(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RECT*);
|
||||
using SetObjectFn = void(STDMETHODCALLTYPE*)(void*, void*);
|
||||
using BarrierFn = UINT(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RESOURCE_BARRIER*);
|
||||
using SetVbFn = void(STDMETHODCALLTYPE*)(void*, UINT, UINT, const D3D12_VERTEX_BUFFER_VIEW*);
|
||||
using SetTargetsFn = void(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_CPU_DESCRIPTOR_HANDLE*, BOOL,
|
||||
const D3D12_CPU_DESCRIPTOR_HANDLE*);
|
||||
using ClearFn = void(STDMETHODCALLTYPE*)(void*, D3D12_CPU_DESCRIPTOR_HANDLE, const FLOAT*, UINT, const D3D12_RECT*);
|
||||
using ExecuteFn = void(STDMETHODCALLTYPE*)(void*, UINT, void* const*);
|
||||
using QueueSignalFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, UINT64);
|
||||
using FenceEventFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, HANDLE);
|
||||
using SetRootConstantFn = void(STDMETHODCALLTYPE*)(void*, UINT, UINT, UINT);
|
||||
using SerializeRootFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**);
|
||||
|
||||
void put32(std::vector<uint8_t>& out, size_t at, uint32_t value) { std::memcpy(out.data() + at, &value, 4); }
|
||||
void put64(std::vector<uint8_t>& out, size_t at, uint64_t value) { std::memcpy(out.data() + at, &value, 8); }
|
||||
|
||||
uint32_t adler32(const std::vector<uint8_t>& data) {
|
||||
uint32_t a = 1, b = 0;
|
||||
for (uint8_t byte : data) {
|
||||
a = (a + byte) % 65521;
|
||||
b = (b + a) % 65521;
|
||||
}
|
||||
return (b << 16) | a;
|
||||
}
|
||||
|
||||
/* A console-style container of one stage's code (see the file comment). `fspx_stage` is the FSPX
|
||||
* stage number (1 pixel, 2 vertex). */
|
||||
std::vector<uint8_t> console_container(const uint32_t* words, size_t count, uint32_t fspx_stage) {
|
||||
// The stage code: one 12-byte header record, then the instructions.
|
||||
std::vector<uint8_t> code(12 + count * 4, 0);
|
||||
put32(code, 0, 0xD5800000u);
|
||||
std::memcpy(code.data() + 12, words, count * 4);
|
||||
// The FSSM block: filler in the stage slots, one stage record, the code.
|
||||
constexpr size_t kBase = 16, kRecord = 0x80, kCodeOffset = 0xA0;
|
||||
std::vector<uint8_t> fssm(kBase + kCodeOffset, 0);
|
||||
std::memcpy(fssm.data(), "FSSM", 4);
|
||||
for (size_t s = 0x18; s < 0x78; s += 8) put64(fssm, s, 0xDEADBEEFDEADBEEFull);
|
||||
put64(fssm, 0x30, kRecord);
|
||||
put64(fssm, kBase + kRecord, kCodeOffset);
|
||||
put64(fssm, kBase + kRecord + 8, code.size());
|
||||
fssm.insert(fssm.end(), code.begin(), code.end());
|
||||
// A zlib stream with one stored block.
|
||||
std::vector<uint8_t> zlib = {0x78, 0x01, 0x01};
|
||||
const uint16_t len = static_cast<uint16_t>(fssm.size());
|
||||
const uint16_t nlen = static_cast<uint16_t>(~len);
|
||||
zlib.insert(zlib.end(), {static_cast<uint8_t>(len), static_cast<uint8_t>(len >> 8), static_cast<uint8_t>(nlen),
|
||||
static_cast<uint8_t>(nlen >> 8)});
|
||||
zlib.insert(zlib.end(), fssm.begin(), fssm.end());
|
||||
const uint32_t sum = adler32(fssm);
|
||||
zlib.insert(zlib.end(), {static_cast<uint8_t>(sum >> 24), static_cast<uint8_t>(sum >> 16), static_cast<uint8_t>(sum >> 8),
|
||||
static_cast<uint8_t>(sum)});
|
||||
// The ACCC chunk: the FSPX table (stage configuration only), then the XBCH record.
|
||||
std::vector<uint8_t> chunk(40 + 24, 0);
|
||||
std::memcpy(chunk.data(), "FSPX", 4);
|
||||
put32(chunk, 4, 1); // version
|
||||
put32(chunk, 8, 1); // section count
|
||||
put32(chunk, 16, 1); // section id 1: stage configuration
|
||||
put32(chunk, 20, 28); // offset
|
||||
put32(chunk, 24, 12); // size
|
||||
put32(chunk, 28, fspx_stage);
|
||||
put32(chunk, 32, 6); // shader model 6.0
|
||||
std::memcpy(chunk.data() + 40, "XBCH", 4);
|
||||
put32(chunk, 44, 1);
|
||||
put64(chunk, 48, zlib.size());
|
||||
put64(chunk, 56, fssm.size());
|
||||
chunk.insert(chunk.end(), zlib.begin(), zlib.end());
|
||||
while (chunk.size() % 4) chunk.push_back(0);
|
||||
const uint32_t total = 32 + 4 + 8 + static_cast<uint32_t>(chunk.size());
|
||||
std::vector<uint8_t> out(total, 0);
|
||||
std::memcpy(out.data(), "DXBC", 4);
|
||||
put32(out, 20, 1);
|
||||
put32(out, 24, total);
|
||||
put32(out, 28, 1); // one chunk
|
||||
put32(out, 32, 36); // at offset 36
|
||||
std::memcpy(out.data() + 36, "ACCC", 4);
|
||||
put32(out, 40, static_cast<uint32_t>(chunk.size()));
|
||||
std::memcpy(out.data() + 44, chunk.data(), chunk.size());
|
||||
return out;
|
||||
}
|
||||
|
||||
/* A pipeline-state stream: subobjects are pointer-aligned { type, payload } pairs. */
|
||||
struct Stream {
|
||||
std::vector<uint8_t> bytes;
|
||||
template <typename T>
|
||||
void add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type, const T& payload) {
|
||||
struct alignas(void*) Subobject {
|
||||
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type;
|
||||
T payload;
|
||||
};
|
||||
Subobject s{};
|
||||
s.type = type;
|
||||
s.payload = payload;
|
||||
const auto* raw = reinterpret_cast<const uint8_t*>(&s);
|
||||
bytes.insert(bytes.end(), raw, raw + sizeof(s));
|
||||
}
|
||||
};
|
||||
|
||||
std::string read_log() {
|
||||
char path[MAX_PATH];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
|
||||
if (n == 0 || n >= sizeof(path)) return {};
|
||||
std::string text;
|
||||
if (FILE* f = std::fopen(path, "rb")) {
|
||||
char buffer[4096];
|
||||
size_t got;
|
||||
while ((got = std::fread(buffer, 1, sizeof(buffer), f)) > 0) text.append(buffer, got);
|
||||
std::fclose(f);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
size_t count_of(const std::string& text, const char* needle) {
|
||||
size_t n = 0;
|
||||
for (size_t pos = text.find(needle); pos != std::string::npos; pos = text.find(needle, pos + 1)) ++n;
|
||||
return n;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
char temp[MAX_PATH] = {};
|
||||
char cache[MAX_PATH + 64] = {};
|
||||
GetTempPathA(sizeof(temp), temp);
|
||||
std::snprintf(cache, sizeof(cache), "%sbx-shader-cache-%lu-%lu", temp, static_cast<unsigned long>(GetCurrentProcessId()),
|
||||
static_cast<unsigned long>(GetTickCount()));
|
||||
SetEnvironmentVariableA("BX_CONSOLE_SHADERS", "1");
|
||||
SetEnvironmentVariableA("BX_SHADER_CACHE", cache);
|
||||
const std::string before = read_log();
|
||||
|
||||
alignas(8) unsigned char title_params[80] = {};
|
||||
const UINT version = 0x20004; // a non-zero version selects the Xbox-layout device
|
||||
std::memcpy(title_params, &version, sizeof(version));
|
||||
void* dev = nullptr;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
|
||||
if (hr == E_NOINTERFACE) {
|
||||
std::printf("SKIP: test_d3d12_console_root_constants: host lacks the Xbox-layout device interface (E_NOINTERFACE)\n");
|
||||
return 77;
|
||||
}
|
||||
CHECK(hr == S_OK && dev != nullptr, "Xbox-layout device creation hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (!dev) return 1;
|
||||
HMODULE d3d12 = LoadLibraryA("d3d12.dll");
|
||||
auto serialize = d3d12 ? reinterpret_cast<SerializeRootFn>(
|
||||
reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature")))
|
||||
: nullptr;
|
||||
HMODULE dxc = LoadLibraryA("dxcompiler.dll");
|
||||
if (!serialize || !dxc) {
|
||||
std::printf("SKIP: test_d3d12_console_root_constants: %s\n",
|
||||
dxc ? "no root-signature serializer in this bottle"
|
||||
: "no dxcompiler.dll beside the shims (run with bx-cli run --gdk-libraries)");
|
||||
return 77;
|
||||
}
|
||||
|
||||
const QueueDescX qdesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
|
||||
const ListDescX ldesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
|
||||
void* queue = nullptr;
|
||||
void* allocator = nullptr;
|
||||
void* list = nullptr;
|
||||
void* fence = nullptr;
|
||||
slot<CreateQueueXFn>(dev, kDevCreateCommandQueueX)(dev, &qdesc, __uuidof(ID3D12CommandQueue), &queue);
|
||||
slot<CreateAllocatorFn>(dev, kDevCreateCommandAllocator)(dev, D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
|
||||
&allocator);
|
||||
slot<CreateListXFn>(dev, kDevCreateCommandListX)(dev, &ldesc, allocator, nullptr, __uuidof(ID3D12GraphicsCommandList), &list);
|
||||
slot<CreateFenceFn>(dev, kDevCreateFence)(dev, 0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), &fence);
|
||||
|
||||
// Nine root parameters of one 32-bit constant each, b0..b8.
|
||||
D3D12_ROOT_PARAMETER params[kParams] = {};
|
||||
for (UINT i = 0; i < kParams; ++i) {
|
||||
params[i].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
|
||||
params[i].Constants = {i, 0, 1};
|
||||
params[i].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
|
||||
}
|
||||
D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
|
||||
root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
|
||||
root_desc.Desc_1_0.NumParameters = kParams;
|
||||
root_desc.Desc_1_0.pParameters = params;
|
||||
root_desc.Desc_1_0.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
|
||||
ID3DBlob* root_blob = nullptr;
|
||||
hr = serialize(&root_desc, &root_blob, nullptr);
|
||||
void* root = nullptr;
|
||||
if (SUCCEEDED(hr) && root_blob) {
|
||||
hr = slot<CreateRootFn>(dev, kDevCreateRootSignature)(dev, 0, root_blob->GetBufferPointer(), root_blob->GetBufferSize(),
|
||||
__uuidof(ID3D12RootSignature), &root);
|
||||
}
|
||||
CHECK(hr == S_OK && root, "CreateRootSignature(nine root constants) hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
|
||||
const std::vector<uint8_t> vs = console_container(kRootVs, sizeof(kRootVs) / 4, 2);
|
||||
const std::vector<uint8_t> ps = console_container(kPs, sizeof(kPs) / 4, 1);
|
||||
const D3D12_INPUT_ELEMENT_DESC elements[] = {
|
||||
{"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
|
||||
};
|
||||
void* pipeline = nullptr;
|
||||
{
|
||||
Stream s;
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, static_cast<ID3D12RootSignature*>(root));
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, D3D12_SHADER_BYTECODE{vs.data(), vs.size()});
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, D3D12_SHADER_BYTECODE{ps.data(), ps.size()});
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, D3D12_INPUT_LAYOUT_DESC{elements, 1});
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE);
|
||||
D3D12_RT_FORMAT_ARRAY formats{};
|
||||
formats.NumRenderTargets = 1;
|
||||
formats.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, formats);
|
||||
D3D12_RASTERIZER_DESC raster{};
|
||||
raster.FillMode = D3D12_FILL_MODE_SOLID;
|
||||
raster.CullMode = D3D12_CULL_MODE_NONE;
|
||||
raster.DepthClipEnable = TRUE;
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, raster);
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, D3D12_DEPTH_STENCIL_DESC{});
|
||||
s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, DXGI_SAMPLE_DESC{1, 0});
|
||||
const D3D12_PIPELINE_STATE_STREAM_DESC desc{s.bytes.size(), s.bytes.data()};
|
||||
hr = slot<CreateStreamFn>(dev, kDevCreatePipelineState)(dev, &desc, __uuidof(ID3D12PipelineState), &pipeline);
|
||||
}
|
||||
CHECK(hr == S_OK && pipeline, "CreatePipelineState(console pair reading root parameter 8) hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
|
||||
D3D12_HEAP_PROPERTIES default_heap{}, upload_heap{}, readback_heap{};
|
||||
default_heap.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
upload_heap.Type = D3D12_HEAP_TYPE_UPLOAD;
|
||||
readback_heap.Type = D3D12_HEAP_TYPE_READBACK;
|
||||
D3D12_RESOURCE_DESC target_desc{};
|
||||
target_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
|
||||
target_desc.Width = kSize;
|
||||
target_desc.Height = kSize;
|
||||
target_desc.DepthOrArraySize = 1;
|
||||
target_desc.MipLevels = 1;
|
||||
target_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
target_desc.SampleDesc.Count = 1;
|
||||
target_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
|
||||
D3D12_RESOURCE_DESC buffer_desc{};
|
||||
buffer_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
buffer_desc.Height = 1;
|
||||
buffer_desc.DepthOrArraySize = 1;
|
||||
buffer_desc.MipLevels = 1;
|
||||
buffer_desc.SampleDesc.Count = 1;
|
||||
buffer_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
auto committed = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource);
|
||||
void* target = nullptr;
|
||||
void* readback = nullptr;
|
||||
void* vertices = nullptr;
|
||||
hr = committed(dev, &default_heap, D3D12_HEAP_FLAG_NONE, &target_desc, D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr,
|
||||
__uuidof(ID3D12Resource), &target);
|
||||
CHECK(hr == S_OK && target, "render target hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
buffer_desc.Width = static_cast<UINT64>(kRowPitch) * kSize;
|
||||
hr = committed(dev, &readback_heap, D3D12_HEAP_FLAG_NONE, &buffer_desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
|
||||
__uuidof(ID3D12Resource), &readback);
|
||||
CHECK(hr == S_OK && readback, "readback buffer hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
buffer_desc.Width = 4096;
|
||||
hr = committed(dev, &upload_heap, D3D12_HEAP_FLAG_NONE, &buffer_desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
|
||||
__uuidof(ID3D12Resource), &vertices);
|
||||
CHECK(hr == S_OK && vertices, "vertex buffer hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
D3D12_DESCRIPTOR_HEAP_DESC heap_desc{};
|
||||
heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
|
||||
heap_desc.NumDescriptors = 1;
|
||||
void* rtv_heap = nullptr;
|
||||
hr = slot<CreateHeapFn>(dev, kDevCreateDescriptorHeap)(dev, &heap_desc, __uuidof(ID3D12DescriptorHeap), &rtv_heap);
|
||||
CHECK(hr == S_OK && rtv_heap, "RTV heap hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (!queue || !allocator || !list || !fence || !root || !pipeline || !target || !readback || !vertices || !rtv_heap) {
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_console_root_constants: setup\n");
|
||||
return 1;
|
||||
}
|
||||
const D3D12_CPU_DESCRIPTOR_HANDLE rtv = slot<HeapStartFn>(rtv_heap, kHeapGetCpuStart)(rtv_heap);
|
||||
slot<CreateRtvFn>(dev, kDevCreateRenderTargetView)(dev, target, nullptr, rtv);
|
||||
|
||||
const float quad[] = {-1, 1, 1, 1, -1, -1, -1, -1, 1, 1, 1, -1};
|
||||
void* mapped = nullptr;
|
||||
hr = slot<MapFn>(vertices, kResMap)(vertices, 0, nullptr, &mapped);
|
||||
CHECK(hr == S_OK && mapped, "vertex buffer Map hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (!mapped) return 1;
|
||||
std::memcpy(mapped, quad, sizeof(quad));
|
||||
const D3D12_VERTEX_BUFFER_VIEW vbv{slot<GetGpuVaFn>(vertices, kResGetGpuVirtualAddress)(vertices), sizeof(quad), 8};
|
||||
|
||||
const D3D12_VIEWPORT viewport{0, 0, static_cast<float>(kSize), static_cast<float>(kSize), 0, 1};
|
||||
const D3D12_RECT scissor{0, 0, static_cast<LONG>(kSize), static_cast<LONG>(kSize)};
|
||||
const FLOAT green[4] = {0, 1, 0, 1};
|
||||
slot<SetObjectFn>(list, kListSetGraphicsRootSignature)(list, root);
|
||||
const float half = 0.5f;
|
||||
UINT half_bits = 0;
|
||||
std::memcpy(&half_bits, &half, sizeof(half_bits));
|
||||
for (UINT i = 0; i < kParams; ++i) {
|
||||
slot<SetRootConstantFn>(list, kListSetGraphicsRoot32BitConstant)(list, i, i == kParams - 1 ? half_bits : 0u, 0);
|
||||
}
|
||||
slot<ViewportsFn>(list, kListRSSetViewports)(list, 1, &viewport);
|
||||
slot<ScissorsFn>(list, kListRSSetScissorRects)(list, 1, &scissor);
|
||||
slot<SetVbFn>(list, kListIASetVertexBuffers)(list, 0, 1, &vbv);
|
||||
slot<TopologyFn>(list, kListIASetPrimitiveTopology)(list, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
|
||||
slot<SetTargetsFn>(list, kListOMSetRenderTargets)(list, 1, &rtv, FALSE, nullptr);
|
||||
slot<ClearFn>(list, kListClearRenderTargetView)(list, rtv, green, 0, nullptr);
|
||||
slot<SetObjectFn>(list, kListSetPipelineState)(list, pipeline);
|
||||
slot<DrawFn>(list, kListDrawInstanced)(list, 6, 1, 0, 0);
|
||||
D3D12_RESOURCE_BARRIER to_copy{};
|
||||
to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
to_copy.Transition.pResource = static_cast<ID3D12Resource*>(target);
|
||||
to_copy.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
|
||||
to_copy.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
|
||||
to_copy.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
|
||||
slot<BarrierFn>(list, kListResourceBarrier)(list, 1, &to_copy);
|
||||
D3D12_TEXTURE_COPY_LOCATION dst{};
|
||||
dst.pResource = static_cast<ID3D12Resource*>(readback);
|
||||
dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
|
||||
dst.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, kSize, kSize, 1, kRowPitch};
|
||||
D3D12_TEXTURE_COPY_LOCATION src{};
|
||||
src.pResource = static_cast<ID3D12Resource*>(target);
|
||||
src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
|
||||
slot<CopyTextureFn>(list, kListCopyTextureRegion)(list, &dst, 0, 0, 0, &src, nullptr);
|
||||
CHECK(slot<CloseFn>(list, kListClose)(list) == S_OK, "list Close");
|
||||
|
||||
void* lists[] = {list};
|
||||
slot<ExecuteFn>(queue, kQueueExecuteCommandLists)(queue, 1, lists);
|
||||
CHECK(slot<QueueSignalFn>(queue, kQueueSignal)(queue, fence, 1) == S_OK, "queue Signal");
|
||||
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
CHECK(slot<FenceEventFn>(fence, kFenceSetEventOnCompletion)(fence, 1, done) == S_OK, "fence event");
|
||||
CHECK(WaitForSingleObject(done, 20000) == WAIT_OBJECT_0, "GPU work completes");
|
||||
CloseHandle(done);
|
||||
|
||||
void* result = nullptr;
|
||||
hr = slot<MapFn>(readback, kResMap)(readback, 0, nullptr, &result);
|
||||
CHECK(hr == S_OK && result, "readback Map hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (!result) return 1;
|
||||
unsigned wrong = 0;
|
||||
for (UINT y = 1; y < kSize; y += 7) {
|
||||
for (UINT x = 1; x < kSize; x += 7) {
|
||||
const auto* p = static_cast<const uint8_t*>(result) + static_cast<size_t>(y) * kRowPitch + static_cast<size_t>(x) * 4;
|
||||
const bool ok = std::abs(p[0] - 128) <= 2 && p[1] <= 2 && p[2] <= 2;
|
||||
if (!ok && wrong++ < 3) std::fprintf(stderr, " pixel (%u, %u): %d %d %d, want 128 0 0\n", x, y, p[0], p[1], p[2]);
|
||||
}
|
||||
}
|
||||
CHECK(wrong == 0, "the draw shows root parameter 8 as red 0.5: %u sampled pixel(s) differ", wrong);
|
||||
|
||||
const std::string log = read_log();
|
||||
if (!log.empty()) {
|
||||
const std::string mine = log.substr(before.size() <= log.size() ? before.size() : 0);
|
||||
CHECK(count_of(mine, "is not drawn") == 0, "the pipeline is not refused (%zu)", count_of(mine, "is not drawn"));
|
||||
CHECK(count_of(mine, "console_descriptor") == 0, "no table entry is looked up for root constants (%zu)",
|
||||
count_of(mine, "console_descriptor"));
|
||||
} else {
|
||||
std::printf("note: no BX_LOG_FILE; the log checks did not run\n");
|
||||
}
|
||||
|
||||
for (void* object : {rtv_heap, vertices, readback, target, pipeline, root, fence, list, allocator, queue, dev}) {
|
||||
slot<ReleaseFn>(object, kRelease)(object);
|
||||
}
|
||||
std::printf("%s: test_d3d12_console_root_constants (%d of %d checks passed)\n", g_failed ? "FAIL" : "PASS",
|
||||
g_checks - g_failed, g_checks);
|
||||
return g_failed ? 1 : 0;
|
||||
}
|
||||
@@ -39,6 +39,7 @@ static const ShimExpectation kChecks[] = {
|
||||
{"bx_shader_bridge.dll", "bx_shader_free_buffer"},
|
||||
{"bx_shader_bridge.dll", "bx_shader_translate_pair"},
|
||||
{"bx_shader_bridge.dll", "bx_shader_free_pair_translation"},
|
||||
{"bx_shader_bridge.dll", "bx_shader_translate_pair_rooted"},
|
||||
};
|
||||
|
||||
/* Distinct DLLs named in kChecks, so the summary reports a counted number. */
|
||||
|
||||
Reference in new issue
Block a user