diff --git a/.githooks/pre-commit b/.githooks/pre-commit old mode 100644 new mode 100755 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 80e6a35..5400e00 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,25 +5,44 @@ on: push: branches: [main] -permissions: - contents: read +# No token permissions by default; the job grants only what it uses. +permissions: {} +# A newer push to a PR cancels its older run. Runs on main are never +# cancelled: only main saves the rust-cache, so a cancelled main run would +# leave PRs restoring a stale cache. concurrency: group: ci-${{ github.ref }} - cancel-in-progress: true + cancel-in-progress: ${{ github.event_name == 'pull_request' }} env: CARGO_TERM_COLOR: always jobs: + # The name repeats the id, so the required check stays `check`. check: + name: check runs-on: windows-latest + # checkout only. + permissions: + contents: read timeout-minutes: 60 steps: - - uses: actions/checkout@v5 + # Actions are pinned to full commit SHAs (tag in the trailing comment): + # a tag can be moved to other code, a commit cannot. Bump both together. + # Nothing here pushes; keep the token out of .git/config. + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false # The version and components pinned in rust-toolchain.toml. - - run: rustup toolchain install - - uses: Swatinem/rust-cache@v2 + # --no-self-update: rustup would otherwise replace itself with whatever + # release is newest that day, unpinned and mid-job. + - run: rustup toolchain install --no-self-update + # Save the cache only from main: PR runs restore it but do not write + # their own entries, which would evict main's from the 10 GB quota. + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + save-if: ${{ github.ref == 'refs/heads/main' }} - name: Clippy run: cargo clippy --workspace --all-targets --locked -- -D warnings - name: Clippy, diagnostics build diff --git a/.github/workflows/linux-subset.yml b/.github/workflows/linux-subset.yml new file mode 100644 index 0000000..5752e7b --- /dev/null +++ b/.github/workflows/linux-subset.yml @@ -0,0 +1,1149 @@ +# Interim Linux CI for the crates that already build without Windows. +# Superseded once full-workspace Linux CI lands; fold or delete then. +# +# Every step here passes on plain Linux with no Windows SDK, no cross target +# and no game data. The PR that added this lists the same commands for local use. +name: linux-subset + +on: + push: + branches: [main] + pull_request: + +# No token permissions by default; each job grants only what it uses, so a +# job added later starts with none instead of inheriting these. +permissions: {} + +# The implicit default shell is plain `bash -e`, where a failing command on +# the left of a pipe (e.g. the `echo ... | sha256sum -c -` checksum checks) +# is ignored. Set it once so every `run:` script gets pipefail, plus nounset: +# a misspelt or missing variable (say a renamed *_CRATES list) is an error +# instead of expanding to nothing, which would e.g. run `cargo clippy` with +# no -p flags on whatever the default members are. inherit_errexit makes +# `set -e` apply inside command substitutions too, which Bash otherwise +# resets there: a failing command in `x="$(a; b)"` stops the step instead +# of letting `b` run on. +defaults: + run: + shell: bash --noprofile --norc -O inherit_errexit -euo pipefail {0} + +# Actions are pinned to full commit SHAs (tag in the trailing comment): a tag +# can be moved to other code, a commit cannot. Bump both together. + +# A newer push to a PR cancels its older run. Runs on main are never +# cancelled: only main saves the rust-cache, so a cancelled main run would +# leave PRs restoring a stale cache. +concurrency: + group: linux-subset-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + CARGO_TERM_COLOR: always + CARGO_INCREMENTAL: 0 + # A failing test or build script prints where it panicked. + RUST_BACKTRACE: 1 + # Folded package lists are read into Bash arrays of Cargo arguments. + # Crates (plus xtask) that build, test and are clippy-clean on Linux today. + LINUX_CRATES: >- + -p victory-core -p victory-pe -p victory-formats -p victory-pipeline + -p victory-game -p victory-loader -p victory-shader -p xtask + # Crates that are clippy-clean for the Windows target today: every + # workspace member but xtask, which is host-only. + WINDOWS_CLIPPY_CRATES: >- + -p victory-core -p victory-pe -p victory-formats -p victory-pipeline + -p victory-game -p victory-loader -p victory-shader -p victory-gpu + -p victory-hle -p victory + # Packages that are rustfmt-clean today. The rest (victory-formats, + # victory-loader, victory-gpu, victory-hle) are not yet; add each one + # once it is, and switch to `cargo fmt --all --check` when all are. + RUSTFMT_CRATES: >- + -p victory-core -p victory-pe -p victory-pipeline -p victory-game + -p victory-shader -p victory -p xtask + # Crates whose rustdoc builds with no warnings on Linux (broken or private + # intra-doc links, bad code-block attributes, ...): LINUX_CRATES plus + # victory-gpu, whose docs build on Linux although its code does not. + RUSTDOC_CRATES: >- + -p victory-core -p victory-pe -p victory-formats -p victory-pipeline + -p victory-game -p victory-loader -p victory-shader -p victory-gpu + -p xtask + # Crates whose rustdoc builds with no warnings for the Windows target, where + # cfg(windows) items (all of victory-hle, apps/victory's host) exist and the + # Linux rustdoc step never sees them. Every workspace member but the + # host-only xtask, like WINDOWS_CLIPPY_CRATES. + WINDOWS_RUSTDOC_CRATES: >- + -p victory-core -p victory-pe -p victory-formats -p victory-pipeline + -p victory-game -p victory-loader -p victory-shader -p victory-gpu + -p victory-hle -p victory + +jobs: + # Each job's name repeats its id, so the check names that branch protection + # requires stay `linux` and `windows-target-check`; zizmor's auditor + # persona (below) flags unnamed jobs. + # Both jobs pin the runner image's Ubuntu release rather than + # `ubuntu-latest`, like the action and tool pins: the alias moves to a new + # release (new preinstalled rustup, curl, tar, coreutils, ...) under us, so + # a passing PR could fail on main with no change. Bump it deliberately. + linux: + name: linux + runs-on: ubuntu-24.04 + # checkout, plus zizmor's online audits (impostor commits, advisories). + permissions: + contents: read + timeout-minutes: 30 + steps: + # Nothing here pushes; keep the token out of .git/config. + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + + # Every step here, and the rust-cache key, trusts rust-toolchain.toml to + # name one exact release. A channel of `stable` (or `beta`, `nightly`, + # a bare `1.98`) still installs and passes, but floats to whatever is + # newest that day: new lints fail a PR that changed nothing, and main + # and a PR build with different compilers. A `path` toolchain is a + # local directory the runner does not have, and a legacy + # `rust-toolchain` file next to it would take precedence over the + # .toml in rustup. The pin must also be no older than the workspace's + # rust-version, or the msrv job checks with a compiler newer than the + # one every other step uses. Read with the runner's Python 3 tomllib + # (-I: no site packages, no cwd on sys.path) before rustup reads it. + - name: Toolchain pin is one exact release + run: | + python3 -I - <<'EOF' + import os, re, sys, tomllib + + def load(path): + with open(path, "rb") as f: + return tomllib.load(f) + + failed = False + if os.path.lexists("rust-toolchain"): + print("::error file=rust-toolchain::legacy toolchain file overrides rust-toolchain.toml", file=sys.stderr) + failed = True + toolchain = load("rust-toolchain.toml").get("toolchain", {}) + channel = toolchain.get("channel") + pin = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)", channel) if isinstance(channel, str) else None + if pin is None: + print(f"::error file=rust-toolchain.toml::channel {channel!r} is not an exact release (MAJOR.MINOR.PATCH)", file=sys.stderr) + failed = True + if "path" in toolchain: + print("::error file=rust-toolchain.toml::toolchain names a local path", file=sys.stderr) + failed = True + msrv = load("Cargo.toml").get("workspace", {}).get("package", {}).get("rust-version", "") + floor = re.fullmatch(r"(\d+)\.(\d+)(?:\.(\d+))?", msrv) if isinstance(msrv, str) else None + if floor is None: + print(f"::error file=Cargo.toml::unexpected workspace rust-version {msrv!r}", file=sys.stderr) + failed = True + elif pin is not None: + have = tuple(int(g) for g in pin.groups()) + need = tuple(int(g or 0) for g in floor.groups()) + if have < need: + print(f"::error file=rust-toolchain.toml::channel {channel} is older than the workspace rust-version {msrv}", file=sys.stderr) + failed = True + if failed: + sys.exit(1) + print(f"Pinned toolchain {channel}, rust-version {msrv}") + EOF + + # rustup is preinstalled; this installs the toolchain pinned in + # rust-toolchain.toml (with clippy and rustfmt). --no-self-update keeps + # the runner image's rustup as is: otherwise rustup replaces itself + # with whatever release is newest that day, unpinned and mid-job. + - name: Install pinned toolchain + run: rustup toolchain install --no-self-update + + # Save the cache only from main: PR runs restore it but do not write + # their own entries, which would evict main's from the 10 GB quota. + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + save-if: ${{ github.ref == 'refs/heads/main' }} + + # Spelled out rather than the `cargo xtask` alias (`run --package xtask + # --`), which has no room for --locked: this is the job's first cargo + # command, and without it a Cargo.lock out of date with the manifests + # would be rewritten here, so every later `--locked` step would check + # against the rewritten file and pass. + - name: Asset policy + run: cargo run --locked --quiet --package xtask -- policy + + # The crate lists above are written out by hand, so a workspace member + # added later would silently get no clippy or rustdoc at all. Fail + # instead: every member but the host-only xtask must be in both Windows + # lists (which say they hold every member but xtask), and xtask, which + # nothing else lints, must be in LINUX_CRATES. Every LINUX_CRATES crate + # must also be in RUSTDOC_CRATES (which says it holds them all), so one + # moved onto Linux CI gets its rustdoc lints too. Lists may still name + # fewer crates on purpose (LINUX_CRATES, RUSTFMT_CRATES, ...). + - name: Crate lists cover the workspace + run: | + metadata="$(cargo metadata --locked --no-deps --format-version 1)" + names="$(jq -r '.packages[].name' <<< "${metadata}")" + mapfile -t members <<< "${names}" + if [[ "${#members[@]}" -lt 2 ]]; then + echo "::error::cargo metadata listed no workspace members" >&2 + exit 1 + fi + declare -A linux=() clippy=() rustdoc=() linux_rustdoc=() + read -r -a args <<< "${LINUX_CRATES}" + for a in "${args[@]}"; do linux["${a}"]=1; done + read -r -a args <<< "${RUSTDOC_CRATES}" + for a in "${args[@]}"; do linux_rustdoc["${a}"]=1; done + read -r -a args <<< "${WINDOWS_CLIPPY_CRATES}" + for a in "${args[@]}"; do clippy["${a}"]=1; done + read -r -a args <<< "${WINDOWS_RUSTDOC_CRATES}" + for a in "${args[@]}"; do rustdoc["${a}"]=1; done + missing=0 + read -r -a args <<< "${LINUX_CRATES}" + for c in "${args[@]}"; do + if [[ "${c}" != -p && ! -v linux_rustdoc["${c}"] ]]; then + echo "::error::LINUX_CRATES member ${c} is not in RUSTDOC_CRATES" >&2 + missing=1 + fi + done + for m in "${members[@]}"; do + if [[ "${m}" == xtask ]]; then + if [[ ! -v linux["${m}"] ]]; then + echo "::error::xtask is not in LINUX_CRATES" >&2 + missing=1 + fi + continue + fi + if [[ ! -v clippy["${m}"] ]]; then + echo "::error::workspace member ${m} is not in WINDOWS_CLIPPY_CRATES" >&2 + missing=1 + fi + if [[ ! -v rustdoc["${m}"] ]]; then + echo "::error::workspace member ${m} is not in WINDOWS_RUSTDOC_CRATES" >&2 + missing=1 + fi + done + if [[ "${missing}" -ne 0 ]]; then + exit 1 + fi + printf 'Covered: %s\n' "${members[@]}" + + # The clippy and rustdoc steps lint with whatever `[lints]` each crate + # declares, so a member added (or edited) without `[lints] workspace = + # true` silently drops `undocumented_unsafe_blocks`, + # `unsafe_op_in_unsafe_fn = deny`, ... and still passes. The hle-probe + # fixture is outside the workspace and repeats those lints by hand + # ("keep the two in step"); fail when the copies drift apart. cargo + # metadata does not report lints, so the manifests are read with the + # runner's Python 3 tomllib (-I: no site packages, no cwd on sys.path). + # The same goes for the [workspace.package] fields every member + # inherits today: a member that spells out its own `edition` (or + # `license`, `publish`) instead of `.workspace = true` drifts unseen + # when the root one is bumped, so each must be inherited, and the + # fixture's hand-written copies must match the root's. + - name: Workspace lints and package fields apply everywhere + run: | + metadata="$(cargo metadata --locked --no-deps --format-version 1)" + manifests="$(jq -r '.packages[].manifest_path' <<< "${metadata}")" + mapfile -t manifest_list <<< "${manifests}" + python3 -I - Cargo.toml tests/fixtures/hle-probe/Cargo.toml "${manifest_list[@]}" <<'EOF' + import sys, tomllib + + def load(path): + with open(path, "rb") as f: + return tomllib.load(f) + + root, fixture, *members = sys.argv[1:] + want = load(root).get("workspace", {}).get("lints") + inherited = ("edition", "license", "publish") + root_package = load(root).get("workspace", {}).get("package", {}) + failed = False + for key in inherited: + if key not in root_package: + print(f"::error::root Cargo.toml has no [workspace.package] {key}", file=sys.stderr) + failed = True + if not want: + print("::error::root Cargo.toml has no [workspace.lints]", file=sys.stderr) + failed = True + if len(members) < 2: + print("::error::cargo metadata listed no workspace members", file=sys.stderr) + failed = True + for m in members: + manifest = load(m) + if manifest.get("lints") != {"workspace": True}: + print(f"::error file={m}::[lints] must be exactly `workspace = true`", file=sys.stderr) + failed = True + package = manifest.get("package", {}) + for key in inherited: + if package.get(key) != {"workspace": True}: + print(f"::error file={m}::[package] {key} must be `{key}.workspace = true`", file=sys.stderr) + failed = True + fixture_manifest = load(fixture) + if fixture_manifest.get("lints") != want: + print(f"::error file={fixture}::[lints] differs from the root [workspace.lints]", file=sys.stderr) + failed = True + fixture_package = fixture_manifest.get("package", {}) + for key in inherited: + if fixture_package.get(key) != root_package.get(key): + print(f"::error file={fixture}::[package] {key} differs from the root [workspace.package] {key}", file=sys.stderr) + failed = True + if failed: + sys.exit(1) + print(f"Workspace lints and {', '.join(inherited)} on {len(members)} members and the hle-probe fixture") + EOF + + # Every dependency today is a checksummed crates.io release. A git + # dependency (or a `[patch]` pointing at one), a path dependency outside + # the repository, or a crate from another registry or a source + # replacement would build and pass every step here, while pulling code + # that is neither checksummed nor reviewable from Cargo.lock, so fail on + # one instead. Both lockfiles are read with tomllib, without the + # network: each package must either have no source and be a workspace + # member (the fixture's lock: the fixture itself), or come from the + # crates.io index with a checksum. The root manifest and the cargo + # config must not redirect sources with [patch], [replace], [source] + # or [registries]. + - name: Dependencies come only from crates.io + run: | + metadata="$(cargo metadata --locked --no-deps --format-version 1)" + names="$(jq -r '.packages[].name' <<< "${metadata}")" + mapfile -t members <<< "${names}" + python3 -I - "${members[@]}" <<'EOF' + import sys, tomllib + + def load(path): + with open(path, "rb") as f: + return tomllib.load(f) + + crates_io = { + "registry+https://github.com/rust-lang/crates.io-index", + "sparse+https://index.crates.io/", + } + members = set(sys.argv[1:]) + failed = False + if len(members) < 2: + print("::error::cargo metadata listed no workspace members", file=sys.stderr) + failed = True + fixture = "tests/fixtures/hle-probe" + fixture_name = load(f"{fixture}/Cargo.toml")["package"]["name"] + counted = 0 + for lock, local in (("Cargo.lock", members), (f"{fixture}/Cargo.lock", {fixture_name})): + packages = load(lock).get("package", []) + if not packages: + print(f"::error file={lock}::no [[package]] entries", file=sys.stderr) + failed = True + for p in packages: + counted += 1 + name, source = p["name"], p.get("source") + if source is None: + if name not in local: + print(f"::error file={lock}::{name} has no source but is not a workspace member (path dependency outside the workspace?)", file=sys.stderr) + failed = True + elif source not in crates_io: + print(f"::error file={lock}::{name} comes from {source}, not crates.io", file=sys.stderr) + failed = True + elif not p.get("checksum"): + print(f"::error file={lock}::{name} from crates.io has no checksum", file=sys.stderr) + failed = True + for path, keys in ( + ("Cargo.toml", ("patch", "replace")), + (f"{fixture}/Cargo.toml", ("patch", "replace")), + (".cargo/config.toml", ("patch", "source", "registries")), + ): + found = [k for k in keys if k in load(path)] + if found: + print(f"::error file={path}::redirects dependency sources with [{'], ['.join(found)}]", file=sys.stderr) + failed = True + if failed: + sys.exit(1) + print(f"{counted} locked packages: workspace members or checksummed crates.io releases") + EOF + + # .gitattributes stores every text file with LF (`text=auto eol=lf`; + # *.cmd and *.ps1 get CRLF only in the working tree). That applies only + # when git normalises the file at `git add`: a file committed with + # core.autocrlf=false from a Windows editor, or one added before the + # attribute, keeps its CRLFs in the index, and every Linux checkout + # then shows it modified. Fail on any tracked file whose stored copy + # has CRLF or mixed endings (`git ls-files --eol`, index column). + # Merge-conflict markers left in a resolved file do not always break + # the build (a comment, a doc, a workflow, a fixture), so fail on those + # too: `<<<<<<< `, `||||||| ` or `>>>>>>> ` opening a line in any + # tracked text file. A bare `=======` is left alone; it is also a + # Markdown heading underline. + # Trailing spaces or tabs, and a last line with no newline, are clean + # everywhere on main too, but only the rustfmt-clean packages are + # checked by rustfmt; the rest (workflows, TOML, docs, the crates + # rustfmt skips) pick up whitespace-only diff noise unseen. Both are + # read from the index (`git grep --cached`, the `--eol` list), so a + # CRLF working-tree copy (*.cmd, *.ps1) cannot trip or hide either. + # A UTF-8 byte-order mark (U+FEFF, which Notepad and some Visual Studio + # setups write) is invisible in an editor and in a diff, but it is not + # whitespace to the check above: at the top of a file it hides a + # script's `#!` line (the kernel, the file-mode step below and the + # ShellCheck list all look for `#!` at byte 0) and shows as a mystery + # first-line change in review. Mid-file it is a stray zero-width + # character. Fail on it anywhere in a tracked text file; Rust source + # that needs the character can spell it `\u{feff}`. + - name: LF line endings, no conflict markers, no stray whitespace or BOMs + run: | + list="${RUNNER_TEMP}/eol" + git ls-files -z --eol > "${list}" + bad=() + no_final_newline=() + while IFS= read -r -d '' entry; do + index_eol="${entry%% *}" + path="${entry#*$'\t'}" + if [[ "${index_eol}" == i/crlf || "${index_eol}" == i/mixed ]]; then + bad+=("${path}") + fi + # i/-text is binary; an empty file has nothing to end. + if [[ "${index_eol}" != i/-text ]]; then + last="$(git cat-file blob ":${path}" | tail -c 1)" + if [[ -n "${last}" ]]; then + no_final_newline+=("${path}") + fi + fi + done < "${list}" + if [[ "${#bad[@]}" -ne 0 ]]; then + echo "::error::tracked files stored with CRLF line endings (re-add them with git add --renormalize)" >&2 + printf '%s\n' "${bad[@]}" >&2 + exit 1 + fi + if [[ "${#no_final_newline[@]}" -ne 0 ]]; then + echo "::error::tracked text files whose last line has no newline" >&2 + printf '%s\n' "${no_final_newline[@]}" >&2 + exit 1 + fi + # git grep exits 1 when nothing matches; any other failure stops. + trailing="$(git grep --cached -nIE -e '[[:blank:]]+$')" || [[ $? -eq 1 ]] + if [[ -n "${trailing}" ]]; then + echo "::error::trailing spaces or tabs in tracked files" >&2 + printf '%s\n' "${trailing}" >&2 + exit 1 + fi + # git grep exits 1 when nothing matches; any other failure stops. + bom="$(git grep --cached -nIF -e $'\xEF\xBB\xBF')" || [[ $? -eq 1 ]] + if [[ -n "${bom}" ]]; then + echo "::error::UTF-8 byte-order marks (U+FEFF) in tracked text files" >&2 + printf '%s\n' "${bom}" >&2 + exit 1 + fi + # git grep exits 1 when nothing matches; any other failure stops. + markers="$(git grep -nIE -e '^(<{7}|[|]{7}|>{7})( |$)')" || [[ $? -eq 1 ]] + if [[ -n "${markers}" ]]; then + echo "::error::merge-conflict markers in tracked files" >&2 + printf '%s\n' "${markers}" >&2 + exit 1 + fi + + # Git records two file modes that a Linux checkout honours and a Windows + # one does not. A symlink (mode 120000) is checked out on Windows, where + # core.symlinks is off by default, as a plain text file holding the + # target path, so the two platforms build different trees; nothing here + # needs one, so fail on any. An executable bit (100755) on a file that + # is not a script is usually an accident from a Linux, WSL or mounted- + # NTFS editor and shows as mode noise in every diff; fail on executable + # files that do not start with `#!`. Read from the index (`git ls-files + # -s`), not the checkout, so the runner's umask cannot hide either. + - name: Portable file modes + run: | + list="${RUNNER_TEMP}/modes" + git ls-files -z -s > "${list}" + links=() + stray_exec=() + while IFS= read -r -d '' entry; do + mode="${entry%% *}" + path="${entry#*$'\t'}" + case "${mode}" in + 120000) links+=("${path}") ;; + 100755) + magic="$(head -c 2 -- "${path}")" + if [[ "${magic}" != '#!' ]]; then + stray_exec+=("${path}") + fi + ;; + *) ;; + esac + done < "${list}" + failed=0 + if [[ "${#links[@]}" -ne 0 ]]; then + echo "::error::tracked symlinks (Windows checkouts get a text file instead)" >&2 + printf '%s\n' "${links[@]}" >&2 + failed=1 + fi + if [[ "${#stray_exec[@]}" -ne 0 ]]; then + echo "::error::executable files without a #! line (git update-index --chmod=-x)" >&2 + printf '%s\n' "${stray_exec[@]}" >&2 + failed=1 + fi + if [[ "${failed}" -ne 0 ]]; then + exit 1 + fi + + # Path names that a Linux checkout accepts and a Windows one cannot + # hold. NTFS is case-insensitive, so two tracked paths that differ only + # in case (`Foo.rs`, `foo.rs`) collapse into one file there and the + # checkout shows a permanent spurious change. Windows also refuses a + # path component that holds `< > : " | ? *`, a backslash or a control + # character, that ends in a dot or a space, or whose name before the + # first dot is a reserved device (CON, PRN, AUX, NUL, COM0-9, LPT0-9, + # any case): `git checkout` there fails outright. Read from the index, + # NUL-delimited, so no name can split; the comparison runs under the + # C locale so it folds ASCII case only, as the check is meant to. + - name: Portable file names + env: + LC_ALL: C + run: | + list="${RUNNER_TEMP}/names" + git ls-files -z > "${list}" + bad=() + declare -A seen=() + collide=() + reserved='^(con|prn|aux|nul|com[0-9]|lpt[0-9])$' + while IFS= read -r -d '' path; do + # Walk every prefix (each directory, then the file), so `Src/a` + # and `src/b` collide too, not only whole paths. + prefix="" + rest="${path}" + flagged=0 + while [[ -n "${rest}" ]]; do + part="${rest%%/*}" + if [[ "${rest}" == */* ]]; then + rest="${rest#*/}" + else + rest="" + fi + prefix="${prefix:+${prefix}/}${part}" + lower="${prefix,,}" + if [[ -z "${seen[${lower}]+set}" ]]; then + seen["${lower}"]="${prefix}" + elif [[ "${seen[${lower}]}" != "${prefix}" ]]; then + collide+=("${seen[${lower}]} <-> ${prefix}") + fi + stem="${part%%.*}" + if [[ "${flagged}" -eq 0 ]] \ + && { [[ "${part}" =~ [\<\>:\"\|?*\\[:cntrl:]] ]] \ + || [[ "${part}" == *. || "${part}" == *' ' ]] \ + || [[ "${stem,,}" =~ ${reserved} ]]; }; then + bad+=("${path}") + flagged=1 + fi + done + done < "${list}" + failed=0 + if [[ "${#collide[@]}" -ne 0 ]]; then + echo "::error::tracked paths that differ only in case (one file on Windows)" >&2 + printf '%s\n' "${collide[@]}" | sort -u >&2 + failed=1 + fi + if [[ "${#bad[@]}" -ne 0 ]]; then + echo "::error::tracked paths Windows cannot check out (reserved name, character, or trailing dot or space)" >&2 + printf '%s\n' "${bad[@]}" >&2 + failed=1 + fi + if [[ "${failed}" -ne 0 ]]; then + exit 1 + fi + # Lints all workflows: expression and context typos, unknown keys, and + # (via ShellCheck) the `run:` scripts, which YAML parsing alone never + # checks. actionlint silently skips the shell checks when shellcheck is + # not on PATH, and the runner image's shellcheck changes version under + # us, so a pinned ShellCheck release is downloaded and passed explicitly + # instead: the same checks run on every runner image, and a missing + # binary fails the step rather than skipping the checks. Both releases + # are pinned and their checksums verified, like the actions above. + # Every download (here and in zizmor below) is HTTPS-only, redirects + # included (--proto =https), with TLS 1.2 or newer. Each attempt is + # capped (--connect-timeout, --max-time): a stalled release download + # fails and is retried within minutes instead of holding the job until + # its 30-minute timeout. + # pyflakes is off: no step runs Python. + # SHELLCHECK_OPTS turns on ShellCheck's optional checks (masked return + # codes, `set -e` suppressed in functions, unassigned uppercase vars, + # `[[ ]]` over `[ ]`, `${var}` over `$var`, useless `cat`, ...) for the + # `run:` scripts. Every optional check of the pinned release is listed + # and passes (`shellcheck --list-optional`); they are named rather than + # `--enable=all` so bumping ShellCheck cannot add one unseen. + # --norc: a `.shellcheckrc` (committed, or added by a PR) cannot + # quietly disable checks or drop these optional ones; disabling a check + # takes an inline `# shellcheck disable=` next to the code, in review. + # -config-file /dev/null does the same for actionlint's own config: a + # `.github/actionlint.yaml` (or .yml) can `ignore:` any error by regex, + # which actionlint otherwise picks up silently. + # actionlint only sees `run:` scripts, so the same ShellCheck (same + # SHELLCHECK_OPTS, which ShellCheck reads itself) then lints the + # standalone scripts too: the git hooks, any tracked *.sh / *.bash, and + # any tracked text file whose first line is a sh/bash/dash/ksh shebang + # (a script with no extension, e.g. under scripts/). The list comes + # from git, so a script added later is checked without editing this + # step; the step fails if the list is empty, rather than passing while + # checking nothing. File names are NUL-delimited end to end, so no name + # (spaces, newlines, a leading `-`) can split, glob or become a flag. + - name: actionlint + ShellCheck + env: + SHELLCHECK_OPTS: >- + --norc + --enable=add-default-case,avoid-negated-conditions,avoid-nullary-conditions,check-extra-masked-returns,check-set-e-suppressed,check-unassigned-uppercase,deprecate-which,quote-safe-variables,require-double-brackets,require-variable-braces,useless-use-of-cat + SHELLCHECK_VERSION: 0.11.0 + SHELLCHECK_SHA256: 8c3be12b05d5c177a04c29e3c78ce89ac86f1595681cab149b65b97c4e227198 + ACTIONLINT_VERSION: 1.7.12 + ACTIONLINT_SHA256: 8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8 + run: | + cd "${RUNNER_TEMP}" + sc_tarball="shellcheck-v${SHELLCHECK_VERSION}.linux.x86_64.tar.xz" + curl -sSfL --proto =https --tlsv1.2 --retry 3 --connect-timeout 20 --max-time 300 -O "https://github.com/koalaman/shellcheck/releases/download/v${SHELLCHECK_VERSION}/${sc_tarball}" + echo "${SHELLCHECK_SHA256} ${sc_tarball}" | sha256sum -c - + tar xJf "${sc_tarball}" --strip-components=1 "shellcheck-v${SHELLCHECK_VERSION}/shellcheck" + shellcheck_bin="${RUNNER_TEMP}/shellcheck" + "${shellcheck_bin}" --version + tarball="actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz" + curl -sSfL --proto =https --tlsv1.2 --retry 3 --connect-timeout 20 --max-time 300 -O "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/${tarball}" + echo "${ACTIONLINT_SHA256} ${tarball}" | sha256sum -c - + tar xzf "${tarball}" actionlint + cd "${GITHUB_WORKSPACE}" + "${RUNNER_TEMP}/actionlint" -color -config-file /dev/null -shellcheck="${shellcheck_bin}" -pyflakes= + list="${RUNNER_TEMP}/shell-scripts" + git ls-files -z -- '.githooks/*' '*.sh' '*.bash' > "${list}" + # git grep exits 1 when nothing matches; any other failure stops. + git grep -lzI -e '^#!' > "${list}.candidates" || [[ $? -eq 1 ]] + shebang_re='^#![[:space:]]*(/usr)?/bin/(env[[:space:]]+)?(ba|da|k)?sh([[:space:]]|$)' + while IFS= read -r -d '' f; do + first_line="$(head -n 1 -- "${f}")" + if [[ "${first_line}" =~ ${shebang_re} ]]; then + printf '%s\0' "${f}" >> "${list}" + fi + done < "${list}.candidates" + sort -zu -o "${list}" -- "${list}" + mapfile -d '' -t script_list < "${list}" + if [[ "${#script_list[@]}" -eq 0 ]]; then + echo "::error::no shell scripts found to check" >&2 + exit 1 + fi + printf 'ShellCheck: %s\n' "${script_list[@]}" + "${shellcheck_bin}" -- "${script_list[@]}" + + # Security audit of the workflows, which actionlint does not do: + # template injection in `run:` scripts, credentials persisted by + # checkout, over-broad permissions, cache poisoning, unpinned actions. + # With the job's read-only token it also checks online that each pinned + # SHA really is a commit of the action's repository (impostor commits) + # and that no pinned version has a known advisory. Pinned and + # checksum-verified like actionlint; exits non-zero on any finding. + # The auditor persona runs every audit at every confidence: the + # code-quality ones the default persona hides (unnamed jobs, ...) and + # the low-confidence ones pedantic still drops. Every one passes today. + # --strict-collection fails on a workflow zizmor cannot parse, which it + # otherwise only warns about and skips, auditing nothing in it. + # --no-config: a `zizmor.yml` or `.github/zizmor.yml` (committed, or + # added by a PR) cannot disable audits or loosen the pin policy unseen; + # silencing a finding takes an inline `# zizmor: ignore[...]`, in review. + - name: zizmor + env: + ZIZMOR_VERSION: 1.32.0 + ZIZMOR_SHA256: bb110cc765eca9cd7efb2e284a956be5974c60027b0970f16397d86208a9957b + GH_TOKEN: ${{ github.token }} + run: | + tarball="zizmor-x86_64-unknown-linux-gnu.tar.gz" + cd "${RUNNER_TEMP}" + curl -sSfL --proto =https --tlsv1.2 --retry 3 --connect-timeout 20 --max-time 300 -O "https://github.com/zizmorcore/zizmor/releases/download/v${ZIZMOR_VERSION}/${tarball}" + echo "${ZIZMOR_SHA256} ${tarball}" | sha256sum -c - + tar xzf "${tarball}" zizmor + cd "${GITHUB_WORKSPACE}" + "${RUNNER_TEMP}/zizmor" --color=always --persona=auditor --strict-collection --no-config .github/workflows + + # Fast, needs no build: keep the clean packages clean. load_probe.rs is + # checked by itself, since the rest of victory-loader is not clean yet. + - name: rustfmt (clean packages) + run: | + read -r -a crates <<< "${RUSTFMT_CRATES}" + cargo fmt --check "${crates[@]}" + rustfmt --check --edition 2024 crates/victory-loader/tests/load_probe.rs + + - name: clippy (all targets) + run: | + read -r -a crates <<< "${LINUX_CRATES}" + cargo clippy --all-targets --locked "${crates[@]}" -- -D warnings + + # The steps above build default features only, so code behind the + # `diagnostics` (and victory-shader's `host`) features is never compiled. + # Lint it too. Both builds stay: some code is cfg(not(feature = ...)). + - name: clippy (all features) + run: | + read -r -a crates <<< "${LINUX_CRATES}" + cargo clippy --all-targets --all-features --locked "${crates[@]}" -- -D warnings + + # Every step builds its crates together, so Cargo unifies their + # features: a crate that uses a dependency's feature (one of serde's, + # object's, windows-sys's, ...) without enabling it in its own + # Cargo.toml still builds, because a sibling enables it, and breaks only + # when built alone (`cargo test -p` it, or a downstream user). Check + # each crate by itself, with default features and with all of its own. + # Lints stay with clippy above; this only fails on build errors. + - name: cargo check (each crate on its own) + run: | + read -r -a crates <<< "${LINUX_CRATES}" + for ((i = 1; i < ${#crates[@]}; i += 2)); do + cargo check --locked --quiet --all-targets -p "${crates[i]}" + cargo check --locked --quiet --all-targets --all-features -p "${crates[i]}" + done + + # Doc tests run under `cargo test` below, but rustdoc's own lints (a + # renamed item leaving a dangling [`link`], a public doc linking to a + # private item) only fire when the docs are built. Private items are + # documented too, so their doc comments (most of the code's) are linted + # as well; a public doc linking to a private item still fails. The + # second run turns every feature on, so the doc comments on `diagnostics` + # (and victory-shader's `host`) code are linted too. + - name: rustdoc (clean crates) + env: + RUSTDOCFLAGS: -D warnings + run: | + read -r -a crates <<< "${RUSTDOC_CRATES}" + cargo doc --no-deps --locked --document-private-items "${crates[@]}" + cargo doc --no-deps --locked --document-private-items --all-features "${crates[@]}" + + # The skipped tests parse the test executable itself as a PE image, which + # is an ELF on Linux. They still run on Windows. Once the workspace's + # Linux gates land they are cfg(windows) and these --skip flags are no-ops. + # --no-fail-fast: report failures from every test binary, not the first. + # The second run turns every feature on, like the clippy and rustdoc + # steps: `diagnostics` changes what some code does (victory-core's log + # cap, victory-shader's loop limit read from the environment), so the + # tests must pass with it too, not only compile. + # Two more runs build the tests the way the game itself is built: the + # release profile (what ships), and the diag profile with every feature + # (the development build, `--profile diag --features diagnostics`). Both + # optimise and drop debug assertions and overflow checks, which the dev + # profile above keeps: an invariant held only by a debug_assert (the + # shader IR and bitcode writer have several), arithmetic that panics in + # debug but wraps in release, or unsafe code (the loader's, the PE + # parser's) whose undefined behaviour only shows once the optimiser + # relies on it would otherwise pass here and misbehave only in a real + # build. Each adds one optimised build of the crates, well under the + # job's timeout. + # The release run also uses --test-threads 1: the runner compiles with as + # many cores as cargo wants, but each test binary then runs one test at + # a time, so a test that races on a shared static, a temp file under + # TMPDIR, or an OS-global resource can still pass under the default + # parallel harness on a fast machine and fail under Wine or in a + # debugger, where timing differs. One ordered pass is enough; the other + # three runs keep the default threading so nothing only fails in release. + # All four runs get a fresh, empty TMPDIR (std::env::temp_dir() reads it), so + # a test that leaves scratch files behind fails here: the checkout check + # below never sees the temp dir, and on a contributor's machine the + # leftovers pile up in /tmp with every run. rustc and the linker clean + # up their own temp files there, so the directory must end up empty. + # HOME is a fresh, empty directory too, with the XDG base directories + # unset: victory-core's config falls back to $XDG_CACHE_HOME or + # ~/.cache for its cache and data, so a test that resolves the default + # config instead of passing its own paths would read a contributor's + # real cache (game data included) and write into it, passing there and + # nowhere else. Anything a test leaves in that HOME fails the step as + # well. rustup and cargo keep their own homes: both are pinned to where + # they were before HOME moves, so the toolchain and the registry cache + # are the ones the steps above used. + # Both directories sit under one whose name has a space and a non-ASCII + # letter, as a contributor's may ("/home/zoë/My Files"). The runner's + # own paths are plain ASCII with no spaces, so a test that splits a + # temp path on whitespace, passes it unquoted through a shell, or + # assumes it is ASCII would otherwise pass here and fail for them. + # All four also have no network: they run in a new network namespace + # (unshare, as the runner user, so permission checks still apply) that + # holds only a downed loopback, with CARGO_NET_OFFLINE set. A test or + # build script that downloads something (a fixture, a reference file) + # passes here only by luck of the network and fails for anyone offline + # or behind a proxy; this makes it fail every time instead. The steps + # above already fetched every dependency, all features included, into + # CARGO_HOME. Ubuntu 24.04 lets unprivileged users create user + # namespaces only after an AppArmor sysctl is lifted, so lift it first + # (on this throwaway runner) and fail loudly if unshare still cannot. + # All four also start from an empty environment (env -i) that keeps + # only what Cargo, rustup and the linker need, plus the settings above. + # The runner exports dozens of variables a contributor's shell never + # has (CI, GITHUB_*, RUNNER_*, ImageOS, a UTF-8 LANG), and a + # contributor's shell has ones the runner never does (VICTORY_LOG, + # RUST_LOG, VICTORY_CONFIG, LOCALAPPDATA, LC_ALL): a test that reads + # any of them, directly or through a default it resolves, passes in + # one place and fails in the other. With none of them set, a test sees + # the same environment here as under `env -i` locally. A kept variable + # that is unset becomes empty rather than going missing, which would + # change what Cargo and rustup do, so only set ones are passed on. + # LC_ALL=C is kept explicitly (the runner has a UTF-8 LANG, a contributor + # may have another): libc collation, character classes and strerror + # strings then match a POSIX locale everywhere. + # All four also run under umask 077, not the runner's 022, so every + # file and directory a test or build script makes is private to its + # owner, as on a contributor's machine set up that way (a hardened + # distro default, or a shared box). A test that has another process + # read back what it wrote as a different mode, compares the mode of a + # file it made against 0644 or 0755, or copies a file's permissions + # and expects group or world bits would otherwise pass here and fail + # there. The umask is inherited through unshare and env -i, and + # checked inside them, so the tests see exactly it. + # #[ignore] tests never run in the four runs above, nor anywhere else + # unless someone asks for them by name, so they rot unseen: a benchmark + # that unwraps an API it no longer matches still compiles and still + # "passes" by being skipped. The ones that need nothing from outside + # the repository (the synthetic benchmarks in IGNORED_HERMETIC) run + # here too, once, in the release profile they are written for; their + # timings are only printed, so a slow runner cannot fail them. The + # rest (IGNORED_EXTERNAL) read game data or reference files named by + # environment variables and cannot run here. Every ignored test in the + # Linux crates must be on exactly one of the two lists in all four + # build passes above (default, all-features, release, diag), so a + # cfg(feature) or profile-only benchmark cannot hide from the lists, a + # new one is either run or says why it cannot be, and a renamed or + # deleted one cannot leave a stale entry behind. + - name: cargo test + env: + IGNORED_HERMETIC: >- + bcpack::tests::bcpack_throughput + emit::bitcode::tests::bench_write + IGNORED_EXTERNAL: >- + bcpack::tests::reference_chunks + xma::tests::matches_a_reference_decoder + xma::tests::walks_saved_streams + run: | + userns=/proc/sys/kernel/apparmor_restrict_unprivileged_userns + if [[ -e "${userns}" && "$(< "${userns}")" != 0 ]]; then + sudo sysctl -q -w kernel.apparmor_restrict_unprivileged_userns=0 + fi + umask 077 + export CARGO_NET_OFFLINE=true + export CARGO_HOME="${CARGO_HOME:-${HOME}/.cargo}" + export RUSTUP_HOME="${RUSTUP_HOME:-${HOME}/.rustup}" + scratch="${RUNNER_TEMP}/cargo test ä" + export HOME="${scratch}/home" + mkdir -p "${HOME}" + unset XDG_CACHE_HOME XDG_CONFIG_HOME XDG_DATA_HOME XDG_STATE_HOME + export TMPDIR="${scratch}/tmp" + mkdir "${TMPDIR}" + export LC_ALL=C + keep=() + for name in PATH HOME TMPDIR CARGO_HOME RUSTUP_HOME CARGO_NET_OFFLINE \ + CARGO_TERM_COLOR CARGO_INCREMENTAL RUST_BACKTRACE LC_ALL; do + if [[ -v "${name}" ]]; then + keep+=("${name}=${!name}") + fi + done + offline=(unshare --user --map-current-user --net -- env -i "${keep[@]}") + inner_uid="$("${offline[@]}" id -u)" + if [[ "${inner_uid}" != "${UID}" ]]; then + echo "::error::unshare did not keep the runner's user id" >&2 + exit 1 + fi + inner_umask="$("${offline[@]}" sh -c umask)" + if [[ "${inner_umask}" != 0077 ]]; then + echo "::error::the tests would run under umask ${inner_umask}, not 0077" >&2 + exit 1 + fi + # Fail if anything beyond the kept variables reaches the tests. + extra="$("${offline[@]}" env | cut -d= -f1 | grep -vxF -f <(printf '%s\n' "${keep[@]%%=*}") || true)" + if [[ -n "${extra}" ]]; then + echo "::error::the test environment is not empty beyond the kept variables" >&2 + printf '%s\n' "${extra}" >&2 + exit 1 + fi + read -r -a crates <<< "${LINUX_CRATES}" + skips=( + --skip image::tests::parses_own_test_binary + --skip image::tests::rva_to_file_offset_maps_entry_point + --skip image::tests::rva_to_file_offset_rejects_offsets_past_4_gib + --skip image::tests::rejects_iat_outside_image + --skip prepare::tests::patches_own_test_binary + --skip prepare::tests::keeps_iat_slots_when_import_size_excludes_the_terminator + --skip prepare::tests::file_name_is_stable_per_build + ) + "${offline[@]}" cargo test --locked --no-fail-fast "${crates[@]}" -- --exact "${skips[@]}" + "${offline[@]}" cargo test --locked --no-fail-fast --all-features "${crates[@]}" -- --exact "${skips[@]}" + "${offline[@]}" cargo test --locked --no-fail-fast --release "${crates[@]}" -- --exact --test-threads 1 "${skips[@]}" + "${offline[@]}" cargo test --locked --no-fail-fast --profile diag --all-features "${crates[@]}" -- --exact "${skips[@]}" + read -r -a hermetic <<< "${IGNORED_HERMETIC}" + read -r -a external <<< "${IGNORED_EXTERNAL}" + expected="${RUNNER_TEMP}/ignored-expected" + listed="${RUNNER_TEMP}/ignored-listed" + printf '%s\n' "${hermetic[@]}" "${external[@]}" | sort > "${expected}" + dups="$(uniq -d "${expected}")" + if [[ -n "${dups}" ]]; then + echo "::error::a test is listed twice in IGNORED_HERMETIC/IGNORED_EXTERNAL" >&2 + printf '%s\n' "${dups}" >&2 + exit 1 + fi + for build in default --all-features --release "--profile diag --all-features"; do + case "${build}" in + default) flags=() ;; + --all-features) read -r -a flags <<< "--all-features" ;; + --release) read -r -a flags <<< "--release" ;; + *) read -r -a flags <<< "${build}" ;; + esac + "${offline[@]}" cargo test --locked -q "${flags[@]}" "${crates[@]}" -- --list --ignored --format terse > "${listed}.raw" + sed -n 's/: test$//p' "${listed}.raw" | sort -u > "${listed}" + if ! diff "${listed}" "${expected}" > "${listed}.diff"; then + echo "::error::ignored tests (cargo test ${build}) differ from IGNORED_HERMETIC + IGNORED_EXTERNAL (< listed, > expected)" >&2 + cat "${listed}.diff" >&2 + exit 1 + fi + done + "${offline[@]}" cargo test --locked --no-fail-fast --release "${crates[@]}" -- --exact --ignored "${hermetic[@]}" + leftovers="$(find "${TMPDIR}" -mindepth 1 -maxdepth 2)" + if [[ -n "${leftovers}" ]]; then + echo "::error::cargo test left files in TMPDIR" >&2 + printf '%s\n' "${leftovers}" >&2 + exit 1 + fi + leftovers="$(find "${HOME}" -mindepth 1 -maxdepth 3)" + if [[ -n "${leftovers}" ]]; then + echo "::error::cargo test wrote into HOME" >&2 + printf '%s\n' "${leftovers}" >&2 + exit 1 + fi + + # Builds, build scripts and tests must leave the checkout as they found + # it: a test writing scratch files into the source tree (instead of a + # temp dir), a build script regenerating a tracked file, or rustfmt or + # xtask rewriting something would otherwise pass here and dirty every + # contributor's tree. Untracked files count too, and so do ignored ones + # (a test's scratch.bin), except the build output in target/ and a + # fixture's target/. --locked already covers Cargo.lock. + - name: Checkout unchanged by the steps above + run: | + changes="$(git status --porcelain=v1 --untracked-files=all)" + if [[ -n "${changes}" ]]; then + echo "::error::the steps above modified or created files in the checkout" >&2 + printf '%s\n' "${changes}" >&2 + git diff --stat >&2 + exit 1 + fi + # .gitignore hides *.bin, *.dll, *.dat, ... from `git status`, so a + # scratch file of those kinds would pass the check above. List the + # ignored files too (whole ignored directories collapse to one + # entry) and allow only the build output directories. + list="${RUNNER_TEMP}/ignored-files" + git ls-files -z --others --ignored --exclude-standard --directory > "${list}" + mapfile -d '' -t ignored < "${list}" + stray=() + for f in "${ignored[@]}"; do + if [[ "${f}" != target/ && ! "${f}" =~ ^tests/fixtures/[^/]+/target/$ ]]; then + stray+=("${f}") + fi + done + if [[ "${#stray[@]}" -ne 0 ]]; then + echo "::error::the steps above created ignored files outside target/" >&2 + printf '%s\n' "${stray[@]}" >&2 + exit 1 + fi + + # Type-checks the Windows build from Linux: no MSVC, no linking, nothing runs. + # Catches compile errors in cfg(windows) code (most of victory-gpu, + # victory-hle and apps/victory, and the Windows-only tests) that the job + # above never compiles. + windows-target-check: + name: windows-target-check + runs-on: ubuntu-24.04 + # checkout only. + permissions: + contents: read + timeout-minutes: 30 + env: + # blake3's build script compiles C/assembly with MSVC tools for this + # target. Its build script reads this variable to select the pure-Rust + # implementation; nothing is linked here, so the choice has no effect. + CARGO_FEATURE_PURE: "1" + # rustc warnings (unused imports, dead code, ...) fail every step, + # including the workspace-wide `cargo check` ones. Set for the whole job + # so all steps share one build. + # Dependencies are unaffected: cargo caps their lints. + RUSTFLAGS: -D warnings + steps: + # Nothing here pushes; keep the token out of .git/config. + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + + # rust-toolchain.toml already lists the x86_64-pc-windows-msvc target. + # --no-self-update: as in the linux job. + - name: Install pinned toolchain + run: rustup toolchain install --no-self-update + + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + key: windows-target + save-if: ${{ github.ref == 'refs/heads/main' }} + + - name: cargo check (workspace, all targets) + run: cargo check --locked --workspace --all-targets --target x86_64-pc-windows-msvc + + - name: clippy (Windows target, clean crates) + run: | + read -r -a crates <<< "${WINDOWS_CLIPPY_CRATES}" + cargo clippy --locked --all-targets --target x86_64-pc-windows-msvc "${crates[@]}" -- -D warnings + + # Same as the step above with every feature on, so the + # `diagnostics` code (frame capture, the host debug layer, scripted keys, + # mostly cfg(windows)) is compiled and linted too. Both builds stay: some + # code is cfg(not(feature = "diagnostics")). + - name: cargo check + clippy (Windows target, all features) + run: | + read -r -a crates <<< "${WINDOWS_CLIPPY_CRATES}" + cargo check --locked --workspace --all-targets --all-features --target x86_64-pc-windows-msvc + cargo clippy --locked --all-targets --all-features --target x86_64-pc-windows-msvc "${crates[@]}" -- -D warnings + + # As the Linux job's per-crate step: the steps above unify features + # across the workspace, so a crate missing a feature it uses on a + # dependency (windows-sys's Win32_* features most of all) still builds. + # Check each one by itself. RUSTFLAGS above makes warnings fail too. + - name: cargo check (Windows target, each crate on its own) + run: | + read -r -a crates <<< "${WINDOWS_CLIPPY_CRATES}" + for ((i = 1; i < ${#crates[@]}; i += 2)); do + cargo check --locked --quiet --all-targets --target x86_64-pc-windows-msvc -p "${crates[i]}" + cargo check --locked --quiet --all-targets --all-features --target x86_64-pc-windows-msvc -p "${crates[i]}" + done + + # The hle-probe fixture is outside the workspace (load_probe builds it on + # demand on Windows), so the steps above never compile it. It is + # Windows-only and needs no linker to check. It cannot inherit the + # workspace lints, so its Cargo.toml repeats them (SAFETY comments etc.). + - name: clippy (hle-probe fixture, Windows target) + run: > + cargo clippy --locked --all-targets --target x86_64-pc-windows-msvc + --manifest-path tests/fixtures/hle-probe/Cargo.toml -- -D warnings + + # Same rustdoc lints as the Linux job (private items included), but for + # the Windows-only code it never compiles, plus the hle-probe fixture. + # Nothing is linked; RUSTFLAGS above is unchanged, so the dependency + # builds are shared with the steps above. The all-features run covers + # the docs on the `diagnostics` code, which is mostly cfg(windows). + - name: rustdoc (Windows target, clean crates) + env: + RUSTDOCFLAGS: -D warnings + run: | + read -r -a crates <<< "${WINDOWS_RUSTDOC_CRATES}" + cargo doc --no-deps --locked --document-private-items --target x86_64-pc-windows-msvc "${crates[@]}" + cargo doc --no-deps --locked --document-private-items --all-features --target x86_64-pc-windows-msvc "${crates[@]}" + cargo doc --no-deps --locked --document-private-items --target x86_64-pc-windows-msvc --manifest-path tests/fixtures/hle-probe/Cargo.toml + + # The fixture is outside the workspace, so `cargo fmt --all` never reaches + # it. It is rustfmt-clean today; keep it that way. (The workspace itself + # is not rustfmt-clean on main yet, so it is not checked here.) + - name: rustfmt (hle-probe fixture) + run: cargo fmt --check --manifest-path tests/fixtures/hle-probe/Cargo.toml + + # As in the linux job: the Windows-target builds (the workspace's and the + # hle-probe fixture's, build scripts included) must leave the checkout as + # they found it. Build output (target/, the fixture's target/) does not + # count; anything else, tracked, untracked or ignored, fails. The + # fixture's --locked steps already cover its own Cargo.lock. + - name: Checkout unchanged by the steps above + run: | + changes="$(git status --porcelain=v1 --untracked-files=all)" + if [[ -n "${changes}" ]]; then + echo "::error::the steps above modified or created files in the checkout" >&2 + printf '%s\n' "${changes}" >&2 + git diff --stat >&2 + exit 1 + fi + # .gitignore hides *.bin, *.dll, *.dat, ... from `git status`, so a + # scratch file of those kinds would pass the check above. List the + # ignored files too (whole ignored directories collapse to one + # entry) and allow only the build output directories. + list="${RUNNER_TEMP}/ignored-files" + git ls-files -z --others --ignored --exclude-standard --directory > "${list}" + mapfile -d '' -t ignored < "${list}" + stray=() + for f in "${ignored[@]}"; do + if [[ "${f}" != target/ && ! "${f}" =~ ^tests/fixtures/[^/]+/target/$ ]]; then + stray+=("${f}") + fi + done + if [[ "${#stray[@]}" -ne 0 ]]; then + echo "::error::the steps above created ignored files outside target/" >&2 + printf '%s\n' "${stray[@]}" >&2 + exit 1 + fi + + # Cargo.toml declares `rust-version` (the MSRV) for every member, but the + # jobs above build with the newer toolchain pinned in rust-toolchain.toml, + # so code using a newer language feature or std API, or a Cargo.lock bump + # to a dependency that needs a newer rustc, passed CI and broke anyone + # building with the declared version. Type-check with exactly that version + # (read from Cargo.toml, so the two cannot drift): the Linux crates and the + # whole workspace for the Windows target, default and all features, plus + # the hle-probe fixture, which load_probe builds with the same cargo that + # ran the test. Only `cargo check`: older rustc and clippy warn + # differently, so warnings are left to the pinned-toolchain jobs. Its own + # target dir in RUNNER_TEMP keeps a second compiler's output out of the + # rust-cache entries the other jobs share. + msrv: + name: msrv + runs-on: ubuntu-24.04 + # checkout only. + permissions: + contents: read + timeout-minutes: 30 + env: + # As in windows-target-check: blake3's build script picks its + # pure-Rust code instead of calling MSVC's tools. Nothing is linked. + CARGO_FEATURE_PURE: "1" + steps: + # Nothing here pushes; keep the token out of .git/config. + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + + # The root [workspace.package] rust-version is read with the runner's + # Python 3 tomllib (-I: no site packages, no cwd on sys.path), since + # cargo would first install the pinned toolchain. Every member must + # inherit it; one that declares its own would not be checked against + # the version it claims. --no-self-update: as in the linux job. + - name: Install the rust-version toolchain + run: | + msrv="$(python3 -I -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["rust-version"])')" + if [[ ! "${msrv}" =~ ^[0-9]+\.[0-9]+(\.[0-9]+)?$ ]]; then + echo "::error file=Cargo.toml::unexpected workspace rust-version '${msrv}'" >&2 + exit 1 + fi + rustup toolchain install "${msrv}" --profile minimal --target x86_64-pc-windows-msvc --no-self-update + metadata="$(cargo +"${msrv}" metadata --locked --no-deps --format-version 1)" + others="$(jq -r --arg v "${msrv}" '.packages[] | select(.rust_version != $v) | "\(.name) (\(.rust_version))"' <<< "${metadata}")" + if [[ -n "${others}" ]]; then + echo "::error::workspace members whose rust-version is not the workspace's ${msrv}:" >&2 + printf '%s\n' "${others}" >&2 + exit 1 + fi + echo "MSRV=${msrv}" >> "${GITHUB_ENV}" + echo "CARGO_TARGET_DIR=${RUNNER_TEMP}/msrv-target" >> "${GITHUB_ENV}" + + - name: cargo check (Linux crates) + run: | + read -r -a crates <<< "${LINUX_CRATES}" + cargo +"${MSRV}" check --locked --all-targets "${crates[@]}" + cargo +"${MSRV}" check --locked --all-targets --all-features "${crates[@]}" + + - name: cargo check (Windows target, workspace and hle-probe fixture) + run: | + cargo +"${MSRV}" check --locked --workspace --all-targets --target x86_64-pc-windows-msvc + cargo +"${MSRV}" check --locked --workspace --all-targets --all-features --target x86_64-pc-windows-msvc + cargo +"${MSRV}" check --locked --all-targets --target x86_64-pc-windows-msvc --manifest-path tests/fixtures/hle-probe/Cargo.toml + + # As in the linux and windows-target-check jobs: build scripts and the + # msrv checks must leave the checkout as they found it (output under + # CARGO_TARGET_DIR in RUNNER_TEMP, or target/, does not count). + - name: Checkout unchanged by the steps above + run: | + changes="$(git status --porcelain=v1 --untracked-files=all)" + if [[ -n "${changes}" ]]; then + echo "::error::the steps above modified or created files in the checkout" >&2 + printf '%s\n' "${changes}" >&2 + git diff --stat >&2 + exit 1 + fi + list="${RUNNER_TEMP}/ignored-files" + git ls-files -z --others --ignored --exclude-standard --directory > "${list}" + mapfile -d '' -t ignored < "${list}" + stray=() + for f in "${ignored[@]}"; do + if [[ "${f}" != target/ && ! "${f}" =~ ^tests/fixtures/[^/]+/target/$ ]]; then + stray+=("${f}") + fi + done + if [[ "${#stray[@]}" -ne 0 ]]; then + echo "::error::the steps above created ignored files outside target/" >&2 + printf '%s\n' "${stray[@]}" >&2 + exit 1 + fi diff --git a/README.md b/README.md index 36b77e4..d0a0f82 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,9 @@ loads the world, where rendering fails. | Loading into the world (about 50 s) | works | | The world (first mission's intro) | reached and runs with indirect draws; its title card renders, the scene after it is still dark; 0.5-1.8 s per frame | -Tested on one machine: Windows 11, AMD RX 6700 XT. +Tested on one machine: Windows 11, AMD RX 6700 XT; and on Linux under +Proton Experimental: CachyOS, AMD RX 9070 XT (see +[docs/linux-proton.md](docs/linux-proton.md)). > **Warning.** Entering the world on a real GPU can currently hang it, and > Windows then resets the display driver (every monitor goes black for a @@ -46,19 +48,43 @@ What each part does today and what it still needs: ## Getting started -Requirements: Windows 10/11 x64, a CPU with AVX2, a Direct3D 12 GPU with +Community reports show the Windows-target build running on Linux under +Wine/Proton with vkd3d-proton. This is experimental; see +[Linux + Wine/Proton](docs/linux-wine.md) for the reported setup and caveats. +The project does not currently build as a native Linux application; cross-build +the Windows executable and run it under Wine/Proton instead. + +Windows requirements: Windows 10/11 x64, a CPU with AVX2, a Direct3D 12 GPU with shader model 6.6 (and mesh shaders for the world), Rust (pinned in `rust-toolchain.toml`). +Under Wine or Proton, indirect execution also needs DXC's `dxcompiler.dll` (with +its `dxil.dll`): Wine's `d3dcompiler_47` cannot compile the indirect-argument +clamp. It is looked for in `VICTORY_DXC` (the DLL or its folder), beside the +`dxil.dll` that shader validation finds, then the executable's folder and System32. + The title also needs several GiB of available Windows commit at startup. Check **Committed** under **Task Manager → Performance → Memory**. If `crashes.log` reports Windows error 1455, close other applications or increase the Windows paging file size, then retry. +On Linux, enter the Nix development shell and build the Windows executable: + +```sh +nix-shell +cargo xwin build --release -p victory --target x86_64-pc-windows-msvc +./scripts/run-ge-proton.sh +``` + +The launch helper defaults to the supplied game path and uses an installed +GE-Proton release; pass a different executable path to override it. + +On Windows, run the workspace tests and install the asset-policy hook: + ```powershell +cargo test --workspace # needs no game data cargo xtask install-hooks # asset-policy check on every commit copy victory.example.toml victory.toml # then set your paths (outside the repo) -cargo test --workspace # needs no game data cargo run -p victory -- config # check your paths ``` @@ -85,6 +111,19 @@ title's window has focus: | F / H | stick clicks | | Esc, Tab | Menu, View | +### Linux (Proton) + +VIctory also runs on Linux under Proton Experimental, built with +`cargo-xwin`, and gets as far there as on Windows: see +[docs/linux-proton.md](docs/linux-proton.md) and `scripts/proton-run.sh`. + +Tests on a Linux host, under Wine: `cargo xtask wine-test` cross-builds the +Windows test binaries (clang-cl, lld-link and llvm-lib on `PATH`, the MSVC CRT +and Windows SDK from `xwin splat --output ~/.xwin`) and runs them in a Wine +prefix of their own under `target/`. `--vkd3d-proton ` puts that +folder's `d3d12.dll` and `d3d12core.dll` into the prefix (Wine's own D3D12 +has no shader model 6.6); arguments after `--` go to `cargo test`. + ## Commands ``` diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index 4cf7c31..dcc0e2f 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -18,7 +18,7 @@ use clap::{Parser, Subcommand, ValueEnum}; #[command( name = "victory", version, - about = "Run an Xbox Series title natively on Windows" + about = "Inspect and translate Xbox Series title files; run titles on Windows" )] struct Cli { #[command(subcommand)] diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 5213147..5e32c14 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -1,6 +1,8 @@ use std::path::Path; -use anyhow::{Context, Result}; +#[cfg(windows)] +use anyhow::Context; +use anyhow::Result; use crate::{Console, Unimplemented}; diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index 4ea1f14..4a5f327 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -7,8 +7,13 @@ use std::sync::Mutex; use std::sync::atomic::{AtomicUsize, Ordering}; use anyhow::Result; +#[cfg(not(windows))] +use unsupported::{Host, Validator, host}; +use victory_shader::emit; +#[cfg(windows)] use victory_shader::emit::host::{self, Host}; -use victory_shader::emit::{self, validator::Validator}; +#[cfg(windows)] +use victory_shader::emit::validator::Validator; use victory_shader::structure::{self, Atom, LaneExit}; use victory_shader::{ Container, FourCC, HwStage, NativeProgram, RootType, ShaderError, ir, native_programs, @@ -160,6 +165,12 @@ pub fn run( jobs: Option, ) -> Result<()> { let paths = crate::default_paths(paths)?; + // The validator and the host checks are Windows-only; on other hosts + // they are skipped with a note instead of failing. + let validate_requested = validate; + let pipelines_requested = pipelines; + let validate = validate && cfg!(windows); + let pipelines = pipelines && cfg!(windows); let dll = validate.then(Validator::default_path).flatten(); if validate { Validator::load(dll.as_deref()).map_err(anyhow::Error::msg)?; @@ -168,9 +179,13 @@ pub fn run( dll.as_ref() .map_or("dxil.dll".into(), |p| p.display().to_string()) ); + } else if validate_requested { + println!("validator skipped (Windows only)"); } if pipelines { Host::new(false).map_err(anyhow::Error::msg)?; + } else if pipelines_requested { + println!("host pipelines skipped (Windows only)"); } let pairs: Vec<(String, String)> = std::env::var("VICTORY_PAIRS") .unwrap_or_default() @@ -271,22 +286,29 @@ pub fn run( t.ms_emitted, t.ms_programs, t.ms_validated, t.ms_pipelines ); if !pairs.is_empty() { - let host = Host::new(false).map_err(anyhow::Error::msg)?; - let kept = lock(&kept); - let find = |name: &str| kept.iter().find(|(l, _)| l.contains(name)); - for (v, p) in &pairs { - let made = match (find(v), find(p)) { - (Some((_, vs)), Some((_, ps))) => if vs.stage == HwStage::Ms { - host.mesh_pipeline(vs, ps) - } else { - host.pipeline(vs, ps) - } - .map(|_| "pipeline created".to_owned()) - .unwrap_or_else(|e| e), - _ => "not emitted".to_owned(), - }; - println!("pair {v} + {p}: {made}"); + // The host check is Windows-only: without a host device the + // pairs are not checked at all. + #[cfg(windows)] + { + let host = Host::new(false).map_err(anyhow::Error::msg)?; + let kept = lock(&kept); + let find = |name: &str| kept.iter().find(|(l, _)| l.contains(name)); + for (v, p) in &pairs { + let made = match (find(v), find(p)) { + (Some((_, vs)), Some((_, ps))) => if vs.stage == HwStage::Ms { + host.mesh_pipeline(vs, ps) + } else { + host.pipeline(vs, ps) + } + .map(|_| "pipeline created".to_owned()) + .unwrap_or_else(|e| e), + _ => "not emitted".to_owned(), + }; + println!("pair {v} + {p}: {made}"); + } } + #[cfg(not(windows))] + println!("host pipelines skipped (Windows only)"); } let mut lines = t.lines; lines.sort(); @@ -669,3 +691,62 @@ fn tally_structured(program: &ir::Program, s: &structure::Structured, t: &mut Ta fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { m.lock().unwrap_or_else(|e| e.into_inner()) } + +/// `--validate` and `--pipelines` need the host's DXIL validator and D3D12 +/// device, which only Windows has; elsewhere they refuse to start. +#[cfg(not(windows))] +mod unsupported { + use std::path::{Path, PathBuf}; + + use victory_shader::emit::HostShader; + + const WHY: &str = "needs Windows (the host DXIL validator and D3D12)"; + + pub struct Validator; + + impl Validator { + pub fn default_path() -> Option { + None + } + + pub fn load(_: Option<&Path>) -> Result { + Err(WHY.into()) + } + + pub fn validate(&mut self, _: &mut [u8]) -> Result<(), String> { + Err(WHY.into()) + } + } + + pub struct Host; + + impl Host { + pub fn new(_warp: bool) -> Result { + Err(WHY.into()) + } + + pub fn pipeline(&self, _: &HostShader, _: &HostShader) -> Result<(), String> { + Err(WHY.into()) + } + + pub fn mesh_pipeline(&self, _: &HostShader, _: &HostShader) -> Result<(), String> { + Err(WHY.into()) + } + + pub fn compute_pipeline(&self, _: &HostShader) -> Result<(), String> { + Err(WHY.into()) + } + } + + pub mod host { + use victory_shader::emit::HostShader; + + pub fn stub_ps() -> HostShader { + unreachable!("Host::new fails first") + } + + pub fn stub_vs(_: &HostShader) -> Result { + Err(super::WHY.into()) + } + } +} diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index 6a735b6..7ac09a1 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -330,13 +330,18 @@ impl Layout { let element_log2 = d.element_bytes.trailing_zeros(); let bpe = u64::from(d.element_bytes); let block_bytes = 1u64 << block_log2; - let thick = d.dimension == Dimension::Tex3d && (d.swizzle.standard() || d.swizzle.display()); + let thick = + d.dimension == Dimension::Tex3d && (d.swizzle.standard() || d.swizzle.display()); let block = if thick { // ComputeThickBlockDimension let amp = (block_log2 - 10) / 3; let rest = (block_log2 - 10) % 3; let b = BLOCK_1K_3D[element_log2 as usize]; - [b[0] << amp, b[1] << (amp + rest / 2), b[2] << (amp + u32::from(rest != 0))] + [ + b[0] << amp, + b[1] << (amp + rest / 2), + b[2] << (amp + u32::from(rest != 0)), + ] } else { // ComputeThinBlockDimension let samples_log2 = d.samples.trailing_zeros(); @@ -352,7 +357,12 @@ impl Layout { let mip_depth = |i: u32| if thick { padded_dim(d.depth, i, 1) } else { 1 }; let depth_of = |i: u32| if three_d { dim(d.depth, i, 1) } else { 1 }; let (width, height) = (|i| dim(d.width, i, d.block), |i| dim(d.height, i, d.block)); - let padded = |i| (padded_dim(d.width, i, d.block), padded_dim(d.height, i, d.block)); + let padded = |i| { + ( + padded_dim(d.width, i, d.block), + padded_dim(d.height, i, d.block), + ) + }; let mut mips = Vec::with_capacity(d.mips as usize); let mut first_tail_mip = d.mips; let mut slice_size = 0u64; @@ -367,10 +377,8 @@ impl Layout { offset: 0, tail: None, }); - slice_size = u64::from(mips[0].pitch) - * u64::from(mips[0].rows) - * bpe - * u64::from(d.samples); + slice_size = + u64::from(mips[0].pitch) * u64::from(mips[0].rows) * bpe * u64::from(d.samples); } else { // GetMipTailDim: the largest mip the tail takes. let mut tail_max = block; @@ -564,7 +572,8 @@ impl Layout { // offset inside the tail block. let y = y + m.tail.map_or(0, |t| t.y); let blocks = u64::from(y / bh) * u64::from(m.pitch / bw); - (blocks << log2) + u64::from(self.pattern[1][(y % bh) as usize] | self.pattern[2][z as usize]) + (blocks << log2) + + u64::from(self.pattern[1][(y % bh) as usize] | self.pattern[2][z as usize]) } /// The part of an address that depends on the column. @@ -594,9 +603,17 @@ impl Layout { row_pitch: usize, depth_pitch: usize, ) -> Result<(), Error> { - self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, len| { - linear[l..][..len].copy_from_slice(&tiled[t..][..len]); - }) + self.walk( + tiled.len(), + mip, + slice, + linear.len(), + row_pitch, + depth_pitch, + |t, l, len| { + linear[l..][..len].copy_from_slice(&tiled[t..][..len]); + }, + ) } /// The reverse of [`Layout::detile`]: linear rows into tiled memory. @@ -609,9 +626,17 @@ impl Layout { row_pitch: usize, depth_pitch: usize, ) -> Result<(), Error> { - self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, len| { - tiled[t..][..len].copy_from_slice(&linear[l..][..len]); - }) + self.walk( + tiled.len(), + mip, + slice, + linear.len(), + row_pitch, + depth_pitch, + |t, l, len| { + tiled[t..][..len].copy_from_slice(&linear[l..][..len]); + }, + ) } /// Visits contiguous runs as (tiled byte offset, linear byte offset, length). @@ -776,7 +801,14 @@ impl Texture { 1 }; let mips = match desc.mips { - 0 => 32 - desc.width.max(desc.height).max(depth3d).max(1).leading_zeros(), + 0 => { + 32 - desc + .width + .max(desc.height) + .max(depth3d) + .max(1) + .leading_zeros() + } n => n, }; let plane = |bytes| Desc { @@ -908,7 +940,11 @@ mod tests { let mut seen = vec![false; l.size as usize]; let mut tiled = vec![0u8; l.size as usize]; let n = d.element_bytes as usize; - let slices = if d.dimension == Dimension::Tex3d { 1 } else { d.depth }; + let slices = if d.dimension == Dimension::Tex3d { + 1 + } else { + d.depth + }; for slice in 0..slices { for mip in 0..d.mips { let m = l.mips[mip as usize]; @@ -937,7 +973,11 @@ mod tests { seen[at] = true; } } - assert!(back[base + plane - 11..base + plane].iter().all(|&b| b == 0xcc)); + assert!( + back[base + plane - 11..base + plane] + .iter() + .all(|&b| b == 0xcc) + ); } } } diff --git a/crates/victory-formats/src/xma.rs b/crates/victory-formats/src/xma.rs index e6ca931..589c5ed 100644 --- a/crates/victory-formats/src/xma.rs +++ b/crates/victory-formats/src/xma.rs @@ -151,7 +151,8 @@ fn next_frame(data: &[u8], start: usize, end: usize) -> Option { let mut end = end; if end.is_multiple_of(PACKET_BITS) || (last && end / PACKET_BITS == index) { // The next frame begins in the next packet of this stream. - let next = (end - 1) / PACKET_BITS + 1 + packet(data, (end - 1) / PACKET_BITS)?.skip as usize; + let next = + (end - 1) / PACKET_BITS + 1 + packet(data, (end - 1) / PACKET_BITS)?.skip as usize; let header = packet(data, next)?; end = next * PACKET_BITS + HEADER_BITS + header.first_frame_bit as usize; } @@ -248,10 +249,20 @@ fn codes() -> &'static Codes { scale: pairs(&SCALE, -60), scale_rl: pairs(&SCALE_RL, 0), coef: [ - Vlc::new(COEF0_SYMS.iter().zip(COEF0_LENS).map(|(&s, l)| (s as i32, l))), + Vlc::new( + COEF0_SYMS + .iter() + .zip(COEF0_LENS) + .map(|(&s, l)| (s as i32, l)), + ), pairs(&COEF1, 0), ], - vec4: Vlc::new(VEC4_SYMS.iter().zip(VEC4_LENS).map(|(&s, l)| (s as i32 - 1, l))), + vec4: Vlc::new( + VEC4_SYMS + .iter() + .zip(VEC4_LENS) + .map(|(&s, l)| (s as i32 - 1, l)), + ), vec2: pairs(&VEC2, -1), vec1: pairs(&VEC1, 0), } @@ -757,7 +768,11 @@ impl Decoder { ch.scale_factors = target; if ch.reuse_sf { let from = ch.saved_scale_factors[ch.scale_factor_idx]; - for (sf, &offset) in ch.saved_scale_factors[target].iter_mut().zip(&sf_offsets).take(self.num_bands) { + for (sf, &offset) in ch.saved_scale_factors[target] + .iter_mut() + .zip(&sf_offsets) + .take(self.num_bands) + { *sf = from[offset]; } } @@ -890,7 +905,11 @@ impl Decoder { } quant += 31; } - quant_step += if negative { -(quant + step) } else { quant + step }; + quant_step += if negative { + -(quant + step) + } else { + quant + step + }; } if self.channels_for_cur_subframe == 1 { self.ch[self.channel_indexes[0]].quant_step = quant_step; @@ -933,13 +952,21 @@ impl Decoder { let sf = ch.saved_scale_factors[ch.scale_factors]; for band in 0..self.num_bands { let end = sfb[band + 1].min(subframe_len); - let exp = ch.quant_step - (ch.max_scale_factor - sf[band]) * ch.scale_factor_step; + let exp = + ch.quant_step - (ch.max_scale_factor - sf[band]) * ch.scale_factor_step; let quant = 10f32.powf(exp as f32 / 20.0); - for (t, &c) in tmp[sfb[band]..end].iter_mut().zip(&ch.coeffs[sfb[band]..end]) { + for (t, &c) in tmp[sfb[band]..end] + .iter_mut() + .zip(&ch.coeffs[sfb[band]..end]) + { *t = c * quant; } } - imdct_half(&tmp[..subframe_len], &mut ch.out[at..at + subframe_len], scale); + imdct_half( + &tmp[..subframe_len], + &mut ch.out[at..at + subframe_len], + scale, + ); } } else { for i in 0..self.channels_for_cur_subframe { @@ -956,7 +983,10 @@ impl Decoder { start += (winlen - subframe_len) / 2; winlen = subframe_len; } - window_overlap(&mut ch.out[start..start + winlen], &windows()[log2(winlen) as usize - 7]); + window_overlap( + &mut ch.out[start..start + winlen], + &windows()[log2(winlen) as usize - 7], + ); ch.prev_block_len = subframe_len; } @@ -1057,7 +1087,9 @@ mod tests { -(input .iter() .enumerate() - .map(|(k, &x)| x as f64 * (std::f64::consts::PI / n as f64 * t * (k as f64 + 0.5)).cos()) + .map(|(k, &x)| { + x as f64 * (std::f64::consts::PI / n as f64 * t * (k as f64 + 0.5)).cos() + }) .sum::() as f32) }) .collect() @@ -1109,7 +1141,12 @@ mod tests { } } for i in n..5 * n { - assert!((out[i] - signal[i]).abs() < 1e-3, "{i}: {} vs {}", out[i], signal[i]); + assert!( + (out[i] - signal[i]).abs() < 1e-3, + "{i}: {} vs {}", + out[i], + signal[i] + ); } } diff --git a/crates/victory-formats/src/xma/tables.rs b/crates/victory-formats/src/xma/tables.rs index bf8fc43..7a78993 100644 --- a/crates/victory-formats/src/xma/tables.rs +++ b/crates/victory-formats/src/xma/tables.rs @@ -4,407 +4,871 @@ //! (symbol, code length) in canonical code order. pub(super) const CRITICAL_FREQ: [u16; 28] = [ - 100, 200, 300, 400, 510, 630, 770, 920, - 1080, 1270, 1480, 1720, 2000, 2320, 2700, 3150, - 3700, 4400, 5300, 6400, 7700, 9500, 12000, 15500, - 20675, 28575, 41375, 63875, + 100, 200, 300, 400, 510, 630, 770, 920, 1080, 1270, 1480, 1720, 2000, 2320, 2700, 3150, 3700, + 4400, 5300, 6400, 7700, 9500, 12000, 15500, 20675, 28575, 41375, 63875, ]; pub(super) const SCALE: [(u16, u8); 121] = [ - (58, 5), (64, 6), (66, 7), (65, 7), (62, 5), (63, 6), (68, 9), (69, 10), - (54, 15), (19, 19), (20, 19), (21, 19), (22, 19), (23, 19), (24, 19), (25, 19), - (26, 19), (27, 19), (28, 19), (29, 19), (30, 19), (31, 19), (32, 19), (33, 19), - (34, 19), (17, 19), (36, 19), (37, 19), (38, 19), (39, 19), (40, 19), (41, 19), - (42, 19), (43, 19), (44, 19), (45, 19), (46, 19), (47, 19), (48, 19), (49, 19), - (50, 19), (51, 19), (52, 19), (15, 19), (16, 19), (14, 19), (13, 19), (12, 19), - (11, 19), (10, 19), (0, 19), (9, 19), (8, 19), (7, 19), (6, 19), (5, 19), - (4, 19), (55, 13), (70, 13), (3, 19), (2, 19), (1, 19), (35, 19), (71, 19), - (72, 19), (73, 19), (74, 19), (75, 19), (76, 19), (77, 19), (78, 19), (79, 19), - (80, 19), (81, 19), (82, 19), (83, 19), (84, 19), (85, 19), (86, 19), (87, 19), - (88, 19), (89, 19), (90, 19), (91, 19), (92, 19), (93, 19), (94, 19), (95, 19), - (96, 19), (97, 19), (98, 19), (99, 19), (100, 19), (101, 19), (102, 19), (103, 19), - (104, 19), (105, 19), (106, 19), (107, 19), (108, 19), (109, 19), (110, 19), (111, 19), - (112, 19), (113, 19), (114, 19), (115, 19), (116, 19), (117, 19), (118, 19), (119, 19), - (120, 19), (18, 18), (53, 16), (56, 11), (57, 8), (67, 7), (61, 3), (59, 2), + (58, 5), + (64, 6), + (66, 7), + (65, 7), + (62, 5), + (63, 6), + (68, 9), + (69, 10), + (54, 15), + (19, 19), + (20, 19), + (21, 19), + (22, 19), + (23, 19), + (24, 19), + (25, 19), + (26, 19), + (27, 19), + (28, 19), + (29, 19), + (30, 19), + (31, 19), + (32, 19), + (33, 19), + (34, 19), + (17, 19), + (36, 19), + (37, 19), + (38, 19), + (39, 19), + (40, 19), + (41, 19), + (42, 19), + (43, 19), + (44, 19), + (45, 19), + (46, 19), + (47, 19), + (48, 19), + (49, 19), + (50, 19), + (51, 19), + (52, 19), + (15, 19), + (16, 19), + (14, 19), + (13, 19), + (12, 19), + (11, 19), + (10, 19), + (0, 19), + (9, 19), + (8, 19), + (7, 19), + (6, 19), + (5, 19), + (4, 19), + (55, 13), + (70, 13), + (3, 19), + (2, 19), + (1, 19), + (35, 19), + (71, 19), + (72, 19), + (73, 19), + (74, 19), + (75, 19), + (76, 19), + (77, 19), + (78, 19), + (79, 19), + (80, 19), + (81, 19), + (82, 19), + (83, 19), + (84, 19), + (85, 19), + (86, 19), + (87, 19), + (88, 19), + (89, 19), + (90, 19), + (91, 19), + (92, 19), + (93, 19), + (94, 19), + (95, 19), + (96, 19), + (97, 19), + (98, 19), + (99, 19), + (100, 19), + (101, 19), + (102, 19), + (103, 19), + (104, 19), + (105, 19), + (106, 19), + (107, 19), + (108, 19), + (109, 19), + (110, 19), + (111, 19), + (112, 19), + (113, 19), + (114, 19), + (115, 19), + (116, 19), + (117, 19), + (118, 19), + (119, 19), + (120, 19), + (18, 18), + (53, 16), + (56, 11), + (57, 8), + (67, 7), + (61, 3), + (59, 2), (60, 1), ]; pub(super) const SCALE_RL: [(u16, u8); 120] = [ - (103, 7), (80, 11), (60, 11), (18, 10), (56, 10), (21, 12), (90, 12), (58, 11), - (27, 11), (69, 12), (84, 15), (48, 15), (86, 14), (47, 13), (19, 10), (32, 9), - (78, 6), (5, 5), (28, 4), (53, 5), (9, 7), (31, 8), (38, 8), (10, 7), - (88, 11), (25, 12), (105, 12), (118, 11), (23, 12), (82, 14), (98, 16), (110, 16), - (108, 15), (93, 13), (68, 10), (72, 12), (97, 12), (81, 12), (42, 12), (64, 8), - (4, 4), (1, 2), (7, 6), (14, 7), (0, 9), (55, 9), (61, 9), (117, 10), - (24, 12), (44, 12), (67, 12), (70, 16), (99, 18), (96, 21), (95, 21), (2, 21), - (77, 21), (52, 21), (111, 21), (102, 20), (101, 17), (46, 15), (73, 15), (109, 15), - (51, 14), (92, 14), (30, 7), (11, 7), (66, 7), (15, 8), (16, 8), (116, 9), - (65, 9), (57, 10), (59, 10), (115, 9), (12, 7), (35, 9), (17, 9), (41, 9), - (20, 11), (91, 11), (26, 12), (75, 15), (45, 15), (107, 14), (83, 14), (100, 15), - (89, 15), (43, 11), (62, 9), (37, 9), (104, 8), (6, 5), (39, 8), (40, 9), - (34, 9), (79, 7), (8, 6), (63, 6), (87, 12), (94, 14), (49, 14), (50, 13), - (22, 11), (119, 10), (33, 9), (36, 9), (113, 11), (106, 12), (112, 13), (71, 15), - (85, 15), (74, 14), (76, 10), (114, 7), (29, 5), (54, 6), (13, 6), (3, 2), + (103, 7), + (80, 11), + (60, 11), + (18, 10), + (56, 10), + (21, 12), + (90, 12), + (58, 11), + (27, 11), + (69, 12), + (84, 15), + (48, 15), + (86, 14), + (47, 13), + (19, 10), + (32, 9), + (78, 6), + (5, 5), + (28, 4), + (53, 5), + (9, 7), + (31, 8), + (38, 8), + (10, 7), + (88, 11), + (25, 12), + (105, 12), + (118, 11), + (23, 12), + (82, 14), + (98, 16), + (110, 16), + (108, 15), + (93, 13), + (68, 10), + (72, 12), + (97, 12), + (81, 12), + (42, 12), + (64, 8), + (4, 4), + (1, 2), + (7, 6), + (14, 7), + (0, 9), + (55, 9), + (61, 9), + (117, 10), + (24, 12), + (44, 12), + (67, 12), + (70, 16), + (99, 18), + (96, 21), + (95, 21), + (2, 21), + (77, 21), + (52, 21), + (111, 21), + (102, 20), + (101, 17), + (46, 15), + (73, 15), + (109, 15), + (51, 14), + (92, 14), + (30, 7), + (11, 7), + (66, 7), + (15, 8), + (16, 8), + (116, 9), + (65, 9), + (57, 10), + (59, 10), + (115, 9), + (12, 7), + (35, 9), + (17, 9), + (41, 9), + (20, 11), + (91, 11), + (26, 12), + (75, 15), + (45, 15), + (107, 14), + (83, 14), + (100, 15), + (89, 15), + (43, 11), + (62, 9), + (37, 9), + (104, 8), + (6, 5), + (39, 8), + (40, 9), + (34, 9), + (79, 7), + (8, 6), + (63, 6), + (87, 12), + (94, 14), + (49, 14), + (50, 13), + (22, 11), + (119, 10), + (33, 9), + (36, 9), + (113, 11), + (106, 12), + (112, 13), + (71, 15), + (85, 15), + (74, 14), + (76, 10), + (114, 7), + (29, 5), + (54, 6), + (13, 6), + (3, 2), ]; pub(super) const SCALE_RL_RUN: [u8; 120] = [ - 0, 0, 0, 0, 1, 2, 3, 4, - 5, 6, 7, 8, 9, 10, 11, 12, - 13, 14, 15, 16, 17, 18, 19, 20, - 21, 22, 23, 24, 0, 1, 2, 3, - 4, 5, 6, 7, 8, 9, 10, 11, - 12, 13, 14, 15, 16, 17, 18, 19, - 20, 21, 22, 23, 24, 0, 1, 2, - 3, 4, 5, 6, 7, 8, 9, 10, - 11, 12, 13, 14, 15, 16, 17, 18, - 19, 20, 21, 22, 23, 24, 0, 1, - 2, 3, 4, 5, 6, 7, 8, 9, - 10, 11, 12, 13, 14, 15, 16, 17, - 18, 19, 20, 21, 22, 23, 24, 0, - 1, 2, 3, 4, 5, 6, 7, 8, - 9, 10, 0, 1, 0, 1, 0, 1, + 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, + 24, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 0, 1, + 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 0, 1, 2, 3, + 4, 5, 6, 7, 8, 9, 10, 0, 1, 0, 1, 0, 1, ]; pub(super) const SCALE_RL_LEVEL: [u8; 120] = [ - 0, 0, 1, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 6, - 6, 6, 6, 6, 6, 6, 6, 6, - 6, 6, 7, 7, 8, 8, 9, 9, + 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, ]; pub(super) const COEF0_LENS: [u8; 272] = [ - 2, 9, 14, 14, 13, 12, 13, 14, - 15, 15, 12, 10, 10, 10, 13, 14, - 15, 15, 12, 11, 13, 14, 14, 13, - 15, 15, 14, 12, 12, 8, 10, 10, - 15, 15, 14, 13, 14, 14, 13, 15, - 20, 20, 19, 21, 21, 20, 19, 17, - 17, 18, 18, 15, 15, 13, 12, 14, - 15, 15, 14, 15, 15, 12, 11, 6, - 7, 8, 9, 13, 13, 13, 14, 14, - 11, 10, 7, 8, 14, 14, 14, 14, - 12, 13, 13, 12, 12, 12, 11, 9, - 13, 14, 14, 12, 11, 11, 11, 9, - 8, 7, 14, 15, 15, 14, 14, 12, - 13, 15, 16, 17, 17, 14, 12, 12, - 12, 15, 15, 14, 14, 14, 13, 13, - 9, 9, 11, 11, 10, 7, 6, 13, - 15, 15, 14, 14, 14, 13, 14, 15, - 15, 13, 14, 14, 14, 14, 10, 9, - 10, 10, 11, 11, 10, 8, 9, 13, - 14, 14, 12, 11, 14, 15, 15, 13, - 12, 14, 14, 14, 14, 13, 14, 14, - 3, 5, 8, 10, 10, 15, 15, 14, - 14, 16, 16, 15, 12, 11, 11, 11, - 7, 8, 8, 9, 12, 13, 13, 12, - 14, 15, 15, 13, 10, 11, 11, 13, - 14, 14, 13, 14, 14, 11, 10, 13, - 15, 15, 14, 12, 11, 4, 6, 6, - 8, 12, 12, 12, 13, 13, 12, 13, - 13, 14, 14, 13, 13, 13, 9, 7, - 9, 11, 14, 14, 13, 14, 14, 13, - 10, 8, 7, 5, 9, 12, 13, 14, - 15, 15, 12, 12, 10, 14, 14, 13, - 12, 13, 14, 14, 12, 13, 13, 12, - 12, 12, 9, 7, 6, 3, 4, 4, + 2, 9, 14, 14, 13, 12, 13, 14, 15, 15, 12, 10, 10, 10, 13, 14, 15, 15, 12, 11, 13, 14, 14, 13, + 15, 15, 14, 12, 12, 8, 10, 10, 15, 15, 14, 13, 14, 14, 13, 15, 20, 20, 19, 21, 21, 20, 19, 17, + 17, 18, 18, 15, 15, 13, 12, 14, 15, 15, 14, 15, 15, 12, 11, 6, 7, 8, 9, 13, 13, 13, 14, 14, 11, + 10, 7, 8, 14, 14, 14, 14, 12, 13, 13, 12, 12, 12, 11, 9, 13, 14, 14, 12, 11, 11, 11, 9, 8, 7, + 14, 15, 15, 14, 14, 12, 13, 15, 16, 17, 17, 14, 12, 12, 12, 15, 15, 14, 14, 14, 13, 13, 9, 9, + 11, 11, 10, 7, 6, 13, 15, 15, 14, 14, 14, 13, 14, 15, 15, 13, 14, 14, 14, 14, 10, 9, 10, 10, + 11, 11, 10, 8, 9, 13, 14, 14, 12, 11, 14, 15, 15, 13, 12, 14, 14, 14, 14, 13, 14, 14, 3, 5, 8, + 10, 10, 15, 15, 14, 14, 16, 16, 15, 12, 11, 11, 11, 7, 8, 8, 9, 12, 13, 13, 12, 14, 15, 15, 13, + 10, 11, 11, 13, 14, 14, 13, 14, 14, 11, 10, 13, 15, 15, 14, 12, 11, 4, 6, 6, 8, 12, 12, 12, 13, + 13, 12, 13, 13, 14, 14, 13, 13, 13, 9, 7, 9, 11, 14, 14, 13, 14, 14, 13, 10, 8, 7, 5, 9, 12, + 13, 14, 15, 15, 12, 12, 10, 14, 14, 13, 12, 13, 14, 14, 12, 13, 13, 12, 12, 12, 9, 7, 6, 3, 4, + 4, ]; pub(super) const COEF0_SYMS: [u16; 272] = [ - 2, 25, 111, 94, 69, 58, 87, 93, - 136, 135, 59, 37, 34, 36, 82, 182, - 120, 138, 195, 45, 168, 216, 178, 86, - 140, 219, 186, 162, 239, 18, 156, 35, - 127, 236, 109, 85, 180, 253, 88, 147, - 268, 264, 256, 266, 270, 262, 260, 248, - 246, 252, 258, 137, 189, 230, 64, 179, - 146, 208, 101, 118, 238, 163, 46, 9, - 153, 0, 26, 247, 169, 76, 202, 131, - 194, 38, 13, 19, 132, 106, 191, 97, - 65, 198, 77, 62, 66, 164, 48, 27, - 81, 183, 102, 60, 47, 49, 159, 227, - 20, 14, 112, 263, 144, 217, 104, 63, - 79, 209, 269, 250, 254, 203, 241, 196, - 61, 220, 148, 124, 185, 100, 80, 78, - 193, 28, 50, 235, 41, 1, 10, 171, - 226, 150, 103, 114, 115, 170, 105, 211, - 149, 249, 108, 188, 107, 255, 231, 155, - 42, 40, 55, 160, 39, 21, 29, 215, - 234, 184, 228, 51, 116, 142, 145, 172, - 165, 181, 130, 113, 117, 89, 128, 204, - 3, 7, 154, 157, 43, 141, 265, 133, - 225, 271, 244, 221, 74, 54, 56, 52, - 15, 222, 22, 30, 83, 199, 173, 73, - 123, 210, 143, 175, 44, 53, 237, 174, - 139, 134, 110, 218, 129, 161, 213, 177, - 267, 151, 125, 67, 223, 5, 11, 192, - 23, 214, 243, 166, 200, 176, 68, 224, - 187, 257, 261, 232, 96, 251, 31, 16, - 32, 57, 207, 121, 91, 126, 119, 99, - 158, 24, 212, 8, 33, 70, 92, 205, - 240, 242, 75, 197, 233, 259, 190, 98, - 71, 201, 122, 206, 72, 90, 95, 84, - 167, 245, 229, 17, 12, 4, 152, 6, + 2, 25, 111, 94, 69, 58, 87, 93, 136, 135, 59, 37, 34, 36, 82, 182, 120, 138, 195, 45, 168, 216, + 178, 86, 140, 219, 186, 162, 239, 18, 156, 35, 127, 236, 109, 85, 180, 253, 88, 147, 268, 264, + 256, 266, 270, 262, 260, 248, 246, 252, 258, 137, 189, 230, 64, 179, 146, 208, 101, 118, 238, + 163, 46, 9, 153, 0, 26, 247, 169, 76, 202, 131, 194, 38, 13, 19, 132, 106, 191, 97, 65, 198, + 77, 62, 66, 164, 48, 27, 81, 183, 102, 60, 47, 49, 159, 227, 20, 14, 112, 263, 144, 217, 104, + 63, 79, 209, 269, 250, 254, 203, 241, 196, 61, 220, 148, 124, 185, 100, 80, 78, 193, 28, 50, + 235, 41, 1, 10, 171, 226, 150, 103, 114, 115, 170, 105, 211, 149, 249, 108, 188, 107, 255, 231, + 155, 42, 40, 55, 160, 39, 21, 29, 215, 234, 184, 228, 51, 116, 142, 145, 172, 165, 181, 130, + 113, 117, 89, 128, 204, 3, 7, 154, 157, 43, 141, 265, 133, 225, 271, 244, 221, 74, 54, 56, 52, + 15, 222, 22, 30, 83, 199, 173, 73, 123, 210, 143, 175, 44, 53, 237, 174, 139, 134, 110, 218, + 129, 161, 213, 177, 267, 151, 125, 67, 223, 5, 11, 192, 23, 214, 243, 166, 200, 176, 68, 224, + 187, 257, 261, 232, 96, 251, 31, 16, 32, 57, 207, 121, 91, 126, 119, 99, 158, 24, 212, 8, 33, + 70, 92, 205, 240, 242, 75, 197, 233, 259, 190, 98, 71, 201, 122, 206, 72, 90, 95, 84, 167, 245, + 229, 17, 12, 4, 152, 6, ]; pub(super) const COEF1: [(u16, u8); 244] = [ - (2, 2), (3, 3), (102, 3), (4, 4), (148, 6), (134, 9), (171, 10), (18, 10), - (11, 8), (159, 8), (14, 9), (156, 14), (235, 15), (61, 15), (38, 13), (153, 13), - (48, 14), (49, 14), (23, 11), (203, 13), (208, 19), (204, 19), (129, 18), (94, 17), - (87, 16), (62, 15), (174, 15), (147, 15), (29, 12), (191, 12), (64, 15), (65, 15), - (146, 14), (164, 13), (142, 5), (132, 4), (103, 5), (154, 7), (165, 9), (181, 11), - (109, 12), (30, 12), (86, 16), (92, 16), (239, 15), (138, 14), (39, 13), (50, 14), - (115, 15), (238, 21), (228, 21), (236, 21), (222, 21), (216, 20), (226, 20), (196, 18), - (192, 17), (120, 16), (221, 14), (51, 14), (24, 11), (143, 8), (7, 6), (9, 7), - (152, 10), (136, 12), (160, 12), (241, 15), (66, 15), (168, 14), (219, 14), (113, 14), - (193, 12), (19, 10), (173, 10), (105, 8), (149, 9), (15, 9), (205, 13), (207, 13), - (125, 17), (190, 17), (182, 16), (68, 15), (70, 15), (67, 15), (137, 13), (31, 12), - (223, 14), (116, 15), (210, 19), (220, 19), (198, 18), (126, 17), (88, 16), (41, 13), - (25, 11), (40, 13), (73, 15), (243, 15), (53, 14), (195, 12), (183, 11), (225, 14), - (52, 14), (71, 15), (121, 16), (89, 16), (170, 14), (55, 14), (69, 15), (83, 15), - (209, 13), (108, 11), (32, 12), (54, 14), (122, 16), (184, 16), (176, 15), (42, 13), - (12, 8), (161, 8), (6, 5), (167, 9), (106, 9), (20, 10), (145, 12), (111, 13), - (43, 13), (26, 11), (175, 10), (107, 10), (34, 12), (33, 12), (197, 12), (74, 15), - (128, 17), (232, 20), (212, 20), (224, 19), (202, 18), (90, 16), (57, 14), (227, 14), - (97, 16), (93, 16), (140, 15), (185, 11), (27, 11), (16, 9), (158, 11), (211, 13), - (56, 14), (117, 15), (72, 15), (166, 13), (91, 16), (95, 16), (80, 15), (101, 16), - (194, 17), (127, 17), (82, 15), (21, 10), (144, 10), (177, 10), (151, 6), (10, 7), - (157, 7), (8, 6), (5, 4), (13, 8), (0, 9), (213, 13), (46, 13), (199, 12), - (35, 12), (162, 12), (135, 10), (169, 9), (45, 13), (59, 14), (114, 14), (44, 13), - (188, 16), (186, 16), (75, 15), (79, 15), (118, 15), (187, 11), (112, 13), (139, 14), - (178, 15), (81, 15), (110, 12), (28, 11), (163, 8), (133, 6), (104, 6), (17, 9), - (22, 10), (229, 14), (172, 14), (217, 13), (201, 12), (36, 12), (218, 20), (242, 22), - (240, 22), (234, 21), (230, 19), (206, 18), (200, 18), (214, 18), (130, 17), (131, 17), - (141, 15), (84, 15), (76, 15), (215, 13), (58, 14), (231, 14), (233, 14), (180, 15), - (77, 15), (37, 12), (189, 11), (179, 10), (155, 10), (47, 13), (96, 16), (99, 16), - (119, 15), (63, 14), (237, 14), (78, 15), (85, 15), (60, 14), (98, 16), (100, 16), - (124, 16), (123, 16), (150, 11), (1, 7), + (2, 2), + (3, 3), + (102, 3), + (4, 4), + (148, 6), + (134, 9), + (171, 10), + (18, 10), + (11, 8), + (159, 8), + (14, 9), + (156, 14), + (235, 15), + (61, 15), + (38, 13), + (153, 13), + (48, 14), + (49, 14), + (23, 11), + (203, 13), + (208, 19), + (204, 19), + (129, 18), + (94, 17), + (87, 16), + (62, 15), + (174, 15), + (147, 15), + (29, 12), + (191, 12), + (64, 15), + (65, 15), + (146, 14), + (164, 13), + (142, 5), + (132, 4), + (103, 5), + (154, 7), + (165, 9), + (181, 11), + (109, 12), + (30, 12), + (86, 16), + (92, 16), + (239, 15), + (138, 14), + (39, 13), + (50, 14), + (115, 15), + (238, 21), + (228, 21), + (236, 21), + (222, 21), + (216, 20), + (226, 20), + (196, 18), + (192, 17), + (120, 16), + (221, 14), + (51, 14), + (24, 11), + (143, 8), + (7, 6), + (9, 7), + (152, 10), + (136, 12), + (160, 12), + (241, 15), + (66, 15), + (168, 14), + (219, 14), + (113, 14), + (193, 12), + (19, 10), + (173, 10), + (105, 8), + (149, 9), + (15, 9), + (205, 13), + (207, 13), + (125, 17), + (190, 17), + (182, 16), + (68, 15), + (70, 15), + (67, 15), + (137, 13), + (31, 12), + (223, 14), + (116, 15), + (210, 19), + (220, 19), + (198, 18), + (126, 17), + (88, 16), + (41, 13), + (25, 11), + (40, 13), + (73, 15), + (243, 15), + (53, 14), + (195, 12), + (183, 11), + (225, 14), + (52, 14), + (71, 15), + (121, 16), + (89, 16), + (170, 14), + (55, 14), + (69, 15), + (83, 15), + (209, 13), + (108, 11), + (32, 12), + (54, 14), + (122, 16), + (184, 16), + (176, 15), + (42, 13), + (12, 8), + (161, 8), + (6, 5), + (167, 9), + (106, 9), + (20, 10), + (145, 12), + (111, 13), + (43, 13), + (26, 11), + (175, 10), + (107, 10), + (34, 12), + (33, 12), + (197, 12), + (74, 15), + (128, 17), + (232, 20), + (212, 20), + (224, 19), + (202, 18), + (90, 16), + (57, 14), + (227, 14), + (97, 16), + (93, 16), + (140, 15), + (185, 11), + (27, 11), + (16, 9), + (158, 11), + (211, 13), + (56, 14), + (117, 15), + (72, 15), + (166, 13), + (91, 16), + (95, 16), + (80, 15), + (101, 16), + (194, 17), + (127, 17), + (82, 15), + (21, 10), + (144, 10), + (177, 10), + (151, 6), + (10, 7), + (157, 7), + (8, 6), + (5, 4), + (13, 8), + (0, 9), + (213, 13), + (46, 13), + (199, 12), + (35, 12), + (162, 12), + (135, 10), + (169, 9), + (45, 13), + (59, 14), + (114, 14), + (44, 13), + (188, 16), + (186, 16), + (75, 15), + (79, 15), + (118, 15), + (187, 11), + (112, 13), + (139, 14), + (178, 15), + (81, 15), + (110, 12), + (28, 11), + (163, 8), + (133, 6), + (104, 6), + (17, 9), + (22, 10), + (229, 14), + (172, 14), + (217, 13), + (201, 12), + (36, 12), + (218, 20), + (242, 22), + (240, 22), + (234, 21), + (230, 19), + (206, 18), + (200, 18), + (214, 18), + (130, 17), + (131, 17), + (141, 15), + (84, 15), + (76, 15), + (215, 13), + (58, 14), + (231, 14), + (233, 14), + (180, 15), + (77, 15), + (37, 12), + (189, 11), + (179, 10), + (155, 10), + (47, 13), + (96, 16), + (99, 16), + (119, 15), + (63, 14), + (237, 14), + (78, 15), + (85, 15), + (60, 14), + (98, 16), + (100, 16), + (124, 16), + (123, 16), + (150, 11), + (1, 7), ]; pub(super) const COEF0_RUN: [u16; 272] = [ - 0, 0, 0, 1, 2, 3, 4, 5, - 6, 7, 8, 9, 10, 11, 12, 13, - 14, 15, 16, 17, 18, 19, 20, 21, - 22, 23, 24, 25, 26, 27, 28, 29, - 30, 31, 32, 33, 34, 35, 36, 37, - 38, 39, 40, 41, 42, 43, 44, 45, - 46, 47, 48, 49, 50, 51, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, - 62, 63, 64, 65, 66, 67, 68, 69, - 70, 71, 72, 73, 74, 75, 76, 77, - 78, 79, 80, 81, 82, 83, 84, 85, - 86, 87, 88, 89, 90, 91, 92, 93, - 94, 95, 96, 97, 98, 99, 100, 101, - 102, 103, 104, 105, 106, 107, 108, 109, - 110, 111, 112, 113, 114, 115, 116, 117, - 118, 119, 120, 121, 122, 123, 124, 125, - 126, 127, 128, 129, 130, 131, 132, 133, - 134, 135, 136, 137, 138, 139, 140, 141, - 142, 143, 144, 145, 146, 147, 148, 149, - 0, 1, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, - 32, 33, 34, 35, 36, 37, 38, 39, - 0, 1, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 0, 1, 2, 3, - 4, 5, 6, 7, 8, 9, 0, 1, - 2, 3, 4, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, + 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, + 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, + 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, + 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, + 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, + 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 0, 1, 2, 3, 4, 5, 6, + 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, + 31, 32, 33, 34, 35, 36, 37, 38, 39, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, ]; pub(super) const COEF0_LEVEL: [f32; 272] = [ - 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, - 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, - 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, - 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, - 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, - 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, - 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, - 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0, - 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 5.0, 5.0, - 5.0, 5.0, 5.0, 6.0, 6.0, 7.0, 7.0, 8.0, - 8.0, 9.0, 9.0, 10.0, 10.0, 11.0, 11.0, 12.0, - 12.0, 13.0, 13.0, 14.0, 14.0, 15.0, 15.0, 16.0, - 16.0, 17.0, 17.0, 18.0, 18.0, 19.0, 19.0, 20.0, - 20.0, 21.0, 21.0, 22.0, 22.0, 23.0, 23.0, 24.0, - 24.0, 25.0, 25.0, 26.0, 26.0, 27.0, 27.0, 28.0, + 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, + 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 5.0, 5.0, 5.0, 5.0, 5.0, 6.0, + 6.0, 7.0, 7.0, 8.0, 8.0, 9.0, 9.0, 10.0, 10.0, 11.0, 11.0, 12.0, 12.0, 13.0, 13.0, 14.0, 14.0, + 15.0, 15.0, 16.0, 16.0, 17.0, 17.0, 18.0, 18.0, 19.0, 19.0, 20.0, 20.0, 21.0, 21.0, 22.0, 22.0, + 23.0, 23.0, 24.0, 24.0, 25.0, 25.0, 26.0, 26.0, 27.0, 27.0, 28.0, ]; pub(super) const COEF1_RUN: [u16; 244] = [ - 0, 0, 0, 1, 2, 3, 4, 5, - 6, 7, 8, 9, 10, 11, 12, 13, - 14, 15, 16, 17, 18, 19, 20, 21, - 22, 23, 24, 25, 26, 27, 28, 29, - 30, 31, 32, 33, 34, 35, 36, 37, - 38, 39, 40, 41, 42, 43, 44, 45, - 46, 47, 48, 49, 50, 51, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, - 62, 63, 64, 65, 66, 67, 68, 69, - 70, 71, 72, 73, 74, 75, 76, 77, - 78, 79, 80, 81, 82, 83, 84, 85, - 86, 87, 88, 89, 90, 91, 92, 93, - 94, 95, 96, 97, 98, 99, 0, 1, - 2, 3, 4, 5, 6, 7, 8, 9, - 10, 11, 12, 13, 14, 15, 16, 17, - 18, 19, 20, 21, 22, 23, 24, 25, - 26, 27, 28, 29, 0, 1, 2, 3, - 4, 5, 6, 7, 8, 9, 0, 1, - 2, 3, 4, 5, 0, 1, 2, 0, - 1, 2, 0, 1, 2, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 0, 0, + 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, + 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, + 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, + 97, 98, 99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, + 23, 24, 25, 26, 27, 28, 29, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 0, 1, 2, 0, 1, 2, + 0, 1, 2, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, ]; pub(super) const COEF1_LEVEL: [f32; 244] = [ - 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, - 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, - 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, - 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, - 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, - 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, - 4.0, 4.0, 4.0, 4.0, 5.0, 5.0, 5.0, 6.0, - 6.0, 6.0, 7.0, 7.0, 7.0, 8.0, 8.0, 9.0, - 9.0, 10.0, 10.0, 11.0, 11.0, 12.0, 12.0, 13.0, - 13.0, 14.0, 14.0, 15.0, 15.0, 16.0, 16.0, 17.0, - 17.0, 18.0, 18.0, 19.0, 19.0, 20.0, 20.0, 21.0, - 21.0, 22.0, 22.0, 23.0, 23.0, 24.0, 24.0, 25.0, - 25.0, 26.0, 26.0, 27.0, 27.0, 28.0, 28.0, 29.0, - 29.0, 30.0, 30.0, 31.0, 31.0, 32.0, 32.0, 33.0, - 33.0, 34.0, 34.0, 35.0, 35.0, 36.0, 36.0, 37.0, - 37.0, 38.0, 38.0, 39.0, 39.0, 40.0, 40.0, 41.0, - 41.0, 42.0, 42.0, 43.0, 43.0, 44.0, 44.0, 45.0, - 45.0, 46.0, 46.0, 47.0, 47.0, 48.0, 48.0, 49.0, - 49.0, 50.0, 51.0, 52.0, + 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 3.0, + 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 5.0, 5.0, 5.0, 6.0, + 6.0, 6.0, 7.0, 7.0, 7.0, 8.0, 8.0, 9.0, 9.0, 10.0, 10.0, 11.0, 11.0, 12.0, 12.0, 13.0, 13.0, + 14.0, 14.0, 15.0, 15.0, 16.0, 16.0, 17.0, 17.0, 18.0, 18.0, 19.0, 19.0, 20.0, 20.0, 21.0, 21.0, + 22.0, 22.0, 23.0, 23.0, 24.0, 24.0, 25.0, 25.0, 26.0, 26.0, 27.0, 27.0, 28.0, 28.0, 29.0, 29.0, + 30.0, 30.0, 31.0, 31.0, 32.0, 32.0, 33.0, 33.0, 34.0, 34.0, 35.0, 35.0, 36.0, 36.0, 37.0, 37.0, + 38.0, 38.0, 39.0, 39.0, 40.0, 40.0, 41.0, 41.0, 42.0, 42.0, 43.0, 43.0, 44.0, 44.0, 45.0, 45.0, + 46.0, 46.0, 47.0, 47.0, 48.0, 48.0, 49.0, 49.0, 50.0, 51.0, 52.0, ]; pub(super) const VEC4_LENS: [u8; 127] = [ - 1, 6, 8, 10, 10, 10, 10, 8, - 8, 10, 10, 9, 8, 8, 9, 12, - 12, 11, 12, 12, 11, 9, 9, 8, - 8, 9, 9, 8, 8, 9, 9, 12, - 12, 12, 14, 14, 13, 11, 11, 9, - 8, 9, 9, 11, 11, 10, 9, 8, - 6, 6, 6, 6, 6, 6, 11, 11, - 10, 11, 11, 10, 10, 11, 11, 9, - 7, 6, 7, 7, 6, 6, 6, 5, - 7, 11, 11, 10, 9, 8, 6, 9, - 9, 10, 10, 9, 8, 8, 6, 6, - 6, 8, 8, 9, 12, 12, 11, 10, - 8, 8, 8, 10, 10, 10, 10, 9, - 9, 8, 10, 11, 11, 9, 8, 8, - 8, 9, 9, 10, 11, 12, 12, 9, - 9, 9, 8, 8, 7, 7, 7, + 1, 6, 8, 10, 10, 10, 10, 8, 8, 10, 10, 9, 8, 8, 9, 12, 12, 11, 12, 12, 11, 9, 9, 8, 8, 9, 9, 8, + 8, 9, 9, 12, 12, 12, 14, 14, 13, 11, 11, 9, 8, 9, 9, 11, 11, 10, 9, 8, 6, 6, 6, 6, 6, 6, 11, + 11, 10, 11, 11, 10, 10, 11, 11, 9, 7, 6, 7, 7, 6, 6, 6, 5, 7, 11, 11, 10, 9, 8, 6, 9, 9, 10, + 10, 9, 8, 8, 6, 6, 6, 8, 8, 9, 12, 12, 11, 10, 8, 8, 8, 10, 10, 10, 10, 9, 9, 8, 10, 11, 11, 9, + 8, 8, 8, 9, 9, 10, 11, 12, 12, 9, 9, 9, 8, 8, 7, 7, 7, ]; pub(super) const VEC4_SYMS: [u16; 127] = [ - 0, 4370, 275, 8195, 4146, 12545, 8225, 290, - 4625, 515, 20, 8706, 8210, 4355, 4131, 16385, - 5121, 8961, 321, 1041, 51, 4641, 546, 4610, - 530, 513, 8451, 4385, 4130, 33, 8211, 5, - 66, 4161, 1281, 81, 6, 801, 8196, 8481, - 8449, 4611, 531, 561, 769, 12290, 8226, 19, - 4097, 2, 4369, 274, 4354, 4114, 12291, 16641, - 12305, 49, 12321, 260, 4100, 516, 21, 12546, - 8466, 4353, 4371, 4626, 257, 18, 17, 1, - 4386, 8241, 771, 4865, 8705, 8194, 4098, 12561, - 276, 50, 785, 4116, 8209, 4099, 273, 4113, - 258, 259, 4609, 35, 1026, 1025, 16401, 305, - 34, 529, 289, 770, 12289, 4, 4145, 4356, - 12306, 8193, 12801, 261, 16386, 4881, 3, 514, - 4129, 545, 306, 36, 4101, 65, 20481, 786, - 4401, 4866, 8721, 291, 8450, 8465, 4115, + 0, 4370, 275, 8195, 4146, 12545, 8225, 290, 4625, 515, 20, 8706, 8210, 4355, 4131, 16385, 5121, + 8961, 321, 1041, 51, 4641, 546, 4610, 530, 513, 8451, 4385, 4130, 33, 8211, 5, 66, 4161, 1281, + 81, 6, 801, 8196, 8481, 8449, 4611, 531, 561, 769, 12290, 8226, 19, 4097, 2, 4369, 274, 4354, + 4114, 12291, 16641, 12305, 49, 12321, 260, 4100, 516, 21, 12546, 8466, 4353, 4371, 4626, 257, + 18, 17, 1, 4386, 8241, 771, 4865, 8705, 8194, 4098, 12561, 276, 50, 785, 4116, 8209, 4099, 273, + 4113, 258, 259, 4609, 35, 1026, 1025, 16401, 305, 34, 529, 289, 770, 12289, 4, 4145, 4356, + 12306, 8193, 12801, 261, 16386, 4881, 3, 514, 4129, 545, 306, 36, 4101, 65, 20481, 786, 4401, + 4866, 8721, 291, 8450, 8465, 4115, ]; pub(super) const VEC2: [(u16, u8); 137] = [ - (19, 5), (165, 10), (211, 11), (46, 11), (75, 10), (177, 11), (12, 11), (86, 8), - (83, 7), (38, 7), (133, 9), (178, 10), (28, 10), (104, 9), (73, 9), (35, 5), - (52, 6), (113, 9), (8, 9), (101, 8), (69, 7), (0, 3), (71, 8), (119, 9), - (91, 10), (179, 10), (114, 8), (166, 10), (10, 10), (44, 10), (145, 10), (66, 6), - (21, 6), (24, 8), (146, 9), (26, 9), (65, 7), (5, 7), (226, 11), (225, 12), - (15, 12), (180, 10), (147, 9), (115, 8), (40, 8), (89, 9), (134, 9), (84, 7), - (54, 7), (42, 9), (60, 10), (31, 11), (193, 11), (181, 10), (76, 10), (148, 9), - (37, 6), (67, 6), (33, 6), (3, 6), (17, 6), (2, 6), (102, 8), (87, 8), - (116, 8), (56, 8), (50, 5), (20, 5), (120, 9), (58, 9), (29, 10), (194, 10), - (135, 9), (97, 8), (7, 8), (105, 9), (13, 11), (241, 12), (16, 12), (45, 10), - (149, 9), (74, 9), (98, 7), (23, 7), (85, 7), (70, 7), (195, 10), (161, 10), - (129, 9), (72, 8), (51, 5), (36, 5), (117, 8), (61, 10), (11, 10), (162, 9), - (1, 7), (4, 6), (49, 6), (68, 6), (9, 9), (27, 9), (130, 8), (39, 7), - (53, 6), (99, 7), (25, 8), (150, 9), (90, 9), (103, 8), (163, 9), (196, 10), - (210, 10), (136, 9), (121, 9), (41, 8), (131, 8), (43, 9), (164, 9), (118, 8), - (88, 8), (81, 7), (6, 7), (55, 7), (59, 9), (30, 10), (209, 11), (14, 11), - (151, 9), (106, 9), (82, 6), (22, 6), (100, 7), (132, 8), (57, 8), (18, 4), + (19, 5), + (165, 10), + (211, 11), + (46, 11), + (75, 10), + (177, 11), + (12, 11), + (86, 8), + (83, 7), + (38, 7), + (133, 9), + (178, 10), + (28, 10), + (104, 9), + (73, 9), + (35, 5), + (52, 6), + (113, 9), + (8, 9), + (101, 8), + (69, 7), + (0, 3), + (71, 8), + (119, 9), + (91, 10), + (179, 10), + (114, 8), + (166, 10), + (10, 10), + (44, 10), + (145, 10), + (66, 6), + (21, 6), + (24, 8), + (146, 9), + (26, 9), + (65, 7), + (5, 7), + (226, 11), + (225, 12), + (15, 12), + (180, 10), + (147, 9), + (115, 8), + (40, 8), + (89, 9), + (134, 9), + (84, 7), + (54, 7), + (42, 9), + (60, 10), + (31, 11), + (193, 11), + (181, 10), + (76, 10), + (148, 9), + (37, 6), + (67, 6), + (33, 6), + (3, 6), + (17, 6), + (2, 6), + (102, 8), + (87, 8), + (116, 8), + (56, 8), + (50, 5), + (20, 5), + (120, 9), + (58, 9), + (29, 10), + (194, 10), + (135, 9), + (97, 8), + (7, 8), + (105, 9), + (13, 11), + (241, 12), + (16, 12), + (45, 10), + (149, 9), + (74, 9), + (98, 7), + (23, 7), + (85, 7), + (70, 7), + (195, 10), + (161, 10), + (129, 9), + (72, 8), + (51, 5), + (36, 5), + (117, 8), + (61, 10), + (11, 10), + (162, 9), + (1, 7), + (4, 6), + (49, 6), + (68, 6), + (9, 9), + (27, 9), + (130, 8), + (39, 7), + (53, 6), + (99, 7), + (25, 8), + (150, 9), + (90, 9), + (103, 8), + (163, 9), + (196, 10), + (210, 10), + (136, 9), + (121, 9), + (41, 8), + (131, 8), + (43, 9), + (164, 9), + (118, 8), + (88, 8), + (81, 7), + (6, 7), + (55, 7), + (59, 9), + (30, 10), + (209, 11), + (14, 11), + (151, 9), + (106, 9), + (82, 6), + (22, 6), + (100, 7), + (132, 8), + (57, 8), + (18, 4), (34, 4), ]; pub(super) const VEC1: [(u16, u8); 101] = [ - (7, 5), (32, 8), (59, 10), (60, 10), (83, 11), (82, 11), (62, 10), (33, 8), - (45, 9), (61, 10), (84, 11), (85, 11), (1, 6), (13, 5), (19, 6), (25, 7), - (34, 8), (46, 9), (47, 9), (14, 5), (6, 5), (64, 10), (87, 11), (86, 11), - (63, 10), (88, 11), (90, 11), (35, 8), (26, 7), (0, 7), (48, 9), (65, 10), - (66, 10), (36, 8), (15, 5), (20, 6), (91, 11), (89, 11), (67, 10), (49, 9), - (50, 9), (69, 10), (92, 11), (93, 11), (27, 7), (5, 5), (37, 8), (68, 10), - (71, 10), (51, 9), (52, 9), (70, 10), (94, 11), (96, 11), (38, 8), (21, 6), - (16, 5), (4, 5), (28, 7), (53, 9), (95, 11), (97, 11), (73, 10), (39, 8), - (29, 7), (72, 10), (98, 11), (99, 11), (54, 9), (40, 8), (22, 6), (30, 7), - (55, 9), (74, 10), (76, 10), (56, 9), (75, 10), (77, 10), (17, 5), (3, 5), - (23, 6), (41, 8), (57, 9), (78, 10), (79, 10), (31, 7), (10, 4), (9, 4), - (100, 5), (2, 5), (11, 4), (8, 4), (18, 5), (42, 8), (58, 9), (80, 10), - (81, 10), (43, 8), (44, 8), (24, 6), (12, 4), + (7, 5), + (32, 8), + (59, 10), + (60, 10), + (83, 11), + (82, 11), + (62, 10), + (33, 8), + (45, 9), + (61, 10), + (84, 11), + (85, 11), + (1, 6), + (13, 5), + (19, 6), + (25, 7), + (34, 8), + (46, 9), + (47, 9), + (14, 5), + (6, 5), + (64, 10), + (87, 11), + (86, 11), + (63, 10), + (88, 11), + (90, 11), + (35, 8), + (26, 7), + (0, 7), + (48, 9), + (65, 10), + (66, 10), + (36, 8), + (15, 5), + (20, 6), + (91, 11), + (89, 11), + (67, 10), + (49, 9), + (50, 9), + (69, 10), + (92, 11), + (93, 11), + (27, 7), + (5, 5), + (37, 8), + (68, 10), + (71, 10), + (51, 9), + (52, 9), + (70, 10), + (94, 11), + (96, 11), + (38, 8), + (21, 6), + (16, 5), + (4, 5), + (28, 7), + (53, 9), + (95, 11), + (97, 11), + (73, 10), + (39, 8), + (29, 7), + (72, 10), + (98, 11), + (99, 11), + (54, 9), + (40, 8), + (22, 6), + (30, 7), + (55, 9), + (74, 10), + (76, 10), + (56, 9), + (75, 10), + (77, 10), + (17, 5), + (3, 5), + (23, 6), + (41, 8), + (57, 9), + (78, 10), + (79, 10), + (31, 7), + (10, 4), + (9, 4), + (100, 5), + (2, 5), + (11, 4), + (8, 4), + (18, 5), + (42, 8), + (58, 9), + (80, 10), + (81, 10), + (43, 8), + (44, 8), + (24, 6), + (12, 4), ]; - diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index a24dd1a..e186e8e 100644 --- a/crates/victory-gpu/Cargo.toml +++ b/crates/victory-gpu/Cargo.toml @@ -30,6 +30,7 @@ workspace = true windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_SystemInformation", "Win32_System_Threading"] } windows = { workspace = true, features = [ "Win32_Graphics_Direct3D", + "Win32_Graphics_Direct3D_Dxc", "Win32_Graphics_Direct3D_Fxc", "Win32_Graphics_Direct3D12", "Win32_Graphics_Dxgi", diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index e91cf62..0a6bbde 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -213,9 +213,62 @@ fn dump_on() -> bool { *ON.get_or_init(|| folder().is_some() && std::env::var_os("VICTORY_DUMP_TARGETS").is_some()) } +/// `VICTORY_SHOW_TARGET=x-f[-]`: each frame, the `n`th +/// (1-based, default 1) texture of that size and format the frame renders +/// to or writes, in first-use order, is presented instead of the title's +/// frame: a view of an intermediate target (a G-buffer's normals or +/// albedo, say) while the final image is still black. Names as in the +/// `VICTORY_DUMP_TARGETS` files (`frame----x-f`). +fn show_spec() -> Option<(u64, u32, i32, usize)> { + static SPEC: std::sync::OnceLock> = std::sync::OnceLock::new(); + *SPEC.get_or_init(|| { + let v = std::env::var("VICTORY_SHOW_TARGET").ok()?; + let mut parts = v.split('-'); + let (w, h) = parts.next()?.split_once('x')?; + let f = parts.next()?.strip_prefix('f')?.parse().ok()?; + let n = parts.next().map_or(Some(1), |n| n.parse().ok())?; + let spec = (w.parse().ok()?, h.parse().ok()?, f, n.max(1)); + tracing::info!( + ?spec, + "presenting an intermediate target (VICTORY_SHOW_TARGET)" + ); + Some(spec) + }) +} + +/// The frame being built's targets matching [`show_spec`], in order. +static SHOWN: std::sync::Mutex)>> = + std::sync::Mutex::new(Vec::new()); + +/// At a present: the target [`show_spec`] names, if this frame had it, and +/// its host state; the list starts afresh for the next frame. +pub(crate) fn take_shown() -> Option<(std::sync::Arc, u32)> { + use std::sync::atomic::Ordering::Relaxed; + let (.., n) = show_spec()?; + let shown = std::mem::take(&mut *SHOWN.lock().unwrap_or_else(|e| e.into_inner())); + let (_, copy) = shown.into_iter().nth(n - 1)?; + let state = copy.state.load(Relaxed); + Some((copy, state)) +} + /// Notes a title texture the frame being built renders to or writes. pub(crate) fn note_target(resource: crate::object::This) { - if resource.is_null() || !dump_on() || !listed(crate::queue::presented() + 1) { + if resource.is_null() { + return; + } + if let Some((w, h, f, _)) = show_spec() { + let mut shown = SHOWN.lock().unwrap_or_else(|e| e.into_inner()); + if !shown.iter().any(|&(r, _)| r == resource as usize) + && let Some(copy) = crate::resource::host_copy(resource) + { + // SAFETY: a live resource. + let d = unsafe { copy.texture.GetDesc() }; + if (d.Width, d.Height, d.Format.0) == (w, h, f) && d.SampleDesc.Count == 1 { + shown.push((resource as usize, copy)); + } + } + } + if !dump_on() || !listed(crate::queue::presented() + 1) { return; } let mut targets = TARGETS.lock().unwrap_or_else(|e| e.into_inner()); @@ -230,7 +283,9 @@ pub(crate) fn note_target(resource: crate::object::This) { pub(crate) fn dump_targets(frame: u64) { use std::sync::atomic::Ordering::Relaxed; let targets = std::mem::take(&mut *TARGETS.lock().unwrap_or_else(|e| e.into_inner())); - let Some(host) = crate::host::host() else { return }; + let Some(host) = crate::host::host() else { + return; + }; for (i, (resource, copy)) in targets.iter().enumerate() { let texture = ©.texture; // SAFETY: a live resource. @@ -240,7 +295,15 @@ pub(crate) fn dump_targets(frame: u64) { } // Every submission has run; the dump's list moves it there and back. let state = copy.state.load(Relaxed); - dump_one(host, texture, state, frame, i, *resource as crate::object::This, &d); + dump_one( + host, + texture, + state, + frame, + i, + *resource as crate::object::This, + &d, + ); } } @@ -271,7 +334,9 @@ fn dump_one( }; list.close(); host.execute(&[&list]); - let Some((buffer, footprint)) = read else { return }; + let Some((buffer, footprint)) = read else { + return; + }; let f = footprint.Footprint; let mut data = std::ptr::null_mut(); // SAFETY: the copy finished; the mapping spans the footprint's rows. @@ -281,7 +346,13 @@ fn dump_one( } let pitch = f.RowPitch as usize; let rows = std::slice::from_raw_parts(data.cast::(), pitch * f.Height as usize); - if let Some(rgba) = to_rgba(f.Format.0 as u32, f.Width as usize, f.Height as usize, pitch, rows) { + if let Some(rgba) = to_rgba( + f.Format.0 as u32, + f.Width as usize, + f.Height as usize, + pitch, + rows, + ) { let name = format!( "frame-{frame}-{i:02}-{resource:?}-{}x{}-f{}", d.Width, d.Height, d.Format.0 @@ -295,7 +366,11 @@ fn dump_one( } fn half(h: u16) -> f32 { - let (sign, exp, man) = ((h >> 15) as u32, ((h >> 10) & 0x1f) as i32, (h & 0x3ff) as f32); + let (sign, exp, man) = ( + (h >> 15) as u32, + ((h >> 10) & 0x1f) as i32, + (h & 0x3ff) as f32, + ); let v = match exp { 0 => man * 2f32.powi(-24), 31 => f32::INFINITY, @@ -323,7 +398,8 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option let mut out = Vec::with_capacity(w * h * 4); let px = |x: usize, y: usize, n: usize| &rows[y * pitch + x * n..][..n]; let u16_at = |b: &[u8], i: usize| u16::from_le_bytes([b[2 * i], b[2 * i + 1]]); - let u32_at = |b: &[u8], i: usize| u32::from_le_bytes(b[4 * i..4 * i + 4].try_into().unwrap_or([0; 4])); + let u32_at = + |b: &[u8], i: usize| u32::from_le_bytes(b[4 * i..4 * i + 4].try_into().unwrap_or([0; 4])); // Channel values as floats, then scaled. type Decode = Box [f32; 3]>; let (n, decode): (usize, Decode) = match format { @@ -346,23 +422,62 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option } return Some(out); } - 23..=25 | 89 => (4, Box::new(move |b| { - let v = u32_at(b, 0); - [(v & 0x3ff) as f32, (v >> 10 & 0x3ff) as f32, (v >> 20 & 0x3ff) as f32] - })), - 26 => (4, Box::new(move |b| { - let v = u32_at(b, 0); - [small_float(v & 0x7ff, 6), small_float(v >> 11 & 0x7ff, 6), small_float(v >> 22, 5)] - })), - 9..=10 => (8, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), half(u16_at(b, 2))])), - 11..=14 => (8, Box::new(move |b| [0, 1, 2].map(|i| f32::from(u16_at(b, i))))), - 33..=34 => (4, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), 0.0])), - 1..=2 => (16, Box::new(move |b| { - [0, 1, 2].map(|i| f32::from_bits(u32_at(b, i))) - })), - 15..=16 => (8, Box::new(move |b| [f32::from_bits(u32_at(b, 0)), f32::from_bits(u32_at(b, 1)), 0.0])), - 35..=38 => (4, Box::new(move |b| [f32::from(u16_at(b, 0)), f32::from(u16_at(b, 1)), 0.0])), - 48..=52 => (2, Box::new(move |b| [f32::from(b[0]), f32::from(b[1]), 0.0])), + 23..=25 | 89 => ( + 4, + Box::new(move |b| { + let v = u32_at(b, 0); + [ + (v & 0x3ff) as f32, + (v >> 10 & 0x3ff) as f32, + (v >> 20 & 0x3ff) as f32, + ] + }), + ), + 26 => ( + 4, + Box::new(move |b| { + let v = u32_at(b, 0); + [ + small_float(v & 0x7ff, 6), + small_float(v >> 11 & 0x7ff, 6), + small_float(v >> 22, 5), + ] + }), + ), + 9..=10 => ( + 8, + Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), half(u16_at(b, 2))]), + ), + 11..=14 => ( + 8, + Box::new(move |b| [0, 1, 2].map(|i| f32::from(u16_at(b, i)))), + ), + 33..=34 => ( + 4, + Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), 0.0]), + ), + 1..=2 => ( + 16, + Box::new(move |b| [0, 1, 2].map(|i| f32::from_bits(u32_at(b, i)))), + ), + 15..=16 => ( + 8, + Box::new(move |b| { + [ + f32::from_bits(u32_at(b, 0)), + f32::from_bits(u32_at(b, 1)), + 0.0, + ] + }), + ), + 35..=38 => ( + 4, + Box::new(move |b| [f32::from(u16_at(b, 0)), f32::from(u16_at(b, 1)), 0.0]), + ), + 48..=52 => ( + 2, + Box::new(move |b| [f32::from(b[0]), f32::from(b[1]), 0.0]), + ), // Single channels (and depth planes): shown as grey. 39..=43 => (4, Box::new(move |b| [f32::from_bits(u32_at(b, 0)); 3])), 19..=22 => (8, Box::new(move |b| [f32::from_bits(u32_at(b, 0)); 3])), @@ -531,11 +646,20 @@ mod tests { fn unorm16_and_xr_bias_targets_decode_as_their_formats() { // Red 0x8000 (a half-float -0), green 0x4000, blue 0. let unorm16 = [0x00, 0x80, 0x00, 0x40, 0, 0, 0xff, 0xff]; - assert_eq!(super::to_rgba(11, 1, 1, 8, &unorm16), Some(vec![255, 127, 0, 255])); + assert_eq!( + super::to_rgba(11, 1, 1, 8, &unorm16), + Some(vec![255, 127, 0, 255]) + ); // Red 0x3ff, green 0x1ff, blue 0, alpha 3. let xr = (0x3ffu32 | 0x1ff << 10 | 3 << 30).to_le_bytes(); - assert_eq!(super::to_rgba(89, 1, 1, 4, &xr), Some(vec![255, 127, 0, 255])); + assert_eq!( + super::to_rgba(89, 1, 1, 4, &xr), + Some(vec![255, 127, 0, 255]) + ); // B8G8R8A8 still swaps to RGBA. - assert_eq!(super::to_rgba(87, 1, 1, 4, &[1, 2, 3, 4]), Some(vec![3, 2, 1, 255])); + assert_eq!( + super::to_rgba(87, 1, 1, 4, &[1, 2, 3, 4]), + Some(vec![3, 2, 1, 255]) + ); } } diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 20b33fb..1182eb7 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -59,6 +59,11 @@ pub(crate) struct Heap { host: std::sync::OnceLock>, #[cfg(windows)] pending: std::sync::Mutex>, + /// The write-watch asking (see [`crate::watch::writes`]) up to which + /// the host heap has caught up with what the title wrote into its + /// memory itself (see [`resync_title_writes`]). + #[cfg(windows)] + synced: std::sync::atomic::AtomicU64, } pub(crate) fn heap<'a>(this: This) -> &'a Heap { @@ -68,6 +73,7 @@ pub(crate) fn heap<'a>(this: This) -> &'a Heap { impl Heap { /// Whether this is a sampler heap. + #[cfg(windows)] pub(crate) fn samplers(&self) -> bool { self.desc.kind == SAMPLERS } @@ -100,6 +106,7 @@ impl Heap { } /// The descriptor index of `handle` in this heap, if it lies in it. + #[cfg(windows)] pub(crate) fn index(&self, handle: u64) -> Option { let step = u64::from(increment(self.desc.kind)?); let at = handle.checked_sub(self.start)?; @@ -148,6 +155,49 @@ fn mirror(handle: u64) { } } +/// Brings the host heaps up to date with descriptors the title wrote into +/// heap memory itself (copies of whole slots, which no create or copy call +/// reports), before a submission runs: slots read directly by index (not +/// through a table) are made only from what was mirrored, so a slot the +/// title turned from a texture into a constant buffer kept the texture, +/// whose upper half the shader read as a buffer at address 0: a GPU page +/// fault and a lost device in the world. Only the 64 KiB blocks written +/// since the last call are looked at; heaps in memory the kernel does not +/// watch (ours, not the title's) are left as they are. +#[cfg(windows)] +pub(crate) fn resync_title_writes() { + use std::sync::atomic::Ordering::Relaxed; + // Held throughout: registered heaps stay alive while it is. + let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + for &(start, end, at) in heaps.iter() { + // SAFETY: registered heaps are live (removed when dropped). + let heap = unsafe { &*(at as *const Heap) }; + let (Some(Some(host)), Some(step)) = (heap.host.get(), increment(heap.desc.kind)) else { + continue; // no host heap yet: its first use mirrors everything + }; + let page = crate::watch::PAGE as u64; + let (first, last) = (start / page * page, end.div_ceil(page) * page); + let Some((now, written)) = crate::watch::writes(first as usize, last as usize, true) else { + continue; + }; + let before = heap.synced.swap(now, Relaxed); + let step = u64::from(step); + for (p, asked) in written { + if asked <= before { + continue; + } + let from = (p as u64 * page).max(start); + let to = ((p as u64 + 1) * page).min(end); + for i in (from - start) / step..(to - start).div_ceil(step) { + let i = i as u32; + if i < heap.desc.count { + host.mirror(i, start + u64::from(i) * step, false); + } + } + } + } +} + /// Gives back dynamic slots of the host heap behind the title heap at /// `heap`, if that heap still exists. #[cfg(windows)] @@ -383,6 +433,7 @@ fn record(handle: u64, view: View) { } /// The title released `resource`: the views naming it go stale. +#[cfg(any(windows, test))] pub(crate) fn forget(resource: usize) { let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); let Some(entries) = views.by_resource.remove(&resource) else { @@ -412,6 +463,7 @@ fn view_at(i: u32, generation: u32) -> Option { } /// The view recorded at `handle`, if one is (and its resource is alive). +#[cfg(any(windows, test))] pub(crate) fn view(handle: u64) -> Option { if handle == 0 { return None; @@ -564,15 +616,18 @@ pub(crate) extern "system" fn copy( } /// The view recorded at `handle`, if one is. +#[cfg(windows)] pub(crate) fn rtv_record(handle: u64) -> Option { tagged_record(handle, RTV_TAG) } /// The depth view recorded at `handle`, if one is. +#[cfg(windows)] pub(crate) fn dsv_record(handle: u64) -> Option { tagged_record(handle, DSV_TAG) } +#[cfg(windows)] fn tagged_record(handle: u64, tag: u32) -> Option { if handle == 0 { return None; @@ -624,6 +679,8 @@ pub(crate) extern "system" fn create_heap( host: std::sync::OnceLock::new(), #[cfg(windows)] pending: Default::default(), + #[cfg(windows)] + synced: std::sync::atomic::AtomicU64::new(0), }); #[cfg(windows)] if visible { diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 582f234..0d94ac0 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -51,7 +51,11 @@ pub(crate) fn near_heaps(va: u64) -> String { } else if va < start + bytes { format!("inside, slot {}", (va - start) / step) } else { - format!("{:#x} past its end (slot {})", va - start - bytes, (va - start) / step) + format!( + "{:#x} past its end (slot {})", + va - start - bytes, + (va - start) / step + ) }; text.push_str(&format!("; {kind} heap {start:#x}+{bytes:#x}: {place}")); } @@ -112,7 +116,11 @@ impl HostHeap { // shortcut: descriptors past the host's limit are left // out; a title that reaches them needs remapping. tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}"); - (make(PORTABLE_VIEWS).ok()?, PORTABLE_VIEWS - MIN_DYNAMIC, MIN_DYNAMIC) + ( + make(PORTABLE_VIEWS).ok()?, + PORTABLE_VIEWS - MIN_DYNAMIC, + MIN_DYNAMIC, + ) } Err(e) => { tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); @@ -155,7 +163,10 @@ impl HostHeap { if let Err(e) = h.fill_null(kind, count + extra) { tracing::warn!(error = %e, "host descriptor heap not made null"); } - tracing::debug!(ms = started.elapsed().as_millis(), "host descriptor heap made null"); + tracing::debug!( + ms = started.elapsed().as_millis(), + "host descriptor heap made null" + ); Some(h) } @@ -167,11 +178,12 @@ impl HostHeap { // SAFETY: plain heap creation and copies inside live heaps. unsafe { let block: ID3D12DescriptorHeap = - host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { - Type: kind, - NumDescriptors: BLOCK, - ..Default::default() - })?; + host.device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: BLOCK, + ..Default::default() + })?; let start = block.GetCPUDescriptorHandleForHeapStart(); let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start.ptr + (i * self.step) as usize, @@ -184,13 +196,15 @@ impl HostHeap { let mut filled = 1; while filled < BLOCK { let n = filled.min(BLOCK - filled); - host.device.CopyDescriptorsSimple(n, at(filled), start, kind); + host.device + .CopyDescriptorsSimple(n, at(filled), start, kind); filled += n; } let mut done = 0; while done < total { let n = BLOCK.min(total - done); - host.device.CopyDescriptorsSimple(n, self.cpu(done), start, kind); + host.device + .CopyDescriptorsSimple(n, self.cpu(done), start, kind); done += n; } } @@ -249,7 +263,9 @@ impl HostHeap { } let Some(first) = found else { static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| tracing::warn!(n, "no free dynamic descriptor slots: a table is not made")); + ONCE.call_once(|| { + tracing::warn!(n, "no free dynamic descriptor slots: a table is not made") + }); return None; }; taken[first..first + n].fill(true); @@ -306,6 +322,41 @@ impl HostHeap { } } + /// The shader-visible handle of slot `index`. + pub(crate) fn gpu_handle(&self, index: u32) -> D3D12_GPU_DESCRIPTOR_HANDLE { + // SAFETY: a live shader-visible heap. + let start = unsafe { self.heap.GetGPUDescriptorHandleForHeapStart().ptr }; + D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: start + u64::from(index) * u64::from(self.step), + } + } + + /// Makes slot `index` (a dynamic one) a raw buffer view of `len` bytes + /// of `buffer` from byte `offset` (4-byte units, rounded down), holding + /// the buffer while the slot does. + pub(crate) fn raw_srv_at(&self, index: u32, buffer: &ID3D12Resource, offset: u64, len: u64) { + let Some(host) = host() else { return }; + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: offset / 4, + NumElements: (len / 4).clamp(1, u64::from(u32::MAX)) as u32, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }, + }, + }; + // SAFETY: a live buffer and a slot of our heap; the range lies in it. + unsafe { + host.device + .CreateShaderResourceView(buffer, Some(&desc), self.cpu(index)) + }; + self.keep(index, Some(buffer.clone())); + } + /// Makes slot `index` (a dynamic one) a constant buffer view of host /// memory (the list's own, which it holds). pub(crate) fn constant_at(&self, index: u32, gpu: u64, size: u32) { @@ -383,7 +434,11 @@ impl HostHeap { /// a slot never made or left null. #[cfg(feature = "diagnostics")] pub(crate) fn describe_slot(&self, index: u32) -> Option { - let key = *self.made.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize)?; + let key = *self + .made + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get(index as usize)?; if key == 0 { return Some("null".into()); } @@ -554,7 +609,11 @@ fn buffer_uav( }; let offset = shadow.offset(address); if element == 0 || offset % element != 0 { - once!(offset, element, "unordered buffer view not on an element of its host copy"); + once!( + offset, + element, + "unordered buffer view not on an element of its host copy" + ); return None; } buffer.FirstElement += offset / element; @@ -562,8 +621,12 @@ fn buffer_uav( let host = host()?; // SAFETY: a live buffer and a slot of our heap. unsafe { - host.device - .CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), at) + host.device.CreateUnorderedAccessView( + &shadow.buffer, + None::<&ID3D12Resource>, + Some(&desc), + at, + ) }; Some(Some(shadow.buffer.clone())) } @@ -720,7 +783,10 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { // shortcut: unordered access to a texture the title placed // itself is not mirrored; give it a resource as shader // views of such textures get when a dispatch writes one. - once!(dimension = resource[0], "placed unordered texture view not mirrored"); + once!( + dimension = resource[0], + "placed unordered texture view not mirrored" + ); return None; } // The resource description's width, after the alignment. diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index d2537cc..8d36c12 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -74,6 +74,9 @@ pub(crate) struct State { /// Tables made afresh in this list: (table, what it holds) → first /// dynamic slot. fresh_tables: std::collections::HashMap<(u64, u64), u32>, + /// Root SRV views made in this list: (title heap, title address) → + /// dynamic slot (see [`State::bind_root_srv`]). + root_srv_slots: std::collections::HashMap<(usize, u64), u32>, /// The dynamic slots the list holds: title heap, first, count; given /// back when the list is reset or released. dynamic: Vec<(usize, u32, u32)>, @@ -245,7 +248,12 @@ impl State { } pub(crate) fn clear_vertex_buffers(&mut self, start: u32, count: u32) { - for slot in self.vertex.iter_mut().skip(start as usize).take(count as usize) { + for slot in self + .vertex + .iter_mut() + .skip(start as usize) + .take(count as usize) + { *slot = VertexView::default(); } } @@ -349,7 +357,10 @@ impl State { return false; }; if p.compute || p.mesh != mesh { - once!(mesh, "a draw or mesh dispatch with another kind of pipeline"); + once!( + mesh, + "a draw or mesh dispatch with another kind of pipeline" + ); return false; } if !self.bind(list, p, false) { @@ -493,6 +504,12 @@ impl State { } for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] { for &(slot, param) in views { + // Root SRVs are bounded one-view tables (see the host + // root signature). + if srv { + self.bind_root_srv(list, compute, slot, param); + continue; + } let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) else { once!(slot, "a shader reads a root view the title did not set"); @@ -516,6 +533,77 @@ impl State { true } + /// Binds the title's root SRV `slot` as the one-view table `param` (see + /// the host root signature): a raw view of the rest of the title + /// buffer's host copy, in a dynamic slot of the bound view heap, so + /// reads past the copy return zeros rather than fault. Zeros (our null + /// buffer) if the title set none or it lies outside every buffer. + fn bind_root_srv(&mut self, list: &HostList, compute: bool, slot: u8, param: u32) { + let l = &list.list; + let heap = self.heaps[0]; + if heap == 0 { + once!("a root SRV with no view heap bound: left unset"); + return; + } + let title_heap = crate::descriptor::heap(heap as This); + let Some(host) = title_heap.host() else { + return; + }; + let address = match self.roots_ref(compute).get(usize::from(slot)) { + Some(Root::View(address)) => *address, + _ => 0, + }; + let shadow = crate::shadow::find(address, 1) + .filter(|_| address != 0) + .map(|s| (s, address)); + // The same buffer again in this list: its slot, refreshed again. + if let Some(&index) = self.root_srv_slots.get(&(heap, address)) { + if let Some((shadow, address)) = &shadow { + shadow.refresh(list, *address, shadow.left(*address).min(1 << 20)); + } + let table = host.gpu_handle(index); + // SAFETY: an open list; the slot is held by this list. + unsafe { + if compute { + l.SetComputeRootDescriptorTable(param, table); + } else { + l.SetGraphicsRootDescriptorTable(param, table); + } + } + return; + } + let Some(index) = host.dynamic(1) else { + once!("no free dynamic slot for a root SRV: left unset"); + return; + }; + self.dynamic.push((heap, index, 1)); + self.root_srv_slots.insert((heap, address), index); + match shadow { + Some((shadow, address)) => { + let len = shadow.left(address); + shadow.refresh(list, address, len.min(1 << 20)); + host.raw_srv_at(index, &shadow.buffer, shadow.offset(address), len); + } + None => { + once!( + slot, + "a root SRV the title did not set, or outside every buffer: reads zeros" + ); + host.make_null(index); + } + } + let table = host.gpu_handle(index); + // SAFETY: an open list; the slot is in the bound heap and held by + // this list until it is reset. + unsafe { + if compute { + l.SetComputeRootDescriptorTable(param, table); + } else { + l.SetGraphicsRootDescriptorTable(param, table); + } + } + } + /// Runs a dispatch on the host. pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32) { #[cfg(feature = "diagnostics")] @@ -1032,13 +1120,19 @@ impl State { #[cfg(feature = "diagnostics")] match crate::pipeline::host_pipeline(self.pipeline as This) { None => crate::pipeline::note_drop(self.pipeline as This), - Some(p) => why(&format!("prepare failed (compute {}, mesh {})", p.compute, p.mesh)), + Some(p) => why(&format!( + "prepare failed (compute {}, mesh {})", + p.compute, p.mesh + )), } return false; } #[cfg(feature = "diagnostics")] list.note_op(|| { - self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH) + self.op_text( + format!("indirect kind {kind} max {max} at {arguments:#x}"), + kind == DISPATCH, + ) }); // SAFETY: an open list with everything set; the buffers are host // copies the list keeps alive (refresh), the signature is cached. @@ -1155,7 +1249,10 @@ fn describe(view: Option<&View>) -> String { crate::resource::host_resource(r).map(|t| { // SAFETY: a live resource. let d = unsafe { t.GetDesc() }; - format!("{}x{} f{} flags {:#x}", d.Width, d.Height, d.Format.0, d.Flags.0) + format!( + "{}x{} f{} flags {:#x}", + d.Width, d.Height, d.Format.0, d.Flags.0 + ) }) }; match view { diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs index 285e7bd..19509bb 100644 --- a/crates/victory-gpu/src/fence.rs +++ b/crates/victory-gpu/src/fence.rs @@ -135,7 +135,9 @@ static FUNCTIONS: Table<24> = { #[cfg(test)] mod tests { + #[cfg(windows)] use super::*; + #[cfg(windows)] use crate::object::slot; #[cfg(windows)] diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 6672c1e..39741ce 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -64,14 +64,18 @@ unsafe impl Sync for Host {} /// Time spent in submissions since the last frame-rate line, in /// microseconds: preparing them on the CPU (title memory copies, texture /// detiling), then waiting for the GPU. -static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] = - [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)]; +static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] = [ + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), +]; /// After submissions: shader-written ranges compared and copied back into /// title memory (microseconds, bytes that differed), since the last /// frame-rate line. -static COPY_BACK: [std::sync::atomic::AtomicU64; 2] = - [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)]; +static COPY_BACK: [std::sync::atomic::AtomicU64; 2] = [ + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), +]; /// Of the preparing: title memory copies (microseconds, bytes) and texture /// refreshes (microseconds, bytes hashed), since the last frame-rate line. @@ -104,9 +108,9 @@ pub(crate) fn fail(what: std::fmt::Arguments) -> ! { } match host.log_messages() { Some(first) => text.push_str(&format!("; debug layer: {first}")), - None if host.messages.is_none() => text.push_str( - "; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command", - ), + None if host.messages.is_none() => { + text.push_str("; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command") + } None => {} } } @@ -319,10 +323,8 @@ const STAMPS: u32 = 4096; #[cfg(feature = "diagnostics")] type Note = (String, Option<(u64, u64)>); -type States = std::collections::HashMap< - usize, - (u32, u32, std::sync::Arc), ->; +type States = + std::collections::HashMap)>; /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics /// builds). @@ -494,6 +496,21 @@ impl Host { // One submission at a time from preparation to copy-back: snapshots // and the ranges shaders write are per host copy, not per submission. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); + self.submit(&mut submitted, runs); + } + + /// Runs a title's submission: as [`execute`](Self::execute), but first, + /// under the same lock, starts a new watch submission and refreshes heap + /// slots the title wrote. Inside the lock, another queue's submission + /// can't refresh a heap while this one's GPU work still reads it. + pub(crate) fn execute_title(&self, runs: &[&HostList]) { + let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); + crate::watch::new_submission(); + crate::descriptor::resync_title_writes(); + self.submit(&mut submitted, runs); + } + + fn submit(&self, submitted: &mut u64, runs: &[&HostList]) { let started = std::time::Instant::now(); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Submissions, 1); @@ -545,8 +562,16 @@ impl Host { if groups.len() > 1 && started.elapsed() > std::time::Duration::from_millis(50) { // SAFETY: a plain query. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1); - let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len(); - tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list"); + let commands = runs[i] + .notes + .lock() + .unwrap_or_else(|e| e.into_inner()) + .len(); + tracing::warn!( + ms = started.elapsed().as_millis(), + commands, + "slow host list" + ); for (ms, op) in runs[i].slowest(frequency, 6) { tracing::warn!("slow list command, {ms:.1} ms: {op}"); } @@ -561,9 +586,19 @@ impl Host { if gpu > std::time::Duration::from_millis(250) { let pipelines: std::collections::BTreeSet = runs .iter() - .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone()) + .flat_map(|l| { + l.pipelines + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone() + }) .collect(); - tracing::warn!(ms = gpu.as_millis(), lists = runs.len(), ?pipelines, "slow host submission"); + tracing::warn!( + ms = gpu.as_millis(), + lists = runs.len(), + ?pipelines, + "slow host submission" + ); } // SAFETY: a plain query. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() { @@ -584,9 +619,9 @@ impl Host { for list in runs { for step in &list.deferred().copies { if let Step::GpuWrite(shadow, address, len) = step - && !back - .iter() - .any(|(s, a, l)| std::sync::Arc::ptr_eq(s, shadow) && (*a, *l) == (*address, *len)) + && !back.iter().any(|(s, a, l)| { + std::sync::Arc::ptr_eq(s, shadow) && (*a, *l) == (*address, *len) + }) { back.push((shadow.clone(), *address, *len)); } @@ -794,14 +829,20 @@ impl HostList { let device = &host()?.device; let mut heap: Option = None; let mut back: Option = None; - let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let readback = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: u64::from(STAMPS) * 8, Height: 1, DepthOrArraySize: 1, MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }; @@ -809,7 +850,11 @@ impl HostList { unsafe { device .CreateQueryHeap( - &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 }, + &D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, + Count: STAMPS, + NodeMask: 0, + }, &mut heap, ) .ok()?; @@ -838,7 +883,10 @@ impl HostList { return Vec::new(); }; let mut data = std::ptr::null_mut(); - let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 }; + let range = D3D12_RANGE { + Begin: 0, + End: (count + 1) * 8, + }; // SAFETY: a read-back buffer the finished list resolved into. let stamps: Vec = unsafe { if back.Map(0, Some(&range), Some(&mut data)).is_err() { @@ -851,7 +899,10 @@ impl HostList { let mut times: Vec<(f64, String)> = (0..count) .map(|i| { let ticks = stamps[i + 1].saturating_sub(stamps[i]); - (ticks as f64 * 1e3 / frequency.max(1) as f64, notes[i].0.chars().take(300).collect()) + ( + ticks as f64 * 1e3 / frequency.max(1) as f64, + notes[i].0.chars().take(300).collect(), + ) }) .collect(); times.sort_by(|a, b| b.0.total_cmp(&a.0)); @@ -862,11 +913,13 @@ impl HostList { pub(crate) fn close(&self) { #[cfg(feature = "diagnostics")] if let Some((heap, back)) = self.stamps() { - let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1); + let count = + (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1); // SAFETY: an open list, our heap and read-back buffer. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count); - self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0); + self.list + .ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0); } } // SAFETY: our list. @@ -881,8 +934,14 @@ impl HostList { /// for). pub(crate) fn reset(&self) { *self.deferred() = Deferred::default(); - self.states.lock().unwrap_or_else(|e| e.into_inner()).clear(); - self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear(); + self.states + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clear(); + self.pipelines + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clear(); #[cfg(feature = "diagnostics")] self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear(); { @@ -982,7 +1041,9 @@ impl HostList { fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) { if dred_on() { let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32; - if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 { + if let Some((heap, _)) = self.stamps() + && at < STAMPS - 1 + { // SAFETY: an open list and our query heap. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) }; } @@ -991,7 +1052,8 @@ impl HostList { const UNICODE: u32 = 0; // SAFETY: an open list; the marker is copied when recorded. unsafe { - self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32) + self.list + .SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32) }; self.notes .lock() @@ -1122,9 +1184,9 @@ impl HostList { deferred.budget_zeroed = true; let at = *data; // SAFETY: the list's own mapped word, written before it runs. - deferred - .copies - .push(Step::Host(Box::new(move || unsafe { (at as *mut u32).write_volatile(0) }))); + deferred.copies.push(Step::Host(Box::new(move || unsafe { + (at as *mut u32).write_volatile(0) + }))); } // SAFETY: a live buffer. Some(unsafe { buffer.GetGPUVirtualAddress() }) @@ -1260,7 +1322,8 @@ impl Batch { /// Whether `staging` is still to be refreshed in this submission (and /// notes it refreshed). fn texture_due(&mut self, staging: &std::sync::Arc) -> bool { - self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize) + self.textures + .insert(std::sync::Arc::as_ptr(staging) as *const () as usize) } /// Before a step that writes title memory: pending refreshes are done @@ -1314,7 +1377,10 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b let moved = std::time::Instant::now(); let whole = read(src, dst, len); #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64); + crate::copystat::add( + crate::copystat::C::MoveUs, + moved.elapsed().as_micros() as u64, + ); if whole { return; } @@ -1510,16 +1576,14 @@ impl Meter { let draws = (drawn - self.drawn) as f64 / frames; (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn); // Of a frame, ms preparing submissions and ms waiting for the GPU. - let [cpu, gpu] = [0, 1].map(|i| { - SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames - }); + let [cpu, gpu] = + [0, 1].map(|i| SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames); let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| { let scale = if i % 2 == 0 { 1e3 } else { 1e6 }; PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames }); - let [back_ms, back_mb] = [0, 1].map(|i| { - COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames - }); + let [back_ms, back_mb] = + [0, 1].map(|i| COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames); let dropped = crate::draw::take_dropped() as f64 / frames; let indirect = crate::list::take_indirect() as f64 / frames; // Over the same frames as the counts above. @@ -1588,6 +1652,14 @@ impl Host { /// as frame `frame` (saved if captures are on). `None` if nothing was /// shown; else, in diagnostics builds, whether the frame was black. pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option { + // Diagnostics: an intermediate target instead (VICTORY_SHOW_TARGET). + #[cfg(feature = "diagnostics")] + let shown = crate::capture::take_shown(); + #[cfg(feature = "diagnostics")] + let (texture, state) = match &shown { + Some((copy, s)) => (©.texture, *s), + None => (texture, state), + }; // SAFETY: a live resource. let desc = unsafe { texture.GetDesc() }; let Some(format) = swap_format(desc.Format) else { @@ -1825,7 +1897,11 @@ fn last_notes(runs: &[&HostList]) -> String { for (i, r) in runs.iter().enumerate() { let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner()); for (n, _) in notes.iter().rev().take(6).rev() { - text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len())); + text.push_str(&format!( + "; list {i} of {}, of its {}: {n}", + runs.len(), + notes.len() + )); } } text @@ -1856,9 +1932,16 @@ fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String { /// barriers overlaps on the GPU), by kind, and what the markers just /// before them say (`HostList::note_op`: diagnostics builds with /// device-removed data on). -fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String { +fn in_flight( + history: &[D3D12_AUTO_BREADCRUMB_OP], + markers: &[(u32, String)], + done: usize, +) -> String { let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER; - let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1); + let from = history[..done] + .iter() + .rposition(barrier) + .map_or(0, |b| b + 1); let to = history[done..] .iter() .position(barrier) @@ -1981,7 +2064,8 @@ fn pump() { } #[cfg(test)] -mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file +mod batch { + // Batch::texture_due lives here; `mod tests` is already taken at the top of this file use super::Batch; use std::sync::Arc; diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index c0236d8..3b980da 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -4,7 +4,8 @@ //! billion vertices or a dispatch past the host's limits runs until the //! host resets the display driver. So every record is clamped on the GPU, //! just before its execution, by a compute shader of ours (HLSL compiled by -//! the system's compiler; a 5.1 shader with its root signature inside). +//! the system's compiler as a 5.1 shader; its root signature is built here, +//! since Wine's compiler does not embed one). //! //! Each list also has a budget (2^27 vertex instances or threads, groups //! counted as 64 threads, mesh groups as 128): records past it run empty, @@ -23,52 +24,191 @@ use windows::core::s; use crate::host::{HostList, host, transition}; +// Written for both compilers `D3DCompile` may be: Microsoft's and, under +// Wine, vkd3d-shader's, which has no `RWByteAddressBuffer` methods. So the +// buffers are structured buffers of words (a root UAV takes either). const SOURCE: &str = r#" -#define RS "RootConstants(num32BitConstants=4, b0), UAV(u0), UAV(u1)" cbuffer Record : register(b0) { uint kind; uint stride; uint records; uint unused; }; -RWByteAddressBuffer args : register(u0); +RWStructuredBuffer args : register(u0); // The list's work so far (vertex instances, threads): past the budget, // records run empty. -RWByteAddressBuffer budget : register(u1); +RWStructuredBuffer budget : register(u1); static const uint BUDGET = 1u << 27; // Groups of one dispatch; more run empty. static const uint GROUPS = 1u << 20; -[RootSignature(RS)] [numthreads(64, 1, 1)] void main(uint3 id : SV_DispatchThreadID) { if (id.x >= records) return; - uint at = id.x * stride; + uint at = id.x * (stride / 4); uint cost; if (kind <= 1) { // Draws: vertex or index count, then instances. - uint count = min(args.Load(at), 1u << 24); - uint instances = min(args.Load(at + 4), (1u << 26) / max(count, 1u)); + uint count = min(args[at], 1u << 24); + uint instances = min(args[at + 1], (1u << 26) / max(count, 1u)); cost = count * instances; - args.Store2(at, uint2(count, instances)); + args[at] = count; + args[at + 1] = instances; } else if (kind == 2) { - uint3 g = min(args.Load3(at), uint3(65535, 65535, 65535)); + uint3 g = min(uint3(args[at], args[at + 1], args[at + 2]), uint3(65535, 65535, 65535)); // x * y fits 32 bits; the whole count may not. if (g.z != 0 && g.x * g.y > GROUPS / g.z) { g = uint3(0, 0, 0); } cost = g.x * g.y * g.z * 64; - args.Store3(at, g); + args[at] = g.x; + args[at + 1] = g.y; + args[at + 2] = g.z; } else { // Mesh dispatches: the console's are one-dimensional. - uint3 g = args.Load3(at); - g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u)); + uint3 g = uint3(min(args[at], 65535u), min(args[at + 1], 1u), min(args[at + 2], 1u)); cost = g.x * g.y * g.z * 128; - args.Store3(at, g); + args[at] = g.x; + args[at + 1] = g.y; + args[at + 2] = g.z; } uint before; - budget.InterlockedAdd(0, cost, before); + InterlockedAdd(budget[0], cost, before); if (before >= BUDGET || before + cost > BUDGET) { // Draws keep their layout with no vertices; groups become zero. - args.Store(at, 0); + args[at] = 0; } } "#; +/// Where `dxcompiler.dll` is looked for: `VICTORY_DXC` (the DLL or its +/// folder), beside the `dxil.dll` shader validation uses (the SDK ships them +/// together), then the executable's folder and System32. +fn dxc_library() -> windows::core::Result { + use windows::Win32::System::LibraryLoader::{ + LOAD_LIBRARY_SEARCH_APPLICATION_DIR, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS, + LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW, + }; + use windows::core::{HSTRING, w}; + let mut paths: Vec = Vec::new(); + if let Some(p) = std::env::var_os("VICTORY_DXC").map(std::path::PathBuf::from) { + paths.push(if p.is_dir() { + p.join("dxcompiler.dll") + } else { + p + }); + } + if let Some(dir) = victory_shader::emit::validator::Validator::default_path() + .and_then(|p| p.parent().map(|d| d.to_path_buf())) + { + paths.push(dir.join("dxcompiler.dll")); + } + for path in paths.iter().filter(|p| p.is_file()) { + // SAFETY: a NUL-terminated path; its folder (dxil.dll) is searched first. + if let Ok(m) = unsafe { + LoadLibraryExW( + &HSTRING::from(path.as_path()), + None, + LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS, + ) + } { + return Ok(m); + } + } + // SAFETY: a bare name, searched only in the executable's folder and System32. + unsafe { + LoadLibraryExW( + w!("dxcompiler.dll"), + None, + LOAD_LIBRARY_SEARCH_APPLICATION_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32, + ) + } +} + +/// Compiles a compute shader with DXC (see [`dxc_library`]). +fn dxc_compile(source: &str) -> windows::core::Result> { + use windows::Win32::Graphics::Direct3D::Dxc::*; + use windows::Win32::System::LibraryLoader::GetProcAddress; + use windows::core::{Interface, w}; + type Create = unsafe extern "system" fn( + *const windows::core::GUID, + *const windows::core::GUID, + *mut *mut std::ffi::c_void, + ) -> windows::core::HRESULT; + // SAFETY: loading the compiler and calling its documented entry point with + // out pointers of ours; the buffer and arguments outlive the calls. + unsafe { + let library = dxc_library()?; + let create: Create = std::mem::transmute( + GetProcAddress(library, s!("DxcCreateInstance")) + .ok_or_else(windows::core::Error::from_thread)?, + ); + let mut raw = std::ptr::null_mut(); + create(&CLSID_DxcCompiler, &IDxcCompiler3::IID, &mut raw).ok()?; + let compiler = IDxcCompiler3::from_raw(raw); + let buffer = DxcBuffer { + Ptr: source.as_ptr().cast(), + Size: source.len(), + Encoding: DXC_CP_UTF8.0, + }; + let arguments = [w!("-T"), w!("cs_6_0"), w!("-E"), w!("main"), w!("-O3")]; + let result: IDxcResult = compiler.Compile(&buffer, Some(&arguments), None)?; + if let Err(e) = result.GetStatus()?.ok() { + if let Ok(errors) = result.GetErrorBuffer() { + let text = std::slice::from_raw_parts( + errors.GetBufferPointer().cast::(), + errors.GetBufferSize(), + ); + tracing::warn!( + "argument clamp: DXC: {}", + String::from_utf8_lossy(text).trim() + ); + } + return Err(e); + } + let blob = result.GetResult()?; + let mut bytes = + std::slice::from_raw_parts(blob.GetBufferPointer().cast::(), blob.GetBufferSize()) + .to_vec(); + sign_dxc_bytecode(library, &mut bytes)?; + Ok(bytes) + } +} + +/// Older DXC DLLs can compile successfully without finding the signing DLL. +/// The resulting container has a zero digest and native D3D12 rejects it. +fn sign_dxc_bytecode( + compiler: windows::Win32::Foundation::HMODULE, + bytes: &mut [u8], +) -> windows::core::Result<()> { + use std::os::windows::ffi::OsStringExt; + use victory_shader::emit::validator::Validator; + use windows::Win32::Foundation::E_FAIL; + use windows::Win32::System::LibraryLoader::GetModuleFileNameW; + + if bytes + .get(4..20) + .is_some_and(|digest| digest.iter().any(|&b| b != 0)) + { + return Ok(()); + } + + let explicit = std::env::var_os("VICTORY_DXIL").map(std::path::PathBuf::from); + let beside_compiler = || { + let mut path = vec![0; 32_768]; + // SAFETY: the compiler module is loaded and the buffer is ours. + let len = unsafe { GetModuleFileNameW(Some(compiler), &mut path) } as usize; + if len == 0 || len >= path.len() { + return None; + } + let compiler = std::path::PathBuf::from(std::ffi::OsString::from_wide(&path[..len])); + let validator = compiler.with_file_name("dxil.dll"); + validator.is_file().then_some(validator) + }; + let path = explicit + .or_else(beside_compiler) + .or_else(Validator::default_path); + Validator::load(path.as_deref()) + .and_then(|mut validator| validator.validate(bytes)) + .map_err(|error| { + windows::core::Error::new(E_FAIL, format!("cannot sign DXC shader: {error}")) + }) +} + struct Clamp { root: ID3D12RootSignature, pso: ID3D12PipelineState, @@ -112,21 +252,39 @@ fn make() -> windows::core::Result { Some(&mut errors), ) }; - if let Err(e) = compiled { - if let Some(errors) = errors { + // Wine's d3dcompiler_47 (vkd3d-shader) rejects RWByteAddressBuffer loads: + // then DXC (dxcompiler.dll; see `dxc_library` for where it is looked for) compiles + // the same source as cs_6_0, root signature inside. + let fallback; + if let Err(e) = &compiled { + if let Some(errors) = &errors { // SAFETY: the blob's own bytes. let text = unsafe { - std::slice::from_raw_parts(errors.GetBufferPointer().cast::(), errors.GetBufferSize()) + std::slice::from_raw_parts( + errors.GetBufferPointer().cast::(), + errors.GetBufferSize(), + ) }; - tracing::warn!("argument clamp: {}", String::from_utf8_lossy(text)); + tracing::info!(error = %e, "argument clamp: the system compiler refused it ({}); trying DXC", String::from_utf8_lossy(text).trim()); } - return Err(e); + fallback = dxc_compile(SOURCE) + .inspect_err(|e| tracing::warn!(error = %e, "argument clamp: DXC failed too"))?; + } else { + fallback = Vec::new(); } - let code = code.ok_or_else(windows::core::Error::empty)?; - // SAFETY: the blob's own bytes; the root signature is inside the shader. + // SAFETY: the blob's own bytes; the DXC fallback carries its root + // signature inside the shader. unsafe { - let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); - let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; + let (bytes, root) = match &code { + Some(code) => ( + std::slice::from_raw_parts( + code.GetBufferPointer().cast::(), + code.GetBufferSize(), + ), + root_signature(device)?, + ), + None => (&fallback[..], device.CreateRootSignature(0, &fallback[..])?), + }; let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&root), CS: D3D12_SHADER_BYTECODE { @@ -139,6 +297,53 @@ fn make() -> windows::core::Result { } } +/// Constants b0 (four words: kind, stride, records, unused), then the +/// arguments as root UAV u0 and the budget as root UAV u1. +fn root_signature(device: &ID3D12Device) -> windows::core::Result { + let uav = |register| D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR { + ShaderRegister: register, + RegisterSpace: 0, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }; + let params = [ + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: 0, + Num32BitValues: 4, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }, + uav(0), + uav(1), + ]; + let desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: params.len() as u32, + pParameters: params.as_ptr(), + NumStaticSamplers: 0, + pStaticSamplers: std::ptr::null(), + Flags: D3D12_ROOT_SIGNATURE_FLAG_NONE, + }; + // SAFETY: the description points at a live array; the blob is read in + // full before it is released. + unsafe { + let mut blob: Option = None; + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None)?; + let blob = blob.ok_or_else(windows::core::Error::empty)?; + let bytes = + std::slice::from_raw_parts(blob.GetBufferPointer().cast::(), blob.GetBufferSize()); + device.CreateRootSignature(0, bytes) + } +} + /// Records, in `list`, the clamp of `records` records of `kind` (PC /// argument numbering) `stride` bytes apart at host address `gpu` in /// `buffer`, and leaves the buffer ready to be read as arguments. Replaces @@ -199,7 +404,9 @@ fn uav_barrier() -> D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, Anonymous: D3D12_RESOURCE_BARRIER_0 { - UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }), + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), }, } } @@ -214,4 +421,80 @@ mod tests { } assert!(super::clamp().is_some()); } + + /// The clamp bounds a draw, a dispatch and a mesh dispatch on the GPU. + #[test] + fn arguments_are_clamped_on_the_gpu() { + clamp_on_the_gpu(false); + } + + /// The same in a list with the title's kind of descriptor heaps bound + /// (under vkd3d-proton the clamp then faulted on address 0). + #[test] + fn arguments_are_clamped_with_heaps_bound() { + clamp_on_the_gpu(true); + } + + fn clamp_on_the_gpu(heaps: bool) { + use super::*; + let Some(host) = host() else { + return; // no host GPU here + }; + let (buffer, data) = host.shared_buffer(256).unwrap(); + let words = data.cast::(); + let records: [(usize, [u32; 4]); 3] = [ + (0, [u32::MAX, 5, 0, 0]), // draw: vertices, instances + (16, [70_000, 2, 3, 0]), // dispatch + (32, [100_000, 7, 9, 0]), // mesh dispatch + ]; + for (at, w) in records { + // SAFETY: inside the mapped 256 bytes. + unsafe { std::ptr::copy_nonoverlapping(w.as_ptr(), words.add(at / 4), 4) }; + } + let list = host.new_list().unwrap(); + if heaps { + let heap = |kind, count| -> ID3D12DescriptorHeap { + // SAFETY: plain heap creation. + unsafe { + host.device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: count, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + } + .unwrap() + }; + let views = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1024); + let samplers = heap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 16); + // SAFETY: an open list and shader-visible heaps it keeps alive. + unsafe { + list.list + .SetDescriptorHeaps(&[Some(views.clone()), Some(samplers.clone())]) + }; + list.keep(&views); + list.keep(&samplers); + } + // SAFETY: a live buffer and an open list. + let gpu = unsafe { + list.list.ResourceBarrier(&[transition( + &buffer, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + buffer.GetGPUVirtualAddress() + }; + for (kind, at, stride) in [(0, 0, 16), (2, 16, 12), (3, 32, 12)] { + assert!(bound(&list, &buffer, gpu + at, (kind, stride, 1))); + done(&list, &buffer); + } + list.close(); + host.execute(&[&list]); + // SAFETY: the list ran (execute waits); inside the mapped bytes. + let read = |at: usize| unsafe { std::slice::from_raw_parts(words.add(at / 4), 3).to_vec() }; + assert_eq!(read(0)[..2], [1 << 24, 4]); + assert_eq!(read(16), [65_535, 2, 3]); + assert_eq!(read(32), [65_535, 1, 1]); + } } diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 7adb4e4..778011d 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -256,6 +256,8 @@ extern "system" fn close(this: This) -> HRESULT { if let Some(host) = host_list(this) { host.close(); } + #[cfg(not(windows))] + let _ = this; S_OK } extern "system" fn reset(this: This, allocator: This, pipeline: This) -> HRESULT { @@ -341,6 +343,7 @@ fn host_barrier(list: &crate::host::HostList, b: &Barrier) -> Option { /// An unordered access barrier on every resource: earlier shader writes /// finish before later work reads or writes. +#[cfg(windows)] const UAV_BARRIER: Barrier = Barrier { kind: 2, flags: 0, @@ -351,6 +354,8 @@ const UAV_BARRIER: Barrier = Barrier { /// Returns the console's barrier "actions" (none). extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> u32 { + #[cfg(not(windows))] + let _ = (this, count, barriers); #[cfg(windows)] if let Some(list) = host_list(this) && !barriers.is_null() @@ -754,8 +759,13 @@ extern "system" fn clear_dsv( let dsv = host.dsv(texture, record.depth_desc().as_ref()); // SAFETY: an open list, a fresh view of a live texture. unsafe { - list.list - .ClearDepthStencilView(dsv, D3D12_CLEAR_FLAGS(flags as i32 & 3), depth, stencil, rects) + list.list.ClearDepthStencilView( + dsv, + D3D12_CLEAR_FLAGS(flags as i32 & 3), + depth, + stencil, + rects, + ) }; } #[cfg(not(windows))] @@ -887,7 +897,10 @@ extern "system" fn reset_x(this: This, allocator: This, pipeline: This, _flags: /// `E_NOTIMPL` as a pointer). extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mut u8 { let align = usize::try_from(alignment).unwrap_or(0).max(16); - let Some(len) = usize::try_from(size).ok().and_then(|s| s.checked_add(align)) else { + let Some(len) = usize::try_from(size) + .ok() + .and_then(|s| s.checked_add(align)) + else { return std::ptr::null_mut(); }; if this.is_null() || !align.is_power_of_two() { @@ -900,7 +913,10 @@ extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mu // SAFETY: the title passes one of our lists. let uploads = unsafe { &(*this.cast::()).uploads }; // Moving the vector keeps its heap block where it is. - uploads.lock().unwrap_or_else(|e| e.into_inner()).push(block); + uploads + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(block); at } @@ -1163,15 +1179,25 @@ extern "system" fn execute_indirect( return; }; let address = crate::resource::buffer_bytes(arguments).map(|(p, _)| p as u64 + offset); + #[cfg(windows)] let counter = crate::resource::buffer_bytes(count).map(|(p, _)| p as u64 + count_offset); + #[cfg(not(windows))] + let _ = (this, count_offset); + #[cfg(windows)] let mut ran = false; + #[cfg(not(windows))] + let ran = false; #[cfg(windows)] if let ([[kind, ..]], Some(address)) = (args, address) && (count.is_null() || counter.is_some()) { const DISPATCH: u32 = 2; const DISPATCH_SINGLE: u32 = 105; - let kind = if *kind == DISPATCH_SINGLE { DISPATCH } else { *kind }; + let kind = if *kind == DISPATCH_SINGLE { + DISPATCH + } else { + *kind + }; with_state(this, |list, s| { ran = s.execute_indirect(list, (kind, stride, max), address, counter); }); @@ -1203,6 +1229,7 @@ extern "system" fn execute_indirect( } /// Indirect executions dropped since the last call. +#[cfg(windows)] pub(crate) fn take_indirect() -> u64 { INDIRECT.swap(0, std::sync::atomic::Ordering::Relaxed) } @@ -1241,7 +1268,8 @@ extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { { use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; // SAFETY: the same layout; no resource named. - let barrier = unsafe { std::mem::transmute::(UAV_BARRIER) }; + let barrier = + unsafe { std::mem::transmute::(UAV_BARRIER) }; // SAFETY: an open list. unsafe { list.list.ResourceBarrier(&[barrier]) }; } @@ -1438,10 +1466,18 @@ mod tests { assert!(!p.is_null() && (p as usize).is_multiple_of(0x100)); // SAFETY: 40 bytes were handed out. unsafe { p.write_bytes(0xab, 40) }; - assert!(allocate_upload(list, 8, 0x30).is_null(), "not a power of two"); + assert!( + allocate_upload(list, 8, 0x30).is_null(), + "not a power of two" + ); assert_eq!(reset(list, allocator, null), S_OK); - // SAFETY: the list is ours. - assert!(unsafe { &(*list.cast::()).uploads }.lock().unwrap().is_empty()); + assert!( + // SAFETY: the list is ours. + unsafe { &(*list.cast::()).uploads } + .lock() + .unwrap() + .is_empty() + ); let release = |o: This| slot:: u32>(o, 0x10)(o); assert_eq!(release(list), 0); assert_eq!(release(allocator), 0); diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index b1dc393..dcf0a3a 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -18,7 +18,9 @@ use std::collections::HashMap; use std::mem::offset_of; -use std::sync::{Arc, Mutex, OnceLock}; +#[cfg(windows)] +use std::sync::OnceLock; +use std::sync::{Arc, Mutex}; use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, PIPELINE, Table, This, guid}; use crate::resource::PAGEABLE_IIDS; @@ -275,7 +277,10 @@ pub(crate) fn note_drop(this: This) { #[cfg(all(windows, feature = "diagnostics"))] pub(crate) fn note_why(why: String) { let mut drops = DROPS.lock().unwrap_or_else(|e| e.into_inner()); - *drops.get_or_insert_with(HashMap::new).entry(why).or_default() += 1; + *drops + .get_or_insert_with(HashMap::new) + .entry(why) + .or_default() += 1; } /// The drops counted since the last call, most first (diagnostics). diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 00aa9aa..650216d 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -34,6 +34,15 @@ pub(crate) struct GraphicsState { samples: DXGI_SAMPLE_DESC, } +impl GraphicsState { + /// Whether this draws depth-tested geometry (the 3D scene), not flat + /// layers (interface, full-screen passes), which keep their own pixel + /// shaders in the debug view. + pub(crate) fn draws_geometry(&self) -> bool { + self.depth_format != DXGI_FORMAT_UNKNOWN && self.depth.DepthEnable.as_bool() + } +} + impl Default for GraphicsState { fn default() -> Self { let target = D3D12_RENDER_TARGET_BLEND_DESC { @@ -179,7 +188,12 @@ impl GraphicsState { .map(|(e, name)| { format!( "{name:?} {} {} {} {} {} {}", - e.SemanticIndex, e.Format.0, e.InputSlot, e.AlignedByteOffset, e.InputSlotClass.0, e.InstanceDataStepRate + e.SemanticIndex, + e.Format.0, + e.InputSlot, + e.AlignedByteOffset, + e.InputSlotClass.0, + e.InstanceDataStepRate ) }) .collect(); @@ -277,6 +291,31 @@ pub(crate) struct HostPipeline { pub(crate) name: String, } +/// `VICTORY_DEBUG_PS=1`: graphics pipelines that draw depth-tested +/// geometry draw with our debug pixel shader ([`victory_shader::emit::debug_ps`]), surfaces coloured by their +/// slope, instead of the title's: the geometry of every draw whose vertex +/// or mesh stage translates, lit or not, its pixel shader translated or not. +pub(crate) fn debug_ps() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var_os("VICTORY_DEBUG_PS").is_some(); + if on { + tracing::info!( + "graphics pipelines draw with the debug pixel shader (VICTORY_DEBUG_PS)" + ); + } + on + }) +} + +/// Whether geometry whose pixel shader does not translate (or is refused) +/// is drawn with the debug pixel shader instead of dropped: on unless +/// `VICTORY_PS_FALLBACK=0`. +fn ps_fallback() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("VICTORY_PS_FALLBACK").map_or(true, |v| v != "0")) +} + /// Logs a pipeline that gets no host pipeline, once per reason. fn refuse(reason: &'static str, shaders: &[Arc]) -> Option { static SEEN: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); @@ -290,8 +329,41 @@ fn refuse(reason: &'static str, shaders: &[Arc]) -> Option impl HostPipeline { /// A host pipeline for vertex and pixel shaders with the graphics - /// state `g`, or for one compute shader. + /// state `g`, or for one compute shader. A pipeline drawing depth-tested + /// geometry falls back to our debug pixel shader where the title's does + /// not translate or the host refuses it (and, in the debug view, to the + /// title's where ours is refused), so its geometry is drawn rather than + /// dropped (`VICTORY_PS_FALLBACK=0` turns that off). pub(crate) fn new(shaders: &[Arc], g: Option<&GraphicsState>) -> Option { + let geometry = g.is_some_and(GraphicsState::draws_geometry) + && shaders.iter().any(|s| s.stage == "pixel"); + if !geometry { + return Self::make(shaders, g, false); + } + let first = debug_ps(); + if let Some(p) = Self::make(shaders, g, first) { + return Some(p); + } + if !first && !ps_fallback() { + return None; + } + let p = Self::make(shaders, g, !first)?; + if !first { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::info!("pixel shaders that do not translate are replaced by the debug one") + }); + } + Some(p) + } + + /// [`HostPipeline::new`] with our debug pixel shader (`debug`) or the + /// title's. + fn make( + shaders: &[Arc], + g: Option<&GraphicsState>, + debug: bool, + ) -> Option { let find = |stage| shaders.iter().find(|s| s.stage == stage); let compute = match shaders { [cs] if cs.stage == "compute" => Some(cs), @@ -317,11 +389,18 @@ impl HostPipeline { (None, None) => return refuse("no vertex or mesh shader", shaders), }; let mut stages = vec![first]; - stages.extend(find("pixel").map(|ps| (ps, D3D12_SHADER_VISIBILITY_PIXEL))); + // Debug view: the title's pixel shader is left out (it need not + // translate) and ours stands in at the pixel slot. + if !debug { + stages.extend(find("pixel").map(|ps| (ps, D3D12_SHADER_VISIBILITY_PIXEL))); + } stages }; if mesh.is_some() && !host()?.mesh_shaders() { - return refuse("the host GPU has no mesh shaders (or no shader model 6.6)", shaders); + return refuse( + "the host GPU has no mesh shaders (or no shader model 6.6)", + shaders, + ); } for (s, _) in &stages { s.translated()?; @@ -330,6 +409,9 @@ impl HostPipeline { // The root signature the translated shaders' bindings define. let mut params: Vec = Vec::new(); + // Root SRVs are bound as one-view tables (see below); their ranges + // must outlive the serialisation, so each is boxed here. + let mut ranges: Vec> = Vec::new(); let mut samplers = Vec::new(); let mut bound = Vec::new(); for &(shader, visibility) in &stages { @@ -369,6 +451,36 @@ impl HostPipeline { ] { for &slot in slots { out.push((slot, params.len() as u32)); + // A root SRV is a raw address the GPU reads without + // bounds: the console's reads past the title buffer + // land in other title memory, ours past its host copy + // in unmapped memory (a GPU page fault and a lost + // device in the world). A table of one raw view sized + // to the copy reads zeros there instead; the shader's + // binding (`t`, a ByteAddressBuffer) is the same. + if kind == D3D12_ROOT_PARAMETER_TYPE_SRV { + ranges.push(Box::new(D3D12_DESCRIPTOR_RANGE1 { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + NumDescriptors: 1, + BaseShaderRegister: u32::from(slot), + RegisterSpace: ROOT_CBV_SPACE, + Flags: D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE + | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, + OffsetInDescriptorsFromTableStart: 0, + })); + let range: &D3D12_DESCRIPTOR_RANGE1 = ranges.last().expect("just pushed"); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE1 { + NumDescriptorRanges: 1, + pDescriptorRanges: range, + }, + }, + ShaderVisibility: visibility, + }); + continue; + } params.push(D3D12_ROOT_PARAMETER1 { ParameterType: kind, Anonymous: D3D12_ROOT_PARAMETER1_0 { @@ -401,14 +513,26 @@ impl HostPipeline { } bound.push(stage); } - let (root, root_blob) = match root_signature(&host.device, ¶ms, &samplers, compute.is_some()) { - Ok(root) => root, - Err(e) => { - tracing::warn!(error = %e, ?shaders, "host root signature refused"); - return None; - } - }; + let (root, root_blob) = + match root_signature(&host.device, ¶ms, &samplers, compute.is_some()) { + Ok(root) => root, + Err(e) => { + tracing::warn!(error = %e, ?shaders, "host root signature refused"); + return None; + } + }; + // The debug view's pixel shader, one output per colour target. + let debug = (compute.is_none() && debug) + .then(|| victory_shader::emit::debug_ps(g.map_or(1, |g| g.targets.NumRenderTargets))); let code = |i: usize| { + if i == 1 + && let Some(d) = &debug + { + return D3D12_SHADER_BYTECODE { + pShaderBytecode: d.dxil.as_ptr().cast(), + BytecodeLength: d.dxil.len(), + }; + } stages.get(i).and_then(|(s, _)| s.translated()).map_or( D3D12_SHADER_BYTECODE::default(), |t| D3D12_SHADER_BYTECODE { @@ -585,15 +709,27 @@ fn mesh_pipeline( samples: Sub, } let mut stream = Stream { - root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()), + root: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, + root.as_raw(), + ), ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms), ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps), blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, g.blend), - mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, g.sample_mask), + mask: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, + g.sample_mask, + ), raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, g.rasterizer), depth: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, g.depth), - targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, g.targets), - dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, g.depth_format), + targets: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, + g.targets, + ), + dsv: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, + g.depth_format, + ), samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples), }; let desc = D3D12_PIPELINE_STATE_STREAM_DESC { @@ -616,7 +752,8 @@ fn code_bytes(code: &D3D12_SHADER_BYTECODE) -> Vec { return Vec::new(); } // SAFETY: a translation's own bytes, alive while its shader is. - unsafe { std::slice::from_raw_parts(code.pShaderBytecode.cast::(), code.BytecodeLength) }.to_vec() + unsafe { std::slice::from_raw_parts(code.pShaderBytecode.cast::(), code.BytecodeLength) } + .to_vec() } fn root_signature( diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index aa611e2..5c9fabc 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -75,31 +75,62 @@ fn library() -> Option<&'static Mutex> { /// adapter or driver change, damage). fn open(device: &ID3D12Device1, blob: Vec) -> Option { let make = |bytes: &[u8]| -> windows::core::Result { - // SAFETY: the bytes outlive the library (kept beside it). + // An empty library is asked for with a null blob: an empty slice's + // pointer is dangling, which vkd3d-proton (Proton) rejects. + let data = if bytes.is_empty() { + std::ptr::null() + } else { + bytes.as_ptr() + }; + let mut library: Option = None; + // SAFETY: the bytes outlive the library (kept beside it); the out + // pointer is ours and typed by the interface id passed with it. unsafe { - device.CreatePipelineLibrary::(bytes)?.cast() + (Interface::vtable(device).CreatePipelineLibrary)( + Interface::as_raw(device), + data.cast(), + bytes.len(), + &ID3D12PipelineLibrary::IID, + (&raw mut library).cast(), + ) + .ok()?; } + library.ok_or_else(windows::core::Error::empty)?.cast() }; if !blob.is_empty() { match make(&blob) { Ok(library) => { tracing::info!(bytes = blob.len(), "host pipeline library loaded"); - return Some(Library { library, _blob: blob, added: 0 }); + return Some(Library { + library, + _blob: blob, + added: 0, + }); + } + Err(e) => { + tracing::info!(error = %e, "host pipeline library rejected; starting an empty one") } - Err(e) => tracing::info!(error = %e, "host pipeline library rejected; starting an empty one"), } } else { tracing::info!("no host pipeline library yet; starting an empty one"); } let library = make(&[]).ok()?; - Some(Library { library, _blob: Vec::new(), added: 0 }) + Some(Library { + library, + _blob: Vec::new(), + added: 0, + }) } /// A pipeline's name in the library: the hash of what its host /// description holds. pub(crate) fn name(kind: &str, root: &[u8], code: &[&[u8]], state: &str) -> String { let mut h = blake3::Hasher::new(); - for part in [kind.as_bytes(), root].into_iter().chain(code.iter().copied()).chain([state.as_bytes()]) { + for part in [kind.as_bytes(), root] + .into_iter() + .chain(code.iter().copied()) + .chain([state.as_bytes()]) + { h.update(&(part.len() as u64).to_le_bytes()); h.update(part); } @@ -118,7 +149,10 @@ pub(crate) fn pipeline( MADE.fetch_add(1, Ordering::Relaxed); return create(); }; - if let Ok(pso) = load(&library.lock().unwrap_or_else(|e| e.into_inner()).library, PCWSTR(wide.as_ptr())) { + if let Ok(pso) = load( + &library.lock().unwrap_or_else(|e| e.into_inner()).library, + PCWSTR(wide.as_ptr()), + ) { LOADED.fetch_add(1, Ordering::Relaxed); return Ok(pso); } @@ -139,7 +173,9 @@ pub(crate) fn pipeline( pub(crate) fn save(now: bool) { static LAST: Mutex> = Mutex::new(None); const SAVE_EVERY: std::time::Duration = std::time::Duration::from_secs(20); - let (Some(dir), Some(library)) = (DIR.get(), library()) else { return }; + let (Some(dir), Some(library)) = (DIR.get(), library()) else { + return; + }; { let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); if !now && last.is_some_and(|t| t.elapsed() < SAVE_EVERY) { @@ -168,7 +204,13 @@ pub(crate) fn save(now: bool) { } } }; - let used: Vec = USED.lock().unwrap_or_else(|e| e.into_inner()).iter().flatten().cloned().collect(); + let used: Vec = USED + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .flatten() + .cloned() + .collect(); let written = std::fs::create_dir_all(dir) .and_then(|()| write_atomically(&dir.join(LIBRARY_FILE), &blob)) .and_then(|()| write_atomically(&dir.join(EARLY_FILE), used.join("\n").as_bytes())); @@ -204,7 +246,11 @@ fn used() -> std::sync::MutexGuard<'static, Option>> { .get() .and_then(|d| std::fs::read_to_string(d.join(EARLY_FILE)).ok()) .unwrap_or_default(); - let set: HashSet = listed.lines().filter(|l| !l.is_empty()).map(str::to_owned).collect(); + let set: HashSet = listed + .lines() + .filter(|l| !l.is_empty()) + .map(str::to_owned) + .collect(); tracing::info!(pipelines = set.len(), "title pipelines to start early"); *used = Some(set); } @@ -243,10 +289,12 @@ mod tests { #[test] fn a_rejected_blob_gives_an_empty_library() { - let Some(device) = crate::host::host().and_then(|h| h.device.cast::().ok()) else { + let Some(device) = crate::host::host().and_then(|h| h.device.cast::().ok()) + else { return; // no host GPU here }; - let library = open(&device, b"not a pipeline library".repeat(16)).expect("an empty library"); + let library = + open(&device, b"not a pipeline library".repeat(16)).expect("an empty library"); // SAFETY: a plain query on a live library. assert!(unsafe { library.library.GetSerializedSize() } > 0); assert!(library._blob.is_empty()); diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 6ffc032..975567f 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -12,8 +12,8 @@ //! bake) are there at once as before; past the budget a draw or dispatch //! whose pipeline is not ready is dropped, as an untranslated one is. //! -//! shortcut: the budget (half a second of waiting per title frame) is a -//! guess; a pass the title runs only once and whose pipeline takes longer +//! shortcut: the budget (half a second of waiting per title frame, +//! `VICTORY_PIPELINE_WAIT_MS`) is a guess; a pass the title runs only once and whose pipeline takes longer //! is lost. use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; @@ -48,7 +48,13 @@ impl Pending { key.update(s.stage.as_bytes()); key.update(s.hash.as_bytes()); } - key.update(graphics.as_ref().map(|g| g.describe()).unwrap_or_default().as_bytes()); + key.update( + graphics + .as_ref() + .map(|g| g.describe()) + .unwrap_or_default() + .as_bytes(), + ); Pending { shaders, graphics, @@ -94,8 +100,19 @@ pub(crate) fn missing(p: &Pending) -> Option { /// Signalled whenever a worker has made a pipeline. static DONE: (Mutex<()>, Condvar) = (Mutex::new(()), Condvar::new()); -/// Waiting allowed per title frame, over all threads. -const BUDGET: Duration = Duration::from_millis(500); +/// Waiting allowed per title frame, over all threads: 500 ms unless +/// `VICTORY_PIPELINE_WAIT_MS` says otherwise (0: never wait, a draw whose +/// pipeline is not made yet is dropped until it is; one-off passes such as +/// a colour-grading bake may then be lost). +fn budget() -> Duration { + static MS: std::sync::OnceLock = std::sync::OnceLock::new(); + Duration::from_millis(*MS.get_or_init(|| { + std::env::var("VICTORY_PIPELINE_WAIT_MS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(500) + })) +} /// Pipelines queued and not made yet. static WAITING: AtomicU64 = AtomicU64::new(0); @@ -122,7 +139,10 @@ pub(crate) fn ready(p: &Arc) -> Option<&HostPipeline> { /// Queues `p` for the workers, once. fn start(p: &Arc) { if !p.queued.swap(true, Ordering::Relaxed) { - PEAK.fetch_max(WAITING.fetch_add(1, Ordering::Relaxed) + 1, Ordering::Relaxed); + PEAK.fetch_max( + WAITING.fetch_add(1, Ordering::Relaxed) + 1, + Ordering::Relaxed, + ); queue(p.clone()); } } @@ -143,7 +163,7 @@ fn wait(p: &Pending, frame: u64) { if FRAME.swap(frame, Ordering::Relaxed) != frame { WAITED_US.store(0, Ordering::Relaxed); } - let left = BUDGET.saturating_sub(Duration::from_micros(WAITED_US.load(Ordering::Relaxed))); + let left = budget().saturating_sub(Duration::from_micros(WAITED_US.load(Ordering::Relaxed))); let started = Instant::now(); let (lock, done) = &DONE; let mut held = lock.lock().unwrap_or_else(|e| e.into_inner()); @@ -152,7 +172,10 @@ fn wait(p: &Pending, frame: u64) { if rest.is_zero() { break; } - held = done.wait_timeout(held, rest).unwrap_or_else(|e| e.into_inner()).0; + held = done + .wait_timeout(held, rest) + .unwrap_or_else(|e| e.into_inner()) + .0; } WAITED_US.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); } diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 5992fad..9ae6ff7 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -123,7 +123,7 @@ extern "system" fn execute(_: This, count: u32, lists: *const This) { .iter() .filter_map(|&l| crate::list::host_list(l)) .collect(); - host.execute(&host_lists); + host.execute_title(&host_lists); return; } static ONCE: AtomicBool = AtomicBool::new(false); @@ -227,7 +227,7 @@ fn system_timestamp() -> u64 { /// Frames presented so far. static FRAMES: AtomicU64 = AtomicU64::new(0); -#[cfg(feature = "diagnostics")] +#[cfg(all(windows, feature = "diagnostics"))] pub(crate) fn presented() -> u64 { FRAMES.load(Ordering::Relaxed) } @@ -403,7 +403,9 @@ extern "system" fn copy_page_mappings( } if !ok { static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| tracing::warn!(pool = format_args!("{pool:#x}"), "a page mapping failed")); + ONCE.call_once(|| { + tracing::warn!(pool = format_args!("{pool:#x}"), "a page mapping failed") + }); } S_OK } diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 46c5c71..f626a23 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -228,6 +228,7 @@ fn footprint(desc: &ResourceDesc) -> Option { /// A format as the host has it. The console's 16-bit depth with stencil /// (and its typeless views) has no PC format: the 24-bit ones stand in. +#[cfg(windows)] pub(crate) fn pc_format(format: u32) -> u32 { match format { 118 => 45, @@ -238,6 +239,7 @@ pub(crate) fn pc_format(format: u32) -> u32 { } /// The typeless format of a format's family (itself if it has none). +#[cfg(windows)] pub(crate) fn family(format: u32) -> u32 { const FAMILIES: [(u32, u32); 22] = [ (1, 4), @@ -274,11 +276,13 @@ pub(crate) fn family(format: u32) -> u32 { } /// sRGB formats and their linear twins. +#[cfg(windows)] pub(crate) const SRGB: [(u32, u32); 3] = [(29, 28), (91, 87), (93, 88)]; /// The format a view of a title texture must name when its host copy is /// typeless (see [`DEPTH_FORMATS`], [`SRGB`]): the title's own; `None` if /// the host copy is typed. +#[cfg(windows)] pub(crate) fn view_format(this: This) -> Option { let own = pc_format(resource(this).desc.format); let host = host_resource(this)?; @@ -290,6 +294,7 @@ pub(crate) fn view_format(this: This) -> Option { /// Depth formats with their typeless family: depth textures that shaders /// read are made typeless on the host, which only allows views of /// typeless depth resources. +#[cfg(windows)] pub(crate) const DEPTH_FORMATS: [(u32, u32); 4] = [(20, 19), (40, 39), (45, 44), (55, 53)]; /// Mip levels, the full chain for 0. @@ -325,6 +330,7 @@ pub(crate) struct PlacedFootprint { impl PlacedFootprint { /// The bytes it spans in a buffer: every row pitched but the last. + #[cfg(windows)] pub(crate) fn bytes(&self) -> Option { let (element, block) = element(self.format)?; let lines = u64::from(self.height).div_ceil(block) * u64::from(self.depth); @@ -867,13 +873,17 @@ fn host_texture( } if let Some(t) = &texture { crate::host::name(t, || { - format!("texture {}x{} f{} flags {:#x}", d.width, d.height, d.format, d.flags) + format!( + "texture {}x{} f{} flags {:#x}", + d.width, d.height, d.format, d.flags + ) }); } texture } /// A texture's console memory and description; `None` for buffers. +#[cfg(windows)] pub(crate) fn texture_memory(this: This) -> Option<(*const u8, ResourceDesc)> { if this.is_null() { return None; diff --git a/crates/victory-gpu/src/root.rs b/crates/victory-gpu/src/root.rs index 10368e9..fc5397b 100644 --- a/crates/victory-gpu/src/root.rs +++ b/crates/victory-gpu/src/root.rs @@ -52,6 +52,8 @@ type SerializeVersioned = /// An export of the host's `d3d12.dll` in System32, looked up once. fn host_export(cache: &OnceLock>, name: &CStr) -> Option { + #[cfg(not(windows))] + let _ = name; *cache.get_or_init(|| { #[cfg(windows)] { @@ -214,7 +216,9 @@ static FUNCTIONS: Table<24> = { #[cfg(test)] mod tests { + #[cfg(windows)] use super::*; + #[cfg(windows)] use crate::object::{S_OK, slot}; /// One 32-bit constant at b0, serialized by the host, then created. diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index c7b390b..351b9a4 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -155,7 +155,8 @@ impl Shadow { .push((address, address + len)); let (from, to) = self.inside(address, len); // SAFETY: inside the mapping. - let host = |a: usize, b: usize| unsafe { std::slice::from_raw_parts(self.data.add(a), b - a) }; + let host = + |a: usize, b: usize| unsafe { std::slice::from_raw_parts(self.data.add(a), b - a) }; let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); let (start, end) = match &*before { Some((at, bytes)) => ((*at).min(from), (at + bytes.len()).max(to)), diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 7694609..7322689 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -35,14 +35,141 @@ struct Journal { written: BTreeMap, /// Room for the kernel's answer. found: Vec, + /// Page ranges the kernel was asked about since the submission began + /// (see [`new_submission`]); under Wine only. + asked_now: Vec<(usize, usize)>, } static JOURNAL: Mutex = Mutex::new(Journal { asked: 0, written: BTreeMap::new(), found: Vec::new(), + asked_now: Vec::new(), }); +/// Whether we run under Wine (its ntdll exports `wine_get_version`). +fn on_wine() -> bool { + static WINE: std::sync::LazyLock = std::sync::LazyLock::new(|| { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; + // SAFETY: plain lookups in ntdll, always loaded. + unsafe { + let ntdll = GetModuleHandleA(c"ntdll.dll".as_ptr().cast()); + !ntdll.is_null() && GetProcAddress(ntdll, c"wine_get_version".as_ptr().cast()).is_some() + } + }); + *WINE +} + +/// A title allocation as Wine reports it, in [`PAGE`] units. +#[derive(Clone, Copy)] +struct Region { + /// The allocation base, for dropping stale entries. + base: usize, + first: usize, + last: usize, + /// A file view (xmem's physical pages): not write-watched. + mapped: bool, + /// Small enough (4 GiB at most) to be asked about whole. + whole: bool, +} + +/// The allocation holding `at`, cached by allocation base (walking an +/// allocation's regions under Wine costs one VirtualQuery each). Those +/// above 4 GiB are not asked about whole. +fn allocation(at: usize) -> Option { + use windows_sys::Win32::System::Memory::{MEM_MAPPED, MEMORY_BASIC_INFORMATION, VirtualQuery}; + let page = at / PAGE; + // Known allocations first: under Wine VirtualQuery takes the same lock + // the title's write faults do. + if let Some((_, &r)) = REGIONS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .range(..=page) + .next_back() + && page < r.last + { + return Some(r); + } + let query = |p: usize| { + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) }; + (n != 0).then_some(info) + }; + let info = query(at)?; + let base = info.AllocationBase as usize; + if base == 0 { + return None; + } + // Walk the allocation's regions (Wine splits it by protection, one + // region per run of pages); a long walk stops, and the allocation is + // then only remembered as far as it went, never asked about whole. + let mut end = base; + let mut done = false; + for _ in 0..256 { + let Some(i) = query(end) else { + done = true; + break; + }; + if i.AllocationBase as usize != base { + done = true; + break; + } + end = i.BaseAddress as usize + i.RegionSize; + } + if !done { + // At least past `at`, so the next asking here is a cache hit. + end = end.max((at / PAGE + 1) * PAGE).max(at + (256 << 20)); + } + if end <= at { + return None; + } + let r = Region { + base, + first: base.div_ceil(PAGE), + last: end / PAGE, + mapped: info.Type == MEM_MAPPED, + whole: done && end - base <= 4 << 30, + }; + if r.first * PAGE > at || r.last <= r.first { + return None; + } + let mut regions = REGIONS.lock().unwrap_or_else(|e| e.into_inner()); + // An allocation that replaced older ones in its range. + regions.retain(|_, o| o.last <= r.first || o.first >= r.last); + regions.insert(r.first, r); + Some(r) +} + +/// Allocations seen by [`allocation`], by first page. Remaps (xmem's views) +/// and failed askings drop entries. +static REGIONS: Mutex> = Mutex::new(BTreeMap::new()); + +fn forget_region(base: usize) { + REGIONS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .retain(|_, r| r.base != base); +} + +/// A submission begins: memory asked about from now on is asked of the +/// kernel again. Within one submission, a range the kernel already +/// answered for is answered from the journal: Wine emulates write watching +/// page by page under one lock (about 1 ms an asking), and the world's +/// copies ask about the same big buffers dozens of times per submission +/// (17 GB checked per frame, 3 s of a frame). A write between two askings +/// in one submission keeps its dirty bit, so the next submission sees it. +pub(crate) fn new_submission() { + if on_wine() { + JOURNAL + .lock() + .unwrap_or_else(|e| e.into_inner()) + .asked_now + .clear(); + } +} + /// The pages of `[start, end)` (whole pages) as last written, for pages /// written since tracking began: `(page number, asking)` in page order, and /// this asking's number, which is higher than any in the list but those the @@ -54,29 +181,82 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve let (first, last) = (start / PAGE, end.div_ceil(PAGE)); let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); let j = &mut *j; - let mut count = (last - first) * PAGE / KERNEL_PAGE; - j.found.resize(count.max(j.found.len()), 0); - let mut granularity = 0; + if on_wine() && j.asked_now.iter().any(|&(f, l)| f <= first && last <= l) { + j.asked += 1; + return Some(( + j.asked, + j.written + .range(first..last) + .map(|(&p, &w)| (p, w)) + .collect(), + )); + } + // Under Wine: view memory cannot be watched (straight to its guards), + // and watched memory is asked about whole allocations at a time, so + // the other buffers in one are answered from the journal for the rest + // of the submission (see `new_submission`). + let region = if on_wine() { allocation(start) } else { None }; + let mapped = region.is_some_and(|r| r.mapped); + let (kfirst, klast) = match region { + Some(r) if !r.mapped && r.whole && r.first <= first && last <= r.last => (r.first, r.last), + _ => (first, last), + }; #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); - // SAFETY: the answer buffer holds `count` entries. - let failed = unsafe { - GetWriteWatch( - WRITE_WATCH_FLAG_RESET, - (first * PAGE) as *const _, - (last - first) * PAGE, - j.found.as_mut_ptr().cast(), - &mut count, - &mut granularity, - ) - } != 0; + let ask = |kfirst: usize, klast: usize, found: &mut Vec| -> Option { + let mut count = (klast - kfirst) * PAGE / KERNEL_PAGE; + if found.len() < count { + found.resize(count, 0); + } + let mut granularity = 0; + // SAFETY: the answer buffer holds `count` entries. + let ok = unsafe { + GetWriteWatch( + WRITE_WATCH_FLAG_RESET, + (kfirst * PAGE) as *const _, + (klast - kfirst) * PAGE, + found.as_mut_ptr().cast(), + &mut count, + &mut granularity, + ) + } == 0; + ok.then_some(count) + }; + let mut asked = (kfirst, klast); + let mut answer = if mapped { + None + } else { + ask(kfirst, klast, &mut j.found) + }; + if answer.is_none() && !mapped && (kfirst, klast) != (first, last) { + // The allocation was not one watched range after all (or is gone): + // just ours, and look it up again next time. + if let Some(r) = region { + forget_region(r.base); + } + asked = (first, last); + answer = ask(first, last, &mut j.found); + } + let failed = answer.is_none(); + let mut count = answer.unwrap_or(0); let guarded = if failed { count = 0; if !guarded { return None; } - guard(first * PAGE, last * PAGE)? + match guard(first * PAGE, last * PAGE, mapped) { + Some(g) => g, + None => { + if let Some(r) = region { + forget_region(r.base); + } + return None; + } + } } else { + if on_wine() && j.asked_now.len() < 4096 { + j.asked_now.push(asked); + } Vec::new() }; #[cfg(feature = "diagnostics")] @@ -91,13 +271,12 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve for page in pages.collect::>() { j.written.insert(page, now); } - Some(( - now, - j.written - .range(first..last) - .map(|(&p, &w)| (p, w)) - .collect(), - )) + let out = j + .written + .range(first..last) + .map(|(&p, &w)| (p, w)) + .collect(); + Some((now, out)) } /// Guarded blocks of view memory. @@ -122,14 +301,16 @@ fn guards() -> std::sync::MutexGuard<'static, Guards> { /// For view memory: the pages of `[start, end)`'s blocks written since /// they were last guarded (all of a block's pages), guarding them again /// before the caller copies them. `None` if the memory is not a view. -fn guard(start: usize, end: usize) -> Option> { +fn guard(start: usize, end: usize, known_mapped: bool) -> Option> { use windows_sys::Win32::System::Memory::{MEM_MAPPED, MEMORY_BASIC_INFORMATION, VirtualQuery}; - // SAFETY: plain data filled in by the query. - let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; - // SAFETY: a valid out pointer of the right size. - let n = unsafe { VirtualQuery(start as *const _, &mut info, size_of_val(&info)) }; - if n == 0 || info.Type != MEM_MAPPED { - return None; + if !known_mapped { + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(start as *const _, &mut info, size_of_val(&info)) }; + if n == 0 || info.Type != MEM_MAPPED { + return None; + } } install(); let mut g = guards(); @@ -217,6 +398,7 @@ pub fn writing(at: usize, len: usize) { /// The runtime mapped or unmapped title memory `[at, at + len)`: what it /// shows is new and read-write, so it is no longer guarded. pub fn title_memory_remapped(at: usize, len: usize) { + REGIONS.lock().unwrap_or_else(|e| e.into_inner()).clear(); let mut g = guards(); let blocks: Vec = g .protected @@ -307,6 +489,8 @@ mod tests { assert!(before.is_empty()); // SAFETY: committed pages of ours. unsafe { ((p + PAGE + 8) as *mut u8).write(1) }; + // Under Wine a range is asked of the kernel once per submission. + new_submission(); let (now, after) = writes(start, end, false).expect("watched"); assert_eq!(after, [(p / PAGE + 1, now)]); // Another asker after the kernel's bit was cleared still sees it. @@ -326,6 +510,43 @@ mod tests { unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) }; } + /// Under Wine, a write after a range was asked about in a submission + /// is reported in the next one, not lost. + #[test] + fn writes_within_a_submission_show_in_the_next() { + if !on_wine() { + return; + } + // SAFETY: a fresh write-watched allocation, freed at the end. + let p = unsafe { + VirtualAlloc( + std::ptr::null(), + 2 * PAGE, + MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, + PAGE_READWRITE, + ) + } as usize; + assert_ne!(p, 0); + // Kept, not freed: another test given this address would see the + // journal's entries for it. The journal may already hold some (a + // freed allocation of another test here), so compare with them. + new_submission(); + let (_, before) = writes(p, p + 2 * PAGE, false).expect("watched"); + // SAFETY: committed pages of ours. + unsafe { ((p + 8) as *mut u8).write(1) }; + let (_, same) = writes(p, p + 2 * PAGE, false).expect("watched"); + assert_eq!( + same, before, + "answered from the journal within the submission" + ); + new_submission(); + let (now, next) = writes(p, p + 2 * PAGE, false).expect("watched"); + assert!( + next.contains(&(p / PAGE, now)), + "the write shows in the next submission" + ); + } + /// A kernel read into a guarded view block fails; opened first, it /// lands and the block counts as written. #[test] @@ -348,7 +569,7 @@ mod tests { MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK).Value as usize }; assert_ne!(view, 0); - assert!(guard(view, view + 2 * BLOCK).is_some()); // now read-only + assert!(guard(view, view + 2 * BLOCK, false).is_some()); // now read-only let mut file = tempfile::tempfile().unwrap(); file.write_all(b"from the disk").unwrap(); // `ReadFile` inside: the kernel writes the view. @@ -358,14 +579,29 @@ mod tests { let into = unsafe { std::slice::from_raw_parts_mut((view + 100) as *mut u8, 13) }; file.read(into).is_ok_and(|n| n == 13) }; - assert!(!read(&mut file), "the kernel does not fault into our handler"); + assert!( + !read(&mut file), + "the kernel does not fault into our handler" + ); writing(view + 100, 13); assert!(read(&mut file)); - // SAFETY: the bytes just read. - assert_eq!(unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) }, b"from the disk"); - assert_eq!(guard(view, view + 2 * BLOCK), Some((view / PAGE..view / PAGE + 1).collect())); + assert_eq!( + // SAFETY: the bytes just read. + unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) }, + b"from the disk" + ); + assert_eq!( + guard(view, view + 2 * BLOCK, false), + Some((view / PAGE..view / PAGE + 1).collect()) + ); // SAFETY: our view. - unsafe { UnmapViewOfFile(windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut _ }) }; + unsafe { + UnmapViewOfFile( + windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { + Value: view as *mut _, + }, + ) + }; title_memory_remapped(view, 2 * BLOCK); } diff --git a/crates/victory-hle/src/host.rs b/crates/victory-hle/src/host.rs index 8a2a875..6cb7d4d 100644 --- a/crates/victory-hle/src/host.rs +++ b/crates/victory-hle/src/host.rs @@ -84,6 +84,7 @@ impl HostPolicy { /// The host's own `name` from the System32 DLL `dll`: what a title import /// of it is bound to when we do not override it. +#[cfg(windows)] pub(crate) fn function(dll: &str, name: &str) -> Option { let name = ImportSymbol::Name { hint: 0, diff --git a/crates/victory-hle/src/modules/audio.rs b/crates/victory-hle/src/modules/audio.rs index 4bd223a..2bdfae1 100644 --- a/crates/victory-hle/src/modules/audio.rs +++ b/crates/victory-hle/src/modules/audio.rs @@ -492,9 +492,10 @@ impl Xma { let start = Instant::now(); let mut active = 0; for index in 0..self.voices.len() as u32 { - if let (Some(context), Some(voice)) = - (self.context(index), &mut *lock(&self.voices[index as usize])) - { + if let (Some(context), Some(voice)) = ( + self.context(index), + &mut *lock(&self.voices[index as usize]), + ) { pump(context, voice); active += 1; } @@ -643,7 +644,10 @@ fn dump_input(index: u32, context: Context) { ); let _ = std::fs::create_dir_all(&dir); let _ = std::fs::write(dir.join(format!("{n:02}-{index}.ctx")), words); - let _ = std::fs::write(dir.join(format!("{n:02}-{index}.xma")), input.unwrap_or_default()); + let _ = std::fs::write( + dir.join(format!("{n:02}-{index}.xma")), + input.unwrap_or_default(), + ); } /// Starts the decoding thread on the first enabled voice, and has it fill diff --git a/crates/victory-hle/src/modules/audio/capture.rs b/crates/victory-hle/src/modules/audio/capture.rs index f39bb3d..4392204 100644 --- a/crates/victory-hle/src/modules/audio/capture.rs +++ b/crates/victory-hle/src/modules/audio/capture.rs @@ -12,6 +12,7 @@ use std::io::{Seek, SeekFrom, Write}; use std::path::Path; use std::time::{Duration, Instant}; +use windows::Win32::Foundation::WAIT_OBJECT_0; use windows::Win32::Media::Audio::{ AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY, AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, AUDCLNT_STREAMFLAGS_LOOPBACK, @@ -23,7 +24,6 @@ use windows::Win32::Media::Audio::{ VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, WAVE_FORMAT_PCM, WAVEFORMATEX, }; use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx}; -use windows::Win32::Foundation::WAIT_OBJECT_0; use windows::Win32::System::Threading::{ OpenProcess, PROCESS_SYNCHRONIZE, Sleep, WaitForSingleObject, }; diff --git a/crates/victory-hle/src/modules/d3d12x.rs b/crates/victory-hle/src/modules/d3d12x.rs index 23bbccf..71c9b03 100644 --- a/crates/victory-hle/src/modules/d3d12x.rs +++ b/crates/victory-hle/src/modules/d3d12x.rs @@ -17,10 +17,12 @@ extern "system" fn create_device( iid: *const Iid, out: *mut *const Object, ) -> HRESULT { - victory_gpu::resource::use_allocator(super::xmem::XMemAlloc, super::xmem::XMemFree); - victory_gpu::resource::use_page_mapper(super::xmem::map_alias); #[cfg(windows)] - victory_gpu::on_failure(host_gpu_failed); + { + victory_gpu::resource::use_allocator(super::xmem::XMemAlloc, super::xmem::XMemFree); + victory_gpu::resource::use_page_mapper(super::xmem::map_alias); + victory_gpu::on_failure(host_gpu_failed); + } device::create(adapter, parameters, iid, out) } diff --git a/crates/victory-hle/src/modules/display.rs b/crates/victory-hle/src/modules/display.rs index 41f9cbd..b5777b7 100644 --- a/crates/victory-hle/src/modules/display.rs +++ b/crates/victory-hle/src/modules/display.rs @@ -5,7 +5,7 @@ use std::ffi::{c_char, c_void}; use super::xgameruntime::{ - Guid, HRESULT, Interface, Methods, NOT_SUPPORTED, Object, add_ref, missing, put, text, + Guid, HRESULT, Interface, Methods, NOT_SUPPORTED, Object, add_ref, missing, text, }; /// HDR mode; asked for with this interface id since 2020. @@ -104,7 +104,7 @@ extern "system" fn acquire_deferral(_: This, out: *mut *mut c_void) -> HRESULT { unsafe { windows_sys::Win32::Foundation::CloseHandle(request) }; return hr; } - put(out, request) + super::xgameruntime::put(out, request) } #[cfg(windows)] diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index c94146f..e7155fd 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -445,7 +445,10 @@ fn work(scheduler: &'static Scheduler) { let mut lanes = scheduler.lock(); loop { let Some(job) = lanes.start() else { - lanes = scheduler.work.wait(lanes).unwrap_or_else(|e| e.into_inner()); + lanes = scheduler + .work + .wait(lanes) + .unwrap_or_else(|e| e.into_inner()); continue; }; drop(lanes); @@ -484,7 +487,8 @@ impl Lanes { reading_workers = format_args!("{:.2}", reading / elapsed.as_secs_f64()), staging_waits = std::mem::take(&mut self.refused), bcpack_mb = self.bcpack.0 / 1_000_000, - bcpack_workers = format_args!("{:.2}", self.bcpack.1.as_secs_f64() / elapsed.as_secs_f64()), + bcpack_workers = + format_args!("{:.2}", self.bcpack.1.as_secs_f64() / elapsed.as_secs_f64()), waiting, "dstorage: last {:.1} s", elapsed.as_secs_f64() @@ -596,7 +600,11 @@ impl Lane { fn flush(&mut self) { while let Some(&(seq, _)) = self.statuses.front() { let waiting = self.reads.front().map(|r| r.0); - if waiting.into_iter().chain(self.running.first().copied()).any(|s| s < seq) { + if waiting + .into_iter() + .chain(self.running.first().copied()) + .any(|s| s < seq) + { return; } let Some((_, status)) = self.statuses.pop_front() else { @@ -689,7 +697,6 @@ enum Command { Status(Status), } - /// A status entry to write, holding a reference on its array. struct Status { array: Array, @@ -817,7 +824,11 @@ fn execute(request: &Request) -> Result<(), HRESULT> { return into_destination(request, size, |out| read_into(request, out).map(|()| size)) .map_err(|hr| fail(hr, "copying")); } - let tables = if bc != 0 { Some(bcpack_tables()?) } else { None }; + let tables = if bc != 0 { + Some(bcpack_tables()?) + } else { + None + }; let source = read_source(request).map_err(|hr| fail(hr, "reading the source"))?; // The console's order: zlib first, then BCPack. let source = if bc != 0 && options & ZLIB != 0 { @@ -889,7 +900,9 @@ fn use_bcpack_tables(dir: std::path::PathBuf) { #[cfg(test)] fn load_bcpack_tables() -> Result { - let dir = BCPACK_DIR.get().ok_or("no folder set for the test tables")?; + let dir = BCPACK_DIR + .get() + .ok_or("no folder set for the test tables")?; let bytes = std::fs::read(dir.join("tables.bin")).map_err(|e| e.to_string())?; Tables::parse(&bytes).map_err(|e| e.to_string()) } @@ -915,7 +928,9 @@ static READING: AtomicU64 = AtomicU64::new(0); fn read_into(request: &Request, out: &mut [u8]) -> Result<(), HRESULT> { if request.options & MEMORY_SOURCE != 0 { // SAFETY: the title's source holds `out.len()` bytes until completion. - out.copy_from_slice(unsafe { std::slice::from_raw_parts(request.source.cast(), out.len()) }); + out.copy_from_slice(unsafe { + std::slice::from_raw_parts(request.source.cast(), out.len()) + }); return Ok(()); } // SAFETY: a file object we created; the title keeps it open. @@ -1205,7 +1220,8 @@ mod tests { // Requests in flight together run in any order, so none of them // shares a destination (failed ones leave theirs undefined). let mut buffers = [[0u8; 16]; 5]; - let [failed, failed_too, out, other, bcpack] = buffers.each_mut().map(|b| b.as_mut_ptr().cast()); + let [failed, failed_too, out, other, bcpack] = + buffers.each_mut().map(|b| b.as_mut_ptr().cast()); // Segment 0: a read past the end, then a bad stream; the first wins. enqueue(queue, &request(0, failed, 16, file, 4090, 16)); @@ -1421,7 +1437,10 @@ mod tests { let (_dir, file) = file_with(&contents); let (queue, array) = (new_queue(0), status_array(1)); let mut out = [0u8; 16]; - enqueue(queue, &request(4 << 1, out.as_mut_ptr().cast(), 16, file, 100, 88)); + enqueue( + queue, + &request(4 << 1, out.as_mut_ptr().cast(), 16, file, 100, 88), + ); enqueue_status(queue, array, 0); void(queue, 0x30); assert_eq!(wait(array, 0), S_OK); diff --git a/crates/victory-hle/src/modules/files.rs b/crates/victory-hle/src/modules/files.rs index e25513d..83087f9 100644 --- a/crates/victory-hle/src/modules/files.rs +++ b/crates/victory-hle/src/modules/files.rs @@ -747,7 +747,10 @@ mod tests { let file = std::fs::File::open(&path).unwrap(); let (mut out, mut n) = ([0u8; 10], 0); let handle = file.as_raw_handle().cast(); - assert_ne!(ReadFile(handle, out.as_mut_ptr(), 10, &mut n, std::ptr::null_mut()), 0); + assert_ne!( + ReadFile(handle, out.as_mut_ptr(), 10, &mut n, std::ptr::null_mut()), + 0 + ); assert_eq!((&out, n), (b"0123456789", 10)); } diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index a411bd0..3639fda 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -818,7 +818,10 @@ extern "system" fn unregister_callback(this: This, token: u64, timeout: u64) -> return true; } state = match deadline { - None => hub.returned.wait(state).unwrap_or_else(PoisonError::into_inner), + None => hub + .returned + .wait(state) + .unwrap_or_else(PoisonError::into_inner), Some(deadline) => { let Some(left) = deadline.checked_duration_since(Instant::now()) else { return false; @@ -1564,7 +1567,16 @@ mod tests { let mut token = 0; let context = (&raw const hub.object).cast_mut().cast(); assert_eq!( - register(&hub.object, std::ptr::null(), GAMEPAD_KIND, 1, 0, context, Some(slow), &mut token), + register( + &hub.object, + std::ptr::null(), + GAMEPAD_KIND, + 1, + 0, + context, + Some(slow), + &mut token + ), S_OK ); host.lock().unwrap().pads[1] = Some(PadState::default()); @@ -1573,7 +1585,10 @@ mod tests { std::thread::sleep(Duration::from_millis(1)); } let unregister = slot:: bool, _>(&hub.object, 0x68); - assert!(!unregister(&hub.object, token, 5000), "times out while it runs"); + assert!( + !unregister(&hub.object, token, 5000), + "times out while it runs" + ); let leave = std::thread::spawn(|| { std::thread::sleep(Duration::from_millis(50)); LEAVE.store(true, Ordering::SeqCst); diff --git a/crates/victory-hle/src/modules/kernel.rs b/crates/victory-hle/src/modules/kernel.rs index 3ab3067..affdd7f 100644 --- a/crates/victory-hle/src/modules/kernel.rs +++ b/crates/victory-hle/src/modules/kernel.rs @@ -597,6 +597,7 @@ mod tests { use super::*; #[test] + #[cfg_attr(not(windows), ignore = "title paths are Windows paths")] fn title_images_report_their_original_path() { let base = 0x7000_0000_0000; runtime::set_image_path(base, std::path::Path::new(r"C:\title\game.exe")); @@ -655,6 +656,7 @@ mod tests { } #[test] + #[cfg_attr(not(windows), ignore = "title paths are Windows paths")] fn title_dlls_and_pseudo_modules_are_found_by_name() { let base = 0x7100_0000_0000usize; runtime::set_image_path(base, std::path::Path::new(r"C:\title\Mapped.dll")); diff --git a/crates/victory-hle/src/modules/mod.rs b/crates/victory-hle/src/modules/mod.rs index 51e3590..16d593a 100644 --- a/crates/victory-hle/src/modules/mod.rs +++ b/crates/victory-hle/src/modules/mod.rs @@ -45,7 +45,7 @@ pub mod xuser; use crate::HleModule; pub(crate) fn all() -> Vec { - let mut all = vec![ + vec![ kernel::module(), xgameruntime::module(), gameinput::module(), @@ -53,22 +53,21 @@ pub(crate) fn all() -> Vec { audio::module(), dsp::module(), xg::module(), - ]; - #[cfg(windows)] - all.push(apu::module()); - #[cfg(windows)] - all.push(media::module()); - #[cfg(windows)] - all.push(dstorage::module()); - #[cfg(windows)] - all.push(files::module()); - #[cfg(windows)] - all.push(lifecycle::module()); - #[cfg(windows)] - all.push(net::module()); - #[cfg(windows)] - all.push(xmem::module()); - #[cfg(windows)] - all.push(xsystem::module()); - all + #[cfg(windows)] + apu::module(), + #[cfg(windows)] + media::module(), + #[cfg(windows)] + dstorage::module(), + #[cfg(windows)] + files::module(), + #[cfg(windows)] + lifecycle::module(), + #[cfg(windows)] + net::module(), + #[cfg(windows)] + xmem::module(), + #[cfg(windows)] + xsystem::module(), + ] } diff --git a/crates/victory-hle/src/modules/net.rs b/crates/victory-hle/src/modules/net.rs index 857b351..4b805be 100644 --- a/crates/victory-hle/src/modules/net.rs +++ b/crates/victory-hle/src/modules/net.rs @@ -307,22 +307,77 @@ pub extern "system" fn WSAConnectByList( timeout: *const c_void, reserved: *mut c_void, ) -> i32 { - if !list.is_null() { - // SAFETY: the title passes a `SOCKET_ADDRESS_LIST`. - let entries = unsafe { - let count = usize::try_from(list.cast::().read()).unwrap_or(0); - std::slice::from_raw_parts(list.add(8).cast::(), count) - }; - if !entries + // SAFETY: the title passes a `SOCKET_ADDRESS_LIST` or null. + let entries = (!list.is_null()).then(|| unsafe { + let count = usize::try_from(list.cast::().read()).unwrap_or(0); + std::slice::from_raw_parts(list.add(8).cast::(), count) + }); + if let Some(entries) = entries + && !entries .iter() .all(|e| reachable("network connect blocked", e.addr, e.len)) - { - return 0; + { + return 0; + } + static HOST: std::sync::OnceLock> = std::sync::OnceLock::new(); + match *HOST.get_or_init(|| crate::host::function("ws2_32.dll", "WSAConnectByList")) { + Some(address) => { + type ConnectByList = extern "system" fn( + Socket, + *const u8, + *mut u32, + *mut c_void, + *mut u32, + *mut c_void, + *const c_void, + *mut c_void, + ) -> i32; + // SAFETY: the host's export, with this signature. + let host = unsafe { std::mem::transmute::(address) }; + host( + s, list, local_len, local, remote_len, remote, timeout, reserved, + ) } + None => connect_each( + s, + entries.unwrap_or_default(), + local_len, + local, + remote_len, + remote, + ), } - host!("ws2_32.dll", "WSAConnectByList": extern "system" fn(Socket, *const u8, *mut u32, *mut c_void, *mut u32, *mut c_void, *const c_void, *mut c_void) -> i32)( - s, list, local_len, local, remote_len, remote, timeout, reserved, - ) +} + +/// `WSAConnectByList` where the host lacks it (Wine): `connect` to each +/// candidate in turn until one takes. Blocking; the timeout is not kept. +fn connect_each( + s: Socket, + entries: &[SocketAddress], + local_len: *mut u32, + local: *mut c_void, + remote_len: *mut u32, + remote: *mut c_void, +) -> i32 { + const WSAEINVAL: i32 = 10022; + type Name = extern "system" fn(Socket, *mut c_void, *mut i32) -> i32; + let connect = host!("ws2_32.dll", "connect": extern "system" fn(Socket, *const u8, i32) -> i32); + let set_error = host!("ws2_32.dll", "WSASetLastError": extern "system" fn(i32)); + if entries.is_empty() { + set_error(WSAEINVAL); + return 0; + } + if !entries.iter().any(|e| connect(s, e.addr, e.len) == 0) { + // `connect` left the last candidate's error. + return 0; + } + if !local.is_null() && !local_len.is_null() { + host!("ws2_32.dll", "getsockname": Name)(s, local, local_len.cast()); + } + if !remote.is_null() && !remote_len.is_null() { + host!("ws2_32.dll", "getpeername": Name)(s, remote, remote_len.cast()); + } + 1 } pub extern "system" fn WSAJoinLeaf( @@ -580,7 +635,28 @@ pub extern "system" fn GetAddrInfoExA( if !resolvable(narrow(name)) { return WSAHOST_NOT_FOUND; } - host!("ws2_32.dll", "GetAddrInfoExA": extern "system" fn(*const c_char, *const c_char, u32, *const c_void, *const c_void, *mut *mut c_void, *const c_void, *mut c_void, *const c_void, *mut Handle) -> i32)( + type GetAddrInfoExA = extern "system" fn( + *const c_char, + *const c_char, + u32, + *const c_void, + *const c_void, + *mut *mut c_void, + *const c_void, + *mut c_void, + *const c_void, + *mut Handle, + ) -> i32; + static HOST: std::sync::OnceLock> = std::sync::OnceLock::new(); + // Hosts without the ANSI form (Wine): the name does not resolve, as for + // one we block. + let Some(address) = *HOST.get_or_init(|| crate::host::function("ws2_32.dll", "GetAddrInfoExA")) + else { + return WSAHOST_NOT_FOUND; + }; + // SAFETY: the host's export, with this signature. + let host = unsafe { std::mem::transmute::(address) }; + host( name, service, namespace, provider, hints, result, timeout, overlapped, completion, handle, ) } @@ -895,6 +971,50 @@ mod tests { const AWAY: [u8; 4] = [192, 0, 2, 1]; const HOME: [u8; 4] = [127, 0, 0, 1]; + #[test] + fn connect_by_list_falls_back_to_connect() { + // Also starts Winsock for the raw calls below. + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let socket = host!("ws2_32.dll", "socket": extern "system" fn(i32, i32, i32) -> Socket); + let close = host!("ws2_32.dll", "closesocket": extern "system" fn(Socket) -> i32); + let s = socket(2, 1, 6); + assert_ne!(s, INVALID_SOCKET); + let home = v4(HOME, port); + let entries = [SocketAddress { + addr: home.as_ptr(), + len: 16, + }]; + let (mut local, mut remote) = ([0u8; 16], [0u8; 16]); + let (mut local_len, mut remote_len) = (16u32, 16u32); + assert_eq!( + connect_each( + s, + &entries, + &mut local_len, + local.as_mut_ptr().cast(), + &mut remote_len, + remote.as_mut_ptr().cast(), + ), + 1 + ); + listener.accept().unwrap(); + assert_eq!(remote[2..8], home[2..8]); + assert_eq!(local[4..8], HOME); + close(s); + assert_eq!( + connect_each( + s, + &[], + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + ), + 0 + ); + } + #[test] fn only_loopback_is_reachable() { // Also starts Winsock for the raw calls below. @@ -1048,22 +1168,28 @@ mod tests { named.name ); } - // Every override names a real export of its DLL. Some exports only - // exist on newer Windows (WinHttpGetProxySettingsEx is absent from - // Windows 10's winhttp.dll); the HLE supplies those itself, so skip - // them only when the host really lacks them. - const NEWER_WINDOWS_ONLY: &[&str] = &["WinHttpGetProxySettingsEx"]; - for e in m.exports.iter().filter(|e| !e.name.starts_with('#')) { + // Every override names a real export of its DLL, but for those with + // a fallback of our own (Wine lacks them). + const OPTIONAL: [&str; 3] = [ + "WSAConnectByList", + "GetAddrInfoExA", + "WinHttpGetProxySettingsEx", + ]; + for e in m + .exports + .iter() + .filter(|e| !e.name.starts_with('#') && !OPTIONAL.contains(&e.name)) + { let dll = if e.name.starts_with("WinHttp") { "winhttp.dll" } else { "ws2_32.dll" }; - let present = crate::host::function(dll, e.name).is_some(); - if !present && NEWER_WINDOWS_ONLY.contains(&e.name) { - continue; - } - assert!(present, "{dll} lacks {}", e.name); + assert!( + crate::host::function(dll, e.name).is_some(), + "{dll} lacks {}", + e.name + ); } } } diff --git a/crates/victory-hle/src/modules/storage.rs b/crates/victory-hle/src/modules/storage.rs index 585b641..4b36c75 100644 --- a/crates/victory-hle/src/modules/storage.rs +++ b/crates/victory-hle/src/modules/storage.rs @@ -174,10 +174,17 @@ static VTABLE: Methods<8> = Methods([ #[cfg(test)] mod tests { + #[cfg(windows)] use super::*; + #[cfg(windows)] use crate::modules::xgameruntime::method; + /// The drive-over-folder mount is a Windows-only path (the virtual + /// drives themselves live in the `files` module), so this test runs + /// on Windows only. + #[cfg(windows)] #[test] + #[cfg_attr(not(windows), ignore = "the title's file calls are Windows-only")] fn serves_a_drive_over_the_title_folder_and_its_quota() { type Size = extern "system" fn(This, *mut usize) -> HRESULT; type Get = extern "system" fn(This, usize, *mut u8, *mut usize) -> HRESULT; @@ -205,14 +212,17 @@ mod tests { let drive = std::str::from_utf8(&buffer[..3]).unwrap(); assert!(drive.ends_with(":\\"), "{drive}"); // Title file calls on it reach the folder. - let path = format!("{drive}save.dat\0"); - let mut attributes = [0u8; 36]; - let get_attributes = super::super::files::GetFileAttributesExW; - let wide: Vec = path.encode_utf16().collect(); - assert_ne!( - get_attributes(wide.as_ptr(), 0, attributes.as_mut_ptr().cast()), - 0 - ); + #[cfg(windows)] + { + let path = format!("{drive}save.dat\0"); + let mut attributes = [0u8; 36]; + let get_attributes = super::super::files::GetFileAttributesExW; + let wide: Vec = path.encode_utf16().collect(); + assert_ne!( + get_attributes(wide.as_ptr(), 0, attributes.as_mut_ptr().cast()), + 0 + ); + } let mut info = SpaceInfo { available_free: 0, diff --git a/crates/victory-hle/src/modules/xasync.rs b/crates/victory-hle/src/modules/xasync.rs index 068d75f..f6b8921 100644 --- a/crates/victory-hle/src/modules/xasync.rs +++ b/crates/victory-hle/src/modules/xasync.rs @@ -760,7 +760,10 @@ pub fn pending_with( identity: *const c_void, work: impl FnOnce() -> Result, HRESULT> + Send + 'static, ) -> HRESULT { - type Data = Mutex<(Option Result, HRESULT> + Send>>, Vec)>; + type Data = Mutex<( + Option Result, HRESULT> + Send>>, + Vec, + )>; extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT { // SAFETY: the runtime passes valid provider data; the context is the // boxed state until cleanup frees it. @@ -771,7 +774,11 @@ pub fn pending_with( OP_CLEANUP => drop(unsafe { Box::from_raw(state) }), OP_BEGIN => { // SAFETY: as above; cleanup waits for completion. - let work = unsafe { &*state }.lock().unwrap_or_else(|e| e.into_inner()).0.take(); + let work = unsafe { &*state } + .lock() + .unwrap_or_else(|e| e.into_inner()) + .0 + .take(); let (block, state) = (data.block as usize, state as usize); std::thread::spawn(move || { let result = work.map_or(Err(E_ABORT), |work| work()); @@ -800,7 +807,13 @@ pub fn pending_with( } let state: Box = Box::new(Mutex::new((Some(Box::new(work)), Vec::new()))); let context = Box::into_raw(state); - let hr = XAsyncBegin(block, context.cast(), identity, std::ptr::null(), Some(provider)); + let hr = XAsyncBegin( + block, + context.cast(), + identity, + std::ptr::null(), + Some(provider), + ); if hr < 0 { // SAFETY: refused before the call existed; still ours. drop(unsafe { Box::from_raw(context) }); @@ -1164,7 +1177,13 @@ mod tests { }; let identity = 0x77 as *const c_void; assert_eq!( - XAsyncBegin(&mut block, std::ptr::null_mut(), identity, std::ptr::null(), Some(provider)), + XAsyncBegin( + &mut block, + std::ptr::null_mut(), + identity, + std::ptr::null(), + Some(provider) + ), S_OK ); assert!(XTaskQueueDispatch(q, WORK, 0)); @@ -1175,11 +1194,20 @@ mod tests { let mut value = 0u64; let mut used = 0; assert_eq!( - XAsyncGetResult(&mut block, identity, 8, (&mut value as *mut u64).cast(), &mut used), + XAsyncGetResult( + &mut block, + identity, + 8, + (&mut value as *mut u64).cast(), + &mut used + ), S_OK ); assert_eq!((value, used), (0x1234, 8)); - assert!(call(&raw mut block).is_none(), "the call ends with its result"); + assert!( + call(&raw mut block).is_none(), + "the call ends with its result" + ); XTaskQueueCloseHandle(q); } diff --git a/crates/victory-hle/src/modules/xg.rs b/crates/victory-hle/src/modules/xg.rs index 46912d7..d26d8c6 100644 --- a/crates/victory-hle/src/modules/xg.rs +++ b/crates/victory-hle/src/modules/xg.rs @@ -582,19 +582,19 @@ struct Vtable([*const (); 13]); unsafe impl Sync for Vtable {} static VTABLE: Vtable = Vtable([ - add_ref as *const (), // 0x00 - release as *const (), // 0x08 - layout as *const (), // 0x10 - unused as *const (), // 0x18 size - unused as *const (), // 0x20 alignment - unused as *const (), // 0x28 mip offset + add_ref as *const (), // 0x00 + release as *const (), // 0x08 + layout as *const (), // 0x10 + unused as *const (), // 0x18 size + unused as *const (), // 0x20 alignment + unused as *const (), // 0x28 mip offset element_offset as *const (), // 0x30 - unused as *const (), // 0x38 element coordinate - copy_into as *const (), // 0x40 - copy_from as *const (), // 0x48 - tiling as *const (), // 0x50 - unused as *const (), // 0x58 view descriptor - unused as *const (), // 0x60 tiled resource? + unused as *const (), // 0x38 element coordinate + copy_into as *const (), // 0x40 + copy_from as *const (), // 0x48 + tiling as *const (), // 0x50 + unused as *const (), // 0x58 view descriptor + unused as *const (), // 0x60 tiled resource? ]); pub(crate) fn module() -> HleModule { diff --git a/crates/victory-hle/src/modules/xgame.rs b/crates/victory-hle/src/modules/xgame.rs index c54f837..2cc4f5a 100644 --- a/crates/victory-hle/src/modules/xgame.rs +++ b/crates/victory-hle/src/modules/xgame.rs @@ -74,17 +74,28 @@ extern "system" fn launch_new_game( args: *const c_char, _user: *const c_void, ) { - let (exe, args) = (text(exe).unwrap_or_default(), text(args).unwrap_or_default()); + let (exe, args) = ( + text(exe).unwrap_or_default(), + text(args).unwrap_or_default(), + ); tracing::info!(exe, args, "XLaunchNewGame"); let current = runtime::main_image() .and_then(runtime::image_path) .unwrap_or_default(); let ours: Vec<_> = std::env::args_os().skip(1).collect(); let command = relaunch_args(ours, current.as_os_str(), &exe, &args); + #[cfg(not(windows))] + let _ = command; + #[cfg(windows)] super::lifecycle::end_title( "XLaunchNewGame", Box::new(move || super::lifecycle::relaunch(command)), ); + #[cfg(not(windows))] + { + let _ = &command; + tracing::info!("XLaunchNewGame: not implemented on this host; the title ends"); + } loop { std::thread::park(); } @@ -195,15 +206,32 @@ mod tests { #[test] fn a_relaunch_keeps_our_options() { - let ours: Vec = - ["run", "G:/game.exe", "--execute", "--console", "series-s", "--", "-old"] - .map(Into::into) - .into(); + let ours: Vec = [ + "run", + "G:/game.exe", + "--execute", + "--console", + "series-s", + "--", + "-old", + ] + .map(Into::into) + .into(); let current = std::ffi::OsStr::new("G:/game.exe"); let again = relaunch_args(ours.clone(), current, "G:/game.exe", " -config=x -y "); - let expected = ["run", "G:/game.exe", "--execute", "--console", "series-s", "--"]; + let expected = [ + "run", + "G:/game.exe", + "--execute", + "--console", + "series-s", + "--", + ]; assert_eq!(again[..6], expected.map(std::ffi::OsString::from)); - assert_eq!(again[6..], ["-config=x", "-y"].map(std::ffi::OsString::from)); + assert_eq!( + again[6..], + ["-config=x", "-y"].map(std::ffi::OsString::from) + ); let other = relaunch_args(ours, current, "G:/other.exe", ""); assert_eq!(other.len(), 5); assert_eq!(other[1], "G:/other.exe"); diff --git a/crates/victory-hle/src/modules/xgamesave.rs b/crates/victory-hle/src/modules/xgamesave.rs index d77ac8a..50bafd5 100644 --- a/crates/victory-hle/src/modules/xgamesave.rs +++ b/crates/victory-hle/src/modules/xgamesave.rs @@ -256,8 +256,9 @@ fn commit( match source { Source::Data(data) => write(path, data)?, // Files are never changed in place, so sharing one is safe. - Source::Kept(from) => std::fs::hard_link(from, &path) - .or_else(|_| std::fs::copy(from, &path).map(drop))?, + Source::Kept(from) => { + std::fs::hard_link(from, &path).or_else(|_| std::fs::copy(from, &path).map(drop))? + } } step(); } @@ -460,7 +461,9 @@ impl Update { } let replaced: u64 = current.as_ref().map_or(0, |v| { let sizes = v.sizes(); - let changed = sizes.iter().filter(|(n, _)| self.changes.iter().any(|(c, _)| c == n)); + let changed = sizes + .iter() + .filter(|(n, _)| self.changes.iter().any(|(c, _)| c == n)); changed.map(|(_, size)| size).sum() }); let root = self.dir.parent().unwrap_or(&self.dir); @@ -513,7 +516,11 @@ fn read(c: &Container, names: Option>) -> Result bool, context: *mut c_void, callback: ContainerCallback) { +fn report( + root: &Path, + keep: impl Fn(&str) -> bool, + context: *mut c_void, + callback: ContainerCallback, +) { let infos: Vec<(CString, CString, u32, u64, i64)> = { let _saves = saves_lock(); containers(root) @@ -974,7 +986,10 @@ mod tests { fn a_full_disk_is_not_the_quota() { let mb = 1 << 20; assert_eq!(no_room(2 * mb, 0, 0, mb), Some(OUT_OF_LOCAL_STORAGE)); - assert_eq!(no_room(2 * mb, 0, QUOTA - mb, 100 * mb), Some(QUOTA_EXCEEDED)); + assert_eq!( + no_room(2 * mb, 0, QUOTA - mb, 100 * mb), + Some(QUOTA_EXCEEDED) + ); // Replacing a blob of the same size fits a full quota. assert_eq!(no_room(mb, mb, QUOTA, 100 * mb), None); assert_eq!(no_room(mb, 0, 0, mb), None); @@ -1003,18 +1018,28 @@ mod tests { } fn old_state() -> Option<(String, Vec<(String, String)>)> { - Some(("one".into(), vec![("a".into(), "old a".into()), ("b".into(), "old b".into())])) + Some(( + "one".into(), + vec![("a".into(), "old a".into()), ("b".into(), "old b".into())], + )) } /// Run by the crash test in a child process; does nothing otherwise. #[test] fn crash_child() { - let (Ok(root), Ok(op)) = (std::env::var("VICTORY_SAVE_CHILD"), std::env::var("VICTORY_SAVE_OP")) else { + let (Ok(root), Ok(op)) = ( + std::env::var("VICTORY_SAVE_CHILD"), + std::env::var("VICTORY_SAVE_OP"), + ) else { return; }; let root = PathBuf::from(root); let hr = if op == "update" { - update(&root, "two", &[("a", Some("new a")), ("b", None), ("c", Some("new c"))]) + update( + &root, + "two", + &[("a", Some("new a")), ("b", None), ("c", Some("new c"))], + ) } else { delete(&root, "Slot") }; @@ -1027,15 +1052,25 @@ mod tests { /// new one. #[test] fn a_kill_at_any_step_leaves_old_or_new() { - let new = Some(("two".into(), vec![("a".into(), "new a".into()), ("c".into(), "new c".into())])); + let new = Some(( + "two".into(), + vec![("a".into(), "new a".into()), ("c".into(), "new c".into())], + )); for (op, after) in [("update", new), ("delete", None)] { let mut seen = (0, 0); for stop in 1.. { let dir = tempfile::tempdir().unwrap(); let root = dir.path(); - assert_eq!(update(root, "one", &[("a", Some("old a")), ("b", Some("old b"))]), S_OK); + assert_eq!( + update(root, "one", &[("a", Some("old a")), ("b", Some("old b"))]), + S_OK + ); let mut child = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", "modules::xgamesave::tests::crash_child", "--nocapture"]) + .args([ + "--exact", + "modules::xgamesave::tests::crash_child", + "--nocapture", + ]) .args(["--test-threads=1"]) .env("VICTORY_SAVE_CHILD", root) .env("VICTORY_SAVE_OP", op) @@ -1080,16 +1115,35 @@ mod tests { for good in ["Profile/Slot_1", "a/b/Save-2.sav", "x", &"a".repeat(256)] { assert!(valid_container(good), "{good}"); } - for bad in ["a b", "", "a/", "a.", "a..b", "a.b/c", "a-b/c", &"a".repeat(257)] { + for bad in [ + "a b", + "", + "a/", + "a.", + "a..b", + "a.b/c", + "a-b/c", + &"a".repeat(257), + ] { assert!(!valid_container(bad), "{bad}"); } // Containers and blobs differing only in case, reserved device // names, characters the host forbids, long names: all distinct. let dir = tempfile::tempdir().unwrap(); - let p = Provider { root: dir.path().into() }; + let p = Provider { + root: dir.path().into(), + }; let long = "n".repeat(300); - let blobs = ["A", "a", "CON", "nul.txt", "x/y:z*?\"<>|", long.as_str(), "end. "]; + let blobs = [ + "A", + "a", + "CON", + "nul.txt", + "x/y:z*?\"<>|", + long.as_str(), + "end. ", + ]; for container in ["Save", "save", "SAVE/CON.x"] { let c = p.container(container); let u = Update { @@ -1121,7 +1175,10 @@ mod tests { #[test] fn the_old_layout_moves_over() { let saves = tempfile::tempdir().unwrap(); - let root = saves.path().join(format!("{:016X}", xuser::XUID)).join("scid"); + let root = saves + .path() + .join(format!("{:016X}", xuser::XUID)) + .join("scid"); let old = root.join("Player"); std::fs::create_dir_all(&old).unwrap(); std::fs::write(old.join("Save%20Game%20Data"), b"data").unwrap(); @@ -1214,7 +1271,10 @@ mod tests { S_OK ); type Delete = extern "system" fn(This, *mut Update, *const c_char) -> HRESULT; - assert_eq!(method::(&OBJECT, 0xd0)(this, update, c"gone".as_ptr()), S_OK); + assert_eq!( + method::(&OBJECT, 0xd0)(this, update, c"gone".as_ptr()), + S_OK + ); type Submit = extern "system" fn(This, *const Update, *mut AsyncBlock) -> HRESULT; let mut b = block(); assert_eq!(method::(&OBJECT, 0xe0)(this, update, &mut b), S_OK); diff --git a/crates/victory-hle/src/modules/xgameui.rs b/crates/victory-hle/src/modules/xgameui.rs index ab2d9e0..642e455 100644 --- a/crates/victory-hle/src/modules/xgameui.rs +++ b/crates/victory-hle/src/modules/xgameui.rs @@ -60,7 +60,8 @@ extern "system" fn text_entry_async( _scope: u32, max_length: u32, ) -> HRESULT { - let [title, description, default] = [title, description, default].map(|t| text(t).unwrap_or_default()); + let [title, description, default] = + [title, description, default].map(|t| text(t).unwrap_or_default()); tracing::info!(title, description, max_length, "text entry"); xasync::pending_with(block, (&raw const TEXT).cast(), move || { match ask(&title, &description, &default, max_length) { @@ -111,11 +112,17 @@ fn limit(typed: &str, max: u32) -> String { } /// Asks the user in a modal host dialog; `None` if dismissed. -#[cfg(not(test))] +#[cfg(all(windows, not(test)))] fn ask(title: &str, description: &str, default: &str, max: u32) -> Option { dialog::ask(title, description, default, max) } +/// No host dialog yet: as if the user dismissed it. +#[cfg(all(not(windows), not(test)))] +fn ask(_: &str, _: &str, _: &str, _: u32) -> Option { + None +} + /// Tests answer for the user: "typed" for a title starting with "Type", /// cancelled otherwise. #[cfg(test)] @@ -123,6 +130,7 @@ fn ask(title: &str, _: &str, default: &str, _: u32) -> Option { title.starts_with("Type").then(|| format!("{default}typed")) } +#[cfg(windows)] mod dialog { use windows_sys::Win32::Foundation::{HWND, LPARAM, WPARAM}; use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; @@ -178,7 +186,13 @@ mod dialog { let ok = wm::BS_DEFPUSHBUTTON as u32 | tab; item(ok, [129, 40, 50, 14], wm::IDOK as u16, button, "OK"); let cancel = wm::BS_PUSHBUTTON as u32 | tab; - item(cancel, [183, 40, 50, 14], wm::IDCANCEL as u16, button, "Cancel"); + item( + cancel, + [183, 40, 50, 14], + wm::IDCANCEL as u16, + button, + "Cancel", + ); // The template must start on a DWORD. let template: Vec = t .chunks(2) @@ -199,7 +213,12 @@ mod dialog { entry.typed } - extern "system" fn procedure(dialog: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> isize { + extern "system" fn procedure( + dialog: HWND, + message: u32, + wparam: WPARAM, + lparam: LPARAM, + ) -> isize { // SAFETY: our dialog; its user data is the `Entry` from `ask`, // stored at WM_INITDIALOG. unsafe { @@ -214,12 +233,16 @@ mod dialog { 0 // focus set here } wm::WM_COMMAND => { - let entry = &mut *(wm::GetWindowLongPtrW(dialog, wm::GWLP_USERDATA) as *mut Entry); + let entry = + &mut *(wm::GetWindowLongPtrW(dialog, wm::GWLP_USERDATA) as *mut Entry); match (wparam & 0xffff) as i32 { wm::IDOK => { - let mut buffer = vec![0u16; wm::GetWindowTextLengthW(edit) as usize + 1]; - let n = wm::GetWindowTextW(edit, buffer.as_mut_ptr(), buffer.len() as i32); - entry.typed = Some(String::from_utf16_lossy(&buffer[..n.max(0) as usize])); + let mut buffer = + vec![0u16; wm::GetWindowTextLengthW(edit) as usize + 1]; + let n = + wm::GetWindowTextW(edit, buffer.as_mut_ptr(), buffer.len() as i32); + entry.typed = + Some(String::from_utf16_lossy(&buffer[..n.max(0) as usize])); wm::EndDialog(dialog, 1); } wm::IDCANCEL => { @@ -295,19 +318,29 @@ mod tests { u32, ) -> HRESULT; type Size = extern "system" fn(This, *mut AsyncBlock, *mut u32) -> HRESULT; - type Result_ = extern "system" fn(This, *mut AsyncBlock, u32, *mut c_char, *mut u32) -> HRESULT; + type Result_ = + extern "system" fn(This, *mut AsyncBlock, u32, *mut c_char, *mut u32) -> HRESULT; let null = std::ptr::null(); let entry = method::(&OBJECT, 0x88); // Dismissed: cancelled. let mut b = block(); - assert_eq!(entry(this, &mut b, c"Name".as_ptr(), null, null, 0, 16), S_OK); + assert_eq!( + entry(this, &mut b, c"Name".as_ptr(), null, null, 0, 16), + S_OK + ); assert_eq!(xasync::XAsyncGetStatus(&mut b, true), E_ABORT); let mut size = 0; - assert_eq!(method::(&OBJECT, 0x90)(this, &mut b, &mut size), E_ABORT); + assert_eq!( + method::(&OBJECT, 0x90)(this, &mut b, &mut size), + E_ABORT + ); // Typed: the text, cut to the limit, with its NUL. let mut b = block(); let default = c"abc".as_ptr(); - assert_eq!(entry(this, &mut b, c"Type".as_ptr(), null, default, 0, 6), S_OK); + assert_eq!( + entry(this, &mut b, c"Type".as_ptr(), null, default, 0, 6), + S_OK + ); assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); assert_eq!(method::(&OBJECT, 0x90)(this, &mut b, &mut size), S_OK); assert_eq!(size, 7); diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs index c8479c5..c93aa47 100644 --- a/crates/victory-hle/src/runtime.rs +++ b/crates/victory-hle/src/runtime.rs @@ -26,12 +26,40 @@ static IMAGE_PATHS: Mutex> = Mutex::new(Vec::new()); /// own path (`GetModuleFileName`) to find its data, and must not get our /// cache copy. pub fn set_image_path(base: usize, path: &Path) { - let path = std::path::absolute(path).unwrap_or_else(|_| path.to_owned()); + let path = absolute_title_path(path); let mut paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner()); paths.retain(|(b, _)| *b != base); paths.push((base, path)); } +/// Makes `path` absolute, as the title stored it: an already-absolute path +/// is kept as is; a relative path is made absolute against the current +/// directory. A Windows path is absolute everywhere, regardless of the +/// host: `C:\title\game.exe` is a title path, not a bare relative one +/// that the host would make absolute against the wrong root. +fn absolute_title_path(path: &Path) -> PathBuf { + if path.is_absolute() || title_absolute(path) { + return path.to_path_buf(); + } + std::path::absolute(path).unwrap_or_else(|_| path.to_owned()) +} + +/// Whether `path` looks like an absolute Windows path: a drive root (`C:\`), +/// a drive-rooted path (`C:\title\game.exe`) or a UNC path (`\\server\share`). +fn title_absolute(path: &Path) -> bool { + let s = path.to_string_lossy(); + let bytes = s.as_bytes(); + // A drive root: `X:` (nothing else), then a separator. + if bytes.len() >= 2 + && bytes[0].is_ascii_alphabetic() + && bytes[1] == b':' + && (bytes.len() == 2 || bytes[2] == b'\\' || bytes[2] == b'/') + { + return true; + } + s.starts_with("\\\\") +} + /// Forgets a title image that was unmapped again. pub fn forget_image(base: usize) { let mut paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner()); @@ -51,10 +79,19 @@ pub fn image_named(file: &str) -> Option { let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner()); paths .iter() - .find(|(_, p)| p.file_name().is_some_and(|n| n.eq_ignore_ascii_case(file))) + .find(|(_, p)| title_file_name(p).is_some_and(|n| n.eq_ignore_ascii_case(file))) .map(|(b, _)| *b) } +/// The file name of a path, whatever its shape: `C:\title\Mapped.dll` and +/// `C:\title/Mapped.dll` both name `Mapped.dll`, on whatever host the title +/// runs on. +fn title_file_name(path: &Path) -> Option { + let s = path.to_string_lossy(); + let name = s.rsplit(['\\', '/']).next()?; + Some(name.to_string()) +} + /// Maps a title DLL the title loads itself (`LoadLibrary`) and returns its /// base; `Ok(None)` if `file` is not one of the title's DLLs. pub type TitleDllLoader = Box Result, String> + Send + Sync>; @@ -149,9 +186,15 @@ fn elements(text: &str) -> Vec<(String, String)> { .unwrap_or(""); path.push(name); let body = rest[..rest.find('<').unwrap_or(rest.len())].trim(); - let body = [("<", "<"), (">", ">"), (""", "\""), ("'", "'"), ("&", "&")] - .iter() - .fold(body.to_owned(), |b, (entity, c)| b.replace(entity, c)); + let body = [ + ("<", "<"), + (">", ">"), + (""", "\""), + ("'", "'"), + ("&", "&"), + ] + .iter() + .fold(body.to_owned(), |b, (entity, c)| b.replace(entity, c)); out.push((path.join("/"), body)); if closed { path.pop(); diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs index 7d13646..ecd3ee5 100644 --- a/crates/victory-loader/src/crash.rs +++ b/crates/victory-loader/src/crash.rs @@ -64,8 +64,11 @@ pub fn log_crashes_to(file: std::path::PathBuf) { /// Appends a failure that is not an exception (the host GPU's) to the crash /// log, with the title's last debug output, and prints it. pub fn log_crash(text: &str) { - let text = format!("{text} -{}", title_output()); + let text = format!( + "{text} +{}", + title_output() + ); eprint!("{text}"); append_to_log(&text); } @@ -76,9 +79,16 @@ fn append_to_log(text: &str) { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| d.as_secs()); - let opened = std::fs::OpenOptions::new().create(true).append(true).open(file); + let opened = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(file); if let Ok(mut f) = opened { - let _ = write!(f, "unix time {now}, process {}\n{text}\n", std::process::id()); + let _ = write!( + f, + "unix time {now}, process {}\n{text}\n", + std::process::id() + ); } } @@ -105,7 +115,9 @@ fn title_output() -> String { let Ok(said) = SAID.try_lock() else { return String::new(); }; - said.iter().map(|l| format!(" title said: {l}\n")).collect() + said.iter() + .map(|l| format!(" title said: {l}\n")) + .collect() } /// Installs the handlers; call once before running title code. @@ -336,12 +348,20 @@ unsafe fn sse4a(code: *const u8, xmm: &mut [M128A; 16]) -> Option { ((b(at + 3), b(at + 4)), at + 5) } else { // extrq reads its fields from src's low half, insertq from its high. - let f = if prefix == 0x66 { xmm[src].Low } else { xmm[src].High as u64 }; + let f = if prefix == 0x66 { + xmm[src].Low + } else { + xmm[src].High as u64 + }; ((f as u8, (f >> 8) as u8), at + 3) }; let (n, at_bit) = (u32::from(fields.0 & 63), u32::from(fields.1 & 63)); let bits = if n == 0 { 64 } else { n }; - let mask = if bits == 64 { u64::MAX } else { (1u64 << bits) - 1 }; + let mask = if bits == 64 { + u64::MAX + } else { + (1u64 << bits) - 1 + }; if prefix == 0x66 { // extrq: register form takes its fields from src, works on dst. if immediate && (modrm >> 3) & 7 != 0 { @@ -414,8 +434,7 @@ unsafe fn thrown(p: &[usize]) -> String { let types = p[3] + rva(p[2] + 12); let name = |i: usize| { let descriptor = p[3] + rva(p[3] + rva(types + 4 + 4 * i) + 4); - std::ffi::CStr::from_ptr((descriptor + 16) as *const std::ffi::c_char) - .to_string_lossy() + std::ffi::CStr::from_ptr((descriptor + 16) as *const std::ffi::c_char).to_string_lossy() }; let first = name(0); let value = match &*first { diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs index 233ca47..3164cd9 100644 --- a/crates/victory-loader/src/lib.rs +++ b/crates/victory-loader/src/lib.rs @@ -36,12 +36,12 @@ mod tls; #[cfg(windows)] mod windows; +#[cfg(all(windows, feature = "diagnostics"))] +pub use crash::save_on_crash; #[cfg(windows)] pub use crash::{ locate, log_crash, log_crashes_to, note_title_output, report_crashes, report_unhandled, }; -#[cfg(all(windows, feature = "diagnostics"))] -pub use crash::save_on_crash; pub use prepare::{PrepareError, PreparedImage, prepare}; pub use resolve::{ImportResolver, Provenance, Resolution}; #[cfg(all(windows, feature = "diagnostics"))] diff --git a/crates/victory-loader/src/prepare.rs b/crates/victory-loader/src/prepare.rs index c893508..c3f8c90 100644 --- a/crates/victory-loader/src/prepare.rs +++ b/crates/victory-loader/src/prepare.rs @@ -175,9 +175,12 @@ fn write(bytes: &mut [u8], at: usize, v: &[u8]) -> Result<(), PrepareError> { #[cfg(test)] mod tests { + #[cfg(windows)] use super::*; + #[cfg(windows)] #[test] + #[cfg_attr(not(windows), ignore = "parses the test binary as a PE image")] fn patches_own_test_binary() { let original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); let prepared = prepare(&original).unwrap(); @@ -204,7 +207,9 @@ mod tests { assert_eq!(prepared.bytes.len(), original.len()); } + #[cfg(windows)] #[test] + #[cfg_attr(not(windows), ignore = "parses the test binary as a PE image")] fn keeps_iat_slots_when_import_size_excludes_the_terminator() { let mut original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); let info = ImageInfo::parse(&original).unwrap(); @@ -273,7 +278,9 @@ mod tests { ); } + #[cfg(windows)] #[test] + #[cfg_attr(not(windows), ignore = "parses the test binary as a PE image")] fn file_name_is_stable_per_build() { let original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); let a = prepare(&original).unwrap(); diff --git a/crates/victory-loader/src/threads.rs b/crates/victory-loader/src/threads.rs index 903aebd..a7a85d0 100644 --- a/crates/victory-loader/src/threads.rs +++ b/crates/victory-loader/src/threads.rs @@ -164,8 +164,8 @@ fn end_other_threads(keep: &[u32]) { CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, }; use windows_sys::Win32::System::Threading::{ - GetCurrentProcessId, GetCurrentThreadId, OpenThread, THREAD_TERMINATE, TerminateThread, - THREAD_QUERY_INFORMATION, + GetCurrentProcessId, GetCurrentThreadId, OpenThread, THREAD_QUERY_INFORMATION, + THREAD_TERMINATE, TerminateThread, }; // SAFETY: plain queries of the calling process and thread. let (process, me) = unsafe { (GetCurrentProcessId(), GetCurrentThreadId()) }; @@ -323,7 +323,10 @@ impl OwnTls { /// title callbacks. fn started_by_rust() -> bool { // SAFETY: the calling thread's pseudo handle. - starts_in(unsafe { windows_sys::Win32::System::Threading::GetCurrentThread() }, c"") + starts_in( + unsafe { windows_sys::Win32::System::Threading::GetCurrentThread() }, + c"", + ) } /// Whether `thread`'s start routine lies in the module named `module` diff --git a/crates/victory-loader/tests/load_probe.rs b/crates/victory-loader/tests/load_probe.rs index cf1111b..ad225d0 100644 --- a/crates/victory-loader/tests/load_probe.rs +++ b/crates/victory-loader/tests/load_probe.rs @@ -19,22 +19,100 @@ fn workspace_root() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("..") } -/// Builds the fixture into its own target dir (the outer cargo holds the -/// lock on the main one while tests run), in the outer one's scratch folder -/// for tests, so that it follows `CARGO_TARGET_DIR` like the rest of the -/// build. -fn build_probe() -> PathBuf { +/// Set to a prebuilt `hle_probe.dll` to load it instead of building one. +const PREBUILT_PROBE: &str = "VICTORY_HLE_PROBE_DLL"; + +/// Whether we run under Wine (its ntdll exports `wine_get_version`). +fn under_wine() -> bool { + // SAFETY: NUL-terminated strings; ntdll is always loaded. + unsafe { + let ntdll = LoadLibraryA(c"ntdll.dll".as_ptr().cast()); + !ntdll.is_null() && GetProcAddress(ntdll, c"wine_get_version".as_ptr().cast()).is_some() + } +} + +/// The fixture to load, or `None` when it cannot be had here. +/// +/// Normally it is built into its own target dir under `CARGO_TARGET_TMPDIR` +/// (the outer cargo holds the lock on the main one while tests run), so it +/// follows `CARGO_TARGET_DIR` and `build.target-dir` like the rest of the +/// build. Under Wine, as when a test exe cross-built on Linux is run by Wine +/// or Proton, the `cargo` that built the test is a host program the guest +/// cannot run, so the test is skipped unless the fixture was built +/// beforehand, e.g. with +/// `cargo xwin build --manifest-path tests/fixtures/hle-probe/Cargo.toml +/// --target x86_64-pc-windows-msvc` and its path in `VICTORY_HLE_PROBE_DLL`. +fn probe_dll() -> Option { + if let Some(path) = std::env::var_os(PREBUILT_PROBE).filter(|p| !p.is_empty()) { + let path = PathBuf::from(path); + // Under Wine a bare Unix path (`/home/...`) resolves against the + // current drive and silently misses; fail with the fix instead of a + // bare "not found" from the read below. + assert!( + path.is_file(), + "{PREBUILT_PROBE}={} is not a file; under Wine use its Windows \ + path, e.g. Z:/home/you/VIctory/tests/fixtures/hle-probe/target/\ + x86_64-pc-windows-msvc/debug/hle_probe.dll", + path.display() + ); + return Some(path); + } + if under_wine() { + eprintln!( + "skipping: under Wine the host cargo cannot build hle-probe; \ + set {PREBUILT_PROBE} to a prebuilt hle_probe.dll to run this test" + ); + return None; + } let manifest = workspace_root().join("tests/fixtures/hle-probe/Cargo.toml"); let target = Path::new(env!("CARGO_TARGET_TMPDIR")).join("hle-probe"); - let status = Command::new(env!("CARGO")) - .args(["build", "--quiet", "--manifest-path"]) + // Name the target: a `CARGO_BUILD_TARGET` or `build.target` from the + // environment or a user config would otherwise move the output under a + // triple directory the path below does not expect. The fixture's build + // script passes MSVC linker flags, hence `-msvc`. + let triple = format!("{}-pc-windows-msvc", std::env::consts::ARCH); + // The cargo that built this test, recorded at compile time. A test exe + // cross-built elsewhere and copied here names a cargo that is not on this + // machine; say so instead of a bare "not found" from the spawn below. + let cargo = Path::new(env!("CARGO")); + assert!( + cargo.is_file(), + "{} (the cargo that built this test) is not on this machine; build \ + hle-probe and set {PREBUILT_PROBE} to its hle_probe.dll", + cargo.display() + ); + let status = Command::new(cargo) + .args(["build", "--quiet", "--locked", "--manifest-path"]) .arg(&manifest) - .arg("--target-dir") + .args(["--target", &triple, "--target-dir"]) .arg(&target) .status() - .expect("running cargo"); - assert!(status.success(), "building hle-probe failed"); - target.join("debug").join("hle_probe.dll") + .unwrap_or_else(|e| panic!("running {}: {e}", cargo.display())); + assert!( + status.success(), + "building {} for {triple} failed ({status})", + manifest.display() + ); + let dll = target.join(&triple).join("debug").join("hle_probe.dll"); + assert!( + dll.is_file(), + "hle-probe built, but {} is missing", + dll.display() + ); + Some(dll) +} + +/// A stand-in title DLL: `version.dll` from the system directory. Built from +/// `%SystemRoot%` (Windows may not be on `C:`); the copy names both paths if +/// it fails. +fn copy_stand_in_dll(to: &Path) { + let windows = std::env::var_os("SystemRoot") + .filter(|p| !p.is_empty()) + .map_or_else(|| PathBuf::from(r"C:\Windows"), PathBuf::from); + let from = windows.join("System32").join("version.dll"); + if let Err(e) = std::fs::copy(&from, to) { + panic!("copying {} to {}: {e}", from.display(), to.display()); + } } extern "system" fn fake_xgameruntime_initialize() -> i32 { @@ -98,7 +176,9 @@ fn host(dll: &str, name: &str) -> Option { #[test] fn loads_binds_and_calls_probe() { - let dll = build_probe(); + let Some(dll) = probe_dll() else { + return; + }; let original = std::fs::read(&dll).unwrap(); let prepared = prepare(&original).unwrap(); @@ -130,11 +210,7 @@ fn loads_binds_and_calls_probe() { // The "title" ships victory-probe-title.dll: any real DLL will do. let title_dir = tempfile::tempdir().unwrap(); - std::fs::copy( - r"C:\Windows\System32\version.dll", - title_dir.path().join("victory-probe-title.dll"), - ) - .unwrap(); + copy_stand_in_dll(&title_dir.path().join("victory-probe-title.dll")); let dlls = victory_loader::load_title_dlls(image.info(), title_dir.path(), dir.path(), &|_| true) .unwrap(); @@ -251,11 +327,7 @@ fn maps_a_title_dll_the_title_loads_itself() { let title_dir = tempfile::tempdir().unwrap(); let cache = tempfile::tempdir().unwrap(); // Any real DLL will do; it imports only host DLLs, which are not in the folder. - std::fs::copy( - r"C:\Windows\System32\version.dll", - title_dir.path().join("Late.dll"), - ) - .unwrap(); + copy_stand_in_dll(&title_dir.path().join("Late.dll")); let load = |name: &str, wanted: &dyn Fn(&str) -> bool| { victory_loader::load_title_dll(name, title_dir.path(), cache.path(), wanted).unwrap() }; diff --git a/crates/victory-pe/src/image.rs b/crates/victory-pe/src/image.rs index fc8f0f6..2489d27 100644 --- a/crates/victory-pe/src/image.rs +++ b/crates/victory-pe/src/image.rs @@ -410,7 +410,9 @@ mod tests { std::fs::read(std::env::current_exe().unwrap()).unwrap() } + #[cfg(windows)] #[test] + #[cfg_attr(not(windows), ignore = "parses the test binary as a PE image")] fn parses_own_test_binary() { let info = ImageInfo::parse(&own_image()).unwrap(); assert_eq!(info.machine, MACHINE_AMD64); @@ -429,7 +431,9 @@ mod tests { assert!(info.tls.is_some()); } + #[cfg(windows)] #[test] + #[cfg_attr(not(windows), ignore = "parses the test binary as a PE image")] fn rva_to_file_offset_maps_entry_point() { let data = own_image(); let info = ImageInfo::parse(&data).unwrap(); @@ -437,7 +441,9 @@ mod tests { assert!(off < data.len()); } + #[cfg(windows)] #[test] + #[cfg_attr(not(windows), ignore = "parses the test binary as a PE image")] fn rva_to_file_offset_rejects_offsets_past_4_gib() { let mut info = ImageInfo::parse(&own_image()).unwrap(); let rva = info.sections[0].rva + 0x20; @@ -457,7 +463,9 @@ mod tests { assert!(ImageInfo::parse(&truncated).is_err()); } + #[cfg(windows)] #[test] + #[cfg_attr(not(windows), ignore = "parses the test binary as a PE image")] fn rejects_iat_outside_image() { let mut data = own_image(); let dd = layout::data_directory_offset(&data, dir::IMPORT).unwrap(); diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c5fbd80..eb2e9a3 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -222,6 +222,10 @@ struct Lower<'a> { counters: HashMap)>, /// The block a loop stopped by [`LOOP_LIMIT`] leaves the program from. abort: Option, + /// The one block that returns: every end of the program branches to it, + /// so the function has a single exit as DXC emits it (dxil-spirv, under + /// Proton, cannot structure a loop left by both a break and a return). + ret: Option, } /// Iterations after which a loop is left (per entry into it), unless @@ -515,6 +519,7 @@ impl<'a> Lower<'a> { code_table: None, counters: HashMap::new(), abort: None, + ret: None, } } @@ -6811,7 +6816,7 @@ impl<'a> Lower<'a> { self.s .op(self.cur, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]); } - Term::Ret + Term::Br(self.ret_block()) } LaneExit::Indirect => return Err(unsupported(offset, "an indirect jump")), }; @@ -6857,11 +6862,23 @@ impl<'a> Lower<'a> { self.s .op(a, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]); } - self.s.m.terminate(a, Term::Ret); + let r = self.ret_block(); + self.s.m.terminate(a, Term::Br(r)); self.abort = Some(a); a } + /// The function's single returning block (see `ret`). + fn ret_block(&mut self) -> usize { + if let Some(r) = self.ret { + return r; + } + let r = self.s.m.new_block(); + self.s.m.terminate(r, Term::Ret); + self.ret = Some(r); + r + } + /// The DXIL block a branch from IR block `from` to `to` goes to. fn edge(&mut self, from: usize, to: usize) -> usize { let target = self.block[to].expect("reachable"); @@ -7099,9 +7116,7 @@ mod tests { S_ENDPGM, ]; - let code: Vec = words.iter() - .flat_map(|w| w.to_le_bytes()) - .collect(); + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); let native = NativeProgram { stage: HwStage::Cs, @@ -7118,9 +7133,12 @@ mod tests { let p = ir::build(&native.code, false, 256).unwrap(); - assert!(p.blocks.iter() - .flat_map(|b| &b.insts) - .any(|i| i.name() == "v_perm_b32")); + assert!( + p.blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| i.name() == "v_perm_b32") + ); let st = structure::structure(&p).unwrap(); let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); @@ -7137,13 +7155,12 @@ mod tests { outputs: vec![], prims: vec![], mesh_stride: 0, - }).unwrap(); + }) + .unwrap(); - let container = - crate::Container::parse(&emitted.dxil).unwrap(); + let container = crate::Container::parse(&emitted.dxil).unwrap(); - let features = - container.part(crate::FourCC::SFI0).unwrap(); + let features = container.part(crate::FourCC::SFI0).unwrap(); u64::from_le_bytes(features.data.try_into().unwrap()) } diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 89652da..c388e1e 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -402,8 +402,92 @@ fn signature(part: &[u8]) -> Result, ShaderError> { Ok(out) } +/// A pixel shader for debug views (`VICTORY_DEBUG_PS` in the GPU crate): +/// colours each pixel by the slope of its surface, from the screen-space +/// derivatives of its depth (`SV_Position.z`), written to all `targets` +/// colour targets. It reads nothing of the title's, so a draw's geometry +/// shows whether or not its own pixel shader translates: a check that the +/// vertex and mesh stages place what they draw where it belongs. +pub fn debug_ps(targets: u32) -> HostShader { + use bitcode::{Attr, Bin, Term}; + use container::SigElement; + let mut s = shader::Shader::new(true); + let b = s.entry; + let undef = s.m.undef(s.t.i32); + let load = |s: &mut shader::Shader, col: u8| { + let args = [s.m.i32(0), s.m.i32(0), s.m.i8(col), undef]; + s.op(b, "loadInput.f32", Attr::ReadNone, s.t.f32, 4, &args) + }; + let z = load(&mut s, 2); + let unary = |s: &mut shader::Shader, op: u32, v| { + s.op(b, "unary.f32", Attr::ReadNone, s.t.f32, op, &[v]) + }; + // DerivCoarseX, DerivCoarseY: depth changes slowly, so scale it up. + let (dx, dy) = (unary(&mut s, 83, z), unary(&mut s, 84, z)); + let k = s.m.f32((-4096.0f32).to_bits()); + let nx = s.m.bin(b, Bin::Mul, dx, k); + let ny = s.m.bin(b, Bin::Mul, dy, k); + let one = s.m.f32(1.0f32.to_bits()); + let half = s.m.f32(0.5f32.to_bits()); + let xx = s.m.bin(b, Bin::Mul, nx, nx); + let yy = s.m.bin(b, Bin::Mul, ny, ny); + let sum = s.m.bin(b, Bin::Add, xx, yy); + let sum = s.m.bin(b, Bin::Add, sum, one); + let len = unary(&mut s, 24, sum); // Sqrt + let colour = |s: &mut shader::Shader, v| { + let n = s.m.bin(b, Bin::SDiv, v, len); // fdiv on floats + let n = s.m.bin(b, Bin::Mul, n, half); + s.m.bin(b, Bin::Add, n, half) + }; + let rgb = [colour(&mut s, nx), colour(&mut s, ny), colour(&mut s, one)]; + let targets = targets.clamp(1, 8); + for t in 0..targets { + for (col, v) in rgb.iter().copied().chain([one]).enumerate() { + let args = [s.m.i32(t), s.m.i32(0), s.m.i8(col as u8), v]; + s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); + } + } + s.inputs = vec![SigElement { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 4, + row: Some(0), + col: 0, + cols: 4, + usage: 0b0100, + half: false, + }]; + s.outputs = (0..targets) + .map(|t| SigElement { + name: "SV_Target".into(), + index: t, + kind: 16, + comp: 9, + interp: 0, + row: Some(t), + col: 0, + cols: 4, + usage: 0b1111, + half: false, + }) + .collect(); + s.m.terminate(b, Term::Ret); + HostShader { + stage: HwStage::Ps, + dxil: s.finish(), + user_data: Vec::new(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + } +} + #[cfg(test)] mod tests { + #[cfg(windows)] use super::bitcode::Attr; use super::lower::LOOP_LIMIT; use super::parse_loop_limit; @@ -419,6 +503,7 @@ mod tests { } } use super::container::SigElement; + #[cfg(windows)] use super::shader::Shader; use super::*; use crate::native::{ComputeIo, StageIo}; @@ -550,6 +635,18 @@ mod tests { s.finish() } + #[test] + #[cfg(windows)] + fn debug_pixel_shader_makes_a_pipeline() { + let Ok(host) = super::host::Host::new(false) else { + eprintln!("no SM 6.6 device; skipped"); + return; + }; + let ps = super::debug_ps(3); + let vs = super::host::stub_vs(&ps).unwrap(); + host.pipeline(&vs, &ps).unwrap(); + } + #[test] #[cfg(windows)] fn stub_pipeline_is_created() { @@ -586,6 +683,16 @@ mod tests { v.validate(&mut vs.dxil.clone()).unwrap(); } host.pipeline(&vs, &ps).unwrap(); + // vkd3d-proton (Wine, Proton) does not check the container hash. + // SAFETY: plain lookups in ntdll, always loaded. + let wine = unsafe { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; + let ntdll = GetModuleHandleA(c"ntdll.dll".as_ptr().cast()); + !ntdll.is_null() && GetProcAddress(ntdll, c"wine_get_version".as_ptr().cast()).is_some() + }; + if wine { + return; + } // The runtime checks the container hash: no hash or a wrong one is // refused. (Recent runtimes also take sixteen 0x01 bytes, a bypass // value; ours works with older ones too.) @@ -671,8 +778,7 @@ mod tests { let c = super::Container::parse(&bytes).unwrap(); let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); let st = crate::structure::structure(&p).unwrap(); - let res = - crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); let io = crate::io::raise(&p, &native).unwrap(); let out = super::emit(&c, &native, &p, &st, &io, &res).unwrap(); // dxil.dll, where there is one, checks PSV0 against the module. diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 62ddd5d..c35e5ef 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -247,12 +247,12 @@ pub fn track( for (block, (accesses, mut reads)) in first_lane_at { reads.sort_unstable(); reads.dedup(); - let proof = t - .waterfall(block, &accesses, &reads) - .map_err(|what| ShaderError::Unsupported { - offset: t.inst((block, accesses[0])).machine.offset, - what, - })?; + let proof = + t.waterfall(block, &accesses, &reads) + .map_err(|what| ShaderError::Unsupported { + offset: t.inst((block, accesses[0])).machine.offset, + what, + })?; out.waterfall.compares.extend(proof.compares); out.waterfall.reads.extend(proof.reads); } @@ -1538,7 +1538,8 @@ impl<'a> Tracer<'a> { } else { continue; }; - let Some(matched) = mask(inst.write(Reg::S(code)), inst.write(Reg::S(code + 1))) else { + let Some(matched) = mask(inst.write(Reg::S(code)), inst.write(Reg::S(code + 1))) + else { continue; }; if meet(&[reach, (selected, true), (matched, false)]) { diff --git a/crates/victory-shader/src/structure.rs b/crates/victory-shader/src/structure.rs index ae70179..962909d 100644 --- a/crates/victory-shader/src/structure.rs +++ b/crates/victory-shader/src/structure.rs @@ -632,7 +632,11 @@ impl<'a> Lanes<'a> { .filter(|(lo, hi)| lo != hi) .map(|&(lo, hi)| (hi, lo)) .collect(), - paired_masks: if self.p.wave64 { self.masks } else { Map::default() }, + paired_masks: if self.p.wave64 { + self.masks + } else { + Map::default() + }, active: self.active, bools: self.b, exits, diff --git a/docs/linux-proton.md b/docs/linux-proton.md new file mode 100644 index 0000000..f5e43fc --- /dev/null +++ b/docs/linux-proton.md @@ -0,0 +1,118 @@ +# Linux (Proton) + +VIctory is a Windows program, and it also runs on Linux under Proton's Wine +with vkd3d-proton for Direct3D 12. Under Proton it gets as far as on Windows: +boot, first-boot screens, intro video, start screen, saves, loading, and the +opening of the first mission (credits over the scene; the scene itself is +still dark, as on Windows). + +Tested on one machine (2026-11-24): CachyOS, Linux 7.3, AMD RX 9070 XT +(RADV, Mesa 26.3.1), Proton Experimental `experimental-11.0-20261112`. + +## Requirements + +- Steam's **Proton Experimental** (Steam → Library → Tools). Older Protons + may not work: GE-Proton 11-11's vkd3d-proton turns some translated + shaders into invalid SPIR-V, on which RADV crashes (`vkCreateGraphicsPipelines`, + exit code 3). +- A Vulkan driver with mesh shaders (RADV on RDNA 2 or later has them). +- `rustup` and [`cargo-xwin`](https://github.com/rust-cross/cargo-xwin) + to build the Windows target on Linux. + +## Building + +```sh +rustup target add x86_64-pc-windows-msvc +cargo install --locked cargo-xwin +# cargo-xwin downloads the MSVC CRT and Windows SDK; this accepts their licence. +export XWIN_ACCEPT_LICENSE=1 +cargo xwin build --release -p victory --target x86_64-pc-windows-msvc +``` + +The diagnostics build likewise: +`cargo xwin build --profile diag -p victory --features diagnostics --target x86_64-pc-windows-msvc`. + +## Running + +`scripts/proton-run.sh` runs `victory.exe` with Proton's Wine, in a prefix of +its own (`~/.local/share/victory/proton`, made on first use), with +vkd3d-proton and DXVK. Linux paths work as arguments. + +```sh +scripts/proton-run.sh config +scripts/proton-run.sh run /path/to/game/ --execute +``` + +`PROTON` selects another Proton folder, `PREFIX` another prefix and +`VICTORY_EXE` another exe (the diagnostics build, say). Saves, settings and +`crashes.log` live in the prefix's `%LOCALAPPDATA%\victory\data` unless +`victory.toml` or `VICTORY_DATA_DIR` says otherwise. + +With an Xbox controller connected, the keyboard is not a pad (as on +Windows), so `VICTORY_KEYS` presses do not reach the title either. + +### Without Proton (system Wine) + +A system Wine works too (reported with Wine 11.22 on RDNA2, RDNA3 and +RDNA 3.5). What Proton brings has to be added: + +- **vkd3d-proton 3.2 or newer**: `d3d12.dll` and `d3d12core.dll` (Proton + Experimental's `files/lib/wine/vkd3d-proton/x86_64-windows`). 3.1 turns + some translated shaders into SPIR-V RADV cannot take. +- **DXVK's `dxgi.dll`**, and `WINEDLLOVERRIDES="d3d12,d3d12core,dxgi=n"`. +- No Microsoft `d3dcompiler_47`: Wine's built-in one compiles the argument + clamp since it no longer needs `RWByteAddressBuffer` methods. + +### Diagnostics switches + +In the diagnostics build: + +- `VICTORY_NO_WATCHDOG=1` (from #454, if merged) keeps the title's stall + watchdog from ending slow runs. +- `VICTORY_SHOW_TARGET=x-f[-]` presents an intermediate + render target instead of the final frame, the `n`th of that size and + format the frame writes (names as in `VICTORY_DUMP_TARGETS` files). The + world's G-buffer shows its geometry while the final image is dark: + `VICTORY_SHOW_TARGET=2560x1440-f28-3` on a Series X profile. +- `VICTORY_DEBUG_PS=1` draws depth-tested geometry with a debug pixel + shader (surfaces coloured by their slope, from depth derivatives) instead + of the title's: the geometry of every draw whose vertex or mesh stage + translates, whether its pixel shader does or not. With the two switches + together you can walk the world in a flat-colour view. + +In every build, a draw of depth-tested geometry whose pixel shader does +not translate (or that the host refuses) is drawn with that debug shader +instead of dropped; `VICTORY_PS_FALLBACK=0` turns that off. +`VICTORY_PIPELINE_WAIT_MS` sets how long a frame may wait for pipelines +being made (500 by default; 0 never waits, pipelines then appear a few +frames later). + +## Tests + +```sh +CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUNNER=$PWD/scripts/proton-run.sh \ + cargo xwin test --workspace --target x86_64-pc-windows-msvc +``` + +Two tests start Linux programs from inside Wine and fail there for that +reason only: `loads_binds_and_calls_probe` (builds its fixture with `cargo`) +and `policy::tests::repository_passes_policy` (runs `git`). Run +`cargo xtask policy` natively instead. + +## Known differences + +- **Speed.** Wine emulates write watching page by page, so the copies of + title memory take longer than on Windows. Under Wine the kernel is asked + about each title allocation once per submission (`watch::new_submission`), + views of physical pages go straight to their guards, and allocations are + looked up from a cache rather than with `VirtualQuery`, which takes the + same lock as the title's write faults. +- **Software rendering does not work.** On lavapipe, Wine cannot handle the + write faults of VIctory's guarded title memory when lavapipe's own + threads take them. +- **vkd3d-proton differs from Windows drivers in a few places VIctory now + handles:** its HLSL compiler (Wine's `D3DCompile`) lacks + `RWByteAddressBuffer` methods and does not embed root signatures; it + refuses an empty pipeline library given a non-null blob pointer; it does + not check DXIL container hashes; and its descriptor layout makes a texture + descriptor read as a constant buffer (a stale slot) a read at address 0. diff --git a/docs/linux-wine.md b/docs/linux-wine.md new file mode 100644 index 0000000..4f7cc31 --- /dev/null +++ b/docs/linux-wine.md @@ -0,0 +1,115 @@ +# Linux with Wine/Proton (experimental) + +VIctory is a Windows application: the title loader uses Windows APIs and the +GPU backend uses D3D12. Linux reports have successfully run it through Wine +with vkd3d-proton translating D3D12 to Vulkan. Cross-build the Windows +executable; native Linux builds are not currently supported. + +## Reported working setup + +A community report (#879) used Arch/CachyOS, an AMD RADV GPU, Wine 11.22, and +vkd3d-proton 3.2.0 from Proton Experimental. DXVK supplied `dxgi.dll` (and +`d3d11.dll`/`d3d10core.dll`); the report used: + +```sh +WINEDLLOVERRIDES="d3d12=n,b;d3d12core=n,b;dxgi=n,b" +``` + +The `n,b` overrides are important: they select the native Proton DLLs before +Wine's built-ins. Use a vkd3d-proton version compatible with your GPU and +driver. The report found 3.1 crashed during world loading, while 3.2.0 reached +menus and loading. This is community-reported, not a tested or supported +configuration; other reports describe crashes and severe performance issues. + +## Build and launch + +Enter the project shell (Nix with `` available), then cross-compile +the Windows MSVC target. The shell provides Rustup, `cargo-xwin`, Vulkan +tools, Clang, LLVM, and LLD: + +```sh +nix-shell +cargo xwin build --release -p victory --target x86_64-pc-windows-msvc +``` + +Rustup reads `rust-toolchain.toml` and installs the pinned toolchain/target on +first use. Outside Nix, install Rustup and `cargo-xwin` yourself. + +The project shell prefers an installed GE-Proton compatibility tool (on this +machine it selects `GE-Proton-nix`). The helper builds if needed, creates a +dedicated prefix outside the repository, and launches through GE-Proton's own +runner. This is the path verified with the supplied game installation: + +```sh +nix-shell +./scripts/run-ge-proton.sh +``` + +The helper defaults to the game executable path supplied for this machine. +For another installation, pass the executable or set `VICTORY_TITLE_EXE`. +Override `GE_PROTON` to select another installed GE-Proton release. A GE-Proton +installation can be discovered under Steam's `compatibilitytools.d`. The helper +uses GE-Proton directly because that path was verified with the supplied game +files; UMU is another option but requires explicit pressure-vessel access for +game files outside the home directory. + +## Controller + +VIctory reads up to four XInput gamepads. Proton should expose an Xbox or +Xbox-compatible controller as XInput; connect it before starting the title. +The gamepad path includes buttons, D-pad, sticks, and analog triggers. Basic +motor rumble is sent through XInput, but the title's trigger/adaptive rumble +is not implemented. + +The launch helper runs GE-Proton outside the Steam client, so Steam Input's +virtual controller mapping is not automatically applied. If your controller +is not seen, or it is not XInput-compatible, add the built `victory.exe` to +Steam as a non-Steam game, force the installed GE-Proton compatibility tool, +enable Steam Input, and use these launch options (adjust the game path if +needed): + +```text +WINEDLLOVERRIDES="d3d12=n,b;d3d12core=n,b;dxgi=n,b" %command% run "Z:\mnt\data\Games\GTA6\GTA6.Xbox.v1.0.2.1\GTA6.Xbox.v1.0.2.1\game_scarlett_master.exe" --execute +``` + +As a fallback, when no gamepad is connected, the keyboard acts as a pad while +the title window is focused: WASD/IJKL are the sticks, arrows the D-pad, +Enter/Backspace/X/Y the face buttons, Q/E the shoulders, Z/C the triggers, +F/H the stick clicks, and Esc/Tab Menu/View. + +For manual Wine/Proton launches, use a win64 prefix with the Proton versions of +`d3d12.dll`, `d3d12core.dll`, and DXVK's `dxgi.dll` available to that prefix. +The exact installation method depends on whether you use system Wine or +Proton; do not mix arbitrary Wine built-ins with the Proton D3D12 stack. +The shell sets the reported DLL overrides by default; Wine falls back to its +built-ins if native DLLs are not installed, which is not a working D3D12 setup. + +Run from an active graphical session. For a KDE Wayland session launched +remotely, one report needed the session's `XDG_RUNTIME_DIR`, `DISPLAY` (for +XWayland), and `XAUTHORITY`; obtain these from that session rather than +hard-coding another user's runtime directory. + +For example, with a prefix already configured and the game directory visible +to Wine as `Z:\path\to\game`: + +```sh +export WINEPREFIX="$HOME/.wine-victory" +export WINEDLLOVERRIDES="d3d12=n,b;d3d12core=n,b;dxgi=n,b" +wine target/x86_64-pc-windows-msvc/release/victory.exe config +wine target/x86_64-pc-windows-msvc/release/victory.exe run \ + 'Z:\path\to\game\game.exe' --execute +``` + +Configure paths in `victory.toml` (or `VICTORY_*_DIR` variables) so they are +valid inside the Wine process. Keep the repository, game data, and derived +cache/data directories separate as required by the asset policy. + +## Current limitations + +Linux/Wine reports have reached responsive menus, but performance can be +extremely low and the world is not reliably playable. Missing shaders and +indirect draws are still dropped; the title/runtime also has reported GPU +crashes and hangs. Enabling indirect execution may require Microsoft's +`d3dcompiler_47.dll`, since some Wine versions cannot compile the required +`cs_5_1` shader. No Linux setup is currently part of the project's tested +platform matrix. diff --git a/scripts/proton-run.sh b/scripts/proton-run.sh new file mode 100755 index 0000000..d06de5a --- /dev/null +++ b/scripts/proton-run.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# Runs victory.exe (or another Windows exe) under Proton's Wine on Linux, +# with vkd3d-proton (D3D12) and DXVK (DXGI) from the Proton build. +# See docs/linux-proton.md. +# +# scripts/proton-run.sh config +# scripts/proton-run.sh run /path/to/game/ --execute +# +# As cargo's runner (its first argument is the test exe): +# CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUNNER=$PWD/scripts/proton-run.sh \ +# cargo xwin test --workspace --target x86_64-pc-windows-msvc +# +# Environment: +# PROTON a Proton folder (default: Proton - Experimental from Steam) +# PREFIX the Proton prefix to use (default: ~/.local/share/victory/proton) +# VICTORY_EXE the exe to run (default: this checkout's release build) +set -euo pipefail +ROOT="$(cd "$(dirname "${0}")/.." && pwd)" + +if [[ -z "${PROTON:-}" ]]; then + for d in "${HOME}/.steam/steam/steamapps/common/Proton - Experimental" \ + "${HOME}/.local/share/Steam/steamapps/common/Proton - Experimental" \ + "${HOME}/.var/app/com.valvesoftware.Steam/data/Steam/steamapps/common/Proton - Experimental"; do + if [[ -x "${d}/files/bin/wine" ]]; then PROTON="${d}"; break; fi + done +fi +if [[ -z "${PROTON:-}" || ! -x "${PROTON}/files/bin/wine" ]]; then + echo "Proton not found: install Proton Experimental in Steam or set PROTON" >&2 + exit 1 +fi +PREFIX="${PREFIX:-${XDG_DATA_HOME:-${HOME}/.local/share}/victory/proton}" + +# First run: let Proton build the prefix (it installs vkd3d-proton and DXVK). +if [[ ! -f "${PREFIX}/pfx/system.reg" ]]; then + mkdir -p "${PREFIX}" + STEAM_COMPAT_DATA_PATH="${PREFIX}" \ + STEAM_COMPAT_CLIENT_INSTALL_PATH="${STEAM_COMPAT_CLIENT_INSTALL_PATH:-${HOME}/.steam/steam}" \ + SteamAppId=0 SteamGameId=0 \ + python3 "${PROTON}/proton" run cmd /c exit >/dev/null 2>&1 || true +fi + +export WINEPREFIX="${PREFIX}/pfx" +export WINEDLLOVERRIDES="d3d12,d3d12core,dxgi,d3d11,d3d10core=n,b;${WINEDLLOVERRIDES:-}" +export WINEDEBUG="${WINEDEBUG:--all}" +export WINEFSYNC=1 +# vkd3d-proton's pipeline cache, out of the working directory. +export VKD3D_SHADER_CACHE_PATH="${VKD3D_SHADER_CACHE_PATH:-${PREFIX}/vkd3d-cache}" +mkdir -p "${VKD3D_SHADER_CACHE_PATH}" + +WINE="${PROTON}/files/bin/wine" +if [[ -n "${VICTORY_EXE:-}" ]]; then + exec "${WINE}" "${VICTORY_EXE}" "$@" +elif [[ "${1:-}" == *.exe && -f "${1:-}" ]]; then + exec "${WINE}" "$@" +else + exec "${WINE}" "${ROOT}/target/x86_64-pc-windows-msvc/release/victory.exe" "$@" +fi diff --git a/scripts/run-ge-proton.sh b/scripts/run-ge-proton.sh new file mode 100755 index 0000000..11f5e47 --- /dev/null +++ b/scripts/run-ge-proton.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +set -euo pipefail + +repo="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +app="${repo}/target/x86_64-pc-windows-msvc/release/victory.exe" +title_exe="${1:-${VICTORY_TITLE_EXE:-/mnt/data/Games/GTA6/GTA6.Xbox.v1.0.2.1/GTA6.Xbox.v1.0.2.1/game_scarlett_master.exe}}" + +if [[ -z "${GE_PROTON:-}" || ! -x "${GE_PROTON}/proton" ]]; then + echo "GE-Proton not found. Enter nix-shell or set GE_PROTON=/path/to/GE-Proton." >&2 + exit 1 +fi +if [[ ! -f "${app}" ]]; then + echo "Windows build missing; building it now..." >&2 + (cd "${repo}" && cargo xwin build --release -p victory --target x86_64-pc-windows-msvc) +fi +if [[ ! -f "${title_exe}" ]]; then + echo "Title executable not found: ${title_exe}" >&2 + echo "Pass its path as the first argument or set VICTORY_TITLE_EXE." >&2 + exit 1 +fi + +# The title path is an argument to a Windows process, so express it through +# Wine's Z: mapping rather than relying on Unix-path argument conversion. +case "${title_exe}" in + [A-Za-z]:\\*) title_exe_win="${title_exe}" ;; + *) title_exe_win="Z:$(printf '%s' "${title_exe}" | sed 's,/,\\,g')" ;; +esac + +export STEAM_COMPAT_CLIENT_INSTALL_PATH="${STEAM_COMPAT_CLIENT_INSTALL_PATH:-${HOME}/.local/share/Steam}" +export STEAM_COMPAT_DATA_PATH="${STEAM_COMPAT_DATA_PATH:-${HOME}/.local/share/victory/ge-proton-compatdata}" +export WINEDLLOVERRIDES="${WINEDLLOVERRIDES:-d3d12=n,b;d3d12core=n,b;dxgi=n,b}" + +mkdir -p "${STEAM_COMPAT_DATA_PATH}" +if [[ -f "${repo}/victory.toml" ]]; then + repo_win="Z:$(printf '%s' "${repo}" | sed 's,/,\\,g')" + export VICTORY_CONFIG="${repo_win}\\victory.toml" +fi +# vkd3d-proton writes its pipeline cache relative to the process working +# directory. Keep it (and VIctory's default config lookup) outside the repo. +cd "${STEAM_COMPAT_DATA_PATH}" +exec "${GE_PROTON}/proton" run "${app}" run "${title_exe_win}" --execute diff --git a/shell.nix b/shell.nix new file mode 100644 index 0000000..263c979 --- /dev/null +++ b/shell.nix @@ -0,0 +1,42 @@ +{ pkgs ? import { } }: + +pkgs.mkShell { + name = "victory-linux"; + + packages = with pkgs; [ + rustup + cargo-xwin + vulkan-loader + vulkan-tools + pkg-config + clang + llvm + lld + python3 + ]; + + shellHook = '' + export LD_LIBRARY_PATH="${pkgs.vulkan-loader}/lib''${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" + # Prefer a GE-Proton compatibility tool already installed by Steam. + if [ -z "''${GE_PROTON:-}" ]; then + for candidate in \ + "$HOME/.local/share/Steam/compatibilitytools.d/GE-Proton-nix" \ + "$HOME/.local/share/Steam/compatibilitytools.d"/GE-Proton* \ + "$HOME/.steam/root/compatibilitytools.d"/GE-Proton*; do + if [ -x "$candidate/proton" ]; then + export GE_PROTON="$candidate" + break + fi + done + fi + # Prefer an installed GE-Proton compatibility tool. + export WINEDLLOVERRIDES="''${WINEDLLOVERRIDES:-d3d12=n,b;d3d12core=n,b;dxgi=n,b}" + echo "VIctory Linux shell: cargo xwin build --release -p victory --target x86_64-pc-windows-msvc" + if [ -n "''${GE_PROTON:-}" ]; then + echo "GE-Proton: $GE_PROTON (launch with ./scripts/run-ge-proton.sh)" + else + echo "GE-Proton not found; set GE_PROTON to its installation directory." + fi + echo "Rust uses rust-toolchain.toml (rustup may download it on first use)." + ''; +} diff --git a/tests/fixtures/hle-probe/Cargo.toml b/tests/fixtures/hle-probe/Cargo.toml index 6c7f87b..d16aad5 100644 --- a/tests/fixtures/hle-probe/Cargo.toml +++ b/tests/fixtures/hle-probe/Cargo.toml @@ -16,3 +16,13 @@ crate-type = ["cdylib"] panic = "abort" [workspace] + +# The workspace's lints (root Cargo.toml), repeated here because the fixture +# is outside the workspace and cannot inherit them. Keep the two in step. +[lints.rust] +unsafe_op_in_unsafe_fn = "deny" +unused_must_use = "deny" + +[lints.clippy] +all = { level = "warn", priority = -1 } +undocumented_unsafe_blocks = "warn" diff --git a/tests/fixtures/hle-probe/src/lib.rs b/tests/fixtures/hle-probe/src/lib.rs index 1eca794..c85a46d 100644 --- a/tests/fixtures/hle-probe/src/lib.rs +++ b/tests/fixtures/hle-probe/src/lib.rs @@ -38,18 +38,21 @@ unsafe extern "system" { /// Console-only API, answered by the resolver's HLE implementation. #[unsafe(no_mangle)] pub extern "system" fn probe_xgameruntime_init() -> i32 { + // SAFETY: takes no arguments; victory-loader binds it to its HLE version. unsafe { XGameRuntimeInitialize() } } /// Exists on the host too, but the resolver overrides it. #[unsafe(no_mangle)] pub extern "system" fn probe_tick() -> u32 { + // SAFETY: takes no arguments and has no preconditions. unsafe { GetTickCount() } } /// Exists on the host and is passed through to it. #[unsafe(no_mangle)] pub extern "system" fn probe_pid() -> u32 { + // SAFETY: takes no arguments and has no preconditions. unsafe { GetCurrentProcessId() } } @@ -61,18 +64,23 @@ pub extern "system" fn probe_title() -> u32 { .chain(Some(0)) .collect(); let mut handle = 0; + // SAFETY: `path` is a NUL-terminated UTF-16 string and `handle` a + // writable u32, both live for the call. unsafe { GetFileVersionInfoSizeW(path.as_ptr(), &mut handle) } } /// A delay-loaded console API. #[unsafe(no_mangle)] pub extern "system" fn probe_delayed() -> u32 { + // SAFETY: takes no arguments; the delay-load helper binds it on first call. unsafe { VIctoryProbeDelayed() } } /// Nobody implements this one: it must land in an unimplemented-import stub. #[unsafe(no_mangle)] pub extern "system" fn probe_missing() -> u64 { + // SAFETY: takes a plain integer; the loader binds it to a stub that + // reports the call, which is what the test checks. unsafe { VIctoryProbeNotImplemented(42) } } @@ -96,6 +104,7 @@ static ON_THREAD: unsafe extern "system" fn(*mut c_void, u32, *mut c_void) = on_ pub extern "system" fn DllMain(_: *mut c_void, reason: u32, _: *mut c_void) -> i32 { if reason == DLL_THREAD_ATTACH { MAIN_THREAD_STARTS.fetch_add(1, Ordering::Relaxed); + // SAFETY: takes no arguments and has no preconditions. unsafe { GetTickCount() }; } if reason == DLL_PROCESS_DETACH { diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 911ed80..96ba7fd 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -1,6 +1,7 @@ //! Repository maintenance. Run with `cargo xtask `. mod policy; +mod wine; use std::path::{Path, PathBuf}; use std::process::Command; @@ -26,6 +27,20 @@ enum Cmd { }, /// Point git at .githooks/ so every commit runs the policy check. InstallHooks, + /// Linux host: cross-build for Windows and run the tests under Wine + /// (clang-cl, lld-link and llvm-lib on PATH, an `xwin` splat). + WineTest { + /// The `xwin splat` output folder (default: ~/.xwin). + #[arg(long)] + xwin: Option, + /// Folder with vkd3d-proton's x64 d3d12.dll and d3d12core.dll, used + /// instead of Wine's own D3D12 (which lacks shader model 6.6). + #[arg(long)] + vkd3d_proton: Option, + /// Arguments for `cargo test` (default: the workspace but xtask). + #[arg(last = true)] + args: Vec, + }, } fn main() -> Result<()> { @@ -45,6 +60,18 @@ fn main() -> Result<()> { println!("hooks installed: commits now run `cargo xtask policy --staged`"); Ok(()) } + Cmd::WineTest { + xwin, + vkd3d_proton, + args, + } => wine::run( + &root, + wine::Options { + xwin, + vkd3d_proton, + args, + }, + ), } } diff --git a/xtask/src/policy.rs b/xtask/src/policy.rs index 9bcf24c..7e5875e 100644 --- a/xtask/src/policy.rs +++ b/xtask/src/policy.rs @@ -15,6 +15,7 @@ const MAX_ENCODED_RUN: usize = 512; const ALLOWED_EXTENSIONS: &[&str] = &[ "rs", "toml", "md", "txt", "lock", "yml", "yaml", "json", "hlsl", "hlsli", "ps1", "cmd", "sh", + "nix", ]; const ALLOWED_NAMES: &[&str] = &[ ".gitignore", diff --git a/xtask/src/wine.rs b/xtask/src/wine.rs new file mode 100644 index 0000000..be19c52 --- /dev/null +++ b/xtask/src/wine.rs @@ -0,0 +1,150 @@ +//! `cargo xtask wine-test`: the Windows build's tests on a Linux host, +//! cross-compiled with clang-cl/lld-link against an `xwin` splat and run +//! under Wine in a prefix of our own (`target/wine-prefix`). + +use std::ffi::OsString; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use anyhow::{Context, Result, ensure}; + +const TARGET: &str = "x86_64-pc-windows-msvc"; + +pub struct Options { + /// The MSVC CRT and Windows SDK, as `xwin splat` lays them out. + pub xwin: Option, + /// A folder holding vkd3d-proton's x64 `d3d12.dll` and `d3d12core.dll`, + /// put in the prefix in place of Wine's own D3D12. + pub vkd3d_proton: Option, + /// Arguments for `cargo test`; the whole workspace but xtask without. + pub args: Vec, +} + +pub fn run(root: &Path, o: Options) -> Result<()> { + let xwin = match o.xwin { + Some(dir) => dir, + None => PathBuf::from(std::env::var_os("HOME").context("HOME is not set")?).join(".xwin"), + }; + ensure!( + xwin.join("crt").is_dir() && xwin.join("sdk").is_dir(), + "no xwin splat at {} (make one with `xwin --accept-license splat --output {0}`, \ + which accepts Microsoft's licence for the CRT and SDK)", + xwin.display() + ); + let target_dir = root.join("target"); + let prefix = target_dir.join("wine-prefix"); + let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into()); + + // cc splits *FLAGS like a shell when CC_SHELL_ESCAPED_FLAGS is set; + // quote each include so a path with spaces stays one argument. + let includes = [ + xwin.join("crt/include"), + xwin.join("sdk/include/ucrt"), + xwin.join("sdk/include/um"), + xwin.join("sdk/include/shared"), + ] + .map(|dir| shell_quote(&format!("/imsvc{}", dir.display()))) + .join(" "); + let cflags = format!("--target={TARGET} -Wno-unused-command-line-argument {includes}"); + // Cargo splits RUSTFLAGS on spaces inside paths, so encode the + // separators. Every cargo call below passes --target, so these flags + // never reach host build scripts or proc macros. + let rustflags = [ + xwin.join("crt/lib/x86_64"), + xwin.join("sdk/lib/um/x86_64"), + xwin.join("sdk/lib/ucrt/x86_64"), + ] + .map(|dir| format!("-Lnative={}", dir.display())) + .join("\x1f"); + let env: Vec<(&str, OsString)> = vec![ + ("CC_x86_64_pc_windows_msvc", "clang-cl".into()), + ("CXX_x86_64_pc_windows_msvc", "clang-cl".into()), + ("AR_x86_64_pc_windows_msvc", "llvm-lib".into()), + ("CFLAGS_x86_64_pc_windows_msvc", cflags.clone().into()), + ("CXXFLAGS_x86_64_pc_windows_msvc", cflags.into()), + ("CC_SHELL_ESCAPED_FLAGS", "1".into()), + ( + "CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_LINKER", + "lld-link".into(), + ), + ("CARGO_ENCODED_RUSTFLAGS", rustflags.into()), + ("CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUNNER", "wine".into()), + ("WINEPREFIX", prefix.clone().into()), + ]; + let command = |program: &OsString| { + let mut c = Command::new(program); + c.current_dir(root).envs(env.iter().map(|(k, v)| (k, v))); + c + }; + + // Wine makes the prefix on first use; D3D12 goes into it after that. + let system32 = prefix.join("drive_c/windows/system32"); + if !system32.is_dir() { + let status = command(&"wineboot".into()) + .arg("-i") + .status() + .context("running wineboot (is Wine installed?)")?; + ensure!(status.success(), "wineboot failed"); + } + let mut overrides = None; + if let Some(dir) = o.vkd3d_proton { + for dll in ["d3d12.dll", "d3d12core.dll"] { + // A copy keeps the source's permissions (read-only in Proton), + // so the one from an earlier run is removed, not overwritten. + let (from, to) = (dir.join(dll), system32.join(dll)); + let _ = std::fs::remove_file(&to); + std::fs::copy(&from, &to) + .with_context(|| format!("copying {} into the prefix", from.display()))?; + } + overrides = Some("d3d12,d3d12core=n"); + } + + // The loader's end-to-end test cannot start cargo from inside Wine: + // its fixture is built here and named to it. + let probe_dir = target_dir.join("hle-probe"); + let status = command(&cargo) + .args(["build", "--quiet", "--target", TARGET, "--manifest-path"]) + .arg(root.join("tests/fixtures/hle-probe/Cargo.toml")) + .arg("--target-dir") + .arg(&probe_dir) + .status() + .context("running cargo")?; + ensure!(status.success(), "building hle-probe failed"); + let probe = probe_dir.join(TARGET).join("debug").join("hle_probe.dll"); + + let mut test = command(&cargo); + test.args(["test", "--target", TARGET]) + .env("VICTORY_HLE_PROBE_DLL", wine_path(&probe)) + .env( + "WINEDEBUG", + std::env::var_os("WINEDEBUG").unwrap_or_else(|| "-all".into()), + ); + if let Some(overrides) = overrides { + // vkd3d-proton writes its pipeline cache to the working directory + // (the crate's, in tests), which the asset policy refuses. + test.env("WINEDLLOVERRIDES", overrides).env( + "VKD3D_SHADER_CACHE_PATH", + wine_path(&target_dir.join("vkd3d-proton-cache")), + ); + std::fs::create_dir_all(target_dir.join("vkd3d-proton-cache"))?; + } + if o.args.is_empty() { + // xtask is a host tool (it runs git); it is not tested under Wine. + test.args(["--workspace", "--exclude", "xtask", "--no-fail-fast"]); + } else { + test.args(&o.args); + } + let status = test.status().context("running cargo")?; + ensure!(status.success(), "tests failed under Wine"); + Ok(()) +} + +/// `path` as Wine's Z: drive (the host's root) names it. +fn wine_path(path: &Path) -> String { + format!("Z:{}", path.display()).replace('/', "\\") +} + +/// `arg` as one shell word for cc's `CC_SHELL_ESCAPED_FLAGS` parsing. +fn shell_quote(arg: &str) -> String { + format!("'{}'", arg.replace('\'', "'\\''")) +}