mirror of
https://github.com/seedds/nxnative.git
synced 2026-11-23 11:39:42 -10:00
Port PRAGMATA (0400C76024710000, Switch 2, RE Engine): it plays on the Mac from the title into the station's first rooms, and 36,778 of its 36,779 shaders build
The picture. NVN2's graphics stages read the buffer entries the game pushes from a bank of their own, c[25 + stage index], which is push block 1 + stage index, not a uniform slot: the title, the ship and the base were black until the translator mapped the bank onto the block in c[24] (DMSH_NVN2_STAGE_BANK, DMSH_PUSH_BLOCKS 6). With it: NVN2 compute's second push block, bindless constant buffer handles in the hardware's layout, uniform words read through a buffer address (cx), global memory at a storage buffer's address on some paths only, handles a shader computes (they index the pools), a handle loaded from memory on one path only (compute 02e1292114121308 did not load), mesh shaders' per-primitive system values and their own outputs read back, 64-bit image max and min, MEMBAR as a fence, threadgroup stores in warp-synchronous code (PR #1775), FSETP / ISETP pairs and IMAD's B (PR #1800), the shared compare-and-swap loop (PR #1796), and integer outputs held in a float local. The host. A sparse pool's run list grows past 1,024; no page changes under a buffer the GPU still uses; the runs a mapping or unmap replaces change in one step (mtl_pool_replace: a buffer address the game pushed was in no pool for a frame); a sync never fenced since its Initialize is signalled; H.264 parameter sets past the eighth argument; touch gestures; the queue builder's size getters, SetRayTracingMemorySize and SetProvokingVertexMode; DM_CRASH_PEEK, DM_NVN_PRESENT_FINISH and DM_NVN_DLSS_BILINEAR (diagnostics). The shader build. Of 91 shaders that did not build: FRND of a half (65); one handle read as a 2D texture and as a 2D array is an array for both reads, the 2D read at layer 0 (24 pixel shaders whose Metal source did not compile: ResourceManager.UnifyArrayTypes); the one-lane subgroup rewrite takes domain shaders and declares the types a module lacks (2); TLD through a uniform register (0xf66, by the family's pattern, 17), I2F of an immediate (3) and SUATOM.CAS (0x595, operands as Mesa NAK's 0x396, 1). Open: IPA at an offset (pixel 4a9d4507eea6c837); pixel c4ac3ca598cea32e ends Apple's compiler service in any pipeline (the prebuild records the pair and goes on); nvnCommandBufferSetFloatBlendClamp (method 0x10b0, a reserved software method in NVIDIA's header); the unbound uniform slot line of 9d5de89b049f5915. Also: the profile (the NSP script's guess, unchanged: no patch, no cut), its note, its row in the games table and its line in README; the reference entries and the symptom index; four rows of docs/env_switches.tsv (DM_NVN_VCONV_KEEP's was missing on main); and the testsf75ac06ebroke (test_dmsh_gather_offsets, test_dmsh_raw_last and test_dmsh_wrapv read MAC_METAL without dmsh_chain, test_pr_areas copied no min_os.mk). DMSH_CHAIN changes (the translator, dmsh_build.py, dmsh_entry.py and others), so every game's shaders are built again once. Checked on an M4 Pro (48 GB), macOS 27.2: the tool tests (1,452) and the translator tests with DMSH_TEST_XLATE set (537) pass; make run in dm/gfx/tests and lint_c.py tidy (no finding on a line this adds) passed before the last translator and build-tool changes, which touch no C. PRAGMATA, five windowed runs of 4 to 7 minutes with DM_PSO_PREPARE=0: 60 fps at the title, 44 to 52 fps walking in the station, its red lines the three open ones above. regress.py check on OCTOPATH TRAVELER II (full route, baseline8b55ebb3): 13,980 of 13,980 shaders on both chains, 59.8 -> 59.8 fps, p99 18.34 -> 18.29 ms, no new red line, screenshots within noise; it showed 11 pixel shaders whose integer output had moved to a float one, because the rule for a float local did not follow an element of a local array, which is fixed here with a test. On the final chain (regress.py chain) 177 of its shaders differ: 175 gain simdgroup memory fences or take a fence for a barrier (MEMBAR), and 2 (3304c88fa2dbef97, c2e9d77afb5f4d67) name colour 2 as their integer output, into which they write a computed integer. Not run: Mario Kart World or any other Switch 2 game under regress.py (skipped at the user's request), OCTOPATH TRAVELER II's route on the final chain, a new game's intro on the final chain (last seen on chain 79939b004bb5), combat and later areas, a first start with the prepare step (48,957 pipelines), iOS, lint_python.py, and Bayonetta 3's two domain shaders with the rewrite.
This commit is contained in:
1 parent
0b1244866a
commit
ccd834e06a
75 files changed
+95262
-270
No files matched your search
@@ -19,6 +19,7 @@ These Switch 2 games have passed Mac gameplay testing. Build them from a [`.nup`
|
||||
- [Mario Kart World](dm/games/0400C3F00006E000/README.md)
|
||||
- [Mario Tennis Fever](dm/games/0400D4201C6EA000/README.md)
|
||||
- [Pokémon Pokopia](dm/games/0400A3A01EE4C000/README.md)
|
||||
- [PRAGMATA](dm/games/0400C76024710000/README.md)
|
||||
- [Splatoon Raiders](dm/games/0400380020056000/README.md)
|
||||
- [Star Fox](dm/games/0400E88025B1A000/README.md)
|
||||
- [The Legend of Zelda: Ocarina of Time](dm/games/0400486024DEC000/README.md)
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
# PRAGMATA (`0400C76024710000`)
|
||||
|
||||
A Switch 2 game: update v196608, SDK 20.5.15 built for the Switch 2 (`Ounce`), NVN2. Capcom's RE Engine, with Havok and Wwise. Modules `main` and `sdk`; `subsdk0` and `subsdk1` (C / libc) are not loaded. It plays on the Mac: the title, a new game's intro (the ship, the tower and the lunar base; last run on chain `79939b004bb5`) and, with the save those runs left, walking through the station's first rooms (chain `d24f05cf9d78`). Tested on an M4 Pro (48 GB) only.
|
||||
|
||||
## What it needs
|
||||
|
||||
| Setting | Where | Why |
|
||||
|---|---|---|
|
||||
| `mem_reserve 0x140000000`, `mem_alias 0x118000000`, `mem_stack 0x10000000`, `app_pool 0x240000000` | [`game.tsv`](game.tsv) | the Switch 2's 9 GB pool; `main` sets a heap. On the Mac the host's own alias default applies: in its first 15 s the game's regions reach alias +38.41 GB, one request of 32 GB among them, so the profile's 4.38 GB alias region (the iPhone layout) is not enough as it is |
|
||||
| `sys_resource 0x1400000` | `game.tsv` | the NPDM declares 20 MB, so virtual address memory is on |
|
||||
| `modules main sdk` | `game.tsv` | `main` takes nothing from the two subsdks that the host does not supply |
|
||||
| `romfs_marker re_chunk_000.pak`, `zip_store .pak:.metallib` | `game.tsv` | the RomFS is three RE Engine PAKs (12.86 GB) |
|
||||
| `shader_groups re_chunk=sdf` | `game.tsv` | the shaders are [SDF definitions inside the PAKs](../../../docs/reference/shaders.md#sdf-definitions-in-re-engine-paks) |
|
||||
| `depth_mode zero` | `game.tsv` | the game calls `nvnDeviceSetDepthMode` with near = 0 |
|
||||
|
||||
There is no game-specific patch and no rewriter cut. The profile is the NSP script's guess from the survey, unchanged; only v196608's build row exists, and the base game has not been run.
|
||||
|
||||
## Shaders
|
||||
|
||||
36,779 in [`shader_map.tsv`](shader_map.tsv): 18,406 pixel, 10,829 vertex, 6,880 compute, 539 mesh, 62 domain, 33 hull, 30 geometry. On chain `d24f05cf9d78` 36,778 build and none is lost; a full Mac build with nothing cached took 82 minutes with 10 jobs on the M4 Pro (other work running beside it for part of the time), 39 minutes with the Metal compiles cached.
|
||||
|
||||
- **Open:** pixel shader `4a9d4507eea6c837` does not translate: [`IPA at an offset`](../../../docs/reference/shaders.md#ampere-forms-met-on-pragmata-tld-through-a-uniform-register-i2f-of-an-immediate-suatomcas).
|
||||
- **Open:** pixel shader `c4ac3ca598cea32e` builds, but a render pipeline with it ends Apple's compiler service, with each of its three vertex shaders (`02721ccb12f9f810`, `467d5368b677b114`, `7a8f2da68bafd2d3`): `[RED] pipeline prebuild: the base of … failed: Compilation failed due to an interrupted connection: XPC_ERROR_CONNECTION_INTERRUPTED`, and a `MTLCompilerService` crash report whose stack is a fatal error under `llvm::MCObjectStreamer::emitInstruction`. Other pipelines of those vertex shaders build. The compiles in flight when the service ends fail with it (two to four other pairs in a run with five workers, other ones each run) and are left to the draws too. The prebuild lists the pairs in `prebuild_failed.tsv` and goes on; what in the shader the compiler stops on is not found, and no draw with it has been seen (macOS 27.2, M4 Pro).
|
||||
- Resolved on this chain: 65 shaders with [FRND of a half](../../../docs/reference/shaders.md#frnd-of-a-half-frndf16), 24 pixel shaders reading [one handle as a texture and as an array](../../../docs/reference/shaders.md#one-handle-read-as-a-texture-and-as-an-array) (their alpha test entry points failed with them), 2 domain shaders under [the one-lane subgroup rewrite](../../../docs/reference/shaders.md#subgroup-operations-rewritten-for-a-one-lane-subgroup), and 21 on three [instruction forms](../../../docs/reference/shaders.md#ampere-forms-met-on-pragmata-tld-through-a-uniform-register-i2f-of-an-immediate-suatomcas).
|
||||
|
||||
## Driving it on the Mac
|
||||
|
||||
`python3 scripts/build_ipa_from_nsp.py <folder> --platform mac` builds the Mac shaders and the host and prints the run command. In a window, `DM_PSO_PREPARE=0` skips the prepare step, which otherwise builds 48,957 pipelines before the first frame. The title is up about 90 s after boot; through `DM_CTL`, `A` (title), `A` (New Game), `A` (Standard), then left and `A` (Yes) start a new game, which plays its intro (the ship, the tower, the lunar base). With a save from an earlier run the same presses put the player in the station, where the left stick walks; which menu entries they chose there was not looked at.
|
||||
|
||||
Measured on the M4 Pro, in a 1920x1080 window: 60 fps at the title, 44 to 52 fps walking through the station's first rooms over four runs, with pipelines still compiling in the background. Whether the game's own target there is 60 or 30 is not known.
|
||||
|
||||
## Found on this game
|
||||
|
||||
- [H.264 parameter sets past the eighth argument](../../../docs/reference/movies.md#h264-parameter-sets-past-the-eighth-argument): its opening movies.
|
||||
- [More than 1,024 mapped runs in a sparse pool](../../../docs/reference/nvn-objects.md#more-than-1024-mapped-runs-in-a-sparse-pool): the GPU hang 3 to 4 minutes into the intro.
|
||||
- [Pages changed under a buffer the GPU still uses](../../../docs/reference/nvn-objects.md#pages-changed-under-a-buffer-the-gpu-still-uses): absurd indirect dispatches and a hang while it maps and unmaps sparse pages.
|
||||
- [A sparse pool's runs replaced in two steps](../../../docs/reference/nvn-objects.md#a-sparse-pools-runs-replaced-in-two-steps): mesh shaders `765e6d9d2588ce70` and `5aab38bb5ba67ef7` bound to a dummy buffer for a frame.
|
||||
- [Queue builder size getters](../../../docs/reference/nvn-objects.md#queue-builder-size-getters): read after `SetDefaults` as it makes its queue.
|
||||
- [A sync never fenced since its Initialize is signalled](../../../docs/reference/nvn-objects.md#a-sync-never-fenced-since-its-initialize-is-signalled).
|
||||
- [The provoking vertex is the first](../../../docs/reference/rendering.md#the-provoking-vertex-is-the-first): it sets mode 0.
|
||||
- [Touch gestures recognized from the touch points](../../../docs/reference/services.md#touch-gestures-recognized-from-the-touch-points).
|
||||
- [SDF definitions in RE Engine PAKs](../../../docs/reference/shaders.md#sdf-definitions-in-re-engine-paks).
|
||||
- [Integer outputs told from float bits](../../../docs/reference/shaders.md#integer-outputs-told-from-float-bits).
|
||||
- [Mesh shader per-primitive system values: the primitive count overwritten, the primitive id lost](../../../docs/reference/shaders.md#mesh-shader-per-primitive-system-values-the-primitive-count-overwritten-the-primitive-id-lost).
|
||||
- [Mesh shaders that also address their vertices as records](../../../docs/reference/shaders.md#mesh-shaders-that-also-address-their-vertices-as-records).
|
||||
- [Mesh shaders that read their own outputs back](../../../docs/reference/shaders.md#mesh-shaders-that-read-their-own-outputs-back).
|
||||
- [Threadgroup stores in warp-synchronous code](../../../docs/reference/shaders.md#threadgroup-stores-in-warp-synchronous-code).
|
||||
- [FSETP / ISETP pairs on their own accumulator, and IMAD's B](../../../docs/reference/shaders.md#fsetp--isetp-pairs-on-their-own-accumulator-and-imads-b).
|
||||
- [The shared compare-and-swap loop retries with the value it got](../../../docs/reference/shaders.md#the-shared-compare-and-swap-loop-retries-with-the-value-it-got).
|
||||
- [Ampere forms with a handle in a register, and SURED's other operations](../../../docs/reference/shaders.md#ampere-forms-with-a-handle-in-a-register-and-sureds-other-operations).
|
||||
- [Ampere BMSK and the read of a covered pixel](../../../docs/reference/shaders.md#ampere-bmsk-and-the-read-of-a-covered-pixel).
|
||||
- [A guard band cull in every vertex shader (0x80d)](../../../docs/reference/shaders.md#a-guard-band-cull-in-every-vertex-shader-0x80d).
|
||||
- [MEMBAR is a fence, not a barrier](../../../docs/reference/shaders.md#membar-is-a-fence-not-a-barrier).
|
||||
- [NVN2 compute's second push block holds buffer entries](../../../docs/reference/shaders.md#nvn2-computes-second-push-block-holds-buffer-entries): the hang at frame ~1,300.
|
||||
- [NVN2 graphics stages' buffer banks (c\[25\] to c\[29\]) are push blocks](../../../docs/reference/shaders.md#nvn2-graphics-stages-buffer-banks-c25-to-c29-are-push-blocks): the black title and structures: the root cause.
|
||||
- [Uniform words read through a buffer address (cx)](../../../docs/reference/shaders.md#uniform-words-read-through-a-buffer-address-cx).
|
||||
- [Pixel `c0 + 0x620`: the sample index and GLSLC's sample position table](../../../docs/reference/shaders.md#pixel-c0--0x620-the-sample-index-and-glslcs-sample-position-table).
|
||||
- [Global memory at a storage buffer's address on some paths only](../../../docs/reference/shaders.md#global-memory-at-a-storage-buffers-address-on-some-paths-only).
|
||||
- [Bindless constant buffer handles in the hardware's layout](../../../docs/reference/shaders.md#bindless-constant-buffer-handles-in-the-hardwares-layout).
|
||||
- [Handles a shader computes index the pools](../../../docs/reference/shaders.md#handles-a-shader-computes-index-the-pools): 65,241 deleted texture reads in 8,630 shaders, the intro a saturated cyan.
|
||||
- [A handle loaded from memory on one path only](../../../docs/reference/shaders.md#a-handle-loaded-from-memory-on-one-path-only): compute shader `02e1292114121308` did not load.
|
||||
- [64-bit image max and min (SURED.MAX.U64)](../../../docs/reference/shaders.md#64-bit-image-max-and-min-suredmaxu64).
|
||||
- [One handle read as a texture and as an array](../../../docs/reference/shaders.md#one-handle-read-as-a-texture-and-as-an-array): 24 pixel shaders did not compile.
|
||||
- [FRND of a half (FRND.F16)](../../../docs/reference/shaders.md#frnd-of-a-half-frndf16): 65 shaders did not translate.
|
||||
- [Ampere forms met on PRAGMATA](../../../docs/reference/shaders.md#ampere-forms-met-on-pragmata-tld-through-a-uniform-register-i2f-of-an-immediate-suatomcas): 21 shaders.
|
||||
- [Subgroup operations rewritten for a one-lane subgroup](../../../docs/reference/shaders.md#subgroup-operations-rewritten-for-a-one-lane-subgroup): two domain shaders.
|
||||
|
||||
## Open
|
||||
|
||||
- `[RED] NVN unimplemented function called: nvnCommandBufferSetFloatBlendClamp`: the driver writes method 0x10b0, which NVIDIA's published class header (`clb197.h`) lists only as a reserved software method (read through a summary of the file, not verbatim), so what it selects is not known; the game passes 1.
|
||||
- `[RED] stage 5 cb1 has no uniform buffer bound: shader 9d5de89b049f5915_b`: the shader reads slot 1 only for a workgroup count of 2,048 or more, so the unbound slot is not read; the line is still printed.
|
||||
- `[RED] queue 4: an event wait has held it 8.1 s`, once in one run, as the game left the title: the wait sat inside a frame of 11.9 s, 11.6 s of it 29 pipelines compiled at first use (the run skipped the prepare step), so the producer's submission was late, not missing. Not seen in the two runs after it.
|
||||
- The two shaders under [Shaders](#shaders).
|
||||
- How long the prepare step's 48,957 pipelines take on a first start has not been measured. A `pso_manifest.tsv` has not been recorded. Combat, later areas, a long session and iOS are not tested; the alias region above has no iPhone answer.
|
||||
@@ -0,0 +1 @@
|
||||
# generated
|
||||
|
@@ -0,0 +1,47 @@
|
||||
# PRAGMATA (Switch 2, update v196608). Plays on the Mac: see README.md
|
||||
# RE Engine, SDK 20.5.15 built for the Switch 2 (Ounce), NVN2; Havok, Wwise. Modules main, sdk; subsdk0 and subsdk1 (C / libc) are not loaded.
|
||||
# The RomFS is three KPKA PAKs; the shaders are SDF definitions inside them (shader_split.py kpka_jobs / sdf_shaders), as in Monster Hunter Rise.
|
||||
# Made by scripts/build_ipa_from_nsp.py from the survey (dm/games/profile_guess.py); the values below are its guesses, kept as the game runs with them.
|
||||
|
||||
# ---- Identity ----
|
||||
title_id 0400C76024710000
|
||||
program_id 0400C76024710000
|
||||
|
||||
# ---- App ----
|
||||
name PRAGMATA
|
||||
ipa Pragmata.ipa
|
||||
app_category public.app-category.games
|
||||
|
||||
# ---- Versions ----
|
||||
build v196608 v196608 main=b83eeb94da35ff07d0cfa955875e8258 sdk=820cd7d096aac448693f504400cc2375
|
||||
package v196608
|
||||
shader_versions v196608
|
||||
|
||||
# ---- Files ----
|
||||
# not loaded, main takes nothing from them the host does not supply: subsdk0 (C / libc), subsdk1 (C / libc)
|
||||
modules main sdk
|
||||
romfs_marker re_chunk_000.pak
|
||||
zip_store .pak:.metallib
|
||||
|
||||
# ---- Memory ----
|
||||
# the NPDM declares 20 MB of system resource (virtual address memory) and main sets a heap: a 5 GB block with a large alias region; the heap check sizes the heap region from the heap the game asks for
|
||||
mem_reserve 0x140000000
|
||||
mem_alias 0x118000000
|
||||
mem_stack 0x10000000
|
||||
# the sdk is built for the Switch 2 (spec: Ounce): its 9 GB pool
|
||||
app_pool 0x240000000
|
||||
# the NPDM declares 20 MB of system resource
|
||||
sys_resource 0x1400000
|
||||
|
||||
# ---- Shader split ----
|
||||
# RE Engine: the shaders are SDF definitions inside the KPKA PAKs (shader_split.py kpka_jobs / sdf_shaders), as in Monster Hunter Rise's and PRAGMATA's profiles
|
||||
shader_groups re_chunk=sdf
|
||||
shader_note PRAGMATA shaders
|
||||
|
||||
# heap check: 2026-11-09, heap 0.12 GB
|
||||
|
||||
# ---- Address region check ----
|
||||
# the game calls nvnDeviceSetDepthMode with near = 0 in the check boot: the pipeline bases made before it runs are made for that mode
|
||||
depth_mode zero
|
||||
|
||||
# address regions: 2026-11-10, in its first 15 s in nnMain the game's regions reach alias +38.41 GB, past the profile's 4.38 GB alias region, the iPhone layout: the request returning to main+0x12de5a4 takes 32.00 GB: a smaller one works only if its allocator places nothing by fixed offsets; the request returning to main+0x14cda60 takes 6.27 GB: a smaller one works only if its allocator places nothing by fixed offsets (docs/reference/memory.md, Virtual address memory and the alias region) (rewrite 6d87e4dc95ee)
|
||||
|
@@ -0,0 +1,2 @@
|
||||
# Prewarm seed list (shipped in the app, next to shader_map.tsv). Rows: S<TAB>shader key<TAB>stage / R<TAB>render pipeline key (pso_skey hex) / C<TAB>compute shader key / M<TAB>task shader key or -<TAB>native task / mesh pipeline key (pso_skey hex: the mesh shader in the vertex place).
|
||||
# Provisional profile: empty until recorded on the Mac (DM_PSO_MANIFEST=off DM_PSO_RECORD).
|
||||
|
@@ -0,0 +1 @@
|
||||
# kind: evidence supplemental vertex / pixel shader pairs (BAHS program variations and legacy Unity pass-input covers) for vertex output padding and the pipeline prebuild (generated by dm/gfx/tools/shader_split.py, do not edit): vertex key <TAB> pixel key
|
||||
|
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,2 @@
|
||||
# kind: evidence control-section key conflict rulings: empty
|
||||
dm_ctl_sha16 chosen_pc class candidates records
|
||||
|
File diff suppressed because it is too large.
Load diff
@@ -150,6 +150,7 @@ One row per profile; the notes are each profile's `README.md`.
|
||||
| [Pokémon Violet](01008F6008C5E000/README.md) | `01008F6008C5E000` | 1.0.0 | 13.3.5 | Game Freak's Trinity engine | NVN |
|
||||
| [Portal](01007BB017812000/README.md) | `01007BB017812000` | 1.0.3 | 13.3.0 | Valve's Source engine (28 NROs) | NVN |
|
||||
| [Portal 2](0100ABD01785C000/README.md) | `0100ABD01785C000` | 1.0.3 | 13.3.0 | Valve's Source engine (21 NROs) | NVN |
|
||||
| [PRAGMATA](0400C76024710000/README.md) | `0400C76024710000` | v196608 (Switch 2) | 20.5.15 (Ounce) | RE Engine, Havok, Wwise | NVN2 |
|
||||
| [Princess Peach: Showtime!](01007A3009184000/README.md) | `01007A3009184000` | 1.0.0 | 15.3.2 | Unreal Engine 4.27 (Good-Feel), Wwise | NVN |
|
||||
| [Raging Loop](010020400E1C2000/README.md) | `010020400E1C2000` | 1.0.0 (base) | 7.3.2 | Unity 2018.3.10f1 IL2CPP | NVN |
|
||||
| [Red Dead Redemption](01007820196A6000/README.md) | `01007820196A6000` | 1.0.7 | 15.3.2 | Rockstar's RAGE (Double Eleven port) | NVN |
|
||||
|
||||
@@ -18,11 +18,14 @@ from romfs import Path, os, open, is_image, source
|
||||
MAGICS = [(b'UnityFS\0', 'UnityFS'), (b'UnityWeb', 'UnityWeb'), (b'UnityRaw', 'UnityRaw'), (b'BNSH', 'BNSH'), (b'BAHS', 'BAHS'), (b'SARC', 'SARC'), (b'Yaz0', 'Yaz0'),
|
||||
(bytes.fromhex('28b52ffd'), 'zstd'), (b'FRES', 'bfres'), (b'BNTX', 'BNTX'), (b'BWAV', 'BWAV'), (b'FSAR', 'BFSAR'), (b'CPK ', 'CRI CPK'), (b'CRID', 'CRI USM'),
|
||||
(b'@UTF', 'CRI UTF'), (b'AKPK', 'Wwise pck'), (b'BKHD', 'Wwise bnk'), (b'FSB5', 'FMOD'), (b'\x89PNG', 'PNG'), (b'RIFF', 'RIFF'), (b'OggS', 'Ogg'), (b'PK\x03\x04', 'zip'), (b'NSO0', 'NSO'),
|
||||
(bytes.fromhex('03022307'), 'SPIR-V'), (b'ONEPACK\0', 'Trinity pack'), (b'ARC\0', 'MT Framework ARC'), (b'SCNE', 'Bezel Engine archive'), (b'XNB', 'XNB'), (b'pkzl', 'PlatinumGames PKZ')]
|
||||
PACKED = {'UnityFS', 'UnityWeb', 'Yaz0', 'zstd', 'BWAV', 'CRI CPK', 'CRI USM', 'Wwise pck', 'FMOD', 'PNG', 'Ogg', 'zip', 'Trinity pack', 'MT Framework ARC', 'Bezel Engine archive', 'PlatinumGames PKZ'} # file headers of compressed / media formats (zip_store)
|
||||
(bytes.fromhex('03022307'), 'SPIR-V'), (b'ONEPACK\0', 'Trinity pack'), (b'ARC\0', 'MT Framework ARC'), (b'SCNE', 'Bezel Engine archive'), (b'XNB', 'XNB'), (b'pkzl', 'PlatinumGames PKZ'),
|
||||
(b'KPKA', 'RE Engine PAK')]
|
||||
PACKED = {'UnityFS', 'UnityWeb', 'Yaz0', 'zstd', 'BWAV', 'CRI CPK', 'CRI USM', 'Wwise pck', 'FMOD', 'PNG', 'Ogg', 'zip', 'Trinity pack', 'MT Framework ARC', 'Bezel Engine archive', 'PlatinumGames PKZ', 'RE Engine PAK'} # file headers of compressed / media formats (zip_store)
|
||||
# Unreal by its name, which every Unreal 4 / 5 main here has; 'UE4' alone is no marker: it is a build path in Octopath Traveler II's main, and four bytes of machine code in Unreal 5 mains and in PRAGMATA's
|
||||
# (RE Engine), whose DLSS module also has a 'UE4 generic plugin' string. RE Engine by its via.render.* type names (PRAGMATA's main: 1,925)
|
||||
# IL2CPP by the metadata file every IL2CPP player opens: Unity 2022's main (Ace Attorney Investigations Collection) has no il2cpp_ API names, Engage's 2020.3 has both
|
||||
MARKERS = [(b'nvnBootstrapLoader', 'NVN'), (b'vkCreateInstance', 'Vulkan'), (b'eglGetProcAddress', 'EGL / OpenGL'), (b'global-metadata.dat', 'Unity IL2CPP'), (b'UnityEngine', 'Unity'),
|
||||
(b'sead::', 'Nintendo sead'), (b'agl::', 'Nintendo agl'), (b'gsys::', 'Nintendo gsys'), (b'Unreal', 'Unreal'), (b'UE4', 'Unreal 4'), (b'Havok', 'Havok'), (b'CRIWARE', 'CRIWARE'), (b'Wwise', 'Wwise'),
|
||||
(b'sead::', 'Nintendo sead'), (b'agl::', 'Nintendo agl'), (b'gsys::', 'Nintendo gsys'), (b'Unreal', 'Unreal'), (b'via.render.', 'RE Engine'), (b'Havok', 'Havok'), (b'CRIWARE', 'CRIWARE'), (b'Wwise', 'Wwise'),
|
||||
(b'MonoGame.Framework', 'MonoGame'), (b'FMOD mixer', 'FMOD')]
|
||||
GLSLC_MAGIC = b'\x91\x68\x86\x19' # GLSLC compiler outputs (shader_split.py glslc_shaders)
|
||||
GL_SRC = rb'\0#version [0-9]' # a GLSL source string as dm/gfx/tools/gl_shaders.py takes it from main (Balatro's main has none, only glslang's messages that start with '#version:')
|
||||
@@ -173,11 +176,13 @@ def guess(F, hooks=None):
|
||||
G['sys_resource'] = (f'{F["sysres"]:#x}', f'the NPDM declares {F["sysres"] // MiB} MB of system resource' + ('' if F['sysres'] else
|
||||
': IsVirtualAddressMemoryEnabled is false, as on Horizon (Big Brain Academy: Brain vs. Brain sets a heap only then)'))
|
||||
|
||||
if F.get('main_markers', set()) & {'Unreal', 'Unreal 4'} and R['exts'].get('.pak') and 'nvnBootstrapLoader' in imp:
|
||||
if 'Unreal' in F.get('main_markers', set()) and R['exts'].get('.pak') and 'nvnBootstrapLoader' in imp:
|
||||
G['shader_groups'] = ('ShaderArchive-Global-=global ShaderArchive-=game', 'the decoded shader code archives: the engine\'s global shaders and the game\'s material shaders')
|
||||
if 'RE Engine' in F.get('main_markers', set()) and R['mags'].get('RE Engine PAK'):
|
||||
G['shader_groups'] = ('re_chunk=sdf', 'RE Engine: the shaders are SDF definitions inside the KPKA PAKs (shader_split.py kpka_jobs / sdf_shaders), as in Monster Hunter Rise\'s and PRAGMATA\'s profiles')
|
||||
# The engine region needs virtual address memory; without it (OCTOPATH TRAVELER 1.0.5, Unreal Engine 4 on SDK 3.5.1, no system resource; Yoshi's Crafted World, SDK 4: 0xc5200000) nninitStartup sets a heap of pool − used instead,
|
||||
# which the heap-region layout above holds
|
||||
if F.get('main_markers', set()) & {'Unreal', 'Unreal 4'} and R['exts'].get('.pak') and 'nvnBootstrapLoader' in imp and F['sysres']:
|
||||
if 'Unreal' in F.get('main_markers', set()) and R['exts'].get('.pak') and 'nvnBootstrapLoader' in imp and F['sysres']:
|
||||
G['mem_reserve'] =('0x1028000000', 'Unreal: nninitStartup reserves a 62 GB address region and its FMallocBinned3 takes 37 GB of it, so a 64 GB alias region for the bring-up on the Mac. '
|
||||
'The rewriter cuts the allocator in any Unreal 4 / 5 main (dm/tools/ue_malloc.py) and gives the region what the alias region has room for (dm/tools/ue_region.py), so an iPhone '
|
||||
'takes a smaller guest block, as Octopath Traveler 0\'s profile (docs/reference/memory.md)')
|
||||
|
||||
@@ -35,6 +35,11 @@
|
||||
#define DMSH_C0_DISPATCH_NVN2 4 // NVN2 compute keeps them here, below its per-shader layout at 0x10 (x and y read by Fire Emblem Fortune's Weave's light culling; z by their order)
|
||||
#define DMSH_C0_CS_UBO 0x210 // compute: uniform slot r's address and size at 0x210 + 0x10 r, read through global memory (the build's ubo_ptr bindings); it ends where the storage buffer table starts
|
||||
#define DMSH_C0_CS_UBO_SLOTS 16 // uniform slots of that table
|
||||
// NVN2 graphics stages read the buffer entries the game pushes for them from a bank of their own: stage i's (vertex 0, hull or mesh 1, domain 2, geometry 3, pixel 4) is
|
||||
// c[25 + i], which holds graphics push block 1 + i (DMSH_PUSH_BLOCKS): {address, size} entries of 16 bytes, or 8-byte handles. PRAGMATA's shaders read c[25] in 9,944
|
||||
// vertex shaders, c[26] in 538 mesh and 3 hull shaders, c[27] in 37 domain shaders, c[28] in 1 geometry shader and c[29] in 12,195 pixel shaders, and the game binds no
|
||||
// storage buffer at all. The translator maps the bank onto that block of c[24] (the build's job key stage_bank, InstEmitAmpere.cs AStageBlock)
|
||||
#define DMSH_NVN2_STAGE_BANK 25
|
||||
|
||||
// NVN2 push constants (nvnCommandBufferPushGraphicsConstants / PushComputeConstants): the bytes the game pushes, read by its shaders as c[24] (the translator maps NVN2
|
||||
// compute's c0 push region there); one block for the graphics stages, one for compute
|
||||
@@ -47,6 +52,11 @@
|
||||
// the current bindings; only a shader with such a read has the table
|
||||
#define DMSH_CBSIZE_BANK 25
|
||||
#define DMSH_CBSIZE_SLOTS 14 // a u32 for each of uniform slots 0 to 13, as four uint4: 64 bytes
|
||||
// The push call's word before the offset names a block of the stage group; c[24] holds block b at b * DMSH_PUSH_SIZE. Block 0 holds the group's constants. Block 1 + i holds
|
||||
// stage i's buffer entries: compute has one stage and reads block 1 where its c0 layout counts it (control +0xaa, in words, right after block 0's +0xa9; the translator maps it
|
||||
// to c[24] + DMSH_PUSH_SIZE); graphics stage i reads its block through its own bank (DMSH_NVN2_STAGE_BANK + i), up to the pixel stage's block 5. PRAGMATA pushes 16-byte buffer
|
||||
// entries (a 64-bit GPU address, then a size) or 8-byte handles there before its dispatches and draws, and its shaders load and store through those addresses
|
||||
#define DMSH_PUSH_BLOCKS 6
|
||||
#define DMSH_C0_POINT_SIZE 0x610 // graphics stages: the largest point size, to which GLSLC clamps a shader-written gl_PointSize (Super Mario Odyssey's point sprites)
|
||||
#define DMSH_C0_SAMPLE_TABLE 0x620 // pixel stage: GLSLC's sample position table, one byte per (pixel of the location grid, sample): x and y in 1/16 pixel, low and high nibble
|
||||
#define DMSH_C0_SAMPLE_BYTES 16 // bytes of that table
|
||||
@@ -62,6 +72,7 @@
|
||||
#define DMSH_KIND_GEOMETRY "geometry" // one of the geometry lowering's helper buffers, reg = its index (dmsh_geometry.py HELPERS)
|
||||
#define DMSH_KIND_SBUF "sbuf" // storage buffer slot reg, its address in the stage's c0 table; rw = the shader writes it
|
||||
#define DMSH_KIND_SBUF_UBO "sbuf_ubo" // a storage buffer whose address the game keeps in its own uniform slot reg at byte off
|
||||
#define DMSH_KIND_SBUF_PUSH "sbuf_push" // a storage buffer whose address the game pushed: c[24] (both push blocks, DMSH_PUSH_BLOCKS) at byte off
|
||||
#define DMSH_KIND_UBO_PTR "ubo_ptr" // compute: uniform slot reg read through its address in c0 (DMSH_C0_CS_UBO)
|
||||
#define DMSH_KIND_TEX "tex" // texture slot reg (combined, or DMSH_SEPTEX_SLOT0 + r for a separate texture)
|
||||
#define DMSH_KIND_TBUF "tbuf" // a buffer texture in texture slot reg
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
// Generated file (dm/gfx/tools/dmsh_chain.py --header): the B shader library translation chain version this source tree expects (default options), one for every game;
|
||||
// the host loads only <library dir>/b-<V>/. Run dmsh_chain.py --header after changing the chain's tools and commit this file with the change
|
||||
#define DMSH_CHAIN "2afd39090b76"
|
||||
#define DMSH_CHAIN "d24f05cf9d78"
|
||||
+150
-33
@@ -229,6 +229,14 @@ NVN(nvnDeviceGetInteger, void, const NVNdevice *d, NVNdeviceInfo what, int *out)
|
||||
OLOG("DeviceGetInteger %#x -> %d", w, *out);
|
||||
}
|
||||
NVN(nvnDeviceGetImageHandle, NVNimageHandle, const NVNdevice *d, int id) { (void)d; return (NVNimageHandle)id; }
|
||||
// NVN2's bindless uniform buffer handle: the shaders read it as cx[URb][offset] (InstEmitAmpere.cs ABindlessConstant), and it is the buffer's address, as in the uniform
|
||||
// entries of c[0] that NVN2 compute shaders take theirs from. PRAGMATA never calls this; the arguments (device, address, size) are inferred from NVN's other handle getters
|
||||
// and the first call's are logged, to be checked against a game's call site
|
||||
NVN_NOPROTO(nvnDeviceGetUniformBufferHandle, uint64_t, const NVNdevice *d, NVNbufferAddress addr, size_t size) {
|
||||
(void)d;
|
||||
static int once; if (!once++) LOG("[nvn] DeviceGetUniformBufferHandle address %#llx size %#zx (first call)", (unsigned long long)addr, size);
|
||||
return addr;
|
||||
}
|
||||
// Separate texture / sampler handles: value = descriptor index (the sampler index goes in bit 20 and above, consistent with the bit layout of combined handles)
|
||||
NVN(nvnDeviceGetSeparateTextureHandle, NVNseparateTextureHandle, const NVNdevice *d, int id) { (void)d; return (NVNseparateTextureHandle){(uint64_t)id}; }
|
||||
NVN(nvnDeviceGetSeparateSamplerHandle, NVNseparateSamplerHandle, const NVNdevice *d, int id) { (void)d; return (NVNseparateSamplerHandle){(uint64_t)id << 20}; }
|
||||
@@ -827,7 +835,7 @@ NVN(nvnSyncFinalize, void, NVNsync *s) { nvn_sync_release((sync_t *)s); ((sync_t
|
||||
NVN(nvnSyncSetDebugLabel, void, NVNsync *s, const char *l) { (void)s; (void)l; }
|
||||
// Fence = "all commands previously submitted to the queue have completed": record the fence value of the most recent submit
|
||||
NVN(nvnQueueFenceSync, void, NVNqueue *q, NVNsync *s, NVNsyncCondition c, int f) { (void)c; (void)f; nvn_queue_fence((queue_t *)q,(sync_t *)s); }
|
||||
// A sync object that was never fenced waits until timeout, as on a real device; a fenced one is released only after the GPU has actually completed up to that fence value
|
||||
// A sync object that was never fenced has nothing pending: SyncWait answers ALREADY_SIGNALED (below); a fenced one is released only after the GPU has actually completed up to that fence value
|
||||
// Queue dependencies capture the current logical receipt; later re-fencing or finalizing the sync cannot retarget work already queued.
|
||||
NVN(nvnQueueWaitSync, NVNboolean, NVNqueue *q, const NVNsync *s) { nvn_queue_wait_sync((queue_t *)q,(const sync_t *)s); return 1; }
|
||||
// ZCull data: the host does no ZCull, so there is nothing to save / restore
|
||||
@@ -837,14 +845,25 @@ NVN(nvnCommandBufferSaveZCullData, void, NVNcommandBuffer *c, NVNbufferAddress a
|
||||
// depth-stencil state still does. The host does no ZCull, so there is nothing to set (Donkey Kong Bananza: EQUAL, 0xff)
|
||||
NVN_NOPROTO(nvnCommandBufferSetStencilCullCriteria, void, NVNcommandBuffer *c, int func, int ref) { (void)c; (void)func; (void)ref; }
|
||||
static _Atomic uint64_t g_sync_ns;
|
||||
// A long wait that expires is what a game's GPU watchdog acts on (PRAGMATA aborts when its 15 s wait for the previous frame's sync does): said with the sync's state
|
||||
static NVNsyncWaitResult sync_expired(const sync_t *o, uint64_t timeout, uint64_t waited) {
|
||||
static _Atomic int n;
|
||||
if (timeout >= 1000000000ull && atomic_fetch_add(&n, 1) < 8)
|
||||
LOG("[RED] nvnSyncWait: a %.1f s wait on sync %p expired after %.1f s (%s, fence %#llx)", timeout / 1e9, (const void *)o, waited / 1e9,
|
||||
o->fenced == 0 ? "never fenced since its Initialize" : o->fenced == 3 ? "its queue receipt not published" : "its fence not reached", (unsigned long long)o->fence);
|
||||
return NVN_SYNC_WAIT_RESULT_TIMEOUT_EXPIRED;
|
||||
}
|
||||
NVN(nvnSyncWait, NVNsyncWaitResult, const NVNsync *s, uint64_t timeout) {
|
||||
const sync_t *o = (const sync_t *)s;
|
||||
if (!o->fenced) return NVN_SYNC_WAIT_RESULT_TIMEOUT_EXPIRED;
|
||||
if(o->fenced==3) { if(nvn_sync_wait(o,0)) return NVN_SYNC_WAIT_RESULT_ALREADY_SIGNALED; uint64_t t0=now_ns(); int ok=nvn_sync_wait(o,timeout); atomic_fetch_add(&g_sync_ns,now_ns()-t0); return ok?NVN_SYNC_WAIT_RESULT_CONDITION_SATISFIED:NVN_SYNC_WAIT_RESULT_TIMEOUT_EXPIRED; }
|
||||
// Never fenced since its Initialize: no GPU work stands behind it, so it is signalled. PRAGMATA initializes its two frame syncs again at a screen change (the Initial Settings
|
||||
// menu's Next) and then waits 15 s on the one it has not fenced yet, aborting on TIMEOUT_EXPIRED or FAILED (main+0x4a8cf0) once two frames are in flight: a shipped path,
|
||||
// so on the console that wait does not expire. Answered as a timeout (the host's rule from its first version, with no game behind it), the game aborted at once
|
||||
if (!o->fenced) return NVN_SYNC_WAIT_RESULT_ALREADY_SIGNALED;
|
||||
if(o->fenced==3) { if(nvn_sync_wait(o,0)) return NVN_SYNC_WAIT_RESULT_ALREADY_SIGNALED; uint64_t t0=now_ns(); int ok=nvn_sync_wait(o,timeout); atomic_fetch_add(&g_sync_ns,now_ns()-t0); return ok?NVN_SYNC_WAIT_RESULT_CONDITION_SATISFIED:sync_expired(o,timeout,now_ns()-t0); }
|
||||
int (*w)(uint64_t, uint64_t) = o->fenced == 2 ? mtl_wait_acq : mtl_wait;
|
||||
if (w(o->fence, 0)) return NVN_SYNC_WAIT_RESULT_ALREADY_SIGNALED;
|
||||
uint64_t t0 = now_ns(); int ok = w(o->fence, timeout); atomic_fetch_add(&g_sync_ns, now_ns() - t0); // the frame's blocked SyncWait time (@sync_ms)
|
||||
return ok ? NVN_SYNC_WAIT_RESULT_CONDITION_SATISFIED : NVN_SYNC_WAIT_RESULT_TIMEOUT_EXPIRED;
|
||||
return ok ? NVN_SYNC_WAIT_RESULT_CONDITION_SATISFIED : sync_expired(o, timeout, now_ns() - t0);
|
||||
}
|
||||
NVN(nvnEventBuilderSetDefaults, void, NVNeventBuilder *b) { memset(b, 0, sizeof(ev_builder_t)); }
|
||||
NVN(nvnEventBuilderSetStorage, void, NVNeventBuilder *b, const NVNmemoryPool *p, int64_t off) { *(ev_builder_t *)b = (ev_builder_t){(const pool_t *)p, off}; }
|
||||
@@ -863,20 +882,31 @@ NVN(nvnEventSignal, void, NVNevent *e, NVNeventSignalMode m, uint32_t v) { ev_si
|
||||
|
||||
// ---------- Queue ----------
|
||||
#define QB(b) ((queue_builder_t *)(b))
|
||||
// The memory sizes start unset (0) and a setter marks its size set, as in NVN2's driver (PRAGMATA's sdk: SetDefaults 0x5e70e0 clears the sizes at +0x2c..+0x38 and their flags at
|
||||
// +0x24..+0x27; SetCommandMemorySize 0x5e7120 stores the size and sets its flag); the queue takes its defaults for those left unset (qb_size)
|
||||
NVN(nvnQueueBuilderSetDefaults, void, NVNqueueBuilder *b) {
|
||||
NVNdevice *dev = QB(b)->dev; memset(b, 0, sizeof(queue_builder_t)); QB(b)->dev = dev;
|
||||
QB(b)->cmd_sz = 65536; QB(b)->comp_sz = 262144; QB(b)->ctl_sz = 16384; QB(b)->flush = 4096; // Device defaults
|
||||
}
|
||||
static void qb_set(NVNqueueBuilder *b, int k, size_t n) { QB(b)->sz[k] = (uint32_t)n; QB(b)->set[k] = 1; }
|
||||
static uint64_t qb_size(const queue_builder_t *o, int k) { static const uint32_t def[4] = {65536, 262144, 16384, 0}; return o->set[k] ? o->sz[k] : def[k]; } // Device defaults
|
||||
NVN(nvnQueueBuilderSetDevice, void, NVNqueueBuilder *b, NVNdevice *d) { QB(b)->dev = d; }
|
||||
NVN(nvnQueueBuilderSetFlags, void, NVNqueueBuilder *b, int f) { QB(b)->flags = f; }
|
||||
NVN(nvnQueueBuilderSetCommandMemorySize, void, NVNqueueBuilder *b, size_t n) { QB(b)->cmd_sz = n; }
|
||||
NVN(nvnQueueBuilderSetComputeMemorySize, void, NVNqueueBuilder *b, size_t n) { QB(b)->comp_sz = n; }
|
||||
NVN(nvnQueueBuilderSetControlMemorySize, void, NVNqueueBuilder *b, size_t n) { QB(b)->ctl_sz = n; }
|
||||
NVN(nvnQueueBuilderSetCommandFlushThreshold, void, NVNqueueBuilder *b, size_t n) { QB(b)->flush = n; }
|
||||
NVN(nvnQueueBuilderSetCommandMemorySize, void, NVNqueueBuilder *b, size_t n) { qb_set(b, QB_CMD, n); }
|
||||
NVN(nvnQueueBuilderSetComputeMemorySize, void, NVNqueueBuilder *b, size_t n) { qb_set(b, QB_COMP, n); }
|
||||
NVN(nvnQueueBuilderSetControlMemorySize, void, NVNqueueBuilder *b, size_t n) { qb_set(b, QB_CTL, n); }
|
||||
NVN_NOPROTO(nvnQueueBuilderSetRayTracingMemorySize, void, NVNqueueBuilder *b, size_t n) { qb_set(b, QB_RT, n); } // NVN2; the host traces no rays, and only reports it back
|
||||
NVN(nvnQueueBuilderSetCommandFlushThreshold, void, NVNqueueBuilder *b, size_t n) { QB(b)->flush = (uint32_t)n; }
|
||||
// The getters write the size and return whether it was set (0x5e7450 and on: ldr w8, [x0, #0x2c]; str w8, [x1]; ldrb w0, [x0, #0x24]). PRAGMATA reads all four into its own
|
||||
// queue description after SetDefaults and the setters; unimplemented, they left its fields as they were
|
||||
static NVNboolean qb_get(const NVNqueueBuilder *b, int k, int *size) { *size = (int)QB(b)->sz[k]; return QB(b)->set[k]; }
|
||||
NVN_NOPROTO(nvnQueueBuilderGetCommandMemorySize, NVNboolean, const NVNqueueBuilder *b, int *size) { return qb_get(b, QB_CMD, size); }
|
||||
NVN_NOPROTO(nvnQueueBuilderGetComputeMemorySize, NVNboolean, const NVNqueueBuilder *b, int *size) { return qb_get(b, QB_COMP, size); }
|
||||
NVN_NOPROTO(nvnQueueBuilderGetControlMemorySize, NVNboolean, const NVNqueueBuilder *b, int *size) { return qb_get(b, QB_CTL, size); }
|
||||
NVN_NOPROTO(nvnQueueBuilderGetRayTracingMemorySize, NVNboolean, const NVNqueueBuilder *b, int *size) { return qb_get(b, QB_RT, size); }
|
||||
// Queue memory: the sum of the command + compute + control blocks rounded to 4 KiB (the host does not use it; the game only needs to allocate this size)
|
||||
NVN(nvnQueueBuilderGetQueueMemorySize, size_t, const NVNqueueBuilder *b) {
|
||||
const queue_builder_t *o = (const queue_builder_t *)b;
|
||||
return (o->cmd_sz + o->comp_sz + o->ctl_sz + 4095) & ~(size_t)4095;
|
||||
return (qb_size(o, QB_CMD) + qb_size(o, QB_COMP) + qb_size(o, QB_CTL) + 4095) & ~(size_t)4095;
|
||||
}
|
||||
NVN(nvnQueueBuilderSetQueueMemory, void, NVNqueueBuilder *b, void *m, size_t n) { QB(b)->mem = m; QB(b)->mem_sz = n; }
|
||||
NVN(nvnQueueInitialize, NVNboolean, NVNqueue *q, const NVNqueueBuilder *b) {
|
||||
@@ -2421,6 +2451,9 @@ NVN(nvnQueuePresentTexture, void, NVNqueue *q, NVNwindow *w, int idx) {
|
||||
o->ticket[idx] = nvn_queue_present((queue_t *)q,t,present_period(o) / 1e9,crop);
|
||||
}
|
||||
gfx_leave();
|
||||
// Diagnostic DM_NVN_PRESENT_FINISH=1 (off by default): a present returns once the GPU has run the frame, so the game never runs ahead of the GPU
|
||||
{ static int fin = -1; if (fin < 0) { const char *e = getenv("DM_NVN_PRESENT_FINISH"); fin = e && atoi(e); if (fin) LOG("DM_NVN_PRESENT_FINISH: every frame waited for at present (diagnostic)"); }
|
||||
if (fin) nvn_queue_finish((queue_t *)q); }
|
||||
atomic_fetch_add(&g_nvn_ns, now_ns() - t0);
|
||||
uint64_t f = g_frame, ps, dr; mtl_stats(&ps, &dr);
|
||||
if (nvn_real[0] || nvn_real[1]) { // DM_NVN_PROF: record phase = time of all implemented functions except submit; submit phase = QueueSubmitCommands
|
||||
@@ -2601,9 +2634,9 @@ _Static_assert(sizeof(map_req) == 0x28, "NVNmappingRequest");
|
||||
// sparse. OCTOPATH TRAVELER (Unreal Engine 4) gives each streamed texture a virtual pool of its own (0x20000 to 0x560000 bytes, flags 0x2a1), creates the texture in it, maps its mip
|
||||
// tail from a 4 MB physical pool and later the higher mips from other pages of it, after writing their texels there on the CPU: aliased, the texture had no storage (created before any
|
||||
// mapping) and the later mappings were refused (`[RED] MapVirtual: non-contiguous mapping`). A pool larger than the application pool is sparse from the start
|
||||
enum { NVRUN = 1024, VPT_LEAF = 512 }; // a page-table leaf covers 2 MB
|
||||
typedef struct { const uint8_t *phys; uint64_t gen; } vpte;
|
||||
struct vpool { const pool_t *pool; uint8_t *base; uint64_t len, size, top; int nrun; struct { uint64_t lo, hi; } run[NVRUN]; vpte **pt; struct vlog_ent *log; _Atomic uint64_t nlog; }; // len: reserved; size: the pool's; top: highest mapped end so far (logged per 128 MB)
|
||||
enum { VPT_LEAF = 512 }; // a page-table leaf covers 2 MB
|
||||
typedef struct { const uint8_t *phys; uint64_t gen; uint32_t live; } vpte; // live: the page has been mapped and may still be under a zero-copy buffer the GPU uses (see vunmap_defer)
|
||||
struct vpool { const pool_t *pool; uint8_t *base; uint64_t len, size, top; int nrun; struct vrun { uint64_t lo, hi; } *run; vpte **pt; struct vlog_ent *log; _Atomic uint64_t nlog; }; // len: reserved; size: the pool's; top: highest mapped end so far (logged per 128 MB)
|
||||
struct vlog_ent { uint64_t off, len; }; // a mapping request: the pool's change log (nvn_sparse_log_read), kept once a placement sparse texture asks for it
|
||||
enum { VLOG_N = 4096 };
|
||||
static struct vpool **g_vp; static int g_nvp, g_cvp; // the pools with a range of their own, under g_vp_mu
|
||||
@@ -2637,27 +2670,54 @@ static void vpool_drop(pool_t *o) { // caller holds g_vp_mu
|
||||
munmap(v->base, v->len);
|
||||
for (uint64_t l = 0; l < (v->size + (2u << 20) - 1) >> 21; l++) free(v->pt[l]);
|
||||
for (int i = 0; i < g_nvp; i++) if (g_vp[i] == v) { g_vp[i] = g_vp[--g_nvp]; break; }
|
||||
free(v->pt); free(v->log); free(v); o->vp = NULL;
|
||||
free(v->pt); free(v->log); free(v->run); free(v); o->vp = NULL;
|
||||
}
|
||||
static void vpool_release(pool_t *o) { pthread_mutex_lock(&g_vp_mu); vpool_drop(o); pthread_mutex_unlock(&g_vp_mu); }
|
||||
// Mapped runs of a sparse pool: [lo, hi) sorted, disjoint, adjacent runs merged. Caller holds g_vp_mu
|
||||
static void vunmap_run(int all); static int g_nvun; // the deferred unmaps (below)
|
||||
// Pool finalize: the reservation goes (munmap) with its runs' buffers. The GPU finishes the work submitted so far first: the buffers' deferred release keeps them alive for that
|
||||
// work, but not the pages under them, and inaccessible pages under a buffer still in submitted work or in the residency set are a GPU page fault (see vunmap_defer)
|
||||
static void vpool_release(pool_t *o) { if (o->vp && o->vp->nrun) mtl_finish(); pthread_mutex_lock(&g_vp_mu); if (g_nvun) vunmap_run(0); vpool_drop(o); pthread_mutex_unlock(&g_vp_mu); }
|
||||
// Mapped runs of a sparse pool: [lo, hi) sorted, disjoint, adjacent runs merged, each one a buffer the GPU addresses (mtl_pool_add). Caller holds g_vp_mu. The list grows with the
|
||||
// pool: it held 1,024 runs, and past that a new run was neither listed nor added, so the GPU did not reach it, and runs past the limit fell off the list while their buffers stayed
|
||||
// (PRAGMATA's RE Engine maps more in its opening; an indirect dispatch then read its group counts from other memory and the GPU hung). A change touches the runs it overlaps: a map
|
||||
// joins them into one, an unmap leaves at most a piece on either side, so the new list has at most two more runs. The runs' pools change in one step (mtl_pool_replace): the replay
|
||||
// looks addresses up on its own thread meanwhile, and an address that stays mapped must stay in a pool
|
||||
static void vrun_set(struct vpool *v, uint64_t lo, uint64_t hi, int mapped) {
|
||||
uint64_t nl[NVRUN][2]; int nn = 0; uint64_t mlo = lo, mhi = hi;
|
||||
struct vrun *nl = malloc(((size_t)v->nrun + 2) * sizeof *nl); int nn = 0, nd = 0, na = 0; uint64_t mlo = lo, mhi = hi;
|
||||
const void **del = malloc(((size_t)v->nrun + 1) * sizeof *del), *add[2]; uint64_t asz[2];
|
||||
if (!nl || !del) die("sparse pool run list allocation failed");
|
||||
for (int k = 0; k < v->nrun; k++) {
|
||||
uint64_t a = v->run[k].lo, b = v->run[k].hi;
|
||||
if (b < lo || a > hi || (!mapped && (b == lo || a == hi))) { if (nn < NVRUN) { nl[nn][0] = a; nl[nn][1] = b; nn++; } continue; } // untouched (an unmap leaves adjacent runs alone)
|
||||
mtl_pool_del(v->base + a);
|
||||
if (b < lo || a > hi || (!mapped && (b == lo || a == hi))) { nl[nn++] = (struct vrun){a, b}; continue; } // untouched (an unmap leaves adjacent runs alone)
|
||||
del[nd++] = v->base + a;
|
||||
if (mapped) { if (a < mlo) mlo = a; if (b > mhi) mhi = b; continue; } // joins the new run
|
||||
if (a < lo && nn < NVRUN) { nl[nn][0] = a; nl[nn][1] = lo; nn++; mtl_pool_add(v->base + a, lo - a); } // what the unmap leaves on either side
|
||||
if (b > hi && nn < NVRUN) { nl[nn][0] = hi; nl[nn][1] = b; nn++; mtl_pool_add(v->base + hi, b - hi); }
|
||||
// what the unmap leaves on either side: only the first run it touches starts before it and only the last ends after it, so two pieces at most
|
||||
if (a < lo) { nl[nn++] = (struct vrun){a, lo}; add[na] = v->base + a; asz[na++] = lo - a; } // NOLINT(clang-analyzer-security.ArrayBound): two pieces at most (above), which the analyzer cannot derive from the sorted, disjoint runs
|
||||
if (b > hi) { nl[nn++] = (struct vrun){hi, b}; add[na] = v->base + hi; asz[na++] = b - hi; } // NOLINT(clang-analyzer-security.ArrayBound): two pieces at most (above), which the analyzer cannot derive from the sorted, disjoint runs
|
||||
}
|
||||
if (mapped && nn < NVRUN) { nl[nn][0] = mlo; nl[nn][1] = mhi; nn++; mtl_pool_add(v->base + mlo, mhi - mlo); }
|
||||
if (nn == NVRUN) LOG("[RED] virtual pool %p: more than %d separate mapped runs", (const void *)v->pool, NVRUN);
|
||||
for (int a = 1; a < nn; a++) for (int b = a; b > 0 && nl[b][0] < nl[b - 1][0]; b--) { uint64_t t0 = nl[b][0], t1 = nl[b][1]; nl[b][0] = nl[b - 1][0]; nl[b][1] = nl[b - 1][1]; nl[b - 1][0] = t0; nl[b - 1][1] = t1; }
|
||||
v->nrun = nn; for (int k = 0; k < nn; k++) { v->run[k].lo = nl[k][0]; v->run[k].hi = nl[k][1]; }
|
||||
if (mapped) { nl[nn++] = (struct vrun){mlo, mhi}; add[na] = v->base + mlo; asz[na++] = mhi - mlo; }
|
||||
if (nd || na) mtl_pool_replace(del, nd, add, asz, na);
|
||||
free(del);
|
||||
for (int a = 1; a < nn; a++) for (int b = a; b > 0 && nl[b].lo < nl[b - 1].lo; b--) { struct vrun t = nl[b]; nl[b] = nl[b - 1]; nl[b - 1] = t; }
|
||||
if (nn > v->nrun && nn >= 1024 && !(nn & (nn - 1))) LOG("[nvn] virtual pool %p: %d separate mapped runs", (const void *)v->pool, nn);
|
||||
free(v->run); v->run = nl; v->nrun = nn;
|
||||
}
|
||||
// Page table of a sparse pool (see above). Caller holds g_vp_mu
|
||||
static const vpte *vpt_get(const struct vpool *v, uint64_t o) { const vpte *l = v->pt[o >> 21]; return l ? &l[(o >> 12) & (VPT_LEAF - 1)] : NULL; }
|
||||
// For the address notes (nvn_mtl.m dm_gfx_addr_note, DM_CTL "addr", the crash dump): the sparse pool an address is in, whether its page is mapped, and the mapped run holding it.
|
||||
// Takes g_vp_mu only if it is free (the crash dump may run with it held)
|
||||
void nvn_vpool_note(uint64_t a, char *note, size_t n) {
|
||||
if (!n) return; note[0] = 0;
|
||||
if (pthread_mutex_trylock(&g_vp_mu)) { snprintf(note, n, " (sparse pools busy)"); return; }
|
||||
for (int i = 0; i < g_nvp; i++) { const struct vpool *v = g_vp[i]; uint64_t b = (uint64_t)(uintptr_t)v->base;
|
||||
if (a < b || a >= b + v->len) continue;
|
||||
const vpte *e = vpt_get(v, a - b); int run = -1;
|
||||
for (int r = 0; r < v->nrun; r++) if (a - b >= v->run[r].lo && a - b < v->run[r].hi) { run = r; break; }
|
||||
snprintf(note, n, " sparse pool %p (+%#llx of %#llx reserved, %d runs): page %s%s%#llx, %s", (void *)v->pool, (unsigned long long)(a - b), (unsigned long long)v->len, v->nrun,
|
||||
e && e->phys ? "mapped" : "not mapped", e && e->phys ? " from physical " : "", e && e->phys ? (unsigned long long)(uintptr_t)(e->phys + ((a - b) & 0xfff)) : 0ull,
|
||||
run >= 0 ? "in a mapped run" : "in no run"); // the physical address: where the game's CPU writes what the GPU reads here
|
||||
break; }
|
||||
pthread_mutex_unlock(&g_vp_mu);
|
||||
}
|
||||
static void vpt_set(struct vpool *v, uint64_t voff, uint64_t size, const uint8_t *phys) {
|
||||
uint64_t gen = atomic_fetch_add(&g_vp_gen, 1) + 1;
|
||||
if (v->log) { v->log[atomic_load_explicit(&v->nlog, memory_order_relaxed) % VLOG_N] = (struct vlog_ent){voff, size}; atomic_fetch_add_explicit(&v->nlog, 1, memory_order_release); }
|
||||
@@ -2665,9 +2725,45 @@ static void vpt_set(struct vpool *v, uint64_t voff, uint64_t size, const uint8_t
|
||||
vpte **l = &v->pt[(voff + o) >> 21];
|
||||
if (!*l && !phys) continue; // never mapped: stays unmapped
|
||||
if (!*l && !(*l = calloc(VPT_LEAF, sizeof **l))) die("sparse pool page table allocation failed");
|
||||
(*l)[((voff + o) >> 12) & (VPT_LEAF - 1)] = (vpte){phys ? phys + o : NULL, gen};
|
||||
vpte *e = &(*l)[((voff + o) >> 12) & (VPT_LEAF - 1)]; *e = (vpte){phys ? phys + o : NULL, gen, phys ? 1u : e->live};
|
||||
}
|
||||
}
|
||||
// No page under a live buffer changes. A sparse run is a zero-copy buffer over the pages vm_remap put in its range, and the buffer keeps the pages it was made over, not
|
||||
// the address: a run's buffer leaves the replay at once (vrun_set) but lives on in submitted work and the residency set until its deferred release, at the fence after the
|
||||
// last commit. So an unmap keeps its pages until that fence has completed and only then makes them inaccessible (unless a newer request has mapped them since: the page
|
||||
// table's generation moved on), and a mapping over pages mapped before waits for the GPU first (vpool_overwrites). Before, pages changed at once under live buffers: the GPU
|
||||
// then read or wrote the old physical pages, which the game may have mapped elsewhere since (PRAGMATA: indirect dispatch counts read as another effect's floats, a hung
|
||||
// GPU, and a render-command list overwritten under the game). After uncraftablexd's sparse safe mode (PR #1407). Caller holds g_vp_mu; the queue is worked through
|
||||
// on later MapVirtual calls and at pool finalize
|
||||
enum { VUNMAP_N = 4096 };
|
||||
static struct { struct vpool *v; uint64_t off, len, gen, fence; } g_vun[VUNMAP_N];
|
||||
static _Atomic uint64_t g_vp_kept, g_vp_waits, g_vp_released, g_vp_unmap_lost;
|
||||
static void vunmap_defer(struct vpool *v, uint64_t off, uint64_t len) {
|
||||
if (g_nvun == VUNMAP_N) { atomic_fetch_add(&g_vp_unmap_lost, 1); return; } // full: these pages stay kept (safe; a later mapping over them waits)
|
||||
g_vun[g_nvun++] = (typeof(g_vun[0])){v, off, len, atomic_load(&g_vp_gen), mtl_last_fence() + 1};
|
||||
}
|
||||
static void vunmap_run(int all) { // caller holds g_vp_mu; all: the pool is going (the GPU has finished, see vpool_release)
|
||||
uint64_t done = mtl_completed_fence(), pg = (uint64_t)getpagesize();
|
||||
for (int i = 0; i < g_nvun; ) {
|
||||
if (!all && g_vun[i].fence > done) { i++; continue; }
|
||||
struct vpool *v = g_vun[i].v; uint64_t off = g_vun[i].off, len = g_vun[i].len, gen = g_vun[i].gen;
|
||||
int alive = 0; for (int k = 0; k < g_nvp && !alive; k++) alive = g_vp[k] == v;
|
||||
g_vun[i] = g_vun[--g_nvun];
|
||||
if (!alive) continue;
|
||||
for (uint64_t a = (off + pg - 1) & ~(pg - 1); a + pg <= off + len && a + pg <= v->len; a += pg) { // whole host pages only, none mapped since
|
||||
int ok = 1; for (uint64_t q = 0; q < pg && ok; q += 0x1000) { const vpte *e = vpt_get(v, a + q); ok = !e || (!e->phys && e->gen <= gen); }
|
||||
if (!ok) continue;
|
||||
if (mmap(v->base + a, pg, PROT_NONE, MAP_ANON | MAP_PRIVATE | MAP_FIXED, -1, 0) == MAP_FAILED) continue;
|
||||
for (uint64_t q = 0; q < pg; q += 0x1000) { vpte *e = (vpte *)vpt_get(v, a + q); if (e) e->live = 0; }
|
||||
atomic_fetch_add(&g_vp_released, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
static int vpool_overwrites(const struct vpool *v, const map_req *r) { // does a mapping request put new pages over pages mapped before? Caller holds g_vp_mu
|
||||
if (!r->phys || r->voff < 0 || (uint64_t)r->voff + r->size > v->size) return 0;
|
||||
for (uint64_t o = 0; o < r->size; o += 0x1000) { const vpte *e = vpt_get(v, (uint64_t)r->voff + o); if (e && e->live) return 1; }
|
||||
return 0;
|
||||
}
|
||||
static int vpool_map(struct vpool *v, const map_req *r) { // caller holds g_vp_mu; → 0 on failure
|
||||
uint64_t pg = (uint64_t)getpagesize();
|
||||
if (r->voff < 0 || (uint64_t)r->voff + r->size > v->size) { LOG("[RED] virtual pool %p: request at %#llx+%#llx is beyond the pool's %#llx", (const void *)v->pool, (unsigned long long)r->voff, (unsigned long long)r->size, (unsigned long long)v->size); return 0; }
|
||||
@@ -2682,9 +2778,10 @@ static int vpool_map(struct vpool *v, const map_req *r) { // caller holds g_vp
|
||||
(const void *)v->pool, (uint64_t)r->voff + r->size > v->len ? "beyond the reservation" : "not aligned to the host page", r->phys ? "map" : "unmap", (unsigned long long)r->voff, (unsigned long long)r->size);
|
||||
return 1;
|
||||
}
|
||||
if (!r->phys) { // unmap: inaccessible pages again
|
||||
if (mmap((void *)to, r->size, PROT_NONE, MAP_ANON | MAP_PRIVATE | MAP_FIXED, -1, 0) == MAP_FAILED) { LOG("[RED] virtual pool unmap %#lx+%#llx failed (errno %d)", (unsigned long)to, (unsigned long long)r->size, errno); return 0; }
|
||||
vrun_set(v, (uint64_t)r->voff, (uint64_t)r->voff + r->size, 0); return 1;
|
||||
if (!r->phys) { // unmap: the pages stay until the work that may use them has completed (see vunmap_defer); the page table says unmapped, so textures read 0 at once
|
||||
atomic_fetch_add(&g_vp_kept, 1);
|
||||
vrun_set(v, (uint64_t)r->voff, (uint64_t)r->voff + r->size, 0);
|
||||
vunmap_defer(v, (uint64_t)r->voff, r->size); return 1;
|
||||
}
|
||||
uintptr_t from = (uintptr_t)ph->mem + (uintptr_t)r->poff;
|
||||
vm_prot_t cur, max;
|
||||
@@ -2705,6 +2802,16 @@ NVN(nvnMemoryPoolMapVirtual, NVNboolean, NVNmemoryPool *p, int n, const NVNmappi
|
||||
else o->vmode = 2;
|
||||
}
|
||||
struct vpool *v = o->vmode == 2 ? vpool_of(o) : NULL; int ok = 1;
|
||||
if (g_nvun) vunmap_run(0); // pages kept by earlier unmaps whose work has completed
|
||||
if (v) { // new pages over ones mapped before: the GPU may still use the old ones through a buffer made over them, so the submitted work finishes first (see vunmap_defer)
|
||||
int over = 0; for (int i = 0; i < n && !over; i++) over = vpool_overwrites(v, &r[i]);
|
||||
if (over) {
|
||||
pthread_mutex_unlock(&g_vp_mu); mtl_finish(); uint64_t w = atomic_fetch_add(&g_vp_waits, 1) + 1; pthread_mutex_lock(&g_vp_mu); v = o->vmode == 2 ? vpool_of(o) : NULL;
|
||||
if (g_nvun) vunmap_run(0);
|
||||
if (w == 1 || !(w & (w - 1))) LOG("[nvn] sparse pools: %llu mapping requests over pages that may be under a live buffer waited for the GPU first (%llu unmaps deferred, %llu host pages released after their work, %d still queued, %llu kept for good: queue full)",
|
||||
(unsigned long long)w, (unsigned long long)atomic_load(&g_vp_kept), (unsigned long long)atomic_load(&g_vp_released), g_nvun, (unsigned long long)atomic_load(&g_vp_unmap_lost));
|
||||
}
|
||||
}
|
||||
for (int i = 0; v && i < n && ok; i++) ok = vpool_map(v, &r[i]);
|
||||
pthread_mutex_unlock(&g_vp_mu);
|
||||
if (v) return (NVNboolean)ok;
|
||||
@@ -3061,19 +3168,29 @@ NVN_NOPROTO(nvnCommandBufferEvaluateDlss, void, NVNcommandBuffer *c, const dlss_
|
||||
o->net = n->serial; o->iw = p->iw; o->ih = p->ih; o->ow = n->b.w; o->oh = n->b.h; o->flags = n->b.flags;
|
||||
memcpy(o->mv, p->mv, sizeof o->mv); memcpy(o->jitter, p->jitter, sizeof o->jitter); o->pre_exposure = p->pre_exposure; o->reset = p->reset != 0;
|
||||
}
|
||||
// NVN2 push constants: (command buffer, a word seen 0, byte offset, size, data). The bytes form a constant block of the graphics stages or of compute, which their shaders read
|
||||
// NVN2 push constants: (command buffer, block, byte offset, size, data). The bytes form a constant block of the graphics stages or of compute, which their shaders read
|
||||
// as c[24] (DMSH_PUSH_BANK; NVN2 compute's own c0 layout starts with them, which the translator maps there). Donkey Kong Bananza's upscaler pushes (1 / w, 1 / h, w, h) of its
|
||||
// target for its graphics passes, and two integer rectangles (source, destination) for its compute network
|
||||
// target for its graphics passes, and two integer rectangles (source, destination) for its compute network. Block 1 + i holds stage i's buffer entries (dmsh_abi.h DMSH_PUSH_BLOCKS):
|
||||
// compute's single stage reads block 1 (PRAGMATA: 16-byte {address, size} entries, 1 to 3 at offset 0, before its dispatches), at DMSH_PUSH_SIZE in c[24]; with it taken for
|
||||
// block 0, PRAGMATA's persistent compute shaders spun on a work counter in the wrong buffer and the GPU never finished its first 3D frame. Graphics stage i reads block 1 + i
|
||||
// through its own bank: PRAGMATA pushes its vertex stage's entries into block 1, its mesh stage's into block 2 and its pixel stage's into block 5. Blocks 2 to 5 were dropped,
|
||||
// and the objects of its visibility buffer drew black
|
||||
static void push_const(NVNcommandBuffer *c, int compute, uint64_t w, uint64_t off, uint64_t n, const void *data) {
|
||||
if (w) { static int once; if (!once++) LOG("[RED] push constants with the word before the offset %#llx: its meaning is not known", (unsigned long long)w); }
|
||||
const uint64_t blocks = compute ? 2 : DMSH_PUSH_BLOCKS; // compute: its constants and its one stage's entries
|
||||
if (w >= blocks) { static int once; if (!once++) LOG("[RED] %s push constants into block %llu (%#llx + %#llx): the host keeps %llu, dropped", compute ? "compute" : "graphics", (unsigned long long)w, (unsigned long long)off, (unsigned long long)n, (unsigned long long)blocks); return; }
|
||||
if (off + n > DMSH_PUSH_SIZE || !data) { static int k; if (k++ < 8) LOG("[RED] push constants at %#llx + %#llx: beyond the host's %#x-byte block, dropped", (unsigned long long)off, (unsigned long long)n, DMSH_PUSH_SIZE); return; }
|
||||
p_push_const *r = RECN(c, OP_PUSH_CONST, p_push_const, data, n); r->compute = (uint16_t)compute; r->offset = (uint16_t)off; r->size = (uint32_t)n; memcpy(r->data, data, n);
|
||||
p_push_const *r = RECN(c, OP_PUSH_CONST, p_push_const, data, n); r->compute = (uint16_t)compute; r->offset = (uint16_t)(w * DMSH_PUSH_SIZE + off); r->size = (uint32_t)n; memcpy(r->data, data, n);
|
||||
}
|
||||
NVN_NOPROTO(nvnCommandBufferPushGraphicsConstants, void, NVNcommandBuffer *c, uint64_t w, uint64_t off, uint64_t n, const void *data) { push_const(c, 0, w, off, n, data); }
|
||||
NVN_NOPROTO(nvnCommandBufferPushComputeConstants, void, NVNcommandBuffer *c, uint64_t w, uint64_t off, uint64_t n, const void *data) { push_const(c, 1, w, off, n, data); }
|
||||
// NVN2 command buffer modes Donkey Kong Bananza sets on every command buffer it begins: they tune how the GPU's front end runs the commands (whether compute may overlap the next
|
||||
// work, how geometry is processed, how commands are recorded), not what they produce. The host records and replays every command in order on Metal, so none changes its result.
|
||||
// Logged once each with the first value; open: what the values select on the console
|
||||
// NVN2's driver writes the mode into the 3D class's SET_PROVOKING_VERTEX (method 0x1684: 0x800005a1 | mode << 16, PRAGMATA's sdk 0x60b690), where 0 is FIRST and 1 is LAST.
|
||||
// Metal's flat interpolation takes the first vertex of each primitive, so FIRST is what the host draws; LAST has no Metal setting
|
||||
NVN_NOPROTO(nvnCommandBufferSetProvokingVertexMode, void, NVNcommandBuffer *c, int mode) {
|
||||
(void)c; if (mode) { static int once; if (!once++) LOG("[RED] nvnCommandBufferSetProvokingVertexMode %d (the last vertex): Metal's flat values come from the first vertex", mode); }
|
||||
}
|
||||
NVN_NOPROTO(nvnCommandBufferSetRecordingMode, void, NVNcommandBuffer *c, int mode) { (void)c; ONCE_LOG("nvnCommandBufferSetRecordingMode %d: the host records every command buffer alike", mode); }
|
||||
NVN_NOPROTO(nvnCommandBufferSetGeometryProcessingMode, void, NVNcommandBuffer *c, int mode) { (void)c; ONCE_LOG("nvnCommandBufferSetGeometryProcessingMode %d: no effect on Metal", mode); }
|
||||
NVN_NOPROTO(nvnCommandBufferSetComputeWorkloadPriority, void, NVNcommandBuffer *c, int a, int b) { (void)c; ONCE_LOG("nvnCommandBufferSetComputeWorkloadPriority %d %d: Metal runs compute in submission order, with no priority", a, b); }
|
||||
|
||||
@@ -323,7 +323,7 @@ static geo_access geo_access_of(NvProg *pr, NvShader *gs) {
|
||||
const p_bind_buf *u=b->kind==NVN_RB_SBUFP?&S.ssbo[st][b->reg]:&S.ubo[st][b->reg];
|
||||
int write=b->kind==NVN_RB_SBUFP && b->rw && !(sh->sb_ro>>b->reg&1);
|
||||
geo_access_add(&a,u->addr,b->kind==NVN_RB_CBUF?cb_len(sh,b->reg,u->size):u->size,write);
|
||||
} else if (b->kind==NVN_RB_SBUFU || b->kind==NVN_RB_IMG || b->kind==NVN_RB_IMGU || b->kind==NVN_RB_TBUF || b->kind==NVN_RB_TBUFU) a.unknown=1;
|
||||
} else if (b->kind==NVN_RB_SBUFU || b->kind==NVN_RB_SBUFQ || b->kind==NVN_RB_IMG || b->kind==NVN_RB_IMGU || b->kind==NVN_RB_TBUF || b->kind==NVN_RB_TBUFU) a.unknown=1;
|
||||
}
|
||||
}
|
||||
return a;
|
||||
@@ -692,6 +692,7 @@ static void mesh_tasks_draw(const p_draw *dw) {
|
||||
if (!mdx_find(dw->ind, dw->ind, &ind)) { mdx_run(dw, NULL); if (!mdx_find(dw->ind, dw->ind, &ind)) ind = 0; }
|
||||
if (!ind || !mtl_gpu_addr(dw->ind, 8, &mb, &mo, &ind_rec)) { RED_ONCE(154, "DrawMeshTasksIndirect record at %#llx is in no memory pool: draw skipped", (unsigned long long)dw->ind); return; }
|
||||
}
|
||||
PD("m %llu mesh tasks task=%s mesh=%s fs=%s first=%d count=%d indirect=%#llx", g_stat_pass + !g_enc, ts ? ts->key : "-", ms->key, pr->sh[1] ? pr->sh[1]->key : "-", dw->first, dw->count, (unsigned long long)dw->ind); // the draw_ below is a stand-in triangle
|
||||
g_mtk.on = 1; g_mtk.miss = 0; g_mtk.ts = ts; g_mtk.ms = ms; g_mtk.first = (uint32_t)dw->first; g_mtk.count = (uint32_t)dw->count;
|
||||
g_mtk.ind = ind; g_mtk.ind_rec = ind_rec;
|
||||
g_geo_program = raster;
|
||||
|
||||
@@ -16,6 +16,8 @@ void bf_want_note(const char *key);
|
||||
void mtl_pool_add(const void *mem, uint64_t size);
|
||||
void mtl_pool_addressed(const void *mem, uint64_t size); // the game holds a GPU address in this range, so raw global memory may reach it
|
||||
void mtl_pool_del(const void *mem);
|
||||
void mtl_pool_replace(const void *const *del, int ndel, const void *const *add, const uint64_t *size, int nadd); // in one step for every lookup (a sparse pool's runs, hle_nvn.c vrun_set)
|
||||
void dm_gfx_addr_note(uint64_t a, char *note, size_t n); // what the graphics layer knows of an address (the crash dump, red lines)
|
||||
// memory pool Finalize: evict the textures built on this pool (pool object address) from the storage-sharing table
|
||||
void mtl_alias_drop_pool(const void *pool);
|
||||
// physical memory pool Finalize: the shared placement sparse tiles of its memory go back once no texture maps them (sp_release)
|
||||
|
||||
+211
-51
@@ -843,18 +843,11 @@ typedef struct { uintptr_t lo, hi, a, b; const void *mem; int *chunk, full; NSMu
|
||||
static big_pool g_big[BIG_MAX]; static int g_nbig;
|
||||
static id<MTLBuffer> pool_buf(uintptr_t a, uintptr_t b); // a pool's zero-copy buffer over [a, b), made over writable pages (below)
|
||||
static int big_of(uint64_t addr) { for (int i = 0; i < g_nbig; i++) if (addr >= g_big[i].lo && addr < g_big[i].hi) return i; return -1; }
|
||||
void mtl_pool_add(const void *mem, uint64_t size) {
|
||||
mtl_init(); // the change is recorded once the pool can be found (reg_bump below): a reader that sees the new generation sees the pool
|
||||
uintptr_t pg = (uintptr_t)getpagesize(), lo = (uintptr_t)mem, hi = lo + size;
|
||||
uintptr_t a = lo & ~(pg - 1), b = (hi + pg - 1) & ~(pg - 1);
|
||||
static int chunks = -1; if (chunks < 0) { const char *e = getenv("DM_NVN_POOL_CHUNKS"); chunks = !e || atoi(e); }
|
||||
if (size >= BIG_MIN && chunks) {
|
||||
pthread_mutex_lock(&g_mu); int k = g_nbig < BIG_MAX ? g_nbig : -1;
|
||||
if (k >= 0) { int *ch = calloc(((b - a) >> 24) + 1, sizeof *ch); if (!ch) MDIE("pool chunk table"); g_big[g_nbig++] = (big_pool){lo, hi, a, b, mem, ch, 0, [NSMutableArray array]};
|
||||
g_pidx_ok = 0; g_plast = -1; atomic_fetch_add(&g_pool_gen, 1); g_pool_adds++; atomic_fetch_add(&g_big_n, 1); }
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
if (k >= 0) { reg_bump(-1, REG_POOL); static int nl; if (nl++ < 8) MLOG("memory pool %p+%llu MB: in chunks, wired as far as lookups reach", mem, (unsigned long long)(size >> 20)); return; }
|
||||
}
|
||||
// A pool to put into the table: its zero-copy buffer is made first, outside g_mu (pool_new_prep; it may retry for seconds), and the entry goes in under g_mu (pool_new_put), so a change
|
||||
// of several pools can be one step for every lookup (mtl_pool_replace)
|
||||
typedef struct { const void *mem; uint64_t size; uintptr_t lo, hi, a, b; __strong id<MTLBuffer> buf; } pool_new; // buf nil: in chunks (a large pool)
|
||||
static int pool_chunks(void) { static int c = -1; if (c < 0) { const char *e = getenv("DM_NVN_POOL_CHUNKS"); c = !e || atoi(e); } return c; }
|
||||
static id<MTLBuffer> pool_buf_made(const void *mem, uint64_t size, uintptr_t a, uintptr_t b) {
|
||||
id<MTLBuffer> buf = pool_buf(a, b);
|
||||
// Pokémon Legends: Z-A: twice on the Mac a small pool's buffer was refused although its pages were one read-write VM region, both times while another heavy job (a shader compile,
|
||||
// a second game instance) took the machine's memory; every run on an idle machine created all of them. Wiring the pages may fail under memory pressure: retry for up to about 2 s
|
||||
@@ -872,13 +865,33 @@ void mtl_pool_add(const void *mem, uint64_t size) {
|
||||
}
|
||||
MDIE("memory pool %p+%#llx: failed to create the zero-copy buffer over %#lx..%#lx", mem, (unsigned long long)size, (unsigned long)a, (unsigned long)b);
|
||||
}
|
||||
pthread_mutex_lock(&g_mu);
|
||||
return buf;
|
||||
}
|
||||
static void pool_new_prep(pool_new *n, const void *mem, uint64_t size) {
|
||||
uintptr_t pg = (uintptr_t)getpagesize(), lo = (uintptr_t)mem, hi = lo + size;
|
||||
*n = (pool_new){mem, size, lo, hi, lo & ~(pg - 1), (hi + pg - 1) & ~(pg - 1), nil};
|
||||
if (size >= BIG_MIN && pool_chunks()) { pthread_mutex_lock(&g_mu); int room = g_nbig < BIG_MAX; pthread_mutex_unlock(&g_mu); if (room) return; }
|
||||
n->buf = pool_buf_made(mem, size, n->a, n->b);
|
||||
}
|
||||
static void pool_new_put(pool_new *n) { // caller holds g_mu
|
||||
if (!n->buf && g_nbig == BIG_MAX) n->buf = pool_buf_made(n->mem, n->size, n->a, n->b); // the chunk table filled since pool_new_prep looked
|
||||
if (!n->buf) {
|
||||
int *ch = calloc(((n->b - n->a) >> 24) + 1, sizeof *ch); if (!ch) MDIE("pool chunk table");
|
||||
g_big[g_nbig++] = (big_pool){n->lo, n->hi, n->a, n->b, n->mem, ch, 0, [NSMutableArray array]};
|
||||
g_pidx_ok = 0; g_plast = -1; atomic_fetch_add(&g_pool_gen, 1); g_pool_adds++; atomic_fetch_add(&g_big_n, 1);
|
||||
static int nl; if (nl++ < 8) MLOG("memory pool %p+%llu MB: in chunks, wired as far as lookups reach", n->mem, (unsigned long long)(n->size >> 20));
|
||||
return;
|
||||
}
|
||||
if (g_npool == g_cap) { g_cap = g_cap ? g_cap * 2 : 64; g_pools = realloc_or_die(g_pools, g_cap * sizeof *g_pools, "the memory pool table"); }
|
||||
g_pidx_ok = 0; g_plast = -1; atomic_fetch_add(&g_pool_gen, 1); // the address index and the per-thread caches are invalid (pool_find, pc_get)
|
||||
g_pools[g_npool++] = (pool_ent){lo, hi, a, buf, buf.gpuAddress, mem, 0, clock_gettime_nsec_np(CLOCK_MONOTONIC), hi, 1}; // not in the residency set yet: put in the first time it is addressed (pool_res)
|
||||
g_pools[g_npool++] = (pool_ent){n->lo, n->hi, n->a, n->buf, n->buf.gpuAddress, n->mem, 0, clock_gettime_nsec_np(CLOCK_MONOTONIC), n->hi, 1}; // not in the residency set yet: put in the first time it is addressed (pool_res)
|
||||
g_pool_adds++;
|
||||
[g_keep addObject:buf];
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
[g_keep addObject:n->buf];
|
||||
}
|
||||
void mtl_pool_add(const void *mem, uint64_t size) {
|
||||
mtl_init(); // the change is recorded once the pool can be found (reg_bump below): a reader that sees the new generation sees the pool
|
||||
pool_new n; pool_new_prep(&n, mem, size);
|
||||
pthread_mutex_lock(&g_mu); pool_new_put(&n); pthread_mutex_unlock(&g_mu);
|
||||
reg_bump(-1, REG_POOL);
|
||||
}
|
||||
|
||||
@@ -888,18 +901,11 @@ static void big_moved(int i) { // caller holds g_mu: entry i has a new index
|
||||
if (e->unk == 0) b->full = i + 1; else b->chunk[(e->lo - b->a) >> 24] = i + 1;
|
||||
return; }
|
||||
}
|
||||
void mtl_pool_del(const void *mem) {
|
||||
reg_bump(-1, REG_POOL);
|
||||
pthread_mutex_lock(&g_mu);
|
||||
// The no-copy buffer goes through deferred release (out of the residency set and unreferenced after submitted commands complete). It used to be removed only from g_keep while the residency set still held a strong reference: after the pool was freed the buffer stayed alive wrapping that guest memory,
|
||||
// and a new pool at the same address wrapped it again. Engage's title demo cycles scenes; GPU allocated grew to 5.4 GB and resident memory to 3.6 GB in 850 s.
|
||||
// Its own autorelease pool: this runs on the guest thread that finalizes the pool, whose implicit pool never drains, and adding to the weak table g_dead_pools left the buffer
|
||||
// autoreleased there, so every finalized pool buffer stayed alive for good (Ghost Trick: Phantom Detective, 125 buffers and 6.6 GB of GPU allocations 300 frames into the boot, 0 with the pool)
|
||||
// Once out of the table and with g_pool_gen bumped, a buffer is reached only by what a submission already encoded: so with none open it waits for the last committed fence, not the
|
||||
// next one, which a game that stops submitting never reaches (defer_kick). The open flag is read after the bump, and mtl_sub_begin sets it before its lookups, each side with a full
|
||||
// fence: a submission either is seen open or sees the bump, and then neither the per-thread cache (pc_get, no lock) nor the table gives it this buffer
|
||||
@autoreleasepool {
|
||||
NSMutableArray<id<MTLBuffer>> *gone = [NSMutableArray array];
|
||||
// The no-copy buffer goes through deferred release (out of the residency set and unreferenced after submitted commands complete). It used to be removed only from g_keep while the residency set still held a strong reference: after the pool was freed the buffer stayed alive wrapping that guest memory,
|
||||
// and a new pool at the same address wrapped it again. Engage's title demo cycles scenes; GPU allocated grew to 5.4 GB and resident memory to 3.6 GB in 850 s.
|
||||
// In an autorelease pool of its caller's: this runs on the guest thread that finalizes the pool, whose implicit pool never drains, and adding to the weak table g_dead_pools left the buffer
|
||||
// autoreleased there, so every finalized pool buffer stayed alive for good (Ghost Trick: Phantom Detective, 125 buffers and 6.6 GB of GPU allocations 300 frames into the boot, 0 with the pool)
|
||||
static void pool_take_out(const void *mem, NSMutableArray<id<MTLBuffer>> *gone) { // caller holds g_mu
|
||||
int bg = -1; for (int k = 0; k < g_nbig; k++) if (g_big[k].mem == mem) bg = k;
|
||||
for (int i = 0; i < g_npool; i++)
|
||||
if (g_pools[i].key == mem) { id<MTLBuffer> b = g_pools[i].buf; [g_keep removeObject:b]; [gone addObject:b]; if (g_pools[i].res) g_pool_res_n--;
|
||||
@@ -912,11 +918,42 @@ void mtl_pool_del(const void *mem) {
|
||||
[gone addObjectsFromArray:g_big[bg].old];
|
||||
free(g_big[bg].chunk); g_big[bg] = g_big[--g_nbig]; g_pidx_ok = 0; g_plast = -1; atomic_fetch_add(&g_pool_gen, 1); atomic_fetch_sub(&g_big_n, 1);
|
||||
}
|
||||
}
|
||||
// Once out of the table and with g_pool_gen bumped, a buffer is reached only by what a submission already encoded: so with none open it waits for the last committed fence, not the
|
||||
// next one, which a game that stops submitting never reaches (defer_kick). The open flag is read after the bump, and mtl_sub_begin sets it before its lookups, each side with a full
|
||||
// fence: a submission either is seen open or sees the bump, and then neither the per-thread cache (pc_get, no lock) nor the table gives it this buffer
|
||||
static void pool_gone_release(NSMutableArray<id<MTLBuffer>> *gone) { // caller holds g_mu
|
||||
atomic_thread_fence(memory_order_seq_cst);
|
||||
uint64_t fence = g_fence + (atomic_load(&g_sub_on) ? 1 : 0);
|
||||
for (id<MTLBuffer> b in gone) defer_obj_at(b, 0, fence);
|
||||
}
|
||||
void mtl_pool_del(const void *mem) {
|
||||
reg_bump(-1, REG_POOL);
|
||||
@autoreleasepool {
|
||||
NSMutableArray<id<MTLBuffer>> *gone = [NSMutableArray array];
|
||||
pthread_mutex_lock(&g_mu); pool_take_out(mem, gone); pool_gone_release(gone); pthread_mutex_unlock(&g_mu);
|
||||
}
|
||||
}
|
||||
// Pools that take the place of others, in one step under g_mu: a lookup finds the old ones or the new ones, never neither. A sparse pool's mapped run is a pool of its own, replaced
|
||||
// whenever a mapping joins it to its neighbours or an unmap splits it (hle_nvn.c vrun_set), on the game's thread while the replay looks addresses up on its own. Removed and then
|
||||
// added, an address mapped all along was in no pool between the two: PRAGMATA's mesh shaders 765e6d9d2588ce70 and 5aab38bb5ba67ef7 read a buffer whose address the game pushes,
|
||||
// 0x3000000 into a sparse pool whose one run kept growing (0x8c5e304000..0x8c7b1a4000, then on), and got a dummy buffer at frames 2971 and 4484, the frames the run was replaced in
|
||||
void mtl_pool_replace(const void *const *del, int ndel, const void *const *add, const uint64_t *size, int nadd) {
|
||||
mtl_init();
|
||||
pool_new *n = nadd ? (pool_new *)calloc((size_t)nadd, sizeof *n) : NULL; if (nadd && !n) MDIE("pool replacement");
|
||||
for (int i = 0; i < nadd; i++) pool_new_prep(&n[i], add[i], size[i]);
|
||||
reg_bump(-1, REG_POOL);
|
||||
@autoreleasepool {
|
||||
NSMutableArray<id<MTLBuffer>> *gone = [NSMutableArray array];
|
||||
pthread_mutex_lock(&g_mu);
|
||||
for (int i = 0; i < ndel; i++) pool_take_out(del[i], gone);
|
||||
for (int i = 0; i < nadd; i++) pool_new_put(&n[i]);
|
||||
pool_gone_release(gone);
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
}
|
||||
for (int i = 0; i < nadd; i++) n[i].buf = nil; // release the references before the memory goes (a strong member of a calloc'd array)
|
||||
free(n);
|
||||
reg_bump(-1, REG_POOL);
|
||||
}
|
||||
|
||||
// Address → pool: the last hit first, then a binary search over indices sorted by start address, and a full linear scan only when that fails (pools overlapping).
|
||||
@@ -1307,6 +1344,11 @@ static int sbw_hits(uint64_t lo, uint64_t hi) {
|
||||
// The bytes a writable storage binding at Metal buffer offset mo can write: its size, else (bound with size 0, as Breath of the Wild's GPU particle dispatches bind their outputs, or a
|
||||
// size not known) the rest of that buffer. A device pointer that runs past its buffer is out of bounds on Metal, which the host could not give the Switch's meaning anyway. Before, such
|
||||
// a binding counted as a write anywhere, and every partly covered uniform shadow after it in the submission was refused (BotW shrines: about 240 more passes a frame, GitHub issue #534)
|
||||
// A bindless constant buffer handle in the hardware's layout (Ampere; as NVK's nvk_bindless_cbuf): bits 0..44 the address >> 4, 45..63 the size >> 4, which the shaders
|
||||
// decode (InstEmitAmpere.cs ABindlessConstant). PRAGMATA builds its own: b12078fe3bce1273 pushes 0x5a0083055d124, 32 bytes at 0x83055d1240. ucb_handle_addr reads a buffer
|
||||
// word that holds either one or a plain address: a handle of any size has a bit at 45 or above, which no guest address has (they lie below 2^40)
|
||||
static uint64_t ucb_handle(uint64_t addr, uint64_t size) { uint64_t s = (size + 15) >> 4; return (addr >> 4 & ((1ull << 45) - 1)) | (s < (1u << 19) ? s : (1u << 19) - 1) << 45; }
|
||||
static uint64_t ucb_handle_addr(uint64_t v) { return v >> 45 ? (v & ((1ull << 45) - 1)) << 4 : v; }
|
||||
static uint64_t sbw_len(uint64_t size, void *mb, uint64_t mo) { if (size) return size; uint64_t len = ((__bridge id<MTLBuffer>)mb).length; return len > mo ? len - mo : 0; }
|
||||
static inline unsigned pend_bucket(uint64_t page) { return (unsigned)((page * 0x9E3779B97F4A7C15ull) >> (64 - PEND_HB_BITS)); }
|
||||
static void pend_reset(void) { g_nhw_sub = 0; g_npend =g_pend_over = g_nupd = g_npnode = g_nwide = g_nsbw = g_nsbw_w = g_sbw_over = 0; if (!++g_pend_gen) { memset(g_pend_hgen, 0, sizeof g_pend_hgen); memset(g_sbwp, 0, sizeof g_sbwp); g_pend_gen = 1; } }
|
||||
@@ -2322,6 +2364,7 @@ static const char *cctx_snap(void); // What is in this submission (printed int
|
||||
typedef struct cbs_list cbs_list; // The game's shaders one command buffer encoded (defined before encode_args)
|
||||
static cbs_list *cbs_take(void);
|
||||
static void cbs_feedback(cbs_list *l, NSError *err, const char *where);
|
||||
static void cbs_fly_report(uint64_t fence); static void cbs_fly_put(uint64_t fence, const cbs_list *l); static void ind_fly_put(const char *key, uint64_t ind, uint64_t off, void *buf);
|
||||
static void lc_land(void);
|
||||
// A submission's CPU-side writes at its end (events, samples-passed and counter reports): run once, by its feedback handler or, when a game's SyncWait wakes on the
|
||||
// GPU's own signal of the fence first, by that waiter (DM_NVN_FAST_WAKE, on by default): the feedback handler comes 0.26 ms after the GPU end on an M2 Max
|
||||
@@ -2409,7 +2452,7 @@ uint64_t mtl_sub_commit(void) {
|
||||
[o addFeedbackHandler:^(id<MTL4CommitFeedback> f) { (void)f; atomic_fetch_sub(&g_seg_inflight, 1); for (dispatch_block_t block in commit_blocks) block(); }];
|
||||
uint64_t gpu_f = atomic_load(&g_cur_frame); gpu_tag_begin(gpu_f);
|
||||
NSString *cctx = @(cctx_snap());
|
||||
cbs_list *cbs = cbs_take();
|
||||
cbs_list *cbs = cbs_take(); cbs_fly_put(fence, cbs);
|
||||
seg_clk *sc = g_sclk; uint32_t seg_last = g_seg; g_sclk = NULL;
|
||||
pthread_mutex_lock(&g_post_mu);
|
||||
if (!atomic_load(&pr->claimed) && pr->fence) MDIE("post ring: the writes of fence %llu never ran", (unsigned long long)pr->fence);
|
||||
@@ -2475,7 +2518,20 @@ static int mtl_wait_at(uint64_t fence, uint64_t timeout_ns, int site) {
|
||||
dl.tv_sec += ns / 1000000000ull; dl.tv_nsec = ns % 1000000000ull;
|
||||
pthread_mutex_lock(&g_mu);
|
||||
int r = 0;
|
||||
while (g_done < fence) if ((r = pthread_cond_timedwait(&g_cv, &g_mu, &dl))) break;
|
||||
// An unbounded wait still waiting after 10 s is a hang: said once, with what it waits for (PRAGMATA's queue worker stopped here at its first 3D scene, no GPU error)
|
||||
struct timespec said; clock_gettime(CLOCK_REALTIME, &said); said.tv_sec += 10; int told = timeout_ns != UINT64_MAX;
|
||||
while (g_done < fence) {
|
||||
int late = !told && (dl.tv_sec > said.tv_sec || (dl.tv_sec == said.tv_sec && dl.tv_nsec > said.tv_nsec));
|
||||
if (!(r = pthread_cond_timedwait(&g_cv, &g_mu, late ? &said : &dl))) continue;
|
||||
if (!late) break;
|
||||
told = 1; static _Atomic int n;
|
||||
if (atomic_fetch_add(&n, 1) < 4) {
|
||||
uint64_t stuck = g_done + 1;
|
||||
MLOG("[RED] the host has waited 10 s for GPU work up to fence %llu (wait site %d): completed %llu, submitted %llu; the GPU runs nothing it can finish",
|
||||
(unsigned long long)fence, site, (unsigned long long)g_done, (unsigned long long)g_fence);
|
||||
pthread_mutex_unlock(&g_mu); cbs_fly_report(stuck); pthread_mutex_lock(&g_mu); // the list's lock is not taken under g_mu
|
||||
}
|
||||
}
|
||||
int ok = g_done >= fence;
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
if (ws_on()) { ws_put(site, w0, 1); if (site == WS_SYNC_NEWEST || site == WS_SYNC || site == WS_ACQ) ws_wake(fence); }
|
||||
@@ -2502,7 +2558,7 @@ void mtl_drain(void) { present_drop_for_suspend(); mtl_present_flush(); snap_dra
|
||||
|
||||
// ================= Render replay =================
|
||||
#include "../../host/front.h"
|
||||
static int g_red_once[165]; // one past the highest key: a new key raises this, and the macro refuses to compile otherwise
|
||||
static int g_red_once[166]; // one past the highest key: a new key raises this, and the macro refuses to compile otherwise
|
||||
#define RED_ONCE(k, ...) do { _Static_assert((k) < sizeof g_red_once / sizeof *g_red_once, "a RED_ONCE key past g_red_once: raise its size"); if (!g_red_once[k]++) MLOG("[RED] " __VA_ARGS__); } while (0)
|
||||
// NVN vertex streams 0–15 → Metal vertex buffer slots: 0–13 go to 16–29 (30 is the constant fallback buffer), 14 and 15 to 14 and 15. Metal has only the 31 slots 0–30; translated shaders use only buffer(0) (the argument buffer),
|
||||
// and the host's own vertex functions read no vertex buffers. 13 Sentinels uses stream 15, and the old 16 + stream went out of range (Metal assertion: buffer index (31) must be < 31)
|
||||
@@ -2909,13 +2965,18 @@ static int pkg_edges_clean(NvPkg *pk, const tex_t *t) { // the covered pages w
|
||||
// Usage an NVN image takes: shader writes, and for R32Uint / R32Sint the shader-atomic usage too, since Metal runs texture atomics only on such textures (dummy_img_atomic) and NVN does
|
||||
// not say which images a shader will use atomically
|
||||
static inline int pf_r32i(MTLPixelFormat pf) { return pf == MTLPixelFormatR32Uint || pf == MTLPixelFormatR32Sint; }
|
||||
// 64-bit texture atomics (texture2d<ulong>::atomic_max / atomic_min, MSL 3.1; dmsh_atomic.wide_atomics): Metal runs them on an RG32Uint texture made with the shader-atomic usage,
|
||||
// on Apple GPU family 9 (M3 / A17 Pro and later). PRAGMATA's visibility buffer (SURED.D.2D.MAX.U64, depth << 32 | ID) is an NVN RG32UI image. Older GPUs have no 64-bit texture
|
||||
// atomic at all (the pipeline does not build there), so their RG32Uint textures keep the usage they had. After uncraftablexd's PRAGMATA bring-up (PR #1801)
|
||||
static int dev_atomic64(void) { static int v = -1; if (v < 0 && g_dev) v = [g_dev supportsFamily:MTLGPUFamilyApple9] ? 1 : 0; return v > 0; }
|
||||
static inline int pf_atomic(MTLPixelFormat pf) { return pf_r32i(pf) || (pf == MTLPixelFormatRG32Uint && dev_atomic64()); }
|
||||
static MTLTextureUsage img_usage(const tex_t *t, MTLPixelFormat pf) {
|
||||
if (!(t->d.flags & NVN_TEXTURE_FLAGS_IMAGE)) return 0;
|
||||
return MTLTextureUsageShaderWrite | (pf_r32i(pf) ? MTLTextureUsageShaderAtomic : 0);
|
||||
return MTLTextureUsageShaderWrite | (pf_atomic(pf) ? MTLTextureUsageShaderAtomic : 0);
|
||||
}
|
||||
// Metal leaves MTLTextureUsageShaderAtomic out of a texture's usage property (0x3 for a texture made with 0x23), so it cannot be read back: every shader-writable R32Uint / R32Sint
|
||||
// texture the host makes has it (img_usage, tex_upgrade, dummy_img_atomic), and that is what this tests
|
||||
static int tex_atomic_capable(id<MTLTexture> base) { return pf_r32i(base.pixelFormat) && (base.usage & MTLTextureUsageShaderWrite); }
|
||||
static int tex_atomic_capable(id<MTLTexture> base) { return pf_atomic(base.pixelFormat) && (base.usage & MTLTextureUsageShaderWrite); } // RG32Uint too on Apple GPU family 9 (pf_atomic)
|
||||
// Metal runs texture atomics only on R32Uint / R32Sint storage, while NVN takes them on any 32-bit format through an R32 image: Ocarina of Time's NDSR upscaler ORs into an RGBA8 target (d17eefaff4f0bc23).
|
||||
// Such a texture moves to R32 storage, the same bytes, with its own format as a view for rendering and sampling (tex_upgrade). Not packaged textures: those are the guest's bytes, uploaded
|
||||
static int tex_atomic_alias(id<MTLTexture> base) {
|
||||
@@ -3000,7 +3061,7 @@ static id<MTLTexture> tex_upgrade(const tex_t *t, id<MTLTexture> asked, MTLTextu
|
||||
d.resourceOptions = base.resourceOptions; d.usage = base.usage | add | (tex_atomic_capable(base) ? MTLTextureUsageShaderAtomic : 0); // the usage property leaves the atomic usage out
|
||||
// A linear texture aliases the guest pool. Adding usage must keep that backing: a new standalone texture copies the old pixels once, but later GPU writes never reach the CPU map.
|
||||
id<MTLBuffer> backing = base.buffer;
|
||||
int reinterpret = (add & MTLTextureUsageShaderAtomic) && !pf_r32i(base.pixelFormat);
|
||||
int reinterpret = (add & MTLTextureUsageShaderAtomic) && !pf_atomic(base.pixelFormat); // an RG32Uint texture takes 64-bit atomics as it is (pf_atomic)
|
||||
if (reinterpret && (!tex_atomic_alias(base) || !pf_r32i(view_pf) || [holder isKindOfClass:[NvPkg class]])) return asked;
|
||||
id<MTLTexture> upgraded;
|
||||
if (reinterpret) {
|
||||
@@ -7137,7 +7198,7 @@ static struct {
|
||||
uint32_t st_vmask[2], st_wmask[2], st_ref[2];
|
||||
p_poly_offset po; float vp[16][4]; float dr[2]; int has_vp; int depth_clamp; uint8_t vp_sw[16][4]; // vp_sw: viewport swizzles XOR the identity (p_vp_swizzle)
|
||||
float blend_color[4], alpha_ref; int64_t copy_stride, copy_img_stride; // alpha_ref: SetAlphaRef (at_bind)
|
||||
uint8_t push[2][DMSH_PUSH_SIZE]; // NVN2 push constants of the graphics stages and of compute (p_push_const), bound as c[24]
|
||||
uint8_t push[2][DMSH_PUSH_BLOCKS * DMSH_PUSH_SIZE]; // NVN2 push constants of the graphics stages and of compute, both blocks (p_push_const), bound as c[24]
|
||||
p_tf_bind tf[4]; int tf_on, rast_discard; // capture buffers and enables; byte offsets and captured count stay on the GPU (nvn_feedback.inc)
|
||||
int tex_base, samp_base; // host-table bases of the texture / sampler pool bound (OP_SET_TEX_POOL / OP_SET_SAMP_POOL), for handles read at replay from uniform buffers (encode_args)
|
||||
} S;
|
||||
@@ -7369,7 +7430,7 @@ static void udc_note_draw(NvProg *pr, uint32_t raster_mask) {
|
||||
if (pr && !pr->c_iw) for (int st = 0; st < 6; st++) { __unsafe_unretained NvShader *sh = pr->sh[st]; if (!sh) continue;
|
||||
// A writable image, atomic image pointer or storage pointer may alias an attachment. Do not infer its identity from bound texture slots (bindless shaders need not use them).
|
||||
for (int i = 0; i < sh->rf.nb; i++) { const nvn_rbind *b = &sh->rf.b[i];
|
||||
if (b->rw && (b->kind == NVN_RB_IMG || b->kind == NVN_RB_IMGU || b->kind == NVN_RB_SBUFP || b->kind == NVN_RB_SBUFU || b->kind == NVN_RB_GMEM)) { image_write = 1; break; } }
|
||||
if (b->rw && (b->kind == NVN_RB_IMG || b->kind == NVN_RB_IMGU || b->kind == NVN_RB_SBUFP || b->kind == NVN_RB_SBUFU || b->kind == NVN_RB_SBUFQ || b->kind == NVN_RB_GMEM)) { image_write = 1; break; } }
|
||||
if (image_write) break;
|
||||
}
|
||||
if (pr && !pr->c_iw) pr->c_iw = (int8_t)(image_write + 1);
|
||||
@@ -10580,10 +10641,10 @@ static void image_prepare(NvProg *pr, unsigned stages) {
|
||||
// much as a linear one's pool memory. They used to go through a raw pointer beside the texture, which for a block-linear image (a deswizzled copy) could only be a scratch buffer
|
||||
// nothing read, and a 3D image's did not compile. Metal allows texture atomics only on an R32Uint / R32Sint texture made with the shader-atomic usage (img_usage); any other
|
||||
// texture in an atomic slot is replaced by an atomic-capable write sink, logged red, rather than left to the GPU's undefined behaviour
|
||||
static id<MTLTexture> dummy_img_atomic(int dtt, int dpf) {
|
||||
static __strong id<MTLTexture> cache[8][2];
|
||||
int s = dpf == NVN_DPF_SINT; id<MTLTexture> t = cache[dtt & 7][s]; if (t) return t;
|
||||
MTLPixelFormat pf = s ? MTLPixelFormatR32Sint : MTLPixelFormatR32Uint;
|
||||
static id<MTLTexture> dummy_img_atomic(int dtt, int dpf, int wide) { // wide: a 64-bit atomic's sink (RG32Uint; nvn_rbind atom 2)
|
||||
static __strong id<MTLTexture> cache[8][3];
|
||||
int s = wide && dev_atomic64() ? 2 : dpf == NVN_DPF_SINT; id<MTLTexture> t = cache[dtt & 7][s]; if (t) return t;
|
||||
MTLPixelFormat pf = s == 2 ? MTLPixelFormatRG32Uint : s ? MTLPixelFormatR32Sint : MTLPixelFormatR32Uint;
|
||||
MTLTextureUsage u = MTLTextureUsageShaderRead | MTLTextureUsageShaderWrite | MTLTextureUsageShaderAtomic;
|
||||
if ((MTLTextureType)dtt == MTLTextureTypeTextureBuffer) {
|
||||
MTLTextureDescriptor *d = [MTLTextureDescriptor textureBufferDescriptorWithPixelFormat:pf width:16 resourceOptions:MTLResourceStorageModePrivate usage:u];
|
||||
@@ -10598,7 +10659,8 @@ static id<MTLTexture> dummy_img_atomic(int dtt, int dpf) {
|
||||
}
|
||||
static int img_atomic_ok(id<MTLTexture> t, const nvn_rbind *b) {
|
||||
id<MTLTexture> base = t; while (base.parentTexture) base = base.parentTexture; // a view of a view: a descriptor of R32 over a texture moved to R32 storage has its colour view as parent (tex_upgrade)
|
||||
return pf_r32i(t.pixelFormat) && tex_atomic_capable(base) && t.textureType == (MTLTextureType)b->dtt && t.sampleCount == 1;
|
||||
int fmt = b->atom == 2 ? t.pixelFormat == MTLPixelFormatRG32Uint && dev_atomic64() : pf_r32i(t.pixelFormat); // atom 2: 64-bit atomics (texture2d<ulong>), see pf_atomic
|
||||
return fmt && tex_atomic_capable(base) && t.textureType == (MTLTextureType)b->dtt && t.sampleCount == 1;
|
||||
}
|
||||
// Snapshot substitution for same-pass feedback sampling (registered by fb_prepare, used by encode_args; see the notes before draw)
|
||||
static uint64_t g_draw_seq, g_fb_seq, g_fb_count; static int g_fb_n, g_fb_rebind;
|
||||
@@ -10751,6 +10813,7 @@ static void gml_read(id<MTLBuffer> b, id<MTLBuffer> map, int predicted, uint64_t
|
||||
pthread_mutex_lock(&g_mu); int p = pool_peek(e[0]); double age = p >= 0 ? (double)(now - g_pools[p].born) / 1e6 : -1; pthread_mutex_unlock(&g_mu);
|
||||
if (age >= 0) { if (age < age_lo) age_lo = age; if (age > age_hi) age_hi = age; }
|
||||
g_gml_lo[g_gml_n] = e[0]; g_gml_hi[g_gml_n++] = e[1]; added++;
|
||||
if (g_gml_n <= 64) MLOG("raw global memory: stores reach %#llx..%#llx (pool table entry %d)", (unsigned long long)e[0], (unsigned long long)e[1], i * 32 + __builtin_ctz(bits)); // which pools a store went to: a game's CPU data in one (PRAGMATA's draw items) means a misplaced store
|
||||
}
|
||||
// Once the prediction has begun, a pool found late is added and the prediction goes on: going back to a write anywhere until more logs agreed (8 then) made every geometry draw
|
||||
// after the stores wait for the GPU (geo_cpu_hazard), 400-2,000 ms frames for a second or more after each miss in Donkey Kong Bananza, and bought nothing, as the next late
|
||||
@@ -11012,7 +11075,10 @@ static uint64_t cbuf_slot(NvShader *sh, int nvn_stage, const nvn_rbind *b, __str
|
||||
int reg = b->reg; const p_bind_buf *u = reg < 16 ? &S.ubo[nvn_stage][reg] : NULL;
|
||||
void *mb; uint64_t mo, gpu;
|
||||
if (!u || !u->addr || !mtl_gpu_addr(u->addr, u->size ? u->size : 1, &mb, &mo, &gpu)) { // reads 0 (the all-zero bank), as an unbound texture slot does, instead of through a null pointer
|
||||
RED_ONCE(16, "stage %d cb%d has no uniform buffer bound", nvn_stage, reg); *use = zero_bank(); return zero_bank_gpu(); }
|
||||
if (!g_red_once[16]) { char note[400] = ""; if (u && u->addr) dm_gfx_addr_note(u->addr, note, sizeof note); // which shader, and what the address is (unbound, or in no pool)
|
||||
RED_ONCE(16, "stage %d cb%d has no uniform buffer bound: shader %s, address %#llx size %#llx (frame %llu)%s", nvn_stage, reg, sh->key, u ? (unsigned long long)u->addr : 0ull, u ? (unsigned long long)u->size : 0ull,
|
||||
(unsigned long long)atomic_load(&g_cur_frame), note); }
|
||||
*use = zero_bank(); return zero_bank_gpu(); }
|
||||
if (__builtin_expect(ub_bound(u->size) < 4u * b->fixw, 0)) { // bound shorter than the shader reads it at fixed offsets: those reads give 0, as on Maxwell
|
||||
void *rb; uint64_t ro, rg, live = u->size && mtl_gpu_addr(u->addr, ub_bound(u->size), &rb, &ro, &rg) && rb == mb ? ub_bound(u->size) : u->size; // the pool may end before the rounded size
|
||||
return ub_padded(sh, nvn_stage, reg, u, live, 4u * b->fixw, (const uint8_t *)[(__bridge id<MTLBuffer>)mb contents] + mo, use); }
|
||||
@@ -11048,6 +11114,36 @@ static int args_cbuf_only(NvShader *sh) {
|
||||
sh->ab_cbuf_only = ok && cb ? 1 : 2;
|
||||
return sh->ab_cbuf_only == 1;
|
||||
}
|
||||
// The shader lists of the last CBS_FLY committed command buffers, by fence: a hang report names what the command buffer it waits for runs (mtl_wait_at)
|
||||
#define CBS_FLY 64
|
||||
static struct { uint64_t fence; cbs_list *l; } g_cbs_fly[CBS_FLY]; static uint32_t g_cbs_fly_i;
|
||||
static void cbs_fly_put(uint64_t fence, const cbs_list *l) {
|
||||
if (!l) return;
|
||||
cbs_list *c = malloc(sizeof *c + l->n * sizeof *l->e); if (!c) return;
|
||||
memcpy(c, l, sizeof *c + l->n * sizeof *l->e);
|
||||
pthread_mutex_lock(&g_cbs_mu); uint32_t i = g_cbs_fly_i++ % CBS_FLY; free(g_cbs_fly[i].l); g_cbs_fly[i].fence = fence; g_cbs_fly[i].l = c; pthread_mutex_unlock(&g_cbs_mu);
|
||||
}
|
||||
// The last IND_FLY indirect dispatches (fence of their command buffer, shader, where the GPU reads the group counts): a hang report prints the counts as they are now
|
||||
#define IND_FLY 64
|
||||
static struct { uint64_t fence, ind, off; void *buf; char key[CBS_KEY]; } g_ind_fly[IND_FLY]; static uint32_t g_ind_fly_i;
|
||||
static void ind_fly_put(const char *key, uint64_t ind, uint64_t off, void *buf) {
|
||||
pthread_mutex_lock(&g_cbs_mu); uint32_t i = g_ind_fly_i++ % IND_FLY;
|
||||
g_ind_fly[i].fence = g_fence + 1; g_ind_fly[i].ind = ind; g_ind_fly[i].off = off; g_ind_fly[i].buf = buf; strlcpy(g_ind_fly[i].key, key, CBS_KEY);
|
||||
pthread_mutex_unlock(&g_cbs_mu);
|
||||
}
|
||||
static void cbs_fly_report(uint64_t fence) {
|
||||
pthread_mutex_lock(&g_cbs_mu);
|
||||
for (uint32_t i = 0; i < CBS_FLY; i++) if (g_cbs_fly[i].l && g_cbs_fly[i].fence == fence) {
|
||||
const cbs_list *l = g_cbs_fly[i].l; char b[CBS_SHOW * (CBS_KEY + 1) + 32], *e = b; *b = 0;
|
||||
for (uint32_t k = 0; k < l->n && k < CBS_SHOW; k++) e += snprintf(e, sizeof b - (size_t)(e - b), "%s%s", k ? " " : "", l->e[k].key);
|
||||
MLOG("[RED] game shaders of the command buffer of fence %llu: %u: %s%s", (unsigned long long)fence, l->n, l->n ? b : "none", l->n > CBS_SHOW ? " and more" : "");
|
||||
}
|
||||
for (uint32_t i = 0; i < IND_FLY; i++) if (g_ind_fly[i].buf && g_ind_fly[i].fence == fence) {
|
||||
const uint32_t *g = (const uint32_t *)((uint8_t *)[(__bridge id<MTLBuffer>)g_ind_fly[i].buf contents] + g_ind_fly[i].off);
|
||||
MLOG("[RED] its indirect dispatch of %s: %u x %u x %u groups now at %#llx", g_ind_fly[i].key, g[0], g[1], g[2], (unsigned long long)g_ind_fly[i].ind);
|
||||
}
|
||||
pthread_mutex_unlock(&g_cbs_mu);
|
||||
}
|
||||
static int encode_args_(id<MTLCommandEncoder> en, NvShader *sh, int nvn_stage, int metal_vertex);
|
||||
static int encode_args(id<MTLCommandEncoder> en, NvShader *sh, int nvn_stage, int metal_vertex) { cbs_note(sh); AP_B; int r = encode_args_(en, sh, nvn_stage, metal_vertex); AP_E(3); return r; }
|
||||
static int encode_args_(id<MTLCommandEncoder> en, NvShader *sh, int nvn_stage, int metal_vertex) {
|
||||
@@ -11167,7 +11263,7 @@ static int encode_args_(id<MTLCommandEncoder> en, NvShader *sh, int nvn_stage, i
|
||||
if (real) { id<MTLTexture> base = t; while (base.parentTexture) base = base.parentTexture;
|
||||
RED_ONCE(93, "image atomics on a texture Metal cannot run them on (shader %s stage %d slot %d texture ID %d: Metal format %lu of base format %lu, type %lu for %u, %s): they go to a write sink",
|
||||
sh->key, nvn_stage, reg, tid, (unsigned long)t.pixelFormat, (unsigned long)base.pixelFormat, (unsigned long)t.textureType, b->dtt, base.usage & MTLTextureUsageShaderWrite ? "shader-writable" : "not shader-writable"); }
|
||||
t = dummy_img_atomic(b->dtt, b->dpf); trid = t.gpuResourceID._impl; real = 0;
|
||||
t = dummy_img_atomic(b->dtt, b->dpf, b->atom == 2); trid = t.gpuResourceID._impl; real = 0;
|
||||
} else if (b->atom && !(sh->logged & 2)) { sh->logged |= 2; static int nlog; const tex_t *tt = tid < g_ntreg && g_treg[tid].ok ? &g_treg[tid].t : NULL;
|
||||
if (tt && nlog++ < 8) MLOG("shader %s (stage %d): image atomics on image slot %d, texture ID %d (target %d, %s, %llu bytes)", sh->key, nvn_stage, reg, tid, (int)tt->d.target,
|
||||
tt->d.target == NVN_TEXTURE_TARGET_BUFFER || (tt->d.flags & (NVN_TEXTURE_FLAGS_LINEAR | NVN_TEXTURE_FLAGS_LINEAR_RENDER_TARGET)) ? "linear" : "block-linear", (unsigned long long)tt->L.size); }
|
||||
@@ -11251,11 +11347,20 @@ static int encode_args_(id<MTLCommandEncoder> en, NvShader *sh, int nvn_stage, i
|
||||
else { slots[aid] = dummy_buf_gpu(); USE(dummy_buf(), MTLResourceUsageRead); }
|
||||
if (bl) PD("B %llu st%d sbufp reg%d %s addr=%#llx size=%llu %s", g_stat_pass, nvn_stage, reg, u && u->addr ? "real" : "dummy", u ? (unsigned long long)u->addr : 0ull, u ? (unsigned long long)u->size : 0ull, b->rw ? "rw" : "ro");
|
||||
} else if (b->kind == NVN_RB_SBUFU) { // B: a storage buffer whose GPU address the game keeps in its own uniform buffer (Monster Hunter Rise's compute shaders: c3 + 0x38); read like a bindless handle
|
||||
uint64_t addr; ubo_read(nvn_stage, reg, b->off, 8, &addr);
|
||||
uint64_t addr; ubo_read(nvn_stage, reg, b->off, 8, &addr); addr = ucb_handle_addr(addr);
|
||||
void *mb; uint64_t mo, gpu;
|
||||
if (addr && mtl_gpu_addr(addr, 1, &mb, &mo, &gpu)) { slots[aid] = gpu; USE((__bridge id<MTLBuffer>)mb, b->rw ? MTLResourceUsageRead | MTLResourceUsageWrite : MTLResourceUsageRead); if (b->rw) sbw_note(addr, sbw_len(0, mb, mo), SBW_GPU); } // size not known
|
||||
else { slots[aid] = dummy_buf_gpu(); USE(dummy_buf(), MTLResourceUsageRead); }
|
||||
if (bl) PD("B %llu st%d sbufu reg%d+%#x addr=%#llx %s", g_stat_pass, nvn_stage, reg, b->off, (unsigned long long)addr, b->rw ? "rw" : "ro");
|
||||
} else if (b->kind == NVN_RB_SBUFQ) { // B: a storage buffer whose GPU address the game pushed (c[24] at b->off, both blocks: PRAGMATA's compute buffer entries); resolved like NVN_RB_SBUFU
|
||||
uint64_t addr = 0; const uint8_t *pb = S.push[nvn_stage == 5 ? 1 : 0]; if (b->off + 8u <= sizeof S.push[0]) memcpy(&addr, pb + b->off, 8);
|
||||
addr = ucb_handle_addr(addr);
|
||||
void *mb; uint64_t mo, gpu;
|
||||
if (addr && mtl_gpu_addr(addr, 1, &mb, &mo, &gpu)) { slots[aid] = gpu; USE((__bridge id<MTLBuffer>)mb, b->rw ? MTLResourceUsageRead | MTLResourceUsageWrite : MTLResourceUsageRead); if (b->rw) sbw_note(addr, sbw_len(0, mb, mo), SBW_GPU); }
|
||||
else { slots[aid] = dummy_buf_gpu(); USE(dummy_buf(), MTLResourceUsageRead);
|
||||
if (!g_red_once[165]) { char note[400]; dm_gfx_addr_note(addr, note, sizeof note); // what is known of it: a sparse pool's page, a texture's storage
|
||||
RED_ONCE(165,"shader %s: the buffer address the game pushed at c[24] + %#x is %#llx, in no memory pool: bound to a dummy buffer (frame %llu;%s)", sh->key, b->off, (unsigned long long)addr, (unsigned long long)atomic_load(&g_cur_frame), note); } }
|
||||
if (bl) PD("B %llu st%d sbufq push+%#x addr=%#llx %s", g_stat_pass, nvn_stage, b->off, (unsigned long long)addr, b->rw ? "rw" : "ro");
|
||||
} else if (b->kind == NVN_RB_C1) { // B: the shader's own constant segment, built when the shader is fetched
|
||||
id<MTLBuffer> cb = sh->c1buf ? sh->c1buf : zero_bank(); // c1 has length 0 (600 of them in the whole library) yet the shader still declares it: reads 0
|
||||
slots[aid] = (sh->c1buf ? sh->c1_gpu : zero_bank_gpu()) + (sh->c1buf ? sh->c1off : 0);
|
||||
@@ -11271,8 +11376,8 @@ static int encode_args_(id<MTLCommandEncoder> en, NvShader *sh, int nvn_stage, i
|
||||
} else if (b->kind == NVN_RB_CBSIZE) { // the uniform slots' bound sizes (cbsize_table)
|
||||
id<MTLBuffer> db; slots[aid] = cbsize_table(nvn_stage, &db); USE(db, MTLResourceUsageRead);
|
||||
} else if (b->kind == NVN_RB_PUSH) { // NVN2 push constants (c[24]): the stage group's current block
|
||||
id<MTLBuffer> db; size_t doff = arena_alloc(DMSH_PUSH_SIZE, &db);
|
||||
memcpy(g_cur_arena->cpu + doff, S.push[nvn_stage == 5 ? 1 : 0], DMSH_PUSH_SIZE);
|
||||
id<MTLBuffer> db; size_t doff = arena_alloc(sizeof S.push[0], &db);
|
||||
memcpy(g_cur_arena->cpu + doff, S.push[nvn_stage == 5 ? 1 : 0], sizeof S.push[0]);
|
||||
slots[aid] = g_cur_arena->gpu + doff; USE(db, MTLResourceUsageRead);
|
||||
} else if (b->kind == NVN_RB_DRV0 || b->kind == NVN_RB_DRV2) {
|
||||
// NVN driver constant segments: those proven unread by static analysis at packaging time are supplied as 0; those read are filled on the spot from the current bindings - c0 = storage buffer table (base + 0x10 r: address 64 bits, size 32 bits),
|
||||
@@ -11303,8 +11408,12 @@ static int encode_args_(id<MTLCommandEncoder> en, NvShader *sh, int nvn_stage, i
|
||||
memcpy(d + DMSH_C0_DISPATCH, g_dispatch_dim, 12); g_c0_dim_buf = db; g_c0_dim_off = doff + DMSH_C0_DISPATCH;
|
||||
// NVN2 compute also reads them below its per-shader layout: a light culling shader's cluster is (z * c0[8] + y) * c0[4] + x, and at zero every cluster of a column wrote the same entry
|
||||
if (dm_sdk_ounce()) memcpy(d + DMSH_C0_DISPATCH_NVN2, g_dispatch_dim, 12);
|
||||
for (int r = 0; r < DMSH_C0_CS_UBO_SLOTS; r++) { uint64_t a = S.ubo[5][r].addr; uint32_t n = (uint32_t)S.ubo[5][r].size; memcpy(d + DMSH_C0_CS_UBO + DMSH_C0_ROW * r, &a, 8); memcpy(d + DMSH_C0_CS_UBO + DMSH_C0_ROW * r + 8, &n, 4); }
|
||||
}
|
||||
// Compute's uniform slots at 0x210 + 16 r (address 64 bits, size 32 bits). NVN2's compute shaders read a slot through its first 8 bytes as a bindless constant buffer
|
||||
// handle too (cx[UR], InstEmitAmpere.cs ABindlessConstant), which NVN2's driver writes there in the hardware's layout (ucb_handle); NVN's read the address itself
|
||||
// (Link's Awakening's c0[0x280]). NVN2's graphics stages read no such table: their bank holds the entries the game pushes (dmsh_abi.h DMSH_NVN2_STAGE_BANK)
|
||||
int ounce = dm_sdk_ounce();
|
||||
if (nvn_stage == 5) for (int r = 0; r < DMSH_C0_CS_UBO_SLOTS; r++) { uint64_t a = S.ubo[nvn_stage][r].addr; uint32_t n = (uint32_t)S.ubo[nvn_stage][r].size; if (ounce) a = ucb_handle(a, n); memcpy(d + DMSH_C0_CS_UBO + DMSH_C0_ROW * r, &a, 8); memcpy(d + DMSH_C0_CS_UBO + DMSH_C0_ROW * r + 8, &n, 4); }
|
||||
} else {
|
||||
// A shader with dynamic handle arrays (TEXD / SAMPD, profile key tex_dyn_slots) picks a table slot at run time and ORs a texture word with a sampler word into a handle,
|
||||
// whose texture / sampler IDs index the arrays. For it the tables hold slot indices instead of handles (texture slot r → r, and r << 20 when a combined handle carries
|
||||
@@ -13766,7 +13875,7 @@ static int csh_draw_reads(NvProg *pr, const p_draw *dw, const p_draw_idx *di, cs
|
||||
if (!t.serial || !csh_add(r, n, (uint64_t)t.mem, t.L.size)) return 0;
|
||||
break; }
|
||||
case NVN_RB_TEXU: case NVN_RB_TEXD: case NVN_RB_TEXA: return 0;
|
||||
case NVN_RB_SBUFP: case NVN_RB_SBUFU: case NVN_RB_IMG: case NVN_RB_TBUF: case NVN_RB_GMEM: return 0; // may write memory, or reads memory not listed here
|
||||
case NVN_RB_SBUFP: case NVN_RB_SBUFU: case NVN_RB_SBUFQ: case NVN_RB_IMG: case NVN_RB_TBUF: case NVN_RB_GMEM: return 0; // may write memory, or reads memory not listed here
|
||||
default: break; } } }
|
||||
return 1;
|
||||
}
|
||||
@@ -13777,7 +13886,7 @@ static int csh_cs(NvShader *cs, const p_dispatch *dp, csh_rng *w, int *nw, int *
|
||||
switch (b->kind) {
|
||||
case NVN_RB_SBUFP: if (b->reg >= 16 || csh_attachment_hit(S.ssbo[5][b->reg].addr, S.ssbo[5][b->reg].size) || !csh_add(w, nw, S.ssbo[5][b->reg].addr, S.ssbo[5][b->reg].size)) return 0; break;
|
||||
case NVN_RB_CBUF: case NVN_RB_UBOP: if (b->reg >= 16 || csh_attachment_hit(S.ubo[5][b->reg].addr, S.ubo[5][b->reg].size)) return 0; break;
|
||||
case NVN_RB_SBUFU: case NVN_RB_IMG: case NVN_RB_TEXU: case NVN_RB_TEXD: case NVN_RB_TEXA: case NVN_RB_GMEM: return 0;
|
||||
case NVN_RB_SBUFU: case NVN_RB_SBUFQ: case NVN_RB_IMG: case NVN_RB_TEXU: case NVN_RB_TEXD: case NVN_RB_TEXA: case NVN_RB_GMEM: return 0;
|
||||
case NVN_RB_TEX: case NVN_RB_TBUF: { uint64_t h = tex_slot_h(S.tex[5], S.img[5], b->reg); int tid = (int)(h & 0xfffff); if (!tid) break;
|
||||
os_unfair_lock_lock(&g_rmu); tex_t t = tid < g_ntreg && g_treg[tid].ok ? g_treg[tid].t : (tex_t){0}; os_unfair_lock_unlock(&g_rmu);
|
||||
if (!t.serial) return 0;
|
||||
@@ -14347,6 +14456,30 @@ static id<MTL4ComputeCommandEncoder> dispatch_enc(void) {
|
||||
args_dirty_all();
|
||||
return e;
|
||||
}
|
||||
// DM_CTL bufsnap (hle_hid.c): guest memory as the GPU leaves it right after the next dispatch of a shader, copied in the same encoder behind a barrier and saved when the
|
||||
// submission completes. A read of guest memory at some later moment sees what later work of the frame, or the next frame's clear, left there (PRAGMATA's culling chain)
|
||||
static pthread_mutex_t g_bs_mu = PTHREAD_MUTEX_INITIALIZER; static char g_bs_key[32], g_bs_path[512]; static uint64_t g_bs_addr; static size_t g_bs_n; static int g_bs_on;
|
||||
void dm_gfx_bufsnap(const char *key, uint64_t a, size_t n, const char *path) {
|
||||
pthread_mutex_lock(&g_bs_mu); snprintf(g_bs_key, sizeof g_bs_key, "%s", key); snprintf(g_bs_path, sizeof g_bs_path, "%s", path); g_bs_addr = a; g_bs_n = n; g_bs_on = 1; pthread_mutex_unlock(&g_bs_mu);
|
||||
MLOG("DM_CTL: bufsnap of %#llx + %zu bytes after the next dispatch of %s → %s", (unsigned long long)a, n, key, path);
|
||||
}
|
||||
static void bufsnap_after(NvShader *cs, id ce) {
|
||||
if (!g_bs_on) return;
|
||||
pthread_mutex_lock(&g_bs_mu);
|
||||
if (!g_bs_on || strncmp(cs->key, g_bs_key, strlen(g_bs_key))) { pthread_mutex_unlock(&g_bs_mu); return; }
|
||||
uint64_t a = g_bs_addr; size_t n = g_bs_n; NSString *path = @(g_bs_path); g_bs_on = 0; pthread_mutex_unlock(&g_bs_mu);
|
||||
void *mb; uint64_t mo;
|
||||
if (!n || !mtl_addr(a, n, &mb, &mo)) { MLOG("[RED] bufsnap: %#llx + %zu bytes is in no memory pool", (unsigned long long)a, n); return; }
|
||||
id<MTLBuffer> dst = [g_dev newBufferWithLength:n options:MTLResourceStorageModeShared];
|
||||
if (!dst) { MLOG("[RED] bufsnap: no buffer of %zu bytes", n); return; }
|
||||
res_add(dst); res_commit();
|
||||
[(id<MTL4ComputeCommandEncoder>)ce barrierAfterEncoderStages:MTLStageDispatch | MTLStageBlit beforeEncoderStages:MTLStageDispatch | MTLStageBlit visibilityOptions:blit_vis()];
|
||||
[(id<MTL4ComputeCommandEncoder>)ce copyFromBuffer:(__bridge id<MTLBuffer>)mb sourceOffset:mo toBuffer:dst destinationOffset:0 size:n];
|
||||
g_blit_ops = 1; // the next copy or dispatch is ordered after it
|
||||
NSString *key = @(cs->key);
|
||||
[g_commit_blocks addObject:^{ BOOL ok = [[NSData dataWithBytes:dst.contents length:n] writeToFile:path atomically:NO];
|
||||
MLOG("bufsnap after %s: %zu bytes %s %s", key.UTF8String, n, ok ? "saved to" : "could not be written to", path.UTF8String); }];
|
||||
}
|
||||
static void dispatch(const p_dispatch *dp) {
|
||||
zskip_clear();
|
||||
g_wr_epoch++; g_mdx_epoch++;
|
||||
@@ -14357,6 +14490,9 @@ static void dispatch(const p_dispatch *dp) {
|
||||
if (dp->ind) { static int once; if (!once++) MLOG("indirect dispatch: first time (the GPU reads the threadgroup counts from %#llx)", (unsigned long long)dp->ind); }
|
||||
NvShader *cs = prog_get(S.cprog)->sh[5];
|
||||
if (!cs) { RED_ONCE(28, "the dispatched program has no compute shader (or it is not mapped)"); return; }
|
||||
if (dp->ind) ind_fly_put(cs->key, dp->ind, io, ib);
|
||||
if (passdump()) { uint32_t n[3] = {0, 0, 0}; if (dp->ind && nvn_host_readable(dp->ind, 12)) memcpy(n, (const void *)(uintptr_t)dp->ind, 12);
|
||||
PD("g %llu dispatch %s %ux%ux%u indirect=%#llx (now %u %u %u)", g_stat_pass, cs->key, dp->x, dp->y, dp->z, (unsigned long long)dp->ind, n[0], n[1], n[2]); }
|
||||
int off = !border_need(cs, 5);
|
||||
cps_key k = {(__bridge const void *)cs, (uintptr_t)off};
|
||||
id<MTLComputePipelineState> ps = hm_get_id(&g_cps, &k);
|
||||
@@ -14429,6 +14565,7 @@ static void dispatch(const p_dispatch *dp) {
|
||||
[(id<MTL4ComputeCommandEncoder>)ce barrierAfterEncoderStages:MTLStageBlit beforeEncoderStages:MTLStageDispatch visibilityOptions:resource_vis()]; }
|
||||
enc_c_dispatch_indirect(ce, ig, MTLSizeMake(tg[0], tg[1], tg[2]));
|
||||
} else enc_c_dispatch(ce, MTLSizeMake(dp->x, dp->y, dp->z), MTLSizeMake(tg[0], tg[1], tg[2]));
|
||||
bufsnap_after(cs, ce);
|
||||
if (own) enc_c_end(ce);
|
||||
}
|
||||
// GPU: texture -> buffer (row stride taken from SetCopyRowStride, layer stride from SetCopyImageStride, 0 = tightly packed)
|
||||
@@ -14967,7 +15104,9 @@ static void dlss_eval(const p_dlss *c) {
|
||||
zskip_del(c->tex[DLSS_OUTPUT]->serial); sparse_gpu_wrote(c->tex[DLSS_OUTPUT]);
|
||||
NSUInteger iw = c->iw > 0 ? (NSUInteger)c->iw : col.width, ih = c->ih > 0 ? (NSUInteger)c->ih : col.height;
|
||||
rp_end(); if (g_blit) { enc_b_end(g_blit); g_blit = nil; }
|
||||
dlss_scaler *e = dep && mot ? dlss_scaler_for(c, col, dep, mot, out, iw, ih) : NULL;
|
||||
// Diagnostic DM_NVN_DLSS_BILINEAR=1 (off by default): every evaluation takes the bilinear stand-in below, to tell MetalFX's part in a GPU fault or stall
|
||||
static int bilinear = -1; if (bilinear < 0) { const char *be = getenv("DM_NVN_DLSS_BILINEAR"); bilinear = be && atoi(be); if (bilinear) MLOG("DM_NVN_DLSS_BILINEAR: DLSS drawn bilinear (diagnostic)"); }
|
||||
dlss_scaler *e = dep && mot && !bilinear ? dlss_scaler_for(c, col, dep, mot, out, iw, ih) : NULL;
|
||||
if (!e) {
|
||||
NVNcopyRegion sr = {c->base[DLSS_COLOR][0], c->base[DLSS_COLOR][1], 0, (int)iw, (int)ih, 1}, dr = {c->base[DLSS_OUTPUT][0], c->base[DLSS_OUTPUT][1], 0, (int)out.width, (int)out.height, 1};
|
||||
if (!(out.usage & MTLTextureUsageRenderTarget) && !mtl_fmt_block(out.pixelFormat) && !fmt_int_or_ds(out.pixelFormat)) out = tex_upgrade(c->tex[DLSS_OUTPUT], out, MTLTextureUsageRenderTarget, out.pixelFormat);
|
||||
@@ -15124,7 +15263,7 @@ static void sub_cut(void) {
|
||||
uint64_t f = atomic_load(&g_cur_frame); gpu_tag_begin(f);
|
||||
uint32_t k = g_seg++; seg_clk *sc = NULL; // reports encoded so far keep this segment's GPU times (seg_ts)
|
||||
if (seg_ts()) { if (!g_sclk) { g_sclk = calloc(1, sizeof *g_sclk); if (!g_sclk) MDIE("segment clock allocation failed"); atomic_store(&g_sclk->refs, 1); } sc = g_sclk; atomic_fetch_add(&sc->refs, 1); if (k < SEG_CLK_N) sc->cm[sc->ncm++] = (uint16_t)k; } // this command buffer ends with segment k (seg_idle_before)
|
||||
cbs_list *cbs = cbs_take(); uint64_t cbs_fence = g_fence + 1;
|
||||
cbs_list *cbs = cbs_take(); uint64_t cbs_fence = g_fence + 1; cbs_fly_put(cbs_fence, cbs);
|
||||
MTL4CommitOptions *o = [MTL4CommitOptions new];
|
||||
atomic_fetch_add(&g_seg_inflight, 1);
|
||||
[o addFeedbackHandler:^(id<MTL4CommitFeedback> cb) {
|
||||
@@ -15673,6 +15812,27 @@ void dm_gfx_texlist(int target) {
|
||||
t->d.width, t->d.height, t->d.depth, t->d.format, t->d.levels, t->d.flags, (void *)t->mem, (unsigned long long)t->L.size, t->L.tileH, t->L.tileD); }
|
||||
os_unfair_lock_unlock(&g_rmu);
|
||||
}
|
||||
// For the crash dump (crash.c): what is known of an address. Read without the locks (the process is going), so a table being changed at that moment may print nonsense, never fault
|
||||
// on a freed table: g_pools and g_treg are only reallocated, and both are read through their current pointer and count
|
||||
void dm_gfx_addr_note(uint64_t a, char *note, size_t n) {
|
||||
size_t k = 0; note[0] = 0;
|
||||
#define NOTE(...) do { if (k < n) { int w = snprintf(note + k, n - k, __VA_ARGS__); if (w > 0) k += (size_t)w; } } while (0)
|
||||
const pool_ent *pl = g_pools; int np = g_npool;
|
||||
for (int i = 0; pl && i < np; i++) if (a >= pl[i].lo && a < pl[i].hi) { NOTE(" memory pool %#lx..%#lx (+%#llx)", (unsigned long)pl[i].lo, (unsigned long)pl[i].hi, (unsigned long long)(a - pl[i].lo)); break; }
|
||||
const treg_t *tr = g_treg; int nt = g_ntreg, shown = 0;
|
||||
for (int i = 1; tr && i < nt && shown < 2; i++) { const tex_t *t = &tr[i].t; uint64_t m = (uint64_t)(uintptr_t)t->mem;
|
||||
if (tr[i].ok && m && a >= m && a < m + t->L.size) { NOTE(" texture ser=%llu %ux%u format %#x storage +%#llx", (unsigned long long)t->serial, t->d.width, t->d.height, t->d.format, (unsigned long long)(a - m)); shown++; } }
|
||||
uint64_t pg = a >> 12, done = atomic_load(&g_done); const gw_ent *e = &g_gw[gw_slot(pg)];
|
||||
if (e->page == pg || e->page == ~0ull) NOTE(" GPU write recorded on the page%s: fence %llu (completed %llu, last %llu)", e->page == ~0ull ? " (shared slot)" : "", (unsigned long long)e->fence, (unsigned long long)done, (unsigned long long)mtl_last_fence());
|
||||
for (int i = 0; i < GWW_N; i++) if (g_gww[i].fence && a >= g_gww[i].lo && a < g_gww[i].hi) NOTE(" in a large GPU write %#llx..%#llx: fence %llu", (unsigned long long)g_gww[i].lo, (unsigned long long)g_gww[i].hi, (unsigned long long)g_gww[i].fence);
|
||||
id<MTLBuffer> gm = g_gmem_buf; // the raw global memory table (gmem_map): what a raw load or store of the address reaches
|
||||
if (gm) { const uint64_t *t = (const uint64_t *)gm.contents; int hit = 0;
|
||||
for (int k = 1; k < DMSH_GMEM_MAP_ENTRIES && t[(size_t)k * (DMSH_GMEM_MAP_ENTRY / 8)] != ~0ull; k++) { const uint64_t *e = t + (size_t)k * (DMSH_GMEM_MAP_ENTRY / 8); if (a >= e[0] && a < e[1]) { hit = k; break; } }
|
||||
if (hit) NOTE(" raw memory table entry %d", hit);
|
||||
else NOTE(" in no raw memory table entry (a raw load reads 0, a store is dropped)%s", addr_meets((uintptr_t)a, (uintptr_t)a + 1) ? "" : "; no pool address given in it"); }
|
||||
{ char vn[200]; void nvn_vpool_note(uint64_t, char *, size_t); nvn_vpool_note(a, vn, sizeof vn); NOTE("%s", vn); }
|
||||
#undef NOTE
|
||||
}
|
||||
void dm_gfx_texdump_next(const char *path) {
|
||||
if (g_td_frame == -2) td_note(nil, 0); // read DM_NVN_TEXDUMP first, so it does not override the request
|
||||
g_td_path = strdup(path); g_td_list = [NSMutableArray array]; g_td_done = 0; g_td_frame = (long)atomic_load(&g_cur_frame) + 1;
|
||||
|
||||
@@ -14,7 +14,9 @@
|
||||
typedef struct { uint32_t flags; } dev_builder_t; FITS(dev_builder_t, NVNdeviceBuilder);
|
||||
typedef struct { uint32_t magic, flags, origin, depth_mode; void *dbg_cb, *dbg_data; } dev_t_; FITS(dev_t_, NVNdevice);
|
||||
|
||||
typedef struct { NVNdevice *dev; uint32_t flags; uint64_t cmd_sz, comp_sz, ctl_sz, flush; void *mem; uint64_t mem_sz; } queue_builder_t;
|
||||
// The memory sizes as the driver keeps them: 32-bit, 0 until set, with a flag each that a setter sets (hle_nvn.c, nvnQueueBuilderGet*MemorySize); the queue's own defaults apply at use
|
||||
enum { QB_CMD, QB_COMP, QB_CTL, QB_RT };
|
||||
typedef struct { NVNdevice *dev; uint32_t flags; uint32_t sz[4], flush; uint8_t set[4]; void *mem; uint64_t mem_sz; } queue_builder_t;
|
||||
FITS(queue_builder_t, NVNqueueBuilder);
|
||||
typedef struct { uint32_t magic; NVNdevice *dev; uint64_t submits; int origin_ll; uint64_t serial; } queue_t; FITS(queue_t, NVNqueue);
|
||||
|
||||
@@ -267,7 +269,7 @@ typedef struct { const tex_t *tex[DLSS_TEXTURES]; uint64_t net; int32_t iw, ih,
|
||||
typedef struct { uint64_t addr, size; uint32_t value, _pad; } p_clear_buf; // buffer filled with a 32-bit value (ClearBuffer)
|
||||
typedef struct { float rgba[4]; } p_blend_color;
|
||||
typedef struct { float ref; } p_alpha_ref;
|
||||
typedef struct { uint16_t compute, offset; uint32_t size; uint8_t data[]; } p_push_const; // NVN2 push constants: the bytes at offset in the graphics or compute block (DMSH_PUSH_*) // SetAlphaRef: the reference of the alpha test (ColorStateSetAlphaTest; nvn_mtl.m at_bind)
|
||||
typedef struct { uint16_t compute, offset; uint32_t size; uint8_t data[]; } p_push_const; // NVN2 push constants: the bytes at offset in the graphics or compute group's c[24] (block b at b * DMSH_PUSH_SIZE) // SetAlphaRef: the reference of the alpha test (ColorStateSetAlphaTest; nvn_mtl.m at_bind)
|
||||
typedef struct { int32_t index, pad; uint64_t addr, size; } p_tf_bind; // BindTransformFeedbackBuffer(s): one record per buffer (index 0-3)
|
||||
typedef struct { int32_t what, pad; uint64_t ctl; } p_tf_state; // what: 0 begin, 1 end, 2 pause, 3 resume; ctl = the game's 32-byte control buffer
|
||||
typedef struct { int32_t on; } p_rast_discard;
|
||||
|
||||
@@ -12,7 +12,7 @@ typedef struct nq_node {
|
||||
struct nq_node *next;
|
||||
uint8_t *bytes; size_t length, capacity;
|
||||
unsigned kind, mode, closed, waiting; volatile uint32_t *event; uint32_t value;
|
||||
uint64_t wait_fence, event_predecessor; unsigned wait_kind; const sync_t *sync_source; nq_receipt *receipt;
|
||||
uint64_t wait_fence, event_predecessor, wait_since; unsigned wait_kind, wait_said; const sync_t *sync_source; nq_receipt *receipt;
|
||||
nq_signal *signals; unsigned signal_count; // NQ_COMMANDS: every event signal it records, in order (nq_event_issued at its commit)
|
||||
tex_t texture; double period; int crop[4];
|
||||
} nq_node;
|
||||
@@ -130,10 +130,20 @@ static void *nq_worker(void *unused) {
|
||||
// for the writer's completion left the GPU idle while the host encoded the next submission, 2 ms of its 14.5 ms frame, which its dynamic resolution read as work
|
||||
nq_event_write *queued=predecessor>mtl_completed_fence() ? nq_event_write_of(n->event) : NULL;
|
||||
if(queued && queued->exact && nq_predicate(queued->value,n->mode,n->value)) break;
|
||||
if(predecessor>mtl_completed_fence() || !nq_predicate(atomic_load_explicit((_Atomic uint32_t *)n->event,memory_order_acquire),n->mode,n->value)) { n->waiting=1; mapped_event_wait=1; continue; }
|
||||
if(predecessor>mtl_completed_fence() || !nq_predicate(atomic_load_explicit((_Atomic uint32_t *)n->event,memory_order_acquire),n->mode,n->value)) {
|
||||
// A queue held more than 5 s by one event wait: what it waits for, since the game's own GPU watchdog acts on the fences behind it (PRAGMATA aborts after 15 s)
|
||||
uint64_t t=now_ns(); if(!n->wait_since) n->wait_since=t;
|
||||
else if(t-n->wait_since>5000000000ull && !n->wait_said) { static _Atomic int said; n->wait_said=1; if(atomic_fetch_add(&said,1)<8)
|
||||
LOG("[RED] queue %llu: an event wait has held it %.1f s: word %p is %#x, waiting for %s %#x; a GPU write of it is %s",(unsigned long long)q->serial,(t-n->wait_since)/1e9,(void *)n->event,
|
||||
atomic_load_explicit((_Atomic uint32_t *)n->event,memory_order_acquire),n->mode==0?"equal to":"at least",n->value,predecessor>mtl_completed_fence()?"queued, not completed":"not queued"); }
|
||||
n->waiting=1; mapped_event_wait=1; continue; }
|
||||
}
|
||||
if(n->kind==NQ_SYNC) {
|
||||
if(n->receipt && !n->receipt->published) continue;
|
||||
if(n->receipt && !n->receipt->published) {
|
||||
uint64_t t=now_ns(); if(!n->wait_since) n->wait_since=t;
|
||||
else if(t-n->wait_since>5000000000ull && !n->wait_said) { static _Atomic int said; n->wait_said=1; if(atomic_fetch_add(&said,1)<8)
|
||||
LOG("[RED] queue %llu: a sync wait has held it %.1f s: the fence it waits for (receipt %p) is not published yet",(unsigned long long)q->serial,(t-n->wait_since)/1e9,(void *)n->receipt); }
|
||||
continue; }
|
||||
// Targets are immutable snapshots. One Metal queue orders an encoded producer before this continuation. A sync not yet fenced when the wait was submitted
|
||||
// (wait_kind 0) is a snapshot of nothing to wait for, and the wait passes. Sparking! ZERO, on one NVN queue, waits on a sync before that queue's own first
|
||||
// fence of it at its first load, which runs on the console; parked here, the fence behind the wait never published and its SyncWait stalled the game (#1808)
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
#include <stdint.h>
|
||||
|
||||
enum { NVN_RB_CBUF = 1, NVN_RB_SAMP, NVN_RB_TEX, NVN_RB_IMG, NVN_RB_TBUF,
|
||||
NVN_RB_SBUFP, NVN_RB_SUPPORT, NVN_RB_C1, NVN_RB_DRV0, NVN_RB_DRV2, NVN_RB_SAMPT, NVN_RB_UBOP, NVN_RB_TEXU, NVN_RB_SAMPU, NVN_RB_SAMPI, NVN_RB_SBUFU, NVN_RB_TEXD, NVN_RB_SAMPD, NVN_RB_TEXA, NVN_RB_SAMPA, NVN_RB_GEOMETRY, NVN_RB_TEXP, NVN_RB_SAMPP, NVN_RB_TEXH, NVN_RB_SAMPH, NVN_RB_BORDER, NVN_RB_PUSH, NVN_RB_GMEM, NVN_RB_GMEML, NVN_RB_IMGU, NVN_RB_TBUFU, NVN_RB_CBSIZE };
|
||||
NVN_RB_SBUFP, NVN_RB_SUPPORT, NVN_RB_C1, NVN_RB_DRV0, NVN_RB_DRV2, NVN_RB_SAMPT, NVN_RB_UBOP, NVN_RB_TEXU, NVN_RB_SAMPU, NVN_RB_SAMPI, NVN_RB_SBUFU, NVN_RB_TEXD, NVN_RB_SAMPD, NVN_RB_TEXA, NVN_RB_SAMPA, NVN_RB_GEOMETRY, NVN_RB_TEXP, NVN_RB_SAMPP, NVN_RB_TEXH, NVN_RB_SAMPH, NVN_RB_BORDER, NVN_RB_PUSH, NVN_RB_GMEM, NVN_RB_GMEML, NVN_RB_IMGU, NVN_RB_TBUFU, NVN_RB_CBSIZE, NVN_RB_SBUFQ };
|
||||
// IMGU / TBUFU: an image / a buffer texture whose handle the game keeps in uniform slot reg at byte off, as TEXU (Unreal Engine 5.4 on the Switch 2 keeps every image in c[3]). Read at encode time
|
||||
// GMEM: the host's memory pool table for global memory the translator traced to no storage buffer (dmsh_abi.h DMSH_GMEM_MAP_*, nvn_mtl.m gmem_map_gpu): the shader may read, and with rw
|
||||
// write, anything in any pool. GMEML: the write log of those stores (dmsh_abi.h DMSH_GMEM_LOG_*, nvn_mtl.m gml_take)
|
||||
@@ -39,7 +39,7 @@ typedef struct {
|
||||
uint16_t soff; // TEXA / SAMPA: c2 byte of a separate sampler word ORed into every element's handle (handle type 1), 0 = none; TEXU / SAMPU: byte of the other word ORed into the handle (handle type 1) + 1, in uniform slot sreg (DMSH_SREG_C2: SAMPU's sampler is the word at that c2 byte), 0 = none
|
||||
uint8_t sreg;
|
||||
uint8_t f1d; // TEX: read by 1D integer fetches as 2D rows of 16384 texels (dmsh_build.py "fetch1d"): a buffer texture here is bound as such rows (nvn_mtl.m tbuf_as_2d)
|
||||
uint8_t atom; // IMG: the shader runs image atomics on it (dmsh_build.py "atomic"): the texture must allow Metal's texture atomics (nvn_mtl.m dummy_img_atomic)
|
||||
uint8_t atom; // IMG: the shader runs image atomics on it (dmsh_build.py "atomic"): the texture must allow Metal's texture atomics (nvn_mtl.m dummy_img_atomic); 2: 64-bit ones (texture2d<ulong>, an RG32Uint texture: pf_atomic)
|
||||
uint16_t fixw; // CBUF: the slot's words the shader reads at fixed offsets, from its start to the end of the highest (dmsh_reflect.py "fixed"): a binding shorter than that is encoded with zeros up to there (nvn_mtl.m ub_padded)
|
||||
uint8_t bw; // SAMP / SAMPT / SAMPU / SAMPI: a twin sampler for border colours (dmsh_rewrite.py border_emu), its bit in the BORDER block + 1; 0 = an ordinary sampler binding
|
||||
} nvn_rbind;
|
||||
|
||||
@@ -20,7 +20,7 @@ static void dummy_kind(NSString *t, uint8_t *tt, uint8_t *pf) {
|
||||
else if ([t hasPrefix:@"texture1d"]) y = MTLTextureType1D;
|
||||
else if ([t hasPrefix:@"texture_buffer"]) y = MTLTextureTypeTextureBuffer;
|
||||
*tt = (uint8_t)y;
|
||||
*pf = [t hasPrefix:@"depth"] ? NVN_DPF_DEPTH : [t containsString:@"<uint"] ? NVN_DPF_UINT : [t containsString:@"<int"] ? NVN_DPF_SINT : NVN_DPF_FLOAT;
|
||||
*pf = [t hasPrefix:@"depth"] ? NVN_DPF_DEPTH : [t containsString:@"<uint"] || [t containsString:@"<ulong"] ? NVN_DPF_UINT : [t containsString:@"<int"] ? NVN_DPF_SINT : NVN_DPF_FLOAT;
|
||||
}
|
||||
|
||||
// array<element, n> → n and the element type (0 and the type itself for anything else)
|
||||
@@ -89,14 +89,15 @@ int nvn_refl_from_json(NSDictionary *j, nvn_refl *o, char *err, int errlen) {
|
||||
if (r->kind == NVN_RB_TEXA) dummy_kind(el, &r->dtt, &r->dpf);
|
||||
}
|
||||
else if ([k isEqualToString:@DMSH_KIND_IMG]) { r->kind = NVN_RB_IMG; dummy_kind(b[@"msl_type"], &r->dtt, &r->dpf); // rw: the shader writes it (access::write / read_write; a load-only view of the slot is not)
|
||||
r->rw = [ty isKindOfClass:[NSString class]] && ([ty containsString:@"access::write"] || [ty containsString:@"access::read_write"]); r->atom = [b[@"atomic"] boolValue]; }
|
||||
r->rw = [ty isKindOfClass:[NSString class]] && ([ty containsString:@"access::write"] || [ty containsString:@"access::read_write"]); r->atom = [b[@"atomic"] boolValue] ? ([ty isKindOfClass:[NSString class]] && [ty containsString:@"<ulong"] ? 2 : 1) : 0; } // 2: 64-bit atomics (texture2d<ulong>)
|
||||
else if ([k isEqualToString:@DMSH_KIND_TBUF]) { r->kind = NVN_RB_TBUF; uint8_t tt; dummy_kind(b[@"msl_type"], &tt, &r->dpf); }
|
||||
else if ([k isEqualToString:@DMSH_KIND_IMG_UBO]) { r->kind = NVN_RB_IMGU; dummy_kind(b[@"msl_type"], &r->dtt, &r->dpf); r->off = (uint16_t)[b[@"off"] intValue]; o->bindless = 1;
|
||||
r->rw = [ty isKindOfClass:[NSString class]] && ([ty containsString:@"access::write"] || [ty containsString:@"access::read_write"]); r->atom = [b[@"atomic"] boolValue]; }
|
||||
r->rw = [ty isKindOfClass:[NSString class]] && ([ty containsString:@"access::write"] || [ty containsString:@"access::read_write"]); r->atom = [b[@"atomic"] boolValue] ? ([ty isKindOfClass:[NSString class]] && [ty containsString:@"<ulong"] ? 2 : 1) : 0; } // 2: 64-bit atomics (texture2d<ulong>)
|
||||
else if ([k isEqualToString:@DMSH_KIND_TBUF_UBO]) { r->kind = NVN_RB_TBUFU; uint8_t tt; dummy_kind(b[@"msl_type"], &tt, &r->dpf); r->off = (uint16_t)[b[@"off"] intValue]; o->bindless = 1; }
|
||||
else if ([k isEqualToString:@DMSH_KIND_SBUF]) { r->kind = NVN_RB_SBUFP; r->rw = sbuf_rw(b); }
|
||||
else if ([k isEqualToString:@DMSH_KIND_UBO_PTR]) r->kind = NVN_RB_UBOP;
|
||||
else if ([k isEqualToString:@DMSH_KIND_SBUF_UBO]) { r->kind = NVN_RB_SBUFU; r->rw = sbuf_rw(b); r->off = (uint16_t)[b[@"off"] intValue]; }
|
||||
else if ([k isEqualToString:@DMSH_KIND_SBUF_PUSH]) { r->kind = NVN_RB_SBUFQ; r->rw = sbuf_rw(b); r->off = (uint16_t)[b[@"off"] intValue]; }
|
||||
else if ([k isEqualToString:@DMSH_KIND_GEOMETRY]) { if (reg < 0 || reg > 4) FAIL("invalid geometry helper slot"); r->kind = NVN_RB_GEOMETRY; }
|
||||
else if ([k isEqualToString:@DMSH_KIND_SUPPORT]) r->kind = NVN_RB_SUPPORT;
|
||||
else if ([k isEqualToString:@DMSH_KIND_GMEM_MAP]) { r->kind = NVN_RB_GMEM; r->rw = [b[@"rw"] boolValue]; }
|
||||
|
||||
@@ -899,7 +899,7 @@ int main(void) {
|
||||
|
||||
// 6. Sync / window / present
|
||||
NVNsync s1, s2; P(nvnSyncInitialize)(&s1, &dev); P(nvnSyncInitialize)(&s2, &dev);
|
||||
EXPECT("wait on an unfenced sync = timeout (2)", 2, P(nvnSyncWait)(&s1, 0));
|
||||
EXPECT("wait on a sync never fenced since Initialize = already signaled (0)", 0, P(nvnSyncWait)(&s1, 0)); // the console's driver initializes it signalled (docs/reference/nvn-objects.md)
|
||||
P(nvnQueueFenceSync)(&q, &s1, NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE, 0);
|
||||
EXPECT("wait after fence = already signaled (0)", 0, P(nvnSyncWait)(&s1, 0));
|
||||
NVNtexture sc[2]; NVNtextureBuilder tb; P(nvnTextureBuilderSetDevice)(&tb, &dev); P(nvnTextureBuilderSetDefaults)(&tb);
|
||||
|
||||
@@ -240,6 +240,36 @@ class DirectedRounding(Alu):
|
||||
self.assertNotIn('& 65535', self.kept(self.F2F_RN, srcs=(19,)))
|
||||
|
||||
|
||||
class Frnd(Alu):
|
||||
"""FRND rounds a float to an integer value; FRND.F16 does so on a half (PRAGMATA: 65 shaders did not translate). The half is rounded in 32 bits and packed, which is
|
||||
exact. PRAGMATA's encodings (000ff000001008000000000400057307 and, with .FLOOR, 000e2600001048000000000c00257307) with the registers of this file"""
|
||||
F16 = (0x000fe20000100800, 0x0000001300067307) # FRND.F16 R6, R19
|
||||
F16_FLOOR = (0x000fe20000104800, 0x0000001300067307) # FRND.F16.FLOOR R6, R19
|
||||
F32 = (0x000fe20000201000, 0x0000001300067307) # FRND R6, R19
|
||||
|
||||
def test_a_half_is_unpacked_rounded_and_packed(self):
|
||||
msl = self.kept(self.F16, srcs=(19,))
|
||||
self.assertRegex(msl, r'float2\(as_type<half2>\(as_type<uint>\(_\d+\)\)\)\.x')
|
||||
self.assertRegex(msl, r'half2\(float2\(_\d+, 0\.0\)\)')
|
||||
self.assertIn('rint(', msl)
|
||||
|
||||
def test_a_half_floor(self):
|
||||
self.assertIn('floor(', self.kept(self.F16_FLOOR, srcs=(19,)))
|
||||
|
||||
def test_a_float_stays_a_float(self):
|
||||
msl = self.kept(self.F32, srcs=(19,))
|
||||
self.assertIn('rint(', msl); self.assertNotIn('half2', msl)
|
||||
|
||||
|
||||
class I2fImmediate(Alu):
|
||||
"""I2F of an immediate (form 4): bits 32..63 are the value, so 60..62 select no byte. PRAGMATA's I2F.F16.S32 of -2 (000e620000200c00fffffffe000f7906, 3 compute
|
||||
shaders) was refused as a byte select of a 32-bit source"""
|
||||
I2F_F16_M2 = (0x000fe20000200c00, 0xfffffffe00067906) # I2F.F16.S32 R6, -2
|
||||
|
||||
def test_translates(self):
|
||||
self.kept(self.I2F_F16_M2)
|
||||
|
||||
|
||||
class CompareFtz(Alu):
|
||||
"""FSETP / FSET .FTZ (bit 80): a denormal operand compares as zero, as on NVIDIA; Apple's GPUs keep denormals. Mario Kart World's deferred lighting 635061c90d75a8d1
|
||||
normalises its four depth-weighted samples by 1 / sum only where FSETP.NEU.FTZ says sum != 0: a denormal sum passed, its reciprocal overflowed, and the NaN came out
|
||||
@@ -286,5 +316,36 @@ class Vote(Alu):
|
||||
self.assertIn('simd_any', self.kept(self.FSETP, self.VOTE, self.MOV_P0, srcs=(6, 19, 20)))
|
||||
|
||||
|
||||
class SingleInstructionSemantics(Alu):
|
||||
"""Constant inputs the translator folds, the result stored (R6). From uncraftablexd's offline per-instruction tester (PR #1800: single instructions with nvdisasm-checked
|
||||
encodings run on the GPU against an interpreter on Mesa NAK's folds).
|
||||
- SETP's two results: Pd1 reads the accumulator P as it was, also when Pd0 is P (Pd1 was computed after Pd0 had been written).
|
||||
- IMAD has no negation of B: bit 63 (B a register, constant or uniform register) and bit 75 (B the 64-slot register of forms 2, 3, 7) are not printed
|
||||
by nvdisasm and are not modifiers; B was negated."""
|
||||
SEL_P0 = (0x000fc200040000ff, 0x00000001ff067807) # SEL R6, RZ, 0x1, !P0: R6 = P0 ? 1 : 0
|
||||
P2_TRUE = (0x000fc20003f42070, 0x000000ffff00720c) # ISETP.EQ.U32.AND P2, PT, RZ, RZ, PT: P2 = true
|
||||
MOV_R5_3 = (0x000fc20000000fff, 0x00000003ff057802) # MOV R5, 0x3
|
||||
|
||||
def stored(self, *code):
|
||||
m = re.findall(r'\] = (\w+);', self.kept(*code))
|
||||
return m[-1] if m else None
|
||||
|
||||
def test_isetp_second_result_reads_the_old_accumulator(self):
|
||||
isetp = (0x000fc2000104507f, 0x000000ffffff720c) # ISETP.NE.U32.AND P2, P0, RZ, RZ, P2: P2 = false AND P2, P0 = true AND the old P2 (true)
|
||||
self.assertEqual(self.stored(self.P2_TRUE, isetp, self.SEL_P0), '1u')
|
||||
|
||||
def test_fsetp_second_result_reads_the_old_accumulator(self):
|
||||
fsetp = (0x000fc200010450ff, 0x000000ffffff720b) # FSETP.NE.AND P2, P0, RZ, RZ, P2
|
||||
self.assertEqual(self.stored(self.P2_TRUE, fsetp, self.SEL_P0), '1u')
|
||||
|
||||
def test_imad_bit_63_is_no_negation(self):
|
||||
imad = (0x000fc200078e02ff, 0x8000000505067224) # IMAD R6, R5, R5, RZ with bit 63 set: 9, not -9
|
||||
self.assertEqual(self.stored(self.MOV_R5_3, imad), '9u')
|
||||
|
||||
def test_imad_bit_75_of_the_c_slot_forms_is_no_negation(self):
|
||||
imad = (0x000fc200078e0a05, 0x0000000105067424) # IMAD R6, R5, R5, 0x1 (form 2) with bit 75 set: 10, not -8
|
||||
self.assertEqual(self.stored(self.MOV_R5_3, imad), '10u')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -15,7 +15,7 @@ def inst(hi, lo): return struct.pack('<QQ', lo, hi)
|
||||
|
||||
@unittest.skipUnless(os.environ.get('DMSH_TEST_XLATE'), 'set DMSH_TEST_XLATE to the offline translator')
|
||||
class Translated(unittest.TestCase):
|
||||
def translate(self, code, **extra):
|
||||
def translate(self, code, atomics=False, **extra):
|
||||
with tempfile.TemporaryDirectory(prefix='ampere_mem_') as d:
|
||||
work = Path(d); (work / 'k.bin').write_bytes(code)
|
||||
# c0 layout (QueryAmpereComputeC0Layout): no uniform or storage buffers, 3 texture handles from 0x10, image handles from 0x28 (word 12 = image slot 1), 0x40 bytes
|
||||
@@ -27,10 +27,21 @@ class Translated(unittest.TestCase):
|
||||
self.res = json.loads((work / 'k.res.json').read_text()) # the translator's own report of the shader
|
||||
sys.path.insert(0, str(TOOLS)); import dmsh_geometry
|
||||
dmsh_geometry.flatten_sets(work / 'k.spv')
|
||||
r = subprocess.run([str(TOOLS / 'spirv_cross_bin/spirv-cross'), '--msl', '--msl-version', '20300', '--msl-argument-buffers', '--msl-texture-buffer-native',
|
||||
str(work / 'k.spv')], capture_output=True, text=True)
|
||||
xc = ['--msl', '--msl-version', '20300', '--msl-argument-buffers', '--msl-texture-buffer-native']
|
||||
if atomics: # as dmsh_build runs it for image atomics: MSL 3.1 and the native-atomic checks and rewrites (dmsh_atomic.py)
|
||||
import dmsh_atomic
|
||||
xc = dmsh_atomic.cross_args(xc, str(work / 'k.spv'))
|
||||
r = subprocess.run([str(TOOLS / 'spirv_cross_bin/spirv-cross'), *xc, str(work / 'k.spv')], capture_output=True, text=True)
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
return r.stdout
|
||||
return dmsh_atomic.check_msl(r.stdout) if atomics else r.stdout
|
||||
|
||||
def refused(self, code): # the translator's output for code it refuses
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
(Path(d) / 'k.bin').write_bytes(code)
|
||||
(Path(d) / 'jobs.json').write_text(json.dumps([dict(key='k', stage='cs', arch='sm86', code=str(Path(d) / 'k.bin'), tex={}, img={}, attr={}, fout={}, local=[32, 1, 1], nvn2_cs=[0, 0, 3, 0x40, 0])]))
|
||||
r = subprocess.run([os.environ['DMSH_TEST_XLATE'], str(Path(d) / 'jobs.json'), d], capture_output=True, text=True)
|
||||
self.assertFalse((Path(d) / 'k.spv').exists(), r.stdout + r.stderr)
|
||||
return r.stdout + r.stderr
|
||||
|
||||
|
||||
class GuardedWrites(Translated):
|
||||
@@ -57,6 +68,19 @@ class GuardedWrites(Translated):
|
||||
for code in ((0x000f4200081e0f04, 0x3000040702067f63), (0x000142000c1e03ff, 0x2000040400167f6c), (0x00014200001e0f12, 0x3800001002101364)): # TLD4 and TXD through a uniform register, TLD4 through a register
|
||||
self.translate(inst(*code) + inst(*EXIT))
|
||||
|
||||
def test_a_computed_handle_reads_the_pools(self):
|
||||
# R16 = c4[0] & 0x7fff | 0x10800000, a heap index clamped and ORed with sampler 0x108 (PRAGMATA's RE Engine materials), then TLD4 through R16: a handle no table holds, which
|
||||
# BindlessElimination deleted (its result read 0); a sampled texture's ID indexes the texture pool whatever made it
|
||||
mov, mask, sampler = (0x000fe20000000f00, 0x0100000000107a02), (0x000fe400078ec0ff, 0x00007fff10107812), (0x000fe400078efcff, 0x1080000010107812)
|
||||
tld4 = (0x00014200001e0f12, 0x3800001002101364) # write barrier 5, which the SUATOM after it waits on (it adds what the TLD4 read)
|
||||
msl = self.translate(inst(*mov) + inst(*mask) + inst(*sampler) + inst(*tld4) + inst(0x020ea200001ee000, 0x00000c10030c7593) + inst(*EXIT))
|
||||
self.assertIn('cb0_40000000', msl) # the pool arrays (dmsh_build.py pool_arrays makes them pointers)
|
||||
self.assertIn('gather(', msl)
|
||||
|
||||
def test_size_query_through_a_uniform_register_translates(self): # TXQ R10, UR6, R10 (0xf6f; PRAGMATA, as encoded there): the size of a texture the pools hold
|
||||
msl = self.translate(inst(0x000f4200080001ff, 0x000006000a0a7f6f) + inst(SUATOM[0], 0x00000c0a030c7593) + inst(*EXIT)) # the size added by an image atomic, so it stays
|
||||
self.assertIn('get_width(', msl)
|
||||
|
||||
def test_lod_query_handle_forms_translate(self): # TMML through a uniform register and a register (Kirby Air Riders' 4,776 pixel shaders, as encoded there)
|
||||
for code in ((0x000f4200080002ff, 0x600004ff20277f69), (0x000f4200000002ff, 0x68000018141d736a)):
|
||||
self.translate(inst(*code) + inst(*EXIT))
|
||||
@@ -119,14 +143,6 @@ class Suatom(Translated):
|
||||
def test_sured_takes_its_operation(self): # SURED.OR.U32 as Yoshi and the Mysterious Book's compute shaders encode it, in bank 3
|
||||
self.assertIn('atomic_fetch_or', self.translate(inst(0x000fe2000310e000, 0xa0c002010800759f) + inst(*EXIT)))
|
||||
|
||||
def test_sured_u64_is_still_refused(self): # the MAX.U64 of its Nanite shaders: no 64-bit image atomics here yet
|
||||
code = inst(0x000fe2000110e400, 0xa0c002010800759f) + inst(*EXIT)
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
(Path(d) / 'k.bin').write_bytes(code)
|
||||
(Path(d) / 'jobs.json').write_text(json.dumps([dict(key='k', stage='cs', arch='sm86', code=str(Path(d) / 'k.bin'), tex={}, img={}, attr={}, fout={}, local=[32, 1, 1], nvn2_cs=[0, 0, 3, 0x40, 0])]))
|
||||
r = subprocess.run([os.environ['DMSH_TEST_XLATE'], str(Path(d) / 'jobs.json'), d], capture_output=True, text=True)
|
||||
self.assertIn('SURED form', r.stdout + r.stderr)
|
||||
|
||||
def test_add_u32_on_a_1d_image(self):
|
||||
msl = self.translate(inst(*SUATOM) + inst(*EXIT))
|
||||
self.assertIn('atomic_fetch_add', msl) # native (the build's options) or through spirv-cross's buffer alias (these defaults)
|
||||
@@ -180,6 +196,7 @@ class PixelCovered(unittest.TestCase):
|
||||
"""0x925 as Star Fox's quad efficiency views encode it (826168691af2e211 +0x0): 1 for a covered pixel, 0 for a helper invocation"""
|
||||
COVERED = (0x040e0200000e4000, 0x0000000000007925)
|
||||
OTHER = (0x040e0200000e8000, 0x0000000000007925) # bits 78..80 = 2, not seen
|
||||
SAMPLE = (0x040e0200000ec000, 0x0000000000007925) # bits 78..80 = 3: the sample index
|
||||
SPH = struct.pack('<32I', *([0x000c5482] + [0] * 4 + [0xb0000000] + [0] * 12 + [0xf] + [0] * 13)) # the game's: writes colour 0
|
||||
|
||||
def run_job(self, *ops):
|
||||
@@ -205,6 +222,11 @@ class PixelCovered(unittest.TestCase):
|
||||
self.assertIsNone(msl)
|
||||
self.assertIn('0x925 form 2', log)
|
||||
|
||||
def test_form_3_reads_the_sample_index(self): # PRAGMATA's a689530d00090ebf +0x0 (into R2 there, R0 here: colour 0's x, so it stays)
|
||||
msl, log = self.run_job(self.SAMPLE)
|
||||
self.assertIsNotNone(msl, log)
|
||||
self.assertIn('[[sample_id]]', msl)
|
||||
|
||||
|
||||
@unittest.skipUnless(os.environ.get('DMSH_TEST_XLATE'), 'set DMSH_TEST_XLATE to the offline translator')
|
||||
class DepthRegister(unittest.TestCase):
|
||||
@@ -282,6 +304,12 @@ class StageMemory(Translated):
|
||||
def test_word_store_goes_to_the_outputs(self): # 0x120 + 0x80
|
||||
self.assertIn('0 + 416', self.msl(self.ATTRIBUTE))
|
||||
|
||||
READBACK = (0x000fe6000000f800, 0x00018000ff087923) # ISBERD R8, [RZ + 0x180], mode 0xf8 (PRAGMATA 5aab38bb5ba67ef7 +0x1680, its base register made RZ): a position word read back
|
||||
KEEP_R8 = (0x0041e8000000b800, 0x00001008ff007927) # 0x927 [RZ + 0x10], R8, mode 0xb8
|
||||
|
||||
def test_an_attribute_word_is_read_back_from_the_outputs(self): # 0x120 + 0x180 = word 168
|
||||
self.assertRegex(self.msl(self.READBACK, self.KEEP_R8), r'as_type<float>\(_\d+\[168\]\)')
|
||||
|
||||
def test_the_zero_count_is_left_out(self): # threads are not in step on Metal: it could land after the real count, and the stage memory starts at zero
|
||||
without = self.msl(self.COUNT)
|
||||
with_zero = self.msl(self.COUNT_ZERO, self.COUNT)
|
||||
@@ -290,6 +318,19 @@ class StageMemory(Translated):
|
||||
def test_a_byte_goes_through_its_word_atomically(self): # neighbouring threads write neighbouring bytes; the shader build makes the helper's loop one byte store (test_dmsh_shared_store.py)
|
||||
self.assertIn('atomic_compare_exchange', self.msl(self.INDEX))
|
||||
|
||||
def test_vertex_records_go_to_their_soa_word(self): # a mesh shader's mode 0xb8 (PRAGMATA 6adf14e9a4100082): records of 6 words from 0x200, 128 vertices
|
||||
mesh = self.translate(inst(*self.PAYLOAD) + inst(*EXIT), stage_memory=[0, 0x10, 0x120, 0x400, 0x200, 6, 128 * 24], shared=0x800)
|
||||
self.assertRegex(mesh, r'< 3072u') # inside the 128 * 24 bytes of records only
|
||||
self.assertRegex(mesh, r'\* 43691u?\b') # v = w * ceil(2^18 / 6) >> 18
|
||||
self.assertRegex(mesh, r'\* 768u?\b') # a block of 32 vertices: 6 components of 0x80 bytes
|
||||
self.assertNotRegex(self.msl(self.PAYLOAD), r'43691') # a task's mode 0xb8 is its payload, as before
|
||||
|
||||
def test_vertex_records_of_many_components_divide_exactly(self): # 51 components, 160 vertices: the reciprocal gives vertex 109 for word 5609 (110 * 51 = 5610 > 5609 >= 109 * 51 + 50)
|
||||
mesh = self.translate(inst(*self.PAYLOAD) + inst(*EXIT), stage_memory=[0, 0x10, 0x120, 0x400, 0x200, 51, 160 * 4 * 51], shared=0x8000)
|
||||
self.assertRegex(mesh, r'< 32640u') # inside the records only
|
||||
self.assertNotRegex(mesh, r'\* %du?\b' % (((1 << 18) + 50) // 51)) # no reciprocal
|
||||
self.assertRegex(mesh, r'/ 51\b') # an integer division
|
||||
|
||||
def test_outside_a_task_or_mesh_shader_it_is_refused(self):
|
||||
with self.assertRaises(AssertionError) as e: self.translate(inst(*self.PAYLOAD) + inst(*EXIT))
|
||||
self.assertIn('outside a task or mesh shader', str(e.exception))
|
||||
@@ -556,5 +597,70 @@ class Pokopia(Translated):
|
||||
self.assertRegex(self.msl(self.MEMBAR, self.ERRBAR), r'threadgroup_barrier|atomic_thread_fence')
|
||||
|
||||
|
||||
# SURED.D.2D.MAX.U64.STRONG.GPU.IGN [R0], R2 (PRAGMATA's visibility buffer, 336 shaders: 002292c6b1542bce +0x3510 has 0001e2000110e400600034020000059f, handle 0x34 and
|
||||
# predicated on P0), here unpredicated on the image whose handle is word 12 of c0 (image slot 1): coordinate R0, R1; value R2 (low word), R3 (high word). After uncraftablexd's PR #1801
|
||||
SURED_MAX_U64 = (0x0001e2000110e400, 0x60000c020000759f)
|
||||
SURED_MIN_U64 = (SURED_MAX_U64[0] & ~(0x1f << 23) | 1 << 23, SURED_MAX_U64[1]) # operation 87..91: 1 = MIN
|
||||
SURED_ADD_U64 = (SURED_MAX_U64[0] & ~(0x1f << 23), SURED_MAX_U64[1]) # 0 = ADD: Metal has no 64-bit texture add
|
||||
SURED64 = (mov(0, 5), mov(1, 2), mov(2, 0xffffffff), mov(3, 1), inst(*SURED_MAX_U64))
|
||||
|
||||
|
||||
class Sured64(Translated):
|
||||
"""64-bit image max / min: one texture2d<ulong> atomic on the rg32ui image, low word then high word (dmsh_atomic.wide_atomics, nvn_mtl.m pf_atomic)"""
|
||||
def msl(self, *code):
|
||||
return self.translate(b''.join(code) + inst(*EXIT), atomics=True)
|
||||
|
||||
def test_max_is_one_64_bit_texture_atomic(self):
|
||||
msl = self.msl(*SURED64)
|
||||
self.assertIn('texture2d<ulong, access::read_write> cp_i_tcb_4A_rg32ui', msl)
|
||||
self.assertEqual(len(re.findall(r'\.atomic_max\(uint2\(\w+\), ulong4\(as_type<ulong>\(uint2\(4294967295u, 1u\)\)\)\);', msl)), 1)
|
||||
self.assertNotIn('atomic_fetch', msl)
|
||||
|
||||
def test_bounds_guard_stays(self): # IGN: outside the image nothing is written
|
||||
self.assertRegex(self.msl(*SURED64), r'if \(all\(uint2\(\w+\) < uint2\(spvDescriptorSet0\.cp_i_tcb_4A_rg32ui\.get_width\(\), spvDescriptorSet0\.cp_i_tcb_4A_rg32ui\.get_height\(\)\)\)\)')
|
||||
|
||||
def test_min(self):
|
||||
msl = self.msl(mov(0, 5), mov(1, 2), mov(2, 6), mov(3, 7), inst(*SURED_MIN_U64))
|
||||
self.assertRegex(msl, r'\.atomic_min\(uint2\(\w+\), ulong4\(as_type<ulong>\(uint2\(6u, 7u\)\)\)\);')
|
||||
|
||||
def test_add_is_refused(self):
|
||||
self.assertIn('Metal 64-bit image atomics', self.refused(b''.join((mov(0, 5), mov(1, 2), inst(*SURED_ADD_U64), inst(*EXIT)))))
|
||||
|
||||
|
||||
class WideAtomics(unittest.TestCase):
|
||||
"""dmsh_atomic.wide_atomics on the shape SPIRV-Cross writes, and its refusals (no translator needed)"""
|
||||
DECL = 'struct spvDescriptorSetBuffer0\n{\n texture2d<uint, access::read_write> cp_i_tcb_4A_rg32ui [[id(0)]];\n};\n'
|
||||
GUARD = ' if (all(uint2(_29) < uint2(spvDescriptorSet0.cp_i_tcb_4A_rg32ui.get_width(), spvDescriptorSet0.cp_i_tcb_4A_rg32ui.get_height())))\n {\n'
|
||||
PAIR = (' uint _40 = spvDescriptorSet0.cp_i_tcb_4A_rg32ui.atomic_fetch_max(uint2(_29), uint(_12)).x;\n'
|
||||
' uint _41 = spvDescriptorSet0.cp_i_tcb_4A_rg32ui.atomic_fetch_max(uint2(_29), as_type<uint>(f(_13, 2))).x;\n')
|
||||
|
||||
def wide(self, body):
|
||||
sys.path.insert(0, str(TOOLS)); import dmsh_atomic
|
||||
return dmsh_atomic.wide_atomics(self.DECL + self.GUARD + body + ' }\n')
|
||||
|
||||
def test_pair(self):
|
||||
out = self.wide(self.PAIR)
|
||||
self.assertIn('texture2d<ulong, access::read_write> cp_i_tcb_4A_rg32ui', out)
|
||||
self.assertIn('spvDescriptorSet0.cp_i_tcb_4A_rg32ui.atomic_max(uint2(_29), ulong4(as_type<ulong>(uint2(uint(_12), as_type<uint>(f(_13, 2))))));', out)
|
||||
self.assertNotIn('atomic_fetch', out)
|
||||
|
||||
def test_a_lone_32_bit_atomic_fails(self):
|
||||
with self.assertRaisesRegex(ValueError, 'not the translator'):
|
||||
self.wide(self.PAIR.split('\n')[0] + '\n')
|
||||
|
||||
def test_halves_on_different_texels_fail(self):
|
||||
with self.assertRaisesRegex(ValueError, 'different texels'):
|
||||
self.wide(self.PAIR.replace('(uint2(_29), as_type', '(uint2(_30), as_type'))
|
||||
|
||||
def test_another_access_fails(self):
|
||||
with self.assertRaisesRegex(ValueError, 'accesses of a 64-bit atomic image'):
|
||||
self.wide(self.PAIR + ' uint4 _50 = spvDescriptorSet0.cp_i_tcb_4A_rg32ui.read(uint2(_29));\n')
|
||||
|
||||
def test_32_bit_images_are_left_alone(self):
|
||||
sys.path.insert(0, str(TOOLS)); import dmsh_atomic
|
||||
src = self.DECL.replace('rg32ui', 'r32ui') + ' uint _40 = spvDescriptorSet0.cp_i_tcb_4A_r32ui.atomic_fetch_max(uint2(_29), 1u).x;\n'
|
||||
self.assertEqual(dmsh_atomic.wide_atomics(src), src)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -14,7 +14,8 @@ TOOLS = Path(__file__).resolve().parents[1] / 'tools'
|
||||
sys.path.insert(0, str(TOOLS))
|
||||
from dmsh_rewrite import gather_offsets, gather_quad # noqa: E402
|
||||
# the Mac compile's flags, from the build's own line (dmsh_build.py runs a build when imported)
|
||||
MAC_METAL = next(ast.literal_eval(n.value) for n in ast.parse((TOOLS / 'dmsh_build.py').read_text()).body
|
||||
import dmsh_chain # noqa: E402 (the line names its deployment target, dmsh_chain.MAC_MIN_FLAG)
|
||||
MAC_METAL = next(eval(compile(ast.Expression(n.value), 'dmsh_build.py', 'eval'), {'dmsh_chain': dmsh_chain}) for n in ast.parse((TOOLS / 'dmsh_build.py').read_text()).body
|
||||
if isinstance(n, ast.Assign) and getattr(n.targets[0], 'id', None) == 'MAC_METAL')
|
||||
|
||||
HEAD = '''#include <metal_stdlib>
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env python3
|
||||
"""dmsh_rewrite.py membar_fence: the device-scope threadgroup_barrier SPIRV-Cross prints for OpMemoryBarrier (MEMBAR) becomes a device-scope fence, a MEMBAR.SC + ERRBAR pair
|
||||
becomes one, and a real barrier (BAR.SYNC: threadgroup_barrier(mem_flags::mem_threadgroup)) stays. With DMSH_TEST_METAL=1 the result also compiles with the Metal compiler.
|
||||
Adapted from uncraftablexd's test in the PRAGMATA bring-up (PR #1407)."""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
TOOLS = Path(__file__).resolve().parents[1] / 'tools'
|
||||
sys.path.insert(0, str(TOOLS))
|
||||
import dmsh_rewrite
|
||||
membar_fence, MEMBAR = dmsh_rewrite.membar_fence, dmsh_rewrite._MEMBAR
|
||||
FENCE = 'atomic_thread_fence(mem_flags::mem_device | mem_flags::mem_threadgroup | mem_flags::mem_texture, memory_order_seq_cst, thread_scope_device);'
|
||||
BAR = 'threadgroup_barrier(mem_flags::mem_threadgroup);'
|
||||
|
||||
# The shape of PRAGMATA's culling queue 12a52b683eec95c1: a persistent loop polling a done flag, MEMBAR.SC.GPU; ERRBAR at the end of its body, no BAR.SYNC
|
||||
QUEUE = """#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
struct B { uint _m0[1024]; };
|
||||
struct spvDescriptorSetBuffer0 { device B* cp_s0 [[id(0)]]; };
|
||||
|
||||
kernel void main0(constant spvDescriptorSetBuffer0& spvDescriptorSet0 [[buffer(0)]], uint3 gl_LocalInvocationID [[thread_position_in_threadgroup]])
|
||||
{
|
||||
do
|
||||
{
|
||||
uint _7 = atomic_fetch_or_explicit((device atomic_uint*)&(*spvDescriptorSet0.cp_s0)._m0[512], 0u, memory_order_relaxed);
|
||||
if (_7 != 0u)
|
||||
{
|
||||
break;
|
||||
}
|
||||
(*spvDescriptorSet0.cp_s0)._m0[gl_LocalInvocationID.x] = _7;
|
||||
MEMBAR_LINE
|
||||
MEMBAR_LINE
|
||||
} while (true);
|
||||
BAR_LINE
|
||||
}
|
||||
""".replace('MEMBAR_LINE', MEMBAR).replace('BAR_LINE', BAR)
|
||||
|
||||
|
||||
class MembarFence(unittest.TestCase):
|
||||
def test_a_membar_becomes_a_device_fence(self):
|
||||
out = membar_fence(QUEUE)
|
||||
self.assertNotIn(MEMBAR, out)
|
||||
self.assertEqual(out.count(FENCE), 1) # MEMBAR.SC and ERRBAR's pair: one fence
|
||||
self.assertIn(BAR, out) # BAR.SYNC stays a barrier
|
||||
|
||||
def test_a_shader_without_one_is_unchanged(self):
|
||||
src = QUEUE.replace(MEMBAR, '')
|
||||
self.assertEqual(membar_fence(src), src)
|
||||
|
||||
@unittest.skipUnless(os.environ.get('DMSH_TEST_METAL') and shutil.which('xcrun'), 'set DMSH_TEST_METAL=1 to compile with the Metal compiler')
|
||||
def test_the_fence_compiles(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p = Path(d) / 'q.metal'; p.write_text(membar_fence(QUEUE))
|
||||
r = subprocess.run(['xcrun', '-sdk', 'macosx', 'metal', '-c', str(p), '-o', str(Path(d) / 'q.air')], capture_output=True, text=True)
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -2,6 +2,7 @@
|
||||
"""NVN2 task and mesh shaders as Metal stage functions (dmsh_meshstage.py), on the shape of Mario Kart World's: the control section's facts, the SPH's outputs, the stage memory's layout
|
||||
and the wrapper's entry points. When the Metal compiler is installed, the stages compile for macOS and iOS."""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
@@ -83,6 +84,47 @@ class Facts(unittest.TestCase):
|
||||
lay, size = ms.memory(i)
|
||||
self.assertEqual(lay[3], lay[2] + 5 * 0x80); self.assertEqual(size, lay[3] + 4 + 32)
|
||||
|
||||
def test_primitive_system_value_has_room(self):
|
||||
# PRAGMATA 5aab38bb5ba67ef7 (and 493 more): 128 vertices of a position, 126 primitives, a per-primitive SPH enabling only the primitive array id (0x35 bit 0).
|
||||
# Its code writes vertex v at (v / 32) * 0x200 + 0x80 * c and primitive p's id at 0x800 + (p / 32) * 0x80 + 4 * (p % 32) from the outputs: the id must not
|
||||
# reach the primitive bytes (before, the count byte was 0x893, inside primitive 0's id, so every workgroup drew nothing)
|
||||
area = sph(0xf0) + sph(0x01)
|
||||
i = ms.info(control(7, payload=128, max_v=128, max_p=126, prim_at=0x80), area)
|
||||
self.assertEqual((i['primitive'], i['primitive_system']), ([], 1))
|
||||
lay, size = ms.memory(i)
|
||||
self.assertEqual(lay[2], 0x90); self.assertEqual(lay[3], 0x90 + 0x800 + 4 * 0x80)
|
||||
last_id = lay[2] + 0x800 + (125 // 32) * 0x80 + 4 * (125 % 32)
|
||||
self.assertLess(last_id + 4, lay[3] + 1)
|
||||
src = ms.to_stage(KERNEL % (size // 4, lay[3] // 4), i)
|
||||
self.assertIn('uint b = 36u + (n / 32u) * 128u + n % 32u;', src) # the vertex blocks keep their 0x200 bytes
|
||||
self.assertIn(f'uint np = min(_23[{lay[3] // 4}] >> 24, 126u);', src)
|
||||
self.assertIn(f'uint at = {lay[3] + 4}u + n;', src)
|
||||
|
||||
def test_without_per_primitive_components_unchanged(self): # the same shader without a per-primitive SPH keeps the layout it had
|
||||
i = ms.info(control(7, payload=128, max_v=128, max_p=126), sph(0xf0))
|
||||
lay, size = ms.memory(i); self.assertEqual((lay[:4], size), ([0, 0x10, 0x90, 0x890], 0x890 + 4 + 3 * 128)) # index bytes for whole primitive blocks (d365496d); [4..6]: the vertex records (test_mesh_vertex_records)
|
||||
|
||||
def test_system_values_of_an_sph(self):
|
||||
self.assertEqual(ms.sph_system(sph(0xf1)), [8]); self.assertEqual(ms.sph_system(sph(0xf0)), [])
|
||||
|
||||
def test_mesh_vertex_records(self): # PRAGMATA 6adf14e9a4100082's shape: 128 vertices of 6 components. Its non-skew attribute stores (mode 0xb8) name vertex records from
|
||||
# the end of its own SoA area, 24 bytes a vertex: [4..6] tell the translator where (AosToSoa)
|
||||
lay, _ = ms.memory(ms.info(control(7, payload=128, max_v=128, max_p=64), sph(0xf0, b'\x30')))
|
||||
self.assertEqual(lay[4:], [lay[3] - lay[2], 6, 128 * 24])
|
||||
lay, _ = ms.memory(ms.info(control(7, payload=128, max_v=128, max_p=128), sph(0xf0))) # 4fcffc73d65dc1ed's shape: 4 components
|
||||
self.assertEqual(lay[4:], [lay[3] - lay[2], 4, 128 * 16])
|
||||
self.assertEqual(len(ms.memory(ms.info(control(6), bytes(0x80)))[0]), 4) # a task's mode 0xb8 is its payload: no records
|
||||
|
||||
def test_vertex_record_to_soa_word(self): # InstEmitAmpereMem.cs AosToSoa's arithmetic: v = w * ceil(2^18 / n) >> 18 is w / n for every record word a Metal mesh can have
|
||||
for n in range(1, 33):
|
||||
m = ((1 << 18) + n - 1) // n
|
||||
for v in range(256):
|
||||
for c in range(n):
|
||||
w = v * n + c; vv = (w * m) >> 18
|
||||
self.assertEqual((vv, w - vv * n), (v, c))
|
||||
n = 6; m = ((1 << 18) + n - 1) // n; rel = 37 * 24 + 5 * 4; w = rel >> 2; v = (w * m) >> 18 # vertex 37, component 5: block 1, lane 5
|
||||
self.assertEqual((v >> 5) * n * 0x80 + (v & 31) * 4 + (w - v * n) * 0x80, 0x300 + 5 * 4 + 5 * 0x80)
|
||||
|
||||
def test_largest_of_the_game_fits_metal(self): # c34e01565dac1124: 256 vertices, 192 primitives
|
||||
i = ms.info(control(7, max_v=256, max_p=192), sph(0xf0, b'\x00\x0f'))
|
||||
self.assertLessEqual(ms.memory(i)[1], ms.METAL_MAX_SHARED)
|
||||
@@ -118,6 +160,14 @@ class Stage(unittest.TestCase):
|
||||
def test_memory_starts_at_zero(self): # the count byte relies on it (InstEmitAmpereMem.cs AStageOut)
|
||||
self.assertIn('_23[i] = 0u;', self.task()[0])
|
||||
|
||||
def test_loop_guard_counter_before_the_stage_memory(self): # dmsh_build.py loop_guard runs first: its counter comes before the array and stays in the body
|
||||
i = ms.info(control(6), bytes(0x80))
|
||||
src = (KERNEL % (ms.memory(i)[1] // 4, ms.memory(i)[0][2] // 4 + 1)).replace('{\n threadgroup', '{\n uint dm_lg = 0u; (void)dm_lg;\n threadgroup', 1)
|
||||
out = ms.to_stage(src, i)
|
||||
body = out[out.index('void dm_stage_body('):]
|
||||
self.assertIn('uint dm_lg = 0u; (void)dm_lg;', body[:body.index('\n}')])
|
||||
self.assertIn('[[object]] void main0(', out)
|
||||
|
||||
def test_mesh_has_both_depth_conventions(self):
|
||||
src, _ = self.mesh()
|
||||
gl, z = src.split('[[mesh]] void main0_z(')
|
||||
@@ -189,6 +239,13 @@ class Stage(unittest.TestCase):
|
||||
s = bytearray(0x80); s[0x18] = 0x03; s[0x18 + 3] = 0xaa; s[0x18 + 4] = 0x2a
|
||||
self.assertEqual(ms.pixel_reads(bytes(s)), {0: 1, 3: 0xf, 4: 0x7})
|
||||
|
||||
def test_per_primitive_attribute_after_the_system_values(self): # a primitive id (0x35 bit 0) and generic 0's x: p0 is the block's second component
|
||||
area = sph(0xf0, b'\x30') + sph(0x01, b'\x01')
|
||||
i = ms.info(control(7, payload=128, max_v=128, max_p=64, prim_at=0x80), area)
|
||||
src = ms.to_stage(KERNEL % (ms.memory(i)[1] // 4, ms.memory(i)[0][3] // 4), i)
|
||||
self.assertIn('uint b = 804u + (n / 32u) * 64u + n % 32u;', src)
|
||||
self.assertRegex(src, r'p\.p0 = float4\(as_type<float>\(_23\[b \+ 32u\]\), 0\.0, 0\.0, 1\.0\);')
|
||||
|
||||
def local_word(self): # a private variable spirv-cross initializes ahead of the stage memory: the last entry of a raw global memory lookup (GlobalToStorage.TryGenerateRawStorageOp)
|
||||
i = ms.info(control(7, payload=128, max_v=128, max_p=64), sph(0xf0, b'\x30'))
|
||||
src = (KERNEL % (ms.memory(i)[1] // 4, ms.memory(i)[0][3] // 4)).replace('{\n threadgroup', '{\n uint _9 = 0u;\n threadgroup', 1)
|
||||
@@ -201,6 +258,39 @@ class Stage(unittest.TestCase):
|
||||
self.assertRegex(body, r'void dm_stage_body\([^)]*\)\n\{\n uint _9 = 0u;\n _5\(_9\);')
|
||||
self.assertNotIn('_9', entries)
|
||||
|
||||
def test_primitive_id_handed_to_metal(self):
|
||||
# PRAGMATA 5aab38bb5ba67ef7: its per-primitive SPH enables only the primitive id (0x35 bit 0), which its code writes as (cluster << 7) | p and its fragment shader
|
||||
# 6c475973 reads as gl_PrimitiveID (the visibility buffer's cluster bits). The primitive gets it as its [[primitive_id]], from the first primitive block's first component
|
||||
# (36 + 4 * 4 * 32 words: the four vertex blocks of a position)
|
||||
area = sph(0xf0) + sph(0x01)
|
||||
i = ms.info(control(7, payload=128, max_v=128, max_p=126, prim_at=0x80), area)
|
||||
self.assertEqual(i['primitive_builtins'], [8])
|
||||
src = ms.to_stage(KERNEL % (ms.memory(i)[1] // 4, ms.memory(i)[0][3] // 4), i)
|
||||
self.assertIn('struct dm_prim_t {\n uint dm_pid [[primitive_id]];\n};', src)
|
||||
self.assertIn('metal::mesh<dm_vertex_t, dm_prim_t, 128, 126,', src)
|
||||
self.assertEqual(src.count('uint b = 548u + (n / 32u) * 32u + n % 32u;'), 2) # both depth conventions
|
||||
self.assertEqual(src.count('p.dm_pid = _23[b + 0u];'), 2)
|
||||
self.assertEqual(src.count('dm_out.set_primitive(n, p);'), 2)
|
||||
|
||||
def test_primitive_id_beside_an_attribute(self): # the id first, generic 0's x after it in the block
|
||||
area = sph(0xf0, b'\x30') + sph(0x01, b'\x01')
|
||||
i = ms.info(control(7, payload=128, max_v=128, max_p=64, prim_at=0x80), area)
|
||||
src = ms.to_stage(KERNEL % (ms.memory(i)[1] // 4, ms.memory(i)[0][3] // 4), i)
|
||||
self.assertIn(' uint dm_pid [[primitive_id]];\n float4 p0 [[user(locn0)]];\n', src)
|
||||
self.assertIn('p.dm_pid = _23[b + 0u];', src)
|
||||
self.assertRegex(src, r'p\.p0 = float4\(as_type<float>\(_23\[b \+ 32u\]\), 0\.0, 0\.0, 1\.0\);')
|
||||
|
||||
def test_layer_and_viewport_keep_room_only(self): # 0x35 bits 1 and 2: room in the block, no Metal output (no game's mesh shader writes them)
|
||||
i = ms.info(control(7, payload=128, max_v=128, max_p=64, prim_at=0x80), sph(0xf0) + sph(0x07))
|
||||
self.assertEqual((i['primitive_system'], i['primitive_builtins']), (3, [8, 9, 10]))
|
||||
src = ms.to_stage(KERNEL % (ms.memory(i)[1] // 4, ms.memory(i)[0][3] // 4), i)
|
||||
self.assertNotIn('render_target_array_index', src); self.assertNotIn('viewport_array_index', src)
|
||||
self.assertIn('uint b = 548u + (n / 32u) * 96u + n % 32u;', src)
|
||||
|
||||
def test_no_primitive_id_without_its_bit(self): # a mesh shader without per-primitive components hands Metal no primitive: its fragment reads Metal's own index
|
||||
src = self.mesh()[0]
|
||||
self.assertNotIn('dm_prim_t', src); self.assertNotIn('[[primitive_id]]', src)
|
||||
|
||||
def test_past_metal_refused(self):
|
||||
with self.assertRaises(ValueError): self.mesh(vertices=300)
|
||||
|
||||
@@ -217,7 +307,8 @@ class Stage(unittest.TestCase):
|
||||
|
||||
@unittest.skipUnless(shutil.which('xcrun') and subprocess.run(['xcrun', '-sdk', 'macosx', '-f', 'metal'], capture_output=True).returncode == 0, 'no Metal compiler')
|
||||
def test_compiles(self):
|
||||
cases = [self.task()[0], self.mesh()[0], self.mesh(task=True)[0], self.mesh(primitive=True)[0], self.mesh(vertices=32, primitives=32, pos=0xf8, verts=1, reads={5: 0x7})[0], self.mesh(primitive=True, reads={0: 1, 1: 0xf, 5: 0xf})[0], self.local_word()]
|
||||
i = ms.info(control(7, payload=128, max_v=128, max_p=126, prim_at=0x80), sph(0xf0) + sph(0x01, b'\x01')) # the primitive id and an attribute
|
||||
cases = [self.task()[0], self.mesh()[0], self.mesh(task=True)[0], self.mesh(primitive=True)[0], self.mesh(vertices=32, primitives=32, pos=0xf8, verts=1, reads={5: 0x7})[0], self.mesh(primitive=True, reads={0: 1, 1: 0xf, 5: 0xf})[0], self.local_word(), ms.to_stage(KERNEL % (ms.memory(i)[1] // 4, ms.memory(i)[0][3] // 4), i)]
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
for n, src in enumerate(cases):
|
||||
f = Path(d, f's{n}.metal'); f.write_text(src)
|
||||
@@ -226,6 +317,59 @@ class Stage(unittest.TestCase):
|
||||
self.assertEqual(r.returncode, 0, f'{sdk} case {n}: {r.stderr[-1500:]}')
|
||||
|
||||
|
||||
# The fragment stage reads the mesh's [[primitive_id]]: a mesh function from to_stage whose body writes two full-screen triangles with the ids 1000 + 77 and 1000 + 99 (the
|
||||
# second drawn last), and a fragment function that returns its [[primitive_id]] into an R32Uint target. Metal's own index would read 1
|
||||
GPU_KERNEL = HEAD + """
|
||||
kernel void main0(constant spvDescriptorSetBuffer0& spvDescriptorSet0 [[buffer(0)]], uint3 gl_LocalInvocationID [[thread_position_in_threadgroup]])
|
||||
{
|
||||
threadgroup spvUnsafeArray<uint, %(words)d> _23;
|
||||
if (gl_LocalInvocationID.x != 0u) return;
|
||||
float4 pos[3] = { float4(-1.0, -1.0, 0.5, 1.0), float4(3.0, -1.0, 0.5, 1.0), float4(-1.0, 3.0, 0.5, 1.0) };
|
||||
for (uint v = 0u; v < 3u; v++) for (uint c = 0u; c < 4u; c++) _23[%(out)du + c * 32u + v] = as_type<uint>(pos[v][c]);
|
||||
_23[%(pid)du] = 1077u; _23[%(pid)du + 1u] = 1099u;
|
||||
_23[%(count)du] = 2u << 24;
|
||||
_23[%(count)du + 1u] = 0x00020100u; _23[%(count)du + 2u] = 0x00000201u;
|
||||
}
|
||||
fragment uint fs(uint id [[primitive_id]]) { return id; }
|
||||
"""
|
||||
GPU_HOST = r"""
|
||||
#import <Metal/Metal.h>
|
||||
#include <stdio.h>
|
||||
int main(int argc, char **argv) { @autoreleasepool {
|
||||
id<MTLDevice> d = MTLCreateSystemDefaultDevice(); NSError *e = nil;
|
||||
id<MTLLibrary> lib = [d newLibraryWithURL:[NSURL fileURLWithPath:@(argv[1])] error:&e]; if (!lib) { printf("library: %s\n", e.description.UTF8String); return 1; }
|
||||
MTLMeshRenderPipelineDescriptor *m = [MTLMeshRenderPipelineDescriptor new]; m.meshFunction = [lib newFunctionWithName:@"main0_z"]; m.fragmentFunction = [lib newFunctionWithName:@"fs"];
|
||||
m.colorAttachments[0].pixelFormat = MTLPixelFormatR32Uint;
|
||||
id<MTLRenderPipelineState> ps = [d newRenderPipelineStateWithMeshDescriptor:m options:0 reflection:nil error:&e]; if (!ps) { printf("pipeline: %s\n", e.description.UTF8String); return 1; }
|
||||
MTLTextureDescriptor *td = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatR32Uint width:4 height:4 mipmapped:NO];
|
||||
td.usage = MTLTextureUsageRenderTarget; td.storageMode = MTLStorageModeShared; id<MTLTexture> t = [d newTextureWithDescriptor:td];
|
||||
id<MTLBuffer> b = [d newBufferWithLength:256 options:MTLResourceStorageModeShared];
|
||||
id<MTLCommandBuffer> cb = [[d newCommandQueue] commandBuffer]; MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor new];
|
||||
rp.colorAttachments[0].texture = t; rp.colorAttachments[0].loadAction = MTLLoadActionClear; rp.colorAttachments[0].storeAction = MTLStoreActionStore;
|
||||
id<MTLRenderCommandEncoder> en = [cb renderCommandEncoderWithDescriptor:rp]; [en setRenderPipelineState:ps];
|
||||
for (int k = 0; k < 31; k++) [en setMeshBuffer:b offset:0 atIndex:k];
|
||||
[en drawMeshThreadgroups:MTLSizeMake(1, 1, 1) threadsPerObjectThreadgroup:MTLSizeMake(1, 1, 1) threadsPerMeshThreadgroup:MTLSizeMake(32, 1, 1)];
|
||||
[en endEncoding]; [cb commit]; [cb waitUntilCompleted];
|
||||
uint32_t px[16]; [t getBytes:px bytesPerRow:16 fromRegion:MTLRegionMake2D(0, 0, 4, 4) mipmapLevel:0];
|
||||
for (int i = 0; i < 16; i++) printf("%u ", px[i]); printf("\n"); return 0; } }
|
||||
"""
|
||||
|
||||
|
||||
@unittest.skipUnless(os.environ.get('DMSH_TEST_GPU') == '1' and shutil.which('xcrun'), 'set DMSH_TEST_GPU=1 (draws on the GPU)')
|
||||
class PrimitiveIdOnTheGpu(unittest.TestCase):
|
||||
def test_fragment_reads_the_mesh_shaders_id(self):
|
||||
i = ms.info(control(7, payload=128, max_v=32, max_p=2, prim_at=0x80), sph(0xf0) + sph(0x01))
|
||||
lay, size = ms.memory(i); out = lay[2] // 4; pfirst = ms.attributes(i)[1]
|
||||
src = ms.to_stage(GPU_KERNEL % {'words': size // 4, 'out': out, 'pid': out + pfirst, 'count': lay[3] // 4}, i)
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
f = Path(d, 'm.metal'); f.write_text(src); lib = Path(d, 'm.metallib'); host = Path(d, 'h.m'); host.write_text(GPU_HOST); exe = Path(d, 'h')
|
||||
r = subprocess.run(['xcrun', '-sdk', 'macosx', 'metal', str(f), '-o', str(lib)], capture_output=True, text=True); self.assertEqual(r.returncode, 0, r.stderr[-1500:])
|
||||
r = subprocess.run(['clang', '-fobjc-arc', '-framework', 'Metal', '-framework', 'Foundation', str(host), '-o', str(exe)], capture_output=True, text=True)
|
||||
self.assertEqual(r.returncode, 0, r.stderr[-1500:])
|
||||
r = subprocess.run([str(exe), str(lib)], capture_output=True, text=True); self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||
self.assertEqual(r.stdout.split(), ['1099'] * 16)
|
||||
|
||||
|
||||
class IntegerPassThrough(unittest.TestCase):
|
||||
"""dmsh_entry.py fs_uint: a pixel shader that passes a flat input through to an integer target needs the integer entry point: Mario Kart World's dcb0504c844f1ecc, whose R8Uint output
|
||||
comes from its mesh stage's per-primitive attribute. A smooth input is not integer data"""
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
#!/usr/bin/env python3
|
||||
"""NVN2 buffer addresses through the offline translator (dmsh_xlate, arch sm86), as PRAGMATA's compute shaders read them: a buffer entry the game pushed into push block 1
|
||||
(c0 layout +0xaa, after push block 0 and before the uniform entries, mapped to c[24] + 0x100), and a bindless constant buffer read (cx[UR][offset]) through a pushed handle. Needs DMSH_TEST_XLATE (the
|
||||
translator) like the other translator tests."""
|
||||
import json, os, struct, subprocess, tempfile, unittest
|
||||
from pathlib import Path
|
||||
|
||||
EXIT = (0x000fea0003800000, 0x000000000000794d)
|
||||
ULDC64_C0_20 = (0x000fe20000000a00, 0x0000080000047ab9) # ULDC.64 UR4, c[0][0x20]
|
||||
ULDC64_C0_10 = (0x000fe20000000a00, 0x0000040000047ab9) # ULDC.64 UR4, c[0][0x10]
|
||||
LDG_UR4 = (0x000ea200081e8900, 0x00000004ff057981) # LDG.E R5, [UR4] (Ra = RZ)
|
||||
ULDCX = (0x000fe40008000800, 0x0000040004057ab9) # ULDC UR5, cx[UR4][0x10], a word (bit 91: the bank's handle in the uniform register at 24)
|
||||
MOV_R5_UR5 = (0x000fe20008000000, 0x0000000500057c02) # MOV R5, UR5
|
||||
SUATOM_R5 = (0x004ea200001ee000, 0x00000c05030c7593) # SUATOM.ADD on image slot 0 (c0 word 12), adding R5: keeps R5 alive
|
||||
ULDC64_C29_10 = (0x000fe20000000a00, 0x0000040000047ab9 | 29 << 54) # ULDC.64 UR4, c[29][0x10]: the pixel stage's buffer bank, entry 1
|
||||
LDG_R0_UR4 = (0x000ea200081e8900, 0x00000004ff007981) # LDG.E R0, [UR4] (Ra = RZ): colour 0's x, so it stays
|
||||
ISETP_NE_P0_R5 = (0x004fc20003f05070, 0x000000ff0500720c) # ISETP.NE.U32.AND P0, PT, R5, RZ, PT, waiting on the LDG's scoreboard (2), as SUATOM_R5
|
||||
MOV_R6_C3_10_NP0 = (0x000fe20000000f00, (0xa02 | 0x8 << 12 | 6 << 16 | 0x10 << 38 | 3 << 54)) # @!P0 MOV R6, c[3][0x10]: a word of the game's uniform buffer
|
||||
MOV_R6_R5_P0 = (0x000fe20000000f00, (0x202 | 6 << 16 | 5 << 32)) # @P0 MOV R6, R5: the word loaded from memory
|
||||
LOP3_R6_OR_SAMPLER = (0x000fe20000000000 | 0xff | 0xfc << 8 | 7 << 17 | 7 << 23, (0x812 | 0x7000 | 6 << 16 | 6 << 24 | 0x10400000 << 32)) # LOP3.LUT R6, R6, 0x10400000, RZ, 0xfc: | sampler 0x104
|
||||
TEX_LZ_R6 = (0x000fe20000000000 | 0xff | 1 << 8 | 7 << 17 | 1 << 23, (0x361 | 0x7000 | 7 << 16 | 2 << 24 | 6 << 32 | 1 << 61)) # TEX.LZ R7, R2, R6 (the handle), 2D, x only
|
||||
MOV_R6_C3_10 = (MOV_R6_C3_10_NP0[0], MOV_R6_C3_10_NP0[1] & ~(0xf << 12) | 0x7 << 12) # MOV R6, c[3][0x10], unconditional
|
||||
TEX_LZ_R6_ARRAY = (TEX_LZ_R6[0], TEX_LZ_R6[1] & ~(7 << 61) | 5 << 61) # the same read as ARRAY_2D
|
||||
SUATOM_R7 = (SUATOM_R5[0], (SUATOM_R5[1] & ~(0xff << 32)) | 7 << 32) # adding R7: keeps the texture read
|
||||
PS_SPH = struct.pack('<32I', *([0x000c5482] + [0] * 4 + [0xb0000000] + [0] * 12 + [0xf] + [0] * 13)) # a pixel shader that writes colour 0 (as test_dmsh_ampere_mem.py's)
|
||||
|
||||
|
||||
def inst(hi, lo): return struct.pack('<QQ', lo, hi)
|
||||
|
||||
|
||||
@unittest.skipUnless(os.environ.get('DMSH_TEST_XLATE'), 'set DMSH_TEST_XLATE to the offline translator')
|
||||
class Nvn2Buffers(unittest.TestCase):
|
||||
def translate(self, code, nvn2_cs):
|
||||
with tempfile.TemporaryDirectory(prefix='nvn2_buffers_') as d:
|
||||
work = Path(d); (work / 'k.bin').write_bytes(code)
|
||||
job = [dict(key='k', stage='cs', arch='sm86', code=str(work / 'k.bin'), tex={}, img={}, attr={}, fout={}, local=[32, 1, 1], nvn2_cs=nvn2_cs)]
|
||||
(work / 'jobs.json').write_text(json.dumps(job))
|
||||
r = subprocess.run([os.environ['DMSH_TEST_XLATE'], str(work / 'jobs.json'), d], capture_output=True, text=True)
|
||||
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||
return json.loads((work / 'k.res.json').read_text())
|
||||
|
||||
def translate_ps(self, code, stage_bank):
|
||||
with tempfile.TemporaryDirectory(prefix='nvn2_buffers_') as d:
|
||||
work = Path(d); (work / 'k.bin').write_bytes(PS_SPH + code)
|
||||
(work / 'jobs.json').write_text(json.dumps([dict(key='k', stage='ps', arch='sm86', code=str(work / 'k.bin'), tex={}, img={}, attr={}, fout={}, stage_bank=stage_bank)]))
|
||||
r = subprocess.run([os.environ['DMSH_TEST_XLATE'], str(work / 'jobs.json'), d], capture_output=True, text=True)
|
||||
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||
return json.loads((work / 'k.res.json').read_text())
|
||||
|
||||
def test_a_graphics_stage_bank_is_its_push_block(self):
|
||||
# The pixel stage (index 4) reads its buffer entries from c[29]: what the game pushes into graphics push block 5 (PRAGMATA's material pass), at c[24] + 5 * 0x100
|
||||
res = self.translate_ps(inst(*ULDC64_C29_10) + inst(*LDG_R0_UR4) + inst(*EXIT), 29)
|
||||
self.assertIn((24, (5 * 0x100 + 0x10) // 4), [(s['cb_slot'], s['cb_offset']) for s in res['sbufs']])
|
||||
|
||||
def test_another_stage_bank_is_refused(self):
|
||||
with tempfile.TemporaryDirectory(prefix='nvn2_buffers_') as d:
|
||||
work = Path(d); (work / 'k.bin').write_bytes(PS_SPH + inst(*ULDC64_C29_10) + inst(*LDG_R0_UR4) + inst(*EXIT))
|
||||
(work / 'jobs.json').write_text(json.dumps([dict(key='k', stage='ps', arch='sm86', code=str(work / 'k.bin'), tex={}, img={}, attr={}, fout={}, stage_bank=25)]))
|
||||
r = subprocess.run([os.environ['DMSH_TEST_XLATE'], str(work / 'jobs.json'), d], capture_output=True, text=True)
|
||||
self.assertIn("not this stage's buffer bank", r.stdout + r.stderr)
|
||||
|
||||
def test_a_pushed_buffer_entry_is_read_from_push_block_1(self):
|
||||
# c0: no push words, push block 1 at 0x10 (+0xaa: 4 words, one entry), one uniform entry at 0x20, images from 0x30 (image slot 0 = word 12)
|
||||
res = self.translate(inst(*ULDC64_C0_10) + inst(*LDG_UR4) + inst(*SUATOM_R5) + inst(*EXIT), [1, 0, 0, 0x40, 0, 0, 0, 0x10])
|
||||
self.assertIn((24, 0x100 // 4), [(s['cb_slot'], s['cb_offset']) for s in res['sbufs']]) # the storage buffer's address: c[24] + 0x100
|
||||
|
||||
def test_a_uniform_entry_follows_push_block_1(self):
|
||||
res = self.translate(inst(*ULDC64_C0_20) + inst(*LDG_UR4) + inst(*SUATOM_R5) + inst(*EXIT), [1, 0, 0, 0x40, 0, 0, 0, 0x10])
|
||||
self.assertIn((0, 0x210 // 4), [(s['cb_slot'], s['cb_offset']) for s in res['sbufs']]) # uniform slot 0's address: c[0] + 0x210
|
||||
|
||||
def test_a_bindless_constant_read_loads_through_a_pushed_handle(self):
|
||||
# UR4:UR5 = the first 8 bytes of push block 1 (a handle the game pushed, in the hardware's layout: address >> 4, size >> 4 at 45), then a word of that buffer through it.
|
||||
# The address the shader decodes (handle << 4) is traced back to the handle's words, which the host decodes (nvn_mtl.m ucb_handle_addr)
|
||||
res = self.translate(inst(*ULDC64_C0_10) + inst(*ULDCX) + inst(*MOV_R5_UR5) + inst(*SUATOM_R5) + inst(*EXIT), [1, 0, 0, 0x40, 0, 0, 0, 0x10])
|
||||
self.assertIn((24, 0x100 // 4), [(s['cb_slot'], s['cb_offset']) for s in res['sbufs']])
|
||||
|
||||
def test_a_texture_id_loaded_on_one_path_indexes_the_pools(self):
|
||||
# The handle is (a word loaded from memory, or on the other path a word of c[3]) | constant sampler 0x104, as PRAGMATA's compute shader 02e1292114121308 reads a material's texture.
|
||||
# The loaded word may name any texture, so the read indexes the pools by its ID; the uniform word alone was taken as the handle, a binding the host has no slot for
|
||||
code = [ULDC64_C0_10, LDG_UR4, ISETP_NE_P0_R5, MOV_R6_C3_10_NP0, MOV_R6_R5_P0, LOP3_R6_OR_SAMPLER, TEX_LZ_R6, SUATOM_R7, EXIT]
|
||||
res = self.translate(b''.join(inst(*i) for i in code), [1, 0, 0, 0x40, 0, 0, 0, 0x10])
|
||||
self.assertEqual([t for t in res['textures'] if t['cbuf_slot'] not in (0, 2)], [], res['textures']) # no texture named by a word of the uniform buffer
|
||||
self.assertTrue(any(t['array'] > 32 for t in res['textures']), res['textures']) # the pool array
|
||||
|
||||
|
||||
def test_a_handle_read_as_2d_and_as_a_2d_array_is_an_array(self):
|
||||
# One handle, TEX 2D and TEX ARRAY_2D (PRAGMATA: 24 pixel shaders, 21ba8fea5a5eb03c among them, whose Metal source did not compile: the binding was declared an array
|
||||
# and the 2D read gave no layer). The binding is an array for both, in the declaration and in the descriptor, and the 2D read takes layer 0
|
||||
code = [MOV_R6_C3_10, LOP3_R6_OR_SAMPLER, TEX_LZ_R6, SUATOM_R7, TEX_LZ_R6_ARRAY, SUATOM_R7, EXIT]
|
||||
res = self.translate(b''.join(inst(*i) for i in code), [1, 0, 0, 0x40, 0, 0, 0, 0x10])
|
||||
self.assertEqual([t['type'] for t in res['textures'] if t['cbuf_slot'] not in (0, 2)], [0x103], res['textures']) # Texture2D | Array, once
|
||||
only = self.translate(b''.join(inst(*i) for i in code[:4] + [EXIT]), [1, 0, 0, 0x40, 0, 0, 0, 0x10])
|
||||
self.assertEqual([t['type'] for t in only['textures'] if t['cbuf_slot'] not in (0, 2)], [3], only['textures']) # a 2D read alone stays 2D
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -19,7 +19,8 @@ from test_dmsh_ampere_alu import STORE, waiting, s2r_tid # noqa: E402
|
||||
|
||||
TOOLS = Path(__file__).resolve().parents[1] / 'tools'
|
||||
tree = ast.parse((TOOLS / 'dmsh_build.py').read_text())
|
||||
scope = {}
|
||||
sys.path.insert(0, str(TOOLS)); import dmsh_chain # noqa: E402 (the line names its deployment target, dmsh_chain.MAC_MIN_FLAG)
|
||||
scope = {'dmsh_chain': dmsh_chain}
|
||||
exec(compile(ast.Module(body=[n for n in tree.body if isinstance(n, ast.Assign) and any(getattr(t, 'id', None) == 'MAC_METAL' for t in n.targets)], type_ignores=[]),
|
||||
str(TOOLS / 'dmsh_build.py'), 'exec'), scope)
|
||||
MAC_METAL = scope['MAC_METAL']
|
||||
|
||||
@@ -131,6 +131,23 @@ class DriverReads(unittest.TestCase):
|
||||
def test_sample_rows_are_not_filled_for_other_stages(self):
|
||||
self.assertEqual(UNFILLABLE(self.SAMPLE_LOOKUP, 'vs'), ['c0 dynamic index', 'c0+0x630'])
|
||||
|
||||
# PRAGMATA's sample position lookup without the grid (a689530d00090ebf): a byte of the table at 0x620 + the sample index, row 98
|
||||
SAMPLE_BYTE = ('float _115 = as_type<float>(gl_SampleID);\n'
|
||||
'int _141 = as_type<int>(_115) + 1568;\n'
|
||||
'uint _144 = uint(int(uint(_141) >> uint(2)));\n'
|
||||
'uint _146 = uint(int(uint(int(_144)) >> uint(2)));\n'
|
||||
'int _148 = int(_144) & 3;\n'
|
||||
'float _150 = (*spvDescriptorSet0.fp_c0)._m0[int(_146)][_148];')
|
||||
|
||||
def test_sample_byte_by_the_sample_index_is_filled_in_a_pixel_shader(self):
|
||||
self.assertEqual(UNFILLABLE(self.SAMPLE_BYTE), [])
|
||||
|
||||
def test_sample_byte_is_not_filled_for_other_stages(self):
|
||||
self.assertEqual(UNFILLABLE(self.SAMPLE_BYTE, 'vs'), ['c0+0x620'])
|
||||
|
||||
def test_index_reassigned_in_a_loop_stays_dynamic(self):
|
||||
self.assertEqual(UNFILLABLE(self.SAMPLE_BYTE.replace('int _148', '_146 = 7u;\nint _148')), ['c0 dynamic index'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,102 @@
|
||||
"""Warp-synchronous shared memory (dmsh_rewrite.py tg_fence): Ampere compilers drop the barrier in small scans whose lanes run in lockstep (Unreal's GPU radix sort downsweep,
|
||||
Orbitals' d032ce5090303e01: STS, then LDS of the neighbouring lane's word, then STS). For one thread such a load and its own earlier store do not alias, so Metal may move the
|
||||
load above the store. tg_fence puts a simdgroup-scope memory fence (not an execution barrier) after each threadgroup store. When the Metal compiler is installed, the result
|
||||
is compiled as the build compiles it (dmsh_build.py MAC_METAL), and a kernel whose array spills to device memory (tg_spill, after tg_fence) gets fences that order device memory as well."""
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
TOOLS = Path(__file__).resolve().parents[1] / 'tools'
|
||||
sys.path.insert(0, str(TOOLS))
|
||||
import dmsh_abi as abi, dmsh_rewrite
|
||||
tg_fence, tg_spill, FENCE = dmsh_rewrite.tg_fence, dmsh_rewrite.tg_spill, dmsh_rewrite.TG_FENCE
|
||||
|
||||
ARRAY = """template<typename T, size_t Num>
|
||||
struct spvUnsafeArray
|
||||
{
|
||||
T elements[Num ? Num : 1];
|
||||
thread T& operator [] (size_t pos) thread { return elements[pos]; }
|
||||
device T& operator [] (size_t pos) device { return elements[pos]; }
|
||||
threadgroup T& operator [] (size_t pos) threadgroup { return elements[pos]; }
|
||||
};
|
||||
"""
|
||||
# The downsweep's shape: each lane stores its word, reads its neighbour's, adds and stores again, with no barrier
|
||||
SCAN = """#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
""" + ARRAY + """
|
||||
struct B { uint _m0[1]; };
|
||||
kernel void main0(device B& out [[buffer(1)]], uint3 gl_LocalInvocationID [[thread_position_in_threadgroup]])
|
||||
{
|
||||
threadgroup spvUnsafeArray<uint, %d> _39;
|
||||
uint _10 = gl_LocalInvocationID.x;
|
||||
_39[_10] = out._m0[_10];
|
||||
uint _11 = _39[_10 - 1u] + _39[_10];
|
||||
_39[_10] = _11;
|
||||
out._m0[_10] = _39[_10];
|
||||
}
|
||||
"""
|
||||
PLAIN = """#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
struct B { uint _m0[1]; };
|
||||
kernel void main0(device B& out [[buffer(1)]], uint3 gl_LocalInvocationID [[thread_position_in_threadgroup]])
|
||||
{
|
||||
uint _10 = gl_LocalInvocationID.x;
|
||||
out._m0[_10] = _10;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def lines_after_stores(src):
|
||||
ls = src.split('\n')
|
||||
return [(ls[i].strip(), ls[i + 1].strip()) for i in range(len(ls) - 1) if re.match(r'\s*_39\[[^\]]*\]\s*=(?!=)', ls[i])]
|
||||
|
||||
|
||||
class TgFence(unittest.TestCase):
|
||||
def test_a_fence_follows_each_threadgroup_store(self):
|
||||
out = tg_fence(SCAN % 64)
|
||||
pairs = lines_after_stores(out)
|
||||
self.assertEqual(len(pairs), 2)
|
||||
for _, nxt in pairs:
|
||||
self.assertEqual(nxt, FENCE)
|
||||
self.assertEqual(out.count(FENCE), 2) # not after the loads, nor after the device store
|
||||
|
||||
def test_compound_and_member_stores_get_a_fence_too(self): # SPIRV-Cross writes a read-modify-write of one element as a compound assignment
|
||||
src = SCAN.replace(' _39[_10] = _11;\n', ' _39[_10] += _11;\n _39[_10 ^ 1u] <<= 1u;\n _39[_10 + 2u].x = _11;\n bool _12 = _39[_10] >= _11;\n bool _13 = _39[_10] <= _11;\n') % 64
|
||||
out = tg_fence(src).split('\n')
|
||||
for store in ('_39[_10] += _11;', '_39[_10 ^ 1u] <<= 1u;', '_39[_10 + 2u].x = _11;'):
|
||||
k = next(i for i, ln in enumerate(out) if ln.strip() == store)
|
||||
self.assertEqual(out[k + 1].strip(), FENCE, store)
|
||||
for compare in ('bool _12', 'bool _13'): # comparisons are no stores
|
||||
k = next(i for i, ln in enumerate(out) if ln.strip().startswith(compare))
|
||||
self.assertNotEqual(out[k + 1].strip(), FENCE, compare)
|
||||
|
||||
def test_it_is_a_simdgroup_memory_fence_not_a_barrier(self):
|
||||
self.assertIn('thread_scope_simdgroup', FENCE)
|
||||
self.assertNotIn('barrier', FENCE)
|
||||
self.assertNotIn('threadgroup_barrier', tg_fence(SCAN % 64))
|
||||
|
||||
def test_a_kernel_without_threadgroup_memory_is_left_as_it_is(self):
|
||||
self.assertEqual(tg_fence(PLAIN), PLAIN)
|
||||
|
||||
def test_spilled_arrays_get_device_fences(self): # tg_spill runs after tg_fence: an array past abi.TG_MAX moves to device memory, and so must the fence's scope
|
||||
n = abi.TG_MAX // 4 + 1024
|
||||
src, spill = tg_spill(tg_fence(SCAN % n))
|
||||
self.assertGreater(spill, abi.TG_MAX)
|
||||
self.assertEqual(src.count('mem_flags::mem_device | mem_flags::mem_threadgroup, memory_order_seq_cst, thread_scope_simdgroup'), 2)
|
||||
|
||||
@unittest.skipUnless(shutil.which('xcrun') and subprocess.run(['xcrun', '-f', 'metal'], capture_output=True).returncode == 0, 'no Metal compiler')
|
||||
def test_compiles(self):
|
||||
for src in (tg_fence(SCAN % 64), tg_spill(tg_fence(SCAN % (abi.TG_MAX // 4 + 1024)))[0]):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p = Path(d) / 'k.metal'
|
||||
p.write_text(src)
|
||||
r = subprocess.run(['xcrun', '-sdk', 'macosx', 'metal', '-c', '-O1', '-fpreserve-invariance', str(p), '-o', str(Path(d) / 'k.air')], capture_output=True, text=True)
|
||||
self.assertEqual(r.returncode, 0, r.stderr[-2000:])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -18,7 +18,9 @@ import ios_metal # noqa: E402
|
||||
|
||||
def mac_metal(): # dmsh_build.py's MAC_METAL, read without running the script
|
||||
for n in ast.parse((TOOLS / 'dmsh_build.py').read_text()).body:
|
||||
if isinstance(n, ast.Assign) and any(isinstance(t, ast.Name) and t.id == 'MAC_METAL' for t in n.targets): return ast.literal_eval(n.value)
|
||||
if isinstance(n, ast.Assign) and any(isinstance(t, ast.Name) and t.id == 'MAC_METAL' for t in n.targets):
|
||||
sys.path.insert(0, str(TOOLS)); import dmsh_chain # the line names its deployment target, dmsh_chain.MAC_MIN_FLAG
|
||||
return eval(compile(ast.Expression(n.value), 'dmsh_build.py', 'eval'), {'dmsh_chain': dmsh_chain})
|
||||
raise AssertionError('no MAC_METAL in dmsh_build.py')
|
||||
|
||||
|
||||
|
||||
@@ -8,9 +8,10 @@ import tempfile
|
||||
import unittest
|
||||
|
||||
path = Path(__file__).resolve().parents[1] / 'tools/dmsh_build.py'
|
||||
nodes = [n for n in ast.parse(path.read_text()).body if isinstance(n, ast.FunctionDef) and n.name in ('early_fragment_tests', 'job_for')]
|
||||
sys.path.insert(0, str(path.parent)); import dmsh_ampere
|
||||
scope = {'struct': struct, 'os': os, 'dmsh_ampere': dmsh_ampere, 'FACTS': {}, 'tf_layout': lambda key, ctl: None, 'vertex_ab': lambda key, code, ctl: None}
|
||||
nodes = [n for n in ast.parse(path.read_text()).body if (isinstance(n, ast.FunctionDef) and n.name in ('early_fragment_tests', 'job_for'))
|
||||
or (isinstance(n, ast.Assign) and getattr(n.targets[0], 'id', None) == 'NVN2_STAGE_INDEX')]
|
||||
sys.path.insert(0, str(path.parent)); import dmsh_ampere, dmsh_abi
|
||||
scope = {'struct': struct, 'os': os, 'dmsh_ampere': dmsh_ampere, 'abi': dmsh_abi, 'FACTS': {}, 'tf_layout': lambda key, ctl: None, 'vertex_ab': lambda key, code, ctl: None}
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), str(path), 'exec'), scope)
|
||||
early = scope['early_fragment_tests']; job_for = scope['job_for']
|
||||
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
"""RE Engine PAKs (KPKA) and SDF shader definitions, without game data: Monster Hunter Rise's layouts and PRAGMATA's (block table, 0x110-byte SDF entries)."""
|
||||
from pathlib import Path
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools'))
|
||||
import shader_split as ss
|
||||
|
||||
|
||||
def nvn2(stage_byte, sph_type):
|
||||
"""An NVN2 control section (magic, version 0xc9, code length at +0x44, stage byte at +0x56) and a 0x80-byte code area whose SPH word 0 names sph_type"""
|
||||
code = struct.pack('<I', sph_type << 10 | 1).ljust(0x80, b'\0')
|
||||
ctl = bytearray(0x60); ctl[:4] = ss.CTL_MAGIC; ctl[4:8] = b'\xc9\0\0\0'
|
||||
struct.pack_into('<I', ctl, 0x44, len(code)); ctl[0x56] = stage_byte
|
||||
return bytes(ctl), code
|
||||
|
||||
|
||||
def sdf(layout, stages):
|
||||
"""One SDF entry with stages {slot: (ctl, code)} in layout 0 (Monster Hunter Rise) or 1 (PRAGMATA)"""
|
||||
base, size, lens, at = ss.SDF_LAYOUTS[layout]
|
||||
head = b'SDF\0' + struct.pack('<HH', 1, 1) + bytes(base - 8)
|
||||
body, offs, o = b'', [0] * 6, base + size
|
||||
for slot, (ctl, code) in stages.items():
|
||||
rec = bytes(lens) + struct.pack('<II', len(ctl), len(code)) + bytes(at - lens - 8) + ctl + code
|
||||
offs[slot] = o + len(body); body += rec
|
||||
entry = bytearray(size); struct.pack_into('<6Q', entry, 0x10, *offs)
|
||||
return head + bytes(entry) + body
|
||||
|
||||
|
||||
class SdfTests(unittest.TestCase):
|
||||
def test_both_layouts(self):
|
||||
vs, ps, ms = nvn2(0, 1), nvn2(0, 5), nvn2(7, 3)
|
||||
for layout in (0, 1):
|
||||
with self.subTest(layout=layout):
|
||||
got = ss.sdf_shaders(sdf(layout, {0: vs, 4: ps}), 'x')
|
||||
self.assertEqual([(st, c, k) for _, st, c, k in got], [('vs', *vs), ('ps', *ps)])
|
||||
self.assertEqual(ss.sdf_layout(sdf(layout, {0: vs}), 1, 'x'), ss.SDF_LAYOUTS[layout])
|
||||
|
||||
def test_mesh_shader_in_the_hull_slot(self): # PRAGMATA keeps mesh shaders in the hull slot
|
||||
got = ss.sdf_shaders(sdf(1, {1: nvn2(7, 3), 4: nvn2(0, 5)}), 'x')
|
||||
self.assertEqual([st for _, st, _, _ in got], ['ms', 'ps'])
|
||||
|
||||
def test_wrong_slot_is_rejected(self):
|
||||
with self.assertRaisesRegex(SystemExit, r'the stage \(ps\) does not match'):
|
||||
ss.sdf_shaders(sdf(1, {0: nvn2(0, 5)}), 'x')
|
||||
|
||||
|
||||
class OcioTests(unittest.TestCase):
|
||||
def ocio(self, *stages): # an OCIO file: a header, then stage records (0x58-byte header, lengths at +8) among other data, as PRAGMATA's colour pipelines hold them
|
||||
d = bytearray(b'OCIO' + bytes(0xc4) + b'names\0' + bytes(2))
|
||||
for ctl, code in stages:
|
||||
d += bytes(8) + struct.pack('<II', len(ctl), len(code)) + bytes(0x48) + ctl + code + bytes(8)
|
||||
return bytes(d)
|
||||
|
||||
def test_records_are_read(self):
|
||||
ps, cs = nvn2(0, 5), nvn2(5, 0)
|
||||
got = ss.ocio_shaders(self.ocio(ps, cs), 'x')
|
||||
self.assertEqual([(st, c, k) for _, st, c, k in got], [('ps', *ps), ('cs', *cs)])
|
||||
|
||||
def test_records_packed_to_four_bytes(self): # the larger OCIO files (8ae6c7ee83bc0563): a record whose control section starts 4 bytes off an 8-byte boundary
|
||||
ps, cs = nvn2(0, 5), nvn2(5, 0)
|
||||
d = self.ocio(ps) + bytes(4) + self.ocio(cs)[0xd0:]
|
||||
self.assertTrue([m.start() & 7 for m in re.finditer(re.escape(ss.CTL_MAGIC), d)][1])
|
||||
self.assertEqual([st for _, st, _, _ in ss.ocio_shaders(d, 'x')], ['ps', 'cs'])
|
||||
|
||||
def test_a_section_whose_record_names_another_length_is_left_out(self):
|
||||
ctl, code = nvn2(0, 5)
|
||||
d = bytearray(self.ocio((ctl, code))); at = d.index(ss.CTL_MAGIC)
|
||||
struct.pack_into('<I', d, at - 0x4c, len(code) + 0x10) # the record's code length disagrees with the file's bytes after it
|
||||
self.assertEqual(ss.ocio_shaders(bytes(d), 'x'), [])
|
||||
|
||||
|
||||
class KpkaTests(unittest.TestCase):
|
||||
def test_block_table(self):
|
||||
zstd = ss.zstd_mod()
|
||||
bl = 0x100
|
||||
plain = b'SDF\0' + bytes(12)
|
||||
big = bytes(range(256)) + b'tail' * 16 # two blocks: one stored, one zstd frame of a padded block
|
||||
b0, b1 = big[:bl], zstd.compress(big[bl:].ljust(bl, b'\0'))
|
||||
n = 2; table_end = 16 + 0x30 * n
|
||||
blocks_at = table_end + 8; data_at = blocks_at + 16
|
||||
p_off = data_at; b0_off = p_off + len(zp := zstd.compress(plain)); b1_off = b0_off + len(b0)
|
||||
ents = struct.pack('<Qqqqqq', 0x1111, p_off, len(zp), len(plain), 2, 0) + struct.pack('<Qqqqqq', 0x2222, 0, len(b0) + len(b1), len(big), ss.KPKA_IN_BLOCKS | 0x400, 0)
|
||||
blocks = struct.pack('<II', bl, 2) + struct.pack('<QQ', b0_off | len(b0) << 42, b1_off | len(b1) << 42)
|
||||
pak = b'KPKA' + bytes([4, 2]) + struct.pack('<HII', ss.KPKA_BLOCKS, n, 0) + ents + blocks + zp + b0 + b1
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / 're_chunk_000.pak'; path.write_bytes(pak)
|
||||
es = ss.kpka_entries(str(path)); bt = ss.kpka_blocks(str(path))
|
||||
self.assertEqual([e[0] for e in es], [0x1111, 0x2222])
|
||||
self.assertEqual(bt, (bl, [(b0_off, len(b0)), (b1_off, len(b1))]))
|
||||
self.assertEqual(ss.kpka_data(pak, es[0], blocks=bt), plain)
|
||||
self.assertEqual(ss.kpka_data(pak, es[1], blocks=bt), big)
|
||||
self.assertEqual(ss.kpka_data(pak, es[1], 4, bt), big[:4])
|
||||
|
||||
def test_unknown_feature_is_rejected(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / 'x.pak'; path.write_bytes(b'KPKA' + bytes([4, 0]) + struct.pack('<HII', 0x8, 0, 0))
|
||||
with self.assertRaisesRegex(SystemExit, 'features 0x8'):
|
||||
ss.kpka_entries(str(path))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -57,6 +57,34 @@ OpFunctionEnd
|
||||
'''
|
||||
|
||||
|
||||
# A domain shader that reads only the lane ID, in a module with no bool and no uvec4 (PRAGMATA's 859225c91a5fe2b2): the rewrite declares the types its constants need
|
||||
LANE_ONLY = '''OpCapability Tessellation
|
||||
OpCapability GroupNonUniform
|
||||
OpMemoryModel Logical GLSL450
|
||||
OpEntryPoint TessellationEvaluation %main "main" %lane %pos
|
||||
OpExecutionMode %main Triangles
|
||||
OpDecorate %lane BuiltIn SubgroupLocalInvocationId
|
||||
OpDecorate %pos BuiltIn Position
|
||||
%void = OpTypeVoid
|
||||
%fn = OpTypeFunction %void
|
||||
%uint = OpTypeInt 32 0
|
||||
%float = OpTypeFloat 32
|
||||
%v4 = OpTypeVector %float 4
|
||||
%in_uint = OpTypePointer Input %uint
|
||||
%out_v4 = OpTypePointer Output %v4
|
||||
%lane = OpVariable %in_uint Input
|
||||
%pos = OpVariable %out_v4 Output
|
||||
%main = OpFunction %void None %fn
|
||||
%entry = OpLabel
|
||||
%id = OpLoad %uint %lane
|
||||
%f = OpConvertUToF %float %id
|
||||
%p = OpCompositeConstruct %v4 %f %f %f %f
|
||||
OpStore %pos %p
|
||||
OpReturn
|
||||
OpFunctionEnd
|
||||
'''
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which('spirv-as') and shutil.which('spirv-val') and shutil.which(SPIRV_CROSS), 'requires SPIR-V tools')
|
||||
class SubgroupTests(unittest.TestCase):
|
||||
def test_mask_component_pointer_becomes_valid_constant_extraction(self):
|
||||
@@ -75,5 +103,18 @@ class SubgroupTests(unittest.TestCase):
|
||||
self.assertFalse(scope['spv_single_lane'](spv))
|
||||
|
||||
|
||||
def test_a_module_without_the_constant_types(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory); src, spv = root / 'lane.spvasm', root / 'lane.spv'
|
||||
src.write_text(LANE_ONLY)
|
||||
subprocess.run(['spirv-as', '--target-env', 'spv1.3', str(src), '-o', str(spv)], check=True, capture_output=True)
|
||||
self.assertNotEqual(subprocess.run([SPIRV_CROSS, '--msl', str(spv)], capture_output=True, text=True).returncode, 0) # SPIRV-Cross refuses the builtin in this stage
|
||||
self.assertTrue(scope['spv_single_lane'](spv))
|
||||
result = subprocess.run(['spirv-val', '--target-env', 'spv1.3', str(spv)], capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
result = subprocess.run([SPIRV_CROSS, '--msl', str(spv)], capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -54,8 +54,65 @@ def cross_args(xc, spv):
|
||||
_EMULATED = re.compile(r'\bspvImage2DAtomicCoord\b|device\s+atomic_u?int\s*\*\s*\w+_atomic\b')
|
||||
|
||||
|
||||
# 64-bit image atomics (after uncraftablexd's PRAGMATA bring-up, PR #1801). Ampere SURED.D.2D.MAX.U64 (PRAGMATA's visibility buffer: depth << 32 | ID, 336 compute
|
||||
# shaders) is a 64-bit unsigned max with no result. Metal has it as texture2d<ulong, access::read_write>::atomic_max / atomic_min (MSL 3.1, an RG32Uint texture made with
|
||||
# the shader-atomic usage, Apple GPU family 9: M3 / A17 Pro and later), with no fetch form and no other operation. SPIRV-Cross refuses every 64-bit atomic, so the translator
|
||||
# (CodeGen/Spirv GenerateImageAtomic) writes the operation on its rg32ui image as two 32-bit atomics of the same operation on the same texel, the low word then the high word,
|
||||
# inside the IGN bounds check. wide_atomics turns each such pair into the one 64-bit atomic and declares the image as ulong; the high word is the more significant half, as the
|
||||
# RG32Uint texel's R channel holds the low 32 bits (Metal's ulong view of RG32Uint, little-endian as the guest's 64-bit texel). The image may be bound only for that: any
|
||||
# other access of it (a read, a write, a lone 32-bit atomic) fails the shader rather than run on the wrong type
|
||||
_WIDE_DECL = re.compile(r'\b(texture(?:2d|2d_array|3d))<uint, access::read_write>(\s+)(\w+_rg32ui)\b')
|
||||
_WIDE_STMT = r'^([ \t]*)(?:uint _\d+ = )?([\w.]*?\b%s)\.atomic_fetch_(max|min)\((.*)\)(?:\.x)?;[ \t]*$'
|
||||
_WIDE_QUERY = r'\.get_(?:width|height|depth|array_size)\(\)'
|
||||
|
||||
|
||||
def _split_args(text):
|
||||
"""The top-level comma-separated arguments of a call's argument text"""
|
||||
out, depth, cur = [], 0, ''
|
||||
for ch in text:
|
||||
depth += {'(': 1, '[': 1, ')': -1, ']': -1}.get(ch, 0)
|
||||
if ch == ',' and depth == 0:
|
||||
out.append(cur.strip()); cur = ''
|
||||
else:
|
||||
cur += ch
|
||||
out.append(cur.strip())
|
||||
return out
|
||||
|
||||
|
||||
def wide_atomics(source):
|
||||
"""The translator's 32-bit atomic pairs on rg32ui images as Metal's 64-bit texture atomics (see above); the source unchanged when there are none"""
|
||||
if '_rg32ui' not in source:
|
||||
return source
|
||||
for m in list(_WIDE_DECL.finditer(source)):
|
||||
name = m.group(3)
|
||||
if not re.search(r'\b%s\.atomic_' % re.escape(name), source):
|
||||
continue # an rg32ui image the shader only reads or writes: not this case
|
||||
lines = source.split('\n')
|
||||
stmt = re.compile(_WIDE_STMT % re.escape(name))
|
||||
out, i = [], 0
|
||||
while i < len(lines):
|
||||
a = stmt.match(lines[i])
|
||||
if not a:
|
||||
out.append(lines[i]); i += 1; continue
|
||||
b = stmt.match(lines[i + 1]) if i + 1 < len(lines) else None
|
||||
if not b or b.group(2) != a.group(2) or b.group(3) != a.group(3):
|
||||
raise ValueError(f'{name}: a 32-bit atomic on a 64-bit image that is not the translator\'s low / high pair')
|
||||
x, y = _split_args(a.group(4)), _split_args(b.group(4))
|
||||
if len(x) < 2 or x[:-1] != y[:-1]:
|
||||
raise ValueError(f'{name}: the two halves of a 64-bit atomic name different texels')
|
||||
out.append(f'{a.group(1)}{a.group(2)}.atomic_{a.group(3)}({", ".join(x[:-1])}, ulong4(as_type<ulong>(uint2({x[-1]}, {y[-1]}))));')
|
||||
i += 2
|
||||
source = '\n'.join(out)
|
||||
left = re.sub(r'\b%s(?:%s|\.atomic_(?:max|min)\()' % (re.escape(name), _WIDE_QUERY), '', source)
|
||||
uses = len(re.findall(r'\b%s\b' % re.escape(name), left))
|
||||
if uses != 1: # the declaration alone
|
||||
raise ValueError(f'{name}: {uses - 1} accesses of a 64-bit atomic image besides its atomics and size queries')
|
||||
source = re.sub(r'\b(texture(?:2d|2d_array|3d))<uint, access::read_write>(\s+%s)\b' % re.escape(name), r'\1<ulong, access::read_write>\2', source)
|
||||
return source
|
||||
|
||||
|
||||
def check_msl(source):
|
||||
"""Fail closed on SPIRV-Cross's pointer emulation of image atomics; return the source unchanged"""
|
||||
"""Fail closed on SPIRV-Cross's pointer emulation of image atomics; return the source with 64-bit image atomics made native (wide_atomics)"""
|
||||
if 'tomic' in source and _EMULATED.search(source): # (both alternatives hold the word; the pattern alone tries every character of the source)
|
||||
raise ValueError('image atomics emulated through a raw pointer; they must be native texture atomics (MSL 3.1)')
|
||||
return source
|
||||
return wide_atomics(source)
|
||||
@@ -412,6 +412,8 @@ def ps_omap(code):
|
||||
NaN above Ocarina of Time's horizon to the missing per-component mask (their commit 79c1516; Ocarina's agl_common depth pass has map 0x10f: output 0 RGBA, output 2 R only)"""
|
||||
return struct.unpack_from('<I', code, 18 * 4)[0] if len(code) >= 0x50 else None
|
||||
|
||||
NVN2_STAGE_INDEX = {'vs': 0, 'hs': 1, 'ms': 1, 'ds': 2, 'gs': 3, 'ps': 4} # NVN2 graphics stage indices (PRAGMATA's banks: vertex c[25], hull and mesh c[26], domain c[27], geometry c[28], pixel c[29])
|
||||
|
||||
def job_for(key, name, rec, w):
|
||||
ci = rec.find(bytes.fromhex('34127698'), 0x38); code = rec[0x38:ci]; stage = name[:2]
|
||||
extra = {}
|
||||
@@ -424,8 +426,14 @@ def job_for(key, name, rec, w):
|
||||
extra['arch'] = 'sm86'
|
||||
# compute lays out its driver constants in c[0] per shader: the control section gives its push constants' words (+0xa9), counts its uniform buffer, storage
|
||||
# buffer, texture, separate texture and separate sampler entries (+0xb1, +0xb2, +0xb3, +0xb4, +0xb5; images, +0xb6, come last) and gives the size (+0xba);
|
||||
# the translator maps them to c[24] and NVN's fixed tables (InstEmitAmpere.cs AMapC0). Graphics keeps NVN's tables
|
||||
if stage == 'cs': extra['nvn2_cs'] = [rec[ci + 0xb1], rec[ci + 0xb2], rec[ci + 0xb3], struct.unpack_from('<H', rec, ci + 0xba)[0], rec[ci + 0xa9] * 4, rec[ci + 0xb4], rec[ci + 0xb5]]
|
||||
# the translator maps them to c[24] and NVN's fixed tables (InstEmitAmpere.cs AMapC0). Graphics keeps NVN's tables.
|
||||
# +0xaa counts the words of push block 1 (NVN2's own accessor reads +0xa9 + block): what the game pushes there (PRAGMATA: {address, size} buffer entries, or 8-byte handles),
|
||||
# laid out right after push block 0, before the uniform entries; the translator maps it to c[24] + DMSH_PUSH_SIZE (dmsh_abi.h DMSH_PUSH_BLOCKS). With it every one of
|
||||
# PRAGMATA's 6,856 compute shaders adds up to its size (+0xba); Donkey Kong Bananza's and Star Fox's sizes add up without it, as +0xaa is 0 there
|
||||
if stage == 'cs': extra['nvn2_cs'] = [rec[ci + 0xb1], rec[ci + 0xb2], rec[ci + 0xb3], struct.unpack_from('<H', rec, ci + 0xba)[0], rec[ci + 0xa9] * 4, rec[ci + 0xb4], rec[ci + 0xb5], rec[ci + 0xaa] * 4]
|
||||
# a graphics stage reads the buffer entries the game pushes into its push block 1 + stage index from a bank of its own, c[25 + stage index]; the translator maps
|
||||
# that bank onto the block in c[24] (dmsh_abi.h DMSH_NVN2_STAGE_BANK). A task shader's bank has not been seen
|
||||
if stage in NVN2_STAGE_INDEX: extra['stage_bank'] = abi.NVN2_STAGE_BANK + NVN2_STAGE_INDEX[stage]
|
||||
if stage in ('ts', 'ms'):
|
||||
# A task or mesh shader: translated as compute, its SPH taken off and its stage memory in shared memory, then wrapped as the Metal stage function (dmsh_meshstage.py).
|
||||
# Graphics stages' c[0] and c[2] tables stay: the translator reads their addresses out of the code as for a vertex shader
|
||||
@@ -626,10 +634,13 @@ def spv_single_lane(path):
|
||||
if any(op(x) in (65, 66) and len(x) > 3 and x[3] in bptr for x in ins): return False
|
||||
uint = next((x[1] for x in ins if op(x) == 21 and x[2:4] == [32, 0]), None); boolt = next((x[1] for x in ins if op(x) == 20), None)
|
||||
uvec4 = next((x[1] for x in ins if op(x) == 23 and x[2] == uint and x[3] == 4), None)
|
||||
if uint is None or boolt is None or uvec4 is None: return False
|
||||
bound = hdr[3]; c = {}
|
||||
# A type the module lacks is declared with the constants (PRAGMATA's domain shaders 859225c91a5fe2b2 and f1ad8f78c6c1551e read only the lane ID and have no uvec4)
|
||||
bound = hdr[3]; c = {}; types = []
|
||||
if uint is None: uint = bound; bound += 1; types.append([21 | 4 << 16, uint, 32, 0])
|
||||
if boolt is None: boolt = bound; bound += 1; types.append([20 | 2 << 16, boolt])
|
||||
if uvec4 is None: uvec4 = bound; bound += 1; types.append([23 | 4 << 16, uvec4, uint, 4])
|
||||
for nm in ('zero', 'one', 'zero4', 'one4', 'true'): c[nm] = bound; bound += 1
|
||||
consts = [[43 | 4 << 16, uint, c['zero'], 0], [43 | 4 << 16, uint, c['one'], 1], [44 | 7 << 16, uvec4, c['zero4'], c['zero'], c['zero'], c['zero'], c['zero']],
|
||||
consts = types + [[43 | 4 << 16, uint, c['zero'], 0], [43 | 4 << 16, uint, c['one'], 1], [44 | 7 << 16, uvec4, c['zero4'], c['zero'], c['zero'], c['zero'], c['zero']],
|
||||
[44 | 7 << 16, uvec4, c['one4'], c['one'], c['zero'], c['zero'], c['zero']], [41 | 3 << 16, boolt, c['true']]]
|
||||
out, placed = [], False
|
||||
for x in ins:
|
||||
@@ -739,7 +750,7 @@ def finish(key, w, j, c1):
|
||||
return 'ok', '', refl
|
||||
try: return geometry_finish(key, w, j, c1)
|
||||
except (ValueError, subprocess.CalledProcessError) as e: return 'geometry failed', str(e)[:160], None
|
||||
if j['stage'] == 'vs': spv_single_lane(os.path.join(w, key + '.spv')) # one-lane subgroups (see spv_single_lane)
|
||||
if j['stage'] in ('vs', 'ds'): spv_single_lane(os.path.join(w, key + '.spv')) # one-lane subgroups (see spv_single_lane); a domain shader is a vertex function in Metal too
|
||||
r = subprocess.run([SPIRV_CROSS, *dmsh_atomic.cross_args(XC, os.path.join(w, key + '.spv')), os.path.join(w, key + '.spv'), '--output', msl], capture_output=True, text=True)
|
||||
if r.returncode: return 'MSL failed', r.stderr.strip()[:160], None
|
||||
src = open(msl).read()
|
||||
@@ -756,6 +767,7 @@ def finish(key, w, j, c1):
|
||||
try: src = dmsh_atomic.check_msl(src)
|
||||
except ValueError as e: return 'image atomic MSL failed', str(e), None
|
||||
src = dmsh_rewrite.precise(src) # min / max / clamp with Maxwell's NaN results (see precise)
|
||||
src = dmsh_rewrite.membar_fence(src) # MEMBAR as a fence, not an execution barrier (see membar_fence)
|
||||
try: src = dmsh_fetch.select_guards(src) # bounded uniform reads as a load and a select, as the translator means them, not a branch for each (see dmsh_fetch.select_guards)
|
||||
except ValueError as e: return 'uniform bounds rewrite failed', str(e)[:160], None
|
||||
src = dmsh_rewrite.mul_extended(src) # scalar extended products without the optnone wrapper (see mul_extended)
|
||||
@@ -768,6 +780,7 @@ def finish(key, w, j, c1):
|
||||
try: src = dmsh_reflect.pool_arrays(src) # handles traced to no slot read the pools the replay keeps (see pool_arrays)
|
||||
except ValueError as e: return 'pool rewrite failed', str(e)[:160], None
|
||||
src = dmsh_wide.wide_loads(src) # storage words the translator split, read whole again (see dmsh_wide.py)
|
||||
src = dmsh_rewrite.tg_fence(src) # warp-synchronous shared memory: a simdgroup-scope fence after each threadgroup store (see tg_fence)
|
||||
src = dmsh_rewrite.border_emu(src) # border colours Metal lacks (see border_emu)
|
||||
if j['stage'] == 'ps': src = dmsh_rewrite.frag_z_snap(src)[0] # gl_FragCoord.z against a depth of its own surface (see frag_z_snap)
|
||||
blend0 = 0
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Translation chain tool fingerprints (written by tool_lock.py --update-lock; regenerate after changing tools and commit it)
|
||||
dmsh_xlate b59d042d9425c229
|
||||
xlate_source 657232fd201f16a1
|
||||
dmsh_xlate 90c1264b7831364c
|
||||
xlate_source fcb37fccd2f53012
|
||||
spirv-cross e37945d8e441d34d
|
||||
metal_macosx Apple metal version 32023.922 (metalfe-32023.922.4)
|
||||
metal_iphoneos Apple metal version 32023.922 (metalfe-32023.922.4)
|
||||
@@ -156,10 +156,15 @@ def int_outputs(src, body, cols):
|
||||
printed through the output's type. → the outputs with integers and no float bits, or, when none is that clean (a register reused by two branches), the outputs with integers"""
|
||||
types = {v: t for t, v in re.findall(r'^\s*(u?int\d?|float\d?|bool)\s+(_\d+)\b', body, re.M)}
|
||||
defs = collections.defaultdict(list)
|
||||
for v, e in re.findall(r'^\s*(?:(?:u?int\d?|float\d?|bool)\s+)?(_\d+)\s*=\s*([^;]+);', body, re.M): defs[v].append(e.strip())
|
||||
# An element of a local array (_30[0], a register the translator kept in one) is a local of its own: read as an expression it counted as a computed integer, and OCTOPATH
|
||||
# TRAVELER II's 05af5b1924d3b8b7 got colour 2 (floats) as its integer output once a float local was followed to as_type<float>(_30[0])
|
||||
for v, e in re.findall(r'^\s*(?:(?:u?int\d?|float\d?|bool)\s+)?(_\d+(?:\[\d+\])?)\s*=\s*([^;]+);', body, re.M): defs[v].append(e.strip())
|
||||
def kinds(e, seen):
|
||||
if re.fullmatch(r'_\d+', e):
|
||||
if types.get(e, '').startswith('float'): return {'float'}
|
||||
if re.fullmatch(r'_\d+(?:\[\d+\])?', e):
|
||||
if types.get(e, '').startswith('float'): # a float local is float bits, unless every value it takes is a register's bits (as_type<float>(…)): PRAGMATA's visibility shaders
|
||||
bits = [re.fullmatch(r'as_type<float\d?>\((.*)\)', x) for x in defs[e]] # write float _n = as_type<float>(int(gl_PrimitiveID)) into an RG32Uint target
|
||||
if not bits or not all(bits) or e in seen: return {'float'}
|
||||
seen.add(e); return set().union(*(kinds(b[1].strip(), seen) for b in bits))
|
||||
if e in seen: return set()
|
||||
seen.add(e); return set().union(*(kinds(x, seen) for x in defs[e])) if defs[e] else set()
|
||||
if re.fullmatch(r'-?\d+u?', e): return {'int'} if 0 < abs(int(e.rstrip('u'))) < 0x800000 else set()
|
||||
@@ -175,7 +180,7 @@ def int_outputs(src, body, cols):
|
||||
w = w.strip(); a = re.fullmatch(r'as_type<float\d?>\((.*)\)', w)
|
||||
if a: k |= kinds(a[1].strip(), set())
|
||||
elif re.fullmatch(r'-?[0-9.]+(?:e[-+]?\d+)?f?', w): k |= {'int'} if 0 < abs(float(w.rstrip('f'))) < 1.17549e-38 else set()
|
||||
else: k.add('float')
|
||||
else: k |= kinds(w, set()) if re.fullmatch(r'_\d+', w) else {'float'} # a local: what it holds (a float local is float bits unless it holds a register's)
|
||||
found[nm] = k
|
||||
return {nm for nm, k in found.items() if k == {'int'}} or {nm for nm, k in found.items() if 'int' in k}
|
||||
|
||||
@@ -204,13 +209,15 @@ def fs_uint(src):
|
||||
w = w.strip(); d = re.fullmatch(r'\w+', w) and re.search(r'\bfloat\d? %s = (in\.\w+(?:\.\w+)?);' % w, src)
|
||||
i = re.fullmatch(r'in\.(\w+)(?:\.\w+)?', d[1] if d else w)
|
||||
return bool(i and i[1] in flat)
|
||||
body = src[m.start():]; body = body[:body.find('return out;') + 1 or len(body)]
|
||||
ints = int_outputs(src, body, cols)
|
||||
if not from_int and not ints and not (writes and (all(re.fullmatch(r'-?[0-9.]+f?|float\d\([-0-9., ]*\)', w.strip()) for w in writes) or all(passed(w) for w in writes))): return None, 0
|
||||
uty = lambda ty: 'u' + ty.replace('float', 'int') # float4 → uint4, float → uint
|
||||
try: e = dmsh_side.entry(src, 'main0')
|
||||
except ValueError: e = None
|
||||
if not e: return None, 0
|
||||
# main0's whole body: every return's writes. Up to the first return out; only, PRAGMATA's visibility shaders (a9c1f9ea0c76a54c: an early return writing 0.0 after a discard, then the
|
||||
# primitive id's bits and the depth into an RG32Uint target) showed nothing but zeros, got no main0_u, and their mesh pipelines failed (float4 into RG32Uint): the 3D scene stayed black
|
||||
body = src[e['start']:e['end']]
|
||||
ints = int_outputs(src, body, cols)
|
||||
if not from_int and not ints and not (writes and (all(re.fullmatch(r'-?[0-9.]+f?|float\d\([-0-9., ]*\)', w.strip()) for w in writes) or all(passed(w) for w in writes))): return None, 0
|
||||
uty = lambda ty: 'u' + ty.replace('float', 'int') # float4 → uint4, float → uint
|
||||
def entry(sfx, as_uint): # main0_<sfx>: main0's body (dmsh_side.shared_body), its outputs in as_uint returned as the unsigned integer vectors of their bits
|
||||
struct = f'struct main0_out_{sfx}\n{{\n' + ''.join(f' {uty(cols[nm]) if nm in as_uint else ty} {nm} {at};\n' for ty, nm, at in mem) + '};\n\n'
|
||||
conv = f'return main0_out_{sfx}{{' + ', '.join(f'as_type<{uty(cols[nm])}>(out.{nm})' if nm in as_uint else f'out.{nm}' for _, nm, _ in mem) + '};'
|
||||
|
||||
@@ -14,7 +14,10 @@ threadgroups (nvn_geometry.inc mtk_encode). The task and object functions read t
|
||||
INPUT the payload a mesh shader's task wrote (ISBERD mode 0x38). Its word 0 is the mesh workgroup's number among its task's launches, which the hardware puts there
|
||||
outputs a task's payload (0xb8): its word 1 is the number of mesh workgroups to launch, its records start at +0x10
|
||||
or a mesh shader's attributes (0xf8): all blocks of 32 vertices (the components the SPH's OMAP enables, 0x80 bytes each, a word per vertex), followed by all blocks of 32
|
||||
primitives (the components the per-primitive SPH's OMAP enables, 0x80 bytes each, a word per primitive)
|
||||
primitives (the per-primitive SPH's system values (OMAP 0x34 and 0x35 bits 0..3: primitive id, layer, viewport, ...) before its generic attributes, 0x80 bytes
|
||||
each, a word per primitive). The primitive id is handed to Metal as the primitive's [[primitive_id]] (PRIMITIVE_BUILTINS), which the fragment stage reads as NVN's
|
||||
gl_PrimitiveID. PRAGMATA's mesh shaders (5aab38bb5ba67ef7) write a primitive id (0x35 bit 0): without its room it lay over the primitive count byte, and every
|
||||
workgroup drew nothing
|
||||
primitives a mesh shader's primitive bytes: the count at +3 (0x88), index bytes from +4 (0x80, control +0x5f per primitive: 1 point, 2 line, 3 triangle)
|
||||
"""
|
||||
import re
|
||||
@@ -43,6 +46,12 @@ def sph_outputs(sph):
|
||||
return out
|
||||
|
||||
|
||||
def sph_system(sph):
|
||||
"""The system-value components an SPH's OMAP enables besides the position (byte 0x34, byte 0x35 bits 0..3), lowest bit first."""
|
||||
bits = sph[0x34] | (sph[0x35] & 0xf) << 8
|
||||
return [b for b in range(12) if bits >> b & 1]
|
||||
|
||||
|
||||
def info(ctl, area):
|
||||
"""A task or mesh shader's facts from its control section and its whole code area (the SPH, the instructions, a mesh shader's second SPH): +0x58 its workgroup's threads, +0x5a its
|
||||
payload's bytes, +0x5e whether a mesh shader has a task, +0x5f a primitive's vertices, +0x60 / +0x62 a mesh shader's most vertices and primitives, +0x64 the offset of its per-primitive
|
||||
@@ -54,7 +63,8 @@ def info(ctl, area):
|
||||
max_v, max_p = struct.unpack_from('<2H', ctl, 0x60)
|
||||
at = struct.unpack_from('<I', ctl, 0x64)[0] if ctl[0x68] & 0x80 else 0
|
||||
prim = sph_outputs(area[at:at + 0x80]) if at else []
|
||||
out.update(task=bool(ctl[0x5e]), verts=ctl[0x5f] or 3, max_v=max_v, max_p=max_p, vertex=sph_outputs(area[:0x80]), primitive=[c for c in prim if isinstance(c[0], int)])
|
||||
out.update(task=bool(ctl[0x5e]), verts=ctl[0x5f] or 3, max_v=max_v, max_p=max_p, vertex=sph_outputs(area[:0x80]), primitive=[c for c in prim if isinstance(c[0], int)],
|
||||
primitive_system=len(sph_system(area[at:at + 0x80])) if at else 0, primitive_builtins=sph_system(area[at:at + 0x80]) if at else [])
|
||||
return out
|
||||
|
||||
|
||||
@@ -65,12 +75,38 @@ def memory(i):
|
||||
return [WORKGROUP, INPUT, out, out + i['payload']], out + (i['payload'] + 3 & ~3)
|
||||
# The guest's attribute stores: all vertex blocks of 32 vertices first, then all primitive blocks of 32 primitives, each block its own SPH's components (Ocarina of Time's
|
||||
# ee4ef51a4fddc28e, 128 vertices of 6 components and 64 primitives of 4, writes vertex v at (v / 32) * 768 + (v % 32) * 4 and primitive p at 3072 + (p / 32) * 512 + (p % 32) * 4)
|
||||
v_blocks = (max(i['max_v'], 1) + BLOCK - 1) // BLOCK
|
||||
p_blocks = (max(i['max_p'], 1) + BLOCK - 1) // BLOCK
|
||||
prim = out + max(v_blocks * len(i['vertex']) + p_blocks * len(i['primitive']), 1) * BLOCK * 4
|
||||
# A primitive block holds the per-primitive SPH's system values first, then its generic attributes (per_primitive)
|
||||
v_blocks, p_blocks = blocks_of(i['max_v']), blocks_of(i['max_p'])
|
||||
# (r9 review) with no per-primitive component this is smaller than r6's blocks_of(max(max_v, max_p)) when max_p > max_v; PRAGMATA's three record meshes (6adf14e9 4fcffc73 c0e44513:
|
||||
# 128/64, 128/128, 128/128) have max_p <= max_v, so their records' base (AosToSoa, words 4..6) is unchanged
|
||||
prim = out + max(v_blocks * len(i['vertex']) + p_blocks * per_primitive(i), 1) * BLOCK * 4
|
||||
# The guest writes the index bytes of primitive min(count - 1, lane + 32k) in each of its primitive blocks, and a meshlet count of 0 wraps count - 1, so every lane of every primitive
|
||||
# block writes: the bytes are reserved for whole blocks of 32 primitives, a primitive's vertices each (a mesh with max_p 126 wrote past 4 + 3 * 126, into the next workgroup's memory)
|
||||
return [WORKGROUP, INPUT, out, prim], prim + (4 + i.get('verts', 3) * p_blocks * BLOCK + 3 & ~3)
|
||||
# [4..6]: the vertex records the non-skew attribute addresses (ISBEWR / ISBERD .O.ATTR.32, mode 0xb8) name, right after the SoA area: InstEmitAmpereMem.cs AosToSoa
|
||||
# sends each to its SoA word (before, PRAGMATA 6adf14e9 / 4fcffc73 / c0e44513 wrote them over the primitive count and index bytes)
|
||||
n = max(len(i['vertex']), 1)
|
||||
return [WORKGROUP, INPUT, out, prim, prim - out, n, i['max_v'] * 4 * n], prim + (4 + i.get('verts', 3) * p_blocks * BLOCK + 3 & ~3)
|
||||
|
||||
|
||||
# The per-primitive system values a Metal mesh hands on, by their OMAP bit (attribute 0x40 + 4 * bit, NAK_ATTR_*): the primitive id (0x60). The fragment stage's [[primitive_id]] then
|
||||
# reads the value the mesh shader wrote, as NVN's gl_PrimitiveID does, and a vertex pipeline's fragment function (the same function) still reads Metal's own. The layer (0x64) and the
|
||||
# viewport (0x68) keep their room but are not handed on: no game's mesh shader is known to write them, and a layered mesh pass would need the host's layered-pass handling
|
||||
PRIMITIVE_BUILTINS = {8: ('dm_pid', 'primitive_id')}
|
||||
|
||||
|
||||
def primitive_builtins(i):
|
||||
"""[(the member's name, its Metal attribute, its component in a primitive block)] of the per-primitive system values the mesh function hands on."""
|
||||
return [PRIMITIVE_BUILTINS[b] + (k,) for k, b in enumerate(i.get('primitive_builtins', [])) if b in PRIMITIVE_BUILTINS]
|
||||
|
||||
|
||||
def blocks_of(n):
|
||||
"""Blocks of 32 for n vertices or primitives (at least one)."""
|
||||
return (max(n, 1) + BLOCK - 1) // BLOCK
|
||||
|
||||
|
||||
def per_primitive(i):
|
||||
"""A mesh shader's per-primitive components: its per-primitive system values, then its per-primitive attributes."""
|
||||
return i.get('primitive_system', 0) + len(i['primitive'])
|
||||
|
||||
|
||||
def own_shared(code):
|
||||
@@ -79,9 +115,12 @@ def own_shared(code):
|
||||
return any(struct.unpack_from('<H', code, o)[0] & 0xfff in (0x984, 0x388, 0x988, 0x38c, 0x98c, 0xf8c) for o in range(0, len(code) - 15, 16))
|
||||
|
||||
|
||||
# The kernel, its parameters, the thread variables spirv-cross declares ahead of the threadgroup memory (a private variable's initializer: GlobalToStorage.TryGenerateRawStorageOp's last entry,
|
||||
# uint _N = 0u;), and its stage memory, the first threadgroup array
|
||||
_KERNEL = re.compile(r'kernel\s+void\s+main0\s*\(((?:[^()]|\([^()]*\))*)\)\s*\{\s*((?:(?!threadgroup\b)[^\n{};]+;\n\s*)*)threadgroup\s+spvUnsafeArray<uint,\s*(\d+)>\s+(\w+);\n')
|
||||
# The kernel's head, through its stage memory array: SPIRV-Cross declares the array first, but dmsh_build.py loop_guard (which runs before to_stage) puts its counter
|
||||
# (uint dm_lg = 0u; (void)dm_lg;) as the body's first line, and spirv-cross declares a private variable's initializer ahead of it (GlobalToStorage.TryGenerateRawStorageOp's last entry, uint _N = 0u;),
|
||||
# so plain declarations before the array are taken along (group 2) and stay at the top of the body.
|
||||
# PRAGMATA's 539 mesh shaders all failed here when the array had to follow the brace
|
||||
_KERNEL = re.compile(r'kernel\s+void\s+main0\s*\(((?:[^()]|\([^()]*\))*)\)\s*\{[ \t]*\n((?:(?![ \t]*threadgroup\b)[ \t]+[^\n{}]*;[ \t]*\n)*?)'
|
||||
r'[ \t]*threadgroup\s+spvUnsafeArray<uint,\s*(\d+)>\s+(\w+);\n')
|
||||
_NAME = re.compile(r'(\w+)\s*(?:\[\[.*\]\])?$')
|
||||
_THREAD = re.compile(r'(uint3?)\s+(\w+)\s*\[\[(thread_position_in_threadgroup|threadgroup_position_in_grid)\]\]$')
|
||||
|
||||
@@ -172,10 +211,12 @@ def to_stage(msl, i, reads=None):
|
||||
if verts not in TOPOLOGY: raise ValueError(f'ms: primitive vertex count {verts} is not 1, 2 or 3')
|
||||
if max_v > METAL_MAX_VERTICES or max_p > METAL_MAX_PRIMITIVES: raise ValueError(f'ms: {max_v} vertices and {max_p} primitives exceed a Metal mesh')
|
||||
v_blocks = max(max(max_v, 1) + BLOCK - 1, 0) // BLOCK
|
||||
v_stride, p_stride = max(len(vertex), 1) * BLOCK, max(len(primitive), 1) * BLOCK # words of a vertex or primitive attribute block
|
||||
nsys = i.get('primitive_system', 0) # a primitive block's system values come first
|
||||
v_stride, p_stride = max(len(vertex), 1) * BLOCK, max(per_primitive(i), 1) * BLOCK # words of a vertex or primitive attribute block
|
||||
p_out = out + v_blocks * len(vertex) * BLOCK # per-primitive blocks follow all vertex blocks
|
||||
word = lambda comps: [f'{mem}[b + {comps[k] * BLOCK}u]' if comps[k] is not None else None for k in range(4)]
|
||||
vm, pm = _members(vertex), _members(primitive)
|
||||
vm, pm = _members(vertex), {n: [c + nsys if c is not None else None for c in v] for n, v in _members(primitive).items()}
|
||||
pb = primitive_builtins(i)
|
||||
# Each output as wide as its pixel shaders can see (_width): what Metal counts against a mesh's 32 KB is the declared outputs, and the float4 of every attribute the SPH names
|
||||
# put Ocarina of Time's foliage mesh 626fbf48041cb82b (160 vertices, 26 components written) at 35,840 bytes. A location they read that no SPH enables is padded (0,0,0,1)
|
||||
read = (lambda n: reads.get(n, 0)) if reads is not None else (lambda n: None)
|
||||
@@ -189,15 +230,16 @@ def to_stage(msl, i, reads=None):
|
||||
(' float point_size [[point_size]];\n' if 'psiz' in vm else '') +
|
||||
''.join(f' {_type(w)} a{n} [[user(locn{n})]];\n' for n, w in vw.items()) +
|
||||
''.join(f' {_type(w)} dm_pad{n} [[user(locn{n})]];\n' for n, w in mw.items()) + '};\n' +
|
||||
('struct dm_prim_t {\n' + ''.join(f' {_type(w)} p{n} [[user(locn{n})]];\n' for n, w in pw.items()) + '};\n' if pm else '') +
|
||||
f'using dm_mesh_t = metal::mesh<dm_vertex_t, {"dm_prim_t" if pm else "void"}, {max_v}, {max_p}, metal::topology::{TOPOLOGY[verts]}>;\n')
|
||||
('struct dm_prim_t {\n' + ''.join(f' uint {name} [[{attr}]];\n' for name, attr, _ in pb) + ''.join(f' {_type(w)} p{n} [[user(locn{n})]];\n' for n, w in pw.items()) + '};\n'
|
||||
if pm or pb else '') +
|
||||
f'using dm_mesh_t = metal::mesh<dm_vertex_t, {"dm_prim_t" if pm or pb else "void"}, {max_v}, {max_p}, metal::topology::{TOPOLOGY[verts]}>;\n')
|
||||
v_block = lambda v: f'{out}u + ({v} / {BLOCK}u) * {v_stride}u + {v} % {BLOCK}u'
|
||||
p_block = lambda p: f'{p_out}u + ({p} / {BLOCK}u) * {p_stride}u + {p} % {BLOCK}u'
|
||||
sets = ''.join(f' v.point_size = as_type<float>({word(c)[0]});\n' if n == 'psiz' else
|
||||
f' v.position = {_value(4, word(c))};\n' if n is None else
|
||||
f' v.a{n} = {_value(vw[n], word(c))};\n' for n, c in vm.items()) + \
|
||||
''.join(f' v.dm_pad{n} = {_value(w, [None] * 4)};\n' for n, w in mw.items())
|
||||
psets = ''.join(f' p.p{n} = {_value(pw[n], word(c))};\n' for n, c in pm.items())
|
||||
psets = ''.join(f' p.{name} = {mem}[b + {k * BLOCK}u];\n' for name, _, k in pb) + ''.join(f' p.p{n} = {_value(pw[n], word(c))};\n' for n, c in pm.items())
|
||||
if None not in vm: raise ValueError('ms: its SPH enables no position component')
|
||||
|
||||
def entry(name, gl):
|
||||
@@ -213,7 +255,7 @@ def to_stage(msl, i, reads=None):
|
||||
f' for (uint n = {lid}; n < {max_v}u; n += {thr}u)\n {{\n uint b = {v_block("n")};\n dm_vertex_t v;\n{sets}' +
|
||||
(' v.position.z = fma(v.position.z, 0.5, v.position.w * 0.5);\n' if gl else '') +
|
||||
' dm_out.set_vertex(n, v);\n }\n' +
|
||||
(f' for (uint n = {lid}; n < np; n += {thr}u)\n {{\n uint b = {p_block("n")};\n dm_prim_t p;\n{psets} dm_out.set_primitive(n, p);\n }}\n' if pm else '') +
|
||||
(f' for (uint n = {lid}; n < np; n += {thr}u)\n {{\n uint b = {p_block("n")};\n dm_prim_t p;\n{psets} dm_out.set_primitive(n, p);\n }}\n' if pm or pb else '') +
|
||||
f' for (uint n = {lid}; n < np * {verts}u; n += {thr}u)\n {{\n uint at = {prim + 4}u + n;\n dm_out.set_index(n, ({mem}[at >> 2] >> ((at & 3u) * 8u)) & 0xffu);\n }}\n}}\n')
|
||||
if i['task']: return src + '\n' + head + entry('main0', True) + '\n' + entry('main0_z', False)
|
||||
# The object function of a mesh shader with no task: one thread a block of METAL_MAX_GRID workgroups
|
||||
|
||||
@@ -280,6 +280,8 @@ def reflect(key, stage, msl, res):
|
||||
e.update(kind=abi.KIND_GMEM_MAP, rw=any(re.search(r'operation "(Store|Atomic\w*)" traced to no storage buffer', n) for n in res.get('notes', ()))); continue
|
||||
if stage == 'cs' and off is not None and abi.C0_CS_UBO <= off < abi.C0_CS_UBO + abi.C0_ROW * abi.C0_CS_UBO_SLOTS and (off - abi.C0_CS_UBO) % abi.C0_ROW == 0:
|
||||
e.update(kind=abi.KIND_UBO_PTR, reg=(off - abi.C0_CS_UBO) // abi.C0_ROW) # compute-stage uniform slot r: address at c0[C0_CS_UBO + 0x10 r], read through global memory (checked against cs_lut_combine_c reading cb10[66])
|
||||
elif b and b['cb_slot'] == abi.PUSH_BANK: # the address is one the game pushed (c[24]; PRAGMATA's compute buffer entries in push block 1): the host reads it from its push blocks
|
||||
e.update(kind=abi.KIND_SBUF_PUSH, off=b['cb_offset'] * 4)
|
||||
elif b and b['cb_slot'] >= 3: # the address is in the game's own uniform buffer c[n] = uniform slot n - 3 (Monster Hunter Rise's compute shaders: c3 + 0x38); the replay reads it there
|
||||
e.update(kind=abi.KIND_SBUF_UBO, reg=b['cb_slot'] - 3, off=b['cb_offset'] * 4)
|
||||
else: e['reg'] = (off - base) // abi.C0_ROW if off is not None and base is not None and 0 <= off - base < abi.C0_ROW * abi.C0_SSBO_SLOTS and (off - base) % abi.C0_ROW == 0 else None
|
||||
@@ -289,14 +291,59 @@ def reflect(key, stage, msl, res):
|
||||
DRV_FILL = {0: [(b, b + abi.C0_ROW * abi.C0_SSBO_SLOTS) for k, b in sorted(SSBO.items(), key=lambda kv: kv[1]) if k not in ('ts', 'ms')], # c0: storage buffer address tables (vertex / compute / geometry / pixel; a task or mesh stage's: unfillable())
|
||||
2: [(TEX_BASE, SEPTEX_BASE), (IMG_BASE, IMG_BASE + abi.C2_ROW * IMG_SLOTS), (SEPTEX_BASE, SAMP_BASE), (SAMP_BASE, SAMP_BASE + abi.C2_ROW * abi.C2_SEP_SLOTS)]} # c2: the handle tables above, all filled by the replay layer
|
||||
|
||||
INDEX_BUILTINS = {'gl_SampleID': (0, abi.C0_SAMPLE_BYTES - 1)} # a computed index's inputs known to be bounded: the sample index, below the sample count (at most the table's bytes)
|
||||
INDEX_DEF = re.compile(r'^\s*(?:int|uint)\s+(_\d+)\s*=\s*([^;\n]+);', re.M)
|
||||
INDEX_SET = re.compile(r'^\s*(_\d+)\s*=', re.M)
|
||||
|
||||
def index_range(src, expr):
|
||||
"""The range [lo, hi] of a computed vector index in the MSL, or None: an integer expression of literals and bounded builtins (INDEX_BUILTINS), through SPIRV-Cross's
|
||||
single-assignment int / uint temporaries and bit-casts, with + - * & | ^ << >> on non-negative values. Anything else (a float operation, a uniform read, a temporary
|
||||
assigned twice) gives None. PRAGMATA's 156 pixel shaders read the sample position table byte by byte at c0 0x620 + gl_SampleID (a689530d00090ebf: row 98)"""
|
||||
defs, sets = {}, set(INDEX_SET.findall(src)) # a temporary assigned again after its declaration (a loop's phi) has no single value
|
||||
for name, e in INDEX_DEF.findall(src): defs.setdefault(name, []).append(e)
|
||||
float_defs = dict(re.findall(r'^\s*float\s+(_\d+)\s*=\s*as_type<float>\(([\w.]+)\);', src, re.M)) # a bit-cast of a builtin into a float temporary keeps its bits
|
||||
import ast as _ast # here, so the reflection tests can lift this function alone (test_dmsh_reflect.py builder_unfillable)
|
||||
def ev(n, depth):
|
||||
if depth > 64: return None
|
||||
if isinstance(n, _ast.Constant) and isinstance(n.value, int): return (n.value, n.value)
|
||||
if isinstance(n, _ast.Name):
|
||||
if n.id in INDEX_BUILTINS: return INDEX_BUILTINS[n.id]
|
||||
if n.id in float_defs and float_defs[n.id] in INDEX_BUILTINS and n.id not in sets: return INDEX_BUILTINS[float_defs[n.id]]
|
||||
if len(defs.get(n.id, ())) != 1 or n.id in sets: return None
|
||||
return parse(defs[n.id][0], depth + 1)
|
||||
if isinstance(n, _ast.Call) and isinstance(n.func, _ast.Name) and n.func.id == '_c' and len(n.args) == 1 and not n.keywords: return ev(n.args[0], depth + 1)
|
||||
if not isinstance(n, _ast.BinOp): return None
|
||||
a, b = ev(n.left, depth + 1), ev(n.right, depth + 1)
|
||||
if a is None or b is None: return None
|
||||
op = type(n.op)
|
||||
if op is _ast.Add: r = (a[0] + b[0], a[1] + b[1])
|
||||
elif op is _ast.Sub: r = (a[0] - b[1], a[1] - b[0])
|
||||
elif op is _ast.Mult: r = (a[0] * b[0], a[1] * b[1])
|
||||
elif op is _ast.RShift and b[0] == b[1] and b[0] < 32: r = (a[0] >> b[0], a[1] >> b[0])
|
||||
elif op is _ast.LShift and b[0] == b[1] and b[0] < 32: r = (a[0] << b[0], a[1] << b[0])
|
||||
elif op is _ast.BitAnd: r = (0, min(a[1], b[1]))
|
||||
elif op in (_ast.BitOr, _ast.BitXor): r = (0, (1 << max(a[1], b[1]).bit_length()) - 1)
|
||||
else: return None
|
||||
return r if 0 <= r[0] <= r[1] < 1 << 31 else None
|
||||
def parse(e, depth):
|
||||
e = re.sub(r'\b(?:as_type<\s*u?int\s*>|u?int)\s*\(', '_c(', e) # integer casts and bit-casts keep a non-negative value's bits
|
||||
e = re.sub(r'\b(\d+)u\b', r'\1', e)
|
||||
try: tree = _ast.parse(e, mode='eval')
|
||||
except SyntaxError: return None
|
||||
return ev(tree.body, depth)
|
||||
return parse(expr, 0)
|
||||
|
||||
def drv_reads(src):
|
||||
"""Reads of driver segments c0 / c2 in the MSL: constant index → byte range; non-constant indices are recorded as dynamic"""
|
||||
"""Reads of driver segments c0 / c2 in the MSL: constant index → byte range; a computed index whose range is known (index_range) → the rows it can read;
|
||||
any other non-constant index is recorded as dynamic"""
|
||||
out = {}
|
||||
for bank in (0, 2):
|
||||
offs, dyn = set(), False
|
||||
for m in re.finditer(r'fp_c%d\)\._m0\[([^\]]+)\]' % bank, src):
|
||||
idx = m.group(1).rstrip('u')
|
||||
if idx.isdigit(): offs.add(int(idx) * 16)
|
||||
if idx.isdigit(): offs.add(int(idx) * 16); continue
|
||||
r = index_range(src, m.group(1))
|
||||
if r and r[1] - r[0] < 16: offs.update(range(r[0] * 16, r[1] * 16 + 16, 16))
|
||||
else: dyn = True
|
||||
if offs or dyn: out[str(bank)] = {'vec4_offsets': sorted(offs), 'dynamic': dyn}
|
||||
return out
|
||||
@@ -307,6 +354,7 @@ def unfillable(dr, stage):
|
||||
bad = []
|
||||
for bank, d in dr.items():
|
||||
fill = DRV_FILL[int(bank)] + (SAMPLE_ROWS if bank == '0' and stage == 'ps' else []) + ([(SSBO[stage], SSBO[stage] + abi.C0_ROW * abi.C0_SSBO_SLOTS)] if bank == '0' and stage in ('ts', 'ms') else [])
|
||||
if bank == '0' and stage == 'cs': fill = fill + [(abi.C0_CS_UBO, abi.C0_CS_UBO + abi.C0_ROW * abi.C0_CS_UBO_SLOTS)] # compute's uniform address table, which the host fills
|
||||
# a computed index into c2 reads one of its handle tables, which the replay layer fills whole (nvn_mtl.m DRV2: EA SPORTS FC 27's lights read the separate texture words
|
||||
# at 0x168 + 8i to test each light's handle); c0 is filled only in its tables and words above, so a computed index there may read what the replay does not write.
|
||||
# The one computed c0 index known is GLSLC's sample position lookup in a pixel shader: a byte of the table at 0x620, at an index made of the sample index (PIXLD.MYINDEX)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python3
|
||||
# The rewrites dmsh_build.py makes in a translated shader's MSL before it compiles it, where Metal or the translator falls short of what the Switch code does: precise
|
||||
# arithmetic (precise), 64-bit products (mul_extended), Ampere's HMMA as simdgroup matrices (hmma_msl), first stores and shared-memory stores (first_store,
|
||||
# arithmetic (precise), memory barriers as fences (membar_fence, tg_fence), 64-bit products (mul_extended), Ampere's HMMA as simdgroup matrices (hmma_msl), first stores and shared-memory stores (first_store,
|
||||
# shared_store_msl), threadgroup memory past Metal's limit (tg_spill), texture gathers with offsets (gather_offsets), border colours Metal has no sampler state for
|
||||
# (border_emu) and a pixel shader's depth snapped to its position (frag_z_snap). Functions of the MSL text and the library ABI only, with no build state, so tests import
|
||||
# them. Part of the translation chain (dmsh_chain.FILES) and of every shader's cache key (dmsh_build.py CODE_FP).
|
||||
@@ -11,6 +11,36 @@ import dmsh_abi as abi, dmsh_side
|
||||
# and its saturation gives 0, as Metal's precise:: functions (IEEE fmin / fmax) do on every GPU. The M4 Pro's fast ones happen to agree, an A20 Pro's do not: Super Mario Galaxy 2's
|
||||
# GX lighting takes max(0, NaN) from light directions left at zero, and the half of Mario its fill light faces came out white on the iPhone (GitHub issue 72; vk_shaders.py PRECISE)
|
||||
def precise(msl): return re.sub(r'\bfast::(min|max|clamp)\(', r'precise::\1(', msl)
|
||||
_MEMBAR = 'threadgroup_barrier(mem_flags::mem_device | mem_flags::mem_threadgroup | mem_flags::mem_texture);'
|
||||
def membar_fence(msl):
|
||||
"""MEMBAR as a fence, not a barrier. The translator turns BAR.SYNC into OpControlBarrier (workgroup scope; SPIRV-Cross prints threadgroup_barrier(mem_flags::mem_threadgroup)) and
|
||||
MEMBAR.GPU / .SYS into OpMemoryBarrier at device scope (Ryujinx CodeGen/Spirv/Instructions.cs GenerateMemoryBarrier), which SPIRV-Cross prints as a threadgroup_barrier with device,
|
||||
threadgroup and texture memory: an execution barrier the Switch code does not have. Where the threads of a group are not converged it waits for threads that never come.
|
||||
PRAGMATA's GPU culling queue 12a52b683eec95c1 has no BAR.SYNC at all, only MEMBAR.SC.GPU; ERRBAR inside its persistent work loop. Each becomes the fence it is,
|
||||
atomic_thread_fence at device scope, sequentially consistent; two in a row (MEMBAR.SC and ERRBAR) become one. From uncraftablexd's PRAGMATA bring-up (PR #1407)"""
|
||||
if _MEMBAR not in msl: return msl
|
||||
fence = 'atomic_thread_fence(mem_flags::mem_device | mem_flags::mem_threadgroup | mem_flags::mem_texture, memory_order_seq_cst, thread_scope_device); // MEMBAR (membar_fence)'
|
||||
msl = re.sub(r'^([ \t]*)' + re.escape(_MEMBAR) + r'\n\1' + re.escape(_MEMBAR) + r'$', lambda m: m[1] + _MEMBAR, msl, flags=re.M)
|
||||
return msl.replace(_MEMBAR, fence)
|
||||
|
||||
TG_FENCE_DECL = re.compile(r'\bthreadgroup\s+(?:spvUnsafeArray<[^;&]*?>|[A-Za-z_][\w<>, ]*?)\s*&?\s*(\w+)\s*(?:\[[^\]]*\])?\s*[;,)]')
|
||||
TG_FENCE = 'atomic_thread_fence(mem_flags::mem_threadgroup, memory_order_seq_cst, thread_scope_simdgroup);'
|
||||
def tg_fence(src):
|
||||
"""A store to threadgroup memory followed by a load of another lane's word, with no barrier between them (Ampere compilers rely on lockstep warps for small
|
||||
scans, e.g. Unreal's GPU radix sort downsweep d032ce5090303e01 at 0x2eb0: STS / LDS [x-4] / STS / LDS [x-8]): for one thread the load and the earlier store do not
|
||||
alias, so Metal moves the load above the store and reads another lane's old value (Orbitals: Niagara's sorted index list wrong every frame, beams and particles broken).
|
||||
A simdgroup-scope memory fence after each threadgroup store keeps the order; it is not an execution barrier, so it is safe in divergent code. Only kernels with a
|
||||
threadgroup array are touched. A plain or compound assignment (SPIRV-Cross folds a load, an operation and a store of the same element into `_46[i] += 1u;`), also to a
|
||||
member or component (`_39[i].x = v;`). From uncraftablexd's Orbitals bring-up (PR #1775)"""
|
||||
names = {m.group(1) for m in TG_FENCE_DECL.finditer(src) if m.group(1) not in ('operator',)}
|
||||
if not names: return src
|
||||
store = re.compile(r'^(\s*)(?:%s)\s*\[[^\n;]*\](?:\.\w+)?\s*(?:[-+*/%%&|^]|<<|>>)?=(?!=)[^\n]*;\s*$' % '|'.join(map(re.escape, sorted(names))))
|
||||
out = []
|
||||
for ln in src.split('\n'):
|
||||
out.append(ln)
|
||||
m = store.match(ln)
|
||||
if m: out.append(m.group(1) + TG_FENCE)
|
||||
return '\n'.join(out)
|
||||
|
||||
# spirv-cross writes OpUMulExtended / OpSMulExtended as calls of an optnone template, spvMulExtended, as Metal's compiler may fail on an inlined mulhi (spirv_msl.cpp,
|
||||
# SPVFuncImplMulExtended). The barrier keeps every product a call that is never folded: Switch 2 shaders divide by constants through the high word of a product (Ocarina of Time
|
||||
|
||||
@@ -68,6 +68,7 @@ static class SwshXlate
|
||||
// c1 constant segment (the 0x100 bytes before the control segment in the shader package): the jump table of indirect jump BRX lives here (LDC c[1]); without it the translator cannot resolve jump targets and control flow goes wrong (particle shaders loop forever)
|
||||
public int QueryConstantBuffer1Size() => _c1.Length;
|
||||
public int[] QueryAmpereComputeC0Layout() => _job["nvn2_cs"] is JsonArray l ? l.Select(v => (int)v).ToArray() : null;
|
||||
public int QueryAmpereStageBank() => _job["stage_bank"] is JsonNode b ? (int)b : -1; // an NVN2 graphics stage's own bank, its push block 1 + stage index (dmsh_build.py job_for)
|
||||
public int[] QueryAmpereStageMemory() => _job["stage_memory"] is JsonArray l ? l.Select(v => (int)v).ToArray() : null; // a task or mesh shader (dmsh_meshstage.py)
|
||||
public uint ConstantBuffer1Read(int offset) { if (offset >= 0 && offset + 4 <= _c1.Length) return BitConverter.ToUInt32(_c1, offset); Notes.Add($"c1 read out of bounds +{offset:X} (c1 length {_c1.Length})"); return 0; }
|
||||
// All resources go into set 0, each with a distinct binding number (spirv-cross emits them as one argument buffer); the translator's convention of giving the buffer of constant segment number index binding = index+1 is not relied on
|
||||
|
||||
Binary file not shown.
@@ -57,7 +57,7 @@
|
||||
# With an update: give RomFS and main as comma-separated lists (base game first, e.g. data/v0/RomFS,data/v327680/RomFS); the output is the union of both versions (see main())
|
||||
# Unity type trees need Unity's common string table, which is taken from the first main
|
||||
# Pair table: (vertex key, pixel key) of every BNSH variation (every Unity program); dmsh_build uses it to give vertex shaders the outputs their pixel shaders read but they do not write (see dmsh_build.py vs_pad)
|
||||
import base64, collections, concurrent.futures as cf, glob, hashlib, json, os, re, struct, subprocess, sys, time, zlib
|
||||
import base64, collections, concurrent.futures as cf, functools, glob, hashlib, json, os, re, struct, subprocess, sys, time, zlib
|
||||
from typing import NoReturn
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../tools'))
|
||||
from romfs import os, open, is_image
|
||||
@@ -614,23 +614,53 @@ def linkdata_shaders(path, rel, rng, out):
|
||||
if n: kt_shaders(d[off:off + (stored if comp else n)], f'/{rel}#{i}', out)
|
||||
|
||||
KPKA = b'KPKA'
|
||||
KPKA_BLOCKS = 0x20 # header feature: a block table follows the entries
|
||||
KPKA_IN_BLOCKS = 0x1000000 # entry attribute: the entry's data is in the block table's blocks
|
||||
SDF_STAGES = ['vs', 'hs', 'ds', 'gs', 'ps', 'cs'] # an SDF entry's stage offsets, in BNSH order
|
||||
def kpka_entries(path):
|
||||
"""Capcom's RE Engine PAK (Monster Hunter Rise: re_chunk_000.pak plus 16 .patch_NNN.pak, 19.6 GB): 'KPKA', u8 version 4, u8 0, u16 features (0: the table is not encrypted), u32 count, u32 fingerprint,
|
||||
then count 0x30-byte entries {u32 hash of the lower-case path, u32 hash of the upper-case path, u64 offset, u64 stored length, u64 length, u64 attributes, u64 checksum}.
|
||||
"""Capcom's RE Engine PAK (Monster Hunter Rise: re_chunk_000.pak plus 16 .patch_NNN.pak, 19.6 GB): 'KPKA', u8 version 4, u8 minor version, u16 features, u32 count, u32 fingerprint,
|
||||
then count 0x30-byte entries {u64 path hash, u64 offset, u64 stored length, u64 length, u64 attributes, u64 checksum}. Monster Hunter Rise's PAKs are minor version 0 with no feature
|
||||
(its path hash is two u32 murmur hashes, lower- then upper-case path); PRAGMATA's (Switch 2) are minor version 2 with feature KPKA_BLOCKS (kpka_blocks).
|
||||
Attribute bits 0-3: 0 stored, 1 raw deflate, 2 zstd. → [(path hash, offset, stored length, length, attributes)]"""
|
||||
with open(path, 'rb') as f:
|
||||
h = f.read(16)
|
||||
if h[:4] != KPKA: return None
|
||||
ver, feat, n = h[4], struct.unpack_from('<H', h, 6)[0], struct.unpack_from('<I', h, 8)[0]
|
||||
if ver != 4 or feat: red(f'{path}: PAK version {ver}, features {feat:#x}: only version 4 with a plain entry table is known')
|
||||
if ver != 4 or feat & ~KPKA_BLOCKS: red(f'{path}: PAK version {ver}, features {feat:#x}: only version 4 with a plain entry table, or with a block table (0x20), is known')
|
||||
t = f.read(0x30 * n)
|
||||
return [(lo | hi << 32, off, csz, usz, attr) for lo, hi, off, csz, usz, attr, _ in struct.iter_unpack('<IIqqqqQ', t)]
|
||||
return [e[:5] for e in struct.iter_unpack('<Qqqqqq', t)]
|
||||
|
||||
def kpka_data(d, e, head=None):
|
||||
"""An entry's data (head: only its first bytes)"""
|
||||
@functools.lru_cache(maxsize=8)
|
||||
def kpka_blocks(path):
|
||||
"""The block table of a PAK with feature KPKA_BLOCKS (PRAGMATA's re_chunk_000.pak: 51,006 blocks, 3,288 of its 88,582 entries, the Wwise packs and movies), right after the entries:
|
||||
u32 block length (0x80000), u32 block count, then one u64 per block, its stored length in bits 42-63 and its offset in the file in bits 0-41. A block whose stored length is the block length
|
||||
is stored, any other is one zstd frame of a whole block (the last block of an entry is padded). An entry with attribute KPKA_IN_BLOCKS starts at the block its offset field names, and its
|
||||
stored length is the sum of its blocks' stored lengths. → (block length, [(offset, stored length)]), or None"""
|
||||
with open(path, 'rb') as f:
|
||||
h = f.read(16)
|
||||
if h[:4] != KPKA or not struct.unpack_from('<H', h, 6)[0] & KPKA_BLOCKS: return None
|
||||
f.seek(16 + 0x30 * struct.unpack_from('<I', h, 8)[0])
|
||||
bl, nb = struct.unpack('<II', f.read(8))
|
||||
return bl, [(b & (1 << 42) - 1, b >> 42) for b in struct.unpack(f'<{nb}Q', f.read(8 * nb))]
|
||||
|
||||
def kpka_block_data(d, e, blocks, head=None):
|
||||
"""An entry with attribute KPKA_IN_BLOCKS: its (still compressed, attribute bits 0-3) bytes, joined from its blocks"""
|
||||
bl, bs = blocks; out = bytearray(); want = min(head or e[3], e[3]); i = e[1]
|
||||
while len(out) < want:
|
||||
if i >= len(bs): red(f'PAK entry {e[0]:016x}: block {i} is past the block table ({len(bs)} blocks)'); return bytes(out)
|
||||
off, n = bs[i]; raw = d[off:off + n]
|
||||
out += raw if n == bl else zstd_mod().decompress(raw); i += 1
|
||||
return bytes(out[:want])
|
||||
|
||||
def kpka_data(d, e, head=None, blocks=None):
|
||||
"""An entry's data (head: only its first bytes); blocks: kpka_blocks of its PAK, for an entry with attribute KPKA_IN_BLOCKS"""
|
||||
import zlib
|
||||
_, off, csz, usz, attr = e; raw = d[off:off + csz]
|
||||
_, off, csz, usz, attr = e
|
||||
if attr & KPKA_IN_BLOCKS:
|
||||
if not blocks: return red(f'PAK entry {e[0]:016x}: its data is in blocks, but its PAK has no block table')
|
||||
if attr & 0xf: return red(f'PAK entry {e[0]:016x}: compression {attr & 0xf} inside blocks is not known')
|
||||
return kpka_block_data(d, e, blocks, head)
|
||||
raw = d[off:off + csz]
|
||||
if attr & 0xf == 0: return raw[:head] if head else raw
|
||||
if attr & 0xf == 1: return zlib.decompressobj(-15).decompress(raw, head or 0)
|
||||
if attr & 0xf == 2:
|
||||
@@ -654,29 +684,73 @@ def kpka_jobs(files, parts=64):
|
||||
jobs += [(p_, r_, tuple(es)) for (p_, r_), es in cur.items()]
|
||||
return jobs, {p for p, _ in paks}
|
||||
|
||||
SDF_LAYOUTS = ((0x10, 0x108, 0, 8), (0x18, 0x110, 8, 0x58)) # (first entry, entry length, the stage record's lengths at, its control section at), sdf_shaders
|
||||
def sdf_layout(d, n, label):
|
||||
"""The one SDF_LAYOUTS entry under which every stage offset of every entry leads to a control section; both layouts are SDF version 1"""
|
||||
def fits(lay):
|
||||
base, size, lens, at = lay
|
||||
if base + size * n > len(d): return False
|
||||
offs = [o for i in range(n) for o in struct.unpack_from('<6Q', d, base + size * i + 0x10) if o]
|
||||
return bool(offs) and all(o + at + 4 <= len(d) and d[o + at:o + at + 4] == CTL_MAGIC for o in offs)
|
||||
lay = [x for x in SDF_LAYOUTS if fits(x)]
|
||||
if len(lay) != 1: red(f'{label}: the SDF entries fit {len(lay)} of the {len(SDF_LAYOUTS)} known layouts')
|
||||
return lay[0]
|
||||
|
||||
def sdf_shaders(d, label):
|
||||
"""RE Engine shader definition ('SDF\\0', 2,685 entries in Monster Hunter Rise's PAKs): u16 version 1, u16 entry count, u64, then 0x108-byte entries from +0x10. Entry +0x10: six u64 offsets
|
||||
(vertex, hull, domain, geometry, pixel, compute; 0 = no stage), each to {u32 control length, u32 code length} followed by the control section and the code area. Compute code has no header.
|
||||
"""RE Engine shader definition ('SDF\\0'): u16 version 1, u16 entry count, then one of two layouts (sdf_layout picks the one the file's offsets fit). Each entry has six u64 offsets at +0x10
|
||||
(vertex, hull, domain, geometry, pixel, compute; 0 = no stage), each to a stage record of {u32 control length, u32 code length} followed by the control section and the code area. Compute code has no header.
|
||||
· Monster Hunter Rise (2,685 SDF files in its PAKs, SDK 11) and Ghost Trick: a u64, then 0x108-byte entries from +0x10; the record is the two lengths, then the control section.
|
||||
· PRAGMATA (759 files, Switch 2, NVN2): two u64s, then 0x110-byte entries from +0x18 (entry +0: the offset of its name); the record is a 0x58-byte header, the lengths at +8 after a u64 hash,
|
||||
then the control section.
|
||||
The stages of one entry form a program, so its vertex / pixel stages are a pair"""
|
||||
ver, n = field(d, '<HH', 4, f'{label} SDF header'); out = []
|
||||
if not ver and not n: return out # an empty definition: 16 bytes, version 0, no entries
|
||||
if ver != 1: red(f'{label}: SDF version {ver}')
|
||||
if not n: return out
|
||||
base, size, lens, at = sdf_layout(d, n, label)
|
||||
for i in range(n):
|
||||
offs = field(d, '<6Q', 0x10 + 0x108 * i + 0x10, f'{label} SDF entry {i}')
|
||||
offs = field(d, '<6Q', base + size * i + 0x10, f'{label} SDF entry {i}')
|
||||
for st, o in zip(SDF_STAGES, offs):
|
||||
if not o: continue
|
||||
nctl, ncode = field(d, '<II', o, f'{label} SDF entry {i} {st}'); b = span(d, o + 8, nctl + ncode, f'{label} SDF entry {i} {st}'); ctl, code = b[:nctl], b[nctl:]
|
||||
nctl, ncode = field(d, '<II', o + lens, f'{label} SDF entry {i} {st}'); b = span(d, o + at, nctl + ncode, f'{label} SDF entry {i} {st}'); ctl, code = b[:nctl], b[nctl:]
|
||||
why = check(label, st, ctl, code)
|
||||
if not why and st != 'cs' and sph_stage(code) != st: why = 'the SPH stage does not match the entry slot'
|
||||
if not why and nvn2_ctl(ctl): # NVN2: the stage from the control section or the SPH (nvn2_stage); PRAGMATA keeps its 1,407 mesh shaders in the hull slot
|
||||
got = nvn2_stage(ctl, code)
|
||||
if got == st or (st, got) == ('hs', 'ms'): st = got
|
||||
else: why = f'the stage ({got}) does not match the entry slot'
|
||||
elif not why and st != 'cs' and sph_stage(code) != st: why = 'the SPH stage does not match the entry slot'
|
||||
if why: red(f'{label} SDF entry {i} {st}: {why}')
|
||||
out.append((f'{label}#SDF#var{i}', st, ctl, code))
|
||||
return out
|
||||
|
||||
def kpka_shaders(path, rel, ents, out):
|
||||
from romfs import mmap
|
||||
blocks = kpka_blocks(path)
|
||||
with open(path, 'rb') as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as d:
|
||||
for e in ents:
|
||||
if e[3] >= 0x10 and kpka_data(d, e, 4) == b'SDF\0': out.extend(sdf_shaders(kpka_data(d, e), f'/{rel}#{e[0]:016x}'))
|
||||
if e[3] < 0x10: continue
|
||||
head = kpka_data(d, e, 4, blocks)
|
||||
if head == b'SDF\0': out.extend(sdf_shaders(kpka_data(d, e, blocks=blocks), f'/{rel}#{e[0]:016x}'))
|
||||
elif head == OCIO: out.extend(ocio_shaders(kpka_data(d, e, blocks=blocks), f'/{rel}#{e[0]:016x}'))
|
||||
|
||||
OCIO = b'OCIO'
|
||||
def ocio_shaders(d, label):
|
||||
"""RE Engine's OpenColorIO pipelines ('OCIO'): the colour transforms the frame's last passes draw with (PRAGMATA: its tonemap and display transform; the frame's final composite had no shaders
|
||||
without them, so the picture came out cyan-saturated with each new subtitle drawn over the old ones). Their shaders are stage records as in PRAGMATA's SDF files: a 0x58-byte header with the
|
||||
control section's and the code area's lengths at +8, the control section, the code area. Found by scanning for NVN2 control sections whose record header names their length and whose +0x44
|
||||
names the code area's after them, since the file's own tables are not known. Single stages: the program a pipeline pairs them into is in those tables"""
|
||||
out, other = [], 0
|
||||
for m in re.finditer(re.escape(CTL_MAGIC), d):
|
||||
c = m.start()
|
||||
if c < 0x50 or c & 3: continue # 4-byte aligned: the larger OCIO files pack their records so (8ae6c7ee83bc0563: 63 of its 65; compute 2ceb3ec288321a37 at 0x3a9f3c)
|
||||
nctl, ncode = struct.unpack_from('<II', d, c - 0x50)
|
||||
ctl, code = d[c:c + nctl], d[c + nctl:c + nctl + ncode]
|
||||
if len(code) != ncode or not nctl or not nvn2_ctl(ctl): other += ctl[:4] == CTL_MAGIC and not nvn2_ctl(ctl); continue
|
||||
st = nvn2_stage(ctl, code)
|
||||
if (why := check(label, st, ctl, code)): red(f'{label} OCIO record @{c - 0x58:#x} {st}: {why}'); continue
|
||||
out.append((f'{label}#OCIO@{c - 0x58:x}', st, ctl, code))
|
||||
if other: print(f'[RED] {label}: {other} control sections of a GPU other than NVN2 in an OCIO file are left out (no such file has been read yet)', file=sys.stderr)
|
||||
return out
|
||||
|
||||
PKZL, PGDAT = b'pkzl', b'DAT\0'
|
||||
PG_STAGES = {b'VSO\0': 'vs', b'HSO\0': 'hs', b'DSO\0': 'ds', b'GSO\0': 'gs', b'PSO\0': 'ps', b'CSO\0': 'cs'}
|
||||
|
||||
@@ -157,6 +157,7 @@ static void crash_gate(int sig) {
|
||||
if (none == me) _exit(128 + sig);
|
||||
for (;;) pause();
|
||||
}
|
||||
__attribute__((weak)) void dm_gfx_addr_note(uint64_t a, char *note, size_t n) { (void)a; if (n) note[0] = 0; } // nvn_mtl.m provides the strong definition
|
||||
static void on_crash(int sig, siginfo_t *si, void *uc_) {
|
||||
ucontext_t *uc = uc_;
|
||||
if (sig == SIGTRAP && g_trap_hook && g_trap_hook(uc)) return;
|
||||
@@ -191,6 +192,33 @@ static void on_crash(int sig, siginfo_t *si, void *uc_) {
|
||||
for (int k = 0; k < 6; k++) off("", w[k]);
|
||||
fputc('\n', stderr);
|
||||
}
|
||||
// What the graphics layer knows of the addresses in the registers (dm_gfx_addr_note: the memory pool, a texture's storage, a GPU write the host recorded on the page). A game's own
|
||||
// data overwritten with float words (PRAGMATA's render command lists) asks whether the GPU or a host copy wrote there
|
||||
for (int i = 0; i < 29; i++) {
|
||||
uint64_t a = uc->uc_mcontext->__ss.__x[i]; char note[512]; note[0] = 0;
|
||||
if (a < 0x100000000ull) continue;
|
||||
dm_gfx_addr_note(a, note, sizeof note);
|
||||
if (note[0]) fprintf(stderr, "[dm] x%d %#llx:%s\n", i, (unsigned long long)a, note);
|
||||
}
|
||||
// DM_CRASH_PEEK="sp+0x248*,x22-0x20": 0x100 bytes at each address, given as sp or a register plus or minus an offset, a trailing * reading the pointer stored there first
|
||||
// (PRAGMATA's render function keeps its current draw item at sp + 0x248: the item and what it points at tell where a bad pointer came from); with what the graphics layer knows of it
|
||||
if (getenv("DM_CRASH_PEEK")) {
|
||||
char spec[512]; snprintf(spec, sizeof spec, "%s", getenv("DM_CRASH_PEEK"));
|
||||
for (char *tok = strtok(spec, ","); tok; tok = strtok(NULL, ",")) {
|
||||
uint64_t a = 0; char *p = tok;
|
||||
if (!strncmp(p, "sp", 2)) { a = uc->uc_mcontext->__ss.__sp; p += 2; }
|
||||
else if (*p == 'x') { long r = strtol(p + 1, &p, 10); if (r < 0 || r > 28) continue; a = uc->uc_mcontext->__ss.__x[r]; }
|
||||
else continue;
|
||||
if (*p == '+' || *p == '-') { long long d = strtoll(p, &p, 0); a += (uint64_t)d; }
|
||||
if (*p == '*') { uint64_t v = 0; vm_size_t got = 0; if (vm_read_overwrite(mach_task_self(), (vm_address_t)a, 8, (vm_address_t)&v, &got) != KERN_SUCCESS || got != 8) { fprintf(stderr, "[dm] peek %s: %#llx unreadable\n", tok, (unsigned long long)a); continue; } a = v; }
|
||||
uint64_t w[32]; vm_size_t got = 0; char note[512]; note[0] = 0;
|
||||
if (vm_read_overwrite(mach_task_self(), (vm_address_t)a, sizeof w, (vm_address_t)w, &got) != KERN_SUCCESS || got != sizeof w) { fprintf(stderr, "[dm] peek %s: %#llx unreadable\n", tok, (unsigned long long)a); continue; }
|
||||
dm_gfx_addr_note(a, note, sizeof note);
|
||||
fprintf(stderr, "[dm] peek %s = %#llx:%s", tok, (unsigned long long)a, note);
|
||||
for (int k = 0; k < 32; k++) { if (!(k % 4)) fprintf(stderr, "\n[dm] +%#04x", k * 8); off("", w[k]); }
|
||||
fputc('\n', stderr);
|
||||
}
|
||||
}
|
||||
dm_backtrace(uc->uc_mcontext->__ss.__fp);
|
||||
// Stack scan: when the frame chain is broken (a return address was overwritten, pc = lr lands on garbage) the backtrace prints nothing; scan 512 words up from sp and list everything that resolves to a module / host symbol (nearest callers first)
|
||||
{ uint64_t sp = uc->uc_mcontext->__ss.__sp; // The frame just popped (when a return address was overwritten, the bad value and the leftovers of whatever overwrote it sit below sp)
|
||||
|
||||
@@ -353,7 +353,11 @@ static Result cv_dec_submit(uint64_t *out, void *t, const void *data, uint64_t s
|
||||
if (d->nheld >= CV_HOLD) { static int n; if (n++ < 4) LOG("nn::codec %s: busy (result 3603), a packet refused with %d pictures waiting for a released buffer",k_cv_name[d->codec], d->nheld); if (d->event) hle_clear_system_event(d->event); pthread_mutex_unlock(&d->mu); return CV_BUSY; }
|
||||
int got = 0;
|
||||
if (d->codec == CV_H264 && d->avc) { // VideoToolbox reorders: pictures leave in presentation order, all of them at the end of the stream
|
||||
if (size && mavc_decode(d->avc, data, (int)size, ts / 1000) < 0) { static int n; if (n++ < 4) LOG("[RED] nn::codec H.264: VideoToolbox could not decode a packet"); }
|
||||
if (size && mavc_decode(d->avc, data, (int)size, ts / 1000) < 0) { // with the packet's first bytes: how its NAL units are framed
|
||||
static int n; const uint8_t *b = data;
|
||||
if (n++ < 4) LOG("[RED] nn::codec H.264: VideoToolbox could not decode a packet (%llu bytes: %02x %02x %02x %02x %02x %02x %02x %02x)", (unsigned long long)size,
|
||||
b[0], size > 1 ? b[1] : 0, size > 2 ? b[2] : 0, size > 3 ? b[3] : 0, size > 4 ? b[4] : 0, size > 5 ? b[5] : 0, size > 6 ? b[6] : 0, size > 7 ? b[7] : 0);
|
||||
}
|
||||
uint8_t *nv12 = malloc((size_t)d->w * d->h * 3 / 2); int64_t pts = 0;
|
||||
while (nv12 && d->nheld < CV_HOLD && mavc_take(d->avc, eos, nv12, d->w, d->h, &pts) == 1) { vpx_image_t *c = nv12_to_i420(nv12, d->w, d->h); if (c) got += cv_hold(d, c, pts * 1000); }
|
||||
free(nv12);
|
||||
@@ -400,11 +404,17 @@ static Result cv_dec_props(uint16_t *w, uint16_t *h, uint16_t *cw, uint16_t *ch,
|
||||
return ok ? 0 : CV_NONE;
|
||||
}
|
||||
static Result cv_dec_encrypted(void) { static int once; if (!once++) LOG("[RED] nn::codec: an encrypted input buffer: protected streams are not served"); return CV_R(2004); }
|
||||
// Each decoder type's entry points, by their names in the SDK (the work buffer, the two Initialize overloads without the H.264 parameter sets, …)
|
||||
// Each decoder type's entry points, by their names in the SDK (the work buffer, the two Initialize overloads, …). H.264's two Initialize overloads end with the stream's parameter
|
||||
// sets (SPS / PPS: a pointer and a size), which the others do not have: read only for H.264. Past the eight registers the guest's AAPCS64 gives each argument an 8-byte slot where
|
||||
// Apple's arm64 packs them, so those are declared 64 bits wide. PRAGMATA (SDK 20.5.15) gives its movies' parameter sets only there: none in the stream, whose packets start with
|
||||
// an SEI, so with them dropped VideoToolbox had no format and every movie stayed black
|
||||
#define CV_FAMILY(tag, codec, s_work, s_init, s_init2, s_fin, s_reg, s_unreg, s_start, s_stop, s_flush, s_ev, s_sub, s_enc, s_acq, s_rel, s_props) \
|
||||
HLE_FORCE(s_work, "the host decoder needs no work memory", Result, h_cv_##tag##work, uint64_t *size, uint64_t *align, uint64_t bs, uint16_t w, uint16_t h) { (void)bs; (void)w; (void)h; *size = 0x1000; *align = 0x1000; return 0; } \
|
||||
HLE_FORCE(s_init, "decoded on the host", Result, h_cv_##tag##init, void *t, void *work, uint64_t wsize, uint64_t bs, uint16_t w, uint16_t h, uint32_t refs, uint32_t in, uint32_t out) { (void)work; (void)wsize; (void)bs; (void)refs; return cv_dec_init(t, codec, w, h, in, out, NULL, 0); } \
|
||||
HLE_FORCE(s_init2, "decoded on the host", Result, h_cv_##tag##init2, void *t, uint64_t bs, uint16_t w, uint16_t h, uint32_t refs, uint32_t in, uint32_t out) { (void)bs; (void)refs; return cv_dec_init(t, codec, w, h, in, out, NULL, 0); } \
|
||||
HLE_FORCE(s_init, "decoded on the host", Result, h_cv_##tag##init, void *t, void *work, uint64_t wsize, uint64_t bs, uint16_t w, uint16_t h, uint32_t refs, uint32_t in, uint64_t out, \
|
||||
const void *csd, uint64_t csd_n) { (void)work; (void)wsize; (void)bs; (void)refs; \
|
||||
return cv_dec_init(t, codec, w, h, in, (uint32_t)out, codec == CV_H264 ? csd : NULL, codec == CV_H264 ? csd_n : 0); } \
|
||||
HLE_FORCE(s_init2, "decoded on the host", Result, h_cv_##tag##init2, void *t, uint64_t bs, uint16_t w, uint16_t h, uint32_t refs, uint32_t in, uint32_t out, const void *csd, uint64_t csd_n) { \
|
||||
(void)bs; (void)refs; return cv_dec_init(t, codec, w, h, in, out, codec == CV_H264 ? csd : NULL, codec == CV_H264 ? csd_n : 0); } \
|
||||
HLE_FORCE(s_fin, "frees the host decoder", Result, h_cv_##tag##fin, void *t) { return cv_dec_fin(t); } \
|
||||
HLE_FORCE(s_reg, "a buffer of the host decoder, acquirable at once", Result, h_cv_##tag##reg, void *t, uint32_t i, void *pool, uint32_t pidx) { return cv_dec_reg(t, i, pool, pidx); } \
|
||||
HLE_FORCE(s_unreg, "the buffer leaves the host decoder", Result, h_cv_##tag##unreg, void *t, uint32_t i) { return cv_dec_unreg(t, i); } \
|
||||
@@ -437,7 +447,7 @@ CV_FAMILY(vp8, CV_VP8, "_ZN2nn5codec29CalculateVp8DecoderWorkBufferEPmS1_mtt",
|
||||
"_ZN2nn5codec36SubmitEncryptedVp8DecoderInputBufferEPmPNS0_14Vp8DecoderTypeEPKNS0_18EncryptionPropertyEPKvmNS_8TimeSpanEb",
|
||||
"_ZN2nn5codec29AcquireVp8DecoderOutputBufferEPjPNS_2gs16NativeSyncHandleEPNS0_14Vp8DecoderTypeE", "_ZN2nn5codec29ReleaseVp8DecoderOutputBufferEPNS0_14Vp8DecoderTypeEjNS_2gs16NativeSyncHandleE",
|
||||
"_ZN2nn5codec35GetVp8DecoderOutputBufferPropertiesEPtS1_S1_S1_PNS_8TimeSpanEPbPNS0_14Vp8DecoderTypeEj")
|
||||
// H.264: its Initialize overloads also take the stream's parameter sets (SPS / PPS, a pointer and a size), one of them an output mode too
|
||||
// H.264: its Initialize overloads also take the stream's parameter sets (read above); the one with an output mode too is below
|
||||
CV_FAMILY(h264, CV_H264, "_ZN2nn5codec30CalculateH264DecoderWorkBufferEPmS1_mtt",
|
||||
"_ZN2nn5codec21InitializeH264DecoderEPNS0_15H264DecoderTypeEPvmmttjNS0_23VideoDecoderInputFormatENS0_24VideoDecoderOutputFormatEPKvm",
|
||||
"_ZN2nn5codec21InitializeH264DecoderEPNS0_15H264DecoderTypeEmttjNS0_23VideoDecoderInputFormatENS0_24VideoDecoderOutputFormatEPKvm",
|
||||
|
||||
+10
-1
@@ -223,7 +223,8 @@ void hid_keys_init(void) {
|
||||
// (hle_fpslock.c dm_ctl_cvar_f32; "cvari" an int one), "peek <address> <count>" logs that many floats of guest memory, "memdump <address> <bytes> <path>" saves guest memory
|
||||
// to a file (a buffer texture's storage, which the pass dump's tbuf lines print, holds what the GPU wrote: buffer textures are views of the pool), "texlist <NVN target>" logs the
|
||||
// registered textures of that target (2 = 3D) with storage address and block-linear layout (nvn_mtl.m dm_gfx_texlist), "texraw <serial> <path>"
|
||||
// saves a host texture's level 0 raw, every slice (a cube's six faces, a 3D texture's depth slices) (nvn_mtl.m dm_gfx_texraw), "drag <x0> <y0> <x1> <y1> [seconds=0.3]" moves one finger in a straight line between the two normalized picture
|
||||
// saves a host texture's level 0 raw, every slice (a cube's six faces, a 3D texture's depth slices) (nvn_mtl.m dm_gfx_texraw), "addr <hex address>" logs what the host knows of a guest
|
||||
// address (nvn_mtl.m dm_gfx_addr_note: its memory pool, a texture's storage, a recorded GPU write, the raw memory table, a sparse pool's page), "drag <x0> <y0> <x1> <y1> [seconds=0.3]" moves one finger in a straight line between the two normalized picture
|
||||
// points over that time and lifts it (the touch screen's pans and swipes, hle_touch.c gesture_sample), "dump" logs what each guest thread waits on and the graphics wait points
|
||||
// (crash_dump_now, as the iOS app's DM_LOG_PORT dump; scripts/regress.py asks for it before stopping a hung game), "program <n>" makes oe::ExecuteProgram(n) with no parameters (a multi-program application's way between its programs, headless), "webshot <path>" saves the offline page shown as a PNG, "#…" is ignored.
|
||||
// Look at a screen, decide, press, look again: menus whose timing moves from run to run (loading) need no blind timed script
|
||||
@@ -240,12 +241,18 @@ static void *ctl_main(void *arg) {
|
||||
off += (long)n; line[--n] = 0; if (n && line[n - 1] == '\r') line[--n] = 0;
|
||||
if (!n || line[0] == '#') continue;
|
||||
if (!strcmp(line, "dump")) { crash_dump_now("DM_CTL dump"); continue; }
|
||||
if (!strncmp(line, "atrace ", 7)) { void probe_atrace(uint64_t lo, uint64_t n); char *e2; uint64_t a = strtoull(line + 7, &e2, 16); probe_atrace(a, strtoull(e2, NULL, 0)); continue; } // probe.c
|
||||
if (!strncmp(line, "program ", 8)) { void dm_oe_execute(int index, const void *param, size_t n); LOG("DM_CTL: oe::ExecuteProgram(%d)", atoi(line + 8)); dm_oe_execute(atoi(line + 8), NULL, 0); continue; }
|
||||
if (!strncmp(line, "webshot ", 8)) { void front_web_shot(const char *path); front_web_shot(line + 8); continue; }
|
||||
if (!strncmp(line, "shot ", 5)) { dm_gfx_shot_at(1, line + 5); LOG("DM_CTL: screenshot of the next frame → %s", line + 5); continue; }
|
||||
if (!strncmp(line, "texlist ", 8)) { void dm_gfx_texlist(int target); dm_gfx_texlist(atoi(line + 8)); continue; }
|
||||
if (!strcmp(line, "restop")) { void dm_gfx_restop(void); dm_gfx_restop(); continue; } // what the residency set holds (nvn_mtl.m res_top)
|
||||
if (!strncmp(line, "addr ", 5)) { void dm_gfx_addr_note(uint64_t a, char *note, size_t n); char note[600]; uint64_t a = strtoull(line + 5, NULL, 16); // what the host knows of a guest address
|
||||
dm_gfx_addr_note(a, note, sizeof note); LOG("DM_CTL: addr %#llx:%s", (unsigned long long)a, note[0] ? note : " nothing known"); continue; }
|
||||
if (!strncmp(line, "texraw ", 7)) { void dm_gfx_texraw(uint64_t serial, const char *path); char *e2; uint64_t s = strtoull(line + 7, &e2, 10); while (*e2 == ' ') e2++; dm_gfx_texraw(s, e2); continue; }
|
||||
if (!strncmp(line, "bufsnap ", 8)) { // bufsnap <shader key> <hex address> <bytes> <path>: guest memory as the GPU left it right after that shader's next dispatch (nvn_mtl.m dm_gfx_bufsnap)
|
||||
void dm_gfx_bufsnap(const char *key, uint64_t a, size_t n, const char *path); char key[32] = {0}, path[512] = {0}; unsigned long long a = 0, n = 0;
|
||||
if (sscanf(line + 8, "%31s %llx %lli %511s", key, &a, &n, path) == 4) dm_gfx_bufsnap(key, a, (size_t)n, path); else LOG("DM_CTL: bufsnap <shader key> <hex address> <bytes> <path>"); continue; }
|
||||
if (!strncmp(line, "peek ", 5)) { void dm_ctl_peek(uint64_t a, int n); char *e2; uint64_t a = strtoull(line + 5, &e2, 16); dm_ctl_peek(a, (int)strtol(e2, NULL, 0)); continue; }
|
||||
if (!strncmp(line, "memdump ", 8)) { void dm_ctl_memdump(uint64_t a, uint64_t n, const char *path); char *e2, *e3; uint64_t a = strtoull(line + 8, &e2, 16), n = strtoull(e2, &e3, 0);
|
||||
while (*e3 == ' ') e3++; dm_ctl_memdump(a, n, e3); continue; }
|
||||
@@ -1180,6 +1187,8 @@ TOUCH(1) TOUCH(2) TOUCH(3) TOUCH(4) TOUCH(5) TOUCH(6) TOUCH(7) TOUCH(8) TOUCH(9)
|
||||
// Gestures: recognized from the same touch points (hle_touch.c gesture_fill), so only in handheld mode too
|
||||
int gesture_fill(void *out, int n, uint64_t now_ns);
|
||||
HLE_FORCE("_ZN2nn3hid17InitializeGestureEv", "connect to the hid gesture recognizer; the host recognizes gestures from the touch points", void, h_hid_InitGesture, void) {}
|
||||
// Two-argument overload (PRAGMATA, SDK 20.5.15): the SDK's own one opens the hid service and aborts in sm::Initialize (Result 0xe15), as the touch screen's above did
|
||||
HLE_FORCE("_ZN2nn3hid17InitializeGestureEii", "connect to the hid gesture recognizer (two-argument version); the host recognizes gestures from the touch points", void, h_hid_InitGesture2, int a, int b) { (void)a; (void)b; }
|
||||
HLE_FORCE("_ZN2nn3hid16GetGestureStatesEPNS0_12GestureStateEi", "gesture states, newest first (handheld mode: recognized from the touch points; console mode: none)", int, h_hid_Gestures, void *out, int n) {
|
||||
keys_sync();
|
||||
return dm_opmode() == 0 ? gesture_fill(out, n, now_ns()) : 0;
|
||||
|
||||
+30
-3
@@ -307,7 +307,7 @@ static void *watch_arm(void *p) {
|
||||
// the bytes and, on each change, prints old → new and dumps every guest thread with its backtrace (svc_thread_dump, the first 8 changes): the writer is still inside the code that wrote.
|
||||
// Tears of the Kingdom's memory-shortage flag (a word its frame check compares with 1 and clears) lies on such a page. A suffix =<value> (hex) snapshots and dumps only the changes to that value,
|
||||
// for a word that changes thousands of times before the bad store (Mario vs. Donkey Kong: a heap block's list link, rewritten by every allocation beside it, until 0x3f landed in it)
|
||||
static uint64_t g_poll, g_plen, g_pval; static int g_pwant, g_pheap;
|
||||
static uint64_t g_poll, g_plen, g_pval; static int g_pwant, g_pheap, g_palias;
|
||||
// All threads but this one stopped at once, then their pc, lr and 8 frame-pointer frames read and printed after they run again: the writer is caught a few microseconds after its store
|
||||
static void poll_snap(void) {
|
||||
enum { MT = 256, NF = 8 }; static uint64_t fr[MT][NF + 2]; static thread_act_t keep[MT];
|
||||
@@ -338,6 +338,7 @@ static void *poll_run(void *p) {
|
||||
(void)p; void svc_thread_dump(void); extern uint64_t g_t0_ns; uint64_t now_ns(void); vm_size_t got;
|
||||
uint64_t old = 0; // read through the kernel: the address is not readable until the game maps it (the heap before SetHeapSize)
|
||||
if (g_pheap) { uint64_t hb = 0; while (dm_guest_heap_range(&hb, NULL), !hb) usleep(1000); g_poll += hb; } // heap+<offset>
|
||||
if (g_palias) { void svc_alias_range(uint8_t **base, size_t *size); uint8_t *ab = NULL; size_t as = 0; while (svc_alias_range(&ab, &as), !ab) usleep(1000); g_poll += (uint64_t)(uintptr_t)ab; } // alias+<offset>: memory the game maps in its alias region (PRAGMATA's physical pools)
|
||||
while (vm_read_overwrite(mach_task_self(), g_poll, g_plen, (vm_address_t)&old, &got) || got != g_plen) usleep(1000);
|
||||
LOG("POLL %#llx + %llu armed, value %#llx", (unsigned long long)g_poll, (unsigned long long)g_plen, (unsigned long long)old);
|
||||
for (int n = 0;;) {
|
||||
@@ -353,9 +354,9 @@ static void *poll_run(void *p) {
|
||||
}
|
||||
static void watch_install(void) {
|
||||
{ const char *e = getenv("DM_PROBE_POLL");
|
||||
if (e) { char *end; g_pheap = !strncmp(e, "heap+", 5); if (g_pheap) e += 5; g_poll = strtoull(e, &end, 16); g_plen = *end == '+' ? strtoull(end + 1, &end, 16) : 4;
|
||||
if (e) { char *end; g_pheap = !strncmp(e, "heap+", 5); if (g_pheap) e += 5; g_palias = !strncmp(e, "alias+", 6); if (g_palias) e += 6; g_poll = strtoull(e, &end, 16); g_plen = *end == '+' ? strtoull(end + 1, &end, 16) : 4;
|
||||
if (*end == '=') { g_pwant = 1; g_pval = strtoull(end + 1, 0, 16); }
|
||||
if ((!g_poll && !g_pheap) || !g_plen || g_plen > 8) die("DM_PROBE_POLL format: <address>[+<length up to 8>][=<value>] (hex)");
|
||||
if ((!g_poll && !g_pheap && !g_palias) || !g_plen || g_plen > 8) die("DM_PROBE_POLL format: [heap+|alias+]<address>[+<length up to 8>][=<value>] (hex)");
|
||||
pthread_t t; pthread_create(&t, NULL, poll_run, NULL); pthread_detach(t); } }
|
||||
const char *e = getenv("DM_PROBE_WATCH"); if (!e) return;
|
||||
char *end; g_wheap = !strncmp(e, "heap+", 5);
|
||||
@@ -372,6 +373,32 @@ static void watch_install(void) {
|
||||
|
||||
#endif
|
||||
|
||||
// DM_CTL atrace <hex address> <bytes> (hle_hid.c): the range made inaccessible; the first access to each page after that logs who made it (pc / lr as module offsets, read or write)
|
||||
// and opens the page again. Tells which code reads memory the GPU writes (PRAGMATA: the culling chain's results, read back by the game). Up to 64 ranges, 64 lines in all
|
||||
#if !TARGET_OS_IPHONE
|
||||
static struct { uint64_t lo, hi; } g_at[64]; static _Atomic int g_atn, g_atlog;
|
||||
static int atrace_fault(void *addr, int is_write, void *uc_) {
|
||||
uint64_t a = (uint64_t)(uintptr_t)addr; int n = atomic_load(&g_atn);
|
||||
for (int i = 0; i < n; i++) if (a >= g_at[i].lo && a < g_at[i].hi) {
|
||||
uint64_t pg = (uint64_t)getpagesize(), p = a & ~(pg - 1);
|
||||
mprotect((void *)(uintptr_t)p, pg, PROT_READ | PROT_WRITE);
|
||||
if (atomic_fetch_add(&g_atlog, 1) < 64) { ucontext_t *uc = uc_; char b[256]; int k = snprintf(b, sizeof b, "[dm] atrace %s %#llx (range %d +%#llx):", is_write ? "write" : "read", (unsigned long long)a, i, (unsigned long long)(a - g_at[i].lo));
|
||||
uint64_t at[2] = {uc->uc_mcontext->__ss.__pc, uc->uc_mcontext->__ss.__lr};
|
||||
for (int j = 0; j < 2; j++) { module_t *m = module_of((void *)(uintptr_t)at[j]); k += m ? snprintf(b + k, sizeof b - k, " %s=%s+%#llx", j ? "lr" : "pc", m->name, (unsigned long long)(at[j] - (uint64_t)(uintptr_t)m->base)) : snprintf(b + k, sizeof b - k, " %s=%#llx", j ? "lr" : "pc", (unsigned long long)at[j]); }
|
||||
b[k++] = '\n'; if (write(2, b, (size_t)k) < 0) {} }
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
void probe_atrace(uint64_t lo, uint64_t n) {
|
||||
static int hooked; if (!hooked) { hooked = 1; dm_fault_hook_register(atrace_fault); }
|
||||
int i = atomic_load(&g_atn); if (i >= 64 || !n) { LOG("atrace: 64 ranges at most"); return; }
|
||||
uint64_t pg = (uint64_t)getpagesize(); lo &= ~(pg - 1); n = (n + pg - 1) & ~(pg - 1);
|
||||
g_at[i].lo = lo; g_at[i].hi = lo + n; atomic_store(&g_atn, i + 1);
|
||||
int r = mprotect((void *)(uintptr_t)lo, n, PROT_NONE);
|
||||
LOG("DM_CTL: atrace range %d %#llx + %#llx armed%s", i, (unsigned long long)lo, (unsigned long long)n, r ? " (mprotect failed)" : "");
|
||||
}
|
||||
#endif
|
||||
void probe_install(void) {
|
||||
#if !TARGET_OS_IPHONE
|
||||
crash_set_trap_hook(probe_hit);
|
||||
|
||||
+9
@@ -226,12 +226,21 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv
|
||||
|
||||
private static void DeclareImages(CodeGenContext context, IEnumerable<TextureDefinition> images)
|
||||
{
|
||||
bool extendedFormats = false;
|
||||
|
||||
foreach (TextureDefinition image in images)
|
||||
{
|
||||
int setIndex = context.TargetApi == TargetApi.Vulkan ? image.Set : 0;
|
||||
|
||||
Dim dim = GetDim(image.Type);
|
||||
|
||||
// nxnative: the rg32ui image of a 64-bit image atomic (Instructions.GenerateImageAtomic) is an extended storage format in SPIR-V (PR #1801)
|
||||
if (context.HostCapabilities.MetalImageAtomics && image.Format == TextureFormat.R32G32Uint && !extendedFormats)
|
||||
{
|
||||
extendedFormats = true;
|
||||
context.AddCapability(Capability.StorageImageExtendedFormats);
|
||||
}
|
||||
|
||||
SpvInstruction imageType = context.TypeImage(
|
||||
context.GetType(image.Format.GetComponentType()),
|
||||
dim,
|
||||
|
||||
+20
-1
@@ -644,10 +644,21 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv
|
||||
}
|
||||
// Metal's texture atomics (MSL 3.1) cover buffer, 2D, 2D-array and 3D textures of
|
||||
// R32Uint / R32Sint; source 1D surfaces arrive here already normalized to 2D.
|
||||
// nxnative: a 64-bit max / min (InstEmitSurface.EmitSuatom, Ampere SURED.U64) on an rg32ui image, value low word then high word. SPIRV-Cross has no 64-bit
|
||||
// atomics ("MSL currently does not support 64-bit atomics"), so it is written as two 32-bit atomics of the same operation on the same texel pointer, low word
|
||||
// first; dmsh_atomic.wide_atomics turns that pair into one texture2d<ulong>::atomic_max / atomic_min on the RG32Uint texture and fails the shader on any other
|
||||
// access of the image. The pair is only ever a marker: it never runs as two 32-bit atomics. After uncraftablexd's PR #1801
|
||||
bool wide = bounded && texOp.Format == TextureFormat.R32G32Uint;
|
||||
if (wide && (!texOp.Flags.HasFlag(TextureFlags.AtomicDiscardResult) ||
|
||||
((texOp.Flags & TextureFlags.AtomicMask) != TextureFlags.Minimum && (texOp.Flags & TextureFlags.AtomicMask) != TextureFlags.Maximum) ||
|
||||
texOp.Type == SamplerType.TextureBuffer))
|
||||
{
|
||||
throw new NotSupportedException("Metal 64-bit image atomics support a max or min with no result on 2D/2D-array/3D images only.");
|
||||
}
|
||||
if (bounded && (declaration.IsIndexed ||
|
||||
(texOp.Type != SamplerType.TextureBuffer && texOp.Type != SamplerType.Texture2D &&
|
||||
texOp.Type != (SamplerType.Texture2D | SamplerType.Array) && texOp.Type != SamplerType.Texture3D) ||
|
||||
(texOp.Format != TextureFormat.R32Uint && texOp.Format != TextureFormat.R32Sint)))
|
||||
(texOp.Format != TextureFormat.R32Uint && texOp.Format != TextureFormat.R32Sint && !wide)))
|
||||
{
|
||||
throw new NotSupportedException("Metal image atomics support non-indexed 32-bit buffer/2D/2D-array/3D images only.");
|
||||
}
|
||||
@@ -687,6 +698,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv
|
||||
}
|
||||
|
||||
SpvInstruction value = Src(componentType);
|
||||
SpvInstruction valueHigh = wide ? Src(componentType) : null;
|
||||
|
||||
SpvInstruction merge = null;
|
||||
SpvInstruction valid = null;
|
||||
@@ -742,6 +754,13 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv
|
||||
_ => context.AtomicIAdd(resultType, pointer, one, zero, value),
|
||||
};
|
||||
|
||||
if (wide)
|
||||
{
|
||||
result = (texOp.Flags & TextureFlags.AtomicMask) == TextureFlags.Minimum
|
||||
? context.AtomicUMin(resultType, pointer, one, zero, valueHigh)
|
||||
: context.AtomicUMax(resultType, pointer, one, zero, valueHigh);
|
||||
}
|
||||
|
||||
if (bounded)
|
||||
{
|
||||
context.Branch(merge);
|
||||
|
||||
@@ -38,6 +38,15 @@ namespace Ryujinx.Graphics.Shader
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// NVN2 (Switch 2) graphics stages: the stage's own constant bank, c[25 + stage index], which holds the buffer entries the game pushes into graphics push block
|
||||
/// 1 + stage index; the translator maps it onto that block of c[24] (AStageBlock). -1 for other shaders.
|
||||
/// </summary>
|
||||
int QueryAmpereStageBank()
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// NVN2 (Switch 2) task and mesh shaders, translated as compute: the byte offsets in shared memory of the stage memory the build reads back (dmsh_meshstage.py): the
|
||||
/// workgroup's number, the stage input (a task's payload), the outputs (a payload, or a mesh shader's attributes) and a mesh shader's primitive bytes; null for other shaders.
|
||||
|
||||
+83
-3
@@ -136,6 +136,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
UReg,
|
||||
Imm,
|
||||
Cbuf,
|
||||
BindlessCbuf, // cx[URb][offset]: Bank holds URb, the uniform register pair with the constant buffer's handle (ABindlessConstant)
|
||||
}
|
||||
|
||||
readonly struct ASrc
|
||||
@@ -249,7 +250,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
{
|
||||
if (x.Bit(91))
|
||||
{
|
||||
throw AFail(context, "constant buffer operand with its bank in a uniform register");
|
||||
return new ASrc(AKind.BindlessCbuf, x.Bits(38, 54), x.Bits(32, 38), neg, abs); // cx[URb][offset], URb at 32 where the register form has Rb
|
||||
}
|
||||
|
||||
(int bank, int offset) = AMapC0(context, x.Bits(54, 59), x.Bits(38, 54));
|
||||
@@ -264,8 +265,22 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
// They are mapped to the places the build's reflection and the host know: the push constants to c[24] (where the graphics stages read theirs), uniform slot r to
|
||||
// c[0] + 0x210 + 0x10 r and storage slot s to c[0] + 0x310 + 0x10 s (NVN's compute tables), texture slot t to c[2] + 0x20 + 8 t, separate texture r to
|
||||
// c[2] + 0x168 + 8 r, separate sampler r to c[2] + 0x568 + 8 r and image slot i to c[2] + 0x120 + 8 i (NVN's handle tables). Other offsets stay.
|
||||
// Push block 1 (control +0xaa words; PRAGMATA's buffer entries and handles) lies between push block 0 and the uniform entries, mapped to c[24] + 0x100.
|
||||
// NVN2 graphics stages read the buffer entries the game pushes for them from a bank of their own, c[25 + stage index] (QueryAmpereStageBank): mapped to their push block
|
||||
// in c[24] (AStageBlock). A bank past the push constants' (24) that is not the stage's is refused here: the binding table ends there, and it failed later as an
|
||||
// IndexOutOfRangeException (PRAGMATA: 18,198 shaders before the map)
|
||||
private static (int Bank, int Offset) AMapC0(EmitterContext context, int bank, int offset)
|
||||
{
|
||||
if (bank > 24)
|
||||
{
|
||||
if (offset < 0 || offset >= 0x100)
|
||||
{
|
||||
throw AFail(context, $"stage buffer bank c[{bank}] read at 0x{offset:x}, past its push block");
|
||||
}
|
||||
|
||||
return (24, AStageBlock(context, bank) * 0x100 + offset);
|
||||
}
|
||||
|
||||
int[] layout = bank == 0 ? context.TranslatorContext.GpuAccessor.QueryAmpereComputeC0Layout() : null;
|
||||
|
||||
if (layout == null || layout.Length < 5)
|
||||
@@ -274,23 +289,41 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
}
|
||||
|
||||
int ubos = layout[0], ssbos = layout[1], textures = layout[2], size = layout[3], push = (layout[4] + 0xf) & ~0xf;
|
||||
int ub = 0x10 + push;
|
||||
// Push block 1 (control +0xaa: the driver's accessor reads +0xa9 + block, the words of each push block; dmsh_abi.h DMSH_PUSH_BLOCKS) follows push block 0,
|
||||
// before the uniform entries: PRAGMATA's c8f5a992ec204a44 reads {address, size} pairs at 0x20 / 0x28 and 0x30 / 0x38, right after its one push word, and
|
||||
// b12078fe3bce1273, with no push words, the three 8-byte handles it pushes at 0x10, 0x18 and 0x20, then its uniform entries
|
||||
int pushed = layout.Length > 7 ? (layout[7] + 0xf) & ~0xf : 0;
|
||||
int pb = 0x10 + push;
|
||||
int ub = pb + pushed;
|
||||
int sb = ub + 0x10 * ubos;
|
||||
int hb = sb + 0x10 * ssbos;
|
||||
int sepTextures = hb + 8 * textures;
|
||||
int sepSamplers = sepTextures + 8 * (layout.Length > 5 ? layout[5] : 0);
|
||||
int ib = sepSamplers + 8 * (layout.Length > 6 ? layout[6] : 0);
|
||||
|
||||
if (offset >= 0x10 && offset < ub)
|
||||
if (offset >= 0x10 && offset < pb)
|
||||
{
|
||||
return (24, offset - 0x10);
|
||||
}
|
||||
|
||||
if (offset >= ub && offset < sb)
|
||||
{
|
||||
// the host's table holds 16 uniform slots (dmsh_abi.h DMSH_C0_CS_UBO_SLOTS); past them lies the storage buffer table
|
||||
if (offset - ub >= 0x100)
|
||||
{
|
||||
throw AFail(context, $"compute uniform slot {(offset - ub) >> 4}, past the host's 16");
|
||||
}
|
||||
|
||||
return (0, 0x210 + (offset - ub));
|
||||
}
|
||||
|
||||
// Push block 1, mapped to c[24] + 0x100. PRAGMATA's compute shaders load and store through the buffer addresses it holds (a persistent kernel spins on a work counter
|
||||
// behind one); taken for uniform slots, which the game never bound, or read at the wrong place, the GPU never finished its first 3D frame
|
||||
if (offset >= pb && offset < ub)
|
||||
{
|
||||
return (24, 0x100 + (offset - pb));
|
||||
}
|
||||
|
||||
if (offset >= sb && offset < hb)
|
||||
{
|
||||
return (0, 0x310 + (offset - sb));
|
||||
@@ -319,6 +352,22 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
return (bank, offset);
|
||||
}
|
||||
|
||||
// A constant bank past the push constants' (24) is an NVN2 graphics stage's buffer bank: stage i (vertex 0, hull or mesh 1, domain 2, geometry 3, pixel 4) reads c[25 + i]
|
||||
// (QueryAmpereStageBank), which holds what the game pushes into the graphics push block 1 + i with nvnCommandBufferPushGraphicsConstants: {address, size} entries, 16 bytes
|
||||
// each, or 8-byte handles, as compute reads its own from push block 1. PRAGMATA pushes the mesh stage's six entries into block 2 and the pixel stage's five into block 5 before
|
||||
// its visibility and material passes. The bank maps to that block of c[24] (dmsh_abi.h DMSH_PUSH_BLOCKS; an indexed read, LDC Ra / ULDC URa, is moved by the block's base
|
||||
// with it). Taken for the uniform slots the game binds, the mesh shader read three unbound slots and the material pass the wrong tables: every object drawn through the
|
||||
// visibility buffer came out black. Another stage's bank is refused.
|
||||
private static int AStageBlock(EmitterContext context, int bank)
|
||||
{
|
||||
if (bank != context.TranslatorContext.GpuAccessor.QueryAmpereStageBank())
|
||||
{
|
||||
throw AFail(context, $"constant bank c[{bank}], which is not this stage's buffer bank");
|
||||
}
|
||||
|
||||
return bank - 24;
|
||||
}
|
||||
|
||||
// The operand's 32-bit value, modifiers not applied.
|
||||
private static Operand AGet(EmitterContext context, ASrc s)
|
||||
{
|
||||
@@ -330,6 +379,8 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
return Register(s.Value, RegisterType.Uniform);
|
||||
case AKind.Imm:
|
||||
return Const(s.Value);
|
||||
case AKind.BindlessCbuf:
|
||||
return ABindlessConstant(context, s.Bank, Const(0), s.Value);
|
||||
default:
|
||||
if ((s.Value & 3) != 0)
|
||||
{
|
||||
@@ -348,10 +399,39 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
AKind.Reg => s.Value == RegisterConsts.RegisterZeroIndex ? Const(0) : Register(s.Value + 1, RegisterType.Gpr),
|
||||
AKind.UReg => s.Value == RegisterConsts.UniformZeroIndex ? Const(0) : Register(s.Value + 1, RegisterType.Uniform),
|
||||
AKind.Imm => Const(s.Value < 0 ? -1 : 0),
|
||||
AKind.BindlessCbuf => ABindlessConstant(context, s.Bank, Const(0), s.Value + 4),
|
||||
_ => Cbuf(s.Bank, (s.Value >> 2) + 1),
|
||||
};
|
||||
}
|
||||
|
||||
// A bindless constant buffer read, cx[URb][index + offset]: URb and URb + 1 hold the buffer's 64-bit handle, the hardware's layout: bits 0..44 the address >> 4, 45..63 the
|
||||
// size >> 4 (as NVK's nvk_bindless_cbuf). NVN2 compute shaders take it from c[0]'s uniform entries, which the host fills in that layout (nvn_mtl.m,
|
||||
// DMSH_C0_CS_UBO) as NVN2's driver does (PRAGMATA's compute shader b12078fe3bce1273: ULDC.64 of c[0] + 0x220, uniform slot 1, then cx[UR][4]); the game
|
||||
// builds its own too: those it pushes (b12078fe3bce1273's at push block 1: 0x5a0083055d124, 32 bytes at 0x83055d1240) and those its pixel shaders load with LDG.64 from
|
||||
// its buffers. Read as a plain address, a game handle reached no memory pool: a dummy buffer, or 0 through the pool table. The word is read from global memory at the
|
||||
// address plus the offset: the storage pass traces the address (handle << 4) back to the handle's constant buffer word (GlobalToStorage.cs TryUnwrapHandle), and an
|
||||
// address loaded from memory goes through the memory pool table. An offset past the size reads what lies there, where the hardware reads 0 (open: not checked)
|
||||
private static Operand ABindlessConstant(EmitterContext context, int ur, Operand index, int offset)
|
||||
{
|
||||
if (ur == RegisterConsts.UniformZeroIndex)
|
||||
{
|
||||
return Const(0);
|
||||
}
|
||||
|
||||
Operand lo = Register(ur, RegisterType.Uniform);
|
||||
Operand hi = Register(ur + 1, RegisterType.Uniform);
|
||||
|
||||
// The address, 49 bits: (handle & (2^45 - 1)) << 4
|
||||
Operand baseLo = context.ShiftLeft(lo, Const(4));
|
||||
Operand baseHi = context.BitwiseAnd(context.BitwiseOr(context.ShiftLeft(hi, Const(4)), context.ShiftRightU32(lo, Const(28))), Const(0x1ffff));
|
||||
|
||||
Operand add = context.IAdd(index, Const(offset));
|
||||
Operand sum = context.IAdd(baseLo, add);
|
||||
Operand carry = context.ConditionalSelect(context.ICompareLessUnsigned(sum, baseLo), Const(1), Const(0));
|
||||
|
||||
return context.Load(StorageKind.GlobalMemory, sum, context.IAdd(baseHi, carry));
|
||||
}
|
||||
|
||||
private static Operand AFloat(EmitterContext context, ASrc s, Instruction fpType = Instruction.FP32)
|
||||
{
|
||||
return context.FPAbsNeg(AGet(context, s), s.Abs, s.Neg, fpType);
|
||||
|
||||
+134
-23
@@ -83,6 +83,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
x(0xab9, InstName.Ldc, AUldc, N, uniform: true);
|
||||
x(0xabb, InstName.Ldc, AUldc, N, uniform: true);
|
||||
x(AmpereOpcodes.Ldc, InstName.Ldc, ALdc, N);
|
||||
x(0x582, InstName.Ldc, ALdcBindless, N);
|
||||
x(0x822, InstName.Fswzadd, AFswzadd, N);
|
||||
x(0x804, InstName.R2p, AR2p, N, writesRd: false);
|
||||
x(0x204, InstName.R2p, AR2p, N, writesRd: false);
|
||||
@@ -205,8 +206,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
Operand p = APred(context, x, 87, 90);
|
||||
BoolOp bop = (BoolOp)x.Bits(74, 76);
|
||||
|
||||
ASetPred(context, x.Bits(81, 84), GetPredLogicalOp(context, bop, cmp, p));
|
||||
ASetPred(context, x.Bits(84, 87), GetPredLogicalOp(context, bop, context.BitwiseNot(cmp), p));
|
||||
ASetPredPair(context, x, GetPredLogicalOp(context, bop, cmp, p), GetPredLogicalOp(context, bop, context.BitwiseNot(cmp), p));
|
||||
}
|
||||
|
||||
public static void AFsel(EmitterContext context)
|
||||
@@ -312,7 +312,8 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
throw AFail(context, "I2F size");
|
||||
}
|
||||
|
||||
int select = x.Bits(60, 62);
|
||||
// An immediate (form 4) fills 32..63, so it has no select: I2F.F16.S32 of -2 read the immediate's top bits as one (PRAGMATA: 3 compute shaders)
|
||||
int select = x.Form == 4 ? 0 : x.Bits(60, 62);
|
||||
|
||||
if (select != 0 && srcSize == 2)
|
||||
{
|
||||
@@ -426,17 +427,31 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
ASet(context, x, x.Bit(74) ? context.IConvertS32ToFP32(src) : context.IConvertU32ToFP32(src));
|
||||
}
|
||||
|
||||
// FRND: a float rounded to an integer value (78..80: nearest even, floor, ceiling, truncation)
|
||||
// FRND: a float rounded to an integer value (78..80: nearest even, floor, ceiling, truncation).
|
||||
// FRND.F16 (both sizes 1): the half 60..62 selects, as F2F's, and the result in the low 16 bits. The rounding is done in 32 bits and packed: an integer value of a half's
|
||||
// range is a half (every half from 2^10 up is an integer, and an integer below 2^11 has 11 significant bits), so the pack is exact (PRAGMATA: 65 shaders)
|
||||
public static void AFrnd(EmitterContext context)
|
||||
{
|
||||
AmpereOp x = new(context.CurrOp);
|
||||
int size = x.Bits(84, 86);
|
||||
|
||||
if (x.Bits(84, 86) != 2 || x.Bits(75, 77) != 2)
|
||||
if (size is not (1 or 2) || x.Bits(75, 77) != size)
|
||||
{
|
||||
throw AFail(context, "FRND of a float that is not 32-bit");
|
||||
throw AFail(context, "FRND of a float that is neither 16-bit nor 32-bit, or to another size");
|
||||
}
|
||||
|
||||
Operand src = AFloat(context, AOne(context, x));
|
||||
ASrc s = AOne(context, x);
|
||||
Operand src;
|
||||
|
||||
if (size == 1)
|
||||
{
|
||||
src = AGet(context, s);
|
||||
src = context.FPAbsNeg(x.Bits(60, 62) is 1 or 3 ? context.UnpackHalf2x16High(src) : context.UnpackHalf2x16Low(src), s.Abs, s.Neg);
|
||||
}
|
||||
else
|
||||
{
|
||||
src = AFloat(context, s);
|
||||
}
|
||||
|
||||
Operand res = x.Bits(78, 80) switch
|
||||
{
|
||||
@@ -446,7 +461,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
_ => context.FPTruncate(src),
|
||||
};
|
||||
|
||||
ASet(context, x, res);
|
||||
ASet(context, x, size == 1 ? context.PackHalf2x16(res, ConstF(0f)) : res);
|
||||
}
|
||||
|
||||
// F2F: between half, single and double precision (sizes as F2I); a half lands in the low 16 bits
|
||||
@@ -730,12 +745,36 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
|
||||
if (x.Opcode == 0xab9 && x.Bit(91))
|
||||
{
|
||||
throw AFail(context, "ULDC with its bank in a uniform register");
|
||||
// ULDC URd, cx[URa][offset]: URa (at 24, where the indexed form has its index) holds a bindless constant buffer's handle (ABindlessConstant)
|
||||
int size = x.Bits(73, 76);
|
||||
|
||||
if (size > 5)
|
||||
{
|
||||
throw AFail(context, $"constant load size {size}");
|
||||
}
|
||||
|
||||
int offset = (int)x.SignedField(38, 54);
|
||||
int rd = ARd(x, uniform: true);
|
||||
|
||||
for (int k = 0; k < (size == 5 ? 2 : 1) && rd + k < RegisterConsts.UniformZeroIndex; k++)
|
||||
{
|
||||
Operand value = ABindlessConstant(context, x.Bits(24, 30), Const(0), (offset & ~3) + 4 * k);
|
||||
|
||||
if (size < 4)
|
||||
{
|
||||
value = ExtractSmallInt(context, (LsSize)size, Const((offset & 3) * 8), value);
|
||||
}
|
||||
|
||||
context.Copy(ADestReg(rd + k, uniform: true), value);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (x.Opcode == 0xabb)
|
||||
{
|
||||
ALoadConstant(context, x, x.Bits(54, 59), Register(x.Bits(24, 30), RegisterType.Uniform), (int)x.SignedField(38, 54), uniform: true);
|
||||
(int bank, int offset) = AIndexedBank(context, x.Bits(54, 59), (int)x.SignedField(38, 54));
|
||||
ALoadConstant(context, x, bank, Register(x.Bits(24, 30), RegisterType.Uniform), offset, uniform: true);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -744,6 +783,37 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
}
|
||||
}
|
||||
|
||||
// LDC Rd, cx[URa][Rb + offset] (0x582): URa (at 24, where LDC has Ra) holds a bindless constant buffer's handle, Rb (at 64) the index; a byte, short, word or word
|
||||
// pair (size 73..76) read through ABindlessConstant. PRAGMATA's pixel shaders read a material's parameters so, from a handle they load with LDG.64 (19 of 116 failures
|
||||
// in a sample of its shaders were this instruction)
|
||||
public static void ALdcBindless(EmitterContext context)
|
||||
{
|
||||
AmpereOp x = new(context.CurrOp);
|
||||
int size = x.Bits(73, 76);
|
||||
|
||||
if (!x.Bit(91) || size > 5)
|
||||
{
|
||||
throw AFail(context, $"0x582 form (bindless bit {(x.Bit(91) ? 1 : 0)}, size {size})");
|
||||
}
|
||||
|
||||
int rb = x.Bits(64, 72);
|
||||
Operand index = rb == RegisterConsts.RegisterZeroIndex ? Const(0) : Register(rb, RegisterType.Gpr);
|
||||
Operand addr = context.IAdd(index, Const((int)x.SignedField(38, 54)));
|
||||
Operand word = context.BitwiseAnd(addr, Const(~3));
|
||||
|
||||
for (int k = 0; k < (size == 5 ? 2 : 1) && x.Rd + k < RegisterConsts.RegisterZeroIndex; k++)
|
||||
{
|
||||
Operand value = ABindlessConstant(context, x.Bits(24, 30), context.IAdd(word, Const(4 * k)), 0);
|
||||
|
||||
if (size < 4)
|
||||
{
|
||||
value = ExtractSmallInt(context, (LsSize)size, GetBitOffset(context, addr), value);
|
||||
}
|
||||
|
||||
context.Copy(Register(x.Rd + k, RegisterType.Gpr), value);
|
||||
}
|
||||
}
|
||||
|
||||
// LDC Rd, c[bank][Ra + offset]
|
||||
public static void ALdc(EmitterContext context)
|
||||
{
|
||||
@@ -776,10 +846,17 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
}
|
||||
else
|
||||
{
|
||||
ALoadConstant(context, x, x.Bits(54, 59), Register(x.Ra, RegisterType.Gpr), (int)x.SignedField(38, 54), uniform: false);
|
||||
(int bank, int offset) = AIndexedBank(context, x.Bits(54, 59), (int)x.SignedField(38, 54));
|
||||
ALoadConstant(context, x, bank, Register(x.Ra, RegisterType.Gpr), offset, uniform: false);
|
||||
}
|
||||
}
|
||||
|
||||
// An indexed constant read's bank and immediate offset: an NVN2 graphics stage's buffer bank moves to c[24] by its push block's base (AMapC0, AStageBlock)
|
||||
private static (int Bank, int Offset) AIndexedBank(EmitterContext context, int bank, int offset)
|
||||
{
|
||||
return bank > 24 ? (24, AStageBlock(context, bank) * 0x100 + offset) : (bank, offset);
|
||||
}
|
||||
|
||||
private static void ALoadConstant(EmitterContext context, AmpereOp x, int bank, Operand index, int offset, bool uniform)
|
||||
{
|
||||
ALoadConstant(context, x, Const(bank), index, offset, uniform, null);
|
||||
@@ -886,8 +963,17 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
Operand p = APred(context, x, 87, 90, u);
|
||||
BoolOp bop = (BoolOp)x.Bits(74, 76);
|
||||
|
||||
ASetPred(context, x.Bits(81, 84), GetPredLogicalOp(context, bop, cmp, p), u);
|
||||
ASetPred(context, x.Bits(84, 87), GetPredLogicalOp(context, bop, context.BitwiseNot(cmp), p), u);
|
||||
ASetPredPair(context, x, GetPredLogicalOp(context, bop, cmp, p), GetPredLogicalOp(context, bop, context.BitwiseNot(cmp), p), u);
|
||||
}
|
||||
|
||||
// The two predicate results of a SETP (FSETP, ISETP and the like): Pd0 (81..84) and Pd1 (84..87), both computed (the callers' arguments) before either is
|
||||
// written. A predicate register is read where an operation uses it, so computing Pd1 after writing Pd0 gave it the new value when Pd0 is the accumulator P
|
||||
// (ISETP.GE.AND P0, P1, R2, R3, P0: Pd1 = !cmp AND the new P0, not the P0 given), as PLOP3 already does. Found by uncraftablexd's offline per-instruction tester
|
||||
// against Mesa NAK's OpISetP::fold (PR #1800): 3 to 69 of 128 cases wrong per such encoding
|
||||
private static void ASetPredPair(EmitterContext context, AmpereOp x, Operand r0, Operand r1, bool uniform = false)
|
||||
{
|
||||
ASetPred(context, x.Bits(81, 84), r0, uniform);
|
||||
ASetPred(context, x.Bits(84, 87), r1, uniform);
|
||||
}
|
||||
|
||||
// 0x80d: what the compiler puts at the end of a vertex shader's position in Kirby Air Riders (all 6,319 of them, no other game's), its meaning inferred from what surrounds it. Before it, FSETP sets P0..P5 where x, y or z lies
|
||||
@@ -899,9 +985,15 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
AmpereOp x = new(context.CurrOp);
|
||||
uint imm = (uint)x.Imm32;
|
||||
int pd = x.Bits(81, 84), pd2 = x.Bits(84, 87), ps = x.Bits(87, 90), cmp = x.Bits(76, 79);
|
||||
bool plain = pd2 == RegisterConsts.PredicateTrueIndex && ps == RegisterConsts.PredicateTrueIndex && context.TranslatorContext.Definitions.Stage == ShaderStage.Vertex;
|
||||
bool plain = pd2 == RegisterConsts.PredicateTrueIndex && ps == RegisterConsts.PredicateTrueIndex;
|
||||
|
||||
if (!plain || !(imm == 0xc4321111 && pd == RegisterConsts.PredicateTrueIndex && cmp == 0 || imm == 0x80000000 && cmp == 6))
|
||||
// With no predicate result it writes nothing the shader can read: PRAGMATA's shaders have it with immediate 0x80000007 (8 of 116 failures in a sample of them)
|
||||
if (plain && pd == RegisterConsts.PredicateTrueIndex)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!plain || context.TranslatorContext.Definitions.Stage != ShaderStage.Vertex || !(imm == 0x80000000 && cmp == 6))
|
||||
{
|
||||
throw AFail(context, "a 0x80d not of the guard band cull");
|
||||
}
|
||||
@@ -999,12 +1091,22 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
return context.ConditionalSelect(APred(context, x, 87, 90, u), Const(1), Const(0));
|
||||
}
|
||||
|
||||
// IMAD Rd, a, b, c: the low word of a * b + c (B and C may be negated)
|
||||
// IMAD's sources: only C has a negation (75 where C is the 64-slot register, forms 1, 4, 5, 6; 63 where it is the immediate, constant or uniform register, forms 2, 3, 7).
|
||||
// The other slot's bit is no modifier of B: nvdisasm prints IMAD R4, R8, R9, R10 with bit 63 set in form 1, and IMAD R4, R8, R9, UR4 with bit 75 set in form 7 (Mesa NAK's OpIMad
|
||||
// takes no source modifiers at all). Negating B there made a * -b (found by uncraftablexd's per-instruction tester, PR #1800)
|
||||
private static (ASrc A, ASrc B, ASrc C) AImadSrcs(EmitterContext context, AmpereOp x, bool u = false)
|
||||
{
|
||||
(ASrc a, ASrc b, ASrc c) = AAluSrcs(context, x, u, abs: false);
|
||||
|
||||
return (a.WithMods(false, false), b.WithMods(false, false), c);
|
||||
}
|
||||
|
||||
// IMAD Rd, a, b, c: the low word of a * b + c (C may be negated)
|
||||
public static void AImad(EmitterContext context)
|
||||
{
|
||||
AmpereOp x = new(context.CurrOp);
|
||||
bool u = AUniform(context);
|
||||
(ASrc a, ASrc b, ASrc c) = AAluSrcs(context, x, u, abs: false);
|
||||
(ASrc a, ASrc b, ASrc c) = AImadSrcs(context, x, u);
|
||||
|
||||
if (x.Bits(81, 84) != RegisterConsts.PredicateTrueIndex)
|
||||
{
|
||||
@@ -1037,9 +1139,9 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
{
|
||||
AmpereOp x = new(context.CurrOp);
|
||||
bool u = AUniform(context);
|
||||
(ASrc a, ASrc b, ASrc c) = AAluSrcs(context, x, u, abs: false);
|
||||
(ASrc a, ASrc b, ASrc c) = AImadSrcs(context, x, u);
|
||||
|
||||
if (b.Neg || c.Neg)
|
||||
if (c.Neg)
|
||||
{
|
||||
throw AFail(context, "IMAD.WIDE negation");
|
||||
}
|
||||
@@ -1099,7 +1201,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
public static void AImadHi(EmitterContext context)
|
||||
{
|
||||
AmpereOp x = new(context.CurrOp);
|
||||
(ASrc a, ASrc b, ASrc c) = AAluSrcs(context, x, abs: false);
|
||||
(ASrc a, ASrc b, ASrc c) = AImadSrcs(context, x);
|
||||
|
||||
if (c.Neg)
|
||||
{
|
||||
@@ -1474,14 +1576,23 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
|
||||
// 0x925 Rd (78..80 = 1, no predicate result): 1 for a covered pixel, 0 for a helper invocation. No table at hand names it (PIXLD.COVERED, perhaps). What it reads comes from the two shaders
|
||||
// that use it, Star Fox's quad efficiency views 46040940ce0fd49b and 826168691af2e211, which add it up over the quad through SHFL and FSWZADD: one takes sum - 1 as the index of a
|
||||
// 4-entry palette, so a shaded pixel's sum is at least 1; the other draws 0.03125 + 0.15625 sum in red. Any other form stays refused
|
||||
// 4-entry palette, so a shaded pixel's sum is at least 1; the other draws 0.03125 + 0.15625 sum in red.
|
||||
// Form 3 is the index of the sample the fragment runs for (Maxwell's PIXLD.MY_INDEX, numbered 5 there): PRAGMATA's pixel shaders (154) read it first and index the driver's sample
|
||||
// position table with it (LDC c[0][R + 0x620], a byte of x and y nibbles), as GLSLC's Maxwell code does with MY_INDEX (InstEmitMove.Pixld). Any other form stays refused
|
||||
public static void APixelCovered(EmitterContext context)
|
||||
{
|
||||
AmpereOp x = new(context.CurrOp);
|
||||
int form = x.Bits(78, 81);
|
||||
|
||||
if (x.Bits(78, 81) != 1 || x.Bits(81, 84) != 7 || x.Bits(24, 32) != 0 || x.Bits(32, 48) != 0 || context.TranslatorContext.Definitions.Stage != ShaderStage.Fragment)
|
||||
if ((form != 1 && form != 3) || x.Bits(81, 84) != 7 || x.Bits(24, 32) != 0 || x.Bits(32, 48) != 0 || context.TranslatorContext.Definitions.Stage != ShaderStage.Fragment)
|
||||
{
|
||||
throw AFail(context, $"0x925 form {x.Bits(78, 81)} outside a covered pixel's read in a pixel shader");
|
||||
throw AFail(context, $"0x925 form {form} outside a covered pixel's or sample index read in a pixel shader");
|
||||
}
|
||||
|
||||
if (form == 3)
|
||||
{
|
||||
ASet(context, x, context.Load(StorageKind.Input, IoVariable.SampleId), false);
|
||||
return;
|
||||
}
|
||||
|
||||
Operand helper = context.Load(StorageKind.Input, IoVariable.HelperInvocation);
|
||||
|
||||
+100
-12
@@ -1,6 +1,7 @@
|
||||
using Ryujinx.Graphics.Shader.Decoders;
|
||||
using Ryujinx.Graphics.Shader.IntermediateRepresentation;
|
||||
using Ryujinx.Graphics.Shader.Translation;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Numerics;
|
||||
using static Ryujinx.Graphics.Shader.Instructions.InstEmitAluHelper;
|
||||
@@ -47,6 +48,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
x(0x367, InstName.Tld, ATex, InstProps.Tex);
|
||||
x(0xf60, InstName.Tex, ATex, InstProps.Tex);
|
||||
x(0xf63, InstName.Tld4, ATex, InstProps.Tex);
|
||||
x(0xf66, InstName.Tld, ATex, InstProps.Tex);
|
||||
x(0xf6c, InstName.Txd, ATex, InstProps.Tex);
|
||||
x(0xf69, InstName.Tmml, ATex, InstProps.Tex);
|
||||
x(0x36a, InstName.Tmml, ATex, InstProps.Tex);
|
||||
@@ -54,13 +56,16 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
x(0xb63, InstName.Tld4, ATex, InstProps.Tex);
|
||||
x(0xb69, InstName.Tmml, ATex, InstProps.Tex);
|
||||
x(0xb6c, InstName.Txd, ATex, InstProps.Tex);
|
||||
x(0x36d, InstName.Txd, ATex, InstProps.Tex);
|
||||
x(0xb6f, InstName.Txq, ATxq, InstProps.Tex);
|
||||
x(0x370, InstName.Txq, ATxq, InstProps.Tex);
|
||||
x(0xf6f, InstName.Txq, ATxq, InstProps.Tex);
|
||||
x(0xb97, InstName.Suld, ASurface, N);
|
||||
x(0xb99, InstName.Suld, ASurface, N);
|
||||
x(0xb9b, InstName.Sust, ASurface, N, writesRd: false);
|
||||
x(0xb9d, InstName.Sust, ASurface, N, writesRd: false);
|
||||
x(0x593, InstName.Suatom, ASuatom, N);
|
||||
x(0x595, InstName.Suatom, ASuatomCas, N);
|
||||
x(0x59f, InstName.Sured, ASured, N, writesRd: false);
|
||||
x(0xb1d, InstName.Bar, ABar, N, writesRd: false);
|
||||
}
|
||||
@@ -133,16 +138,23 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
|
||||
if (stage != null)
|
||||
{
|
||||
// A task or mesh shader's stage input (QueryAmpereStageMemory). Mode 0x78: its workgroup's number; 0x38: a word of the payload its task wrote, [Ra + offset];
|
||||
// 0xb8: a word it wrote itself with 0x927's mode 0xb8 (Ocarina of Time's task shader 5d3a096025e375a1 reads its payload back in a later thread)
|
||||
// A task or mesh shader's stage input (QueryAmpereStageMemory). Mode 0x78: its workgroup's number; 0x38: a word of the payload its task wrote, [Ra + offset].
|
||||
// The mode's bits as nvdisasm names them: 0x80 .O (the output area), 0x40 .SKEW, 0x30 .ATTR, 0x08 .32. So 0xf8 (ISBERD.O.ATTR.SKEW.32) and 0xb8 (.O.ATTR.32)
|
||||
// read back a word the shader's own ISBEWR of the same mode wrote: a mesh shader's attributes (0xb8 through its vertex records, AosToSoa), a task's payload
|
||||
// (AStageOut). PRAGMATA's mesh shaders 5aab38bb5ba67ef7 and 28ef097c07ceb429 (the title's lunar terrain) read the x, y and w of each triangle's three positions
|
||||
// back this way and swap two of its indices by the sign of their determinant (a mirrored instance's winding). Ocarina of Time's task shader 5d3a096025e375a1
|
||||
// reads its payload back with 0xb8 in a later thread. From uncraftablexd's PRAGMATA bring-up (PR #1407)
|
||||
int mode = x.Bits(72, 80);
|
||||
|
||||
if (mode != 0x78 && mode != 0x38 && mode != 0xb8)
|
||||
if (mode != 0x78 && mode != 0x38 && mode != 0xf8 && mode != 0xb8)
|
||||
{
|
||||
throw AFail(context, $"ISBERD mode {mode:x2} in a task or mesh shader");
|
||||
}
|
||||
|
||||
Operand addr = mode == 0x78 ? Const(stage[0]) : context.IAdd(AGpr(x.Ra), Const(stage[mode == 0xb8 ? 2 : 1] + (int)x.SignedField(40, 64)));
|
||||
int baseOffset = mode switch { 0x38 => stage[1], 0xf8 or 0xb8 => stage[2], _ => 0 };
|
||||
Operand addr = mode == 0x78 ? Const(stage[0])
|
||||
: mode == 0xb8 && stage.Length >= 7 ? context.IAdd(Const(stage[2]), AosToSoa(context, context.IAdd(AGpr(x.Ra), Const((int)x.SignedField(40, 64))), stage))
|
||||
: context.IAdd(AGpr(x.Ra), Const(baseOffset + (int)x.SignedField(40, 64)));
|
||||
EmitLoad(context, StorageKind.SharedMemory, LsSize2.B32, addr, x.Rd, 0);
|
||||
return;
|
||||
}
|
||||
@@ -175,10 +187,46 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
}
|
||||
|
||||
bool word = mode == 0xb8 || mode == 0xf8;
|
||||
Operand addr = context.IAdd(AGpr(x.Ra), Const((word ? stage[2] : stage[3]) + (int)x.SignedField(40, 64)));
|
||||
Operand addr = mode == 0xb8 && stage.Length >= 7
|
||||
? context.IAdd(Const(stage[2]), AosToSoa(context, context.IAdd(AGpr(x.Ra), Const((int)x.SignedField(40, 64))), stage))
|
||||
: context.IAdd(AGpr(x.Ra), Const((word ? stage[2] : stage[3]) + (int)x.SignedField(40, 64)));
|
||||
EmitStore(context, StorageKind.SharedMemory, word ? LsSize2.B32 : LsSize2.U8, addr, x.Rb, 0);
|
||||
}
|
||||
|
||||
// A mesh shader's attribute word by its non-skew address (ISBEWR / ISBERD .O.ATTR.32, mode 0xb8 in a mesh shader; in a task shader it is the payload). Besides the
|
||||
// SoA blocks (.SKEW, mode 0xf8: per component 0x80 bytes for 32 vertices or primitives), a mesh shader may address its vertices as records: vertex v's n enabled
|
||||
// components at aos + 4n * v + 4c, aos being the end of the SoA area. PRAGMATA's 6adf14e9a4100082, 4fcffc73d65dc1ed and c0e44513c35d209a write every vertex both
|
||||
// ways, with the same values. A record word is the SoA word of vertex v, component c, so it goes there: the two writes coincide. Before, the record addresses ran past
|
||||
// the SoA area over the primitive count and index bytes (stage[3]) and drew garbage triangles (white streaks over PRAGMATA's cockpit window). stage[4] = aos,
|
||||
// stage[5] = n, stage[6] = the records' size (max vertices * 4n), from dmsh_meshstage.memory(); other addresses stay as they are. v = w / n as
|
||||
// w * ceil(2^18 / n) >> 18 where that is exact for every word of the records (AosVertex checks it: it is for n up to 42, not for every n above, e.g. 51
|
||||
// components and 160 vertices give vertex 109 for word 5609), else as an integer division
|
||||
private static Operand AosToSoa(EmitterContext context, Operand off, int[] stage)
|
||||
{
|
||||
int n = Math.Max(stage[5], 1);
|
||||
Operand rel = context.ISubtract(off, Const(stage[4]));
|
||||
Operand inside = context.ICompareLessUnsigned(rel, Const(stage[6]));
|
||||
Operand w = context.ShiftRightU32(rel, Const(2));
|
||||
Operand v = AosVertex(context, w, n, (uint)Math.Max(stage[6], 0) / 4);
|
||||
Operand c = context.ISubtract(w, context.IMultiply(v, Const(n)));
|
||||
Operand soa = context.IAdd(context.IAdd(context.IMultiply(context.ShiftRightU32(v, Const(5)), Const(n * 0x80)), context.ShiftLeft(context.BitwiseAnd(v, Const(31)), Const(2))), context.ShiftLeft(c, Const(7)));
|
||||
return context.ConditionalSelect(inside, soa, off);
|
||||
}
|
||||
|
||||
// w / n for every w below words: by the reciprocal when it gives the quotient for all of them (and w * m stays within 32 bits), else by a division
|
||||
internal static Operand AosVertex(EmitterContext context, Operand w, int n, uint words)
|
||||
{
|
||||
uint m = ((1u << 18) + (uint)n - 1) / (uint)n;
|
||||
bool exact = (ulong)words * m < (1ul << 32);
|
||||
|
||||
for (uint k = 0; exact && k < words; k++)
|
||||
{
|
||||
exact = (k * m) >> 18 == k / (uint)n;
|
||||
}
|
||||
|
||||
return exact ? context.ShiftRightU32(context.IMultiply(w, Const((int)m)), Const(18)) : context.Add(Instruction.Divide, Local(), w, Const(n));
|
||||
}
|
||||
|
||||
public static void ALepc(EmitterContext context)
|
||||
{
|
||||
AmpereOp x = new(context.CurrOp);
|
||||
@@ -577,14 +625,23 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
public static void ASured(EmitterContext context)
|
||||
{
|
||||
AmpereOp x = new(context.CurrOp);
|
||||
int size = x.Bits(73, 76); // 0 U32, 2 U64 (SuatomSize)
|
||||
|
||||
if ((x.Bits(64, 96) & ~(0xf << 23)) != 0x0010e000 || x.Bits(59, 61) != 0)
|
||||
if ((x.Bits(64, 96) & ~(0xf << 23) & ~(0x7 << 9)) != 0x0010e000 || x.Bits(59, 61) != 0 || (size != 0 && size != (int)SuatomSize.U64))
|
||||
{
|
||||
throw AFail(context, $"SURED form {x.Bits(64, 96):x8}");
|
||||
}
|
||||
|
||||
(int handle, int cbufSlot) = ATexHandle(context, x);
|
||||
|
||||
// U64 (PRAGMATA's visibility buffer, SURED.D.2D.MAX.U64: depth << 32 | primitive id, 336 compute shaders): a 64-bit max / min with no result, which EmitSuatom writes as Metal's
|
||||
// 64-bit texture atomics (it refuses every other 64-bit form). The value is the pair Rb (low word), Rb + 1. After uncraftablexd's PRAGMATA bring-up (PR #1801)
|
||||
if (size == (int)SuatomSize.U64)
|
||||
{
|
||||
EmitSuatom(context, (SuDim)x.Bits(61, 64), 0, (SuatomOp)x.Bits(87, 91), SuatomSize.U64, handle, x.Ra, x.Rb, 0, RegisterConsts.RegisterZeroIndex, false, isBindless: false, compareAndSwap: false, cbufSlot: cbufSlot);
|
||||
return;
|
||||
}
|
||||
|
||||
EmitSured(context, (SuDim)x.Bits(61, 64), 0, (RedOp)x.Bits(87, 91), SuatomSize.U32, handle, x.Ra, x.Rb, 0, false, isBindless: false, cbufSlot: cbufSlot);
|
||||
}
|
||||
|
||||
@@ -619,6 +676,22 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
|
||||
// ---- textures ----
|
||||
|
||||
// SUATOM.CAS Rd, [Ra], Rb (0x595): the compare-and-swap of an image through a handle, 0x593's layout with no operation field. Rb is the value compared with and
|
||||
// Rb + 1 the new value (Mesa NAK: opcode 0x396 for AtomOp::CmpExch beside 0x394, as 0x593 is beside 0x394 with the handle bound; its data source is the pair
|
||||
// {compare, new value}), which is the order EmitSuatom reads them in. Rd is the old value (PRAGMATA: compute shader 50fece0d891feba4, Rd = RZ)
|
||||
public static void ASuatomCas(EmitterContext context)
|
||||
{
|
||||
AmpereOp x = new(context.CurrOp);
|
||||
(int handle, int cbufSlot) = ATexHandle(context, x);
|
||||
|
||||
if (x.Bits(81, 84) != 7)
|
||||
{
|
||||
throw AFail(context, "SUATOM.CAS with a predicate result");
|
||||
}
|
||||
|
||||
EmitSuatom(context, (SuDim)x.Bits(61, 64), 0, 0, (SuatomSize)x.Bits(73, 76), handle, x.Ra, x.Rb, 0, x.Rd, false, isBindless: false, compareAndSwap: true, cbufSlot: cbufSlot);
|
||||
}
|
||||
|
||||
// Texture dimension (61..64) → Maxwell's TexDim
|
||||
private static TexDim ATexDim(EmitterContext context, int dim)
|
||||
{
|
||||
@@ -737,9 +810,14 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
Operand boundHandle = null;
|
||||
// 0xf69 and 0x36a are TMML the same way (0xb69's other fields; Kirby Air Riders: 4,776 pixel shaders).
|
||||
bool handleInB = opcode is 0x361 or 0x364 or 0x367 or 0x36a;
|
||||
bool bindless = handleInB || opcode is 0xf60 or 0xf63 or 0xf6c or 0xf69;
|
||||
// 0x36d is TXD the same way (0xb6c's other fields), but its handle leads the first block, the coordinates after it: the second holds only the derivatives
|
||||
// (PRAGMATA's pixel shader b8246ccc36f8d648: Ra = R0, the texture word ORed with c[2] + 0x568, a separate sampler; R1, R2 the coordinates; Rb = R20..R23, four
|
||||
// products of the screen-space gradients; 84 of 164 shaders of a sample of its shaders stopped here)
|
||||
bool handleInA = opcode == 0x36d;
|
||||
// 0xf66 is TLD the same way (0xb66's other fields), by the family's pattern: uniform-register forms at 0xf60 + 3n beside 0xb60 + 3n (PRAGMATA: 17 shaders)
|
||||
bool bindless = handleInB || handleInA || opcode is 0xf60 or 0xf63 or 0xf66 or 0xf6c or 0xf69;
|
||||
|
||||
if (opcode is 0xf60 or 0xf63 or 0xf6c or 0xf69)
|
||||
if (opcode is 0xf60 or 0xf63 or 0xf66 or 0xf6c or 0xf69)
|
||||
{
|
||||
int ur = x.Bits(40, 46);
|
||||
|
||||
@@ -748,7 +826,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
|
||||
if (bindless)
|
||||
{
|
||||
opcode = opcode is 0xf63 or 0xf6c or 0xf69 ? opcode - 0x400 : opcode is 0x364 or 0x367 or 0x36a ? opcode + 0x7ff : 0xb60;
|
||||
opcode = opcode is 0xf63 or 0xf66 or 0xf6c or 0xf69 ? opcode - 0x400 : opcode is 0x364 or 0x367 or 0x36a or 0x36d ? opcode + 0x7ff : 0xb60;
|
||||
}
|
||||
|
||||
TexDim dim = ATexDim(context, x.Bits(61, 64));
|
||||
@@ -825,7 +903,13 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
if (opcode == 0xb6c)
|
||||
{
|
||||
int n0 = coords + (isArray || offset ? 1 : 0);
|
||||
(List<Operand> a, List<Operand> b) = ATexBlocks(context, x, n0, 2 * coords);
|
||||
(List<Operand> a, List<Operand> b) = ATexBlocks(context, x, n0 + (handleInA ? 1 : 0), 2 * coords);
|
||||
|
||||
if (handleInA)
|
||||
{
|
||||
boundHandle = a[0];
|
||||
a = a.GetRange(1, a.Count - 1);
|
||||
}
|
||||
|
||||
if (bindless)
|
||||
{
|
||||
@@ -1071,7 +1155,9 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
int mask = x.Bits(72, 76);
|
||||
// 0x370 is to 0xb6f as 0x361 to 0xb60: the handle in a register, Ra, with the LOD after it (Fire Emblem Fortune's Weave's lighting: MOV R1c, R64; MOV R1d, RZ; TXQ R1d, R1c). The shape
|
||||
// has no field here and the size query does not depend on it, so 2D, as Maxwell's bindless TXQ
|
||||
bool bindless = x.Opcode == 0x370;
|
||||
// 0xf6f is to 0xb6f as 0xf60 to 0xb60: the handle in a uniform register at 40..46, Ra the LOD (PRAGMATA: 12 shaders, the size of a texture whose handle a ULDC read)
|
||||
bool inUniform = x.Opcode == 0xf6f;
|
||||
bool bindless = x.Opcode == 0x370 || inUniform;
|
||||
(int handle, int cbufSlot) = bindless ? (0, TextureOperation.DefaultCbufSlot) : ATexHandle(context, x);
|
||||
SamplerType type = bindless ? SamplerType.Texture2D : context.TranslatorContext.GpuAccessor.QuerySamplerType(handle);
|
||||
TextureFlags flags = bindless ? TextureFlags.Bindless : TextureFlags.None;
|
||||
@@ -1086,7 +1172,9 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
|
||||
Operand Src(int reg) => reg >= RegisterConsts.RegisterZeroIndex ? Const(0) : context.Copy(Register(reg, RegisterType.Gpr));
|
||||
|
||||
Operand[] sources = bindless ? [Src(x.Ra), Src(x.Ra + 1)] : [Src(x.Ra)];
|
||||
Operand Ur(int ur) => ur == RegisterConsts.UniformZeroIndex ? Const(0) : context.Copy(Register(ur, RegisterType.Uniform));
|
||||
|
||||
Operand[] sources = inUniform ? [Ur(x.Bits(40, 46)), Src(x.Ra)] : bindless ? [Src(x.Ra), Src(x.Ra + 1)] : [Src(x.Ra)];
|
||||
|
||||
if (query == 0)
|
||||
{
|
||||
|
||||
+17
-1
@@ -210,7 +210,18 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
// Preserve source width before descriptor-sized formats are resolved.
|
||||
// Other backends retain their existing surface-instruction handling.
|
||||
bool metalAtomics = context.TranslatorContext.Options.Flags.HasFlag(TranslationFlags.MetalImageAtomics);
|
||||
if (metalAtomics &&
|
||||
// nxnative: a 64-bit unsigned max / min whose result is discarded (Ampere SURED.D.2D.MAX.U64, PRAGMATA's visibility buffer: depth << 32 | ID, 336 compute
|
||||
// shaders) maps onto Metal's 64-bit texture atomics (MSL 3.1 texture2d<ulong>::atomic_max / atomic_min, an RG32Uint texture with the shader-atomic usage,
|
||||
// Apple GPU family 9). Metal has no 64-bit fetch, add or bitwise texture atomic, so every other 64-bit form stays refused. The value is the register pair
|
||||
// Rb (low word), Rb + 1 (high word); see GenerateImageAtomic and dmsh_atomic.py for how the pair reaches the Metal source. After uncraftablexd's PR #1801
|
||||
bool wide = metalAtomics && size == SuatomSize.U64;
|
||||
if (wide &&
|
||||
(compareAndSwap || hasPredicateResult || dest != RegisterConsts.RegisterZeroIndex || atomicOp is not (SuatomOp.Max or SuatomOp.Min) ||
|
||||
isBindless || (dimensions != SuDim._2d && dimensions != SuDim._2dArray && dimensions != SuDim._3d)))
|
||||
{
|
||||
throw new NotSupportedException($"Metal 64-bit image atomics: only a 2D / 2D-array / 3D U64 max or min with no result ({atomicOp}, {dimensions}).");
|
||||
}
|
||||
if (metalAtomics && !wide &&
|
||||
size is not (SuatomSize.U32 or SuatomSize.S32 or SuatomSize.Sd32))
|
||||
{
|
||||
throw new NotSupportedException("Metal image atomics require a 32-bit integer source size.");
|
||||
@@ -294,6 +305,11 @@ namespace Ryujinx.Graphics.Shader.Instructions
|
||||
|
||||
sourcesList.Add(Rb());
|
||||
|
||||
if (wide)
|
||||
{
|
||||
sourcesList.Add(Rb()); // the high word
|
||||
}
|
||||
|
||||
Operand[] sources = sourcesList.ToArray();
|
||||
|
||||
TextureFlags flags = (compareAndSwap ? TextureFlags.CAS : GetAtomicOpFlags(atomicOp)) | (TextureFlags)((int)clamp << 20);
|
||||
|
||||
+6
-1
@@ -529,15 +529,20 @@ namespace Ryujinx.Graphics.Shader.Translation
|
||||
private static Operand GenerateSharedAtomicCasLoop(EmitterContext context, Operand wordOffset, int id, Func<Operand, Operand> opCallback)
|
||||
{
|
||||
Operand lblLoopHead = Label();
|
||||
Operand oldValue = Local();
|
||||
context.Copy(oldValue, context.Load(StorageKind.SharedMemory, id, wordOffset));
|
||||
|
||||
context.MarkLabel(lblLoopHead);
|
||||
|
||||
Operand oldValue = context.Load(StorageKind.SharedMemory, id, wordOffset);
|
||||
Operand newValue = opCallback(oldValue);
|
||||
|
||||
Operand casResult = context.AtomicCompareAndSwap(StorageKind.SharedMemory, id, wordOffset, oldValue, newValue);
|
||||
|
||||
Operand casFail = context.ICompareNotEqual(casResult, oldValue);
|
||||
// nxnative: a retry takes the value the exchange returned, not a new plain load: a plain reload can read a stale line, so the exchange never matches and the loop
|
||||
// spins (uncraftablexd, PR #1796). A helper function's locals may be assigned more than once; the main program's sites keep their plain reload, as the Optimizer's
|
||||
// PropagateCopy takes a local there as single-assignment
|
||||
context.Copy(oldValue, casResult);
|
||||
|
||||
context.BranchIfTrue(lblLoopHead, casFail);
|
||||
|
||||
|
||||
Vendored
+35
-9
@@ -97,9 +97,20 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
// A game's own uniform buffer holds other data than handles, so a word of it alone is no handle here, but a texture word ORed with a sampler word of its bank or a constant sampler is one: Unreal
|
||||
// Engine 5.4 on the Switch 2 keeps its handles in c[3] and builds them under a guard (R = c[3][a]; R |= c[3][b]) for a read under a guard Utils.FindLastOperation cannot tie to it: !UP0
|
||||
// and !P0 with UP0 the vote of P0, P4 and P5 with P5 = P4 && !P1, and P6 and a branch over !P6. The phi then also takes the handle's first word and what the register held before.
|
||||
// With the OR unguarded the phi lies on its source, not on the handle
|
||||
// With the OR unguarded the phi lies on its source, not on the handle.
|
||||
// A handle whose words the shader loads from memory on some path (a Load, or a global load GlobalToStorage served through a helper: IsLoaded) is a real
|
||||
// bindless access, also as a source of the OR, for a read GenerateBindlessAccess indexes the pools for (pooled: a sampled texture other than a buffer texture): that reads the
|
||||
// texture the handle names whatever its source. Other reads keep their candidates for those leaves (their slot arrays take c[2]'s handles only). PRAGMATA's
|
||||
// compute shader 02e1292114121308 reads its texture with (an ID from a material record, through the pool table) | constant sampler 0x104, under the guard that loads the ID; the
|
||||
// register held c[24] + 0x114 (a pushed buffer address's high word) on the other path, and that word alone was taken as the handle: the host had no slot for it and the dispatch ran
|
||||
// without its shader
|
||||
private enum TableHandle { None, Set, Deferred }
|
||||
|
||||
// A global load GlobalToStorage served is a copy that keeps the load's storage kind, of its helper's result (or of 0 where it dropped the load): Copy.GlobalMemory(Call)
|
||||
private static bool IsLoaded(Operand leaf) => leaf.AsgOp is Operation op && (op.Inst is Instruction.Load or Instruction.Call || (op.Inst == Instruction.Copy && op.StorageKind != StorageKind.None));
|
||||
|
||||
private static bool IsPooled(TextureOperation texOp) => !texOp.Inst.IsImage() && (texOp.Type & SamplerType.Mask) != SamplerType.TextureBuffer; // as GenerateBindlessAccess
|
||||
|
||||
private static TableHandle TryTableHandle(BasicBlock block, ResourceManager resourceManager, IGpuAccessor gpuAccessor, TextureOperation texOp, LinkedListNode<INode> node, bool deferSeveral)
|
||||
{
|
||||
Operand handle = texOp.GetSource(0);
|
||||
@@ -119,9 +130,16 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
}
|
||||
else if (!texOp.Inst.IsImage() && leaf.AsgOp is Operation orOp && orOp.Inst == Instruction.BitwiseOr)
|
||||
{
|
||||
foreach (Operand texture in PhiLeaves(orOp.GetSource(0)))
|
||||
List<Operand> textures = PhiLeaves(orOp.GetSource(0)), samplers = PhiLeaves(orOp.GetSource(1));
|
||||
|
||||
if (IsPooled(texOp) && (textures.Exists(IsLoaded) || samplers.Exists(IsLoaded)))
|
||||
{
|
||||
foreach (Operand sampler in PhiLeaves(orOp.GetSource(1)))
|
||||
return TableHandle.None; // loaded from memory on some path (above)
|
||||
}
|
||||
|
||||
foreach (Operand texture in textures)
|
||||
{
|
||||
foreach (Operand sampler in samplers)
|
||||
{
|
||||
(Operand t, Operand sm) = IsSamplerWord(texture) && !IsSamplerWord(sampler) ? (sampler, texture) : (texture, sampler); // either order, as TryConvertBindless
|
||||
|
||||
@@ -132,7 +150,7 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (leaf.AsgOp is Operation load && load.Inst == Instruction.Load)
|
||||
else if (leaf.AsgOp is Operation { Inst: Instruction.Load } || (IsPooled(texOp) && IsLoaded(leaf)))
|
||||
{
|
||||
return TableHandle.None; // a handle loaded from memory or an input is a real bindless access (GenerateBindlessAccess)
|
||||
}
|
||||
@@ -221,6 +239,11 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
? "Bindless handle taken from the one constant buffer handle among its phi inputs."
|
||||
: $"Bindless handle chosen at run time among {found.Count} constant buffer handles of its phi inputs.");
|
||||
|
||||
if (Environment.GetEnvironmentVariable("DMSH_BINDLESS_TRACE") != null) // nxnative: what the handle was made of, for a diagnosis (dmsh_xlate on one job)
|
||||
{
|
||||
Console.Error.WriteLine($"bindless handle from {found.Count} phi candidate(s): {Describe(handle, 0)}");
|
||||
}
|
||||
|
||||
return TableHandle.Set;
|
||||
}
|
||||
|
||||
@@ -357,7 +380,14 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
|
||||
Operand bindlessHandle = texOp.GetSource(0);
|
||||
|
||||
if (!IsBindlessHandleAllowed(bindlessHandle))
|
||||
// nxnative: a sampled texture other than a buffer texture is indexed in the game's whole texture and sampler pools (the replay binds them by ID: dmsh_build.py pool_arrays,
|
||||
// nvn_mtl.m pool_gpu), so its arrays take the pool lengths. Buffer textures and images keep arrays of NvnSlotArrayLength, which the replay binds slot by slot (tex_dyn_slots)
|
||||
bool pooled = !texOp.Inst.IsImage() && (texOp.Type & SamplerType.Mask) != SamplerType.TextureBuffer;
|
||||
|
||||
// nxnative: a pooled read takes its handle from any source. Its texture ID indexes the pool as the GPU's does, so where the handle comes from does not matter; a handle the
|
||||
// shader computes (RE Engine: a heap index from game memory or a uniform buffer, clamped to its range and ORed with a sampler ID) was deleted and read 0 before.
|
||||
// The slot arrays of images and buffer textures keep Ryujinx's limit: the replay binds them only for handles from c2's tables
|
||||
if (!pooled && !IsBindlessHandleAllowed(bindlessHandle))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -369,10 +399,6 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
block.Operations.AddBefore(node, new Operation(Instruction.BitwiseAnd, textureHandle, bindlessHandle, OperandHelper.Const(0xfffff)));
|
||||
block.Operations.AddBefore(node, new Operation(Instruction.ShiftRightU32, samplerHandle, bindlessHandle, OperandHelper.Const(20)));
|
||||
|
||||
// nxnative: a sampled texture other than a buffer texture is indexed in the game's whole texture and sampler pools (the replay binds them by ID: dmsh_build.py pool_arrays,
|
||||
// nvn_mtl.m pool_gpu), so its arrays take the pool lengths. Buffer textures and images keep arrays of NvnSlotArrayLength, which the replay binds slot by slot (tex_dyn_slots)
|
||||
bool pooled = !texOp.Inst.IsImage() && (texOp.Type & SamplerType.Mask) != SamplerType.TextureBuffer;
|
||||
|
||||
int texturePoolLength = pooled ? Math.Max(BindlessToArray.MinimumArrayLength, gpuAccessor.QueryTextureArrayLengthFromPool()) : NvnSlotArrayLength;
|
||||
|
||||
block.Operations.AddBefore(node, new Operation(Instruction.MinimumU32, textureIndex, textureHandle, OperandHelper.Const(texturePoolLength - 1)));
|
||||
|
||||
Vendored
+158
-24
@@ -10,6 +10,10 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
static class GlobalToStorage
|
||||
{
|
||||
private const int DriverReservedCb = 0;
|
||||
private const int PushCb = 24; // NVN2 push constants (dm/gfx/nvn/dmsh_abi.h DMSH_PUSH_BANK)
|
||||
|
||||
// A constant buffer that holds buffer addresses: the driver's (c0: storage and uniform entries) and NVN2's push constants (c24: the buffer entries a game pushes)
|
||||
private static bool IsAddressCb(int slot) => slot == DriverReservedCb || slot == PushCb;
|
||||
|
||||
enum LsMemoryType
|
||||
{
|
||||
@@ -159,7 +163,7 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
(existingResult.Offset != result.Offset ||
|
||||
existingResult.ConstOffset != result.ConstOffset))
|
||||
{
|
||||
targetCbs[targetCb] = new SearchResult(result.SbCbSlot, result.SbCbOffset);
|
||||
targetCbs[targetCb] = new SearchResult(result.SbCbSlot, result.SbCbOffset, result.Handle);
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -202,19 +206,23 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
public int SbCbOffset { get; }
|
||||
public Operand Offset { get; }
|
||||
public int ConstOffset { get; }
|
||||
// nxnative: the constant buffer words hold a bindless constant buffer handle, not an address and size (InstEmitAmpere.cs ABindlessConstant; TryUnwrapHandle)
|
||||
public bool Handle { get; }
|
||||
|
||||
public SearchResult(int sbCbSlot, int sbCbOffset)
|
||||
public SearchResult(int sbCbSlot, int sbCbOffset, bool handle = false)
|
||||
{
|
||||
SbCbSlot = sbCbSlot;
|
||||
SbCbOffset = sbCbOffset;
|
||||
Handle = handle;
|
||||
}
|
||||
|
||||
public SearchResult(int sbCbSlot, int sbCbOffset, Operand offset, int constOffset = 0)
|
||||
public SearchResult(int sbCbSlot, int sbCbOffset, Operand offset, int constOffset = 0, bool handle = false)
|
||||
{
|
||||
SbCbSlot = sbCbSlot;
|
||||
SbCbOffset = sbCbOffset;
|
||||
Offset = offset;
|
||||
ConstOffset = constOffset;
|
||||
Handle = handle;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,7 +290,7 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
SearchResult result = FindUniqueBaseAddressCb(gtsContext, block, value, needsOffset: false);
|
||||
if (result.Found)
|
||||
{
|
||||
uint targetCb = PackCbSlotAndOffset(result.SbCbSlot, result.SbCbOffset);
|
||||
uint targetCb = PackCbSlotAndOffset(result.SbCbSlot, result.SbCbOffset, result.Handle);
|
||||
gtsContext.AddMemoryTargetCb(type, baseOffset, constOffset, targetCb, result);
|
||||
}
|
||||
}
|
||||
@@ -607,7 +615,7 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
SearchResult result,
|
||||
out int functionId)
|
||||
{
|
||||
List<uint> targetCbs = [PackCbSlotAndOffset(result.SbCbSlot, result.SbCbOffset)];
|
||||
List<uint> targetCbs = [PackCbSlotAndOffset(result.SbCbSlot, result.SbCbOffset, result.Handle)];
|
||||
|
||||
if (gtsContext.TryGetFunctionId(operation, isMultiTarget: false, targetCbs, out functionId))
|
||||
{
|
||||
@@ -696,6 +704,7 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
HashSet<PhiNode> visited = [];
|
||||
List<uint> targetCbs = [];
|
||||
raw = false;
|
||||
bool untraced = false; // nxnative: a source of the address traced to no storage buffer (below)
|
||||
|
||||
Operand globalAddress = operation.GetSource(0);
|
||||
|
||||
@@ -724,7 +733,7 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
|
||||
if (result.Found)
|
||||
{
|
||||
targetCbs.Add(PackCbSlotAndOffset(result.SbCbSlot, result.SbCbOffset));
|
||||
targetCbs.Add(PackCbSlotAndOffset(result.SbCbSlot, result.SbCbOffset, result.Handle));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -739,22 +748,48 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
|
||||
if (result.Found)
|
||||
{
|
||||
uint targetCb = PackCbSlotAndOffset(result.SbCbSlot, result.SbCbOffset);
|
||||
uint targetCb = PackCbSlotAndOffset(result.SbCbSlot, result.SbCbOffset, result.Handle);
|
||||
|
||||
if (!targetCbs.Contains(targetCb))
|
||||
{
|
||||
targetCbs.Add(targetCb);
|
||||
}
|
||||
}
|
||||
else if (phiSource.AsgOp is PhiNode phi2 && visited.Add(phi2))
|
||||
else if (phiSource.AsgOp is PhiNode phi2)
|
||||
{
|
||||
phis.Enqueue(phi2);
|
||||
if (visited.Add(phi2))
|
||||
{
|
||||
phis.Enqueue(phi2);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
untraced = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
targetCbs.Sort();
|
||||
|
||||
// nxnative: an address that is a storage buffer's on some paths and one the shader loaded from memory on others (PRAGMATA's cluster culling 251426e9d44fd558 reads each
|
||||
// instance's mesh header either at an offset of its push+0x170 buffer or at an address from the table at push+0x110, in other pools) misses every traced buffer on the
|
||||
// second kind of path. Ryujinx reads 0 there, which gave every instance 0 clusters, and nothing drawn by mesh shaders reached the title or the cockpit. Such a miss goes
|
||||
// through the memory pool table instead, as an access traced to no buffer does (TryGenerateRawStorageOp). The tag after the buffers keeps the helper apart from one
|
||||
// whose address is traced on every path. An access the table cannot serve (an atomic on a small integer) keeps the read of 0
|
||||
int rawFallback = -1;
|
||||
|
||||
if (untraced && targetCbs.Count != 0 &&
|
||||
(gtsContext.TryGetFunctionId(operation, isMultiTarget: true, [], out rawFallback) ||
|
||||
TryGenerateRawStorageOp(gtsContext, resourceManager, gpuAccessor, operation, out rawFallback)))
|
||||
{
|
||||
gpuAccessor.Log($"Global memory operation \"{operation.Inst}\" traced to a storage buffer on some paths only: the others go through the memory pool table.");
|
||||
targetCbs.Add(RawFallbackTag);
|
||||
}
|
||||
else
|
||||
{
|
||||
rawFallback = -1;
|
||||
}
|
||||
|
||||
if (targetCbs.Count == 0)
|
||||
{
|
||||
gpuAccessor.Log($"Global memory operation \"{operation.Inst}\" traced to no storage buffer: it goes through the memory pool table.");
|
||||
@@ -790,12 +825,27 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
|
||||
foreach (uint targetCb in targetCbs)
|
||||
{
|
||||
if (targetCb == RawFallbackTag)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
(int sbCbSlot, int sbCbOffset) = UnpackCbSlotAndOffset(targetCb);
|
||||
bool handle = IsHandleTarget(targetCb);
|
||||
|
||||
Operand baseAddrLow = Cbuf(sbCbSlot, sbCbOffset);
|
||||
Operand baseAddrHigh = Cbuf(sbCbSlot, sbCbOffset + 1);
|
||||
Operand size = Cbuf(sbCbSlot, sbCbOffset + 2);
|
||||
|
||||
if (handle)
|
||||
{
|
||||
// nxnative: a bindless constant buffer handle (InstEmitAmpere.cs ABindlessConstant): address (handle & (2^45 - 1)) << 4, size (handle >> 45) << 4
|
||||
Operand handleLow = baseAddrLow;
|
||||
baseAddrLow = context.ShiftLeft(handleLow, Const(4));
|
||||
baseAddrHigh = context.BitwiseAnd(context.BitwiseOr(context.ShiftLeft(baseAddrHigh, Const(4)), context.ShiftRightU32(handleLow, Const(28))), Const(0x1ffff));
|
||||
size = context.ShiftLeft(context.ShiftRightU32(Cbuf(sbCbSlot, sbCbOffset + 1), Const(13)), Const(4));
|
||||
}
|
||||
|
||||
Operand offset = context.ISubtract(globalAddressLow, baseAddrLow);
|
||||
Operand borrow = context.ICompareLessUnsigned(globalAddressLow, baseAddrLow);
|
||||
|
||||
@@ -823,7 +873,7 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
value = Argument(2);
|
||||
}
|
||||
|
||||
SearchResult result = new(sbCbSlot, sbCbOffset);
|
||||
SearchResult result = new(sbCbSlot, sbCbOffset, handle);
|
||||
|
||||
int alignment = gpuAccessor.QueryHostStorageBufferOffsetAlignment();
|
||||
|
||||
@@ -860,7 +910,27 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
|
||||
bool returnsValue = operation.Dest != null;
|
||||
|
||||
if (returnsValue)
|
||||
if (rawFallback >= 0)
|
||||
{
|
||||
Operand[] args = new Operand[inArgumentsCount];
|
||||
|
||||
for (int index = 0; index < inArgumentsCount; index++)
|
||||
{
|
||||
args[index] = Argument(index);
|
||||
}
|
||||
|
||||
Operand rawResult = context.Call(rawFallback, returnsValue, args);
|
||||
|
||||
if (returnsValue)
|
||||
{
|
||||
context.Return(rawResult);
|
||||
}
|
||||
else
|
||||
{
|
||||
context.Return();
|
||||
}
|
||||
}
|
||||
else if (returnsValue)
|
||||
{
|
||||
context.Return(Const(0));
|
||||
}
|
||||
@@ -1133,16 +1203,24 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
return true;
|
||||
}
|
||||
|
||||
private static uint PackCbSlotAndOffset(int cbSlot, int cbOffset)
|
||||
// nxnative: the last entry of a multi-target helper's buffers whose misses go through the memory pool table (TryGenerateMultiTargetStorageOp); no constant buffer has slot 0xffff
|
||||
private const uint RawFallbackTag = uint.MaxValue;
|
||||
|
||||
// nxnative: bit 15 marks a target whose words hold a bindless constant buffer handle (SearchResult.Handle); constant buffer slots stay below it
|
||||
private const int HandleBit = 0x8000;
|
||||
|
||||
private static uint PackCbSlotAndOffset(int cbSlot, int cbOffset, bool handle = false)
|
||||
{
|
||||
return (uint)((ushort)cbSlot | ((ushort)cbOffset << 16));
|
||||
return (uint)((ushort)(cbSlot | (handle ? HandleBit : 0)) | ((ushort)cbOffset << 16));
|
||||
}
|
||||
|
||||
private static (int, int) UnpackCbSlotAndOffset(uint packed)
|
||||
{
|
||||
return ((ushort)packed, (ushort)(packed >> 16));
|
||||
return ((ushort)packed & (HandleBit - 1), (ushort)(packed >> 16));
|
||||
}
|
||||
|
||||
private static bool IsHandleTarget(uint packed) => (packed & HandleBit) != 0;
|
||||
|
||||
private static string GetFunctionName(Operation baseOp, bool isMultiTarget, IReadOnlyList<uint> targetCbs)
|
||||
{
|
||||
StringBuilder nameBuilder = new();
|
||||
@@ -1164,9 +1242,15 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
|
||||
foreach (uint targetCb in targetCbs)
|
||||
{
|
||||
if (targetCb == RawFallbackTag)
|
||||
{
|
||||
nameBuilder.Append("_raw");
|
||||
continue;
|
||||
}
|
||||
|
||||
(int sbCbSlot, int sbCbOffset) = UnpackCbSlotAndOffset(targetCb);
|
||||
|
||||
nameBuilder.Append($"_c{sbCbSlot}o{sbCbOffset}");
|
||||
nameBuilder.Append($"_c{sbCbSlot}o{sbCbOffset}{(IsHandleTarget(targetCb) ? "h" : "")}");
|
||||
}
|
||||
|
||||
return nameBuilder.ToString();
|
||||
@@ -1345,6 +1429,11 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
{
|
||||
globalAddress = Utils.FindLastOperation(globalAddress, block);
|
||||
|
||||
if (TryUnwrapHandle(globalAddress, block, out Operand handleCb))
|
||||
{
|
||||
return GetBaseAddressCbWithOffset(handleCb, Const(0), 0, handle: true);
|
||||
}
|
||||
|
||||
if (globalAddress.Type == OperandType.ConstantBuffer)
|
||||
{
|
||||
return GetBaseAddressCbWithOffset(globalAddress, Const(0), 0);
|
||||
@@ -1379,7 +1468,9 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
offset = src1;
|
||||
}
|
||||
|
||||
SearchResult result = GetBaseAddressCbWithOffset(baseAddr, offset, 0);
|
||||
SearchResult result = TryUnwrapHandle(baseAddr, block, out Operand baseHandleCb)
|
||||
? GetBaseAddressCbWithOffset(baseHandleCb, offset, 0, handle: true)
|
||||
: GetBaseAddressCbWithOffset(baseAddr, offset, 0);
|
||||
if (result.Found)
|
||||
{
|
||||
return result;
|
||||
@@ -1397,6 +1488,20 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
src1 = operation.GetSource(0);
|
||||
src2 = operation.GetSource(1);
|
||||
|
||||
// nxnative: a source that is a bindless constant buffer handle's address (handle << 4) stands for the handle's words
|
||||
bool handle1 = TryUnwrapHandle(Utils.FindLastOperation(src1, block), block, out Operand handleCb1);
|
||||
bool handle2 = TryUnwrapHandle(Utils.FindLastOperation(src2, block), block, out Operand handleCb2);
|
||||
|
||||
if (handle1)
|
||||
{
|
||||
src1 = handleCb1;
|
||||
}
|
||||
|
||||
if (handle2)
|
||||
{
|
||||
src2 = handleCb2;
|
||||
}
|
||||
|
||||
// If we have two possible results, we give preference to the ones from
|
||||
// the driver reserved constant buffer, as those are the ones that
|
||||
// contains the base address.
|
||||
@@ -1408,20 +1513,48 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
// (Donkey Kong Bananza's effect compute shaders: c0 storage entry + offset from c1, by UIMAD.WIDE),
|
||||
// and the IR keeps the order of their sources.
|
||||
|
||||
// NVN2's push constants (c[24]) hold addresses too: PRAGMATA's compute shaders add an offset from c1 to a buffer entry the game pushed (push block 1), and the c1
|
||||
// operand, the shader's own constants, was taken for the base (its first word, 8): the buffer had no slot and the shader did not load
|
||||
if (src1.Type == OperandType.ConstantBuffer && src2.Type == OperandType.ConstantBuffer &&
|
||||
src1.GetCbufSlot() == DriverReservedCb && src2.GetCbufSlot() != DriverReservedCb)
|
||||
IsAddressCb(src1.GetCbufSlot()) && !IsAddressCb(src2.GetCbufSlot()))
|
||||
{
|
||||
return GetBaseAddressCbWithOffset(src1, src2, constOffset);
|
||||
return GetBaseAddressCbWithOffset(src1, src2, constOffset, handle1);
|
||||
}
|
||||
|
||||
if (src1.Type != OperandType.ConstantBuffer ||
|
||||
(src1.Type == OperandType.ConstantBuffer && src2.Type == OperandType.ConstantBuffer) ||
|
||||
(src2.Type == OperandType.ConstantBuffer && src2.GetCbufSlot() == DriverReservedCb))
|
||||
(src2.Type == OperandType.ConstantBuffer && IsAddressCb(src2.GetCbufSlot())))
|
||||
{
|
||||
return GetBaseAddressCbWithOffset(src2, src1, constOffset);
|
||||
return GetBaseAddressCbWithOffset(src2, src1, constOffset, handle2);
|
||||
}
|
||||
|
||||
return GetBaseAddressCbWithOffset(src1, src2, constOffset);
|
||||
return GetBaseAddressCbWithOffset(src1, src2, constOffset, handle1);
|
||||
}
|
||||
|
||||
// nxnative: a bindless constant buffer read's address is the handle << 4 (InstEmitAmpere.cs ABindlessConstant, the low word: the handle's low word << 4). When the
|
||||
// handle is a constant buffer's words (c[0]'s uniform entries, a graphics stage's uniform bank mapped there, or a handle the game pushed into c[24]), the access is traced
|
||||
// to them as to an address, with SearchResult.Handle: the host decodes the handle it reads there (nvn_mtl.m NVN_RB_SBUFQ / NVN_RB_SBUFU), and a multi-target helper
|
||||
// compares the decoded address and size
|
||||
private static bool TryUnwrapHandle(Operand value, BasicBlock block, out Operand handleCb)
|
||||
{
|
||||
handleCb = null;
|
||||
|
||||
if (value.AsgOp is Operation shift &&
|
||||
shift.Inst == Instruction.ShiftLeft &&
|
||||
shift.GetSource(1).Type == OperandType.Constant &&
|
||||
shift.GetSource(1).Value == 4)
|
||||
{
|
||||
Operand source = Utils.FindLastOperation(shift.GetSource(0), block);
|
||||
|
||||
if (source.Type == OperandType.ConstantBuffer)
|
||||
{
|
||||
handleCb = source;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static SearchResult FindBaseAddressCbFromMemory(GtsContext gtsContext, Operation operation, int constOffset, bool needsOffset)
|
||||
@@ -1438,7 +1571,8 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
result.SbCbSlot,
|
||||
result.SbCbOffset,
|
||||
result.Offset,
|
||||
result.ConstOffset + constOffset);
|
||||
result.ConstOffset + constOffset,
|
||||
result.Handle);
|
||||
}
|
||||
|
||||
return result;
|
||||
@@ -1448,7 +1582,7 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
return SearchResult.NotFound;
|
||||
}
|
||||
|
||||
private static SearchResult GetBaseAddressCbWithOffset(Operand baseAddress, Operand offset, int constOffset)
|
||||
private static SearchResult GetBaseAddressCbWithOffset(Operand baseAddress, Operand offset, int constOffset, bool handle = false)
|
||||
{
|
||||
if (baseAddress.Type == OperandType.ConstantBuffer)
|
||||
{
|
||||
@@ -1459,7 +1593,7 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
|
||||
// since the address size is 64-bit and the GPU only supports aligned memory access.
|
||||
if ((sbCbOffset & 1) == 0)
|
||||
{
|
||||
return new SearchResult(sbCbSlot, sbCbOffset, offset, constOffset);
|
||||
return new SearchResult(sbCbSlot, sbCbOffset, offset, constOffset, handle);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+79
@@ -507,6 +507,85 @@ namespace Ryujinx.Graphics.Shader.Translation
|
||||
return types;
|
||||
}
|
||||
|
||||
// nxnative: one texture read as an array by some instructions and as a plain texture by others. A handle has one binding, declared with one type: the declaration took the
|
||||
// last instruction's and the descriptor the first accurate one's, and each instruction built its coordinates for its own, so a 2D read of a binding declared a 2D array had
|
||||
// no layer (SPIRV-Cross then wrote `coord.z` of a float2, which Metal refuses: PRAGMATA, 24 pixel shaders, cb65542 handle 0x3041000E sampled with TEX 2D at level 0 and with
|
||||
// TXD ARRAY_2D). The GPU reads the texture the handle names with the coordinates each instruction gives, and without a layer that is layer 0. So such a binding is an
|
||||
// array for every instruction, and those that give no layer read layer 0. 1D and 2D only (a cube array's layer goes with the reference of a shadow read, and 3D has none);
|
||||
// a level-of-detail query takes no layer either way. Runs once every function is translated (TranslatorContext)
|
||||
public void UnifyArrayTypes(IReadOnlyList<Function> funcs)
|
||||
{
|
||||
Dictionary<SetBindingPair, List<TextureOperation>> ops = new();
|
||||
|
||||
foreach (Function func in funcs)
|
||||
{
|
||||
foreach (BasicBlock block in func.Blocks)
|
||||
{
|
||||
foreach (INode node in block.Operations)
|
||||
{
|
||||
if (node is TextureOperation texOp && !texOp.Inst.IsImage() && (texOp.Flags & TextureFlags.Bindless) == 0 && texOp.Type != SamplerType.None)
|
||||
{
|
||||
SetBindingPair pair = new(texOp.Set, texOp.Binding);
|
||||
|
||||
if (!ops.TryGetValue(pair, out List<TextureOperation> list))
|
||||
{
|
||||
ops.Add(pair, list = new());
|
||||
}
|
||||
|
||||
list.Add(texOp);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ((SetBindingPair pair, List<TextureOperation> list) in ops)
|
||||
{
|
||||
if (!Properties.Textures.TryGetValue(pair, out TextureDefinition definition) || definition.ArrayLength != 1)
|
||||
{
|
||||
continue; // an array of textures: its instructions' first source is the index
|
||||
}
|
||||
|
||||
SamplerType kind = list[0].Type & SamplerType.Mask;
|
||||
bool sameKind = list.TrueForAll(o => (o.Type & SamplerType.Mask) == kind && (o.Type & SamplerType.Multisample) == 0);
|
||||
bool mixed = list.Exists(o => (o.Type & SamplerType.Array) != 0) && list.Exists(o => (o.Type & SamplerType.Array) == 0);
|
||||
|
||||
if (!sameKind || !mixed || kind is not (SamplerType.Texture1D or SamplerType.Texture2D))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (TextureOperation texOp in list)
|
||||
{
|
||||
if ((texOp.Type & SamplerType.Array) != 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (texOp.Inst == Instruction.TextureSample)
|
||||
{
|
||||
bool intCoords = (texOp.Flags & TextureFlags.IntCoords) != 0;
|
||||
|
||||
texOp.InsertSource(texOp.Type.Dimensions, intCoords ? OperandHelper.Const(0) : OperandHelper.ConstF(0f));
|
||||
}
|
||||
|
||||
texOp.Type |= SamplerType.Array;
|
||||
}
|
||||
|
||||
Properties.AddOrUpdateTexture(new TextureDefinition(
|
||||
definition.Set, definition.Binding, definition.ArrayLength, definition.Separate, definition.Name, definition.Type | SamplerType.Array, definition.Format, definition.Flags));
|
||||
|
||||
foreach ((TextureInfo info, TextureMeta meta) in new List<KeyValuePair<TextureInfo, TextureMeta>>(_usedTextures))
|
||||
{
|
||||
if (meta.Set == pair.SetIndex && meta.Binding == pair.Binding && meta.Type != SamplerType.None)
|
||||
{
|
||||
TextureMeta array = meta;
|
||||
array.Type |= SamplerType.Array;
|
||||
_usedTextures[info] = array;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static TextureMeta MergeTextureMeta(TextureMeta meta, TextureMeta existingMeta)
|
||||
{
|
||||
meta.Set = existingMeta.Set;
|
||||
|
||||
+2
@@ -320,6 +320,8 @@ namespace Ryujinx.Graphics.Shader.Translation
|
||||
funcs[i] = new Function(cfg.Blocks, $"fun{i}", false, inArgumentsCount, outArgumentsCount);
|
||||
}
|
||||
|
||||
resourceManager.UnifyArrayTypes(funcs); // nxnative
|
||||
|
||||
return Generate(
|
||||
funcs,
|
||||
AttributeUsage,
|
||||
|
||||
@@ -36,7 +36,7 @@ def cross(spv, msl):
|
||||
"""spirv-cross as dmsh_build runs it: MSL 3.1 for a module with image atomics, which must come out as native texture atomics"""
|
||||
subprocess.run([str(SPIRV_CROSS), *atomic.cross_args(XC, str(spv)), str(spv), '--output', str(msl)], check=True)
|
||||
source = atomic.check_msl(msl.read_text())
|
||||
assert '.atomic_fetch_' in source and 'access::read_write' in source, msl
|
||||
assert ('.atomic_fetch_' in source or re.search(r'<ulong, access::read_write>.*\.atomic_(max|min)\(', source, re.S)) and 'access::read_write' in source, msl
|
||||
return source
|
||||
|
||||
|
||||
@@ -391,7 +391,18 @@ class Compiler(unittest.TestCase):
|
||||
msl = work / (key + '.metal')
|
||||
cross(spv, msl)
|
||||
self.compile_metal(msl, work, key)
|
||||
else: # U64, S64, descriptor-sized64, float and half2.
|
||||
elif size == 2: # U64: a max with no result is Metal's 64-bit texture atomic (dmsh_atomic.wide_atomics); every other form is refused (PR #1801)
|
||||
if result.returncode == 0:
|
||||
# Universal SPIR-V, not Vulkan: the 32-bit atomic pair on the rg32ui texel is a marker for the Metal rewrite, which Vulkan's
|
||||
# texel-pointer format rule (R32 / R64 only) refuses; it never reaches a Vulkan driver.
|
||||
subprocess.run(['spirv-val', '--target-env', 'spv1.3', str(spv)], check=True)
|
||||
msl = work / (key + '.metal')
|
||||
self.assertIn('texture2d_array<ulong, access::read_write>', cross(spv, msl))
|
||||
self.compile_metal(msl, work, key)
|
||||
else: # Maxwell's SURED (InstEmitSurface.EmitSured) keeps the 32-bit gate; SUATOM forms other than a max / min with no result name the 64-bit rule
|
||||
self.assertRegex(result.stderr, 'Metal 64-bit image atomics|require a 32-bit integer source size')
|
||||
self.assertFalse(spv.exists())
|
||||
else: # S64, descriptor-sized64, float and half2.
|
||||
self.assertNotEqual(result.returncode, 0, key)
|
||||
self.assertIn('require a 32-bit integer source size', result.stderr)
|
||||
self.assertFalse(spv.exists())
|
||||
|
||||
@@ -20,6 +20,7 @@ class Labels(unittest.TestCase):
|
||||
(self.root / 'dm/games' / BOTW / 'game.tsv').write_text('')
|
||||
(self.root / 'dm/gfx/tools').mkdir(parents=True)
|
||||
shutil.copy(REPO / 'dm/gfx/tools/dmsh_chain.py', self.root / 'dm/gfx/tools') # the real chain file list
|
||||
(self.root / 'dm/mac').mkdir(); shutil.copy(REPO / 'dm/mac/min_os.mk', self.root / 'dm/mac') # which dmsh_chain.py reads when run
|
||||
(self.root / 'dm/games/README.md').write_text(f'| [The Legend of Zelda: Breath of the Wild]({BOTW}/README.md) | `{BOTW}` |\n')
|
||||
|
||||
def tearDown(self):
|
||||
|
||||
@@ -124,7 +124,7 @@ class UnrealMemory(unittest.TestCase):
|
||||
'mods': {'main': {'imports': {'nvnBootstrapLoader', pg.HEAP_API}, 'bss': 0, 'far': False}},
|
||||
'romfs': {'root': set(), 'exts': {'.pak': 1}},
|
||||
'sysres': 40 * pg.MiB,
|
||||
'main_markers': {'Unreal 4'},
|
||||
'main_markers': {'Unreal'},
|
||||
}
|
||||
keys = pg.guess(facts, hooks=set())
|
||||
reserve, alias, stack = (int(keys[k][0], 0) for k in ('mem_reserve', 'mem_alias', 'mem_stack'))
|
||||
|
||||
@@ -125,6 +125,22 @@ class IntegerOutputs(unittest.TestCase):
|
||||
self.assertIsNotNone(fs_uint(src)[0])
|
||||
self.assertIsNone(fs_uint(src.replace(', flat]]', ']]'))[0])
|
||||
|
||||
def test_a_float_local_holding_integer_bits(self): # PRAGMATA's visibility shaders: the primitive id's bits and the depth into an RG32Uint target
|
||||
body = ' float _439 = as_type<float>(int(gl_PrimitiveID));\n float _437 = gl_FragCoord.z;\n out.m_0.x = _439;\n out.m_0.y = _437;'
|
||||
self.assertIsNotNone(fs_uint(self.source(body))[0])
|
||||
self.assertIsNone(fs_uint(self.source(body.replace('as_type<float>(int(gl_PrimitiveID))', 'gl_FragCoord.w')))[0])
|
||||
|
||||
def test_writes_after_an_early_return(self): # a9c1f9ea0c76a54c: a discard's branch returns zeros first; the integer bits are written after it
|
||||
early = ' if (!_435)\n {\n discard_fragment();\n }\n if (!_435)\n {\n out.m_0.x = 0.0;\n out.m_0.y = 0.0;\n return out;\n }\n'
|
||||
body = early + ' float _439 = as_type<float>(int(gl_PrimitiveID));\n float _437 = gl_FragCoord.z;\n out.m_0.x = _439;\n out.m_0.y = _437;'
|
||||
self.assertIsNotNone(fs_uint(self.source(body))[0])
|
||||
self.assertIsNone(fs_uint(self.source(body.replace('as_type<float>(int(gl_PrimitiveID))', 'gl_FragCoord.w')))[0])
|
||||
|
||||
def test_a_float_local_holding_an_array_element_of_float_bits(self): # OCTOPATH TRAVELER II's 05af5b1924d3b8b7: a register kept in a local array
|
||||
body = ' uint _30[2];\n _30[0] = 1065353216u;\n _30[0] = as_type<uint>(_680);\n float _884 = as_type<float>(_30[0]);\n out.m_0.x = _884;\n out.m_0.y = _680;'
|
||||
self.assertIsNone(fs_uint(self.source(body))[0])
|
||||
self.assertIsNotNone(fs_uint(self.source(body.replace('as_type<uint>(_680)', '_681 << 3u')))[0]) # a computed integer in the element is one
|
||||
|
||||
|
||||
class ImageAtomics(unittest.TestCase):
|
||||
MAGIC = [0x07230203, 0x10000, 0, 8, 0]
|
||||
|
||||
@@ -46,7 +46,7 @@ Every patch bound tighter than it could be: the open gaps, then the blocked, kep
|
||||
| `build` → `game` | screen shape: the sizes, the view, the layouts' projection and their edge widgets (DM_SCREEN_ASPECT) | rendering | blocked: the stubs have no function-matched form yet | judgement | 1 | [Animal Crossing: New Horizons](../../dm/games/01006F8002326000/README.md) | the output size is the host's, but where the game takes its sizes, its cameras and its layouts are this build's code |
|
||||
| `build` → `game` | 60 fps intervals and dynamic-resolution constants | frame rate | kept: 1.0.3 (v131072) is the newest update of both releases and likely their last: a function match would serve no other build; the rewriter would also need matched rules that write fixups and declare capabilities, a new mechanism (2026-11-09) | checked: both releases' mains, where the host's rows for them were found; the global main's sites mapped into ASTRAL CHAIN and Bayonetta 1-3 (2026-11-09) | 2 | [NieR:Automata The End of YoRHa Edition (010056B015FE8000)](../../dm/games/010056B015FE8000/README.md); [NieR:Automata The End of YoRHa Edition (0100B8E016F76000)](../../dm/games/0100B8E016F76000/README.md) | the game's own constants; the Asian release's function is the global one's 0x13c0 further on, so one function-matched rule could serve both releases. No PlatinumGames sibling shares the code: none of its sites has an exact match in ASTRAL CHAIN or Bayonetta 1-3 (nso_fnmap, 2026-11-09) |
|
||||
| `build` → `game` | NieR's frame interval and dynamic-resolution floor at fixed addresses | frame rate | kept: 1.0.3 (v131072) is the newest update of both releases and likely their last: a function match would serve no other build; the rewriter would also need matched rules that write fixups and declare capabilities, a new mechanism (2026-11-09) | checked: both releases' mains, where these rows were found; the global main's sites mapped into ASTRAL CHAIN and Bayonetta 1-3 (2026-11-09) | 2 | [NieR:Automata The End of YoRHa Edition (010056B015FE8000)](../../dm/games/010056B015FE8000/README.md); [NieR:Automata The End of YoRHa Edition (0100B8E016F76000)](../../dm/games/0100B8E016F76000/README.md) | the game's own display object; the Asian release's function is the global one's 0x13c0 further on, so the rewriter's function match could give the host both releases' addresses. No PlatinumGames sibling shares the code: none of its sites has an exact match in ASTRAL CHAIN or Bayonetta 1-3 (nso_fnmap, 2026-11-09) |
|
||||
| `game` → `host` | one vertex shader's visibility counter (VertexCounterLowering) | shaders | kept: one shader in one game, already handled; a general lowering is a chain change (every game's shaders rebuilt) for no measured gain: revisit when a vertex shader with subgroup operations fails in another game | checked: the shader-build logs of the 51 game builds on the game drive: no shader failed to translate or compile, none mentions a subgroup operation (2026-11-09) | — | [Program.cs:259](../../dm/gfx/tools/dmsh_xlate/Program.cs#L259) | a general lowering of subgroup ballots in vertex shaders (subgroups of one invocation: ballots, votes, lane ids and counts, refusing shuffles that exchange data between lanes) would cover any shader that counts that way |
|
||||
| `game` → `host` | one vertex shader's visibility counter (VertexCounterLowering) | shaders | kept: one shader in one game, already handled; a general lowering is a chain change (every game's shaders rebuilt) for no measured gain: revisit when a vertex shader with subgroup operations fails in another game | checked: the shader-build logs of the 51 game builds on the game drive: no shader failed to translate or compile, none mentions a subgroup operation (2026-11-09) | — | [Program.cs:260](../../dm/gfx/tools/dmsh_xlate/Program.cs#L260) | a general lowering of subgroup ballots in vertex shaders (subgroups of one invocation: ballots, votes, lane ids and counts, refusing shuffles that exchange data between lanes) would cover any shader that counts that way |
|
||||
| `build` → `game` | 60 fps frame step (112 sites) | frame rate | kept: 1.0.1 (2019) is the last update; a function match would serve no other build of this game | checked: nso_fnmap of its 112 sites into those four mains (2026-11-09) | 1 | [ASTRAL CHAIN](../../dm/games/01007300020FA000/README.md) | the game's own clock and timers (a community 60 fps mod on the host's frame step). PlatinumGames' other games do not share them: none of its 15 functions has an exact match in Bayonetta, Bayonetta 2, Bayonetta 3 or NieR:Automata |
|
||||
| `build` → `game` | 60 fps frame step and render scale (ksys::VFR) | frame rate | kept: 44 sites in 34 functions to fingerprint for an update that may not come (1.9.0, the Switch 2 Edition release); convert when a new build appears | checked: nso_fnmap of its 44 sites into those 13 mains (2026-11-09) | 1 | [The Legend of Zelda: Breath of the Wild](../../dm/games/01007EF00011E000/README.md) | the game's own frame code; the frame-step state page is general. No engine sibling shares it: none of its 34 functions has an exact match in Tears of the Kingdom, SMO, MK8D, ACNH, Splatoon 2 / 3, Kirby, Mario Party, Ocarina, Smash, Metroid Dread or Origami King (only the widescreen stubs' sead::PerspectiveProjection functions recur) |
|
||||
| `build` → `game` | Hagi coroutine stack region 1 GB → 64 MB | memory | kept: 1.1.4 is the last update; a match over Hagi would serve no other build of this game | checked: the final build 1.1.4 (the only one the profile packs), 2026-11-04 | 1 | [Super Mario 3D All-Stars: Super Mario Sunshine](../../dm/games/010049900F546002/README.md) | a size inside Hagi's own code: nothing the host sees tells a 1 GB reservation it can shrink from one it cannot |
|
||||
@@ -623,7 +623,7 @@ Applied to the `sdk` of any build without CUTS, found by function fingerprint ([
|
||||
|
||||
## Translator rules keyed by a shader's code
|
||||
|
||||
- [Program.cs:259](../../dm/gfx/tools/dmsh_xlate/Program.cs#L259): Tears of the Kingdom 1.4.3 visibility counter (one vertex shader, exact code SHA-256 below) (**`game` → `host`**, kept: one shader in one game, already handled; a general lowering is a chain change (every game's shaders rebuilt) for no measured gain: revisit when a vertex shader with subgroup operations fails in another game: a general lowering of subgroup ballots in vertex shaders (subgroups of one invocation: ballots, votes, lane ids and counts, refusing shuffles that exchange data between lanes) would cover any shader that counts that way)
|
||||
- [Program.cs:260](../../dm/gfx/tools/dmsh_xlate/Program.cs#L260): Tears of the Kingdom 1.4.3 visibility counter (one vertex shader, exact code SHA-256 below) (**`game` → `host`**, kept: one shader in one game, already handled; a general lowering is a chain change (every game's shaders rebuilt) for no measured gain: revisit when a vertex shader with subgroup operations fails in another game: a general lowering of subgroup ballots in vertex shaders (subgroups of one invocation: ballots, votes, lane ids and counts, refusing shuffles that exchange data between lanes) would cover any shader that counts that way)
|
||||
|
||||
## Profile switches
|
||||
|
||||
|
||||
+26
-1
@@ -422,6 +422,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- a movie with a Vorbis track plays its first seconds with sound; after the game flushes and restarts it (a seek, a loop, or the app losing and regaining focus) the picture goes on but the sound does not come back, for the rest of the movie. The log shows `[movie] Flush`, `Flush`, `Start`, `Start` and no more `GetOutputBuffer … → PCM` lines. With `DM_AUDIO_DUMP`, the game's mix is real audio up to the flush and exact zeros from then on, so the AudioUnit is not at fault (0 underruns). → [Vorbis sound stops for good after a Flush](../reference/movies.md#vorbis-sound-stops-for-good-after-a-flush)
|
||||
- on an iPad with an M1 (the one supported chip without I8MM), the app quits at the first AV1 movie (a title or opening movie): `[dm] CRASH sig=4 addr=put_8tap_neon_i8mm+0x… lr=dav1d_recon_b_inter_8bpc+0x…`, with a `dav1d_worker_task` thread beside it. The same build plays on an M2 or newer iPad, an A17 Pro or newer iPhone, and on the Mac. → [AV1 movies stop an M1 iPad with SIGILL in dav1d](../reference/movies.md#av1-movies-stop-an-m1-ipad-with-sigill-in-dav1d)
|
||||
- a Switch 2 game crashes when a movie starts: `nn::codec::video::Initialize` faults in the SDK (Donkey Kong Bananza: `sdk+0x2de99c`, after its first punch, when the guide movie starts), and before that `nv::InitCheck` aborts (`hle_nv.c`). Later, when a second movie starts: `game called nn::diag abort: Result 0` in `nn::os::ClearSystemEvent` or `TryWaitSystemEvent` on the decoder's event. → [`nn::codec` video decoders taken over](../reference/movies.md#nncodec-video-decoders-taken-over)
|
||||
- every movie stays black; `[RED] nn::codec H.264: VideoToolbox could not decode a packet`, the packets starting with an SEI NAL unit, not a parameter set. → [H.264 parameter sets past the eighth argument](../reference/movies.md#h264-parameter-sets-past-the-eighth-argument)
|
||||
- a movie stays black with the game waiting behind it, the decoder made and no `first picture` line (`Submit…InputBuffer` never called). Or `[RED] nn::codec VP9: Corrupt frame detected`, then `Keyframe / intra-only frame required`, each time about 6 s into a movie or after skipping in one. → [The submission-ready event counted as packets](../reference/movies.md#the-submission-ready-event-counted-as-packets)
|
||||
- a crash in `nn::codec::video::InitializeAv1DecoderByTransferMemory` when a movie starts. → [AV1 movies through SDK 22's decoder](../reference/movies.md#av1-movies-through-sdk-22s-decoder)
|
||||
- an abort in `nn::codec` (the SDK's own decoder client, which opens a service the host does not have) when a movie starts in a game built with SDK 19 for the Switch 2. → [SDK 19's decoder forms](../reference/movies.md#sdk-19s-decoder-forms)
|
||||
@@ -564,6 +565,9 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- `[RED] memory pool … created at retry N`. → [`newBufferWithBytesNoCopy` retried under memory pressure](../reference/nvn-objects.md#newbufferwithbytesnocopy-retried-under-memory-pressure)
|
||||
- a buffer is created with a null pool right after a scene change. → [Virtual memory pools mapped onto one physical pool](../reference/nvn-objects.md#virtual-memory-pools-mapped-onto-one-physical-pool)
|
||||
- `[RED] MapVirtual: non-contiguous mapping (true sparse) not implemented`. → [Sparse virtual pools built from separate physical pools](../reference/nvn-objects.md#sparse-virtual-pools-built-from-separate-physical-pools)
|
||||
- `[RED] virtual pool …: more than 1024 separate mapped runs`, then a GPU hang minutes later: `[RED] the host has waited 10 s for GPU work`, an indirect dispatch of absurd size (`283343572 x 965150577 x 1006648320 groups`), and the game aborts once its 15 s `nvnSyncWait` expires. → [More than 1,024 mapped runs in a sparse pool](../reference/nvn-objects.md#more-than-1024-mapped-runs-in-a-sparse-pool)
|
||||
- in a game that maps and unmaps sparse pages while it runs: an indirect dispatch of absurd size, a GPU hang, then a crash in the game's own code reading a command list that holds another object's data. → [Pages changed under a buffer the GPU still uses](../reference/nvn-objects.md#pages-changed-under-a-buffer-the-gpu-still-uses)
|
||||
- `[RED] shader <key>: the buffer address the game pushed at c[24] + … is …, in no memory pool: bound to a dummy buffer`, once or twice in minutes, for an address inside a mapped run of a sparse pool; the draw or dispatch of that frame reads zeros. → [A sparse pool's runs replaced in two steps](../reference/nvn-objects.md#a-sparse-pools-runs-replaced-in-two-steps)
|
||||
- `[RED] MapVirtual: non-contiguous mapping (true sparse) not implemented`, on small virtual pools; streamed textures black or missing (OCTOPATH TRAVELER's village ground and plants). → [Virtual pools of one texture each, mapped before and after the texture](../reference/nvn-objects.md#virtual-pools-of-one-texture-each-mapped-before-and-after-the-texture)
|
||||
- `[RED] NVN unimplemented function called: nvnTextureBuilderGetSparseTileLayout`, then an out-of-memory abort in Unreal's allocator (`Failed to allocate 1879113728 bytes from Standard Allocator`, on `DM_DBG=1`). → [The sparse tile layout of a texture](../reference/nvn-objects.md#the-sparse-tile-layout-of-a-texture)
|
||||
- `CRASH sig=10` in `memmove` from `pkg_upload` → `nvn_deswizzle`, at an address 32 GB into a sparse virtual pool; textures with unaliased tails came out magenta. → [Textures read through a 4 KB page table of a sparse pool](../reference/nvn-objects.md#textures-read-through-a-4-kb-page-table-of-a-sparse-pool)
|
||||
@@ -585,6 +589,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- `nvn_replay` stops with `program #N (a key …) stage S: the translated shader's bindings or inputs differ from the ones the records were captured against`, and `regress.py replay` reports every game's capture as one the candidate cannot replay, while the shaders' reflection (`<key>_b.json`) is the same in both chains apart from the chain field. → [A capture refused after a change to the reflection structs](../reference/nvn-objects.md#a-capture-refused-after-a-change-to-the-reflection-structs)
|
||||
- `texture object no longer valid`, followed by `CRASH sig=10` in `nvn_sparse_pool` through `sparse_gpu_wrote` and `attach`. In Rhythm Heaven Groove's frog stage, the supposed texture contained a texture handle followed by an `OP_DRAW_IDX` record. → [Bound render targets outlive command recordings](../reference/nvn-objects.md#bound-render-targets-outlive-command-recordings)
|
||||
- `[RED] NVN unimplemented function called: nvnCommandBufferGetControlMemoryFree` (or `…GetControlMemorySize`) once, after the game gives a command buffer control memory. → [Control memory capacity queries](../reference/nvn-objects.md#control-memory-capacity-queries)
|
||||
- `[RED] NVN unimplemented function called: nvnQueueBuilderGetCommandMemorySize` (or `…GetComputeMemorySize`, `…GetControlMemorySize`, `…GetRayTracingMemorySize`, `nvnQueueBuilderSetRayTracingMemorySize`), once each, as the game makes its queue. → [Queue builder size getters](../reference/nvn-objects.md#queue-builder-size-getters)
|
||||
- `FATAL NVN command memory: the game's pool is empty…`. → [Host-lent command memory segments](../reference/nvn-objects.md#host-lent-command-memory-segments)
|
||||
- frames stop after about 15 s; a game thread spins in its command-memory callback (a ring allocator at `main+0x9cc120` waiting for fences that have all signalled). → [What `GetCommandMemoryUsed` counts](../reference/nvn-objects.md#what-getcommandmemoryused-counts)
|
||||
- `CRASH sig=10` in `mtl_exec` after minutes of play, the fault address equal to `x19` and shaped like `0x1000000003`. → [Prerecorded lists in slots of their measured size](../reference/nvn-objects.md#prerecorded-lists-in-slots-of-their-measured-size)
|
||||
@@ -599,6 +604,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- `FATAL submit re-entered` in the first frames. → [Submissions from two queues on two threads](../reference/nvn-objects.md#submissions-from-two-queues-on-two-threads)
|
||||
- going to the background (iOS `sceneDidEnterBackground`, minimizing the Mac window) while the "Preparing shaders" or "Preparing pipelines" screen is up blocks the main thread until the step ends: minutes on a first start, long enough for iOS to end the app. The log's `[nvn] graphics suspended` line comes only after the `pipeline prepare:` line. → [Going to the background during the prepare step](../reference/nvn-objects.md#going-to-the-background-during-the-prepare-step)
|
||||
- frames stop, no crash, the main thread sits in `nvnSyncWait(sync, -1)`, and the watchdog's wait-state line shows the main fence one short (`main fence submitted N / completed N-1`). → [A GPU command buffer that never completes](../reference/nvn-objects.md#a-gpu-command-buffer-that-never-completes)
|
||||
- `game called nn::diag abort` right after a screen change (PRAGMATA: the Initial Settings menu's Next), with nothing slow before it. → [A sync never fenced since its Initialize is signalled](../reference/nvn-objects.md#a-sync-never-fenced-since-its-initialize-is-signalled)
|
||||
- the frame's blocking SyncWait on its newest fence wakes about 0.26–0.29 ms after the GPU end (M2 Max; the wait ledger, `DM_NVN_WAITS=1`), on the critical path of every frame. → [The game's SyncWait wakes on the GPU's own signal of its fence](../reference/nvn-objects.md#the-games-syncwait-wakes-on-the-gpus-own-signal-of-its-fence)
|
||||
- loading screens many times slower on the iPhone than on the Mac (Three Houses' first loading screen 78 s on the iPhone, 5 s on the Mac). → [`nvnQueueFinish` waits for the GPU, not the display](../reference/nvn-objects.md#nvnqueuefinish-waits-for-the-gpu-not-the-display)
|
||||
- CPU texture uploads spend time recalculating block-linear addresses and calling variable-length `memcpy` for every 16-byte segment. → [CPU deswizzle copies use slice and row offsets](../reference/nvn-objects.md#cpu-deswizzle-copies-use-slice-and-row-offsets)
|
||||
@@ -764,6 +770,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- `nvnBlendStateSetAdvancedMode 8` (SRC_OVER) logged and blended with the state's own functions. → [Advanced blend modes as Porter-Duff factors](../reference/rendering.md#advanced-blend-modes-as-porter-duff-factors)
|
||||
- striped lighting: black and white bands that follow depth on every lit surface, as if every pixel were in or out of shadow at random. → [Stencil-mode texture views read through `X32_Stencil8`](../reference/rendering.md#stencil-mode-texture-views-read-through-x32_stencil8)
|
||||
- a character drawn as a dithered silhouette inside a dithered square (DRAGON QUEST VII Reimagined's hero). → [Stencil-mode textures from the texture builder](../reference/rendering.md#stencil-mode-textures-from-the-texture-builder)
|
||||
- `[RED] NVN unimplemented function called: nvnCommandBufferSetProvokingVertexMode`, once. → [The provoking vertex is the first](../reference/rendering.md#the-provoking-vertex-is-the-first)
|
||||
- `[nvn] SetConservativeRasterEnable on: ignored by host for now`, followed by `[RED] NVN unimplemented function called: nvnCommandBufferSetConservativeRasterDilate`. → [Conservative rasterization remains unimplemented](../reference/rendering.md#conservative-rasterization-remains-unimplemented)
|
||||
- characters (skinned models) invisible or stretched into streaks while the level renders; `vertex attribute format … does not match shader input type …` for a remaining mismatch. → [Integer vertex inputs](../reference/rendering.md#integer-vertex-inputs)
|
||||
- red lines 89 and 96 (`vconv_bind`, the CPU conversion every draw); about a quarter of Age of Calamity's replay thread in battle. → [Shadow vertex inputs](../reference/rendering.md#shadow-vertex-inputs)
|
||||
@@ -987,6 +994,10 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- a depth prepass of many small geometry-shader draws, drawn as mesh draws, leaves the GPU nearly idle: the per-pass profile (`DM_NVN_GPUPROF`) shows an idle gap before the pass that grows with its draw count (about 2.3 µs a draw), and the GPU counters show vertex-only time at about 4 % occupancy. → [Mesh geometry draws gathered into one dispatch](../reference/shaders.md#mesh-geometry-draws-gathered-into-one-dispatch)
|
||||
- white blotches over Kokiri Forest's foliage, walkway and ground in Ocarina of Time, which are the house light tiles. The light-tile pass of task `a5288d0a6c4971fd` with meshes `e8c667282ba7bd9b` and `d4171cf9adf0504b` writes constant white through fragment `ea1bf96b72e72476`, and its triangles were corrupt. → [Mesh stage memory reserves the primitive index bytes for every primitive block](../reference/shaders.md#mesh-stage-memory-reserves-the-primitive-index-bytes-for-every-primitive-block)
|
||||
- a mesh shader's per-primitive outputs read as other values once it has more than 32 vertices: Ocarina of Time's Poe Sisters and Phantom Ganon paintings (mesh shaders `ee4ef51a4fddc28e` and `83c0dbc51c5481e3`, 128 vertices, 64 primitives, a per-primitive colour) came out solid green or magenta (pull request #1590). A mesh shader that draws points with a point size takes the size as its position's x. → [Mesh attributes: every vertex block before the primitive blocks](../reference/shaders.md#mesh-attributes-every-vertex-block-before-the-primitive-blocks)
|
||||
- a mesh-shaded draw shows nothing, though its workgroups run: every workgroup ends with a primitive count of 0. Once that is mended, a visibility buffer written from `[[primitive_id]]` holds only the index within the meshlet, and each pixel is shaded from the wrong cluster. → [Mesh shader per-primitive system values: the primitive count overwritten, the primitive id lost](../reference/shaders.md#mesh-shader-per-primitive-system-values-the-primitive-count-overwritten-the-primitive-id-lost)
|
||||
- thin streaks or stray triangles from a mesh shader over parts of the picture its geometry does not cover (PRAGMATA: white vertical streaks over the cockpit window in the opening). → [Mesh shaders that also address their vertices as records](../reference/shaders.md#mesh-shaders-that-also-address-their-vertices-as-records)
|
||||
- `NotSupportedException: Ampere 923 …: ISBERD mode f8 in a task or mesh shader` in the shader build; those mesh shaders are left out and their draws skipped (`[RED] DrawMeshTasks without its task and mesh shaders`). → [Mesh shaders that read their own outputs back](../reference/shaders.md#mesh-shaders-that-read-their-own-outputs-back)
|
||||
- a small scan or sort in a compute shader gives wrong results every frame, with no barrier in its loop (Orbitals: Niagara's sorted particle indices). → [Threadgroup stores in warp-synchronous code](../reference/shaders.md#threadgroup-stores-in-warp-synchronous-code)
|
||||
- `primitive type 14 not implemented`; patch draws skipped. → [Tessellation stages are not drawn](../reference/shaders.md#tessellation-stages-are-not-drawn)
|
||||
- a Switch 2 game's shaders do not translate (the translator reads Maxwell: 64-bit instructions behind scheduling words, a 0x50-byte SPH), or, rewritten as Maxwell code, UI text draws as solid boxes or not at all. → [Ampere shader code (Switch 2)](../reference/shaders.md#ampere-shader-code-switch-2)
|
||||
- a lit pass far slower on an M1 than the M4 Pro's figures suggest, the time spread over every material that loops over the scene's lights; dropping one material's draws (`DM_NVN_UB`) saved only its share. → [Storage words read one by one](../reference/shaders.md#storage-words-read-one-by-one)
|
||||
@@ -995,6 +1006,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- objects from a compute-built list flicker: each is in one of two states, on and off irregularly and independently of the others, while the draws are the same frame to frame and the camera is still. Whole groups may vanish or appear in one frame and stay that way until the list's next rebuild. Shots of consecutive frames show the change per frame jumping between two levels. → [A store only a dispatch's first invocation makes](../reference/shaders.md#a-store-only-a-dispatchs-first-invocation-makes)
|
||||
- `metal` runs for hours on a shader of about 100 MB of MSL, mostly indentation, stuck in LICM (`hoistRegion` → `ScalarEvolution::forgetValue`), then the GPU compiler's connection breaks; even `-O0` and finished libraries crash it. Hundreds of forced one-pass loops nest around the program. → [Goto elimination forcing loops around a whole program](../reference/shaders.md#goto-elimination-forcing-loops-around-a-whole-program)
|
||||
- none met in a game yet: found by differential testing (single instructions with nvdisasm-checked encodings, run on an Apple GPU and compared with an interpreter on Mesa NAK's hardware-checked folds). A 64-bit three-operand add off by 2^32, `POPC R, 0x800000ff` giving 23, a predicate pair from `PLOP3` that reads its own first result, a negative 32-bit index added to a 64-bit address as if positive. → [Ampere carries, PLOP3's second result, POPC / FLO immediates, LEA.SX32 and LEA's negated B](../reference/shaders.md#ampere-carries-plop3s-second-result-popc--flo-immediates-leasx32-and-leas-negated-b)
|
||||
- a predicate pair that disagrees with itself (`FSETP.LT.AND P0, P1, R2, R3, P0`: P1 combined with the new P0, not the old); a multiply-add off by `2 * a * b` (IMAD read as `a * -b + c`). → [FSETP / ISETP pairs on their own accumulator, and IMAD's B](../reference/shaders.md#fsetp--isetp-pairs-on-their-own-accumulator-and-imads-b)
|
||||
- `BRX with no target`, or code about 20 % larger than it should be. → [Ampere jump tables read past their end](../reference/shaders.md#ampere-jump-tables-read-past-their-end)
|
||||
- `BRX with no target found in the c1 jump table`, although the shader's `LDC` of the table's base is on the only path to the BRX. → [An Ampere jump table loaded in a block split later](../reference/shaders.md#an-ampere-jump-table-loaded-in-a-block-split-later)
|
||||
- `Ampere instruction 308` refused; a neural upscaler's programs missing, so the frame never reaches the window (a black 3D scene). → [MUFU.F16](../reference/shaders.md#mufuf16)
|
||||
@@ -1006,6 +1018,9 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- wrong shading where a shader needs a cross product or a 2D rotation of half pairs; on Eden-NS2, which first read the mode as a plain negation of the high lane, sun and cloud shadows were lost. → [HFMA2 .H0_NH1](../reference/shaders.md#hfma2-h0_nh1)
|
||||
- a global load, store or atomic at the wrong address in code that uses `desc[URb][Ra.64]` (the descriptor's value added to the address); a shader with `ATOMG.CAS` refused (`Ampere instruction 3a9 ... is not implemented`); an `ATOMG.INC` / `ATOMG.DEC` / `RED.INC` / `RED.DEC` with no effect. → [Global memory: descriptors, ATOMG.CAS, INC / DEC](../reference/shaders.md#global-memory-descriptors-atomgcas-inc--dec)
|
||||
- a shared-memory counter that never moves (`ATOMS.INC`, `ATOMS.DEC`: CUDA's atomicInc / atomicDec, the old value read as 0); a lock-free update on shared memory that loops or takes a wrong branch after `ATOMS.CAS` (its result 0 or 1 instead of the old value). → [ATOMS.INC / ATOMS.DEC, and ATOMS.CAS's result](../reference/shaders.md#atomsinc--atomsdec-and-atomscass-result)
|
||||
- `[translation failed] NotSupportedException: Ampere 307 at …: FRND of a float that is not 32-bit`. → [FRND of a half (FRND.F16)](../reference/shaders.md#frnd-of-a-half-frndf16)
|
||||
- `[translation failed] NotSupportedException: Ampere instruction f66 … is not implemented`, `Ampere instruction 595 … is not implemented`, or `Ampere 906 …: I2F byte select of a 32-bit source`. → [Ampere forms met on PRAGMATA: TLD through a uniform register, I2F of an immediate, SUATOM.CAS](../reference/shaders.md#ampere-forms-met-on-pragmata-tld-through-a-uniform-register-i2f-of-an-immediate-suatomcas)
|
||||
- a shared-memory atomic built from a compare-and-swap loop (INC, DEC, the 64-bit and float operations) spins longer than it should or stores a value computed from stale data when other threads write the word. → [The shared compare-and-swap loop retries with the value it got](../reference/shaders.md#the-shared-compare-and-swap-loop-retries-with-the-value-it-got)
|
||||
- wrong values in the high lane of half-pair math that scales by one half of a uniform (`HMUL2 R37, R37.H0_H0, c[0x0] [0x168].H0_H0`), or a garbage operand where a half-pair operation reads a 32-bit float (`R20.F32`). → [Half-pair swizzle on a constant, and .F32](../reference/shaders.md#half-pair-swizzle-on-a-constant-and-f32)
|
||||
- a half comparison with `.FTZ` on a subnormal operand passes where NVIDIA's fails (or the reverse): `HSET2.BF.GT.FTZ R6, R19, RZ` gives 1.0 for a positive subnormal half, 0 on NVIDIA. → [HSETP2 / HSET2 .FTZ](../reference/shaders.md#hsetp2--hset2-ftz)
|
||||
- integer division results one off for some operands (the compiler's 32-bit division takes its reciprocal from `I2F.U32.RP`), or a half one ulp off (an overflow giving infinity instead of the largest finite value) after `F2F.F16.F32.RM` / `.RP` / `.RZ`. → [I2F and F2F directed rounding](../reference/shaders.md#i2f-and-f2f-directed-rounding)
|
||||
@@ -1022,12 +1037,16 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- `Ampere instruction <op> at 0x… is not implemented`, `F2FP.MERGE_C` or `F2I from a float that is not 32-bit` in the shader build; those shaders are left out and their draws and dispatches skipped. → [Ampere instructions new in Pokémon Pokopia](../reference/shaders.md#ampere-instructions-new-in-pokémon-pokopia)
|
||||
- single bright dots at thin far geometry (railings, track edges), changing frame to frame as the camera moves, already in the lit picture before anti-aliasing. Most of them come from another cause (below). → [Comparisons with .FTZ](../reference/shaders.md#comparisons-with-ftz)
|
||||
- none on the Mac. Suspected as a cause of GPU hangs (`kIOGPUCommandBufferCallbackErrorHang`) in compute, task and mesh shaders that return before a `threadgroup_barrier`. → [Compute threads that return before a barrier](../reference/shaders.md#compute-threads-that-return-before-a-barrier)
|
||||
- a GPU hang (`kIOGPUCommandBufferCallbackErrorHang`, `[RED] the host has waited 10 s for GPU work`) in a compute shader whose threads poll a flag in a loop with no BAR.SYNC: a persistent work queue. → [MEMBAR is a fence, not a barrier](../reference/shaders.md#membar-is-a-fence-not-a-barrier)
|
||||
- `Ampere instruction f55 at 0x… (000fe20000000000000000001a0f7f55) is not implemented` in the shader build; those shaders are left out. → [Barrier moves around warp shuffles](../reference/shaders.md#barrier-moves-around-warp-shuffles)
|
||||
- `Ampere b82 at 0x…: LDC with a bindless bank or an address mode (…00008a00…7b82)` in the shader build; those shaders are left out. → [LDC with the bank in its address register (`.IS`)](../reference/shaders.md#ldc-with-the-bank-in-its-address-register-is)
|
||||
- 64-bit arithmetic in a shader gives wild results: the 64-bit division behind an exposure average returned 893011 for 218, so the exposure stayed at the end of its range. With only the pair fixed it still gave 2 for 340 / 1. → [IMAD.HI adds a register pair, and IMAD.X its carry](../reference/shaders.md#imadhi-adds-a-register-pair-and-imadx-its-carry)
|
||||
- a scene lit by many small lights comes out too dark, with its clustered light lists empty for most clusters. → [NVN2 compute reads its workgroup counts at c0 + 4](../reference/shaders.md#nvn2-compute-reads-its-workgroup-counts-at-c0--4)
|
||||
- `Ampere instruction 361` (or `f60`, `370`, `38d` and others) refused, or hundreds of `Failed to find handle source for bindless access of type "textureCube"` when the handle was taken from the wrong register: units drawn white, the rest of the scene right. → [Texture handles of SDK 22's Ampere code](../reference/shaders.md#texture-handles-of-sdk-22s-ampere-code)
|
||||
- `reflection conversion failed: B binding cp_t_cb196610_10280074Smplr has no resolved slot number` at load, then `the dispatched program has no compute shader`; the shader's image has no slot either (`cp_i_tcb_AA_`). → [NVN2 compute's separate handles in c[0]](../reference/shaders.md#nvn2-computes-separate-handles-in-c0)
|
||||
- the GPU never finishes the first 3D frame: `[RED] the host has waited 10 s for GPU work`, with persistent compute shaders (a loop on a work counter, `threadgroup_barrier` inside) among the failed command buffer's shaders. → [NVN2 compute's second push block holds buffer entries](../reference/shaders.md#nvn2-computes-second-push-block-holds-buffer-entries)
|
||||
- `Ampere … bank 25` (to 29) refused, or `stage N cbN has no uniform buffer bound` for graphics shaders that read buffers through an address. Then, with those banks taken for the uniform slots: `[RED] graphics push constants into block 5 (0 + 0x10): the host keeps 2, dropped`, `sbufp reg3 dummy` (to reg5) for a mesh shader in the pass dump, and everything a visibility buffer draws comes out black while the rest of the frame is lit. → [NVN2 graphics stages' buffer banks (c[25] to c[29]) are push blocks](../reference/shaders.md#nvn2-graphics-stages-buffer-banks-c25-to-c29-are-push-blocks)
|
||||
- `Ampere … is not implemented` for ALU forms, ULDC (0xab9) or LDC (0x582) with bit 91 set. → [Uniform words read through a buffer address (cx)](../reference/shaders.md#uniform-words-read-through-a-buffer-address-cx)
|
||||
- `reflection conversion failed: B binding fp_t_cb2_170 has no resolved slot number` at load (the draw is skipped), the build summary counting the binding under *slot was not decoded*; or, once the read's other inputs are known, `Failed to find handle source for bindless access of type "texture2D"` and the read answers 0. `DMSH_BINDLESS_TRACE=1` on a `dmsh_xlate` job prints what a refused handle is made of. → [A handle pair ORed sampler word first](../reference/shaders.md#a-handle-pair-ored-sampler-word-first)
|
||||
- a Switch 2 game's frame rate swings between 60 and 30 fps (Donkey Kong Bananza's own controller, `main+0x204a18`, drops to 30 after two frames of 20 ms from their start to the GPU's end, and comes back after six), and the GPU profile (`DM_NVN_GPUPROF`) shows one compute dispatch of 2-6.5 ms a frame: agl's upscaler network (`agl_ndsr.pck`, shader `7629d857a0a93833`). → [Ampere HMMA through simdgroup_matrix](../reference/shaders.md#ampere-hmma-through-simdgroup_matrix)
|
||||
- a Switch 2 game's movie or upscaler network runs slow on the Mac and iPhone, and the GPU profile (`DM_NVN_GPUPROF` with `DM_NVN_DISPATCH_OWN=1`) shows its compute dispatches, small grids of one to four SIMD-groups a threadgroup that loop over tiles, at 1-3 ms each; the dispatches' shaders call `dmsh_hmma16816_f16` hundreds of times (Ampere HMMA through simdgroup_matrix). → [HMMA chains keep their matrices in the SIMD-group](../reference/shaders.md#hmma-chains-keep-their-matrices-in-the-simd-group)
|
||||
@@ -1042,7 +1061,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- point sprites of size 0 (Odyssey's Cap Kingdom fog never parted around Mario). → [Graphics `c0 + 0x610`: the largest point size](../reference/shaders.md#graphics-c0--0x610-the-largest-point-size)
|
||||
- occlusion queries that always return 0 samples (Z-A: characters' legs folded back from the hips once they walked); every instanced draw's transform taken for instance 0. → [Graphics `c0 + 0x644`: the draw's base instance](../reference/shaders.md#graphics-c0--0x644-the-draws-base-instance)
|
||||
- flat grey or background-coloured triangles with straight edges across part of the scene, changing shape from frame to frame while the camera stands still; dropping the colour pass's fragment shaders in groups (`DM_NVN_SKIP_FS`) did not remove them, as the instances are misplaced in the depth pre-pass too, whose depth the colour pass tests for equality. → [The base instance of indirect draws comes from Metal](../reference/shaders.md#the-base-instance-of-indirect-draws-comes-from-metal)
|
||||
- `[RED] shader … reflection conversion failed: reads driver-bank locations at run time that the replay layer cannot fill: c0 dynamic index c0+0x630`, and that shader's draws are missing; the build notes `Shader instruction Pixld is not implemented` for pixel shaders; `[RED] NVN unimplemented function called: nvnProgramSetSampleShading`. → [Pixel `c0 + 0x620`: the sample index and GLSLC's sample position table](../reference/shaders.md#pixel-c0--0x620-the-sample-index-and-glslcs-sample-position-table)
|
||||
- `[RED] shader … reflection conversion failed: reads driver-bank locations at run time that the replay layer cannot fill: c0 dynamic index c0+0x630` (or `c0 dynamic index` alone), and that shader's draws are missing (`[RED] shader … (pixel) failed to load`); the build notes `Shader instruction Pixld is not implemented` for pixel shaders; `[RED] NVN unimplemented function called: nvnProgramSetSampleShading`. → [Pixel `c0 + 0x620`: the sample index and GLSLC's sample position table](../reference/shaders.md#pixel-c0--0x620-the-sample-index-and-glslcs-sample-position-table)
|
||||
- a menu's labels drawn as plain bars, other menus empty except for the cursor (one pool's textures overwritten by another's); a black screen when IDs past a fixed table read as empty slots. → [Texture and sampler pools with overlapping IDs](../reference/shaders.md#texture-and-sampler-pools-with-overlapping-ids)
|
||||
- red lines from the list of command buffers that bound a non-first pool (6,734 in one DARK SOULS: REMASTERED run). → [Bases of bound handles kept in the command buffer](../reference/shaders.md#bases-of-bound-handles-kept-in-the-command-buffer)
|
||||
- distant walls and floors smeared sideways (DARK SOULS: REMASTERED): tiling textures took a clamp-to-edge sampler and repeated their edge column. → [Handles from uniform buffers take the bound pools' bases](../reference/shaders.md#handles-from-uniform-buffers-take-the-bound-pools-bases)
|
||||
@@ -1050,6 +1069,8 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- bindless handles read from a uniform buffer name the wrong texture when the game writes them earlier in the same submission. → [Handles in uniform buffers written earlier in the same submission](../reference/shaders.md#handles-in-uniform-buffers-written-earlier-in-the-same-submission)
|
||||
- a storage buffer reported with `cb_slot` 3, which had no NVN slot. → [Storage buffer addresses in the game's own uniform buffer](../reference/shaders.md#storage-buffer-addresses-in-the-games-own-uniform-buffer)
|
||||
- whatever a shader writes through a pointer it read from memory never happens. The build summary counted `Failed to find storage buffer for global memory operation "Store"`, and the shader's MSL had a store function with an empty body. In Donkey Kong Bananza the tunnel's walls and floor were black and only the loose rocks drew. → [Global memory at an address loaded from memory](../reference/shaders.md#global-memory-at-an-address-loaded-from-memory)
|
||||
- GPU-driven geometry never draws: its indirect draw records keep count 0 and its visibility buffer stays clear, although the culling compute runs every frame. A persistent culling kernel takes its work items (its work counter passes the item count) and writes nothing. Its build notes do not say `traced to no storage buffer`: the loads are traced, to a storage buffer the address is in on only some paths. In PRAGMATA the title's Earth and Moon and the intro's ship and cockpit were black. → [Global memory at a storage buffer's address on some paths only](../reference/shaders.md#global-memory-at-a-storage-buffers-address-on-some-paths-only)
|
||||
- an NVN2 shader that reads a constant buffer through a bindless handle (`cx[UR][offset]`) gets a dummy buffer or zeros, with `[RED] shader <key>: the buffer address the game pushed at c[24] + 0x… is 0x1800830776a28, in no memory pool: bound to a dummy buffer` (an "address" of 49 bits, with a small number in its top bits). → [Bindless constant buffer handles in the hardware's layout](../reference/shaders.md#bindless-constant-buffer-handles-in-the-hardwares-layout)
|
||||
- a pass whose shaders read memory through loaded addresses takes several milliseconds on the GPU for little work. `[gpuprof]` names the pass, and its shaders' build notes say `Global memory operation "Load" traced to no storage buffer`. Ocarina of Time's foliage mesh shader `73dc0b90c4082e43` (`Foliage.Product.110`, 135 such reads) took 10.9 ms of a 683x384 frame; 2,241 of the game's shaders (vertex, compute, fragment and mesh) have such a lookup, some hundreds of them. → [Raw global memory lookups that start from their last entry](../reference/shaders.md#raw-global-memory-lookups-that-start-from-their-last-entry)
|
||||
- a pass of mesh, vertex or compute shaders whose build notes say `Global memory operation "Load" traced to no storage buffer` takes milliseconds of its stage's time for little drawing, at any resolution. Metal System Trace's Shader Timeline shows no samples for task and mesh shaders, so such a pass looks idle there; the encoder's vertex-stage time and an overlay A/B tell. Ocarina of Time's foliage mesh pass took 4.6 ms of vertex-stage time a frame at 683x384, 0.2 ms of fragment. → [128-bit raw global loads read one word at a time](../reference/shaders.md#128-bit-raw-global-loads-read-one-word-at-a-time)
|
||||
- a 64- or 128-bit load through an address in no pool (a null or stale pointer, a gap between pools) reads 0 in its first word and whatever the invocation's `gmem_vec` held in the others: the words of the previous vector load, or undefined data on the first. Before the change in 128-bit raw global loads read one word at a time, every word of such a load read 0. A shader that tests a loaded record's first word for 0 is unaffected; one that uses the other words (a bounding box, a count, a second pointer) gets garbage. → [A 64- or 128-bit raw global load in no pool reads undefined upper words](../reference/shaders.md#a-64--or-128-bit-raw-global-load-in-no-pool-reads-undefined-upper-words)
|
||||
@@ -1059,6 +1080,9 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- the shaders' bindless arrays have no slot and used not to load; the translator falls back to a 32-entry array such as `array<texture_buffer<float>, 32> vp_tb_cb0_40000000`. → [Texture slots picked at run time](../reference/shaders.md#texture-slots-picked-at-run-time)
|
||||
- Ryujinx's fallback arrays (`fp_t2d_cb0_40000000`) in pixel shaders whose handle comes from the game's own uniform buffers; the shaders do not load and their draws are skipped. → [A texture chosen at run time between two uniform-buffer handles](../reference/shaders.md#a-texture-chosen-at-run-time-between-two-uniform-buffer-handles)
|
||||
- `[RED] shader … reflection conversion failed: a texture handle the translator could not trace to one slot (profile key tex_dyn_slots off)`, then `failed to load`, and the draws are skipped: in Mario Party Superstars every character and NPC in a lit scene is a flat grey silhouette (the depth pre-pass draws, the colour pass does not), and the opening scene's pipe is grey. → [Texture handles from game memory index the pools](../reference/shaders.md#texture-handles-from-game-memory-index-the-pools)
|
||||
- `[RED] <key>: the translator deleted N bindless accesses (<type> N): their results read 0` for thousands of shaders, and `lost without failing: …` in the build; textures read as black (PRAGMATA: 65,241 reads in 8,630 shaders, its intro a saturated cyan). → [Handles a shader computes index the pools](../reference/shaders.md#handles-a-shader-computes-index-the-pools)
|
||||
- `reflection conversion failed: B binding … has no resolved slot number` at load, then `the dispatched program has no compute shader` each time the game dispatches it; the build log has `Bindless handle taken from the one constant buffer handle among its phi inputs` for the shader. → [A handle loaded from memory on one path only](../reference/shaders.md#a-handle-loaded-from-memory-on-one-path-only)
|
||||
- `[metal failed]` in the build, the compiler's message `vector component access exceeds type 'float2'` on a line that samples a `texture2d_array` with a two-component coordinate and `uint(rint(coord.z))` as its layer; the shader and its alpha test entry points do not build. → [One handle read as a texture and as an array](../reference/shaders.md#one-handle-read-as-a-texture-and-as-an-array)
|
||||
- the host stops at the shader's first load: `unexpected argument buffer layout: encodedLength=640 maxAid=48`. → [An array of handles in a uniform buffer](../reference/shaders.md#an-array-of-handles-in-a-uniform-buffer)
|
||||
- characters and other moving objects have almost no ambient light: lit only from where the sun reaches, black underneath, while the scenery around them is right. Nothing is red. On Kirby Air Riders a dark red Kirby on a bright course, where the game's own tutorial movie shows him bright pink. → [A table of handles longer than the array](../reference/shaders.md#a-table-of-handles-longer-than-the-array)
|
||||
- a pass that samples through a table of a uniform buffer's handles takes hundreds of milliseconds on the GPU; nothing is red and the picture is right. In Fire Emblem Fortune's Weave on an M1 Pro, the lighting pass at Alcineus Bridge took 196.7 ms and the scene ran at 4 fps. → [Reads of a handle table marked through a null address](../reference/shaders.md#reads-of-a-handle-table-marked-through-a-null-address)
|
||||
@@ -1074,6 +1098,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- `image atomics: unsupported or overflowing IMG extent` at the first dispatch, despite a valid four-byte counter buffer. → [Buffer image reflection keeps its texture type](../reference/shaders.md#buffer-image-reflection-keeps-its-texture-type)
|
||||
- `[RED] image atomics on a texture Metal cannot run them on`, and whatever the shader computes through them is lost: its writes go to a sink. → [Image atomics on a 32-bit colour texture](../reference/shaders.md#image-atomics-on-a-32-bit-colour-texture)
|
||||
- Metal shader validation reports invalid image-atomic stores even with an image-sized scratch buffer; without validation, GPU page faults can freeze rendering. → [Bounds of image atomics](../reference/shaders.md#bounds-of-image-atomics)
|
||||
- `NotSupportedException: Ampere 59f at …: SURED form 0110e400` in the shader build, then the scene's 3D picture black behind a UI that draws: `[RED] shader … (compute) failed to load` and `[RED] the dispatched program has no compute shader`. A texture dump shows the visibility target (RG32Uint) all zero. → [64-bit image max and min (SURED.MAX.U64)](../reference/shaders.md#64-bit-image-max-and-min-suredmaxu64)
|
||||
- the GPU hangs (Metal command-buffer timeouts, `GPU access revoked`, exit 70; on the Mac WindowServer can lose its watchdog check-in and the session restarts) or a draw reads garbage, where a shader reads a uniform slot further than the game bound it. No `[RED]` line. → [Reads past a uniform binding's size](../reference/shaders.md#reads-past-a-uniform-bindings-size)
|
||||
- on an M1 Pro (macOS 26), blue, green and white blocks for one or two frames on trees that dither-fade (OCTOPATH TRAVELER's S'warkii, walking behind a tree); a texture dump shows NaN pixels in the scene colour and holes in the normal G-buffer target, which depth of field spreads into blocks. Not seen on an iPhone or on newer Macs. On every GPU, a branch for each uniform word a shader reads. → [Bounded uniform reads written as select](../reference/shaders.md#bounded-uniform-reads-written-as-select)
|
||||
- the NSP script stops with `captured only 0 run-time shaders` although the game reaches its frame loop with precompiled shaders. → [A GLSL language preamble is not a complete shader](../reference/shaders.md#a-glsl-language-preamble-is-not-a-complete-shader)
|
||||
|
||||
@@ -21,6 +21,7 @@ DM_CHEATS_ON switch Comma-separated cheat names turned on at launch, besides the
|
||||
DM_CHEATS_WINDOW switch `1` opens the Mac Cheats panel beside the game from the start
|
||||
DM_COPY_GAME_RESOURCES switch `NO` skips the Xcode build phase that copies the game's resources into the app (`stage_resources.sh`, on by default); `build_ipa.sh` sets it for its unsigned build, which packs them itself
|
||||
DM_COPY_ROMFS switch `NO` keeps the game files out of the app, in the Xcode build phase (`stage_resources.sh`) and in the unsigned IPA of `build_ipa.sh` (on by default): `main.m` takes the validated `Documents/romfs.img` copied by `scripts/push_romfs.sh`, then a `Documents/romfs` folder; the build writes the image's identity as `romfs.id` into the app, and `main.m` uses only a matching image (`--romfs separate` of the NSP script sets this)
|
||||
DM_CRASH_PEEK diagnostic `="sp+0x248*,x22-0x20"` adds 0x100 bytes at each address to the crash report: `sp` or a register plus or minus an offset, a trailing `*` reading the pointer stored there first
|
||||
DM_CTL diagnostic `=<file>` (Mac): the host polls the file every 100 ms and runs each appended line: button presses, `shot`, `passdump`, `texdump`, `env KEY=VALUE`, `peek`, `memdump`, `drag` and more
|
||||
DM_CTRL_PROMPT_TEXT switch The texts of the controller applet's prompt (a game wants more players than have joined; `ctrl_prompt.h`) in the player's language, one per line: the title, the hint, the count, the done and the cancel button, with `{min}`, `{max}` and `{joined}` replaced by the numbers; a front end sets it ([Starting a game](frontends.md#starting-a-game)), an empty or missing line keeps the English text
|
||||
DM_DBG diagnostic When set, prints the guest's `svcOutputDebugString` text to stderr as `[guest]` lines
|
||||
@@ -141,6 +142,7 @@ DM_NVN_DEPTHOVR diagnostic `=<fragment shader key prefix>,…`: those draws comp
|
||||
DM_NVN_DIRECT_UPLOAD switch 0 disables bounded direct RGBA16F array uploads and keeps staged copies; on by default for supported non-sparse textures.
|
||||
DM_NVN_DIRTYCHECK diagnostic `=1` fully hashes pool content on every use to find changes the dirty-page tracking missed
|
||||
DM_NVN_DISPATCH_OWN switch `=1` gives every compute dispatch a compute encoder of its own with full barriers, as before (by default dispatches share the copy encoder); `DM_NVN_PASSGPU` does the same
|
||||
DM_NVN_DLSS_BILINEAR diagnostic `=1` draws every DLSS evaluation with the bilinear stand-in, to tell MetalFX's part in a GPU fault or stall
|
||||
DM_NVN_DUAL_WANT path `=<file>`: appends the key of each pixel shader a pipeline blends with its output 1 as the second source, while it has no dual-source entry point, to that file, once per key (the profile's `dual_want.tsv`)
|
||||
DM_NVN_ENC_LABEL diagnostic `=1` labels every render encoder `p<pass in frame> <width>x<height> <first 8 digits of the first draw's fragment key> d<draws>` for Instruments traces
|
||||
DM_NVN_ENC_THREAD player `1` runs the replay's Metal encoding on a thread of its own while the submit thread goes on translating; on by default on iOS (`0` turns it off), off on macOS
|
||||
@@ -185,6 +187,7 @@ DM_NVN_POOL_FIRST diagnostic `1` logs every first read through the pool table of
|
||||
DM_NVN_POOL_STANDIN switch `0` leaves the dummy (reads 0) in the pool tables for a texture the walk does not make, as before; by default, once the walk's budget is full, such a texture holds a stand-in until a shader reads its ID: its own smallest levels, or its last level cut down to every n-th block, so the first read draws the texture's colours coarse for one frame instead of black (Ocarina of Time's cliff beside the castle town wall dark for one frame when the game streams a sharper texture into it, issue #1969)
|
||||
DM_NVN_PREDICT switch `0` turns off the parallel precompile look-ahead: a pipeline miss compiles only the pipeline it needs
|
||||
DM_NVN_PREFETCH switch `0` turns off loading a program's shader libraries in the background when the game makes it (`nvnProgramSetShaders`); they load at its first draw instead
|
||||
DM_NVN_PRESENT_FINISH diagnostic `=1` makes each present return once the GPU has run the frame, so the game never runs ahead of the GPU
|
||||
DM_NVN_PROF diagnostic `=1` wraps the implemented NVN functions in a timing wrapper and collects the time each takes during recording
|
||||
DM_NVN_PROGTRACE diagnostic `=<vertex keys,...>` logs matching ProgramSetShaders calls and their guest backtraces
|
||||
DM_NVN_REGLUM diagnostic `=x0,y0,x1,y1:<file>` (normalized coordinates): on every present records the present number, time, mean luminance and a grayscale thumbnail of that region, to check animation speed against frame rate
|
||||
@@ -232,6 +235,7 @@ DM_NVN_UPLOAD_REUSE switch 0 keeps the original one-block upload-slot policy; de
|
||||
DM_NVN_VBUF_CACHE switch `0` turns off the cache of resolved vertex stream addresses and vertex argument table writes across draws (on by default), for A/B runs
|
||||
DM_NVN_VCONV_CHECK diagnostic `=1` scans the indices again at every reuse of a cached vertex conversion range (`vconv_range`) and reports differences
|
||||
DM_NVN_VCONV_CPU switch `=1` converts integer vertex inputs fed formats of another class on the CPU, as before, instead of through the shader's shadow inputs (`<key>_bv`)
|
||||
DM_NVN_VCONV_KEEP switch `=0` turns off the kept vertex conversions (`vk_get`); `=<n>` sets the smallest range kept, in vertices (default 4096)
|
||||
DM_NVN_VCONV_RANGE switch `0` / `1` overrides the profile's `vconv_range`: CPU vertex conversion only over the vertices each draw reads instead of the whole bound range
|
||||
DM_NVN_VLOG diagnostic Set: logs each NVN memory pool as it is created (address, memory, size, flags) with a backtrace
|
||||
DM_NVN_VSDUMP path Output file for post-vertex captures; used with DM_NVN_VSDUMP_KEY and the frame/count bounds
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 19 and column 104.
|
@@ -300,6 +300,13 @@ A decoder hands out as many outputs as it has slots, and while every slot is tak
|
||||
- **Found on:** [Donkey Kong Bananza](../../dm/games/040074A01BF12000/README.md): 101 guide movies (`Movie/*.webm`, VP9 960×540, no sound); its player reads the pictures as NV12 (`ReadDecoderOutputImageNv12`, output format 3).
|
||||
- **Open:** AV1 (no decoder on the host: Initialize fails with a red line, so a client takes its error path instead of reaching the service), encrypted input, native image handles (the GPU route of decoded pictures), alias pools and the readback of part of a picture are not served (each prints a red line once). No game here plays VP8 or H.264 through this API yet: those paths are checked by the test only. Donkey Kong Bananza's player imports all four decoders; its movies are VP9.
|
||||
|
||||
### H.264 parameter sets past the eighth argument
|
||||
|
||||
- **Symptom:** every movie stays black; `[RED] nn::codec H.264: VideoToolbox could not decode a packet`, the packets starting with an SEI NAL unit, not a parameter set.
|
||||
- **Cause:** H.264's two `Initialize…Decoder` overloads end with the stream's parameter sets (SPS / PPS: a pointer and a size), the only place the game gives them. The host's shared entry points (`CV_FAMILY`) took the overloads without them, so VideoToolbox had no format. They are the ninth and tenth arguments of the longer overload: past the eight registers the guest's AAPCS64 gives each stack argument an 8-byte slot, where Apple's arm64 packs a 32-bit one into 4, so the argument before them had to be declared 64 bits wide.
|
||||
- **Fix:** both overloads take the parameter sets for every decoder type and pass them on for H.264 only; the red line prints a refused packet's first bytes, which show how its NAL units are framed.
|
||||
- **Found on:** [PRAGMATA](../../dm/games/0400C76024710000/README.md) (SDK 20.5.15): its opening movies.
|
||||
|
||||
### The submission-ready event counted as packets
|
||||
|
||||
- **Symptom:** a movie stays black with the game waiting behind it, the decoder made and no `first picture` line (`Submit…InputBuffer` never called). Or `[RED] nn::codec VP9: Corrupt frame detected`, then `Keyframe / intra-only frame required`, each time about 6 s into a movie or after skipping in one.
|
||||
|
||||
@@ -83,6 +83,27 @@ A game may tell NVN objects apart by their bytes, without an NVN call. A host re
|
||||
- **Fix:** such a pool gets an address range of its own at `MemoryPoolInitialize` (reserved, inaccessible: 64 GB on the Mac, at most 1 GB on iOS), and each mapping request `vm_remap`s the physical pages over its part of the range, so virtual addresses read and write the same memory, as the GPU's page table does. Each run of mapped pages is registered with the replay like a pool of its own and rebuilt when a request joins or splits runs (`vpool_*` in `hle_nvn.c`). Mario's 128 MB pool, mapped whole onto one physical pool, keeps the alias. The log reports the mapped high-water mark per 128 MB.
|
||||
- **Found on:** [Monster Hunter Rise](../../dm/games/0100B04011742000/README.md).
|
||||
|
||||
### More than 1,024 mapped runs in a sparse pool
|
||||
|
||||
- **Symptom:** `[RED] virtual pool …: more than 1024 separate mapped runs`, then a GPU hang minutes later: `[RED] the host has waited 10 s for GPU work`, an indirect dispatch of absurd size (`283343572 x 965150577 x 1006648320 groups`), and the game aborts once its 15 s `nvnSyncWait` expires.
|
||||
- **Cause:** the run list of [a sparse pool](#sparse-virtual-pools-built-from-separate-physical-pools) was a fixed array of 1,024. Past it, a new run was neither listed nor registered with the replay, so the GPU did not reach it, and runs that no longer fit fell off the list while their zero-copy buffers stayed: after a later remap such a buffer still wired the old pages, and the GPU read what had been there (the dispatch's group counts were float data).
|
||||
- **Fix:** the list grows (`vrun_set` in `hle_nvn.c`); a change touches only the runs it overlaps, so a new list has at most two more runs than the old. The log reports the count at each power of two from 1,024.
|
||||
- **Found on:** [PRAGMATA](../../dm/games/0400C76024710000/README.md): its GPU heap passes 1,024 runs while the title screen loads; the hang came 3 to 4 minutes into the intro.
|
||||
|
||||
### Pages changed under a buffer the GPU still uses
|
||||
|
||||
- **Symptom:** in a game that maps and unmaps sparse pages while it runs: an indirect dispatch of absurd size, a GPU hang, then a crash in the game's own code reading a command list that holds another object's data.
|
||||
- **Cause:** a run of [a sparse pool](#sparse-virtual-pools-built-from-separate-physical-pools) is a zero-copy `MTLBuffer` over the pages `vm_remap` put in its range, and such a buffer keeps the pages it was made over, not the address. An unmap or a new mapping changed the pages at once, while the run's old buffer was still in submitted command buffers and the residency set. The GPU then read or wrote the old physical pages, which the game may already have mapped elsewhere.
|
||||
- **Fix:** no page under a live buffer changes (`hle_nvn.c`). An unmap clears the page table at once (textures read 0) but keeps the host pages until the fence after the last commit has completed (`vunmap_defer`, `vunmap_run`); then it makes the whole host pages no newer request has mapped inaccessible. A mapping over pages mapped before waits for the GPU first (`vpool_overwrites`, `mtl_finish`), and finalizing a pool with runs waits too. The log counts the waits once at each power of two (`[nvn] sparse pools: … waited for the GPU first`). Ported from uncraftablexd's sparse safe mode ([PR #1407](https://github.com/seedds/nxnative/pull/1407)), without its loop caps and skip lists.
|
||||
- **Found on:** [PRAGMATA](../../dm/games/0400C76024710000/README.md).
|
||||
|
||||
### A sparse pool's runs replaced in two steps
|
||||
|
||||
- **Symptom:** `[RED] shader <key>: the buffer address the game pushed at c[24] + … is …, in no memory pool: bound to a dummy buffer`, once or twice in minutes, for an address inside a mapped run of a sparse pool; the draw or dispatch of that frame reads zeros.
|
||||
- **Cause:** each run of [a sparse pool](#sparse-virtual-pools-built-from-separate-physical-pools) is a pool of its own for the replay. A mapping that joins a run to its neighbours, or an unmap that splits one, removed the old runs (`mtl_pool_del`) and then added the new ones (`mtl_pool_add`) on the game's thread, while the replay looks addresses up on its own thread: between the two, an address mapped all along was in no pool.
|
||||
- **Fix:** `vrun_set` (`hle_nvn.c`) hands the runs it removes and the runs it adds to `mtl_pool_replace` (`nvn_mtl.m`), which makes the new runs' buffers first and then takes the old ones out and puts the new ones in under one hold of `g_mu`, so every lookup sees the old runs or the new.
|
||||
- **Found on:** [PRAGMATA](../../dm/games/0400C76024710000/README.md): its mesh shaders `765e6d9d2588ce70` and `5aab38bb5ba67ef7` read a buffer 0x3000000 into a sparse pool whose one run keeps growing; the miss came at frames 2971 and 4484, the frames the run was replaced in; none in a run with the fix.
|
||||
|
||||
### Virtual pools of one texture each, mapped before and after the texture
|
||||
|
||||
- **Symptom:** `[RED] MapVirtual: non-contiguous mapping (true sparse) not implemented`, on small virtual pools; streamed textures black or missing (OCTOPATH TRAVELER's village ground and plants).
|
||||
@@ -261,6 +282,13 @@ A game may tell NVN objects apart by their bytes, without an NVN call. A host re
|
||||
- **Fix:** `cmd_t` records the last `AddControlMemory` block; `GetControlMemorySize` returns its size, `GetControlMemoryUsed` the bytes of control entries the host wrote into it ([A recording's end and links are in control memory](#a-recordings-end-and-links-are-in-control-memory); 0 until then, when the host used none), and `GetControlMemoryFree` the rest. `t_nvn` checks the values before any block, after one, after a recording and after a smaller block replaces it.
|
||||
- **Found on:** South Park: The Fractured But Whole 1.05, whose port is [PR #662](https://github.com/seedds/nxnative/pull/662) (not yet in the games table). With the getters implemented it reached the title, menu, a save and character customization on the Mac; with them returning 0 it also progressed, but submitted commands at a different rate.
|
||||
|
||||
### Queue builder size getters
|
||||
|
||||
- **Symptom:** `[RED] NVN unimplemented function called: nvnQueueBuilderGetCommandMemorySize` (or `…GetComputeMemorySize`, `…GetControlMemorySize`, `…GetRayTracingMemorySize`, `nvnQueueBuilderSetRayTracingMemorySize`), once each, as the game makes its queue.
|
||||
- **Cause:** the calls were not implemented. The driver's getters write the size to `*size` and return whether it was set (`ldr w8, [x0, #0x2c]; str w8, [x1]; ldrb w0, [x0, #0x24]`); the stub returns 0 and writes nothing, so a game that copies the sizes into its own queue description keeps what its fields held.
|
||||
- **Fix:** the queue builder keeps each size with a set flag (`qb_set`, `qb_get` in `hle_nvn.c`); the getters answer from them, and `GetQueueMemorySize` takes the device defaults for the sizes not set, as before. The ray tracing size is kept and reported only: the host traces no rays.
|
||||
- **Found on:** [PRAGMATA](../../dm/games/0400C76024710000/README.md), which reads all four after `SetDefaults` and its setters.
|
||||
|
||||
### Host-lent command memory segments
|
||||
|
||||
- **Symptom:** `FATAL NVN command memory: the game's pool is empty…`.
|
||||
@@ -382,6 +410,13 @@ Games read this count as a position in their own command memory and size their h
|
||||
- **Check:** GPU load from outside: `ioreg -r -d 1 -c IOAccelerator | grep 'Device Utilization'` at 100 % means a shader is looping forever. Find the shaders first used in the last frames (`DM_NVN_PASSDUMP`, compare the `K` keys) and look at their `.metal` for an empty `do {} while (true);` with no `return` (one such case: [Exact program start for the decoder](shaders.md#exact-program-start-for-the-decoder)).
|
||||
- **Found on:** no game named in the source (general).
|
||||
|
||||
### A sync never fenced since its Initialize is signalled
|
||||
|
||||
- **Symptom:** `game called nn::diag abort` right after a screen change (PRAGMATA: the Initial Settings menu's Next), with nothing slow before it.
|
||||
- **Cause:** the game initializes its two frame syncs again and then waits 15 s on the one it has not fenced yet, aborting on `TIMEOUT_EXPIRED` or `FAILED` (`main+0x4a8cf0`) once two frames are in flight. It is a shipped path, so on the console that wait does not expire. The host answered a never-fenced sync with a timeout, a rule from its first version with no game behind it.
|
||||
- **Fix:** `nvnSyncWait` answers `ALREADY_SIGNALED` for a sync never fenced since its `Initialize`: no GPU work stands behind it. A wait that does expire after a second or more is a red line naming the sync's state (`sync_expired`), since that is what a game's GPU watchdog acts on.
|
||||
- **Found on:** [PRAGMATA](../../dm/games/0400C76024710000/README.md).
|
||||
|
||||
### The game's SyncWait wakes on the GPU's own signal of its fence
|
||||
|
||||
- **Symptom:** the frame's blocking SyncWait on its newest fence wakes about 0.26–0.29 ms after the GPU end (M2 Max; the wait ledger, `DM_NVN_WAITS=1`), on the critical path of every frame.
|
||||
|
||||
@@ -861,6 +861,13 @@ The replay on Metal (`dm/gfx/nvn/nvn_mtl.m`) and the Vulkan and OpenGL layers. E
|
||||
- **Fix:** the builder's mode now goes to the texture (`tex_t.stencil`), whose sampling view is the `X32_Stencil8` one a stencil-mode texture view already got.
|
||||
- **Found on:** [DRAGON QUEST VII Reimagined](../../dm/games/0100A9D01C446000/README.md) (the character occlusion mask, `edbfc7a088be545e`).
|
||||
|
||||
### The provoking vertex is the first
|
||||
|
||||
- **Symptom:** `[RED] NVN unimplemented function called: nvnCommandBufferSetProvokingVertexMode`, once.
|
||||
- **Cause:** the call was not implemented. NVN2's driver writes its mode into the 3D class's `SET_PROVOKING_VERTEX` (method 0x1684), 0 for the first vertex of a primitive and 1 for the last.
|
||||
- **Fix:** mode 0 needs nothing: Metal's flat values come from the first vertex. Mode 1 has no Metal setting and is reported once (`[RED] nvnCommandBufferSetProvokingVertexMode 1 (the last vertex)`); open until a game sets it.
|
||||
- **Found on:** [PRAGMATA](../../dm/games/0400C76024710000/README.md), which sets mode 0.
|
||||
|
||||
### Conservative rasterization remains unimplemented
|
||||
|
||||
- **Symptom:** `[nvn] SetConservativeRasterEnable on: ignored by host for now`, followed by `[RED] NVN unimplemented function called: nvnCommandBufferSetConservativeRasterDilate`.
|
||||
|
||||
@@ -536,6 +536,7 @@ Most service calls can be found before they crash, before the first boot or the
|
||||
- **Fix:** the host now recognizes gestures from the same touch points, by yuzu's rules plus an 8 px slop before a touch counts as moving (`hle_touch.c` `gesture_sample`, unit test `t_gesture`; only in handheld mode, as touches): Touch, Press after 0.5 s, Pan, Pinch / Rotate with two fingers, Cancel on a change in the finger count, then Tap (IsDoubleTap within 0.35 s), Swipe above 400 px/s or Complete, and Idle. For every game.
|
||||
- **Check:** every menu, the cards, the map's drag and flick worked by touch with it. `DM_TOUCH_LOG=1` logs each gesture entry, and a `DM_CTL` line `drag <x0> <y0> <x1> <y1> [seconds]` moves a finger for testing pans and swipes on the Mac.
|
||||
- **Found on:** [Taiko Risshiden V DX](../../dm/games/0100346017304000/README.md) (SDK 12.3.3, Koei Tecmo's KTGL).
|
||||
- **Two-argument `InitializeGesture`:** SDK 20.5.15 has an overload `nn::hid::InitializeGesture(int, int)`, whose SDK body opens the hid service and aborts in `sm::Initialize` (Result 0xe15) on the host; it is taken over as the other one is ([PRAGMATA](../../dm/games/0400C76024710000/README.md)).
|
||||
|
||||
### Touch sampling numbers across docked and handheld
|
||||
|
||||
|
||||
+166
-9
@@ -247,8 +247,11 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
|
||||
### SDF definitions in RE Engine PAKs
|
||||
|
||||
- **How it is stored:** shader definitions (`SDF\0`, 2,685 files in the PAK view, [01](../agents/01-extract.md)): u16 version 1, u16 entry count, u64, then 0x108-byte entries from +0x10. Entry +0x10 holds six u64 offsets (vertex, hull, domain, geometry, pixel, compute; 0 = none), each to `{u32 control length, u32 code length}` followed by the control section (0x880 bytes) and the code area; compute code has no header. An entry's stages are one program, so its vertex / pixel stages are a pair. Empty definitions are 16 bytes of version 0.
|
||||
- **Reader:** `kpka_jobs` maps the PAKs, takes the newest copy of each path, peeks at 4 decompressed bytes and inflates only SDF entries (`sdf_shaders`).
|
||||
- **Found on:** [Monster Hunter Rise](../../dm/games/0100B04011742000/README.md): 63,111 shaders (30,233 vertex, 21,475 pixel, 11,271 compute, 53 geometry, 33 hull, 46 domain) and 102,345 pairs, in 5 s with 12 jobs.
|
||||
- **PRAGMATA's form (KPKA 4.2, Switch 2):** the PAK header's feature bit 0x20 adds a block table after the entries (u32 block length 0x80000, u32 count, a u64 per block: offset in bits 0–41, stored length from bit 42; a block whose stored length is the block length is stored, any other is one zstd frame of a padded block). An entry with attribute 0x1000000 starts at a block index, not an offset, and its data runs on through the following blocks. The SDF files hold two u64s, then 0x110-byte entries from +0x18 (entry +0: the offset of its name); each stage record is a 0x58-byte header (a u64 hash, the two lengths at +8), then the NVN2 control section and the code area. Mesh shaders sit in the hull slot (1,407 of them).
|
||||
- **OCIO files:** RE Engine's OpenColorIO colour pipelines (`OCIO`) hold the shaders of the frame's tonemap and display transform as the same stage records, among tables of their own. The control sections there have other hashes at +0x10 and +0x20 than the SDF copies of the same code, so their keys are different shaders. Without them, PRAGMATA's last composite before the window had no shaders and its draw was skipped: the picture came out cyan-saturated, every subtitle drawn over the ones before. The larger OCIO files (3.9 MB, `8ae6c7ee83bc0563` and three more) pack their records to 4 bytes, not 8: a reader that took only 8-byte aligned control sections read 2 of their 65, and left out the compute shaders that bake the colour pipeline's tables (`2ceb3ec288321a37`, dispatched every frame: `[RED] the dispatched program has no compute shader`).
|
||||
- **Reader:** `kpka_jobs` maps the PAKs, takes the newest copy of each path, peeks at 4 decompressed bytes and inflates only SDF and OCIO entries (`kpka_data` joins block-table entries; `sdf_shaders` takes either SDF layout, whichever the file's offsets fit; `ocio_shaders` takes each NVN2 control section whose record header names its length and whose +0x44 names the code area after it).
|
||||
- **Found on:** [Monster Hunter Rise](../../dm/games/0100B04011742000/README.md): 63,111 shaders (30,233 vertex, 21,475 pixel, 11,271 compute, 53 geometry, 33 hull, 46 domain) and 102,345 pairs, in 5 s with 12 jobs. [PRAGMATA](../../dm/games/0400C76024710000/README.md): 759 SDF files, 36,465 shaders, and OCIO files.
|
||||
- **Check:** `python3 dm/gfx/tests/test_kpka.py`.
|
||||
|
||||
### Shader records in Snowdrop SDF data slices
|
||||
|
||||
@@ -847,6 +850,8 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
|
||||
- **Fix:** `dmsh_entry.py` `int_outputs` follows each output write back through the locals: a computed integer or a small constant counts as integer, the bits of a computed float as float, and zero, the bits of a float constant and words copied from a uniform or an input say nothing. A choice (`c ? a : b`) is what its two values are, and a denormal float literal is a small integer printed through the output's type. `main0_m` returns the outputs with integers and no float bits; when none is that clean, those with integers; when none has any, every output written through integer bits, as before. The pipeline path now prints the red line above when a shader has integer entry points and none fits.
|
||||
- **Found on:** [Kirby Star Allies](../../dm/games/01007E3006DDA000/README.md): 687 pixel shaders got the right mask, 0b100.
|
||||
- **Note:** this only chooses among the entry points. A shader whose integer output cannot be told apart still has no entry point for its pipeline, which the red line names.
|
||||
- **A float local that holds a register's bits:** `[RED] task / mesh pipeline failed: … output of type float4 is not compatible with a MTLPixelFormatRG32Uint color attachment` for [PRAGMATA](../../dm/games/0400C76024710000/README.md)'s visibility pass, whose pixel shaders write `float _439 = as_type<float>(int(gl_PrimitiveID))` and the depth to an RG32Uint target. A write of a local counted as float bits whenever the local was declared `float`, so no shader got `main0_u`. A float local whose every value is `as_type<float>(…)` is now what that value is, and a written local is followed like any other value. Check: `python3 dm/tools/tests/test_shader_rewrites.py IntegerOutputs`. An element of a local array (`_30[0]`, a register the translator kept in one) is followed as a local too: read as an expression it counted as a computed integer, and 11 of OCTOPATH TRAVELER II's pixel shaders got colour 2, a float output, as their integer one (`regress.py check`, before this landed).
|
||||
- **Writes after an early return:** with that fix, the same red line stayed on four of those shaders (`a9c1f9ea0c76a54c`, `1282ed0df15021c7`, `a88532b3a2bbc36f`, `bfce48e3c0debea2`), and the visibility target stayed empty. With it went the whole 3D scene: the title's Earth and Moon and the intro's cockpit were black behind the UI. `fs_uint` read `main0` only up to its first `return out;`. These shaders return zeros early, after a discard, and write the primitive id and depth after that. `fs_uint` now reads `main0`'s whole body (`dmsh_side.entry`). Check: `test_writes_after_an_early_return`.
|
||||
|
||||
### Integer textures and images through float declarations keep their bits
|
||||
|
||||
@@ -876,9 +881,10 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
|
||||
|
||||
- **Symptom:** `SPIRV-Cross threw an exception: Subgroup builtins are not available in this type of function`.
|
||||
- **Cause:** Metal has no SIMD-group functions in vertex functions, and SPIRV-Cross's own subgroup emulation covers only `Elect`. RE Engine scalarizes uniform loads: ballot the active lanes, shuffle the first lane's value to all and take a fast path when all agree.
|
||||
- **Fix:** with a one-lane subgroup that is exact, so `dmsh_build.py` rewrites the vertex shaders' SPIR-V that way before SPIRV-Cross (`spv_single_lane`: the ballot is the lane's own bit, shuffles and broadcasts return its own value, all / any are the predicate, all-equal and elect are true, lane ID 0, size 1). A mask component read through `OpAccessChain` / `OpInBoundsAccessChain` becomes an extraction from the constant mask, preserving the index.
|
||||
- **Fix:** with a one-lane subgroup that is exact, so `dmsh_build.py` rewrites the vertex and domain shaders' SPIR-V that way before SPIRV-Cross (`spv_single_lane`: the ballot is the lane's own bit, shuffles and broadcasts return its own value, all / any are the predicate, all-equal and elect are true, lane ID 0, size 1). A mask component read through `OpAccessChain` / `OpInBoundsAccessChain` becomes an extraction from the constant mask, preserving the index.
|
||||
- **Found on:** [Monster Hunter Rise](../../dm/games/0100B04011742000/README.md) (about 4 % of its vertex shaders); [Xenoblade Chronicles 3](../../dm/games/010074F013262000/README.md) (vertex `4b98320a0f512efe`, a prefix ballot that reads `SubgroupLtMask` through a component pointer).
|
||||
- **Note:** the rewrite covers vertex shaders only: two of Bayonetta 3's domain shaders still fail this way ([Tessellation stages are not drawn](#tessellation-stages-are-not-drawn)).
|
||||
- **Types the module lacks:** the rewrite's constants need `bool` and a `uint` 4-vector; a module without one (a shader that reads only the lane ID) was left as it was, and now gets the type declared with the constants.
|
||||
- **Note:** domain shaders take the rewrite too: SPIRV-Cross writes them as post-tessellation vertex functions, with the same limit (PRAGMATA's `859225c91a5fe2b2` and `f1ad8f78c6c1551e` did not build; two of Bayonetta 3's failed this way, not rebuilt since). The host draws no tessellated patches yet ([Tessellation stages are not drawn](#tessellation-stages-are-not-drawn)).
|
||||
|
||||
### Geometry shaders that only pick the layer
|
||||
|
||||
@@ -1136,6 +1142,37 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
|
||||
- **Found on:** [Ocarina of Time](../../dm/games/0400486024DEC000/README.md#found-on-this-game): the layout and the point size checked against the guest's address arithmetic in the translated shaders; the paintings not seen in the game since. Pull request #1590 found the layout and the point size.
|
||||
- **Check:** `python3 dm/gfx/tests/test_dmsh_meshstage.py`.
|
||||
|
||||
### Mesh shader per-primitive system values: the primitive count overwritten, the primitive id lost
|
||||
|
||||
- **Symptom:** a mesh-shaded draw shows nothing, though its workgroups run: every workgroup ends with a primitive count of 0. Once that is mended, a visibility buffer written from `[[primitive_id]]` holds only the index within the meshlet, and each pixel is shaded from the wrong cluster.
|
||||
- **Cause:** a mesh shader's per-primitive SPH can enable system-value outputs besides generic attributes: OMAP byte 0x34 and byte 0x35 bits 0..3, attribute 0x40 + 4 × bit (0x35 bit 0 is the primitive id; bit 1 the layer, bit 2 the viewport). `dmsh_meshstage.info` dropped them, so `memory` left them no room, and the primitive count and index bytes began where the guest keeps the per-primitive blocks: its store of primitive 0's id landed on the count byte. The wrapper also gave Metal no per-primitive id, so the fragment stage's `[[primitive_id]]` was Metal's own index, not the value NVN's `gl_PrimitiveID` reads (here `(cluster << 7) | primitive`).
|
||||
- **Fix:** `info` lists the per-primitive system values (`primitive_system`, `primitive_builtins`); a primitive block holds them first, then the generic attributes, and the primitive bytes follow every block. The primitive id goes to Metal as the mesh primitive's `[[primitive_id]]` (`PRIMITIVE_BUILTINS`), which the fragment stage then reads; the same fragment function in a vertex pipeline still reads Metal's index. The layer and the viewport get room but no Metal output: no mesh shader is known to write them. Ported from uncraftablexd's PRAGMATA bring-up ([PR #1802](https://github.com/seedds/nxnative/pull/1802)); its other part, a storage buffer table at `c0` + 0x210 for mesh shaders in the hull slot, is not taken, since `c[26]` there is the mesh stage's buffer bank, its push block 2 ([NVN2 graphics stages' buffer banks](#nvn2-graphics-stages-buffer-banks-c25-to-c29-are-push-blocks)).
|
||||
- **Found on:** [PRAGMATA](../../dm/games/0400C76024710000/README.md): 494 of its 539 mesh shaders enable the primitive id, among them the title's lunar terrain (`5aab38bb5ba67ef7`, `28ef097c07ceb429`) and the visibility pass (`765e6d9d2588ce70`, `bc8b4e0fcbb79159`).
|
||||
- **Check:** `python3 dm/gfx/tests/test_dmsh_meshstage.py`.
|
||||
|
||||
### Mesh shaders that also address their vertices as records
|
||||
|
||||
- **Symptom:** thin streaks or stray triangles from a mesh shader over parts of the picture its geometry does not cover (PRAGMATA: white vertical streaks over the cockpit window in the opening).
|
||||
- **Cause:** besides the SoA blocks (`ISBEWR.O.ATTR.SKEW.32`, mode 0xf8), a mesh shader may write its vertices as records (`ISBEWR.O.ATTR.32`, mode 0xb8): vertex `v`'s `n` components at `aos + 4n * v + 4c`, `aos` being the end of its SoA area, with the same values as their SoA words. The translator took mode 0xb8 as a word at the outputs' base, so the records ran over the primitive count and the index bytes.
|
||||
- **Fix:** `dmsh_meshstage.memory` passes `stage_memory[4..6]` (the records' start, `n`, their size); in a mesh shader `AStageOut` and `AIsberd` (`InstEmitAmpereMem.cs` `AosToSoa`) send a mode 0xb8 address inside the records to the SoA word of the same vertex and component, so both writes coincide. `v = w / n` is a reciprocal multiply where that is exact for every word of the records (`AosVertex` checks it), a division otherwise. Ported from [PR #1802](https://github.com/seedds/nxnative/pull/1802).
|
||||
- **Found on:** [PRAGMATA](../../dm/games/0400C76024710000/README.md): `6adf14e9a4100082`, `4fcffc73d65dc1ed`, `c0e44513c35d209a`.
|
||||
- **Check:** `DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py` (`test_vertex_records_go_to_their_soa_word`).
|
||||
|
||||
### Mesh shaders that read their own outputs back
|
||||
|
||||
- **Symptom:** `NotSupportedException: Ampere 923 …: ISBERD mode f8 in a task or mesh shader` in the shader build; those mesh shaders are left out and their draws skipped (`[RED] DrawMeshTasks without its task and mesh shaders`).
|
||||
- **Cause:** ISBERD's mode bits as nvdisasm names them: 0x80 .O (the output area), 0x40 .SKEW, 0x30 .ATTR, 0x08 .32. Modes 0xf8 and 0xb8 read back a word the shader's own ISBEWR of the same mode wrote; the translator took only 0xb8, as a task's payload.
|
||||
- **Fix:** `AIsberd` reads both from the stage memory's outputs, 0xb8 through the vertex records (previous entry). From uncraftablexd's PRAGMATA bring-up ([PR #1407](https://github.com/seedds/nxnative/pull/1407)).
|
||||
- **Found on:** [PRAGMATA](../../dm/games/0400C76024710000/README.md): `5aab38bb5ba67ef7` and `28ef097c07ceb429`, the title's lunar terrain, read back each triangle's positions to swap two indices of a mirrored instance's triangles.
|
||||
|
||||
### Threadgroup stores in warp-synchronous code
|
||||
|
||||
- **Symptom:** a small scan or sort in a compute shader gives wrong results every frame, with no barrier in its loop (Orbitals: Niagara's sorted particle indices).
|
||||
- **Cause:** Ampere compilers rely on lockstep warps and leave the barrier out of small scans: a thread stores its word to shared memory, then loads its neighbour's. For one thread the load and its own earlier store do not alias, so Metal may move the load above the store and read the neighbour's old value.
|
||||
- **Fix:** `tg_fence` in `dmsh_build.py` puts a simdgroup-scope memory fence (`atomic_thread_fence(mem_flags::mem_threadgroup, …, thread_scope_simdgroup)`, not an execution barrier, so safe in divergent code) after each store to a threadgroup array, plain, compound or to a member. A kernel whose arrays spill to device memory gets the device scope too (`tg_spill`). Ported from uncraftablexd's Orbitals bring-up ([PR #1775](https://github.com/seedds/nxnative/pull/1775)).
|
||||
- **Found on:** Orbitals (no profile here), by PR #1775; taken for [PRAGMATA](../../dm/games/0400C76024710000/README.md)'s GPU-driven passes.
|
||||
- **Check:** `python3 dm/gfx/tests/test_dmsh_tg_fence.py`.
|
||||
|
||||
### Tessellation stages are not drawn
|
||||
|
||||
- **Symptom:** `primitive type 14 not implemented`; patch draws skipped.
|
||||
@@ -1209,6 +1246,14 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
|
||||
- **Found on:** no game; encodings from the CuAssembler sm_86 corpus, nvdisasm-guided fuzzing and variants.
|
||||
- **Check:** `DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_alu.py` (`CarriesAndModifiers`).
|
||||
|
||||
### FSETP / ISETP pairs on their own accumulator, and IMAD's B
|
||||
|
||||
- **Symptom:** a predicate pair that disagrees with itself (`FSETP.LT.AND P0, P1, R2, R3, P0`: P1 combined with the new P0, not the old); a multiply-add off by `2 * a * b` (IMAD read as `a * -b + c`).
|
||||
- **Cause:** FSETP and ISETP wrote their first predicate before computing the second, which reads the accumulator again, as PLOP3 did ([previous entry](#ampere-carries-plop3s-second-result-popc--flo-immediates-leasx32-and-leas-negated-b)). The decoder read bit 63 (bit 75 in the register-B forms) of IMAD, IMAD.WIDE and IMAD.HI as B's negation; IMAD has none there (nvdisasm prints no `-` on B for either bit), only C's negation.
|
||||
- **Fix:** `ASetPredPair` computes both results before writing either (FSETP, ISETP); `AImadSrcs` gives B without modifiers to the three IMAD forms (`InstEmitAmpereAlu.cs`). Ported from uncraftablexd's PRAGMATA bring-up ([PR #1800](https://github.com/seedds/nxnative/pull/1800)).
|
||||
- **Found on:** [PRAGMATA](../../dm/games/0400C76024710000/README.md), from PR #1800; no picture or hang here has been traced to either alone.
|
||||
- **Check:** `DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_alu.py` (`SingleInstructionSemantics`: the four fail on the translator before).
|
||||
|
||||
### Ampere jump tables read past their end
|
||||
|
||||
- **Symptom:** `BRX with no target`, or code about 20 % larger than it should be.
|
||||
@@ -1298,6 +1343,30 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
|
||||
- **Check:** `DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_alu.py` (`SharedAtomics`: the three fail on `main`). A GPU cross-check of 400 LDS / STS / ATOMS from an nvdisasm-validated sm_86 corpus, run as one-thread compute shaders with the production options (debug and reduced on, MSL 2.3), against a reference: 84 mismatches (all INC, DEC and CAS) to none; the same on encodings from real compiled code.
|
||||
- **Found on:** cross-checking the translator against nvdisasm and a reference interpreter; no game run. Also seen with `debug: false` (the AST optimizer, off by default): a shared store of 8 or 16 bits makes the translator throw, and an ATOMS whose result goes to RZ is dropped.
|
||||
|
||||
### FRND of a half (FRND.F16)
|
||||
|
||||
- **Symptom:** `[translation failed] NotSupportedException: Ampere 307 at …: FRND of a float that is not 32-bit`.
|
||||
- **Cause:** the emitter took 32-bit floats only. `FRND.F16` rounds a half to an integer value: both sizes are 1 (bits 84..86 and 75..77), the rounding at 78..80 as for a float.
|
||||
- **Fix:** a chain change (`AFrnd` in the vendored `InstEmitAmpereAlu.cs`). The half bits 60..62 select (as F2F's) is unpacked, rounded in 32 bits and packed into the low 16 bits. The pack is exact: every half from 2^10 up is an integer already, and an integer below 2^11 has at most 11 significant bits. That the half is selected as F2F's is taken from F2F, not from a disassembly of a high-half case (all of PRAGMATA's read the low half). A source and result of different sizes still fail.
|
||||
- **Found on:** [PRAGMATA](../../dm/games/0400C76024710000/README.md): 65 shaders (47 compute, 11 vertex, 7 pixel), nearest and floor.
|
||||
- **Check:** `DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_alu.py -k Frnd`.
|
||||
|
||||
### Ampere forms met on PRAGMATA: TLD through a uniform register, I2F of an immediate, SUATOM.CAS
|
||||
|
||||
- **Symptom:** `[translation failed] NotSupportedException: Ampere instruction f66 … is not implemented`, `Ampere instruction 595 … is not implemented`, or `Ampere 906 …: I2F byte select of a 32-bit source`.
|
||||
- **Cause:** three forms the emitters did not take. 0xf66 is TLD with its handle in a uniform register (40..46), the fetch beside 0xf60 (TEX), 0xf63 (TLD4), 0xf69 (TMML) and 0xf6c (TXD): its other fields are 0xb66's. That reading is the family's pattern (0xf60 + 3n beside 0xb60 + 3n), not a disassembly. 0x595 is SUATOM's compare-and-swap through a bound handle: Mesa's NAK encodes the bindless ones as 0x394 (atomic) and 0x396 (compare-and-swap, its data the pair compare value, new value), and 0x593 is 0x394 with the handle bound. I2F in its immediate form (0x906) has the value in 32..63, so 60..62 select no byte there; an immediate of -2 read as select 7.
|
||||
- **Fix:** a chain change (vendored `InstEmitAmpereMem.cs`: `ATex` takes 0xf66, `ASuatomCas`; `InstEmitAmpereAlu.cs`: `AI2f` reads no select from an immediate).
|
||||
- **Found on:** [PRAGMATA](../../dm/games/0400C76024710000/README.md): 17 shaders with 0xf66 (11 vertex, 6 pixel), compute shader `50fece0d891feba4` with 0x595, 3 compute shaders with the I2F. All build; none has been watched drawing.
|
||||
- **Open:** `Ampere 326 …: IPA at an offset` (PRAGMATA's pixel shader `4a9d4507eea6c837`): an attribute interpolated at an offset from the pixel centre needs `interpolateAtOffset` through the SPIR-V generator, which is not written.
|
||||
- **Check:** `DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_alu.py -k I2fImmediate`; the other two forms are checked by PRAGMATA's build only.
|
||||
|
||||
### The shared compare-and-swap loop retries with the value it got
|
||||
|
||||
- **Symptom:** a shared-memory atomic built from a compare-and-swap loop (INC, DEC, the 64-bit and float operations) spins longer than it should or stores a value computed from stale data when other threads write the word.
|
||||
- **Cause:** the loop `GenerateSharedAtomicCasLoop` (`HelperFunctionManager.cs`) writes reloaded the word at the head of every iteration instead of taking the value the failed exchange returned, which is the word's current value. The reload is a plain load between atomics, with no ordering against them.
|
||||
- **Fix:** the old value is loaded once before the loop; each iteration computes from it, and a failed exchange's result becomes the next iteration's old value. Ported from uncraftablexd's PRAGMATA bring-up ([PR #1796](https://github.com/seedds/nxnative/pull/1796)).
|
||||
- **Found on:** [PRAGMATA](../../dm/games/0400C76024710000/README.md), from PR #1796; not traced to a symptom here.
|
||||
|
||||
### Half-pair swizzle on a constant, and .F32
|
||||
|
||||
- **Symptom:** wrong values in the high lane of half-pair math that scales by one half of a uniform (`HMUL2 R37, R37.H0_H0, c[0x0] [0x168].H0_H0`), or a garbage operand where a half-pair operation reads a 32-bit float (`R20.F32`).
|
||||
@@ -1341,7 +1410,8 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
|
||||
|
||||
- **Symptom:** `Ampere instruction f63` (or `f6c`, `364`, `367`) `is not implemented`, or `SURED form 0310e000`, in the build.
|
||||
- **Cause:** 0xf60 and 0x361 were known for TEX. The same pairs exist for the others: 0xf63 and 0xf6c are TLD4 and TXD through a uniform register at 40..46, 0x364 and 0x367 are TLD4 and TLD through a register, the first of the second source block, each otherwise laid out as its bound form. 0x364's meaning was inferred from these siblings, and its use agrees: Yoshi's single-layer water converts each of its four results as a device Z (`c4[66]`), which only a gather of a depth texture gives. SURED takes SUATOM's operation field (87..91): MAX, OR and MIN on 32 bits turn up.
|
||||
- **Fix:** `ATex` maps them to the bound forms, `ASured` takes the operation. TMML has the same pair, 0xf69 and 0x36a (Kirby Air Riders' cube map LOD, 4,776 pixel shaders), with a binding of its own only when the handle is bound by its slot. Open: SURED.MAX.U64 (33,550 uses, Nanite's visibility buffer) is still refused, as the host has no 64-bit image atomics; the game does not reach those shaders so far.
|
||||
- **Fix:** `ATex` maps them to the bound forms, `ASured` takes the operation. TMML has the same pair, 0xf69 and 0x36a (Kirby Air Riders' cube map LOD, 4,776 pixel shaders), with a binding of its own only when the handle is bound by its slot. SURED.MAX.U64 (33,550 uses, Nanite's visibility buffer) is now [a 64-bit texture atomic](#64-bit-image-max-and-min-suredmaxu64) on Apple GPU family 9; this game has not been rebuilt with it.
|
||||
- **TXQ:** 0xf6f is TXQ (0xb6f) through a uniform register at 40..46, Ra the LOD (`ATxq`; [PRAGMATA](../../dm/games/0400C76024710000/README.md): 12 shaders); the size query reads the pools like any handle no slot holds. Check: `GuardedWrites.test_size_query_through_a_uniform_register_translates`.
|
||||
- **Found on:** [Kirby Air Riders](../../dm/games/040077201BE50000/README.md) (TMML); [Yoshi and the Mysterious Book](../../dm/games/0400245021D2C000/README.md). Its shaders' jump tables also ran past their code on two compute shaders (`ArgumentOutOfRangeException`, in `GetCode`): an address past the code is now no code, which ends the table as the decoder expected.
|
||||
|
||||
### Ampere BMSK and the read of a covered pixel
|
||||
@@ -1350,6 +1420,7 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
|
||||
- **Cause:** 0x21b, beside SGXT's 0x21a, is BMSK: a mask of b bits from bit a. Star Fox's `58046f286de779e1` takes it from two bytes of a word, ANDs it with the value shifted by the same a and hands the result to an atomic, a bit field written into a word. 0x925 has no name in the tables at hand (the part of CuAssembler's sm_80 table read so far; Mesa's NAK encoder could not be fetched); what it reads comes from its two shaders, quad efficiency views. They rebuild its value at the quad's three other pixels through SHFL and FSWZADD and add the four: one indexes a 4-entry palette with the sum minus 1, so a shaded pixel's sum is at least 1, and the other draws 0.03125 + 0.15625 sum in red. So it is 1 for a covered pixel and 0 for a helper invocation.
|
||||
- **Fix:** `ABmsk` follows PTX's `bmsk` definition, its `.W` at bit 75 as SGXT's (only the clamping form has been seen). `APixelCovered` loads a new `IoVariable.HelperInvocation`, Metal's `simd_is_helper_thread()`, as an integer; any other form of 0x925 stays refused (chain change). `test_dmsh_ampere_mem.py` covers both.
|
||||
- **Found on:** [Star Fox](../../dm/games/0400E88025B1A000/README.md): 1 compute and 2 pixel shaders, none asked for in play so far, so neither instruction has run. Neither opcode is in the shaders of Donkey Kong Bananza, Splatoon Raiders, Mario Tennis Fever or Pokopia.
|
||||
- **Form 3, the sample index:** `[RED] … 0x925 form 3 outside a covered pixel's read` for 154 of [PRAGMATA](../../dm/games/0400C76024710000/README.md)'s pixel shaders, at their first instruction. The register indexes the driver's sample position table (`LDC c[0][R + 0x620]`, a byte of x and y nibbles), which is what GLSLC's Maxwell code does with PIXLD.MY_INDEX (numbered 5 there), so form 3 is the index of the sample the fragment runs for: `IoVariable.SampleId`, Metal's `[[sample_id]]`. Check: `PixelCovered.test_form_3_reads_the_sample_index`.
|
||||
|
||||
### VOTEU writes the uniform predicate
|
||||
|
||||
@@ -1397,7 +1468,7 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
|
||||
|
||||
- **Symptom:** `Ampere instruction 80d ... (000fc80003fe0000c43211110000780d) is not implemented` for every vertex shader of the game, so nothing draws.
|
||||
- **Cause:** the compiler ends the position's computation with a test of its own. FSETP sets P0..P5 where x, y or z lies beyond +/- w times the system registers 30 and 31, which nothing else reads: a guard band. Two 0x80d follow, immediate 0xc4321111 with no predicate result, then immediate 0x80000000 with a result, and that predicate guards an EXIT before the shader writes its position and outputs. All 6,319 vertex shaders hold this once; no other game's do. What the instruction reads is not known: it is inferred from what surrounds it, and no other instruction reads its result.
|
||||
- **Fix:** `AGuardCull` in `InstEmitAmpereAlu.cs`: the result is false, so no vertex leaves early. Every vertex writes its outputs and clipping does the rest, as for a shader without this; only the optimization is lost. Any other form of 0x80d stops the shader.
|
||||
- **Fix:** `AGuardCull` in `InstEmitAmpereAlu.cs`: the result is false, so no vertex leaves early. Every vertex writes its outputs and clipping does the rest, as for a shader without this; only the optimization is lost. A form with no predicate result at all (PT, as the first of the two) writes nothing and is skipped in any stage ([PRAGMATA](../../dm/games/0400C76024710000/README.md)'s mesh and pixel shaders hold it). Any other form of 0x80d stops the shader.
|
||||
- **Found on:** [Kirby Air Riders](../../dm/games/040077201BE50000/README.md).
|
||||
- **Open:** the instruction's real meaning. A vertex output at `a[0x5c]`, written by 4,771 vertex shaders (`Attribute offset 0x5C is not valid`), is dropped; it has no known meaning either.
|
||||
- **Check:** `DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py`.
|
||||
@@ -1431,6 +1502,14 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
|
||||
- **Found on:** PRAGMATA (no profile; 156 of its compute shaders return before a barrier) and Orbitals ([PR #1783](https://github.com/seedds/nxnative/pull/1783)), as PR #1774 reports; neither game's files were run here. Not [Ocarina of Time](../../dm/games/0400486024DEC000/README.md)'s GPU hang: none of its 520 task and mesh shaders has a barrier in its body. Only 12 of its compute kernels return before a barrier, none of them in the pass that hangs.
|
||||
- **Check:** `make -C dm/gfx/tests GAME=<id> t_barrier_exit && dm/gfx/tests/t_barrier_exit`.
|
||||
|
||||
### MEMBAR is a fence, not a barrier
|
||||
|
||||
- **Symptom:** a GPU hang (`kIOGPUCommandBufferCallbackErrorHang`, `[RED] the host has waited 10 s for GPU work`) in a compute shader whose threads poll a flag in a loop with no BAR.SYNC: a persistent work queue.
|
||||
- **Cause:** MEMBAR (and the ERRBAR after it) orders memory and does not wait for other threads. The translator emits it as SPIR-V's `OpMemoryBarrier`, which SPIRV-Cross writes as `threadgroup_barrier(mem_flags::mem_device | mem_flags::mem_threadgroup | mem_flags::mem_texture)`: an execution barrier every thread of the threadgroup must reach. A thread that leaves the polling loop early never reaches it again, and the threads still in the loop wait for it for ever.
|
||||
- **Fix:** `membar_fence` in `dmsh_build.py` rewrites that exact line to `atomic_thread_fence(…, memory_order_seq_cst, thread_scope_device)`, and two of them in a row (MEMBAR.SC then ERRBAR) to one. BAR.SYNC's `threadgroup_barrier(mem_flags::mem_threadgroup)` stays a barrier. Ported from uncraftablexd's PRAGMATA bring-up ([PR #1407](https://github.com/seedds/nxnative/pull/1407)).
|
||||
- **Found on:** [PRAGMATA](../../dm/games/0400C76024710000/README.md): its culling queue `12a52b683eec95c1` polls a done flag with `MEMBAR.SC.GPU; ERRBAR` at the end of the loop body.
|
||||
- **Check:** `python3 dm/gfx/tests/test_dmsh_membar_fence.py` (with `DMSH_TEST_METAL=1` the rewritten shader also compiles with Metal).
|
||||
|
||||
### Barrier moves around warp shuffles
|
||||
|
||||
- **Symptom:** `Ampere instruction f55 at 0x… (000fe20000000000000000001a0f7f55) is not implemented` in the shader build; those shaders are left out.
|
||||
@@ -1477,6 +1556,33 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
|
||||
- **Fix:** `dmsh_build.py` passes the two counts (job `nvn2_cs`) and `AMapC0` maps them to NVN's fixed tables, separate texture r to `c[2]` 0x168 + 8 r and separate sampler r to 0x568 + 8 r (chain change). A shader with neither maps as before. `test_dmsh_ampere_mem.py` covers the image past both.
|
||||
- **Found on:** [Star Fox](../../dm/games/0400E88025B1A000/README.md): one compute shader, dispatched in the prologue. Any NVN2 compute shader with separate handles reads them this way.
|
||||
|
||||
### NVN2 compute's second push block holds buffer entries
|
||||
|
||||
- **Symptom:** the GPU never finishes the first 3D frame: `[RED] the host has waited 10 s for GPU work`, with persistent compute shaders (a loop on a work counter, `threadgroup_barrier` inside) among the failed command buffer's shaders.
|
||||
- **Cause:** `nvnCommandBufferPushComputeConstants(cmd, block, offset, size, data)` writes block 0 or block 1. NVN2 compute's `c[0]` lays out, after its 0x10-byte header, push block 0 (control +0xa9 words, rounded to 16 bytes), then push block 1 (+0xaa words), then the uniform entries (+0xb1), the storage entries and the handle tables of [the entry above](#nvn2-computes-separate-handles-in-c0) (the SDK's accessor at `sdk+0x5e6f20` reads byte +0xa9 + block). PRAGMATA pushes 16-byte `{address, size}` entries, 1 to 3 of them, into block 1 before its dispatches, and its shaders read buffers through those addresses (`ubo_ptr`-style global loads). The host kept one block, so block 1 overwrote block 0, and the translator placed block 1 after the uniform entries: the persistent shaders spun on a counter in the wrong buffer.
|
||||
- **Fix:** the host keeps `DMSH_PUSH_BLOCKS` (2) blocks, block b at `b * DMSH_PUSH_SIZE` of `c[24]` (`push_const` in `hle_nvn.c`; a block past them is a red line). The translator maps `c[0]` reads in push block 1's range to `c[24] + 0x100` (`AMapC0`, `nvn2_cs` field 7 from +0xaa), and `GlobalToStorage` takes `c[24]` as an address bank like `c[0]`. A storage buffer whose address the game pushed binds through the bytes the replay holds (`sbuf_push`, `NVN_RB_SBUFQ`). Chain change.
|
||||
- **Found on:** [PRAGMATA](../../dm/games/0400C76024710000/README.md): with it, the hang at frame ~1,300 is gone.
|
||||
- **Check:** `DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_nvn2_buffers.py`.
|
||||
|
||||
### NVN2 graphics stages' buffer banks (c[25] to c[29]) are push blocks
|
||||
|
||||
- **Symptom:** `Ampere … bank 25` (to 29) refused, or `stage N cbN has no uniform buffer bound` for graphics shaders that read buffers through an address. Then, with those banks taken for the uniform slots: `[RED] graphics push constants into block 5 (0 + 0x10): the host keeps 2, dropped`, `sbufp reg3 dummy` (to reg5) for a mesh shader in the pass dump, and everything a visibility buffer draws comes out black while the rest of the frame is lit.
|
||||
- **Cause:** NVN2 graphics stage i (vertex 0, hull or mesh 1, domain 2, geometry 3, pixel 4) reads buffer entries from a bank of its own, `c[25 + i]`: 16-byte `{address, size}` entries, or 8-byte handles. They are not the uniform slots the game binds. They are what the game pushes with `nvnCommandBufferPushGraphicsConstants` into push block 1 + i, as compute reads its own entries from push block 1 (block 0 holds the constants). The translator mapped the banks onto the uniform slots, and the host kept two push blocks and dropped the rest. PRAGMATA pushes its mesh stage's six entries into block 2 and its pixel stage's five into block 5 before its visibility and material passes. Its mesh shader `5aab38bb5ba67ef7` binds uniform slots 0 to 2 only and read its rows 3 to 5 (the visible-cluster tables) from unbound slots, so the primitive IDs it writes into the visibility buffer were garbage. The material depth pass `93590d7bd6125d1c` took its cluster table from uniform slot 3, a 16-byte buffer, and every raw load it made missed. No material strip passed its depth test, and the G-buffer stayed black.
|
||||
- **Fix:** a chain change, general to NVN2.
|
||||
- **Translator:** `InstEmitAmpere.cs` `AStageBlock` maps the stage's bank to its block of `c[24]`, at `(1 + i) * 0x100` (`AMapC0`, `AIndexedBank`). The addresses read there become `sbuf_push` bindings, which the host reads from its push blocks (`NVN_RB_SBUFQ`, handles decoded).
|
||||
- **ABI:** `DMSH_PUSH_BLOCKS` is 6.
|
||||
- **Host:** `push_const` keeps graphics blocks 0 to 5, and compute's 0 and 1.
|
||||
- **Removed:** the per-stage fill of `c[0] + 0x210` for graphics stages; only compute reads that table.
|
||||
- **Check:** `Nvn2Buffers.test_a_graphics_stage_bank_is_its_push_block` fails on the old translator.
|
||||
- **Found on:** [PRAGMATA](../../dm/games/0400C76024710000/README.md): `c[25]` in 9,944 vertex shaders, `c[26]` in 538 mesh and 3 hull shaders, `c[27]` in 37 domain shaders, `c[28]` in 1 geometry shader, `c[29]` in 12,195 pixel shaders. In one intro frame it pushes block 1 157 times, block 2 51 times and block 5 92 times. A host-only test (each stage's rows filled from its block) brought back the ship's engines and the tower's lights at the moon base.
|
||||
|
||||
### Uniform words read through a buffer address (cx)
|
||||
|
||||
- **Symptom:** `Ampere … is not implemented` for ALU forms, ULDC (0xab9) or LDC (0x582) with bit 91 set.
|
||||
- **Cause:** bit 91 makes a constant operand bindless: `cx[UR][offset]` reads a word of the buffer whose 64-bit GPU address is in the uniform register pair UR, UR + 1 (ALU forms: UR at bits 32–37, offset at 38–54; ULDC: UR at 24–29; 0x582 LDC adds Rb at 64–71). The address is a plain GPU address, not a handle: decoding it as one read through wrong pools and page-faulted the GPU.
|
||||
- **Fix:** `ABindlessConstant` reads it as a global load at UR + offset, through the memory pool table the shader walks for raw global memory (`gmem_map`) (`AUldc`, `ALdcBindless`, `AGet`). Chain change.
|
||||
- **Found on:** [PRAGMATA](../../dm/games/0400C76024710000/README.md): RE Engine's materials read their constants this way; its 0x36d (TXD with the handle leading the first block) and the plain form of [0x80d](#a-guard-band-cull-in-every-vertex-shader-0x80d) came up in the same shaders.
|
||||
|
||||
### A handle pair ORed sampler word first
|
||||
|
||||
- **Symptom:** `reflection conversion failed: B binding fp_t_cb2_170 has no resolved slot number` at load (the draw is skipped), the build summary counting the binding under *slot was not decoded*; or, once the read's other inputs are known, `Failed to find handle source for bindless access of type "texture2D"` and the read answers 0. `DMSH_BINDLESS_TRACE=1` on a `dmsh_xlate` job prints what a refused handle is made of.
|
||||
@@ -1594,10 +1700,10 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
|
||||
|
||||
### Pixel `c0 + 0x620`: the sample index and GLSLC's sample position table
|
||||
|
||||
- **Symptom:** `[RED] shader … reflection conversion failed: reads driver-bank locations at run time that the replay layer cannot fill: c0 dynamic index c0+0x630`, and that shader's draws are missing; the build notes `Shader instruction Pixld is not implemented` for pixel shaders; `[RED] NVN unimplemented function called: nvnProgramSetSampleShading`.
|
||||
- **Symptom:** `[RED] shader … reflection conversion failed: reads driver-bank locations at run time that the replay layer cannot fill: c0 dynamic index c0+0x630` (or `c0 dynamic index` alone), and that shader's draws are missing (`[RED] shader … (pixel) failed to load`); the build notes `Shader instruction Pixld is not implemented` for pixel shaders; `[RED] NVN unimplemented function called: nvnProgramSetSampleShading`.
|
||||
- **Cause:** GLSLC reads the sample index with `PIXLD.MYINDEX` (RZ, offset 0; nouveau reads `gl_SampleID` the same way), which Ryujinx's translator left unwritten, so the register read as 0. For `gl_SamplePosition` (or interpolation at a sample) it then indexes a byte table the NVN driver keeps at `c0 + 0x620`: index = ((((y & w) << z) + (x & z)) << log2 samples) + (sample & mask), with {mask, log2 samples, z, w} at `c0 + 0x630` and x, y the pixel (`gl_FragCoord` over the render scale); each byte holds the sample's x (low nibble) and y in 1/16 pixel. The replay filled neither row, and the build refused any computed index into `c0`.
|
||||
- **Fix:** the translator writes the sample index for `PIXLD.MYINDEX` (`IoVariable.SampleId`, SPIR-V `SampleId` with `SampleRateShading`; MSL `[[sample_id]]`, so the fragment function runs per sample on a multisampled target, and SPIRV-Cross moves `gl_FragCoord` to the sample); the other modes still log. `encode_args` fills both rows for the pixel stage from the pass's sample count (`c0_sample_rows`: Metal's default positions, the same for every pixel, so the grid masks are 0; one sample is 0x88, the pixel centre), and `dmsh_build.py` counts them as filled for pixel shaders (`SAMPLE_ROWS`), with a computed `c0` index accepted when the shader reads the 0x630 row. `nvnProgramSetSampleShading` returns true: Metal has no switch to force per-sample shading, which a shader gets by reading the sample index.
|
||||
- **Found on:** [Metroid Prime Remastered](../../dm/games/010012101468C000/README.md): 438 of the 562 pixel shaders of `MaterialArchive.arc` read the sample index; in 30 the translated shader keeps it, and there it reaches the table, whose byte the G-buffer shaders pack into an integer target (`04023899305e93e1`). Its targets are single-sample (1600×900), so sample 0 was right and only the table mattered: 0 there put every sample in the pixel's corner. No other game here reads either row (58 games' libraries checked). The nibble order for several samples is the hardware's, not seen in a game.
|
||||
- **Fix:** the translator writes the sample index for `PIXLD.MYINDEX` (`IoVariable.SampleId`, SPIR-V `SampleId` with `SampleRateShading`; MSL `[[sample_id]]`, so the fragment function runs per sample on a multisampled target, and SPIRV-Cross moves `gl_FragCoord` to the sample); the other modes still log. `encode_args` fills both rows for the pixel stage from the pass's sample count (`c0_sample_rows`: Metal's default positions, the same for every pixel, so the grid masks are 0; one sample is 0x88, the pixel centre), and `dmsh_build.py` counts them as filled for pixel shaders (`SAMPLE_ROWS`), with a computed `c0` index accepted when the shader reads the 0x630 row, or when its range is proven (`index_range`: an integer expression of literals and the sample index, below 16, through single-assignment temporaries) to lie in the filled rows. `nvnProgramSetSampleShading` returns true: Metal has no switch to force per-sample shading, which a shader gets by reading the sample index.
|
||||
- **Found on:** [Metroid Prime Remastered](../../dm/games/010012101468C000/README.md): 438 of the 562 pixel shaders of `MaterialArchive.arc` read the sample index; in 30 the translated shader keeps it, and there it reaches the table, whose byte the G-buffer shaders pack into an integer target (`04023899305e93e1`). Its targets are single-sample (1600×900), so sample 0 was right and only the table mattered: 0 there put every sample in the pixel's corner. No other game here reads either row (58 games' libraries checked). The nibble order for several samples is the hardware's, not seen in a game. [PRAGMATA](../../dm/games/0400C76024710000/README.md): 156 pixel shaders read the byte at `0x620 + sample` without the grid and without the 0x630 row (`a689530d00090ebf`: `_m0[(sample + 1568) >> 4]`, row 98), and were refused (`c0 dynamic index`) until the build bounded the index; all 156 load, the other 6,753 of its shaders that read `c0` or `c2` keep their result. Check: `DriverReads.test_sample_byte_by_the_sample_index_is_filled_in_a_pixel_shader`.
|
||||
|
||||
### Texture and sampler pools with overlapping IDs
|
||||
|
||||
@@ -1660,6 +1766,25 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
|
||||
- **Open:** the prediction is checked, not proven: a miss that does reach a shadow is reported (`[RED]`) after the frame, not prevented. The records' pointers come from memory, so the pools they will reach are not known ahead of the draw.
|
||||
- **Found on:** [Donkey Kong Bananza](../../dm/games/040074A01BF12000/README.md): its terrain, and agl's compute shader `49bc2268925e25b6` (one load); rebuilding the chain changed only these two of Donkey Kong Bananza's shaders. Vertex shader `588e242a52f5f7aa` (five stores) has one too, the same shader in [The Legend of Zelda: Tears of the Kingdom](../../dm/games/0100F2C0115B6000/README.md) and [Super Mario Bros. Wonder](../../dm/games/010015100B514000/README.md), so likely one the SDK ships; neither drew it in its regression route.
|
||||
|
||||
### Global memory at a storage buffer's address on some paths only
|
||||
|
||||
- **Symptom:** GPU-driven geometry never draws: its indirect draw records keep count 0 and its visibility buffer stays clear, although the culling compute runs every frame. A persistent culling kernel takes its work items (its work counter passes the item count) and writes nothing. Its build notes do not say `traced to no storage buffer`: the loads are traced, to a storage buffer the address is in on only some paths. In PRAGMATA the title's Earth and Moon and the intro's ship and cockpit were black.
|
||||
- **Cause:** for an address that is a phi, `GlobalToStorage.TryGenerateMultiTargetStorageOp` collects the storage buffers its sources trace to and makes a helper that range-checks each one. A source it cannot trace (an address the shader loaded from memory) was skipped without a word, and the helper returned 0 when the address was in none of the buffers. That case is exactly the untraced source. PRAGMATA's cluster culling `251426e9d44fd558` reads each instance's mesh header at an offset of its push+0x170 buffer on one path and at an address from its table at push+0x110 on the other, in other pools. Every header read gave 0, every instance 0 clusters, so the chain after it (`3c5dde027a045df7`, `1b16be7a9ee2c490`, which fills the mesh draws' records) had nothing to count. Found with counters added to the kernel's MSL (a copy laid over the library from a folder beside its image): 59,000 items reached the header test, 0 reached the header read, 0 reached either output store.
|
||||
- **Fix:** general, in the chain (`GlobalToStorage.cs`). A source that is neither traced nor another phi marks the access. Its helper keeps the range checks, and on a miss calls the pool table helper (`TryGenerateRawStorageOp`, [Global memory at an address loaded from memory](#global-memory-at-an-address-loaded-from-memory)) instead of returning 0. A tag after the buffers keeps it apart from a helper whose sources are all traced. An access the table cannot serve (an atomic on an 8- or 16-bit value) keeps the 0. The build notes say `traced to a storage buffer on some paths only`.
|
||||
- **Found on:** PRAGMATA (`0400C76024710000`): the title's 3D and the intro's mesh-shader geometry.
|
||||
|
||||
### Bindless constant buffer handles in the hardware's layout
|
||||
|
||||
- **Symptom:** an NVN2 shader that reads a constant buffer through a bindless handle (`cx[UR][offset]`) gets a dummy buffer or zeros, with `[RED] shader <key>: the buffer address the game pushed at c[24] + 0x… is 0x1800830776a28, in no memory pool: bound to a dummy buffer` (an "address" of 49 bits, with a small number in its top bits).
|
||||
- **Cause:** the handle is not an address. Its layout is the hardware's (as NVK's `nvk_bindless_cbuf`): bits 0..44 hold the address >> 4 and bits 45..63 the size >> 4. The translator (`InstEmitAmpere.cs` `ABindlessConstant`) used the handle as the address, and that worked only for the handles the host writes itself (compute's uniform entries in c[0]), because the host wrote plain addresses there. A game that builds its own handles reached no pool. PRAGMATA pushes them: its SDF compute shader `b12078fe3bce1273` takes three at push block 1, `0x5a0083055d124` = 32 bytes at `0x83055d1240`, the other two 192 bytes each. Its pixel shaders also load such handles with `LDG.64` from the game's own buffers. An earlier attempt to decode the handle in the shader alone met the host's plain addresses: wild reads, a GPU timeout and page faults at the first 3D frame.
|
||||
- **Fix:** general, in the chain and the host.
|
||||
- **Translator:** `ABindlessConstant` decodes the handle: the address is `(handle & (2^45 - 1)) << 4`.
|
||||
- **Storage pass** (`GlobalToStorage.cs` `TryUnwrapHandle`): traces that address (handle << 4) back to the handle's constant buffer words as it traces an address, and marks the target (`SearchResult.Handle`, bit 15 of a packed target). A multi-target helper compares the decoded address and size.
|
||||
- **Host** (`nvn_mtl.m`): writes NVN2's uniform entries in the hardware's layout (`ucb_handle`; NVN1 shaders read the plain address there, Link's Awakening's `c0[0x280]`). The readers of a pushed or a uniform-buffer word (`NVN_RB_SBUFQ`, `NVN_RB_SBUFU`) decode a handle (`ucb_handle_addr`): a handle of any size has a bit at 45 or above, which no guest address has, so a word with a plain address is read as before.
|
||||
- **Traces unchanged:** a 312-shader sample of PRAGMATA's library (every stage, with uniform, pushed and raw bindings) built with the same bindings and raw-access notes as before.
|
||||
- **Open:** a read past the handle's size returns what lies there; the hardware returns 0.
|
||||
- **Found on:** PRAGMATA (`0400C76024710000`).
|
||||
|
||||
### Raw global memory lookups that start from their last entry
|
||||
|
||||
- **Symptom:** a pass whose shaders read memory through loaded addresses takes several milliseconds on the GPU for little work. `[gpuprof]` names the pass, and its shaders' build notes say `Global memory operation "Load" traced to no storage buffer`. Ocarina of Time's foliage mesh shader `73dc0b90c4082e43` (`Foliage.Product.110`, 135 such reads) took 10.9 ms of a 683x384 frame; 2,241 of the game's shaders (vertex, compute, fragment and mesh) have such a lookup, some hundreds of them.
|
||||
@@ -1729,6 +1854,30 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
|
||||
- **Fix:** a chain change. The accessor sizes these arrays to the whole ID ranges (`Program.cs` `QueryTextureArrayLengthFromPool` 2²⁰, `QuerySamplerArrayLengthFromPool` 2¹²) for sampled textures other than buffer textures; buffer textures and images keep 32-entry slot arrays (vendored `BindlessElimination.cs`, `NvnSlotArrayLength`). `dmsh_reflect.py` `pool_arrays` turns each such array into a pointer to `struct spvPool_<name> { uint n; array<element, 1> e; }`, read as `(&e[0])[min(index, n)]`, and renumbers the argument IDs (a pointer takes one). The struct declares one element because Metal's argument encoder walks every element of a declared array (`AGX::IndirectArgumentLayoutGen2::parseArray`): with 2²⁰ textures each pool shader's encoder took 57 ms and 66 MB, and the prewarm of 733 pipelines left the Mac host at 12.5 GB resident (9.7 GB of large mallocs); the elements are 8-byte resource IDs, so the pointer reaches the others (checked on the GPU with a test kernel); the reflection names them `tex_pool` (with the element type) and `samp_pool`. The host keeps one buffer per element type and pool base (`nvn_mtl.m` `pool_gpu`): the bound n, then from `DMSH_POOL_HEAD` the resource ID of each texture (sampler) ID of the pool bound at the draw, the dummy where an ID holds nothing or a texture of another type and at n. It is rebuilt when a registration or a texture's storage changes (`g_reg_gen`, `g_ser_gen`), the old buffer released after its submissions, and an argument block holding a pool address is not reused past a rebuild. Handles read from game memory are the bound pool's IDs, so the pool takes that pool's base (as `ubo_tex_id`), and a pool shader's c2 holds the bound handles without the base `bind_handles` added, as the game wrote them. Every texture is already in the residency set. A walk over every ID also reaches IDs no draw binds, which a game leaves registered after it is done with them: the first walk once crashed in `nvn_sparse_protect` making such a texture (a garbage `pool->vp`; the ID was not caught). So a texture no draw has made is made only while its storage exists (`tex_storage_live`: the memory pool object still holds its magic, and an ordinary pool's storage is in a pool the host maps), and an ID whose memory pool the game finalized is skipped until it is registered again (`treg_t.gone`, set in `treg_drop_pool_views`). Every other route is covered too: [A texture read after its memory pool object was freed](nvn-objects.md#a-texture-read-after-its-memory-pool-object-was-freed).
|
||||
- **Found on:** [Mario Party Superstars](../../dm/games/01006FE013472000/README.md): 6,370 of its 82,790 shaders, every character and NPC material (`_chara/pc/*.bnbshpk`, `_chara/npc/*.bnbshpk`) and some board variants (`hsmn_bg.bnbshpk`); a 2,304-entry texture pool (1,286–1,314 2D textures, 65 cubes) and a 512-entry sampler pool, about 0.1 ms per rebuild once the textures exist.
|
||||
|
||||
### Handles a shader computes index the pools
|
||||
|
||||
- **Symptom:** `[RED] <key>: the translator deleted N bindless accesses (<type> N): their results read 0` for thousands of shaders, and `lost without failing: …` in the build; textures read as black (PRAGMATA: 65,241 reads in 8,630 shaders, its intro a saturated cyan).
|
||||
- **Cause:** the handle is no word of any buffer but a value the shader computes: RE Engine's materials read a heap index from game memory (`cx[UR][off]`) or from a uniform buffer at a computed offset, clamp it to the heap (0x100–0x7fff), and OR it with a sampler ID (`| 0x10800000`, or with a separate sampler word of c2). `GenerateBindlessAccess` read such a handle through [the pools](#texture-handles-from-game-memory-index-the-pools) only when it was loaded straight from a constant buffer, an input or a storage buffer (Ryujinx's `IsBindlessAccessAllowed`, kept there to spare its pool walks), so every other read was deleted.
|
||||
- **Fix:** a chain change. A sampled texture other than a buffer texture indexes the pools whatever made its handle (vendored `BindlessElimination.cs`): its texture ID indexes the texture pool and its sampler ID the sampler pool, as on the GPU. Images and buffer textures keep the old rule, since their slot arrays are bound only for handles from c2's tables.
|
||||
- **Found on:** [PRAGMATA](../../dm/games/0400C76024710000/README.md): no access is deleted after the change. Any game with deleted sampled reads in its build log ([Losses a shader build reports](#losses-a-shader-build-reports)) changes with it.
|
||||
- **Check:** `DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py GuardedWrites.test_a_computed_handle_reads_the_pools`.
|
||||
|
||||
### A handle loaded from memory on one path only
|
||||
|
||||
- **Symptom:** `reflection conversion failed: B binding … has no resolved slot number` at load, then `the dispatched program has no compute shader` each time the game dispatches it; the build log has `Bindless handle taken from the one constant buffer handle among its phi inputs` for the shader.
|
||||
- **Cause:** the handle is a texture ID ORed with a constant sampler, and the ID's register holds a word loaded from memory on the path that reads the texture and something else on the other (a pushed buffer address's high word, `c[24] + 0x114`). `TryTableHandle` walks the OR's phi inputs for words of a uniform buffer, did not count the loaded word (a global load `GlobalToStorage` served is a copy of its helper's result, not a `Load`), and took the stray word alone as the handle: a binding the host has no slot for.
|
||||
- **Fix:** a chain change (vendored `BindlessElimination.cs`). For a read that [indexes the pools](#handles-a-shader-computes-index-the-pools), a handle with a loaded word among its phi inputs (`IsLoaded`: a load, a call, or a copy that keeps a storage kind), alone or as a source of the OR, is left to `GenerateBindlessAccess`: the read takes the texture its ID names, whatever path made it. Images and buffer textures keep their candidates.
|
||||
- **Found on:** [PRAGMATA](../../dm/games/0400C76024710000/README.md): compute shader `02e1292114121308`, which reads a material's texture by an ID from a material record.
|
||||
- **Check:** `DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_nvn2_buffers.py -k test_a_texture_id_loaded_on_one_path_indexes_the_pools`.
|
||||
|
||||
### One handle read as a texture and as an array
|
||||
|
||||
- **Symptom:** `[metal failed]` in the build, the compiler's message `vector component access exceeds type 'float2'` on a line that samples a `texture2d_array` with a two-component coordinate and `uint(rint(coord.z))` as its layer; the shader and its alpha test entry points do not build.
|
||||
- **Cause:** a handle has one binding, declared with one type, but Ryujinx gave the declaration the type of the last instruction that read it and the descriptor the first accurate one, while each instruction built its coordinates for its own type. A 2D read (`TEX` 2D at level 0) of a binding another instruction read as `ARRAY_2D` (`TXD`) gave no layer, which is invalid SPIR-V that SPIRV-Cross wrote out as it was.
|
||||
- **Fix:** a chain change (`ResourceManager.UnifyArrayTypes`, run once every function is translated). A 1D or 2D binding that some instructions read as an array is an array for all of them, in the declaration and in the descriptor the host binds by; an instruction that gives no layer reads layer 0, which is what the GPU reads through a non-array instruction. Level-of-detail queries take no layer either way. Cube and 3D bindings and arrays of handles are left as they were.
|
||||
- **Found on:** [PRAGMATA](../../dm/games/0400C76024710000/README.md): 24 pixel shaders (`21ba8fea5a5eb03c` is one), each reading `cb65542` handle `0x3041000E` both ways.
|
||||
- **Check:** `DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_nvn2_buffers.py -k test_a_handle_read_as_2d_and_as_a_2d_array_is_an_array`.
|
||||
|
||||
### An array of handles in a uniform buffer
|
||||
|
||||
- **Symptom:** the host stops at the shader's first load: `unexpected argument buffer layout: encodedLength=640 maxAid=48`.
|
||||
@@ -1843,6 +1992,14 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
|
||||
- **Found on:** [Pokémon Legends: Z-A](../../dm/games/0100F43008C44000/README.md#rendering) ([PR #178](https://github.com/seedds/nxnative/pull/178)); [SHIN MEGAMI TENSEI V: Vengeance](../../dm/games/010069C01AB82000/README.md), whose two buffer-image counter shaders dispatched at boot consume their returned values.
|
||||
- **Check:** `dm/tools/tests/test_image_atomic_bounds.py`. Portable tests check the MSL version choice and the rejection of the pointer form. With `DMSH_TEST_XLATE` set to a rebuilt translator (and `spirv-val` on `PATH`; spirv-cross is the in-repo build) the synthetic shaders are translated, the guard's dataflow is checked in the SPIR-V (the size query and comparison dominate the atomic, the phi carries zero on the invalid edge), and the MSL is produced; `DMSH_TEST_METAL=1` compiles and links it (`DMSH_TEST_METAL_SDKS=macosx,iphoneos` for both SDKs) and `DMSH_TEST_GPU=1` runs the returning fixtures (above). Changing this path changes the chain version: rebuild the translator and update the lock before building shaders.
|
||||
|
||||
### 64-bit image max and min (SURED.MAX.U64)
|
||||
|
||||
- **Symptom:** `NotSupportedException: Ampere 59f at …: SURED form 0110e400` in the shader build, then the scene's 3D picture black behind a UI that draws: `[RED] shader … (compute) failed to load` and `[RED] the dispatched program has no compute shader`. A texture dump shows the visibility target (RG32Uint) all zero.
|
||||
- **Cause:** a visibility buffer written by compute rasterization keeps, per pixel, the nearest primitive as one 64-bit value, depth in the high word and the primitive id in the low word, through SURED.D.2D.MAX.U64 on an RG32UI image. The decoder took only the 32-bit sizes, and Metal's texture atomics were bound only on R32 textures. SPIRV-Cross has no 64-bit atomics at all.
|
||||
- **Fix:** `ASured` sends the U64 form to `EmitSuatom`, which allows only a 2D, 2D-array or 3D max or min with no result (Metal has no 64-bit texture add, fetch or bitwise atomic). `GenerateImageAtomic` writes it as two 32-bit atomics of the same operation on the same texel, low word then high word, a marker that never runs. `dmsh_atomic.wide_atomics` turns each pair into one `texture2d<ulong, access::read_write>::atomic_max` / `atomic_min` (MSL 3.1) and fails the shader on any other access of that image. The host makes RG32Uint images with the shader-atomic usage on Apple GPU family 9, M3 / A17 Pro and later (`pf_atomic`), and the reflection marks such a binding `atom` 2. Older GPUs have no 64-bit texture atomic, and those pipelines do not build there. Ported from uncraftablexd's PRAGMATA bring-up ([PR #1801](https://github.com/seedds/nxnative/pull/1801)).
|
||||
- **Found on:** [PRAGMATA](../../dm/games/0400C76024710000/README.md): 336 compute shaders, among them `26166d37ed56d6bb` and `3bc957e2739551e7`, dispatched at the title.
|
||||
- **Check:** `DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py Sured64 WideAtomics`; `test_image_atomic_bounds.py` (the source-size gate).
|
||||
|
||||
### Reads past a uniform binding's size
|
||||
|
||||
- **Symptom:** the GPU hangs (Metal command-buffer timeouts, `GPU access revoked`, exit 70; on the Mac WindowServer can lose its watchdog check-in and the session restarts) or a draw reads garbage, where a shader reads a uniform slot further than the game bound it. No `[RED]` line.
|
||||
|
||||
@@ -845,7 +845,7 @@ def survey(nsp_dir, app, fam, keys, repo, py, env):
|
||||
nros = {p.name: p for p in sorted((ex / 'romfs_nro').rglob('*.nro')) if p.is_file()} # files only: a RomFS folder may end in .nro (The Binding of Isaac: Afterbirth+). The manifest pass writes the NROs (their imports decide the API and the modules: Portal 2's main is SDL with EGL, its Source engine NROs draw with NVN)
|
||||
nro_add = pg.nro_modules(ex / 'ExeFS', nros, keep) if nros else {}
|
||||
S = pg.shader_sources(mods['main']['imports'], F['glsl_src'], [m for m in sorted({*keep, *nro_add}, key=pg.load_order) if 'glslcCompile' in mods[m]['exports']], rom['mags']['SPIR-V'],
|
||||
rom['exts'].get('.pak', 0) if F.get('main_markers', set()) & {'Unreal', 'Unreal 4'} else 0, rom['mags']['Trinity pack'], gl_names=F.get('gl_names', 0),
|
||||
rom['exts'].get('.pak', 0) if 'Unreal' in F.get('main_markers', set()) else 0, rom['mags']['Trinity pack'], gl_names=F.get('gl_names', 0),
|
||||
gl_src=F.get('gl_src', 0), gl_files=sum(rom['exts'].get(e, 0) for e in pg.GL_FILES), oodle_pkz=rom['mags']['PlatinumGames PKZ'], # the manifest has no name tables: every PKZ counts
|
||||
nro_imports=frozenset(pg.romfs_nro_imports(ex / 'romfs_nro')))
|
||||
vulkan, gl = S['graphics'][0] == 'vulkan', S['graphics'][0] == 'gl'
|
||||
@@ -864,6 +864,7 @@ def survey(nsp_dir, app, fam, keys, repo, py, env):
|
||||
if F['glslc']: notes.append(f'main has {F["glslc"]} GLSLC compiler output magics (0x19866891): shader_split.py takes those that are whole outputs (13 Sentinels and the KTGL games compile their shaders into main; Unity\'s player has 11 of its own)')
|
||||
if rom['mags']['Trinity pack']: notes.append('Trinity packs (Game Freak, arc/data.trpfs with its index data.trpfd): the shaders are BNSH inside Oodle Mermaid streams; shader_split.py decodes them with the game\'s own OodleLZ_Decompress in the Mac host, which dm/host/hle_oodle.c finds by the library\'s name string')
|
||||
elif rom['mags']['PlatinumGames PKZ']: notes.append('PlatinumGames PKZ archives (pkzl; Bayonetta 3): DAT archives inside, compressed per entry (OodleKraken, ZStandard or None); the shaders are shader objects (VSO / PSO / CSO …) in DATs, which shader_split.py reads (pkz_entries, pg_shader), Oodle Kraken through the game\'s own streaming decoder in the Mac host (dm/host/hle_oodle.c)')
|
||||
elif rom['mags']['RE Engine PAK']: notes.append('RE Engine PAK archives (KPKA; Capcom: Monster Hunter Rise, Ghost Trick, PRAGMATA): file names only as hashes, entries zstd / deflate, PRAGMATA\'s large ones in a block table; the shaders are SDF definitions inside them, which shader_split.py reads (kpka_jobs, sdf_shaders)')
|
||||
elif rom['mags']['MT Framework ARC']: notes.append('MT Framework ARC archives (Capcom, The Great Ace Attorney Chronicles): the shaders are in a shader package (SPK) inside one of them, which shader_split.py reads (mtarc_members, mtspk_shaders)')
|
||||
elif rom['mags']['Bezel Engine archive']: notes.append('NintendoWare Bezel Engine archives (.bea, magic SCNE; Big Brain Academy: Brain vs. Brain): every entry is a zstd frame, and the shaders are BNSH in their .bfsha entries, which shader_split.py reads (bea_members)')
|
||||
elif rom['mags']['CRI CPK'] and not F['glslc']: notes.append('CRI CPK archives (Bayonetta 2; Vanillaware\'s and Atlus\'s games keep their shaders elsewhere): files compressed one by one with CRILAYLA; shader_split.py decodes every entry (dm/gfx/tools/cpk.py, cpk_jobs) and scans it as a loose file (Bayonetta 2: BNSH files in PlatinumGames DAT archives)')
|
||||
|
||||
Reference in new issue
Block a user