Compare commits

..
Author SHA1 Message Date
ates eee9a4fcdc docs: how blockers are found once the target build runs
Working method: people play with recording on, agents replay short
routes through the input shim as ten-run regression tests, and picture
bugs are worked on from captured frames replayed offline. Lists the
signals a problem is recognised by and adds the three tools to the
starting queue.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 10:27:51 +03:00
ates fe28c5c2af docs: rework the proposal for an agent-driven team; stages replace milestone numbers
Collaborators work by telling a coding agent to "work", so the method
now answers what an agent does next without meetings or roles:
- AGENTS.md section 0 is rewritten as that instruction: preflight, then
  exactly one of own pull requests, review, one blocker of the current
  stage, or discovery; "work" authorizes commit, push and a pull request
  for the one item picked.
- docs/process/working-method.md: state lives in GitHub (a pinned ladder
  issue, one blocker issue per signature, claim comments, needs-human),
  the run protocol with per-session bottles and a machine-wide run lock,
  ranked sources of truth, the five-part pull request, and the starting
  queue.
- docs/roadmap.md: the ladder's rungs are named stages (Boot, Picture,
  Menus, World, Fidelity, Playable) instead of M3-M8.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 10:09:49 +03:00
ates e21f41ae24 docs: propose the game-ladder roadmap and the blocker-loop working method
docs/roadmap.md: M0-M2 become the foundation; M3-M8 are rungs the
project-authorized target build reaches (reliable boot, first correct
picture, front end, into the world, the world renders correctly,
playable), each judged on ten recorded runs on a 16 GB Mac, with
decision gates for the back end, reference images, memory and frame
rate, and a step-forward test for what belongs on main.

docs/process/working-method.md (proposed): the blocker loop, the run
protocol and run report, lanes beside tracks, ranked sources of truth,
one-blocker pull requests with a five-part description, the first two
weeks of work, and the AGENTS.md changes this needs. AGENTS.md itself
is not changed here.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 10:05:49 +03:00
30 changed files with 3026 additions and 2641 deletions

No files matched your search

