mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 08:59:52 +00:00
Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
763901541f | ||
|
|
b2654e93a4 | ||
|
|
146d2dd467 | ||
|
|
a0d9b85dbf | ||
|
|
5366b93986 | ||
|
|
50c392111d | ||
|
|
10fd1cd4be | ||
|
|
95aa10c60f | ||
|
|
873b4fd4a9 | ||
|
|
120878de2d | ||
|
|
aba82cdb77 | ||
|
|
a6b0e89cac | ||
|
|
b09d96fd62 | ||
|
|
6814d78230 |
No files matched your search
+22
-1
@@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Changed
|
||||
- Replaced the active phase plan and README X1–X25 roadmap with one native macOS workload sequence and added a pinned PortWatch ecosystem review linked to eight contributor follow-ups. The plan distinguishes existing synthetic execution from future Xbox compatibility; no new runtime behavior, execution result or independent acceptance is claimed.
|
||||
- TLS setup now copies templates from 64 KiB up to 1 MiB straight into the zeroed thread data block, after checking that every template byte is readable, instead of staging them in a second buffer (#111). The pointer array and data block layout, the TLS index write and the error for an unreadable template are unchanged, and nothing is mapped when the template cannot be read. On an Apple M2 Pro, median setup time for original synthetic templates over 31 interleaved samples fell by 21.7 % at 64 KiB, 19.0 % at 256 KiB and 14.2 % at 768 KiB. Smaller and larger templates keep the single staged read and showed no change beyond run-to-run variation.
|
||||
- Removed the contributor avatar section from the README.
|
||||
- Added `.github/CODEOWNERS` so pull requests request review from the `MacosPorters/maintainers` team. With the `main` branch rule that requires code-owner review, a maintainer must approve each change before it merges.
|
||||
@@ -33,6 +34,7 @@ remains unsupported.
|
||||
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
|
||||
|
||||
### Fixed
|
||||
- Restored the DBT benchmark report-test fixture after the cache-invalidation counter was added. Its existing percentile, JSON and comparison tests now run in ordinary workspace CI instead of requiring a separate benchmark test-harness command.
|
||||
- DBT cache hits now compare an executable-generation token instead of rereading every instruction byte. Address-space or executable-memory changes trigger byte and execute-permission revalidation before a translation can be reused; changed code is retranslated. Ordinary data writes retain the fast path. Tests cover cloned spaces, loader bypass writes, split writes, remapping and bounded cache exhaustion. Same-dispatch self-modification and discarded-code reclamation remain unsupported.
|
||||
- Gate A2 checks the cross-compiler driver before invoking it, then checks its helpers before fixture compilation. CI also verifies the driver architecture before requesting its version.
|
||||
- Non-canonical 64-bit guest data addresses now raise `#GP` instead of a memory fault in both the interpreter and native DBT, including accesses that cross the canonical-address boundary. The synthetic architectural test is enabled again.
|
||||
@@ -41,6 +43,24 @@ remains unsupported.
|
||||
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
|
||||
|
||||
### Added
|
||||
- Recorded the migrated PR integration decisions, native verification and scope exclusions in the testing documentation.
|
||||
- Added `xenora-bench startup` (#178), which measures Metal startup in fresh processes and in repeated
|
||||
submissions within one process, phase by phase (launch, device and queue, translation, library, pipeline,
|
||||
submission, GPU, readback), with median, p90, p99 and maximum. Every sample must produce the fixture's
|
||||
expected output, or the run stops without writing results. `docs/testing/benchmarks.md` records one
|
||||
release run on an Apple M4: a fresh process took about 43 ms (median), 36 ms of it creating the Metal
|
||||
device and queue, while repeated runs in one process needed about 0.2 ms of host submission. Measurement
|
||||
only; nothing was optimized.
|
||||
- Added an opt-in, budgeted staged upload for RGBA8 textures (#144). `MetalRgba8Texture::upload_staged` fills a
|
||||
Private-storage texture through one reused Shared staging buffer that never exceeds a `StagingBudget`. It
|
||||
copies whole-row bands with a blit encoder and reuses the buffer only after the previous command buffer has
|
||||
completed with status Completed. `plan_staged_upload` rejects missing, duplicate or out-of-range mip levels,
|
||||
wrong mip sizes, short row pitches or byte buffers, and budgets smaller than one row, all before any Metal
|
||||
object is created. A blit `read_back` returns any mip as tight RGBA8 bytes. On one Apple M4 under Metal API
|
||||
validation, readback matched independently built patterns for every level of a padded 37×19, six-level
|
||||
texture under four budgets, and matched the existing direct `upload`. Staging is slower than the direct path
|
||||
(2048² with 12 mips, release build: 2.1 ms direct, 2.7 ms with a 4 MiB budget, 17.8 ms with 256 KiB), so
|
||||
`upload` and its callers are unchanged. Not yet independently accepted.
|
||||
- The gfx1030 identification benchmark fixture now runs as an ordinary integration test, so workspace tests check LLVM-derived names, families, lengths and byte boundaries without invoking a timing run.
|
||||
- Added a CPU benchmark for gfx1030 metadata identification (#173). It verifies instruction boundaries on a mixed-family stream assembled with LLVM and reports first-pass and repeated-pass throughput.
|
||||
- Added a Win64 ABI regression showing that a service may write the caller-allocated shadow space. Existing negative controls cover nonvolatile XMM-register corruption; the unchanged-home-slot test now describes its handler rather than implying an ABI preservation requirement.
|
||||
@@ -50,10 +70,11 @@ remains unsupported.
|
||||
- Added opt-in shader IR common-subexpression elimination (`CompileOptions::eliminate_common_subexpressions` / `compile_with`) that reuses the first result of an equivalent pure vector unary or binary (#142). Equivalence is the same operation and the same operand values in the same order; constant operands match by bit pattern. Loads, stores, constant definitions, lane masks, merges, branches and other side-effecting or execution-mask-dependent ops are left in place. The pass runs after constant folding, so folded results stay constants and a later pure op on two equal folded constants can still be reused. Default `compile` keeps the historical IR. Covered by hand-derived known-answer compiler tests for reuse (and/xor, not, exact float add), for rejected loads, swapped subtracts, lane masks, lane merges and VCC selects, and for the four combinations with constant folding (1 + 2 = 3, and 1.0 + 2.0 = 3.0), and a check that the 13 golden fixtures, none of which repeats an expression, compile unchanged with the pass on. No speedup is claimed.
|
||||
- The loader now maps an image's PE headers at its image base (#333): the first `SizeOfHeaders` bytes of the file, read-only, in whole 4 KiB pages that are zero past `SizeOfHeaders`. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. When startup relocates an image it writes the load base into the mapped `ImageBase` field after the relocations, so an entry aimed at that field cannot move it twice; this is Xenora's policy and has not been compared with Windows. A load is refused with the new `PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the section table, runs past the file, or its pages would reach into a section, and when the bytes handed to the loader are not the PE32+ headers that were parsed. The page rule refuses images with sub-page section alignment whose first section starts inside the header page, which loaded before. The header pages count toward the 256 MiB mapping budget, which is checked before anything is mapped. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, a relocation aimed at `ImageBase`, the write and execute faults and each refusal with original hand-built images; the image in `pe_mapping_limits.rs` now carries a valid `SizeOfHeaders`. Awaiting independent re-review.
|
||||
- Added 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added Win64 service-call ABI tests in `crates/loader/tests/runtime_services.rs` for #201. A dispatch-level test and a DBT guest-call test verify 16-byte-aligned call entry (`RSP % 16 == 8`), caller-owned 32-byte shadow space accessibility/integrity, return-value/stack/RIP return state, and preservation of RBX/RBP/RDI/RSI/R12-R15 and XMM6-XMM15 across registered service calls. Expected values are derived from the Microsoft x64 calling convention, not from current implementation behavior.
|
||||
- Added Win64 service-call ABI tests in `crates/loader/tests/runtime_services.rs` for #201. A dispatch-level test and a DBT guest-call test verify stack alignment before CALL and at callee entry (`RSP % 16 == 8`), accessibility of the caller-allocated 32-byte shadow space, return-value/stack/RIP return state, and preservation of RBX/RBP/RDI/RSI/R12-R15 and XMM6-XMM15 across registered service calls. Expected values are derived from the Microsoft x64 calling convention, not from current implementation behavior.
|
||||
- `dbt_bench` can compare two of its JSON documents when `XENORA_DBT_BENCH_COMPARE=<baseline.json>,<candidate.json>` is set (#114). It prints each median with its change and whether the change exceeds the larger recorded IQR, and lists changed DBT counters. It refuses, with exit status 1 and the differing field named, to compare runs from different CPUs, operating systems or architectures, with unknown host fields, or with different workloads, sample counts, debug assertions or build labels. A new optional `XENORA_DBT_BENCH_BUILD_LABEL` records build settings the benchmark cannot see, such as LTO. No benchmark runs in this mode.
|
||||
- LAHF and SAHF run in both engines, and guest CPUID reports them in leaf `8000_0001h`, ECX bit 0 (#387; Intel SDM Vol. 2A LAHF, Vol. 2B SAHF). The DBT runs them through the shared semantics. The four known answers from #155 that both engines refused are now verified, with twelve more cases, and the independent reference in `tests/x86_integer.rs` covers both instructions.
|
||||
- LOOP, LOOPE, LOOPNE and JRCXZ run in both engines (#396; Intel SDM Vol. 2A, LOOP/LOOPcc and Jcc). The count is RCX; the address-size prefix stays rejected, so JECXZ and the ECX-counted forms are still refused. The DBT runs them through the shared semantics and ends its block at each. The three known answers from #155 that both engines refused are now verified, with eleven more cases, and `tests/cpu_loop.rs` checks a loop that spans translated blocks against a step-by-step model for every count, ZF match point and step budget.
|
||||
- Added checked, per-mip copy footprints for synthetic block-compressed texture arrays. Contributors can pack tight block rows or repack entire chains with independent row and placement alignment, and pass selected BC1–BC5 levels to the existing Metal readers (#391).
|
||||
- `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=<path>` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged.
|
||||
- Added synthetic guest handle-lifetime regression tests (#205) for capacity reuse, stale handles, duplicate rights and lifetime, wrong object types, thread pseudo handles and failed-output nonmutation. Runtime behavior is unchanged; independent acceptance is pending.
|
||||
- Added a documented independent acceptance rule for promoting AMD RDNA2 desktop GPU (gfx1030) forms from local CPU and Metal results to `fixture verified`, including clean-commit evidence, reviewer independence, raw-log location, review-log summary, failure handling and status regeneration (#302).
|
||||
|
||||
@@ -23,37 +23,26 @@ BetterXen has progressed from executing individual x86-64 instructions to runnin
|
||||
|
||||
The latest verified milestones include **translated gfx1030 vertex and pixel shaders executing through native Apple Metal**, the native Metal **blend pass** (`NativeCompute::render_blend`) and **indexed triangle draws** (`NativeCompute::render_indexed`) into offscreen targets, with rendered pixels compared against independently calculated reference results.
|
||||
|
||||
### Development milestones
|
||||
### Development phases
|
||||
|
||||
| Milestone | Implementation | Status |
|
||||
| --- | --- | --- |
|
||||
| X1 — Guest CPU | Bounded x86-64 instruction execution on ARM64 macOS | Verified |
|
||||
| X2 — Executable loading | Loading original fixed-base PE32+ test executables | Verified |
|
||||
| X3 — GPU compute | Guest-submitted Metal compute workloads and readback | Verified |
|
||||
| X4 — Metal rendering | Guest-driven offscreen rendering using authored Metal shaders | Verified |
|
||||
| X5 — Guest execution expansion | Additional bounded CPU execution and fixture coverage | Implemented |
|
||||
| X6 — Guest control flow | Nested calls, returns, checked memory and synthetic PE execution | Verified |
|
||||
| X7 — Imported services | Named imports, guest-to-host service dispatch and result validation | Verified |
|
||||
| X8 — Translated compute | Original gfx1030 compute shaders executing on Metal, partial Wave32 handling and BC1 readback | Verified subset |
|
||||
| X9 — Translated graphics | Persistent resource handles, translated vertex/pixel stages and offscreen Metal rendering | Verified subset |
|
||||
| X10 — Texture sampling | Translated image instructions are still planned; upload, readback and decode of BC compressed formats is implemented (see [Texture support](#texture-support)) | Planned |
|
||||
| X11 — Graphics pipeline | Bounded multi-draw passes into offscreen RGBA8 targets: translated vertex and pixel stages, indexed triangle draws, colour write masks and blend state | Implemented |
|
||||
| X12 — Wave execution | Expand Wave32/Wave64 semantics, divergent control flow, cross-lane operations, LDS and barriers | Planned |
|
||||
| X13 — Advanced shaders | Mesh, geometry and additional compute shader capabilities with verified Metal execution | Planned |
|
||||
| X14 — CPU recompilation | Native ARM64 dynamic recompilation of supported x86-64 instructions in synthetic fixtures | Implemented subset |
|
||||
| X15 — Executable compatibility | Static PE inspection reports sections, relocations, thread-local storage (TLS) callbacks, imports and entry-point instructions | Static probe implemented |
|
||||
| X16 — Guest memory and threading | Virtual memory mapping, thread scheduling, synchronization primitives and atomic operations | Implemented subset |
|
||||
| X17 — System services | Implement a tested subset of Xbox-compatible runtime APIs, memory services, filesystem access and application lifecycle | Implemented subset |
|
||||
| X18 — Graphics API translation | Translate supported Xbox graphics commands, resource descriptors, command queues, barriers and fences into Metal operations | Planned |
|
||||
| X19 — Advanced GPU features | Indirect rendering, asynchronous compute, additional texture formats and ray-tracing compatibility research | Planned |
|
||||
| X20 — Integrated guest runtime | Connect CPU recompilation, executable loading, system services and graphics translation into one persistent runtime | Planned |
|
||||
| X21 — Application compatibility | Execute increasingly complex independently authored applications through the complete guest CPU and GPU pipeline | Planned |
|
||||
| X22 — First application boot | Establish a reproducible startup and error-reporting path for supported game-like applications | Planned |
|
||||
| X23 — Initial game compatibility | Investigate startup and execution of legally supported game software, identifying missing runtime and graphics behavior | Long-term goal |
|
||||
| X24 — Gameplay and performance | Expand rendering correctness, input, audio, memory management, shader caching and execution performance | Long-term goal |
|
||||
| X25 — Running games | Achieve reproducible, stable execution of compatible games on native Apple Silicon macOS using Metal | Long-term goal |
|
||||
The active plan follows demonstrable native macOS workloads. Every phase has
|
||||
completion checks, dependencies and contributor issues in the
|
||||
[full development plan](docs/development-phases.md).
|
||||
|
||||
**Roadmap note:** X10–X25 are proposed engineering milestones, not completed implementations or a guaranteed sequence. Follow the [BetterXen development phases](docs/development-phases.md) for the current work order and existing issue/PR dependencies. Actual priorities will change as compatibility testing reveals new blockers. Successfully completing one milestone does not guarantee that a particular game will run.
|
||||
| Phase | Result to demonstrate |
|
||||
| --- | --- |
|
||||
| 1 — Compiled guest boot | Reproduce and independently accept the existing original C execution path on native ARM64. |
|
||||
| 2 — Modular guest runtime | Run an original executable with companion libraries, workers, checked waits and lifecycle cleanup. |
|
||||
| 3 — Guest-controlled Metal scene | Reach translated textured rendering through compiled guest calls, with checked resource lifetime and pixels. |
|
||||
| 4 — Interactive application | Combine guest execution, rendering, input, audio, saves and session controls in one original application. |
|
||||
| 5 — Compatibility corpus | Expand CPU/runtime/shader behavior using varied original workloads and independently derived regressions. |
|
||||
| 6 — Sustained native execution | Verify bounded long runs and measured performance on the Apple Silicon hosts actually tested. |
|
||||
| 7 — Xbox compatibility experiments | Resolve public console contracts and demonstrate each separately admitted execution stage before claiming support. |
|
||||
|
||||
These phases replace the previous roadmap. They are targets, not completed
|
||||
acceptance claims or a game-release timeline. Console-contract research and
|
||||
bounded subsystem work can proceed in parallel. Historical fixture identifiers
|
||||
such as X9 remain labels for their original test/evidence records.
|
||||
|
||||
All existing verification refers to independently authored synthetic programs and shaders. Commercial-game compatibility remains unverified.
|
||||
|
||||
@@ -353,7 +342,7 @@ Compiling a shader is not equivalent to proving its GPU output is correct.
|
||||
|
||||
### Where the work is heading
|
||||
|
||||
See the [roadmap table](#development-milestones) for proposed milestones, and the [changelog](CHANGELOG.md) for the current unreleased additions, such as the native blend pass, indexed draws and the depth pass. The remaining research steps are the outstanding items in [current limitations](#current-limitations).
|
||||
See the [development phases](docs/development-phases.md) for the current work order, and the [changelog](CHANGELOG.md) for the current unreleased additions, such as the native blend pass, indexed draws and the depth pass. The remaining research steps are the outstanding items in [current limitations](#current-limitations).
|
||||
|
||||
---
|
||||
|
||||
|
||||
+17
-2
@@ -162,10 +162,21 @@ struct BatchResult {
|
||||
pipelined: Stats,
|
||||
}
|
||||
|
||||
mod startup;
|
||||
mod startup_report;
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
// Taken before anything else so a fresh startup child can report the time
|
||||
// from its parent's spawn to `main`.
|
||||
let entered = SystemTime::now();
|
||||
let mut args = std::env::args().skip(1).peekable();
|
||||
match args.peek().map(String::as_str) {
|
||||
Some("startup") => return startup::run(args.skip(1)),
|
||||
Some("startup-child") => return startup::child(entered, args.skip(1)),
|
||||
_ => {}
|
||||
}
|
||||
let mut output = PathBuf::from("benchmarks/results");
|
||||
let mut reps = DEFAULT_REPS;
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"--output" => {
|
||||
@@ -179,7 +190,11 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
.map_err(|_| "--reps must be a positive integer")?;
|
||||
}
|
||||
"--help" | "-h" => {
|
||||
println!("usage: xenora-bench [--output DIR] [--reps N]");
|
||||
println!(
|
||||
"usage: xenora-bench [--output DIR] [--reps N]\n \
|
||||
xenora-bench startup [--fixture NAME] [--words N] [--processes N] \
|
||||
[--reps N] [--output DIR]"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
other => return Err(format!("unknown argument {other}").into()),
|
||||
|
||||
@@ -0,0 +1,405 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Metal startup distributions: fresh processes versus repeated submissions (#178).
|
||||
//!
|
||||
//! `xenora-bench startup` checks one manifest fixture against the independent
|
||||
//! reference, then measures it two ways:
|
||||
//!
|
||||
//! - **Fresh process.** It launches its own executable `--processes` times. Each
|
||||
//! child creates the Metal device and queue, translates the fixture, runs it
|
||||
//! once with `run_words_profiled`, checks the output and prints one sample line.
|
||||
//! - **Repeated.** In this process it creates one device, then translates and runs
|
||||
//! the same fixture `--reps` times. The first run is reported on its own.
|
||||
//!
|
||||
//! Every sample must produce the expected words. One wrong output, failed child or
|
||||
//! unparsable sample line stops the run before anything is written. The
|
||||
//! numbers describe this host only; two distributions do not explain each other.
|
||||
|
||||
use std::error::Error;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_shader::{Architecture, ENTRY_POINT, compile};
|
||||
|
||||
use crate::startup_report::Report;
|
||||
use crate::{Fixture, Metadata, expand, parse_manifest, percentile, slug};
|
||||
|
||||
const DEFAULT_PROCESSES: usize = 30;
|
||||
const DEFAULT_REPS: usize = 100;
|
||||
/// A fresh process that has not exited by then is killed and fails the run.
|
||||
const CHILD_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// Phases of one run, in seconds. `spawn_to_main` exists only for fresh processes.
|
||||
pub(crate) const PHASES: [&str; 8] = [
|
||||
"spawn_to_main",
|
||||
"device",
|
||||
"translate",
|
||||
"library",
|
||||
"pipeline",
|
||||
"submit",
|
||||
"gpu",
|
||||
"readback",
|
||||
];
|
||||
|
||||
/// One run's phase timings, indexed like [`PHASES`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Default)]
|
||||
pub(crate) struct Sample(pub(crate) [f64; PHASES.len()]);
|
||||
|
||||
impl Sample {
|
||||
fn line(&self) -> String {
|
||||
let fields: Vec<String> = PHASES
|
||||
.iter()
|
||||
.zip(self.0)
|
||||
.map(|(name, value)| format!("{name}={value:e}"))
|
||||
.collect();
|
||||
format!("startup-sample {}", fields.join(" "))
|
||||
}
|
||||
|
||||
/// Parses exactly the line [`Sample::line`] prints: every phase once, in order.
|
||||
pub(crate) fn parse(line: &str) -> Result<Self, String> {
|
||||
let rest = line
|
||||
.strip_prefix("startup-sample ")
|
||||
.ok_or("missing startup-sample prefix")?;
|
||||
let fields: Vec<&str> = rest.split(' ').collect();
|
||||
if fields.len() != PHASES.len() {
|
||||
return Err(format!(
|
||||
"expected {} fields, got {}",
|
||||
PHASES.len(),
|
||||
fields.len()
|
||||
));
|
||||
}
|
||||
let mut sample = Self::default();
|
||||
for (i, (field, name)) in fields.iter().zip(PHASES).enumerate() {
|
||||
let value = field
|
||||
.strip_prefix(name)
|
||||
.and_then(|v| v.strip_prefix('='))
|
||||
.ok_or_else(|| format!("field {i} is not {name}=<seconds>"))?;
|
||||
let value: f64 = value.parse().map_err(|_| format!("bad {name} value"))?;
|
||||
if !value.is_finite() || value < 0.0 {
|
||||
return Err(format!("{name} must be finite and non-negative"));
|
||||
}
|
||||
sample.0[i] = value;
|
||||
}
|
||||
Ok(sample)
|
||||
}
|
||||
}
|
||||
|
||||
/// Median, tail and extremes of one phase.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub(crate) struct Summary {
|
||||
pub(crate) n: usize,
|
||||
pub(crate) min: f64,
|
||||
pub(crate) median: f64,
|
||||
pub(crate) p90: f64,
|
||||
pub(crate) p99: f64,
|
||||
pub(crate) max: f64,
|
||||
}
|
||||
|
||||
pub(crate) fn summarize(values: &[f64]) -> Option<Summary> {
|
||||
if values.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut sorted = values.to_vec();
|
||||
sorted.sort_by(f64::total_cmp);
|
||||
Some(Summary {
|
||||
n: sorted.len(),
|
||||
min: sorted[0],
|
||||
median: percentile(&sorted, 0.5),
|
||||
p90: percentile(&sorted, 0.9),
|
||||
p99: percentile(&sorted, 0.99),
|
||||
max: sorted[sorted.len() - 1],
|
||||
})
|
||||
}
|
||||
|
||||
struct Options {
|
||||
fixture: Option<String>,
|
||||
words: Option<usize>,
|
||||
processes: usize,
|
||||
reps: usize,
|
||||
output: PathBuf,
|
||||
}
|
||||
|
||||
fn count(value: Option<String>, flag: &str) -> Result<usize, String> {
|
||||
let n: usize = value
|
||||
.ok_or_else(|| format!("{flag} needs a count"))?
|
||||
.parse()
|
||||
.map_err(|_| format!("{flag} must be a positive integer"))?;
|
||||
if n == 0 {
|
||||
return Err(format!("{flag} must be at least 1"));
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
fn parse_options(mut args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
let mut options = Options {
|
||||
fixture: None,
|
||||
words: None,
|
||||
processes: DEFAULT_PROCESSES,
|
||||
reps: DEFAULT_REPS,
|
||||
output: PathBuf::from("artifacts/startup"),
|
||||
};
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"--fixture" => options.fixture = Some(args.next().ok_or("--fixture needs a name")?),
|
||||
"--words" => options.words = Some(count(args.next(), "--words")?),
|
||||
"--processes" => options.processes = count(args.next(), "--processes")?,
|
||||
"--reps" => options.reps = count(args.next(), "--reps")?,
|
||||
"--output" => {
|
||||
options.output = PathBuf::from(args.next().ok_or("--output needs a path")?);
|
||||
}
|
||||
other => return Err(format!("unknown startup argument {other}")),
|
||||
}
|
||||
}
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
/// The fixture to time and its word count, after the reference agrees with it.
|
||||
fn select(options: &Options) -> Result<(Fixture, usize), Box<dyn Error>> {
|
||||
let fixtures = parse_manifest(&fs::read_to_string("benchmarks/manifest.toml")?)?;
|
||||
let fixture = match &options.fixture {
|
||||
Some(name) => fixtures.into_iter().find(|f| &f.name == name),
|
||||
None => fixtures.into_iter().next(),
|
||||
}
|
||||
.ok_or("fixture not found in benchmarks/manifest.toml")?;
|
||||
let code = fs::read(&fixture.path)?;
|
||||
let reference = xenora_ref::execute(&code, &fixture.input).map_err(|e| e.to_string())?;
|
||||
if reference != fixture.expected {
|
||||
return Err("reference disagrees with hand-derived expected values".into());
|
||||
}
|
||||
let words = options
|
||||
.words
|
||||
.unwrap_or_else(|| *fixture.sizes.first().unwrap_or(&fixture.input.len()));
|
||||
Ok((fixture, words))
|
||||
}
|
||||
|
||||
/// Translates and runs the fixture once on `metal`, checking the output.
|
||||
fn run_once(
|
||||
metal: &NativeCompute,
|
||||
fixture: &Fixture,
|
||||
words: usize,
|
||||
sample: &mut Sample,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
let input = expand(&fixture.input, words);
|
||||
let expected = expand(&fixture.expected, words);
|
||||
let start = Instant::now();
|
||||
let code = fs::read(&fixture.path)?;
|
||||
let compiled = compile(Architecture::Gfx1030, &code).map_err(|e| e.to_string())?;
|
||||
sample.0[2] = start.elapsed().as_secs_f64();
|
||||
let profile = metal
|
||||
.run_words_profiled(&compiled.msl, ENTRY_POINT, &input)
|
||||
.map_err(|e| e.to_string())?;
|
||||
if profile.output != expected {
|
||||
return Err(format!("{} output disagrees with known answers", fixture.name).into());
|
||||
}
|
||||
sample.0[3] = profile.library_seconds;
|
||||
sample.0[4] = profile.pipeline_seconds;
|
||||
sample.0[5] = profile.host_seconds - profile.library_seconds - profile.pipeline_seconds;
|
||||
sample.0[6] = profile.gpu_seconds;
|
||||
sample.0[7] = profile.readback_seconds;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn unix_nanos(time: SystemTime) -> u128 {
|
||||
time.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_nanos())
|
||||
}
|
||||
|
||||
/// Entry point of one fresh child process, called first thing in `main`.
|
||||
///
|
||||
/// `entered` is the wall-clock time at `main`; the parent passes the wall-clock
|
||||
/// time just before it spawned this process.
|
||||
pub(crate) fn child(
|
||||
entered: SystemTime,
|
||||
mut args: impl Iterator<Item = String>,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
let spawned: u128 = args.next().ok_or("missing spawn time")?.parse()?;
|
||||
let options = parse_options(args)?;
|
||||
let (fixture, words) = select(&options)?;
|
||||
let mut sample = Sample::default();
|
||||
sample.0[0] = unix_nanos(entered).saturating_sub(spawned) as f64 / 1e9;
|
||||
let start = Instant::now();
|
||||
let metal = NativeCompute::new().map_err(|e| e.to_string())?;
|
||||
sample.0[1] = start.elapsed().as_secs_f64();
|
||||
run_once(&metal, &fixture, words, &mut sample)?;
|
||||
println!("{}", sample.line());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn forwarded(fixture: &Fixture, words: usize) -> Vec<String> {
|
||||
vec![
|
||||
"--fixture".into(),
|
||||
fixture.name.clone(),
|
||||
"--words".into(),
|
||||
words.to_string(),
|
||||
]
|
||||
}
|
||||
|
||||
/// Runs one fresh child and returns its spawn-to-exit wall time and stdout.
|
||||
///
|
||||
/// The child inherits this process's environment on purpose, so its `MTL_*`
|
||||
/// validation settings are the ones the run's metadata records.
|
||||
fn spawn_child(
|
||||
exe: &std::path::Path,
|
||||
fixture: &Fixture,
|
||||
words: usize,
|
||||
) -> Result<(f64, String), Box<dyn Error>> {
|
||||
let started = Instant::now();
|
||||
let spawned = unix_nanos(SystemTime::now());
|
||||
let mut child = Command::new(exe)
|
||||
.arg("startup-child")
|
||||
.arg(spawned.to_string())
|
||||
.args(forwarded(fixture, words))
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()?;
|
||||
// Drain both pipes while waiting, so a child that writes more than a pipe
|
||||
// buffer (validation logs, for example) cannot block and look like a hang.
|
||||
let drain = |pipe: Option<Box<dyn std::io::Read + Send>>| {
|
||||
std::thread::spawn(move || {
|
||||
let mut text = String::new();
|
||||
if let Some(mut pipe) = pipe {
|
||||
let _ = pipe.read_to_string(&mut text);
|
||||
}
|
||||
text
|
||||
})
|
||||
};
|
||||
let out = drain(child.stdout.take().map(|p| Box::new(p) as _));
|
||||
let err = drain(child.stderr.take().map(|p| Box::new(p) as _));
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
break status;
|
||||
}
|
||||
if started.elapsed() > CHILD_TIMEOUT {
|
||||
child.kill()?;
|
||||
child.wait()?;
|
||||
return Err(format!("no exit within {} s", CHILD_TIMEOUT.as_secs()).into());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
};
|
||||
let seconds = started.elapsed().as_secs_f64();
|
||||
let stdout = out.join().map_err(|_| "stdout reader panicked")?;
|
||||
let stderr = err.join().map_err(|_| "stderr reader panicked")?;
|
||||
if !status.success() {
|
||||
return Err(format!("{status}: {}", stderr.trim()).into());
|
||||
}
|
||||
Ok((seconds, stdout))
|
||||
}
|
||||
|
||||
/// Runs both regimes and writes `startup.json` and `report.md`.
|
||||
pub(crate) fn run(args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>> {
|
||||
let options = parse_options(args)?;
|
||||
let (fixture, words) = select(&options)?;
|
||||
let exe = std::env::current_exe()?;
|
||||
|
||||
let mut fresh = Vec::with_capacity(options.processes);
|
||||
let mut wall = Vec::with_capacity(options.processes);
|
||||
for i in 0..options.processes {
|
||||
let (seconds, stdout) = spawn_child(&exe, &fixture, words)
|
||||
.map_err(|e| format!("fresh process {i} failed: {e}"))?;
|
||||
wall.push(seconds);
|
||||
let line = stdout
|
||||
.lines()
|
||||
.find(|l| l.starts_with("startup-sample "))
|
||||
.ok_or_else(|| format!("fresh process {i} printed no sample"))?;
|
||||
fresh.push(Sample::parse(line).map_err(|e| format!("fresh process {i}: {e}"))?);
|
||||
}
|
||||
|
||||
let mut first = Sample::default();
|
||||
let start = Instant::now();
|
||||
let metal = NativeCompute::new().map_err(|e| e.to_string())?;
|
||||
first.0[1] = start.elapsed().as_secs_f64();
|
||||
run_once(&metal, &fixture, words, &mut first)?;
|
||||
let mut repeated = Vec::with_capacity(options.reps);
|
||||
for _ in 0..options.reps {
|
||||
let mut sample = Sample::default();
|
||||
run_once(&metal, &fixture, words, &mut sample)?;
|
||||
repeated.push(sample);
|
||||
}
|
||||
|
||||
let metadata = Metadata::collect(&metal.device_name(), options.reps);
|
||||
let dir = options
|
||||
.output
|
||||
.join(slug(&metadata.device))
|
||||
.join(&metadata.run_id);
|
||||
fs::create_dir_all(&dir)?;
|
||||
fs::write(dir.join("metadata.json"), metadata.to_json())?;
|
||||
let report = Report {
|
||||
fixture: &fixture.name,
|
||||
words,
|
||||
fresh: &fresh,
|
||||
wall: &wall,
|
||||
first: &first,
|
||||
repeated: &repeated,
|
||||
};
|
||||
fs::write(dir.join("startup.json"), report.json())?;
|
||||
let markdown = report.markdown(&metadata);
|
||||
fs::write(dir.join("report.md"), &markdown)?;
|
||||
println!("{markdown}");
|
||||
println!("Startup results written to {}", dir.display());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sample_lines_round_trip() {
|
||||
let sample = Sample([0.5, 1e-3, 2.5e-4, 0.0, 7.0, 1e-9, 3.25, 42.0]);
|
||||
assert_eq!(Sample::parse(&sample.line()), Ok(sample));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sample_lines_reject_damaged_input() {
|
||||
let line = Sample([1.0; PHASES.len()]).line();
|
||||
assert!(Sample::parse(&line.replacen("startup-sample", "sample", 1)).is_err());
|
||||
assert!(Sample::parse(&line.replacen("device=", "devise=", 1)).is_err());
|
||||
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=-1e0", 1)).is_err());
|
||||
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=NaN", 1)).is_err());
|
||||
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=x", 1)).is_err());
|
||||
assert!(Sample::parse(line.rsplit_once(' ').unwrap().0).is_err());
|
||||
assert!(Sample::parse(&format!("{line} extra=1")).is_err());
|
||||
// Phases out of order are refused even when every name is present.
|
||||
let swapped = line
|
||||
.replacen("device=", "TMP=", 1)
|
||||
.replacen("translate=", "device=", 1)
|
||||
.replacen("TMP=", "translate=", 1);
|
||||
assert!(Sample::parse(&swapped).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summary_uses_interpolated_percentiles() {
|
||||
// 1..=100: position 0.9 * 99 = 89.1 lies between 90 and 91, and
|
||||
// 0.99 * 99 = 98.01 between 99 and 100.
|
||||
let values: Vec<f64> = (1..=100).rev().map(f64::from).collect();
|
||||
let s = summarize(&values).unwrap();
|
||||
assert_eq!((s.n, s.min, s.max), (100, 1.0, 100.0));
|
||||
assert!((s.median - 50.5).abs() < 1e-9);
|
||||
assert!((s.p90 - 90.1).abs() < 1e-9);
|
||||
assert!((s.p99 - 99.01).abs() < 1e-9);
|
||||
assert_eq!(summarize(&[]), None);
|
||||
let one = summarize(&[3.0]).unwrap();
|
||||
assert_eq!(
|
||||
(one.median, one.p90, one.p99, one.max),
|
||||
(3.0, 3.0, 3.0, 3.0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_reject_bad_counts_and_flags() {
|
||||
let parse = |args: &[&str]| parse_options(args.iter().map(|s| s.to_string()));
|
||||
let defaults = parse(&[]).unwrap();
|
||||
assert_eq!(
|
||||
(defaults.processes, defaults.reps),
|
||||
(DEFAULT_PROCESSES, DEFAULT_REPS)
|
||||
);
|
||||
let set = parse(&["--processes", "3", "--reps", "5", "--words", "64"]).unwrap();
|
||||
assert_eq!((set.processes, set.reps, set.words), (3, 5, Some(64)));
|
||||
assert!(parse(&["--processes", "0"]).is_err());
|
||||
assert!(parse(&["--reps", "-1"]).is_err());
|
||||
assert!(parse(&["--words"]).is_err());
|
||||
assert!(parse(&["--fast"]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! JSON and markdown output of `xenora-bench startup` (#178).
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use crate::startup::{PHASES, Sample, Summary, summarize};
|
||||
use crate::{Metadata, json_str};
|
||||
|
||||
pub(crate) struct Report<'a> {
|
||||
pub(crate) fixture: &'a str,
|
||||
pub(crate) words: usize,
|
||||
pub(crate) fresh: &'a [Sample],
|
||||
pub(crate) wall: &'a [f64],
|
||||
pub(crate) first: &'a Sample,
|
||||
pub(crate) repeated: &'a [Sample],
|
||||
}
|
||||
|
||||
fn column(samples: &[Sample], phase: usize) -> Vec<f64> {
|
||||
samples.iter().map(|s| s.0[phase]).collect()
|
||||
}
|
||||
|
||||
fn summary_json(summary: Option<Summary>) -> String {
|
||||
summary.map_or_else(
|
||||
|| "null".to_string(),
|
||||
|s| {
|
||||
format!(
|
||||
"{{\"n\": {}, \"min\": {:e}, \"median\": {:e}, \"p90\": {:e}, \"p99\": {:e}, \"max\": {:e}}}",
|
||||
s.n, s.min, s.median, s.p90, s.p99, s.max
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
impl Report<'_> {
|
||||
pub(crate) fn json(&self) -> String {
|
||||
let mut out = format!(
|
||||
"{{\n \"fixture\": {},\n \"words\": {},\n \"process_wall\": {},\n",
|
||||
json_str(self.fixture),
|
||||
self.words,
|
||||
summary_json(summarize(self.wall))
|
||||
);
|
||||
for (regime, samples) in [("fresh", self.fresh), ("repeated", self.repeated)] {
|
||||
let _ = writeln!(out, " \"{regime}\": {{");
|
||||
for (i, phase) in PHASES.iter().enumerate() {
|
||||
let comma = if i + 1 < PHASES.len() { "," } else { "" };
|
||||
let summary = if regime == "repeated" && i < 2 {
|
||||
None
|
||||
} else {
|
||||
summarize(&column(samples, i))
|
||||
};
|
||||
let _ = writeln!(out, " \"{phase}\": {}{comma}", summary_json(summary));
|
||||
}
|
||||
out.push_str(" },\n");
|
||||
}
|
||||
let first: Vec<String> = PHASES
|
||||
.iter()
|
||||
.zip(self.first.0)
|
||||
.skip(1)
|
||||
.map(|(p, v)| format!("\"{p}\": {v:e}"))
|
||||
.collect();
|
||||
let _ = writeln!(out, " \"first_in_process\": {{{}}},", first.join(", "));
|
||||
// Raw fresh-process samples in launch order, so a cold first process
|
||||
// (for example an empty Metal shader cache) stays visible.
|
||||
let rows: Vec<String> = self
|
||||
.fresh
|
||||
.iter()
|
||||
.zip(self.wall)
|
||||
.map(|(sample, wall)| {
|
||||
let phases: Vec<String> = sample.0.iter().map(|v| format!("{v:e}")).collect();
|
||||
format!("[{}, {wall:e}]", phases.join(", "))
|
||||
})
|
||||
.collect();
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" \"fresh_samples_columns\": [{}, \"process_wall\"],\n \"fresh_samples\": [\n {}\n ]\n}}",
|
||||
PHASES
|
||||
.iter()
|
||||
.map(|p| json_str(p))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", "),
|
||||
rows.join(",\n ")
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn markdown(&self, metadata: &Metadata) -> String {
|
||||
let ms = |v: f64| format!("{:.3}", v * 1e3);
|
||||
let mut out = format!(
|
||||
"# Metal startup: `{}`, {} words\n\nDevice {}, {} build, commit `{}`, API validation `{}`, shader validation `{}`, power `{}`, thermal `{}`.\n\nAll values in milliseconds. Fresh: {} processes. Repeated: {} runs after the first in one process. Every sample produced the expected output.\n\n| Phase | Fresh median | Fresh p90 | Fresh p99 | Fresh max | First in process | Repeated median | Repeated p90 | Repeated p99 | Repeated max |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n",
|
||||
self.fixture,
|
||||
self.words,
|
||||
metadata.device,
|
||||
metadata.profile,
|
||||
metadata.commit,
|
||||
metadata.api_validation,
|
||||
metadata.shader_validation,
|
||||
metadata.power,
|
||||
metadata.thermal,
|
||||
self.fresh.len(),
|
||||
self.repeated.len(),
|
||||
);
|
||||
for (i, phase) in PHASES.iter().enumerate() {
|
||||
let fresh = summarize(&column(self.fresh, i));
|
||||
let repeated = (i >= 2)
|
||||
.then(|| summarize(&column(self.repeated, i)))
|
||||
.flatten();
|
||||
let cells = |s: Option<Summary>| {
|
||||
s.map_or_else(
|
||||
|| "– | – | – | –".to_string(),
|
||||
|s| {
|
||||
format!(
|
||||
"{} | {} | {} | {}",
|
||||
ms(s.median),
|
||||
ms(s.p90),
|
||||
ms(s.p99),
|
||||
ms(s.max)
|
||||
)
|
||||
},
|
||||
)
|
||||
};
|
||||
let first = if i == 0 {
|
||||
"–".to_string()
|
||||
} else {
|
||||
ms(self.first.0[i])
|
||||
};
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| `{phase}` | {} | {first} | {} |",
|
||||
cells(fresh),
|
||||
cells(repeated)
|
||||
);
|
||||
}
|
||||
if let Some(s) = summarize(self.wall) {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| process wall (spawn to exit) | {} | {} | {} | {} | – | – | – | – | – |",
|
||||
ms(s.median),
|
||||
ms(s.p90),
|
||||
ms(s.p99),
|
||||
ms(s.max)
|
||||
);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -14,8 +14,9 @@
|
||||
//! refused, with exit status 1, unless both runs used the same host, workload,
|
||||
//! build settings and sample counts.
|
||||
//!
|
||||
//! The benchmark target disables Cargo's test harness. To run the percentile
|
||||
//! unit tests, build with
|
||||
//! Report, comparison and percentile tests run in ordinary workspace tests
|
||||
//! through `tests/dbt_benchmark_report.rs`. The benchmark target itself disables
|
||||
//! Cargo's test harness. To run its tests directly, build with
|
||||
//! `cargo rustc --locked -p xenora-loader --bench dbt_bench --message-format=json -- --test`
|
||||
//! and run the executable named by the benchmark's compiler-artifact message.
|
||||
|
||||
@@ -982,6 +983,7 @@ mod tests {
|
||||
blocks_compiled: 626,
|
||||
cache_hits: 0,
|
||||
cache_misses: 626,
|
||||
blocks_invalidated: 0,
|
||||
native_bytes_emitted: 245_168,
|
||||
dbt_dispatches: 626,
|
||||
instructions_executed: 10_002,
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Run the benchmark's report, comparison and percentile tests in normal CI.
|
||||
//! Timing runs remain confined to the standalone benchmark entry point.
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[path = "../benches/dbt_bench.rs"]
|
||||
mod benchmark;
|
||||
@@ -33,6 +33,7 @@ objc2-metal = { version = "=0.3.2", default-features = false, features = [
|
||||
"std",
|
||||
"MTLAllocation",
|
||||
"MTLArgument",
|
||||
"MTLBlitCommandEncoder",
|
||||
"MTLBuffer",
|
||||
"MTLCommandBuffer",
|
||||
"MTLCommandEncoder",
|
||||
|
||||
@@ -11,8 +11,9 @@ use std::ptr::NonNull;
|
||||
use objc2::rc::{Retained, autoreleasepool};
|
||||
use objc2::runtime::ProtocolObject;
|
||||
use objc2_metal::{
|
||||
MTLDevice, MTLOrigin, MTLPixelFormat, MTLRegion, MTLResourceOptions, MTLSize, MTLStorageMode,
|
||||
MTLTexture, MTLTextureDescriptor, MTLTextureUsage,
|
||||
MTLBlitCommandEncoder, MTLBuffer, MTLCommandBuffer, MTLCommandBufferStatus, MTLCommandEncoder,
|
||||
MTLCommandQueue, MTLDevice, MTLOrigin, MTLPixelFormat, MTLRegion, MTLResourceOptions, MTLSize,
|
||||
MTLStorageMode, MTLTexture, MTLTextureDescriptor, MTLTextureUsage,
|
||||
};
|
||||
use xenora_texture::{SamplerError, TextureMetadata};
|
||||
|
||||
@@ -100,6 +101,9 @@ impl Rgba8TextureDesc {
|
||||
pub struct MetalRgba8Texture {
|
||||
texture: Retained<ProtocolObject<dyn MTLTexture>>,
|
||||
desc: Rgba8TextureDesc,
|
||||
/// Shared storage, which `replaceRegion` may write. Private textures are
|
||||
/// filled only through `upload_staged`.
|
||||
cpu_writable: bool,
|
||||
}
|
||||
|
||||
impl MetalRgba8Texture {
|
||||
@@ -108,6 +112,19 @@ impl MetalRgba8Texture {
|
||||
device: &ProtocolObject<dyn MTLDevice>,
|
||||
desc: Rgba8TextureDesc,
|
||||
) -> Result<Self, MetalError> {
|
||||
Self::allocate_with_storage(device, desc, MTLStorageMode::Shared)
|
||||
}
|
||||
|
||||
fn allocate_with_storage(
|
||||
device: &ProtocolObject<dyn MTLDevice>,
|
||||
desc: Rgba8TextureDesc,
|
||||
storage: MTLStorageMode,
|
||||
) -> Result<Self, MetalError> {
|
||||
let options = if storage == MTLStorageMode::Private {
|
||||
MTLResourceOptions::StorageModePrivate
|
||||
} else {
|
||||
MTLResourceOptions::StorageModeShared
|
||||
};
|
||||
autoreleasepool(|_| {
|
||||
// SAFETY: Validated non-zero dimensions within MAX_TEXTURE_PIXELS and RGBA8Unorm format.
|
||||
let descriptor = unsafe {
|
||||
@@ -124,8 +141,8 @@ impl MetalRgba8Texture {
|
||||
descriptor.setMipmapLevelCount(desc.mips as usize);
|
||||
}
|
||||
}
|
||||
descriptor.setStorageMode(MTLStorageMode::Shared);
|
||||
descriptor.setResourceOptions(MTLResourceOptions::StorageModeShared);
|
||||
descriptor.setStorageMode(storage);
|
||||
descriptor.setResourceOptions(options);
|
||||
descriptor.setUsage(MTLTextureUsage::ShaderRead);
|
||||
|
||||
let texture = device
|
||||
@@ -137,51 +154,25 @@ impl MetalRgba8Texture {
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(Self { texture, desc })
|
||||
Ok(Self {
|
||||
texture,
|
||||
desc,
|
||||
cpu_writable: storage == MTLStorageMode::Shared,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Upload a single validated mip level into this texture.
|
||||
///
|
||||
/// Only Shared-storage textures from `allocate` or `upload` accept CPU writes.
|
||||
pub fn upload_mip(&self, mip: &Rgba8MipLevel<'_>) -> Result<(), MetalError> {
|
||||
let (expected_w, expected_h) = self.desc.mip_extent(mip.level)?;
|
||||
if mip.width != expected_w || mip.height != expected_h {
|
||||
if !self.cpu_writable {
|
||||
return Err(MetalError::new(
|
||||
"mip dimensions",
|
||||
format!(
|
||||
"mip level {} expected {}x{}, got {}x{}",
|
||||
mip.level, expected_w, expected_h, mip.width, mip.height
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let tight_pitch = mip
|
||||
.width
|
||||
.checked_mul(RGBA8_TEXEL_BYTES)
|
||||
.ok_or_else(|| MetalError::new("row pitch", "row pitch overflow"))?;
|
||||
if mip.row_pitch < tight_pitch {
|
||||
return Err(MetalError::new(
|
||||
"row pitch",
|
||||
format!(
|
||||
"row pitch {} smaller than tight pitch {}",
|
||||
mip.row_pitch, tight_pitch
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let min_bytes = mip
|
||||
.row_pitch
|
||||
.checked_mul(mip.height)
|
||||
.ok_or_else(|| MetalError::new("mip bytes", "byte length calculation overflow"))?;
|
||||
if mip.bytes.len() < min_bytes {
|
||||
return Err(MetalError::new(
|
||||
"mip buffer bounds",
|
||||
format!(
|
||||
"buffer length {} is less than required {}",
|
||||
mip.bytes.len(),
|
||||
min_bytes
|
||||
),
|
||||
"texture storage",
|
||||
"a Private-storage texture is filled only by upload_staged",
|
||||
));
|
||||
}
|
||||
validate_mip(&self.desc, mip)?;
|
||||
|
||||
autoreleasepool(|_| {
|
||||
let region = MTLRegion {
|
||||
@@ -227,6 +218,148 @@ impl MetalRgba8Texture {
|
||||
Ok(texture)
|
||||
}
|
||||
|
||||
/// Allocate a Private-storage RGBA8 texture and fill every mip level through
|
||||
/// a reused Shared staging buffer that never exceeds `budget`.
|
||||
///
|
||||
/// The plan from [`plan_staged_upload`] is built, and every input checked,
|
||||
/// before any Metal object is created. Each submission copies its rows into
|
||||
/// the staging buffer, blits them into the texture and waits until the
|
||||
/// command buffer has completed. Only a `Completed` status lets the buffer be
|
||||
/// reused; any other status is returned as an error.
|
||||
pub fn upload_staged(
|
||||
device: &ProtocolObject<dyn MTLDevice>,
|
||||
queue: &ProtocolObject<dyn MTLCommandQueue>,
|
||||
desc: Rgba8TextureDesc,
|
||||
mips: &[Rgba8MipLevel<'_>],
|
||||
budget: StagingBudget,
|
||||
) -> Result<(Self, StagedUploadReport), MetalError> {
|
||||
let plan = plan_staged_upload(&desc, mips, budget)?;
|
||||
let staging_len = plan.iter().map(|s| s.staging_bytes).max().unwrap_or(0);
|
||||
let texture = Self::allocate_with_storage(device, desc, MTLStorageMode::Private)?;
|
||||
let staging = device
|
||||
.newBufferWithLength_options(staging_len, MTLResourceOptions::StorageModeShared)
|
||||
.ok_or_else(|| MetalError::new("newBufferWithLength", "staging allocation failed"))?;
|
||||
let mut copied = 0;
|
||||
for submission in &plan {
|
||||
for copy in &submission.copies {
|
||||
let mip = mips
|
||||
.iter()
|
||||
.find(|mip| mip.level == copy.level)
|
||||
.ok_or_else(|| MetalError::new("staged upload", "planned level missing"))?;
|
||||
let tight = mip.width * RGBA8_TEXEL_BYTES;
|
||||
for row in 0..copy.rows {
|
||||
let src = &mip.bytes[(copy.first_row + row) * mip.row_pitch..][..tight];
|
||||
let offset = copy.staging_offset + row * tight;
|
||||
// SAFETY: The plan keeps offset + tight within staging_len, the
|
||||
// buffer is Shared and CPU-visible, and the previous submission
|
||||
// has completed, so the GPU no longer reads these bytes.
|
||||
unsafe {
|
||||
let dst = staging.contents().cast::<u8>().as_ptr().add(offset);
|
||||
std::ptr::copy_nonoverlapping(src.as_ptr(), dst, tight);
|
||||
}
|
||||
}
|
||||
copied += copy.rows * tight;
|
||||
}
|
||||
autoreleasepool(|_| texture.encode_staged(queue, &staging, submission))?;
|
||||
}
|
||||
let report = StagedUploadReport {
|
||||
submissions: plan.len(),
|
||||
peak_staging_bytes: staging_len,
|
||||
bytes_copied: copied,
|
||||
};
|
||||
Ok((texture, report))
|
||||
}
|
||||
|
||||
fn encode_staged(
|
||||
&self,
|
||||
queue: &ProtocolObject<dyn MTLCommandQueue>,
|
||||
staging: &ProtocolObject<dyn MTLBuffer>,
|
||||
submission: &StagedSubmission,
|
||||
) -> Result<(), MetalError> {
|
||||
let command = queue
|
||||
.commandBuffer()
|
||||
.ok_or_else(|| MetalError::new("commandBuffer", "command buffer creation failed"))?;
|
||||
let blit = command
|
||||
.blitCommandEncoder()
|
||||
.ok_or_else(|| MetalError::new("blitCommandEncoder", "blit encoder creation failed"))?;
|
||||
for copy in &submission.copies {
|
||||
let (width, _) = self.desc.mip_extent(copy.level)?;
|
||||
let pitch = width * RGBA8_TEXEL_BYTES;
|
||||
// SAFETY: The plan validated the level, the row range within the mip and
|
||||
// the staging range within the buffer. The command buffer retains both
|
||||
// resources, and the caller waits for completion before reusing staging.
|
||||
unsafe {
|
||||
blit.copyFromBuffer_sourceOffset_sourceBytesPerRow_sourceBytesPerImage_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin(
|
||||
staging,
|
||||
copy.staging_offset,
|
||||
pitch,
|
||||
pitch * copy.rows,
|
||||
MTLSize { width, height: copy.rows, depth: 1 },
|
||||
&self.texture,
|
||||
0,
|
||||
copy.level as usize,
|
||||
MTLOrigin { x: 0, y: copy.first_row, z: 0 },
|
||||
);
|
||||
}
|
||||
}
|
||||
blit.endEncoding();
|
||||
command.commit();
|
||||
command.waitUntilCompleted();
|
||||
check_completed(&command)
|
||||
}
|
||||
|
||||
/// Copy one mip level back into tightly packed RGBA8 bytes through a blit.
|
||||
///
|
||||
/// Works for Shared and Private textures and shares no code with the upload
|
||||
/// paths, so tests can compare its output with independently built pixels.
|
||||
pub fn read_back(
|
||||
&self,
|
||||
device: &ProtocolObject<dyn MTLDevice>,
|
||||
queue: &ProtocolObject<dyn MTLCommandQueue>,
|
||||
level: u32,
|
||||
) -> Result<Vec<u8>, MetalError> {
|
||||
let (width, height) = self.desc.mip_extent(level)?;
|
||||
let pitch = width * RGBA8_TEXEL_BYTES;
|
||||
let len = pitch * height;
|
||||
autoreleasepool(|_| {
|
||||
let buffer = device
|
||||
.newBufferWithLength_options(len, MTLResourceOptions::StorageModeShared)
|
||||
.ok_or_else(|| {
|
||||
MetalError::new("newBufferWithLength", "readback allocation failed")
|
||||
})?;
|
||||
let command = queue.commandBuffer().ok_or_else(|| {
|
||||
MetalError::new("commandBuffer", "command buffer creation failed")
|
||||
})?;
|
||||
let blit = command.blitCommandEncoder().ok_or_else(|| {
|
||||
MetalError::new("blitCommandEncoder", "blit encoder creation failed")
|
||||
})?;
|
||||
// SAFETY: The level is in range, the source region is the whole mip and
|
||||
// the destination buffer holds exactly pitch * height bytes.
|
||||
unsafe {
|
||||
blit.copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toBuffer_destinationOffset_destinationBytesPerRow_destinationBytesPerImage(
|
||||
&self.texture,
|
||||
0,
|
||||
level as usize,
|
||||
MTLOrigin { x: 0, y: 0, z: 0 },
|
||||
MTLSize { width, height, depth: 1 },
|
||||
&buffer,
|
||||
0,
|
||||
pitch,
|
||||
len,
|
||||
);
|
||||
}
|
||||
blit.endEncoding();
|
||||
command.commit();
|
||||
command.waitUntilCompleted();
|
||||
check_completed(&command)?;
|
||||
// SAFETY: The command buffer completed, so the Shared buffer holds len
|
||||
// initialized bytes and the GPU no longer writes it.
|
||||
let bytes =
|
||||
unsafe { std::slice::from_raw_parts(buffer.contents().cast::<u8>().as_ptr(), len) };
|
||||
Ok(bytes.to_vec())
|
||||
})
|
||||
}
|
||||
|
||||
/// Access the underlying native Metal texture protocol object.
|
||||
#[inline]
|
||||
pub fn raw(&self) -> &ProtocolObject<dyn MTLTexture> {
|
||||
@@ -240,6 +373,198 @@ impl MetalRgba8Texture {
|
||||
}
|
||||
}
|
||||
|
||||
/// Upper bound on the staging bytes one staged upload holds at a time.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct StagingBudget {
|
||||
max_bytes: usize,
|
||||
}
|
||||
|
||||
impl StagingBudget {
|
||||
/// A budget of `max_bytes`, which must be a non-zero multiple of the RGBA8
|
||||
/// texel size so every staged row starts on a texel boundary.
|
||||
pub fn new(max_bytes: usize) -> Result<Self, MetalError> {
|
||||
if max_bytes == 0 || !max_bytes.is_multiple_of(RGBA8_TEXEL_BYTES) {
|
||||
return Err(MetalError::new(
|
||||
"staging budget",
|
||||
format!("budget {max_bytes} must be a non-zero multiple of {RGBA8_TEXEL_BYTES}"),
|
||||
));
|
||||
}
|
||||
Ok(Self { max_bytes })
|
||||
}
|
||||
|
||||
/// The largest staging allocation this budget allows.
|
||||
#[must_use]
|
||||
pub fn max_bytes(&self) -> usize {
|
||||
self.max_bytes
|
||||
}
|
||||
}
|
||||
|
||||
/// One blit of whole rows of one mip level from the staging buffer.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct StagedCopy {
|
||||
pub level: u32,
|
||||
pub first_row: usize,
|
||||
pub rows: usize,
|
||||
/// Byte offset of the first row in the staging buffer. Rows are packed tightly.
|
||||
pub staging_offset: usize,
|
||||
}
|
||||
|
||||
/// The copies that share one staging fill and one command buffer.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct StagedSubmission {
|
||||
pub copies: Vec<StagedCopy>,
|
||||
/// Staging bytes this submission uses, never more than the budget.
|
||||
pub staging_bytes: usize,
|
||||
}
|
||||
|
||||
/// What a staged upload did, measured from the executed plan.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct StagedUploadReport {
|
||||
/// Command buffers committed and completed.
|
||||
pub submissions: usize,
|
||||
/// Size of the one staging buffer, the most staging memory held at once.
|
||||
pub peak_staging_bytes: usize,
|
||||
/// Texel bytes copied into the texture.
|
||||
pub bytes_copied: usize,
|
||||
}
|
||||
|
||||
/// Split a full RGBA8 upload into budget-sized submissions of whole rows.
|
||||
///
|
||||
/// Every level `0..desc.mips` must appear exactly once, because a Private
|
||||
/// texture has no defined contents for a level nobody writes. Each mip is
|
||||
/// checked like [`MetalRgba8Texture::upload_mip`] checks it. The budget must hold
|
||||
/// at least one row of the widest level. Rows are packed in level order, and a
|
||||
/// submission closes when the next row would exceed the budget.
|
||||
pub fn plan_staged_upload(
|
||||
desc: &Rgba8TextureDesc,
|
||||
mips: &[Rgba8MipLevel<'_>],
|
||||
budget: StagingBudget,
|
||||
) -> Result<Vec<StagedSubmission>, MetalError> {
|
||||
let mut by_level: Vec<Option<&Rgba8MipLevel<'_>>> = vec![None; desc.mips as usize];
|
||||
for mip in mips {
|
||||
validate_mip(desc, mip)?;
|
||||
let slot = &mut by_level[mip.level as usize];
|
||||
if slot.is_some() {
|
||||
return Err(MetalError::new(
|
||||
"staged upload",
|
||||
format!("mip level {} appears more than once", mip.level),
|
||||
));
|
||||
}
|
||||
*slot = Some(mip);
|
||||
}
|
||||
let mut plan = Vec::new();
|
||||
let mut current = StagedSubmission {
|
||||
copies: Vec::new(),
|
||||
staging_bytes: 0,
|
||||
};
|
||||
for (level, mip) in by_level.iter().enumerate() {
|
||||
let mip = mip.ok_or_else(|| {
|
||||
MetalError::new("staged upload", format!("mip level {level} is missing"))
|
||||
})?;
|
||||
let pitch = mip.width * RGBA8_TEXEL_BYTES;
|
||||
if pitch > budget.max_bytes {
|
||||
return Err(MetalError::new(
|
||||
"staging budget",
|
||||
format!(
|
||||
"budget {} is smaller than one {pitch}-byte row of mip level {level}",
|
||||
budget.max_bytes
|
||||
),
|
||||
));
|
||||
}
|
||||
let mut row = 0;
|
||||
while row < mip.height {
|
||||
let fit = (budget.max_bytes - current.staging_bytes) / pitch;
|
||||
if fit == 0 {
|
||||
// Unreachable after the row check above, but an empty submission
|
||||
// that cannot take one row must never loop.
|
||||
if current.copies.is_empty() {
|
||||
return Err(MetalError::new(
|
||||
"staging budget",
|
||||
"a row does not fit an empty staging buffer",
|
||||
));
|
||||
}
|
||||
plan.push(std::mem::replace(
|
||||
&mut current,
|
||||
StagedSubmission {
|
||||
copies: Vec::new(),
|
||||
staging_bytes: 0,
|
||||
},
|
||||
));
|
||||
continue;
|
||||
}
|
||||
let rows = fit.min(mip.height - row);
|
||||
current.copies.push(StagedCopy {
|
||||
level: mip.level,
|
||||
first_row: row,
|
||||
rows,
|
||||
staging_offset: current.staging_bytes,
|
||||
});
|
||||
current.staging_bytes += rows * pitch;
|
||||
row += rows;
|
||||
}
|
||||
}
|
||||
if !current.copies.is_empty() {
|
||||
plan.push(current);
|
||||
}
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
fn check_completed(command: &ProtocolObject<dyn MTLCommandBuffer>) -> Result<(), MetalError> {
|
||||
let status = command.status();
|
||||
if status != MTLCommandBufferStatus::Completed {
|
||||
let detail = command.error().map_or_else(
|
||||
|| format!("unexpected command status {status:?}"),
|
||||
|error| error.localizedDescription().to_string(),
|
||||
);
|
||||
return Err(MetalError::new("waitUntilCompleted", detail));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check one mip level against the texture description and return its tight row pitch.
|
||||
fn validate_mip(desc: &Rgba8TextureDesc, mip: &Rgba8MipLevel<'_>) -> Result<usize, MetalError> {
|
||||
let (expected_w, expected_h) = desc.mip_extent(mip.level)?;
|
||||
if mip.width != expected_w || mip.height != expected_h {
|
||||
return Err(MetalError::new(
|
||||
"mip dimensions",
|
||||
format!(
|
||||
"mip level {} expected {}x{}, got {}x{}",
|
||||
mip.level, expected_w, expected_h, mip.width, mip.height
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let tight_pitch = mip
|
||||
.width
|
||||
.checked_mul(RGBA8_TEXEL_BYTES)
|
||||
.ok_or_else(|| MetalError::new("row pitch", "row pitch overflow"))?;
|
||||
if mip.row_pitch < tight_pitch {
|
||||
return Err(MetalError::new(
|
||||
"row pitch",
|
||||
format!(
|
||||
"row pitch {} smaller than tight pitch {}",
|
||||
mip.row_pitch, tight_pitch
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let min_bytes = mip
|
||||
.row_pitch
|
||||
.checked_mul(mip.height)
|
||||
.ok_or_else(|| MetalError::new("mip bytes", "byte length calculation overflow"))?;
|
||||
if mip.bytes.len() < min_bytes {
|
||||
return Err(MetalError::new(
|
||||
"mip buffer bounds",
|
||||
format!(
|
||||
"buffer length {} is less than required {}",
|
||||
mip.bytes.len(),
|
||||
min_bytes
|
||||
),
|
||||
));
|
||||
}
|
||||
Ok(tight_pitch)
|
||||
}
|
||||
|
||||
/// Resource binding indices and lifetime conventions for sampling pipelines.
|
||||
///
|
||||
/// In the Xenora fixture ABI and translated shader conventions:
|
||||
@@ -328,3 +653,150 @@ impl BoundSampledTexture {
|
||||
self.sampler_slot
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn copy(level: u32, first_row: usize, rows: usize, staging_offset: usize) -> StagedCopy {
|
||||
StagedCopy {
|
||||
level,
|
||||
first_row,
|
||||
rows,
|
||||
staging_offset,
|
||||
}
|
||||
}
|
||||
|
||||
fn levels<'a>(desc: &Rgba8TextureDesc, bytes: &'a [u8]) -> Vec<Rgba8MipLevel<'a>> {
|
||||
(0..desc.mips)
|
||||
.map(|level| {
|
||||
let (w, h) = desc.mip_extent(level).unwrap();
|
||||
Rgba8MipLevel::new_packed(level, w, h, &bytes[..w * h * RGBA8_TEXEL_BYTES])
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn plan(desc: Rgba8TextureDesc, budget: usize) -> Vec<StagedSubmission> {
|
||||
let bytes = vec![0; desc.width * desc.height * RGBA8_TEXEL_BYTES];
|
||||
plan_staged_upload(
|
||||
&desc,
|
||||
&levels(&desc, &bytes),
|
||||
StagingBudget::new(budget).unwrap(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn error(desc: Rgba8TextureDesc, mips: &[Rgba8MipLevel<'_>], budget: usize) -> String {
|
||||
plan_staged_upload(&desc, mips, StagingBudget::new(budget).unwrap())
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn budget_must_be_a_non_zero_texel_multiple() {
|
||||
assert!(StagingBudget::new(0).is_err());
|
||||
assert!(StagingBudget::new(6).is_err());
|
||||
assert_eq!(StagingBudget::new(8).unwrap().max_bytes(), 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_split_into_budget_sized_submissions() {
|
||||
// 8 texels × 4 bytes = 32 bytes per row; a 64-byte budget holds two rows.
|
||||
let desc = Rgba8TextureDesc::new(8, 4, 1).unwrap();
|
||||
let plan = plan(desc, 64);
|
||||
assert_eq!(plan.len(), 2);
|
||||
assert_eq!(plan[0].copies, [copy(0, 0, 2, 0)]);
|
||||
assert_eq!(plan[1].copies, [copy(0, 2, 2, 0)]);
|
||||
assert!(plan.iter().all(|s| s.staging_bytes == 64));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_submission_packs_every_level_when_it_fits() {
|
||||
// Levels 8×4, 4×2, 2×1: 128 + 32 + 8 = 168 bytes.
|
||||
let desc = Rgba8TextureDesc::new(8, 4, 3).unwrap();
|
||||
let plan = plan(desc, 168);
|
||||
assert_eq!(plan.len(), 1);
|
||||
assert_eq!(
|
||||
plan[0].copies,
|
||||
[copy(0, 0, 4, 0), copy(1, 0, 2, 128), copy(2, 0, 1, 160)]
|
||||
);
|
||||
assert_eq!(plan[0].staging_bytes, 168);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_submission_closes_when_the_next_row_does_not_fit() {
|
||||
// A 40-byte budget holds one 32-byte row of level 0, then two 16-byte rows of
|
||||
// level 1 and the single 8-byte row of level 2 together.
|
||||
let desc = Rgba8TextureDesc::new(8, 4, 3).unwrap();
|
||||
let plan = plan(desc, 40);
|
||||
assert_eq!(plan.len(), 5);
|
||||
for (row, submission) in plan[..4].iter().enumerate() {
|
||||
assert_eq!(submission.copies, [copy(0, row, 1, 0)]);
|
||||
assert_eq!(submission.staging_bytes, 32);
|
||||
}
|
||||
assert_eq!(plan[4].copies, [copy(1, 0, 2, 0), copy(2, 0, 1, 32)]);
|
||||
assert_eq!(plan[4].staging_bytes, 40);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_row_is_planned_once_within_budget() {
|
||||
for (w, h, mips) in [(1, 1, 1), (37, 19, 6), (64, 3, 7), (5, 128, 8)] {
|
||||
let desc = Rgba8TextureDesc::new(w, h, mips).unwrap();
|
||||
let widest = w * RGBA8_TEXEL_BYTES;
|
||||
for budget in [
|
||||
widest,
|
||||
widest + 4,
|
||||
3 * widest,
|
||||
w * h * RGBA8_TEXEL_BYTES * 2,
|
||||
] {
|
||||
let mut next_row = vec![0; mips as usize];
|
||||
for submission in plan(desc, budget) {
|
||||
assert!(submission.staging_bytes <= budget);
|
||||
let mut offset = 0;
|
||||
for c in &submission.copies {
|
||||
let (mw, _) = desc.mip_extent(c.level).unwrap();
|
||||
assert_eq!(c.first_row, next_row[c.level as usize]);
|
||||
assert_eq!(c.staging_offset, offset);
|
||||
assert!(c.rows > 0);
|
||||
offset += c.rows * mw * RGBA8_TEXEL_BYTES;
|
||||
next_row[c.level as usize] += c.rows;
|
||||
}
|
||||
assert_eq!(offset, submission.staging_bytes);
|
||||
}
|
||||
for level in 0..mips {
|
||||
assert_eq!(next_row[level as usize], desc.mip_extent(level).unwrap().1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_partial_and_malformed_uploads_before_planning() {
|
||||
let desc = Rgba8TextureDesc::new(8, 4, 2).unwrap();
|
||||
let bytes = vec![0; 8 * 4 * RGBA8_TEXEL_BYTES];
|
||||
let mips = levels(&desc, &bytes);
|
||||
|
||||
let missing = error(desc, &mips[..1], 1024);
|
||||
assert!(missing.contains("mip level 1 is missing"), "{missing}");
|
||||
|
||||
let duplicate = error(desc, &[mips[0], mips[1], mips[1]], 1024);
|
||||
assert!(duplicate.contains("more than once"), "{duplicate}");
|
||||
|
||||
let out_of_range = Rgba8MipLevel::new_packed(2, 2, 1, &bytes[..8]);
|
||||
let range = error(desc, &[mips[0], mips[1], out_of_range], 1024);
|
||||
assert!(range.contains("out of bounds"), "{range}");
|
||||
|
||||
let wrong_size = Rgba8MipLevel::new_packed(1, 4, 1, &bytes[..16]);
|
||||
assert!(error(desc, &[mips[0], wrong_size], 1024).contains("expected 4x2"));
|
||||
|
||||
let mut short_pitch = mips[0];
|
||||
short_pitch.row_pitch = 28;
|
||||
assert!(error(desc, &[short_pitch, mips[1]], 1024).contains("row pitch"));
|
||||
|
||||
let short_bytes = Rgba8MipLevel::new_packed(0, 8, 4, &bytes[..127]);
|
||||
assert!(error(desc, &[short_bytes, mips[1]], 1024).contains("buffer length"));
|
||||
|
||||
let small = error(desc, &mips, 28);
|
||||
assert!(small.contains("smaller than one 32-byte row"), "{small}");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use xenora_metal::texture_pipeline::{Rgba8TextureDesc, StagingBudget, plan_staged_upload};
|
||||
use xenora_metal::{MetalRgba8Texture, Rgba8MipLevel};
|
||||
use xenora_texture::{Bc1Upload, Bc1UploadDesc, TiledBc1};
|
||||
|
||||
use super::context;
|
||||
@@ -133,3 +135,162 @@ fn samples_pitched_bc1_upload_across_mips_and_layers() {
|
||||
);
|
||||
println!("checked 33 RGBA8 texels from pitched BC1 subresources");
|
||||
}
|
||||
|
||||
/// Texel bytes chosen so neighbouring texels, rows and levels all differ, built
|
||||
/// without any Xenora code so the readback has an independent expectation.
|
||||
fn pattern_texel(level: u32, x: usize, y: usize) -> [u8; 4] {
|
||||
let level = level as usize;
|
||||
[
|
||||
(x * 7 + level * 50) as u8,
|
||||
(y * 13 + level) as u8,
|
||||
((x ^ y) * 3) as u8,
|
||||
(255 - level * 9) as u8,
|
||||
]
|
||||
}
|
||||
|
||||
fn tight_pattern(level: u32, width: usize, height: usize) -> Vec<u8> {
|
||||
(0..height)
|
||||
.flat_map(|y| (0..width).flat_map(move |x| pattern_texel(level, x, y)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Each row padded by `pad` bytes of 0xEE, which must never reach the texture.
|
||||
fn padded_pattern(level: u32, width: usize, height: usize, pad: usize) -> Vec<u8> {
|
||||
let tight = tight_pattern(level, width, height);
|
||||
tight
|
||||
.chunks(width * 4)
|
||||
.flat_map(|row| row.iter().copied().chain(std::iter::repeat_n(0xEE, pad)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn padded_levels(desc: Rgba8TextureDesc, pad: usize) -> Vec<(usize, usize, Vec<u8>)> {
|
||||
(0..desc.mips)
|
||||
.map(|level| {
|
||||
let (w, h) = desc.mip_extent(level).unwrap();
|
||||
(w, h, padded_pattern(level, w, h, pad))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn mip_views(levels: &[(usize, usize, Vec<u8>)], pad: usize) -> Vec<Rgba8MipLevel<'_>> {
|
||||
levels
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(level, (w, h, bytes))| Rgba8MipLevel {
|
||||
level: level as u32,
|
||||
width: *w,
|
||||
height: *h,
|
||||
row_pitch: w * 4 + pad,
|
||||
bytes,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staged_upload_matches_the_source_under_every_budget() {
|
||||
let gpu = context();
|
||||
// 37×19 has six levels, down to 1×1, and odd sizes at every level.
|
||||
let desc = Rgba8TextureDesc::new(37, 19, 6).unwrap();
|
||||
let pad = 12;
|
||||
let levels = padded_levels(desc, pad);
|
||||
let mips = mip_views(&levels, pad);
|
||||
let total: usize = levels.iter().map(|(w, h, _)| w * h * 4).sum();
|
||||
let widest_row = 37 * 4;
|
||||
// One submission, several bands, a single row per band, and a budget that
|
||||
// leaves a remainder at every level.
|
||||
for budget in [total, 3 * widest_row, widest_row, widest_row + 4] {
|
||||
let budget = StagingBudget::new(budget).unwrap();
|
||||
let plan = plan_staged_upload(&desc, &mips, budget).unwrap();
|
||||
let (texture, report) =
|
||||
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget)
|
||||
.unwrap();
|
||||
assert_eq!(report.submissions, plan.len());
|
||||
assert!(report.peak_staging_bytes <= budget.max_bytes());
|
||||
assert_eq!(report.bytes_copied, total);
|
||||
if budget.max_bytes() == total {
|
||||
assert_eq!(report.submissions, 1);
|
||||
} else {
|
||||
assert!(report.submissions > 1);
|
||||
}
|
||||
for level in 0..desc.mips {
|
||||
let (w, h) = desc.mip_extent(level).unwrap();
|
||||
let actual = texture.read_back(gpu.device(), gpu.queue(), level).unwrap();
|
||||
assert_eq!(
|
||||
actual,
|
||||
tight_pattern(level, w, h),
|
||||
"budget {} level {level}",
|
||||
budget.max_bytes()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staged_and_direct_uploads_produce_the_same_texels() {
|
||||
let gpu = context();
|
||||
let desc = Rgba8TextureDesc::new(16, 9, 5).unwrap();
|
||||
let levels = padded_levels(desc, 0);
|
||||
let mips = mip_views(&levels, 0);
|
||||
let direct = MetalRgba8Texture::upload(gpu.device(), desc, &mips).unwrap();
|
||||
let budget = StagingBudget::new(16 * 4 * 2).unwrap();
|
||||
let (staged, _) =
|
||||
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget).unwrap();
|
||||
for level in 0..desc.mips {
|
||||
let (w, h) = desc.mip_extent(level).unwrap();
|
||||
let expected = tight_pattern(level, w, h);
|
||||
assert_eq!(
|
||||
direct.read_back(gpu.device(), gpu.queue(), level).unwrap(),
|
||||
expected
|
||||
);
|
||||
assert_eq!(
|
||||
staged.read_back(gpu.device(), gpu.queue(), level).unwrap(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staged_upload_handles_a_single_texel() {
|
||||
let gpu = context();
|
||||
let desc = Rgba8TextureDesc::new(1, 1, 1).unwrap();
|
||||
let texel = pattern_texel(0, 0, 0);
|
||||
let mips = [Rgba8MipLevel::new_packed(0, 1, 1, &texel)];
|
||||
let budget = StagingBudget::new(4).unwrap();
|
||||
let (texture, report) =
|
||||
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget).unwrap();
|
||||
assert_eq!((report.submissions, report.peak_staging_bytes), (1, 4));
|
||||
assert_eq!(
|
||||
texture.read_back(gpu.device(), gpu.queue(), 0).unwrap(),
|
||||
texel
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staged_upload_rejects_bad_input_before_touching_the_gpu() {
|
||||
let gpu = context();
|
||||
let desc = Rgba8TextureDesc::new(8, 4, 2).unwrap();
|
||||
let levels = padded_levels(desc, 0);
|
||||
let mips = mip_views(&levels, 0);
|
||||
let small = StagingBudget::new(28).unwrap();
|
||||
let error = MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, small)
|
||||
.unwrap_err();
|
||||
assert!(!error.is_capability_unavailable());
|
||||
assert!(
|
||||
error.to_string().contains("smaller than one 32-byte row"),
|
||||
"{error}"
|
||||
);
|
||||
let budget = StagingBudget::new(1024).unwrap();
|
||||
let missing =
|
||||
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips[..1], budget)
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
missing.to_string().contains("mip level 1 is missing"),
|
||||
"{missing}"
|
||||
);
|
||||
|
||||
// A Private texture refuses CPU writes instead of failing inside Metal.
|
||||
let (texture, _) =
|
||||
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget).unwrap();
|
||||
let refused = texture.upload_mip(&mips[0]).unwrap_err();
|
||||
assert!(refused.to_string().contains("Private-storage"), "{refused}");
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
#![cfg(all(feature = "gpu-tests", target_arch = "aarch64", target_os = "macos"))]
|
||||
|
||||
use xenora_metal::{MetalError, NativeCompute};
|
||||
use xenora_texture::{
|
||||
BcAlphaFormat, BcChannelFormat, BcCopyAlignment, BcFormat, BcTextureDesc, BcTextureLayout,
|
||||
PackedBcUpload,
|
||||
};
|
||||
|
||||
const EXTENTS: [(usize, usize); 4] = [(9, 5), (4, 2), (2, 1), (1, 1)];
|
||||
const BLOCK_COUNTS: [usize; 4] = [6, 1, 1, 1];
|
||||
|
||||
// Zero selector bits pick the first endpoint. These RGB565 endpoints encode
|
||||
// exact red, green, blue and white.
|
||||
const COLORS: [[u8; 2]; 4] = [[0x00, 0xf8], [0xe0, 0x07], [0x1f, 0x00], [0xff, 0xff]];
|
||||
const PIXELS: [[u8; 4]; 4] = [
|
||||
[255, 0, 0, 255],
|
||||
[0, 255, 0, 255],
|
||||
[0, 0, 255, 255],
|
||||
[255, 255, 255, 255],
|
||||
];
|
||||
|
||||
fn append_block(bytes: &mut Vec<u8>, format: BcFormat, variant: usize) {
|
||||
let color = COLORS[variant];
|
||||
let color_block = [color[0], color[1], 0, 0, 0, 0, 0, 0];
|
||||
let endpoint_block = |first| [first, 0, 0, 0, 0, 0, 0, 0];
|
||||
match format {
|
||||
BcFormat::Bc1 => bytes.extend(color_block),
|
||||
BcFormat::BcAlpha(format) => {
|
||||
bytes.extend(match format {
|
||||
BcAlphaFormat::Bc2 => [0xff; 8],
|
||||
BcAlphaFormat::Bc3 => endpoint_block(255),
|
||||
});
|
||||
bytes.extend(color_block);
|
||||
}
|
||||
BcFormat::BcChannel(format) => match format {
|
||||
BcChannelFormat::Bc4Unorm => bytes.extend(endpoint_block(PIXELS[variant][0])),
|
||||
BcChannelFormat::Bc5Unorm => {
|
||||
bytes.extend(endpoint_block(PIXELS[variant][0]));
|
||||
bytes.extend(endpoint_block(PIXELS[variant][1]));
|
||||
}
|
||||
BcChannelFormat::Bc4Snorm => bytes.extend(endpoint_block([129, 127, 0, 64][variant])),
|
||||
BcChannelFormat::Bc5Snorm => {
|
||||
bytes.extend(endpoint_block([129, 127, 0, 64][variant]));
|
||||
bytes.extend(endpoint_block([127, 129, 64, 0][variant]));
|
||||
}
|
||||
},
|
||||
_ => unreachable!("native readback fixture covers BC1–BC5"),
|
||||
}
|
||||
}
|
||||
|
||||
fn expected_words(format: BcFormat, layer: usize, mip: usize) -> Vec<u32> {
|
||||
let (width, height) = EXTENTS[mip];
|
||||
let mut result = Vec::new();
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
// The base image has a 3×2 physical block grid. Small levels
|
||||
// have a single block even when either texel extent is below 4.
|
||||
let variant = ((y / 4) * 3 + x / 4 + layer * 2 + mip) % 4;
|
||||
let rgba = match format {
|
||||
BcFormat::Bc1 | BcFormat::BcAlpha(_) => PIXELS[variant],
|
||||
BcFormat::BcChannel(BcChannelFormat::Bc4Unorm) => [PIXELS[variant][0], 0, 0, 255],
|
||||
BcFormat::BcChannel(BcChannelFormat::Bc5Unorm) => {
|
||||
[PIXELS[variant][0], PIXELS[variant][1], 0, 255]
|
||||
}
|
||||
BcFormat::BcChannel(BcChannelFormat::Bc4Snorm) => {
|
||||
[[129, 127, 0, 64][variant], 0, 0, 127]
|
||||
}
|
||||
BcFormat::BcChannel(BcChannelFormat::Bc5Snorm) => [
|
||||
[129, 127, 0, 64][variant],
|
||||
[127, 129, 64, 0][variant],
|
||||
0,
|
||||
127,
|
||||
],
|
||||
_ => unreachable!("native readback fixture covers BC1–BC5"),
|
||||
};
|
||||
result.push(u32::from_le_bytes(rgba));
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn read(
|
||||
gpu: &NativeCompute,
|
||||
upload: &PackedBcUpload<'_>,
|
||||
layer: usize,
|
||||
mip: u32,
|
||||
) -> Result<Vec<u32>, MetalError> {
|
||||
match upload.format() {
|
||||
BcFormat::Bc1 => gpu.read_bc1_upload(&upload.as_bc1(layer, mip).unwrap(), 0, 0),
|
||||
BcFormat::BcAlpha(_) => {
|
||||
gpu.read_bc_alpha_upload(&upload.as_bc_alpha(layer, mip).unwrap(), 0, 0)
|
||||
}
|
||||
BcFormat::BcChannel(_) => {
|
||||
gpu.read_bc_channel_upload(&upload.as_bc_channel(layer, mip).unwrap(), 0, 0)
|
||||
}
|
||||
_ => unreachable!("native readback fixture covers BC1–BC5"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packed_and_aligned_bc_uploads_return_known_pixels_on_metal() {
|
||||
let gpu = NativeCompute::new().expect("native Metal device and queue");
|
||||
for format in [
|
||||
BcFormat::Bc1,
|
||||
BcFormat::BcAlpha(BcAlphaFormat::Bc2),
|
||||
BcFormat::BcAlpha(BcAlphaFormat::Bc3),
|
||||
BcFormat::BcChannel(BcChannelFormat::Bc4Unorm),
|
||||
BcFormat::BcChannel(BcChannelFormat::Bc4Snorm),
|
||||
BcFormat::BcChannel(BcChannelFormat::Bc5Unorm),
|
||||
BcFormat::BcChannel(BcChannelFormat::Bc5Snorm),
|
||||
] {
|
||||
let desc = BcTextureDesc {
|
||||
width: 9,
|
||||
height: 5,
|
||||
mips: 4,
|
||||
layers: 2,
|
||||
format,
|
||||
};
|
||||
let tight = BcTextureLayout::new(desc, BcCopyAlignment::TIGHT).unwrap();
|
||||
let aligned = BcTextureLayout::new(
|
||||
desc,
|
||||
BcCopyAlignment {
|
||||
row: 256,
|
||||
placement: 512,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let mut source = Vec::new();
|
||||
for layer in 0..2 {
|
||||
for (mip, block_count) in BLOCK_COUNTS.into_iter().enumerate() {
|
||||
for n in 0..block_count {
|
||||
append_block(&mut source, format, (n + layer * 2 + mip) % 4);
|
||||
}
|
||||
}
|
||||
}
|
||||
let tight_upload = PackedBcUpload::new(&tight, &source).unwrap();
|
||||
let mut staged = vec![0xff; aligned.byte_len()];
|
||||
tight_upload.repack_into(&aligned, &mut staged).unwrap();
|
||||
let aligned_upload = PackedBcUpload::new(&aligned, &staged).unwrap();
|
||||
|
||||
for (name, upload) in [("tight", &tight_upload), ("aligned", &aligned_upload)] {
|
||||
for layer in 0..2 {
|
||||
for mip in 0..EXTENTS.len() {
|
||||
let actual = read(&gpu, upload, layer, mip as u32).unwrap_or_else(|error| {
|
||||
if error.is_capability_unavailable() {
|
||||
panic!("CAPABILITY UNAVAILABLE: {error}");
|
||||
}
|
||||
panic!("IMPLEMENTATION FAILURE: {format:?} {name} {layer}/{mip}: {error}");
|
||||
});
|
||||
assert_eq!(
|
||||
actual,
|
||||
expected_words(format, layer, mip),
|
||||
"{format:?} {name} layer {layer}, mip {mip}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Linear copy footprints for independently authored block-compressed textures.
|
||||
//!
|
||||
//! For example, a 5×3 BC1 level has two 8-byte blocks forming one 16-byte row.
|
||||
//! Its 2×1 mip takes a single 8-byte block. In a tight layout the levels occupy
|
||||
//! 24 bytes; either can be borrowed directly from the same payload.
|
||||
//!
|
||||
//! ```
|
||||
//! use xenora_texture::{BcCopyAlignment, BcFormat, BcTextureDesc, BcTextureLayout, PackedBcUpload};
|
||||
//!
|
||||
//! let layout = BcTextureLayout::new(
|
||||
//! BcTextureDesc { width: 5, height: 3, mips: 2, layers: 1, format: BcFormat::Bc1 },
|
||||
//! BcCopyAlignment::TIGHT,
|
||||
//! )?;
|
||||
//! let mut bytes = vec![0; layout.byte_len()];
|
||||
//! layout.write_tight(&mut bytes, 0, 1, &[0x55; 8])?;
|
||||
//! let upload = PackedBcUpload::new(&layout, &bytes)?;
|
||||
//! assert_eq!(upload.subresource(0, 1)?.bytes, &[0x55; 8]);
|
||||
//! # Ok::<(), xenora_texture::TextureError>(())
|
||||
//! ```
|
||||
|
||||
use super::{
|
||||
BLOCK_BYTES, Bc1Subresource, Bc1Upload, Bc1UploadDesc, BcAlphaFormat, BcAlphaUpload,
|
||||
BcAlphaUploadDesc, BcChannelFormat, BcChannelUpload, BcChannelUploadDesc, TextureError,
|
||||
mip_blocks,
|
||||
};
|
||||
|
||||
/// Block encoding carried by the layout. The layout handles bytes without decoding texels.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BcFormat {
|
||||
Bc1,
|
||||
BcAlpha(BcAlphaFormat),
|
||||
BcChannel(BcChannelFormat),
|
||||
Bc6hUfloat,
|
||||
Bc6hSfloat,
|
||||
Bc7,
|
||||
}
|
||||
|
||||
impl BcFormat {
|
||||
pub const fn block_bytes(self) -> usize {
|
||||
match self {
|
||||
Self::Bc1 => BLOCK_BYTES,
|
||||
Self::BcChannel(format) => format.block_bytes(),
|
||||
Self::BcAlpha(_) => BcAlphaUpload::BLOCK_BYTES,
|
||||
Self::Bc6hUfloat | Self::Bc6hSfloat | Self::Bc7 => 16,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Dimensions and encoding of a 2D texture or texture array.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct BcTextureDesc {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub mips: u32,
|
||||
pub layers: usize,
|
||||
pub format: BcFormat,
|
||||
}
|
||||
|
||||
/// Row and subresource placement alignments, in bytes. Each must be a nonzero
|
||||
/// power of two. Alignments smaller than a block are raised to its size.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct BcCopyAlignment {
|
||||
pub row: usize,
|
||||
pub placement: usize,
|
||||
}
|
||||
|
||||
impl BcCopyAlignment {
|
||||
pub const TIGHT: Self = Self {
|
||||
row: 1,
|
||||
placement: 1,
|
||||
};
|
||||
}
|
||||
|
||||
/// Logical dimensions and physical storage for one mip in one layer.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct BcFootprint {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub offset: usize,
|
||||
pub row_bytes: usize,
|
||||
pub row_pitch: usize,
|
||||
pub block_rows: usize,
|
||||
/// Full pitched rows, including the final row's padding.
|
||||
pub byte_len: usize,
|
||||
}
|
||||
|
||||
/// Layer-major storage with one footprint per mip. Layers share the same
|
||||
/// layout. Placement padding precedes each subresource as needed and there
|
||||
/// is no trailing placement padding at the end of the final layer.
|
||||
#[derive(Debug)]
|
||||
pub struct BcTextureLayout {
|
||||
desc: BcTextureDesc,
|
||||
mips: Vec<BcFootprint>,
|
||||
layer_stride: usize,
|
||||
byte_len: usize,
|
||||
}
|
||||
|
||||
impl BcTextureLayout {
|
||||
pub fn new(desc: BcTextureDesc, alignment: BcCopyAlignment) -> Result<Self, TextureError> {
|
||||
let max_mips = usize::BITS - desc.width.max(desc.height).leading_zeros();
|
||||
if desc.width == 0
|
||||
|| desc.height == 0
|
||||
|| desc.layers == 0
|
||||
|| desc.mips == 0
|
||||
|| desc.mips > max_mips
|
||||
|| !alignment.row.is_power_of_two()
|
||||
|| !alignment.placement.is_power_of_two()
|
||||
{
|
||||
return Err(TextureError::InvalidLayout);
|
||||
}
|
||||
|
||||
let block_bytes = desc.format.block_bytes();
|
||||
let row_alignment = alignment.row.max(block_bytes);
|
||||
let placement_alignment = alignment.placement.max(block_bytes);
|
||||
let mut mips = Vec::new();
|
||||
mips.try_reserve_exact(desc.mips as usize)
|
||||
.map_err(|_| TextureError::AllocationFailed)?;
|
||||
|
||||
let mut layer_len: usize = 0;
|
||||
for mip in 0..desc.mips {
|
||||
let (blocks_x, block_rows) = mip_blocks(desc.width, desc.height, mip);
|
||||
let row_bytes = blocks_x
|
||||
.checked_mul(block_bytes)
|
||||
.ok_or(TextureError::SizeOverflow)?;
|
||||
let row_pitch = align_up(row_bytes, row_alignment)?;
|
||||
let offset = align_up(layer_len, placement_alignment)?;
|
||||
let byte_len = row_pitch
|
||||
.checked_mul(block_rows)
|
||||
.ok_or(TextureError::SizeOverflow)?;
|
||||
layer_len = offset
|
||||
.checked_add(byte_len)
|
||||
.ok_or(TextureError::SizeOverflow)?;
|
||||
mips.push(BcFootprint {
|
||||
width: (desc.width >> mip).max(1),
|
||||
height: (desc.height >> mip).max(1),
|
||||
offset,
|
||||
row_bytes,
|
||||
row_pitch,
|
||||
block_rows,
|
||||
byte_len,
|
||||
});
|
||||
}
|
||||
|
||||
// A single layer never needs padding after its last mip.
|
||||
let layer_stride = if desc.layers == 1 {
|
||||
layer_len
|
||||
} else {
|
||||
align_up(layer_len, placement_alignment)?
|
||||
};
|
||||
let byte_len = layer_stride
|
||||
.checked_mul(desc.layers - 1)
|
||||
.and_then(|prefix| prefix.checked_add(layer_len))
|
||||
.ok_or(TextureError::SizeOverflow)?;
|
||||
Ok(Self {
|
||||
desc,
|
||||
mips,
|
||||
layer_stride,
|
||||
byte_len,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn byte_len(&self) -> usize {
|
||||
self.byte_len
|
||||
}
|
||||
|
||||
pub fn footprint(&self, layer: usize, mip: u32) -> Result<BcFootprint, TextureError> {
|
||||
if layer >= self.desc.layers {
|
||||
return Err(TextureError::OutOfBounds);
|
||||
}
|
||||
let footprint = self
|
||||
.mips
|
||||
.get(mip as usize)
|
||||
.ok_or(TextureError::OutOfBounds)?;
|
||||
Ok(self.at_layer(*footprint, layer))
|
||||
}
|
||||
|
||||
/// Writes tightly packed block rows to one subresource. Clears that
|
||||
/// subresource's row padding and leaves the rest of the payload alone.
|
||||
/// The destination must include exactly this layout's full byte span.
|
||||
pub fn write_tight(
|
||||
&self,
|
||||
dst: &mut [u8],
|
||||
layer: usize,
|
||||
mip: u32,
|
||||
src: &[u8],
|
||||
) -> Result<(), TextureError> {
|
||||
let fp = self.footprint(layer, mip)?;
|
||||
if dst.len() != self.byte_len || src.len() != fp.row_bytes * fp.block_rows {
|
||||
return Err(TextureError::InvalidByteLength);
|
||||
}
|
||||
|
||||
let dst = &mut dst[fp.offset..fp.offset + fp.byte_len];
|
||||
dst.fill(0);
|
||||
copy_rows(src, fp.row_bytes, dst, fp.row_pitch, fp.row_bytes);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn at_layer(&self, mut footprint: BcFootprint, layer: usize) -> BcFootprint {
|
||||
// Construction checked the span through the end of the final layer.
|
||||
footprint.offset += self.layer_stride * layer;
|
||||
footprint
|
||||
}
|
||||
}
|
||||
|
||||
/// A validated, borrowed payload. Padding bytes in its input may be arbitrary.
|
||||
#[derive(Debug)]
|
||||
pub struct PackedBcUpload<'a> {
|
||||
layout: &'a BcTextureLayout,
|
||||
bytes: &'a [u8],
|
||||
}
|
||||
|
||||
impl<'a> PackedBcUpload<'a> {
|
||||
pub fn new(layout: &'a BcTextureLayout, bytes: &'a [u8]) -> Result<Self, TextureError> {
|
||||
if bytes.len() != layout.byte_len {
|
||||
return Err(TextureError::InvalidByteLength);
|
||||
}
|
||||
Ok(Self { layout, bytes })
|
||||
}
|
||||
|
||||
pub fn format(&self) -> BcFormat {
|
||||
self.layout.desc.format
|
||||
}
|
||||
|
||||
/// Borrows the selected block rows, including their row padding.
|
||||
pub fn subresource(&self, layer: usize, mip: u32) -> Result<Bc1Subresource<'a>, TextureError> {
|
||||
let fp = self.layout.footprint(layer, mip)?;
|
||||
Ok(Bc1Subresource {
|
||||
bytes: &self.bytes[fp.offset..fp.offset + fp.byte_len],
|
||||
width: fp.width,
|
||||
height: fp.height,
|
||||
row_pitch: fp.row_pitch,
|
||||
})
|
||||
}
|
||||
|
||||
/// Copies every logical block to an equivalent layout and zeroes its padding.
|
||||
/// The source and destination must have the same dimensions, mip and layer
|
||||
/// counts, and block encoding. A rejected copy leaves the destination intact.
|
||||
pub fn repack_into(
|
||||
&self,
|
||||
layout: &BcTextureLayout,
|
||||
dst: &mut [u8],
|
||||
) -> Result<(), TextureError> {
|
||||
if self.layout.desc != layout.desc {
|
||||
return Err(TextureError::InvalidLayout);
|
||||
}
|
||||
if dst.len() != layout.byte_len {
|
||||
return Err(TextureError::InvalidByteLength);
|
||||
}
|
||||
|
||||
dst.fill(0);
|
||||
for layer in 0..layout.desc.layers {
|
||||
for (&source, &target) in self.layout.mips.iter().zip(&layout.mips) {
|
||||
let source = self.layout.at_layer(source, layer);
|
||||
let target = layout.at_layer(target, layer);
|
||||
copy_rows(
|
||||
&self.bytes[source.offset..source.offset + source.byte_len],
|
||||
source.row_pitch,
|
||||
&mut dst[target.offset..target.offset + target.byte_len],
|
||||
target.row_pitch,
|
||||
source.row_bytes,
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adapts one BC1 subresource to the existing single-upload reader, without copying.
|
||||
pub fn as_bc1(&self, layer: usize, mip: u32) -> Result<Bc1Upload<'a>, TextureError> {
|
||||
if self.layout.desc.format != BcFormat::Bc1 {
|
||||
return Err(TextureError::InvalidLayout);
|
||||
}
|
||||
let view = self.subresource(layer, mip)?;
|
||||
Bc1Upload::new(
|
||||
view.bytes,
|
||||
Bc1UploadDesc {
|
||||
width: view.width,
|
||||
height: view.height,
|
||||
mips: 1,
|
||||
layers: 1,
|
||||
format: 1,
|
||||
usage: 1,
|
||||
row_pitch: view.row_pitch,
|
||||
slice_pitch: view.bytes.len(),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Adapts one BC2 or BC3 subresource to the existing reader, without copying.
|
||||
pub fn as_bc_alpha(&self, layer: usize, mip: u32) -> Result<BcAlphaUpload<'a>, TextureError> {
|
||||
let BcFormat::BcAlpha(format) = self.layout.desc.format else {
|
||||
return Err(TextureError::InvalidLayout);
|
||||
};
|
||||
let view = self.subresource(layer, mip)?;
|
||||
BcAlphaUpload::new(
|
||||
view.bytes,
|
||||
BcAlphaUploadDesc {
|
||||
width: view.width,
|
||||
height: view.height,
|
||||
mips: 1,
|
||||
layers: 1,
|
||||
format,
|
||||
row_pitch: view.row_pitch,
|
||||
slice_pitch: view.bytes.len(),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Adapts one BC4 or BC5 subresource to the existing reader, without copying.
|
||||
pub fn as_bc_channel(
|
||||
&self,
|
||||
layer: usize,
|
||||
mip: u32,
|
||||
) -> Result<BcChannelUpload<'a>, TextureError> {
|
||||
let BcFormat::BcChannel(format) = self.layout.desc.format else {
|
||||
return Err(TextureError::InvalidLayout);
|
||||
};
|
||||
let view = self.subresource(layer, mip)?;
|
||||
BcChannelUpload::new(
|
||||
view.bytes,
|
||||
BcChannelUploadDesc {
|
||||
width: view.width,
|
||||
height: view.height,
|
||||
mips: 1,
|
||||
layers: 1,
|
||||
format,
|
||||
row_pitch: view.row_pitch,
|
||||
slice_pitch: view.bytes.len(),
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn align_up(value: usize, alignment: usize) -> Result<usize, TextureError> {
|
||||
value
|
||||
.checked_next_multiple_of(alignment)
|
||||
.ok_or(TextureError::SizeOverflow)
|
||||
}
|
||||
|
||||
fn copy_rows(src: &[u8], src_pitch: usize, dst: &mut [u8], dst_pitch: usize, row_bytes: usize) {
|
||||
for (src_row, dst_row) in src
|
||||
.chunks_exact(src_pitch)
|
||||
.zip(dst.chunks_exact_mut(dst_pitch))
|
||||
{
|
||||
dst_row[..row_bytes].copy_from_slice(&src_row[..row_bytes]);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
mod bc;
|
||||
mod bc6h;
|
||||
mod bc7;
|
||||
mod footprint;
|
||||
pub mod sampler;
|
||||
mod upload;
|
||||
pub use bc::{
|
||||
@@ -19,6 +20,9 @@ pub use bc6h::{
|
||||
BC6H_SUPPORTED_MODES, Bc6hError, bc6h_mode, decode_bc6h_sfloat, decode_bc6h_ufloat,
|
||||
};
|
||||
pub use bc7::{BC7_SUPPORTED_MODES, bc7_mode, decode_bc7};
|
||||
pub use footprint::{
|
||||
BcCopyAlignment, BcFootprint, BcFormat, BcTextureDesc, BcTextureLayout, PackedBcUpload,
|
||||
};
|
||||
pub use sampler::{AddressMode, FilterMode, SamplerDesc, SamplerError, TextureMetadata};
|
||||
pub use upload::{
|
||||
Bc1Subresource, Bc1Upload, Bc1UploadDesc, BcAlphaFormat, BcAlphaUpload, BcAlphaUploadDesc,
|
||||
|
||||
@@ -0,0 +1,375 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use xenora_texture::{
|
||||
Bc1Upload, Bc1UploadDesc, BcAlphaFormat, BcChannelFormat, BcCopyAlignment, BcFootprint,
|
||||
BcFormat, BcTextureDesc, BcTextureLayout, PackedBcUpload, TextureError,
|
||||
};
|
||||
|
||||
const DESC: BcTextureDesc = BcTextureDesc {
|
||||
width: 13,
|
||||
height: 9,
|
||||
mips: 4,
|
||||
layers: 2,
|
||||
format: BcFormat::Bc1,
|
||||
};
|
||||
|
||||
const ALIGNED: BcCopyAlignment = BcCopyAlignment {
|
||||
row: 32,
|
||||
placement: 128,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn hand_calculated_footprints_cover_partial_blocks_and_layer_padding() {
|
||||
let tight = BcTextureLayout::new(DESC, BcCopyAlignment::TIGHT).unwrap();
|
||||
let aligned = BcTextureLayout::new(DESC, ALIGNED).unwrap();
|
||||
// 13×9 has four blocks across and three down. 6×4 takes two blocks.
|
||||
// Both 3×2 and 1×1 take one block each.
|
||||
let levels = [(13, 9, 32, 3), (6, 4, 16, 1), (3, 2, 8, 1), (1, 1, 8, 1)];
|
||||
for (layout, offsets, stride, pitches) in [
|
||||
(&tight, [0, 96, 112, 120], 128, [32, 16, 8, 8]),
|
||||
(&aligned, [0, 128, 256, 384], 512, [32; 4]),
|
||||
] {
|
||||
for layer in 0..2 {
|
||||
for (mip, (width, height, row_bytes, block_rows)) in levels.into_iter().enumerate() {
|
||||
let row_pitch = pitches[mip];
|
||||
assert_eq!(
|
||||
layout.footprint(layer, mip as u32),
|
||||
Ok(BcFootprint {
|
||||
width,
|
||||
height,
|
||||
offset: stride * layer + offsets[mip],
|
||||
row_bytes,
|
||||
row_pitch,
|
||||
block_rows,
|
||||
byte_len: row_pitch * block_rows,
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(tight.byte_len(), 256);
|
||||
assert_eq!(aligned.byte_len(), 928);
|
||||
assert_eq!(aligned.footprint(2, 0), Err(TextureError::OutOfBounds));
|
||||
assert_eq!(aligned.footprint(0, 4), Err(TextureError::OutOfBounds));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compact_chain_uses_block_rows_instead_of_reserving_base_size_for_every_mip() {
|
||||
let desc = BcTextureDesc {
|
||||
width: 1024,
|
||||
height: 1024,
|
||||
mips: 11,
|
||||
layers: 1,
|
||||
..DESC
|
||||
};
|
||||
let layout = BcTextureLayout::new(desc, BcCopyAlignment::TIGHT).unwrap();
|
||||
assert_eq!(layout.byte_len(), 699_064);
|
||||
assert_eq!(layout.footprint(0, 10).unwrap().offset, 699_056);
|
||||
let compact = vec![0; layout.byte_len()];
|
||||
PackedBcUpload::new(&layout, &compact).unwrap();
|
||||
let fixed_slice = Bc1UploadDesc {
|
||||
width: 1024,
|
||||
height: 1024,
|
||||
mips: 11,
|
||||
layers: 1,
|
||||
format: 1,
|
||||
usage: 1,
|
||||
row_pitch: 2048,
|
||||
slice_pitch: 524_288,
|
||||
};
|
||||
assert_eq!(
|
||||
Bc1Upload::new(&compact, fixed_slice).unwrap_err(),
|
||||
TextureError::InvalidByteLength
|
||||
);
|
||||
let fixed = vec![0; 5_767_168];
|
||||
let fixed_upload = Bc1Upload::new(&fixed, fixed_slice).unwrap();
|
||||
assert_eq!(fixed_upload.subresource(0, 10).unwrap().bytes.len(), 2048);
|
||||
let aligned = BcTextureLayout::new(
|
||||
desc,
|
||||
BcCopyAlignment {
|
||||
row: 256,
|
||||
placement: 512,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(aligned.byte_len(), 705_280);
|
||||
assert_eq!(aligned.footprint(0, 10).unwrap().offset, 705_024);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_write_clears_its_row_padding_and_preserves_neighbors() {
|
||||
let layout = BcTextureLayout::new(BcTextureDesc { width: 9, ..DESC }, ALIGNED).unwrap();
|
||||
let src: Vec<u8> = (1..=72).collect(); // Three 24-byte rows.
|
||||
let mut dst = vec![0xcc; layout.byte_len()];
|
||||
layout.write_tight(&mut dst, 1, 0, &src).unwrap();
|
||||
let mut expected = vec![0xcc; dst.len()];
|
||||
expected[512..608].fill(0);
|
||||
expected[512..536].copy_from_slice(&src[..24]);
|
||||
expected[544..568].copy_from_slice(&src[24..48]);
|
||||
expected[576..600].copy_from_slice(&src[48..]);
|
||||
assert_eq!(dst, expected);
|
||||
let view = PackedBcUpload::new(&layout, &dst).unwrap();
|
||||
let level = view.subresource(1, 0).unwrap();
|
||||
assert_eq!(level.bytes, &dst[512..608]);
|
||||
assert!(std::ptr::eq(level.bytes.as_ptr(), dst[512..].as_ptr()));
|
||||
assert_eq!((level.width, level.height, level.row_pitch), (9, 9, 32));
|
||||
let legacy = view.as_bc1(1, 0).unwrap().subresource(0, 0).unwrap();
|
||||
assert!(std::ptr::eq(legacy.bytes.as_ptr(), level.bytes.as_ptr()));
|
||||
assert_eq!(legacy.bytes.len(), 96);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repack_ignores_dirty_source_padding_and_zeroes_both_kinds_of_target_padding() {
|
||||
let tight = BcTextureLayout::new(DESC, BcCopyAlignment::TIGHT).unwrap();
|
||||
let aligned = BcTextureLayout::new(DESC, ALIGNED).unwrap();
|
||||
let tight_bytes: Vec<u8> = (0..=255).collect();
|
||||
// Independent byte map from the paper footprints above.
|
||||
let spans = [
|
||||
(0, 0, 96),
|
||||
(96, 128, 16),
|
||||
(112, 256, 8),
|
||||
(120, 384, 8),
|
||||
(128, 512, 96),
|
||||
(224, 640, 16),
|
||||
(240, 768, 8),
|
||||
(248, 896, 8),
|
||||
];
|
||||
let mut dirty_aligned = vec![0xab; 928];
|
||||
let mut clean_aligned = vec![0; 928];
|
||||
for (src, dst, len) in spans {
|
||||
dirty_aligned[dst..dst + len].copy_from_slice(&tight_bytes[src..src + len]);
|
||||
clean_aligned[dst..dst + len].copy_from_slice(&tight_bytes[src..src + len]);
|
||||
}
|
||||
|
||||
let input = PackedBcUpload::new(&aligned, &dirty_aligned).unwrap();
|
||||
let mut compact = vec![0xcc; tight.byte_len()];
|
||||
input.repack_into(&tight, &mut compact).unwrap();
|
||||
assert_eq!(compact, tight_bytes);
|
||||
|
||||
let mut output = vec![0xcc; aligned.byte_len()];
|
||||
input.repack_into(&aligned, &mut output).unwrap();
|
||||
assert_eq!(output, clean_aligned);
|
||||
output.fill(0xcc);
|
||||
PackedBcUpload::new(&tight, &compact)
|
||||
.unwrap()
|
||||
.repack_into(&aligned, &mut output)
|
||||
.unwrap();
|
||||
assert_eq!(output, clean_aligned);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_sizes_before_writing_and_requires_the_same_encoding() {
|
||||
let layout = BcTextureLayout::new(DESC, ALIGNED).unwrap();
|
||||
let mut bytes = vec![0xab; layout.byte_len()];
|
||||
assert_eq!(
|
||||
layout.write_tight(&mut bytes, 0, 3, &[0; 7]),
|
||||
Err(TextureError::InvalidByteLength)
|
||||
);
|
||||
assert_eq!(
|
||||
layout.write_tight(&mut bytes, 0, 3, &[0; 9]),
|
||||
Err(TextureError::InvalidByteLength)
|
||||
);
|
||||
assert_eq!(
|
||||
layout.write_tight(&mut bytes[..927], 0, 3, &[0; 8]),
|
||||
Err(TextureError::InvalidByteLength)
|
||||
);
|
||||
assert_eq!(
|
||||
layout.write_tight(&mut bytes, 2, 3, &[0; 8]),
|
||||
Err(TextureError::OutOfBounds)
|
||||
);
|
||||
assert!(bytes.iter().all(|byte| *byte == 0xab));
|
||||
|
||||
for len in [0, 927, 929] {
|
||||
assert_eq!(
|
||||
PackedBcUpload::new(&layout, &vec![0; len]).unwrap_err(),
|
||||
TextureError::InvalidByteLength
|
||||
);
|
||||
}
|
||||
let upload = PackedBcUpload::new(&layout, &bytes).unwrap();
|
||||
for incompatible in [
|
||||
BcTextureDesc {
|
||||
format: BcFormat::BcChannel(BcChannelFormat::Bc4Unorm),
|
||||
..DESC
|
||||
},
|
||||
BcTextureDesc { width: 14, ..DESC },
|
||||
BcTextureDesc { height: 10, ..DESC },
|
||||
BcTextureDesc { mips: 3, ..DESC },
|
||||
BcTextureDesc { layers: 1, ..DESC },
|
||||
] {
|
||||
let target = BcTextureLayout::new(incompatible, ALIGNED).unwrap();
|
||||
let mut dst = vec![0xcc; target.byte_len()];
|
||||
assert_eq!(
|
||||
upload.repack_into(&target, &mut dst),
|
||||
Err(TextureError::InvalidLayout)
|
||||
);
|
||||
assert!(dst.iter().all(|byte| *byte == 0xcc));
|
||||
}
|
||||
let mut short = vec![0xcc; 927];
|
||||
assert_eq!(
|
||||
upload.repack_into(&layout, &mut short),
|
||||
Err(TextureError::InvalidByteLength)
|
||||
);
|
||||
assert!(short.iter().all(|byte| *byte == 0xcc));
|
||||
assert_eq!(
|
||||
upload.as_bc_alpha(0, 0).unwrap_err(),
|
||||
TextureError::InvalidLayout
|
||||
);
|
||||
assert_eq!(
|
||||
upload.as_bc_channel(0, 0).unwrap_err(),
|
||||
TextureError::InvalidLayout
|
||||
);
|
||||
assert_eq!(upload.as_bc1(0, 4).unwrap_err(), TextureError::OutOfBounds);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_descriptors_and_overflowing_footprints() {
|
||||
for desc in [
|
||||
BcTextureDesc { width: 0, ..DESC },
|
||||
BcTextureDesc { height: 0, ..DESC },
|
||||
BcTextureDesc { mips: 0, ..DESC },
|
||||
BcTextureDesc { mips: 5, ..DESC },
|
||||
BcTextureDesc { layers: 0, ..DESC },
|
||||
] {
|
||||
assert_eq!(
|
||||
BcTextureLayout::new(desc, ALIGNED).unwrap_err(),
|
||||
TextureError::InvalidLayout
|
||||
);
|
||||
}
|
||||
for (row, placement) in [(0, 1), (1, 0), (3, 1), (1, 3)] {
|
||||
assert_eq!(
|
||||
BcTextureLayout::new(DESC, BcCopyAlignment { row, placement }).unwrap_err(),
|
||||
TextureError::InvalidLayout
|
||||
);
|
||||
}
|
||||
for desc in [
|
||||
BcTextureDesc {
|
||||
width: usize::MAX,
|
||||
..DESC
|
||||
},
|
||||
BcTextureDesc {
|
||||
height: usize::MAX,
|
||||
..DESC
|
||||
},
|
||||
BcTextureDesc {
|
||||
layers: usize::MAX,
|
||||
..DESC
|
||||
},
|
||||
] {
|
||||
assert_eq!(
|
||||
BcTextureLayout::new(desc, ALIGNED).unwrap_err(),
|
||||
TextureError::SizeOverflow
|
||||
);
|
||||
}
|
||||
let highest_bit = 1 << (usize::BITS - 1);
|
||||
for alignment in [
|
||||
BcCopyAlignment {
|
||||
row: highest_bit,
|
||||
placement: 1,
|
||||
},
|
||||
BcCopyAlignment {
|
||||
row: 1,
|
||||
placement: highest_bit,
|
||||
},
|
||||
] {
|
||||
assert_eq!(
|
||||
BcTextureLayout::new(DESC, alignment).unwrap_err(),
|
||||
TextureError::SizeOverflow
|
||||
);
|
||||
}
|
||||
// Even an unusually large placement alignment needs no trailing space
|
||||
// after a sole subresource.
|
||||
let one = BcTextureDesc {
|
||||
mips: 1,
|
||||
layers: 1,
|
||||
..DESC
|
||||
};
|
||||
let layout = BcTextureLayout::new(
|
||||
one,
|
||||
BcCopyAlignment {
|
||||
row: 1,
|
||||
placement: highest_bit,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(layout.byte_len(), 96);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_block_sizes_match_a_byte_by_byte_layout_oracle() {
|
||||
let formats = [
|
||||
(BcFormat::Bc1, 8),
|
||||
(BcFormat::BcAlpha(BcAlphaFormat::Bc2), 16),
|
||||
(BcFormat::BcAlpha(BcAlphaFormat::Bc3), 16),
|
||||
(BcFormat::BcChannel(BcChannelFormat::Bc4Unorm), 8),
|
||||
(BcFormat::BcChannel(BcChannelFormat::Bc4Snorm), 8),
|
||||
(BcFormat::BcChannel(BcChannelFormat::Bc5Unorm), 16),
|
||||
(BcFormat::BcChannel(BcChannelFormat::Bc5Snorm), 16),
|
||||
(BcFormat::Bc6hUfloat, 16),
|
||||
(BcFormat::Bc6hSfloat, 16),
|
||||
(BcFormat::Bc7, 16),
|
||||
];
|
||||
for (format, block_bytes) in formats {
|
||||
for (width, height) in [
|
||||
(1_usize, 1_usize),
|
||||
(1, 37),
|
||||
(37, 1),
|
||||
(4, 4),
|
||||
(5, 9),
|
||||
(17, 13),
|
||||
] {
|
||||
for (row, placement) in [(1, 1), (32, 16), (16, 128), (64, 512)] {
|
||||
let mips = usize::BITS - width.max(height).leading_zeros();
|
||||
let desc = BcTextureDesc {
|
||||
width,
|
||||
height,
|
||||
mips,
|
||||
layers: 3,
|
||||
format,
|
||||
};
|
||||
let layout =
|
||||
BcTextureLayout::new(desc, BcCopyAlignment { row, placement }).unwrap();
|
||||
let tight = BcTextureLayout::new(desc, BcCopyAlignment::TIGHT).unwrap();
|
||||
let mut expected = Vec::new();
|
||||
let mut source = Vec::new();
|
||||
for layer in 0..3 {
|
||||
let (mut w, mut h) = (width, height);
|
||||
for mip in 0..mips {
|
||||
while expected.len() % placement != 0 {
|
||||
expected.push(0);
|
||||
}
|
||||
let start = expected.len();
|
||||
let mut tight_level = Vec::new();
|
||||
for y in (0..h).step_by(4) {
|
||||
let row_start = expected.len();
|
||||
for x in (0..w).step_by(4) {
|
||||
for i in 0..block_bytes {
|
||||
let byte =
|
||||
(1 + layer * 51 + mip as usize * 7 + x + 3 * y + i) as u8;
|
||||
expected.push(byte);
|
||||
tight_level.push(byte);
|
||||
}
|
||||
}
|
||||
while (expected.len() - row_start) % row != 0 {
|
||||
expected.push(0);
|
||||
}
|
||||
}
|
||||
let fp = layout.footprint(layer, mip).unwrap();
|
||||
assert_eq!(
|
||||
(fp.offset, fp.offset + fp.byte_len),
|
||||
(start, expected.len())
|
||||
);
|
||||
source.extend(tight_level);
|
||||
(w, h) = ((w / 2).max(1), (h / 2).max(1));
|
||||
}
|
||||
}
|
||||
let upload = PackedBcUpload::new(&tight, &source).unwrap();
|
||||
let mut bytes = vec![0xff; layout.byte_len()];
|
||||
upload.repack_into(&layout, &mut bytes).unwrap();
|
||||
assert_eq!(
|
||||
bytes, expected,
|
||||
"{format:?}, {width}×{height}, {row}/{placement}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,8 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
|
||||
Use the [BetterXen development phases](development-phases.md) for current work
|
||||
order, existing issue/PR dependencies and measurable completion criteria.
|
||||
Historical phase checkpoints retain their original evidence scope.
|
||||
The active plan replaces the former roadmap with workload-based phases, from
|
||||
compiled guest boot to separately admitted Xbox compatibility experiments.
|
||||
|
||||
## Architecture and technical design
|
||||
|
||||
@@ -45,6 +47,7 @@ Historical phase checkpoints retain their original evidence scope.
|
||||
|
||||
## Testing, validation, and benchmarks
|
||||
|
||||
- [Migrated pull-request integration review](testing/migration-pr-review.md) — Merge decisions, integration fixes, native verification and excluded concurrent work.
|
||||
- [Testing and acceptance index](testing/README.md) — Entry point for test procedures, evidence and review records.
|
||||
- [AMD RDNA2 desktop GPU (gfx1030) form acceptance](testing/shader-form-acceptance.md) — Independence, command, log and promotion rules for fixture-verified instruction forms.
|
||||
- [Engineering progress](progress.md) — Verification commands, metric definitions, and open release gates.
|
||||
@@ -57,6 +60,7 @@ Historical phase checkpoints retain their original evidence scope.
|
||||
|
||||
## Research and engineering decisions
|
||||
|
||||
- [PortWatch projects and the native macOS plan](research/portwatch-native-macos.md) — Complete pinned tracker screen, native ARM64 gaps, contributor issues and revised phase dependencies; external claims remain unverified.
|
||||
- [Public sources](research/sources.md), [RDNA 2 notes](research/rdna2.md), and [Xbox GPU evidence](research/xbox-gpu.md) — Specifications, evidence scope, and unknown console behavior.
|
||||
- [Shader inputs](research/shader-containers.md) and [risk register](risk-register.md) — Input provenance and unresolved engineering risks.
|
||||
- [Synthetic integration and upstream evidence](research/synthetic-integration.md) — Audited source snapshots and remaining commercial startup prerequisites.
|
||||
|
||||
+296
-187
@@ -1,238 +1,347 @@
|
||||
# BetterXen development phases
|
||||
|
||||
This is BetterXen's working development plan. Each phase ends with a reproducible
|
||||
application or engineering result. The plan is based on the current repository,
|
||||
not on completing an inherited prompt or reaching a compatibility percentage.
|
||||
No phase authorizes a release, publication, or commercial-game compatibility claim.
|
||||
BetterXen's objective is to execute supported Xbox Series software through an
|
||||
original native ARM64 runtime and direct Metal on macOS. Commercial game
|
||||
execution, including GTA VI, is currently unsupported. The demonstrated results
|
||||
are bounded, independently authored programs and shaders.
|
||||
|
||||
## Starting point
|
||||
This is the sole active phase sequence. It replaces the previous phase plan and
|
||||
the README's X1–X25 roadmap. Historical fixture names and acceptance records
|
||||
retain their meaning as evidence for their original candidates; they are not a
|
||||
second development schedule.
|
||||
|
||||
The source review used `19a905c30ea85166c05084da4fba67e356920912` on destination
|
||||
`main`, with the local documentation work starting after the separate CODEOWNERS
|
||||
commit `f02eb2678e76e91876be5706ce91dca25dcc3017`. The latter changes governance,
|
||||
not runtime behavior. Open issues and PRs were inspected on November 24, 2026
|
||||
(America/Chicago). Recheck their current heads and claims before taking work.
|
||||
## Starting position
|
||||
|
||||
This task performed source inspection and read-only inventories. It did not
|
||||
rerun the Rust, native GPU, application, fuzz, mutation, or performance suites.
|
||||
Historical results below remain evidence for their recorded candidates only.
|
||||
The reviewed main revision is
|
||||
[`b2654e93a42e74e29570183da1f31bb8cdc6f721`](https://github.com/MacosPorters/betterxen/tree/b2654e93a42e74e29570183da1f31bb8cdc6f721),
|
||||
checked on November 24, 2026 (America/Chicago). Research began from a working
|
||||
tree at `f02eb2678e76e91876be5706ce91dca25dcc3017` and inspected newer main in a
|
||||
separate snapshot. This documentation change is based on the reviewed main
|
||||
revision; it changes no runtime implementation.
|
||||
|
||||
| Area | Present in the inspected source | Boundary for this plan |
|
||||
On inspected main, the source contains an x86-64 interpreter, an ARM64 dynamic
|
||||
binary translator (DBT), PE32+ loading, a partial runtime, a deterministic guest
|
||||
scheduler, translated graphics, texture/sampler bindings and a native Swift app.
|
||||
The hosted C fixtures A1 and A2 are implemented and reported locally passing;
|
||||
both still await independent acceptance. These pieces have not established a
|
||||
complete commercial game or one integrated threaded 3D application.
|
||||
|
||||
The [public-project review](research/portwatch-native-macos.md) explains the
|
||||
external comparisons and current-source limits. Windows projects often execute
|
||||
x86-64 instructions directly and use Windows/D3D12 services. The inspected Mac
|
||||
guest-execution projects use Rosetta; native asset renderers demonstrate a
|
||||
different workload. Their progress is a research lead, not BetterXen evidence.
|
||||
No competitor emulator implementation may be copied or adapted.
|
||||
|
||||
No phase is declared complete by this planning task. It ran documentation and
|
||||
inventory checks, not new CPU/GPU execution, fuzzing, mutation or benchmarks.
|
||||
|
||||
## Delivery sequence
|
||||
|
||||
| Phase | Demonstrable result | Principal dependency |
|
||||
| --- | --- | --- |
|
||||
| Guest CPU | Generated x86-64 decoder, interpreter, ARM64 dynamic binary translator (DBT), integer and vector tests; inventory reports 491 declared forms and 206 operations | Declarations and lowering classifications do not establish independent acceptance or broad application compatibility. |
|
||||
| Runtime | PE loading, import resolution, service handlers, process-exit tests and the compiled-C A1 fixture | The typed registry inventories only 20 services: 7 marked implemented and 13 partial. Many handwritten handlers are outside that inventory; 20 is not the total runtime service count. |
|
||||
| Threads | Deterministic scheduler, guest thread contexts and guarded stacks, thread services and compiled-C thread tests | Guest threads execute serially on one host thread. Blocking synchronization, sleep behavior and thread lifecycle callbacks still have documented gaps. |
|
||||
| Graphics | gfx1030 shader decoder/compiler/reference, native Metal execution paths, texture and draw tests | Synthetic desktop instruction fixtures do not establish Xbox behavior. Acceptance is tracked separately from local readback. |
|
||||
| Native app | Swift app, Rust C interface, controller input and audio/virtual-filesystem fixtures | Existing fixtures do not establish one integrated threaded C++ 3D application. |
|
||||
| Quality tools | CPU/runtime inventories, shader coverage reconciliation, task queue, PR checks and acceptance records | Some inventories and ledgers contain stale limitation text. A successful tool invocation does not prove every catalog entry is current. |
|
||||
| 1 | A reproducible compiled guest boots and exits on native ARM64 | Existing A1/A2 and native tool evidence |
|
||||
| 2 | One modular guest program runs workers and cleans up correctly | Module startup, scheduling and lifecycle contracts |
|
||||
| 3 | Guest code controls a translated textured Metal scene | Validated guest graphics calls, bindings and completion |
|
||||
| 4 | An original interactive application combines execution, graphics, input, audio and saves | The supported paths from phases 2 and 3 |
|
||||
| 5 | A varied original workload corpus exposes and closes specific compatibility gaps | A repeatable integrated application and diagnostics |
|
||||
| 6 | Sustained execution is measured and verified across native Apple Silicon hosts | Checked workloads, resource bounds and actual host reports |
|
||||
| 7 | A separately admitted Xbox compatibility experiment has documented contracts and reproducible results | Public console evidence and all behavior required by that input |
|
||||
|
||||
Sources: [CPU registry](cpu/instruction-registry.md),
|
||||
[runtime registry](runtime/registry.md), [guest threads](runtime/threads.md),
|
||||
[interfaces](interfaces.md), [shader coverage](shaders/semantic-coverage.md),
|
||||
[Gate A](testing/gate-a.md), and [QA tooling](testing/infrastructure/README.md).
|
||||
The read-only shader reconciliation reported zero mismatches during this task;
|
||||
that result is inventory consistency, not new GPU verification.
|
||||
Each result has its own admission profile. A simple scene need not wait for all
|
||||
AVX2 instructions, mesh shaders or ray tracing. A workload needing an unsupported
|
||||
feature stops explicitly. Research, diagnostics, CPU expansion and performance
|
||||
measurement can proceed alongside these phases on independently claimed paths.
|
||||
A phase's number does not grant exclusive ownership of a subsystem.
|
||||
|
||||
## How previous phase names fit
|
||||
## Phase 1 — Boot a reproducible compiled guest
|
||||
|
||||
Keep historical evidence and attribution intact. These records remain useful,
|
||||
but their phase numbers are not the sequence for new BetterXen work.
|
||||
**Deliverable:** a contributor can build an original guest from source, start it
|
||||
through BetterXen's supported test entry point and reproduce its output and exit
|
||||
without an Intel host executable or Windows compatibility runtime.
|
||||
|
||||
| Existing record or name | Meaning | How to use it now |
|
||||
| --- | --- | --- |
|
||||
| [Phase 01 checkpoints and assurance](testing/phase01-assurance.md), [risk register](risk-register.md), [review log](testing/review-log.md) and [mutation record](testing/mutation.md) | Earlier bounded shader research and candidate-specific gates | Consult the original gate definitions and unresolved findings; do not relabel them as current acceptance. |
|
||||
| [Phase 02 GPU/guest baseline](testing/phase-02-baseline.md) and [CPU feasibility](research/phase02-cpu-feasibility.md), [ecosystem](research/phase02-ecosystem.md), [collaboration](research/phase02-collaboration.md) research | Early graphics expansion and CPU feasibility work | Reuse documented public sources and evidence limits, checking them against current source. |
|
||||
| [CPU/runtime campaign ledger](coordination/cpu-campaign-ledger.md) | Implementation batches and local evidence | Its older limitations are not a current feature inventory: scheduler, atomic and string work has since landed. |
|
||||
| [Infrastructure Phase II/III tooling](testing/infrastructure/README.md) and [compatibility ledger](testing/infrastructure/phase3-compat-ledger.md) | A separate QA campaign | Tool code now includes compatibility-gap analysis and verification profiles beyond the ledger's early checkpoint. Coordinate with existing issue #219 rather than starting another QA framework. |
|
||||
| [Gate A](testing/gate-a.md) | Compiled C execution, split into A1 and hosted-C A2 | A1 has a main-branch test. A2 is under review in PR #283; the document's “not started” description predates that PR. Neither is independently accepted by this plan. |
|
||||
| Native app numbered gates in `crates/ffi` and `app` | Bounded session, graphics, audio and filesystem fixtures | Inspect their tests before proposing integration. Gate numbers are separate from shader acceptance gates. |
|
||||
| README X1–X25 milestones | Broad capability map | Retain as a capability reference; use the phases below for the next work order. |
|
||||
| Supplied Discord III, III-B, IV, V and VI excerpts | Broad runtime, graphics, application and performance objectives | Only excerpts were supplied. Their omitted requirements and completion status are unknown; they are not execution instructions. |
|
||||
Use the existing [Gate A fixtures](testing/gate-a.md). On inspected main,
|
||||
[PR #283](https://github.com/MacosPorters/betterxen/pull/283) already supplies the
|
||||
hosted C program. Reproduce and review that implementation; do not create a
|
||||
competing CRT startup or mark it unimplemented because this checkout is older.
|
||||
|
||||
Bare issue numbers in historical documents may refer to the source repository.
|
||||
All issue and PR links in the work sections below refer to **MacosPorters/betterxen**.
|
||||
Use [migration records](migration.md) to resolve historical references.
|
||||
The candidate record identifies the exact source revision, local modifications,
|
||||
native compiler/linker, linked support-code licenses, execution path and limits.
|
||||
Check host executables/dependencies with `file`, `lipo -archs` and `otool -L`.
|
||||
Guest x86-64 bytes are permitted data; native host tools must support ARM64.
|
||||
Use `aarch64-apple-darwin` for BetterXen.
|
||||
|
||||
## Phase 1 — Establish a trustworthy working baseline
|
||||
**Completion checks:**
|
||||
|
||||
**Outcome:** contributors can tell what exists on main, what is pending review,
|
||||
and which checks actually ran on the candidate they are using.
|
||||
- A1/A2 reproduce the specified stdout/stderr, files, callback order, exit status
|
||||
and cleanup on the named candidate. Missing compilers fail visibly.
|
||||
- Existing wrong-input, unresolved-import and instruction-budget controls still
|
||||
fail for their specified reasons. A trapped stub is not implemented behavior.
|
||||
- The admission profile states which CPU forms, imports and startup features it
|
||||
supports. The test entry point is distinguished from CLI/app execution.
|
||||
- Independent reviewers accept the semantic expectations and the scope of the
|
||||
native evidence. A local pass alone does not close this phase.
|
||||
|
||||
1. Reconcile the current source with the CPU campaign ledger, Gate A document,
|
||||
runtime inventory scope, and QA compatibility ledger. In particular, the QA
|
||||
CPU inventory's intentional-rejection catalog still lists strings and
|
||||
atomics/fences despite source and tests for supported subsets. Correct the
|
||||
catalog through its existing owner; do not remove explicit unsupported forms.
|
||||
2. Preserve all imported attribution. Repair destination links in migrated PRs
|
||||
without recreating sign-offs or treating archived reviews as current approval.
|
||||
3. Reproduce the applicable existing CPU, generator and repository checks for a
|
||||
pinned candidate. Run GPU and app checks separately on an eligible native host.
|
||||
Record errors, unavailable tools and skipped tests separately.
|
||||
4. Review conflicting PR branches with their authors. Changing descriptions
|
||||
cannot resolve source conflicts or provide missing ARM64 build checks.
|
||||
5. Finish BetterXen's active branding where needed. Preserve copyright notices,
|
||||
licenses and accurate historical records. Package names, C symbols, guest ABI
|
||||
names and environment variables require a compatibility migration, not a
|
||||
blanket search-and-replace. Do not rewrite authorship to imply new ownership.
|
||||
**Contributor work:** [CPU coverage #154](https://github.com/MacosPorters/betterxen/issues/154),
|
||||
[native reports #303](https://github.com/MacosPorters/betterxen/issues/303), and
|
||||
[existing compatibility report #254](https://github.com/MacosPorters/betterxen/issues/254).
|
||||
Use existing audit/test tooling and coordinate schema changes with its owners.
|
||||
|
||||
Existing work: [migration checks #286](https://github.com/MacosPorters/betterxen/issues/286),
|
||||
[QA scope #219](https://github.com/MacosPorters/betterxen/issues/219),
|
||||
[app CI #248](https://github.com/MacosPorters/betterxen/issues/248).
|
||||
## Phase 2 — Run a modular program with guest workers
|
||||
|
||||
**Exit criteria:** a candidate SHA, a current capability/blocker inventory,
|
||||
links to retained logs for each executed gate, explicit pending reviews, and
|
||||
usable PR descriptions. Independent acceptance remains a separate decision.
|
||||
No release is required.
|
||||
**Deliverable:** an original executable and companion libraries initialize,
|
||||
start workers, exchange results, block/resume and exit with checked teardown.
|
||||
|
||||
## Phase 2 — Finish a reproducible hosted C application
|
||||
Begin with [the EXE/two-DLL startup contract #301](https://github.com/MacosPorters/betterxen/issues/301)
|
||||
and [worker lifecycle design #305](https://github.com/MacosPorters/betterxen/issues/305).
|
||||
The fixture records dependency initialization, per-module static thread-local
|
||||
storage (TLS), worker-visible values and supported detach/destructor calls.
|
||||
Expected order must be derived before implementing the loader or callbacks.
|
||||
Built-in service-module lookup is not general guest DLL loading.
|
||||
|
||||
**Outcome:** an original hosted C program starts, uses the runtime, reports
|
||||
results and exits through the guest path with checked cleanup.
|
||||
Extend the existing serial scheduler under
|
||||
[#228](https://github.com/MacosPorters/betterxen/issues/228). Its documented
|
||||
`Sleep` behavior can stall every worker; [#304](https://github.com/MacosPorters/betterxen/issues/304)
|
||||
owns the narrow yielding fix after parent/runtime ownership coordination.
|
||||
Handle critical sections, condition variables and other waits as separately
|
||||
specified gaps, not incidental additions to that fix.
|
||||
|
||||
Review and integrate existing work rather than creating a competing runtime:
|
||||
Broader CPU behavior is driven by the admitted fixture. Start
|
||||
[AVX/YMM design #299](https://github.com/MacosPorters/betterxen/issues/299) and
|
||||
[unwind design #300](https://github.com/MacosPorters/betterxen/issues/300) in
|
||||
parallel, but do not require their entire future scope for a simpler program.
|
||||
A workload using those features must wait for real support. CPU feature bits
|
||||
must not advertise unsupported behavior. Stack walking, structured exception
|
||||
handling (SEH) and C++ exceptions are separate capabilities.
|
||||
|
||||
| Prerequisite | Existing destination work |
|
||||
| --- | --- |
|
||||
| CRT startup calls | [issue #237](https://github.com/MacosPorters/betterxen/issues/237), [PR #273](https://github.com/MacosPorters/betterxen/pull/273) |
|
||||
| Arguments and environment | [issue #242](https://github.com/MacosPorters/betterxen/issues/242), [PR #277](https://github.com/MacosPorters/betterxen/pull/277) |
|
||||
| Normal termination and exit handlers | [issue #243](https://github.com/MacosPorters/betterxen/issues/243), [PR #280](https://github.com/MacosPorters/betterxen/pull/280) |
|
||||
| Formatted standard output | [issue #245](https://github.com/MacosPorters/betterxen/issues/245), [PR #281](https://github.com/MacosPorters/betterxen/pull/281) |
|
||||
| File streams | [issue #246](https://github.com/MacosPorters/betterxen/issues/246), [PR #282](https://github.com/MacosPorters/betterxen/pull/282) |
|
||||
| Integrated hosted-C fixture | [issue #262](https://github.com/MacosPorters/betterxen/issues/262), [PR #283](https://github.com/MacosPorters/betterxen/pull/283) |
|
||||
**Completion checks:**
|
||||
|
||||
Check dependency order and stacked branches against their actual heads. Audit
|
||||
the compiler and linked CRT's per-file licensing and native ARM64 build tools.
|
||||
An x86-64 guest fixture is permitted; its compiler must run natively on ARM64.
|
||||
- The source-built module graph has independently derived results and
|
||||
initialization/teardown records, with explicit forwarder/cycle/search policy.
|
||||
- One worker progresses while another waits. Results hold across specified
|
||||
scheduling quanta; the injected clock and timeout units remain consistent.
|
||||
- Static TLS, dynamic TLS, fiber-local storage (FLS), errors, errno and CPU state
|
||||
retain their specified per-thread isolation. Dropping a value does not count
|
||||
as executing its registered guest callback.
|
||||
- Missing exports, failed attach, invalid callback targets, stack faults,
|
||||
timeouts, deadlock and exhausted budgets have precise, bounded outcomes.
|
||||
- Repeated runs reclaim owned modules, handles, stacks and callback state.
|
||||
Unsupported delayed imports or lifecycle paths are rejected explicitly.
|
||||
|
||||
**Exit criteria:** reproducible original fixture build; checked stdout/stderr,
|
||||
arguments, file contents, exit status, callback order and cleanup; unresolved
|
||||
imports and exhausted budgets fail explicitly. Existing A1 behavior still passes.
|
||||
Independent reviewers derive expected results from public specifications and the
|
||||
fixture contract. No general C++ or Xbox startup claim follows from this result.
|
||||
**Contributor work:** reuse [package census #211](https://github.com/MacosPorters/betterxen/issues/211)
|
||||
and the existing scheduler. Runtime PRs #263/#290 overlap; their authors and
|
||||
maintainers must resolve ownership before shared production edits. Parallel
|
||||
host-thread execution remains outside the serial scheduler's ordering claim.
|
||||
|
||||
## Phase 3 — Make threaded application behavior coherent
|
||||
## Phase 3 — Render a scene controlled by guest code
|
||||
|
||||
**Outcome:** an original worker-based application can block and resume without
|
||||
stalling unrelated guest work or leaking per-thread state.
|
||||
**Deliverable:** a compiled original guest creates resources, uploads a texture
|
||||
and geometry, submits translated rendering, waits for completion and checks the
|
||||
resulting frame through its guest-visible interface.
|
||||
|
||||
Extend the existing scheduler under [issue #228](https://github.com/MacosPorters/betterxen/issues/228).
|
||||
Prioritize a small fixture that exposes a documented gap: guest sleep currently
|
||||
delays all guest threads, and critical-section/SRW/condition-variable waits are
|
||||
not fully connected to scheduling. Claim one gap and its paths before editing.
|
||||
Use [startup-to-frame integration #256](https://github.com/MacosPorters/betterxen/issues/256)
|
||||
as the integration task. A Rust test calling a host graphics method does not
|
||||
alone prove the compiled guest can call it. Specify the supported service/call
|
||||
boundary and check its Win64 argument/return and nonvolatile-state behavior.
|
||||
Guest addresses must resolve to checked ranges and opaque handles, never host
|
||||
pointers.
|
||||
|
||||
Then add the thread lifecycle behavior required by that workload, including
|
||||
static thread-local storage (TLS), library attach/detach and fiber-local storage
|
||||
(FLS) cleanup where supported. Keep unsupported callbacks explicit until their
|
||||
semantics and safety are implemented. Preserve Win64 nonvolatile register checks
|
||||
and coordinate with [issue #193 / PR #268](https://github.com/MacosPorters/betterxen/pull/268).
|
||||
Existing translated `image_sample_lz`, guest descriptor-table bindings, texture
|
||||
upload paths, blend/index/depth tests and packed compressed-texture footprints
|
||||
are starting components. [Binding/entry design #302](https://github.com/MacosPorters/betterxen/issues/302)
|
||||
specifies expansion beyond the bounded texture/sampler contract. Use an original
|
||||
scene with distinguishable textures and resource updates so wrong bindings or
|
||||
stale data change checked pixels.
|
||||
|
||||
**Exit criteria:** deterministic results at several scheduling quanta; another
|
||||
worker progresses while one waits; timeouts, cancellation, abandoned objects,
|
||||
thread-local errors, stack bounds and cleanup have negative controls. Repeat
|
||||
runs reclaim thread resources. Serial guest scheduling remains the execution
|
||||
model unless a separately reviewed memory-ordering design replaces it.
|
||||
**Completion checks:**
|
||||
|
||||
## Phase 4 — Connect resource updates to translated rendering
|
||||
- Actual native Metal execution produces frame readback matching expectations
|
||||
derived independently of the decoder, compiler and production renderer.
|
||||
- Changing one guest texture, transform or binding changes the expected frame;
|
||||
a skipped draw or substituted shader cannot pass as correct rendering.
|
||||
- Update, submit, completion, readback and retirement order are checked.
|
||||
Resources remain valid for in-flight work and stale handles are rejected.
|
||||
- Bad descriptors, overflowing ranges, unsupported shader forms and invalid
|
||||
resource states fail before unsupported work reaches Metal.
|
||||
- The report records device capability queries, validation settings, candidate,
|
||||
commands and hardware. Synthetic gfx1030 success is not Xbox GPU verification.
|
||||
|
||||
**Outcome:** one original guest workload updates a texture and geometry, submits
|
||||
translated rendering, waits for completion and produces an independently checked
|
||||
frame through the existing native Metal backend.
|
||||
**Contributor work:** [resource-update workload #147](https://github.com/MacosPorters/betterxen/issues/147),
|
||||
[shared lifetime #148](https://github.com/MacosPorters/betterxen/issues/148),
|
||||
[fences #224](https://github.com/MacosPorters/betterxen/issues/224), and
|
||||
[format inventory #260](https://github.com/MacosPorters/betterxen/issues/260).
|
||||
Respect the active format claim; do not duplicate its inventory.
|
||||
|
||||
Start with a bounded scene and its concrete missing features. Do not make all
|
||||
RDNA2 instructions, mesh shaders or ray tracing prerequisites for a first scene.
|
||||
Reuse the semantic registry and distinguish declared, decoded, lowered,
|
||||
reference-tested, locally GPU-tested and independently accepted forms.
|
||||
## Phase 4 — Run an original interactive application
|
||||
|
||||
Coordinate [RDNA2 expansion #205](https://github.com/MacosPorters/betterxen/issues/205),
|
||||
[mip footprints #241 / PR #278](https://github.com/MacosPorters/betterxen/pull/278),
|
||||
[graphics fences #224](https://github.com/MacosPorters/betterxen/issues/224),
|
||||
[shared resource lifetime #148](https://github.com/MacosPorters/betterxen/issues/148),
|
||||
and [texture-update workload #147](https://github.com/MacosPorters/betterxen/issues/147).
|
||||
Wave divergence, cross-lane operations and additional formats get separate
|
||||
fixture contracts and claims when this workload needs them.
|
||||
**Deliverable:** one small original game-like application runs through the guest
|
||||
CPU/runtime and native app with translated graphics, scripted input, bounded
|
||||
audio and a save/load cycle in a persistent session.
|
||||
|
||||
**Exit criteria:** actual Metal execution and frame readback against an
|
||||
independently derived expectation; update/submission/retirement order is checked;
|
||||
invalid descriptors, stale handles and unsupported shader forms fail explicitly.
|
||||
Record host capability detection, hardware, validation settings and evidence
|
||||
class. Test counts and tolerances retain their existing definitions. Results
|
||||
remain synthetic desktop-gfx1030 evidence, never Xbox hardware verification.
|
||||
Compose the admitted paths from phases 2 and 3. Define the application source,
|
||||
input replay, frame checkpoints, sample-data checks and save format before
|
||||
implementation. Start with the CPU/shader subset already justified by the scene.
|
||||
Add C++ or additional runtime functionality only when an original failing
|
||||
fixture demonstrates the requirement and linked runtime terms are reviewed.
|
||||
|
||||
## Phase 5 — Run one integrated interactive application reliably
|
||||
Wire the application through the existing Swift/Rust interface and worker
|
||||
lifecycle. Existing native audio, controller and filesystem demonstrations are
|
||||
components, not proof that guest code reaches each service. This phase must
|
||||
exercise those guest connections in one session.
|
||||
|
||||
**Outcome:** a small, original application joins guest execution, rendering,
|
||||
input, bounded audio, filesystem access and lifecycle behavior in one session.
|
||||
**Completion checks:**
|
||||
|
||||
Start from [multi-module startup #256](https://github.com/MacosPorters/betterxen/issues/256)
|
||||
and the existing app/FFI fixtures. First prove a compiled workload can reach a
|
||||
checked frame. Add C++ language/runtime features only when an independently
|
||||
authored failing fixture demonstrates the need. Audit any linked runtime first.
|
||||
Do not treat the Swift audio/input demonstrations as guest integration evidence.
|
||||
- A deterministic replay reaches independently specified state/frame checkpoints.
|
||||
- Input reaches guest logic; expected audio samples are checked before device
|
||||
playback; save/load preserves specified state and reports I/O failures.
|
||||
- Start, pause, resume, stop, restart and worker failure have defined outcomes.
|
||||
Commands do not report success after a worker has failed.
|
||||
- Resource/handle counts and cleanup remain bounded across repeated sessions;
|
||||
invalid guest paths and resource requests fail according to the interface.
|
||||
- The native app/CLI provide a reproducible quick start and useful stage-specific
|
||||
failure reports. This fixture still establishes no commercial compatibility.
|
||||
|
||||
Coordinate [audio #227](https://github.com/MacosPorters/betterxen/issues/227),
|
||||
**Contributor work:** [audio #227](https://github.com/MacosPorters/betterxen/issues/227),
|
||||
[session errors #250](https://github.com/MacosPorters/betterxen/issues/250),
|
||||
[report schema #254](https://github.com/MacosPorters/betterxen/issues/254),
|
||||
[worker diagnostics #255](https://github.com/MacosPorters/betterxen/issues/255),
|
||||
and [application quick start #247](https://github.com/MacosPorters/betterxen/issues/247).
|
||||
Execution-admission changes remain owned by [issue #212](https://github.com/MacosPorters/betterxen/issues/212).
|
||||
[app CI #248](https://github.com/MacosPorters/betterxen/issues/248), and
|
||||
[quick start #247](https://github.com/MacosPorters/betterxen/issues/247).
|
||||
Execution-admission policy remains with
|
||||
[#212](https://github.com/MacosPorters/betterxen/issues/212).
|
||||
|
||||
**Exit criteria:** scripted input and deterministic checkpoints; start, pause,
|
||||
resume, stop and restart behavior; checked audio sample data before device
|
||||
playback; bounded memory and handle use; sandbox escape attempts rejected;
|
||||
useful failure reports and a repeatable soak protocol. Specify soak duration,
|
||||
resource limits and acceptance conditions before measuring. A fixture worker
|
||||
passing does not certify arbitrary files safe or commercial titles playable.
|
||||
## Phase 5 — Expand compatibility through a varied workload corpus
|
||||
|
||||
## Phase 6 — Improve measured bottlenecks
|
||||
**Deliverable:** a versioned set of original source-built workloads exercises
|
||||
meaningfully different CPU, runtime and graphics behavior through the integrated
|
||||
path, with precise accepted/rejected profiles and reproducible regressions.
|
||||
|
||||
**Outcome:** faster or lower-resource execution of workloads whose correctness
|
||||
is already checked, with measurements that another contributor can reproduce.
|
||||
Choose additions from actual failures. Examples include another compiler or
|
||||
runtime profile, vector-heavy arithmetic, runtime-dependent shader branches,
|
||||
bounded loops, multiple resource views and streaming texture updates. Each
|
||||
addition must demonstrate a gap not already owned by an existing task.
|
||||
|
||||
Performance analysis can begin earlier; changes must preserve the relevant
|
||||
phase's correctness. Select bottlenecks from actual measurements rather than
|
||||
assuming every shared-semantics call, allocation or cache miss needs replacement.
|
||||
Potential work includes CPU helper lowering, bounded translation-cache policy,
|
||||
Metal startup, texture transfers and frame-loop overhead.
|
||||
Use [CPU design #299](https://github.com/MacosPorters/betterxen/issues/299),
|
||||
[unwind design #300](https://github.com/MacosPorters/betterxen/issues/300),
|
||||
[runtime uniform branches #179](https://github.com/MacosPorters/betterxen/issues/179),
|
||||
[bounded shader loops #180](https://github.com/MacosPorters/betterxen/issues/180),
|
||||
and [RDNA2 expansion #205](https://github.com/MacosPorters/betterxen/issues/205).
|
||||
Wave divergence, cross-lane operations, local data share (LDS), barriers, mesh
|
||||
stages and ray tracing require their own public contracts, fixtures and native
|
||||
capability checks when a selected workload needs them.
|
||||
|
||||
Reuse [startup measurements #171 / PR #266](https://github.com/MacosPorters/betterxen/pull/266),
|
||||
[TLS optimization #107 / PR #284](https://github.com/MacosPorters/betterxen/pull/284),
|
||||
[DBT comparison #110 / PR #272](https://github.com/MacosPorters/betterxen/pull/272),
|
||||
and [conditional cache prewarming #258](https://github.com/MacosPorters/betterxen/issues/258).
|
||||
**Completion checks:**
|
||||
|
||||
**Exit criteria:** correctness gates pass on the changed candidate; baseline and
|
||||
candidate use equivalent inputs, toolchains, settings and hardware; idle-machine
|
||||
samples include variance and separate cold/warm startup. Report regressions as
|
||||
well as gains. Run validation-off benchmarks separately from validation-on GPU
|
||||
correctness. Capability differences across Apple Silicon generations remain
|
||||
unknown until measured; runtime detection controls optional paths.
|
||||
- Each workload identifies its source/build recipe, required forms/services,
|
||||
original expected outputs, limits and exact independently accepted candidate.
|
||||
- Coverage separates declared, decoded, lowered, CPU-tested, locally GPU-tested
|
||||
and independently accepted behavior. Compilation counts are not compatibility.
|
||||
- Unsupported behavior retains explicit diagnostic controls; expected values do
|
||||
not come from the same implementation being tested.
|
||||
- Targeted mutation/fuzz/regression checks demonstrate sensitivity to the changed
|
||||
behavior without altering tolerances, gate definitions or mutation counting.
|
||||
- Earlier integrated workloads still pass. Failures become bounded tasks with
|
||||
proposed files and dependencies, not a generic rewrite of a subsystem.
|
||||
|
||||
## Taking the next task
|
||||
**Contributor work:** [original corpus #150](https://github.com/MacosPorters/betterxen/issues/150),
|
||||
[shader acceptance #225](https://github.com/MacosPorters/betterxen/issues/225),
|
||||
CPU coverage #154 and the existing QA owner #219. Reuse their tools and acceptance
|
||||
rules; do not create another competing status or test framework.
|
||||
|
||||
Begin with Phase 1's evidence reconciliation and review Phase 2's existing PRs.
|
||||
The phase-plan issue does not claim their implementation files. Read every
|
||||
comment on a target issue and inspect linked PRs; never take a live claim.
|
||||
Issue #219's QA paths and subsystem owners remain independent of this plan.
|
||||
## Phase 6 — Sustain execution across Apple Silicon
|
||||
|
||||
Each implementation task needs a bounded outcome, permitted files, dependencies,
|
||||
public semantic sources, a failing fixture or other meaningful acceptance check,
|
||||
and the required independent reviewers. Use original code and expectations;
|
||||
never copy another emulator to satisfy a phase. Do not require a fixed number
|
||||
of agents: use available resources only within the repository's LOW-reasoning
|
||||
and independent-review rules.
|
||||
**Deliverable:** admitted workloads run for a specified duration under bounded
|
||||
memory/resource use, and performance/correctness reports are reproducible on
|
||||
the actual native hosts contributors test.
|
||||
|
||||
Useful existing commands for the candidate record:
|
||||
Specify soak duration, replay, resource limits and failure conditions before the
|
||||
run. Measure guest execution, translation, service calls, transfers, Metal
|
||||
startup, submission and readback to identify the actual bottleneck. Record
|
||||
cold/warm behavior, variance and regressions as well as improvements.
|
||||
|
||||
```sh
|
||||
PYTHONPATH=scripts python3 -m qa cpu-inventory --compact
|
||||
PYTHONPATH=scripts python3 -m qa runtime-inventory --compact
|
||||
PYTHONPATH=scripts python3 -m qa rdna2 reconcile --compact
|
||||
python3 scripts/audit/status.py --check
|
||||
scripts/audit/claims.sh
|
||||
scripts/audit/dependencies.sh
|
||||
```
|
||||
Use the existing native audit, GPU tests and benchmarks. Reuse merged startup
|
||||
measurements and DBT comparison tooling; evaluate prewarming/persistence only
|
||||
under [#258](https://github.com/MacosPorters/betterxen/issues/258) when measurements
|
||||
justify it. Guest code-cache lifetime and same-block executable writes remain
|
||||
explicit CPU correctness risks under #95 and #291.
|
||||
|
||||
For implementation, run the applicable checkout commands in `AGENTS.md` and the
|
||||
subsystem acceptance protocol. Keep logs under ignored `artifacts/`. Use at most
|
||||
four Cargo jobs across two CPU-heavy jobs, one GPU job and one fuzz or mutation
|
||||
campaign at a time. New verification must name the exact candidate; skipped
|
||||
tests never count as GPU evidence. Passing a phase does not authorize a release.
|
||||
**Completion checks:**
|
||||
|
||||
- The agreed soak/restart protocol passes on the pinned candidate with recorded
|
||||
resource accounting and no hidden fallback or silent loss of work.
|
||||
- Baseline/candidate measurements use equivalent inputs, toolchains, settings
|
||||
and hardware. Validation-on correctness and validation-off performance are
|
||||
separate runs; benchmarks use an idle host as required by the protocol.
|
||||
- [Native reports #303](https://github.com/MacosPorters/betterxen/issues/303)
|
||||
distinguish host binary architecture, documented capabilities, actual execution,
|
||||
failure, unavailable tools and skipped tests. Skips are never GPU passes.
|
||||
- Runtime capability detection selects optional paths. M1–M5/future-device cells
|
||||
stay unknown until actual reports exist; one machine cannot verify them all.
|
||||
- Contributor preview preparation follows app/native gates. Signing, notarization,
|
||||
redistribution review and publication require their own evidence and explicit
|
||||
release authorization; this phase does not authorize uploads.
|
||||
|
||||
**Contributor work:** [soak #149](https://github.com/MacosPorters/betterxen/issues/149),
|
||||
[memory pressure #204](https://github.com/MacosPorters/betterxen/issues/204),
|
||||
[dependency evidence #158](https://github.com/MacosPorters/betterxen/issues/158),
|
||||
and [preview preparation #259](https://github.com/MacosPorters/betterxen/issues/259).
|
||||
|
||||
## Phase 7 — Attempt documented Xbox compatibility
|
||||
|
||||
**Deliverable:** a separately reviewed compatibility experiment with admissible
|
||||
inputs demonstrates exactly the supported startup/execution/rendering stages,
|
||||
or records a specific unresolved contract that prevents the attempt.
|
||||
|
||||
Begin [public console-contract research #306](https://github.com/MacosPorters/betterxen/issues/306)
|
||||
now, alongside the earlier engineering phases. Maintain evidence for launch and
|
||||
CPU entry state, executable admission, service ABI, shader entry/bindings,
|
||||
resource and command layouts, synchronization and memory aliases. Public PE,
|
||||
AMD desktop ISA and D3D12 documents establish their documented contracts; they
|
||||
do not automatically establish Xbox behavior. Unknown console details remain
|
||||
unknown rather than becoming guessed implementations.
|
||||
|
||||
An actual execution attempt depends on demonstrated technical support for its
|
||||
input, project-permitted authorized/unprotected material, explicit admission
|
||||
and independent review. Do not obtain or use leaked executables, restricted
|
||||
SDKs, confidential headers, proprietary shader collections, firmware or keys;
|
||||
do not implement protection bypasses. A torrent filename or container does not
|
||||
establish a supported executable, launch environment or compatibility result.
|
||||
User files stay outside the repository. File validation concerns technical
|
||||
compatibility and safety; it must not demand receipts, accounts or ownership
|
||||
provenance uploads.
|
||||
|
||||
**Completion checks:**
|
||||
|
||||
- Required contracts have precise public sources and repository evidence classes,
|
||||
or are visible blockers. Restricted/unavailable evidence is not bypassed.
|
||||
- The admitted input profile, candidate, runtime capabilities and expected
|
||||
outcomes are reviewed before execution and precisely bounded.
|
||||
- Actual results separately identify inspection, loading, entry, menu/frame,
|
||||
world simulation, interaction and sustained play. Reaching one does not
|
||||
certify the next; crashes and missing behavior remain in the report.
|
||||
- R1 audits evidence/provenance and R2 independently derives semantic expectations.
|
||||
BetterXen has no Xbox hardware access and must never claim such verification.
|
||||
- No game title is called supported or playable without a demonstrated repeatable
|
||||
result. No date, compatibility percentage or release follows from this plan.
|
||||
|
||||
This phase can remain blocked while earlier original workloads continue to
|
||||
improve. There is currently no demonstrated GTA VI execution in BetterXen.
|
||||
|
||||
## How contributors start
|
||||
|
||||
The [research tracker #298](https://github.com/MacosPorters/betterxen/issues/298)
|
||||
links the eight new bounded tasks #299–#306 and the existing work they depend on.
|
||||
The phase plan claims no implementation files. Research/design tasks can begin
|
||||
on their documented paths; production changes must coordinate subsystem owners
|
||||
and active claims. Read all comments, including imported archived claims, and
|
||||
inspect linked open PRs before claiming one issue in a plain reply.
|
||||
|
||||
Every task needs an outcome, proposed files, dependencies, public semantic
|
||||
sources, meaningful positive/negative checks and independent reviewers. Update
|
||||
the changelog for meaningful changes. Record candidate-specific results and raw
|
||||
logs under ignored `artifacts/`; distinguish implementation, local verification
|
||||
and independent acceptance. Preserve historical evidence and attribution.
|
||||
|
||||
Run the applicable commands from `AGENTS.md`. Across simultaneous work use at
|
||||
most four Cargo jobs across two CPU-heavy jobs, one GPU job and one fuzz or
|
||||
mutation campaign. Never count unrun or skipped checks as passes. No commit,
|
||||
push, merge or release is authorized by a phase or an issue claim.
|
||||
@@ -0,0 +1,357 @@
|
||||
# PortWatch review and a native macOS execution plan
|
||||
|
||||
Reviewed November 24, 2026 (America/Chicago). This is a public-documentation and
|
||||
source-boundary review, not a competitor execution campaign or independent
|
||||
acceptance. **BetterXen does not support commercial Xbox game execution.**
|
||||
|
||||
## Recommendation
|
||||
|
||||
Continue BetterXen as an original ARM64 runtime with its own x86-64 CPU
|
||||
translation and direct Metal backend. The Windows projects expose useful
|
||||
engineering questions, test structures and failure categories. Their code is
|
||||
not a drop-in native port. Do not fork a Windows emulator into this repository,
|
||||
replace the CPU with Rosetta, or add a Vulkan/Windows compatibility runtime.
|
||||
|
||||
The next useful result is an original compiled application that starts through
|
||||
a checked module/runtime path and reaches a translated, checked Metal frame.
|
||||
Broader vector instructions, thread lifecycle, binding metadata and console
|
||||
contracts must advance through explicit fixture-backed increments. Completing
|
||||
synthetic applications alone cannot prove Xbox compatibility.
|
||||
|
||||
## What was inspected
|
||||
|
||||
The tracker snapshot is [PortWatch 2cedf62a](https://github.com/4lwayz/portwatch-vi/blob/2cedf62a16b63697f096763ecb99b4c10d4dbccc/data/tracker.json),
|
||||
whose update timestamp is `2026-11-25T04:22:56.289Z` (November 24 locally).
|
||||
Its 35 efforts, 22 tools and 30 candidates were screened. One candidate repeats
|
||||
XCL. Three efforts have no public repository; seven repository endpoints were
|
||||
unavailable across the combined list. Available repositories were pinned to
|
||||
their observed default-branch commit; their metadata, README and public tree
|
||||
were used to classify target, host assumptions, lineage and evidence scope.
|
||||
The per-project tables below include every entry in these three lists: 85
|
||||
unique repository endpoints were checked, 78 available and seven unavailable.
|
||||
|
||||
This is not a line-by-line audit of every source file, proof of all contributor
|
||||
provenance, or a claim to understand unavailable/private code. No upstream
|
||||
project, setup script, Windows executable, game, shader corpus, asset collection,
|
||||
restricted SDK or decryption tool was run. Archive and protection-related entries
|
||||
were screened at metadata/README level only; no mirrored implementation or
|
||||
restricted payload was recovered. The tracker's flagged/ignored discovery/spam
|
||||
queues are not endorsed engineering candidates and were not imported.
|
||||
|
||||
Selected public architecture/status documentation was read more deeply for
|
||||
VIctory, VIctory-macOS, TuxBox, NativeX, SeriesX and XValkyrie; XSXEmu's README
|
||||
provides detailed admission, TLS and graphics boundaries. Those documents
|
||||
explain their own designs; they do not verify their claimed test/hardware results.
|
||||
The supplied `/so` website URL was unavailable to the web reader; the public,
|
||||
pinned repository data was accessible and matched the initial screened JSON.
|
||||
|
||||
BetterXen's working tree started at `f02eb2678e76e91876be5706ce91dca25dcc3017`
|
||||
with existing local documentation edits. Read-only `git fetch` found newer main
|
||||
[`b2654e93`](https://github.com/MacosPorters/betterxen/tree/b2654e93a42e74e29570183da1f31bb8cdc6f721).
|
||||
A separate ignored source snapshot was inspected without switching, resetting
|
||||
or merging the working tree. This distinction changes the hosted-C status.
|
||||
The documentation PR is based on the reviewed newer main revision and changes
|
||||
no runtime implementation.
|
||||
|
||||
## Why the PC results do not transfer directly
|
||||
|
||||
| Layer | Common PC approach described upstream | Native ARM64 BetterXen requirement |
|
||||
| --- | --- | --- |
|
||||
| CPU | Guest x86-64 runs on a matching x86-64 CPU; several projects require AVX2 | Decode/execute or translate each supported form, preserve precise state/faults, and advertise only satisfied guest features. |
|
||||
| Loader/runtime | Windows APIs or Wine/Proton supply much of PE startup, TLS, exceptions, threads, files and CRT behavior | Original checked guest memory, module lifecycle, service implementations, callback bridges and guest exception design. |
|
||||
| Graphics API | Console-facing objects dispatch onto desktop D3D12, sometimes through Vulkan | Explicit validated guest handles/commands and native Metal objects, lifetime, resource state and completion. |
|
||||
| Shaders | RDNA machine code becomes HLSL/DXIL or SPIR-V | Independently verified RDNA-to-IR-to-MSL behavior, entry state and resource bindings. SPIR-V may be an intermediate, not a Vulkan runtime requirement. |
|
||||
| Assets | Title supplies its own loaders or tools convert game-specific data | No need to become an archive viewer to prove guest execution; codecs/layouts require public contracts and demonstrated workload needs. |
|
||||
| Evidence | README milestones, streams, screenshots, compilation counts or self-reported FPS | Pinned original fixtures, independent expectations, actual native execution/readback and candidate-specific receipts. |
|
||||
|
||||
PortWatch is a discovery/editorial service. Its percentages are not compatibility
|
||||
measurements. The observed entries label their verification self-reported;
|
||||
phrases such as “confirmed” inside editorial summaries do not become BetterXen
|
||||
acceptance. Several forks share VIctory/XCL/Leonida lineage: ten forks are not
|
||||
ten independent confirmations. Compilation, shader validation, first pixels,
|
||||
scene completeness, interactive progress and stable play are distinct outcomes.
|
||||
|
||||
## macOS efforts and what “native” means here
|
||||
|
||||
[VIctory-macOS edba53dd](https://github.com/pragyaangaur/VIctory-macOS/blob/edba53ddc2207e6c537679f4ce06f966b7a63a59/README.md)
|
||||
uses Rosetta, CrossOver Wine and D3DMetal for the guest route. Native builds of
|
||||
its portable crates are a different result. Its reported passing tests neither
|
||||
establish a fully ARM64 runtime nor demonstrate playable game execution here.
|
||||
Its [port notes](https://github.com/pragyaangaur/VIctory-macOS/blob/edba53ddc2207e6c537679f4ce06f966b7a63a59/docs/macos.md)
|
||||
provide leads for cache identity, upload visibility, floating-point edge cases,
|
||||
capability/behavior mismatches and masked-store page faults. Reproduce relevant
|
||||
questions with original Metal/CPU fixtures; do not copy its workarounds or assume
|
||||
a D3DMetal defect exists in BetterXen's direct Metal path.
|
||||
|
||||
[XSXEmu 2d937f83](https://github.com/daeken/XSXEmu/blob/2d937f8360fbcdac368a0e363c24df322fa24db2/README.md)
|
||||
is another macOS effort, so “nobody is working on Mac” would be inaccurate.
|
||||
Its guest path uses an x86-64 Mach-O process and Rosetta, while owned shader
|
||||
translation fixtures use Metal. It explicitly separates static audit from
|
||||
execution admission and says no game frame has been produced. Its useful
|
||||
lesson is that entry/binding information and DLL/TLS lifecycle are separate
|
||||
contracts; its Rosetta guest route does not satisfy BetterXen's ARM64 rule.
|
||||
|
||||
[6stars 480d9a4d](https://github.com/meetox80/6stars/blob/480d9a4d00ed11560f7b4d989643723a0f5c451c/README.md)
|
||||
and the separately listed 6stars engine candidate describe Swift/Metal world-data
|
||||
rendering. An independent renderer may produce a convincing scene while never
|
||||
executing the original game program. That is valuable work with a different
|
||||
scope. No verified reusable component or file-level license clearance was
|
||||
established by this review.
|
||||
|
||||
[nativ64 3b826108](https://github.com/Ybucaille/nativ64/blob/3b82610882bc55cb27f0ec563c126a226855a8ea/README.md)
|
||||
targets Linux x86-64. Its central observation is relevant: host Windows APIs
|
||||
that a Windows project forwards still need implementation on a different OS.
|
||||
Its Linux syscalls/futexes and x64 ABI are not native Darwin ARM64 services.
|
||||
BetterXen should prioritize from its own import/fixture failures, not copy that
|
||||
project's title-specific API totals or implementation.
|
||||
|
||||
## BetterXen's actual starting point
|
||||
|
||||
| Area | Observed on current main b2654e93 | Consequence |
|
||||
| --- | --- | --- |
|
||||
| CPU inventory | 498 declared forms, 213 operations; tool classifies 93 operations native and 120 shared-semantics | These are inventory/lowering categories, not 498 independently accepted instructions or a compatibility percentage. VEX remains rejected. |
|
||||
| Typed runtime registry | 47 services: 7 implemented, 37 partial, 3 stubs; tool reports 0 verified entries | This is the typed subset, not the total handwritten runtime. Named exports alone do not prove behavior. |
|
||||
| Hosted C | A1 and A2 are present; PR #283 merged as d26af53c. Gate A records local passes awaiting independent review | Do not open another “implement hosted C” issue. Reproduce/accept the candidate and expand from a failing original workload. |
|
||||
| Modules | startup.rs accepts one image; modules.rs exposes built-in service modules | Built-in LoadLibrary/GetProcAddress is not general EXE plus guest-DLL startup and teardown. |
|
||||
| Threads | Deterministic serial guest scheduler with worker stacks/TEBs, waits and handles | Sleep can stall all workers; static worker TLS and thread/FLS callbacks remain documented gaps. Serial scheduling does not prove parallel x86 memory ordering. |
|
||||
| Graphics | Translated image_sample_lz pixel stage, native texture tests and guest descriptor-table bindings already exist | The inspected README's former X10 description understated this bounded path; the replacement roadmap removes that stale planning row. Broader bindings, control flow and sampling still need contracts. |
|
||||
| Shader inventory | Table records 1,465 identified forms, 189 decoded, 185 IR/MSL, 18 accepted Metal forms; reconciliation finds zero mismatches | Different domains and acceptance stages must stay separate. The compute inventory does not fully describe graphics-only sampling. #225 owns pending acceptance. |
|
||||
| Texture/resource work | Packed BC footprints and bounded private texture staging merged; original resource/draw tests exist | Reuse them. Do not duplicate #260's active format inventory or assume guest/console integration from host upload success. |
|
||||
| Native app | Existing Swift/FFI fixtures; app/CI and usability PRs remain separate | UI/audio/input fixtures are not one integrated compiled guest application. #256 is the existing integration task. |
|
||||
| Console contract | Public AMD desktop ISA/PE/D3D12 documentation and explicit synthetic ABIs | Authentic launch, descriptors/commands and console-specific behavior remain unknown or unverified. No Xbox hardware access exists. |
|
||||
|
||||
Evidence for these boundaries: current-main
|
||||
[CPU registry](https://github.com/MacosPorters/betterxen/blob/b2654e93a42e74e29570183da1f31bb8cdc6f721/docs/cpu/instruction-registry.md),
|
||||
[Gate A](https://github.com/MacosPorters/betterxen/blob/b2654e93a42e74e29570183da1f31bb8cdc6f721/docs/testing/gate-a.md),
|
||||
[startup](https://github.com/MacosPorters/betterxen/blob/b2654e93a42e74e29570183da1f31bb8cdc6f721/crates/loader/src/startup.rs),
|
||||
[module services](https://github.com/MacosPorters/betterxen/blob/b2654e93a42e74e29570183da1f31bb8cdc6f721/crates/loader/src/services/modules.rs),
|
||||
[threads](https://github.com/MacosPorters/betterxen/blob/b2654e93a42e74e29570183da1f31bb8cdc6f721/docs/runtime/threads.md),
|
||||
[graphics compiler](https://github.com/MacosPorters/betterxen/blob/b2654e93a42e74e29570183da1f31bb8cdc6f721/crates/shader/src/graphics.rs),
|
||||
and [semantic coverage](https://github.com/MacosPorters/betterxen/blob/b2654e93a42e74e29570183da1f31bb8cdc6f721/docs/shaders/semantic-coverage.md).
|
||||
These are source/inventory observations. Historical hardware results retain
|
||||
their existing class A scope; none was rerun or independently certified here.
|
||||
|
||||
## What to take forward
|
||||
|
||||
Take **questions and test designs**, then implement independently from primary
|
||||
sources. No emulator source was copied, ported, translated, vendored or adapted.
|
||||
Repository-level license labels below are metadata only. They do not establish
|
||||
per-file grants, GPL-3.0-or-later compatibility or rights to fixtures/data.
|
||||
|
||||
1. Build a small, falsifiable workload before expanding an entire subsystem.
|
||||
TuxBox/NativeX-style separation of loader, ABI, GPU and presentation tests is
|
||||
useful; their own expected outputs cannot become BetterXen's oracle.
|
||||
2. Treat unresolved host services as a concrete inventory. Reuse #211's package
|
||||
census, #254's report schema and #255's startup diagnostics. Keep unsupported
|
||||
calls explicit; never return success merely to get farther.
|
||||
3. Model CPU state and faults before optimizing translation. AVX/YMM, masked
|
||||
memory accesses, unwinding and lifecycle cannot be supplied by ARM64 host
|
||||
calling conventions or a renamed Windows DLL.
|
||||
4. Make shader entry state, resources and pipeline identity explicit. A shader
|
||||
can compile and still read the wrong descriptor or run under the wrong mask.
|
||||
A replaced/skipped shader or an empty draw cannot pass a correctness gate.
|
||||
5. Validate resource ownership and completion before pursuing zero-copy. Apple
|
||||
unified memory does not remove guest/host address translation, storage modes,
|
||||
alignment, cache visibility or in-flight lifetime requirements.
|
||||
6. Expand wave behavior, loops, mesh and ray tracing only as separate reviewed
|
||||
contracts. A first simple scene does not require all of them; future console
|
||||
workloads may. Do not infer optional Metal features from a product name.
|
||||
7. Measure startup/steady-state and correctness separately, with actual host
|
||||
receipts. Cache keys must cover full relevant identity; prewarming is an
|
||||
experiment under #258, not a prerequisite or promised performance win.
|
||||
|
||||
Primary semantic authorities are the [Intel SDM](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html),
|
||||
[public PE format](https://learn.microsoft.com/en-us/windows/win32/debug/pe-format),
|
||||
[Microsoft x64 exception handling](https://learn.microsoft.com/en-us/cpp/build/exception-handling-x64),
|
||||
[AMD ISA publications](https://gpuopen.com/amd-gpu-architecture-programming-documentation/),
|
||||
[public resource-binding specification](https://microsoft.github.io/DirectX-Specs/d3d/ResourceBinding.html),
|
||||
and [Apple Metal feature tables](https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf).
|
||||
Class B applies only to what the relevant public specification documents;
|
||||
applying desktop behavior to Xbox needs separate evidence (often C or U).
|
||||
Feature tables are documentation, not our execution evidence across M1–M5.
|
||||
|
||||
## Contributor work and dependencies
|
||||
|
||||
The review is tracked in [#298](https://github.com/MacosPorters/betterxen/issues/298).
|
||||
The new tasks below have bounded deliverables, proposed paths, public references,
|
||||
negative controls and acceptance limits. They are unclaimed implementation work.
|
||||
Design tasks can begin with public documentation; runtime changes must respect
|
||||
parent claims and shared-file ownership. Read every issue comment and linked PR
|
||||
before claiming. Do not claim several tasks in one comment.
|
||||
|
||||
| Priority/order | Work | Dependency and boundary |
|
||||
| --- | --- | --- |
|
||||
| First, research | [#299 AVX/AVX2 state and decode contract](https://github.com/MacosPorters/betterxen/issues/299) | Extends beyond existing #120–#124; keeps CPUID honest. No blanket AVX2 implementation claim. |
|
||||
| First, research | [#300 bounded AMD64 unwind](https://github.com/MacosPorters/betterxen/issues/300) | Separates metadata/stack walking from SEH and C++ exceptions; existing trap stubs remain. |
|
||||
| First, loader contract/fixtures | [#301 original EXE plus two-DLL startup](https://github.com/MacosPorters/betterxen/issues/301) | Reuses #211 census and supplies a prerequisite to #256. Production mapping changes are separately coordinated. |
|
||||
| First, GPU contract | [#302 shader entry and resource bindings](https://github.com/MacosPorters/betterxen/issues/302) | Builds on existing #226 sampling/table work; coordinates #205, #179, #180 and #224. |
|
||||
| First, QA design | [#303 native capability receipts](https://github.com/MacosPorters/betterxen/issues/303) | Reuses #254 schema, #248 app CI and #158 dependency evidence. No automatic fleet posting. |
|
||||
| Next, scheduler implementation | [#304 Sleep yields ready workers](https://github.com/MacosPorters/betterxen/issues/304) | Narrow #228 child; coordinate parent and runtime PRs before code edits. |
|
||||
| First, lifecycle design | [#305 worker static TLS and callbacks](https://github.com/MacosPorters/betterxen/issues/305) | Depends on module/scheduler contracts for production; no competing scheduler. |
|
||||
| Parallel, public research | [#306 console launch/graphics evidence ledger](https://github.com/MacosPorters/betterxen/issues/306) | Links existing public research; unknown console details remain blockers rather than guesses. |
|
||||
|
||||
Reuse existing tasks rather than adding duplicates: #179 runtime uniform
|
||||
branches, #180 bounded loops, #205 semantic expansion, #225 independent shader
|
||||
acceptance, #224 fences, #147 resource-update workload, #148 shared lifetime,
|
||||
#256 startup-to-frame integration, #260 format inventory, #247 quick start,
|
||||
#250 session errors, #254 compatibility reports and #255 worker diagnostics.
|
||||
PRs #293–#297 already cover app CI, CPU coverage, selection ordering, Open and
|
||||
texture inventory respectively. Runtime PRs #263/#290 overlap substantially;
|
||||
their author/maintainer must resolve them before new runtime edits. These
|
||||
references are destination-repository numbers, not imported source numbers.
|
||||
|
||||
The replacement [development phases](../development-phases.md) define the sole
|
||||
active work order, from compiled guest boot through modular workers, a
|
||||
guest-controlled Metal scene, an interactive application, a compatibility
|
||||
corpus, sustained native execution and conditional Xbox experiments.
|
||||
Hosted C is implemented on inspected main, awaiting independent acceptance;
|
||||
it is no longer an untouched prerequisite. Original integration, then measured
|
||||
optimization, then only evidence-admissible compatibility experiments is the
|
||||
path. There is no supported date or estimate for running a commercial game.
|
||||
|
||||
## Complete project screen
|
||||
|
||||
Each pin links to the exact README reviewed. “Unavailable” means that the
|
||||
observed public GitHub endpoint returned 404; it does not prove why or justify
|
||||
looking for restricted mirrors. “Unresolved” licenses and NOASSERTION are not
|
||||
reuse permission. Descriptions below classify documentation, not executed code.
|
||||
|
||||
### Tracker efforts (35)
|
||||
|
||||
| Entry | Pinned public documentation | Classification and BetterXen decision |
|
||||
| --- | --- | --- |
|
||||
| ZETTROX (`Zettrox/ztrx`) | [`90b529f8`](https://github.com/Zettrox/ztrx/blob/90b529f878a470fec9bf07b7be316bc769a12232/README.md); license metadata: `GPL-3.0` | VIctory/victory-fork lineage; Windows x64 + D3D12. Hardware tuning and reported gameplay are not independent native-Mac evidence. |
|
||||
| Uilian (`uiliannn/VItoriaBr`) | [`c2485475`](https://github.com/uiliannn/VItoriaBr/blob/c24854750132af24c10e954765047525e0249bd3/README.md); license metadata: `GPL-3.0` | VIctory-family Windows/DXIL fork; README and tracker differ on readiness. Keep results self-reported; no ARM64 execution path. |
|
||||
| suri | No public repository in tracker | Private/stream report only; no implementation inspection or reproducibility. No source/fixture reuse proposed. |
|
||||
| omonkey | No public repository in tracker | Private/stream report only; no implementation inspection or reproducibility. No source/fixture reuse proposed. |
|
||||
| CGBJ | No public repository in tracker | Private/stream report only; no implementation inspection or reproducibility. No source/fixture reuse proposed. |
|
||||
| hyphennn (`fxceless/victory-fork`) | [`310c6eb6`](https://github.com/fxceless/victory-fork/blob/310c6eb6c16822ab95076aad61fce19bba86bb98/README.md); license metadata: `GPL-3.0` | VIctory rendering fork, Windows x64/D3D12; useful failure categories include bindings and mesh work. No implementation reuse. |
|
||||
| VIctory (`Marvisak/VIctory`) | [`940d32f6`](https://github.com/Marvisak/VIctory/blob/940d32f69b22265690a0b5a15d6ded572ba33baf/README.md); license metadata: `GPL-3.0` | Windows x64 direct guest execution, HLE and D3D12/DXIL. Public architecture documents host pass-through and title-specific work. |
|
||||
| xbox-emulator (`omonkeyz/xbox-emulator`) | [`f89e4106`](https://github.com/omonkeyz/xbox-emulator/blob/f89e4106fe8a1728515afa34ceb5097132cadcda/README.md); license metadata: `GPL-3.0` | TomBox continuation; Windows-process runtime and RDNA shader work. README title reports are unverified here; assets/captures are excluded. |
|
||||
| XCL (`xcl-dev/xcl`) | [`f5c5bdf0`](https://github.com/xcl-dev/xcl/blob/f5c5bdf0e91035f8f1404f46f4f2f7aedc259e7f/README.md); license metadata: `GPL-2.0` | Windows x64 direct execution plus D3D12/DXIL; host services and pipeline behavior matter. GPL-2.0-only README; no reuse clearance. |
|
||||
| ScarlettX (`Freminet/ScarlettX`) | [`01c642cf`](https://github.com/Freminet/ScarlettX/blob/01c642cf62a6d9978f535e2c438c488ebcb4cd39/README.md); license metadata: `unresolved` | Windows x64 HLE/D3D12; separates console precompiled-shader gaps from desktop paths. Console-binary-derived findings need independent public evidence. |
|
||||
| TuxBox (`brcly/TuxBox`) | [`97b8ad31`](https://github.com/brcly/TuxBox/blob/97b8ad3192def18d491fe72ea3a55e204bc77a5d/README.md); license metadata: `Apache-2.0` | x86-64 Windows and Linux/Proton; owned guest fixtures and provider-specific failures are useful testing patterns, not an ARM64 solution. |
|
||||
| americas-recomp (`realdody/americas-recomp`) | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
|
||||
| Leonida (`ItsNotRexed/Leonida`) | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
|
||||
| OpenScarlett (`californiaAlmonds/OpenScarlett`) | [`022a8b25`](https://github.com/californiaAlmonds/OpenScarlett/blob/022a8b25148cc08412df8ac7e752b9efed4cd819/README.md); license metadata: `MIT` | Windows x64, D3D12/Vulkan; broad completeness claims are upstream reports. Public-spec-backed original fixtures are the only proposed transfer. |
|
||||
| scarlett-layer (`jadeowaowa/scarlett-layer`) | [`0e436b3e`](https://github.com/jadeowaowa/scarlett-layer/blob/0e436b3e1c654765b193c1cb705918fbf101b10b/README.md); license metadata: `Apache-2.0` | Windows import interception/shims, D3D12 and synthetic test tiers; useful distinction between desktop samples and console compatibility. |
|
||||
| Xbox2Windows (`R0Y00/Xbox2Windows`) | [`ab9a020c`](https://github.com/R0Y00/Xbox2Windows/blob/ab9a020c0783f9ce1dd10876cbeb119707b9ada9/README.md); license metadata: `MIT` | x64-to-C++ AOT/loader and DXIL research; distinguishes modified diagnostic startup from original executable compatibility. Host ABI still differs. |
|
||||
| AnyXboxX (`LooperSalty/AnyXboxX`) | [`b92a71b9`](https://github.com/LooperSalty/AnyXboxX/blob/b92a71b9308e76f8ec9059c01d6e18f21611dc20/README.md); license metadata: `GPL-3.0` | Unicorn research and native Windows routes; current README also uses VIctory lineage. Do not treat its older interpreter label as ARM64 readiness. |
|
||||
| XValkyrie (`sammwyy/xvalkyrie`) | [`c4c04970`](https://github.com/sammwyy/xvalkyrie/blob/c4c04970930d029a25622743e3ff4ef873ac17a6/README.md); license metadata: `GPL-3.0` | Windows x64 console API and shader translation; useful subsystem boundaries. Console/title-specific ABI claims remain unverified. |
|
||||
| GTAVI-Recomp (`JamesCicada/GTAVI-Recomp`) | [`71766d8b`](https://github.com/JamesCicada/GTAVI-Recomp/blob/71766d8b5c669bc44639ad85bfd84edd8337c75a/README.md); license metadata: `GPL-2.0` | PS5/AnyPS5 route, not an Xbox launch contract; do not adapt emulator source or transfer PS5 APIs to Series. |
|
||||
| AnyXboxSeries (`edupode/anyxboxseries`) | [`9ca2d053`](https://github.com/edupode/anyxboxseries/blob/9ca2d05329fe878db6abea6060889f9a95566719/README.md); license metadata: `NOASSERTION` | Windows D3D12 loader/inspection and an original sample; sample presentation does not establish Xbox guest execution. |
|
||||
| SCARAB (`p-portela/SCARAB`) | [`8140e0be`](https://github.com/p-portela/SCARAB/blob/8140e0be4908499a5c4381eb4532410f05e39369/README.md); license metadata: `GPL-3.0` | Windows/D3D12 bridge, Linux through vkd3d-proton; memory/presentation incompleteness is explicit. Not native ARM64. |
|
||||
| AnyBox (`Dark3581/AnyBox`) | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
|
||||
| PercyScarlett (`rpatty-dev/PercyScarlett`) | [`64719f96`](https://github.com/rpatty-dev/PercyScarlett/blob/64719f96d32f74d9d68cec69243b515ba675741f/README.md); license metadata: `GPL-2.0` | Windows x64/D3D12; README distinguishes existing DXIL titles from RDNA lifting and reports instability. GPL-2.0-only; no reuse. |
|
||||
| GrandTheftXbox (`zohaiblazuli/GrandTheftXbox`) | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
|
||||
| Scarlett Windows Compat (`ProhorovIlja/NativeX-Runtime`) | [`b3087ce0`](https://github.com/ProhorovIlja/NativeX-Runtime/blob/b3087ce0ab191227dc9e7af37cab97a0b097bb98/README.md); license metadata: `MIT` | Portable inspection and separate Windows/Linux ABI/graphics probes. Useful test decomposition; not a complete application runtime. |
|
||||
| DedSec (`Hylanderry/DedSec`) | [`c44b38ca`](https://github.com/Hylanderry/DedSec/blob/c44b38ca0207900cd27c687bb9213a6c8474bc69/README.md); license metadata: `MIT` | Windows x64/direct execution and D3D12; performance/feature claims need reproducible evidence. No Mac execution established. |
|
||||
| Xbgtasix (`ljm-233/Xbgtasix`) | [`1a767872`](https://github.com/ljm-233/Xbgtasix/blob/1a7678729cd436f9adaa9772b76d97af3d292321/README.md); license metadata: `GPL-3.0` | Windows compatibility DLLs rely on the Windows loader for imports, relocation and TLS. This omitted host work is required on Darwin. |
|
||||
| SeriesX Emulator (`anrq0/SeriesX-Emulator`) | [`4f07d76f`](https://github.com/anrq0/SeriesX-Emulator/blob/4f07d76f9f641ce85ce4238081c06d1cef1b7521/README.md); license metadata: `MIT` | Interpreter, original test applications and desktop launcher; README explicitly excludes commercial compatibility. Reported vectors are not our oracle. |
|
||||
| GTA6-COMPAT-LAYER (ScarlettCompat) (`SSTGxf/ScarlettCompat`) | [`b92f060b`](https://github.com/SSTGxf/ScarlettCompat/blob/b92f060b1754580338dc30f57bb50777af38749d/README.md); license metadata: `MIT` | Windows native loader and console shims. Diagnostic bootstrap is a useful stage model; passing imports is not an implemented API. |
|
||||
| XlaunchVI (`JPTuba9/xlaunch-vi`) | [`40feebd7`](https://github.com/JPTuba9/xlaunch-vi/blob/40feebd73a59c13ac5d65c3e61d21906111294e7/README.md); license metadata: `unresolved` | Windows x64, D3D12/Vulkan and frontend. README explicitly denies game compatibility; UI work is separate from guest execution. |
|
||||
| OpenScarlett (Community Edition) (`OpenCommunityEdition/OpenScarlett`) | [`d1285fdd`](https://github.com/OpenCommunityEdition/OpenScarlett/blob/d1285fddbe399927581a772f536239b33a1e2cf4/README.md); license metadata: `AGPL-3.0` | Windows/Linux API layer; README build requires GDKX. Do not follow restricted tooling dependencies or import its sources. |
|
||||
| Five Star Recomp (`ThatRecompDev/five-star-recomp`) | [`fb3b3a2d`](https://github.com/ThatRecompDev/five-star-recomp/blob/fb3b3a2def5af6eef6004c954c11f2cd22574168/README.md); license metadata: `GPL-3.0` | Windows platform, shader and asset tools; title startup claims do not establish a complete scene or native Mac execution. |
|
||||
| G6Recomp (`Kajcsi/G6Recomp`) | [`82ccaa5d`](https://github.com/Kajcsi/G6Recomp/blob/82ccaa5d4b3fdc1edb9cdd95c8dbab4ee7cde352/README.md); license metadata: `GPL-3.0` | Windows AVX2/direct-execution loader with fixture tests; static-recompilation name does not remove reliance on x64/Windows ABI. |
|
||||
| GTA6-BootTest (`OnlyMoisties/GTA6-BootTest`) | [`32683d8f`](https://github.com/OnlyMoisties/GTA6-BootTest/blob/32683d8fe2841bddeb0b437109e97bc32cf55724/README.md); license metadata: `unresolved` | Windows debugger/shim/GPU startup harness. Reported first UI frame is not full scene correctness; no root license identified by metadata. |
|
||||
| Palmetto (`luizwidmer/palmetto`) | [`6416a273`](https://github.com/luizwidmer/palmetto/blob/6416a273336599341dfd31e64cc3da3fd1b855ed/README.md); license metadata: `GPL-3.0` | Windows runtime and RDNA-to-SPIR-V/Vulkan path; behavior-stage reporting is useful, runtime/backend is incompatible with our target. |
|
||||
|
||||
### Tracker tools (22)
|
||||
|
||||
| Entry | Pinned public documentation | Classification and BetterXen decision |
|
||||
| --- | --- | --- |
|
||||
| `lynxnathan/rage-tools-vi` | [`547ee9ba`](https://github.com/lynxnathan/rage-tools-vi/blob/547ee9ba2dde236644a597cef65a18f7bd5549be/README.md); license metadata: `MIT` | Asset/catalog tooling; README mentions executable-derived information. No derived corpus imported; not a CPU/runtime shortcut. |
|
||||
| `fishingpvalues/gta6-pc-port-hub` | [`3a7d8d18`](https://github.com/fishingpvalues/gta6-pc-port-hub/blob/3a7d8d18f6fdc2071f8609f35153fb07ac25d1b5/README.md); license metadata: `CC0-1.0` | Archived coordination hub. Its missing-executable snapshot is historical, not evidence of current file availability or native compatibility. |
|
||||
| `holdmysocks/SixNG` | [`8897a1f6`](https://github.com/holdmysocks/SixNG/blob/8897a1f60c6700553987954f567d9146f898d882/README.md); license metadata: `GPL-3.0` | Asset exporter with explicit texture fallback limitations; fallback pixels must never become BetterXen correctness evidence. Defer format work to #260. |
|
||||
| `rpatty-dev/PercyStar` | [`ca4cd4c0`](https://github.com/rpatty-dev/PercyStar/blob/ca4cd4c09bb3a4e29cc2d33e69385725c5fb2220/README.md); license metadata: `NOASSERTION` | Asset/shader/media tools with custom attribution terms. macOS tooling does not establish guest execution or GPL-compatible reuse. |
|
||||
| `breadbbbb/rpf9-explorer` | [`cab9bb6e`](https://github.com/breadbbbb/rpf9-explorer/blob/cab9bb6ebe6d46fec6ac90ee5004bdd8cfd9e31a/README.md); license metadata: `unresolved` | Cross-platform asset viewer/exporter; root grant unresolved in metadata. Exclude code/assets; sample viewing is not guest execution. |
|
||||
| `Ahmet-Dedeler/bcpack-rs` | [`b1c3099a`](https://github.com/Ahmet-Dedeler/bcpack-rs/blob/b1c3099a3402de8b76c9263a828791bd8bc0c930/README.md); license metadata: `NOASSERTION` | Texture codec research with reported synthetic tests; useful codec boundary, but exact tables/provenance/file licenses are unreviewed. Defer to #260. |
|
||||
| `nullbrik/RageForge` | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
|
||||
| `woreksami/ttpf-studio` | [`a2fe110d`](https://github.com/woreksami/ttpf-studio/blob/a2fe110d8e7aeb8ed3be37c365c75078a408c089/README.md); license metadata: `MIT` | Texture/archive/video tooling. No original executable execution; no proprietary payload or replacement asset imported. |
|
||||
| `walkthestars/GTA6-Asset-Info` | [`bad5bc21`](https://github.com/walkthestars/GTA6-Asset-Info/blob/bad5bc2180ade416eafdb50aa21e21eeec5adbda/README.md); license metadata: `GPL-3.0` | Asset-format notes for SixNG. Discovery only; derived samples/tables remain outside this review. |
|
||||
| `Ahmet-Dedeler/awesome-gta6-reverse-engineering` | [`34a6e945`](https://github.com/Ahmet-Dedeler/awesome-gta6-reverse-engineering/blob/34a6e945b9698975ccd4e0c2e039034914dcc278/README.md); license metadata: `NOASSERTION` | Discovery index. Linked tools, code and asset claims have separate provenance and terms; no linked payloads were obtained. |
|
||||
| `HolyRoses/gta6-explorer` | [`8e383a49`](https://github.com/HolyRoses/gta6-explorer/blob/8e383a49d07da5068fa30ebf208025e307018fcc/README.md); license metadata: `MIT` | Read-only package/asset inspection; not a guest runtime. No package bytes or format-derived corpus imported. |
|
||||
| `meetox80/6stars` | [`480d9a4d`](https://github.com/meetox80/6stars/blob/480d9a4d00ed11560f7b4d989643723a0f5c451c/README.md); license metadata: `unresolved` | Swift/Metal world-data renderer. Native graphics demonstration is a different objective from executing original Xbox CPU/shader code. |
|
||||
| `Ahmet-Dedeler/rage9-re` | [`30c6d215`](https://github.com/Ahmet-Dedeler/rage9-re/blob/30c6d2150ad9d3021802f509ff3ee232d466f499/README.md); license metadata: `NOASSERTION` | Animation/script asset-format tools, not executable compatibility. No asset samples or derived format tables imported. |
|
||||
| `Albotterin/AWC_from_RPF9_Extractor` | [`decfde54`](https://github.com/Albotterin/AWC_from_RPF9_Extractor/blob/decfde54243d9a982550b08c7db21c34a20a1775/README.md); license metadata: `MIT` | Audio extraction tooling with upstream dependency/license scopes. Does not implement guest audio APIs; no extracted audio or code reuse. |
|
||||
| `SentinelInteractive/0x52504639` | [`f1a383a7`](https://github.com/SentinelInteractive/0x52504639/blob/f1a383a72e90706b88d82f0ed1a674a0d7fcba58/README.md); license metadata: `MIT` | Format notes/catalogs, no execution evidence. Do not promote derived counts into console support. |
|
||||
| `JoshRob297/rpf9-research` | [`144d3451`](https://github.com/JoshRob297/rpf9-research/blob/144d345191bd37de3f6bd5e85df3e8ae8815552e/README.md); license metadata: `GPL-3.0` | Container research/catalogs; protected-index/key questions are outside BetterXen scope. No derived indexes imported. |
|
||||
| `Librett0/vice-lens` | [`8b8c8a84`](https://github.com/Librett0/vice-lens/blob/8b8c8a847ef926d8d6298ecfade142db19cfce5d/README.md); license metadata: `MIT` | Asset viewer/world renderer and media tooling; viewing a scene is not original-game execution. No asset/capture reuse. |
|
||||
| `batatinhafcbatatinha-pixel/xseriesrecomp` | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
|
||||
| `sub-north/xbox-hle-lab` | [`8863028b`](https://github.com/sub-north/xbox-hle-lab/blob/8863028b486dedf660303fcd3c756b05bbbebf91/README.md); license metadata: `MIT` | Separate original probes, docs and XCL patches with different license scopes. Useful falsifiable-reproduction discipline; no patch reuse. |
|
||||
| `kry-vex-gta/XBOX-Inspector` | [`0a3d067f`](https://github.com/kry-vex-gta/XBOX-Inspector/blob/0a3d067f7167a30b5e2517a4e781ec1ada3006d7/README.md); license metadata: `MIT` | Static inspection/recompilation prechecks. Metadata analysis is not guest execution; existing #211/#254 own comparable BetterXen work. |
|
||||
| `nineforge0/forge9` | [`f40381ca`](https://github.com/nineforge0/forge9/blob/f40381cac62ade007a62e728eaa988fd9677bec4/README.md); license metadata: `MIT` | README advertises decryption and executable-derived key/table workflow. Excluded from implementation/input research; no such code or inputs accessed. |
|
||||
| `TheoBIET/OpenVI` | [`fd415911`](https://github.com/TheoBIET/OpenVI/blob/fd4159118e750084451b9bad364169660daaa5e2/README.md); license metadata: `GPL-3.0` | Cross-platform asset explorer. macOS UI availability is not native emulation; no content or auto-update workflow executed. |
|
||||
|
||||
|
||||
### Tracker candidates (30, including repeated XCL)
|
||||
|
||||
| Entry | Pinned public documentation | Classification and BetterXen decision |
|
||||
| --- | --- | --- |
|
||||
| `edsuuu/VI-BR-PORT` | [`7a30f506`](https://github.com/edsuuu/VI-BR-PORT/blob/7a30f5063dafeda1ceab84d251c22dc581d4dfc6/README.md); license metadata: `GPL-3.0` | VIctory-family Windows/NVIDIA memory tuning; wave32 assumptions must not be transferred to Apple GPU capability claims. |
|
||||
| `xcl-dev/xcl` | [`f5c5bdf0`](https://github.com/xcl-dev/xcl/blob/f5c5bdf0e91035f8f1404f46f4f2f7aedc259e7f/README.md); license metadata: `GPL-2.0` | Windows x64 direct execution plus D3D12/DXIL; host services and pipeline behavior matter. GPL-2.0-only README; no reuse clearance. |
|
||||
| `ZigZagBoi1/ScarlettPort` | [`48ba23a9`](https://github.com/ZigZagBoi1/ScarlettPort/blob/48ba23a91a83121f8d0625a633e88fa463d5a0ca/README.md); license metadata: `NOASSERTION` | Windows x64/D3D12 compatibility route; no native Darwin CPU/runtime established. |
|
||||
| `Steinkoloss/port-of-the-americas` | [`0f3be36a`](https://github.com/Steinkoloss/port-of-the-americas/blob/0f3be36aaefe69c25f06e05222b88453f3557acd/README.md); license metadata: `unresolved` | Linux x64/Proton/vkd3d-proton shims; README names Leonida shader conversion. No implementation reuse. |
|
||||
| `Leucodermique/VIce` | [`8c7b24fd`](https://github.com/Leucodermique/VIce/blob/8c7b24fda90eb08fe64044726b7c880065a86ee0/README.md); license metadata: `GPL-3.0` | VIctory-based Windows distribution/frontend; consolidation does not independently validate combined changes. |
|
||||
| `flipflapov/DSTN` | [`7066ae66`](https://github.com/flipflapov/DSTN/blob/7066ae669c7b0e20d0b05675826169cdc7442883/README.md); license metadata: `GPL-3.0` | Leonida fork; tool portability on macOS does not establish native guest execution. No implementation reuse. |
|
||||
| `daeken/XSXEmu` | [`2d937f83`](https://github.com/daeken/XSXEmu/blob/2d937f8360fbcdac368a0e363c24df322fa24db2/README.md); license metadata: `MIT` | macOS Rust host with Rosetta guest execution and separate native Metal shader fixtures; not a fully ARM64 guest CPU path. No game frame claimed. |
|
||||
| `SixLauncher/VILauncher` | [`bf2f6ca9`](https://github.com/SixLauncher/VILauncher/blob/bf2f6ca9a6445aee6ebdff2b1cef87266f9cf1f4/README.md); license metadata: `GPL-3.0` | Linux launcher selecting VIctory/XCL under Wine/Proton. Not a new guest execution or Metal implementation. |
|
||||
| `4Sakens/Project-Kalaga` | [`56b41fb4`](https://github.com/4Sakens/Project-Kalaga/blob/56b41fb4a68b89e5e356c1445699ba4ac6b8cc83/README.md); license metadata: `unresolved` | Windows consolidation of existing efforts; aggregated subsystems and local paths are not independent compatibility evidence. |
|
||||
| `idvwork/rebox` | [`a833078e`](https://github.com/idvwork/rebox/blob/a833078e3366a70a74edef0cbfe01b80a81dd55c/README.md); license metadata: `GPL-2.0` | WineGDK/vkd3d-proton and AnyPS5 shader lineage; incompatible runtime and no emulator adaptation permitted. |
|
||||
| `Yhozen/series-web` | [`d7512b29`](https://github.com/Yhozen/series-web/blob/d7512b299fe2836e08783665308cd8c4bb924345/README.md); license metadata: `GPL-2.0` | PISCO AOT x86-to-WebAssembly/runtime research; original browser workloads differ from native ARM64/Metal and Xbox compatibility. |
|
||||
| `DesignWithTommy/Neonbridge` | [`954c00c5`](https://github.com/DesignWithTommy/Neonbridge/blob/954c00c506a8616e985e94e8ea6bcbfba7f80f48/README.md); license metadata: `GPL-3.0` | Windows VIctory-family launcher/runtime; frontend and startup improvements are not CPU translation for ARM64. |
|
||||
| `moonrelax/basalt` | [`8af09135`](https://github.com/moonrelax/basalt/blob/8af091350e0d5cdf89f3736a756235a72b67bea9/README.md); license metadata: `MIT` | Original interpreter/cooperative scheduler research; GPU objects are fake and no rendering is claimed. Do not reuse stubs as acceptance. |
|
||||
| `ka1qux/victory-ka1qux` | [`77b8a9eb`](https://github.com/ka1qux/victory-ka1qux/blob/77b8a9eb0d29521f34ffe6061530cc873090e844/README.md); license metadata: `GPL-3.0` | VIctory-family AMD Windows rendering fork. Vendor-specific counters and claimed fixes need independent original tests. |
|
||||
| `ethan00013/keylime` | [`361c7e94`](https://github.com/ethan00013/keylime/blob/361c7e94ab9d29d88cb1e5bfaadc8c3fb909bebc/README.md); license metadata: `GPL-3.0` | Windows x64 runtime with Vulkan/SPIR-V; no native Mac route. Backend and console-specific claims need independent contracts. |
|
||||
| `Joaco9020/mangrove` | [`d16326c6`](https://github.com/Joaco9020/mangrove/blob/d16326c652b6f82e7b59b390f63e37cab816acd3/README.md); license metadata: `GPL-3.0` | VIctory-family Windows fork tuned for lower-VRAM NVIDIA GPUs. Settings are not portable Metal correctness work. |
|
||||
| `chvabalo-interactive/sludgemu` | [`29cf795e`](https://github.com/chvabalo-interactive/sludgemu/blob/29cf795e23bb4917b9a8acd6be95d38a0f3b99b1/README.md); license metadata: `unresolved` | Windows direct guest execution and D3D12/DXIL, early startup with logging stubs. Stubs are not behavior support. |
|
||||
| `larpingvibecoder/sonoma` | [`835f386a`](https://github.com/larpingvibecoder/sonoma/blob/835f386a144eca0b903b8bec63c0a003d7e07071/README.md); license metadata: `Apache-2.0` | Windows Rust runtime/direct DXIL, early proof of concept; name does not indicate macOS support. |
|
||||
| `7jycwjmbfn-eng/scenegate-vi` | [`d5908947`](https://github.com/7jycwjmbfn-eng/scenegate-vi/blob/d590894710631a3c6adc6cca526c44d3c0c2bd41/README.md); license metadata: `MIT` | Windows/Vulkan startup and scene work based on Leonida; retain only documented failure categories, not code or title-derived inputs. |
|
||||
| `TaynanGT/victory-windows-anterior-20261125` | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
|
||||
| `TaynanGT/victory-windows` | [`cdcff8fe`](https://github.com/TaynanGT/victory-windows/blob/cdcff8fe96182bade41343a10b985c028e9e8968/README.md); license metadata: `GPL-3.0` | VIctory-family Windows work on a non-main default branch; pin the actual branch, not its name. |
|
||||
| `Archivist-Atlas/gta-vi-astral` | [`ff21332e`](https://github.com/Archivist-Atlas/gta-vi-astral/blob/ff21332e5ea2ea1c254a97c0b3036d36ff8e79ce/README.md); license metadata: `unresolved` | Go Windows runtime research citing VIctory/Leonida designs; no independent ARM64/Metal execution established. |
|
||||
| `airpiglabs/crouton` | [`faad29e6`](https://github.com/airpiglabs/crouton/blob/faad29e6af4c45804cfa8a42901341a52d9c824c/README.md); license metadata: `GPL-2.0` | XCL/Bathyal lineage, Windows then Wine/Proton; GPL-2.0-only and incompatible host/runtime route. |
|
||||
| `natedemoss/vice-pc` | [`2f98c053`](https://github.com/natedemoss/vice-pc/blob/2f98c05325237bc8ed8faf0e7b95bc0e6d22b9bb/README.md); license metadata: `MIT` | Windows loader proof of concept; README says nothing boots. No ARM64 or Metal evidence. |
|
||||
| `JoseArranzSanchez/GTA6_PCPORT_INFO` | [`585b42a1`](https://github.com/JoseArranzSanchez/GTA6_PCPORT_INFO/blob/585b42a184bf1cdf1a5f8e76e0d2e7f8a9102857/README.md); license metadata: `NOASSERTION` | Secondary feasibility report, not implementation or primary legal authority. No legal conclusions adopted from it. |
|
||||
| `DBWilliamEngineering/IraRationis` | [`67106e80`](https://github.com/DBWilliamEngineering/IraRationis/blob/67106e80ef34407f545b82bbd9b2c244f304ca3c/README.md); license metadata: `GPL-3.0` | C#/.NET AOT adaptation of ztrx; Windows x64 target remains. Review mixed license scopes if ever considering unrelated tooling. |
|
||||
| `Guernica4u/GTA6-PC-Port-Archive` | [`7b69fa54`](https://github.com/Guernica4u/GTA6-PC-Port-Archive/blob/7b69fa5430ae19fd013b0ba19ffbd7badf3b93e8/README.md); license metadata: `unresolved` | Archive of other projects. Metadata/README screen only; do not use it to recover unavailable or prohibited implementation/material. |
|
||||
| `idvwork/6stars-gta-vi-engine` | [`26a52ba2`](https://github.com/idvwork/6stars-gta-vi-engine/blob/26a52ba2ce5504c2c94a77c15838573538da5b70/README.md); license metadata: `unresolved` | Swift/Metal asset-world renderer, same stated approach as 6stars. Rendering data is distinct from executing the original guest; license/provenance unresolved. |
|
||||
| `Ybucaille/nativ64` | [`3b826108`](https://github.com/Ybucaille/nativ64/blob/3b82610882bc55cb27f0ec563c126a226855a8ea/README.md); license metadata: `Apache-2.0` | Linux x86-64 Windows-API replacement library, not CPU translation. Its host-API inventory explains native-port work hidden by Windows pass-through. |
|
||||
| `sleep10dev/XPORT` | [`2baf2a0f`](https://github.com/sleep10dev/XPORT/blob/2baf2a0f7c2af9f031158e082dfc4a6bb5b8266c/README.md); license metadata: `GPL-3.0` | Windows Rust loader/HLE/partial RDNA/D3D12 research, no demonstrated game compatibility. |
|
||||
|
||||
|
||||
### Explicitly supplied Mac project and tracker
|
||||
|
||||
| Project | Pin | Decision |
|
||||
| --- | --- | --- |
|
||||
| `pragyaangaur/VIctory-macOS` | [`edba53dd`](https://github.com/pragyaangaur/VIctory-macOS/blob/edba53ddc2207e6c537679f4ce06f966b7a63a59/README.md); license metadata: `GPL-3.0` | Wine/CrossOver + Rosetta + D3DMetal guest route. Native platform unit tests are distinct from Windows-under-Wine GPU tests. |
|
||||
| `4lwayz/portwatch-vi` | [`2cedf62a`](https://github.com/4lwayz/portwatch-vi/blob/2cedf62a16b63697f096763ecb99b4c10d4dbccc/README.md); license metadata: `unresolved` | Editorial discovery site and JSON data, not an emulator. Scores and live-stream summaries are not independent acceptance. |
|
||||
|
||||
## Verification performed and remaining limits
|
||||
|
||||
Read-only inventories ran for both the working-tree baseline and the extracted
|
||||
current-main snapshot. Working-tree CPU/runtime counts were 491 forms/206
|
||||
operations and 20 typed services; current main reports 498/213 and 47. Shader
|
||||
reconciliation reported zero mismatches for both. These checks inspect catalogs;
|
||||
they are not CPU instruction execution, GPU tests or independent acceptance.
|
||||
|
||||
Documentation checks also ran successfully on the working-tree candidate:
|
||||
`python3 scripts/audit/status.py --check`, `scripts/audit/claims.sh` (22 claims),
|
||||
`scripts/audit/dependencies.sh` (five graphics crates), Markdown local-file link
|
||||
checks and `git diff --check`. These audit results do not verify runtime changes
|
||||
present only on the separately inspected newer main snapshot.
|
||||
|
||||
Research metadata and ignored raw documentation are retained locally under
|
||||
`artifacts/research-portwatch/`. GitHub API reads and issue/PR state checks
|
||||
establish accessibility and observed state. Python HTTPS initially failed
|
||||
certificate verification; authenticated `gh api` reads succeeded without
|
||||
turning off certificate checks. No dependency was installed to work around it.
|
||||
|
||||
No Rust build, CPU execution suite, native GPU test, demo, fuzz, mutation or
|
||||
benchmark ran for this documentation task. New acceptance must use the exact
|
||||
candidate, actual native tool architecture and actual eligible hardware.
|
||||
Independent reviewers have not certified this report's proposed implementations.
|
||||
The research stage installed or executed no upstream project or game content.
|
||||
Documentation publication and the GitHub research/follow-up issues were requested
|
||||
by the user; their delivery status is recorded in the linked PR/tracker. No
|
||||
runtime merge, release or compatibility acceptance is implied.
|
||||
@@ -1,5 +1,6 @@
|
||||
# Testing and acceptance
|
||||
|
||||
- [Migrated pull-request integration review](migration-pr-review.md) — Merge decisions, fixes, native verification and remaining scope limits.
|
||||
- [AMD RDNA2 desktop GPU (gfx1030) form acceptance](shader-form-acceptance.md) — Rule and evidence required to promote a form from local results to `fixture verified`.
|
||||
- [Test inventory comparison](test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
|
||||
- [Persistent resource and translated rendering acceptance](x9-acceptance.md) — Native ARM64 results and unsupported cases.
|
||||
|
||||
@@ -76,6 +76,88 @@ cargo build --release -p xenora-benchmarks
|
||||
MTL_DEBUG_LAYER=0 MTL_SHADER_VALIDATION=0 ./target/release/xenora-bench --reps 7
|
||||
```
|
||||
|
||||
## Startup distributions
|
||||
|
||||
`xenora-bench startup` measures what it costs to get one fixture result from
|
||||
Metal, in two regimes:
|
||||
|
||||
- **Fresh process.** The harness launches its own executable `--processes`
|
||||
times (default 30), one after another. Each child creates the Metal device and
|
||||
queue, translates the fixture, runs it once and checks the output.
|
||||
- **Repeated.** The harness process creates one device, runs the fixture once
|
||||
(reported as *first in process*), then translates and runs it `--reps` more
|
||||
times (default 100).
|
||||
|
||||
The fixture is the first one in `benchmarks/manifest.toml` unless `--fixture`
|
||||
names another, at its smallest declared size unless `--words` sets one. The
|
||||
independent reference must agree with the hand-derived expected values first,
|
||||
and every sample in both regimes must produce the expected words. A wrong
|
||||
output, a child that fails or does not exit within 60 seconds, or a damaged
|
||||
sample line stops the run before anything is written.
|
||||
|
||||
| Phase | Source | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `spawn_to_main` | wall clock, parent before spawn to child `main` | Process launch and Rust runtime start (fresh only) |
|
||||
| `device` | host monotonic clock | `NativeCompute::new`: device and queue (fresh, and once in the repeated process) |
|
||||
| `translate` | host monotonic clock | Read the fixture and run `xenora-shader::compile` |
|
||||
| `library` | `RunProfile` | `newLibraryWithSource` |
|
||||
| `pipeline` | `RunProfile` | Compute pipeline state creation |
|
||||
| `submit` | `RunProfile` | `host` minus `library` and `pipeline`: buffers, encode, commit, wait |
|
||||
| `gpu` | `GPUEndTime - GPUStartTime` | Command-buffer GPU execution |
|
||||
| `readback` | `RunProfile` | Copy the output words back |
|
||||
| process wall | host monotonic clock in the parent | Spawn to exit of one fresh child |
|
||||
|
||||
The report gives median, p90, p99 and maximum per phase. Percentiles
|
||||
interpolate linearly, so with 30 processes p99 lies between the two largest
|
||||
samples. `startup.json` also keeps every fresh sample in launch order.
|
||||
Children inherit the parent's environment, so the `MTL_*` validation values in
|
||||
`metadata.json` apply to both regimes. Results go to the ignored
|
||||
`artifacts/startup/<hardware>/<run-id>/` unless `--output` says otherwise.
|
||||
|
||||
```sh
|
||||
cargo build --release -p xenora-benchmarks
|
||||
MTL_DEBUG_LAYER=0 MTL_SHADER_VALIDATION=0 ./target/release/xenora-bench startup
|
||||
```
|
||||
|
||||
### Recorded run
|
||||
|
||||
This is the imported contributor's record for the named source revision.
|
||||
The integration review does not reproduce or independently accept the full
|
||||
measurement protocol below.
|
||||
|
||||
Run `1795544761`, Apple M4, release build of `0fdb995` plus this harness, API
|
||||
and shader validation off, AC power, no thermal warnings, started right after
|
||||
the release build. Fixture `add`, 4 words, 30 fresh processes, 100 repeated
|
||||
runs. All values in milliseconds.
|
||||
|
||||
| Phase | Fresh median | Fresh p90 | Fresh p99 | Fresh max | First in process | Repeated median | Repeated p90 | Repeated p99 | Repeated max |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| `spawn_to_main` | 2.746 | 3.133 | 5.325 | 6.198 | – | – | – | – | – |
|
||||
| `device` | 35.762 | 38.770 | 41.060 | 41.864 | 32.802 | – | – | – | – |
|
||||
| `translate` | 0.061 | 0.071 | 0.084 | 0.089 | 0.067 | 0.016 | 0.023 | 0.041 | 0.043 |
|
||||
| `library` | 0.402 | 0.434 | 18.595 | 25.976 | 0.399 | 0.006 | 0.010 | 0.018 | 0.019 |
|
||||
| `pipeline` | 0.363 | 0.401 | 0.623 | 0.708 | 0.342 | 0.013 | 0.021 | 0.031 | 0.043 |
|
||||
| `submit` | 1.665 | 1.894 | 1.951 | 1.953 | 1.647 | 0.214 | 0.384 | 0.440 | 3.941 |
|
||||
| `gpu` | 0.007 | 0.008 | 0.010 | 0.011 | 0.008 | 0.007 | 0.008 | 0.061 | 1.742 |
|
||||
| `readback` | 0.001 | 0.001 | 0.002 | 0.002 | 0.001 | < 0.001 | < 0.001 | < 0.001 | < 0.001 |
|
||||
| process wall (spawn to exit) | 43.225 | 46.770 | 68.236 | 75.958 | – | – | – | – | – |
|
||||
|
||||
Observations, without causal claims:
|
||||
|
||||
- Device and queue creation is the largest fresh-process phase, about 36 ms of a
|
||||
43 ms median process. Within one process it is paid once.
|
||||
- The `library` tail came from the first child launched after the build
|
||||
(25.976 ms; the other 29 were 0.36–0.45 ms). A second run immediately after,
|
||||
`1795544763`, had a fresh `library` maximum of 0.446 ms, with `device` median
|
||||
36.414 ms and process-wall median 44.111 ms. This fits an on-disk Metal
|
||||
compilation cache, but the run does not show that.
|
||||
- After the first run in a process, `library` and `pipeline` fall to about
|
||||
0.01 ms and `submit` to about 0.2 ms. The `gpu` time for this 4-word kernel is
|
||||
at timer scale in both regimes.
|
||||
|
||||
Two runs on one host do not describe other Apple GPU generations, sustained
|
||||
load, other fixtures or larger word counts.
|
||||
|
||||
## Limitations
|
||||
|
||||
The corpus currently covers three synthetic gfx1030 compute fixtures under the
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
# Migrated pull-request integration review
|
||||
|
||||
Reviewed on November 24, 2026 (America/Chicago). The initial inventory contained
|
||||
23 open pull requests under `Arths17`, including the development-plan PR.
|
||||
Twenty-two were merged after their updated heads passed the applicable GitHub
|
||||
checks. Imported records retain their original author attribution and commits.
|
||||
|
||||
The maintainer authorized per-merge admin overrides for the review restriction.
|
||||
The ARM64 build/test requirement, one-approval rule, code-owner review requirement
|
||||
and enforcement for admins remain configured. Failed or pending checks were
|
||||
resolved before merging. The conditional `verify` comment job is normally skipped;
|
||||
that skip is not independent semantic verification.
|
||||
|
||||
## Results
|
||||
|
||||
All links below refer to the BetterXen repository.
|
||||
|
||||
| PR | Result | Integration work |
|
||||
| --- | --- | --- |
|
||||
| [#263](https://github.com/MacosPorters/betterxen/pull/263) | Pending | Pending: overlaps the contributor's live PR #290, excluded by the maintainer. |
|
||||
| [#264](https://github.com/MacosPorters/betterxen/pull/264) | Merged; checks passed | Identification fixture runs in ordinary tests; benchmark-harness lint fixed. |
|
||||
| [#265](https://github.com/MacosPorters/betterxen/pull/265) | Merged; checks passed | Bounded native texture staging; planner and Metal readback tests. |
|
||||
| [#266](https://github.com/MacosPorters/betterxen/pull/266) | Merged; checks passed | Startup measurement harness; unit tests and correctness smoke run. |
|
||||
| [#267](https://github.com/MacosPorters/betterxen/pull/267) | Merged; checks passed | Bounded flat draws and repeated-frame regressions. |
|
||||
| [#268](https://github.com/MacosPorters/betterxen/pull/268) | Merged; checks passed | Windows x64 calling conventions; writable-home-slot regression and nonvolatile vector-register negative controls. |
|
||||
| [#269](https://github.com/MacosPorters/betterxen/pull/269) | Merged; checks passed | Executable generations with source revalidation; original cache assertions preserved. |
|
||||
| [#270](https://github.com/MacosPorters/betterxen/pull/270) | Merged; checks passed | ARM64 shift encoding and operand checks; draft marked ready. |
|
||||
| [#271](https://github.com/MacosPorters/betterxen/pull/271) | Merged; checks passed | Floating-point unit initialization, combined decoder generation and preserved tests. |
|
||||
| [#272](https://github.com/MacosPorters/betterxen/pull/272) | Merged; checks passed | Dynamic binary translation (DBT) report comparison and input validation. |
|
||||
| [#273](https://github.com/MacosPorters/betterxen/pull/273) | Merged; checks passed | C startup service integration and registry regeneration. |
|
||||
| [#274](https://github.com/MacosPorters/betterxen/pull/274) | Merged; checks passed | Instruction-length faults and precise retirement. |
|
||||
| [#275](https://github.com/MacosPorters/betterxen/pull/275) | Merged; checks passed | Flag-transfer instructions; combined fixtures and supported-case expectations retained. |
|
||||
| [#276](https://github.com/MacosPorters/betterxen/pull/276) | Merged; checks passed | Explicitly unsupported service stubs and combined registry. |
|
||||
| [#277](https://github.com/MacosPorters/betterxen/pull/277) | Merged; checks passed | Guest arguments and environment with combined services. |
|
||||
| [#278](https://github.com/MacosPorters/betterxen/pull/278) | Merged; checks passed | Packed texture footprints; CPU and native GPU checks. |
|
||||
| [#279](https://github.com/MacosPorters/betterxen/pull/279) | Merged; checks passed | Loop instructions; regenerated tables and corrected description to 3,600 comparisons. |
|
||||
| [#280](https://github.com/MacosPorters/betterxen/pull/280) | Merged; checks passed | Process termination and exit callbacks. |
|
||||
| [#281](https://github.com/MacosPorters/betterxen/pull/281) | Merged; checks passed | Formatted output integrated with startup and arguments. |
|
||||
| [#282](https://github.com/MacosPorters/betterxen/pull/282) | Merged; checks passed | File streams; combined registry and dependency readiness. |
|
||||
| [#283](https://github.com/MacosPorters/betterxen/pull/283) | Merged; checks passed | Hosted C fixture; driver architecture checked before execution. |
|
||||
| [#284](https://github.com/MacosPorters/betterxen/pull/284) | Merged; checks passed | Thread-local storage (TLS) template-copy integration and preserved changelog entries. |
|
||||
| [#288](https://github.com/MacosPorters/betterxen/pull/288) | Merged; checks passed | Development phases, README and migration-check record. |
|
||||
|
||||
PR #263 remains open to avoid competing with the contributor's live PR #290.
|
||||
PR #290 was excluded from branch edits, reviews and merge operations as requested.
|
||||
Its filesystem security and integration acceptance are left to that workstream.
|
||||
|
||||
## Verification and evidence scope
|
||||
|
||||
The integrated runtime candidate was
|
||||
`5366b9398668128fdbb0b0879840dfa072bfa352`. Its GitHub native Rust workflow passed,
|
||||
including workspace formatting, strict Clippy, tests and the hosted C fixture.
|
||||
Local native results below concern the reported Apple M4 host running macOS 27.0
|
||||
(class A host observations); they establish no Xbox-hardware or commercial-game
|
||||
execution result.
|
||||
|
||||
| Check | Observed result |
|
||||
| --- | --- |
|
||||
| `scripts/test-gpu.sh` | 124 passed, 0 failed; 2 manual timing tests ignored. Metal API and GPU validation enabled. |
|
||||
| Packed block-compressed texture GPU target | 1 passed, 0 failed, 0 ignored, with both validation layers enabled. |
|
||||
| `scripts/demo.sh` | All three original fixtures matched Metal, reference and known-answer outputs. |
|
||||
| `scripts/audit/native.sh` | 110 executables/loadable dependencies checked with `file`, `lipo` and `otool`; ARM64 architecture and permitted linkage checks passed. |
|
||||
| Status, claims and dependency audits | Passed. |
|
||||
|
||||
The cache fix also passed an isolated local workspace run at `44ac976`: 917
|
||||
passed, 0 failed, 35 ignored, plus strict Clippy. Its three alternating CPU
|
||||
benchmark pairs used native release executables and identical original inputs:
|
||||
per-run warm medians were 87.334–88.333 microseconds with per-byte validation and
|
||||
15.625–18.791 microseconds with generation validation. Machine idleness was not
|
||||
controlled. These measurements do not close the formal performance gate; their
|
||||
candidate scope and cold results are recorded in PR #269.
|
||||
|
||||
A supplemental benchmark test-harness command exposed a missing initialization
|
||||
for the newly added cache-invalidation counter. The follow-up initializes that
|
||||
fixture and runs the existing report, JSON, comparison and percentile tests via
|
||||
an ordinary integration-test target, preserving their assertions. This lets
|
||||
workspace CI detect future benchmark-test compilation failures. All 14 existing
|
||||
tests passed through both the ordinary integration target and the documented
|
||||
manual harness command; strict workspace Clippy passed as well.
|
||||
|
||||
Raw final native logs, cache benchmark JSON and the PR-state inventory are kept
|
||||
under ignored `artifacts/pr-integration/` in the lead checkout. PR checks and merge
|
||||
records remain linked from each GitHub record.
|
||||
|
||||
## Remaining acceptance
|
||||
|
||||
This is an integration and execution record. Independent semantic and security
|
||||
acceptance remains separate from implementer-run checks and administrative merge
|
||||
permission. No release gates were redefined or releases created. Commercial Xbox
|
||||
game execution remains unsupported.
|
||||
|
||||
Active-block self-modifying code is tracked separately in
|
||||
[issue #291](https://github.com/MacosPorters/betterxen/issues/291); native-code cache
|
||||
reclamation remains [issue #95](https://github.com/MacosPorters/betterxen/issues/95).
|
||||
The source fixture programs, desktop instruction evidence and native Mac results
|
||||
retain their existing boundaries.
|
||||
Reference in new issue
Block a user