+52 -39
View File
@@ -4,46 +4,59 @@ These rules apply to every human contributor and coding agent (`CLAUDE.md` is a
---
## 0. Contributor & Agent Task Dispatch (Onboarding & Priority Order)
## 0. What to Do When Told "Work"
Whenever a user points their agent at BetterXen to contribute, get started, or pick work (even with a short prompt like *"help me contribute"* or *"what should we work on?"*), walk through preflight and then select work in the **strict 3-tier priority order** below:
Collaborators point their agent at this repository and say "work" (or "contribute", "continue", "what next?"). That is a complete instruction. Do not ask what to work on: follow this section. The method behind it is in [docs/process/working-method.md](docs/process/working-method.md); the stages are in [docs/roadmap.md](docs/roadmap.md).
1. **Preflight host & tools:**
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`.
- If `mingw-w64`, `cmake`, or `gh` is missing on macOS, ask permission before running `brew install mingw-w64 cmake gh`.
- Run `gh auth status` (if not logged in, pause and ask the user to run `gh auth login`).
- Run `cargo build --locked -p bx-cli && target/debug/bx-cli doctor` to report Apple Silicon, Rosetta 2, CrossOver, and toolchain readiness.
- Verify whether the user has push access or needs a fork (`gh repo fork MacosPorters/betterxen --remote`), and sync with `origin/main`.
2. **Select work in strict priority order:**
- **Priority 1 (Highest) — Handle your own claimed PRs with requested changes or review feedback:**
```sh
gh pr list --repo MacosPorters/betterxen --author "@me" --state open --json number,title,headRefName,reviewDecision,reviews,statusCheckRollup,mergeStateStatus
```
Inspect comments and reviews (`gh pr view <pr> --repo MacosPorters/betterxen --comments` and `gh api repos/MacosPorters/betterxen/pulls/<pr>/comments`). If any of the user's open/claimed PRs has `CHANGES_REQUESTED`, unresolved reviewer feedback, failing CI, or merge conflicts, **address that PR first before starting new work**: check out the PR branch, resolve every review item, re-run Section 8 checks, push the DCO-signed update (with the user's authorization, per Section 7), and summarize how each comment was addressed.
- **Priority 2 — Pick an unclaimed open issue:**
If Priority 1 is clear, query open issues (preferring `status: ready` in the active milestone, then other actionable open issues):
```sh
gh issue list --repo MacosPorters/betterxen --state open --label "status: ready" --json number,title,labels,assignees
gh issue list --repo MacosPorters/betterxen --state open --json number,title,labels,assignees
```
Inspect comments and open PRs on candidate issues to filter out any issue with an active claim (< 7 days old) or open PR. Present the unclaimed options in plain English (recommending 1–2 good matches) and confirm with the user before coding.
- **Priority 3 — Review & independently verify open PRs needing review:**
When Priority 1 is clear and no unclaimed open issues remain (or the user asks to help unblock the queue), query open non-draft PRs by other contributors that still need review/verification:
```sh
gh pr list --repo MacosPorters/betterxen --state open --json number,title,author,headRefName,reviewDecision,isDraft
```
Fetch a candidate PR (`reviewDecision` empty or `REVIEW_REQUIRED`) into an isolated worktree, independently verify its contract and implementation per Section 5, run the Section 8 checks locally (including live CrossOver / D3DMetal runs where available), and draft an honest evidence-backed review for user approval before posting.
3. **Claim & isolate (for Priority 2 issue work):**
- Post `Claiming — branch: track-<a..f>/<issue>-<slug>` on the chosen issue and create that branch (or `git worktree`) off `origin/main`.
4. **Implement strictly in scope:**
- Read the full issue body (`gh issue view <issue> --repo MacosPorters/betterxen`) and the relevant contracts in `abi/defs/` and `abi/include/`.
- Edit **only** files inside the issue's **Exclusive file scope** (plus `CHANGELOG.md`). Add new synthetic C++ conformance tests under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake).
5. **Verify locally (including hosts without CrossOver):**
- Run every command in Section 8 and fix all warnings/failures before stopping.
- **No CrossOver installed?** The contributor can still run all ARM64 Rust checks, `scripts/build-shims.sh` (cross-compiling the 16 mingw-w64 C++ shim DLLs, building the Rust `bx_shader_bridge.dll` with `cargo`, and verifying the exact exports of all 17 PE32+ DLLs), and `python3 scripts/audit/docs_hygiene.py`. Report honestly in the PR that live CrossOver execution was not run locally and needs verification on a CrossOver host—never report an unrun check as passed.
6. **Review & submit PR:**
- Present a concise summary of changes and exact verification outputs, and ask explicit user permission before running `git commit -s` (DCO sign-off, zero AI trailers), pushing, and opening a PR (`Closes #<issue>`).
- After opening the PR, watch CI (`gh pr checks --watch`) until both `Hybrid build and shim checks` and `Repository hygiene` pass.
**"Work" authorizes, for the one item you pick:** posting a claim or a review, committing with DCO sign-off, pushing a branch, and opening a pull request. It does not authorize merging your own person's pull request, changing rules, or anything marked `needs-human`. A more specific instruction from your person always wins.
### Step 1 — Preflight
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`. If `mingw-w64`, `cmake`, or `gh` is missing on macOS, ask permission before running `brew install mingw-w64 cmake gh`.
- Run `gh auth status` (if not logged in, pause and ask the user to run `gh auth login`). Verify push access or fork (`gh repo fork MacosPorters/betterxen --remote`), and sync with `origin/main`.
- Run `cargo build --locked -p bx-cli && target/debug/bx-cli doctor`. It must report the toolchain, CrossOver, at least 10 GB of free disk space, and no other game run on this machine.
- Work in your own worktree and your own bottle. Never use a bottle another session is using.
### Step 2 — Pick exactly one thing, in this order
Take the first that applies. Do not skip ahead because a later one looks more interesting.
1. **Your person's pull requests that need attention.**
```sh
gh pr list --repo MacosPorters/betterxen --author "@me" --state open --json number,title,headRefName,reviewDecision,statusCheckRollup,mergeStateStatus
```
If one has requested changes, unresolved review comments, failing checks or conflicts: fix that pull request. Resolve every review point, re-run Section 8, push, and reply to each point.
2. **Review someone else's pull request.**
```sh
gh pr list --repo MacosPorters/betterxen --state open --json number,title,author,reviewDecision,isDraft,createdAt
```
Take the oldest open, non-draft pull request that your person did not open and that has no current review. Check out its branch, run Section 8 and its new test, confirm the test fails without the fix, read its proof, and post an approval or a change request with what you ran. If it needs deep review (the list is in the working method) and you can give one, do. If it is approved, green and not your person's, merge it (Section 7).
3. **Fix one blocker of the current stage.**
```sh
gh issue list --repo MacosPorters/betterxen --state open --label blocker --label "stage: <current>" --json number,title,labels,comments
```
The current stage is named on the pinned issue labelled `ladder`. Take the top unclaimed blocker: those labelled `first`, then lowest number. A blocker is claimed if it has a `Claiming —` comment less than 3 days old or an open pull request. Then follow Step 3.
4. **Discover.** If the current stage has no unclaimed blocker, run the stage's gate check (ten runs, [run protocol](docs/process/working-method.md#run-protocol)). For each signature in the report that has no issue, open or closed, file a blocker issue in the fixed shape. If the gate passes, post the ten-run result on the ladder issue and label it `needs-human`.
5. **Nothing applies.** Say so and stop. Do not invent work, open research documents, or start on a later stage's blockers while the current stage has claimed, unfinished ones — unless your person tells you to.
**Stop and label `needs-human`** whenever the next step is a decision that is not yours: a decision gate, a licence or provenance question, sources of truth that disagree, or a rule change.
### Step 3 — Work one blocker
1. **Claim:** comment `Claiming — branch: track-<a..f>/<issue>-<slug>` and branch from `origin/main`.
2. **Evidence before code:** find what the build asked for and what it got, from the run report and the diagnostics. If you cannot explain the blocker in this session, write what you learned on the issue, release the claim, and stop. Do not guess a fix.
3. **Smallest fix:** only what removes this blocker. Stay inside the track directories it needs (Section 2); a new cross-DLL export goes through an `[ABI]` pull request first.
4. **Test:** every contract the fix introduces gets a synthetic conformance test under `tests/conformance/test_<name>/` that fails without the fix.
5. **Verify:** every command in Section 8. Without CrossOver you can still run the Rust checks, `scripts/build-shims.sh` and the docs check; say plainly which live checks were not run. Never report an unrun check as passed.
6. **Proof:** ten runs before and ten after, every run reported, with the machine and the `main` commit.
7. **Pull request:** one blocker; the five-part description (Blocker, Contract with its source rank, Fix, Test, Proof); `Closes #<issue>`; DCO sign-off; no AI trailers. Watch CI until `Hybrid build and shim checks` and `Repository hygiene` pass.
8. **Stop.** The next "work" starts again at Step 2.
Nothing from the target build goes into a commit, issue or pull request (Section 6): keep run logs, dumps and captures in your private evidence folder outside the repository.
---
@@ -121,7 +134,7 @@ _Reserved — policy migration in progress._
git worktree add ../wt-<issue> -b track-<a..f>/<issue>-<slug> origin/main
```
3. **Link & sign off:** Reference any related issue (`Closes #<issue>` when applicable) in the PR description and sign off every commit (`git commit -s`, DCO).
4. **Git safety:** Commit, push, and open PRs only when requested or authorized by the user; never change repository visibility without explicit instruction. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
4. **Git safety:** Commit, push, and open PRs only when requested or authorized by the user (being told to "work" authorizes them for the one item picked, Section 0); never change repository visibility without explicit instruction. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
5. **Changelog & docs index:** Read `CHANGELOG.md` before starting and update `[Unreleased]` for every meaningful addition, change, fix, removal, or security update. Update `docs/README.md` whenever documentation is added, removed, or reorganized.
### Merge eligibility
+1 -20
View File
@@ -10,25 +10,11 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Changed
- `xg_xs.dll` follows the documented XG contract titles call: `XG_RESOURCE_DESC` and the 14-method `XGTextureAddressComputer`, from the authorized GDK documentation. Behaviour:
- **Linear layouts:** every texture is laid out linearly with BetterXen's documented alignment.
- **`SW_64KB_S` addressing** for a texture that fits one 64 KiB tile.
- **Other requested swizzle modes** are laid out linearly and reported as `LINEAR`, logged once per mode. Refusing them crashed a title that does not check the result.
- **`GetResourceTiling`** reports the D3D12 standard 64 KB tile shapes and a packed mip tail. 3D resources get the 3D tile shapes with depth tiles; 1D textures and buffers get 64 KiB tiles.
- **Limits:** descriptions past the public D3D12 limits (16384 for 1D/2D, 2048 for 3D and array sizes) are refused rather than truncated, and so is a 3D subresource past the mip count.
The earlier clean-room interface is removed: `xg_xs.cpp`, `xg_texture.h` and `test_xg_xs`. `test_xg_xbox` (42 checks) replaces it, and stage 13 of `test_integration_boot` uses the documented contract.
- **Roadmap and working method (proposed).** `docs/roadmap.md` replaces the subsystem milestones M3–M6 with stages the project-authorized target build reaches (Boot, Picture, Menus, World, Fidelity, Playable), each judged on ten recorded runs on a 16 GB Mac, with decision gates for the D3DMetal back end, reference images, memory and frame rate. [docs/process/working-method.md](docs/process/working-method.md) describes the blocker queue for a team that works by telling coding agents to "work": where state lives, the order of work (own pull requests, review, one blocker, discover), the run protocol, source ranks and pull-request shape. AGENTS.md §0 is rewritten to match.
- `BXVM` configuration writes the output `cpu_pointer` before changing shared configuration or releasing a cached backing heap. If that write fails after the accessibility check, the call returns `E_INVALIDARG` without applying the configuration.
- `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
- [Target-build bring-up: development cycle and review](docs/testing/target-build-review.md): how contributors run a project-authorized target build offline, turn findings into single-track PRs, and review them independently.
- `xgameruntime.dll` serves the XPackage installation monitor offline: the running package is reported fully installed, launchable and complete. Monitor handles share the mount handles' table, generation and lock: stale handles are rejected, closing twice is harmless, and uninitialize releases them. Progress registrations are accepted, logged and never fired. `XPackageEnumeratePackages` reports this game for `XPackageKind::Game` and no content packages. Both replace stubs that a project-authorized target build calls at startup. The save-container mount path ends with the drive-root separator, and `test_xgameruntime_saves` expects it.
- `AcpHal.dll`:
- **Shape contexts:** `AcpHalAllocateShapeContexts` and `AcpHalReleaseShapeContexts` allocate from the APU heap. The layout is the documented `SHAPE_CONTEXTS` (96 bytes; CPU pointers at 24, APU addresses at 72). A second allocation returns `ACP_E_ALREADY_ALLOCATED`.
- **`IAcpHal`** has the documented non-COM slot order: `Connect`, `Disconnect`, `SubmitCommand`, `PopMessage`, `GetNumMessages`, `Release`.
- **The default APU heap** is 64 MB.
- **Tests:** `test_audio_input` checks both. `test_integration_boot` releases `IAcpHal` through its own `Release` slot.
- `d3d12_xs.dll` carries a project-authorized target build from device creation into its frame loop. The Xbox-layout device and its objects get:
- **Descriptor heaps** with title-visible storage and the console descriptor sizes.
- **Committed and placed resources** in title memory, with copy coherence for `Map`/`Unmap`.
@@ -71,11 +57,6 @@ 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
- `XCRDAPI.dll` Xbox DirectStorage fixes:
- **Zlib requests read the file.** The file handle was not set for them, so every compressed file request failed. The request options are now decoded, and zlib streams are inflated in-tree.
- **`AutoSubmitDisabled` is honoured.** Xbox `CreateQueueX` respects `DSTORAGE_QUEUE_OPTIONS.AutoSubmitDisabled`: a queue with the flag runs nothing before `Submit`, and when it is full the enqueuer waits until `Submit` is called on another thread. A queue without the flag submits by itself once half full.
- **Request trace:** `BX_DSTORAGE_TRACE=1`.
- **Tests:** `test_xcrdapi_xbox` covers a file-source zlib request and both queue behaviours. Each check fails with its fix reverted.
- `xmem.dll` physical page numbers count 4 KiB frames. A 64 KiB page's number is a multiple of 16, and each allocation's numbers start at a multiple of 0x1000 frames. With consecutive numbers, callers that keep `number >> 4` collapsed 16 pages into one, and memory written through one page appeared in others. Physical pages are mapped as runs: one view per run of consecutive pages instead of one per page. On a project-authorized target build, startup went from 36 s to 6 s, under the title's 30-second watchdog. Allocation goes through the title's registered allocation hooks, with one section per physical-page call. A GPU-only reservation with large pages (no CPU access, a `PAGE_GRAPHICS_*` bit set) becomes a mappable placeholder region, so console page-mapping calls can fill it. `BX_XMEM_TRACE=1` logs allocations, frees and maps. `test_xmem_physical` checks the page-number units, and `test_xmem_hooks` checks the hooks.
- `d3d12_xs.dll` refuses an Xbox-layout object the host cannot back. If the host object lacked the interface an Xbox table forwards to (on vkd3d, `ID3D12Device10`), `bx_xbox_wrap` returned the PC object, and `D3D12XboxCreateDevice` reported an Xbox-layout device. A title calling Xbox slot numbers would then have reached PC methods. The device and every wrapped family now fail with `E_NOINTERFACE`, logged as `xbox_wrap_refused`. `test_d3d12_xbox_layout` verifies the refusal on such a host and skips (exit 77); it passes on D3DMetal.
- `d3d12_xs` validates placement on **every heap and every placement entry point** (#554, #572). `CreatePlacedResource` (slot 29) checked alignment, extent, buffer clear value and the UPLOAD/READBACK initial state only on the backing heap, and `CreatePlacedResource1` (`ID3D12Device8` slot 70) and `CreatePlacedResource2` (`ID3D12Device10` slot 77) were generated pass-throughs with no check and no `kPlacedResourceHeap` retention, so the shim heap wrapper and its xmem charge could be released while a resource placed through them was still alive. All three now share `create_placed_common` in `vmem.cpp`: a null heap or desc, a misaligned offset or a resource past the heap end returns `E_INVALIDARG` with `*out` null and a `placed_resource` log line naming the method, and a shim heap is retained by the resource on all three. `CreatePlacedResource2` takes a barrier layout, so the resource-state rule is not applied to it, and its allocation info comes from `GetResourceAllocationInfo2` without the castable-format list. `tools/gen_proxy.py` gains a `HANDOFF` table that keeps the generated trace and null-host stub and passes the host interface and unmodified arguments to a function declared from the header signature; `proxy_generated.{h,cpp}` are regenerated, and no new vtable slot is patched. `test_d3d12_placed` adds misaligned, aligned-overhang, valid-offset and UPLOAD-state cases on an ordinary heap for each entry point, and runs the heap-charge retention check through all three. Run live under CrossOver 26.3 in a D3DMetal bottle: passes (173 checks, 1 skipped — the 512 MiB pairing check; at `BX_MEM_LIMIT_MB=512`, 189 checks, 0 skipped), including every `CreatePlacedResource2` case. Against the previous shim the new cases fail ten checks there: D3DMetal returned `S_OK` for a misaligned offset, an aligned overhang and an UPLOAD heap in `COPY_DEST` on all three entry points it was asked about, and the slot 70/77 resources dropped the heap charge. Under `bx-cli run` (vkd3d) the fixture also passes (163 checks, 3 skipped); that host does not expose `ID3D12Device10`.
+2 -2
View File
@@ -3,7 +3,8 @@
## Getting Started & Architecture
- [Project README](../README.md) — Overview, quick start, `bx-cli` commands, and verified scope.
- [Roadmap](roadmap.md) — Single authoritative plan (Milestones M0–M6) and completion gates.
- [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) — Proposed: 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.
- [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/`).
@@ -20,7 +21,6 @@
## Research, Testing & Licensing
- [Target-Build Bring-Up: Development Cycle and Review](testing/target-build-review.md) — How contributors run a project-authorized target build offline, turn findings into single-track PRs, and review them independently without proprietary details.
- [Hybrid Workloads & Measurement Protocol](testing/hybrid-workloads.md) — Original Windows workloads, receipt fields, timing conventions, and negative controls.
- [CrossOver Licensing & Redistribution Boundaries](research/crossover-licensing.md) — Per-component license review for CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, D3DMetal, and Rosetta 2.
- [Upstream Research Registry](research/upstream-registry.md) & [Component Reuse Matrix](research/component-reuse-matrix.md) — Public upstream evaluation and provenance screening.
+198
View File
@@ -0,0 +1,198 @@
# Working Method: the Blocker Queue
**Status: proposed**, together with the matching change to [AGENTS.md §0](../../AGENTS.md).
BetterXen is built by collaborators who each have the project-authorized target build and who work by pointing a coding agent at this repository and saying **"work"**. This document is written for that. It answers one question for an agent that has just been told to work: *what is the single most useful thing to do now, and how do I do it without colliding with the other agents?*
There are no meetings, no rotating roles and no plan to interpret. The state of the project is in GitHub; the rules are here and in AGENTS.md.
## Why this shape
What the first target-build runs taught us:
- **The build finds what tests cannot.** With the start-up milestone verified complete, the build still stopped on a missing handle-duplication call, an instruction loop that trapped two million times and a page-remapping race. Nobody would have written an issue for any of them in advance.
- **Guessing is expensive.** A stall was blamed on network polling for a day; a thread sample found the real cause in minutes.
- **A helpful workaround can hide the real path.** Answering every pipeline call with success kept the frame loop alive and hid the build's fallback to shader containers.
- **One run proves little.** The build takes different start-up paths from run to run. Two blockers looked like one "intermittent stop" until runs were counted.
- **Agents left alone drift.** They wrote long documents, opened large stacked pull requests that nobody reviewed, investigated the same symptom twice, shared one game bottle and filled a disk.
So: the build decides what is next, the queue makes it unambiguous, and reviewing comes before new work.
## The stages
The [roadmap](../roadmap.md) is a ladder of stages the target build reaches: **Boot → Picture → Menus → World → Fidelity → Playable**. Exactly one stage is current. Its exit gate is a ten-run check anyone can repeat.
## Where the state lives
| What | Where | Who writes it |
| --- | --- | --- |
| The current stage and its latest gate result | The pinned **ladder issue** (label `ladder`) | Any agent that runs the gate check |
| Everything the build is known to stop on | One **blocker issue** each (label `blocker`, plus `stage: <name>` and a track label) | The agent that found it |
| Who is working on what | A claim comment on the blocker issue | The claiming agent |
| What needs a person | Label `needs-human` | Any agent |
| Rules | AGENTS.md and this document | Maintainers, by pull request |
Nothing about status is kept in files in the repository: agents editing one status file would conflict all day.
### Blocker issues
A blocker issue is small and has a fixed shape, so that two agents that find the same thing file the same issue.
- **Title:** `[blocker] <signature>`. The signature is taken from the run report, not invented: for example `unimplemented IXUser slot 3`, `fault in XCRDAPI.dll (write, unmapped)`, `exit status 1 after save query`, `stall: presenting thread in trapped instruction`. Before filing, search open and closed issues for the signature.
- **Body:** the stage it blocks; how many of ten runs hit it; the run-report lines; what is known and not known. No bytes, names, hashes or addresses from the build.
- **Order:** within a stage, the label `first` marks blockers that every run hits before any other; after those, lower issue number first.
## What an agent does when told "work"
AGENTS.md §0 has the binding version. In short, in strict order:
1. **Preflight.** Tools, login, disk space, an own bottle, a current `main`.
2. **Your own pull requests first.** Requested changes, failing checks or conflicts on a pull request your person opened.
3. **Then review.** The oldest open, non-draft pull request from *another* person that has no current review. Review it, and merge it if it is approved, green and not your person's. Review comes before new work because unreviewed work is worth nothing to the next run.
4. **Then one blocker.** The top unclaimed blocker of the current stage. Claim it, and do only that.
5. **Then discover.** If the current stage has no unclaimed blocker, run the stage's gate check and file what it finds. If the gate passes, post the result on the ladder issue and label it `needs-human`: a person confirms the stage change.
6. **Otherwise stop.** Report that the queue is empty. Do not invent work.
An agent stops and labels `needs-human` whenever it meets a decision that is not its to make: a decision gate, a licence or provenance question, a rule change, or two sources of truth that disagree.
## Working one blocker
```text
claim → evidence → smallest fix + test → ten runs → pull request → (someone else reviews and merges)
```
1. **Claim.** Comment `Claiming — branch: track-<a..f>/<issue>-<slug>` on the issue. A claim with no commits or pull request after 3 days is free to take; say so in a comment when you take it.
2. **Evidence before code.** Find what the build asked for and what it got. Use the run report, then the diagnostics (thread sampler, fault context, call trace). If that does not explain it within the session, write what was learned on the issue and release the claim; do not guess a fix.
3. **Smallest fix.** Only what removes this blocker, inside the track directories it needs. A new cross-DLL export still goes through an `[ABI]` pull request first.
4. **A test for the contract.** Every contract the fix teaches a shim gets a synthetic conformance test that fails without the fix.
5. **Proof.** Ten runs before and ten after. Report every run.
6. **Pull request.** One blocker, five short parts (below). Then stop: the next "work" starts from the top of the list.
### Pull-request description
Five parts and nothing else:
1. **Blocker:** `Closes #<issue>` and one sentence on what the build did.
2. **Contract:** what the console does, and which source says so (ranks below).
3. **Fix:** what changed.
4. **Test:** the conformance test, and that it fails without the fix.
5. **Proof:** before and after over ten runs (for example "status-5 exits: 4/10 → 0/10"), with the machine and the `main` commit.
### Review
The reviewing agent checks out the branch, runs the Section 8 commands and the new test, confirms the test fails without the fix, and reads the proof. It does not repeat the ten runs unless the proof looks wrong.
**Deep review** — re-deriving the contract from its source, by an agent working for a different person than the author — is required only for:
- a change under `abi/`;
- a new or changed translator instruction class;
- a contract from source rank 4 or 5;
- anything touching the sandbox, security or licensing.
**Merging.** The author's agent never merges its own person's pull request. Any other collaborator's agent merges once the pull request is approved and green. A pull request that is green and unreviewed after one working day gets the label `needs-human`.
**Stacks.** A pull request is based on `main`. One level of stacking is allowed when a fix truly needs an unmerged one; deeper stacks are not.
## Run protocol
A run counts only if it is made this way. The launcher does it; agents do not hand-roll it.
- **Build:** current `main`, or `main` plus exactly the one branch under test.
- **Sandbox:** the offline runner, which refuses to start unless a probe confirms outbound network is blocked.
- **Bottle:** one per agent session, created by the launcher and named for the session. Never a shared one.
- **One game at a time per machine.** The launcher takes a machine-wide lock; a second run waits.
- **Disk:** at least 10 GB free, checked before the run; the session's scratch bottle and build directory are removed afterwards.
- **Count and length:** ten runs, each as long as the stage needs (five minutes for Boot).
- **Machine:** the report states chip and memory. Gates are judged on 16 GB machines.
**The run report** is generated, not written. Per run:
- outcome: frames presented, clean timeout, early exit with its status, or hang;
- the start-up path taken;
- every unimplemented call reached, counted;
- every fault inside a BetterXen module;
- pipelines drawn with: translated, passed through, skipped;
- on a stall: every thread's stack.
It ends with a ten-run summary and a list of **signatures**, the strings blocker issues are titled with.
## Sources of truth
When a fix needs to know what the console does, use the strongest source available and name its rank in the pull request.
| Rank | Source | Notes |
| --- | --- | --- |
| 1 | Authorized GDK documentation and headers | Derived facts may be committed. The files never are. |
| 2 | Our own compiler output for our own source | Built with the console compiler from the GDK. |
| 3 | Run-time observation of the target build | What it calls, with what, and what it does with the answer. |
| 4 | Call-site analysis of the target build (a disassembler such as Ghidra) | When observation cannot explain a wait or a branch. Local only. |
| 5 | The authorized upstream emulator's source | A hint about what the build needs, not a reference for correctness. Confirm with ranks 1–4 or with runs. |
Collaborators may install the GDK and a disassembler for this. AGENTS.md §6 is unchanged: nothing from the build enters git, issues or pull requests — no bytes, file names, hashes, addresses or decompiled code.
## Evidence and references
- **Private evidence store.** Run logs, dumps, disassembly and captures go in a folder outside the repository on the collaborator's machine. Issues and pull requests carry counts, sizes, call shapes and the contract learned.
- **Reference images** (needed from the Picture stage on): a collaborator's own capture from a real console running the same content, or published footage. They live in the private store; a pull request says "matches reference screen 3".
## Finding blockers once the game runs
From the Menus stage on, the build no longer stops by itself at the next missing piece: someone has to take it somewhere. Agents are poor players, so the method does not depend on an agent holding a controller. BetterXen owns both ends of the build's contact with the machine — input (`GameInput`) and graphics (`d3d12_xs`) — and records and replays both.
**1. People play; the launcher records.** A play session with recording on saves the input stream with timestamps and the save files it started from. A hotkey marks a moment ("texture wrong here", "audio cut out"). A crash or hang needs no mark: the run report has it.
**2. Agents replay routes.** A route is a starting save plus a short recorded input stream (about two minutes: load, walk somewhere, enter a vehicle). An agent replays it through the input shim and compares the run with the last good one. Replays drift, because the build is not deterministic, so routes stay short and start from a save. Each route is a regression test, run ten times like any gate.
**3. Frame capture and offline replay.** The graphics layer records every call the build makes for one frame, with the data it referenced. The frame is then redrawn without the build running, in seconds and identically every time. An agent fixing a picture bug replays that frame after each change instead of booting and travelling to the spot again.
**How a problem is recognised,** from most to least reliable without a person:
| Signal | Catches | Needs a person |
| --- | --- | --- |
| Crash, hang, early exit | Stability | No |
| Run-report counters: skipped draws, stubbed shader instructions, unimplemented calls, failed storage requests | Missing pieces, even when the picture looks plausible | No |
| Frame compared with the last good capture of the same route | Regressions | No |
| Frame compared with a console reference image | Wrong rendering | To supply the reference |
| An agent looking at a capture | Obvious breakage: black screen, missing geometry, garbage textures | No; subtle errors are missed |
| A person's mark during play | Feel, audio sync, input lag, anything that "looks off" | Yes |
Findings enter the queue as blocker issues with signatures of the same kind: `route 7: crash at 1:40 (3/10)`, `capture 12: 340 draws skipped`, `capture 12: differs from reference in the sky`. The order of work does not change.
Whether the game is good to play is a question only people answer. Their time goes into playing and marking, never into reproducing or bisecting.
## What people do
People are needed for exactly four things, each marked `needs-human`:
1. confirming a stage change after a gate passes;
2. deciding a decision gate (for example the graphics back end);
3. licence, provenance and legal questions;
4. changing these rules.
Everything else is the queue.
## Starting the queue
The queue starts with what the first target-build runs already found. Each line becomes a blocker issue or a tooling issue when this proposal is accepted.
| Stage | Signature or task | Track |
| --- | --- | --- |
| Boot | Run tooling in the repository: offline runner, per-run report with signatures, ten-run summary, thread sampler, machine-wide run lock, per-session bottle | A |
| Boot | `stall: presenting thread in trapped CLZERO loop` | A |
| Boot | `unimplemented IXUser slot 3` (handle duplication) | E |
| Boot | `unimplemented IXGameRuntimeCore slots 6, 13, 14, 15` (async run; task-queue composite, port, duplicate) | E |
| Boot | `unimplemented IXGameSaveImpl slot 13` (container info; and slot 15) | E |
| Boot | `fault in XCRDAPI.dll (write, unmapped)` — page remapping is not atomic | B |
| Boot | `serialized-pipeline calls succeed with a null pipeline` — they must fail and be logged | C |
| Boot | `exit status 1, nothing logged` (1 run in 5) | A |
| Picture | D3DMetal capability checks: direct heap indexing, 64-lane compute through the translator, 64-bit atomics, mesh and amplification shaders | D, F |
| Picture | Vendor the upstream translator with provenance entries; amend ADR 0008 | D |
| Picture | Translator behind `bx_shader_bridge.dll`; host pipelines created on first use | C, D |
| Picture | `placed texture contents not uploaded` | C |
| Picture | `build waits after sign-in with nothing unimplemented` — needs evidence | E |
| Picture | Reference images for the first screens | `needs-human` |
| Menus | Input record and replay in the `GameInput` shim; routes as ten-run regression tests | E, A |
| Menus | Play-session recording in the launcher: input stream, starting saves, mark hotkey | A |
| Fidelity | Frame capture in `d3d12_xs` and an offline frame replayer | C |
Fixes for several Boot lines exist on a local experiment branch; they still go through the queue, one pull request each, with tests and ten-run proof.
+9 -15
View File
@@ -137,10 +137,8 @@ not define the patterns.
`scarlett-tex-layouts` returns HTTP 200 with only the membership gate; all
`/windows/win32/api/xg/*` paths 404. The numeric `XG_SWIZZLE_MODE` values are
not public. BetterXen's earlier local `BX_XG_LAYOUT_*` constants and clean-room XG
interface have been retired: `xg_xs.dll` now follows the documented XG contract
titles call, with values from the authorized GDK documentation recorded as derived
facts in `shims/xg_xs/xg_xbox.cpp`.
not public, so BetterXen's `BX_XG_LAYOUT_*` values 1/2/3 are **local** constants,
not the console's.
### Element sizes and the derived masks
@@ -166,15 +164,11 @@ distinct offsets, each block-aligned and inside the tile).
### Verification
The three masks above were expanded and their bijectivity checked against an
independently written `pdep` reference, outside the shim. `test_xg_xbox.exe`
(which replaced the retired `test_xg_xs.exe`) does not read its expected values
back from the shim:
- at 32 bpp it compares every offset of a one-tile texture with the public D3D12
standard swizzle, and checks the offset -> texel inverse and a copy round trip;
- at 8 and 16 bytes per element (the 8-byte case as BC1 blocks) it checks that
the offsets are a bijection of aligned slots inside the 64 KiB tile;
- it checks that the 16 texels of a BC block share one byte offset.
Requested modes the shim does not implement (`SW_64KB_D`, multi-tile, multi-mip)
are laid out linearly and reported as `LINEAR`. Synthetic evidence only; no
independently written `pdep` reference, outside the shim. `test_xg_xs.exe`
re-derives its expected offsets from those masks (and, at 32 bpp, from the
D3D12 page) rather than reading them back from the shim: one test per block
size, covering intra-block offsets (the 16 texels of a BC block share one byte
offset), independently derived absolute offsets, and an offset -> texel -> offset
round trip. It keeps asserting `E_NOTIMPL` for `SW_64KB_D`, `SW_64KB_R`, 1D/3D,
MSAA, and every multi-mip or multi-slice case. Synthetic evidence only; no
Xbox-hardware claim.
+81 -20
View File
@@ -1,6 +1,6 @@
# BetterXen Roadmap
**This is the single authoritative active roadmap.** Strategic decisions are recorded in [ADR 0005](adr/0005-crossover-hybrid-direction.md) (CrossOver-based hybrid direction) and [ADR 0006](adr/0006-retire-in-tree-native-workspace.md) (retiring the paused native-first workspace to Git tag `native-first-final`). Track ownership and parallel workflow rules live in [docs/architecture/parallel-tracks.md](architecture/parallel-tracks.md); Wave 1 contributor issues live in [docs/issues/wave-1-backlog.md](issues/wave-1-backlog.md).
**This is the single authoritative active roadmap.** Strategic decisions are recorded in [ADR 0005](adr/0005-crossover-hybrid-direction.md) (CrossOver-based hybrid direction) and [ADR 0006](adr/0006-retire-in-tree-native-workspace.md) (retiring the paused native-first workspace to Git tag `native-first-final`). How the team and its agents work is in [docs/process/working-method.md](process/working-method.md). Track (directory) ownership is in [docs/architecture/parallel-tracks.md](architecture/parallel-tracks.md); the completed Wave 1 issues are in [docs/issues/wave-1-backlog.md](issues/wave-1-backlog.md).
## Direction
@@ -19,7 +19,7 @@ External Foundation (user-installed, never bundled):
Apple Silicon: ARM64, Metal, unified memory
```
This is an active engineering stack, **not a verified commercial Xbox game compatibility layer**. Progress is measured strictly by reproducible synthetic conformance tests and recorded verification evidence — never by commit counts or unverified compatibility claims.
This is an active engineering stack, **not a verified commercial Xbox game compatibility layer**. The product goal is one project-authorized target build, fully playable on Apple Silicon Macs with 16 GB of memory. From the Boot stage on, progress is measured by how far that build gets in repeated, recorded runs ([working method](process/working-method.md)); every contract a fix introduces is also pinned by a synthetic conformance test. Progress is never measured by commit counts or unverified compatibility claims.
Priorities, in order: practical compatibility, correctness, stability, observability, Apple Silicon performance, and long-term maintainability.
@@ -35,34 +35,95 @@ Priorities, in order: practical compatibility, correctness, stability, observabi
---
## Milestones (M0 → M6)
## Foundation and stages
| Milestone | Objective | Exit Gate | Status |
The first three milestones (M0 to M2) were defined by subsystems and synthetic tests. They built the foundation, and they also showed the limit of that approach: with M1 verified complete, the target build still stopped at more than a dozen missing or wrong contracts that no synthetic test had asked for. From here on, the roadmap is a ladder of **stages the target build reaches**, observed in runs every collaborator can repeat. Synthetic conformance tests stay mandatory for every contract a fix introduces; they no longer define progress.
### Foundation (history)
| Milestone | What it established | Status |
| --- | --- | --- |
| **M0 — Repo, ABI & cross-build** | Track layout, frozen `.def`/header contracts, env-isolated `bx-cli`, export verifier, live smoke tests | **Verified complete (#406)** |
| **M1 — Startup shims to `D3D12XboxCreateDevice`** | Wave 1 shims across Tracks A–F and the combined synthetic boot fixture | **Verified complete (Milestone #17)** |
| **M2 — Synthetic first frame & shader format gate** | `PresentX` through D3DMetal with pixel readback; Xbox-layout D3D12 objects (ADR 0009); the shader format question | **Closing.** Remaining: amend ADR 0008 to select Branch D2. The target build supplies console-compiled code only: shader containers whose `DXIL` part carries no bitcode, and serialized pipelines. |
### The stages
Every gate below is measured the same way ([working method](process/working-method.md#run-protocol)): the current `main`, the offline sandbox, a contributor's own bottle, **ten runs**, on a 16 GB Apple Silicon Mac. A gate that says "10/10" means ten of ten. Stages have names, not numbers: exactly one is current, and blocker issues carry its label (`stage: boot`, `stage: picture`, …).
| Stage | The target build… | Exit gate | Status |
| --- | --- | --- | --- |
| **M0 — Repo, ABI & Cross-Build** | Establish 6-track directory layout (`abi/`, `launcher/`, `shims/`, `shader-transpiler/`, `tests/conformance/`), frozen `.def`/header contracts, env-isolated `bx-cli`, strict PE Export Directory verifier, and live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb.exe`, `test_shim_exports.exe`) | ARM64 Rust checks green; all 17 PE32+ DLLs (16 mingw-w64 C++ shims + the Rust `bx_shader_bridge.dll`) pass strict export & zero-MinGW-dep verification; both synthetic EXEs pass live under CrossOver + Rosetta 2 | **Verified complete (`#406`)** |
| **M1 — Startup Shims to `D3D12XboxCreateDevice`** | Complete Wave 1 parallel issues across Tracks A–F: full `clwb` + crash register VEH, `xmem` core + physical/scatter page engine + Lockhart cap, `XCRDAPI` async file I/O MVP, `d3d12_xs` auto-logging COM proxy over Wine `d3d12.dll`, `xg_xs` linear-compatible layout MVP, `dxbc-accc` C ABI hook + `d3dmetal-native` evaluation, offline `xgameruntime` + dynamic loader exports, non-blocking `AcpHal`/`xapu`/`chad` stubs, `GameInput` `@1`, supervised `bx-cli run`, ADR 0007, and combined synthetic integration boot fixture | All Wave 1 conformance binaries pass under CrossOver 26.3 + Rosetta 2; combined `test_integration_boot.exe` passes (19 pass, 2 ADR-0007 pending, 0 fail) | **Verified complete (Milestone #17, 16/16)** |
| **M2 — First Rendered Frame & Shader Format Gate** | Clear dynamic GDK startup (`system32` staging + public GDK COM `QueryApiImpl` dispatch), implement `d3d12_xs` swapchain presentation (`PresentX` → `IDXGISwapChain3::Present`), integrate the shipped xmem-configured D3D12 placed heap (#464) into the first-frame fixture (#469), bridge `dxbc-accc` into Windows guests (`#445`), measure D3DMetal GPU limits (`#453`), and establish whether target runtime shader corpora use **DXIL (Branch D1)** or **console-compiled `ACCC`/`FSPX` RDNA 2 ISA (Branch D2)**. Measured translator constraints: [D3DMetal GPU limits](research/d3dmetal-gpu-limits.md#measured-constraints) | Synthetic D3D12 `PresentX` workload renders and verifies pixel readback through D3DMetal 3.0; M2 Gate ADR selects Branch D1 or Branch D2 | **In development (Milestone #18)** |
| **M3 — Full Shaders, Streaming & Texture Correctness** | DirectStorage decompression, accurate RDNA 2 (`gfx1030`) `xg_xs` tile-addressing & deswizzling, full `d3d12_xs` command-list/barrier/GPUVA fidelity, and Branch D1 DXIL normalization or Branch D2 `ACCC`/`FSPX` → DXIL/MSL transpiler, within the [measured D3DMetal GPU limits](research/d3dmetal-gpu-limits.md#measured-constraints) (`WaveSize(64)` and SM 6.6 64-bit atomics not run; bounded lock emulation) | Synthetic textured/swizzled, compute, multi-queue, and compressed DirectStorage conformance suites pass | Planned |
| **M4 — 3D Rendering, DXR/BVH4 & Upscaling** | Bridge `XboxBvhBuilder` / `ID3D12StateObject` ray tracing to D3DMetal 3.0 DXR (intercepting incompatible AMD BVH4 rehydration → live rebuild), provide PC FidelityFX / MetalFX upscaling shim, and wire full `GameInput` controller/KB/M input | Synthetic DXR + upscaled 3D scene and scripted `GameInput` conformance tests pass | Planned |
| **M5 — Software Audio/DSP, Saves & Stability** | Replace `AcpHal`/`xapu`/`chad` stubs with software audio/DSP decoding + XAudio2_9/CoreAudio output, wire `PersistentLocalStorage`, and resolve concurrency/memory/GPU hang bugs under soak testing | Synthetic audio playback, save round-trip, and multi-hour soak benchmarks pass with bounded memory | Planned |
| **M6 — Shader Cache, 16 GB Optimization & Polish** | Persistent disk PSO + translated-shader cache, Lockhart 16 GB unified memory pressure tuning, Metal System Trace optimization, and optional Swift launcher UI | Reproducible frame-pacing and memory-pressure receipts under [docs/testing/hybrid-workloads.md](testing/hybrid-workloads.md) | Planned |
| **Boot** | starts, reaches its frame loop and stays there | 10/10 runs present frames for 5 minutes; the run report lists no unimplemented call on the path taken, no fault in a BetterXen module, and no early exit | **In development** |
| **Picture** | shows its first non-black screen, correctly | In 10/10 runs the first reference screen matches the reference image within the agreed tolerance; every pipeline drawn with is a translated pipeline, none is skipped | Planned |
| **Menus** | plays its opening sequence and menus with sound and input | A scripted input sequence goes from launch to the last menu before gameplay in 10/10 runs; audio is audible and in sync by the checklist; a save written in one run is read in the next | Planned |
| **World** | loads into gameplay and keeps running | 10/10 runs enter gameplay and run 10 minutes with no crash, hang or early exit; streaming requests complete without error; memory stays inside the 16 GB profile | Planned |
| **Fidelity** | draws its 3D scenes as the console does | The scene checklist (geometry, textures, lighting, effects, HUD) passes against the reference set at the fixed capture points; no draw or dispatch is skipped or stubbed | Planned |
| **Playable** | is playable start to finish on every supported Mac | 30 fps or better at the tier's resolution for each chip tier; a 2-hour session with bounded memory and no hang; warm start uses the shader cache; controller and keyboard/mouse complete | Planned |
### Startup diagnosis
"Reference image" and "reference set" are captures of the same content from a real console or from published footage, kept in the private evidence store, never in the repository ([working method](process/working-method.md#evidence-and-references)).
The product goal is to reach a frame presented by the target software. Under the current [contribution rules](../CONTRIBUTING.md), project runs use original synthetic workloads. Start with `test_integration_boot.exe` for startup and `test_veh_unhandled.exe` as a crash-logging control. Use a focused synthetic reproducer once a failing contract is identified.
### Boot
Before treating either startup warning as causal, add diagnostics that record the requested DirectStorage factory IID and returned HRESULT (#483) and distinguish null, unrecognized and supported BetterXen virtual-memory configurations (#464 follow-up). On a pinned launcher, shim set and backend, repeat the synthetic case before and after a fix. Record normal exit, crash or timeout, the last completed checkpoint, and the exception thread and module offset when available. Progress means reaching the next named checkpoint in the same reproducer. Startup diagnosis and the budget fix proceed alongside the M2 exit gates.
**Known work, all found by running the target build:**
### M2 first-frame acceptance and parallel memory work
| Blocker | Effect | State |
| --- | --- | --- |
| `CLZERO` trapped once per 64 bytes | The frame loop stalls for tens of seconds while the build zeroes memory | Fix exists locally (the loop completes in one trap); needs a PR and a conformance test |
| A storage worker writes into a page xmem is remapping | The build's own fault handler exits (status 5) | Bounded retry exists locally. The real fix is an atomic remap in `xmem` |
| Missing runtime calls: `XUserDuplicateHandle`, `XAsyncRun`, `XTaskQueue` duplicate/port/composite, `XGameSaveGetContainerInfo` and its by-name variant | The build waits forever or exits (status 1) | Implemented locally; need PRs and tests |
| Serialized-pipeline calls answered with success in null-render mode | The build never falls back to its shader containers | Decide and document: these calls fail (logged) until they are implemented |
| One early exit (status 1) with nothing logged | 1 run in 5 | Open: needs the run report's exit capture |
| Run tooling lives outside the repository | Nobody else can repeat a run or read its result the same way | Move the offline runner, the run report and the sampler into `launcher/` and `scripts/` |
- **First frame (#465, #469).** The synthetic placement criterion uses BetterXen's `BXVM` block to configure the separate D3D12-owned WRITE_BACK heap shipped in #486. On the recorded overlay, #494 copied the backbuffer before the flip, counted one host `Present`, then compared 256 RGBA8 pixels through the D3D12 mapping after waiting. The xmem sentinel shows that the original page remained separate. Visibility through the original xmem address remains an open compatibility question for M3, informed by #473. Displayed-image verification is outside this fixture's measurements. Record a single `main` commit containing the integrated presentation and fixture changes, confirm that the fixture executable built, and have someone who authored neither the fixture nor the presentation bridge verify the D3DMetal run and pixel-mismatch control. The shader gate still requires a recorded D1/D2 selection. [Fixture and receipts](https://github.com/MacosPorters/betterxen/pull/494) · [ADR 0008](adr/0008-m2-shader-format-gate.md)
- **Shader format gate (#466, ADR 0008).** D1 remains the only branch with end-to-end execution evidence, and the static scan gives it measured inputs in the target workload: 52 DXIL SM 6.5 compute containers with LLVM bitcode. The same scan makes D2 a concrete compatibility candidate rather than a hypothesis: the workload's FidelityFX upscaler component embeds 29 ACCC-only containers. Select D2 work only when a required pipeline-creation path refuses an ACCC-only container at runtime — if that refusal precedes the first presented frame, treat it as a first-frame blocker; if it appears only with upscaling enabled, track it under M4 upscaling. Two Track D parser prerequisites precede any D2 trial: extend the clean-room `FSPX` section-table layout to accept the observed tables (a maintainer provenance decision, since no public format description exists), and stop the classifier from treating a `NOBC` header-only program as executable DXIL. The first `shader_gate` record the target workload writes names the shader path its first pipeline creation actually submits. [ADR 0008](adr/0008-m2-shader-format-gate.md)
- **Title budget (#550, #552).** Keep current allocation ownership and give xmem atomic admission authority through an ABI-first contract. The initial scope combines xmem usage with the existing charged `CreateHeap` path. Under a 512 MiB cap, an xmem allocation of 256 MiB followed by a 384 MiB heap was refused, while the reverse admitted 640 MiB. Test both orders, concurrent admission and rollback. Charge a backing allocation once across aliases. Accounting for `CreateHeap1`, committed and reserved resources, and internal buffers such as XCRDAPI staging remains an open scope decision. Placement and wrapper lifetime have separate checks (#554, #572). [Merged-base reproduction](https://github.com/MacosPorters/betterxen/pull/486#issuecomment-7209751182)
- **M3 resource handling.** Keep explicit paths for fixed addresses, existing contents, pre-device allocations, sections/scatter and opaque textures. The draft eligibility analysis found no reliable end-to-end classifier. Resolve the `XMemVirtualAlloc` argument-count question (#518) before using graphics flags as evidence. A mapped-buffer trial is optional and opt-in, with the existing path as fallback. Require a known consumer before returning a pointer, verify its alignment and lifetime, and confirm completion on every participating queue before reusing memory for work BetterXen submits. #483 retains its DirectStorage interface scope. [Draft eligibility analysis](https://github.com/MacosPorters/betterxen/blob/7e0b515131150fec6b5117c9498b6c0faf0ca382/docs/architecture/proposals/001-unified-memory/appendix/eligibility.md)
- **M6 optimization.** Compare the existing path with a candidate allocator or bounded pool on the same 16 GB host and backend. Check correct output for both paths across repeated matched workloads. Include cold setup, transfers, fragmentation, pending retirements, post-release footprint and whole-frame time. Require a repeatable workload benefit before choosing a default.
**Not needed for the gate:** audio output, correct pictures, performance.
### Picture
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.** Vendor a pinned copy of the authorized upstream GFX10-to-DXIL translator into `shader-transpiler/` (per-file licence check, upstream registry and reuse matrix entries, ADR 0008 amendment), and expose it through `bx_shader_bridge.dll`. BetterXen owns its copy and fixes it.
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.
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.
### Menus to Playable — known work and unknowns
Listed so lanes can prepare, not as a commitment to order. Each item is confirmed by a run before work starts on it.
| Stage | Known work | Main unknown |
| --- | --- | --- |
| **Menus** | XMA decoding and audio output through the audio coprocessor contract; `GameInput` devices; speech/accessibility provider; saves round trip | What the build waits for between sign-in and its first screen |
| **World** | DirectStorage page destinations, BCPack and swizzle options; XG tiling modes beyond linear; atomic page remapping; the Series S memory profile as the 16 GB default | Streaming behaviour under memory pressure |
| **Fidelity** | Mesh/amplification pipelines; indirect draws with console argument types; rectangle lists; the unimplemented command-list state calls; upscaler substitute (FSR 3.1 or plain scaling in place of the console's FSR 4); ray tracing: bridge it, or run the profile that does not use it | How much of the frame depends on the console's ray-tracing path |
| **Playable** | Translated-shader and pipeline cache; memory copies removed where the host allows; frame pacing against the display; chip-tier matrix | Whether the base 16 GB tier reaches 30 fps, and at what resolution |
### Decision gates
A gate is a question answered by a measurement, with the options written down before the measurement is taken.
| Gate | When | Question | If the answer is no |
| --- | --- | --- | --- |
| **Back end** | Start of Picture | Does D3DMetal run what translated console shaders need? | ADR: translator-side lowering, another host back end, or a narrower shader profile |
| **Reference** | Start of Picture | Do we have reference images for the first screens? | The Picture gate falls back to a written checklist per screen, agreed by two collaborators |
| **Memory** | Start of World | Does the build load into gameplay inside the 16 GB profile? | Series S profile only; reduce copies before any other World work |
| **Frame rate** | Start of Playable | Is the base tier within 2x of 30 fps? | Publish tiers honestly; lower the base tier's resolution before promising it |
### What counts as progress
A change belongs on `main` only if it passes the **step-forward test**. It must do one of these, and say which:
1. remove a blocker of the current stage (shown by the run report before and after);
2. remove a blocker already confirmed for a later stage, when every blocker of the current stage is claimed;
3. make a blocker faster to find (run tooling, diagnostics, a corpus test);
4. retire a risk at a decision gate.
Work that does none of these waits: subsystems nobody has seen the build need, documentation about work not yet done, and optimisation before the Playable stage.
---
## How Progress Is Reported
Milestone status is one of: `Planned`, `In development`, `In validation`, `Verified complete`, or `Blocked`. A milestone reaches `Verified complete` only after independent verification of its exit gate per [AGENTS.md](../AGENTS.md).
For the stages, the pinned ladder issue carries the live status: the current stage, the latest ten-run result for its gate, and the open blocker issues with their claims. A gate result is reported with every run counted, the machine it ran on, and the `main` commit.
-137
View File
@@ -1,137 +0,0 @@
# Target-Build Bring-Up: Development Cycle and Review
This is how any number of contributors run a project-authorized target build on BetterXen, turn what they find into pull requests, and review each other's work. It applies [AGENTS.md](../../AGENTS.md) Sections 5–7, the clean-room and provenance rules in [CONTRIBUTING.md](../../CONTRIBUTING.md), and [docs/legal.md](../legal.md). It adds no new permissions.
## Authorization is recorded, not assumed
AGENTS.md §6 allows evidence from *project-authorized* target builds, but it does not define who authorizes a build or how. Until a governance change defines that, this procedure requires a **recorded authorization**:
- **Before any target-build work,** a contributor writes an authorization note in the team's private evidence store (see "Evidence"). The note covers:
- the build;
- the evidence class: target-build observation, or authorized SDK documentation;
- the maintainer who approved it;
- how the contributor obtained the build or documentation lawfully, under terms that permit the inspection;
- the confirmation that the work needs no decryption or circumvention of security, DRM, licensing or activation controls.
- **Maintainer approval alone is not enough** (CONTRIBUTING.md). If any of these points is unknown, the build is not used.
- **The note's ID goes into every PR and every review** that relies on that evidence.
## Roles
- **Bring-up keeper.** One person keeps a running branch (for example `bringup/<topic>`). It merges the open fix branches, so the title can be run end to end. This branch is never proposed for `main`. The role can rotate.
- **Author.** Turns one finding into one single-track PR.
- **Reviewer.** Anyone other than the author whose own recorded authorization covers the same evidence class. The reviewer re-derives the contract from their own authorized source, never from the author's copies, notes or binaries. Someone who has accessed leaked or confidential material does not review (CONTRIBUTING.md).
- **Merger.** A maintainer other than the original author (AGENTS.md §7).
Work is organised by **area**, not by person. Areas follow the tracks in [parallel-tracks.md](../architecture/parallel-tracks.md): memory and storage, D3D12, XG, runtime and audio, shaders, tests and tooling. Each contributor claims an issue in an area. As more people join, an area takes more claims, but its file scope stays the same.
## Cycle
1. **Measure on the bring-up branch.** Run the title only through the offline-run procedure below. Find the first blocker with BetterXen's own diagnostics.
2. **Record the evidence privately,** under an evidence note ID.
3. **Open an issue** for the blocker. Name the API or contract. Do not name the title.
4. **Fix it on a track branch off `main`.** Stay within the issue's file scope. Add or update a synthetic conformance test for every contract the fix relies on.
5. **Open a PR** using the template below. The bring-up keeper merges the branch into the bring-up branch so that later blockers can be found.
6. **Review independently** (see "What a reviewer does").
7. **Merge and re-sync.** After a merge, the bring-up keeper rebases the bring-up branch on `main`.
### Bring-up checkpoints
These checkpoints describe how far a target build gets. They are **not** milestone status: milestones, their exit gates and the status vocabulary are defined only in [docs/roadmap.md](../roadmap.md) (M0–M6). A checkpoint can serve as evidence for a roadmap exit gate only where that gate says so.
1. **Starts:** reaches its first graphics device.
2. **Presents:** presents its first frame, whatever it contains.
3. **Frame loop:** keeps presenting for a recorded duration.
4. **Rendered content:** presents pixels produced by its own shaders (needs the M2/M3 shader work).
5. **Interactive:** reaches a menu that accepts input.
Each PR states which checkpoint it affects, and the measured result before and after.
## PR description template
```text
Contract: the derived facts (sizes, offsets, slot orders, flags, units, return values)
Source: "authorized SDK documentation" and/or "target-build observation";
never quote header or documentation text, never name the title or build
Authorization: authorization note ID
Evidence: evidence note ID(s)
Reproduce: the BetterXen commit, bx-cli options, BX_* switches and log events a reviewer checks
Test: the conformance test that asserts the contract, and how its expected
values were derived independently of the implementation
Checkpoint: the checkpoint this affects, with the measured result before and after
```
## What a reviewer does
The reviewer re-derives the contract and does not rely on the PR's conclusions (AGENTS.md §5).
1. **Documentation facts.** Compile a local probe against their own authorized headers and print the sizes, offsets and constants. Probes and their output stay outside this repository.
2. **Title behaviour.** If the fix depends on how the title uses an API (for example, units it stores or flags it passes), check this in their own analysis, under their own authorization.
3. **Title run.** Run the PR branch merged into the bring-up branch, using the offline-run procedure, and confirm the stated before-and-after result.
4. **Checks.** Run the AGENTS.md §8 checks. Confirm that the conformance test's expected values do not come from the code under test.
5. **Post the review.** Say what was re-derived and what was run, without proprietary details, and cite the note IDs.
## Offline-run procedure
Every title run must be unable to reach the network, because some titles upload crash dumps. The run is wrapped in a macOS sandbox profile that denies outbound IP traffic. Apple marks `sandbox-exec` as deprecated, but it still enforces profiles on current macOS; if it stops working, do not run the title until a replacement is documented here.
Copy these commands, filling in the bracketed values. Record the BetterXen commit (`git rev-parse HEAD`) and these exact commands in the evidence note.
```sh
CX=/Applications/CrossOver.app/Contents/SharedSupport/CrossOver
BOTTLE=<bottle name>
PREFIX="$HOME/Library/Application Support/CrossOver/Bottles/$BOTTLE"
PROFILE='(version 1)(allow default)(deny network-outbound (remote ip))'
# 1. Stop the bottle's wineserver. A wineserver started outside the sandbox would
# serve the title outside it.
env -i HOME="$HOME" PATH=/usr/bin:/bin WINEPREFIX="$PREFIX" "$CX/bin/wineserver" -k
env -i HOME="$HOME" PATH=/usr/bin:/bin WINEPREFIX="$PREFIX" "$CX/bin/wineserver" -w
# 2. Confirm the profile blocks outbound traffic. This must print BLOCKED; otherwise stop.
sandbox-exec -p "$PROFILE" /usr/bin/curl -sS -m 5 https://example.com >/dev/null 2>&1 \
&& echo REACHABLE || echo BLOCKED
# 3. Run the title inside the same profile. Every process it starts, including the new
# wineserver, inherits the sandbox.
env -i HOME="$HOME" USER="$USER" TMPDIR="$TMPDIR" PATH=/usr/bin:/bin:/usr/sbin:/sbin \
BX_TRACE_D3D=0 BX_NULL_RENDER=1 \
sandbox-exec -p "$PROFILE" target/debug/bx-cli run --inherit-env \
--bottle "$BOTTLE" --backend d3dmetal --profile <profile> \
--log <run>.jsonl --shims build-shims/bin --exe <path to the title executable>
```
**Why `env -i` with `--inherit-env`:** `bx-cli run` normally clears the guest environment to a fixed allowlist (AGENTS.md §3), and that allowlist has no `BX_*` diagnostic switches. Here `env -i` builds an environment that contains only the listed variables, and `--inherit-env` passes exactly that to the guest. Host credentials and other variables still never reach it.
**Confirming that the title stayed offline.** Run a guest-side probe that tries an outbound connection the same way. It must fail inside the sandbox and succeed outside it. The probe and its output belong in the evidence note.
Everyone uses the same pinned environment: the BetterXen commit, the CrossOver version, the macOS version and the `bx-cli` profile. A result is reported together with that environment.
## Diagnostics
All switches are off unless set, and none changes behaviour beyond what its row says. Only switches that exist on `main` are listed. Switches from open PRs are added here when those PRs merge.
| Switch | Where | Effect |
| --- | --- | --- |
| `BX_TRACE_D3D=1` | `d3d12_xs` | Logs every D3D12 call |
| `BX_NULL_RENDER=1` | `d3d12_xs` | Pipelines that cannot be built become null pipelines; their draws and dispatches are skipped and logged |
| `BX_PRESENT_DUMP=<folder>` | `d3d12_xs` | Writes presented frames as BMP files, every Nth present (`BX_PRESENT_DUMP_EVERY`, default 64) |
| `BX_XMEM_TRACE=1` | `xmem` | Logs physical page allocations, frees and mappings |
Their output can contain title addresses and file names, so it goes only into the private evidence store.
## Evidence
Logs, addresses, decompiled output, screenshots and authorization notes live in the team's private evidence store, outside this repository. PRs and reviews refer to them by note ID only.
## What never enters the repository
CONTRIBUTING.md (clean-room and provenance) and docs/legal.md set the rules. For target-build work in particular, never commit or post:
- SDK header or documentation text;
- the title's name or file names;
- identifiers derived from the title or build: its hashes, addresses or raw logs;
- decompiled code or disassembly;
- screenshots of the title;
- personal paths.
Hashes that record the provenance of third-party code (`THIRD_PARTY_NOTICES.md`, `docs/research/upstream-registry.md`) are not affected. Contracts are recorded as derived facts only.
+23 -104
View File
@@ -1,52 +1,29 @@
#include <windows.h>
#include <unknwn.h>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <mutex>
#include <new>
#include "bx_log.h"
namespace {
// IAcpHal (authorized GDK documentation; slot order derived from it): not a COM interface. Its
// six methods are Connect(numCommands, numMessages), Disconnect(), SubmitCommand(command,
// commandId, audioFrame, data, notification), PopMessage(ACP_MESSAGE*), GetNumMessages() and
// Release(). BetterXen has no audio control processor: commands are accepted and logged once,
// and no message ever arrives.
class AcpHal {
UINT32 commands_ = 0, messages_ = 0;
bool connected_ = false;
class AcpHal final : public IUnknown {
LONG refs = 1;
public:
virtual HRESULT WINAPI Connect(UINT32 num_commands, UINT32 num_messages) {
if (connected_) return HRESULT_FROM_WIN32(ERROR_ALREADY_INITIALIZED);
commands_ = num_commands;
messages_ = num_messages;
connected_ = true;
char detail[96];
std::snprintf(detail, sizeof(detail), "commands=%u messages=%u (no ACP processing)", num_commands, num_messages);
bx_log_emit(BX_LOG_INFO, "acphal", "connect", detail);
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
if (!out) return E_POINTER;
*out = nullptr;
if (iid != IID_IUnknown) return E_NOINTERFACE;
AddRef();
*out = this;
return S_OK;
}
virtual HRESULT WINAPI Disconnect() {
connected_ = false;
return S_OK;
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs); }
ULONG WINAPI Release() override {
ULONG left = InterlockedDecrement(&refs);
if (!left) delete this;
return left;
}
virtual HRESULT WINAPI SubmitCommand(UINT32 command, UINT64, UINT32, const void*, UINT32) {
if (!connected_) return E_UNEXPECTED;
static LONG logged = 0;
if (InterlockedIncrement(&logged) == 1) {
char detail[96];
std::snprintf(detail, sizeof(detail), "first command type %u accepted; ACP commands are not processed", command);
bx_log_emit(BX_LOG_WARN, "acphal", "submit_command", detail);
}
return S_OK;
}
virtual bool WINAPI PopMessage(void*) { return false; }
virtual UINT32 WINAPI GetNumMessages() { return 0; }
virtual void WINAPI Release() { delete this; }
virtual ~AcpHal() = default;
};
// Sorted synthetic address ranges. Zero is reserved for failed lookups.
@@ -70,77 +47,19 @@ HRESULT WINAPI AcpHalCreate(void** out) {
return *out ? S_OK : E_OUTOFMEMORY;
}
HRESULT WINAPI ApuAlloc(void** va, uint32_t* apu, uint32_t size, uint32_t alignment);
HRESULT WINAPI ApuFree(void* va);
// AcpHalAllocateShapeContexts(SHAPE_CONTEXTS*) / AcpHalReleaseShapeContexts() (authorized GDK
// documentation; layout and element sizes derived from it, no header text): the caller fills six
// counts, the call allocates each array from the APU heap and returns its CPU pointer and APU
// address. Allocating twice without a release fails with ACP_E_ALREADY_ALLOCATED.
struct ShapeContexts {
uint32_t counts[6]; // SRC, EQ/Comp, Filt/Vol, DMA, XMA, PCM
void* arrays[6]; // CPU pointers, same order
uint32_t apu[6]; // APU addresses, same order
};
static_assert(sizeof(ShapeContexts) == 96, "SHAPE_CONTEXTS is 96 bytes");
static_assert(offsetof(ShapeContexts, arrays) == 24 && offsetof(ShapeContexts, apu) == 72, "SHAPE_CONTEXTS layout");
constexpr uint32_t kShapeElementBytes[6] = {32, 160, 32, 16, 64, 32};
constexpr HRESULT kAcpAlreadyAllocated = static_cast<HRESULT>(0x8AC80001);
constexpr uint32_t kDefaultApuHeapBytes = 64u << 20;
void* shape_arrays[6];
bool shape_allocated = false;
HRESULT WINAPI AcpHalAllocateShapeContexts(void* argument) {
auto* contexts = static_cast<ShapeContexts*>(argument);
if (!contexts) return E_INVALIDARG;
if (shape_allocated) return kAcpAlreadyAllocated;
for (int i = 0; i < 6; ++i) {
if (contexts->counts[i] > (0xFFFFFFFFu / kShapeElementBytes[i])) return E_INVALIDARG;
}
{
// The console has a default non-cached APU heap; create one when the title made none.
std::lock_guard guard(heap_lock);
if (!heap_created) {
capacity = kDefaultApuHeapBytes;
used = 0;
heap_created = true;
bx_log_emit(BX_LOG_INFO, "acphal", "apu_default_heap", "no ApuCreateHeap before shape contexts: 64 MB default heap");
}
}
void* arrays[6] = {};
uint32_t apu[6] = {};
for (int i = 0; i < 6; ++i) {
if (!contexts->counts[i]) continue;
const uint32_t bytes = contexts->counts[i] * kShapeElementBytes[i];
const HRESULT hr = ApuAlloc(&arrays[i], &apu[i], bytes, 64);
if (FAILED(hr)) {
for (int j = 0; j < i; ++j) ApuFree(arrays[j]);
return E_OUTOFMEMORY;
}
std::memset(arrays[i], 0, bytes);
}
for (int i = 0; i < 6; ++i) {
contexts->arrays[i] = arrays[i];
contexts->apu[i] = apu[i];
shape_arrays[i] = arrays[i];
}
shape_allocated = true;
char detail[160];
std::snprintf(detail, sizeof(detail), "src=%u eqcomp=%u filtvol=%u dma=%u xma=%u pcm=%u", contexts->counts[0],
contexts->counts[1], contexts->counts[2], contexts->counts[3], contexts->counts[4], contexts->counts[5]);
bx_log_emit(BX_LOG_INFO, "acphal", "shape_contexts_allocated", detail);
return S_OK;
// NDA constraint: the public Microsoft Learn page for AcpHal is gated behind
// an Xbox developer NDA, so the true signatures and context layout are unknown
// from public sources. BetterXen therefore returns E_NOTIMPL (not the console's
// behaviour) and keeps the stub log so bx-cli trace still surfaces the call.
HRESULT WINAPI AcpHalAllocateShapeContexts(void* context) {
(void)context;
BX_STUB_LOG("AcpHal.dll", "AcpHalAllocateShapeContexts");
return E_NOTIMPL;
}
HRESULT WINAPI AcpHalReleaseShapeContexts(void) {
if (!shape_allocated) return S_OK;
for (void*& array : shape_arrays) {
ApuFree(array);
array = nullptr;
}
shape_allocated = false;
return S_OK;
BX_STUB_LOG("AcpHal.dll", "AcpHalReleaseShapeContexts");
return E_NOTIMPL;
}
HRESULT WINAPI ApuCreateHeap(uint32_t cached, uint32_t non_cached) {
-1
View File
@@ -1,6 +1,5 @@
bx_add_shim_dll(xcrdapi XCRDAPI XCRDAPI.def
xcrdapi.cpp
zlib_inflate.cpp
)
target_include_directories(xcrdapi PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/dstorage")
target_link_libraries(xcrdapi PRIVATE bx_runtime_veh kernel32 uuid)
-3
View File
@@ -55,15 +55,12 @@ struct Request {
UINT compression;
ID3D12Resource* resource = nullptr;
UINT64 resource_offset = 0;
DWORD output_size = 0; // compression_zlib: bytes the stream inflates to at `destination`
};
inline constexpr UINT compression_none = 0;
inline constexpr UINT compression_lz = 1;
inline constexpr UINT compression_bcpack = 2;
inline constexpr UINT compression_gdeflate = 3;
// RFC 1950 zlib streams (Xbox DSTORAGE_REQUEST_OPTIONS.ZlibDecompress); decoded by zlib_inflate.cpp.
inline constexpr UINT compression_zlib = 4;
struct ErrorRecord {
HRESULT first_error;
+11 -135
View File
@@ -1,5 +1,4 @@
#include "synthetic_storage.h"
#include "zlib_inflate.h"
// Public PC DirectStorage contract: Microsoft.Direct3D.DirectStorage 1.4.0,
// MIT per file, vendored unmodified under dstorage/ (see dstorage/README.md).
@@ -9,8 +8,6 @@
#include <cstring>
#include <limits>
#include <new>
#include <mutex>
#include <atomic>
#include "bx_log.h"
@@ -418,65 +415,7 @@ CopyResult copy_staged(HANDLE file, const Request& request) {
return staged.finish(win32_error());
}
HRESULT inflate_request(HANDLE file, const Request& request) {
if (!request.destination || !request.output_size || request.size >= request.output_size) return E_INVALIDARG;
auto* compressed = static_cast<uint8_t*>(HeapAlloc(GetProcessHeap(), 0, request.size));
if (!compressed) return E_OUTOFMEMORY;
HRESULT hr = read_bytes(file, request.file_offset, compressed, request.source, request.size);
if (SUCCEEDED(hr)) {
const BxInflateResult r = bx_zlib_inflate(compressed, request.size, static_cast<uint8_t*>(request.destination),
request.output_size);
if (r != BxInflateResult::ok) {
static std::atomic<UINT> logged{0};
if (logged.fetch_add(1) < 16) {
char detail[160];
std::snprintf(detail, sizeof(detail), "zlib stream of %lu bytes to %lu bytes: %s", request.size,
request.output_size, bx_inflate_result_name(r));
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_zlib_failed", detail);
}
hr = E_DSTORAGE_DECOMPRESSION_ERROR;
}
}
HeapFree(GetProcessHeap(), 0, compressed);
return hr;
}
CopyResult fulfill_request(HANDLE file, const Request& request);
// Diagnostics (off unless BX_DSTORAGE_TRACE=1): one line per memory-destination request with its
// destination range, sizes, file offset, result and the first 16 bytes written, up to 20000.
bool dstorage_trace_enabled() {
static const bool on = [] {
char value[8];
const DWORD n = GetEnvironmentVariableA("BX_DSTORAGE_TRACE", value, sizeof(value));
return n > 0 && n < sizeof(value) && value[0] == '1';
}();
return on;
}
CopyResult fulfill(HANDLE file, const Request& request) {
const CopyResult result = fulfill_request(file, request);
if (!dstorage_trace_enabled() || request.resource) return result;
static std::atomic<UINT> traced{0};
if (traced.fetch_add(1) >= 20000) return result;
const DWORD out = request.compression == compression_zlib ? request.output_size : request.size;
uint64_t head[2] = {0, 0};
if (SUCCEEDED(result.hr) && request.destination && out >= 16) std::memcpy(head, request.destination, 16);
char detail[220];
std::snprintf(detail, sizeof(detail), "dst=%p..%p out=%lu src=%lu offset=0x%llx compression=%u hr=0x%08lx head=%016llx %016llx",
request.destination, static_cast<const uint8_t*>(request.destination) + out, out, request.size,
static_cast<unsigned long long>(request.file_offset), request.compression,
static_cast<unsigned long>(result.hr), static_cast<unsigned long long>(head[0]),
static_cast<unsigned long long>(head[1]));
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_request", detail);
return result;
}
CopyResult fulfill_request(HANDLE file, const Request& request) {
if (request.compression == compression_zlib) {
if (request.resource) return {E_NOTIMPL, false};
return {inflate_request(file, request), false};
}
if (request.compression) {
log_compression(request.compression);
return {E_NOTIMPL, false};
@@ -504,12 +443,9 @@ CopyResult fulfill_request(HANDLE file, const Request& request) {
}
// Each queue is drained serially, in FIFO order, by a single threadpool work item.
// A `blocking` queue makes a full enqueue wait for a free slot instead of failing
// with ERROR_BUSY. A non-zero `auto_submit` submits once that many entries are
// waiting, and a full queue submits what is pending before it waits. With
// `auto_submit` 0 (Xbox DSTORAGE_QUEUE_OPTIONS.AutoSubmitDisabled) nothing runs
// before Submit: a full queue stalls the enqueuer until Submit is called on
// another thread and the drain frees a slot. The public DirectStorage queues use
// A `blocking` queue makes a full enqueue wait for a free slot (submitting what is
// pending first) instead of failing with ERROR_BUSY. A non-zero `auto_submit`
// submits once that many entries are waiting. The public DirectStorage queues use
// both; the BetterXen synthetic queues use neither.
class WorkQueue final : public Object<Queue, queue_iid> {
public:
@@ -535,8 +471,7 @@ public:
}
Entry entry{Kind::request, *request};
if (request->resource) request->resource->AddRef();
// Uncompressed and zlib requests read the file; other compressions are refused when fulfilled.
if (request->file && (request->compression == compression_none || request->compression == compression_zlib)) {
if (request->file && !request->compression) {
const HRESULT result = request->file->GetHandle(&entry.handle);
if (FAILED(result)) {
if (request->resource) request->resource->Release();
@@ -678,7 +613,7 @@ private:
if (closed_) return HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE);
if (size_ < capacity_) return S_OK;
if (!blocking_) return HRESULT_FROM_WIN32(ERROR_BUSY);
if (auto_submit_ && submitted_ < size_) submit();
if (submitted_ < size_) submit();
SleepConditionVariableSRW(&space_, &mutex_, INFINITE, 0);
}
}
@@ -1379,39 +1314,8 @@ static_assert(offsetof(XboxRequest, source_ptr) == 0x20, "source_ptr offset");
static_assert(offsetof(XboxRequest, file_offset) == 0x28, "file_offset offset");
static_assert(offsetof(XboxRequest, source_size) == 0x30, "source_size offset");
// DSTORAGE_REQUEST_OPTIONS (authorized GDK documentation): ZlibDecompress:1, BcpackMode:4,
// SwizzleMode:16, DestinationIsPhysicalPages:1, SourceType:1, SourceIsPhysicalPages:1.
constexpr UINT64 kXboxRequestSourceMemoryBit = 0x400000ull; // SourceType, bit 22
constexpr UINT64 kXboxRequestCompressedBit = 0x1ull; // ZlibDecompress, bit 0
constexpr UINT64 kXboxRequestBcpackMask = 0xFull << 1;
constexpr UINT64 kXboxRequestSwizzleMask = 0xFFFFull << 5;
constexpr UINT64 kXboxRequestDestinationPagesBit = 1ull << 21;
constexpr UINT64 kXboxRequestSourcePagesBit = 1ull << 23;
// Logs each distinct option combination once, so a run shows which MDU stages a title uses.
void log_request_options(UINT64 options, UINT32 source_size, UINT32 destination_size, UINT32 intermediate_size) {
static std::mutex lock;
static UINT64 seen[64];
static size_t count = 0;
const UINT64 key = options & ~kXboxRequestSourceMemoryBit;
{
std::lock_guard<std::mutex> guard(lock);
for (size_t i = 0; i < count; ++i) {
if (seen[i] == key) return;
}
if (count < 64) seen[count++] = key;
}
char detail[200];
std::snprintf(detail, sizeof(detail),
"options=0x%llx zlib=%d bcpack_mode=%llu swizzle_mode=%llu dest_pages=%d source_memory=%d source_pages=%d "
"first sizes: source=%u destination=%u intermediate=%u",
static_cast<unsigned long long>(options), static_cast<int>(options & 1),
static_cast<unsigned long long>((options & kXboxRequestBcpackMask) >> 1),
static_cast<unsigned long long>((options & kXboxRequestSwizzleMask) >> 5),
(options & kXboxRequestDestinationPagesBit) ? 1 : 0, (options & kXboxRequestSourceMemoryBit) ? 1 : 0,
(options & kXboxRequestSourcePagesBit) ? 1 : 0, source_size, destination_size, intermediate_size);
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_request_options", detail);
}
constexpr UINT64 kXboxRequestSourceMemoryBit = 0x400000ull;
constexpr UINT64 kXboxRequestCompressedBit = 0x1ull;
struct IXboxDStorageFile : IUnknown {
virtual void STDMETHODCALLTYPE Close() = 0;
@@ -1520,25 +1424,12 @@ public:
reject(E_DSTORAGE_INVALID_SOURCE_TYPE, Kind::request, "EnqueueRequest");
return;
}
log_request_options(request->options, request->source_size, request->destination_size, request->reserved34);
if (request->options & kXboxRequestBcpackMask) {
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_bcpack");
if ((request->options & kXboxRequestCompressedBit) != 0) {
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_compressed");
reject(E_NOTIMPL, Kind::request, "EnqueueRequest");
return;
}
if (request->options & kXboxRequestSwizzleMask) {
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_swizzle");
reject(E_NOTIMPL, Kind::request, "EnqueueRequest");
return;
}
if (request->options & (kXboxRequestDestinationPagesBit | kXboxRequestSourcePagesBit)) {
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_physical_pages");
reject(E_NOTIMPL, Kind::request, "EnqueueRequest");
return;
}
const bool zlib = (request->options & kXboxRequestCompressedBit) != 0;
if (!request->destination || (zlib ? request->source_size >= request->destination_size
: request->source_size != request->destination_size)) {
if (!request->destination || request->source_size != request->destination_size) {
reject(E_DSTORAGE_INVALID_DESTINATION_SIZE, Kind::request, "EnqueueRequest");
return;
}
@@ -1546,10 +1437,6 @@ public:
Request translated{};
translated.destination = request->destination;
translated.size = request->source_size;
if (zlib) {
translated.compression = compression_zlib;
translated.output_size = request->destination_size;
}
if (is_memory) {
if (!request->source_ptr) {
reject(E_INVALIDARG, Kind::request, "EnqueueRequest");
@@ -1736,22 +1623,11 @@ public:
const UINT slots = desc->capacity - 1u;
auto* entries = new (std::nothrow) Entry[slots];
if (!entries) return E_OUTOFMEMORY;
// desc->flags is DSTORAGE_QUEUE_OPTIONS (authorized GDK documentation): bit 0,
// AutoSubmitDisabled, makes the queue wait for Submit. A title maps a request's
// destination pages after enqueueing it and before submitting, so starting work at half
// capacity wrote into pages that were not mapped yet.
constexpr UINT64 kAutoSubmitDisabled = 1;
const UINT auto_submit = (desc->flags & kAutoSubmitDisabled) ? 0u : desc->capacity / 2u;
auto* queue = new (std::nothrow) WorkQueue(entries, slots, true, auto_submit);
auto* queue = new (std::nothrow) WorkQueue(entries, slots, true, desc->capacity / 2u);
if (!queue) {
delete[] entries;
return E_OUTOFMEMORY;
}
char detail[128];
std::snprintf(detail, sizeof(detail), "xbox queue '%s' capacity=%u source=%llu auto_submit=%s",
desc->name ? desc->name : "", static_cast<unsigned>(desc->capacity),
static_cast<unsigned long long>(desc->source_type), auto_submit ? "half capacity" : "disabled");
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_queue", detail);
if (!queue->create_work()) {
const HRESULT error = win32_error();
queue->Release();
-249
View File
@@ -1,249 +0,0 @@
/* zlib (RFC 1950) / deflate (RFC 1951) decoder; see zlib_inflate.h. */
#include "zlib_inflate.h"
namespace {
struct Bits {
const uint8_t* data;
size_t size;
size_t pos = 0; // next byte
uint32_t buffer = 0;
int count = 0; // valid bits in buffer
bool overrun = false;
// RFC 1951 3.1.1: data elements are packed starting with the least significant bit.
uint32_t get(int n) {
while (count < n) {
if (pos >= size) {
overrun = true;
return 0;
}
buffer |= static_cast<uint32_t>(data[pos++]) << count;
count += 8;
}
const uint32_t value = buffer & ((n == 32) ? 0xFFFFFFFFu : ((1u << n) - 1u));
buffer >>= n;
count -= n;
return value;
}
void align_to_byte() {
buffer >>= (count & 7);
count -= (count & 7);
}
};
constexpr int kMaxBits = 15;
// Canonical Huffman decoding (RFC 1951 3.2.2): counts per code length and symbols sorted by code.
struct Huffman {
uint16_t counts[kMaxBits + 1] = {};
uint16_t symbols[320] = {};
// Returns false for an over-subscribed set of lengths. An incomplete set is allowed (a
// single distance code is legal), and decoding an unassigned code then fails.
bool build(const uint8_t* lengths, int n) {
for (int i = 0; i <= kMaxBits; ++i) counts[i] = 0;
for (int i = 0; i < n; ++i) ++counts[lengths[i]];
counts[0] = 0;
int left = 1;
for (int len = 1; len <= kMaxBits; ++len) {
left <<= 1;
left -= counts[len];
if (left < 0) return false;
}
uint16_t offsets[kMaxBits + 2] = {};
for (int len = 1; len <= kMaxBits; ++len) offsets[len + 1] = offsets[len] + counts[len];
for (int i = 0; i < n; ++i) {
if (lengths[i]) symbols[offsets[lengths[i]]++] = static_cast<uint16_t>(i);
}
return true;
}
// Huffman codes are packed most significant bit first, one bit at a time.
int decode(Bits& in) const {
int code = 0, first = 0, index = 0;
for (int len = 1; len <= kMaxBits; ++len) {
code |= static_cast<int>(in.get(1));
if (in.overrun) return -1;
const int count = counts[len];
if (code - first < count) return symbols[index + (code - first)];
index += count;
first += count;
first <<= 1;
code <<= 1;
}
return -1;
}
};
// RFC 1951 3.2.5 length and distance tables.
constexpr uint16_t kLengthBase[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};
constexpr uint8_t kLengthExtra[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0};
constexpr uint16_t kDistBase[30] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
constexpr uint8_t kDistExtra[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
struct Output {
uint8_t* data;
size_t size;
size_t pos = 0;
};
BxInflateResult codes(Bits& in, Output& out, const Huffman& lit, const Huffman& dist) {
for (;;) {
const int symbol = lit.decode(in);
if (symbol < 0) return in.overrun ? BxInflateResult::truncated : BxInflateResult::bad_data;
if (symbol < 256) {
if (out.pos >= out.size) return BxInflateResult::output_mismatch;
out.data[out.pos++] = static_cast<uint8_t>(symbol);
continue;
}
if (symbol == 256) return BxInflateResult::ok;
const int li = symbol - 257;
if (li >= 29) return BxInflateResult::bad_data;
const size_t length = kLengthBase[li] + in.get(kLengthExtra[li]);
const int ds = dist.decode(in);
if (ds < 0) return in.overrun ? BxInflateResult::truncated : BxInflateResult::bad_data;
if (ds >= 30) return BxInflateResult::bad_data;
const size_t distance = kDistBase[ds] + in.get(kDistExtra[ds]);
if (in.overrun) return BxInflateResult::truncated;
if (distance > out.pos) return BxInflateResult::bad_data;
if (length > out.size - out.pos) return BxInflateResult::output_mismatch;
for (size_t i = 0; i < length; ++i, ++out.pos) out.data[out.pos] = out.data[out.pos - distance];
}
}
BxInflateResult fixed_block(Bits& in, Output& out) {
static Huffman lit, dist;
static bool built = [] {
uint8_t lengths[288];
int i = 0;
for (; i < 144; ++i) lengths[i] = 8;
for (; i < 256; ++i) lengths[i] = 9;
for (; i < 280; ++i) lengths[i] = 7;
for (; i < 288; ++i) lengths[i] = 8;
lit.build(lengths, 288);
uint8_t dl[30];
for (int d = 0; d < 30; ++d) dl[d] = 5;
dist.build(dl, 30);
return true;
}();
(void)built;
return codes(in, out, lit, dist);
}
BxInflateResult dynamic_block(Bits& in, Output& out) {
const int hlit = static_cast<int>(in.get(5)) + 257;
const int hdist = static_cast<int>(in.get(5)) + 1;
const int hclen = static_cast<int>(in.get(4)) + 4;
if (in.overrun) return BxInflateResult::truncated;
if (hlit > 286 || hdist > 30) return BxInflateResult::bad_data;
static constexpr uint8_t kOrder[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
uint8_t lengths[320] = {};
for (int i = 0; i < hclen; ++i) lengths[kOrder[i]] = static_cast<uint8_t>(in.get(3));
if (in.overrun) return BxInflateResult::truncated;
Huffman code_lengths;
if (!code_lengths.build(lengths, 19)) return BxInflateResult::bad_data;
int index = 0;
while (index < hlit + hdist) {
int symbol = code_lengths.decode(in);
if (symbol < 0) return in.overrun ? BxInflateResult::truncated : BxInflateResult::bad_data;
if (symbol < 16) {
lengths[index++] = static_cast<uint8_t>(symbol);
continue;
}
uint8_t value = 0;
int repeat;
if (symbol == 16) {
if (index == 0) return BxInflateResult::bad_data;
value = lengths[index - 1];
repeat = 3 + static_cast<int>(in.get(2));
} else if (symbol == 17) {
repeat = 3 + static_cast<int>(in.get(3));
} else {
repeat = 11 + static_cast<int>(in.get(7));
}
if (in.overrun) return BxInflateResult::truncated;
if (index + repeat > hlit + hdist) return BxInflateResult::bad_data;
while (repeat--) lengths[index++] = value;
}
if (lengths[256] == 0) return BxInflateResult::bad_data; // no end-of-block code
Huffman lit, dist;
if (!lit.build(lengths, hlit) || !dist.build(lengths + hlit, hdist)) return BxInflateResult::bad_data;
return codes(in, out, lit, dist);
}
uint32_t adler32(const uint8_t* data, size_t size) {
uint32_t a = 1, b = 0;
while (size) {
size_t chunk = size < 5552 ? size : 5552; // largest n with no 32-bit overflow before the modulo
size -= chunk;
while (chunk--) {
a += *data++;
b += a;
}
a %= 65521u;
b %= 65521u;
}
return (b << 16) | a;
}
} // namespace
BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size) {
// RFC 1950 2.2: CMF (method 8 = deflate, window <= 32 KiB), FLG (check bits, no FDICT).
if (!input || input_size < 6 || (!output && output_size)) return BxInflateResult::bad_header;
const uint8_t cmf = input[0], flg = input[1];
if ((cmf & 0x0F) != 8 || (cmf >> 4) > 7 || ((cmf << 8) | flg) % 31 != 0 || (flg & 0x20)) {
return BxInflateResult::bad_header;
}
Bits in{input + 2, input_size - 2};
Output out{output, output_size};
for (;;) {
const uint32_t final_block = in.get(1);
const uint32_t type = in.get(2);
if (in.overrun) return BxInflateResult::truncated;
BxInflateResult r;
if (type == 0) {
in.align_to_byte();
const uint32_t len = in.get(16), nlen = in.get(16);
if (in.overrun) return BxInflateResult::truncated;
if ((len ^ 0xFFFFu) != nlen) return BxInflateResult::bad_data;
// After aligning, the bit buffer is empty: copy straight from the byte stream.
if (len > in.size - in.pos) return BxInflateResult::truncated;
if (len > out.size - out.pos) return BxInflateResult::output_mismatch;
for (uint32_t i = 0; i < len; ++i) out.data[out.pos++] = in.data[in.pos++];
r = BxInflateResult::ok;
} else if (type == 1) {
r = fixed_block(in, out);
} else if (type == 2) {
r = dynamic_block(in, out);
} else {
return BxInflateResult::bad_data;
}
if (r != BxInflateResult::ok) return r;
if (final_block) break;
}
if (out.pos != out.size) return BxInflateResult::output_mismatch;
// RFC 1950: the Adler-32 trailer follows the deflate data, byte-aligned, most significant first.
in.align_to_byte();
const size_t trailer = in.pos - static_cast<size_t>(in.count / 8);
if (input_size - 2 - trailer < 4) return BxInflateResult::truncated;
const uint8_t* t = in.data + trailer;
const uint32_t expected = (static_cast<uint32_t>(t[0]) << 24) | (static_cast<uint32_t>(t[1]) << 16) |
(static_cast<uint32_t>(t[2]) << 8) | t[3];
return adler32(output, output_size) == expected ? BxInflateResult::ok : BxInflateResult::bad_checksum;
}
const char* bx_inflate_result_name(BxInflateResult result) {
switch (result) {
case BxInflateResult::ok: return "ok";
case BxInflateResult::bad_header: return "bad_header";
case BxInflateResult::bad_data: return "bad_data";
case BxInflateResult::truncated: return "truncated";
case BxInflateResult::output_mismatch: return "output_mismatch";
case BxInflateResult::bad_checksum: return "bad_checksum";
}
return "unknown";
}
-28
View File
@@ -1,28 +0,0 @@
#pragma once
/*
* A zlib stream decoder written from the public specifications: IETF RFC 1950 (the zlib
* wrapper and its Adler-32 check) and RFC 1951 (deflate: stored, fixed-Huffman and
* dynamic-Huffman blocks, 32 KiB window). No third-party code.
*
* Used for DirectStorage requests whose DSTORAGE_REQUEST_OPTIONS.ZlibDecompress bit is set
* (authorized GDK documentation: RFC 1950 streams, full 32 KiB window, compressed size smaller
* than the decompressed size).
*/
#include <cstddef>
#include <cstdint>
enum class BxInflateResult {
ok,
bad_header, // not an RFC 1950 header, or a preset dictionary is required
bad_data, // malformed deflate data
truncated, // the input ended before the final block
output_mismatch, // the stream does not produce exactly `output_size` bytes
bad_checksum, // Adler-32 of the output does not match the stream trailer
};
/* Decodes `input` into exactly `output_size` bytes at `output`. */
BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size);
const char* bx_inflate_result_name(BxInflateResult result);
+1 -1
View File
@@ -1,4 +1,4 @@
bx_add_shim_dll(xg_xs xg_xs xg_xs.def
xg_xbox.cpp
xg_xs.cpp
)
target_link_libraries(xg_xs PRIVATE bx_runtime_veh kernel32)
+195
View File
@@ -0,0 +1,195 @@
#ifndef BETTERXEN_XG_TEXTURE_H
#define BETTERXEN_XG_TEXTURE_H
/*
* BetterXen M1 linear texture-address contract for xg_xs.dll.
*
* Field meanings follow the public D3D12 resource and footprint documents
* (D3D12_RESOURCE_DIMENSION, D3D12_SUBRESOURCE_FOOTPRINT, and
* D3D12_TEXTURE_DATA_PITCH_ALIGNMENT / D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT).
* Block-compressed footprint width and height are texels rounded up to the
* 4x4 block, the same rounding D3D12 uses for a copyable footprint.
* Format numbers are the public DXGI_FORMAT values. This is not the Xbox
* GDK XG interface and it is not an Xbox hardware result.
*/
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <stdint.h>
#include <dxgiformat.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Public D3D12_RESOURCE_DIMENSION values used by this shim. */
#define BX_XG_DIMENSION_BUFFER 1u
#define BX_XG_DIMENSION_TEXTURE1D 2u
#define BX_XG_DIMENSION_TEXTURE2D 3u
#define BX_XG_DIMENSION_TEXTURE3D 4u
/* Public D3D12 texture copy alignments, in bytes. */
#define BX_XG_LINEAR_PITCH_ALIGNMENT 256u
#define BX_XG_LINEAR_PLACEMENT_ALIGNMENT 512u
/* Public D3D12 texture size limits used as the acceptance cap. */
#define BX_XG_MAX_TEXTURE_EDGE 16384u
#define BX_XG_MAX_ARRAY_SLICES 2048u
/*
* Layout selectors for this shim. LINEAR is computed exactly.
* SW_64KB_S / D / R are named RDNA 2 tile modes reserved for M3. They are
* accepted by XGCreateTextureComputer and every layout or copy call on them
* returns E_NOTIMPL without writing an address.
* XGSuggestSwizzleMode never returns a tile mode. It returns LINEAR or NONE.
*/
typedef enum bx_xg_layout_mode {
BX_XG_LAYOUT_LINEAR = 0,
BX_XG_LAYOUT_SW_64KB_S = 1,
BX_XG_LAYOUT_SW_64KB_D = 2,
BX_XG_LAYOUT_SW_64KB_R = 3,
BX_XG_LAYOUT_NONE = 0xFFFFFFFFu
} bx_xg_layout_mode;
typedef struct bx_xg_sample_desc {
uint32_t count;
uint32_t quality;
} bx_xg_sample_desc;
typedef struct bx_xg_resource_desc {
uint32_t dimension;
uint32_t alignment; /* 0 or BX_XG_LINEAR_PLACEMENT_ALIGNMENT */
uint64_t width; /* texels */
uint32_t height; /* texels */
uint16_t depth_or_array_size;
uint16_t mip_levels; /* 0 selects the full chain, down to 1x1 */
uint32_t format; /* DXGI_FORMAT */
bx_xg_sample_desc sample_desc;
uint32_t layout; /* bx_xg_layout_mode */
uint32_t flags; /* must be 0 */
} bx_xg_resource_desc;
typedef struct bx_xg_subresource_footprint {
uint32_t format;
uint32_t width; /* texels, rounded up to the format block width */
uint32_t height; /* texels, rounded up to the format block height */
uint32_t depth;
uint32_t row_pitch; /* bytes, multiple of BX_XG_LINEAR_PITCH_ALIGNMENT */
} bx_xg_subresource_footprint;
typedef struct bx_xg_placed_footprint {
uint64_t offset;
bx_xg_subresource_footprint footprint;
/*
* Absolute byte just past this subresource's last payload byte:
* offset + (row_count - 1) * row_pitch + row_bytes.
* That is the D3D12 GetCopyableFootprints end. It does not include the
* last row's pitch padding or the 512-byte tail. The copy span of a
* GetResourceLayout call is layouts[last].copy_end - base_offset.
*/
uint64_t copy_end;
} bx_xg_placed_footprint;
/* {B7E4C8A1-6F2D-4C55-8A19-3D0E5F7B91C4} BetterXen IXGTextureAddressComputer */
static const GUID BX_IID_IXGTextureAddressComputer = {
0xB7E4C8A1u, 0x6F2Du, 0x4C55u, {0x8Au, 0x19u, 0x3Du, 0x0Eu, 0x5Fu, 0x7Bu, 0x91u, 0xC4u}};
/* Public COM IUnknown IID. */
static const GUID BX_IID_IUnknown = {
0x00000000u, 0x0000u, 0x0000u, {0xC0u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x46u}};
/*
* GetResourceLayout places every subresource at its absolute offset from
* base_offset, including subresources before first_subresource. total_bytes
* is the BetterXen allocation span: the 512-aligned end of the last requested
* subresource, measured from base_offset, so a partial range still covers the
* earlier subresources and a 1x1 RGBA8 texture reports 512. copy_end on each
* footprint is the separate D3D12-style copy span end described above.
*/
typedef struct bx_xg_texture_computer bx_xg_texture_computer;
typedef struct bx_xg_texture_computer_vtbl {
HRESULT(WINAPI* QueryInterface)(bx_xg_texture_computer* self, const GUID* riid, void** object);
ULONG(WINAPI* AddRef)(bx_xg_texture_computer* self);
ULONG(WINAPI* Release)(bx_xg_texture_computer* self);
HRESULT(WINAPI* GetResourceLayout)(
bx_xg_texture_computer* self,
uint32_t first_subresource,
uint32_t subresource_count,
uint64_t base_offset,
bx_xg_placed_footprint* layouts,
uint32_t* row_counts,
uint64_t* row_sizes_in_bytes,
uint64_t* total_bytes);
HRESULT(WINAPI* GetResourceSizeBytes)(bx_xg_texture_computer* self, uint64_t* size_bytes);
HRESULT(WINAPI* GetResourceBaseAlignmentBytes)(bx_xg_texture_computer* self, uint64_t* alignment_bytes);
HRESULT(WINAPI* GetMipLevelOffsetBytes)(
bx_xg_texture_computer* self,
uint32_t array_slice,
uint32_t mip_level,
uint64_t* offset_bytes);
HRESULT(WINAPI* GetTexelElementOffsetBytes)(
bx_xg_texture_computer* self,
uint32_t array_slice,
uint32_t mip_level,
uint32_t x,
uint32_t y,
uint32_t z,
uint64_t* offset_bytes);
HRESULT(WINAPI* CopyIntoSubresource)(
bx_xg_texture_computer* self,
void* destination,
uint64_t destination_size,
uint32_t subresource,
const void* source,
uint64_t source_size,
uint32_t source_row_pitch,
uint32_t source_depth_pitch);
HRESULT(WINAPI* CopyFromSubresource)(
bx_xg_texture_computer* self,
void* destination,
uint64_t destination_size,
uint32_t destination_row_pitch,
uint32_t destination_depth_pitch,
const void* source,
uint64_t source_size,
uint32_t subresource);
} bx_xg_texture_computer_vtbl;
struct bx_xg_texture_computer {
const bx_xg_texture_computer_vtbl* lpVtbl;
};
/*
* On success, *computer is an IXGTextureAddressComputer with a reference
* count of 1. On failure, *computer is NULL when computer itself is non-NULL.
* Subresource index is mip_level + array_slice * mip_levels.
* A row pitch of 0 on a copy selects the tight logical row size.
*/
HRESULT WINAPI XGCreateTextureComputer(const bx_xg_resource_desc* desc, void** computer);
/*
* Returns BX_XG_LAYOUT_LINEAR when this shim can lay the texture out, and
* BX_XG_LAYOUT_NONE otherwise. The same arguments always return the same mode.
*/
uint32_t WINAPI XGSuggestSwizzleMode(
uint32_t resource_type,
uint32_t format,
uint32_t width,
uint32_t height,
uint32_t depth,
uint32_t mip_levels,
uint32_t sample_count,
uint32_t flags);
#ifdef __cplusplus
}
#endif
#endif /* BETTERXEN_XG_TEXTURE_H */
-683
View File
@@ -1,683 +0,0 @@
/*
* The XG texture-address contract as titles call it (authorized GDK documentation, xg_xs.h):
* XGCreateTextureComputer(const XG_RESOURCE_DESC*, XGTextureAddressComputer**) and
* XGSuggestSwizzleMode(const XG_RESOURCE_DESC*, flags, XG_TEXTURE_LAYOUT*). Only the structure
* layouts, enum values and the method order are taken from there; no header text is reproduced.
*
* The layout this computer reports is BetterXen's, not the console's: every texture is laid out
* linearly (swizzle mode LINEAR), mip-major (each mip holds all of its array or depth slices),
* rows aligned to 256 bytes, mips to 512 bytes, the resource to 64 KB. Depth-stencil formats
* get a separate depth plane and stencil plane. Every method uses the same layout, so sizes,
* offsets, texel addresses and copies agree with each other. Data a title stores pre-tiled for
* the console's swizzle modes is not detiled by this layer.
*
* The one exception is an explicit request for XG_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_S on a 2D
* texture that fits in one 64 KiB tile (one mip, one slice, 4-, 8- or 16-byte elements): that
* gets the RDNA 2 SW_64KB_S addresses (see Sw64kbS). Any other explicit swizzle mode, and
* SW_64KB_S on a texture larger than one tile, is laid out linearly, reported as LINEAR
* (SwizzleMode 0) and logged once per mode: titles do not check XGCreateTextureComputer for a
* mode they request, so refusing it crashed one.
*/
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <dxgiformat.h>
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <new>
#include "bx_log.h"
namespace {
// --- XG types (layouts from xg_xs.h) -------------------------------------------------------
enum : uint32_t {
kDimBuffer = 1,
kDimTexture1D = 2,
kDimTexture2D = 3,
kDimTexture3D = 4,
};
// XG_TEXTURE_LAYOUT: 0 default (XG chooses), 1 row major, 2 64 KB with an undefined swizzle, or
// 0x100 | XG_SWIZZLE_MODE to request one swizzle mode.
constexpr uint32_t kLayoutSwizzleFlag = 0x100;
constexpr uint32_t kLayoutSwizzleLinear = 0x100; // XG_TEXTURE_LAYOUT_SWIZZLE_MODE_LINEAR
constexpr uint32_t kSwizzleModeLinear = 0;
constexpr uint32_t kSwizzleMode64KbS = 9; // XG_SWIZZLE_MODE_64KB_S
enum : uint32_t { kPlaneUnused = 0, kPlaneDefault = 1, kPlaneDepth = 7, kPlaneStencil = 8 };
// --- RDNA 2 SW_64KB_S (clean-room, ported from the earlier xg_xs.cpp) ---------------------
// Within one 64 KiB tile, the byte offset of element (x, y) is pdep(x, x_mask) | pdep(y, y_mask),
// x and y in elements (texels, or 4x4 blocks for BC). The masks come from the public AddrLib RB+
// pattern tables (GFX10_SW_64K_S_RBPLUS_PATINFO, MIT); at 4 bytes per element the x mask equals
// the public D3D12 standard-swizzle xBytesMask 0xAA8F without its two intra-texel bits, and the y
// mask equals D3D12's 0x5570. Each row is a bijection over its tile. How tiles are ordered across a
// larger surface is not established from public sources, so only surfaces that fit in one tile
// are addressed; larger ones fall back to the logged linear layout.
struct Sw64kbS {
uint32_t bytes;
uint32_t x_mask;
uint32_t y_mask;
uint32_t tile_x; // elements per tile row
uint32_t tile_y; // element rows per tile
};
bool sw64kb_s_params(uint32_t bytes, Sw64kbS* out) {
switch (bytes) {
case 4: *out = {4, 0xAA8Cu, 0x5570u, 128, 128}; return true;
case 8: *out = {8, 0xAAC8u, 0x5530u, 128, 64}; return true;
case 16: *out = {16, 0xAAC0u, 0x5530u, 64, 64}; return true;
default: return false;
}
}
uint32_t pdep(uint32_t value, uint32_t mask) {
uint32_t out = 0;
for (uint32_t bit = 1; mask; bit <<= 1) {
const uint32_t lowest = mask & (0u - mask);
if (value & bit) out |= lowest;
mask ^= lowest;
}
return out;
}
uint32_t pext(uint32_t value, uint32_t mask) {
uint32_t out = 0;
for (uint32_t bit = 1; mask; bit <<= 1) {
const uint32_t lowest = mask & (0u - mask);
if (value & lowest) out |= bit;
mask ^= lowest;
}
return out;
}
constexpr uint64_t kTileBytes = 64 * 1024;
struct XgSampleDesc {
UINT Count;
UINT Quality;
};
struct XgResourceDesc {
uint32_t Dimension;
UINT64 Alignment;
UINT64 Width;
UINT Height;
UINT16 DepthOrArraySize;
UINT16 MipLevels;
uint32_t Format;
XgSampleDesc SampleDesc;
uint32_t Layout;
uint32_t MiscFlags;
};
struct XgMipLevelLayout {
UINT64 SizeBytes;
UINT64 OffsetBytes;
UINT64 Slice2DSizeBytes;
UINT32 PitchPixels;
UINT32 PitchBytes;
UINT32 AlignmentBytes;
UINT32 PaddedWidthElements;
UINT32 PaddedHeightElements;
UINT32 PaddedDepthOrArraySize;
UINT32 WidthElements;
UINT32 HeightElements;
UINT32 WidthPixels;
UINT32 HeightPixels;
UINT32 DepthOrArraySize;
UINT32 SampleCount;
uint32_t SwizzleMode;
UINT64 BankRotationAddressBitMask;
UINT64 BankRotationBytesPerSlice;
UINT32 SliceDepthElements;
UINT32 IsMipTail;
UINT32 MipTailOffsetElementsX : 11;
UINT32 MipTailOffsetElementsY : 11;
UINT32 MipTailOffsetElementsZ : 10;
};
constexpr int kMaxMips = 15;
constexpr int kMaxPlanes = 4;
struct XgPlaneLayout {
uint32_t Usage;
UINT64 SizeBytes;
UINT64 SliceSizeBytes;
UINT64 BaseOffsetBytes;
UINT64 BaseAlignmentBytes;
UINT32 BytesPerElement;
UINT32 StandardMipCount;
UINT32 MipTailMipCount;
XgMipLevelLayout MipLayout[kMaxMips];
};
struct XgResourceLayout {
UINT64 SizeBytes;
UINT64 BaseAlignmentBytes;
UINT32 MipLevels;
UINT32 Planes;
XgPlaneLayout Plane[kMaxPlanes];
uint32_t Dimension;
};
// Pinned against the layouts derived from the GDK header (natural x64 alignment).
static_assert(sizeof(XgResourceDesc) == 56, "XG_RESOURCE_DESC size");
static_assert(offsetof(XgResourceDesc, Alignment) == 8 && offsetof(XgResourceDesc, Width) == 16, "XG_RESOURCE_DESC");
static_assert(sizeof(XgMipLevelLayout) == 112, "XG_MIPLEVEL_LAYOUT size");
static_assert(offsetof(XgPlaneLayout, MipLayout) == 56 && sizeof(XgPlaneLayout) == 1736, "XG_PLANE_LAYOUT size");
static_assert(offsetof(XgResourceLayout, Plane) == 24 && sizeof(XgResourceLayout) == 6976, "XG_RESOURCE_LAYOUT size");
struct XgPackedMipDesc {
UINT8 NumStandardMips;
UINT8 NumPackedMips;
UINT32 NumTilesForPackedMips;
UINT32 StartTileIndexInOverallResource;
};
struct XgTileShape {
UINT32 WidthInTexels;
UINT32 HeightInTexels;
UINT32 DepthInTexels;
};
struct XgSubresourceTiling {
UINT32 WidthInTiles;
UINT16 HeightInTiles;
UINT16 DepthInTiles;
UINT32 StartTileIndexInOverallResource;
};
// --- Formats -------------------------------------------------------------------------------
struct FormatInfo {
uint32_t block; // texels per element edge: 1, or 4 for block compression
uint32_t bytes; // bytes per element
uint32_t stencil; // 1 when the format carries a stencil plane
};
bool format_info(uint32_t f, FormatInfo* out) {
auto set = [&](uint32_t block, uint32_t bytes, uint32_t stencil = 0) {
*out = {block, bytes, stencil};
return true;
};
if (f >= DXGI_FORMAT_R32G32B32A32_TYPELESS && f <= DXGI_FORMAT_R32G32B32A32_SINT) return set(1, 16);
if (f >= DXGI_FORMAT_R32G32B32_TYPELESS && f <= DXGI_FORMAT_R32G32B32_SINT) return set(1, 12);
if (f >= DXGI_FORMAT_R16G16B16A16_TYPELESS && f <= DXGI_FORMAT_R32G32_SINT) return set(1, 8);
if (f >= DXGI_FORMAT_R32G8X24_TYPELESS && f <= DXGI_FORMAT_X32_TYPELESS_G8X24_UINT) return set(1, 4, 1);
if (f >= DXGI_FORMAT_R10G10B10A2_TYPELESS && f <= DXGI_FORMAT_R32_SINT) return set(1, 4);
if (f >= DXGI_FORMAT_R24G8_TYPELESS && f <= DXGI_FORMAT_X24_TYPELESS_G8_UINT) return set(1, 4, 1);
if (f >= DXGI_FORMAT_R8G8_TYPELESS && f <= DXGI_FORMAT_R16_SINT) return set(1, 2);
if (f >= DXGI_FORMAT_R8_TYPELESS && f <= DXGI_FORMAT_A8_UNORM) return set(1, 1);
if (f == DXGI_FORMAT_R9G9B9E5_SHAREDEXP || f == DXGI_FORMAT_R8G8_B8G8_UNORM || f == DXGI_FORMAT_G8R8_G8B8_UNORM) return set(1, 4);
if ((f >= DXGI_FORMAT_BC1_TYPELESS && f <= DXGI_FORMAT_BC1_UNORM_SRGB) ||
(f >= DXGI_FORMAT_BC4_TYPELESS && f <= DXGI_FORMAT_BC4_SNORM)) {
return set(4, 8);
}
if ((f >= DXGI_FORMAT_BC2_TYPELESS && f <= DXGI_FORMAT_BC3_UNORM_SRGB) ||
(f >= DXGI_FORMAT_BC5_TYPELESS && f <= DXGI_FORMAT_BC5_SNORM) ||
(f >= DXGI_FORMAT_BC6H_TYPELESS && f <= DXGI_FORMAT_BC7_UNORM_SRGB)) {
return set(4, 16);
}
if (f >= DXGI_FORMAT_B5G6R5_UNORM && f <= DXGI_FORMAT_B5G5R5A1_UNORM) return set(1, 2);
if (f >= DXGI_FORMAT_B8G8R8A8_UNORM && f <= DXGI_FORMAT_B8G8R8X8_UNORM_SRGB) return set(1, 4);
if (f == DXGI_FORMAT_B4G4R4A4_UNORM) return set(1, 2);
return false;
}
uint64_t align_up(uint64_t v, uint64_t a) { return (v + a - 1) / a * a; }
uint32_t mip_extent(uint64_t base, uint32_t mip) {
const uint64_t v = base >> mip;
return v ? static_cast<uint32_t>(v) : 1u;
}
constexpr uint64_t kRowAlign = 256;
constexpr uint64_t kMipAlign = 512;
constexpr uint64_t kResourceAlign = 64 * 1024;
void log_rejected(const XgResourceDesc* d, const char* why) {
char detail[200];
std::snprintf(detail, sizeof(detail), "%s: dim=%u width=%llu height=%u depth_or_array=%u mips=%u format=%u samples=%u layout=0x%x",
why, d->Dimension, static_cast<unsigned long long>(d->Width), d->Height, d->DepthOrArraySize,
d->MipLevels, d->Format, d->SampleDesc.Count, d->Layout);
bx_log_emit(BX_LOG_WARN, "xg_xs", "texture_computer_rejected", detail);
}
// A requested swizzle mode this layer does not implement: laid out (and reported) linearly; the
// first request for each mode is logged, with the description.
void log_linear_instead(const XgResourceDesc* d) {
static std::atomic<uint32_t> seen[32];
const uint32_t mode = d->Layout & 0x1F;
if (seen[mode].exchange(1)) return;
log_rejected(d, "requested swizzle mode is not implemented; laid out and reported as LINEAR");
}
// --- The computer ---------------------------------------------------------------------------
class XGTextureAddressComputer {
public:
virtual ULONG AddRef() = 0;
virtual ULONG Release() = 0;
virtual HRESULT GetResourceLayout(XgResourceLayout* layout) = 0;
virtual UINT64 GetResourceSizeBytes() = 0;
virtual UINT64 GetResourceBaseAlignmentBytes() = 0;
virtual UINT64 GetMipLevelOffsetBytes(UINT32 plane, UINT32 mip) = 0;
virtual UINT64 GetTexelElementOffsetBytes(UINT32 plane, UINT32 mip, UINT64 x, UINT32 y, UINT32 z_or_slice,
UINT32 sample, UINT32* bit_position) = 0;
virtual HRESULT GetTexelCoordinate(UINT64 offset, UINT32* plane, UINT32* mip, UINT64* x, UINT32* y,
UINT32* z_or_slice, UINT32* sample) = 0;
virtual HRESULT CopyIntoSubresource(void* base, UINT32 plane, UINT32 subresource, const void* linear,
UINT32 row_pitch, UINT32 slice_pitch) = 0;
virtual HRESULT CopyFromSubresource(void* linear, UINT32 plane, UINT32 subresource, UINT32 sample,
const void* base, UINT32 row_pitch, UINT32 slice_pitch) = 0;
virtual HRESULT GetResourceTiling(UINT32* total_tiles, XgPackedMipDesc* packed, XgTileShape* shape,
UINT32* subresource_count, UINT32 first_subresource,
XgSubresourceTiling* tilings) = 0;
virtual HRESULT GetTextureViewDescriptor(UINT32 plane, void* descriptor) = 0;
virtual bool IsTiledResource() = 0;
virtual HRESULT GetSwizzlePatternInfo(UINT32 plane, void* info) = 0;
};
class LayoutComputer final : public XGTextureAddressComputer {
public:
static HRESULT create(const XgResourceDesc& desc, XGTextureAddressComputer** out);
ULONG AddRef() override { return ++refs_; }
ULONG Release() override {
const ULONG left = --refs_;
if (!left) delete this;
return left;
}
HRESULT GetResourceLayout(XgResourceLayout* layout) override {
if (!layout) return E_POINTER;
*layout = layout_;
return S_OK;
}
UINT64 GetResourceSizeBytes() override { return layout_.SizeBytes; }
UINT64 GetResourceBaseAlignmentBytes() override { return layout_.BaseAlignmentBytes; }
UINT64 GetMipLevelOffsetBytes(UINT32 plane, UINT32 mip) override {
if (plane >= layout_.Planes || mip >= layout_.MipLevels) return 0;
return layout_.Plane[plane].MipLayout[mip].OffsetBytes;
}
UINT64 GetTexelElementOffsetBytes(UINT32 plane, UINT32 mip, UINT64 x, UINT32 y, UINT32 z, UINT32 sample,
UINT32* bit_position) override {
if (bit_position) *bit_position = 0;
if (plane >= layout_.Planes || mip >= layout_.MipLevels) return 0;
const XgPlaneLayout& p = layout_.Plane[plane];
const XgMipLevelLayout& m = p.MipLayout[mip];
const uint64_t ex = x / block_, ey = y / block_;
if (swizzled_) {
if (ex >= sw_.tile_x || ey >= sw_.tile_y) return 0;
return m.OffsetBytes + element_offset(static_cast<uint32_t>(ex), static_cast<uint32_t>(ey));
}
return m.OffsetBytes + z * m.Slice2DSizeBytes + ey * m.PitchBytes +
(ex * m.SampleCount + sample) * p.BytesPerElement;
}
HRESULT GetTexelCoordinate(UINT64 offset, UINT32* plane, UINT32* mip, UINT64* x, UINT32* y, UINT32* z,
UINT32* sample) override {
for (UINT32 pi = 0; pi < layout_.Planes; ++pi) {
const XgPlaneLayout& p = layout_.Plane[pi];
for (UINT32 mi = 0; mi < layout_.MipLevels; ++mi) {
const XgMipLevelLayout& m = p.MipLayout[mi];
if (offset < m.OffsetBytes || offset >= m.OffsetBytes + m.SizeBytes) continue;
const uint64_t rel = offset - m.OffsetBytes;
if (swizzled_) {
const uint32_t in_tile = static_cast<uint32_t>(rel);
if (plane) *plane = pi;
if (mip) *mip = mi;
if (z) *z = 0;
if (y) *y = pext(in_tile, sw_.y_mask) * block_;
if (x) *x = static_cast<UINT64>(pext(in_tile, sw_.x_mask)) * block_;
if (sample) *sample = 0;
return S_OK;
}
const uint64_t in_slice = rel % m.Slice2DSizeBytes;
const uint64_t element = (in_slice % m.PitchBytes) / p.BytesPerElement;
if (plane) *plane = pi;
if (mip) *mip = mi;
if (z) *z = static_cast<UINT32>(rel / m.Slice2DSizeBytes);
if (y) *y = static_cast<UINT32>(in_slice / m.PitchBytes * block_);
if (x) *x = element / m.SampleCount * block_;
if (sample) *sample = static_cast<UINT32>(element % m.SampleCount);
return S_OK;
}
}
return E_INVALIDARG;
}
HRESULT CopyIntoSubresource(void* base, UINT32 plane, UINT32 subresource, const void* linear, UINT32 row_pitch,
UINT32 slice_pitch) override {
return copy(static_cast<uint8_t*>(base), plane, subresource, static_cast<const uint8_t*>(linear), row_pitch,
slice_pitch, true);
}
HRESULT CopyFromSubresource(void* linear, UINT32 plane, UINT32 subresource, UINT32, const void* base,
UINT32 row_pitch, UINT32 slice_pitch) override {
return copy(static_cast<uint8_t*>(const_cast<void*>(base)), plane, subresource, static_cast<uint8_t*>(linear),
row_pitch, slice_pitch, false);
}
HRESULT GetResourceTiling(UINT32* total_tiles, XgPackedMipDesc* packed, XgTileShape* shape, UINT32* count,
UINT32 first, XgSubresourceTiling* tilings) override {
// D3D12 standard 64 KB tiles (the public D3D12 tiled-resource rules): the tile shape follows
// the element size (256x256 one-byte elements down to 64x64 sixteen-byte ones, in blocks for
// block-compressed formats). Leading mips at least one tile wide and high are standard; the
// smaller rest are packed into a mip tail per array slice, as on the console, whose titles
// expect few standard mips. Tiles are numbered over the subresources in order (mip-major
// within a slice), each slice's packed tail after its standard mips.
// 3D resources use the D3D12 standard 3D tile shapes (64x32x32 one-byte elements down to
// 16x16x16 sixteen-byte ones), 1D textures a 64 KiB row of elements, buffers 64 KiB.
const uint32_t bpe = layout_.Plane[0].BytesPerElement;
const bool volume = layout_.Dimension == kDimTexture3D;
uint32_t tile_w = 128, tile_h = 128, tile_d = 1;
if (layout_.Dimension == kDimBuffer) {
tile_w = 65536;
tile_h = 1;
} else if (layout_.Dimension == kDimTexture1D) {
tile_w = 65536 / (bpe ? bpe : 1) * block_;
tile_h = 1;
} else if (volume) {
switch (bpe) {
case 1: tile_w = 64; tile_h = 32; tile_d = 32; break;
case 2: tile_w = 32; tile_h = 32; tile_d = 32; break;
case 4: tile_w = 32; tile_h = 32; tile_d = 16; break;
case 8: tile_w = 32; tile_h = 16; tile_d = 16; break;
case 16: tile_w = 16; tile_h = 16; tile_d = 16; break;
default: tile_w = 32; tile_h = 32; tile_d = 16; break;
}
tile_w *= block_;
tile_h *= block_;
} else {
switch (bpe) {
case 1: tile_w = 256; tile_h = 256; break;
case 2: tile_w = 256; tile_h = 128; break;
case 4: tile_w = 128; tile_h = 128; break;
case 8: tile_w = 128; tile_h = 64; break;
case 16: tile_w = 64; tile_h = 64; break;
default: break;
}
tile_w *= block_;
tile_h *= block_;
}
auto depth_of = [&](UINT32 m) { return volume ? layout_.Plane[0].MipLayout[m].DepthOrArraySize : 1u; };
const UINT32 mips = layout_.MipLevels;
UINT32 standard = 0;
while (standard < mips && layout_.Plane[0].MipLayout[standard].WidthPixels >= tile_w &&
layout_.Plane[0].MipLayout[standard].HeightPixels >= tile_h && depth_of(standard) >= tile_d) {
++standard;
}
uint64_t tail_bytes = 0;
for (UINT32 m = standard; m < mips; ++m) {
tail_bytes += volume ? layout_.Plane[0].MipLayout[m].SizeBytes : layout_.Plane[0].MipLayout[m].Slice2DSizeBytes;
}
const UINT32 tail_tiles = standard < mips ? static_cast<UINT32>((tail_bytes + kResourceAlign - 1) / kResourceAlign) : 0;
auto tiles_of = [&](UINT32 m) {
const XgMipLevelLayout& l = layout_.Plane[0].MipLayout[m];
return ((l.WidthPixels + tile_w - 1) / tile_w) * ((l.HeightPixels + tile_h - 1) / tile_h) *
((depth_of(m) + tile_d - 1) / tile_d);
};
UINT32 per_slice = tail_tiles;
for (UINT32 m = 0; m < standard; ++m) per_slice += tiles_of(m);
if (total_tiles) *total_tiles = per_slice * slices_;
UINT32 standard_tiles = 0;
for (UINT32 m = 0; m < standard; ++m) standard_tiles += tiles_of(m);
if (packed) {
*packed = {static_cast<UINT8>(standard), static_cast<UINT8>(mips - standard), tail_tiles,
standard < mips ? standard_tiles : 0};
}
if (shape) *shape = {tile_w, tile_h, tile_d};
if (count) {
const UINT32 total = mips * slices_;
UINT32 written = 0;
for (UINT32 i = first; i < total && written < *count && tilings; ++i, ++written) {
const UINT32 m = i % mips, slice = i / mips;
if (m >= standard) {
tilings[written] = {0, 0, 0, 0xFFFFFFFFu}; // packed: no tiling of its own
continue;
}
UINT32 start = slice * per_slice;
for (UINT32 k = 0; k < m; ++k) start += tiles_of(k);
const XgMipLevelLayout& l = layout_.Plane[0].MipLayout[m];
tilings[written] = {(l.WidthPixels + tile_w - 1) / tile_w,
static_cast<UINT16>((l.HeightPixels + tile_h - 1) / tile_h),
static_cast<UINT16>((depth_of(m) + tile_d - 1) / tile_d), start};
}
*count = written;
}
return S_OK;
}
HRESULT GetTextureViewDescriptor(UINT32, void*) override {
BX_STUB_LOG("xg_xs.dll", "XGTextureAddressComputer::GetTextureViewDescriptor");
return E_NOTIMPL;
}
bool IsTiledResource() override { return false; }
HRESULT GetSwizzlePatternInfo(UINT32, void*) override {
BX_STUB_LOG("xg_xs.dll", "XGTextureAddressComputer::GetSwizzlePatternInfo");
return E_NOTIMPL;
}
private:
HRESULT copy(uint8_t* tiled, UINT32 plane, UINT32 subresource, uint8_t* linear_rw, UINT32 row_pitch,
UINT32 slice_pitch, bool into) {
return copy(tiled, plane, subresource, static_cast<const uint8_t*>(linear_rw), row_pitch, slice_pitch, into,
linear_rw);
}
HRESULT copy(uint8_t* tiled, UINT32 plane, UINT32 subresource, const uint8_t* linear, UINT32 row_pitch,
UINT32 slice_pitch, bool into, uint8_t* linear_out = nullptr) {
if (!tiled || !linear || plane >= layout_.Planes) return E_INVALIDARG;
const UINT32 mip = subresource % layout_.MipLevels;
const UINT32 slice = subresource / layout_.MipLevels;
const XgPlaneLayout& p = layout_.Plane[plane];
const XgMipLevelLayout& m = p.MipLayout[mip];
const bool volume = layout_.Dimension == kDimTexture3D;
if (slice >= slices_) return E_INVALIDARG; // slices_ is 1 for a volume: its subresources are its mips
const UINT32 depth = volume ? m.DepthOrArraySize : 1;
if (swizzled_) { // one 2D tile, one mip, one slice: element by element
if (subresource != 0) return E_INVALIDARG;
for (UINT32 row = 0; row < m.HeightElements; ++row) {
for (UINT32 col = 0; col < m.WidthElements; ++col) {
uint8_t* t = tiled + m.OffsetBytes + element_offset(col, row);
const uint64_t lin = static_cast<uint64_t>(row) * row_pitch + static_cast<uint64_t>(col) * sw_.bytes;
if (into) std::memcpy(t, linear + lin, sw_.bytes);
else std::memcpy(linear_out + lin, t, sw_.bytes);
}
}
return S_OK;
}
const uint64_t row_bytes = static_cast<uint64_t>(m.WidthElements) * m.SampleCount * p.BytesPerElement;
for (UINT32 z = 0; z < depth; ++z) {
uint8_t* dst_slice = tiled + m.OffsetBytes + (volume ? z : slice) * m.Slice2DSizeBytes;
for (UINT32 row = 0; row < m.HeightElements; ++row) {
uint8_t* t = dst_slice + static_cast<uint64_t>(row) * m.PitchBytes;
const uint64_t lin = static_cast<uint64_t>(z) * slice_pitch + static_cast<uint64_t>(row) * row_pitch;
if (into) std::memcpy(t, linear + lin, row_bytes);
else std::memcpy(linear_out + lin, t, row_bytes);
}
}
return S_OK;
}
uint32_t element_offset(uint32_t ex, uint32_t ey) const { return pdep(ex, sw_.x_mask) | pdep(ey, sw_.y_mask); }
XgResourceLayout layout_{};
uint32_t block_ = 1;
uint32_t slices_ = 1;
bool swizzled_ = false; // SW_64KB_S, one tile (see Sw64kbS)
Sw64kbS sw_{};
std::atomic<ULONG> refs_{1};
};
HRESULT LayoutComputer::create(const XgResourceDesc& d, XGTextureAddressComputer** out) {
FormatInfo fi{1, 1, 0};
const bool buffer = d.Dimension == kDimBuffer;
if (!buffer && !format_info(d.Format, &fi)) {
log_rejected(&d, "format not in the BetterXen XG table");
return E_INVALIDARG;
}
if (d.Dimension < kDimBuffer || d.Dimension > kDimTexture3D || d.Width == 0) {
log_rejected(&d, "invalid description");
return E_INVALIDARG;
}
// The public D3D12 resource limits (D3D12_REQ_TEXTURE1D/2D_U_DIMENSION 16384,
// D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION 2048, D3D12_REQ_TEXTURE1D/2D_ARRAY_AXIS_DIMENSION
// 2048). Within them every pitch fits 32 bits and no size computation overflows. A buffer
// only needs its 64 KiB-aligned size to fit 64 bits.
{
const bool volume = d.Dimension == kDimTexture3D;
const uint64_t max_xy = volume ? 2048 : 16384;
const uint32_t height = d.Dimension == kDimTexture1D ? 1 : d.Height;
const bool too_big = buffer ? d.Width > UINT64_MAX - kResourceAlign
: d.Width > max_xy || height > max_xy || d.DepthOrArraySize > 2048;
if (too_big) {
log_rejected(&d, "dimension past the D3D12 resource limits");
return E_INVALIDARG;
}
}
auto* c = new (std::nothrow) LayoutComputer();
if (!c) return E_OUTOFMEMORY;
XgResourceLayout& L = c->layout_;
L.Dimension = d.Dimension;
L.BaseAlignmentBytes = d.Alignment > kResourceAlign ? d.Alignment : kResourceAlign;
if (buffer) {
L.MipLevels = 1;
L.Planes = 1;
XgPlaneLayout& p = L.Plane[0];
p.Usage = kPlaneDefault;
p.BytesPerElement = 1;
p.StandardMipCount = 1;
p.SizeBytes = p.SliceSizeBytes = d.Width;
p.BaseAlignmentBytes = L.BaseAlignmentBytes;
XgMipLevelLayout& m = p.MipLayout[0];
m.SizeBytes = m.Slice2DSizeBytes = d.Width;
m.PitchBytes = static_cast<UINT32>(d.Width > UINT32_MAX ? UINT32_MAX : d.Width);
m.WidthElements = m.WidthPixels = m.PitchPixels = m.PaddedWidthElements = m.PitchBytes;
m.HeightElements = m.HeightPixels = m.PaddedHeightElements = 1;
m.DepthOrArraySize = m.PaddedDepthOrArraySize = m.SampleCount = m.SliceDepthElements = 1;
m.AlignmentBytes = static_cast<UINT32>(kRowAlign);
L.SizeBytes = align_up(d.Width, kResourceAlign);
*out = c;
return S_OK;
}
const uint32_t height = d.Dimension == kDimTexture1D ? 1 : (d.Height ? d.Height : 1);
const uint32_t depth_or_array = d.DepthOrArraySize ? d.DepthOrArraySize : 1;
uint32_t full = 1;
for (uint64_t w = d.Width, h = height, z = d.Dimension == kDimTexture3D ? depth_or_array : 1; w > 1 || h > 1 || z > 1;
w >>= 1, h >>= 1, z >>= 1) {
++full;
}
uint32_t mips = d.MipLevels ? d.MipLevels : full;
if (mips > full) mips = full;
if (mips > kMaxMips) {
log_rejected(&d, "more than 15 mip levels");
delete c;
return E_INVALIDARG;
}
const uint32_t samples = d.SampleDesc.Count ? d.SampleDesc.Count : 1;
c->block_ = fi.block;
c->slices_ = d.Dimension == kDimTexture3D ? 1 : depth_or_array;
// Default, row-major and undefined-swizzle requests leave the choice to XG: BetterXen picks
// linear and reports it. A request for SW_64KB_S on one 2D tile gets that layout. Any other
// requested swizzle mode is laid out linearly and reported as LINEAR (titles do not expect
// XGCreateTextureComputer to fail for a mode they ask for); each such mode is logged once.
const uint32_t width_el = static_cast<uint32_t>((d.Width + fi.block - 1) / fi.block);
const uint32_t height_el = (height + fi.block - 1) / fi.block;
Sw64kbS sw{};
const bool requested = (d.Layout & kLayoutSwizzleFlag) && d.Layout != kLayoutSwizzleLinear;
const bool single_tile_s = d.Layout == (kLayoutSwizzleFlag | kSwizzleMode64KbS) && d.Dimension == kDimTexture2D &&
mips == 1 && depth_or_array == 1 && samples == 1 && !fi.stencil &&
sw64kb_s_params(fi.bytes, &sw) && width_el <= sw.tile_x && height_el <= sw.tile_y;
if (requested && !single_tile_s) log_linear_instead(&d);
if (single_tile_s) {
c->swizzled_ = true;
c->sw_ = sw;
L.MipLevels = 1;
L.Planes = 1;
L.BaseAlignmentBytes = d.Alignment > kTileBytes ? d.Alignment : kTileBytes;
XgPlaneLayout& p = L.Plane[0];
p.Usage = kPlaneDefault;
p.BytesPerElement = fi.bytes;
p.StandardMipCount = 1;
p.BaseAlignmentBytes = L.BaseAlignmentBytes;
p.SizeBytes = p.SliceSizeBytes = kTileBytes;
XgMipLevelLayout& m = p.MipLayout[0];
m.WidthPixels = static_cast<UINT32>(d.Width);
m.HeightPixels = height;
m.WidthElements = width_el;
m.HeightElements = height_el;
m.DepthOrArraySize = m.PaddedDepthOrArraySize = m.SampleCount = m.SliceDepthElements = 1;
m.PitchBytes = sw.tile_x * sw.bytes;
m.PitchPixels = sw.tile_x * fi.block;
m.PaddedWidthElements = sw.tile_x;
m.PaddedHeightElements = sw.tile_y;
m.AlignmentBytes = static_cast<UINT32>(kTileBytes);
m.SwizzleMode = kSwizzleMode64KbS;
m.SizeBytes = m.Slice2DSizeBytes = kTileBytes;
L.SizeBytes = kTileBytes;
*out = c;
return S_OK;
}
L.MipLevels = mips;
L.Planes = fi.stencil ? 2 : 1;
uint64_t cursor = 0;
for (uint32_t pi = 0; pi < L.Planes; ++pi) {
XgPlaneLayout& p = L.Plane[pi];
p.Usage = fi.stencil ? (pi == 0 ? kPlaneDepth : kPlaneStencil) : kPlaneDefault;
p.BytesPerElement = fi.stencil && pi == 1 ? 1 : fi.bytes;
p.StandardMipCount = mips;
p.MipTailMipCount = 0;
p.BaseAlignmentBytes = L.BaseAlignmentBytes;
cursor = align_up(cursor, kResourceAlign);
p.BaseOffsetBytes = cursor;
for (uint32_t mi = 0; mi < mips; ++mi) {
XgMipLevelLayout& m = p.MipLayout[mi];
m.WidthPixels = mip_extent(d.Width, mi);
m.HeightPixels = mip_extent(height, mi);
m.DepthOrArraySize = d.Dimension == kDimTexture3D ? mip_extent(depth_or_array, mi) : depth_or_array;
m.WidthElements = (m.WidthPixels + fi.block - 1) / fi.block;
m.HeightElements = (m.HeightPixels + fi.block - 1) / fi.block;
m.SampleCount = samples;
m.PitchBytes = static_cast<UINT32>(align_up(static_cast<uint64_t>(m.WidthElements) * samples * p.BytesPerElement, kRowAlign));
m.PitchPixels = m.PitchBytes / (p.BytesPerElement * samples) * fi.block;
m.PaddedWidthElements = m.PitchBytes / (p.BytesPerElement * samples);
m.PaddedHeightElements = m.HeightElements;
m.PaddedDepthOrArraySize = m.DepthOrArraySize;
m.SliceDepthElements = 1;
m.AlignmentBytes = static_cast<UINT32>(kMipAlign);
m.SwizzleMode = kSwizzleModeLinear;
m.Slice2DSizeBytes = static_cast<uint64_t>(m.PitchBytes) * m.HeightElements;
m.SizeBytes = m.Slice2DSizeBytes * m.DepthOrArraySize;
cursor = align_up(cursor, kMipAlign);
m.OffsetBytes = cursor;
cursor += m.SizeBytes;
}
p.SizeBytes = cursor - p.BaseOffsetBytes;
p.SliceSizeBytes = p.MipLayout[0].Slice2DSizeBytes;
}
L.SizeBytes = align_up(cursor, kResourceAlign);
*out = c;
return S_OK;
}
} // namespace
extern "C" {
__declspec(dllexport) HRESULT WINAPI XGCreateTextureComputer(const XgResourceDesc* desc, XGTextureAddressComputer** out) {
if (!desc || !out) return E_INVALIDARG;
*out = nullptr;
const HRESULT hr = LayoutComputer::create(*desc, out);
if (SUCCEEDED(hr)) {
static std::atomic<uint64_t> created{0};
const uint64_t n = ++created;
if ((n & (n - 1)) == 0) {
char detail[200];
std::snprintf(detail, sizeof(detail),
"BetterXen linear layout (not console tiling): dim=%u %llux%u x%u mips=%u format=%u layout=0x%x size=%llu; total created=%llu",
desc->Dimension, static_cast<unsigned long long>(desc->Width), desc->Height,
desc->DepthOrArraySize, desc->MipLevels, desc->Format, desc->Layout,
static_cast<unsigned long long>((*out)->GetResourceSizeBytes()), static_cast<unsigned long long>(n));
bx_log_emit(BX_LOG_INFO, "xg_xs", "texture_computer", detail);
}
}
return hr;
}
__declspec(dllexport) HRESULT WINAPI XGSuggestSwizzleMode(const XgResourceDesc* desc, uint32_t, uint32_t* layout) {
if (!desc || !layout) return E_INVALIDARG;
*layout = kLayoutSwizzleLinear; // this layer lays every texture out linearly
return S_OK;
}
} // extern "C"
File diff suppressed because it is too large. Load diff
+18 -9
View File
@@ -751,6 +751,12 @@ BX_HR(gs_files_folder_async, "IXGameSaveImpl2", 30, "XGameSaveFilesGetFolderWith
BX_HR(gs_files_folder_result, "IXGameSaveImpl2", 31, "XGameSaveFilesGetFolderWithUiResult")
BX_HR(gs_files_quota, "IXGameSaveImpl2", 32, "XGameSaveFilesGetRemainingQuota")
BX_HR(pk_create_monitor, "IXPackageImpl", 5, "XPackageCreateInstallationMonitor")
BX_VOID(pk_close_monitor, "IXPackageImpl", 6, "XPackageCloseInstallationMonitorHandle")
BX_VOID(pk_get_progress, "IXPackageImpl", 7, "XPackageGetInstallationProgress")
BX_BOOL(pk_update_monitor, "IXPackageImpl", 8, "XPackageUpdateInstallationMonitor")
BX_HR(pk_reg_progress, "IXPackageImpl", 9, "XPackageRegisterInstallationProgressChanged")
BX_BOOL(pk_unreg_progress, "IXPackageImpl", 10, "XPackageUnregisterInstallationProgressChanged")
BX_HR(pk_locale, "IXPackageImpl", 11, "XPackageGetUserLocale")
BX_HR(pk_find_chunk, "IXPackageImpl", 12, "XPackageFindChunkAvailability")
BX_HR(pk_enum_chunk, "IXPackageImpl", 13, "XPackageEnumerateChunkAvailability")
@@ -764,13 +770,16 @@ BX_HR(pk_unknown_20, "IXPackageImpl", 20, "unknown")
BX_HR(pk_unknown_21, "IXPackageImpl", 21, "unknown")
BX_BOOL(pk_unreg_installed, "IXPackageImpl", 22, "XPackageUnregisterPackageInstalled")
BX_HR(pk_unknown_27, "IXPackageImpl", 27, "unknown")
BX_HR(pk_enum_packages, "IXPackageImpl", 28, "XPackageEnumeratePackages")
BX_HR(pk_reg_installed, "IXPackageImpl", 29, "XPackageRegisterPackageInstalled")
BX_HR(pk_write_stats, "IXPackageImpl", 30, "XPackageGetWriteStats")
BX_HR(pk_unknown_31, "IXPackageImpl", 31, "unknown")
BX_HR(pk_uninstall_uwp, "IXPackageImpl", 32, "XPackageUninstallUWPInstance")
BX_HR(pk_enum_features, "IXPackageImpl", 33, "XPackageEnumerateFeatures")
BX_HR(pk_uninstall, "IXPackageImpl", 34, "XPackageUninstallPackage")
BX_HR(pk_enum_packages_2, "IXPackageImpl2", 35, "XPackageEnumeratePackages")
BX_HR(pk_reg_installed_2, "IXPackageImpl2", 36, "XPackageRegisterPackageInstalled")
BX_HR(pk_enum_packages_3, "IXPackageImpl3", 39, "XPackageEnumeratePackages")
BX_HR(pk_reg_installed_3, "IXPackageImpl3", 40, "XPackageRegisterPackageInstalled")
#undef BX_HR
#undef BX_VOID
@@ -818,12 +827,12 @@ const std::array<const void*, 42> kPackageVtbl = [] {
v[0] = reinterpret_cast<const void*>(&package_query_interface);
v[3] = reinterpret_cast<const void*>(&get_current_process_package_identifier);
v[4] = reinterpret_cast<const void*>(&is_packaged_process);
v[5] = reinterpret_cast<const void*>(&create_installation_monitor);
v[6] = reinterpret_cast<const void*>(&close_installation_monitor);
v[7] = reinterpret_cast<const void*>(&get_installation_progress);
v[8] = reinterpret_cast<const void*>(&update_installation_monitor);
v[9] = reinterpret_cast<const void*>(&register_installation_progress);
v[10] = reinterpret_cast<const void*>(&unregister_installation_progress);
v[5] = reinterpret_cast<const void*>(&pk_create_monitor);
v[6] = reinterpret_cast<const void*>(&pk_close_monitor);
v[7] = reinterpret_cast<const void*>(&pk_get_progress);
v[8] = reinterpret_cast<const void*>(&pk_update_monitor);
v[9] = reinterpret_cast<const void*>(&pk_reg_progress);
v[10] = reinterpret_cast<const void*>(&pk_unreg_progress);
v[11] = reinterpret_cast<const void*>(&pk_locale);
v[12] = reinterpret_cast<const void*>(&pk_find_chunk);
v[13] = reinterpret_cast<const void*>(&pk_enum_chunk);
@@ -841,18 +850,18 @@ const std::array<const void*, 42> kPackageVtbl = [] {
v[25] = reinterpret_cast<const void*>(&get_mount_path);
v[26] = reinterpret_cast<const void*>(&close_mount_handle);
v[27] = reinterpret_cast<const void*>(&pk_unknown_27);
v[28] = reinterpret_cast<const void*>(&enumerate_packages);
v[28] = reinterpret_cast<const void*>(&pk_enum_packages);
v[29] = reinterpret_cast<const void*>(&pk_reg_installed);
v[30] = reinterpret_cast<const void*>(&pk_write_stats);
v[31] = reinterpret_cast<const void*>(&pk_unknown_31);
v[32] = reinterpret_cast<const void*>(&pk_uninstall_uwp);
v[33] = reinterpret_cast<const void*>(&pk_enum_features);
v[34] = reinterpret_cast<const void*>(&pk_uninstall);
v[35] = reinterpret_cast<const void*>(&enumerate_packages);
v[35] = reinterpret_cast<const void*>(&pk_enum_packages_2);
v[36] = reinterpret_cast<const void*>(&pk_reg_installed_2);
v[37] = reinterpret_cast<const void*>(&mount_with_ui_async);
v[38] = reinterpret_cast<const void*>(&mount_with_ui_result);
v[39] = reinterpret_cast<const void*>(&enumerate_packages);
v[39] = reinterpret_cast<const void*>(&pk_enum_packages_3);
v[40] = reinterpret_cast<const void*>(&pk_reg_installed_3);
v[41] = reinterpret_cast<const void*>(&get_package_kind);
return v;
+1 -154
View File
@@ -22,18 +22,9 @@
* mounted; BetterXen allows the game's own package so titles can locate their files. Offline
* there is no license or parental-consent prompt, so the asynchronous form shows no UI; an
* identifier mismatch is reported as the operation's status (ERROR_NOT_FOUND).
* - The last XGameRuntimeUninitialize closes every mount handle and installation monitor.
* - Installation monitors (XPackageCreateInstallationMonitor and the functions taking its
* handle) accept only that identifier. The package is fully on local storage, so progress is
* {1, 1, 1, launchable, completed} and never changes: a registered progress callback is
* accepted, logged and never called. Handles share the mount table's lock and generation, so
* a closed or stale handle is rejected and closing twice is harmless.
* - XPackageEnumeratePackages reports this game for XPackageKind::Game in every scope (the
* documented ThisOnly output is the calling game; offline there are no related or publisher
* games), and no packages for Content or PublisherContent: none are installed offline.
* - The last XGameRuntimeUninitialize closes every mount handle.
* - An executable path of MAX_PATH or more fails with ERROR_FILENAME_EXCED_RANGE.
*/
#include "bx_log.h"
#include "runtime_internal.h"
#include "synthetic_keys.h"
@@ -46,7 +37,6 @@
#include <new>
#include <string>
#include <unordered_map>
#include <vector>
namespace bx::gdk {
namespace {
@@ -260,148 +250,6 @@ void WINAPI close_mount_handle(void*, void* handle) {
namespace {
struct Monitor {
uint32_t generation;
std::vector<uint64_t> tokens;
};
// Guarded by mount_mutex, like the mount handles. Tag 5 in bits 40-43 keeps these handles apart
// from mount handles (tag 4) and XGameSave handles.
std::unordered_map<void*, Monitor> monitors;
constexpr uintptr_t kMonitorTag = 5;
uint64_t token_counter = 0;
// Caller holds mount_mutex.
Monitor* find_monitor(void* handle, uint32_t generation) {
const auto found = monitors.find(handle);
if (found == monitors.end() || generation == 0 || found->second.generation != generation) return nullptr;
return &found->second;
}
} // namespace
HRESULT WINAPI create_installation_monitor(void*, const char* identifier, uint32_t, const void*, uint32_t, void*,
void** monitor) {
if (!monitor) return E_POINTER;
*monitor = nullptr;
if (!identifier) return E_INVALIDARG;
const auto generation = active_runtime_generation();
if (!generation) return kRuntimeNotInitialized;
bool match = false;
const auto hr = is_current_package(identifier, match);
if (FAILED(hr)) return hr;
if (!match) return kNotFound;
try {
std::lock_guard lock(mount_mutex);
++handle_counter;
void* handle = reinterpret_cast<void*>(kMonitorTag << 40 | (handle_counter & 0xFFFFFFFFFu) << 4);
monitors.emplace(handle, Monitor{generation, {}});
*monitor = handle;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XPackageCreateInstallationMonitor",
"monitor for the running package: fully installed, progress never changes (offline)");
return S_OK;
}
void WINAPI close_installation_monitor(void*, void* monitor) {
std::lock_guard lock(mount_mutex);
monitors.erase(monitor); // an unknown or already closed handle is ignored
}
void WINAPI get_installation_progress(void*, void* monitor, XPackageInstallationProgress* progress) {
if (!progress) return;
const auto generation = active_runtime_generation();
std::lock_guard lock(mount_mutex);
*progress = find_monitor(monitor, generation) ? XPackageInstallationProgress{1, 1, 1, true, true}
: XPackageInstallationProgress{};
}
bool WINAPI update_installation_monitor(void*, void*) {
return false; // progress never changes offline
}
HRESULT WINAPI register_installation_progress(void*, void* monitor, void*, void* callback, uint64_t* token) {
if (!token) return E_POINTER;
*token = 0;
if (!callback) return E_INVALIDARG;
const auto generation = active_runtime_generation();
try {
std::lock_guard lock(mount_mutex);
Monitor* open = find_monitor(monitor, generation);
if (!open) return stale_handle_error(generation);
*token = ++token_counter;
open->tokens.push_back(*token);
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
char detail[128];
std::snprintf(detail, sizeof(detail), "token=%llu accepted; offline progress never changes, so the callback is never called",
static_cast<unsigned long long>(*token));
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XPackageRegisterInstallationProgressChanged", detail);
return S_OK;
}
bool WINAPI unregister_installation_progress(void*, void* monitor, uint64_t token, bool) {
const auto generation = active_runtime_generation();
std::lock_guard lock(mount_mutex);
Monitor* open = find_monitor(monitor, generation);
if (!open) return false;
for (auto it = open->tokens.begin(); it != open->tokens.end(); ++it) {
if (*it == token) {
open->tokens.erase(it);
return true;
}
}
return false;
}
namespace {
struct XVersionValue {
uint16_t major, minor, build, revision;
};
struct XPackageDetails {
const char* packageIdentifier;
XVersionValue version;
uint32_t kind;
const char* displayName;
const char* description;
const char* publisher;
const char* storeId;
bool installing;
uint32_t index;
uint32_t count;
bool ageRestricted;
const char* titleId;
};
using EnumerationCallback = bool(CALLBACK*)(void* context, const XPackageDetails* details);
constexpr uint32_t kKindGame = 0, kScopeThisPublisher = 2;
} // namespace
HRESULT WINAPI enumerate_packages(void*, uint32_t kind, uint32_t scope, void* context, void* callback) {
if (!callback) return E_INVALIDARG;
if (!active_runtime_generation()) return kRuntimeNotInitialized;
if (kind > 2 || scope > kScopeThisPublisher) return E_INVALIDARG;
char detail[128];
if (kind != kKindGame) {
std::snprintf(detail, sizeof(detail), "kind=%u scope=%u: no content packages installed (offline)", kind, scope);
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XPackageEnumeratePackages", detail);
return S_OK;
}
char id[kIdBytes];
const auto hr = current_identifier(id);
if (FAILED(hr)) return hr;
const XPackageDetails details{id, {}, kKindGame, "", "", "", "", false, 0, 1, false, ""};
std::snprintf(detail, sizeof(detail), "kind=%u scope=%u: reported the running game only (offline)", kind, scope);
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XPackageEnumeratePackages", detail);
reinterpret_cast<EnumerationCallback>(callback)(context, &details);
return S_OK;
}
namespace {
// --- COM object ---
HRESULT WINAPI query_interface(void* self, const GUID* iid, void** out) {
@@ -453,7 +301,6 @@ const void* const package_object = &kObject;
void release_package_state() {
std::lock_guard lock(mount_mutex);
mounts.clear();
monitors.clear();
}
} // namespace bx::gdk
-19
View File
@@ -106,23 +106,4 @@ HRESULT WINAPI get_mount_path_size(void* self, void* handle, size_t* size);
HRESULT WINAPI get_mount_path(void* self, void* handle, size_t size, char* path);
void WINAPI close_mount_handle(void* self, void* handle);
// Installation monitors and enumeration (package.cpp), served on IXPackageImpl slots 5-10 and
// the XPackageEnumeratePackages slots. Layouts follow the documented XPackage structures.
struct XPackageInstallationProgress {
uint64_t totalBytes;
uint64_t installedBytes;
uint64_t launchBytes;
bool launchable;
bool completed;
};
HRESULT WINAPI create_installation_monitor(void* self, const char* identifier, uint32_t selector_count,
const void* selectors, uint32_t interval_ms, void* queue, void** monitor);
void WINAPI close_installation_monitor(void* self, void* monitor);
void WINAPI get_installation_progress(void* self, void* monitor, XPackageInstallationProgress* progress);
bool WINAPI update_installation_monitor(void* self, void* monitor);
HRESULT WINAPI register_installation_progress(void* self, void* monitor, void* context, void* callback,
uint64_t* token);
bool WINAPI unregister_installation_progress(void* self, void* monitor, uint64_t token, bool wait);
HRESULT WINAPI enumerate_packages(void* self, uint32_t kind, uint32_t scope, void* context, void* callback);
} // namespace bx::gdk
@@ -1,2 +0,0 @@
add_executable(test_acphal_default_heap main.cpp)
target_link_libraries(test_acphal_default_heap PRIVATE acphal kernel32)
@@ -1,90 +0,0 @@
// AcpHal's default APU heap, in a fresh process: a title that allocates shape contexts before
// any ApuCreateHeap gets a 64 MB default heap (BetterXen's stand-in for the console's default
// non-cached APU heap). test_audio_input creates its own heap first, so this branch needs a
// process of its own.
//
// Expected values come from this file: 64 MiB is the documented-in-CHANGELOG default, so shape
// contexts of exactly 64 MiB must fit and 64 MiB + 64 bytes must not.
#include <windows.h>
#include <cstdint>
#include <cstdio>
#include <string>
extern "C" {
HRESULT WINAPI AcpHalAllocateShapeContexts(void*);
HRESULT WINAPI AcpHalReleaseShapeContexts(void);
HRESULT WINAPI ApuCreateHeap(uint32_t, uint32_t);
void* WINAPI ApuMapApuAddress(uint32_t);
}
namespace {
int g_failures = 0;
void check(bool ok, const char* what) {
if (!ok) {
++g_failures;
std::printf("FAIL: test_acphal_default_heap: %s\n", what);
}
}
struct ShapeContexts {
uint32_t counts[6]; // SRC, EQ/Comp, Filt/Vol, DMA, XMA, PCM
void* arrays[6];
uint32_t apu[6];
};
static_assert(sizeof(ShapeContexts) == 96, "SHAPE_CONTEXTS");
constexpr uint32_t kXmaBytes = 64;
constexpr uint32_t kDefaultHeap = 64u << 20;
std::string read_log() {
char path[MAX_PATH];
std::string text;
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n == 0 || n >= sizeof(path)) return text;
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
if (f == INVALID_HANDLE_VALUE) return text;
char buf[65536];
DWORD got = 0;
while (ReadFile(f, buf, sizeof(buf), &got, nullptr) && got) text.append(buf, got);
CloseHandle(f);
return text;
}
size_t count_of(const std::string& text, const char* needle) {
size_t n = 0;
for (size_t at = text.find(needle); at != std::string::npos; at = text.find(needle, at + 1)) ++n;
return n;
}
} // namespace
int main() {
char probe[8];
if (GetEnvironmentVariableA("BX_LOG_FILE", probe, sizeof(probe)) == 0) {
std::printf("FAIL: test_acphal_default_heap: BX_LOG_FILE must be set (run under bx-cli run --log)\n");
return 1;
}
// No ApuCreateHeap. One XMA element more than 64 MiB holds does not fit the default heap...
ShapeContexts too_big{};
too_big.counts[4] = kDefaultHeap / kXmaBytes + 1;
check(AcpHalAllocateShapeContexts(&too_big) == E_OUTOFMEMORY, "64 MiB + 64 bytes exceeds the default heap");
// ...and exactly 64 MiB does (the failed attempt above left nothing allocated).
ShapeContexts exact{};
exact.counts[4] = kDefaultHeap / kXmaBytes;
check(AcpHalAllocateShapeContexts(&exact) == S_OK && exact.arrays[4] && exact.apu[4],
"exactly 64 MiB of shape contexts fits the default heap");
check(exact.apu[4] && ApuMapApuAddress(exact.apu[4]) == exact.arrays[4], "the shape array is an APU heap allocation");
// The default heap is the heap: a later ApuCreateHeap finds one already created.
check(ApuCreateHeap(64, 64) == HRESULT_FROM_WIN32(ERROR_BUSY), "ApuCreateHeap after the default heap reports busy");
check(AcpHalReleaseShapeContexts() == S_OK, "release");
const std::string log = read_log();
check(count_of(log, "\"event\":\"apu_default_heap\"") == 1, "the default heap is created once and logged");
if (g_failures) {
std::printf("FAIL: test_acphal_default_heap (%d failed)\n", g_failures);
return 1;
}
std::printf("PASS: test_acphal_default_heap\n");
return 0;
}
+12 -51
View File
@@ -1,7 +1,6 @@
#include <windows.h>
#include <unknwn.h>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
@@ -133,27 +132,11 @@ int main() {
}
const uint64_t log_start = log_file_size(dispatcher_log_path);
// IAcpHal is not a COM interface (authorized GDK documentation): slots Connect(numCommands,
// numMessages), Disconnect(), SubmitCommand(command, id, audioFrame, data, notification),
// PopMessage(message), GetNumMessages() and Release(). BetterXen has no ACP: commands are
// accepted and no message arrives.
void* object = nullptr;
CHECK(AcpHalCreate(&object) == S_OK && object);
void* hal = object;
const void* const* acp = *static_cast<const void* const* const*>(hal);
using ConnectFn = HRESULT(WINAPI*)(void*, uint32_t, uint32_t);
using DisconnectFn = HRESULT(WINAPI*)(void*);
using SubmitFn = HRESULT(WINAPI*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t);
using PopFn = bool(WINAPI*)(void*, void*);
using CountFn = uint32_t(WINAPI*)(void*);
using ReleaseFn = void(WINAPI*)(void*);
CHECK(reinterpret_cast<SubmitFn>(acp[2])(hal, 2, 1, 0, nullptr, 0) == E_UNEXPECTED); // before Connect
CHECK(reinterpret_cast<ConnectFn>(acp[0])(hal, 0x1000, 0x1000) == S_OK);
CHECK(FAILED(reinterpret_cast<ConnectFn>(acp[0])(hal, 0x1000, 0x1000)));
CHECK(reinterpret_cast<SubmitFn>(acp[2])(hal, 2, 1, 0, nullptr, 0) == S_OK);
unsigned char message[64]{};
CHECK(!reinterpret_cast<PopFn>(acp[3])(hal, message) && reinterpret_cast<CountFn>(acp[4])(hal) == 0);
CHECK(reinterpret_cast<DisconnectFn>(acp[1])(hal) == S_OK);
auto* hal = static_cast<IUnknown*>(object);
CHECK(hal->QueryInterface(IID_IUnknown, &object) == S_OK && object == hal);
CHECK(hal->Release() == 1);
void *va = nullptr, *second = nullptr;
uint32_t base = 0, other = 0;
CHECK(ApuAlloc(&va, &base, 64, 64) == E_OUTOFMEMORY && !va && !base);
@@ -182,42 +165,20 @@ int main() {
CHECK(ApuFree(tail) == E_INVALIDARG);
CHECK(ApuFree(va) == S_OK && !ApuMapApuAddress(base) && !ApuMapVirtualAddress(va));
CHECK(ApuFree(va) == E_INVALIDARG && ApuMapApuAddress(other) == second);
CHECK(ApuFree(second) == S_OK);
reinterpret_cast<ReleaseFn>(acp[5])(hal);
CHECK(ApuFree(second) == S_OK && hal->Release() == 0);
// AcpHalAllocateShapeContexts(SHAPE_CONTEXTS*) (authorized GDK documentation): six counts in
// (SRC, EQ/Comp, Filt/Vol, DMA, XMA, PCM), six CPU pointers and six APU addresses out, the
// arrays from the APU heap (XMA elements are 64 bytes). A second allocation without a release
// fails with ACP_E_ALREADY_ALLOCATED (0x8AC80001).
struct ShapeContexts {
uint32_t counts[6];
void* arrays[6];
uint32_t apu[6];
};
static_assert(sizeof(ShapeContexts) == 96 && offsetof(ShapeContexts, arrays) == 24 &&
offsetof(ShapeContexts, apu) == 72,
"SHAPE_CONTEXTS layout");
constexpr HRESULT kAlreadyAllocated = static_cast<HRESULT>(0x8AC80001);
CHECK(AcpHalAllocateShapeContexts(nullptr) == E_INVALIDARG);
CHECK(AcpHalReleaseShapeContexts() == S_OK); // nothing allocated
ShapeContexts shape{};
shape.counts[4] = 2; // two XMA contexts: 128 bytes, the whole 64 + 64 heap
CHECK(AcpHalAllocateShapeContexts(&shape) == S_OK);
CHECK(shape.arrays[4] && shape.apu[4] && ApuMapApuAddress(shape.apu[4]) == shape.arrays[4]);
CHECK(!shape.arrays[0] && !shape.arrays[5] && !shape.apu[0]);
CHECK(static_cast<const unsigned char*>(shape.arrays[4])[127] == 0); // zero-filled
ShapeContexts again{};
again.counts[4] = 1;
CHECK(AcpHalAllocateShapeContexts(&again) == kAlreadyAllocated);
CHECK(AcpHalReleaseShapeContexts() == S_OK && !ApuMapApuAddress(shape.apu[4]));
CHECK(AcpHalAllocateShapeContexts(&again) == S_OK && again.arrays[4]);
CHECK(AcpHalReleaseShapeContexts() == S_OK);
// AcpHal shape-context stubs: NDA-gated contract, so BetterXen returns
// E_NOTIMPL and logs the symbol. Null and sentinel pointers must not crash.
CHECK(AcpHalAllocateShapeContexts(nullptr) == E_NOTIMPL);
CHECK(AcpHalAllocateShapeContexts(reinterpret_cast<void*>(uintptr_t{0xDEADBEEF})) == E_NOTIMPL);
CHECK(AcpHalReleaseShapeContexts() == E_NOTIMPL);
CHECK(AcpHalReleaseShapeContexts() == E_NOTIMPL);
char log_path[MAX_PATH];
DWORD log_len = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
if (log_len > 0 && log_len < sizeof(log_path)) {
CHECK(file_contains(log_path, log_start, "\"event\":\"shape_contexts_allocated\"", "xma=2"));
CHECK(file_contains(log_path, log_start, "\"event\":\"connect\"", "commands=4096"));
CHECK(file_contains(log_path, log_start, "\"event\":\"unimpl_api\"", "AcpHal.dll!AcpHalAllocateShapeContexts"));
CHECK(file_contains(log_path, log_start, "\"event\":\"unimpl_api\"", "AcpHal.dll!AcpHalReleaseShapeContexts"));
} else {
// Unreachable under `bx-cli run --log`. A SKIP that still exits 0 would
// contradict the exit-77 protocol, so a missing log is a failure.
@@ -25,8 +25,7 @@
*
* Function prototypes below mirror the in-tree shim sources and abi/defs; this
* fixture deliberately invents no console structure layouts. The xg_xs
* descriptor and method order are the documented XG contract recorded in
* shims/xg_xs/xg_xbox.cpp (derived facts, no header text).
* descriptor and vtable are BetterXen's own, from shims/xg_xs/xg_texture.h.
*/
#include <windows.h>
#include <unknwn.h>
@@ -34,7 +33,6 @@
#include <immintrin.h>
#include <cstdarg>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
@@ -43,6 +41,7 @@
#include "bx_config.h"
#include "bx_log.h"
#include "bx_xmem_internal.h"
#include "xg_texture.h"
#define BX_IMPORT __declspec(dllimport)
@@ -98,24 +97,7 @@ BX_IMPORT HRESULT WINAPI XDspDisconnect(void* handle);
/* GameInput.dll (ordinal 1) */
BX_IMPORT HRESULT WINAPI GameInputCreate(void** out_game_input);
/* xg_xs.dll: the documented XG_RESOURCE_DESC (56 bytes) and XGTextureAddressComputer, whose
methods are AddRef, Release, GetResourceLayout, GetResourceSizeBytes,
GetResourceBaseAlignmentBytes, GetMipLevelOffsetBytes, ... (no IUnknown QueryInterface). */
struct XgResourceDesc {
uint32_t Dimension;
UINT64 Alignment;
UINT64 Width;
UINT Height;
UINT16 DepthOrArraySize;
UINT16 MipLevels;
uint32_t Format;
UINT SampleCount;
UINT SampleQuality;
uint32_t Layout;
uint32_t MiscFlags;
};
BX_IMPORT HRESULT WINAPI XGCreateTextureComputer(const XgResourceDesc* desc, void** computer);
BX_IMPORT HRESULT WINAPI XGSuggestSwizzleMode(const XgResourceDesc* desc, uint32_t flags, uint32_t* layout);
/* xg_xs.dll is declared by "xg_texture.h". */
/* d3d12_xs.dll (D3D12SerializeVersionedRootSignature is declared by <d3d12.h>) */
BX_IMPORT HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv);
@@ -672,34 +654,25 @@ void stage_acphal_heap() {
/* ---- Stage 13: xg_xs ---------------------------------------------------------------------- */
static_assert(sizeof(XgResourceDesc) == 56 && offsetof(XgResourceDesc, Alignment) == 8, "XG_RESOURCE_DESC");
constexpr uint32_t kXgTexture2D = 3; // XG_RESOURCE_DIMENSION_TEXTURE2D
constexpr uint32_t kXgLayoutSwizzleLinear = 0x100; // XG_TEXTURE_LAYOUT_SWIZZLE_MODE_LINEAR
enum : int { kXgAddRef = 0, kXgRelease = 1, kXgSizeBytes = 3, kXgBaseAlignment = 4, kXgMipOffset = 5 };
template <typename Fn>
Fn xg_slot(void* computer, int slot) {
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(computer))[slot]);
}
/*
* 100x50 R8G8B8A8 with two mips under BetterXen's linear rule (shims/xg_xs/xg_xbox.cpp: rows aligned
* to 256 bytes, mips to 512, the resource to 64 KiB). By hand:
* mip 0: 100 * 4 = 400 bytes per row, pitch 512; 50 rows = 25600 bytes at offset 0.
* mip 1: offset 25600 (already 512-aligned); 50 * 4 = 200 bytes per row, pitch 256;
* 25 rows = 6400 bytes, ending at 32000.
* resource: 32000 rounded up to 64 KiB = 65536, base alignment 65536.
* 100x50 R8G8B8A8 with two mips, so both public D3D12 alignments matter. By hand:
* mip 0: 100 * 4 = 400 bytes per row, pitch 512 (256-byte pitch alignment);
* ends at 49 * 512 + 400 = 25488.
* mip 1: starts at the next 512 boundary, 25600; 50 * 4 = 200 bytes per row,
* pitch 256; ends at 25600 + 24 * 256 + 200 = 31944.
* total: 31944 rounded up to 512 = 32256.
*/
void* stage_xg_texture_computer() {
begin_stage("xg_xs_texture_computer");
XgResourceDesc desc = {};
desc.Dimension = kXgTexture2D;
desc.Width = 100;
desc.Height = 50;
desc.DepthOrArraySize = 1;
desc.MipLevels = 2;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleCount = 1;
bx_xg_resource_desc desc = {};
desc.dimension = BX_XG_DIMENSION_TEXTURE2D;
desc.width = 100;
desc.height = 50;
desc.depth_or_array_size = 1;
desc.mip_levels = 2;
desc.format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.sample_desc.count = 1;
desc.layout = BX_XG_LAYOUT_LINEAR;
void* object = reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD));
HRESULT hr = XGCreateTextureComputer(&desc, &object);
@@ -708,41 +681,41 @@ void* stage_xg_texture_computer() {
static_cast<unsigned long>(hr), object);
return nullptr;
}
using U64Fn = UINT64(WINAPI*)(void*);
using MipFn = UINT64(WINAPI*)(void*, UINT32, UINT32);
const UINT64 size = xg_slot<U64Fn>(object, kXgSizeBytes)(object);
const UINT64 alignment = xg_slot<U64Fn>(object, kXgBaseAlignment)(object);
const UINT64 mip0 = xg_slot<MipFn>(object, kXgMipOffset)(object, 0, 0);
const UINT64 mip1 = xg_slot<MipFn>(object, kXgMipOffset)(object, 0, 1);
if (size == 65536 && alignment == 65536 && mip0 == 0 && mip1 == 25600) {
auto* computer = static_cast<bx_xg_texture_computer*>(object);
bx_xg_placed_footprint mips[2] = {};
uint32_t rows[2] = {};
uint64_t row_bytes[2] = {};
uint64_t total = 0;
hr = computer->lpVtbl->GetResourceLayout(computer, 0, 2, 0, mips, rows, row_bytes, &total);
auto shape_is = [](const bx_xg_subresource_footprint& f, uint32_t width, uint32_t height, uint32_t pitch) {
return f.format == DXGI_FORMAT_R8G8B8A8_UNORM && f.width == width && f.height == height && f.depth == 1 &&
f.row_pitch == pitch;
};
const bool mip0 = mips[0].offset == 0 && shape_is(mips[0].footprint, 100, 50, 512) && mips[0].copy_end == 25488 &&
rows[0] == 50 && row_bytes[0] == 400;
const bool mip1 = mips[1].offset == 25600 && shape_is(mips[1].footprint, 50, 25, 256) && mips[1].copy_end == 31944 &&
rows[1] == 25 && row_bytes[1] == 200;
if (hr == S_OK && mip0 && mip1 && total == 32256) {
checkpoint("xg_xs_texture_computer", Status::Pass,
"100x50 RGBA8 two-mip linear layout matches hand-computed size, alignment and mip offsets");
"100x50 RGBA8 two-mip linear footprints and 32256 total bytes match hand-computed values");
} else {
checkpoint("xg_xs_texture_computer", Status::Fail, "size=%llu alignment=%llu mip0=%llu mip1=%llu",
static_cast<unsigned long long>(size), static_cast<unsigned long long>(alignment),
static_cast<unsigned long long>(mip0), static_cast<unsigned long long>(mip1));
checkpoint("xg_xs_texture_computer", Status::Fail,
"GetResourceLayout hr=0x%08lx mip0_ok=%d mip1_ok=%d total=%llu",
static_cast<unsigned long>(hr), mip0, mip1, static_cast<unsigned long long>(total));
}
return object;
}
void* stage_xg_xs() {
begin_stage("xg_xs_swizzle_mode");
XgResourceDesc desc = {};
desc.Dimension = kXgTexture2D;
desc.Width = 256;
desc.Height = 256;
desc.DepthOrArraySize = 1;
desc.MipLevels = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleCount = 1;
uint32_t mode_a = 0, mode_b = 0;
const HRESULT hr_a = XGSuggestSwizzleMode(&desc, 0, &mode_a);
const HRESULT hr_b = XGSuggestSwizzleMode(&desc, 0, &mode_b);
if (hr_a == S_OK && hr_b == S_OK && mode_a == kXgLayoutSwizzleLinear && mode_b == mode_a) {
checkpoint("xg_xs_swizzle_mode", Status::Pass, "XGSuggestSwizzleMode suggests linear and is deterministic (layout=0x%x)", mode_a);
/* D3D12_RESOURCE_DIMENSION_TEXTURE2D / DXGI_FORMAT_R8G8B8A8_UNORM, 256x256, 1 mip, 1 sample. */
uint32_t mode_a = XGSuggestSwizzleMode(D3D12_RESOURCE_DIMENSION_TEXTURE2D, DXGI_FORMAT_R8G8B8A8_UNORM, 256, 256, 1, 1, 1, 0);
uint32_t mode_b = XGSuggestSwizzleMode(D3D12_RESOURCE_DIMENSION_TEXTURE2D, DXGI_FORMAT_R8G8B8A8_UNORM, 256, 256, 1, 1, 1, 0);
if (mode_a == BX_XG_LAYOUT_LINEAR && mode_b == mode_a) {
checkpoint("xg_xs_swizzle_mode", Status::Pass, "XGSuggestSwizzleMode suggests linear and is deterministic (mode=%u)", mode_a);
} else {
checkpoint("xg_xs_swizzle_mode", Status::Fail, "XGSuggestSwizzleMode hr=0x%08lx/0x%08lx layout=0x%x then 0x%x, expected linear",
static_cast<unsigned long>(hr_a), static_cast<unsigned long>(hr_b), mode_a, mode_b);
checkpoint("xg_xs_swizzle_mode", Status::Fail, "XGSuggestSwizzleMode returned %u then %u, expected linear", mode_a, mode_b);
}
return stage_xg_texture_computer();
@@ -902,7 +875,8 @@ int main(int argc, char** argv) {
/* The fixture holds the only reference, so this Release must return 0. */
ULONG texture_refs = 0;
if (texture_computer) {
texture_refs = xg_slot<ULONG(WINAPI*)(void*)>(texture_computer, kXgRelease)(texture_computer);
auto* computer = static_cast<bx_xg_texture_computer*>(texture_computer);
texture_refs = computer->lpVtbl->Release(computer);
}
release_com(game_input);
bool dsp_closed = true;
@@ -911,8 +885,7 @@ int main(int argc, char** argv) {
dsp_closed = deact_hr == S_OK && XDspDisconnect(dsp) == S_OK;
}
bool apu_closed = apu_conn ? XApuDisconnect(apu_conn) == S_OK : true;
/* IAcpHal is not COM: Release is its sixth slot and returns nothing. */
if (acp_hal) reinterpret_cast<void(WINAPI*)(void*)>((*static_cast<void* const* const*>(acp_hal))[5])(acp_hal);
release_com(acp_hal);
release_com(dstorage_factory);
if (psm_constrained_reg) UnregisterAppConstrainedChangeNotification(psm_constrained_reg);
if (psm_state_reg) UnregisterAppStateChangeNotification(psm_state_reg);
+8 -216
View File
@@ -129,28 +129,6 @@ bool file_contains(const char* path, const char* needle) {
} // namespace
/* "tile %04d ok;" for i % 97, i = 0..399 (5200 bytes), zlib-compressed at level 9 by CPython's
* zlib module; a dynamic-Huffman deflate block. */
constexpr size_t kZlibPlainSize = 5200;
const uint8_t kZlibStream[] = {
0x78, 0xda, 0xed, 0xd4, 0x2b, 0x4e, 0x05, 0x40, 0x10, 0x44, 0xd1, 0xad, 0xbc, 0x25, 0xd0, 0xf3,
0xe9, 0x9e, 0x09, 0xeb, 0x41, 0x10, 0x48, 0x30, 0x6f, 0xff, 0x01, 0x81, 0x38, 0x68, 0x6c, 0x97,
0x2b, 0x77, 0xd4, 0x7d, 0xbe, 0x7f, 0xbe, 0x3d, 0x5e, 0x7e, 0xf6, 0xf8, 0xfa, 0x78, 0x7d, 0xfe,
0x9e, 0xf0, 0x0c, 0xcf, 0xf4, 0x2c, 0xcf, 0xf6, 0xa4, 0xa7, 0x3c, 0xc7, 0x73, 0x39, 0xa1, 0x20,
0x14, 0x84, 0x82, 0x50, 0x10, 0x0a, 0x42, 0x41, 0x28, 0x08, 0x05, 0xa1, 0x20, 0x14, 0x0c, 0x05,
0x43, 0xc1, 0x50, 0x30, 0x14, 0x0c, 0x05, 0x43, 0xc1, 0x50, 0x30, 0x14, 0x0c, 0x05, 0x43, 0xc1,
0x54, 0x30, 0x15, 0x4c, 0x05, 0x53, 0xc1, 0x54, 0x30, 0x15, 0x4c, 0x05, 0x53, 0xc1, 0x54, 0x30,
0x15, 0x2c, 0x05, 0x4b, 0xc1, 0x52, 0xb0, 0x14, 0x2c, 0x05, 0x4b, 0xc1, 0x52, 0xb0, 0x14, 0x2c,
0x05, 0x4b, 0xc1, 0x56, 0xb0, 0x15, 0x6c, 0x05, 0x5b, 0xc1, 0x56, 0xb0, 0x15, 0x6c, 0x05, 0x5b,
0xc1, 0x56, 0xb0, 0x15, 0xa4, 0x82, 0x54, 0x90, 0x0a, 0x52, 0x41, 0x2a, 0x48, 0x05, 0xa9, 0x20,
0x15, 0xa4, 0x82, 0x54, 0x50, 0x0a, 0x4a, 0x41, 0x29, 0x28, 0x05, 0xa5, 0xa0, 0x14, 0x94, 0x82,
0x52, 0x50, 0x0a, 0x4a, 0xc1, 0x51, 0x70, 0x14, 0x1c, 0x05, 0x47, 0xc1, 0x51, 0x70, 0x14, 0x1c,
0x05, 0x47, 0xc1, 0x51, 0x70, 0x14, 0x5c, 0x05, 0x57, 0xc1, 0x55, 0x70, 0x15, 0x5c, 0x05, 0x57,
0xc1, 0xfd, 0x53, 0xa4, 0x8e, 0x5d, 0xc7, 0xae, 0x63, 0xd7, 0xb1, 0xeb, 0xd8, 0x75, 0xec, 0x3a,
0x76, 0x1d, 0xbb, 0x8e, 0x5d, 0xc7, 0xae, 0x63, 0xd7, 0xb1, 0xeb, 0xd8, 0x75, 0xec, 0x3a, 0x76,
0xff, 0x8a, 0xdd, 0x37, 0x11, 0xdb, 0xee, 0x70,
};
int main() {
/* BX_LOG_FILE must name the log before launch (bx-cli run --log): the log checks
* below are the only evidence for the BX_VTABLE_STUB_LOG records. */
@@ -255,71 +233,16 @@ int main() {
static_cast<unsigned long>(status->GetHResult(0)));
check(std::memcmp(dest, payload + 64, sizeof(dest)) == 0, "file read bytes must match payload[64..192]");
/* DSTORAGE_REQUEST_OPTIONS.BcpackMode (bits 1-4) has no decoder: E_NOTIMPL and a stub log. */
XboxRequest bcpack_req = req;
bcpack_req.options = 1ull << 1;
file_q->EnqueueRequest(&bcpack_req);
/* Compressed request must fail with E_NOTIMPL and log stub. */
XboxRequest comp_req = req;
comp_req.options = 1;
file_q->EnqueueRequest(&comp_req);
file_q->EnqueueStatus(status, 1);
file_q->Submit();
check(wait_complete(status, 1), "BCPack request status must complete");
check(status->GetHResult(1) == E_NOTIMPL, "BCPack request must report E_NOTIMPL (hr=0x%08lx)",
check(wait_complete(status, 1), "compressed request status must complete");
check(status->GetHResult(1) == E_NOTIMPL, "compressed request must report E_NOTIMPL (hr=0x%08lx)",
static_cast<unsigned long>(status->GetHResult(1)));
/* A zlib request must be smaller than its output (GDK DirectStorage compression rules). */
XboxRequest same_size = req;
same_size.options = 1;
file_q->EnqueueRequest(&same_size);
file_q->EnqueueStatus(status, 1);
file_q->Submit();
check(wait_complete(status, 1), "same-size zlib request status must complete");
check(status->GetHResult(1) == E_DSTORAGE_INVALID_DESTINATION_SIZE,
"a zlib request whose source is not smaller than its destination must be rejected (hr=0x%08lx)",
static_cast<unsigned long>(status->GetHResult(1)));
/* A zlib request whose source is a file, at a non-zero offset (how titles stream packed
* data): the stream is read from the file and inflated into the destination. */
WCHAR zlib_file[MAX_PATH] = {};
check(GetTempFileNameW(temp_dir, L"bxz", 0, zlib_file) != 0, "GetTempFileNameW (zlib) must succeed");
HANDLE zraw = CreateFileW(zlib_file, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
check(zraw != INVALID_HANDLE_VALUE, "CreateFileW for the zlib payload must succeed");
if (zraw != INVALID_HANDLE_VALUE) {
uint8_t prefix[100];
std::memset(prefix, 0xCC, sizeof(prefix));
DWORD written = 0;
check(WriteFile(zraw, prefix, sizeof(prefix), &written, nullptr) && written == sizeof(prefix) &&
WriteFile(zraw, kZlibStream, sizeof(kZlibStream), &written, nullptr) &&
written == sizeof(kZlibStream),
"WriteFile must write the zlib payload");
CloseHandle(zraw);
}
IXboxDStorageFile* zfile = nullptr;
hr = factory->OpenFile(zlib_file, kXboxFileIid, reinterpret_cast<void**>(&zfile));
check(hr == S_OK && zfile, "OpenFile(zlib payload) must succeed (hr=0x%08lx)", static_cast<unsigned long>(hr));
if (zfile) {
static char expected_text[kZlibPlainSize + 1];
for (int i = 0, at = 0; i < 400; ++i) {
at += std::snprintf(expected_text + at, sizeof(expected_text) - at, "tile %04d ok;", i % 97);
}
static uint8_t file_inflated[kZlibPlainSize];
XboxRequest fz{};
fz.options = 1; // ZlibDecompress, file source
fz.destination = file_inflated;
fz.destination_size = kZlibPlainSize;
fz.source_ptr = zfile;
fz.file_offset = 100;
fz.source_size = sizeof(kZlibStream);
file_q->EnqueueRequest(&fz);
file_q->EnqueueStatus(status, 1);
file_q->Submit();
check(wait_complete(status, 1) && status->GetHResult(1) == S_OK,
"file-source zlib request must succeed (hr=0x%08lx)", static_cast<unsigned long>(status->GetHResult(1)));
check(std::memcmp(file_inflated, expected_text, kZlibPlainSize) == 0,
"file-source zlib request must inflate to the expected text");
zfile->Close();
zfile->Release();
}
DeleteFileW(zlib_file);
/* The Xbox output layout is unverified. A PC-sized test buffer
* detects any accidental writes while keeping the test memory safe. */
DSTORAGE_ERROR_RECORD record;
@@ -361,136 +284,6 @@ int main() {
static_cast<unsigned long>(status->GetHResult(0)));
check(std::memcmp(dest, payload + 32, sizeof(dest)) == 0, "memory copy bytes must match payload[32..96]");
/* ZlibDecompress (bit 0): an RFC 1950 stream produced by an independent zlib encoder,
* checked against plain text this test builds itself. */
static char expected[kZlibPlainSize + 1];
for (int i = 0, at = 0; i < 400; ++i) at += std::snprintf(expected + at, sizeof(expected) - at, "tile %04d ok;", i % 97);
static uint8_t inflated[kZlibPlainSize];
XboxRequest zreq{};
zreq.options = 0x400000ull | 1ull;
zreq.destination = inflated;
zreq.destination_size = kZlibPlainSize;
zreq.source_ptr = const_cast<uint8_t*>(kZlibStream);
zreq.source_size = sizeof(kZlibStream);
mem_q->EnqueueRequest(&zreq);
mem_q->EnqueueStatus(status, 1);
mem_q->Submit();
check(wait_complete(status, 1) && status->GetHResult(1) == S_OK, "zlib request must succeed (hr=0x%08lx)",
static_cast<unsigned long>(status->GetHResult(1)));
check(std::memcmp(inflated, expected, kZlibPlainSize) == 0, "zlib request must inflate to the expected text");
/* DSTORAGE_QUEUE_OPTIONS.AutoSubmitDisabled (flags bit 0, authorized GDK documentation):
* enqueued work waits for Submit. Without it the queue submits by itself once half full
* (public DirectStorage behaviour). Observed through the destination bytes. */
auto copied = [&](const uint8_t* dst, DWORD wait_ms) {
for (DWORD waited = 0;; waited += 10) {
if (std::memcmp(dst, payload + 32, 16) == 0) return true;
if (waited >= wait_ms) return false;
Sleep(10);
}
};
for (const UINT64 flags : {UINT64{1}, UINT64{0}}) {
XboxQueueDesc qd{};
qd.source_type = 1;
qd.capacity = 4;
qd.priority = 1;
qd.name = flags ? "xbox_held_queue" : "xbox_auto_queue";
qd.flags = flags;
IXboxDStorageQueue* q = nullptr;
check(factory->CreateQueueX(&qd, kXboxQueueIid, reinterpret_cast<void**>(&q)) == S_OK && q,
"CreateQueueX(capacity 4, flags %llu) must succeed", static_cast<unsigned long long>(flags));
if (!q) continue;
static uint8_t held_dst[2][16];
std::memset(held_dst, 0, sizeof(held_dst));
for (auto& dst : held_dst) {
XboxRequest r{};
r.options = 0x400000ull;
r.destination = dst;
r.destination_size = sizeof(dst);
r.source_ptr = payload + 32;
r.source_size = sizeof(dst);
q->EnqueueRequest(&r);
}
if (flags) {
check(!copied(held_dst[1], 300), "AutoSubmitDisabled: two of four slots filled must not run before Submit");
q->Submit();
}
check(copied(held_dst[0], 5000) && copied(held_dst[1], 5000),
flags ? "AutoSubmitDisabled: requests must run after Submit"
: "without AutoSubmitDisabled a half-full queue must submit by itself");
q->Close();
q->Release();
}
/* A full AutoSubmitDisabled queue stalls the enqueuer until Submit is called on another
* thread; it must not submit by itself (documented DSTORAGE_QUEUE_OPTIONS behaviour). A
* capacity-4 queue holds 3 requests (one slot stays free, as for the public queues). A
* worker enqueues 5: the fourth waits, and no destination changes until this thread calls
* Submit. */
{
XboxQueueDesc qd{};
qd.source_type = 1;
qd.capacity = 4;
qd.priority = 1;
qd.name = "xbox_full_held_queue";
qd.flags = 1;
IXboxDStorageQueue* q = nullptr;
check(factory->CreateQueueX(&qd, kXboxQueueIid, reinterpret_cast<void**>(&q)) == S_OK && q,
"CreateQueueX(capacity 4, AutoSubmitDisabled) must succeed");
if (q) {
static uint8_t full_dst[5][16];
std::memset(full_dst, 0, sizeof(full_dst));
struct Job {
IXboxDStorageQueue* q;
const uint8_t* src;
volatile LONG enqueued;
} job{q, payload + 32, 0};
auto worker = [](void* arg) -> DWORD {
auto* j = static_cast<Job*>(arg);
for (auto& dst : full_dst) {
XboxRequest r{};
r.options = 0x400000ull;
r.destination = dst;
r.destination_size = sizeof(dst);
r.source_ptr = const_cast<uint8_t*>(j->src);
r.source_size = sizeof(dst);
j->q->EnqueueRequest(&r);
InterlockedIncrement(&j->enqueued);
}
return 0;
};
HANDLE thread = CreateThread(nullptr, 0, worker, &job, 0, nullptr);
Sleep(500);
bool untouched = true;
for (auto& dst : full_dst) untouched = untouched && !copied(dst, 0);
check(untouched, "a full AutoSubmitDisabled queue must not run anything before Submit");
check(job.enqueued == 3, "the enqueue past capacity must wait for Submit (enqueued=%ld)",
static_cast<long>(job.enqueued));
q->Submit(); // runs the three queued requests, freeing slots for the last two
check(thread && WaitForSingleObject(thread, 5000) == WAIT_OBJECT_0,
"Submit from another thread must release the waiting enqueue");
q->Submit(); // the last two requests
bool all = true;
for (auto& dst : full_dst) all = all && copied(dst, 5000);
check(all, "all five requests must run after Submit");
if (thread) CloseHandle(thread);
q->Close();
q->Release();
}
}
/* A corrupted stream fails with the DirectStorage decompression error, not silently. */
static uint8_t corrupted[sizeof(kZlibStream)];
std::memcpy(corrupted, kZlibStream, sizeof(corrupted));
corrupted[sizeof(corrupted) - 1] ^= 0xFF; // the Adler-32 trailer
zreq.source_ptr = corrupted;
mem_q->EnqueueRequest(&zreq);
mem_q->EnqueueStatus(status, 1);
mem_q->Submit();
check(wait_complete(status, 1) && status->GetHResult(1) == E_DSTORAGE_DECOMPRESSION_ERROR,
"a corrupted zlib stream must report E_DSTORAGE_DECOMPRESSION_ERROR (hr=0x%08lx)",
static_cast<unsigned long>(status->GetHResult(1)));
/* A rejected null fence still signals the queue's error event. */
mem_q->EnqueueSignal(nullptr, 1);
mem_q->Submit();
@@ -573,9 +366,8 @@ int main() {
"log must record that Xbox SetStagingBufferSize has no effect");
check(file_contains(log_path, "dstorage_queue_closed"),
"log must record the request enqueued after Close as dropped");
check(file_contains(log_path, "IDStorageQueueX[3]::EnqueueRequest_bcpack"),
"log must record the BCPack request stub");
check(file_contains(log_path, "dstorage_zlib_failed"), "log must record the corrupted zlib stream");
check(file_contains(log_path, "IDStorageQueueX[3]::EnqueueRequest_compressed"),
"log must record compressed request stub");
check(file_contains(log_path, "IDStorageQueueX[10]::RetrieveErrorRecord"),
"log must record the unimplemented Xbox error-record output");
const auto check_rejection = [&](const char* method, HRESULT hr) {
@@ -1,2 +0,0 @@
add_executable(test_xg_xbox main.cpp)
target_link_libraries(test_xg_xbox PRIVATE kernel32)
-468
View File
@@ -1,468 +0,0 @@
// Conformance test for the XG contract titles call (XGCreateTextureComputer / XGSuggestSwizzleMode
// with XG_RESOURCE_DESC and the 14-method XGTextureAddressComputer). Structure layouts, enum values
// and the method order are derived facts recorded in shims/xg_xs/xg_xbox.cpp; no header text.
//
// Expected values are computed here, not by xg_xs.dll:
// - Linear layouts follow BetterXen's documented rule (rows aligned to 256 bytes, mips to 512, the
// resource and each plane to 64 KiB), worked out by hand below.
// - SW_64KB_S at 4 bytes per element is checked against Microsoft's public D3D12 standard-swizzle
// definition, offset = pdep(x * 4, 0xAA8F) | pdep(y, 0x5570), an independent source from the
// AddrLib tables the shim uses. The 8-byte row has only the AddrLib source, so it is checked for
// the properties every tile pattern must have (a bijection of aligned slots inside 64 KiB).
#include <windows.h>
#include <dxgiformat.h>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <vector>
static int g_checks = 0;
static int g_failures = 0;
static void check(bool ok, const char* what) {
++g_checks;
if (!ok) {
std::printf("FAIL: test_xg_xbox: %s\n", what);
++g_failures;
}
}
struct XgResourceDesc {
uint32_t Dimension;
UINT64 Alignment;
UINT64 Width;
UINT Height;
UINT16 DepthOrArraySize;
UINT16 MipLevels;
uint32_t Format;
UINT SampleCount;
UINT SampleQuality;
uint32_t Layout;
uint32_t MiscFlags;
};
struct XgMipLevelLayout {
UINT64 SizeBytes;
UINT64 OffsetBytes;
UINT64 Slice2DSizeBytes;
UINT32 PitchPixels;
UINT32 PitchBytes;
UINT32 AlignmentBytes;
UINT32 PaddedWidthElements;
UINT32 PaddedHeightElements;
UINT32 PaddedDepthOrArraySize;
UINT32 WidthElements;
UINT32 HeightElements;
UINT32 WidthPixels;
UINT32 HeightPixels;
UINT32 DepthOrArraySize;
UINT32 SampleCount;
uint32_t SwizzleMode;
UINT64 BankRotationAddressBitMask;
UINT64 BankRotationBytesPerSlice;
UINT32 SliceDepthElements;
UINT32 IsMipTail;
UINT32 MipTailOffsets;
};
struct XgPlaneLayout {
uint32_t Usage;
UINT64 SizeBytes;
UINT64 SliceSizeBytes;
UINT64 BaseOffsetBytes;
UINT64 BaseAlignmentBytes;
UINT32 BytesPerElement;
UINT32 StandardMipCount;
UINT32 MipTailMipCount;
XgMipLevelLayout MipLayout[15];
};
struct XgResourceLayout {
UINT64 SizeBytes;
UINT64 BaseAlignmentBytes;
UINT32 MipLevels;
UINT32 Planes;
XgPlaneLayout Plane[4];
uint32_t Dimension;
};
static_assert(sizeof(XgResourceDesc) == 56 && offsetof(XgResourceDesc, Alignment) == 8, "XG_RESOURCE_DESC");
static_assert(sizeof(XgMipLevelLayout) == 112, "XG_MIPLEVEL_LAYOUT");
static_assert(sizeof(XgPlaneLayout) == 1736, "XG_PLANE_LAYOUT");
static_assert(sizeof(XgResourceLayout) == 6976, "XG_RESOURCE_LAYOUT");
struct XgPackedMipDesc {
UINT8 NumStandardMips;
UINT8 NumPackedMips;
UINT32 NumTilesForPackedMips;
UINT32 StartTileIndexInOverallResource;
};
struct XgTileShape {
UINT32 Width, Height, Depth;
};
struct XgSubresourceTiling {
UINT32 WidthInTiles;
UINT16 HeightInTiles;
UINT16 DepthInTiles;
UINT32 StartTileIndexInOverallResource;
};
static_assert(sizeof(XgPackedMipDesc) == 12 && sizeof(XgSubresourceTiling) == 12, "tiling structures");
// The interface the DLL implements. It is declared, like the structures it uses, outside the anonymous namespace: with internal
// linkage and no derived class in this file, GCC may treat calls through it as unreachable.
class Computer {
public:
virtual ULONG AddRef() = 0;
virtual ULONG Release() = 0;
virtual HRESULT GetResourceLayout(XgResourceLayout*) = 0;
virtual UINT64 GetResourceSizeBytes() = 0;
virtual UINT64 GetResourceBaseAlignmentBytes() = 0;
virtual UINT64 GetMipLevelOffsetBytes(UINT32 plane, UINT32 mip) = 0;
virtual UINT64 GetTexelElementOffsetBytes(UINT32 plane, UINT32 mip, UINT64 x, UINT32 y, UINT32 z, UINT32 sample,
UINT32* bit) = 0;
virtual HRESULT GetTexelCoordinate(UINT64 offset, UINT32* plane, UINT32* mip, UINT64* x, UINT32* y, UINT32* z,
UINT32* sample) = 0;
virtual HRESULT CopyIntoSubresource(void* base, UINT32 plane, UINT32 sub, const void* linear, UINT32 row_pitch,
UINT32 slice_pitch) = 0;
virtual HRESULT CopyFromSubresource(void* linear, UINT32 plane, UINT32 sub, UINT32 sample, const void* base,
UINT32 row_pitch, UINT32 slice_pitch) = 0;
virtual HRESULT GetResourceTiling(UINT32*, XgPackedMipDesc*, XgTileShape*, UINT32*, UINT32, XgSubresourceTiling*) = 0;
virtual HRESULT GetTextureViewDescriptor(UINT32, void*) = 0;
virtual bool IsTiledResource() = 0;
virtual HRESULT GetSwizzlePatternInfo(UINT32, void*) = 0;
};
namespace {
using CreateFn = HRESULT(WINAPI*)(const XgResourceDesc*, Computer**);
using SuggestFn = HRESULT(WINAPI*)(const XgResourceDesc*, uint32_t, uint32_t*);
CreateFn g_create = nullptr;
constexpr uint32_t kTexture2D = 3, kBuffer = 1;
constexpr uint32_t kLayoutLinear = 0x100, kLayout64KbS = 0x109, kLayout64KbD = 0x10a;
XgResourceDesc tex2d(uint32_t format, uint64_t w, uint32_t h, uint16_t mips, uint32_t layout) {
XgResourceDesc d{};
d.Dimension = kTexture2D;
d.Width = w;
d.Height = h;
d.DepthOrArraySize = 1;
d.MipLevels = mips;
d.Format = format;
d.SampleCount = 1;
d.Layout = layout;
return d;
}
uint32_t pdep(uint32_t value, uint32_t mask) {
uint32_t out = 0;
for (uint32_t bit = 1; mask; bit <<= 1) {
const uint32_t lowest = mask & (0u - mask);
if (value & bit) out |= lowest;
mask ^= lowest;
}
return out;
}
void test_linear_mips() {
const auto d = tex2d(DXGI_FORMAT_R8G8B8A8_UNORM, 256, 128, 3, kLayoutLinear);
Computer* c = nullptr;
check(g_create(&d, &c) == S_OK && c, "linear RGBA8 created");
if (!c) return;
XgResourceLayout L{};
check(c->GetResourceLayout(&L) == S_OK, "linear layout");
const auto& m = L.Plane[0].MipLayout;
// mip0 1024-byte rows x 128; mip1 512 x 64 at 131072; mip2 256 x 32 at 163840; end 172032.
check(L.MipLevels == 3 && L.Planes == 1, "linear mip and plane counts");
check(m[0].PitchBytes == 1024 && m[0].OffsetBytes == 0 && m[0].SizeBytes == 131072, "mip0");
check(m[1].PitchBytes == 512 && m[1].OffsetBytes == 131072 && m[1].SizeBytes == 32768, "mip1");
check(m[2].PitchBytes == 256 && m[2].OffsetBytes == 163840 && m[2].SizeBytes == 8192, "mip2");
check(m[0].SwizzleMode == 0 && m[2].SwizzleMode == 0, "linear swizzle mode");
check(c->GetResourceSizeBytes() == 196608 && L.SizeBytes == 196608, "linear size rounded to 64 KiB");
check(c->GetMipLevelOffsetBytes(0, 2) == 163840, "mip offset");
check(c->GetTexelElementOffsetBytes(0, 1, 5, 3, 0, 0, nullptr) == 131072 + 3 * 512 + 5 * 4, "linear texel offset");
UINT32 plane = 9, mip = 9, y = 0, z = 9, sample = 9;
UINT64 x = 0;
check(c->GetTexelCoordinate(131072 + 3 * 512 + 5 * 4, &plane, &mip, &x, &y, &z, &sample) == S_OK && plane == 0 &&
mip == 1 && x == 5 && y == 3 && z == 0 && sample == 0,
"linear coordinate inverse");
std::vector<uint32_t> src(256 * 128), back(256 * 128);
for (uint32_t i = 0; i < src.size(); ++i) src[i] = i * 2654435761u;
std::vector<uint8_t> mem(c->GetResourceSizeBytes());
check(c->CopyIntoSubresource(mem.data(), 0, 0, src.data(), 1024, 1024 * 128) == S_OK, "linear copy into");
check(std::memcmp(mem.data() + 7 * 1024, &src[7 * 256], 1024) == 0, "linear copy places row 7");
check(c->CopyFromSubresource(back.data(), 0, 0, 0, mem.data(), 1024, 1024 * 128) == S_OK && src == back,
"linear copy round trip");
c->Release();
}
void test_depth_stencil_bc_buffer() {
auto d = tex2d(DXGI_FORMAT_D24_UNORM_S8_UINT, 64, 64, 1, 0);
Computer* c = nullptr;
check(g_create(&d, &c) == S_OK && c, "D24S8 created");
if (c) {
XgResourceLayout L{};
c->GetResourceLayout(&L);
// Depth: 4-byte elements, 256-byte rows, 16 KiB. Stencil: 1-byte elements in its own 64 KiB-aligned plane.
check(L.Planes == 2 && L.Plane[0].BytesPerElement == 4 && L.Plane[1].BytesPerElement == 1, "depth/stencil planes");
check(L.Plane[0].Usage == 7 && L.Plane[1].Usage == 8, "plane usages depth=7 stencil=8");
check(L.Plane[1].BaseOffsetBytes == 65536 && L.Plane[1].MipLayout[0].OffsetBytes == 65536, "stencil plane offset");
check(L.SizeBytes == 131072, "depth/stencil size");
c->Release();
}
d = tex2d(DXGI_FORMAT_BC1_UNORM, 64, 64, 1, kLayoutLinear);
c = nullptr;
check(g_create(&d, &c) == S_OK && c, "BC1 created");
if (c) {
// 16x16 blocks of 8 bytes: 128-byte rows padded to 256. Texel (8, 4) is block (2, 1).
check(c->GetTexelElementOffsetBytes(0, 0, 8, 4, 0, 0, nullptr) == 256 + 16, "BC1 texel offset");
c->Release();
}
XgResourceDesc b{};
b.Dimension = kBuffer;
b.Width = 1000;
b.SampleCount = 1;
c = nullptr;
check(g_create(&b, &c) == S_OK && c && c->GetResourceSizeBytes() == 65536, "buffer rounded to 64 KiB");
if (c) c->Release();
}
void test_64kb_s_32bpp() {
const auto d = tex2d(DXGI_FORMAT_R8G8B8A8_UNORM, 128, 128, 1, kLayout64KbS);
Computer* c = nullptr;
check(g_create(&d, &c) == S_OK && c, "64KB_S RGBA8 one tile created");
if (!c) return;
XgResourceLayout L{};
c->GetResourceLayout(&L);
check(L.Plane[0].MipLayout[0].SwizzleMode == 9, "64KB_S reported as swizzle mode 9");
check(c->GetResourceSizeBytes() == 65536 && c->GetResourceBaseAlignmentBytes() >= 65536, "64KB_S one tile");
bool all = true, inverse = true;
for (uint32_t y = 0; y < 128; ++y) {
for (uint32_t x = 0; x < 128; ++x) {
const uint64_t want = pdep(x * 4, 0xAA8F) | pdep(y, 0x5570);
if (c->GetTexelElementOffsetBytes(0, 0, x, y, 0, 0, nullptr) != want) all = false;
UINT64 gx = 0;
UINT32 gy = 0;
if (c->GetTexelCoordinate(want, nullptr, nullptr, &gx, &gy, nullptr, nullptr) != S_OK || gx != x || gy != y) {
inverse = false;
}
}
}
check(all, "64KB_S 32bpp offsets equal the D3D12 standard swizzle");
check(inverse, "64KB_S coordinate inverse");
std::vector<uint32_t> src(128 * 128), back(128 * 128);
for (uint32_t y = 0; y < 128; ++y)
for (uint32_t x = 0; x < 128; ++x) src[y * 128 + x] = y << 16 | x;
std::vector<uint8_t> tile(65536);
check(c->CopyIntoSubresource(tile.data(), 0, 0, src.data(), 512, 512 * 128) == S_OK, "64KB_S copy into");
uint32_t at = 0;
std::memcpy(&at, tile.data() + (pdep(37 * 4, 0xAA8F) | pdep(91, 0x5570)), 4);
check(at == (91u << 16 | 37u), "64KB_S copy places texel (37, 91)");
check(c->CopyFromSubresource(back.data(), 0, 0, 0, tile.data(), 512, 512 * 128) == S_OK && src == back,
"64KB_S copy round trip");
c->Release();
}
void test_64kb_s_bc1() {
// 512x256 texels = 128x64 blocks of 8 bytes: exactly one tile.
const auto d = tex2d(DXGI_FORMAT_BC1_UNORM, 512, 256, 1, kLayout64KbS);
Computer* c = nullptr;
check(g_create(&d, &c) == S_OK && c, "64KB_S BC1 one tile created");
if (!c) return;
std::vector<bool> used(65536 / 8, false);
bool ok = true;
for (uint32_t by = 0; by < 64; ++by) {
for (uint32_t bx = 0; bx < 128; ++bx) {
const uint64_t off = c->GetTexelElementOffsetBytes(0, 0, bx * 4, by * 4, 0, 0, nullptr);
if (off >= 65536 || off % 8 || used[off / 8]) ok = false;
else used[off / 8] = true;
}
}
check(ok, "64KB_S BC1 offsets are a bijection of aligned 8-byte slots in the tile");
// A BC block is one element: all 16 texels of a block share its byte offset.
bool shared = true;
for (uint32_t b = 0; b < 4; ++b) {
const uint32_t bx = 17 * b + 3, by = 11 * b + 5;
const uint64_t base = c->GetTexelElementOffsetBytes(0, 0, bx * 4, by * 4, 0, 0, nullptr);
for (uint32_t t = 0; t < 16; ++t) {
if (c->GetTexelElementOffsetBytes(0, 0, bx * 4 + t % 4, by * 4 + t / 4, 0, 0, nullptr) != base) shared = false;
}
}
check(shared, "64KB_S BC1 texels of one block share the block's offset");
c->Release();
}
void test_64kb_s_128bpp() {
// 64x64 elements of 16 bytes: exactly one tile.
const auto d = tex2d(DXGI_FORMAT_R32G32B32A32_FLOAT, 64, 64, 1, kLayout64KbS);
Computer* c = nullptr;
check(g_create(&d, &c) == S_OK && c, "64KB_S 128bpp one tile created");
if (!c) return;
std::vector<bool> used(65536 / 16, false);
bool ok = true;
for (uint32_t y = 0; y < 64; ++y) {
for (uint32_t x = 0; x < 64; ++x) {
const uint64_t off = c->GetTexelElementOffsetBytes(0, 0, x, y, 0, 0, nullptr);
if (off >= 65536 || off % 16 || used[off / 16]) ok = false;
else used[off / 16] = true;
}
}
check(ok, "64KB_S 128bpp offsets are a bijection of aligned 16-byte slots in the tile");
c->Release();
}
// A requested mode this layer does not implement: created, laid out and reported as LINEAR.
bool linear_fallback(const XgResourceDesc& d) {
Computer* c = nullptr;
if (g_create(&d, &c) != S_OK || !c) return false;
XgResourceLayout L{};
const bool ok = c->GetResourceLayout(&L) == S_OK && L.Plane[0].MipLayout[0].SwizzleMode == 0;
c->Release();
return ok;
}
void test_refusals_and_suggest(SuggestFn suggest) {
Computer* c = nullptr;
auto d = tex2d(DXGI_FORMAT_R8G8B8A8_UNORM, 256, 256, 1, kLayout64KbS);
check(linear_fallback(d), "64KB_S beyond one tile falls back to a reported LINEAR layout");
d = tex2d(DXGI_FORMAT_R8G8B8A8_UNORM, 64, 64, 2, kLayout64KbS);
check(linear_fallback(d), "64KB_S with two mips falls back to a reported LINEAR layout");
d = tex2d(DXGI_FORMAT_R8G8B8A8_UNORM, 64, 64, 1, kLayout64KbD);
check(linear_fallback(d), "64KB_D falls back to a reported LINEAR layout (logged)");
d = tex2d(DXGI_FORMAT_R8G8B8A8_UNORM, 64, 64, 1, 2); // 64 KB, undefined swizzle: XG chooses
check(g_create(&d, &c) == S_OK && c, "undefined-swizzle request accepted");
if (c) {
XgResourceLayout L{};
c->GetResourceLayout(&L);
check(L.Plane[0].MipLayout[0].SwizzleMode == 0, "undefined-swizzle request laid out linearly");
c->Release();
c = nullptr;
}
check(g_create(nullptr, &c) == E_INVALIDARG && g_create(&d, nullptr) == E_INVALIDARG, "null arguments");
uint32_t layout = 0;
check(suggest && suggest(&d, 0, &layout) == S_OK && layout == kLayoutLinear, "suggested layout is linear");
}
} // namespace
// GetResourceTiling against the public D3D12 standard tile shapes, with BetterXen's linear mip
// sizes for the packed tail. All expected numbers are worked out here by hand.
bool tiling_is(const XgSubresourceTiling& t, UINT32 w, UINT16 h, UINT16 d, UINT32 start) {
return t.WidthInTiles == w && t.HeightInTiles == h && t.DepthInTiles == d && t.StartTileIndexInOverallResource == start;
}
void test_tiling_limits_and_methods() {
// 2D RGBA8 1024x1024, 11 mips, 2 slices: 128x128 tiles. Mips 0-3 are standard
// (8x8 + 4x4 + 2x2 + 1x1 = 85 tiles); mips 4-10 pack into one 64 KiB tile per slice
// (pitches 256 bytes: 16384 + 8192 + 4096 + 2048 + 1024 + 512 + 256 = 32512 bytes).
auto d = tex2d(DXGI_FORMAT_R8G8B8A8_UNORM, 1024, 1024, 11, kLayoutLinear);
d.DepthOrArraySize = 2;
Computer* c = nullptr;
check(g_create(&d, &c) == S_OK && c, "2D array for tiling created");
if (c) {
UINT32 total = 0, count = 22;
XgPackedMipDesc packed{};
XgTileShape shape{};
XgSubresourceTiling t[22]{};
check(c->GetResourceTiling(&total, &packed, &shape, &count, 0, t) == S_OK, "GetResourceTiling 2D");
check(total == 172 && count == 22, "2D: 86 tiles per slice, 172 in all, 22 subresources");
check(shape.Width == 128 && shape.Height == 128 && shape.Depth == 1, "2D RGBA8 tile shape 128x128x1");
check(packed.NumStandardMips == 4 && packed.NumPackedMips == 7 && packed.NumTilesForPackedMips == 1 &&
packed.StartTileIndexInOverallResource == 85,
"2D packed mips: 4 standard, 7 packed into 1 tile starting at 85");
check(tiling_is(t[0], 8, 8, 1, 0) && tiling_is(t[1], 4, 4, 1, 64) && tiling_is(t[2], 2, 2, 1, 80) &&
tiling_is(t[3], 1, 1, 1, 84),
"2D standard mip tilings of slice 0");
check(tiling_is(t[4], 0, 0, 0, 0xFFFFFFFFu) && tiling_is(t[10], 0, 0, 0, 0xFFFFFFFFu),
"2D packed mips have no tiling of their own");
check(tiling_is(t[11], 8, 8, 1, 86) && tiling_is(t[14], 1, 1, 1, 170), "2D slice 1 starts after slice 0's 86 tiles");
check(c->AddRef() == 2 && c->Release() == 1, "AddRef and Release count references");
check(!c->IsTiledResource(), "a linear layout is not a tiled resource");
unsigned char scratch[256]{};
check(c->GetTextureViewDescriptor(0, scratch) == E_NOTIMPL && c->GetSwizzlePatternInfo(0, scratch) == E_NOTIMPL,
"unimplemented methods report E_NOTIMPL (and are logged)");
c->Release();
}
// 3D R8 256x256x64, 2 mips: 64x32x32 tiles. Mip 0: 4x8x2 = 64 tiles; mip 1 (128x128x32): 2x4x1 = 8.
XgResourceDesc v = tex2d(DXGI_FORMAT_R8_UNORM, 256, 256, 2, kLayoutLinear);
v.Dimension = 4; // XG_RESOURCE_DIMENSION_TEXTURE3D
v.DepthOrArraySize = 64;
c = nullptr;
check(g_create(&v, &c) == S_OK && c, "3D texture created");
if (c) {
UINT32 total = 0, count = 2;
XgPackedMipDesc packed{};
XgTileShape shape{};
XgSubresourceTiling t[2]{};
check(c->GetResourceTiling(&total, &packed, &shape, &count, 0, t) == S_OK, "GetResourceTiling 3D");
check(shape.Width == 64 && shape.Height == 32 && shape.Depth == 32, "3D one-byte tile shape 64x32x32");
check(total == 72 && packed.NumStandardMips == 2 && packed.NumPackedMips == 0, "3D: 72 tiles, no packed mips");
check(tiling_is(t[0], 4, 8, 2, 0) && tiling_is(t[1], 2, 4, 1, 64), "3D mip tilings count depth tiles");
std::vector<uint8_t> tiled(1 << 20), linear(1 << 20);
check(c->CopyIntoSubresource(tiled.data(), 0, 2, linear.data(), 256, 65536) == E_INVALIDARG &&
c->CopyFromSubresource(linear.data(), 0, 2, 0, tiled.data(), 256, 65536) == E_INVALIDARG,
"3D subresource past the mip count is refused, not aliased onto mip 0");
c->Release();
}
// 1D RGBA8 16384 wide: one 64 KiB row of 16384 elements is one tile.
XgResourceDesc line = tex2d(DXGI_FORMAT_R8G8B8A8_UNORM, 16384, 1, 1, kLayoutLinear);
line.Dimension = 2; // XG_RESOURCE_DIMENSION_TEXTURE1D
c = nullptr;
check(g_create(&line, &c) == S_OK && c, "1D texture created");
if (c) {
UINT32 total = 0;
XgTileShape shape{};
check(c->GetResourceTiling(&total, nullptr, &shape, nullptr, 0, nullptr) == S_OK && total == 1 &&
shape.Width == 16384 && shape.Height == 1 && shape.Depth == 1,
"1D RGBA8: one 16384x1x1 tile");
c->Release();
}
// The public D3D12 limits: 16384 for 1D/2D, 2048 for 3D and array sizes.
auto refused = [](XgResourceDesc desc) {
Computer* r = nullptr;
const bool no = g_create(&desc, &r) == E_INVALIDARG && !r;
if (r) r->Release();
return no;
};
check(refused(tex2d(DXGI_FORMAT_R8G8B8A8_UNORM, 16385, 16, 1, kLayoutLinear)), "2D width 16385 refused");
check(refused(tex2d(DXGI_FORMAT_R8G8B8A8_UNORM, 1ull << 32, 16, 1, kLayoutLinear)), "2D width 2^32 refused, not truncated");
XgResourceDesc deep = v;
deep.DepthOrArraySize = 2049;
check(refused(deep), "3D depth 2049 refused");
XgResourceDesc arr = tex2d(DXGI_FORMAT_R8G8B8A8_UNORM, 16, 16, 1, kLayoutLinear);
arr.DepthOrArraySize = 2049;
check(refused(arr), "array size 2049 refused");
}
int main() {
setvbuf(stdout, nullptr, _IONBF, 0);
HMODULE xg = LoadLibraryA("xg_xs.dll");
if (!xg) {
std::printf("FAIL: test_xg_xbox: xg_xs.dll not loaded\n");
return 1;
}
g_create = reinterpret_cast<CreateFn>(reinterpret_cast<void*>(GetProcAddress(xg, "XGCreateTextureComputer")));
const auto suggest = reinterpret_cast<SuggestFn>(reinterpret_cast<void*>(GetProcAddress(xg, "XGSuggestSwizzleMode")));
if (!g_create) {
std::printf("FAIL: test_xg_xbox: XGCreateTextureComputer missing\n");
return 1;
}
test_linear_mips();
test_depth_stencil_bc_buffer();
test_64kb_s_32bpp();
test_64kb_s_bc1();
test_64kb_s_128bpp();
test_tiling_limits_and_methods();
test_refusals_and_suggest(suggest);
if (g_failures) {
std::printf("FAIL: test_xg_xbox: %d of %d checks failed\n", g_failures, g_checks);
return 1;
}
std::printf("PASS: test_xg_xbox (%d checks: linear mips, depth/stencil planes, BC1, buffer, tiling, limits, SW_64KB_S vs D3D12 "
"standard swizzle, linear fallbacks)\n",
g_checks);
return 0;
}
@@ -0,0 +1,5 @@
add_executable(test_xg_xs main.cpp)
target_include_directories(test_xg_xs PRIVATE
"${BX_ABI_INCLUDE_DIR}"
"${CMAKE_CURRENT_SOURCE_DIR}/../../../shims/xg_xs")
target_link_libraries(test_xg_xs PRIVATE xg_xs kernel32)
File diff suppressed because it is too large. Load diff
@@ -396,17 +396,6 @@ std::string utf8(const wchar_t* text) {
return out;
}
// The executable's directory in UTF-8, as XPackageGetMountPath reports it: a drive root keeps its
// separator ("G:\\" when bx-cli maps the package root to G: and launches from there).
std::string executable_directory_utf8() {
wchar_t exe_w[MAX_PATH]{};
CHECK(GetModuleFileNameW(nullptr, exe_w, MAX_PATH) > 0);
wchar_t* slash = std::wcsrchr(exe_w, L'\\');
CHECK(slash != nullptr);
slash[slash == exe_w + 2 && exe_w[1] == L':' ? 1 : 0] = L'\0';
return utf8(exe_w);
}
// --- Concurrency ---
constexpr char kShared[] = "shared/race";
@@ -603,7 +592,10 @@ void check_public_dispatch(void* user, void* synthetic_save, void* synthetic_pac
CHECK(std::strncmp(id, "BXPKG", 5) == 0 && std::strlen(id) == 21);
uint32_t kind = 99;
CHECK(slot<GetKindFn>(package, kPkKind)(package, id, &kind) == S_OK && kind == 0);
const std::string exe_dir = executable_directory_utf8();
wchar_t exe_w[MAX_PATH]{};
CHECK(GetModuleFileNameW(nullptr, exe_w, MAX_PATH) > 0);
*std::wcsrchr(exe_w, L'\\') = L'\0';
const std::string exe_dir = utf8(exe_w);
void* mount = nullptr;
CHECK(slot<MountFn>(package, kPkMount)(package, id, &mount) == S_OK && mount);
size_t path_size = 0;
@@ -1003,7 +995,10 @@ int main() {
CHECK(slot<GetKindFn>(package, kGetKind)(package, "BXPKG0000000000000000", &kind) == kNotFound);
// The mount path is the executable's directory in UTF-8 (W API, so non-ASCII paths work).
const std::string exe_dir = executable_directory_utf8();
wchar_t exe_w[MAX_PATH]{};
CHECK(GetModuleFileNameW(nullptr, exe_w, MAX_PATH) > 0);
*std::wcsrchr(exe_w, L'\\') = L'\0';
const std::string exe_dir = utf8(exe_w);
void* mount = nullptr;
CHECK(slot<MountFn>(package, kMount)(package, "BXPKG0000000000000000", &mount) == kNotFound && !mount);
CHECK(slot<MountFn>(package, kMount)(package, id, &mount) == S_OK && mount);
@@ -1021,107 +1016,6 @@ int main() {
slot<CloseFn>(package, kCloseMount)(package, mount);
CHECK(slot<PathSizeFn>(package, kGetMountPathSize)(package, mount, &path_size) == kInvalidHandle);
// Installation monitors (documented XPackage functions; IXPackageImpl slots 5-10). Offline the
// running package is fully installed and its inst never changes.
struct Progress {
uint64_t totalBytes, installedBytes, launchBytes;
bool launchable, completed;
};
using CreateMonitorFn = HRESULT(WINAPI*)(void*, const char*, uint32_t, const void*, uint32_t, void*, void**);
using MonitorVoidFn = void(WINAPI*)(void*, void*);
using ProgressFn = void(WINAPI*)(void*, void*, Progress*);
using UpdateFn = bool(WINAPI*)(void*, void*);
using RegisterFn = HRESULT(WINAPI*)(void*, void*, void*, void*, uint64_t*);
using UnregisterFn = bool(WINAPI*)(void*, void*, uint64_t, bool);
struct Details {
const char* packageIdentifier;
uint16_t version[4];
uint32_t kind;
const char *displayName, *description, *publisher, *storeId;
bool installing;
uint32_t index, count;
bool ageRestricted;
const char* titleId;
};
using EnumCallback = bool(CALLBACK*)(void*, const Details*);
using EnumFn = HRESULT(WINAPI*)(void*, uint32_t, uint32_t, void*, EnumCallback);
auto progress_cb = [](void*, void*) {};
void* pk = nullptr; // the public IXPackageImpl object (QueryApiImpl, IXPackageImpl4)
{
const GUID cls = guid_bytes(0xAF406016, 0xE850, 0x4AA8, 0xA8, 0x8D, 0x2F, 0x3D, 0xCB, 0x9D, 0xAC, 0x7E);
const GUID iid4 = guid_bytes(0x0B9D556E, 0xAB70, 0x43F4, 0xBA, 0xA0, 0x99, 0x99, 0xAC, 0x4C, 0xB0, 0x40);
CHECK(QueryApiImpl(&cls, &iid4, &pk) == S_OK && pk);
}
void* monitor = nullptr;
CHECK(slot<CreateMonitorFn>(pk, kPkCreateMonitor)(pk, id, 0, nullptr, 0, nullptr, nullptr) == E_POINTER);
CHECK(slot<CreateMonitorFn>(pk, kPkCreateMonitor)(pk, nullptr, 0, nullptr, 0, nullptr, &monitor) == E_INVALIDARG);
CHECK(slot<CreateMonitorFn>(pk, kPkCreateMonitor)(pk, "BXPKG0000000000000000", 0, nullptr, 0, nullptr,
&monitor) == kNotFound && !monitor);
CHECK(slot<CreateMonitorFn>(pk, kPkCreateMonitor)(pk, id, 0, nullptr, 0, nullptr, &monitor) == S_OK && monitor);
Progress inst{};
slot<ProgressFn>(pk, kPkGetProgress)(pk, monitor, &inst);
CHECK(inst.totalBytes == 1 && inst.installedBytes == 1 && inst.launchBytes == 1 && inst.launchable &&
inst.completed);
CHECK(!slot<UpdateFn>(pk, kPkUpdateMonitor)(pk, monitor));
uint64_t token = 0, token2 = 0;
CHECK(slot<RegisterFn>(pk, kPkRegisterProgress)(pk, monitor, nullptr, nullptr, &token) == E_INVALIDARG);
CHECK(slot<RegisterFn>(pk, kPkRegisterProgress)(pk, monitor, nullptr, reinterpret_cast<void*>(+progress_cb),
nullptr) == E_POINTER);
CHECK(slot<RegisterFn>(pk, kPkRegisterProgress)(pk, monitor, nullptr, reinterpret_cast<void*>(+progress_cb),
&token) == S_OK && token);
CHECK(slot<RegisterFn>(pk, kPkRegisterProgress)(pk, monitor, nullptr, reinterpret_cast<void*>(+progress_cb),
&token2) == S_OK && token2 != token);
CHECK(slot<UnregisterFn>(pk, kPkUnregisterProgress)(pk, monitor, token, true));
CHECK(!slot<UnregisterFn>(pk, kPkUnregisterProgress)(pk, monitor, token, true)); // already removed
slot<MonitorVoidFn>(pk, kPkCloseMonitor)(pk, monitor);
slot<MonitorVoidFn>(pk, kPkCloseMonitor)(pk, monitor); // a second close is harmless
inst = {7, 7, 7, true, true};
slot<ProgressFn>(pk, kPkGetProgress)(pk, monitor, &inst);
CHECK(inst.totalBytes == 0 && !inst.completed); // a closed handle reports nothing
CHECK(slot<RegisterFn>(pk, kPkRegisterProgress)(pk, monitor, nullptr, reinterpret_cast<void*>(+progress_cb),
&token) == kInvalidHandle);
CHECK(slot<CreateMonitorFn>(pk, kPkCreateMonitor)(pk, id, 0, nullptr, 0, nullptr, &monitor) == S_OK);
void* survivor = monitor; // checked stale after the uninitialize below
// XPackageEnumeratePackages (slots 28, 35, 39): this game for Game (documented for ThisOnly),
// no packages for Content.
struct Seen {
int count = 0;
std::string id;
uint32_t kind = 99;
} seen;
EnumCallback collect = [](void* ctx, const Details* d) {
auto* out = static_cast<Seen*>(ctx);
++out->count;
out->id = d->packageIdentifier;
out->kind = d->kind;
return true;
};
for (int s : {kPkEnumPackages, kPkEnumPackages2, kPkEnumPackages3}) {
seen = {};
CHECK(slot<EnumFn>(pk, s)(pk, 0, 0, &seen, collect) == S_OK); // Game, ThisOnly
CHECK(seen.count == 1 && seen.id == id && seen.kind == 0);
seen = {};
CHECK(slot<EnumFn>(pk, s)(pk, 1, 0, &seen, collect) == S_OK && seen.count == 0); // Content
CHECK(slot<EnumFn>(pk, s)(pk, 0, 0, &seen, nullptr) == E_INVALIDARG);
}
{
// The accepted, never-fired registration is visible in the JSONL log (bx-cli trace).
char log_path[MAX_PATH]{};
std::string log;
if (GetEnvironmentVariableA("BX_LOG_FILE", log_path, MAX_PATH)) {
HANDLE f = CreateFileA(log_path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
if (f != INVALID_HANDLE_VALUE) {
char buf[65536];
DWORD got = 0;
while (ReadFile(f, buf, sizeof(buf), &got, nullptr) && got) log.append(buf, got);
CloseHandle(f);
}
}
CHECK(log.find("\"event\":\"XPackageRegisterInstallationProgressChanged\"") != std::string::npos &&
log.find("callback is never called") != std::string::npos);
}
// --- Uninitialize then reinitialize: old handles stay dead, queued work does not run ---
{
void* old_container = saves.container(provider, "profiles/main");
@@ -1172,11 +1066,6 @@ int main() {
CHECK(saves.read_status(old_container, {}) == kInvalidHandle);
CHECK(saves.write(old_update, "x", "x", 1) == kInvalidHandle);
CHECK(slot<PathSizeFn>(package, kGetMountPathSize)(package, old_mount, &path_size) == kInvalidHandle);
Progress stale_progress{7, 7, 7, true, true};
slot<ProgressFn>(pk, kPkGetProgress)(pk, survivor, &stale_progress);
CHECK(stale_progress.totalBytes == 0); // uninitialize closed every monitor
CHECK(slot<RegisterFn>(pk, kPkRegisterProgress)(pk, survivor, nullptr,
reinterpret_cast<void*>(+progress_cb), &token) == kInvalidHandle);
void* fresh_user = add_user(queue);
void* fresh = saves.provider(fresh_user);