Track bounded depth/stencil writes per depth snapshot cache entry so fb_depth_snap blits only the dirty rectangles written since the previous snapshot instead of copying the entire attachment on every game barrier (see #3227). Controlled by DM_NVN_FB_DEPTH_RECT via sw_mode (default 0; 1 enables, ab alternates under DM_AB for matched-thermal/matched-upload testing before enabling globally): - Keys incremental state by root MTLTexture and MTLHeap plus nvn_sparse_gen(), recording draw writes right before emission and scissored depth-stencil clears in clear_ds_tri. - Snaps dirty rects outward to 16-pixel tile boundaries and merges any overlapping rects so Metal 4's concurrent copy encoder blits strictly disjoint tiles (falling back to a single whole copy when multiple rects cover at least 75% of the level). - Skips the copy and keeps the render pass open when nothing wrote depth since the previous snapshot. - Enforces full-copy fallbacks for non-Load or layered passes, enc_r_begin, MSAA resolveTexture, blits/uploads, heap aliases, sparse pools/remaps, waiting clears, DM_NVN_FB_SNAP=all, point primitives beyond scissor (bounded by scissor only), mesh-task draws, and unbounded viewports. - Adds GPU readback tests in dm/gfx/tests/t_feedback.m covering partial tiles, overlapping merges, aliased serials, no-write skips, and all full-copy fallbacks. Co-authored-by: crt-000 <[email protected]>
680 KiB
Rendering
The replay on Metal (dm/gfx/nvn/nvn_mtl.m) and the Vulkan and OpenGL layers. Each entry: symptom, cause, fix, the games it was found on. The symptom index lists every symptom.
Textures and formats
Direct compute dispatches with an empty grid
- Symptom: a direct zero-sized grid changes replay state or reaches Metal's invalid empty-grid dispatch API.
- Cause: NVN permits zero work, but replay advanced its write epochs and resolved the program before checking the direct group counts. Indirect counts are GPU-owned and cannot be inspected this way.
- Fix: return from direct empty dispatches before replay state changes or encoding. Indirect dispatch handling remains unchanged.
- Check:
t_dispatch_zerocovers each zero dimension and confirms that no program, encoder or write state is required or changed. The fixture fails on main and passes with the guard. - Found on: FIFA 23 Legacy Edition, PR #1696.
Views of placed textures need their parent resident
- Symptom: Shader Validation aborts with
Texture is not residentin a fragment sampling copy even though the texture's heap is resident. - Cause: heap residency covers the placed storage, but a sampled view also needs its parent texture descriptor.
res_add_atregistered only the heap. - Fix: register both heap and texture descriptor. The current owner, heap recycler and queued residency commits already retire them safely: Metal calls run outside the residency-data lock, and retained queue objects are released after the commit lock is unlocked. No additional heap-retirement queue or older ownership code is needed.
- Check: the placed-texture fragment-copy case in
t_image_aliasaborts on main and passes with the fix under Shader Validation, with deferred encoding off/on. Its two allocation-threshold assertions fail identically on unchanged main (337 checks) and with the added case (340 checks); those thresholds were not relaxed.t_upload_budgetseparately passes all 261 checks in both encoder modes on current main without the proposed upload-residency replacement. - Found on: FIFA 23 Legacy Edition, PR #1696. Checks: Apple M6, macOS 27.2.1, Xcode 27.2.
GPU copies into compressed IMAGE textures
- Symptom: a compressed texture's Metal copy and guest storage disagree after a GPU copy. FIFA 23 shows a corrupt checkerboard in place of the controller-button glyph before Select.
- Cause:
tex_storage_okcorrectly allows compressed IMAGE textures to take CPU uploads, because shaders cannot write a block-compressed format.tex_storage_dstinstead excluded every IMAGE texture from storage writes. GPU copies therefore left stale bytes in the storage that subsequent reads or uploads can use. - Fix: apply the same format rule at the write boundary: IMAGE excludes uncompressed shader-writable textures, but not block-compressed textures. Existing storage ownership and the GPU's
gsb_storepath remain in use. No cache flush, re-upload, profile switch or ownership rewrite is added. - Check:
t_compressed_copyfails the guest-storage comparison on main (38 checks, one failure). With the fix it passes all 38 under API Validation and Shader Validation, each with deferred encoding off/on, on Apple M6/macOS 27.2.1/Xcode 27.2. The fixture checks compressed IMAGE off/on, GPU content, deswizzled guest bytes and a subsequent pool-chunk creation. With only this predicate changed, the FIFA menu capture and user retest show the correct button icons. - Found on: FIFA 23 Legacy Edition, PR #1696.
Null textures in diagnostic logs
- Symptom: clang reports null dereferences in
nvnWindowInitializeandclear_tex; clearing a null texture crashes withDM_NVN_PASSDUMP=1. - Cause: window initialization checked the texture count but logged the first texture's dimensions without checking its pointer. Clear replay tolerated a null texture but its pass dump unconditionally read the texture serial.
- Fix: check the first texture before logging its dimensions (
hle_nvn.c) and log serial 0 for a null clear texture (nvn_mtl.m). - Found on: clang static analysis (issue #424); synthetic null-texture tests, with no gameplay failure reported.
Texture objects copied into command records
- Symptom: Metal aborts on a texture descriptor with an absurd size (
height (1869367126) greater than … 16384). - Cause: a command record kept a pointer to the game's
NVNtextureand read it at replay. NVN commands do not depend on the API object once recorded. - Fix: the host now copies the texture object into the record (
REC_SNAP/tex_snapinhle_nvn.c: render targets, texture copies and clears). Replay rejects objects without the texture magic and sizes beyond Metal's limits, with a red line instead of an abort. - Note: the first red lines name the call site and the object's first bytes. In Engage those bytes were 32-bit triangle indices, i.e. another write had already overrun into the texture object; that stopped once the alias region had address space left (Size-aligned regions exhaust the alias address space).
- Found on: Fire Emblem Engage.
New textures start as zero
- Symptom: a decoded movie stays black even though its YUV textures contain the picture; disabling its depth test makes it visible.
- Symptom: a scene background is green and retains silhouettes of moving characters; pixels a character covers can recover their normal colour. The resolved scene is already wrong before postprocessing.
- Cause: Metal leaves a new texture's content undefined; a freshly mapped Switch memory pool reads as 0, and feedback effects (such as Mario's fountain wave simulation, Metal 4 does not order operations inside one encoder) never clear their state texture.
- Fix: non-packaged colour textures are zero-filled from a shared zero buffer when created (
tex_zero_fill, batched with the uploads). Single-sample Depth16Unorm and Depth32Float textures are copied into from the same buffer, in pieces of rows (A clear pass on a large depth texture fails withInsufficient Memory). Stencil formats, and multisample textures (a buffer copy cannot write samples), are cleared to zero in render passes in the same upload batch, for every level and slice, once when the Metal texture is created; the game's own clears, loads and blending are unchanged. Upload-failure recovery tracks these destinations too. - Found on: Super Mario Bros. Wonder; Pokémon Brilliant Diamond: the opening movie's YUV conversion uses GEQUAL against a new 1920×1080 depth texture that the game never clears. Metal supplied depth 1, discarding the movie; zero initialization restores it without a shader override. Rune Factory 5 (
01007B4014086000, no profile in the repository; PR #1760): its opening forest loads a new 1920×1080 two-sample RG11B10Float scene target without a colour clear and blends into it; initializing the target alone restores the picture. - Check:
t_zero_depthpoisons Depth16 and Depth32F textures (levels, layers, a cube) and reads every texel back as zero after the copies;t_clear_dspoisons depth and stencil before calling the real initializer and checks both become zero;t_clear_msaafills a multisample colour texture with a colour, calls the initializer and reads every sample on the GPU (RGBA8, RG11B10Float and RGBA16Float at two and four samples); depth clear, stencil-view and upload-budget tests cover the related paths.
Texture swizzle through swizzled Metal views
- Symptom: glyphs render as white boxes (the font atlas is
(1, 1, 1, R)). - Fix:
TextureBuilderSetSwizzle/TextureViewSetSwizzleare applied with Metal swizzled texture views (NVN and Metal channel enums have the same values). The swizzle names components of the NVN format, which the format's own mapping finds in Metal's (nvn_fmt_to_mtl: alpha 1 for RGBX-type formats; red and blue swapped for the RGB565 family, all four reversed for RGBA4, but only in linear and buffer textures, which read guest memory in place: every other host texture holds Metal's order, RGB565-family textures in Metal's channel order). - Note: Metal makes a swizzled view read-only (usage 0x1), so an image slot gets the same view without the mapping (
img_fit), and the on-chip read merge leaves a swizzled sample alone. - Found on: Super Mario Bros. Wonder (the font atlas); The Legend of Zelda: Echoes of Wisdom's hearts (GitHub PR #66, the RGB565 red / blue swap).
RGB565-family textures in Metal's channel order
- Symptom: RGB565, RGB5A1 or RGB5 textures sample with red and blue exchanged: smeared, banded rock, the shapes right and the colours wrong; or what the GPU cleared, drew or copied into such a texture reads back to the game, or samples, with red and blue exchanged.
- Cause: Metal has these formats only with red and blue exchanged (
B5G6R5Unorm,BGR5A1Unorm; red at bit 11 or 10, the guest's at bit 0), and the host kept them in two orders: packaged textures (NvPkg) in the guest's, swapped when sampled, plain ones in Metal's, as Metal renders and clears into them. Every path that moved bytes from one to the other without converting exchanged the colours: the one-time fill of a plain texture (tex_init_fill), buffer → texture and texture → buffer copies,ReadTexels, a clear or a draw into a packaged texture, a texture copy between a plain and a packaged one, the readback of a copy into a packaged texture's storage. - Fix: one order. Every host texture of these formats holds Metal's order; only guest memory holds the guest's, and bytes are converted where they cross (
rb_packed_shift, fromnvn_fmt_to_mtl's swap): every upload is repacked on the CPU (pkg_upload_; these formats leave the GPU deswizzle), buffer ↔ texture copies exchange the fields on the GPU in the copy encoder (rb_swap_gpu: through a staging area of the frame arena into the texture, in place in the buffer out of it; the GPU may have written the buffer earlier in the submission), andReadTexelsand the readback into a packaged texture's storage exchange them on the CPU (rb_swap_rows). Clears, draws and texture copies then need nothing. Linear and buffer textures read guest memory in place: they keep the guest's order and the swap when sampled (tex_by_id), and copies into or out of them stay raw (rb_copy_shift). - Note: a view of one of these textures in another format of the same size (RG8, R16) now sees Metal's order where it saw the guest's in a packaged texture; no game is known to make one. A linear render target of these formats is drawn in Metal's order into guest memory; not seen.
- Check:
t_view_swizzlefills RGB565, RGB5A1, RGB5 and BGR565 textures fromCPU_UNCACHEDandCPU_NO_ACCESSpools through the realtex_init_fill, reads them on the GPU, draws into one texel and reads both again, and checks the guest storage is unchanged (379 checks).t_readbackrecords the real commands for RGB565, RGB5A1 and RGB5: a buffer → texture copy sampled, copied back and read withReadTexels; a Metal clear to red copied out and read; a packaged texture sampled, one with a texel cleared, one copied into from the cleared plain texture and read from its storage (78 checks, none failed). With the host before the fix, 18 oft_readback's fail. - Found on: The Legend of Zelda: Tears of the Kingdom (GitHub issue #183, the Depths' cave walls: their initial-fill RGB565 / RGB5A1 textures), found and checked in the game by the issue's reporters (M1 with 1.2.1, M4 with 1.4.3); the copy paths found reviewing that fix, checked by the tests only.
RGBA4 textures in Metal's channel order
- Symptom: outdoor battle ground and lower foliage are nearly black while the characters and the UI stay lit: a baked shadowmask takes the sunlight away. RGBA4 textures sample with their four channels reversed.
- Cause: NVN's RGBA4 holds R, G, B, A from bit 0 up, Metal's
ABGR4UnormA, B, G, R; the host kept the guest's bits, so every channel read another's nibble. Super Mario RPG's shadowmask texels are mostly0x0f00(blue 1), sampled through a (B, G, R, A) mapping: red should read 1, and read 0, with green 1. - Fix: RGBA4 takes the RGB565 family's conversion, all four nibbles reversed instead of red and blue (
rb_packed_shift4 inrb_swap_rowsandrb_swap.metal), at the same crossings between guest memory and host textures (uploads are repacked on the CPU and leave the GPU deswizzle, as that family's do); linear and buffer textures, read in place, takenvn_fmt_to_mtl's reversed mapping when sampled. That entry's note holds here too: a same-size view in another format (R16) sees Metal's order; no game is known to make one. - Check:
t_view_swizzlesamples the texels0x8421and0x0f00(every nibble different) uploaded and on a buffer, with and without the (B, G, R, A) mapping, cleared by Metal and filled fromCPU_UNCACHEDandCPU_NO_ACCESSpools;t_readbackruns its RGB565-family copy, clear andReadTexelscases for RGBA4. With the host before the fix, 40 oft_view_swizzle's 554 checks and 6 oft_readback's 154 cases fail. - Found on: Super Mario RPG (Mushroom Way's battles), checked in the game before and after.
nvnTextureCompare compares the channel mapping
- Symptom: dark boxes and cream cloud rectangles behind HUD prompts, a black stamina wheel and a black System menu background (layout captures).
- Cause: agl's layouts rebuild a capture texture on the same storage with a new channel mapping, and replace the registered descriptor only if
nvnTextureComparereports the two textures different. The host compared the description and the storage but not the mapping, so every rebuild was dropped. - Fix:
nvnTextureComparecompares the mapping too, an unset mapping counting as (R, G, B, A).t_nvncovers the comparison. From GitHub PR #6. - Found on: The Legend of Zelda: Breath of the Wild: panes tagged
CaptureOn(about 140 layouts, e.g.PaGuideKeySmoke_00; user dataA8,CaptureScale0.5,MultiFilter) are drawn into a target, blurred at half size and copied into a capture texture that the layout's materials sample in place of the placeholderFBLayout_00. The game creates it with its per-format default mapping (one call site,main+0xecb0bc: R8 → (R, 0, 0, 1), RG8 → (R, G, 0, 1), and so on), then rebuilds it with the capture's own mapping:main+0xf597dcpicks (1, 1, 1, R) for anA8capture (the material colour kept, the mask as alpha) and alpha 1 when the pane saysCaptureOutputAlpha255 (read atmain+0xf58e98; an RGB10A2 capture then reads (R, G, B, 1));main+0xecacf0stores the mapping and rebuilds the texture (main+0xecabe8), andmain+0xec33f0replaces the descriptor only on a difference. The captures kept (R, 0, 0, 1), whose alpha is always 1: hard-edged dark boxes behind every prompt (the shadow panee6a88e12dbae9743: black, alpha = capture alpha × vertex alpha 180/255) and rectangles filled with cream cloud (the glowaa209f57b133e862: alpha = min(cloud alpha, capture alpha)). Checked on the Mac by the PR's author (M4 Pro, unchanged shader libraries): green stamina, the purple noise meter and the game's own blurred System menu background. Super Mario Odyssey: its layouts rebuild their captures through the same agl code (main+0x982320replaces the registered descriptor only ifnvnTextureComparereports a difference), so the fix covers them too. - Note: before the cause was known, a profile key,
alpha_from_red, listed the layout library's pixel shaders and bound such render targets through a view mapped (R, 0, 0, R). In BotW (all 26 pixel-shader variants,main's BNSH at 0x1d83000) that fixed the alpha but zeroed green and blue, so tinted panes such as the stamina wheel came out black, and the System menu background (a capture with alpha forced to 1) stayed black. In Odyssey (all 26 layout pixel shaders,main's BNSH at 0x132c000) it had turned the coin counters' solid white cards into the right shapes. With the comparison fixed it found no (R, 0, 0, 1) target on either game (the mapping a capture is rebuilt with replaces it, on the Mac and the iPhone alike), so the key and its host code (tex_alpha_red, DM_NVN_ALPHA_RED) were removed (c76f6798); Odyssey's note has the A/B runs.
Sampling a depth attachment through a red texture view
- Symptom: Metal validation aborts in
tex_by_idwithMTLPixelFormatDepth32Floatnot compatible withMTLPixelFormatR32Float. - Cause: an NVN sampled view requests the single-channel colour format of a depth attachment. Metal forbids that format cast even with pixel-format-view usage. Reading the unmodified depth texture as colour can also repeat depth in the green and blue channels.
- Fix: for D32F viewed as R32F, or D16 viewed as R16 UNORM, keep the depth format and map its value to
(depth, 0, 0, 1)before applying the descriptor's channel swizzle. The view selects the requested mips and layers of the original attachment, so later depth writes stay visible. - Found on: Burnout Paradise Remastered (#985) (D32F as R32F).
Texture views cached by texture and view parameters
- Symptom:
newTextureViewWithPixelFormattakes a large share of the replay thread (45% in Age of Calamity) when a game registers textures into a ring of IDs before every bind. - Cause: KTGL registers a texture into the next ID of a ring before every bind (
RegisterTexture,GetTextureHandleandBindTexturecounts are equal: 8,000 a frame in battle, up to 28,000 after the cutscene). Only 1 in 6 registrations repeated what the ID held, so the per-ID view (treg_t.view) was rebuilt for half of all binds. - Fix: views are also kept by the Metal texture they view and the view parameters (8 per texture; 4 until same-pass feedback views shared the cache), for as long as the owner holds that texture (a live or ghost entry, a pin or the sharing table:
own_holds_locked), and dropped at the first commit after it lets the texture go (vc_commit, from the owner's list of released objects,own_gone_take_locked) or when its pool is finalized; a registration identical to what the ID holds keeps its view and the registration generation (vc_getinnvn_mtl.m). Kept by serial until PR #2542; the key by Metal texture also covers finalized textures read through a registered ID and render targets initialized again every frame. - Found on: Hyrule Warriors: Age of Calamity: 2,036 views were made in a 15-minute Mac battle run, 211 million reused; the replay before the cutscene went from 14.3 to 10.8 ms a frame.
Texture views re-made for finalized textures every submission
- Symptom:
newTextureViewWithPixelFormatstays a large share of the submit thread although the view cache hits. Ocarina of Time (Switch 2) made about 330 views a frame in Kokiri Forest, about 310 of them for the same textures again. - Cause: the view cache (Texture views cached by texture and view parameters) kept views only for live textures. A texture the game has finalized while one of its IDs is still registered resolves through
g_ghost, andvc_set_forrefused its set because nothing dropped it later. So every submission that read the ID made a transient view, released at the submission's end (treg_finish_submission), and the next submission made it again. - Fix: a finalized texture still resolved through
g_ghostis the same Metal texture, which the ghost entry holds, so the view cache keyed by Metal texture (Texture views cached by texture and view parameters) keeps its views until the ghost table lets it go, and drops them at the next commit. The views hold the texture only as long as the owner already does. A texture buffer's 2D rows (tbuf_as_2d) are kept the same way, with the buffer texture while the owner holds it, finalized or not; only a texture the owner no longer holds has its rows kept by the memory they view (g_tb2_gone). Kept for live textures only, as PR #2542 first had them, a finalized texture's rows went tog_tb2_gone, which missed on about a third of Yoshi and the Mysterious Book's binds. First fixed with sets by serial for finalized textures (PR #2482,DM_NVN_VC_KEEP), replaced by the key by Metal texture in PR #2542, which removed the switch. - Found on: The Legend of Zelda: Ocarina of Time. In-run A/B on its Kokiri Forest route (M2 Air, 20 pairs; measured in PR #2482 on a line before the ghost table was kept by use, PR #2389, and before the sweep moved to the commit):
- views made 330–347 → 38 a frame, none of them evictions;
- submit thread −1.72 M cycles a frame (−6 %), −5.4 M instructions;
- frame time within noise, because the GPU was the limit.
- Found on: Yoshi and the Mysterious Book, through texture-buffer rows. From an empty save past the menus to the opening dialogue (M6, partial library, 120 s): to frame 5,100, 114,091 row binds of finalized textures made 40,308 rows views, and with the rows kept with the texture, 169,774 made 788; over the whole run, 804,505 binds made 108,882, against 1,095,030 making 9,619. Frame time 16.7 ms either way (the game's 60 fps).
Compatible views for a mismatched declared texture type
- Symptom: daylight scenes washed out to white (every read of a texture returned one fixed value);
texture type mismatchred lines, among themdeclares slot … as Metal type 6, texture ID … is type 5(a cube in a cube array slot). - Cause: on Maxwell the sample instruction carries its own dimension, and a non-array sample of an array texture reads layer 0. On Metal a 2D array bound to a
texture2dargument is a type mismatch, and every read returned one fixed value. 3D World creates its deferred pre-lighting buffer (the G-buffer's fourth target, R11G11B10F) as a one-layer 2D array texture, and the lighting shader samples it as 2D, so the whole picture got one pale ambient colour (bloom then blew it out further). Measured on an M4 Pro, a cube view bound astexturecube_arrayreads face 0 in every direction, and bound astexture2d_arrayreads layer 0 at every index; neither faulted the GPU, over 2,000 dispatches of 262,144 reads at random array indices. - Fix: the host compares each texture binding's declared type (the reflection's
dtt) with the texture it resolves to and binds a compatible view (tex_fitinnvn_mtl.m, cached per texture-pool entry). 2D, 2D array, cube and cube array are all layers, and the declared type says how many the view takes: 2D the first (for a cube, the face a non-array sample of its six layers reads), 2D array all of them, cube the first six, cube array all whole cubes. Any other mismatch is reported once.make -C dm/gfx/tests GAME=<id> check_t_tex_fit_rootreads every face and layer through these views under Metal API validation. - Found on: Super Mario 3D World + Bowser's Fury. The cube → cube array view on Splatoon Raiders. The cube → 2D view on Atelier Ryza DX, whose draws leave cube textures in slots they read as 2D (
texture type mismatch … declares slot … as Metal type 2, texture ID … is type 5 (NVN target 8 …); bound as is, up to five over the opening, the textures different in each run): the lines are gone and the field looks the same (0.3 % of pixels differ between the two hosts at the same frame, scattered particles and foliage). A Metal view of one cube face as 2D passes the API validation layer. What the Switch reads there was not measured; ROMANCE OF THE THREE KINGDOMS 8 REMAKE has the same case in two vertex shaders, not run since. - Note: how it was found: a blit-based pass snapshot of that target showed a correct, colourful image while a lighting shader edited to output only that input showed a uniform colour, and both resolved to the same Metal texture. Earlier suspects that turned out correct: fog, bindings, the 1D lookup tables, clear colours, the depth convention, the final sRGB view, blend states, GPU luminance readback. There is no tone-mapping pass in this game: the final composite writes
scene + bloominto an RGB10A2 target.
Compatible views made from the texture under a view
- Symptom: with
MTL_SHADER_VALIDATION=1,Invalid Metal usage: Texture is not residentfor a texture allocated intex_fit; without validation those reads are undefined. - Cause: Metal takes a view's residency from the texture it was made from.
tex_fitmade its view of the texture the binding resolved to, which is often a view itself (the view cache's, a level and layer range or a swizzle), so the new view hung under a texture that is not in the residency set although the texture under both is. - Fix:
tex_fitmakes the view from the texture at the bottom of the chain, with the bound view's level and layer offsets, level count and swizzle (t_tex_fit_root). Registered views and scaling/format-converting copies do the same, composing nonzero mip/slice offsets. The existing view cache remains keyed by its Metal base texture and parameters. - Check: the nested depth/stencil copy in
t_stencil_viewaborts under Shader Validation on main and passes all 20 checks with the fix in both encoder modes.t_view_levelschecks the nested registered range through the current owner API (48 checks, all pass). The tests cover nonzero parent-relative coordinates. - Found on: The Legend of Zelda: Breath of the Wild: a 64x64 environment cube read from a 2D-array view, 7 draws in the outdoors frame replayed with
nvn_replayunder shader validation.
1D textures as one-row 2D textures
- Symptom: a type mismatch when a Metal 1D texture is bound to a shader's
texture2dargument. - Cause: translated shaders never declare
texture1d(none of the five games' libraries did at the time). - Fix: NVN 1D and 1D-array textures are created as one-row 2D / 2D-array Metal textures.
- Found on: Super Mario 3D World + Bowser's Fury: the material shaders sample 64×1 R32F lookup tables created as NVN 1D textures (and filled with
WriteTexels).
A 1D array texture uploaded as its layer count of rows per layer
- Symptom: with Metal API validation, an abort at a texture upload:
(destinationOrigin.y + sourceSize.height)(64) must be <= height(1). Without it, the upload writes past each layer into the next ones, and the texture holds junk rows: a light that flashes across a surface as the camera crosses a distance band. - Cause: a 1D array is a one-row 2D array whose layer count is the NVN height (1D textures as one-row 2D textures), and the storage layout (
nvn_tex.c) and the deswizzler lay it out so, but the upload paths took the NVN height as each layer's row count: every layer went up as that many rows into a one-row slice, and the GPU wrote past each slice. - Fix:
tex_lsize(nvn_mtl.m) gives a level's size as its Metal texture holds it (width, rows, depth planes; one row for a 1D or 1D array texture).pkg_upload_(its byte count, the GPU and CPU deswizzles), the sparse texture's tiles andscissor_fulltake it, so no path keeps a rule of its own. - Open: region-based operations on a 1D array (
WriteTexels,ReadTexels, texture copies) still take the region's y and height as rows, not layers. No game is known to reach them. - Found on: PRAGMATA: its light-profile lookup table, a 512-wide R16F 1D array of 64 layers read by the deferred lighting, went up as 64 copies of 64 rows.
- Check:
make -C dm/gfx/tests GAME=<id> check_t_partial_upload(R16F 1D arrayandRGBA8 1D array with levels, under Metal API validation; without the fix the first aborts).
Cube textures held as 6-layer 2D arrays
- Symptom: shaders that sample a cube texture as
texturecube_arrayget a type mismatch. - Cause: Metal can make a cube-array view only of a 2D-array base texture.
- Fix: NVN cube textures are created as 6-layer 2D arrays and bound through cube / cube-array views by
tex_fit, which also maps a cube array read as a cube to its first cube. - Found on: The Legend of Zelda: Breath of the Wild: 1,512 shaders sample the environment probes as
texturecube_arraywhile a single cube texture is bound.
Cube map arrays count layer-faces
- Symptom: an abort in
MTLTextureDescriptorvalidation,arrayLength (510) … greater than the max allowed size (341), when the prologue movie ends. - Cause: as in OpenGL, an NVN cube map array's depth is its number of layer-faces (a multiple of 6: 510 for 85 cubes), while a Metal cube array's
arrayLengthcounts cubes. The host took the depth as a cube count in three places: the Metal texture, the upload's layer count and the guest layout (nvn_tex.cshape), soGetStorageSizereported six times the storage. - Fix: a cube array is now created like a cube, as a 2D array of all its faces, and
tex_fitmakes the cube-array view a shader asks for (t_nvnchecks the storage size against a 2D array's). - Found on: DRAGON QUEST XI S.
Cube views count their layers in cubes
- Symptom: an abort in Metal's validation:
newSliceRange.length(1) must be a multiple of (6). - Cause: environment maps are 6-layer textures (target 2D array, depth 6) sampled through views with target CUBEMAP and layers 0 + 1. As in the hardware's texture header, a cube view counts its layers in cubes; Metal counts faces.
- Fix: a cube view whose layer count is not a multiple of 6 now takes its layers as cubes when the texture has that many faces (
tex_by_id; else it is read as a 2D array with a red line). - Found on: Pokémon Sword (as the player first walks out of the house).
A 2D texture in a cube slot binds the zero cube
- Symptom:
texture type mismatch … declares slot 10 as Metal type 5, texture … is type 3(undefined reads); the later[RED] texture type mismatch: shader declares a cube, texture is 2Dcould also report an unused conditional input as an error. - Cause: a 2D texture bound where the shader declares a cube (a placeholder for an environment map) has no cube view. The same for a 2D array of fewer than six layers, which is how the host holds some NVN 2D textures. A uniform-controlled branch may choose a different cube input while the unused slot retains a 2D descriptor. Binding all statically declared Metal resources does not establish that this input is sampled.
- Fix: the zero cube is bound instead of a type mismatch with undefined reads (
tex_fit). This supported binding fallback is informational (cube binding fallback), rather than a red error: it cannot diagnose which branch the shader executes. Other unsupported texture mismatches still report errors. - Found on: Pokémon Legends: Z-A; Mario Kart 8 Deluxe binds a 2D array of fewer than six layers (format 0x44) at slot 10 of two pixel shaders that declare a cube there as a race loads, and it was bound as is; Echoes of Wisdom exposed the false error for an unused conditional cube input.
- Check:
make -C dm/gfx/tests GAME=<id> check_t_cube_placeholderuses productiontex_fitand GPU sampling under Metal API validation. For 2D descriptors and one- and five-layer arrays, an unselected fallback preserves the other cube's blue output, a selected fallback reads zero, and binding alone raises no error; both cube and cube-array arguments are covered.
A 2D texture in a 3D slot binds the zero 3D texture
- Symptom:
[RED] texture type mismatch: shader … declares slot … as Metal type 7, texture ID … is type 2 … bound as is(or type 3, a 2D array); the reads are undefined. - Cause: the game leaves a 2D texture bound in a slot its shader samples as a 3D texture, and Metal makes a 3D view only of a 3D texture. Batman: Arkham Knight's shaders sample a volume at world coordinates through separate texture slots that hold 2D textures, mostly half-resolution render targets, from the first frames of New Story on (
553c51835a24a36a, separate slot 2: a 720x406 RGBA16F target); the pass dump shows the game binding them there, so no bind was lost, and the game does create 3D textures (2x2x2, 32x32x32, 71x40x64). What the Switch's texture unit reads from a 2D texture header through a 3D instruction is not known. - Fix: as for a cube slot,
tex_fitbinds the zero 3D texture, a defined read, for a 2D texture or 2D array in a 3D slot, and logs the first case (3D binding fallback); other mismatches no view bridges are still reported and bound as is. - Found on: Batman: Arkham Knight (four shaders, 3,813 draws in a run to the diner). The same red line is recorded on FINAL FANTASY RESONANCE, ROMANCE OF THE THREE KINGDOMS 8 REMAKE, Luigi's Mansion 3 and Hyrule Warriors: Age of Calamity, none of them run with this rule.
- Check:
make -C dm/gfx/tests GAME=<id> check_t_cube_placeholderalso covers a 2D texture and one- and five-layer 2D arrays in atexture3dargument: an unselected fallback leaves the real volume's output alone, a selected one reads zero.
Multisample texture slots
- Symptom:
[RED] texture type mismatch: shader … declares slot … as Metal type 2, texture ID … is type 4 (NVN target 5, …); bound as is, for a shader whose MSL declares the slottexture2d_ms. - Cause: the reflection reader (
nvn_refl.mdummy_kind) had no rule fortexture2d_ms,depth2d_msand their arrays, so it recorded such a slot as 2D. The multisample texture the game binds there was reported as a mismatch although the binding was right; an unbound slot got a 2D zero texture, which a multisample argument does not take; and a handle pool for such a slot would be built of 2D textures. The dummy tables were also indexed by the Metal type masked with 7, where the 2D multisample array (8) shared the 1D entry. - Fix: the multisample types are read as
MTLTextureType2DMultisampleand2DMultisampleArray. Their zero textures are 4-sample private textures cleared by a render pass (dummy_tex; the integer classes as RGBA16, as the 128-bit formats have no multisample form), and the dummy tables have an entry for each Metal texture type. - Found on: Super Monkey Ball Banana Rumble: URP's
CopyDepth(a3d53d20b89e6015) reads the multisample depth buffer at the title. - Check:
make -C dm/gfx/tests GAME=<id> check_t_ms_slot: the reflection of each multisample type, the multisample dummies of every pixel class, the 1D dummy beside the multisample array's, and a kernel reading the float, uint and depth dummies through multisample arguments under Metal API validation (all samples 0).
Integer views for images a shader declares uint or int
- Symptom: translucent UI (frosted text bands, button guides, dialog headers) yellow and white.
- Cause: the composite shader loads the window texture's texel as
r32ui, unpacks the four bytes and stores the blend through a float view of the same image. The host bound the RGBA8Unorm texture to thetexture2d<uint>argument as it was, whose reads are undefined (Metal's validation layer does not check textures in argument tables). - Fix: an image slot the shader declares as uint / int now gets a view of the same texel size in that class (
img_fitinnvn_mtl.m). The format-view usage costs lossless compression, so a texture gets it only when a shader needs such a view: it is upgraded (copied into a texture with the usage) before the next draw pass opens, as the copy cannot run inside the draw's own pass; until then that one draw reads it as before. - Found on: FINAL FANTASY TACTICS - The Ivalice Chronicles: the last passes have no render target; fragment shaders composite each UI layer into the window texture with image stores, blending in software (
uirender.tec,4cf1975ed1e36590).
Float views for integer buffer images
- Symptom: a buffer image appears in both integer atomic and float load/store arguments. The float argument's format differs from the shader declaration.
- Cause:
img_bindingadapted only slots declared as integers. Metal leaves reads and writes through a mismatched texture declaration undefined. The game uses the same histogram bytes throughtexture_buffer<uint>atomics andtexture_buffer<float>loads and stores. - Fix:
img_fittakes a same-width float view of 32-bit integer buffer images usingtbuf_view_format. The view shares the storage and the original coordinate bias.check_t_buffer_image_biasverifies the format, the offset and the original bits through both views under Metal validation. - Found on: LEGO Star Wars: The Skywalker Saga. Clear
9a6b21facc9b346d, accumulationfd31a0e4ff650684, and reduction823aeb9661fb80ebshare the 36-word R32Uint histogram.
Image views of the type a shader declares
- Symptom: a compute pass's image stores are lost with no red line: the levels or layers it writes stay as they were. With
DM_NVN_PASSDUMP, itsWlines readtarget=3 shader wants target 2(a 2D array in a slot the shader declares 2D). - Cause: an image store or load carries its own dimension, as a sample does, and a non-array access of an array image reaches layer 0 of its view. Sampled slots get a view of the declared type (Compatible views for a mismatched declared texture type), but image slots adapted only the pixel class (
img_fit), so a one-layer 2D-array view went to atexture2dargument as it was, and Metal dropped the stores. - Fix:
img_fitmakes the image view with the shader's pixel class and its declared type together, with the layersfit_layersgives (the ruletex_fituses), from the texture under the bound view and without its channel mapping. A type no view bridges (a 2D array in a 3D slot, a multisample texture in a 2D one) is bound as is and logged once:image slot declared as Metal type … holds texture ID … of type …: no view bridges them.make -C dm/gfx/tests GAME=<id> check_t_image_typestores through a 2D slot into one layer and level of a 2D array and checks nothing else changed. - Found on: Mario Kart World (GitHub issue #1648): the blob shadows are two R8 2D arrays (64x64x128 and 128x128x64, one layer per character or vehicle); a compute pass writes each layer's mips through one-layer array views in slots its shader declares 2D. Levels 1 and 2 stayed zero, which showed once the depth downsample was right (
473c9026): the decal8206d20d0055515dread the zero mips at a distance and drew a dark box around each kart's shadow.
Buffer textures behind handles in uniform buffers, and rows of finalized descriptors
- Symptom: flat-coloured objects with no texture detail in an otherwise correct scene: the UVs and colours a vertex factory fetches from buffers read 0. Then
texture buffers bound as 2D rows … N times, about N madein the log, a Metal texture for nearly every bind. - Cause: with a handle in a uniform buffer the build has no descriptor to ask, so a buffer texture there is declared 2D and read in rows; only slots the translator recorded got the row form. And the rows were kept with the texture object, while Unreal Engine 5.4 finalizes its buffer texture objects and keeps using the registered IDs, as the API allows. Comparing the texture's address in the cache missed as well, as new descriptors view the same memory.
- Fix: any
NVN_RB_TEXUdeclared 2D takes the row form for a buffer texture. Rows are kept with the buffer texture while the owner holds it (a live or ghost entry, the sharing table; Texture views re-made for finalized textures every submission), and those of a texture it no longer holds by what they view (g_tb2_gone: buffer, offset, length, format), emptied with the pools. - Found on: Yoshi and the Mysterious Book: 13.1 million views made for 13.2 million binds became 1.08 million, with frame times unchanged at 16.7 ms.
sRGB textures loaded and stored raw through an image
- Symptom: the whole picture pale and washed out, its blacks lifted to grey (a frame's median luminance 0.46 against 0.16 in console footage, its darkest percent 0.18 against 0.01): bloom reads as a haze over everything and the dither of fine detail (Star Fox's fur) as grain. A pass dump shows a compute shader writing an
RGBA8_SRGBtexture (Metal format 71) through an image. - Cause: NVN's image loads and stores convert no sRGB, as OpenGL's image units do not (no sRGB format is an image format there), so a shader that stores an sRGB-encoded value into an sRGB texture's image leaves those bytes as they are; sampling decodes them later. Metal decodes a read and encodes a write through an sRGB format, and the host bound the texture's own Metal format to the image slot, so each stored value was encoded a second time. Star Fox relies on it: after DLSS (MetalFX here) its copy pass encodes the linear result itself (
35ebccc529cc58a9, flag 0x80) into itsRGBA8_SRGBtarget, so that the upscaler network (ddc729bcdb4c8df9), which samples that target, gets encoded colour, and the network stores its encoded output into theRGBA8_SRGBimage it fills (768x432 → 1536x864). Measured on one frame: MetalFX's output equals the decoded input (identity), the stored bytes are the twice-encoded output, and the displayed picture decoded once matches the console footage's percentiles within 0.02. - Fix:
img_binding/img_fit(nvn_mtl.m), for every game: an image slot holding an sRGB texture gets a view of its linear twin (pf_srgb_linear, theg_pfv_srgbpairs, which Metal views without the format-view usage), so loads and stores go raw; the sampled descriptor keeps the sRGB format. Log linesRGB texture bound as an image. The MetalFX stand-in for a game's upscaler (A game's own upscaler drawn by MetalFX) takes its output through the same binding; no game seen gives it an sRGB image (Donkey Kong Bananza's is R11G11B10F). - Check:
make -C dm/gfx/tests GAME=<id> check_t_image_srgb(Metal validation): RGBA8_SRGB and BGRA8_SRGB textures; the image view is the linear twin over the same writable storage, an image load returns the stored byte (0x80 → 0.502), a sampled read decodes it (0.216), and an image store of 0.5 keeps 0x80 (0xbc before). - Found on: Star Fox (update 131072), measured on a build of our fork: every frame after its DLSS pass; with it fixed, General Pepper's close-up in the intro matches console footage (luminance percentiles 1 / 50 / 90 / 99: 0.024 / 0.174 / 0.529 / 0.851 against 0.012 / 0.158 / 0.513 / 0.861), where before it was 0.175 / 0.456 / 0.747 / 0.933. Its bloom chain (separate textures 384x216 to 12x6, additive upsampling as the game sets it, 1/30 in the composite) and MetalFX's DLSS stand-in were measured unchanged by this.
Buffer textures read by 1D integer fetches (row wrap)
- Symptom:
texture type mismatch: shader declares 2, texture is 9; the slot read 0. - Cause: Maxwell fetches a texture buffer and a 1D texture with the same instructions (TLD with integer coordinates only, TLDS
Texture1DLodZero), and the bound descriptor decides which it is. Without PC reflection the translator has no type answer and reads such a slot as a 2D texture at(x, 0), and the host could only bind a dummy when the game put a buffer texture there. - Fix: the vendored translator (
InstEmitTexture.cs, markednxnative:) now addresses every such fetch as(x & 0x3FFF, x >> 14)and reports the slot (fetch1din the reflection). The host binds a buffer texture in a flagged slot as a linear 2D texture of 16,384-texel rows over the same pool memory (tbuf_as_2dinnvn_mtl.m,nvn_tbuf_rowsinnvn_tex.c), cached by texture serial beside the views. A real 1D texture, which the host creates as a single row at most 16,384 wide, reads as before. A mismatch no view can bridge is logged once per shader and slot, with its texture ID, NVN target and formats (tex_mis_note). - Note: limits: a size query on a buffer of more than 16,384 elements returns 16,384 (no shader both size-queries and fetches such a slot in Age of Calamity; the build summary counts them), and the rows stop at the end of the Metal buffer.
- Found on: Hyrule Warriors: Age of Calamity: 16,438 such shaders (98,970 bindings; slots 16–21 hold KTGL's light and decal lists).
- Check: Age of Calamity's 15-minute Mac battle bound 15.7 million of them through 320 row textures, none failed; the scene is darker and more saturated than with the zeros (mean luma 163 against 178 at the start of the battle), GPU time unchanged.
Integer buffer textures read through float slots
- Symptom: none of its own seen here. Pull request #984 reports GPU hangs from huge light counts on its build of the same game.
- Cause: with no type answer the translator declares a fetched texture float. KTGL keeps its light and decal lists in 32-bit integer buffers and takes the fetched bits back with
as_type<int>. Reading an integer texture through a float declaration is undefined in Metal. - Fix:
tbuf_as_2d(nvn_mtl.m) views a 32-bit integer buffer in a slot declared float as the float format of the same size (tbuf_view_format), so the shader reads the stored bits. - Found on: Pokémon Pokopia. No visible change in its tutorial area.
Integer textures read through float slots
- Symptom: none visible on an M6, where at most 0.23 % of pixels differ between paired runs. GitHub issue #783 reports wrong light offsets on an M2.
- Cause: as for buffer textures, but for a 2D texture: with no type answer the translator declares it float, and the shader takes the fetched bits back with
as_type<int>. The answer table cannot say otherwise, because the format is known only at bind time. - Fix:
tex_float_fit(nvn_mtl.m) binds the float view of the same size (tbuf_view_format) in a slot declared float. A texture made without the format-view usage is upgraded before the next draw pass (img_fit_upgrade). 32-bit formats only: a smaller integer format has no float view that keeps its bits. - Found on: Metroid Prime Remastered: the clustered lighting's R32Uint light grid (
fde1a3e769219a77and the other world materials). Reported and fixed by nobz226. - Check:
t_int_float_viewreads small integers (denormal floats), NaN patterns and negatives through the R32Float view in a compute shader and takes back every bit.
Private buffer texture fallbacks must not query CPU contents
- Symptom: Metal API validation aborts in
validateCPUWriteablebefore an unsupported buffer-texture copy can report its fallback. - Cause:
tbuf_shadowandtbuf_rows_copytested!buffer.contentsto detect CPU-inaccessible storage. Callingcontentson a privateMTLBufferis itself invalid under API validation; it is not a safe capability query there. - Fix: check
storageModebefore queryingcontents. Keep the existing warning and unsupported result: the shadow leaves the original view unchanged, while the row copy returns nil. This avoids the invalid API call; it does not make GPU-written snapshots coherent or make private misaligned textures render correctly. - Check:
make -C dm/gfx/tests GAME=<id> check_t_tbuf_accessuses real private Metal allocations and aligned buffer textures under API validation, with both encoder flags. The row case requests a larger row alignment; the shadow case registers a descriptor starting one element into its wider owning view and checks thattbuf_leadreaches the copy guard. Both unguarded helper paths abort; the guards preserve their explicit fallback without a CPU-access query. The fixture submits no unsupported texture to the GPU, and encoder-flag variation alone does not establish replay-thread concurrency. - Found on: synthetic tests during Ocarina of Time source review; no Ocarina crash or rendering artifact is attributed to this path.
Sampled BUFFER reads follow source writes and mappings
- Symptom: synthetic NVN readback sees an earlier producer's bytes after a deferred update or an active virtual remap, or reads early through a wrapped 1D fetch or a BUFFER descriptor table. These are API-level reproductions; no game artifact is attributed to them (issue #2247).
- Cause: the row bridge copied CPU backing before queued GPU writes completed; BUFFER pool and handle tables carried only the aligned view's resource ID, without its logical element lead. A sparse-mapping note invalidated registered views but left the serial/sharing cache on the old backing, including when a new serial first found that shared view. Deferred-update conflicts checked handles and uniforms, not sampled BUFFER storage.
- Fix: retain live aligned views and the existing image read/write/atomic support. Wrapped fetches add the lead before splitting the linear index into 16384-texel rows; their offset metadata also carries logical width for bounds and size queries. BUFFER tables retain the resource-ID layout and carry parallel element leads, located by the header word at
DMSH_POOL_BIAS; queued BUFFER tables are immutable. Existing sparse notes refresh backing through the owner replacement mechanism. Overlapping deferred updates land before sampled BUFFER consumers through the existing conflict check. No sampled GPU snapshots, new owner registry or writable sinks are added. - Check:
make -C dm/gfx/tests GAME=<id> check_t_tbuf_liveuses public builders, registration, recording, queue replay and GPU-gated literal readback, under both encoder flags and Metal validation. It covers ordinary typed reads, live rows across the 16384-texel boundary, private row sources, active same/new-descriptor remaps, pool/handle tables with an exhausted walk budget, and in-pass updates through a second descriptor pool. The initial current-main fixture had ten wrong-output checks; isolated new-serial and exhausted-budget controls exposed three further failures before their fixes.test_image_atomic_bounds.pychecks actual translated row coordinates and compiles row, typed-buffer and nested/forwarded BUFFER table shaders for Mac and iOS. Existing buffer-image, handle and view-lifetime tests cover the retained paths. - Limits: legacy bindings without offset metadata retain their existing fallback. This does not add same-operation sampled/write ordering, GPU-written handles resolved on the CPU, or CPU-post counter/report ordering. Native iOS runtime and game-artifact attribution are unproved.
- Found on: synthetic source review during Ocarina of Time investigation; its floor/glow reports are not attributed to these paths.
Buffer textures at offsets below 16 bytes
- Symptom: particle effects drawn at the wrong scale or place, or flickering, where the particle data is a buffer texture at a pool offset that is not a multiple of 16; log line
buffer texture at pool offset …, below Metal's 16-byte alignment. - Cause: Metal makes a texture buffer view only at an offset that is a multiple of the device's alignment for the format (
minimumTextureBufferAlignmentForPixelFormat,minimumLinearTextureAlignmentForPixelFormat: 16 bytes on an M4 Pro, more on an iPhone), and an Apple GPU addresses a view created at a smaller offset from the boundary below it: on an M4 Pro, R32Float views at offsets 4, 8 and 12 read element 0 where elements 1, 2 and 3 are expected, for every format and width tried, shared and private buffers, bound directly or in an argument buffer (t_tbuf_align). The host used to create the view at the offset anyway, a view Metal does not define (Metal validation stops at it:Offset of a buffer-backed texture … must be aligned to 16 bytes). NVN places buffer textures at any element-aligned offset, and no Metal view can start there. - Fix: every buffer texture's view starts at the aligned boundary below its offset, wider by the elements in between (
tex_mtlinnvn_mtl.m; their count istbuf_lead), so every view is one Metal defines. A shader moves its coordinates by that count from its offset table, bankDMSH_TBIAS_BANK, as long as the entries it uses (up toDMSH_TBIAS_SLOTS, 512): an image slot (Buffer images below the 16-byte alignment), a single texture slot or uniform-buffer handle whose type the translator knows (NVN_RB_TBUF,NVN_RB_TBUFU), and an array of buffer textures (tex_dyn_slots' slot arrays,NVN_RB_TEXD; the driver table's arrays,NVN_RB_TEXA), one entry per element, which an access picks by the same index as the texture. Its fetches move, and its size query gives the view's width less the count. All of them read the pool's own bytes in place, so they see the GPU's writes. A shader whose buffer textures would take more than the table's entries reads the rest through a copy of each texture's own bytes at an aligned offset of a shared staging block (tbuf_shadow), made at its first binding in each submission: a fallback with the old gaps (a GPU write in the same submission is not seen; a texture in a pool the CPU cannot access is read early,[RED]117). Buffer textures never reach a texture pool or a uniform buffer's handle table (pool_arraysindmsh_reflect.pykeeps them as slot arrays); if one did, it would be read early ([RED]167 once). A wrapped 1D fetch (a slot without a type answer, read as 2D rows: Buffer texture rows at a pool offset the device will not view) takes the rows from the texture's own offset. Checked:t_buffer_image_bias(withDM_TBUF_ALIGN=16, under Metal validation: the view from the boundary below, reads in place, an array read element by element by its entries, the copy, the size),test_image_atomic_bounds.py(test_buffer_texture_fetch_and_size_moved: the fetch's coordinate and the size query through the table, with the rebuilt translator),test_dmsh_reflect.py(the table's length, single bindings and arrays). - Found on: Octopath Traveler 0: one at pool offset
0x168, read by its particle shaders (Texture slots picked at run time,shaders.md). FINAL FANTASY RESONANCE: particle data at offsets 4, 8 and 12 past the boundary (village fires, smoke).
Buffer images below the 16-byte alignment
- Symptom: walls, floors and props vanish and come back from frame to frame in Assassin's Creed II (the Abstergo elevator corridor, the background of Ezio's birth scene); before the fix the log had
[RED] image buffer texture at pool offset …, below Metal's 16-byte alignment: shader writes to it land at the 16-byte boundary below. Forcing occlusion queries visible (DM_NVN_VIS_ALL=1, a probe of PR #1399's author, never on main) does not help. - Cause: the game's occlusion culling draws each object's bounding box, and fragment shader
f17624f1613d0321marks "object k visible" in a 4096-entry R32 image buffer, one of three it rotates through, two of them at pool offsets 8 mod 16. A buffer texture view below Metal's alignment is addressed from the 16-byte boundary below its offset on an M4 Pro (Buffer textures at offsets below 16 bytes), so in those frames every mark landed two objects early and the game culled visible geometry. Reads through texture slots already went through an aligned copy; image loads, stores and atomics did not. An M6 (macOS 27.2) writes through such a view at the offset itself (t_buffer_image_biasprints where), so the symptom depends on the GPU. - Fix: the shader moves each coordinate of a buffer image by an element offset the host gives it. The translator (
TranslationFlags.MetalBufferImageBias,Instructions.csBiasBufferImageCoordinate) gives each buffer image of a shader an index in an offset table, bankDMSH_TBIAS_BANK(dmsh_abi.h), adds that entry to every load, store and atomic coordinate of the image, and leaves a coordinate from minus the offset to -1 as it is, outside the image as on the GPU;Program.csexports the index (tbx), whichdmsh_reflect.pygives the image's binding. The image's own view starts at the aligned boundary below its offset, wider by the elements in between (tex_mtlinnvn_mtl.m, Buffer textures at offsets below 16 bytes), and the host fills the table (NVN_RB_TBIAS) inencode_argswith that count (tbuf_lead). The shader works on the pool's own bytes, so the rest of the pass sees its writes, with no copies and no limit. A buffer image in an array of images, or past a shader's 16th, keeps the old addressing ([RED]once at the binding). A shadow copied in before the pass and back after it (the first version of PR #1399) cured the flicker too, but held at most 8 such images a pass, copied back over other writes to the same bytes in the pass, and split a render pass at a shadow's first use. Checked:t_buffer_image_bias(the view, the offset, writes at elements 0 to 15 landing on their own bytes, nothing written before or after, coordinates -1, -2 and 16 dropped),test_image_atomic_bounds.pywith the rebuilt translator on the GPU (buffer image atomics at element offsets 0 and 2, the words before the image untouched; load and store coordinates through the table),test_dmsh_reflect.py. - Found on: Assassin's Creed: The Ezio Collection (0100670014482000, update 1.3; not in the games table), brought up in NX2Apple by the author of GitHub PR #1399, who found the cause and confirmed the shadow fix in the game. This fix has not been run in the game.
Buffer texture rows at a pool offset the device will not view
- Symptom: lighting that alternates between lit and unlit from one frame to the next on an iPhone, the same scene steady on a Mac; log lines
texture buffer (texture ID …, … at pool offset …) has no 2D-row form for a wrapped 1D fetch: the slot reads 0andtexture type mismatch: … a buffer texture: the slot reads 0 (dummy). - Cause: row wrap views a buffer texture at its pool offset, and Metal views only at a multiple of
minimumLinearTextureAlignmentForPixelFormat, which is per device: 16 bytes for 32-bit formats on an M6 Mac, 32 on an M1 Pro, larger on an A17 Pro. Three Houses keeps two copies of its light list 32 bytes apart, so on the phone one copy was bridged and the other read zeros, and the picture alternated with the list (the two copies alternate per rendered frame, which is why no present-interval or frame-rate setting changed it). - Fix:
tbuf_as_2d(nvn_mtl.m) copies the rows of a buffer texture at an unaligned offset into the submission's arena (tbuf_rows_copy; 256-byte offsets, already resident, recycled once the submission is done) and reads the 2D rows there, one copy per texture per submission; rows at an aligned offset are untouched. The copy's cost is counted in the periodictbuf_as_2dline (… copied into aligned rows (N MB)). This is a workaround for the platform limit, with the gaps of the 16-byte case above, open: the copy holds what the CPU wrote before the submission was encoded, and a buffer in a pool the CPU cannot map still reads zeros ([RED]once). The shader-side element offset named there would close them here too. - Found on: Fire Emblem: Three Houses: its lighting flickered on an iPhone 15 Pro class device, its two light-list copies 32 bytes apart.
- Check: on an M1 Pro with
DM_TBUF_ALIGN=64, a Mac that cannot see the problem otherwise:[RED]lines naming the same shaders and slots as the phone's log on the base this was found on (18 of them,094a2d11253f126c_bslots 18/19/20,f54830a75e07e14a_bslot 20,6797af67f88a4ddd_bslot 0), and a static terrain patch that stops being static —YAVGtwo values 0.008 apart alternating frame to frame, against one value for 12 frames with the alignment the Mac reports. With the copy in, the same forced alignment fails nothing, copies 5,058 times over the run (4,592 MB, about 2 copies and 2 MB a frame) and leaves the single value the aligned path gives; with the Mac's own alignment no texture takes the copy. Three Houses' own frames on the phone then hold 60 fps with the flicker gone. - Not checked: another device's alignment (the value is read, not assumed); a game whose such buffer is written by the GPU in the same submission (the copy would be stale).
Automatic block height truncates
- Symptom: torn digits and a background in blue steps (Rhythm Heaven Groove's latency calibration).
- Cause: NVN chooses the automatic block height by truncating
height_in_blocks * 1.5 / 8, whilenvn_tex.crounded the division up, so some sizes (a 160×160 BC3 texture: H3 instead of H2) were read with the wrong layout; Rhythm Heaven Groove's BC7 textures without a packaged layout were read with the wrong block height. - Fix: truncating height in blocks × 1.5 / 8, as MacNativeGames found:
nvn_tex.cnow truncates for every game (pick_tile(ah * 3 / 16)). It changes layouts at 6–10, 17–21, 38–42 and 81–85 block rows, which matters only for data the game lays out itself (no packaged layout: Tears of the Kingdom's flushed textures, Monster Hunter Rise's sparse ones); those were not re-checked. - Found on: found by MacNativeGames on The Legend of Zelda: Tears of the Kingdom (listed there as open); confirmed by Rhythm Heaven Groove on its two 40-block-row textures (two BC7 textures): the rule matches every size checked by eye: 672×160 and 1232×160 (40 block rows: 4 GOBs, where rounding up gives 8), and 112×112 (4), 288×208 (8) and 880×432 (16), where both roundings agree and
floor(rows / 8), the other rule that fits 40 rows, does not; and by Touchable (a d2r-mobile port of Tears of the Kingdom) on 16 of its texture files. - Check: a dump of the guest bytes deswizzled in Python with 1 to 16 GOBs and decoded with
texture2ddecodershows the right one by eye; a smoothness score does not, because a block height too tall reads padding and looks smooth. - Not checked: the games whose textures the game lays out itself (above).
Sparse textures laid out in 64 KB tiles
- Symptom: magenta (the ASTC error colour) on streamed textures in a sparse pool;
DM_NVN_ZBLOCKfinds such textures (all-zero blocks). - Cause: sparse textures have a layout of their own: they are mapped in 64 KB tiles, one row of blocks 128 GOBs / (block height × block depth) wide. The game's files hold its streamed textures pre-swizzled that way, and it places each level at the offset the host reports; the host laid them out unpadded.
- Fix:
nvn_tex.clevel_walk: a level at least one tile wide, high and deep is laid out with its width padded to whole tiles, the levels from the first smaller one on form the mip tail (packed as usual), and the storage is whole tiles, 64 KB aligned. - Found on: Monster Hunter Rise: laid out unpadded, the 1024×1024 ASTC 6×6 clothes of Hinoa and Minoto (43 GOBs wide instead of 48, level 1 at 0x81000 instead of 0x90000) read 2,183 all-zero blocks in level 0 and 3,043 in level 1, which ASTC decodes as its error colour: their trousers, sleeves and gloves were magenta, worst in Kamura Village.
Packaged textures carry width alignment as well as height and depth
- Symptom: a fixed magenta rectangle over part of a packaged ASTC texture (Bayonetta Origins' tutorial-card background), the same in every frame.
- Cause:
SetPackagedTextureLayoutwas kept only as byte 0 (block height and depth) in the texture description. Byte 1's low nibble is log2 of a width alignment in GOBs: the levels at least one tile (that many GOBs wide, one block high and deep) in size are padded to whole tiles, as a sparse texture's are to its 64 KB tiles, the levels from the first smaller one on form the mip tail, and a layered texture's layers align to the whole block times that width. It applies whether or not the texture isSPARSE. Without it a texture whose width is not a whole number of tiles was laid out too narrow: its rows from the second block row on, its later levels and layers read from the wrong place, and the padding they read, all-zero ASTC blocks, decodes as magenta. - Fix:
nvn_tex.c(packaged_width_log2,level_walk,layer_bytes):nvn_texdesc.pkg_layoutholds byte 0 and the width nibble, and the width alignment pads the tiled levels and aligns the layers. A layout with a width nibble of 0 is laid out as before; flags and the sparse tile layout the game reads are unchanged. The[nvn] packaged texturelog line prints the width alignment. - Found on: Bayonetta Origins: Cereza and the Lost Demon (
0100CF5010FEC000, 1.0.0, no profile in the repository): the 2052x1026 ASTC 6x6 tutorial-card background (byte 0 3, width 4) is 96 GOBs wide and 0x120000 bytes; laid out 86 GOBs wide (0x102000) its rows from y 384 on read ten GOB columns of padding, the 240-pixel-wide magenta rectangle. Checked on an iPhone (PR #2268). The packaged layouts logged in nine other games' runs all have a width nibble of 0. - Check:
t_tex_layout(width 0 and 4, a mip tail, an array and a cube; the width-4 shapes fail without the fix) andt_nvn(the builder keeps the nibble, the flags and sparse tile layout are unchanged). The author compared the layout with the SDK's own arithmetic on 37,296 shapes and replayed the game's texture on the GPU; neither is in the repository (they need the game's files).
Sparse textures take the block height of their 64 KB tile
- Symptom: a CPU-filled texture shuffled into a patchwork of rectangles (OCTOPATH TRAVELER's world map on the traveler selection).
- Cause: a sparse 2D texture without a packaged layout is laid out with the block height of its 64 KB tile, whose shape in blocks is the standard one: 256×256, 256×128, 128×128, 128×64 and 64×64 blocks for 1, 2, 4, 8 and 16 bytes per block, i.e. 32, 16, 16, 8 and 8 GOBs. The host used the automatic block height: 16 GOBs for the 4096×2048 BC1 map (512 block rows), whose tiles then landed in the wrong places.
- Fix:
nvn_tex.csparse_tile_hgives such a texture its tile's block height; a packaged layout still wins. - Found on: OCTOPATH TRAVELER (Unreal Engine 4.18 flags its streamed and CPU-loaded textures sparse).
- Check: the map's guest bytes deswizzled in Python at 1 to 32 GOBs read right only at 8; a 512×512 RGBA8 sprite sheet only at 16; Monster Hunter Rise's packaged ASTC 6×6 textures (16 bytes per block) carry 8 in their layout. The 1- and 2-byte heights follow the same tile shapes and were not seen.
Sparse 3D textures take the standard 3D tile
- Symptom: none visible on an M6 on the Frigate Orpheon's deck. Laid out 1 GOB high, the mapped tiles of a streamed 3D texture fall in scattered places, so lookups read zero in the holes; GitHub issue #783 reports a black gunship hull in the opening on an M2.
- Cause: a sparse 3D texture without a packaged layout took the automatic layout (1 GOB high, 32 GOBs deep). Its 64 KB tile is the standard 3D shape: 64x32x32, 32x32x32, 32x32x16, 32x16x16 and 16x16x16 blocks for 1, 2, 4, 8 and 16 bytes per block.
- Fix:
nvn_tex.csparse_tile_h3,sparse_tile_d3give such a texture its tile's block height and depth when level 0 is at least one tile in each direction; a packaged layout still wins, and a smaller texture keeps the automatic layout.nvnTextureBuilderGetSparseTileLayoutanswers the same shape. - Found on: Metroid Prime Remastered: its six 512x256x368 lighting volumes map the same tile indices whichever shape the host reports (256x32x16 or 128x64x16 texels for BC1), so the game's layout is fixed. With this shape BC1's tiles 5-7 and 9-11 of a 16-slice slab and BC6H's 10-15 and 18-23 are the same texels, 128..512 x 64..192. With 1-GOB blocks they were two different patchworks. Reported and fixed by nobz226.
- Check:
t_sparse_layoutfills those tiles of both formats and decodes exactly that box, in exactly that slab, plus the tile shapes of 1, 2, 4 and 8 bytes per block. Only 8 and 16 bytes per block were seen in a game; the others follow the same table. Metal cannot confirm the shape:sparseTileSizeWithTextureType:gives a 3D texture the 2D tile with depth 1.
Sparse textures of 8- and 16-byte blocks: blocks at most 8 GOBs high
- Symptom: crashes that move between runs (30–70% of boots, in the first minute): in the allocator, on bogus pointers, in unrelated threads. Unreal's purgatory proxy (05-debugging) finds freed 64 KB-aligned blocks modified; with the parked blocks read-only, the faulting store is a
memcpyof texture mip data from the texture streamer into the bufferRHILockTexture2Dreturned. - Cause: with the automatic block height the host gave sparse textures the same block height as plain ones (16 GOBs for 96 or more block rows), so a 64 KB tile was 8 GOBs wide. For 8- and 16-byte blocks (DXT1, DXT5 and the like) the real layout uses blocks of at most 8 GOBs and so tiles 16 GOBs (1,024 bytes) wide: the game's pre-swizzled data for a 384×384 DXT5 level is 32 GOBs × two 8-GOB block rows, 0x40000 bytes, where the host's layout said 0x30000 (the padding sits at the end of each 8-GOB block in the dump). 4-byte texels keep 16-GOB blocks (a 1350×270 BGRA8 level is 88 GOBs × three 16-GOB block rows, 0x210000 bytes). Unreal's NVN RHI sizes its lock buffer from the host's level layout and copies the cooked level in at its own size, past the end of the buffer.
- Fix:
nvn_tex.csparse_tile_h(see Sparse textures take the block height of their 64 KB tile): a sparse texture without a packaged layout and with 8 or 16 bytes per block takes 8-GOB blocks.dm/gfx/tests/t_sparse_layout.cchecks 15 measured textures and Monster Hunter Rise's level offsets. - Found on: Yoshi's Crafted World: 9 streamed DXT5 textures (384×384 to 1920×912) overran their buffers by 0x8000–0x20000 bytes; after the fix none of 10,578 level copies did, and 10 of 10 boots ran clean.
Sparse textures smaller than a tile keep the automatic block height
- Symptom: a small CPU-filled sparse texture shows part of its image beside fragments, cut off at the bottom (Yoshi's Crafted World's loading icon: the left half of a chalk drawing and two stray strokes).
- Cause: a sparse texture smaller than one 64 KB tile in width or height is all mip tail, laid out as a plain texture with the automatic block height, but the host gave every sparse texture its tile's block height. The 192×160 DXT5 icon (12 × 5 GOBs, under the 16 × 8 GOBs of a 16-byte tile) is laid out in 4 GOBs and was read with 8; a 384×384 DXT1 (12 GOBs wide, under the 16-GOB tile width, 96 block rows) in 16, also read with 8. The storage sizes stay the same, so only the picture shows it.
- Fix:
nvn_tex.cnvn_tex_layoutgives a sparse texture its tile's block height only when level 0 is at least one tile wide and high, the testlevel_walkuses for padding; the tile's shape for that test and fornvn_tex_sparse_tilescomes from the block size (tile_shape_h), not from the block height the texture got.t_tex_layout.cchecks both block heights and the icon's tile shape. - Found on: Yoshi's Crafted World: the guest bytes of the icon and of the DXT1 deswizzled in Python read right only at 4 and 16 GOBs; its 384×384 DXT5 (24 GOBs wide, at least one tile) still reads right only padded to 32 GOBs at 8.
Sparse textures bound from their first mapped level
- Symptom: streamed textures read 0 (magenta on Monster Hunter Rise's title screen's clothes).
- Cause: the translator drops TEX's LOD clamp and its residency predicate, so streamed textures were sampled at levels the game had not mapped yet.
- Fix: a sparse texture is bound as a view starting at its first level whose pages, and those of every smaller level, are all mapped (
sparse_viewinnvn_mtl.m). That samples exactly as a minimum LOD would; the view follows each upload. - Found on: Monster Hunter Rise.
Texture views of a sparse texture bound from a later level
- Symptom:
[RED] texture view id … starts at mip 2 beyond 1 levels(or mip 1), once per run, for a streamed texture; views from level 1 of such a texture read the level after it. - Cause: a sparse texture is bound as the view of its levels from the first mapped one on (Sparse textures bound from their first mapped level), so its host texture's level 0 is NVN level
vbase. A texture view's levels count from NVN's level 0, andtex_by_idtook them as the host texture's: a view from a level past the host texture's levels was left out (an empty slot), and one from an earlier level read a smaller one. Resident Evil 4 samples its streamed 512x512 and 1024x1024 textures, with only their two or three smallest levels mapped as the title loads, through views of levels 1 + 0 and 2 + 0 (30 such views at frame 1530, all of them sparse). - Fix:
tex_by_idcounts the view's levels from NVN's level 0 (tex_level_shift) and samples levels finer than the first mapped one from it, as the texture's own binding does. - Check:
make -C dm/gfx/tests GAME=<id> check_t_sparse_pool_cache: a three-level sparse texture with level 0 unmapped, read on the GPU through views from levels 1, 2 and 0. Without the fix the first two fail (the level 1 view reads level 2, the level 2 view the dummy). Resident Evil 4's opening to the forest path on the Mac (Apple M6, 2026-11-13): no such line. - Found on: Resident Evil 4.
Sampler reduction (min / max)
- Cause: a sampler built with
SamplerBuilderSetReductionFilter(min / max) was averaged by the host. Metal 26 has the same thing (MTLSamplerDescriptor.reductionMode), but ignores it with a nearest or no mip filter. - Fix: reduction samplers filter mips linearly (
samp_by_id): at the integer LODs reductions are used with, that is the same level. - Found on: Pokémon Legends: Z-A: its depth pyramid is built with a min-reduction sampler (
SamplerBuilderSetReductionFilter 1;151607c7a92386ccsamples the level above at an explicit LOD).
Sampler LOD bias
- Symptom: textures a mip level sharper or blurrier than on the Switch where the game biases its sampler; in the Vulkan layer, a red line
sampler LOD bias … not implemented. - Cause: the host kept NVN's
SamplerBuilderSetLodBiasand Vulkan'smipLodBiasbut never gave them to Metal, taking them for something Metal samplers lack. Metal 26 hasMTLSamplerDescriptor.lodBias(range −16 to 15.99). - Fix:
samp_by_id(NVN) andvkCreateSamplerset it, clamped to that range (Vulkan to the ±15 the device reports asmaxSamplerLodBias). - Found on: Super Mario Galaxy (the Vulkan red line). MacNativeGames uses the property for its own MetalFX bias, which pointed to it.
Border colours Metal has no sampler state for
- Symptom: whatever a game keeps in a texture that it samples past its edge with clamp-to-border reads the wrong value there: grass flattened along Link's path in Tears of the Kingdom, its bend map filled with "bent" wherever the window scrolled.
- Cause: NVN's
SamplerBuilderSetBorderColortakes any RGBA colour;MTLSamplerBorderColorhas transparent black, opaque black and opaque white only, andsamp_by_idtook the nearest of them. Tears of the Kingdom's border (0.5, 0.5, 0.5, 0.5) became (0, 0, 0, 0). - Fix: a filtered sample is linear in the border colour, so two samples through samplers that differ only in their Metal border colour give the exact one: r = s_n + (s_w − s_n)·k, k = (B − Bn) / (Bw − Bn) per channel. The build (
dmsh_rewrite.py border_emu) wraps every sample through a sampler member of the argument buffer indm_bs(…), adds a twin sampler member<member>_wfor each, and one blockdm_border(a mask word, then k per sampler;DMSH_BORDER_*indmsh_abi.h). The host (nvn_border.h) keeps the nearest Metal colour for the sampler and makes a twin only for a colour Metal lacks when a wrap mode reaches the border and no min / max reduction is set;encode_argsbinds the twin and sets the sampler's bit and k, and binds the shared zero bank as the block otherwise. The twin sample runs only for those samplers. A pipeline whose draw or dispatch binds no sampler with a twin is built without the corrections (details). The readable-tile variants (dmsh_fetch.py) replace a wrapped sample whole, so a tile read is never corrected. - Not covered: samples through sampler arrays,
sample_compareandgather, and samples of integer textures (not filtered; their border colour is an integer one) keep the nearest Metal colour; so does the Vulkan layer, which has its own translation. - Found on: The Legend of Zelda: Tears of the Kingdom: the grass bend map, a 256×256 RG8 window that follows Link, advanced by
ff9def5b3c418851with wrap 5 and border 0.5. - Check:
t_border(nvn_border's choices for opaque, translucent and Metal's own colours, and the registry's twins) andtest_dmsh_border.py(the rewrite, the reflection, the readable-tile variant, the compile for macOS and iOS, and withmake check_t_borderthe GPU: corrected samples against Maxwell's bilinear filter with the border colour, and Metal's nearest colour with the mask clear).
Unused border corrections retain sample registers
- Symptom: material pipelines spill registers even when every sampler uses a native Metal border colour.
- Cause: the uniform mask branch in
dm_bskeeps the twin sample's operands live even when no draw needs the correction. - Fix: every shader that corrects a sample exposes
dm_border_off(DMSH_BORDER_FC, 216). An undefined constant preserves the corrections.border_needchecks registered sampler parameters before lazy Metal sampler creation;pso_key.borderdistinguishes draws that need corrections. Binding a sampler, or changing a handle a uniform buffer holds, does not mark the pipeline dirty, so each draw comparesprog_borderwith its last pipeline's and fetches again when it changes (found by the iPhone port, PR #1073); with no twinned sampler registered that is one atomic load a stage. Vertex, fragment, task and mesh stages, including the vertex-pulling replacement, and compute dispatches (cps_new_b) specialize the constant to true only when none of their corrected samples needs a twin. Metal hands out oneMTLFunctionper function content, device-wide (newFunctionWithName:on the same library, or on another library loaded from the same data, returns the same object on macOS 27.2), and the host keys a function's Metal 4 descriptor and its MTLDevice specialization by that object (fn4_note,fn_dev); noting the new constants on the shared object would have taken the corrections from every draw of that shader. So the variant is not a function object: whoever builds a pipeline says which one it builds (theoffargument ofpso_build,pso_build_ex,pso_build_dev,cps_new_band the mesh pipelines, always!pso_key.border), a descriptor always holds the shader's own function, and the base key carries the variant (pbase_key.off).fn_offmakes the variant's descriptor, copying the constants the function was noted with (alpha test, logic operation, merged outputs) and cached by that descriptor;fn4_of_bandfn_dev_bgive the Metal 4 descriptor and the device function of either variant. A function whose entry point does not declare the constant has no variant, and a failed device specialization keeps the corrections. Generated geometry entries record their descriptors throughgeo_mesh_entry. Pair prebuilds use the same border-off specialization (pre_fn), and so does the offline pipeline archive (pso_offline.pyHOST_CONSTANTS: metal-tt specializes a<key>_bor<key>_bpfunction, and the host finds the base by its specialized descriptor), so the pairs stay in the app's archive. Older serialized rows read as border-off and live draws needing corrections have a different key.DM_NVN_BORDER_KEEP=1keeps the corrections in every pipeline (diagnostic;abalternates it withDM_AB). A compute shader with constants is loaded like the other stages (fn_spec):cps_newlooks its pipeline up by the specialized descriptor, in the bundle and the device's archives, builds it through the MTLDevice fromfn_dev_b's specialization on a miss and captures it; compute pipelines are keyed by shader and variant (cps_key), and the prewarm builds the border-off one. Geometry kernels keep the corrections (fn_dev). Sampler arrays, gathers and comparisons retain the existing limitations described above. - Found on: Ocarina of Time: its 1080p material passes spilled 300-400 bytes a thread; in-process A/B on a MacBook Air M4, 1.8 ms of a 26.5 ms frame (1.5 ms in the render stages, the rest in its kernels, NDSR's network among them). Splatoon Raiders and Donkey Kong Bananza on an M1, measured with the corrections taken out of the source at build time (PR #1203), not yet with the constant: Splatoon's
c0ae76e0ca76b574spilled 592 bytes a thread and none without them, a 236-draw 1920x1080 pass 20-21 → 9.3 ms and the frame 31.6 → 19.8 ms; Bananza's6f9fd9cb5fbc873b336 → 160 bytes, its heavy area's scene pass 5.1 → 3.2 ms. - Check:
t_pso_skeycovers old row lengths;t_border --cpucovers first use before sampler creation, per-stage bindings and sampler re-registration. The GPU cases int_bordercheck preservation of existing constants, the variant's own descriptor and device function, the original function and prewarm specialization, each on a kernel of its own content, alongside the existing filtered-border samples. The rewritten kernel oftest_dmsh_border.pyruns on the GPU throughcps_new, with the corrections and without them (cps_new_b).test_pso_offline.pychecks the constant names and the specialized bases and compute pipelines.
Texture fields Metal refuses
- Symptom: the process ends at once (the window vanishes), with
-[MTLTextureDescriptorInternal validateWithDevice:]failing an assertion such asrequests 9 mipmap levels, but the dimensions (1, 1, 1) can only support 1, orsampleCount must be > 1 for multisample textures. - Cause: NVN takes texture fields Metal refuses, and Metal aborts instead of returning nil: more mip levels than the size holds (on NVN the extra levels are 1×1), an array or 3D texture of no layers, more than 2048 layers (a 1D array's layer count is its height, which the size check let through), and sample counts the GPU lacks (an M4 Pro has 1, 2 and 4; NVN also has 8 and 16). A blit at a level the Metal texture lacks is not checked either.
- Fix:
tex_descmakes such textures with the levels their size holds and one layer for none. Textures of more than 2048 layers, and multisample textures of one sample or of a sample count the GPU lacks, are not made, as textures past Metal's size limits are (fewer samples would leave shaders reading sample indices past the texture). A red line names each case once. Copies andReadTexelsat a level the host texture lacks are skipped (tex_level_ok). Retail data is within every bound except, possibly, 8- or 16-sample targets. - Found on: reported by MacNativeGames (
f864eb0): a mod's 1×1 texture in Tears of the Kingdom declaring 9 levels. No game here is known to reach it; the sample counts (an M4 Pro has 1, 2 and 4, and a multisample texture of one sample aborts) were checked on that Mac while porting the fix. - Check:
t_view_levelsmakes each case with Metal's validation layer on: a 1×1 texture of 9 levels, a 3D texture whose depth holds the levels, an array of no layers, a 1D array of 4,096 layers, an 8-sample and a 1-sample multisample texture, and a copy at a missing level.
Unreal's texture streaming pool
- Symptom: in an Unreal Engine game, textures and lighting turn blurry and muddy about a second after an area loads and stay that way, whatever the frame rate, render scale or upscaling; no red line.
- Cause: not the host: the game's own budget. Unreal's texture streamer keeps at most
r.Streaming.PoolSizemegabytes of streamed mips resident and drops the top mips of what is in view once it is past them; lightmaps stream too, so the lighting goes flat with the textures. The game's Switch device profile sets the pool (DRAGON QUEST VII Reimagined: 200, and 1000 on Windows), so the Switch looks the same. The host's texture sizes, which the streamer counts, follow the NVN driver's layout (nvn_tex_layout). - Fix (an improvement over the Switch): the profile key
ue_texture_pool <MB>(DM_UE_TEXTURE_POOLoverrides) raises the variable to that size whenever the game sets a smaller one; a larger value, or −1 (no pool size), stays (hle_uecvar.c, on every present). Unreal's streaming manager reads the variable again when it changes (DRAGON QUEST VII Reimaginedmain+0x342230: game thread copy, MB → bytes, into the pool size thatmain+0x4d98b00reports to the streamer), so a write at run time takes effect. The variable is found by its name, with no address per build: the rewriter names it in main's fixups (Unreal's frame limit and present interval, found by name); until 2026-10-30 the host searched for it on the first present (dm_ue_cvar, 35 ms). It applies on the Mac; on iOS onlyDM_UE_TEXTURE_POOL(Documents/env.txt) turns it on, until an iPhone run shows the memory fits. - Found on: DRAGON QUEST VII Reimagined (GitHub issue #589). The rewriter finds the pool in every Unreal main on the drive: OCTOPATH TRAVELER and Yoshi's Crafted World (UE 4.1x, UTF-32), Pikmin 4 (4.26), OCTOPATH TRAVELER II and DRAGON QUEST VII Reimagined (4.27), Octopath Traveler 0 (UE 5) and FINAL FANTASY RESONANCE (5.6).
- Check:
t_uecvar(the variable named in main's table, or not; the value raised, kept and left); the search itself,test_ue_cvar.py. On a Mac run,DM_CTLcvari <main offset> <MB>sets the pool while the game runs, for an A/B at one spot.
Models black for one frame when a streaming step replaces their textures
- Symptom: large static and mesh-shader models (Ocarina of Time's castle town wall, rocks, trees, Lon Lon Ranch's barn) draw black for exactly one frame, with the fog in front and the terrain untouched, in pairs four or five frames apart; a few times a minute in play, at fixed places of a route.
- Cause: the models' shaders read their textures through the bindless pool table (
pool_gpu). When a walk writes an ID's entry (pool_entry) it makes the ID's Metal texture if it fits the walk's room (pool_room, withinpool_budget()), or, whatever the room, if a shader has read the ID (pool_seen, underPOOL_REQ_BYTES); otherwise the entry is the dummy (black), andpool_seen_scanmakes the texture after the first read. In Ocarina of Time the room is always 0:pool_budget()is a twentieth of Metal's working set (909 MB on a 24 GB Mac) against 15-18 GB ofcurrentAllocatedSize, so only read IDs are made ahead.mtl_reg_texcleared the mark whenever the game registered another texture into the ID, so when the game's streaming replaced the 17 textures of a material set at once (3-7 MB each, finalizing the old texture first; each step registered twice, 4-5 frames apart), the replacements counted as unread and their first reads found the dummy, one frame per registration. - Fix: the read mark is the ID's, not its texture's: it stays while the ID holds a texture and is cleared only when the ID is emptied, so the next walk makes a replacement under the read budget. A render target no pass has written stays the dummy all the same (
pool_unwritten_target), which is what kept transient targets from being made ahead. A texture streamed into an ID no shader has read yet is not covered by this: its first read finds the ID's stand-in (next entry). - Check: a replay of a route past the castle town wall, counting single-frame dips of a per-frame luminance grid, each checked by picture: 4-5 flagged per run before (2-4 at the wall's streaming steps), 0 after (PR #2022);
t_pool_chunkschecks which registrations keep the mark,t_pool_seen_replacethe replacement's pixels in the first table with the walk's room at 0 (a live replacement, one after Finalize, one for an ID whose texture waited for the read budget). - Found on: The Legend of Zelda: Ocarina of Time (a player's recording, M4 Pro, macOS 27.0.1).
Render targets, passes and clears
A streamed texture's first read drew its surface dark for one frame
- Symptom: a patch of scenery (Ocarina of Time's cliff beside the castle town wall) draws darker for exactly one frame, once, as the game gives it a sharper texture; a few times a minute while walking through Hyrule Field. Single frames, not the pairs of the entry above; no red line.
- Cause: the surface's shader reads its textures through the bindless pool table (
pool_gpu). Oncepool_budget()is spent a walk makes only the textures a shader has read (pool_seen), so an ID no shader has read holds the dummy, which reads 0; the first read sets the ID's bit, andpool_seen_scanmakes the texture for the next frame. Ocarina of Time keeps a texture set of its own for each piece of distant scenery and resolution (one level each: a BC5 texture, and two three-layer arrays, BC6H and BC7, of half its size), registers a new set 12 to 969 frames before the material names it, and so the first frame of each such step read the dummy. Which registrations a shader will read is not known ahead: in 58 s of play the game registered 14,455 textures that stayed unread, 9.8 GB, against 10 first reads, and making textures ahead by age and size cost 0.7-1.9 GB for one hit in three (issue #1969). - Fix: a texture the walk leaves out for good holds a stand-in in the tables until its first read (
pool_stand): the texture's own smallest levels, from the first of at most 1 KB on, or, when it has no level that small, its last level cut down to at most 4 KB a layer, every n-th block of every n-th block row (nvn_deswizzle_pick; the blocks stay as they are, compressed or not). The host reads them from the storage on the CPU into a small shared texture cut from a heap that is resident from the start, so making one takes no upload batch and no residency commit, and the first read samples the texture's own colours, coarse, for the one frame before the texture is there. 2D textures and 2D arrays of up to 8 layers get one, with the format and channel swizzle of their view (treg_swizzle); other types, depth formats and render targets no pass has written hold the dummy as before (textures in sparse pools have their own rule). At most 512 are made a frame (an area load registers thousands at once); the rest wait and are written into the tables in place (pool_stand_scan). A table walked while the budget had room is walked once more when the budget has filled.DM_NVN_POOL_STANDIN=0keeps the dummy. - Check:
t_pool_standin(which registrations get a stand-in and what it holds, read back from the GPU; the first read; a frame's share),t_texP (the picked blocks against the level decoded whole, in both GOB orders).DM_NVN_POOL_FIRST=1logs each first read of a texture not made yet and what it found; the totals go to the log every 300 frames (pool stand-ins up to frame). Replays of a player's route past the cliff, 10 withDM_NVN_POOL_STANDIN=0and 8 without: after the area load, 31 first reads of a texture not made found the dummy in the 10 runs and none in the 8, where 49 found a stand-in (none of them made from storage the game wrote afterwards). On a 32x18 luminance grid of every present, the cliff's first read is a connected group of 9-12 cells at 0.70-0.79 of the presents before and after in each of the 4 baseline runs in which its set streamed, and at most 2 cells, the grid's noise, in the 5 runs with stand-ins; by picture the cliff is dark for one frame in the one and a little soft in the other. At the area load 39 first reads a run found the dummy, and 5-11 with stand-ins (the frame's share). A run makes about 57,000 stand-ins in 355 ms (6 µs each on an M4 Pro) and holds about 6,000 at a time, in 16 MB of heaps. Resident memory, GPU allocated, the residency set, frame times and submit+present stay within the run-to-run range (medians: resident 10,830 and 10,883 MB; frame p95 16.85 and 17.19 ms, with runs of both kinds between 16.8 and 19.4). - Found on: The Legend of Zelda: Ocarina of Time (a player's recording, M4 Pro, macOS 27.0.1).
A sparse pool's streamed textures read 0 at their first read
- Symptom: the first frame after a scene cut is dark where newly visible materials are: PRAGMATA's cut from the tower to the tablet draws the cockpit and tablet with their G-buffer base colour at 0.068 on that frame against 0.18 on the next.
- Cause: the stand-ins left out every texture in a sparse pool. Such a pool's address range is read through its page table (an unmapped page stops the host with SIGBUS when read directly), so
stand_makerefused them. PRAGMATA puts all its streamed textures in sparse pools and is past the walk's budget from its first scene (12 GB allocated against a budget of about 0.9 GB), so the materials first read at a cut found the dummy. A texture whose small levels the game maps only after registering it was also refused for the registration's life. - Fix:
stand_fillgathers each layer's bytes from the stand-in's first level to the layer's end through the page table (nvn_sparse_copy, at most 256 KB a layer) and decodes them withnvn_deswizzle_from/nvn_deswizzle_pick. A texture with the SPARSE flag gets one only from its mip tail on, which is laid out as any texture's. When a page behind those levels is not mapped yet, the ID keeps the dummy and waits for a mapping over its pages, the only thing that can map it: the mapping's note (treg_sparse_notes, the notes of PR #1721) lets it be looked at again, and walks and table patches do not look at it in between, so an unmapped texture costs nothing until the game maps over it. Thepool stand-ins up to frameline counts those made in a sparse pool and those not made for an unmapped page. - Check:
make -C dm/gfx/tests GAME=<id> check_t_pool_standin_sparse(Metal validation): a sparse pool's texture left out holds its stand-in, with its level 4 read back from the GPU against the level decoded from the physical pages; one whose small levels are unmapped holds the dummy, charges nothing of the frame's 512, and a walk with no mapping does not look at it again; mapped later in the same frame, it holds its stand-in once the mapping notes it, with no walk; registered again, it holds its stand-in at the next walk. A refused ID looked at on every walk fails two checks, and one whose wait the note does not end fails the same-frame check.t_pool_standin(51 checks; 31 withDM_NVN_POOL_STANDIN=0) andt_pool_notespass. - Found on: PRAGMATA (M4 Pro, macOS 26.6.2, a main-line host with the first version of this change, which looked at an unmapped texture again at every walk, two runs a side): the whole-picture luma at the cut from the tower to the tablet was 65 / 65 / 65 (before / cut / next) with the sparse stand-ins and 65 / 22 / 50 without; 4,872 of the 5,694 stand-ins were in sparse pools; the resident set peaked at 6.5 to 6.6 GB against 6.7 GB without. An earlier build with a G-buffer dump read the cut frame's base colour at 0.181 against 0.181 on the next (0.068 without). Resident Evil 4 (M6, a host at chain
d254f45e8002with and without this change, title to the forest path in 330 s, one run a side): first reads of a texture not made found the dummy 695 times and a stand-in never without it, and the dummy 27 times and a stand-in 999 times with it; 6,834 of its 7,486 stand-ins were in sparse pools, made in 42 ms over the run (20 ms for 655 without), and 149 were not made for an unmapped page, each looked at again only after a mapping over it.
Transient render targets shared by storage
- Symptom: ≈13 MB/frame leak.
- Cause: the game builds new texture objects every frame over the same storage and never finalizes them; each new object allocated a new private Metal texture.
- Fix: host textures are shared by
(pool, offset, description). - Found on: Super Mario Bros. Wonder.
Transient buffer textures shared by storage
- Symptom: the residency line adds and removes thousands of allocations every 300 frames, nearly all from one line, the
res_addof a buffer texture's view intex_mtl_; the memory line'sfinalized textures still referencedstays at the ghost table's 512 while its puts in total climb by about a hundred or more a frame. No red line and no visible effect: the cost is submit-thread time in residency commits. - Cause: a buffer texture (
NVN_TEXTURE_TARGET_BUFFER) got a Metal view of its own for each NVN texture object, made before the storage-sharing table was looked at, while every other texture is shared by(pool, offset, description)(Transient render targets shared by storage). Unreal Engine makes its transient buffer textures again every frame over the same pool ranges, so each frame added new views to the residency set and finalized objects to the ghost table, which they wrapped, pushing out finalized textures that are still in use. - Fix: a buffer texture's view (
tex_bufferinnvn_mtl.m) is shared through the table like any other texture (own_alias_take,own_alias_publish): one view per pool range and description, kept resident by the table until its pool is finalized or a new texture takes its storage over. The view starts at the aligned boundary below its offset as before (Buffer textures at offsets below 16 bytes); textures sharing it have the same offset and width, so the sametbuf_lead. Since the table leavesIMAGEout of its key (IMAGE usage does not split texture storage), the view is made with every usage it can take, whatever the texture's flags (tbuf_usage): shader write, atomics for R32 integers, and format views. Made with read usage alone, a view shared with an IMAGE texture object would be rebuilt (tex_upgrade) at its first image write, and every one viewed in another format at its first such view, and an image write thatimage_preparedoes not see (an image slot past 32) would reach a view that cannot be written. A view on its pool's buffer has no lossless compression for these usages to cost: on an M6, reads of R32F, R32UI, RGBA8, RGBA16F and RGBA32F views over 64 MB took the same time with and without them, within the ±13% the runs differed by. Metal makes no writable BGRA8Unorm texture buffer (its validation refuses one), so that format's view has no write usage; every other format the host maps takes it (checked under validation). - Check:
t_upgrade_aliasunder Metal validation: live, finalized and IMAGE objects over one range share its view; each registered ID of it moves its coordinates by the same lead; an atomic image write and an R32UI view rebuild nothing; 64 objects made again over the range add nothing to the residency set; another width over the same range is a view of its own; a GPU write through the shared view lands on the texture's own bytes in the pool and reads back through another object. Without the fix 5 of its checks fail. - Found on: Mario & Luigi: Brothership (GitHub issue #1061: about 18 transient buffer textures a frame, 5,350 views added every 300 frames), FINAL FANTASY RESONANCE (GitHub issue #2423, an iPhone 15 Pro Max: about 79,000 added and removed every 300 frames of play, 235 ms of residency commits per 300 frames, the ghost table at about 175 puts a frame). Measured on the Mac (M6, macOS 27.2,
regress.py checkheadless at 60 fps, 2026-11-14): Pikmin 4, two runs a side, from about 15,000 views added every 300 frames of its route to 86–232, residency commits from about 1,500 to 114–190 per 300 frames, and the submit thread's wall time a frame from 1.79–1.86 ms to 1.56–1.67 ms at the median (2.26 to 1.92–2.08 ms at p90); OCTOPATH TRAVELER II, one run a side, from 22,898 views added every 300 frames to none by the end of its route, 72,541 residency commits in the run to 1,467 (293 to 70 ms), and the submit thread's wall time from 2.15 to 1.85 ms at the median (3.02 to 2.67 at p90). Frame rate held at 60 in both, and GPU memory was unchanged. - Open: a view no texture object names any more stays in the table, and resident, until its pool is finalized or a new texture takes its range over. The table holds more entries for it: Pikmin 4's levelled off at about 6,300 (2,400 before, 3,600 of them unreferenced) from frame 3,900 of its route; OCTOPATH TRAVELER II's grew as areas loaded, from about 1,900 to 7,100 over 24,000 frames (2,070 before), and stayed flat within an area. Each costs a Metal object and a place in the residency set, not memory (the set's bytes were the same or lower). No game has shown growth without bound. The memory line reports what the table alone keeps: how many textures, their size (each texture once), the part drawn into or shader-written, and the longest any has gone without a lookup, in submissions. Whether they are part of Ocarina of Time's climb from about 11 to 15 GB resident over a long session on an M3 Pro (GitHub issue #2629) is open.
IMAGE usage does not split texture storage
- Symptom: a model has correct geometry, base colour and normals but appears as a black silhouette; deferred lighting's material-ID depth texture stays zero.
- Cause: render and stencil-sampling descriptors name the same pool, offset and layout, differing only by
NVN_TEXTURE_FLAGS_IMAGE. Including that usage flag in the storage key made two independent Metal textures; sampling read the empty one's stencil. - Fix: the storage key excludes
IMAGE. Sampling shares the original texture. A writable image binding prepares any neededShaderWriteusage before opening its encoder; the upgrade copies the pixels and replaces every name of the old texture. Upgrading while encoding arguments would end the active encoder underneath its caller. - Check:
t_stencil_viewwrites both planes, reads through an IMAGE stencil descriptor and copies to separate storage under Metal validation;t_upgrade_aliaschecks image-write preparation and every live/finalized alias. - Found on: Xenoblade Chronicles 3.
Writes into an uncompressed alias of a compressed texture
- Symptom: a surface that Unreal draws from a runtime virtual texture (a landscape floor) stays black; its BC tile caches read all zero in a texture dump, and nothing writes them on the GPU or the CPU; no red line. Or a picture the game compresses on the GPU (a fighter's portrait) shows colourful static where the image should be; no red line.
- Cause: the game writes BC blocks as 8- or 16-byte texels (RGBA32UI: one texel a BC3 block) into a 2D texture it made over the same storage as a BC texture, with that texture's size in 4x4 blocks. On the Switch the alias is the compressed texture's bytes, so any write through it, a texture copy, an image store or a draw, writes the compressed texture, and a write of the compressed texture changes the alias. Here every NVN texture object has a Metal texture of its own, and Metal can neither make a view between a compressed and an uncompressed format nor place two formats' textures over the same bytes with a known layout, so the alias's writes stayed in the alias and the sampled compressed texture kept the content it was made with (zeros, or a fresh allocation's leftovers).
- Fix: compressed-alias pairs in
nvn_mtl.m(bcp_*). A registration that can be either side (a 2D, single-sample, block-linear texture with a BC format of 8- or 16-byte blocks, or an uncompressed format of 8- or 16-byte texels) goes into an index by storage address (g_bcp_idx, kept bymtl_reg_tex), and two registrations at one address whose sizes match in blocks with the same block size are a pair. Each GPU write of a side goes into the other side's Metal texture after it, at the write's level and region in blocks, through a private staging buffer the copies reuse (a blit does not copy between an uncompressed and a compressed format, while buffer copies to and from both are allowed): a texture copy (copy_t2t), a buffer copy (copy_b2t), a texture clear (clear_tex) and a scissored zero clear (clear_rect_zero) at once; an image store (image_prepare, for a dispatch or a draw: the image bindings the host binds, slots below 32 and handles in uniform buffers; a slot past 31 is bound to a dummy), a render target (attach, which every render-target clear goes through, held back or not; a compressed one is drawn through its shadow) and DrawTexture when the dispatch or the render pass has ended (bcp_flush, after the shadows' blocks; a dispatch the host's own kernels take over, MetalFX or nn::ndve's network, flushes too). Before a side is written, it is filled from the other side when that one has a Metal texture and the two have not been made equal since either was made (bcp_synced), so a write of a part of a side keeps the rest. A side made as a GPU texture while the other has a Metal texture is filled from it before its fill from storage (bcp_up_fill,tex_mtl_), so a shader that reads the alias before writing it reads the compressed texture's blocks; and the CPU's bytes uploaded into a side from its storage (a packaged texture's first upload or a re-upload after the CPU wrote its pages) go into the other side's texture (bcp_up_follow): an alias the shaders write is a GPU texture, never taken from its storage. Both run in the upload batch (a texture-to-buffer record,up_t2b_add), which the GPU runs before the replay's next segment, as a fill from storage does: a texture binding can be resolved inside a render pass, where no copy may run in the replay's order. Every pair copy goes into storage the CPU can read too (gsb_store), as the host's other GPU writes do: an image store through the alias reaches the storage, and a compressed side taken from its storage, re-uploaded when the CPU writes its pages, keeps it (mtl_tex_cpu_rewrittenre-uploads a compressed texture whatever the GPU wrote, as every GPU write into its storage is stored there). Scissored zero clears and DrawTexture also take the sparse, use and storage notes every other GPU write takes (sparse_gpu_wrote,tu_wrote,gsb_store), which they lacked. Lookups take the index's own leaf lock, notg_rmu, sincetex_mtl_runs underg_rmuas often as not. The compressed side is made when the alias is written (shaders sample it); an alias follows a compressed write only once it has a texture, and a plain copy (no scaling or mirroring) into an alias that has none goes straight into the compressed texture at four times the block position, so the alias gets none of its own (31 MB for each of Monster Jam's caches;bc_alias_copy, beforecopy_t2tmakes the destination's texture). Finding a pair is one hash lookup; it replaced a walk of every registration for each copy into a candidate. The copies use the forms withoutoptions:, which deferred encoding (DM_NVN_ENC_THREAD, on by default on iOS) records; theoptions:forms stopped the host withFATAL deferred encoding: DmRecEnc has no stand-in.DM_NVN_BC_ALIAS=0turns pairs off, for an A/B test. - Found on: Monster Jam Steel Titans 2 (
010051B0131F0000, update 1.0.2), copies: the landscape's runtime virtual texture renders 264x264 tiles, compresses them to 66x66 RGBA32UI blocks and copies them into a 1386x1386 RGBA32UI texture at the storage of each of its two 5544x5544 BC3 tile caches; the arena floor was black. With the copy fix, on the Mac the caches went from all zero to about 530,000 of their 1.92 million blocks with colour and the floor shows its dirt, tracks and ramps, with no new red line; on an iPhone (deferred encoding on) the copy runs at the arena with no stop, crash or GPU stall, at 30 fps. DRAGON BALL: Sparking! ZERO, copies into its BC3 tile caches the same way. Mortal Kombat 11 (0100F2200C984000, v1703936, main build4f7ab1a3eefc7eb20413936e8e37c2e9; not in the games table yet), image stores:BC3CompressTexture(main+0xa98960) dispatches shaderdb4c650ed89c46ac, which writes a 320x270 RGBA32UI image over a 1280x1080 BC3 character portrait; character selection showed colourful static. A contributor's Mac run (Apple M2) with an earlier image-store fix showed the portraits clear (PR #2802). - Check:
dm/gfx/tests/t_bc_alias.munder Metal validation (65 checks): a copy into an RGBA32UI alias with no texture lands in the BC3 texture's blocks, makes the alias no texture and is counted, and a second one lands through the reused staging buffer; a copy into a texture over other storage leaves the BC3 texture as it was; an image store into the alias (throughimage_prepareandbcp_flush) fills the alias from the BC3 texture first and reaches its blocks byte for byte; a copy into the BC3 texture reaches the alias's texels in its region only; a later store into part of the alias keeps the BC3 copy's blocks; a read-only image binding copies nothing; an image handle relative to the execution pool's base finds the alias; a render pass that clears the alias reaches the BC3 texture when it ends; a registration that changes texture leaves the pair; a second alias made after the BC3 texture was written holds its blocks; an upload into the BC3 texture reaches the alias; a texture clear and a scissored zero clear of the alias reach the BC3 texture's blocks in their regions only. WithDM_NVN_BC_ALIAS=0, 23 checks fail. - Open: the upload batch's fills read the other side as the replay's earlier segments left it: a side made and only read in the segment that wrote the other side, before it, reads what the side held before that write (the side's first write fills it again in order,
bcp_before). Image stores into a texture that has no pair are still not written into storage the CPU can read; a pair's are, through its copy. Mortal Kombat 11 has not been run with this change (no local dump); its profile is PR #2799. Not run on an iPhone.
Shared-storage entries taken over by a new texture
- Symptom: GPU memory grows with every image shown; the memory line's
shared texturescount keeps rising. - Cause: the game decodes each picture it shows into one scratch region of a pool that lives for good, finalizes that texture when it is done with it and builds the next one in the same region with another size or format; during some transitions it builds a new render target every frame, one pixel wider each time (614x720, 615x720, …). The storage-sharing table (
g_alias, keyed by pool, offset and description; Transient render targets shared by storage) kept every one of them until the pool was finalized. - Fix: a new shared texture takes over the entries of its pool whose storage it overlaps under another description (
alias_take_overinnvn_mtl.m), unless a live texture object still resolves to one (Wonder's transient render targets, rebuilt on new objects every frame and never finalized) or a lookup found it in the last 16 submissions (Breath of the Wild finalizes its transient render targets before every submit and builds them again the next frame; targets sharing storage would otherwise evict each other every frame). An entry that only a finalized serial ing_ghoststill holds loses the table's reference and is retired with that serial. The memory line reportsshared textures N (M of them unreferenced; evicted with pools …, on storage takeover …): the unreferenced ones wait for their storage to be reused or their pool to go. - Found on: STEINS;GATE RE:BOOT (ASTC 4x4 images up to 4096 wide, RGBA8 render targets, R8 masks): from a quick save, 297 entries and 1.29 GB of GPU memory at frame 6,600; 468 entries and 1.58 GB 24,000 frames into a new game. With the fix: 97 entries and 0.93 GB at frame 6,600; 15 minutes of story from the quick save (53,700 frames) stayed at 1.08–1.15 GB of GPU memory and 1.02–1.13 GB resident, and a new game from boot stays at 0.97–1.03 GB from its first story scene to frame 27,300 (with the 16-submission guard).
- Check: Captain Toad: Treasure Tracker's opening course, rendered with agl's transient targets, keeps its 26 entries and takes none over, with the same memory and frame times as before.
A storage takeover walked the serial table for each entry
- Symptom: while the game makes many textures (Ocarina of Time's cutscenes), frames of hundreds of milliseconds up to a second, all of it in
submit+present(the[longframe]lines);sampleof the process namesalias_take_overthe submit thread's hottest function. - Cause: for each entry a takeover could remove,
alias_take_overasked whether a live texture object still resolves to it throughserial_holds(&g_by_serial, …), a walk over the serial table's whole capacity. With about 7,500 serials and thousands of shared textures, every new shared texture walked the table once per entry of its pool that overlapped its storage, and the texture pool's walks (pool_gpu, which makes a texture for every registered ID of the table's type) make hundreds of textures in one submission. - Fix: general, in
nvn_mtl.m: a count per object of the serial-table entries holding it (g_by_serial_held), kept by every writer of the serial table (serial_put,serial_del,tex_putand the upgrade's in-place replacement);alias_take_overasks it in one lookup. The count answers only what it counts: a change that lets a live object hold a shared texture some other way (a view's parent, a packaged texture's members, as PR #1404 proposes) must count those holds too, or a takeover retires a texture still read. - Check:
dm/gfx/tests/t_alias_takeover.m: an entry a live object resolves to stays and one nothing resolves to goes afterALIAS_IDLEsubmissions, two serials naming one object keep it held until both go, and a takeover past 1,000 held entries with 20,000 serials in the table takes 0.025 ms instead of 4.3 ms (M5 Max). In the game, a host that asked both the count and the walk (Ocarina of Time, loading a Kokiri Forest save, Saria's dialogue and a walk through the village, M4 Pro) compared them 393,216 times and they never differed, so the takeover makes the same choices as before; on the same route the[longframe]lines went from 332 to 212. - Found on: The Legend of Zelda: Ocarina of Time (Switch 2,
0400486024DEC000, update v131072, with PR #1299), Saria's cutscene in Kokiri Forest, M5 Max. In 60 ssamplecaptures of the submit thread over the cutscene,alias_take_overtook 2,277 of the 3,711 samples spent making textures (tex_mtl_), 61 %; with the fix 38 of 618, 6 %. Game runs on the wall clock (the game does not run underDM_DETCLOCK) put the cutscene's heaviest part in or out of the run, so frame counts moved within their noise. - Open: the same captures and the memory line show the textures themselves being made again and again: 84,000 to 103,000 storage takeovers in about 200 s of play with 1,400 to 1,900 shared textures alive.
A storage takeover walked the sharing table for each texture made
- Symptom: a scene that makes tens of thousands of textures never finishes loading: no frame is presented, the submit thread stays at 100 % of a core, and
samplenamesalias_take_over(undertex_mtl_←tex_by_id←encode_args). - Cause:
alias_take_overlooked for the entries a new shared texture's storage overlaps by walking the sharing table's whole capacity (g_alias), with a layout and ag_alias_seenlookup for each entry of the same pool. The cost of each texture made grew with the textures already shared, so a load that shares about 90,000 textures walked 131,072 slots for each of them. - Fix: general, in
nvn_mtl.m: an index of the shared textures by where their storage lies (alias_index,g_alias_cells): {pool, 64 KB cell of the pool} → the entries whose bytes reach into that cell, each with its end.alias_take_overreads the cells of the new texture only. The image families' owner lookup (image_texture: the entries of the same pool, offset and format), which walked the table for each image made in a GPU-only pool, reads the one cell of its offset. The entries it chooses from are the same (same pool, another description, overlapping bytes, not looked up lately, held by no serial); when more than 16 qualify, which 16 go first follows the cells instead of the table's order, and the rest go at later takeovers as before. The table's keys have two writers,alias_putandalias_del, which keep the index,g_alias_setandg_alias_seentogether; code that writesg_aliasany other way hides its entries from the takeover. Walks of the whole table remain where they run once per event, not per texture: a pool's release, a texture's upgrade (which walks the serial tables as well), the memory report and the census. An entry costs one lookup per 64 KB of its storage when it is put or removed (16 for a 1 MB texture). - Check:
dm/gfx/tests/t_alias_takeover.m: an entry that starts in an earlier cell is found, one in the same cell that ends before the new texture stays, one spanning several of the new texture's cells goes once, another pool's entries are not met, a removal and a pool drop leave no cell behind, and a takeover with 100,000 entries in the table takes 0.0003 ms instead of 0.65 ms (M6).t_image_alias.m: two families whose offsets lie in one cell keep a heap each. - Found on: Mario Golf: Super Rush (4.0.0, issue #814), All-Star Summit, MacBook Pro M1 Pro, the PR author's runs: the course registers 134,400 textures and shares about 90,000 as it loads; on main the load showed no frame in 5 minutes (88,513 entries after 12), with the index the first frame comes about 3 s after the start (PR #2229).
- Open: Whether 90,000 live Metal textures for one course is what the game needs, and what it costs in memory on an iPhone, is not examined.
A texture ID with no texture kept its cached view
- Symptom: a command buffer fails with a GPU page fault on the same frames in every run, in a compute or draw command buffer whose shaders sample through the texture pool. Ocarina of Time with
DM_NVN_RT_RECLAIM=1(PR #1588's render-target reclaim; the switch was never on main): f3,677 and f4,851, compute shader 9e6b00b050e30801, each run. - Cause:
tex_by_id(nvn_mtl.m) keeps an ID's cached view when the slow path finds the same texture behind it:cur == v || v.parentTexture == cur. When the ID has no texture now,treg_texreturns nil ascur. That happens for a texture that went and was not made again, a texture that could not be made, or a reclaimed render target. A cached view that is the base texture itself has no parent either, so nil == nil kept it and marked it valid again. The pool tables' fast path (tex_fast_rid) then wrote its resource ID after the host had released the texture and dropped its residency. With the reclaim it happened about 60 times in a 5,000-frame run. - Fix: general, in
tex_by_id: the cached view is kept only whencuris non-nil. An ID with no texture drops its view, and its slot takes the typed zero texture an empty slot of that type gets. - Check: Ocarina of Time on an M2 Pro 16 GB with
DM_NVN_RT_RECLAIM=1(PR #1588's test host; the switch was never on main, so this run cannot be repeated on a main host), to f5,241 and f7,750. The f3,677 and f4,851 faults are gone, with no trimmed texture handed back (checked by marking every texture the reclaim's trim released). Pace is the same (7,750 frames in 202.5 s against 7,731 in 202.75 s), and reclaim counts are alike. A fault at f786 has another cause and is there without the reclaim too. The picture there was not compared: a dead ID now reads the typed zero texture instead of the released one. - Found on: The Legend of Zelda: Ocarina of Time (Switch 2,
0400486024DEC000, v131072).
Live resolution variants share physical image storage
- Symptom: GPU memory grows as resolution changes or rooms load, although almost every retained texture still has a live NVN descriptor; reclaiming unused sharing-table entries cannot recover it.
- Cause: an NVN texture object describes storage in a pool. Several live descriptions at the same pool offset can describe the same physical memory at different resolutions, but
(pool, offset, description)sharing allocated a separate private Metal texture for every size. The live-object guard inalias_take_overcorrectly kept those descriptors, and consequently kept all their independent allocations. - Fix:
image_textureinnvn_mtl.mgives a declared resolution family an exact-sized placement heap. Eligibility is GPU-only, mapped, non-sparse storage,COMPRESSIBLEwithoutDISPLAY,VIDEO_DECODE,LINEAR,SPARSEorLINEAR_RENDER_TARGET(with or withoutIMAGE: a depth target carries onlyCOMPRESSIBLE), single-level, single-sample 2D images. Sharing stays within one NVN pool, offset and format. Live descriptions are recorded at initialization so the first used resolution can allocate the largest declared requirement; a single-description address retains its ordinary allocation. No power-of-two capacity or extra pixel-format-view usage is imposed. A fresh heap is zeroed through its largest description; creating a later alias never queues a zero fill over another alias's content. Metal 4 residency names the heap, and encoder boundaries include resource-alias visibility while these heaps exist. Each texture holds its heap owner; normal sharing-table eviction and deferred texture release retire the allocation after its last texture/view goes, without a pool-lifetime heap cache. - Limits: this handles initialized resolution families, not arbitrary overlapping offsets, cross-format inheritance, CPU-visible or sparse storage. If a larger description is declared later and cannot fit an existing heap, it gets a new heap from the recycled heaps (the entry below); an old heap follows its textures' lifetimes and then waits there. Inherited texels are not translated between incompatible texture layouts, and the family's textures are not compressed (the entry below). No game-specific profile switch is used.
- Check:
make -C dm/gfx/tests GAME=0100DCA0064A6000 check_t_image_aliasruns under Metal validation with direct and deferred encoding: 128 live descriptions retain their individual dimensions while sharing one allocation; small-first fresh storage, literal pixels across resolution changes, descriptor creation after a writer, indirect Metal 4 argument-buffer access, native integer-image atomics, depth/stencil clears and stencil views, pool/offset/format separation, excluded CPU-visible/sparse/linear images, a depth family withCOMPRESSIBLEalone and repeated destruction are checked. Integer-image matching restores theShaderAtomicusage that Metal omits from its queried usage flags. - Found on: Luigi's Mansion 3, investigated from #257 and #100. The game's note records the live-allocation census and Mac comparison; other games and long iOS sessions remain unvalidated. The Legend of Zelda: Ocarina of Time: its dynamic-resolution depth buffer, Depth32Float with
COMPRESSIBLEalone in a virtual pool, had 15–16 live sizes of 1,882–1,920 pixels at one offset, 14.5 MB each, outside the family until the flags rule took any compressible image; in Kokiri Forest on an M3 Pro (18 GB, measured before main's Ocarina fixes) Depth32Float textures went from 95 (458 MB) to 60 (191 MB) plus 21 family heaps (82 MB), and GPU allocation from 7,710 to 7,520 MB.
A resolution family member reads another size's compressed blocks as garbage
- Symptom: after the game renders at another resolution for a while (a pause menu, a resolution switch) and comes back, a render target it loads instead of clearing holds non-finite or random pixels, in a screen-shaped region that opaque draws wipe away and transparent ones keep; bloom spreads them into a strobing glow. A non-finite scan (
DM_NVN_MAGSCAN) counts about a million of them in the first pass back. - Cause: a resolution family places every size in one Metal heap. Metal compresses a private texture losslessly by default (
allowGPUOptimizedContents), and each texture reads the shared bytes through its own compression layout. When one size reads what another size wrote, it decodes the other's compressed blocks as garbage. On the console the same bytes are texels of the same format in other places, which stay finite. - Fix:
image_textureinnvn_mtl.mcreates every family member uncompressed, and so the largest description that zeroes a new heap: inherited bytes read back as the other size's texels, misplaced, as on the console. Storage with one description keeps its ordinary, compressed allocation.DM_NVN_FAMILY_NOCOMPRESS=0turns compression back on (an A/B of its cost). - Cost: Ocarina of Time makes 215 family heaps in the Kokiri Forest (202 of them Depth32F). On its
kokiri-deckroute on an M4 Pro, one host with the switch on and off, the median GPU time a frame over the runs that stayed on the route was 22.07 ms compressed (4 runs, 21.94–22.23) and 22.38 ms uncompressed (5 runs, 21.73–22.73): at most about 0.3 ms, within the spread of the runs. - Check:
check_t_image_alias(above) clears a 1440x810 RGBA16F render target through the host's clear path and reads the 1600x900 size of its family back: every texel is the clear colour or zero. With compression (DM_NVN_FAMILY_NOCOMPRESS=0) 6,144 of 1,440,000 texels were neither on an M4 Pro. - Found on: ASTRAL CHAIN (1.0.1): the 1600x900 HDR targets (RG11B10Float) share their storage with the pause menu's 1440x810 targets; the first pass back from the menu loaded 1,115,523 of 1,440,000 non-finite pixels, which the game never clears (issue #1935, PR #1936).
A 4-sample target over a single-sample image's pool storage
- Symptom: an engine's effects pass draws (hundreds of draws, instances that follow the weapon) and nothing appears: particles, beams, decals, muzzle flashes, the laser sight and the spiderweb sprites are all missing, while the scene, lighting, HUD and bloom are right. The pass's colour target is never bound, sampled or copied by any later pass. Metro 2033 Redux:
DM_CTL texlistshowed ser 2630 (640x360,RGBA8_SRGB, 4 samples) and ser 2611 (1280x720,RGBA8_SRGB, 1 sample) over one pool storage,0x3c0000bytes each, with differentmtl=pointers. - Cause: NVN shares storage by bytes: texture objects over one pool offset read and write one another's texels whatever their descriptions. A 4-sample W x H target and the single-sample 2W x 2H image of its format over the same offset are one storage, sample s of pixel (x, y) being texel (2x + (s & 1), 2y + (s >> 1)); this engine draws its effects into such a target over its scene target and reads the bytes as the scene. The host's sharing table keys on pool + offset + description (
alias_keyinnvn_owner.m), and only resolution families (image_texture) shared memory, so the two got two Metal allocations and the effects went where the upscale never read. - Fix: general,
pair_textureinnvn_mtl.m: whichever of such a pair is made second (one level, a non-depth colour format, aCPU_NO_ACCESSpool, not sparse or linear, the same NVN storage size) is placed at offset 0 of the live other's heap (a resolution family's or recycled memory's), with the other's compression, and only when Metal gives both descriptors the same size. It is not filled. It holds that heap's owner, so the heap goes back to the recycled heaps only once both textures are gone, and while it lives barriers flush aliased memory (resource_vis). On Apple GPUs (checked on an M6) Metal lays such a pair out as NVN does: a 4-sample texture placed over the 2W x 2H one holds every sample at that texel, compressed or not, for ten colour formats (8 to 128 bits a texel) and sizes from 66x34 to 1920x1080. It does not with 2 or 8 samples (Metal sizes them differently), nor with one compressed and one not, so those stay apart. Other GPUs (the iPhone's) are not assumed: before the first pair of each kind (format, size, both compressions)pair_layout_okplaces the two in a scratch heap, copies a pattern into the single-sample one and compares every sample with its texel in a kernel (dm/gfx/msl/pair.metal), about 2 ms once on an M6; a kind laid out otherwise stays apart with a red line, and the result is logged (storage pair layout:). A partner outside a heap (DM_NVN_RT_RECYCLE=0) keeps them apart with a red line.DM_NVN_STORAGE_ALIAS=0keeps every pair apart. - Check:
check_t_storage_pair: through the host's own textures, a ramp drawn per sample into the 4-sample target is read back from every texel of the image, and one drawn into the image from every sample (921,600 of 921,600 each way), in recycled memory (compressed) with either made first, and in a resolution family's heap (uncompressed). It also checks that releasing the first one leaves its heap out of the recycled heaps while the second lives, and that a first one made again joins the heap with the content kept. 2 samples, another format, size or layout, depth and a CPU-visible pool stay apart. The runtime check passes the kinds paired, runs once for each, and finds a compressed image over an uncompressed 4-sample target laid out otherwise (921,600 of 921,600 samples elsewhere); with the check failing, the pair stays apart with its red line. The checks fail without the heap owner (the heap was handed out while the 4-sample texture used it), and without the compression match (0 of 921,600). Metro 2033 Redux on an M1 Max, with the first version (no owner held): the weapon's laser beam and dot, the muzzle flash and the sparks appear, the scene's 1:1 detail is unchanged and there are no Metal validation errors. - Found on: Metro 2033 Redux (1.0.0), PR #2789, its port PR #2743
Render targets that move with the dynamic resolution get new Metal memory each time
- Symptom: while a game's dynamic resolution moves, the residency set's
addedcount in theresidency set up to framelines stays at hundreds of MB per 300 frames from the shared-texture site, and frames stutter. On a 16 GB Mac, wired memory and swap follow, with p95 frame times near 100 ms. Ocarina of Time after04419bc2, which freed its dynamic resolution from its floor (GitHub issue #1831). - Cause: the engine keeps its render targets in a GPU-only pool and gives them new offsets and sizes as its resolution changes. Each
(pool, offset, description)is a Metal texture of its own (the sharing table), and the storage takeover (alias_take_over) lets as many go. On an M6, 3,468 textures were made in about 1,000 frames of Ocarina's village: 97% were in its 305 MB virtual pool, at 1,965 offsets and 289 sizes, and they added 450-575 MB to the residency set every 300 frames. The live total stayed bounded at about 2.1 GB: it is churn, not a leak. Metal does not lay a texture out as NVN does, so these targets cannot share the pool's memory as on the console. A placement heap that mirrors the pool (PR #1453) and a reclaim of targets dead by overwrite (PR #1588) both corrupted the picture: the game keeps live targets in the part of the full-size scene target that its current resolution leaves unused. - Fix: general,
rh_heap,rh_placeandrh_textureinnvn_mtl.m. Such a target (a texture in aCPU_NO_ACCESSpool that the GPU can render or write to, so not of a block-compressed format, private storage, not display, video, linear or sparse) is made in a placement heap of its own, an eighth larger than the texture. When its texture is freed, which happens after the submissions that used it complete (defer_drain), the heap stays resident in a free list. The smallest waiting heap that fits, up to half as large again, takes the next texture. Metal's allocation sizes come in steps of about 10% near 2 MB (#1583'srt_sizes: 855 resolutions at 2048x1152 fall into 21), so the eighth of headroom lets a target that grows by one step fit the heap it freed the frame before. The same free list serves the heaps of resolution families (image_texture, the entry above: a new family heap is taken from it, and a family heap whose last texture goes waits in it) and same-pass feedback snapshots (fb_snap), which are made again at each new size of their attachment. The new texture is filled as a new allocation is (tex_init_fillor zeros), so nothing it reads depends on the reuse. Its memory was the old texture's only up to that texture's completed last use, so no alias flush is added. Heaps that wait 3 s, and the oldest past 256 MB waiting, leave the residency set when a submission begins (rh_trim). The memory line counts the heaps made, reused, freed and waiting.DM_NVN_RT_RECYCLE=0turns it off (each texture its own allocation, family heaps exact and freed with their last texture), andabalternates it with theDM_ABphases. This does not lower the steady total of the live targets (Render targets drawn over stayed while their texture objects lived does), and it does not remove the rest of a resize's cost: each new size is still a new Metal texture, filled, and the takeover of the old one. - Check:
make -C dm/gfx/tests GAME=<id> check_t_rt_recycle: placement with an eighth of headroom, the heap kept resident while it waits, reuse at a smaller size with zeroed contents and at a size one of Metal's steps larger (a texture withoutCOMPRESSIBLE), a new heap for a size the waiting ones cannot hold, CPU-visible pools and block-compressed textures kept apart, the trim, a feedback snapshot in a recycled heap, and the switch off.check_t_image_aliaschecks that a family heap holds its largest size and waits, resident, after its last texture. It runs with direct and deferred encoding under Metal validation. In the game: Ocarina of Time on an M6 (16 GB), the village walk with dynamic resolution on andDM_NVN_RT_RECYCLE=ab DM_AB=300, one run. Over the phases while its resolution moved, the shared-texture site added 455, 457 and 521 MB per 300 frames off, and 317, 37 and 27 MB on. Frame p90 was 33.3 and 49.8 ms off, 16.8 and 17.6 ms on. Phases after the resolution settled measured the same either way. Screenshots of the village were clean, with no GPU errors or red lines. Measured with the shaders of chain f9f01e4f9994, which were on disk. Mario Kart World on an M6 (16 GB), its race with two outside GPU loads so that its dynamic resolution moved every frame, one run with the free list as it was before (exact heaps taken up to an eighth larger, onlyCOMPRESSIBLEtargets, family heaps and snapshots allocated apart) and as above alternating every 600 frames: per 300 frames, 970 residency commits (137 ms) and 1.8 GB added before, 272 commits (26 ms) and 0.34 GB after; the replay's CPU time a frame (encoding and commits) 6.94 ms before, 6.36 ms after. Frame time (p50 16.7 ms, p95 about 24 ms) and GPU time (13.2-13.4 ms) were the same: on the M6 the gain is CPU headroom. Measured on maina77c0ee8with the shaders of chain cb2e91c138e3. - Found on: The Legend of Zelda: Ocarina of Time (Switch 2,
0400486024DEC000, v131072), #1831. Mario Kart World (Switch 2,0400C3F00006E000): its dynamic resolution moves since it reads real GPU times (#1823).
Render targets drawn over stayed while their texture objects lived
- Symptom: on an iPhone the game is ended for memory (a jetsam event, iOS ends the app once the guest's touched pages reach its memory limit) at an area load, with the guest memory already in files. On the Mac,
footprintshows most of the process asOwned physical footprint (unmapped) (graphics): Ocarina of Time reached 6.36 GB of footprint stepping into the village, 4.4 GB of it Metal memory, the phone's limit being about 6.1 GB. - Cause: the engine keeps its render targets as texture objects over one GPU-only pool (Ocarina's is 304 MB) and moves them as its resolution and passes change, so newer targets draw over the bytes of older ones whose objects it keeps. Each
(pool, offset, description)is a Metal texture of its own (the sharing table), and the takeover (alias_take_over) frees one only when a new texture is made over it, and never while a live texture object still resolves to it, as an object rebuilt over the same storage must keep finding it (Transient render targets shared by storage). So a target stayed for as long as its object lived, holding bytes the console no longer has. A census of a test host in Ocarina's village: the pool's Metal textures held 2,893 MB, 987 textures; 162–170 MB of them had been used in the last second, 2,678–2,714 MB not for 20 s or more, nearly all of it (2,665–2,701 MB) overlapped by a target used since, and 2,667–2,750 MB was held by a live object. - Fix: general (
nvn_owner.mown_alias_dead_locked,nvn_mtl.mtu_*). A shared texture that the GPU alone writes (aCPU_NO_ACCESSpool, render-target or shader-write usage, not display, video, linear or sparse) and that a pool walk reads as the dummy until a pass writes it (COMPRESSIBLE,pool_unwritten_target) has two stamps: its last use and its last write by the GPU. Uses are a lookup by texture object outside a pool walk (attachments, copies, clears), a binding of one of its texture IDs (tex_fast_rid,tex_by_id; each pass encodes its bindings again), a handle table kept for a new pass, and a read the shaders mark in a pool (the bitmap of Shaders report which textures they read through a pool, whose folded marks the pass clears so the next one sees new reads). A pool walk resolves every ID and stamps nothing. Once a second, when a submission begins (tu_pass), such a texture goes when it has been unused for 3 s and another covered texture of its pool wrote its bytes after that last use: its content is gone on the console too. It leaves every serial entry that names it or a view of it (live and ghost, each a note) and the sharing table (retired after the submissions that used it), and its texture IDs drop their views, so a pool walk reads it as the dummy, as a target never written, rather than making it again. A pin keeps it. A binding or a write makes it again, filled as a new texture is (tex_init_fillor zeros; in a resolution family's heap, the bytes the family holds). At most 256 a pass.DM_NVN_RT_DEAD=0keeps them all,abalternates with theDM_ABphases; a line every 300 frames counts the released textures and MB, those made again and the passes' time. - Why the idle time: a reclaim by overwrite alone (PR #1588: dead once other targets' whole passes covered its range) corrupted Ocarina's picture, a flat green area over half the screen. The engine keeps live targets in the part of the full-size scene target that its current resolution leaves unused (PR #1453), so a pass over a range does not mean its bytes were all written. Those targets are read every frame, so they are never unused for 3 s. A target the game reads less often than that, in a range another target's later write covers without writing those bytes, would lose its content: none was seen. If one turns up, the overlap test can be narrowed to the block rows a write really covers.
- Check:
make -C dm/gfx/tests GAME=<id> check_t_dead_targets, under Metal validation: a target drawn over and unused goes, with its serial entry, and its ID drops its view; the one that drew over it stays, as do one nothing overlaps, one read every frame, one whose neighbour wrote before its last use and one a pin holds; drawn into again, it is made again; a pass over about 4,000 covered targets releasing 256 takes 0.5 ms. In the game, Ocarina of Time on an M6 (16 GB): the village save, Continue and about 2.5 minutes around Link's house, one run with each host (the phone's commit34ada028, chain 73b94575300e, with and without the change). Footprint after the load 5.35–5.47 GB without, 3.70–3.80 GB with. The run released 1,738 textures (4.4 GB counting those made and dropped during the load) and made 72 again, in 108 passes of 0.64 ms on average. Both held 60 fps (frame p50 16.66 ms). In steady play the worst frame of each 300 was 17–20 ms with the change and up to 100–780 ms without. Screenshots alike, no red line, no GPU error. - Found on: The Legend of Zelda: Ocarina of Time (Switch 2,
0400486024DEC000, v131072), on a 12 GB iPhone, ended about 9.5 minutes in at an area load.
Render-target views that change the format
- Symptom: the whole picture came out darker and more saturated on the Mac and the iPhone: comparing with a Switch screenshot, every channel at every level equalled the Switch value decoded from sRGB once more (0.55 → 0.26, 0.75 → 0.52).
- Cause: Mario's last pass writes the
RGBA8swapchain texture through anRGBA8_SRGBview (TextureViewSetFormat0x38 on a 0x25 texture), so the GPU encodes the linear shader output to sRGB on write. The host used to attach the base texture, which stored the linear values unencoded. - Fix:
attachnow attaches a Metal view of the view's format, so the pipelines get that format too; the view is kept until the submission completes. A format change that is not an sRGB / linear pair needsMTLTextureUsagePixelFormatViewon the base texture; without it the host draws in the base format and reportsrender target view format … cannot be attached. - Present step: the matching rule: the Switch scans out the stored bytes, so an sRGB-typed swapchain texture (
RGBA8_SRGB/BGRA8_SRGB) is sampled through a non-sRGB view (present_raw_src); sampling it directly would decode it once more on screen only, which aDM_NVN_SHOTcapture (raw bytes) does not show. Mario's swapchain isRGBA8, so this path is for other games (t_present_cropcovers it). - Check:
DM_NVN_PASSDUMPprints these views asV <pass> c<i> view format …; Mario uses only this one (1 of 80 passes in a course frame). - Found on: Super Mario Bros. Wonder.
A render-target view of another class: the texture is upgraded, not drawn in its base format
- Symptom: whenever a Switch 2 game's NDSR upscaler runs, the upscaled 3D scene is solid red with black specks, and the UI drawn over it has its red channel gone (white text cyan, skin teal): menus whose scene is not upscaled look right. The log has
[RED] render target view format 0xb cannot be attached (base texture Metal format 93 was created without the format-view usage): drawing in the base formatonce. - Cause: agl's NDSR packs its input into an
RGB9E5Ftexture (534x1200 for a 1600x900 input) through anR32_UIrender-target view, with a fragment shader (401877446d25d079inagl_ndsr.pck) whose output is the packed bits as uint: NVIDIA's GPUs have no RGB9E5 colour target. Colour textures are made withoutMTLTextureUsagePixelFormatView, andattachdrew such a view in the base format instead. The pipeline then took the shader's float entry (main0,as_type<float>(bits)in red, 0 in green and blue) for anRGB9E5Floatattachment, which stored the float value of the bits: red in the millions or infinite. The network turned that into a red picture; the UI's lost red is most likely 0 × ∞ = NaN where the UI, blended over that picture, is opaque (not traced further: it went with the fix). A uint output into anRGB9E5Floatattachment is no way out either: Metal refuses the pipeline (output of type uint4 is not compatible). - Fix:
attach(rt_view_upgradeinnvn_mtl.m) upgrades a texture without the usage to it before the pass opens when the view's format has the same texel size, as clears and images of another class do, and attaches the view, so the pipeline takes the uint entry (main0_u) and the stored bits are the shader's. AnRGB9E5texture the GPU writes has the usage from its creation (tex_desc): the game makes a new one at each size of its dynamic resolution, and each was upgraded (copied) once, 27 in 80 s of its menus. Every colour slot of a pass is upgraded before any is attached (rt_view_upgrade_all): an upgrade moves every serial sharing the texture's storage to the new texture, so a slot attached first would keep the retired one. Textures, descriptors and argument tables resolved before the upgrade follow it:tex_upgradebumpsg_ser_genwith no note, so the texture ID cache starts a new epoch (ser_sync,tex_by_id/tex_fast), and the argument blocks (args_sync_dirty) and pool tables (pool_gpu) are rebuilt. A format pair Metal makes no view for after an upgrade, and a texture whose upgrade fails or is refused (a placement sparse texture), are remembered and not tried again. The pipeline prediction (rt_view_fmt_predict) gives the view's format for a slot that will be upgraded. A view of another texel size still draws in the base format with the red line. Two costs, accepted: any game whose render-target views change the format within the same texel size now gets the view (and the upgrade's copy once per texture) where it was drawn in the base format before, which changes what such passes store; and RGB9E5 textures the GPU writes lose Apple's lossless compression. - Check:
make -C dm/gfx/tests GAME=<id> check_t_pfv: anR32_UIview of anRGB9E5Ftexture (made with the usage) and of anRG16Fone (upgraded) is attached asR32Uintand stores a uint draw's bits, and a texture ID registered before the pass samples the new texture and those bits after it; anRGBA16Ftexture is left as it was; two serials over one texture in two slots both end on the upgraded texture; a refused pair or texture is not upgraded again; the prediction givesR32Uintbefore the upgrade. In the game, from a new save withDM_KEYS="20:A*60/3"and a screenshot every 4 frames from 1800 to 2800: before, 21 of the 27 screenshots taken while the packing shader ran (DM_NVN_KEYDUMP=401877446d25d079) were 12-59 % pure red; after, none of 30. - Found on: Nintendo Switch Sports Resort (Switch 2,
04008E001F098000, v65536).
Textures of an sRGB / linear pair over the same storage
- Symptom: a movie (or another picture the game converts each frame) does not show: the screen keeps the last 3D frame while the decoder delivers every picture. A pass dump shows a pass writing one serial and the composite sampling another serial of the same size, the two Metal formats
RGBA8Unorm(70) andRGBA8Unorm_sRGB(71). - Cause: the game makes two NVN texture objects over the same pool and offset with the same description but for the format,
RGBA8(0x25) andRGBA8_SRGB(0x38): it renders into the linear one and samples the sRGB one, which on NVN share their bytes. The storage-sharing table is keyed by pool, offset and the whole description (Transient render targets shared by storage), so each got its own Metal texture and the sampled one never changed. - Fix:
tex_mtl_(nvn_mtl.m): a texture that misses the table, but whose description differs from a shared texture's only by the other format of an sRGB / linear pair (g_pfv_srgb, the pairs Metal views withoutPixelFormatViewusage), is a Metal view of that texture in its own format (2D and 2D array, single-sample). Other format changes keep their own texture. A usage upgrade (tex_upgrade) asked through the view upgrades its parent and makes the view again on it; a view whose parent left the sharing table (upgraded through its own serial, taken over, evicted) is dropped at its next lookup and made again on what holds the storage now (log linestale sRGB / linear view dropped). - Check:
make -C dm/gfx/tests GAME=<id> check_t_srgb_alias(Metal validation): the sRGB texture is a view of the linear one, pixels written through the linear texture read back through the sRGB one, anR32Ftexture over the same storage keeps its own; after the linear texture is upgraded the view reads the upgraded storage, and an upgrade through the view upgrades the parent. - Found on: Mario Kart World (
0400C3F00006E000; its profile is a separate pull request): the Grand Prix's cup opening movie (2560x1440: the YUV pass writes ser 31381RGBA8, the composite samples ser 31382RGBA8_SRGB, both at offset 0 of a 15 MB pool).
Render-target use added on demand
- Symptom: a clear of, or a format-converting copy into, a texture made without render-target use is declined.
- Cause: a whole-level clear and
copy_t2t_draw(which renders into the destination, Copies a blit cannot do, drawn) need a texture with render-target use. - Fix: the texture is upgraded to render-target use first, as format views are upgraded (
tex_upgrade; Integer views for images a shader declares uint or int). - Found on: Monster Hunter Rise (the clear of a 32x80 packaged texture); Paper Mario: The Thousand-Year Door (a format-converting copy of a 128x128 RGBA8 render target into a packaged RG8 texture, mirrored in Y, as the boat arrives in Rogueport, about frame 10,950:
copy_t2t_drawdeclined a destination made without render-target use).
A texture upgrade while a draw binds its arguments ends the pass
- Symptom:
CRASH sig=11 addr=0x794in-[AGXG16GFamilyRenderContext_mtlnext drawIndexedPrimitives:…]+0x50, called fromdraw_, right after the log linetexture upgraded to allow format views(Metal API validation reports nothing first). - Cause:
draw_takes its render encoder fromrp_begin_ex, then binds the program's arguments (encode_args). Binding a texture view of another format callstex_by_id, which upgrades a texture made withoutPixelFormatView(tex_upgrade); the upgrade copies the old texture throughblit(), which ends the render pass (rp_end). The draw then encoded on that ended encoder: the driver reads the context it released at end of encoding (ldr x21, [x0, ivar], then[x21 + 0x794]). - Fix: after
encode_args, a draw whose pass ended (g_enc != en) is encoded again from the start in a new pass; the texture is already upgraded, so the second binding does not end it (a second end would be logged red and the draw skipped). - Found on: Need for Speed: Hot Pursuit Remastered (a 4096x1024 texture sampled through a view of another format at its first loading screen).
Compressed textures as render targets through an uncompressed shadow
- Symptom:
render target is a compressed-format texture …; the pass's draws did nothing (the attachment was left out), or the pipeline-descriptor validation aborts the process. - Cause: a GPU block encoder writes a BC texture through an uncompressed integer view (one texel per block). Metal can neither attach a compressed format nor make an uncompressed view of one.
- Fix: such a pass draws into an uncompressed shadow of blocks × blocks in the view's format: the level's (or layer's, or depth plane's) blocks are copied into it through a buffer before the pass and back after it (
bcrt_attach/bcrt_flushinnvn_mtl.m; the method comes from PR #11). The shadows stay resident and are reused, and they are kept out of the load-skip and store-elision bookkeeping.attach, the pipeline prediction and the sampling views go by the NVN format, so BC textures are never attached or viewed raw. The encoder's output must be declareduint(Integer fragment outputs declared by hand). - Found on: The Legend of Zelda: Breath of the Wild: agl's BC4 block encoder (
8e2cc2671cae6020) writes a 32×32 RGTC1 (BC4) texture through anRGBA16UIview (one texel per 8-byte block); its twin for a 2D source (93aa5e22a8202409) failed in an iPhone run; GitHub issue #4 (reported from an iPhone 14 Pro / A16). The Legend of Zelda: Tears of the Kingdom: agl's BC4 block encoder (0544282c162305db, the same shader Mario Wonder ships) encodes a 32×32×32 BC4 3D texture one depth plane per pass through anRGBA16UIview; a raw dump at frame 1500 of the new-game route: the texture was all zeros before, now all 32 planes hold encoded blocks. - Note: the A16 has no BC formats; the host used to store BC textures decompressed on such GPUs (about 3.9 GB instead of 2.8 GB for BotW, over iOS's limit on a 6 GB iPhone), and that path has since been removed: only GPUs with BC are supported (GPUs without BC textures are refused at start).
GPUs without BC textures are refused at start
-
Symptom: on an iPhone before the A17 Pro, the game runs until its first BC texture, then
failed assertion 'Texture Descriptor Validation' … MTLTextureDescriptor has invalid pixelFormat (134).(or another number from 130 to 153, Metal's BC formats; 134 isBC3_RGBA) andCRASH sig=6, the backtrace throughtex_mtl,tex_by_idandencode_args. -
Cause: BC textures are created and uploaded as BC, with no decompression path (Compressed textures as render targets, note), and the A16 and older iPhone GPUs have no BC formats (
MTLDevice.supportsBCTextureCompressionfalse). The format mapping is right; the device cannot make the texture. -
Fix: the device is checked before the game starts. The iOS app checks it when Play is pressed (
front_ios_device_checkindm/ios/Sources/main.m, called bystartGameinfront_ios.m, or at once in an app without a launcher) and does not start the host on such a GPU: the screen says the device is not supported and names the GPU and the devices that are (iPhone 15 Pro or newer, M1 iPads or newer), and the log has a[RED] boot:line. The host's early loading, which makes no device, still starts at launch on such a GPU and is left unused.mtl_init(nvn_mtl.m) stops every other route the same way, with aFATAL … has no BC texture formatsline, for the NVN, Vulkan and GL layers alike. A virtual Mac without Metal 4 can still use the classic-only path for shader capture.The iOS check creates a Metal device, so it runs after Play has applied the launcher settings. On an M4 iPad Air, applying the Performance HUD choice at Play was still too late.
boot_envnow applies the saved HUD choice beforeUIApplicationMainwhen saved choices are in use and there is no explicit override. If the saved choice enabled the process HUD and the player switches it off before Play,startGamedisables the HUD on the game layer. A first-time switch on takes effect at the next launch. GitHub issue #840 · M4 iPad Air verification -
Found on: FINAL FANTASY X/X-2 HD Remaster: GitHub issue #704, an iPhone 15 (A16) with another region's copy (
0100B3600AE9A000): the launcher ran (no BC textures), FFX aborted at its first BC3 texture.
A depth texture drawn through a colour view
- Symptom: the boot aborts in Metal's pipeline validation:
MTLPixelFormatDepth16Unorm is not color renderable. - Cause: a depth texture drawn through a colour view (a 1024×1024 D16 texture through an R16 view); Metal has no colour view of a depth texture.
- Fix: such a pass draws into a colour shadow of the same pixel size, copied in before and back after the pass through a buffer, as a compressed render target is (Compressed textures as render targets through an uncompressed shadow;
shrt_block; D16 and D32F, whose Metal pixel is the NVN pixel; not D24S8). - Found on: Luigi's Mansion 3.
The same texture attached at two colour slots
- Symptom: a G-buffer target holds only scattered squares (a different order for each 32×32 tile).
- Cause: on Maxwell the ROP writes only masked channels, so two slots holding the same texture with one at write mask 0 do not interfere. On Apple's TBDR each attachment has its own tile memory and the whole tile is stored at the end of the pass, so the copy stored later (loaded, never written) overwrote the other one's writes.
- Fix: a slot whose texture, level and layer repeat an earlier slot is left unattached (
rt_dup_slot), also in pipeline prediction; a draw that really writes such a slot is reported once (color slot … holds the same texture as an earlier slot). Records hold copies of texture objects (tex_snap), so slots are compared by serial, not by pointer. - Found on: The Legend of Zelda: Breath of the Wild: the G-buffer passes attach the albedo and another buffer twice each (c1 = c2, c3 = c4), the duplicate slots with write mask 0; the albedo held only scattered squares.
Passes with no render target
- Symptom:
no render target could get an MTLTexture(the pass skipped). - Cause: a fragment shader that only stores to a storage buffer draws into a viewport with no colour or depth target set.
- Fix: the host opens an attachment-less pass at the viewport's size (
bare_dimsinnvn_mtl.m, from PR #11). - Found on: The Legend of Zelda: Tears of the Kingdom: an agl fragment shader draws one triangle into a 1×1 viewport (it samples a 64×64 cube map, and the game reads the result back from the buffer). Compared at the same frames of the new-game route, the cave's rock and stone blocks now get ambient light they lacked, and Zelda's bloom halo in the descent cutscene is gone.
Layered passes for vertex shaders that write the layer
- Symptom: a black world: everything rendered through a 3D LUT built by layered draws comes out black (every plane went to plane 0);
DM_NVN_PASSDUMPshows noLline. - Cause: a Metal vertex shader selects the attachment layer per primitive only when the render pass has
renderTargetArrayLength. - Fix: a draw whose vertex shader writes the layer opens a layered pass (
g_rp_layeredindraw,g_pass.layeredinrp_begin_ex): the pass gets every layer the attachments have from their attached one on (3D textures: depth planes), and it is split when the next draw's shader differs.DM_NVN_PASSDUMPprintsL … layered pass: n layers. - Found on: Pokémon Legends: Z-A: the 3D scene came out black once the opening reached Lumiose. The game builds its 32×32×32 colour grading LUT with
b29f08619f379a83, one instance per depth plane, each writing its plane throughrender_target_array_index, and tone-maps the frame through that LUT.
Passes into other layers of one texture level run as one layered pass
- Symptom: a frame-time spike every few frames (the Metal HUD's frame-time line jumps by several ms at a regular interval) while the scene stands still;
DM_NVN_GPUPROFover consecutive frames shows the slow frame with about 130 more render passes, each one draw into a 64x64 to 8x8 face of a cube or array level, and the next pass starting late. - Cause: on Apple GPUs a render pass costs about 35–40 µs whatever it draws (M2 Max, with or without barriers: a Metal 4 microbenchmark of 132 one-draw 64x64 cube-face passes took 5.4 ms, 4.2 ms without barriers). An environment cube map filtered face by face, one pass per face and level, pays that cost once per face.
- Fix: the draw that opens a pass looks ahead (
sm_scan,sm_planinnvn_mtl.m): when its only target is one layer of an array or cube texture level and the following targets switch to other layers of the same level with nothing but state, uniform updates and draws between them (no game barrier, clear, copy or dispatch), the pass is opened over those layers (renderTargetArrayLength) andOP_SET_RTswitches layers inside it. Each draw reaches its layer through a vertex amplification view mapping (count 1,renderTargetArrayIndexOffset); a pipeline built with the defaultmaxVertexAmplificationCountof 1 ignores the mapping (every draw landed in the first layer), so these draws use pipelines built with 2 (sm_amp_get, keyedAMP_MARK), compiled in the background on first use while the passes stay apart. A draw that samples the attachment or a clear ends the merged pass.DM_NVN_SLICE_MERGE=0turns it off;DM_NVN_PASSDUMPprintsL … slice-merged passandM … goes on in layer n, and the residency set line counts merged passes and layer switches. - Found on: Breath of the Wild: every tenth frame filters the environment cube map in 132 passes (22 levels of 6 faces); 284 → 173 render passes in that frame, frame p95 13.2 → 11.1 ms at 900p on an M2 Max.
- Check:
DM_NVN_TEXDUMP=layers=100:pathdumps the first such frame with and without the switch: the 173 targets matched (105 identical, the rest within 1% RMSE, the scene's rain). - Resolved in review of #213: the first draw now gets the attachment-read check before planning a merged pass. Every later check refuses unknown bindless/dynamic reads (
TEXU,TEXD,TEXA, image atomics and their reflection flags), and considers textures sharing the attachment's storage. Slot-only reads cannot prove those draws independent.t_perf_orderchecks all six array layers' pixels and five actual continuations after pipeline warm-up, plus the first-draw and unknown-read refusals. It runs with both encoding modes and merging disabled. - Compact binds (2026-11-16): the look-ahead ended at the compact uniform and vertex buffer binds the recorder writes (
OP_BIND_UBO_SMALL,OP_BIND_VBUF1), plain state asOP_BIND_UBOandOP_BIND_VBUFare, so a game that binds them between its layers merged at most two.sm_scantakes them as state. Mario Kart World draws three runs into the five layers of a 128x128 array and one into a 64x64 array of six every frame, binding them between layers: merged in pairs (0-1, 2-3, then 4 alone) and the later runs not at all, about 9 passes more a frame. In a handheld race at the 60 fps cap (M3 Max, the bind look-ahead alternated in 300-frame phases, both orders): 9.0-9.1 fewer passes a frame, GPU time -1.03 to -1.23 ms a frame, replay CPU -0.15 ms, process CPU -0.35 to -0.52 ms, CPU energy -0.15 W in both orders.t_perf_orderbinds them between some of its six layers, and fails without them taken as state.
A draw into the six faces of a cube level at once ran short of threads
- Symptom: in
DM_NVN_GPUPROF, render passes with six colour attachments on the faces of one cube level take far longer than their size explains: a 2x2 level as long as a 16x16 one (65–120 µs each), a 64x64 level 200–300 µs. - Cause: the draw's fragment shader computes all six outputs in one thread, each from its own face's direction. Mario Kart World's cube map filters make 32 cube samples per face, 192 per thread. A 64x64 level is 128 SIMD groups of such threads, a 2x2 level one, too few to hide the samples' latency: the pass costs a few long threads, whatever its pixel count.
- Fix:
fsp_planinnvn_mtl.m, for every game. A draw of at most six vertices and one instance, whose four to eight colour targets are distinct layers of one level of one array or cube texture, is drawn once per target into one layered attachment. Each draw has a pipeline with only that target's colour output, built whole (PSO_FACEinpso_build_ex), so the compiler drops the other outputs' work; the encoder's colour attachment map sends that output to the one attachment, and a vertex amplification view mapping sends the draw to the target's layer, as in slice-merged passes. The same samples then run in six times the threads. Each output is the same function of the same inputs and lands on the same texel. The draw keeps its targets when it could tell the difference or when a precondition is missing: blending, alpha to coverage, a logic operation or alpha test, a depth or stencil target, a fragment that may discard or writes the sample mask, any storage or image write (made once per layer), a read of its own targets, a target it does not write, a clear, a texture whose layers cannot be attached together, no Metal 4 compiler, or pipelines still building in the background. The pass holds that one draw and ends after it.DM_NVN_FACE_SPLIT=0turns it off andabalternates it withDM_AB;DM_NVN_PASSDUMPprintsL … face-split pass. - Found on: Mario Kart World: three chains of six levels a frame (GearPassShader
4744589bb8f9f7dd, DrivePassShaderDefault765844f5609bb11b) and three other six-face passes. Per pass on an M3 Max, docked race: 64x64 271 → 66 µs, 32x32 150 → 30 µs, 16x16 to 2x2 about 95 → 21–25 µs. In-run A/B (DM_AB=300, uncapped, nine phases against eight): docked GPU p50 9.53 → 8.57 ms with the frame unchanged at about 13.1 ms (that run was bound elsewhere, with other processes loading the CPU); handheld GPU p50 7.93 → 7.37 ms and frame p50 9.59 → 9.31 ms, shorter in each of six phase pairs. - Check: a Metal harness drew all six levels of a chain with the game's uniform blocks (
DM_NVN_CBDUMP) both ways and read them back: no texel differs.t_perf_orderdraws six outputs into six array layers in reverse order through the replay: before the pipelines are built, after the split (one face-split pass), and with a fragment that may discard (no split); every layer holds its own output each time.
Face-split passes of one level size, one per texture
- Symptom: in
DM_NVN_PASSDUMP, face-split passes (L … face-split pass) of one size a few passes apart, each into another texture or another cube of an array and each with its one layered attachment; inDM_NVN_GPUPROFeach small one costs about as much GPU time as a larger pass. - Cause: a face-split draw holds its pass alone (A draw into the six faces of a cube level at once ran short of threads), and a game that filters several cube maps level by level draws each chain's levels in a row. Mario Kart World's three chains (one cube texture, and an array of two cubes) come as A0 B0 C0, A1–A6, B1–B6, C1–C6: 21 passes a frame, though each level of a chain samples only that chain's source cube.
- Fix:
fsm_plan,fsm_attachandfsm_runinnvn_mtl.m, for every game. When a face-split pass is about to open, a scan of the ops after its draw in replay order (as for dispatches moved ahead of a pass) applies the state and target changes and finds face-split draws into other textures or layers whose level has the same size, format and layer count. Up to three join the pass as attachments 1–3 (a colour attachment map sends their outputs there) and are drawn after its own draw with their own state; the replay skips them where it reaches them (fsm_take). One joins only when nothing passed over reads or writes its targets and nothing passed over writes what it samples. Every draw passed over must draw into colour targets only and sample known textures (texture and read-only image slots: no bindless, pool, handle, buffer-texture, storage or global memory reads), and the scan stops at any other draw or op (a clear, a copy, a dispatch, an inline uniform update, a query); nothing joins while lazy clears or deferred uniform updates wait or occlusion samples are counted.DM_NVN_FACE_MERGE=0turns it off,abalternates it withDM_AB. - Found on: Mario Kart World: the cube filter's 21 passes become 7, about 101 → 87 passes a race frame. In-run A/B (M3 Max, handheld race,
DM_AB=300,DM_NVN_GPUPROF=every:20, a Mac busy with other apps): at the 60 fps cap the GPU time of passes up to 64x64 −0.67 and −0.76 ms a frame in the two phase orders (lower in six of six pairs each), the render passes' GPU time −0.54 and −1.15 ms, system GPU energy −0.60 and −0.26 W; uncapped, GPU p50 −0.52 ms handheld and −0.52 ms docked (six of six pairs each), docked frame p50 −0.38 ms. Process CPU unchanged within the noise. - Check:
t_perf_orderdraws X level 0, X level 1, then layers 0–5 and 6–11 of Y at levels 0 and 1, each a face-split draw with six outputs, into textures cleared first: two passes of three attachments with the merge, six without, every layer of both levels holding its own output, under Metal validation (check_t_perf_orderalso runs it withDM_NVN_FACE_MERGE=0). - Ordering: the scan resolves texture and image slots in the execution descriptor pool, checks each draw's full reads before adding them to earlier reads, and checks texture storage overlaps even across different serials. It also checks vertex, index and uniform buffer reads and stops at unknown or sparse storage. The pixel fixture checks a draw that samples a texture before a write and another that samples it afterwards, including with the same slot in a second descriptor pool.
Compute dispatches between the draws of a pass run ahead of it
- Symptom: a GPU-bound frame with many passes on the same targets, one after the other, each preceded by a compute encoder of one dispatch (
DM_NVN_GPUPROF:compute / copy after pass … dispatches 1between render passes of the same size); about 4 ms of GPU idle a frame inside command buffers in Metal System Trace. - Cause: Metal cannot dispatch compute inside a render pass, so every dispatch between two draws ends the pass; on Apple GPUs each extra pass and encoder costs its fixed 35–40 µs plus the store and reload of every attachment.
- Fix:
cs_hoist_try(nvn_mtl.m,DM_NVN_CS_HOIST, on by default,0off): when a draw opens a pass, the ops up to the first one that would end the pass anyway are scanned, and each dispatch met on the way runs before the pass when moving it ahead of the draws before it changes nothing they read (no storage buffer they read, no colour attachment of the pass sampled, no image written, the draws write no memory). A dispatch that samples the pass's depth moves only while no draw before it in the pass writes depth, so it sees the same depth.DM_NVN_PASSDUMPprintsH … dispatch … moved ahead of the pass; the residency set line counts moved dispatches and why scans stopped. - Found on: Breath of the Wild: the NintendoWare VFX GPU particles run one dispatch per emitter between the effect draws of the G-buffer and of the half-resolution passes; 28 → 8 compute encoders and 149 → 132 render passes a frame, frame p50 9.9 → 9.0 ms at 900p on an M2 Max. Its particle collision samples the G-buffer depth, and no draw before those dispatches writes depth (counted: 0 stops).
- Check: the cube-filter frame's 173 targets dumped with and without (
DM_NVN_TEXDUMP=layers=100): every 3D target within 0.7% RMSE; only the 2D overlay of the final picture differed (a loading banner's animation, timed by the wall clock). - Resolved in review of #213: a nonzero game barrier stops the scan. A sample of depth-stencil storage cannot move ahead of either a depth or stencil write. Unknown indexed-indirect ranges and bindless/dynamic draw texture reads refuse hoisting; fixed-slot sampled textures contribute their storage ranges (including linear and buffer-backed textures). Sparse virtual addresses, unknown sizes and overflowing ranges do not prove independence. Compute uniform/storage accesses overlapping attachment storage also refuse hoisting; sampled texture storage is compared by extent, including different offsets into one linear buffer. Texture registration uses its actual unfair lock. These are general dependency checks, without profile rules.
- Regression:
t_perf_orderdrives the production replay with an independent dispatch (moved exactly once, GPU writes 73), an explicit barrier (not moved), and the scanner with a stencil-only view after a stencil-writing draw. It also checks indirect index ranges, sampled buffer storage, unknown texture reads and aliased attachments. The initial PR failed 13 harness assertions; restoring only its depth-only write guard makes the stencil case fail too. The fixed harness passes under Metal validation in both encoding modes and with optimizations disabled. BotW gameplay exercises both optimizations on/off; it retains pass savings but does not demonstrate a timing gain in the tested 60 fps workload. Metroid Dread gameplay broadens coverage without activating either optimization.
Clears of attachments larger than the render pass
- Symptom: a scene drawn only in a small square in the top-left corner of a black screen; speckled and blocky patches; a full-screen overlay showing one tile; the texture dump right after the scene pass shows the picture only in the corner, and
DM_NVN_HILITEon the scene's shaders lights only the corner. - Cause: a Metal render pass covers only the smallest of its attachments, and so does a clear in its load action. A clear folded into a pass whose other attachment is smaller cleared only that corner of the larger target, so later draws failed the depth test against the previous frames' depth everywhere else. NVN clears the whole target.
- Fix:
rp_begin_ex_(nvn_mtl.m) clears an attachment larger than the pass in a pass of its own first and loads it in the real one (C … cleared in a pass of its ownin a pass dump). - Found on: Bayonetta 2: every frame starts with a pass whose colour target is 32x32 (then 256x256 ones) beside the 1280x720 depth buffer, and the game clears the depth there; the story's opening narration showed its scene in a 32x32 or 256x256 square of a black screen. Bayonetta needed nothing more.
- Not checked: the fix in other games beyond the unit tests.
Clears of layered render targets in a pass that is not layered
- Symptom: a point light (a lantern, a lighter) lights only one side of the room with straight, sharp edges, and everything else around it is dark as if in shadow; a dump of the shadow cube (DM_CTL
texraw, every face) shows face 0 drawn and faces 1-5 all zero; more generally, layers above the first of an array, cube or 3D target keep their old or zero content after a clear. - Cause: NVN clears every layer of the render target view that is bound (the whole texture without a layer range). A clear folded into a Metal pass's load action clears only the layers the pass attaches, and a pass that is not layered (
renderTargetArrayLengthunset) attaches one. When the clear lands in such a pass (the vertex capture pass of a geometry shader draw, a lazy clear landed on its own), the other layers kept zero depth from creation, every fragment the later layered pass drew there failed the depth test, and the comparison sampler read them as fully shadowed. - Fix:
rp_begin_ex_(nvn_mtl.m,att_layers) clears a cleared attachment whose view covers more layers than a pass that is not layered in a pass of its own, withrenderTargetArrayLengthset to the view's layers, and loads it in the real one, as it does for attachments larger than the pass (Clears of attachments larger than the render pass). A view limited to some layers clears only those. The pass dump printsC … cleared in a pass of its own (… N layers …).t_clear_layersruns the production replay on a cube depth target and a 2D array colour target, with and without layer ranges. - Found on: Little Nightmares (
01002FC00412C000, Unreal Engine 4, a provisional profile): its point lights' one-pass cube shadows (geometry shaderffc21034b958840b, which emits each triangle into the six faces) clear the 512x512 cube in the pass that captures the vertex shader's output; only the +X face was cleared, so the lantern's and the lighter's light passed only through that face. - Check (2026-11-01): before rebasing, the full Metal graphics suite and Breath of the Wild's full Mac route passed. These local checks used an M4 Pro, macOS 27.2 and Xcode 27.2; both regression revisions used the documented
DM_ALLOW_OTHER_METAL=1override because the installed Metal compiler was32023.922while the then-current lock pinned32023.921. After rebasing onto the Xcode 27.2 pin and #730,t_clear_layersand the image-store integration regression pass. Tears of the Kingdom's runtime comparison remains incomplete; its foreground-controlled repeat and Pokemon Scarlet's remaining checks were stopped at the maintainer's request. The other games and iOS remain unchecked here.
Lazy clears folded into the next pass
- Fix: lazy clears (
DM_NVN_LAZY_CLEAR) fold clear-only passes into the pass that follows. - Found on: The Legend of Zelda: Breath of the Wild: the four clear-only passes before the G-buffer fold into its first pass (about 30 MB less loaded and stored a frame at 1600x900).
A waiting lazy clear landed after a scissored clear and its draws
- Symptom: a scene drawn into a scissored part of a target is wiped to the clear colour, while what a later pass draws on top (UI, menus) shows. No red lines.
- Cause: a lazy clear (Lazy clears folded into the next pass) waits for the next pass that attaches its target, and a draw opening a pass takes it as a load action (
lc_take). A clear drawn as a triangle (Clears inside a pass, with a partial mask or a partial scissor) opens its pass without taking it, and the draws that follow in that pass do not either, since a pass is already open. The older whole clear kept waiting and landed as the load action of the next pass on that target, after the draws it should have come before. The zero-clear copy into a scissor rectangle (clear_rect_zero) had the same ordering. - Fix: every pass that opens takes the waiting clears of its attachments as its load actions and lands the rest before it (
rp_begin_ex_callslc_take_rt, the part oflc_takethat does not depend on a program), so no clear waits while a pass is open; a draw still callslc_takefirst, for its sampled textures and before the work it runs ahead of the pass.clear_rect_zerolands the waiting clears before its copy.dm/gfx/tests/t_lazy_clear_order.mchecks the three paths.DM_NVN_LAZY_CLEAR=0avoids it on a host without the fix;DM_NVN_UB_DEFER=0hid it too, because a uniform update then ends the pass and the next draw opens a new one, which takes the clear. - Check:
DM_NVN_PASSDUMPshows the scissoredclear drawn as a trianglelines in a pass that loads, and noC … cleared toload-action clear of that target in a later pass of the frame. - Found on: FINAL FANTASY IX (
01007EF00B094000, no profile in the repository): each field frame clears the window whole, then clears the 4:3 field view (scissor 189,0 1542x1080) as a triangle and draws the backgrounds and characters in that pass; the whole clear landed in the UI pass, so fields showed only the UI. Battles, which clear the whole window, were unaffected.
A channel mask that covers every channel is a whole clear
- Symptom:
texture clear case not implemented … mask 0x1. - Cause: an R8 render target cleared with channel mask 0x1.
- Fix: a mask that covers every channel the format has is a whole clear (
mtl_pf_chmask). - Found on: FINAL FANTASY TACTICS - The Ivalice Chronicles.
Texture clears with partial channel masks or regions
- Symptom:
texture clear case not implemented … mask 0x8while entering a rendered scene. - Cause:
ClearTextureonly handled whole-level clears whose mask covered every channel. Persona 5 Royal clears only alpha on a 1920x1080 RGBA8 target; a load-action clear cannot preserve its RGB channels. - Fix: partial colour texture clears use the existing clear-triangle shaders in a load/store pass, with the requested channel mask and rectangle. The viewport comes from the selected mip, the region selects the slices or depth planes, and the current draw scissor does not affect the operation. Whole-level whole-channel clears keep the load-action path.
t_clear_texchecks pixel and channel preservation, mip/layer selection, integer values, an empty mask and the whole-clear path under Metal validation. - Found on: Persona 5 Royal, the opening casino.
Scissored colour clears
- Cause: NVN
ClearColorhonours the scissor. Clears are normally folded into the next pass's load action, which only works for a full-target clear; Mario clears sub-rectangles of small targets to zero (pyramid levels packed into 480×272, 256×256 and 64×36 targets). - Fix: a zero clear outside a pass with a partial scissor is now a copy from the shared zero buffer into that rectangle of the attachment's level / slice (
clear_rect_zero). - Check:
DM_NVN_CLEARLOG=1logs clears that are still skipped (mid-pass, partial channel mask or non-zero colour with a partial scissor). - Found on: Super Mario Bros. Wonder.
Clears inside a pass, with a partial mask or a partial scissor
- Symptom: red lines for unimplemented mid-pass, partial-mask and partial-scissor clears (the clears were dropped);
depth-stencil clear with a scissor or partial stencil mask, cleared whole(logged once). - Cause: NVN clears obey the scissor and the clear's own channel or stencil write mask, and can come between draws, while a Metal load action clears a whole attachment at the start of a pass.
- Fix: such clears are drawn as one triangle over the pass in the open render encoder (
clear_color_tri/clear_ds_triinnvn_mtl.m, adapted from MacNativeGames, MIT). The pipeline has the pass's formats, the clear's mask as the write mask of its slot and no writes to the other slots. Depth isALWAYS(and written for a depth clear), stencilREPLACEthrough the clear's write mask, the scissor is clamped as for draws, and visibility counting is off for the triangle. The value comes from the frame arena through the triangle's own argument tables, and the draws' tables are put back after it. A clear outside a pass opens the pass as a draw would. Clears a load action can express keep it. Two cases are still cleared whole, logged once: a depth / stencil clear with a scissor outside a pass, and a partial stencil write mask. - Found on: The Legend of Zelda: Tears of the Kingdom: it issues the first whole-cleared case (a depth clear scissored to 8×8 of a 64×64 target), and so does Wonder (Super Mario Bros. Wonder). With the conditions evaluated (Conditional rendering evaluated at replay) TOTK's scissored colour clears are all skipped; without it they are 50×50 tiles of a 500×400 target cleared to opaque black, about five a frame. Metroid Dread logged the red line once while loading on its smoke route.
A depth clear over the whole target with a partial stencil mask
- Symptom: a pass loads a whole depth/stencil target every frame only to clear it: Donkey Kong Bananza clears a 2880x1620 Depth32F-S8 target with stencil mask
0x1, before any pass is open, and loads 22.8 MB a frame for it. - Cause: any stencil mask other than 0 or 0xff takes
clear_ds_tri, for depth too, and the triangle's pass loads both planes. - Fix: with no pass open and a depth clear that covers the whole target, the depth half is the next pass's load action (
OP_CLEAR_DSinnvn_mtl.m), and only the stencil is drawn. A clear that is partial in either sense, or made with a pass open, keeps the triangle for both. - Check:
t_clear_ds: the depth and stencil planes after a masked stencil clear with a full depth clear, outside and inside a pass. - Found on: Donkey Kong Bananza (issue #1138): on an M2 MacBook Air the pass went from 346 to 284 µs of GPU time and its load from 22.8 MB to 4.6 MB a frame.
Depth16 load-clears match fragment writes
- Symptom: a tile grid in Ultrahand and Recall highlights; an
EQUALdepth test rejects fragments writing the same depth as a cleared Depth16 target. - Cause: Apple GPUs truncate a
Depth16Unormload-clear but round fragment depth. A clear of 0.5 stores 32767 while a fragment writing 0.5 stores 32768. - Fix:
nvn_depth16_clear_valueselects the nearest D16 value in double precision and adds a quarter-unit margin inside both its truncation and rounding bins, surviving Metal's conversion of the descriptor to float. Both attachment load-clears (rp_begin_ex_) and whole-texture clears (clear_tex) use it only forDepth16Unorm. Other formats and clears drawn as fragments retain their existing conversion.t_depth16_clearcompares both production command paths with fragment-written reference depths, including half-bin boundaries and adjacent floats. - Found on: The Legend of Zelda: Tears of the Kingdom, reported in MacNativeGames commit
3d90e41and ported in PR #199. The conversion difference is reproduced here with a synthetic Mac GPU test; the game's highlight effect and the iPhone have not been rechecked.
Integer colour clears
- Cause:
nvnCommandBufferClearColori/ClearColoruiclear an integer target. - Fix: recorded as a float clear; both replay paths convert the value to the attachment's integer type.
- Found on: Paper Mario: The Thousand-Year Door (an integer target cleared once Mario stands on Rogueport's docks, about frame 12,300 of a new file).
Same-pass feedback read through a snapshot
- Symptom: solid magenta blocks, exactly (255, 0, 255), hard-edged and aligned to the 16-pixel grid (16×16, sometimes two stacked): Super Mario 3D World and Super Mario Odyssey showed them only on the iPhone; Captain Toad and Origami King on a Mac, Apple M6, Captain Toad in about half the frames of the opening course, moving with the falling leaves. On an RG11B10F target (no alpha) the blocks are pure black or neon green, (0, 252, 0), and flicker, sometimes only part of a tile: Super Mario Bros. Wonder on an Apple M6 and an M1, most visible on the speech bubbles of dialogue; or non-finite pixels that bloom spreads into green blobs (NieR:Automata on the Mac). A rendered cutscene alternates brightness every game frame, with blocky bands of light and shadow switching on and off: each lighting-zone bit flips every frame (Xenoblade Chronicles 3, a read-only image load).
- Cause: a draw writes an attachment while sampling it (agl's post-effect program writes the RGB10A2 image as an attachment while sampling it; Origami King's anti-aliasing and NieR's FXAA likewise). Writing and sampling one attachment within a render pass is undefined in Metal: the M4 Pro happens to return the old content, while the A20 Pro and the Apple M6 now and then return whole 16×16 blocks as (1, 0, 1), probably blocks of the compressed render target caught while another tile stores them. On the Switch the read returns the content from before the draw.
- Fix:
fb_prepareinnvn_mtl.m, for every game. A draw whose fragment stage samples the level and layer of a colour attachment of its pass, and that writes that attachment (its channel mask and the shader's fragment outputs) or follows a draw of the same Metal pass that wrote it, samples a snapshot instead: the host ends the pass, copies the attachment's level and layer into a snapshot texture in the replay stream and binds it for that draw. NVN makes rendering visible to texture reads only throughnvnCommandBufferBarrier, so a snapshot taken since the game's last barrier (and in the same submission) holds everything the game may expect to read: later such draws reuse it without ending the pass. A pass that read the attachment directly ends before a draw that writes it, so the earlier reads cannot see these writes in other tiles. A draw that samples an attachment nothing in its pass writes reads it directly. A sampled view that spans more levels or layers than the attachment's gets what the levels its sampler reads need (Mip-chain pass sampling the level it renders). A draw that samples the attachment at its own pixel reads the tile instead (Same-pass feedback read from the tile). The binding scan covers combined slots 0–127 and separate texture slots 128–255 (NTEX), using the argument encoder's handle lookup; an earlier bound of 128 silently skipped separate bindings. Before this rule, each game's profile listed its shaders in afeedback_snapkey (six profiles), and a shader not yet seen to break stayed unprotected.DM_NVN_FB_SNAP=0turns the snapshots off,alltakes a fresh one for every draw that samples an attachment of its pass. - A clear still waiting: a clear with no draw after it waits to be the load action of the next pass on its targets, so when the draw that takes a snapshot is the first of its pass, the attachment still holds what it had before the clear. The copy lands that clear first (
rp_flush, not only the end of an open pass), for the colour snapshots and the depth copies (Depth sampled in the pass that writes it): before, a game that clears a target, sets a barrier and then draws into it while sampling it read the content from before its clear. Found by reading issue #1932's patch, not seen in a game;pending_clear_caseandreal_depth_snap_casewith a clear waiting check it (they failed before). - Uniform-buffer handles: a texture a shader names by one handle in a uniform buffer (
NVN_RB_TEXUwith no count) follows the same rule:fb_prepareresolves the handle as the argument encoder does (ubo_bind_handle,ubo_tex_id), and the encoder puts the snapshot in its place as for a slot (fb_snapshot_slot). Before,fb_preparelooked at texture and image slots only, so such a draw read the attachment it blended into in the same Metal pass, andDM_NVN_FB_SNAP=allchanged nothing because no read was seen, while the pass dump still showed it (R … ser=of the attachment). A handle has no slot, so it never reads the tile, and its sampler is not a slot's, so no level is pinned for it. Arrays of handles (TEXUwith a count) and handle tables (TEXH,TEXA) are still not taken: the encoder does not substitute them either, and no game has shown one.check_t_feedbackruns the slot case through a handle in uniform slot 2 (it failed 5 checks before, the GPU reading the overwritten green). - Image loads: the same snapshot serves a read-only fragment image when its resolved single-level 2D view overlaps a colour attachment. Lookup and argument encoding use the same image view. Images that reinterpret the registered pixel class, writable images and atomic bindings keep their original bindings. Only sampled texture slots qualify for tile reads.
- Check:
make -C dm/gfx/tests GAME=<id> check_t_feedbackexercises the production snapshot and argument encoder at slots 0, 128 and 255 (GPU readback must retain a red snapshot after the original attachment is overwritten green, then read the green original on the next draw), and the rule: a draw that writes nothing reads an unwritten attachment directly, a writing draw takes a snapshot, the next one reuses it without ending the pass, a writing draw after a direct read ends the pass, a game barrier makes the next one take a fresh snapshot. 69 checks pass with Metal API validation on the Apple M6. On that Mac without a list (2026-10-30): Origami King's castle route went from blocks of up to 273 magenta pixels in its screenshots withDM_NVN_FB_SNAP=0to 0–8 single pixels; Wonder's opening course from blocks in 4 of 97 screenshots to 0 of 160; NieR's opening flight from 662,086 non-finite pixels in 19DM_NVN_MAGSCANframes to none. Each snapshotted only the shaders its profile had listed. - Found on:
- FINAL FANTASY XII THE ZODIAC AGE (
0100EB100AB42000, its bring-up in PR #2528): every limit break (Quickening) drew magenta strokes and short coloured dashes over the screen on a Mac (M3 Max), and purple blocks on an iPhone. The overlay layer (1920x1080 RGBA8) is drawn in one pass; its echo shadere40adef79f6f29b7(6 draws a frame) samples that layer through a uniform-buffer handle while blending into it.DM_NVN_SKIP_FS=e40adef79f6f29b7removed the strokes,DM_NVN_FB_SNAP=alland=0changed nothing; with handles taken, both devices draw the limit breaks right (reported in the PR). - Xenoblade Chronicles 3: the lighting shader reads its zone mask through an image slot.
- Super Mario 3D World + Bowser's Fury:
DM_NVN_MAGSCANon the A20 Pro found the blocks first in the 1920×1080 RGB10A2 composite (ser=30) in World 1-1, in the pass whose shader66a71a3081b91b9arenders into that texture while sampling it. They kept appearing with the sparkle particle5e4de7561c670feedropped, so that earlier suspect (picked by position) is not the cause. The profile listed66a71a3081b91b9aand30e3ccb0bd304ead(which samples a G-buffer target of its own pass on the title screen); in 1-1 that is one 8 MB copy per frame.3e8567da37eb28a1renders level 1 of a texture while its view covers levels 0–4: a mip-chain pass, which samples the levels below (Mip-chain pass sampling the level it renders). The source said the fix was in place and waiting for a device run when written; the README lists the game as tested and playable on the iPhone. - NieR:Automata The End of YoRHa Edition: its FXAA (
fd2c47b73f0e7e24,filter09.pso) samples the RG11B10F scene target it renders into through a separate texture bind, andfb_preparetook only combined slots (b->reg >= 128was skipped), so the key had no effect. On the Mac some of its reads came back NaN in red and blue; the bloom spread them into green blobs and the eye adaptation darkened the frame (DM_NVN_MAGSCAN: 50,000+ non-finite pixels a frame over the opening's ocean, 0 with the snapshot). Separate texture binds now take the snapshot too. - Captain Toad: Treasure Tracker: agl's post-effect program 987 (
54f58a7cab608766, the same program as 3D World's66a71a3081b91b9ain another build);DM_NVN_FB_SNAP=allcleared every frame and named this one shader, which the profile then listed. - Super Mario Odyssey: 16×16 magenta blocks on an iPhone 17 Pro (1.4.1), reported with
DM_NVN_FB_SNAPruns that named the same agl post-effect program (5345f3231650f0b7) on the 1280×720 RGB10A2 image (seedds/nxnative#544). Odyssey draws it so only in handheld mode (the iPhone's): docked, it renders at 1600×900 and the post-effect reads another target. The report proposed a sixth list; the host now finds such draws itself, and on the Mac withDM_OPMODE=0the rule snapshots this shader from frame 617, where the iPhone's log had named it. - Super Mario Bros. Wonder: black and green blocks on the Mac (Apple M6; an M1 in seedds/nxnative#377) from its two feedback draws
a7e5c6fd501cf21fand22a61cb1ec732aefon the RG11B10F scene, the same keys in v0 and 1.2.1, which had shown nothing on the iPhone. Screenshots with a flicker detector: v0's opening course 6 of 160 frames with blocks before, 0 of 150 with both listed; 1.2.1's Badge House dialogue 23 of 158 before, 0 of 158 after. - The Legend of Zelda: Breath of the Wild: the cost case (below): over a thousand draws a frame sample a G-buffer target of their own pass, about 460 of them writing it.
- Paper Mario: The Origami King: magenta 16×16 blocks on the Mac (Apple M6) from its anti-aliasing pass
8dc20835c07cd7ff(shaders/aa.bfsha) on the 1920×1080 RGB10A2 scene, the only shaderDM_NVN_FB_SNAP=allsnapshotted; about one block a frame at Peach's castle before, none with it listed.
- FINAL FANTASY XII THE ZODIAC AGE (
- Note: the cost. Breath of the Wild's G-buffer decals write and sample their own targets (
4d3d5a4408c2e8d9,753d0169ae3ce4f0and others on the 1600×900 G-buffer), about 460 such draws a frame outdoors on the Great Plateau; a fresh snapshot for each (DM_NVN_FB_SNAP=all) takes the Mac's GPU time from about 4 to 28 ms a frame (frame time 16.6 → 36.6 ms before). Between the game's barriers they need about ten snapshots a frame, and about 50 draws reuse each: GPU time p50 3.5–4.1 ms withDM_NVN_FB_SNAP=0and 3.7–4.5 ms with the rule over four runs each (2026-10-30, Apple M6, the outdoor save looking around, frames 4,800–6,900; the frame time stays at its 30 fps budget). The decals had shown no blocks on the iPhone; the snapshot makes them read what the Switch guarantees rather than what the tile happened to hold.DM_NVN_FB_SNAP=allwith a screenshot detector shows whether blocks come from such a draw at all, and a pass dump (N … same-pass feedback samplinglines after the draw'sKkeys) names the shaders.
Same-pass feedback read from the tile
- Symptom: a scene full of deferred decals runs far below its target where the same scene with
DM_NVN_FB_SNAP=0holds it, and the log'ssame-pass feedback sampling: snapshot #…count climbs by hundreds a frame. Tears of the Kingdom's first shrine on an iPad Pro 11 (M5): GPU p50 58.8 ms, about 15 fps, about 284 snapshots a frame (seedds/nxnative#737); Breath of the Wild on the Great Plateau, camera toward the Temple of Time, on an iPad Pro 13 (M4): 60 → about 42 fps, about 45 one-draw passes more a frame on the 1920×1080 G-buffer. Splatoon Raiders in inked stages on a MacBook Air (M2): GPU p50 22–26 ms against 11–14 ms in the hub, a one-draw pass and a whole-map snapshot of its 6400×6400 ink map (80 MB) for each ink stamp (seedds/nxnative#1063). The[nvn] same-pass feedback up to frame …line (every 300 frames) gives the snapshots, reuses and tile reads per frame. - Cause: the snapshot rule is right but each snapshot costs a pass end, full-size copies and a pass reopened with every attachment loaded. The games issue a barrier (
0x12,ORDER_FRAGMENTS | INVALIDATE_TEXTURE) before each decal that reads the G-buffer it writes, and such a barrier makes rendering visible to texture reads, so every decal after one needs a fresh snapshot. The turnaround between passes dominates (about 250 µs a pass on the M4 iPad, against 7–10 µs of work), so the cost is far higher on iPads than on a Mac. The decals sample the G-buffer at their own pixel: their vertex shader writes the clip → screen varying((x + w) / 2, (w − y) / 2, ·, w)ofgl_Position, and the fragment shader samples at its.xy / .w. Splatoon Raiders' ink stamps (6a5b76a60670e513) set a barrier before each stamp too, and sample the map atgl_FragCoord.xyover the render scale timesc[6].xy, which an inline uniform update sets to 1/6400 just before. - Fix: in the chain and the host, for every game.
dmsh_fetch.pyrewrites a sample atin.m_X.xy / in.m_X.win the readable-tile version (<key>_bf) as it does a sample at a plain interpolated output, and marks it projective;screen_varyingsproves on a vertex shader's source that output X is the screen varying in every entry point (final assignments at the function's top level, one return, variables assigned once, constant coefficients). It also rewrites a sample at(gl_FragCoord.x [/ render scale] * U, gl_FragCoord.y [/ render scale] * V), U and V uniform components, and records them (frag_pos); the host's render scale is always 1.fpos_prooftakes such a sample when U and V, as the draw reads them, are 1 / the target's width and height (within 1/256 of a texel at the far edge):gl_FragCoordis the pixel centre whatever the viewport, and a lower-left window origin stores the image bottom-up, so its rows andgl_FragCoord.ymove together.ubo_floatgives the value of an inline update queued earlier in the submission instead of refusing it (pend_read).fb_tile_planinnvn_mtl.mthen makes a draw whose every sample of an attachment of its open pass is such a sample (for a projective sample the viewport over the whole target with no swizzle, upper-left window origin and no tessellation or geometry stage; the sampled view the attachment's own level, layer and format with no channel mapping beyond 0, 0, 1 for the channels its format lacks (sw_tile: Raiders' RG8 map is sampled through red, green, zero, one), no alpha test, logic operation or multisampling, TBDR optimizations off) read the attachment from the tile ([[color(k)]]) through its_bffunction: no snapshot, no pass end. On Apple's GPUs the tile holds every earlier fragment of the pass in order, which is what NVN guarantees such a draw after a barrier, and one of the values it leaves undefined without one. The pipeline is built in the background on first use; until it is there the draw takes its snapshot, so no frame waits for the compiler.DM_NVN_FB_TILE=0turns the tile reads off. A draw that opens its pass reads the tile too: the pass loads the attachment, or clears it to what a waiting clear gave it, so the tile holds what a snapshot would. Its pipeline is named by the formats of a pass not yet open, so they are learned: the first such draw of a program on a set of targets that samples an attachment it writes takes its snapshot, andfb_early_afternotes the passrp_begin_exopened for it (64 entries, keyed by the two shaders and the targets); later ones plan with those formats and are checked once the pass opens. A pass that differs (formats, size, a slice-merged pass) is ended, the draw takes its snapshot and the pass opens again; after three such passes the entry plans no more. Predicting the formats instead would repeatattach's choices (render-target usage, view formats, shadows for compressed and depth formats, duplicate slots) and still need the check.DM_NVN_FB_TILE_EARLY=0turns this off (seedds/nxnative#2092). A tile read of an R, RG or RG11B10 attachment gives 0, 0, 1 in the channels the format lacks, as a sample does (M4 Pro, every R and RG float and normalized format);t_feedbackchecks it for RG8. - Check:
make -C dm/gfx/tests GAME=<id> check_t_feedbackrunstest_dmsh_fetch.py --fixture(Breath of the Wild's decal pair, cut down) and thent_feedbackon it: a snapshot while the tile pipeline builds, then after a barrier none, the pass still open, the GPU reading green that an earlier draw of the pass wrote and red elsewhere, and a snapshot again with a viewport smaller than the target. Then Raiders' stamp, cut down, on an RG8 attachment: with the scale 1/8 in memory a snapshot and no tile pipeline, with an inline update of 1/4 queued the proof holds, and after a barrier the GPU reads green where an earlier draw wrote it, red elsewhere, with blue 0 and alpha 1; and the channel mappingssw_tiletakes and refuses (152 checks with Metal API validation, Apple M4 Pro). Then a draw that opens its pass: one that writes no attachment it samples learns nothing, the first that does takes its snapshot and its pass is noted, the next plans with no pass open and gets the pipeline built for the open-pass case, the GPU reads the green and red its pass loaded, and a pass other than the planned one is refused, counted and followed by a snapshot, with no plan after three.test_dmsh_fetch.pychecks the spellings the rewrite takes, the ones it must refuse, and that the variants compile for the Mac and the iPhone;t_reflchecks thefrag_posfields. A frame captured looking at the Temple of Time (Breath of the Wild, chain7ea22518e071) replays bit-identical to the live frame with tile reads, and within 10 pixels by one in one byte with snapshots. - Found on:
- The Legend of Zelda: Tears of the Kingdom: the shrine slowdown of #737 (
7d1b1cac266f08f2,5733c5bf03d78005,9a5e3335514e4cbbon the 1600×896 G-buffer, vertex shaderbb19fab2f950e587). - The Legend of Zelda: Breath of the Wild: the decals
4d3d5a4408c2e8d9,753d0169ae3ce4f0and others (vertex shader095cd6ad97fd779a); about 320 draws a frame read the tile outdoors. - Splatoon Raiders: the ink stamps
6a5b76a60670e513on the 6400×6400 RG8 ink map, reported with a first patch in #1063 by David Padron-Harris.
- The Legend of Zelda: Tears of the Kingdom: the shrine slowdown of #737 (
- Note: on a Mac (Apple M4 Pro) Breath of the Wild's outdoor save with the camera turning (frames 3,000–7,000, two runs each): snapshots 28.6 → 4.5 a frame, attachment traffic 666 / 596 → 354 / 344 MB load / store a frame, render passes p50 146 → 141, GPU span (first start to last end) p50 12.15 → 11.84 ms, GPU time p50 8.87 → 8.78 ms; the Mac's pass turnaround is small, so the gain there is small. The iPad cases are not measured here. The snapshots left a frame are draws whose samples are not projective (
b2f5ae9ef79011b9on attachment 5,7636e1d2542c221a). Splatoon Raiders on the Mac (M4 Pro), the same scripted route to the first beach twice, frames 7,500–14,000:DM_NVN_FB_TILE=04.2 snapshots a frame and GPU p50 12.78 ms (windows of 300 frames, median), tile reads 0.6 snapshots, about 111 tile reads a frame (the stamps6a5b76a60670e513and649e8d19b45094e7) and GPU p50 9.50 ms; screenshots at the same moments differ only in animated water, smoke and the character. Breath of the Wild has 38 such shaders: 5 → 4 snapshots a frame and 71 → 0 draws reusing one, the same 293 tile reads. The reporter's heavier inked stage (22–26 ms of GPU on an M2) is not reproduced here. Breath of the Wild also opened about 3.75 passes a frame with such a draw, each with its snapshot; reading their tile too (#2092, measured by its author on a fork of main at413e8808): on an M4 Max at 190% render scale, uncapped, 30,000 → 4 snapshots over 11,000 frames and GPU p50 5.99 → 5.56 and 6.9 → 5.9 ms in two alternated pairs; on an iPad Pro 13 (M4) at 120%, 150 snapshots a second → 0 and GPU p50 10.88 → 10.77 and 11.62 → 10.90 ms. On an M4 Pro, the outdoors save's regress route on main (2026-11-14): 4.0 → 0 snapshots a frame, 293 → 295 tile reads, no pass refused.
Snapshot textures taken by format and size
- Symptom: the
[nvn] residency set up to frame …line (every 300 frames) shows hundreds to thousands of additions fromfb_snap's line innvn_mtl.m, gigabytes of them, and as many removals, with the residency commits' time and the submit thread's kernel time up. Tears of the Kingdom on an iPhone 17 (1.4.2, seedds/nxnative#931): 1,500-1,600 additions of 2.4 MB textures every 300 frames, residency commits 250-600 ms every 300 frames against about 25 in an older build, kernel time on the submit thread 1-2 ms a frame against 0.2. - Cause: the snapshot cache has eight entries, and a new key took them in turn. A frame that snapshots attachments of several sizes almost never found an entry whose texture had the size it needed, so it released that texture and made one: Tears of the Kingdom takes 4-5 snapshots a frame of 1600×896 and smaller targets, and every one made a texture.
- Fix:
fb_snapinnvn_mtl.m, for every game: a new key takes an entry whose texture already has its format and size, preferring one no later draw can still reuse, then an entry no later draw can reuse, then the least recently used. An entry whose snapshot a draw may still reuse until the game's next barrier is taken last, so reuse is unchanged. The cache still holds at most eight textures. - One draw's snapshots: ranking by shape let a draw overwrite a snapshot it had already bound. With all eight entries live, a draw that samples two attachments of one format and size found the first one's entry the only one of that shape, and the second attachment's copy replaced it: both bindings sampled the second attachment. No game has been seen to do this; the test below reproduces it (PR #813).
fb_snapnow marks each entry it hands out with the draw (g_draw_seq), whether cached or copied, and takes no entry the current draw holds for another key. A draw takes at most four snapshots, so four entries are always left. - Check:
make -C dm/gfx/tests GAME=<id> check_t_feedback: 30 snapshots of four sizes over six frames, each after a barrier, make four textures, and a live snapshot is not taken by another key while a stale entry is free. A draw sampling a red and a green attachment of one shape with every entry live reads red and green from two snapshots, with the first one cached or copied; before the fix both read green (4 of 324 checks failed). - Found on: The Legend of Zelda: Tears of the Kingdom. On the Mac (Apple M4 Pro, 2026-11-03, the regression route, frames 1,800-5,100) against
mainat12915a31: textures made 1,274-1,650 (4.4-6.0 GB) → 0-4 every 300 frames, residency commits 1,208-1,390 taking 150-212 ms → 31-65 taking 1.8-5.3 ms, the submit thread's kernel time 0.81-0.85 → 0.29 ms a frame (together with the readback buffers); snapshots, reuses and tile reads a frame the same (13.0, 7.0, 22.0), 59.8 fps in both.
Bindless shaders taken as depth readers
- Symptom: a scene with many bindless decals runs well below its target with the GPU busy, and a pass dump (
DM_NVN_PASSDUMP) shows long runs of one-draw passes on the same targets, each loading and storing every attachment. Fire Emblem Fortune's Weave's battle maps: 31 consecutive one-draw passes on four 1024×576 targets a frame, 126.5 passes and about 1.4 GB of attachment loads and stores a frame. - Cause:
fb_preparemarked the pass's depth attachment as read (g_fb_dread) for every fragment shader with handles in uniform buffers (rf.bindless), since which texture such a handle names is known only at replay. A later draw that writes depth then ended the pass (the depth half of the snapshot rule). Fortune's Weave's decals are bindless and write depth, so each one ended the pass the one before it opened. - Fix:
fb_texu_readsinnvn_mtl.m, for every game. A bindless fragment shader counts as a depth reader only when one of its TEXU handles, read from its uniform buffer asencode_argsreads it for the draw, names a texture of the depth attachment's serial. Pool handles (rf.pool), dynamically indexed tables (rf.dyn) and a bindless shader with a TEXA binding still count as readers, as before. Like the colour rule, the test is by serial: a depth texture read through another NVN texture object over the same storage is not seen. - Check:
make -C dm/gfx/tests GAME=<id> run. WithDM_AB=300 DM_NVN_FB_TEXU=ab(an A/B switch used for the measurement, not part of the change) on the battle map, in-process over 16 phases: passes 126.5 → 93.5 a frame, attachment traffic 603 / 784 → 239 / 420 MB load / store, frame time p50 18.9 → 17.3 ms (MacBook Pro M1 Pro). Screenshots of the same frames with the rule off and on differ only where the fog and effects animate; the decals draw the same. - Found on: Fire Emblem Fortune's Weave.
Pool shaders taken as depth readers
- Symptom: a game that reads textures through a pool runs slower than its draws explain, with passes of one draw each on the same targets. A pass dump (
DM_NVN_PASSDUMP) showsSetRenderTargetsgoing on in the open pass and the pass ending anyway. Ocarina of Time in Kokiri Forest: two frames of four had 219 passes, 127 of them on the 128x128 reflection probe's cube faces, and frame times of 15, 15, 18, 18.5 ms in a cycle. - Cause:
fb_preparemarked the depth attachment as read (g_fb_dread) for every fragment shader with pool bindings (rf.pool), since which texture a pool handle names is known only on the GPU. The next draw that wrote depth then ended the pass (the depth half of the snapshot rule). What a pool could hold does not narrow this: the game registers its depth textures in the pool every material shader reads (issue 1385, PR 1396). - Fix:
pool_ds_readinnvn_mtl.m, for every game. The shaders already report which IDs they read (read tracking), so each submission's new bits add their depth and stencil textures to a set, and a pool shader counts as a depth reader only for a texture in it. The set is keyed bytex_alias_key, what makes objects one Metal texture, so a second object over the same storage counts, and a new object of another size over reused memory does not. It has no size limit: the game makes new shadow maps as its resolution moves, and a first version with 64 entries overflowed after 3 minutes and lost the whole gain. Colour textures over the depth texture's memory do not count: Metal keeps them in textures of their own.rf.dynand TEXA bindings still count as readers. - Limit: the bitmap is read at the next submission, so the very first pass that reads a depth texture through a pool is not ended for it, as read tracking has the same lag. If a later area reads its main depth through a pool, every depth-writing draw after such a shader ends its pass again: the
pool walkline counts those passes (passes ended after a pool shader that may read depth), 0 in Kokiri Forest. PR 1430 goes the other way, not counting a draw that writes depth as a reader, which assumes a shader never reads the depth it writes; Ocarina of Time's cave fixtures do (Depth sampled in the pass that writes it). - Check:
make -C dm/gfx/tests GAME=<id> check_t_feedback(pool_depth_case). On Ocarina's walk: passes a frame 182 → 101 and level across frames, attachments 300 / 325 → 254 / 277 MB load / store, the heavy frame's GPU span 19.2 → 12.6 ms, summed GPU p50 17.5 → 15.5 ms. No depth attachment of the main pass or the probes was ever read through a pool; about 70 shadow maps were. The pictures show no tile pattern. - Found on: The Legend of Zelda: Ocarina of Time.
Depth sampled in the pass that writes it
-
Symptom: blocks over the scene where an effect compares against the scene's depth, changing from frame to frame. Short screen-aligned dashes or blocks over rock and wall surfaces, light blue (the sky behind) or black, that stay on the same surfaces as the camera moves; how large and how many depends on the tree and the render size. Per-pass snapshots (
DM_NVN_TEXDUMPwithDM_NVN_TEXSNAP) show the surface drawn whole, then a later full-screen pass painting the blocks over it. Or light square blocks, 8×8 pixels, in the sky over distant hills and trees, where a soft-edged effect fades against the scene's depth. -
Cause: a draw samples the depth attachment of its own render pass while that pass writes it: the draw writes depth (or stencil) itself, or an earlier draw of the pass did, with no barrier between them. On the console a draw reads the depth stored when it starts. On Apple's GPUs a depth attachment sampled in the pass that writes it reads whole compressed blocks of undefined content, so the shader's comparison against the sample fails or passes block by block, and Metal has no tile read for depth.
fb_prepareended the pass only for a depth write after a read (g_fb_dread, the depth half of the snapshot rule), and only in passes with a colour attachment. -
Fix:
fb_depth_ruleinnvn_mtl.m, called byfb_prepare, tracks depth and stencil separately for every game. A resolved texture binding names the plane of its Metal view. Unknown views and bindings keep both dependencies.- A draw that writes the plane it samples through a texture slot reads a copy (
fb_depth_snap). The pass ends, the attachment's level and layer are copied into a snapshot (fb_snap, the cache the colour snapshots use), and the draw's binding reads the copy. The copy is reused until the game's next barrier. - A draw that samples a plane an earlier draw or clear wrote, and leaves that plane alone itself, ends the pass first and reads what was stored. The rule applies to slots and uniform handles. Reads of one plane can continue while a draw writes the other.
- A draw that samples a plane first in its pass reads it directly. A later write to the same plane ends the pass.
The rule runs in depth-only passes too. There it takes only reads it can name: a handle table in c2 (TEXA), pool shaders and dynamically indexed tables, which the host cannot resolve to a texture, count as possible readers only in passes with a colour attachment, as before; in shadow passes they would end the pass at every draw.
DM_NVN_FB_DEPTH=0reads the attachment directly in every case, as before. The log names the first copy (same-pass depth sampling: copy #1) and the first pass ended (same-pass depth sampling: pass end #1). WithDM_NVN_FB_DEPTH_RECT=1(off by default,abunderDM_ABfor matched-thermal measurement), each depth snapshot tracks the pairwise-disjoint 16-pixel tile-aligned rectangles written to its root Metal texture since the copy and blits only those on the next barrier (skipping the copy and keeping the pass open when nothing wrote depth), falling back to a whole copy on any untracked write (non-Loador layered pass,enc_r_begin, MSAAresolveTexture, blits/uploads, heap aliases, sparse pool remaps, waiting clears, mesh-task draws, or unbounded viewports). - A draw that writes the plane it samples through a texture slot reads a copy (
-
Limit: a draw that writes depth and reads it through an image slot, a uniform-buffer handle, a pool or a dynamic table still reads it in the pass: no copy can stand in for a binding the host does not encode itself. PR 1430's assumption, that a shader never reads the depth it writes (Pool shaders taken as depth readers), does not hold: the Ocarina of Time draws below do.
-
Check:
make -C dm/gfx/tests GAME=<id> check_t_feedback:depth_snap_case(a copy for a draw that writes and samples depth, reuse until a barrier, a direct read by a draw that leaves depth alone, the switch off),depth_after_write_case(the pass ends before a draw that samples the depth an earlier draw wrote, not before one that samples it first, the switch off) andreal_depth_snap_case(an actual private Depth32Float attachment, cleared by the production render pass, copied and read back, Depth32Float and Depth32Float_Stencil8, in a colour pass and a depth-only one, and with the clear still waiting for the draw's pass).regress.py checkon Octopath Traveler II (Apple M4 Pro, 2026-11-10), which takes both paths on its Depth32Float_Stencil8 scene depth (599866e198259922ande2d2ca47a4112324copy it, about 21 draws reusing each copy;e0eb1b2bdef248caends about one pass a frame): no new[RED]line, fps p50 59.8 and frame p99 18.19 → 18.27 ms, screenshots the same. -
Found on:
- The Legend of Zelda: Ocarina of Time, the cave entrance on Death Mountain Trail from a player's save (PR 1917). Right after the cave walls, the full-screen 25a8adc977ff813d samples the scene depth (1536×864 Depth32Float) and writes it with LEQUAL, and five decal draws after it do the same. There are no barriers between those six draws: with a copy for each, 1,000 of them took 1,000 copies, and reused until a barrier about 190, with the same picture and no measurable GPU difference between the two (M4 Pro, two runs each). In play (docked, in a window on the M4 Pro), thin light-blue dashes over the dark rock above the cave arch, gone with the copy. Headless captures of the same spot at 1440x810 and 1536x864 did not show them, so the check there is by eye. Cost of the copy at that spot (headless, docked, against the attachment read directly, two runs each): GPU p50 12.17 against 12.23 ms, frame times the same.
- The Legend of Zelda: Ocarina of Time, the snow in adult Zora's Domain (issue 1932) and on frozen walls, pillars and stairs (PR 1995): square holes or black blocks along the snow's edges on an M3 Max, moving every frame. The snow's pixel shaders (
1d3d97b789b9a6e6,06750e798cfec8ef,c2352ccb908fa8d0,55845639d605e028,ee567dea65288f58) write depth with LEQUAL and sample the scene depth through texture slot 6 to fade their alpha; the depth read came back NaN in whole 8×8 blocks, and a NaN fade is alpha 0. About 145 such draws a frame in Zora's Domain. On the reporter's tree the same copy reused until a barrier took the holes from 108 / 37 blocks (snow / rocks, a tile detector) to 4–8 / 0, and GPU p50 from 25 to 15 ms (passes 244 → 99 a frame, 39 → 60 fps): before it, the depth half of the colour rule gave each of these draws a pass of its own. Not yet run on this repository's main. PR 1995's other design, a pass of its own per draw that draws into a copy of the depth and copies it back, cost a pass and two depth copies a draw. - Red Dead Redemption (
01007820196A6000, profile not in this repository; PR 1866): its cloud fogrdr2_clouds_fog(c0ab3c051753e36d) fades the clouds against the depth it samples through a uniform-buffer handle, in the pass where the billboards (rdr2_billboard), the low-detail terrain and other geometry have just written depth: beige blocks above the ridge behind Armadillo, in both 1.0.0 and 1.0.4. With the pass ended before it (Apple M4, macOS 27.0.1, the route out of the saloon in Armadillo): the blocks gone, about one more pass end a frame, GPU p50 14.3 → 14.7 ms, frame time unchanged at the game's 30 fps.
Mip-chain pass sampling the level it renders
- Symptom: NaN texels in the upper levels of a texture the game fills level by level (each level drawn from the one above), and from there NaN wherever the texture is read: black speckles in whole 2×2 quads, white blotches once bloom spreads them, and a dark frame from the eye adaptation.
- Cause: a mip-chain pass renders level n while its fragment shader samples level n − 1 through a view that covers the whole chain (explicit level, linear mip filter). On NVIDIA that reads level n − 1 only. On Metal the fetch can also touch level n, at weight 0 but still fetched, and an attached level read through a texture holds no defined data on Apple's GPUs; 0 × NaN is NaN. The same-pass feedback rule (above) left such passes as they were.
- Fix:
fb_prepareinnvn_mtl.m, for every game, by the levels the slot's sampler lets the draw fetch (fb_reach: the combined handle's sampler, the shader'sSAMPTbinding of the same slot; its minimum and maximum LOD clamp whatever LOD the shader asks for, an explicit one too, and a linear mip filter also fetches the level above an integer LOD at weight 0). A sampler that clamps from below the attachment's level, or one not known here, gives the draw a view of the same texture limited to the levels below the attachment (same base, so the shader's level numbers keep their meaning): no copy, and exact whenever the clamp ends below the attachment's level. A sampler that clamps to one other level gives a view of that level alone (below); a range wholly above the attachment's level reads the view as it is. A clamp that starts at the attachment's level (a pin there, or a range or a fractional LOD from there up), and a pass that renders the view's base level with no level pinned, or one layer of a layered view, take a snapshot of the whole view: its type, sizes, layers and levels, so the shader's LODs and the sampler's clamp keep their meaning, with the levels the sampler can reach copied (every level when it is not known), in the type the shader declares (the host holds cube maps as 2D arrays). The prefix view stood in for those before: a pin at the attachment's level read the level below, and a range or fractional LOD from it up was clamped to the level below too; a base-level or layer pass read the attachment it rendered. The snapshot cache keys a view by serial, base level and layer and its shape (type, size, layers, levels) and copies a level a later draw reaches that an earlier one did not, until the next barrier. The view of the attachment's level and layer alone keeps the single-level 2D snapshot. - Check:
make -C dm/gfx/tests GAME=<id> check_t_feedback:mip_chain_casechecks the view or snapshot each sampler gets;mip_pixels_casesamples a 4×4 chain of red, green and blue levels at LOD 2 through registered samplers after the pass overwrites the attachment's level, and reads the pre-pass level each clamp names (blue, red, green, blue for the pins away from the attachment and a range above it, with no snapshot; green, blue and a green-blue blend for a pin at the attachment, a range from it and a fractional pin, with one);base_level_caserenders the base level of a 2D view, a view whose base is level 1, a 2D-array view of layers 1–2 and a cube, overwrites every level and layer, and reads the level the shader asks for as it was. With the earlier rule 18 of 506 checks fail (the three clamps from the attachment's level and the four base-level passes); all pass, with Metal API validation and direct, threaded and idle-feedback encoding (Apple M4 Pro). The clamps from the attachment's level were PR #1004's. - Found on: Donkey Kong Bananza: its environment cube (128×128, 8 levels, R11G11B10F, levels 1–7 drawn by
d1a506c1a94ffdfaand89dfaeb53f85920a) got NaN texels; copied into the sources of the prefiltered cube (62dc9b15931e0290) and fed back through reflections and the cube capture every frame, they reached 59,592 NaN pixels of the first gameplay frame's scene (0 with the fix).
Upsample pass reading the level above the one it renders
- Symptom: bloom wide and hard around bright edges: neon letters swell into fat, filled shapes. With
DM_NVN_FB_SNAP=0they are thin again, but the white blotches of the entry above come back. - Cause: the fix in Mip-chain pass sampling the level it renders gives a mip-chain pass a view of the levels below its attachment, which assumes the pass downsamples. An upsample pass renders level n and reads level n + 1, chosen by its sampler's LOD clamp (n + 1..n + 1). In a view that ends at level n − 1 Metal clamps that read to level n − 1, a sharper level, and the chain adds it back up to the top. An upsample into the view's base level got no view at all and read the attached level.
- Fix:
fb_prepareinnvn_mtl.m(fb_reach), for every game: when the slot's sampler (the combined handle's, the shader'sSAMPTbinding of the same slot) has a mip filter and a minimum and maximum LOD that are the same whole number, every fetch reads that level, so the draw samples a view of that level alone, whichever side of the attachment it lies on. A pin at the attachment's own level takes the snapshot of the entry above.t_feedback(mip_chain_case,mip_pixels_case) checks the view each sampler gets and the pixels it reads. - Open: an upsample that picks its level in the shader (an explicit LOD through a sampler whose clamp starts below the attachment's level, such as one that clamps nothing) still gets the view of the levels below, and reads its last level; no game is known to do it. Telling it from a downsample would need the shader's LOD.
- Found on: Donkey Kong Bananza, found by the author of PR #1073: its two bloom chains (576×324 R11G11B10F, 5 levels) downsample with
ef18c6eca9b2f991(sampler LOD n − 1..n − 1) and upsample withad1a5991aaad135e(n + 1..n + 1); a pass dump showed the upsample drawing level 3 through view0+3with LOD 4..4. With the rule switched off and on through the Ingot Isle stage intro, the neon letters went fat and filled, then thin, with it.
Lower-left window origin
- Symptom: text a game renders into textures for the title and the menus comes out upside down, while the scene looks right.
- Cause: a game that never calls
nvnDeviceSetWindowOriginModekeeps NVN's default, lower-left (OpenGL), where NDC y = -1 lands on a render target's first memory row. Read as upper-left, every texture the game renders and samples came out flipped and cancelled out, but not the text, and the game copies the frame withMIRROR_Y. - Fix: viewport and scissor rectangles, fragment coordinates, copies and texture coordinates address the same memory rows in both conventions, so the host flips the direction inside the viewport (negative viewport height, using its recorded device origin) and flips the window image at present and in raw screenshots (
g_origin_llinnvn_mtl.m). Facing also follows the raster flip captured at queue initialization. - Found on: The Legend of Zelda: Link's Awakening; the six games before it all switch to upper-left.
- Note: the window's Y-direction system register under this origin is open (Open: the window Y-direction register
SR_Y_DIRECTION); the OpenGL layer renders through this origin (GL orientation through the lower-left origin), and Absolum combines it with a viewport swizzle (Viewport swizzles applied as a flipped viewport).
Queue initialization captures the raster origin
- Symptom: geometry appears inside out and almost black; a fullscreen indirect-lighting triangle is entirely culled even though its vertex data and polygon state match the game.
- Cause: NVN emits
SET_WINDOW_ORIGIN.FLIP_Yinto a queue's initial GPU state.DeviceSetWindowOriginModeonly changes the device field that later viewport construction reads; it does not rewrite an existing queue's raster flip. Deriving Metal winding from the current device origin loses this distinction when the game creates a queue before changing the origin. Reversing winding globally fixes that sequence but breaks games that set their origin first. - Fix:
queue_t.origin_llcaptures the device origin innvnQueueInitialize. Each submission selects that queue's raster origin under the submission lock. Metal winding uses this captured origin; viewport direction uses the origin recorded with the viewport, while presentation keeps using the device origin. - Original validation:
t_queue_originalternated two queues created with different origins on one device: 389 checks passed with direct and deferred Metal encoding; restoring the previous winding expression failed 48. The complete Metal suite and Mario Wonder's full smoke route passed then. The current fixture also checks the recording device's viewport origin. - Found on: Xenoblade Chronicles 2, with native SDK initialization evidence and the comparison with Mario Wonder recorded there.
Viewport origin belongs to the recording device
- Symptom: a movie pass clears its target but its back-face-culled YUV-to-RGB quad disappears when a second NVN device records commands for the game's queue.
- Cause:
SetViewportsconstructs the viewport using the command buffer's device origin. The recorder retained only the rectangle, and replay applied the current global device origin instead. A later origin change, including one on another device, could flip an already recorded viewport and reverse its facing relative to the queue's independent raster origin. - Fix: the full viewport payload and compact viewport header carry the recording device's origin. Replay retains it with each viewport in the queue state and uses it for the Metal viewport and projective sample-coordinate proof. Updating another viewport does not replace viewport 0's origin. Queue winding remains fixed by queue initialization. The unused depth slot in the existing viewport payload holds the origin without changing command sizes. Complete format-2 captures made before this field keep their previous device-origin interpretation because the slot was zero; format-1 captures remain rejected because their descriptor handles have different semantics.
- Check:
t_queue_origintests full and compact records, later origin changes, a second recording device, independent viewport updates, retained queue state, implicit and legacy viewports, culling, facing, asymmetric pixels, negative-Y swizzles and the projective sample proof. On Apple M6 / macOS 27.2 / Xcode 27.2, 3,072 of 13,839 checks fail on unchanged main; all 13,839 pass with the correction in each encoder mode.t_capturechecks the origin's layout and relocation, accepts the complete earlier format-2 layout and rejects format 1 and incomplete layouts. - Found on: Deathsmiles II's
NvnVideoRenderer, reported by hada0127 in issue #593. Its movie device keeps the default lower-left origin while submitting to the game's upper-left device queue. - Open: Deathsmiles has no repository profile; its current-build movie and iOS confirmation remain open. The issue's separate idle VideoToolbox session failure and the remaining game bring-up are not resolved by this change.
The residency set committed before a present
- Symptom: a pink window with every command buffer ignored while headless runs look right: the first presents fail on the display command buffer with
kIOGPUCommandBufferCallbackErrorPageFault, and after a few of those macOS ignores every submission of the process ("Ignored (for causing prior/excessive GPU errors)"). - Cause: the game presents its window texture in its first frames before drawing into it; the texture was made on that first resolution in the present path and added to the residency set (
res_add), but only a submission commits the set, so the display command buffer sampled a texture outside the committed set. Headless runs never present, which is why they looked right. - Fix:
present_nowcommits the residency set after resolving the presented texture (res_commit, free when nothing changed), for every game. - Found on: Super Smash Bros. Ultimate (13.0.5,
DM_WINDOW=1). - Check: Breath of the Wild windowed with the change: its title, 60 fps, no GPU error.
Naming the shaders of a GPU fault
- Symptom:
kIOGPUCommandBufferCallbackErrorPageFaultorkIOGPUCommandBufferCallbackErrorHangon a command buffer, and nothing says which draw or dispatch caused it;DM_RES_CHECK=1reports nomissing residency. - Cause: Metal 4's commit feedback gives only the error and two times, so the log can name a submission but no pass or shader.
MTL_SHADER_VALIDATION=1can name one, at about a fifth of the frame rate, which is little use for a fault several minutes into a game. - Fix: each command buffer keeps the list of the game shaders it encoded (
cbs_noteinencode_args, one comparison per binding once a shader is listed). On an error that command buffer caused, the log has[RED] game shaders of failed command buffer #N (fence F, segment K): …, then[RED] game shaders by failed/ran over N failed of M command buffers: key failed/ran, …, most often failed first: in how many failed command buffers the shader was, of how many that encoded it. Read the second line of the last report: a shader in most failures with a high ratio is the suspect; one that runs everywhere has a low ratio. A victim of another's fault and a submission refused after one do not count. The first 16 failures are printed. The lists leave out the host's own passes and geometry emulation's kernels, so no shader standing out points there. Nothing here shows a shader is wrong, only that it was present: check it with validation or by reading what it addresses. A validation run must not share apso_archivewith normal runs: they cannot use the files it writes. - What can fault: measured on an M4 Pro, with a Metal 4 queue: loads and atomics through a buffer address that is unmapped, freed, not resident or null, from compute or fragment shaders, raise no error (reads give 0 or whatever is mapped there, so an overrun can silently write into another allocation). A fragment shader sampling a texture not in the residency set, or one freed whose resource ID nothing holds, raises
PageFault; after two of these macOS refused every later submission. A freed texture's resource ID goes to the next texture made, and a stale binding then reads that texture with no error. An M6 behaves the same (A GPU fault at address 0 has its measurements); the M5 does not. - Early release:
DM_RES_CHECK=1also reports[RED] released too early: an object retired behind an earlier fence than a binding of it. Itsmissing residencyline cannot see this, as the object is still in the set at that binding. - Found on: Splatoon Raiders (issue #1289), whose faults recur every minute or so before a fatal one.
- Check:
make -C dm/gfx/tests GAME=<id> check_t_cbs_fault.
A GPU fault at address 0
- Symptom:
kIOGPUCommandBufferCallbackErrorPageFaulton a command buffer, and the report macOS writes for it (gpuEvent-<process>-*.ipsin/Library/Logs/DiagnosticReports, itsbif0_fault) is a read at address 0 or a few bytes past it (0x40).DM_RES_CHECK=1reports nomissing residencyand noreleased too early. - Cause: open. The GPU read through a base address of 0. A lifetime fault and an overrun leave other addresses: measured on an M6 with a Metal 4 queue (
t_gpu_fault_kinds), a texture freed before its command buffer runs faults at its own address (0x10000496000, 0x10004088000), and a load through a buffer address of 0 or 64, from a freed 64 MB buffer or 256 MB past a 16 KB buffer's end, an index buffer at 0 and an indirect dispatch record at 0 all read 0 with no error. So the M6 and the M4 Pro read a zero address as 0, and only a chip that faults there shows it.DM_RES_CHECKchecks the objects a binding names, and a zero address names none. In the reports, the M6's data masters are 1 vertex, 2 fragment and 3 compute; sideband 72 is a texture read and 70 a texture write. - Fix: none yet; the host names what it hands Metal. Every GPU address below 1 MB it gives an argument table, an index buffer, an indirect draw, dispatch or mesh record, or an address slot of a shader's argument block (
encode_args,ZA_ADDR_KINDS) is noted (za_check,nvn_mtl.m). The game's tables (vertex, fragment, compute, object) go through theenc_*functions andbind_args; every host pass's own table goes throughat_addr, which names the pass (index conversion, multi-draw indirect, clear, texture copy draw, the NDVE network and others; uploads and presents, which run in command buffers of their own, are printed only). The first 16 are printed as[RED] zero GPU address #N: <table> slot <n> = <address> (pass <p>, last game shader <key>), and each command buffer keeps its first 4. A failed one prints them after its shader lists, as[RED] zero GPU addresses in failed command buffer #N: …, or0 (none). One compare per address, off the failure path. - Not seen by the check: an address a shader computes, and a table slot a shader reads that nothing ever set. The tables are made once and keep what was set, so only a slot no draw has set since boot is still 0; such a shader would fault on nearly every run of it. Seeing it would take each function's buffer slots: the game's shader libraries carry no reflection (
reflectionForFunctionWithName:returns nil for them), so the chain would have to record them, with the pipeline variant each draw uses tracked in the host. - Found on: Splatoon Raiders on an M5 and an M5 Max (issue #1289): 18 reports from one day on the M5, all reads at 0 (one at 0x40), sideband 79, page-table level 2, data master 2, from the same unit of 8 cores. Never on the M4 Pro or the M6.
- Check:
make -C dm/gfx/tests GAME=<id> check_t_cbs_faultfor the notes.make -C dm/gfx/tests GAME=<id> t_gpu_fault_kinds && dm/gfx/tests/t_gpu_fault_kindsruns each kind of bad read in a process of its own and prints Metal's error and macOS's report; it faults the GPU on purpose, so it is not in the run list. macOS writes a limited number of these reports (on the M6 none came after about nine in 25 minutes).t_gpu_fault_kinds --report dmhostprints a process's reports of the last 7 days.
A present snapshot's copy needs the same residency commit
- Symptom: with present snapshots on (
DM_PRESENT_SNAP, the iOS launcher's Frame buffering), a frozen, corrupted picture from the first presents; the first error is alreadykIOGPUCommandBufferCallbackErrorSubmissionsIgnored("Ignored (for causing prior/excessive GPU errors)") on the display command buffer, then on every upload, segment and submission command buffer, and[RED] present snapshots: the previous copy into a ring slot did not finish within 2 s. With snapshots off the same game runs. - Cause: the case of the entry above, on the snapshot path:
snap_takeresolves the presented texture and copies it into a ring slot on the game's queue beforepresent_nowruns, and onlypresent_nowcommitted the residency set. A window texture presented before any submission had used it was outside the committed set when the copy read it. The copy's command buffer has no error handler, so its fault shows only as the ignored command buffers after it. - Fix:
snap_takecommits the residency set after resolving the source (res_commit, free when nothing changed), for every game. - Found on: DRAGON QUEST XI S 1.0.4 on an iPad mini 7 (A17 Pro), which presents three times before its first submission (GitHub issue #626). The reporter's Apple M4 test did not fault without the fix.
- Not checked: the iPad with the fix.
A residency commit stays blocked in the iPhone kernel
- Symptom: the last frame stays on screen at 0 fps while the process stays alive and audio continues. The log stops advancing with no
[RED]line or GPU error. Within 10 s,DM_THRCPUshows the main thread, game workers,NVN queue replayanddm-encodeat 0%. Ending the app can leave the process alive. In one run the phone restarted itself 15 minutes after the freeze. - Cause: the state dump showed
iokit_user_client_trap ← res_commit ← pool_res ← mtl_gpu_addr ← bind_vbufs ← draw_on replay and__psynch_mutexwait ← post_completeon the completion queue. On the reported build, replay heldg_muandg_res_muacross[MTLResidencySet commit]. With completion waiting forg_mu, the main fence stayed at 206256 with 206262 submitted. A system stack report 15 minutes later showed replay as the process's last thread inTH_WAIT | TH_UNINTwithTH_SFLAG_RW_PROMOTEDand a kernel thread blocked on it. The phone reported 7.2 GB wired and 34 MB free at that point. An independent compute dispatch still completed once a second during the freeze. The game's footprint was 4.2 GB against its 8.2 GB limit, similar to the preceding run that kept playing. - Open: what made the kernel call stop returning. Main now applies changes outside
g_res_mu, underg_res_commit_mu.pool_rescan still callres_commitwithg_muheld, andpost_completestill needsg_muto advance the fence. A retest on current main and any link to the Mac GPU hangs remain open. - Collect: from a paired Mac,
xcrun devicectl device process signal --device <UDID> --pid <pid> --signal SIGALRMasks the host to dump thread and wait state and exit. Save the app'sDocuments/log.txt. After a restart,xcrun devicectl device copy from --device <UDID> --domain-type systemCrashLogs --source . --destination <folder>collectsstacks-*.ipsand anygpuEvent-*.ips. The process can keep its memory until the phone restarts. - Found on: Mario Kart World 1.8.0 (v917504), iPhone 19,4, iOS 27.3 beta (24C5037i), 2026-11-09. PR #2098 reports two freezes in four runs on
04811a63plus #1709, #1695, #1262, #1599 and #1713. One froze 2–3 s into a race, 184 s after launch. The other froze in the title demo without input at 353 s withDM_PSO_MTL4=1. Both occurred during scene loads. The race logged about 1,400–1,800 residency commits and 2.3–3.9 GB added per 300 frames around the load. The 300 frames before the title freeze logged 678 commits and 1,599 MB added. Four 5–7 minute races with6f50de00and12a44e09also applied had no freeze. The small sample leaves the effect of those commits unknown.
A GPU whose access macOS revoked stops the game
-
Symptom: after a GPU hang or GPU page faults, every upload, segment, submission and display command buffer comes back
kIOGPUCommandBufferCallbackErrorSubmissionsIgnored("Ignored (for causing prior/excessive GPU errors)"). Nothing is drawn again while the game's sound and logic go on, until the game aborts itself (game called nn::diag abort, about 70 s later); in full screen, WindowServer froze for 40 s and its watchdog killed it. With the fix the log has[RED] GPU access revoked: the … command buffer was ignored, and a Mac app shows an alert and quits. -
Cause: macOS revokes a process's GPU access after GPU errors it caused, and from then on runs none of its command buffers: they come back at once with
MTL4CommandQueueErrorAccessRevoked. The host logged them and went on. Their feedback still came, but the GPU no longer signalled the shared event a game's SyncWait waits on (for up to an hour,mtl_wait_at), and each present took a drawable that no command buffer drew. Metal 4 reports a commit's error asMTL4CommandQueueErrorTimeoutwith no text, with the command buffer's own error underNSUnderlyingErrorKeyandNSMultipleUnderlyingErrorsKey, so the top-level code alone never shows it. -
Fix:
gpu_lost_check(nvn_mtl.m) looks forMTL4CommandQueueErrorAccessRevokedin each command buffer's error and the errors under it; the first one stops the game, for every game:- presents stop (
present_now); - the shared event is raised from the CPU to the last fence whose feedback has come back, then again at each later submission's feedback (
gpu_lost_release), so no SyncWait waits for a signal that will not come, and no command allocator is reset before Metal hands its command buffer back; - the front end is told once (
front_gpu_lost,dm/host/front.h). A Mac app leaves full screen, says why in an alert that points to the log andscripts/bug_report.py, and quits with exit status 70 (⌘Q's is 0). Without a window, and on the iPhone, the run ends with a FATAL line and an abort.
A hang or a page fault alone does not stop the game: the GPU recovers from those, and command buffers discarded as innocent victims (
kIOGPUCommandBufferCallbackErrorInnocentVictim, also a timeout) come back while the game goes on.DM_TEST_GPU_LOST=<n>imitates the revoked access from the nth submission on, andt_gpu_lostchecks the error's shape, the single call, the released waits and the stopped presents. - presents stop (
-
Found on: The Legend of Zelda: Ocarina of Time (v131072) on a Mac (GitHub issue #1326). Its first run hung in full screen and every command buffer after the hang was ignored. Its second run, in a window, recovered from several innocent-victim timeouts, page-faulted at fences 110102 and 110108, and had every command buffer ignored from fence 110114, two frames later.
-
Open: the hang and the page faults that made macOS revoke the access.
-
Not checked: a real revoked access with the fix; only the imitation (
t_gpu_lost).
A CPU-written window texture resolved where the present is queued
- Symptom: an abort at the first present:
[RED] upload batches belong to the submit thread only: up_begin called on thread 'nvn-present-link', withpkg_upload,tex_mtlandpresent_nowin the backtrace. - Cause: the game fills its window textures with
nvnTextureWriteTexelsat boot and presents one before drawing into it. A texture whose content comes from its storage (CPU-written, packaged) is uploaded when it is first resolved, and again when its pages have changed since, in an upload batch only the submit thread may open; the first resolution of this one waspresent_nowon the present thread. Two cases were left after the first fix: a texture first used by the present, whose first use decides whether it is taken from its storage (storage the CPU wrote before its first use,tex_cpu_content), so it did not count as one before; and an uploaded one whose pages changed between the queue and the present thread, which the present thread uploaded again. - Fix:
present_enqueue, on the thread that queues the present, resolves the texture when that is the submit thread, and commits the upload batch (up_flush) when it is taken from its storage, so the display command buffer comes after the upload on the queue. Off the submit threadtex_mtlhands back an uploaded storage texture as it is, without looking at its pages (the submit thread's next look still finds a write since): a present shows the content as of when the game queued it. For every game. - Found on: Bastion (1.0.0, SDK 5.4.0: both 1920x1080 window textures written by
main+0x9374). The two later cases int_nvn, whose window textures nothing draws into: they were GPU textures while a sliver of another GPU-written span counted, and came up as storage textures once it did not (c06d1e79). - Check:
t_nvn(present pacing presents its never-drawn window textures).
The present upscales through MetalFX
- Symptom: a game that renders below the screen's resolution looks soft on a phone, in a large Mac window or on a 4K screen.
- Cause: the drawable has the layer's native pixel size (
front_ios.m,front_mac.m), and the present pass (present_encode_m4) scaled the presented texture into it bilinearly. - Fix:
DM_PRESENT_UPSCALE=metalfx(the iOS launcher's Upscaling; off by default on every platform, no profile key): where the picture's rectangle on the canvas (present_viewport) is larger than the content (fx_wanted), MetalFX's spatial scaler (MTL4FXSpatialScaler, perceptual colour processing: the input is the raw gamma-encoded bytes the present samples) scales the content to the rectangle's size in the present's Metal 4 command buffer (fx_encode). It reads the presented texture itself when the picture is all of it, private and readable by the scaler (DM_FX_INPLACE=0turns that off); otherwise the present copies the content to the origin of a texture of its size (MetalFX reads from the origin, so a crop with an offset works too). It writes the canvas itself when the picture fills it, unflipped, and the canvas has the picture's size, format and the scaler's output usage (the iOS layer hasframebufferOnly = NO; the Mac layer keeps Metal's default, so on the Mac the pass stays), and then no present pass is drawn (DM_FX_DIRECT=0keeps it); otherwise it writes a texture of the rectangle's size that the present pass draws 1:1, so letterbox, the lower-left origin and the drawable format stay the pass's. The scaler's own input and output textures are made only when a present needs them. The scaler's encoders take no barrier: before them a blit (the copy, or one word of a scratch buffer when the presented texture is read in place;mfx_order) waits for the queue's earlier work and ends with a producer barrier that they wait behind (An encoder of barriers alone orders nothing). A new size or format makes a new scaler after the presents on the GPU finish, at most once every 30 presents (a window being resized shows bilinear frames meanwhile); a size MetalFX refuses stays bilinear. Whole-window captures andDM_NVN_SHOT_OUTscreenshots draw the picture the same way (present_offscreen_m4), with separate scaler state and resources retained until GPU completion;DM_NVN_SHOTandDM_CTL"shot" still save the game's own frame. iPad Pro 13" M4, Breath of the Wild 1920x1440 → 2752x2064: writing the drawable took the present command buffer from 1.61 to 1.34 ms (PR #1541); reading in place saves the 11 MB input texture, and its copy's GPU time is within the noise on an M4 Pro (1920x1440). Tests:t_present_crop(sizing, offset crops, letterbox, sRGB bytes, lower-left origin, standard fallback, resize throttling, asynchronous whole-window capture, and an in-place, direct present while the frame that draws its texture is still running). - Found on: The Legend of Zelda: Breath of the Wild — upscaling and measurements.
- Limit: the scaler takes the presented frame, including any filtering and HUD drawing the game already performed. Feeding it an earlier scene target would mean replacing a draw of the game's own, and nothing general identifies which draw is a plain upscale. Scaler support is checked at runtime; unsupported devices, sizes and formats use standard scaling.
The NVN present crops by the vi layer crop
- Symptom: in handheld mode the picture fills only two thirds of the screen's width and height, in the bottom-left corner (the top-left with the upper-left origin), the rest black.
- Cause: the game keeps its 1920x1080 window textures in handheld mode, draws 1280x720 into them and crops through
vi::SetLayerCrop, nevernvnWindowSetCrop. The host recorded the layer crop (hle_vi.c) only for the Vulkan present (Swapchain pre-transform and layer crop); the NVN present read only the window's crop and showed the whole texture. - Fix: the NVN present shows the window's own crop when the game set one, else the vi layer crop (
present_cropinhle_nvn.c); on the Switch both become the crop of the buffer queued to the layer. A layer crop that does not fit the window texture is reported once in red and the whole texture is shown, as before. - Check:
t_present_crop: the window's crop wins, the layer crop is used without one, one larger than the texture is ignored, and a realnvnQueuePresentTexturequeues the layer crop (that check fails with the old call). On an iPhone 15 Pro in handheld mode Link's Awakening's picture fills the screen's height. - Found on: The Legend of Zelda: Link's Awakening (1.1.0, handheld mode on the iPhone).
A crop only picks texels; the picture has the layer's shape
- Symptom: a scene turns narrow, with black bars at its sides, while the swapchain or window textures keep their size; circles come out as tall ovals. The log has
vi::SetLayerCrop 0,0 1200x960andpresent upscaling: ... 1200x960 → 1800x1440in a 2560x1440 window. - Cause: the present used one rectangle for two things: which texels to read and the shape to show them in. On the Switch the compositor stretches a buffer's crop to the layer, so a game can draw an anamorphic picture into a crop of another shape: 1200x960 of a 1920x1080 swapchain docked, 800x640 handheld. The host fitted the crop's own 5:4 into the canvas, and reported 5:4 to the front ends.
- Fix: the crop still selects the source texels, for every graphics API, and
present_shape(nvn_mtl.m) gives the shape: the display's 16:9, or a sized layer's (vi::CreateLayerwith a size,mtl_present_layer). A screen taller than 16:9 (DM_SCREEN_ASPECT,mtl_present_screen) counts only for a texture of its shape, since only builds with screen-shape stubs render it. Both encoders, MetalFX, the screen-sized captures and the shape reported to the front ends (front_picture_shape) use it, so a canvas of another shape still gets bars around a 16:9 picture and clicks map onto the picture as drawn.vi::SetLayerScalingModestays ignored: the games seen set mode 2 or none. - Check:
t_present_crop: a 5:4 crop fills a 16:9 canvas and keeps bars on a 16:10 one on the classic and Metal 4 presents, a sized layer's shape, bothDM_SCREEN_ASPECTcases and the shape a real present reports. - Found on: Super Mario Galaxy 2 (issue #949).
Setting the same targets again continues the pass
- Symptom: one-draw passes on one target, hundreds of times a frame, with the same attachments each time (a
DM_NVN_GPUPROFframe:loadandstoreof the whole target in every line); a low frame rate that follows the target's size. - Cause:
nvnCommandBufferSetRenderTargetsended the host's pass even when it named the targets of the open pass. On the Switch the call costs nothing; on a tile-based GPU each pass stores its attachments, and the next one starts again. - Fix: the call goes on in the open pass when the targets are the same (
rt_same,rtc_oninnvn_mtl.m;DM_NVN_RT_CONTINUE=0ends every pass as before). What a pass end gave the draws around it is covered: a colour attachment sampled by the same-pass feedback rule, a game barrier bybarrier_game. Depth has two rules of its own: a draw that samples the depth attachment after the call ends the pass there, as its memory holds nothing of this pass until then, and a draw writing depth or stencil after a draw of the pass read that attachment ends it too, as the GPU stores the pass tile by tile, so the earlier reads would see the later writes in the tiles already done. A pass with no colour attachment ends as before. - Found on: Splatoon Raiders: its ink map (6400x6400 RG8 with a Depth32F-S8) got about 150 one-draw occlusion queries a frame, each after setting the map again: 150 passes of about 1 ms, 42 GB of attachment loads a frame, about 6 fps. Without the depth rules its water came out in grey blocks of tiles: the water reads the scene's depth, then the next draw writes the water's own.
- Check:
make -C dm/gfx/tests GAME=<id> check_t_feedback(the depth attachment read, then written).
Empty target bindings between draws broke continuation
- Symptom: hundreds of one-draw passes loading and storing the same attachments;
same-target continuation: first casenever appears even though each draw uses the same targets. - Cause: an empty
SetRenderTargetsended the encoder before the next binding could match the open pass. View comparisons also counted reserved bytes, inactive fields and trailing empty color slots. The continued-pass sampling guard rejected every bindless shader, including handles that name no attachment. Its handle proof initially also depended onDM_NVN_UNBIND_DEFER, so disabling deferral split eligible same-target draws even without an empty bind. - Fix: general,
unb_keeps,rt_sameanddraw_samples_rtinnvn_mtl.m. Defer an empty binding across state changes and sub-list calls/returns. A rebind compares against the open pass, including when it has only depth/stencil. Work (including inline buffer updates), barriers and the submission's end first finalize the old pass and apply the empty binding. A different target bind ends the old pass. Compare only active view fields and ignore trailing empty color slots. Resolve vertex and fragment uniform texture handles through their own stage's uniforms, with serial, overlapping-storage and sparse-alias guards. Exact fragment depth reads use the depth feedback rule. Vertex reads of an attachment split the pass. Unknown handles, tables, pools, dynamic bindings, uniform image/buffer handles and other shader stages retain conservative splits. Mixed bindless shaders with raw/storage buffer access also split because attachment mirrors reach those pool bytes only at pass end.DM_NVN_UNBIND_DEFER=0restores immediate empty-target unbinding. The handle proof stays enabled with feedback snapshots (DM_NVN_FB_SNAP) and applies to same-target binds without an intervening empty bind. - Check:
check_t_rt_unbindexercises real replay and GPU readback in both encoding modes with deferral enabled and disabled: redundant/repeated empty bindings, sub-list return, changed targets, submission end, attachment-less draws, barriers, clears and texture copies, semantic view identity, resolved nonattachment handles, overlapping storage and unsupported handles. A draw sampling a nonattachment through a uniform handle continues a same-target pass with no intervening empty bind, including with deferral disabled; the handle assertions also run in every configuration. Existingcheck_t_perf_order,check_t_feedbackandcheck_t_lazy_clear_ordercover ordering, color/depth snapshots and lazy clears. The correction's graphics suite completed successfully on Apple M6 (2026-11-17), with two reflection-sample checks skipped because their external fixtures were unavailable. The original change's two-game validation is recorded in NieR Automata and Octopath Traveler II; Orbitals records the remaining target-game validation. - Follow-up check:
check_t_rt_unbindcounts passes and reads Metal output in direct and deferred encoding. It checks equal and changed depth-only targets, reads and writes to disjoint and matching depth/stencil planes, clear ordering, and disjoint versus attachment-aliasing vertex handles with different vertex and fragment uniform contents. The full 65-second Xenoblade Chronicles 2 regression passed on Apple M6, macOS 27.2, againste4b0d9b7. Both builds reached the required frame and passed the screenshot checks with 15,910 identical shader outputs and no new red lines. - Found on: Orbitals, issue #2806. The game note records the measurements and remaining validation.
A render area for passes on very large targets
- Symptom: a pass on a very large target costs about the same however little it draws;
DM_NVN_GPUPROFshows time proportional to the target's area. - Cause: a pass with no render area covers its whole attachments. A synthetic pass on a flat 6400x6400 target cost about 0.1 ms, so the cost depends on what the target holds or how the host creates it; which of the two was not found.
- Fix: a draw pass on a target of 16 M pixels or more that loads what it keeps stops at the far corner of its scissor when that is at most half the target (
renderTargetWidth/renderTargetHeight,g_rp_awinnvn_mtl.m;DM_NVN_RP_AREA=0turns it off). Only the draw path opens such a pass. A draw whose scissor leaves the area ends it, and so does anything else that needs the pass (rp_begin). - Found on: Splatoon Raiders: each ink stamp's pass, scissored to 1952x2940 at (0, 3460), about 0.95 → 0.32 ms. Metal keeps what lies outside the area (a 6400x6400 target checked texel by texel on an M4 Pro, with API validation on).
- Note: the same stamps sample the map they write, with a game barrier each, so each still takes a whole snapshot of it (Same-pass feedback read through a snapshot), about 0.76 ms; a copy of the stamp's rectangle takes 0.09 ms, but nothing proves a stamp samples only inside it. Open.
Variable rate shading ignored
- Symptom:
[RED] NVN unimplemented function called: nvnCommandBufferShadingRateImagePalette, ornvnCommandBufferBindShadingRateImageornvnCommandBufferSetShadingRatePaletteMode, every frame. - Cause: NVN2 lets a game shade tiles of a pass at a coarser rate. Metal's render passes have no per-tile rate: a rasterization rate map resamples the whole target instead, which is another thing.
- Fix:
hle_nvn.caccepts the three calls and records nothing. Shading every pixel is the most any rate asks for, so the picture is the same or sharper, and the only cost is GPU time where the game meant to save it. This drops a feature rather than emulating it, and the choice is a platform limit. - Found on: Mario Kart World, every frame; Splatoon Raiders, the palette.
Screenshots of a cropped window held what lay outside the crop
- Symptom:
regress.pyflagged Bastion as a REGRESSION on a screenshot (RGB difference about 30) whose game picture was the same on both sides: a strip beside the picture was black in some runs and purple (68, 34, 136) in others, on the baseline as well as the candidate. - Cause: a screenshot (
DM_NVN_SHOT,DM_CTL shot) saved the window texture whole, 1920x1080, while the game crops what it presents to 1600x900 (nvnWindowSetCrop,[nvn] WindowCrop 0,0 1600x900). Outside the crop the texture is never presented and holds whatever it held before, which differs from run to run. - Fix: a screenshot of a window the game crops is the picture as presented: the present pass draws the crop at the window texture's own size (as
DM_NVN_SHOT_OUTdraws it at a size of its own), so its size stays the same when a dynamic resolution moves the crop. An uncropped window is still saved as its texture's own pixels. Until a regression baseline includes this, a check of a cropping game against an older revision compares two kinds of shot. - Found on: Bastion, in regression checks of the review's steps (step 15's audit).
Screenshots of GL and Vulkan frames wait for rendering
- Symptom: diagnostic screenshots can be black or incomplete while the corresponding GL or Vulkan frame displays correctly.
- Cause: the external graphics queue signals a Metal event after writing the frame. The present queue waits for it, while the screenshot can read the texture on a separate queue.
- Fix: diagnostic captures wait for the presented frame's producer event before reading it. A timeout skips the capture, and a failed Metal readback does not write a PNG.
- Found on: UnMetal. The original PR reported 82 black captures out of 86 before its producer wait and none afterward. PR #2805
- Check:
t_present_crop --external-screenshotsholds back submission of a producer on another Metal queue. The scheduled and queued captures both wrote black on2149d856and both wrote the expected green pixels with the patch. On the M4 Pro with macOS 27.2.1, both builds saved 86 captures of UnMetal 1.2.0's first cell with zero black images.
Blend, depth and stencil
Ten attachment records for eight colors and depth-stencil
- Symptom: angle-dependent character smearing, or vertex-only pipeline failures with
invalid depth/stencil pipeline formats 16843012/260, although the pass began with valid260/260formats. - Cause: the store-decision ledger
g_sdhad nine entries, but eight color targets plus separately tracked depth and stencil need ten. The tenthsd_attoverran the array. On the observed iPad build it overlappedg_pass:udc_note_drawwrote the overflow entry'swroteandwwhybytes into the high bytes of the cached depth format. A later vertex-only skinning pipeline was rejected, so its dependent draws consumed stale bone matrices. The lookahead's nine-byte result array had the same capacity error. - Fix: one
SD_ATT_MAXconstant sizes the ten ledger entries and both store-lookahead result declarations. Both aspects retain their own write/store decisions; no optimization or shader is disabled. - Check:
t_attachment_capacityreplays eight distinct color targets with combined depth/stencil and dependent vertex-only producer/consumer draws. Literal GPU readbacks verify all 8,192 storage values, all eight color clears, and both depth/stencil clears; it also checks formats remain260/260and neither pipeline fails. The test runs through both pipeline compilers, both encoding modes and both TBDR settings. AddressSanitizer reproduces the old 56-byte write past the 504-byte ledger and passes after the fix (renderer/test TU instrumented; NVN linker-section registration helpers kept uninstrumented). - Found on: Xenoblade Chronicles 2, iPad runtime watchpoint and fixed-camera diagnostic comparison. Testing the rebuilt permanent correction on iPad remains open.
Combined depth-stencil formats stay paired in passes and pipeline keys
- Symptom: Metal aborts at pipeline creation:
depthAttachmentPixelFormat (MTLPixelFormatInvalid) and stencilAttachmentPixelFormat (MTLPixelFormatDepth32Float_Stencil8) must match. - Cause: the renderer treated the two aspects of combined storage as independent attachment formats.
rp_begin_ex(3)attached only stencil;pso_predict_rest_also enumerated a stencil-only0/260alternative, even with TBDR lookahead off. Historical prewarm keys retained those formats. macOS accepts that pipeline and pass; the reported iPadOS legacy pipeline validator rejects it. The original log has TBDR off and no attachment capture, so the exact live pass behind its synchronouspso_getstack is still unidentified; the speculative producer is established from the source, not inferred from the cutscene. - Fix: a combined texture occupies both physical attachment slots whenever either aspect is needed. The unused plane is loaded and preserved, with its test and writes still disabled through the logical
g_pass.hd/hsflags. Native depth-only and stencil-only textures occupy only their valid slots; sampling throughX32_Stencil8is unchanged.pso_ds_pairgives live, predicted and parsed prewarm keys the same effective pair, without replacing any nonzero conflicting format. Repeated alternatives coalesce in the pipeline cache.pso_build_exrejects conflicting or non-renderable depth/stencil formats with an error before either compiler path can assert.DM_NVN_PASSDUMPincludesJlines with the source NVN/view format, physical Metal formats, logical use, pass mode, pipeline key, cache hit and draw/prediction origin. - Check:
make -C dm/gfx/tests GAME=0100E95004038000 check_t_pso_depth_stencil: synthetic shaders, native depth-only/stencil-only, both combined NVN formats, stencil-only/depth-only usage, omission of both planes, attachment-free draws, historical keys, format transitions, cache hits, speculation and invalid descriptors. Literal GPU readbacks check that the unused plane keeps its poisoned value. Both pipeline compilers and both encoding modes run under Metal validation.t_rt_rangeaccounts for the retained stencil plane and still checks identical colour/depth/stencil and occlusion results. - Found on: Xenoblade Chronicles 2, issue #702 (the reporter's log, not independent confirmation). The reporter confirms the descriptor-guard build reaches cutscenes and gameplay on iPad; its subsequent character smear is traced to the attachment-ledger overflow. Playing and skipping the opening with the complete correction remain separate device checks. Attaching the unused plane can add traffic in opt-in TBDR single-aspect passes; the default full-attachment path does not acquire another attachment.
No writes to colour outputs the shader does not write
- Symptom: undefined values blended into attachments the fragment shader leaves alone.
- Cause: Maxwell leaves targets outside the shader's output map untouched; on Metal such an attachment gets undefined values blended in.
- Fix: pipelines get a zero write mask and no blending for colour outputs the shader does not write (reflection
colors,color_knowninnvn_refl.m). - Found on: Super Mario 3D World + Bowser's Fury: volume draws after the G-buffer (
50d813761ca3f1f9and others) write only outputs 0 and 2, with blending and all channels enabled on targets 1 and 3. - Check: all five games' regressions were unchanged by it.
No writes to colour components outside the shader's output map
- Symptom: undefined values in the components of a target the fragment shader does not write: a NaN or garbage alpha (or G, B) that later passes, such as bloom, spread.
- Cause: the SPH's output map (word 18, 4 bits per colour output, R G B A from the low bit) names the components the GPU writes; it leaves the others of a bound target as they were. The translator stores only the mapped components, but Metal writes the whole attachment under its write mask, the unstored components undefined. The entry above covered only outputs with no component in the map.
- Fix:
dmsh_build.pyps_omaprecords a pixel shader's output map in its reflection (raster.omap, Maxwell's 0x50-byte SPH and NVN2's 0x80-byte one alike);pso_descANDs each target's write mask with its output's nibble, andfirst_draw_coversproves a load skippable only when the map covers every channel the target's format stores (pf_chan_bits). Libraries of an older chain have no map and keep the channel mask alone.t_omap_maskchecks both Metal pipeline paths. - Found on: reported by Lichii, a Switch 2 emulator, on The Legend of Zelda: Ocarina of Time (their commit
79c1516): a depth-only visibility draw with target 0 still bound left a band of NaN and red / blue above the horizon, which bloom spread into violet halos. Ocarina's agl_common depth pass maps output 0 RGBA and output 2 R only (map 0x10f,TranslatorContext.GetDepthRegister). Not reproduced here (open).
The alpha test through a library of its own
- Symptom: foliage, hair and fences drawn as solid quads (the parts the texture leaves transparent filled with its colour or black), dissolve effects solid instead of breaking up; once per run
SetAlphaRef …: the host has no alpha test. - Cause:
nvnColorStateSetAlphaTestandnvnCommandBufferSetAlphaRefselect Maxwell's fixed-function alpha test: the alpha a pixel shader writes to colour 0 is compared with the reference before blending, and the fragment is dropped when the comparison fails. Metal has none, and the host recorded the function without applying it and only logged the reference. - Fix: every pixel shader whose colour 0 has a float alpha gets an alpha test entry point beside each of its own in its side library
<key>_bx(One compile for a pixel shader's side entry points,dm/gfx/tools/dmsh_alpha.py):main0_a, andmain0_d_awhere the shader has it (the typed-output entry pointmain0_uholds the same test under a function constant since 2026-11-16: Typed outputs for every pixel shader), each running the body, taking the function and the reference from fragment bufferDMSH_ALPHA_BUFFER(30) and testing colour 0's alpha,discard_fragment()when it fails.SetAlphaRefis recorded (OP_ALPHA_REF). A pipeline drawn with a function other thanALWAYShaspso_key.atestset and takes its fragment from that library (atest_key,at_fn, loaded on first need); its draws bind the function and reference, a copy in the frame arena per value and pass (at_bind). The function and the reference are data, so one pipeline serves every function and a reference that changes every draw keeps it; draws without the test keep the base library, whose size and load time do not change. As in OpenGL, there is no test when colour 0 goes to an integer target.[[early_fragment_tests]]stays in the variant: such a shader has its depth written before the test, on Maxwell too. Alpha-tested draws count as discarding for the first-draw load elision (first_draw_covers). Prewarm rows written before the key field read as alpha test off (pso_skey_parse). Not covered: a readable-tile merged draw (bf_fn) draws without the test, with a red line naming the shader.t_alpha.mreplays every function against references 0, 0.3125, 0.5, 1 and NaN over an alpha ramp, andtest_dmsh_alpha.pychecks the entry points and compiles them for the Mac and the iPhone. - Found on: reported on DARK SOULS: REMASTERED (grass and ferns in Firelink Shrine and Darkroot Garden, PR #32), ASTRAL CHAIN (the death effect's tendrils,
EffectOpacityBlood, solid black) and Animal Crossing: New Horizons (the island map, issue #73, PR #430), each with an implementation of its own; not yet checked in those games with this one.
Alpha-test comparisons without an alpha export
- Symptom:
[RED] shader ... draws with alpha function 5 but has no alpha test entry point (its colour 0 has no float alpha): drawn without the teston depth-pass programs. An RGB-only colour output can also lose fragments despite exporting no alpha. - Cause: alpha-test eligibility checked only the state and the translated shader's side entry points. Maxwell's original output map, SPH word 18 bit 3, says whether output 0 exports alpha (NVIDIA's SPH specification). Relational/equality comparisons consume that export; an MSL
float4may contain padding where the original program exports only RGB. The existing translator applies the same export gate inEmitterContext.PrepareForReturn;NEVERis unconditional and needs no alpha input. Depth-pass programs can instead clip their own fragments without exporting any colour. - Fix:
atest_keyuses the recorded original output map to leave comparisons off when output 0 exports no alpha. This avoids both the false missing-variant warning and comparisons of padding.NEVER, an unknown output map, and genuine missing variants retain their existing paths. The shader's own discard and side effects still run. This is general host binding; no shader rewrite, chain change or game rule is needed. - Check:
t_alphatests absent colour, RGB-only output 0, alpha at output 1, missing/unknown metadata andNEVER, and GPU readback of all comparison functions and references. Its RGB-only fixture has a padded alpha ramp: comparisons leave every fragment, whileNEVERdrops them. Before the fix, the expanded replay fails 168 checks. - Found on: Divinity: Original Sin 2 - Definitive Edition.
Logic operations through a library of its own
-
Symptom: data a game builds in a target by combining draws comes out wrong; in Xenoblade Chronicles 2 indoor lighting has hard-edged dark boxes (world-space boxes in perspective, darker with the time of day) and lighter translucent rectangles elsewhere; in Skyward Sword HD a brown cast covers the distance and near objects turn into dark silhouettes, coming and going with the camera. A pass dump shows
lo=7(or any value other than 3) on theDlines of the draws that write the target. -
Cause:
nvnColorStateSetLogicOpmakes the hardware combine the bits a pixel shader writes with the bits already in the target (CLEAR, AND, …, OR, …, SET) in place of blending; as in OpenGL and Vulkan it acts on integer and normalized targets. Metal has none, and the host recorded the operation without applying it, so every draw wrote with COPY. Xenoblade Chronicles 2 builds a per-pixel list of up to four light probes in an RG32Uint target: each probe's box writes its index into the next free byte with OR, and every other fragment writes 0 and relies on OR to leave the list as it is. With COPY each fragment replaced the list, so inside every probe volume the indirect-lighting pass read the wrong probes or none. Skyward Sword HD clears its RGBA8Unorm frame's alpha to 0, thenDof_FogToAlphadraws(0, 0, 0, fog)with OR and every channel enabled, to put fog in the alpha for the depth of field: OR with 0 keeps the colours, and COPY blacked them out. -
Fix: every pixel shader with colour outputs gets logic operation entry points in its side library
<key>_bx(One compile for a pixel shader's side entry points,dm/gfx/tools/dmsh_logic.py):main0_l(and, until 2026-11-16,main0_u_l; since then the typed-output entry pointmain0_uholds the operation under a function constant, and a shader with it has nomain0_l: Typed outputs for every pixel shader) runs the body, reads each output's attachment ([[color(n)]], framebuffer fetch; inmain0_uas a float or an unsigned integer, as its colour is) and combine it with the output by the operation and the target's channel masks from fragment bufferDMSH_LOGIC_BUFFER(29). A float output goes through its normalized target's stored bits: rounded to them as the target would store it, combined, and normalized again (dm_logic_norm); masks of zero, on a target with no such bits, pass it through. Every shader has the entry points, not a listed few, because which ones draw with an operation shows only in play (Skyward Sword HD: a second shader,eb1648acad4e38e3, in the Knight Academy); the side library is loaded only on first need. Each read depends on the function constantDMSH_LOGIC_FC + n(Metal refuses a pipeline that reads an output whose target the pass lacks); the host specializes the entry per set of targets and keeps each (lo_fn). A pipeline drawn with an operation other than COPY into an unsigned integer or normalized target haspso_key.logicset (lop_key; the field was padding, so older prewarm rows read it as off), blending off, since the operation takes its place, and its draws bind the operation and the masks (8, 16 or 32 bits a channel, RGB10A2's 10 and 2, the 5, 6 and 1 of the packed formats), a copy in the frame arena per value and pass (lo_bind). The operation is data, so one pipeline serves every operation; draws with COPY keep the base library and read no attachment. Logic-op draws count as reading the target for the first-draw load elision (first_draw_covers) and end a readable-tile merged pass before them. Not covered, with a red line: a floating-point, sRGB, signed normalized or signed integer target, a draw with an alpha test as well in a shader withoutmain0_u(which does both), and a merged pass's first phase.t_logic.mreplays all 16 operations into RG32Uint, RGBA8Uint, RGBA8Unorm and RGBA16Unorm targets;test_dmsh_logic.pychecks the entry points and compiles them for the Mac and the iPhone. -
Found on: Xenoblade Chronicles 2: the probe-list writers,
shd_lgt.wishpvar3 (ef07fd3d5046164f,aa9a0923524b7e46,2717a0aa47361bbd,d95874c161deb77d,f24b58784a33adea), read by the indirect-lighting pass93d0e7a7c14cdfb0(GitHub issue #643). Normalized targets: The Legend of Zelda: Skyward Sword HD,f11c15a99b0c1790(GitHub issue #928; the cause and the approach were first reported by Zatteo in issue #497). -
Typed-output binding regression (2026-11-17):
c75f0126moved the operation intomain0_u, whose generated reflection hasentry_u_logicwithout the legacylogicdictionary. Pipeline selection acceptedu_logic, but drawing bound buffer 29 only forhas_logic(the dictionary), leaving the operation and masks unbound. Draws now bind for either capability.t_logicloads reflection and libraries made by the production build finisher throughshader_load, then reads back all 16 operations on unsigned and normalized targets; it previously sethas_logicby hand and hid the missing bind. Skyward Sword HD's reported return of the dark cinematic cast bisects to this change, but a matching pass capture and gameplay retest are still needed to confirm that connection.
Source-only blending on floating-point targets
- Symptom: the title background and gameplay render black while the HUD and text remain visible. A pass dump shows the scene and its color lookup table rendered before tone mapping, but the bloom input holds positive infinity.
- Cause: the bloom blur
f9895ce248715e99enables ADD with source ONE and destination ZERO for both color and alpha. This state replaces the destination. On an M4 Pro with macOS 27.2.1, the enabled Metal blend state produced infinity in all 90,400 texels of the R11G11B10F target. The input RGBA8 texture and blur weights were finite. Tone mapping then sampled outside its color lookup table. An isolated Metal draw using the same fragment code and captured input with controlled vertices produced finite values with either blend state, so the lower-level trigger in the live pipeline remains open. - Fix:
pso_descimplements source replacement by leaving blending disabled on float attachments for this exact state. Blends that use the destination or alter the source retain their blend factors and operations.check_t_blend_zerocovers the pipeline descriptors and the existing float blend results. - Found on: LEGO Star Wars: The Skywalker Saga. With the source-only state represented directly, all 90,400 bloom texels were finite and the “Boarding Party” corridor rendered on the same Mac.
Advanced blend modes as Porter-Duff factors
- Symptom:
nvnBlendStateSetAdvancedMode 8(SRC_OVER) logged and blended with the state's own functions. - Cause: the hardware ignores the blend state's own functions while an advanced mode is set.
- Fix: the blend state keeps the mode, the premultiplied-source flag and the overlap (
blend_stinnvn_obj.h), and the pipeline (adv_blendinnvn_mtl.m) blends the Porter-Duff modes (ZERO, SRC, DST, SRC/DST_OVER, _IN, _OUT, _ATOP, XOR, the PLUS modes) with the fixed-function factors they amount to under uncorrelated overlap, with premultiplied colours as NV_blend_equation_advanced defines them; a source that is not premultiplied is multiplied by As where the source factor is ONE. Multiply, screen, overlay, the HSL modes and the other overlaps need the destination colour in the shader and keep the state's functions, with a red line naming the mode. - Found on: Mario vs. Donkey Kong (SRC_OVER, on one blend state in the levels).
Float colours rounded into normalized targets as NVIDIA's colour unit does
- Symptom: surfaces out of direct light nearly black, as if there were no ambient, sky or bounce light at all: shadows on grass pitch black where console footage shows them a soft, lit green, cliffs and the character black in shadow. More generally, data a game packs into an 8-bit (or 16-bit, RGB10A2) normalized target as a half step, such as material flags written as (n + 0.5) / 255, reads back one higher than on the console. No red line.
- Cause: NVIDIA's colour unit converts a float colour into a normalized target by multiplying in float32 and rounding that product to nearest even; Apple's rounds the exact product to nearest. Measured on an M6 (65,536 colours into RGBA8Unorm): every one stored the nearest integer to the exact x × 255, 128 of them differ from the float32 rule, all within rounding of a half step. Sonic Frontiers' G-buffer pixel shaders write their material flags as the constant 0.2607843 (66.5 / 255 in float32): its float32 product is exactly 66.5, stored as 66 on the Switch, while the exact product is 66.5000036, stored as 67 on the Mac. The deferred lighting shader
17fef41bdcaf727ereads the flags astrunc(a × 255), and bit 0 makes it skip the sky's spherical-harmonics ambient for an ambient from G-buffer 2's colour, which these shaders write as 0. The Switch's rule is inferred from that picture (NVIDIA documents none for ties); it is the plain float32 multiply and round to nearest even. - Fix: general, in the chain and the host. The guard every pixel shader calls before it returns (A NaN colour under a zero blend weight,
dmsh_rewrite.pyblend_zero,dm_blend0) takes a second word at fragment bufferDMSH_BLEND_BUFFER,round,DMSH_BLEND_ROUND_BITSbits per colour output (DMSH_ROUND_8,_16,_10_2), and makes such an outputrint(float32(saturate(c) × scale)) / scale(dm_rop), which Apple's conversion stores as NVIDIA's integer. The host (nvn_mtl.mrop_word, bound with the zero word bybz_bind) sets it for R8, RG8, RGBA8, BGRA8, the 16-bit and the 10/2-bit normalized targets whose stored value is the colour's conversion: blending off for that output, MIN or MAX on both colour and alpha (they keep one of two stored values, so rounding first keeps the same one), or a logic operation (which takes blending's place;dm_logic_normthen finds the colour exact). A draw whose pipeline maps its outputs to other attachments takes the word under that map, as the zero word does.DM_NVN_ROP_ROUND=0turns it off for A/B runs. - Cost: a draw into float targets only, or blended ones, pays the second word's load and the existing test. A rounded output pays a clamp, a multiply, a round and a divide per channel. Not measured apart.
- Not covered: a blended sum (rounded after the blend, out of a shader's reach), sRGB targets (NVIDIA's sRGB encode is not known here), signed normalized targets, the packed 16-bit formats (RGB565, RGB5A1, RGBA4), and shaders from libraries of an older chain (no word).
- Check:
make -C dm/gfx/tests GAME=<id> check_t_rop_round(t_rop_round.m: 256 colours, half steps of 8, 16, 10 and 2 bits and the edges, through the replay into RGBA8, RGBA16 and RGB10A2 targets with blending off, MAX and a blended sum, then the same withDM_NVN_ROP_ROUND=0, every stored value against both rules, androp_wordby format, blend state, logic operation and a merged pass's mapping, and a merged pass drawn and read back: output 0 into an RGBA8 attachment 1 stores 66.5 / 255 as 66);python3 dm/gfx/tests/test_dmsh_blend_zero.py(the rule on the CPU, the guard's text). - Found on: Sonic Frontiers Definitive Edition, Cyber Space 1-1, compared with a capture of the Switch version. Found by following the lighting pass's inputs: the probe volumes, the sky SH in its uniform buffer, the occlusion in G-buffer 2's alpha and the AO target all held light; the G-buffer's flags (
DM_CTLtexraw) did not.
Depth clamp
- Fix:
SetDepthClampis recorded (OP_DEPTH_CLAMP) and replayed as Metal's depth clip mode (it used to be ignored). - Found on: Fire Emblem: Three Houses (the game turns it on).
Depth bounds
- Symptom:
nvnCommandBufferSetDepthBoundswas a no-op (g_nops), and the Vulkan layer did not forwarddepthBoundsTestEnable/minDepthBounds/maxDepthBoundsorvkCmdSetDepthBounds, so draws expecting the depth bounds test ran over pixels outside[min, max]. - Cause: Metal added hardware depth bounds testing (
setDepthTestMinBound:maxBound:) withMTLGPUFamilyApple10(macOS 26 / iOS 26 SDKs). Before that, no host path recorded or encoded depth bounds. - Fix:
dbnd_resolve(dm/gfx/nvn/nvn_dbnd.h) resolves(enable, min, max)to off ([0, 1]), an active[lo, hi]interval, or empty (lo > hior NaN). NVN recordsSetDepthBoundsasOP_DEPTH_BOUNDS(preserving state across queues, deferred unbinds, compute-hoist scans and frame capture) and encodessetDepthTestMinBound:maxBound:(direct and deferredRO_R_DBND) on Apple10+ GPUs when a depth attachment is bound, skipping empty-bounds draws before opening a render pass and keeping depth-writing bounded draws out of reordered mesh runs (nvn_geometry.inc). Vulkan forwards both static pipeline bounds and dynamicVK_DYNAMIC_STATE_DEPTH_BOUNDS/vkCmdSetDepthBounds(hle_vk.m), resetting encoder state across pass reopens.DM_NVN_DEPTH_BOUNDS=0disables the test (abalternates withDM_AB). Older GPUs (belowMTLGPUFamilyApple10) ignore depth bounds without a red line. - Check:
make -C dm/gfx/tests GAME=<id> check_t_depth_boundsrunsdbnd_resolveedge cases, real Apple10+ GPU pixel pass/rejection (direct and deferred encoder thread underMTL_DEBUG_LAYER=1), mid-pass reset,DM_NVN_DEPTH_BOUNDS=0, simulated Apple9 fallback, redundant-call caching, empty-bounds pre-pass skip, deferred unbind and multi-queue state (85/85 on Apple M6 / Apple11 GPU, macOS 27.2.1, Xcode 27.2).check_t_capture,check_t_geometry_meshandcheck_t_vk_desccover capture serialization, mesh-run exclusion and Vulkan static/dynamic state. - Found on: PR #2866 (from kencalx/NX18). Measured on Apple M6 (Apple11 GPU,
DM_NVN_DEPTH_BOUNDS=ab,DM_AB=300): The Legend of Zelda: Breath of the Wild (Great Plateau outdoors, 5,700 frames, 23–34.5 calls/frame), The Legend of Zelda: Tears of the Kingdom (opening cave, 5,700 frames, 23–25.8 calls/frame) and Pokémon Scarlet (outdoors, 2,400 frames, 65–66.7 calls/frame) all calledSetDepthBoundsexclusively withenable=0, (0, 1)along those routes (0 tested draws, 0 ms GPU change). No Switch game tested so far enables a non-trivial depth bounds interval on those routes.
Depth on the far plane
- Symptom: blocks of another sky layer in the sky, in stair-stepped squares and half squares that follow the dome's mesh. In Mario Kart 8 Deluxe's Sky-High Sundae, salmon-red blocks of the sunset panorama show through the blue sky, the same blocks every time from the same camera.
- Cause: a vertex shader that stores one value in gl_Position z and w puts every vertex at the viewport's far value, the usual way to draw a sky. NVIDIA's GPU fills such a triangle with exactly that value. Apple's rasterizer does not: a triangle whose three vertices have the same depth comes out up to one step short of it at many pixels, whatever the depth (z = 0.5w gives 0.49999994; only 0 is exact). In Metal tests of random z = w triangles into a
Depth32Floattarget, 43 % of the pixels came out below 1.0 on an Apple M5 and 9 to 27 % on an M4 Pro, down to 1 − 2⁻²³; the GL convention's z' = z/2 + w/2, which keeps z = w, does the same. Two layers drawn there then fight. Sundae draws a red panorama and then a blue dome over it, and where the panorama landed one step in front, the blue failed its depth test. The rounding is in the rasterizer, not in the translation: z and w are bit-identical at every vertex. - Fix (a workaround for the platform's rasterizer, which cannot be changed): the build marks such vertex shaders (
dmsh_reflect.pyfar_plane: the last stores to z and w are one register defined once, or one constant other than 0, with no branches; reflectionraster.far,nvn_reflpos_far). The host draws them with a constant depth bias of 16 units past the far value and depth clamping (nvn_mtl.mdraw), which puts every pixel exactly on it: in the same tests 2 units already left none short, with depth ranges 0..1, 0..0.5 and 0.25..0.75. A draw that sets the game's own polygon offset keeps it, and a program with a geometry or tessellation stage and a wide line are left alone. Only the far plane can be pinned this way, because there the exact value is also the clamp's bound; other constant depths stay as Metal draws them. - Open: a reversed depth range (near value above the far one, so z = w lands on the lower bound). Metal scales a float target's bias by the depth's exponent, so near 0 the bias is nothing: with −16 units and clamping, 24 to 75 % of the pixels stayed 2⁻²⁴ above 0 on the M4 Pro, and the host leaves such draws alone. Moving z past w in the vertex shader (z = w · (1 + 2⁻²⁰)) with clamping put every pixel on the far value in every range, reversed included, but it changes what the vertex stage outputs, which a geometry stage or a capture reads, and needs clamping tied to the shader; no game is known to draw z = w with a reversed range.
- Found on: Mario Kart 8 Deluxe (245 of its 12,530 vertex shaders: the skies, and full-screen passes at depth 1). Also marked in Sonic Superstars (117), Mario Kart World (32) and Mario Tennis Fever (5).
Telling depth rejection from no rasterization
DM_NVN_DEPTHOVR(depth test forced toALWAYS) withHILITEtells "rejected by depth" from "never rasterized".TEXSNAPcopies used to run before the pass they were meant to show (classic-queue command buffer committed ahead of the Metal 4 one); they now go through the replay's copy encoder.- Found on: The Legend of Zelda: Tears of the Kingdom, tracing the tile lighting: the G-buffer class byte selects per-class half-resolution passes through a depth buffer of class values (
gl_FragDepth = mix(0.5, 1, nibble-swapped class / 255), then full-screen or per-tile quads with depthEQUAL).
Front and back stencil reference values
- Symptom: a two-sided stencil draw whose back faces test against their own reference value passes nowhere (or everywhere) on the back faces; nothing in the log. In Mario Golf: Super Rush the ground decals are missing: the driving range's scoring target in Golf Adventure (a ring with a blue centre on the fairway) is not drawn, in the normal view or the top view.
- Cause:
SetStencilReftakes a face, and the replay keeps both values, but sent Metal the front one for both faces (setStencilReferenceValue:), while the depth-stencil state (dss_get) already gave each face its own compare function, operations and masks. A back face therefore tested the front value. Mario Golf's decals are volumes drawn twice: front faces mark stencil bit 0x80 where the volume lies behind the ground, then back faces draw the colour wherestencil & 0x90equals the back value 0x10 (the ground's mark, written by the terrain draws) while the front value is 0. With 0 for both, the colour draw passed nowhere on the ground. - Fix:
enc_r_stencil_refsends both values (setStencilFrontReferenceValue:backReferenceValue:), the per-encoder state cache compares both, and the deferred recorder (nvn_rec.hRO_R_SREF) carries both. The Vulkan layer already sent both (hle_vk.m). - Found on: Mario Golf: Super Rush (4.0.0, issue #814), Golf Adventure's driving-range lesson, the PR author's runs (PR #2351): pass with fragment shader
6f91c05c60985a33, four draws of 384 indices (two decals, two draws each); the target shows in the top view and from the tee.
Stencil-mode texture views read through X32_Stencil8
- Symptom: 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.
- Cause: a shader that reads a depth-stencil texture through a view whose
nvnTextureViewSetDepthStencilModeisSTENCIL: the host ignored the mode and bound depth, so a stencil test read bits of the depth value's float bits. - Fix:
tex_by_idbinds anX32_Stencil8view for such a view. The shader declares a float texture (the translator has no integer texture type) and takes the raw bits withas_type<uint>, and a read of the integer view gives the stencil value in those bits. Metal allows such a view only of a texture with the pixel-format-view usage: Apple GPUs read it correctly without, but the API validation layer aborts at the first one (PR #106, Luigi's Mansion 3). Upgrading the texture when the view appears recreated the depth buffer while it was attached, and the next occlusion-counted draw crashed insidesetVisibilityResultMode, so every depth-stencil texture has that usage from the start (tex_desc; Vulkan depth-stencil images too,vkCreateImage), which costs nothing measured (on an M4 Pro the same allocated size and GPU time);t_stencil_viewchecks it under validation. - Found on: Pokémon Legends: Z-A: the deferred lighting pixel shader (
ead6e2a32540b19a, 31 bindings) first reads the depth-stencil buffer through such a view, tests stencil bit 6 and discards. Luigi's Mansion 3 (PR #106, the validation abort). - Note: inputs ruled out on the way in Z-A: the G-buffer albedo, the normals (12-bit pairs packed into 3 bytes, noisy by design), the screen-space shadow mask, the scaled depth copies and conditional rendering (evaluating it changed nothing in this game).
Stencil-mode textures from the texture builder
- Symptom: a character drawn as a dithered silhouette inside a dithered square (DRAGON QUEST VII Reimagined's hero).
- Cause: Unreal's stencil shader resources are second textures on the depth buffer's storage built with
nvnTextureBuilderSetDepthStencilMode(STENCIL), which the host only logged, so the character occlusion mask read depth where it tests stencil bits. - Fix: the builder's mode now goes to the texture (
tex_t.stencil), whose sampling view is theX32_Stencil8one a stencil-mode texture view already got. - Found on: DRAGON QUEST VII Reimagined (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, 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. - Cause:
hle_nvn.cignores the enable setter and has no implementation for the dilation setter. The requested raster coverage state never reaches Metal. - Fix: Open. Neither setter has been implemented. The opening indoor scene renders and accepts input, but the visual contribution of the missing coverage state has not been isolated. The diagnostic remains visible.
- Found on: Pokémon Scarlet (1.0.0, the first playable bedroom). Super Mario RPG calls the dilation setter and
nvnCommandBufferSetSubpixelPrecisionBiasrepeatedly and did not turn the enable on along the route tested, so the dilation has nothing to act on there.
Vertex input and draws
Integer vertex inputs
- Symptom: 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. - Cause: integer vertex inputs (bone indices) translated as float: without PC reflection the translator declares every vertex input
float4. Skinned models read their bone index (R8UI/RG8UI/RGBA8UI) as raw integer bits (as_type<int>(in.m_N.x) * 48); Metal converted the integers to floats, and every bone index was garbage. - Fix:
dmsh_build.py(int_inputs) now re-translates a vertex shader withuintinputs when every use of an input is an integer bit cast (529 of 4,854 in Mario), and the host makes the Metal vertex format agree with the declared type (vfmt_for_ct; signedness swaps of 32-bit components and 32-bit float→int reinterpretation keep the bits, while float-type formats and 8- and 16-bit integers of the other sign go through shadow vertex inputs, next entry). A remaining mismatch is reported asvertex attribute format … does not match shader input type …. - Check: finding the draws: log model file ranges with
DM_PROBE=main:480f0(x1 = file data, x2 = size), match the vertex/index buffer addresses inDM_NVN_PASSDUMP_ALLagainst them, thenDM_NVN_HILITEtheir fragment shader. - Found on: Super Mario Bros. Wonder (skinned characters).
Shadow vertex inputs
- Symptom: red lines 89 and 96 (
vconv_bind, the CPU conversion every draw); about a quarter of Age of Calamity's replay thread in battle. - Cause: an input that
int_inputsdeclares an integer may still be fed a format of another class. A float-type format (half, unorm / snorm, 10:10:10:2, 11:11:10) leaves the converted float32 bits in the register; an 8- or 16-bit integer of the other signedness is widened by the format's own sign (Fire Emblem: Three Houses, CPU conversion of vertex attributes the input type cannot take). Metal reads a format only into an input of its own class, so the replay used to convert those attributes on the CPU every draw (vconv_bind). - Fix: shadow inputs (
<key>_bv,dm/gfx/tools/dmsh_vin.py): the build also writes a side library for each such vertex shader. In it, every integer input is declared again as afloat4and as the integer of the other sign, at Metal attribute indices 16–30 (NVN uses 0–15), and the body starts within.m_N = dm_in.m_N | as_type<T>(dm_in.m_N_vf) | as_type<T>(dm_in.m_N_vo). The host sends each attribute to the index of its format's class and the zero buffer to the others (vin_ct,vin_oninnvn_mtl.m; pipeline keys unchanged), so a pipeline with any mix of formats reads Maxwell's register bits. The float shadows are assigned first: with more than 7 integer inputs the last ones get only the float shadow (169 of 8,201 inputs in Age of Calamity). - Note: a format with no shadow keeps the CPU conversion, as do transform feedback draws (
main0_tfhas no variant) andDM_NVN_VCONV_CPU=1. The host loads a side library only for a pipeline that routes an attribute to a shadow, but the build cannot tell which shaders will need one (an input used only as an integer may hold bone indices or float bits), so it writes them all. Shadows cover only integer inputs; 8- and 16-bit integer formats feeding float inputs are pulled. - Found on:
- Hyrule Warriors: Age of Calamity: 2,259 libraries, 77 MB each for Mac and iOS. Its Mac battle at 60 fps against the CPU conversion: 0 vertices converted instead of 545,000 per submission, submit + present 10.0 → 5.7 ms a frame, CPU 3.97 → 2.44 W, GPU unchanged, the same picture.
- Other games have 0–2,000 libraries (at most 31 MB on iOS), except Monster Hunter Rise: 16,781 libraries, 344 MB on iOS (21% of its shader libraries, 1.5% of its IPA), and its Mac and iPhone runs so far load none. Its 8- and 16-bit integer formats feeding float inputs (red line 99, about 60,000 vertices per submission on its Mac route into the opening) still go through the CPU.
Pulling vertex inputs
- Cause: a pipeline's vertex descriptor fixes the vertex layout it is drawn with, so a shader pair drawn with a layout it has no pipeline for waits until one is compiled.
- Fix: pulling inputs (
<key>_bp,dm/gfx/tools/dmsh_pull.py, decoderdm/gfx/tools/dmsh_pull.metal): a side library of every vertex shader with stage inputs, whosemain0/main0_zhave no[[stage_in]]. They read their inputs themselves from a per-draw layout block at buffer 16 (dm_vlayout): per stream the base address, stride and divisor, and per NVN attribute, all 32 of NVN2's, the raw attribute state word. The base instance comes from[[base_instance]], so indirect draws are right too.dm_fetchdecodes the NVN format at run time into the register words Maxwell's fetch gives the shader, and the input takes them withas_type. A pipeline made with it has no vertex descriptor, so it serves every vertex layout a shader pair is drawn with; it is meant for drawing while the pipeline for the draw's own layout is still being built. - Note: the words are bit-identical to Metal's vertex-descriptor fetch for every format
vfmtknows, and to the host's CPU conversion for the integer-read-as-float formats. unorm / snorm go through theunpack_*builtins, because a plain division under fast math is off by one unit in the last place for some values; NaNs of R11G11B10F come out canonical, as from Metal's fetch. With a divisor the element isbase instance + (instance - base instance) / divisor, Metal's own rule. Positions match the vertex-descriptor pipeline's ([[invariant]], preserved invariance). - Note: the run-time format decode costs GPU time: on an M2 Max, 8 attributes in a vertex-bound draw of tiny visible triangles took 65 % longer (about 1.0 ms per million vertices) than with the vertex descriptor. With the formats as compile-time constants it was 9 %, and with the whole layout compiled in, 0. So these pipelines only stand in until the fast one is built, except for a layout the fast one cannot read: Attributes the vertex fetch cannot read, pulled. Other entry points (transform feedback, geometry capture, layer) get no variant; shaders without stage inputs need none, since their pipelines have no vertex descriptor.
- Symptom: an unsigned iOS build reports
[RED] pulling library ... not usable (no library ...)and its draws wait for pipelines, either with the profile'spso_mtl4 onor with Metal 4 pipelines and Pipeline prebuild turned on in the launcher for a game whose profile leavespso_mtl4off. Then the prebuild ends at once as if finished (pipeline prebuild done: 7495 pairs, 0 bases built, 0 already archived, 7495 left to the draws, 0 failed, 0.6 s), and the shader image holds_bp_left_outinstead of the_bp.metallibfiles. Or packaging withIOS_PULL=1fails withSKIPS[@]: unbound variable. - Cause: the IPA packer used to strip
_bp.metallibunlessIOS_PULL=1, independently of the runtime's profile default. It later followed the profile'spso_mtl4(build_ipa.sh, and the NSP script'sios_wants_pullingwithDMSH_IOS_PULL=0, sodmsh_build.pydid not compile them either), as if nothing could read them with the key off. But the launcher offers the Metal 4 pipelines toggle for every NVN game, with the profile's key as its default only, and with it the device's prebuild and hybrid pipelines read the pulling libraries. The inclusion path also expanded an empty array underset -u, which macOS Bash 3.2 treats as unset. - Fix: an iOS build keeps the pulling libraries whatever the profile's
pso_mtl4says (build_ipa.sh,ios_wants_pulling);IOS_PULL=0leaves them out, for a smaller IPA whose launcher toggles then build no bases. An IPA that packs a pipeline archive made offline (pso/), or an Xcode project, always carries them, whateverIOS_PULLsays, since the archive's bases are made of them. An image built without them (_bp_left_out) is built again at the next shader step. Packing options always contain--store, so both inclusion and exclusion work under Bash 3.2. A device that already wrote its prebuild stamp from an app without the libraries, on the same chain version, runs the prebuild again once the app carries them: A prebuild stamp written without the pulling libraries. - Measured: the pulling libraries are 4–10 % of a game's library bytes (in the Mac images: Fire Emblem: Three Houses 10 MB, Luigi's Mansion 3 22 MB, OCTOPATH TRAVELER II 62 MB, Minecraft Dungeons II 137 MB). On the device they are worth the size: Echoes of Wisdom with both toggles on, without them on an iPhone 17, compiled 564 pipelines during play (23.3 s, the worst frame 2.6 s); with them on an iPad mini 6, its prebuild built 7,488 bases in 513 s once, and play compiled none.
- Check:
dm/gfx/tests/t_pull.m(the words against Metal's fetch and the CPU conversion),t_pull_inv.m(a depth prepass with one pipeline and depth-equal with the other),test_dmsh_pull.py;dm/ios/tests/test_profile_pack.pypacks tiny fixtures through the actual archive step and checks runtime-prebuild library inclusion, explicit overrides and an IPA with a pipeline archive in the ZIP. - Found on: The Legend of Zelda: Breath of the Wild: draws that waited for their pipeline on a cold start. The Legend of Zelda: Echoes of Wisdom: an iPhone build whose launcher toggles built no bases (issue #1684).
Absent vertex attributes lose W
- Symptom: a projectile paints the floor but its airborne mesh is invisible, without a missing-shader error.
- Cause: the native vertex descriptor and the pulling decoder supplied four zero words for an absent attribute (format 0). The shader instead needs the default float vector
(0, 0, 0, 1)as raw register bits, including when its Metal declaration uses integers. An alpha-tested depth pass can discard every fragment when that W component contributes to opacity; a color pass with depth EQUAL then draws nothing. - Fix:
vertex_constantsprovides the default vector at offset 16 of slot 30 for active absent inputs inpso_desc; inactive shadow declarations and unknown formats still read zeros at offset 0.dm_fetchsupplies the same default for format 0.pull_layout_fillpreserves nonzero formats with missing buffers so the decoder can distinguish them from absent attributes and keep their zero reads. Unknown formats and invalid streams still read zeros. - Check:
t_default_attribchecks float, signed, and unsigned native inputs (beyondS.nattr, explicitly absent, and unknown format) as well as shadow-input pipelines with both active shadowed and absent attributes.t_pullchecks the pulling default, missing buffers, invalid streams, and unknown formats alongside its format comparisons. - Found on: Splatoon Raiders, the Slosher projectile's alpha-tested depth pass (#3181).
Float32 vertex padding through integer inputs
- Symptom: a fullscreen post-process draw writes no color, then a later blur composite darkens scenery while the character remains visible.
- Cause: reinterpreting Float1/2/3 as UInt1/2/3 preserves supplied bits but pads missing
wwith integer1. A shader that bitcasts the input back to float receivesw=1.4e-45, rather than1.0, and can clip the whole draw. Float4 has no missing components. - Fix: short float32 vectors use the existing float shadow input, or CPU expansion with float
(0,0,0,1)defaults when shadows are unavailable or disabled. Float4 keeps direct reinterpretation.t_float_padchecks signed/unsigned GPU fetch, CPU fallback and Float4 controls. - Found on: Xenoblade Chronicles: Definitive Edition (the game profile is a separate, pending contribution).
CPU conversion of vertex attributes the input type cannot take
- Symptom:
Vertex attribute m_36(5) of type uint4 cannot be read using MTLAttributeFormatHalf2(draws dropped: black silhouettes); UVs collapse onto one texel (flat tan characters); vertices far out of view (negative 16-bit values widened with zeros). - Cause:
int_inputsdeclares an inputuintwhen its first translation only bit-casts it, and the shader then takes it back withas_type<float>. Maxwell's fetch converts by the format and the register holds the float32 bits, and widens integers by the format's signedness, whatever type the shader gives the register. Metal refuses a float-type format for an integer input; reading the raw bytes as integers gives denormals. For a signed format on an unsigned inputvfmt_for_ctswappedShort4forUShort4, which keeps the 16 bits but widens them with zeros, so every negative value read as 32,768–65,535. - Fix: the replay converts such attributes (half, unorm / snorm 8 and 16, 10:10:10:2, 11:11:10, BGRA8 into an int / uint input) on the CPU into float32 bits, four components with the fetch's (0, 0, 0, 1.0) defaults, in the frame arena, and binds them as UInt4 / Int4 on buffer slots 1–12 (
vconv_bind, once per range and layout per submission; red line 89). 8- and 16-bit integer formats whose signedness differs from the input's go through the same conversion (vconv_intinnvn_mtl.m, red line 96 once): 32-bit values extended by the format's own sign, missing components (0, 0, 0, 1) as integers. - Found on: Fire Emblem: Three Houses: KTGL's character and soldier shaders, fed a Half2 (UVs); also Hyrule Warriors: Age of Calamity's soldiers (flat tan). The ground under close-up battle cameras was flat steel blue: the terrain's vertex shader (
56778feb1cfdee7e) reads its grid position from anRGBA16Iattribute (x and z the grid cell, y the height, which spans the whole int16 range), and so does the side pass that draws the river surface into targets of its own (db725c85ca060403). - Note: shadow vertex inputs (
dmsh_vin.py) have since replaced both conversions; they remain for the formats shadow inputs cannot take (and for transform feedback draws andDM_NVN_VCONV_CPU=1), and the profile-side answer for one shader is Integer-typed vertex inputs fed normalized formats. - Note: how the steel-blue ground was traced, since two steps misled: where the ground was missing nothing wrote the depth (reversed-Z, cleared to 0), the lighting takes depth 0 for sky and paints the fog colour, and the never-cleared G-buffer colour targets kept an old image there (cobblestones of a mesh under the terrain, which from the map camera showed through the gaps like a road). A
HILITEcolour over the gap was stale too (the never-cleared albedo), and the end-of-frame depth showed 0 there. Recomputing every draw's clip positions fromCBDUMPdata showed that no draw of the shader reached the gap; then the side pass's layer, which showed only scattered tiles of the river, led to the vertex format. Ruled out on the way: depth clamp (Metal's clip and clamp modes gave the same depth), the pass without a depth attachment (142595 is a screen-space decal pass: it samples the depth and writes albedo and normals), polygon offset (none), dropped draws. - Note: to confirm in Three Houses: 64-pixel rectangles in the albedo where decals land. The decal pass (
417a523053457352, slots 16 and 18) and the lighting (094a2d11253f126c,f54830a75e07e14a, slots 18–20) read their decal and light lists from texture buffers that the translation declaredtexture2d, because those handles have no PC type (texture type mismatch: shader declares 2, texture is 9); skipping the decal pass removed the rectangles. Since row wrap (Buffer textures read by 1D integer fetches (row wrap), general) they read the real lists: slot 18 holds 1,052,640 elements, 65 rows. On the Mac prologue route the torches and burning houses now light the battle map and the close-up ground (they lit nothing before), and the blood decals take the scene's light instead of showing as dark blue patches. The rectangles did not appear on that route in either build (no 64-pixel structure in the close-up frames), so the scene where they were seen still has to be checked.
More than 16 vertex attributes
- Symptom:
[RED] BindVertexAttribState n=17, tens of thousands of times, and a scene that draws wrong or not at all: the bind was refused, so the draws kept the previous layout. - Cause: NVN has 16 vertex attributes and NVN2 32, and every table in the host held 16.
- Fix: the attribute tables hold 32 (
p_bind_vattr, the replay's state), and so does the answer to the device query. The pipeline key keeps the first 16 where they were and addsattr_hiat its end, so a prewarm row written before reads as 0 (pso_skey_parse);dmsh_vin.pyleaves out such shaders (its shadows take Metal attributes 16–30), and they take the ordinary path;dmsh_pull.pymakes their pulling libraries, since its layout block holds all 32 attributes. Vertex bindings stay 16. - Found on: Yoshi and the Mysterious Book: Unreal Engine 5.4's vertex factories use attribute 16 on stream 6.
Vertex formats Metal lacks
- Symptom:
vertex attribute format … not mapped(printed once). - Cause / Fix: Mario uses
RGB10A2SN(0x69) →MTLVertexFormatInt1010102Normalized. Unmapped formats fall back to a 4-component read and print the line once. The integer-read-as-float formats (*_UI2F/*_I2F, 0x51–0x68), which Metal has no vertex format for, are converted on the CPU at replay like the other conversions (vconv_i2f). - Found on: Super Mario Bros. Wonder (
RGB10A2SN); The Legend of Zelda: Breath of the Wild has anRG8_UI2Fattribute.
Long vertex ranges in the CPU conversion
- Symptom:
[RED] vertex attribute conversion: a range of 915138 vertices exceeds the per-frame staging (format 0x14)and geometry stretched into streaks from the picture's centre (a stadium's stands and roof), while the pitch, the HUD and the characters draw right. - Cause: the CPU conversion (
vconv_bind) refused a range above 4 MiB of staging, 262,144 vertices of four 32-bit values. The attribute was then left unconverted: Maxwell's fetch gives the shader the integers as float32 bits, and the bytes were read as they were. 8- and 16-bit integer formats feeding float inputs took this path (red line 99; shadow vertex inputs cover integer inputs only); they are now pulled. - Fix: the conversion takes up to 64 MiB, 4,194,304 vertices (
arena_allocmakes an arena of its own above 4 MiB, whichARENA_IDLEreleases), and a range that long is normally converted once and kept (Kept vertex conversions). - Found on: EA SPORTS FC 27, by the author of PR #1726: the Estadio da Luz at the 1.8d.6523 update, a stream of 915,138
UI16 x2vertices. Not run here (no files of that update). Other grounds, or any mesh with a stream longer than 262,144 vertices, may be affected.
Kept vertex conversions
- Symptom: the
vertex conversion:line reports millions of vertices per submission and the submitting thread's translation takes most of a frame: 7.65 million vertices, 122 MB written every frame, 26.8 ms on an M4 (about 37 fps) in the stadium above, as PR #1727 measured. - Cause: the CPU conversion was made again in every submission, whether or not the source had changed, and a stadium's meshes do not change.
- Fix: a conversion is kept across submissions while its source is unchanged (
vk_getinnvn_mtl.m). A key (range, format, layout) is noted at its first submission with 64 samples of its source, and converted into a buffer of its own at the next one that finds the samples unchanged (a stream the game rewrites is then never kept; a change the samples miss is found by the checks below). The pages wholly inside the source are write-protected (nvn_dirty_protect, as a kept index range); the bytes before and after them, in pages shared with other data, are compared with a copy, so a neighbour written every frame neither drops the conversion nor takes a fault for it. A GPU write queued on the source (copy, update, fill, transform feedback, a writable storage binding:vk_gpu_write) drops it, and none may be queued or in flight when it is made. A changed source releases its buffer once the submissions that read it complete, and is tried again after 32 submissions, twice as many after each further change, so a stream rewritten every frame costs a write-protection that often. - Note: not kept: ranges below 4,096 vertices, sources outside tracked pools, anything while the game has sparse mappings (a write through an alias takes no fault), and conversions past 256 MB in all. A key not drawn for 600 submissions is forgotten.
DM_NVN_VCONV_KEEP=0turns it off (=nsets the smallest range kept). Thevertex conversion:line gives the vertices bound from kept conversions, the conversions held and their size, and how many were made and dropped, by cause.t_vconv_keepchecks the content againstvconv_elemand each way a conversion is dropped or left. - Note: the cache allocates the edge copy before write-protecting any pages. If allocation fails, the caller converts into the frame arena and the cache can try again on the next submission.
- Note: PR #1727 proposed converting long ranges on every core instead (26.8 → 10.6–12.7 ms on that M4). That still writes the 122 MB every frame and takes every core beside the game's threads; it was not taken. A fetch on the GPU serves streams that do change too: such layouts are now pulled, and kept conversions serve the draws that still convert on the CPU.
- Found on: EA SPORTS FC 27 (the measurement above is the PR author's; the stadium was not run here with this change, so its effect there is open). Run here on Fire Emblem: Three Houses with
DM_NVN_VCONV_CPU=1: on the note's new-game route into the prologue battle (M4 Pro), the battle's bound ranges came to about 2.0 million vertices a submission, of which 1.8 million were bound from 144 kept conversions (18 MB) and 0.2 million converted; frame time p50 16.68 ms with and without, p99 17.2–17.6 against 20.4 ms, the same picture at 450 s. That run was made before the samples were added: in the cutscenes it made and dropped about 1.2 conversions a frame, nearly all of streams the game rewrites, which the samples are there to leave alone. The form with the samples passest_vconv_keepand was not run in a game.
Attributes the vertex fetch cannot read, pulled
- Symptom: the
vertex conversion:line reports millions of vertices per submission (0 keptwhen the game has sparse mappings), thetranslationline's submit CPU takes most of a frame while the GPU idles, and red line 99 (… feeds a float input) or the line for an integer-read-as-float format appears. EA SPORTS FC 27 at the Estadio da Luz: 10.7–12.0 million vertices per submission, submit CPU 17–19 ms a frame, 50–58 fps. - Cause: a vertex descriptor makes Metal's fetch read a format only into an input of its own class. What it cannot read as Maxwell's fetch does (an 8- or 16-bit integer format feeding a float input, the integer-read-as-float formats, other formats where the shader has no shadow input) went through the CPU conversion, which converts the draw's whole bound range when an indirect draw gives no vertex range, in every submission. Kept conversions are off while the game has sparse mappings and cannot serve a stream that changes.
- Fix: such a layout draws with the vertex shader's pulling entry as its own pipeline (
pull_conversion,pull_psoinnvn_mtl.m):dm_fetchdecodes every format on the GPU into the words the CPU conversion made, for the vertices drawn only. The pipeline is made as any pipeline is (pso_build: from its base made or archived, else compiled, and through theMTLDevicewithout the Metal 4 compiler, so the iPhone's default path takes it too), recorded in the prewarm lists under the layout's key, and made by the prewarm in its place (warm_task). Shadow inputs still take what they can, since a vertex descriptor's fetch costs nothing. With hybrid pipelines and the layout's own pipeline already made, that one draws (converting on the CPU) until the pulling base is made in the background. Not pulled, so still converted on the CPU: layer-writing and transform feedback vertex shaders, merged passes, a shader without a pulling library (an iOS build withIOS_PULL=0), a pulling pipeline that failed to build (red line), and everything withDM_NVN_VCONV_CPU=1. - Measured: FC 27, 1.8d.310c, Kick Off at the Estadio da Luz on an Apple M6 (16 GB), the last 70 s of play, three runs a side alternated from one save: 0 vertices converted against 10.7–12.0 million, submit CPU 1.25–1.37 against 17.3–19.2 ms a frame, frame time p50 16.66–16.68 against 17.3–20.1 ms (0–3 against 17–271 frames dropped per 300), CPU energy 2.0 against 4.6–8.1 W, footprint 3.7–4.3 against 4.6–4.9 GB. GPU p50 2–6 ms on both sides, following the scene (replays, close-ups); no cost of the run-time decode was resolved there (about 151 pulled draws a frame). The same with
DM_PSO_MTL4=0(pipelines through theMTLDevice, no hybrid pipelines, the iPhone's default): 151 pulled draws a frame, submit CPU 1.43 ms, frame time p50 16.64 ms, the same picture. The decode's cost elsewhere is the pulling entry's: about 1 ms per million vertices drawn on an M2 Max in the worst case measured. - Note: pulling libraries cover NVN2's attributes 16–31 too (the layout block holds all 32). Before that, Yoshi and the Mysterious Book's
0b0c84c390e64a6d, an Unreal Engine vertex factory with an input at attribute 16 that feedsRGBA8UIto a float input, had no pulling library and stayed on the CPU (about 15,000 vertices a submission, nearly all from kept conversions). On its route to the opening dialogue (Apple M6, headless, empty save) it now draws pulled, about 145 draws a frame: 0 vertices converted and red line 99 gone, frame time p50 16.72–16.74 against 16.70–16.73 ms, submit CPU 5.1–5.5 against 4.8–5.2 ms (runs of one host differ by that much), the same scenes. Its seen-shader library gained 184 pulling libraries (377 → 561, of its 1,520 shaders), 409.5 → 434.5 MB. - Check:
t_pull(the words against Metal's fetch and the CPU conversion; which layoutspull_conversionpulls; the host's block for attributes past 15),test_dmsh_pull.py(an input at attribute 16). - Found on: EA SPORTS FC 27: its stadium's 915,138-vertex
UI16 x2stream feeding float inputs; the selection is from PR #1129.
Null vertex buffers bound past stream 15
- Symptom:
[RED] BindVertexBuffers first=16 n=1…first=31, thousands of times a run and no visible fault. - Cause: Mario Tennis Fever clears 32 streams before each model, while NVN has 16.
- Fix: a null range past stream 15 is dropped silently, as nothing can read it (
hle_nvn.c); a real one still prints a red line, limited to 8. - Found on: Mario Tennis Fever.
Vertex streams 14 and 15 at Metal slots 14 and 15
- Symptom: the assertion
buffer index (31) must be < 31. - Cause: the host bound NVN stream n to Metal vertex buffer 16 + n, but Metal has slots 0–30 only (30 is the host's constant fallback), so stream 15 went to 31.
- Fix: translated shaders use only
buffer(0), so streams 14 and 15 now go to slots 14 and 15 (VB_SLOT). - Found on: 13 Sentinels: Aegis Rim (a minute and a half into the prologue).
Vertex streams at addresses that are not 4-byte aligned
- Symptom: Scaleform fills come out as solid white or light grey sheets over the whole screen, hard-edged triangles and bands, and the menu text is missing (a language list or a title screen that is all white behind its button prompt).
- Cause: Metal reads a vertex buffer only from a 4-byte-aligned address: bound at an address 2 mod 4, every vertex was read 2 bytes early. NVN takes any address, and Scaleform's vertex streams (16-byte vertices: two RGBA8 attributes and an RG32F position) sit at addresses such as
…6d6a. The positions became garbage spanning the screen, and the shapes, white with alpha 0.2–0.7 by their colour transforms, overlapped many times. - Fix:
bind_vbufscopies a stream whose address is not 4-byte aligned into the submission's arena (vbuf_unaligned; one copy per address and size until guest writes or pool mappings change, up to 64 MB) and binds the copy. CPU copies require a host-readable, non-sparse range without pending GPU writers in this or an earlier submission; otherwisevbuf_prepareencodes an ordered GPU copy before the render encoder, including feedback and geometry captures. Submissions and pool mappings invalidate copies; buffer and shader writes invalidate the copies they can overlap, so unrelated uniform updates keep their vertex copies. The log'svertex bindingsline counts the copies;t_vbufchecks byte-aligned readbacks, reuse, queued writes, writes between draws and pool replacement. The index buffers at addresses 2 mod 4 (16-bit indices) needed nothing. - Found on: Batman: Arkham Knight (
0100ACD0163D0000; its profile and note are in a PR of their own) (Scaleform GFx; 2–13 copies of 3–18 MB a frame in the menus and at the title, which the draws' vertex ranges could narrow). With the copy the language menu and the title screen draw right.
Vertex fetches past a stream's bound size
- Symptom: hard-edged translucent slabs and triangles over the scene that move with the camera, where a full-screen pass blends an effect in (Super Mario Odyssey: white wedges through the Cascade Kingdom's waterfall mist, one edge through the centre of the screen).
- Cause: NVN binds each vertex stream with a size (
nvnCommandBufferBindVertexBuffers), and Maxwell's fetch reads zeros past it: a draw may ask for more vertices than the stream holds, and those vertices collapse into degenerate triangles. Metal's fetch has no such limit and read on into whatever followed the stream in the pool. agl's half-resolution composite drawsDrawArrays(TRIANGLES, 0, 9)from a 36-byte stream holding one full-screen triangle; vertices 6–8 read (0, 0), (0, 1), (0.98, 0.20) from the pool's next bytes, a second triangle that blended the mist in twice. A numpy model of the composite from the frame's inputs matched the GPU's output everywhere but there, where the output matched the composite applied twice (1 % against 39 % error). - Fix: before the draw's render encoder,
vbuf_preparetakes the inputs the vertex shader reads and the draw's last element per stream (vstream_last: the last vertex of a direct draw, the last instance of a per-instance stream, element 0 of a stride-0 stream), and where that reaches past the bound size (vbuf_need, element sizes fromvattr_bytes), binds the stream as a copy of its bound bytes followed by zeros up to the last byte read. The copy isvbuf_unaligned's (per submission, CPU or ordered GPU copy); the vertex table, the pulling pipelines' layout and transform feedback take it, and the CPU-converted inputs (vconv_bind) convert zero bytes past the bound range.t_vbufreads the zeros back on the GPU;t_pullchecksvattr_bytesagainst Metal's element sizes. - Open: per-vertex streams of indexed draws, indirect draws and the batched geometry captures are not bounded (their last element is not known on the CPU without scanning the indices or reading the arguments).
- Absent streams (resolved, found by clang-tidy): CPU conversion already binds zero for a stream outside the sixteen stream slots, but its range query indexed
S.streamfirst.vstream_lastnow returns unknown before accessing an absent slot;t_vbufchecks both boundary indices. No game failure was observed. - Found on: Super Mario Odyssey (GitHub issue #558): the composite of agl's half-resolution translucent pass (
alProgramShader, vertex40cc99352976d0ff, pixel934386ce027e72be), every frame the half-resolution effects draw.
A vertex stream in no memory pool
- Symptom:
[RED] vertex stream N's buffer 0x… is in no memory pool; draw skipped(; its attributes read zerosfor a pulling pipeline,; a geometry capture reads the buffer bound beforefor one). Before the line existed: a draw whose vertices came from an earlier draw's buffer, with nothing in the log. - Cause: the host failed to place a non-zero stream address in any memory pool it tracks (a pool it missed, or an address the game computed wrongly; on the Switch the GPU would fault).
bind_vbufsskipped such a stream, so its Metal slot kept the buffer an earlier draw had bound there. A stream with address 0 is different: the vertex descriptor points its attributes at the zero buffer (ZERO_ATTR). - Fix:
bind_vbufsreports the first stream the vertex shader reads (vs_streams, from its reflection) that is in no pool, after binding the others. The draw is skipped with the red line, as for an index buffer in no pool, and so are a transform feedback capture and the vertex dump; a pulling pipeline's layout gives the stream's attributes zeros. A geometry capture shares its encoder with the job's later stages, which read what it writes, so it runs with the red line and the old binding. A stale address on a stream no input reads changes nothing. Not a fix for the address itself: the red line is there to find which pool the host missed. - Found on: The S2Arm project reported the stale binding on its copy of this layer. South Park: The Fractured But Whole also logged the warning for a stream whose declared range was too large, covered by the next entry.
t_vbufchecks that a read stream in no pool is reported and the others still bound, and that an unread one is not.
A vertex stream bound past its memory pool
- Symptom: South Park's character creator draws its backdrop, shadow and menus with the character missing. The loading screen is black and the title flickers between black and visible frames. The host may log only one skipped vertex stream, then silently skip later draws with the same problem.
- Cause: Snowdrop binds a stream from an interior offset with the buffer's full size. In the captured preview frame, stream 0 began at
0x705f714b80, inside the pool up to0x705f7dd000. Its declared0xcb9c0bytes ended0x3540past the pool. The UI binds a 4 MiB range from successive offsets, although individual draws may fetch only a few hundred bytes. Those offsets make the full-range lookup succeed near the start of the buffer and fail on most frames, even with the same indexed draws submitted by the game. - Fix:
bind_vbufsand the pulling layout can resolve the mapped prefix of an aligned stream after the full lookup fails. They prove the last byte from the draw and every reflected attribute on that stream. For direct indexed draws the proof scans CPU-readable indices and includes the base vertex. Pending writes, possible sparse aliases and invalid indices prevent the proof. Draws with unknown bounds or a fetch beyond the mapped bytes still fail. The smaller limit also bounds format conversion for the draw. Full-range cache hits include the requested size, and a prefix-only result is checked again for the next draw. - Found on: South Park: The Fractured But Whole 1.05.
t_vbufexercises the Metal binding and readback, the pulling range, rejection of draws beyond the mapped pool and cache reuse after the declared size changes.
Programs bound per stage
- Symptom: scenes and characters black, only foliage, light shafts and the HUD drawn; pass dumps full of
Z … draw skipped: no program bound. - Cause: NVN's
BindProgram(program, stageBits)binds per stage, and a null program unbinds just those stages. Metroid Dread's depth prepass callsBindProgram(program, vertex | fragment), thenBindProgram(null, fragment), and draws depth with the vertex shader alone. The host replaced its single bound program on every bind, so a null bind meant "no program bound", and all of the prepass's ~140 draws per frame were dropped. The depth buffer stayed empty, and the G-buffer passes, which test depthEQUALwithout writing, passed no pixel. - Fix: the replay tracks the program per stage (
bind_stagesinnvn_mtl.m). When the stages come from different programs, or the fragment stage is unbound, it builds a composite program, which gives a vertex-only pipeline for the prepass. Games that always bind every stage from one program (Mario, Engage) are unchanged. - Found on: Metroid Dread: the combinations it uses are (program, 0x3), (null, 0x2), (null, 0x7). 13 Sentinels: Aegis Rim builds one program per GLSLC output and pairs them only through these composites (Single-stage programs paired with a cover).
- Note: pass dumps print a
Zline wherever a draw is dropped (no program, no pipeline, empty scissor, both faces culled, no render pass). That is how this one was found: 144Z … draw skipped: no program boundlines in a frame whose G-buffer pass had draws but stayed black.
Single-stage programs bound with every graphics bit
- Symptom: a black screen from boot while the game keeps running (its frame loop issues draws every frame);
[RED] program has no vertex shader (or it is not mapped)once; GPU time 0.0 ms/s. - Cause: the game makes one program per shader (
ProgramSetShaderswith one stage) and binds each with all graphics bits:BindProgram(vertex program, 0x1f), thenBindProgram(pixel program, 0x1f), then the draw.bind_stagesgave every stage in the bits to the bound program, so the pixel program's bind also replaced the vertex slot. Every draw then had a program without a vertex shader, andpso_get_dropped it. On Maxwell/Ampere hardware, binding a non-null pixel-only (or geometry/tessellation-only) graphics program with0x1fleaves the vertex stage (VertexB) intact, whereas fragment, geometry, tessellation and mesh stages without a shader in the bound program are still unbound (as Xenoblade Chronicles 2 relies on when binding vertex-only programs with0x1fafter VS+FS, and Mario Kart World and The Legend of Zelda: Ocarina of Time rely on when binding NVN2 mesh and depth-only task/mesh programs with0xff/0xc3). - Fix:
bind_stages(nvn_mtl.m) clears the vertex bit (bit 0) only for a non-null graphics program whose known stages (prog_stage_mask, read fromNvProg.stagesorg_shmapwithout triggeringshader_get) include another graphics stage and neither a vertex nor an NVN2 mesh shader, and have no unresolved stage. Fragment, geometry, tessellation, NVN2 mesh, compute-only, partially unmapped andNULLbinds still update or unbind every bit they name. Covered bydm/gfx/tests/t_bind_stages.m. - Found on: Little Busters! Converted Edition (
0100943010310000, PR #3055): 51 single-stage programs (12 vertex and 38 pixel shaders), every bind0x1f. Without the fix, frames 120 and 1900 are all black; with it they show the Joy-Con strap notice and the title menu.
Conditional rendering survives queue continuations
- Symptom: a draw disabled by
SetRenderEnable(false)executes after an event or fence, or a conditional clear erases a target whose preceding timestamp report should make it skip. - Cause: physical submission initialization reset the global render-enable state and discarded known pending counter values. A logical NVN queue can continue across several Metal submissions, including event waits; those boundaries do not reset its render state. Timestamp reports are written to guest memory at GPU completion, so reading their old CPU bytes before that completion also gives the wrong predicate.
- Fix: render-enable state belongs to the logical queue. Known timestamp counter values survive physical prefixes until their completion writes land. Completion expires that knowledge before an event release can wake a CPU writer; a later CPU rewrite therefore remains visible. Later inline updates, fills and copies replace overlapping counter bytes and carry the latest writer’s completion fence. Copy sources with unfinished or unknown GPU writes remain unknown. This preserves the existing conservative treatment of unavailable occlusion-query results.
- Check:
t_render_enable_queueuses the public NVN API and pixel readback to cover event, signal, sync and fence boundaries, independent queues, pending reports behind a GPU gate, and a later CPU counter rewrite. Seven checks failed before the fix; all 38 pass in both encoding modes with Metal validation.t_render_counter_overlapadds checks for explicit updates, fills, copies, partial writes and a second fence; five predicates failed before the metadata fix and all pass in both encoding modes. Both tests run under any profileGAMEnames, since every game evaluates the conditions. This does not resolve the older CPU-post report emulation: a later GPU read can still observe the report’s previous bytes, and a late CPU report write can overwrite a later GPU write. The fixture prints those bytes as OPEN lines and checks the predicates (37 checks): it had checked them, and failed on the race in 3 of 60 runs. - Open: reports written on the GPU in command order (a counter heap, a resolve and a kernel at the end of each submission, keeping each game's time values) were built and measured: correct bytes in every case, but about 0.5 to 0.7 ms more GPU a frame on Ocarina of Time (about 14 submissions a frame) and no game symptom traced to the order, so not landed. The patch is kept outside the repository; each report's own GPU time instead of the segment times broke Ocarina's dynamic resolution (GPU timestamps per submission segment). The game note records visual validation.
- Found on: the queue-ordering investigation for The Legend of Zelda: Ocarina of Time, M4 Pro.
Composite program taken again after a replay state restore
- Symptom:
[RED] failed to create render pipeline (vertex 790573a52b9c5053_b fragment f39fb42850f50ecd_b): Fragment input(s) user(locn0),user(locn1) … not written by vertex shader, once on entering the first investigation;texture type mismatch: shader declares a cube, texture is 2D(a pixel shader run with another pair's bindings). - Cause: a draw ran with the vertex shader of another Shader object (
Legacy Shaders/VertexLit's shadow caster with the pixel shader ofPSYNC/BG_AlphaTest, whose own pass pairs it with00b462fe0dec6e06). Unity binds the vertex and fragment programs apart, so every draw's pair is a composite ofbind_stages, one of a ring of 64. The precompile prediction (pso_predict_rest, at a submission's first pipeline miss) saves the replay state, replays the rest of the submission's binds and restores it; in a 280-draw submission it made more than 64 composites, reused the slot the savedS.prognamed, and the draws after it up to the next bind ran with that slot's new pair. The fusion probe and redraw and the deferred-draw replay restoreSfrom copies the same way. - Fix: each restore takes the composite again from the per-stage bindings it restored (
prog_resolve, logged ascombined program taken again after a state restore); a draw already under way keeps itsNvProg, whose release is deferred. Every game. - Found on: AI: THE SOMNIUM FILES (Unity 2017.4).
- Check: two runs each from one save with one key script, prewarm off: the old host logged the
texture type mismatchline both times, the fixed host no red line, with the slot taken again twice.
Compute programs bound apart from graphics programs
- Symptom:
no program bound before the draw,program has no vertex shader(a draw after a dispatch is dropped);the dispatched program has no compute shader(a dispatch after a graphics bind). - Cause:
BindProgram(program, stageBits)with the compute bit replaced the one bound program, so a draw after a dispatch found the compute program (or none), and a dispatch after a graphics bind found no compute shader. - Fix: the replay keeps the compute program apart (
S.cproginnvn_mtl.m, andg_pp_cprogin the pass analysis). - Found on: Hyrule Warriors: Age of Calamity: the game interleaves dispatches and draws; its intro movie's NV12 → RGB draw was dropped and the movie played black under its "+ Skip" prompt.
Instanced array draws
- Instanced array draws (
DrawArraysInstanced) carry instance count and base instance in theOP_DRAWrecord. - Found on: Super Mario Bros. Wonder.
8-bit index buffers
- Cause: Metal has only 16/32-bit indices.
- Fix: 8-bit indices are widened to 16-bit at replay into the frame arena.
- Found on: Super Mario Bros. Wonder: its full-screen passes and its final copy use them.
8-bit indices widened on the GPU after a write in the same submission
- Symptom: a red line: the 8-bit index buffer had GPU-side writes in the submission (indices read stale).
- Cause: Metal has no 8-bit index type, so replay widens 8-bit indices to 16-bit on the CPU. When a copy, update or fill encoded earlier in the submission covers them (
pend_hits), the CPU reads the bytes from before that write. - Fix: those draws are widened on the GPU (
wide_run): a compute pass reads the indices from a 16-byte-aligned address, with the byte shift as a constant, and writes 16-bit ones into the frame arena. As inixc_run, the first such draw widens every such draw after it up to the next buffer write outside a render pass, so only a draw met inside an open render pass with no widening yet would split it. Draws whose indices no write covers keep the CPU widening. Log line8-bit index GPU expansion. - Found on: The Legend of Zelda: Tears of the Kingdom: about one draw per widening, up to a dozen widenings a frame on the title and load screens, no pass split.
Triangle fans and indexed quads
- Cause: Metal has neither triangle fans nor quads.
- Fix: non-indexed fans draw through a shared
(0, i, i+1)index buffer withfirstas the base vertex; indexed fans and quads are expanded on the CPU into a 32-bit triangle list in the frame arena at replay (nvn_mtl.m, as for 8-bit indices). - Found on: 13 Sentinels: Aegis Rim.
Indirect draws and dispatches read by the GPU
- Symptom: indirect draws whose record the GPU writes earlier in the frame cannot be read on the CPU at replay; GPU-driven effects drawn as indirect quads, which Metal has no primitive for.
- Cause:
nvnCommandBufferDrawArraysIndirect's record{count, instances, first, base instance}has the layout ofMTLDrawPrimitivesIndirectArguments(andDrawElementsIndirect's{count, instances, first index, base vertex, base instance}that ofMTLDrawIndexedPrimitivesIndirectArguments), but quads, fans and indexed draws with 8-bit indices have no Metal form. - Fix: the replay issues Metal indirect draws from the pool buffer.
ixc_runinnvn_mtl.mconverts records of quads, fans and indexed ones with 8-bit indices with a compute pass into indexed indirect arguments in the frame arena, and the draw indexes the shared quad / fan index buffers (indexed ones get a 32-bit list expanded on the GPU). A compute pass cannot run inside a render pass, so when the first such draw is met it converts every such draw up to the next buffer write outside a render pass (copy, update, fill, texture → buffer, dispatch; they bumpg_wr_epoch). Each record is then read after its last writer, and only a draw met inside an already open render pass splits it.DispatchComputeIndirect→dispatchThreadgroupsWithIndirectBuffer; when the shader reads the driver segment, the GPU copies the counts into c0 + 0x200 first. - Found on: Hyrule Warriors: Age of Calamity (its GPU-driven effects are indirect quads).
- Check:
DM_NVN_IXCLOG=<n>logs the first n conversions (record → arguments) once the GPU has run them.
Indirect-count multi-draws
- Symptom: an empty G-buffer pass (the title screen showed only the UI); later, the submitting thread waiting for the GPU before each such draw (36–54 fps in Kamura Village on an iPhone). MIO also reported missing level geometry with maxima of 4,594 and 8,192 draws.
- Cause:
nvnCommandBufferMultiDrawElementsIndirectCount/MultiDrawArraysIndirectCountwere empty. The scene is GPU-driven: compute culling writes the draw records (stride 20) and a u32 count, then up tomaxdraws (1–49 per call) are made from them. The original recorder also truncated every call at 1,024 draws, before the GPU-produced count was available. - Fix: calls with a maximum of up to 1,024 are recorded as individual indirect draws. Larger calls store the argument address, stride, count address and maximum in a single command. For ordinary array and indexed draws, a compute pass masks the argument records on the GPU in batches, writing zeros after the live count. Consecutive draws in the same render pass reuse their encoder state. Maxima beyond the mask table capacity use the synchronized count to bound the work to live draws. The recording size for a large call is independent of its maximum.
- Found on: Monster Hunter Rise and MIO: Memories in Orbit, issue #941. The visibility-buffer shading issue in MIO is still open.
- Note: the replay used to commit its work and wait for the GPU before the first such draw after each GPU write, then read the count on the CPU (
mdi_wait; still used when a CPU count is needed, including quads, fans and 8-bit indices). In Kamura Village that wait held the submitting thread 14 of its 20 ms a frame on an iPhone (36–54 fps). On the Mac the same scene's submit took 20 ms of wall time for 6.1 ms of work, and now 5.1 ms, all of it work.
Indirect-count multi-draws split the pass an earlier draw opened
- Symptom: in a pass dump (
DM_NVN_PASSDUMP),M … indirect-count multi-draw masking: render pass split hereinside scene passes, and the periodicindirect-count multi-draw masking:line countsrender pass splittimes in the tens of thousands. Each split loads the pass's colour and depth again (Mario Kart World: 2048x1152, 20 MB). - Cause:
mdx_runcopies a multi-draw's records at its first draw, and the compute pass that copies them cannot run inside a render pass. When an ordinary draw had already opened the pass, the copy ended it. - Fix: general (
nvn_mtl.mmdx_prescan): a draw that is not such a multi-draw and opens a pass first runs the same forward scan, once perg_mdx_epochand submission, so the multi-draws after it are copied before the pass. It runs only once the game has drawn such a multi-draw or an indirect mesh draw (g_mdx_runs), so other games do not walk their submissions for it. Ranges replayed throughdraw_multiare not scanned ahead and behave as before. - Draw-written records and counts: a copy made ahead comes before the draw that opens the pass, and a draw's shader can write a record or visibility count a later multi-draw reads. Both
ORDER_PRIMITIVESandORDER_INDIRECT_DATAorder earlier work before later vertex or indirect fetch (GAME_BARRIER_FULL). Either barrier after shader writes since the copies were made (g_mdx_wragainstg_vbuf_write_epoch) bumpsg_mdx_epoch, and later multi-draws copy again. Previously onlyORDER_INDIRECT_DATAinvalidated them: Bayonetta 3's depth prepass wrote visibility flags after the prescan had read their old zeros, and its primitive barrier left those zero draw arguments cached. The colour draws then disappeared, leaving background-coloured characters and dotted surfaces. This also applies to the scan from a multi-draw's own first draw over later draws.dm/gfx/tests/t_mdx_prescan.mchecks split counts and GPU pixels, including a real fragment store to an indexed draw's count, a 20-byte record stride, and primitive barriers with the writer at the opening draw or later in the pass. - Result on Mario Kart World, the Grand Prix route: at a race frame, masking splits 2 → 0 and mergeable splits 5 → 2 (
tbdr_pass_merge.py: 118 → 47 MB a frame); on an iPad Pro (M5) over 10 minutes, 72,000 splits → 0; GPU time on an M4 Pro p50 13.0 ms against 13.65–14.1 ms in five runs without it; on the iPad unchanged within noise (race p50 about 14.3 ms). Those were measured before the rebase onto the mesh-grid changes. On maine5fb1556(1.8.0, M4 Pro, the regression route, 2026-11-14): in pass dumps every 600 frames, 12 and 10 masking splits in two runs without it (two a frame from frame 4500 to 6900, one later) and 0 in two runs with it. In one run alternatingDM_NVN_MDX_PRESCAN=abevery 300 frames: over the first ten race phases, attachment loads 69 MB and stores 47 MB a frame lower and 2.2 fewer passes, every phase. Over the last fifteen phases no difference, where the game's passes do not split. GPU time is unchanged within the noise in every window (p50 −0.15 ms in the first ten phases, about 9.6 ms over the race). - Found on: Mario Kart World; Bayonetta 3 (draw-written visibility counts).
CPU reads after a drain wait only for later writes
- Symptom: a hitch of a second or more as a level opens: a few frames of 330–540 ms whose submission takes 2–3 times its CPU time, and the wait ledger (
DM_NVN_WAITS=1) shows thousands of indirect-count multi-draw waits for those frames only. - Cause: a draw with a geometry stage cannot be masked on the GPU (
mdx_run): the geometry path reads its count, its indirect record and its indices on the CPU, after a drain (mdi_wait: commit, wait for the GPU) when the GPU may have written them. Which writes required one was decided too coarsely.mdi_livedrained after anyg_wr_epochbump since the last drain, and the draw before had bumped it by dispatching its own geometry kernel.geo_cpu_hazardlooked at every GPU write of the submission, including those the drain had completed. So each geometry draw of such a multi-draw drained the GPU once or twice: about 1,900 drains a frame in Donkey Kong Bananza's level build (35,775 draws in one frame). - Fix: a drain completes every GPU write encoded before it, so until the submission ends only writes encoded after it can make a CPU read stale. Those are kept in a short list of ranges from the same sources the submission-wide sets have: storage writes and global-memory writes (
sbw_note), and copies, updates and fills (pend_add). The drain also marks all argument buffers dirty, becauseencode_argsnotes storage writes only when it encodes a binding, not when it reuses one. The list is trusted only in the drain's submission, until it overflows or a write of unknown size arrives, and while everyg_wr_epochbump since the drain came from a geometry kernel, compute or mesh (g_wr_geo), whose storage writes are noted as its arguments are encoded. Transform feedback's writes are not, so it falls back to the old rule.mdi_liveandgeo_cpu_hazardread without draining when nothing on the list overlaps the bytes read (drw_valid,drw_hitsinnvn_mtl.m). - Check:
t_geometry_hazardscovers the rule: earlier writes stop counting after a drain, later storage writes and copies count byte for byte, a geometry kernel keeps the list, another epoch bump, an unknown size or an overflow drops it, adjacent writes merge, and a new submission starts without one. That is 39 checks, passing with early submission on and off; the 1,920-check geometry suite also passes. On Donkey Kong Bananza's scripted route the level opening went from 540 + 433 + 337 ms to one frame of 195–280 ms (the CPU-bound build), and the indirect-count waits from 18.85 to 0.10 a frame in that window. Frames through the opening and the first gameplay show the terrain, rocks, vines and props as before. - Found on: Donkey Kong Bananza.
nvnCommandBufferDrawTexture
- Symptom: a black screen while the frame loop runs at full rate, with
[RED] NVN unimplemented function called: nvnCommandBufferDrawTexture; once drawn, the picture alternates frame by frame between the right image and another texture's (a solid colour, a still image). - Cause: the call draws a texture region (texels, through the handle's sampler) into the destination region of the bound colour targets (pixels) without a shader of the game's, and the host had no implementation. Its handle holds IDs of the texture and sampler pools the command buffer bound, as a bind's does: read as IDs of the first pool, a game that draws from a second pool got that pool's textures at the same IDs.
- Fix: recorded as
OP_DRAW_TEXwith the handle moved to the bound pools, asbind_handlesdoes (hle_nvn.c), and replayed bydraw_tex(nvn_mtl.m): its own render pass per bound colour target after the pass in progress, the pending clears landed first, with the scissor and channel mask; the replay's analyses (pass fusion, deferral, clear hoisting, the store lookahead) treat it as a texture copy. Region coordinates map to the targets' rows directly in either window origin, since the host keeps the Switch's memory layout. Blending is not applied ([RED] DrawTexture with blending on), and integer, depth and compressed targets are not drawn. - Found on: Streets of Rage 4: its scene target gets the movie frame this way (the intro, the title's flames), from movie textures registered at IDs 256 and 257 of a second texture pool.
Rasterizer discard preserves vertex storage writes
- Symptom: the HUD and sky render but the battle's characters and terrain are absent; the replay logs
draw skipped: rasterizer discardbetween model draws. - Cause: the replay returned from every discarded draw without active transform feedback. Rasterizer discard only suppresses rasterization: vertex storage writes and atomics still execute. Metal additionally requires a void-returning vertex function when rasterization is disabled.
- Fix: the offline builder adds
main0_discardto vertex shaders with writable reflected bindings or image stores (vs_writesindmsh_build.py: an image declaredaccess::writeoraccess::read_write). It retains the original body and early returns and drops only the stage outputs. Replay uses that entry in a separate pipeline with no fragment stage and rasterization disabled, with the ordinary array/indexed/instanced draw machinery and GPU-write tracking. Switching discard marks the pipeline dirty; discarded draws cannot prove an attachment fully overwritten. Pure vertex shaders with neither storage or image writes nor active feedback can still be skipped (draw skipped: rasterizer discard with no vertex storage or image writes). Transform feedback retains its capture entry. - Check:
t_rast_discardpasses 19 checks under Metal validation: array/indexed storage writes despite an empty scissor and both faces culled, two instances, unchanged clear colours, normal rendering between two discard phases, and an ordered storage-write consumer.test_discard.pycompiles a generated entry with side effects before two different returns for Mac and iOS, and checks which vertex shaders get one. - Found on: Xenoblade Chronicles 3; its note tracks the gameplay verification.
- Also found on: Metroid Prime Remastered: image stores only. Its volumetric fog fills a 100×57×64 RGBA16F froxel volume with
1cbc19f806a08166, 5,700 points with rasterization off that each write the 3D image; a full-screen pass (1b17e5a457135e3b) then samples the volume at each pixel's depth and blends it over the scene (colour × alpha + inscatter). Only storage buffer writes counted, so the draw was skipped, the volume stayed zero, and every scene (the Frigate's hull, the gunship in the opening) came out black while the HUD drew over it. Neither the CPU nor any other GPU operation writes the volume (its guest memory stays zero, pool flags0x22);DM_NVN_TEXSNAPshowed the scene intact until the fog pass.
Primitive barriers order vertex storage writes
- Symptom: exploding meshes and displaced model parts after vertex-only work; native post-vertex captures can contain valid positions for some meshes while other palettes are incorrect.
- Cause:
ORDER_PRIMITIVESwas omitted from the pass-splitting condition after shader storage writes. A primitive barrier orders earlier vertex work before later vertex work, including its storage writes. Metal does not supply that ordering between draws in one render encoder. Xenoblade Chronicles 3 uses barrier0x21after vertex shaders update its bone matrices; fragment-only barrier handling left dependent vertex work unordered. - Fix: a primitive barrier after shader writes ends the render pass, as fragment barriers already do. The next encoder's full consumer barrier supplies the required visibility.
- Check:
t_rast_discardpasses 19 GPU checks under Metal validation, including a 4,096-vertex storage producer followed by a primitive barrier and a vertex consumer in the same submission. - Found on: Xenoblade Chronicles 3;
boot24barrierremoves the exploding meshes.
Ordering barriers before a draw that writes
- Symptom: a character's mesh stretched for one frame into a long wedge or sheet that reaches another character, and other characters missing in that frame; intermittent (about one frame in a hundred near a group of characters). A pass dump shows
barrier bits 0x1 (render pass open)before vertex-only draws (fs=-,discard=1) that bind a storage bufferrwwhich the draws before them readro. - Cause: a barrier with an ordering bit (ORDER_PRIMITIVES, ORDER_FRAGMENTS, ORDER_FRAGMENTS_TILED) also makes the earlier work finish before a later draw writes, so a write cannot reach memory those draws still read. The host ended the pass at such a barrier only when the pass already had shader writes (Primitive barriers order vertex storage writes), so a write after it ran in the same Metal pass as the readers, where Metal gives no order between draws. Xenoblade Chronicles 2 skins each character with a vertex-only draw (
shd_post.wishpvar122) that writes its blended bone matrices from slot 0 of one shared 384,000-byte buffer, which the character's draws then read, and puts ORDER_PRIMITIVES before the next character's: one dumped frame had 91 such draws, 43 of them in a pass with the previous character's draws, whose later vertices could read the next character's matrices. - Fix: an ordering barrier in an open pass without shader writes leaves a mark (
g_pass_order: primitives, fragments), and the next draw whose program writes an image or a storage buffer is ordered after the pass's earlier draws (order_draw). When those draws read memory only in their vertex stage (order_note: anything bound in a later stage but samplers and driver data counts), or the barrier orders only primitives (NVN leaves the earlier fragments unordered then too), a barrier inside the pass from the vertex stage to the writer's stages does it (barrierAfterEncoderStages), and the pass keeps its attachments; otherwise, for a write in a geometry or tessellation stage, or in a merged or deferred pass, the pass ends first (Metal has no barrier from the fragment stage back to the vertex stage inside a pass). A draw without writes changes nothing. Ending the pass instead split Xenoblade Chronicles 2's geometry pass about a hundred times a frame (510 passes instead of 400, GPU p50 8.8 → 10.3 ms at Goldmouth Return Port); the in-pass barrier keeps 400 passes and the GPU time (8.2 to 8.7 ms).t_rast_discardchecks six cases under Metal validation. - Found on: Xenoblade Chronicles 2: the stretched geometry of GitHub issue #643, at Goldmouth Return Port and in the Argentum Bazaar.
Transform feedback captured by a vertex entry point
-
Symptom: characters collapsed into one thin spike (vertex streams read from feedback buffers that were never written); a character covered by a solid box while it moves (its fur shells pulled toward lagged positions that were never written); a pass dump shows draws with a vertex shader and no fragment shader (
fs=-) before the draws that read them, andY tf begin … written 0/0/0/0with noT … tf captureline. -
Cause: a game that skins on the GPU with transform feedback: a vertex-only program runs under
SetRasterizerDiscardbetweenBeginTransformFeedback/EndTransformFeedbackand writes into feedback buffers that later draws read as vertex streams. The host ignored all of it, so the streams kept whatever was there. Metal has no feedback stage. -
Fix:
- the layout comes from the program's control section (
tf_layoutindmsh_build.py): +0x6dc u16 strides, +0x6e8 per-buffer output counts, +0x6ec buffer count, and per buffer b the output locations (0x20 + n) at +0xdc + 0x80 b and matching byte component counts at +0x4dc + 0x80 b. Multiple outputs are interleaved in that order. Unknown forms get a red line and no capture entry; main0_tf(vs_tf) retains the body and stores the output bits into Metal vertex buffers 8–11, with the GPU-prepared capture record at buffer 14. The reflection listsentry_tfandtf_strides. Geometry programs give their output reader the same entry; it gathers the packed point/line/triangle indices while writing linear feedback records;nvn_feedback.inckeeps offsets and counts on the GPU when they come from it (a resume from a control buffer, a geometry capture), else on the CPU (Transform feedback captures, a pass and a dispatch each). Begin clears them; End/Pause save them in the game's opaque 32-byte control buffer; Resume restores them. A compute helper bounds each capture by all active streams and complete primitives.DrawTransformFeedbackuses the saved count as indirect array-draw arguments. Captures, counter copies and consuming draws follow encoder ordering, and captured ranges enter GPU-write tracking. Plain vertex capture supports array point/line/triangle lists with or without rasterizer discard, including instances; indexed/indirect vertex capture remains open. Geometry capture uses the existing general assembly and compute path.DM_NVN_PASSDUMPprints the records asY tf …and array captures asT … tf capture.
- the layout comes from the program's control section (
-
Check:
test_transform_feedback.pycompiles generated vertex/geometry entries for Mac and iOS;t_transform_feedbackchecks interleaving, saved offsets, resume, bounded capture, GPU-produced geometry counts, complete primitives and a following draw that consumes the saved count in the same submission. -
Found on: Pokémon Legends: Z-A: the character preview. 28 such shaders (e.g.
681cc42e48c0bbc0in thespecial/imgui.trshapack; skin indices in attribute 12, weights in 13) write positions (location 0 xyz, 12 bytes a vertex) and packed normal and tangent bits (locations 1 and 2, x only, 4 bytes) into three feedback buffers; the character draws read them as vertex streams 0–2 (RGB32F,RGB10A2SN,RGB10A2SN). Every buffer in this game holds one output from x on (strides 12/4/4, 12/12/12, 12/4, 12). The game draws these while its frame target is bound. The pass dump showed a pass of 19 draws withfs=-before the character pass. Tears of the Kingdom's 14,766 and Ace Attorney's 2,475 vertex shaders have no feedback at all.- Donkey Kong Country: Tropical Freeze: DK's fur. While DK moved, his fur shells (an instanced draw,
648304c43bbe3463/5b5ffba62bca9e0a, three shells on the body's index buffer) covered him as one solid box. Each frame a vertex-only draw (6979dd3cdbd62373/7dcdaed991c74bfe, 3,400 vertices) captures the fur's lagged positions into one buffer, two outputs per vertex (xyz each, stride 24; output count 2, component bytes03 03), and the shells read them as vertex attribute 6. Two things kept the buffer at zero (DM_NVN_KEYDUMP=5b5ffba62bca9e0a: stream 6 held zeros and2.3e24): the old one-output rule rejected the layout ([RED] … transform feedback buffer 0 has a layout of unknown form), and the game draws the capture with rasterization on (no fragment shader, colour mask 0, noSetRasterizerDiscard), which the host did not capture. Four of its 11,644 vertex shaders have this form; over Z-A's and this game's 23,277 vertex shaders together, the old and new readings give identical layouts and capture code for all 28 shaders the old rule took.
- Donkey Kong Country: Tropical Freeze: DK's fur. While DK moved, his fur shells (an instanced draw,
-
Found on: Xenoblade Chronicles 3: effect vertex and geometry programs use interleaved outputs, including eleven outputs in a 172-byte stream, and draw from saved feedback counts.
Transform feedback captures, a pass and a dispatch each
- Symptom: a game that skins with transform feedback has hundreds of encoders a frame (
DM_NVN_GPUPROF), and the GPU is idle for much of the frame between them; the pass dump showsT … tf capturelines one pass apart. - Cause: every array capture was a copy of the capture state into a buffer at its begin, a
tf_preparecompute dispatch that clipped the count and advanced the offsets, and an attachment-less render pass of its own: three encoders behind full barriers per capture. Metal orders nothing between the draws of one pass for what their vertex functions read and write, which is why each capture had its own pass. - Fix:
- the capture state (four byte offsets, the count) is known on the CPU from a begin until a resume loads it from a control buffer or a geometry capture takes its count from the GPU (
tf_state_to_gpuuploads it then): an array capture's count is in its draw. While it is known,tf_job_cpudoestf_prepare's arithmetic (dm/gfx/msl/tf.metal), and a begin or an end without a control buffer encodes nothing. An end or a pause with a control buffer while the capture pass is open is queued (g_tf_save) and copied when the pass ends; - captures that follow each other share one pass (
g_tf_enc).tf_pass_endends it before any other encoder of the command buffer begins and before the command buffer ends. A capture that reads or writes a control buffer saved in the pass, or reads or writes an inline update deferred in it (tf_update_waits), ends the pass first, since those land after it; - inside the pass a capture waits behind a barrier from the vertex stage to the vertex stage (
tf_order, asorder_drawdoes in draw passes) when it reads what an earlier capture of the pass wrote, writes what one read (vertex streams, the vertex stage's uniform and storage buffers) or wrote, follows a game barrier that orders primitives or fragments, or when it or an earlier capture since the last barrier writes memory from its vertex stage or reads it through a binding whose range is not in the state (a texture, an image, a buffer texture, global memory, a storage buffer named by a uniform buffer:tf_vs_wild); DM_NVN_TF_CPU=0sends every capture throughtf_preparein a pass of its own. The power summary has atransform feedbackline: captures with the state on the CPU, throughtf_prepare, passes and barriers in them, per frame.
- the capture state (four byte offsets, the count) is known on the CPU from a begin until a resume loads it from a control buffer or a geometry capture takes its count from the GPU (
- Check:
t_transform_feedback(both runs, the default andDM_NVN_TF_CPU=0): captures into separate ranges share a pass with no barrier; a reader of an earlier capture's output, a capture into a range written or read since the last barrier, a capture after a game barrier, and a capture with a write or an unknown read get a barrier; saves and deferred updates end the pass; the bytes and control buffers match the GPU path. - Found on: Pokémon Scarlet: a begin, one capture and an end with a control buffer per mesh, 73 to 182 a frame in Scarlet and Violet; 80 captures in the player's house went from 80 passes to 3.
Mesh geometry reports unused compute scratch as zero GPU addresses
- Symptom: a composed geometry mesh renders correctly but logs zero GPU addresses for geometry argument bindings on every draw, exhausting the first 16 diagnostics.
- Cause:
geo_mesh_encodeuses the lean compute kernel's argument layout.dmsh_mesh.composereplaces its vertex capture, vertex/index outputs and topology buffer reads with threadgroup capture, a local mask and identity indices, and rejects a kernel if those accesses remain. Their struct fields stay in the shared layout, soencode_argsincorrectly checked the unused zero slots as live GPU pointers. - Fix:
args_check_addressesexcludes only geometry registers 0, 1, 2 and 4 while encoding the composed mesh's geometry stage. Register 3 (vb_info), every guest binding and every helper in the compute path are still checked. No binding, shader, draw or graphics setting changes; this fixes the diagnostic, not a measured frame-rate bottleneck. - Check:
t_geometry_meshfails before the fix with 12 false addresses for six draws, then passes depth, per-draw storage counters, scissor, fragment discard and samples-passed comparisons in single, gathered and encoding-thread modes.t_cbs_faultchecks that missingvb_infoand guest storage still report, and switching back to compute reports all missing scratch buffers. - Found on: Donkey Kong Bananza, geometry shader
5d537f7630ec3671_bl3: registers 0/1/2/4 occupy argument slots 2/3/4/7. The separate performance investigation remains open.
Geometry-shader draws encoded a run at a time
- Symptom: a scene drawn with a geometry shader per mesh runs at 5 to 15 fps on the Mac, with the submitting thread or the GPU taking most of the frame.
- Cause: the general geometry replay (
nvn_geometry.inc) handled each draw on its own. It waited for the GPU before every indexed draw (the indices are assembled on the CPU), ended the open render pass, and ran four encoders: the vertex capture, the geometry kernel, the index compaction in one GPU thread, and the raster draw reopening the pass with its loads. - Fix:
- CPU index assembly waits when pending or current/prior GPU writes, unknown ranges or sparse aliases prevent a safe read (
geo_index_wait); native capture retains GPU ordering, and unique capture indices use a bounded bitset instead ofqsort; - the compaction (
dm/gfx/msl/geo_pack.metal) uses three blocked parallel prefix-scan stages (geo_pack_count,geo_pack_scan,geo_pack_write) with threadgroup barriers; - the first geometry draw of a run looks ahead (
geo_run_walk, with state replay only) across the geometry draws that follow it with only state, query reports and event signals in between. It encodes all their vertex captures in one render pass and all their kernels and compactions in one compute pass. Each later draw of the run then only rasterizes its prepared output in the open render pass, omitting inactive colour attachments across the run whengeo_color_omitholds.
- CPU index assembly waits when pending or current/prior GPU writes, unknown ranges or sparse aliases prevent a safe read (
- Found on: NieR:Automata The End of YoRHa Edition and US 1.0.3: about 70 index-build draws a frame in the flight section and up to 932 in heavy outdoor combat.
Helper encoders end the open copy encoder first
- Symptom:
SIGSEGVin-[AGXG18GFamilyComputeContext_mtlnext performEndEncoding](fromrp_begin_ex_, or in itsdeallocon the encoding thread); Metal validation (MTL_DEBUG_LAYER=1 MTL_DEBUG_LAYER_ERROR_MODE=nslog) names it: "Command buffer already has an open command encoder". - Cause:
tf_drawopened its render encoder while the copy encoder (g_blit) was open, which the inline updatesubd_landcopies there leave behind, as does a copy or a dispatch just before it. - Fix: every other helper pass ends
g_blitbefore it opens its own encoder, and nowtf_drawdoes too (GitHub issue #101). - Found on: Pokémon Legends: Z-A: two minutes into a new game, about frame 3390 on the Mac, with the encoding thread on and off.
Viewport swizzles applied as a flipped viewport
- Symptom: the whole picture upside down (Absolum's title logo and "Press Any Button" mirrored top to bottom); a red-reporting stub for
nvnCommandBufferSetViewportSwizzles. - Cause: the game keeps NVN's lower-left window origin (handled as for Link's Awakening, Lower-left window origin) and, twice a frame, sets viewport 0's swizzle with
nvnCommandBufferSetViewportSwizzlesto (x, −y, z, w), which negates clip-space y: how a renderer with OpenGL heritage flips its picture. - Fix: the swizzle is recorded (
OP_VP_SWIZZLE) and applied at the draw as a viewport flipped about its centre, the same mapping. Facing is decided after the swizzle on the GPU as in Metal, so the winding stays. Other swizzles (axis exchanges, negated x / z / w) give a red line and are drawn unswizzled. - Found on: Absolum (FNA3D's NVN driver,
FNA3D_Driver_NVN.cpp).
Black shapes on sprites when Unreal's GPU work runs late
- Symptom: on an Unreal Engine game with a full GPU, moving sprites flicker black for a frame: cut straight across, or a whole silhouette in the sprite's outline. It follows GPU time against the frame budget, and goes away at 30 fps or with GPU time to spare. The black is already in the scene colour the base pass writes.
- Cause: a race in the engine's NVN code. A dynamic buffer keeps
nvn.NumBufferedFramescopies (3), and each write lock moves to the next one with no fence. The render thread can come round to a copy while draws queued for the GPU still read it. If that lands between a sprite's depth prepass and its base pass, the two see different vertices: the base pass tests depthEQUAL, draws nothing where they differ, and the cleared black stays. - Fix: a workaround, since the missing fence is in the game's code: the rewriter gives each dynamic buffer a fourth copy (
dm/tools/ue_ring.py, called bypatch_nso.py), with no build ID, on any main where its chain holds. A buffer has room for exactly 4. The variable itself cannot be set to 4: its other readers size fixed tables, and the deferred-delete table has room for 3, so only the constructor's load changes. Open: this adds one lock of margin and no fence, so a GPU further behind, or a buffer locked more than once a frame, can still reach a queued copy. A single comparison has been run (5 black frames against 0 at equal load), and hit counts vary between runs. The fallback is copying small vertex streams at encode, which gave 0 against 10 and 14 in a diagnostic build; it costs every game a copy per draw and does not cover index buffers. - Found on: TRIANGLE STRATEGY, issue #1040.
Uniforms, copies and ordering
Bindless handles read from guest memory directly
- Symptom: a
sampleof the submit thread showsubo_readcalling-[MTLBuffer contents]withobjc_retainAutoreleaseat every handle read, andobjc_autoreleasePoolPopat commit draining those buffers. Fire Emblem Fortune's Weave: about 4 % of the submit thread in the reads and as much again in the drain. - Cause:
contentsis an inner-pointer method, so under ARC each call retains and autoreleases the buffer; a bindless shader reads dozens of handles a draw. The argument writes inencode_args_asked the arena's buffer for its contents the same way. - Fix:
ubo_readinnvn_mtl.m, for every game. A pool's buffer wraps guest memory without a copy at its own address (mtl_pool_addis the only place pools are made), so oncemtl_addrfinds the pool, the bytes are read at the guest address itself;mtl_addrstill runs, so the pool check and its residency are unchanged. An arena keeps its buffer'scontents(NvArena.cpu), and the argument, push-constant, driver-segment and border writes go through it. If pools ever stop being no-copy wrappers, this read would need the buffer again. - Check:
make -C dm/gfx/tests GAME=<id> run. Fortune's Weave's battle map (MacBook Pro M1 Pro): submit 42.8k → 39.2k instructions per draw. - Found on: Fire Emblem Fortune's Weave.
Depth plane copies between depth formats
- Symptom:
[RED] texture→texture copy case not implemented: 1920x1080x1→1920x1080x1 flags 0 format 260→252 3D 0→0. - Cause: the game copies its depth-stencil target (Metal
Depth32Float_Stencil8, 260) into a depth-only texture (Depth32Float, 252) of the same size. A Metal blit copies only between equal formats, and the draw path does not take depth formats. - Fix: such a copy, either way between the two formats, goes through a staging buffer kept from copy to copy: the 32-bit float depth is copied out of the source with
MTLBlitOptionDepthFromDepthStenciland into the destination's depth plane the same way (nvn_mtl.m, the texture copy). - Found on: EA SPORTS FC 27 (Frostbite): from the title on.
Depth plane copies on the encode thread
- Symptom:
FATAL deferred encoding: DmRecEnc has no stand-in for -copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:toBuffer:destinationOffset:destinationBytesPerRow:destinationBytesPerImage:options:with Metal encoding on its own thread (DM_NVN_ENC_THREAD=1, the default on iOS), at the first depth plane copy. - Cause: that copy is the only one that passes blit options (
MTLBlitOptionDepthFromDepthStencil,enc_b_copy_texture_buffer_optandenc_b_copy_buffer_texture_optinnvn_mtl.m), and the encode thread's recorder (DmRecEncinnvn_rec.h) had stand-ins only for the copies without options. A call it has no stand-in for stops the host. - Fix:
nvn_rec.hrecords both copies with their options (RO_C_COPY_TB_OPT,RO_C_COPY_BT_OPT) and replays them on the Metal 4 compute encoder. Every selector the host's encoder wrappers send now has a stand-in.check_t_rt_rangealso runs withDM_NVN_ENC_THREAD=1;t_rt_rangeandt_unwritten_storestopped there before. - Found on: the host's tests. PR #930 added the texture-to-buffer stand-in for The Legend of Zelda: Breath of the Wild on the Mac with the encode thread on (not run here).
Indirect task / mesh draws on the encode thread
- Symptom:
FATAL deferred encoding: DmRecEnc has no stand-in for -drawMeshThreadgroupsWithIndirectBuffer:threadsPerObjectThreadgroup:threadsPerMeshThreadgroup:, thenCRASH sig=6undermtk_encode, with Metal encoding on its own thread (DM_NVN_ENC_THREAD=1, the default on iOS), at the first indirect task / mesh draw. - Cause:
nvn_geometry.incencodes an indirect task / mesh draw withdrawMeshThreadgroupsWithIndirectBuffer:…, and the encode thread's recorder (DmRecEncinnvn_rec.h) had a stand-in only for the direct one (drawMeshThreadgroups:…). A call it has no stand-in for stops the host. - Fix:
nvn_rec.hrecords the indirect draw (RO_R_MESH_IND: the argument buffer's GPU address and the threads per object and mesh threadgroup, asRO_R_MESHkeeps them) and replays it.t_rec_drawschecks that the recorder has a stand-in for every draw the NVN layer encodes. - Found on: The Legend of Zelda: Ocarina of Time: the iOS app aborted when a save loaded; on the Mac with the encode thread on, 28 s after the title (issue #1265).
The GPU idles before each submission while the replay waits for the encode thread
- Symptom: with Metal encoding on its own thread (
DM_NVN_ENC_THREAD=1, the default on iOS), a frame's GPU span is far above its GPU work, and the gaps sit before the first encoder of a submission:DM_NVN_GPUPROFwith its CPU timeline shows the GPU done with everything committed while the next submission is still being encoded. The wait ledger (DM_NVN_WAITS=1) showsencode thread drainblocked about once per submission. - Cause:
mtl_sub_commitwaited for the encode thread to finish the submission (rec_drain) before returning, so the replay never translated the next submission while the encode thread encoded the last one, and the GPU got each submission only once both had finished it. A game that splits its frame at every event signal makes many submissions (eachnvnQueueSubmitCommandsis cut into one per wait, signal and fence by the queue scheduler,nq_flatten), and a submission undercut_draws()draws has no segment to start the GPU early. - Fix: the submission's records go to the encode thread with a note of its fence (
RO_NOTEong_sub_cmt), and the replay goes on. Everything else that goes to the queue after it is a record too (the next submission's commits, upload batches, snapshot copies, sparse mappings), a CPU wait for the GPU waits for the fence's signal, which comes after the commit, and graphics suspend waits for the last fence. The one direct commit that reads the game's work is the display command buffer of a present without a snapshot: it waits for the note of the submissions before it (sub_commit_wait,pq_item.sub_v).DM_NVN_SUB_DRAIN=1brings the wait back (abalternates withDM_AB). - Found on: The Legend of Zelda: Ocarina of Time on the iPhone 17 (Kokiri Forest, 2026-11-10): about 30 submissions a frame; frame 3600 spanned 34.9 ms for 20.2 ms of GPU work, and 13.6 of its 14.75 ms of gaps came before a submission's first encoder; the replay thread waited for the encode thread 36 times a frame, 10 ms in all.
- Check:
make -C dm/gfx/tests GAME=<id> t_sub_overlap && dm/gfx/tests/t_sub_overlapholds the encode thread inside a submission (a queue block) and checks that the submission returns, that its note waits for the encode thread's commit, and that a present's wait holds until then (3 of 8 checks fail with the old wait).check_t_present_cropandcheck_t_present_snaprun presents with and without the encode thread and snapshots.
Mesh draws with no task shader above 1024 workgroups
- Symptom: a GPU page fault (
kIOGPUCommandBufferCallbackErrorPageFault) 30 to 40 s after a save loads, then the game hangs or stops.DM_NVN_SKIP_MESH=1makes it go away. - Cause: Metal allows at most 1024 threadgroups in a mesh grid. The object grid has no such limit. A mesh draw with no task shader has no object function, so its workgroup count becomes the mesh grid. Indirect mesh draws reached 1,771 workgroups, direct ones at most 32. A mesh grid above 1024 reads out of bounds. Draws with a task shader are safe:
dmsh_meshstage.pyclamps the grid they emit toMETAL_MAX_GRID. - Fix: a mesh shader with no task shader gets an object function of its own (
dmsh_meshstage.pymain0_o, the library'sentry_object). Each of its one-thread threadgroups launches a block of up toDMSH_MESH_GRID(1024) mesh threadgroups and passes the block's first workgroup in its payload, and the mesh shader takes its workgroup as that plus its threadgroup ID. So the draw stays one Metal draw of ceil(count / 1024) object threadgroups, with no limit of its own:mtk_encodecomputes that for a direct draw, and for an indirect onemdx_maskwrites it beside the task shader's{count, 1, 1}. The task and object functions read the draw's{count, first}at buffer 29 (DMSH_MESH_DRAW_SLOT): an indirect draw's record itself, a direct draw's copy.t_mesh_first_usedraws 3,072 workgroups in three blocks, directly and indirectly, each to its own pixel. The object stage costs nothing measurable: Ocarina of Time'skokiri-deckroute on an M4 Pro held 60 fps at GPU p50 12.0-13.2 ms against 11.8-13.4 ms without it, 3 runs each. An earlier version of the fix, which split the draw into 8 Metal draws of at most 1024 (pull request #1708), cost nothing measurable either, but stopped at 8,192 workgroups. - Found on: The Legend of Zelda: Ocarina of Time on an M2 Max (issue #1326, pull request #1708): the foliage's mesh draws. With a pipeline archive state that faulted every time at about frame 1,930, the game ran 14 minutes (frame 30,600) without a fault with the split. On an M4 Pro the Kokiri Forest deck route has about 19 such draws a frame, up to 1,056 workgroups, 28 above 1024 in a run, without a fault on main. PRAGMATA's mesh-only grids reach 6,623 (a test of the split in the pull request).
Inline uniform updates as ordered GPU copies
- Cause: reading the uniform buffer from the CPU at encode time gives the frame's last value, not the draw's.
- Fix: inline uniform updates (
CommandBufferUpdateUniformBuffer) are replayed as in-order GPU copies (their order inside one encoder: Metal 4 does not order operations inside one encoder; inside a pass: Inline uniform updates inside a render pass). They are snapshotted at encode time (mtl_sub_update): the data is copied into a host-owned ring instead of being read from command memory when the GPU runs. - Found on: Super Mario Bros. Wonder.
Pending clears land before a compute dispatch
- Symptom: a scene opens near white and fades to its normal colours over several seconds, at each scene change, while the settled picture is right.
- Cause: a full clear with no draw after it waits on the current targets for the next pass that attaches them, as its load action. Copies land such clears first, but a dispatch only ended the open pass. So a clear before a dispatch landed after it. The game resets its auto exposure by clearing the exposure image to 1 and dispatching the shaders that read and write it as an image: the late clear overwrote the exposure they had just written, and adaptation then climbed back from 1.
- Fix:
dispatchcallsrp_flushascopy_t2tdoes. A dispatch moved ahead of a pass (cs_hoist_try) already waits for no pending clear. The cost is one clear-only pass where a game clears targets and dispatches before drawing to them. - Found on: Fire Emblem Fortune's Weave: 7 s after boot on the same route, exposure 3.035 and still climbing with 63 % of the frame near white, then 5.555 and settled with 0.1 %. The user's battle scenes, blown white before, look right after it.
[[primitive_id]] in a specialized Metal 4 pipeline
- Symptom: a regular lattice of dots over the ground, and the light wrong: three of four layers of an interleaved ambient occlusion array stay empty, while the draws and their bindings look right.
- Cause: a Metal 4 pipeline specialized from a base with unspecialized colour state gives the fragment shader
[[primitive_id]]0 for every primitive. The same shader built whole counts properly. Measured in small test programs (16384 0 0 0 pixels per layer, against 4096 each), M6, macOS 27.2. The game writes the layer from the primitive ID, drawing four triangles. Ruled out:gl_Layer, view layers, clears, and the classic and Metal 4 API alone. This is a platform behaviour the host cannot change. - Fix: the reflection records
reads_prim_id(raster.primitive_id,dmsh_build.py), andpso_build_exbuilds such a pipeline whole. Such pipelines give up the specialization's compile time, for these shaders only. - Prebuild:
pre_desc(the prebuild of a game's shader pairs) andpso_offline.py(the offline archive) leave pairs with such a fragment shader out, as no draw uses their base. - Check:
t_image_primitive_iddraws four full-screen triangles that store into the layer of their primitive ID through the host's draw path (an attachment-less pass, a metallib loaded as game shaders are). Each of the four layers holds its own primitive's value; without the flag, layers 1 to 3 stay empty (macOS 27.0.1, M3 Pro).test_pso_offline.pychecks that such a pair is left out. - Found on: Fire Emblem Fortune's Weave:
b6726be4afc44691.
Every start after play captures the whole pipeline archive again
- Symptom: the start after a play session spends minutes in the prepare step ("Preparing shaders") with MTLCompilerService at 700-980% CPU, and only a few bases are new:
pipeline prepare: 30838 lines (…) in 713.42 s on 10 workers before the first frame, progress screen shown; bases 262 compiled, 8346 from the archive, 637 reused, thenpipeline archive compacted: 14 files of bases with a vertex layout gave 8543 bases to the files just written and were removed. - Cause: play writes a run file per flush (the timer's, 10 s after a burst of new bases; 13 to 273 in an Ocarina of Time session), and a compaction leaves a file per
ARCH_PERIOD_MAXbases, 5 here. A few files of play bring the count overPSO_ARCH_COMPACT, and with every run file in the compaction its prewarm captures every base it takes from them again from the original shader functions (the #342 workaround), a full compile each: 9 files of play beside a compaction's 5 made the next start capture 8,543 bases again. A start 6 minutes after a compaction captured the same bases again in as long (654 s against 669 s). From the code, not seen: a compaction of more than 16,000 bases writes more thanPSO_ARCH_COMPACTfiles itself and compacts again at every start. - Fix: a run file's name holds how many pipelines it holds (
<seq>-<count>.mtl4a), and compaction takes files by size tier,PSO_ARCH_COMPACTtimes the one below (under 8 pipelines, 64, 512, then up to a full period): when a tier holds more thanPSO_ARCH_COMPACTfiles, its files and those of every smaller tier are compacted (arch_compact_pick), and a base found in another file is used as it is (arch_compact_takes). Only the compacted files are removed. A full period's file is never compacted, since a compaction would write it again as it was. A file named before, or with a count that is not all digits, counts as the largest tier below a full period, so an earlier compaction's full files stay; a pile of more than 8 such files is compacted once, as before. Cost, from the rule alone (a test runs 200 sessions of 30 files of 6 pipelines): a start captures again about what the last session added, 506 pipelines on average, where the old rule took the whole archive; now and then the tiers above it fill and merge: 16,380 pipelines at sessions 91 and 191 in that run, about 19 minutes of compiler work on this Mac's 10 workers by the 0.7 s figure (not measured). How large such a start can be depends on what play brings: a start takes every file of the tiers it compacts, however many. At most 17 files below a full period stayed open after any start in that run (a merge can leave 9 in the tier above until the next start), each about 0.06 ms of a lookup that misses in it. A compaction never removes a full file, so one whose binaries a system update makes miss stays open until the archive folder is removed (from the code, not seen). - Check:
t_pso_archive: which files a start compacts, by tier, from their names (5 full files beside 9, 30 and 273 files of play, 9 full files, old and malformed names, each tier boundary), and 200 sessions by the rule alone; a compaction of two full periods' files and nine of one base captures only the nine again and keeps both full files, and the next start takes every base with none compiled; a compute pipeline in a file left out is not captured again. a merge that makes a ninth file in the tier above, taken at the next start.test_pso_archive.py, in fresh processes: the same compaction and the start after it; nine files named before the count compacted once, then not again. In the game (Ocarina of Time on an M4 with 16 GB, macOS 27.2, mainbd979cedwitheed7c429, copies of the device archive with a 30,838-line list, stopped at the title): a compaction's 5 files and 9 files of play (16, 19, 4, 7, 12, 5, 7, 6 and 11 pipelines, 5 under 8 and 4 under 64, so no tier overflows), with 262 bases new to the list: 713.42 s capturing 8,543 bases again before, 23.58 s compiling only the 262 with the change, and 2.35 s the start after. An earlier revision of the rule, the same for these files: after a real 17-minute session (29 files) the next start took 24.9 s capturing 255, the one after 3.0 s; an archive of 547 files named before compacted once, 669 s, then 3.5 s. - See also: Metal's archiver store filled by one flush period.
- Found on: The Legend of Zelda: Ocarina of Time on an M4 (16 GB, macOS 27.2 26B123).
Metal's archiver store filled by one flush period
- Symptom: hundreds of
[RED] background render pipeline creation failed: error: cannot commit transaction no. '50463' on '…/com.apple.gpuarchiver/gpuarchiver-…/PersistentState': MDB_MAP_FULL: Environment mapsize limit reached(orcannot write 'UNITSMAPPINGS' database: MDB_MAP_FULL), thenpipeline archive: compaction left the old files (the flush failed); the draws of those pipelines are missing and the frame rate falls (Ocarina of Time's Kakariko Village at 30-70 ms a frame, 1,502 such lines in one session). - Cause: a pipeline the run captures for its archive is compiled through the flush period's Metal 4 compiler, bound to that period's pipeline data set serializer (
ep->comp,arch_capture). Metal keeps each serializer's state in an LMDB environment of its own, agpuarchiver-*folder undercom.apple.gpuarchiverin the user cache folder, with a fixed map size of 10 MB (thePersistentStatemeta page). Once it is full every compile through that compiler fails, not only the capture, and the host took the error as the pipeline's: the pipeline was never built, and the period's file was not written either. A period had no size limit while a compacting prewarm ran: the timer's flushes waited for the prewarm's end so that the recaptured bases would make one file, and a prewarm of 40,000 rows put 8,693 bases into one period. Periods of 3,508 bases were written whole. - Fix: a period is handed over at its 2,000th capture (
ARCH_PERIOD_MAX,arch_flush_from), during a compacting prewarm too, so each gets a fresh environment; a compaction now writes a file per period and removes the old files once every period that may hold recaptured bases is written, and keeps them when one was not written or a base was not captured again. A pipeline the capture refuses is built by the plain compiler (g_comp4), since the archive is a cache, never a condition of drawing; the failing period is handed over once, and a failure in a period that has captured nothing (so not a full store) stops capturing for the run, said in red. A pipeline both compilers refuse returns the plain compiler's error, and costs a second compile. - Check:
t_pso_archive: concurrent bases with a failing capture compiler all get a pipeline and the period is handed over once; a failure in a new period stops the captures; both compilers refusing returns the error; a compaction with a period of 4 writes a file per period and keeps the old files until its last period is written.t_pso_stall: a base Apple's compiler cannot build fails on both compilers and leaves capturing on. In the log,pipeline archive: capturing a render pipeline failed after N in its flush period. - See also: Metal's build folders left by pipeline archive flushes: the folders stay on the Mac; they take disk space but do not fill later runs' stores, each period making a new one.
- Found on: The Legend of Zelda: Ocarina of Time on an M3 Pro.
An archive period written after the compiler service died
- Symptom: every start on an archive aborts a few seconds in, during the pipeline prewarm, with
failed assertion 'Mesh Render Pipeline Descriptor Validation meshFunction must not be nil.'andCRASH sig=6; the backtrace runsmtk_build→arch_lookup→-[AGXG14GFamilyArchive_mtlnext newRenderPipelineStateWithDescriptor:error:]→AGX::ArchivePipelineFactory::lookupRenderPipeline→-[MTLMeshRenderPipelineDescriptor validateWithDevice:error:]. The run that wrote the archive hadCompilation failed due to an interrupted connection: XPC_ERROR_CONNECTION_INTERRUPTEDlines and[RED] pipeline archive: capturing a render pipeline failed after N in its flush period, and~/Library/Logs/DiagnosticReportshasMTLCompilerService-*.ipsreports (SIGBUS in AGX's LLVM backend). - Cause: Apple's compiler crashed on one shader, and the compiler service took every compile it held down with it, a capture of the current flush period among them. Since the hand-over of a failed capture's period (Metal's archiver store filled by one flush period), that period was written: its serializer holds pipelines whose functions never came back, their keys in its index. A later start's lookup of such a mesh pipeline made Metal's archive build a descriptor with no mesh function, and Metal aborts on it instead of failing the lookup.
- Fix: a capture marks its exact period
crashedbefore leaving the period's completion group, independently of its plain fallback's result. Shared Metal compilation helpers collect errors even when callers ignore them, callarch_diedon compiler-service interruption (err_compiler_died: the GPU-family error domain and generic code 2 do not identify it, so the XPC interruption text does), and finish that notification before leaving the serialization gate.arch_diedinvalidates the current period and advances the compiler-death count; periods created before that count, including ones already handed over to the writer, are untrusted.arch_write_filewaits for compiles before checking those marks and never serializes such a period. If the bounded wait ends with plain compiles still unresolved, it drops the period rather than publishing before their errors are known; a stuck capture still holds only its own period back. Its unwritten counts are drained and a compaction keeps the old files. The next start captures its pipelines again. The compiler crash itself remains open in Apple's compiler. Previously poisoned files need separate recovery: remove the period file identified in the old failure log (<seq>-N.mtl4aand its.keys), or rebuild the archive if the bad period cannot be identified. - Check:
t_pso_archivecovers discarding a crashed period, draining its counts and capturing into a fresh one.crashed_flush_raceholds a render or compute capture across hand-over, blocks its failing fallback until the writer runs, and checks that no archive is published.compiler_death_notificationsinjects interrupted specialization and MTLDevice compiles with no error output, holds a background prediction past the writer's bounded wait after its period was handed over, and checks that ordinary compile errors still publish valid captures. Run the focused cases witht_pso_archive --compiler-death. Ocarina of Time (cut10, M2): the archive without the bad period starts and plays (F1233); that period alone aborts at every start. - Found on: The Legend of Zelda: Ocarina of Time on an M2.
Missing required functions at the render pipeline API
- Symptom: Metal can abort on a nil vertex, mesh or mesh fragment function when the host builds a pipeline through
MTLDevice. - Cause: the device API validates its descriptor before returning a pipeline or an error. An unavailable shader function can leave a required descriptor member empty. Native mesh depth passes need the empty fragment function from
mtk_nop_fragment. - Fix:
dev_rpsanddev_mpsreturn a pipeline error before calling Metal when a required function is missing. Vertex depth-only passes can still omit their fragment function, and a mesh pipeline can still omit its object function. - Check:
t_pso_warmwith Metal API validation reproduces the nil vertex abort before the guard and verifies a returned error for missing vertex, mesh and mesh fragment functions after it. It also builds and draws valid native mesh pipelines and builds a depth-only mesh pipeline. - Found on: examined after the Ocarina of Time compiler failures. The fresh-start assertion logged in #2825 occurs inside Metal's archive lookup after the host presents a complete Metal 4 descriptor. The device API checks cover a separate failure path.
A pipeline compile crashes while an archive period is written
- Symptom: the pipeline prebuild (
DM_PSO_PREBUILD=tool, the NSP script's[RED] dmhost exit code -11), or a run that captures pipelines, dies with SIGSEGV and noCRASHline of its own. macOS's crash report hasobjc_msgSend←MultiLevelAirntBinaryCache::getElementAtDestination←-[MTLCompiler compileFunctionRequestInternal:…]←arch_capture, and a thread on theMTLBinaryArchive_Serializequeue inairntSerializeToURL←arch_write_file. - Cause: in Metal. Serializing a flush period's archive frees entries of Metal's compiled-binary cache that a compile under way through another compiler (the next period's, or the plain one) still reads. Each of the three crashes had a serialization under way; the in-game prebuild that survived four writes was luck. A write also ran 2 to 5 times longer while 14 compiles went on beside it (142, 85 and 62 s for about 1,000 bases, against 25 to 29 s).
- Fix: a workaround for Metal's race,
ser_begin/ser_compile_begininnvn_mtl.m: a serialization waits for the compiles under way and holds new ones back until it is written, the writer first. It waits at most 2 s (SER_WAIT_MS) for those under way: a compile that does not return must not stop every later one behind the waiting write (t_pso_stall's held compile), so the write then goes ahead beside it, with a line in the log. Every compile of the archive's paths (arch_capture,arch_capture_cs, captured or plain) goes through it. A compile held back waits for one write, which in play is a period of the bases since the last flush. The write's log line counts the compiles held back and their time. - Check: Super Mario Party's prebuild of 39,111 pairs, which had crashed three times out of three on an M4 Pro (macOS 27.2) after 4,000 to 22,000 pairs, ran through twice: 39,111 bases in 867 and 773 s, 21 files each, the writes 7 to 52 s for about 2,000 bases. The writes held the 14 workers' compiles back for 5,582 and 3,965 s of their time in all: 45 and 51 pairs a second against about 60 before (the crashed run's pace up to 22,000), 15 to 25% slower, the price of not crashing. The 2 s wait never ran out.
- Found on: Super Mario Party (
010036B0034E4000, no profile yet), #2513; one crash report of another prebuild the same day had the same two threads.
A timed archive write stalls active presentation
- Symptom: the title screen or a menu stops for over a second. The log shows a pipeline archive write and several compiles waiting for it, even when the affected frame did little new pipeline work.
- Cause: the timer flushes a partial archive after a burst of captures. Metal needs serialization and compilation to run separately, so the write can block a compile that the current frame needs.
- Fix: the windowed timer leaves captures in the current period until it can take the serialization gate. It retries if a frame was presented in the last ten seconds or a compile is still under way. Once admitted, the timed write starts on the archive queue without waiting for a compile to finish. Full periods still roll over to bound Metal's store. Offline preparation, headless runs and explicit saves use the ordinary flush path.
- Check:
t_pso_archive --active-flushholds a capture across a timer tick, resumes presentation before the capture finishes, and drives the armed retry until it writes in an idle window. It also covers an outstanding plain compile, explicit saves, full periods and headless timer writes. - Found on: Mario Kart World.
Two captures of one shader function crash in Metal's binary cache
- Symptom: the pipeline prebuild dies with SIGSEGV (
[RED] dmhost exit code -11) and noCRASHline of its own, sometimes seconds into the run and not on every run. macOS's crash report hasobjc_msgSend←MultiLevelAirntBinaryCache::getElementAtDestination(+60) ←-[MTLCompiler compileFunctionRequestInternal:…]←AGX::Compiler::compileProgram<AGX::VertexProgramKey…>←arch_capture←pre_pair, other prebuild workers wait in-[_MTLBinaryArchive getBinaryDataForKey:reflectionType:]under the same function, and no thread is inairntSerializeToURL(unlike A pipeline compile crashes while an archive period is written). - Cause: in Metal. A capturing compile looks its program up in its period's archive and messages the entry
getBinaryDataForKeyreturned without holding it; another compile that captures the same program at that moment replaces and frees the entry. The prebuild handed its pairs out in list order, and consecutive pairs often share a vertex shader (Ocarina of Time: 17,515 of 33,365 pairs use the previous pair's), so several workers compiled one vertex program at once. - Fix: a workaround for Metal's race,
fn_claiminnvn_mtl.m: captures that share a vertex-stage function (a render pipeline's vertex function, a mesh pipeline's object and mesh functions, a compute pipeline's kernel; by its library's digest and entry name) never compile at the same time (arch_capture,arch_capture_cs). The fragment function is not claimed: every crash compiled a vertex program, and Octopath Traveler II, whose 1,910 pairs each have their own vertex shader and share a few pixel shaders, prebuilt on 14 workers in some 45regress.pyruns without one; claiming its pixel shaders held that prebuild to about one compile at a time (17 s → 118 s). A capture that cannot claim its functions never goes ahead beside the other. The prebuild does not wait beside it: it puts the pair back with its functions and takes another, and a worker takes a pair it put back, before a new one, as soon as none of its functions is under way (pre_later_take), so the captures of a function many pairs share follow one another all through the prebuild instead of piling up at its end (Ocarina of Time: one vertex shader in 996 pairs). Once the list is handed out, the workers wait for the functions of the pairs still put back, with no time limit: what they wait for is a compile under way, which holds its own worker as long. The prepare step waits for the pairs put back too, not only for every pair to be handed out. A prebuild the process's end cuts short writes noprebuilt.tsv, so the next start builds what is left. Every other capture (the draws, the prewarm lists, harvests) waits up to 2 s and then builds the pipeline with the plain compiler, which captures nothing; the archive gets it at a later start. So a compile that does not return (#294) holds back the captures of its own functions by 2 s each and races none of them. The prebuild hands a vertex shader's pairs out one after another, the shader with the most pairs first (pre_order): the workers build one of its pairs at a time and the others' pairs meanwhile, so each shader's run starts at once and falls in few flush periods. The prebuild's last line counts the pairs put back; the prebuild tool's, the captures that waited and those built without the archive.t_pso_stallchecks the claim, the wait, the fallback, the putting back, the prebuild waiting for a capture under way and stopping without a stamp, and the order;t_pso_racestresses the capture path with real Metal and measures the waits (it has not reproduced the crash, with shaders this small). - Check: Ocarina of Time's tool prebuild (
DM_PSO_PREBUILD=tool) from a cold archive on an M4 Pro (macOS 27.2.1, 34,649 pairs, 14 workers, nothing else running), main against the change on the same shaders: main 644.1-663.9 s and 9.2 GB of archive in four runs (it crashed with this stack in one of six across two series, the other on the previous shaders); the change 493.1-495.8 s and 8.5 GB in two runs, no crash, every base built (33,365), none left to the draws by the guard. Octopath Traveler II inregress.py check(its prepare step and smoke route): prebuild 18.7 s on main, 18.8 s with the change, the same frames and pictures; the prewarm lists of its prepare step 0.93 → 1.63 s (captures of one vertex function waiting for each other). Tried on the way: claiming the fragment function too held Octopath Traveler II's prebuild to 113 s, and the prepare step ended once every pair was handed out, before the ones put back were built; the pairs spread across the list (i * stride mod n) took 707-713 s and 10 GB, since every flush period then held nearly every shader and wrote its own copy of each (556 MB a period against 160 MB); giving a pair up after 2 s left 223-282 pairs to the draws. - Found on: The Legend of Zelda: Ocarina of Time on an M2 Max, three prebuilds of three (#815), and one of five on an M4 Pro; The Legend of Zelda: Breath of the Wild 1.9.0 once on an M4 Pro (macOS 27.2.1), in a
regress.pyrun whose other host passed.
A cold start leaves a file per timer flush, and the next start compacts them all
- Symptom: the start after a cold start spends minutes in the prepare step ("Preparing shaders"), with MTLCompilerService at 700-980% CPU, yet the log says no base was compiled:
pipeline prepare: 30838 lines (…) in 761.61 s on 10 workers before the first frame, progress screen shown; bases 0 compiled, 8608 from the archive, 637 reused, thenpipeline archive compacted: 80 files of bases with a vertex layout gave 8859 bases to the files just written and were removed(issue #1747: a cold start of 457 s, then a warm one of 309 s with 0 compiled). - Cause: the timer's flush (10 s after a burst of new bases) ran during a prewarm that does not compact, so a cold start wrote a file every 10 s: 80 files on Ocarina of Time here, 43 in #1747. More than
PSO_ARCH_COMPACTrun files make the next start a compaction, and its prewarm captures every base it takes from them again from the original shader functions (the #342 workaround), a full compile each. A capture counted neither as compiled nor apart from the lookups, so the prepare line read 0 compiled. - Fix: the timer's flushes wait for the prewarm's end whether it compacts or not (
arch_flush_from), as they already did during a compacting one, so a prewarm writes a file perARCH_PERIOD_MAXbases. The prepare line says how many bases were captured again,pipeline bases so faralso their time. What a prewarm holds unwritten is written when the player quits (mtl_arch_savefromatexit, for ⌘Q, closing the window andexit(): it waits up to 10 s for the period's compiles and the writes, a file of 900 bases having taken 1.8-4 s;dm_gfx_quitin the graceful exit, within its 1.5 s) and starts writing when the app goes to the background or the window is minimized (dm_gfx_suspend). A write the exit cuts short leaves nocompactingmarker, which would turn compaction off on that system build (only this run's marker goes; a crashed run's stays). Only a process killed in its prewarm (a crash,SIGKILL) still leaves up to a period's captures unwritten (ARCH_PERIOD_MAX, plus compute pipelines still queued), built again at the next start. A cold start of more thanPSO_ARCH_COMPACTxARCH_PERIOD_MAX(16,000) bases still writes more thanPSO_ARCH_COMPACTfiles, and the next start compacts them (from the code, not seen). - Check:
t_pso_archive: nine new bases in a prewarm with a timer flush after each make one file per full period of 4 and one for the rest, 3 files, no more thanPSO_ARCH_COMPACT; a compaction counts its recaptured bases and their time.test_pso_archive.py, in fresh processes: that cold start, then a next start that compacts nothing and builds nothing; a cold start killed in its prewarm after 6 bases (_exit), which leaves the full period's file alone, so the next start takes those 4 and builds the other 5; and one that quits there (exit()), which writes the other 2 as well, so the next start takes all 6 and builds the other 3, leaving an earlier run'scompactingmarker in place. In the game (Ocarina of Time on an M4 with 16 GB, macOS 27.2, mainbd979cedwitheed7c429, copies of the device archive's prebuilt files with a 30,838-line list, stopped at the title): before, the cold start took 861.94 s writing 80 run files and the next start captured 8,859 pipelines again, 761.61 s before the first frame; with the change the cold start took 716.20 s writing 5 files (4 full periods and the rest) and the next start 3.30 s, with no compaction (one run each, nothing else running; an earlier pair with a build overlapping both cold starts: 854 and 725 s, then 736 and 3.67 s). - See also: Metal's archiver store filled by one flush period.
- Found on: The Legend of Zelda: Ocarina of Time on an M4 (16 GB, macOS 27.2 26B123); #1747 on an M4 Pro.
SIGTERM during the first Metal initialization
- Symptom: SIGTERM during startup logs
received SIGTERM: graceful exit, thenCRASH sig=5in_os_object_releasefrommtl_init. The caller can be the graphics drain or the guest's first NVN memory pool registration. - Cause: the shutdown worker calls
mtl_drainwhile pool registration can callmtl_initon the guest thread. Both callers can see a nullg_devand enter initialization. Replacingg_feedback_qreleases the queue the other initializer published, and the trap occurs at that release. A non-null device also became visible before the queues and residency sets were ready. - Fix: guard the complete shared Metal initialization with
dispatch_once. Every caller ofmtl_initwaits for the initialized state before proceeding. - Check:
t_mtl_initpauses the first device request while the real graphics suspend path runs. It checks for a single device request and waits for both callers to finish with the graphics state ready. The fixture also runs two device requests with the classic fallback forced. - Found on: NieR:Automata The End of YoRHa Edition.
A classic shutdown has no residency sets to attach
- Symptom: shutdown after classic Metal initialization throws
NSInvalidArgumentExceptioninuseResidencySet:. The exception reports-[NSCountedSet addObject:]: attempt to insert nil. - Cause: the classic fallback keeps
g_resandg_snap_resnil. The graphics drain creates a valid classic command buffer throughcl_cb, andres_nameused to pass both absent sets to Metal's nonnull API. - Fix:
res_nameattaches each residency set only when present. The classic drain can submit and wait on a command buffer with no residency sets. - Check:
t_mtl_initnow drains after forced-classic initialization. On an M4 Pro with macOS 27.2.1, the same drain passed with the Metal 4 capability check masked and the test switch unset. Normal Metal 4 shutdown attached both shared sets. - Found on: the Mac graphics-suspend fixture. The macOS 27.2.1 paravirtual command buffer inherits the same IOGPU residency method. Issue #112 records why virtual Macs need the classic capture path.
A run that ends in its prewarm loses what it compiled
- Symptom: a run without a window (headless, or
DM_PSO_PREPARE=0) compiles the same few dozen to few hundred bases again at every start, and area loads stall on them (a draw waits inpso_get→arch_capture→MTLCompiler), although each run compiled them before. The run's last lines saypipeline archive at exit: 425 pipelines not written yet, not all written in time: those left are built again at the next start (968 ms), or[RED] graceful exit not done in 1.5 seconds, exiting at oncewith no archive line at all. - Cause: since A cold start leaves a file per timer flush, the timer's flushes wait for the prewarm's end, and a period is written only when full (
ARCH_PERIOD_MAX, 2,000) or at exit. With a window the prewarm is the prepare step, which ends before the first frame; without one it runs beside the game, and Ocarina of Time's (31,663 lines) outlives a play session, so everything a session compiled waited for the exit. The graceful exit (SIGTERM, andoe::ExecuteProgram's hand-over) gave the archive what was left of 1.5 s, while a quit gives it 10 s and writing takes 1.8–4 s per 900 bases. When a draw was still compiling its pipeline, the drain (dm_gfx_suspend) waited on that draw, and the 1.5 s fallback ended the process before anything was handed over. A harness that stops a run for "no new frame" sendsSIGTERMexactly then. The prewarm also went on compiling during the exit, beside the write and into a period no one wrote. - Fix:
- During a prewarm the game plays through (not the prepare step, not a compaction), the timer's flush hands the period over once it is
DM_PSO_ARCH_WARM_FLUSH_MSold (60 s by default,0turns it off). Each later one waits twice as long, up to 16 times, so a cold start adds about one file per doubling, not one per 10 s. While captures wait, the timer looks again every 10 s. There is no cap by count: a period handed over at 512 captures would be a file of the top compacted tier, and a cold start's 8,600 bases in 16 of them would make the next start compact them all again. - Every end the host controls stops the prewarm and the pairs' prebuild first (
mtl_warm_stop: what they had not built is built at the next start) and gives the archive the same time,DM_QUIT_ARCH_MS(10 s,MTL_QUIT_ARCH_MSon the graphics side): atexit (⌘Q, closing the window,exit()), and the graceful exit (hle_lifecycle.c). The graceful exit starts the write first (dm_gfx_quit_begin), drains graphics on another thread and waits for that at most 1.5 s, then waits for the write; a red line says when the drain did not end, and the archive is written all the same.oe::ExecuteProgramstarts the write before the iPhone's 1.5–3 s notice (hle_oe.c). - A draw that is still compiling its pipeline holds its period, so that period is written only if the compile returns within the time; the periods before it are written either way. Past the time plus 0.5 s, a deadline ends the process, and starts the next program if the exit had not, so a stuck exit does not turn a program switch into a quit; one flag lets only one of the two run the continuation (
execve). - Files are still written as
.tmpand renamed after their index, so a write the deadline cuts short leaves the files already there valid; a start removes a.mtl4a.tmpa stopped write left, and an index whose file never came.
- During a prewarm the game plays through (not the prepare step, not a compaction), the timer's flush hands the period over once it is
- Check:
test_pso_archive.py, in fresh processes. Five new bases in a prewarm beside the game, then the timer's flush afterDM_PSO_ARCH_WARM_FLUSH_MS=300, then_exit: one file, and the next start takes all five and compiles none (before: no file, five compiled); the same in the prepare step leaves no file.SIGTERMin a prewarm, with and without a draw that holds the graphics layer (DM_TEST_STUCK_DRAW:dm_gfx_enterwith no leave): one file, all five taken at the next start (before: none with the draw held). A hand-over (dm_host_shutdown_then) with that draw held: the next program starts after the write and finds the file. A torn write's.tmpand an index without its file, beside a file that is not an archive: the leftovers are removed, the bad file is skipped, and all five bases come from the good file (before: the.tmpstays). The deadline's path (past 10.5 s) has no test. In game, Mario Golf: Super Rush headless on an empty archive, each run ended bySIGTERM(2026-11-15): during a cold pair prebuild, 1,890 bases written at the exit in 5.3 s; withDM_PSO_PREPARE=0, 929 in 4.7 s; withDM_PSO_ARCH_WARM_FLUSH_MS=5000, the timer's flush handed the period over at 10 s and the exit waited for its write (367 bases, 6.1 s), the prewarm stopped at 1,396 of 2,573 lines, and 1 capture made after the hand-over stayed unwritten; the next start took 360 bases from those files and compiled only the 360 of lines the run had not reached, and its exit wrote 381 pulling bases in 8.5 s. The 1.3 s before would have written none of them. - Found on: The Legend of Zelda: Ocarina of Time on an M4 Pro (macOS 26.6), headless: every warm-up run ended with 400–500 bases not written, and the next runs compiled 57–167 bases and missed the archive 57–256 times (PR #2625).
Archive lookups asked every file, so a few files made a start compile every base again
- Symptom: a start after some play spends minutes in the prepare step and the log says
pipeline archive compacted: N files of bases with a vertex layout gave M bases to the files just written and were removed: Ocarina of Time on an M4, 9 files of play beside a compaction's 5 made the next start capture 8,543 bases again, 713 s before the first frame (PR #1880); after a cold start's 80 files, 762 s (A cold start leaves a file per timer flush, issue #1747). - Cause: a lookup asked every file of the pipeline archive in turn, about 0.06 ms for each file the pipeline is not in, so every flush's file made each later lookup dearer, and more than
PSO_ARCH_COMPACT(8) run files made a start a compaction. A compaction compiles every base it takes from the old files again from the original shader functions, because importing them through lookup archives crashes Metal (the #342 workaround), a full compile each. So a rule that saved a few seconds of lookups (80 files: about 4.8 ms per miss, 2-4 s over a 9,000-base prewarm on 10 workers) cost minutes, and play, writing a file per timer flush, brought it on after a session or two. Every start after play captures the whole pipeline archive again limits what a compaction takes; this entry is the lookups that made the file count matter. - Fix: an index beside each archive file (
<file>.keys,arch_write_file): the keys of the pipelines in it, and whether every pipeline in it has one. A key digests what the pipeline's Metal 4 descriptor sets (arch_key): its functions by library (a digest of its bytes,lib_from_file; by the file it came from before Bases of byte-identical libraries compiled again at every start), entry name and constant values (by value: Metal has no getter for them, but their class describes and hashes them by value), the vertex layout, the colour attachments and every other field. A start reads every index into one table, newest file first, and opens the files in parallel (pso4_init); a lookup (arch_lookup: render bases, compute, task / mesh pipelines, the prebuild) asks the file the index names alone, and a miss asks none. A pipeline with no key (a library with no name: embedded kernels, diagnostic overrides) and a file with no index (written before it, or renamed) go through the files without a complete index, as before. Which files a compaction takes stays the size-tier rule (arch_compact_pick;arch_compact_takesnow finds a file among every run file,g_arch_run, indexed or not), and a compacted file's index goes with it: the file count no longer costs lookups, only the start's opening of the files (in parallel) and the disk, which the tiers bound. A key the index names a file for is looked up there alone: a miss (an OS update that changed the GPU compiler) compiles it, and the new, newer file holds it from the next start on. A field the host starts setting on a pipeline descriptor must go into the key too, or two pipelines that differ only there share one, and one of them is compiled and written again at every start. - Check:
t_pso_archive: the first file's index holds its base's key, complete; the same pipeline gives the same key, another layout another, constant values by their values whatever the order they were set in, and a library with no name no key.test_pso_archive.py, in fresh processes: after a cold start's 3 indexed files the next start asks one file for each base it finds and none for the 5 it does not (also after a cut-short and a quit cold start); a compaction of 9 one-base files leaves one file with its index and removes the 9 with theirs; files renamed to the names of before lose their index and are asked in turn (the tier tests). In the game (ŌKAMI HD on an M4 Pro, macOS 27.2, its package split again for keyed records, a 152-line prewarm list, a fresh archive, two starts each): the first start compiled its 41 bases into one indexed file; a second start that asked for the same pipelines took all 41 from the archive (twice; and a third start, after a second had written the 4 it lacked to a file of its own, took 41 of 41). Some second starts compiled 2, 4 or 8 again: those pipelines paired the same pixel shaders with another vertex library (a7537d4f1786cfdawhere the first start usedc59f90…andb555f7…), so no file held them and asking every file would have missed them too. Resolved:a7537d4f1786cfdaandb555f7058434e1faare one library, and the key named whichever Metal's shared function was noted with last (Bases of byte-identical libraries compiled again at every start). - Found on: The Legend of Zelda: Ocarina of Time (PRs #1879 and #1880, issue #1747).
A first start builds every base of the prewarm list before the first frame
- Symptom: the first start of an app with a big prewarm list sits in the prepare step ("Preparing shaders") for minutes with MTLCompilerService at full CPU: Ocarina of Time (40,154 lines) took 450-475 s on an M5 Max with an empty device archive, and the log says
pipeline prepare: … bases N compiled. The start after it takes the bases frompso_archivein seconds. - Cause: the archive bundled with the app (
pso_offline.py) holds the pairs' pulling bases and the compute pipelines. A base with a vertex layout depends on the descriptorpso_descmakes from a row'spso_skeyand the vertex shader's reflection, so only the host can make it, and the prepare step made about 6,400 of them at the first start. The host's offline mode, the prebuild tool (DM_PSO_PREBUILD=tool), built only the pairs' bases, so a--platform macbuild left the lists to the first run as well. - Fix: the prebuild tool (
mtl_pso_prebuild_tool,nvn_mtl.m) builds what a first start would: after the pairs, the prewarm lists' lines (pre_warm_lists) through the prepare step's ownwarm_parse,warm_taskandpso_desc, theRrows' bases, theCrows' compute pipelines and theMrows' mesh pipelines, captured and nothing kept (no specialization, none is archived;DM_PSO_PREBUILD_WARM=0builds the pairs alone). Its bundle form,DM_PSO_PREBUILD_OUT=<folder>, captures into a work folder in periods ofARCH_PERIOD_MAXand writes<GPU>-prewarm-<NN>.mtl4a, the index of each (<GPU>-prewarm-<NN>.keys), each period as a pipelines script (prewarm-<NN>.mtl4-json,prewarm_script) andprewarm.tsv. The NSP script's--prebake(--platform mac-app, on by default) runs it after the pipeline archive, compiles the scripts withmetal-tt -arch <GPU>for every other GPU--gpunames (after finding the libraries the scripts name by their SHA-256: the host loads them from memory, so a script has no path for them), andpack_app.pypacks the files. The host opens them inside the archive-open window (pso_bundle_open_prewarm, mapped), before the device's files: a complete index puts its keys in the archive's index (g_arch_ix), a file without one is searched first among the files of bases with a vertex layout. A--platform macbuild's tool run puts the lists' pipelines into the device's own archive. TheCandMrows' captures, which the harvest queue makes, are in the bundle: Captures still queued on the harvest queue left out of a waiting flush. - Check:
t_pso_prewarm: a row decodes to the descriptor and base key the draw makes; the bundle form writes a file per period with a complete index, a pipelines script for each (valid JSON with its libraries) and a stamp with the depth mode, again on the same work folder compiles nothing, and fails without a work folder; the device form puts the bases in the device's archive with no script, andDM_PSO_PREBUILD_WARM=0builds none; aCrow with the harvest queue held for 500 ms (T_HARVEST_HOLD) is captured before the bundle is made, in its own file and counted in the stamp, with nothing written at exit; the host opens the files, skips one that is no archive, takes the keys of two files into the index and searches the third, which has none, first; the tool's bases are found without compiling and the device's own after them.test_nsp_mac_app.py: the step's inputs, the key that reruns it, the work folder of other inputs cleared, the files and indexes packed, a failed tool leaving the app as it was, the scripts' libraries found by their SHA-256, themetal-ttcommand per other GPU, a failed period leaving that GPU without it and the next build trying again, a missing library leaving the other GPUs without files. - Measurement: with the tool's first form, which built the
Rrows alone (PR #2353), Ocarina of Time,0400486024DEC000v131072, 40,154 lines, M5 Max: prepare before the first frame 450-475 s on a first start with an empty device archive; 4.3 s on a first start with the bundled files and a new shader chain (bases: 15 compiled, 12,064 from the archive). The stage took about 3 minutes at pack time and added 17-18 files, 1.3 GB. On a MacBook Neo (applegpu_g17p) with the app packed on the M5 Max, a first start with an empty device archive and no user list prepared in 361 s (3,705 bases compiled) with the pair archive alone, and in 7 s (0 compiled, 11,975 from the archive) with themetal-ttfiles for it. Earlier, with--gpu g17pand no prewarm files for it, the first start prepared in 419 s, against 893 s plus a 1,608 s prebuild with no archive at all. With the merged tool, Cuphead (34Rrows, M4 Pro, empty device archive): 27 of 28 bases from the prewarm file, 1 compiled, against 28 compiled without it; the stage took 1 s. The one compiled was a base whose key named another of several byte-identical libraries than the tool's had (resolved: Bases of byte-identical libraries compiled again at every start); with keys by content, three first starts with the tool's file each took 28 of 28 and compiled none. - See also: Archive lookups asked every file, Metal's archiver store filled by one flush period.
- Found on: The Legend of Zelda: Ocarina of Time, Cuphead.
An iPhone builds its prewarm lists' pipelines again after an iOS update
- Symptom: after an iOS update, every start of the app logs one
[RED] pipeline archive file …/pso_archive/<file>.mtl4a not usable (deployment target for architecture applegpu_g18p found in archive … is not compatible with current OS)per file of the device's archive (Ocarina of Time on an iPhone 17 after iOS 27.2.1: 121 files, at every start until PR #2539 removed them), and the device builds the prewarm lists' bases and mesh pipelines again: at the prepare step for the listed ones, at their first draw in play for the others (pipelines up to frame N: … bases compiled 17 / 12872 ms, and4 / 45122 msin Castle Town, in windows that ran at 12-22 fps). The archive bundled with the app still opens. - Cause: the device's archive files are compiled for the system build that wrote them, and an update makes Metal refuse them; the bundled archive is made for the OS's major version (
DM_PSO_IOS_MIN), so it survives, but it held only the shader pairs' pulling bases and the compute pipelines. A prewarm list'sRrow is a base with a vertex layout and anMrow a native task / mesh pipeline, both built from a descriptor only the host makes (pso_desc,mtk_build), and the IPA got none of the prebuild tool's prewarm files, which A first start builds every base of the prewarm list before the first frame made for the Mac app. - Fix:
pso_offline.py --prewarm-host <Mac dmhost>makes them for the IPA (development.md): the Mac host's prebuild tool in its bundle form, run on the iOS libraries the app ships (a Mac's Metal loads and compiles a library built for iOS) with the profile's tables less the pair lists and a list of theRandMrows alone, writes each flush period's pipelines script and index;metal-ttcompiles each script for every GPU the IPA is built for as<arch>-prewarm-<NN>.mtl4abeside the index, andmetal-tttakes the mesh pipeline descriptors as it takes the render ones.build_ipa.shpassesDM_PSO_HOST, or the existing per-gamedm/host/gen/<id>/dmhost, made current first. The host opens the files as it opens the Mac app's (pso_bundle_open_prewarm); no host change. The index must name a library by its bytes (Bases of byte-identical libraries compiled again at every start): with keys by file name, a phone build missed 20% of the bundled bases, the ones whose shaders have a byte-identical twin library (Ocarina of Time: 563 of the 6,689 shader keys theRrows name, in 2,482 of 7,138 rows), because the Mac's tool and the phone named a different twin. - Cache and fallback: the prewarm cache includes library images and directory files (libraries, reflection and stamps), including file replacement or writes preserving modification times; it is checked independently of the pair archive cache. Unchanged published links or copies retain their file identity for packer reuse. Relative host and library paths are resolved before changing the child process directory; launch errors leave the pair archive intact. A period where
metal-ttomitted a pipeline is published without a complete index, because an entry for an absent pipeline would shadow its later device capture. - Check:
test_pso_offline.pyPrewarm: library invalidation without a changed input stamp, relative child paths, launch errors, the independent pair fast path, unchanged publication with links or copies, the tool's environment, tables and rows, the files and indexes per GPU, reuse with nothing run, a GPU dropped, new rows rerunning the host alone, groups merged with a pipelinemetal-ttrefuses left out, a failed or missing host leaving the archive, a real mesh pipeline descriptor compiled forapplegpu_g18p;IpaFallback:DM_PSO_HOSTreachespso_offline.py, discovery follows the current per-game host target without the removed game stamp, and a failed host refresh preserves the pair archive. - Validation: the original iPhone measurements and the current Mac export, prepare and walking test are in Ocarina of Time: Offline pipeline bundle. The matched phone start without the files remains open.
- Found on: The Legend of Zelda: Ocarina of Time.
Captures still queued on the harvest queue left out of a waiting flush
- Symptom: the NSP script's
[RED] prewarm pipelines: the host's prebuild tool failed (see …/logs/pso_prewarm_mac.log); the app is packed without them and builds them on its first start, though the tool's log ends atpipeline prebuild: N files (… MB) for the app to bundle in …with 0 failed; the tool's crash report (EXC_BREAKPOINT) has the main thread inmtl_arch_saveunderexit→__cxa_finalize_ranges, and the crashing thread ondm.nvn.pso-archiveinlocaleconv_l←strtod_l←libllvm-flatbuffers←-[_MTL4PipelineDataSetSerializer serializeAsPipelinesScriptWithError:]←prewarm_script←arch_write_file. Not every build: one of two of the same inputs. - Cause: a compute or native mesh pipeline that the MTLDevice builds (
cps_new_b,mtk_build) is captured for the archive later, one at a time on the harvest queue (arch_harvest, utility QoS). The flushes that wait for the archive's writes (arch_flush_wait, andmtl_arch_savewhen quitting) waited for the periods' compiles under way, but not for captures still queued there: those joined the next period, which nothing wrote in time. In the prebuild tool's bundle form,pre_warm_lists' last flush left theCandMrows' late captures out of the bundle, and the atexit handler (arch_at_exit→mtl_arch_save) wrote them as one more period with its pipelines script. Metal's serializer parses that script with libllvm-flatbuffers' locale, a static made after the handler was registered, whichexit()had already destroyed, so it trapped when the freed memory had been reused. The tool ended by a signal andmac_prebakeremoved its complete files. A game that quit with captures still queued lost them and compiled them again at the next start. A compaction's recaptures (arch_harvestof a pipeline the prewarm found in an old file) had the same gap: the flush after the prewarm (warm_finish) closed the compaction while some were still queued, so a late one went into a period the compaction did not wait for, and one that then failed found its old file already removed. And a compaction due to close stayed open for the run when that flush found the current period empty, so the next start compacted again. - Fix: a waiting flush first waits for what the harvest queue holds (
arch_harvest_wait: a marker block behind the queued captures, so captures queued after it are not waited for and draws that keep building pipelines cannot hold the wait).arch_flush_waitwaits for them without a limit;mtl_arch_savewithin its ownwait_ms, before it hands the period over. Going to the background (wait_ms0) waits for nothing, as before. The tool's bundle now holds every capture, and nothing is left for its exit. A compaction closes only once no recapture is queued (g_compact_harvests); the last queued one flushes when it has joined its period, and that flush closes it. A flush that finds the current period empty closes a compaction that is due all the same, and finishes it on the archive queue when its periods are all written. - Found on: The Legend of Zelda: Ocarina of Time (GitHub issue #2498, PRs #2499 and #2529): the tool trapped at exit on an M5 Pro and an M4 Pro, one build in two; with the queued captures waited for, the bundle went from 456.4 to 485.1 MB and holds all 164 task and mesh pipelines (20 of them the harvest queue's late ones), against 44.9 s of first-start prepare on an M4 Pro when the app shipped without the files.
- Check:
t_pso_prewarm: aCrow with the harvest queue held for 500 ms (T_HARVEST_HOLD) is captured before the bundle is made, in its own file and counted in the stamp, with nothing written at exit.t_pso_archive: with the harvest queue held for 300 ms, a compute pipeline's queued capture is written byarch_flush_wait, and bymtl_arch_saveas at a quit; a recapture queued when the prewarm ends keeps the compaction open until its own flush closes it; a compaction due to close with the current period empty closes. - See also: A first start builds every base of the prewarm list before the first frame, Compute pipelines outside the bundled archive built at every start.
Bases of byte-identical libraries compiled again at every start
- Symptom: every start compiles a few prewarm bases again and writes them to a new archive file, though the archive holds them: Cuphead's second and third windowed starts
bases 9 compiled, 19 from the archiveandbases 8 compiled, 20 from the archiveof its 28 (one newpso_archivefile each); ŌKAMI HD 2 and 3 of 14. The count varies from start to start and was 0 in some headless runs. - Cause: Metal hands out one
MTLFunctionper function content, device-wide:newFunctionWithName:on two libraries loaded from the same bytes returns the same object (Unused border corrections retain sample registers met it first). Games ship many shader keys whose libraries are the same bytes (Cuphead: 3,131 libraries, 1,625 distinct; Unity's sprite vertex shadersc58ee1901c9eaaff,229e46ed4370120b,bf6707736e88cca0and8e36438c7208b3c6are one 23,038-byte library; ŌKAMI HD: 126, 117 distinct). The host notes each function's Metal 4 descriptor by that object (fn4_note), so the descriptor names the library of whichever key was loaded last, and the archive's index key named a library by its file (arch_key, fromlib_from_file). Which key loads last depends on the order the prewarm's workers and the draws load shaders in, which changed when a start'spso_user.tsvadded shaders: the first start keyed 8 bases by229e46…, the next looked them up bybf6707…, found no file named for that key, and compiled them again. The pipelines were the same (one function), so the file held them all along. - Fix: a library's name in the key is a digest of its bytes (SHA-256, first 16 bytes;
lib_from_filefrom the mapped file,lib_tag), so any of those libraries gives the same key and one compile serves them all. The index format changed with it (DMPSOIX2): a file whose index holds keys by file name (DMPSOIX1) is reached only through keys no lookup makes now, so a start removes it with its index, and the prebuild's stamp (prebuilt.tsv) when a prebuild file goes, so the prebuild runs again (pipeline archive: N files indexed by library file names removed). The first start after the change builds those bases once more. The digest costs about 7 µs for a 20 KB library (2.8 GB/s on an M4 Pro), once per library load.fn4_notestill keeps the last descriptor; with the key by content that no longer matters, but a key whose functions Metal shared across libraries of different bytes would vary again (not seen: in a Cuphead start all 195 functions noted with a second library had libraries of the same bytes). - Check:
t_pso_archive: two library files of the same bytes give one function object and the same key whichever was noted last, and a library of other bytes another (on the code before, the second check fails).test_pso_archive.py: a cold start's archive with its indexes markedDMPSOIX1and a prebuild file beside them is removed withprebuilt.tsv, the start builds every base into indexed files, and the start after takes them all. In the games (M4 Pro, macOS 27.2, windowed, a fresh archive,DM_PSO_PREBUILD=0): Cuphead (the packed Mac app's files, this host) 28 compiled, then 0 compiled and 28 from the archive on the second and third starts, one archive file; an archive of three old files gave the removal line, 28 compiled, then 0. ŌKAMI HD (shaders rebuilt for chain94ec9a118fb3), a list of 17 render pipelines: before, starts 2 and 3 compiled 2 and 3 of 14 and wrote a file each; after, starts 2 to 4 compiled 0 of 14, one file. The prebuild tool's 1,556 Cuphead pairs were found on a second run before and after. With the prebuild tool's bundle form (A first start builds every base of the prewarm list), Cuphead's first start with the tool's prewarm file compiled 1 of 28 in that entry's measurement and 0 of 28 with this change (three first starts, then a second start: 0). - Found on: Cuphead and ŌKAMI HD.
A specialization descriptor iOS 26.0 returns autoreleased
- Symptom: with Metal 4 pipelines on (
DM_PSO_MTL4=1), the iOS app crashes before its first frame, right afterpipeline prewarm list … lines:CRASH sig=11 pc=objc_release+0x10,bt: objc_autoreleasePoolPop warm_task __warm_prepare_block_invoke, on several prepare workers at once. The Mac runs the same pipelines. - Cause:
newRenderPipelineDescriptorForSpecializationpromises a +1 object by its name, so ARC releases it once at the end ofpso_build_ex. On iOS 26.0 (23A341) the driver returns it autoreleased. On an iPad Pro M4 the method is-[AGXG16GFamilyRenderPipeline newRenderPipelineDescriptorForSpecialization]inAGXMetalG16G_B0. So ARC's release freed it, and the warm task's pool released it again. Under LLDB on the iPad:- the descriptor sits in the autorelease pool when the call returns (
_objc_autoreleasePoolPrint); NSZombieEnabled=YESreports-[MTL4RenderPipelineDescriptor release]: message sent to deallocated instance. That one release freed it, so the driver keeps no reference of its own. macOS 27.0 (26A428, M4 Pro) returns it retained. There, the direct call made the same prewarm's 34 specializations without a crash.
- the descriptor sits in the autorelease pool when the call returns (
- Fix:
spec_desc(nvn_mtl.m) finds out on its first call how the driver returns the descriptor. A weak reference survives the call's own autorelease pool only if the caller owns the descriptor. After that it takes the descriptor the way the driver gives it, so the caller owns exactly one reference either way. The answer holds for the process: every base comes from the one device's compiler or its archives. Thepipeline bases so farline names it:their descriptors returned retainedorreturned autoreleased.t_pso_stallspecializes through it too. - Check:
make -C dm/gfx/tests GAME=01005CA01580E000 check_t_pso_archiverunsspec_descagainst two stand-in bases, one that returns the descriptor retained and one that returns it autoreleased. On the first call and on later ones, the descriptor outlives every pool and is freed once dropped. The previous direct call dies on the autoreleased stand-in. Axiom Verge withDM_PSO_MTL4=1:- on the iPad, it crashed on every start before the fix. Now it runs at 60 fps: the cold start compiled 18 bases and made 25 specializations, and later starts take the bases from the archive. The log says
returned autoreleased; - on the Mac, it says
returned retained.
- on the iPad, it crashed on every start before the fix. Now it runs at 60 fps: the cold start compiled 18 bases and made 25 specializations, and later starts take the bases from the archive. The log says
- Found on: Axiom Verge 1.0.3 (
0100052004384000, its profile a separate change) with the launcher's Metal 4 pipelines on: an iPhone 16 Pro Max (iOS 26.0, LiveContainer) and an iPad Pro 11-inch (M4, iPadOS 26.0, from Xcode and in LiveContainer) crashed the same way.
A specialized Metal 4 pipeline keeps its base's fixed state in its descriptor
- Symptom: with Metal's API validation on (
MTL_DEBUG_LAYER=1), the game stops at a draw in a multisampled pass:-[MTL4DebugRenderCommandEncoder setRenderPipelineState:]: failed assertion 'Render Command Encoder Set Render Pipeline State Validation The color sample count (4) does not match the renderPipelineState's color sample count (1) The raster sample count (4) does not match the renderPipelineState's raster sample count (1)'. WithMTL_DEBUG_LAYER_ERROR_MODE=nslogthe game plays on and logs the pair at every such bind. Without validation nothing is wrong on screen. - Cause:
pso_build_exspecializes a base, whose colour state is left open, with the descriptornewRenderPipelineDescriptorForSpecializationreturns. That descriptor holds the colour state open, but its fixed state is at its defaults (1 sample, alpha to coverage off, no input primitive class, amplification count 1), whatever the base was built with. The specialized pipeline is described by that descriptor, so the debug layer reads a pipeline of a 4x pass as a 1-sample one. The pipeline key, the pass and the guest's state were right: NVN rasterizes at the target's sample count, as the host's key does (g_pass.samplesfrom the attachments). - Fix:
pso_fixed4(nvn_mtl.m) writes a pipeline's fixed state (sample count, alpha to coverage, rasterization, input primitive class, amplification count) into a Metal 4 descriptor.pso_desc4builds the base with it, andpso_build_exwrites the same state into the specialization descriptor before the colour state, so a specialization always says what its base was built with. - Check:
make -C dm/gfx/tests GAME=0100E95004038000 check_t_pso_msaa: the production pass setup and pipeline lookup in a 4x depth-only pass, a 4x colour and depth pass (also with alpha to coverage) and a 1x pass, through both pipeline compilers and both encoding modes, each bound and drawn under API validation, with the pipeline archive off (every pipeline compiled in the test). The pipeline reads as the pass's sample count and keeps the draw's alpha to coverage, and a 4x pipeline with a triangle input class and amplification count 2 (a layered, slice-merged pass's) keeps all three throughpso_build; without the debug layer, which alone reports a pipeline's descriptor, those checks print a skip line. Without the fix the Metal 4 runs stop at the first bind; with only the sample count and alpha to coverage copied, the input class and amplification count checks fail. - Found on: PRAGMATA (no profile): three depth-only pipelines of its 4x depth passes (fragments
36a5f8e07d4b90d2, which writes depth from a texture,ccfad64e9842a35candf2ff0a146037ecae) stop validation at the first gameplay frame; 11,067 such binds in a 128 s nslog run.
NVN2's DLSS on MetalFX
- Symptom: a Switch 2 game calls
nvnCommandBufferEvaluateDlssand its builder functions, which the host did not have. - Cause: NVN2 has DLSS as a part of the API, a neural network that runs on NVIDIA's GPU, with no counterpart on the Mac.
- Fix:
hle_nvn.ctakes the builder, the network and the parameters (the network's texture IDs and storage are the driver's own needs and are dropped), and answersGetOptimalSettingswith the optimal input from the method (0: 2x, 1: 3x, 2: 1x) and a range of inputs from a third of the output to the output (see Input range below). The replay'sOP_DLSSruns MetalFX's temporal scaler (dlss_eval,nvn_mtl.m) over colour, depth and motion vectors, with the jitter and a history reset, falling back to a bilinear draw when there is no scaler. This replaces the upscaler, so the picture is close to the game's, not the same. - Bias mask: DLSS's bias-current-colour mask (
nvnDlssParametersSetBiasCurrentColorMaskand its subrectangle base) is MetalFX's reactive mask: both run from 0, the temporal history as usual, to 1, the current colour alone. The scaler is made withreactiveMaskTextureEnabledand the mask's format (a part of its key), and each evaluation gives it the texture and its corner; a mask too small for the input is not used, and a format MetalFX makes no scaler for is dropped with a red line, keeping the scaler. Before, the mask was only logged ([RED] DLSS: the game's bias mask (a reactive mask for MetalFX) is not passed on). Star Fox's mask is R8 at the input's size, 960x540, with 0 or 255 only: 21-27% of the picture across its prologue, a band at the top and the bottom (about 57 rows each, the 2.39:1 frame inside 16:9) and the near cockpit and ship edges that cross into it, and 0 on every character. In the prologue on an M4 Pro, shots with the mask passed and not passed show no visible difference, fur and bands included, and neither shows trails. Check:check_t_dlss_mfxmoves a checkerboard one pixel with motion vectors of 0, not reset: 0.164 from a reset's output with the mask at 0, 0.021 at 1, and 0.164 at 1 before the change. - Encoding thread: with
DM_NVN_ENC_THREAD(the iOS default) the replay's command buffer is the recording's stand-in, which has none of MetalFX's calls: the host stopped at the first evaluation (deferred encoding: DmRecCB has no stand-in for -useResidencySet:). The scaler's state and its encode are a block run on the encoding thread with the real command buffer (rec_cb_blockinnvn_rec.h), as for a game's own upscaler. Check:make -C dm/gfx/tests GAME=040074A01BF12000 check_t_dlss_mfx(two evaluations through one scaler in a submission, the thread off and on). Not run on a game with the thread. The scaler's encoders take no barrier:mfx_orderorders them after the work before them and the next draw pass after them (An encoder of barriers alone orders nothing). - Input range:
GetOptimalSettingsreturns the optimal input size, then the smallest and the largest input the network takes (not NGX's order, which has the largest first). A game may render at another size in that range and evaluates only inside it: Xenoblade Chronicles 2's Switch 2 program stores the fourth and fifth arguments as its lower bound and the sixth and seventh as its upper one, and its evaluation (main+0x8ee0e0) returns beforenvnCommandBufferEvaluateDlssunless lower <= input <= upper. It renders 1024x576 into its 1536x864 network (method 0); while the host answered one size per method (min = max = 768x432), DLSS never ran, the game's own upscaler after it read an output nothing wrote, and every 3D frame reached the window black. The order rests on that one game: Fire Emblem Fortune's Weave stores the four values (main+0x1913cfc) but its evaluation (main+0xb70f00) checks no bound, and Donkey Kong Bananza, Switch Sports Resort, Pokopia, Resident Evil 4 and PRAGMATA look the function up without calling it. The range's values are this host's choice from DLSS's modes, not read from NVIDIA's driver. A game with a dynamic resolution renders a new size into the same textures as often as each frame, sodlss_scaler_forkeys a scaler by the textures' sizes, not the input's: the scaler's input is the textures' common size, its content scale runs from that size's up to the device's most (3x on the M6 tested), and each evaluation sets its content size. Keyed by the input's size, each new size made a scaler again (a Metal compile) and reset its history. Check:check_t_dlss_mfxruns a 1024x576 → 1536x864 evaluation, then 768x432 in the same textures through the same scaler. - Open: the jitter's sign has not been checked; no ghosting has been seen. A game whose bias mask covers what it draws, not only a band, has not been run.
- Found on: Fire Emblem Fortune's Weave:
gfxa::TaskDLSS, 1024x576 to 2048x1152. Star Fox: the bias mask. Xenoblade Chronicles 2, Nintendo Switch 2 Edition (0400E95004038001): the input range.
MetalFX's DLSS stand-in preserves alpha
- Symptom: a later pass that composites an RGBA DLSS output sees opaque alpha, whatever alpha the input colour held. RGB is correct and no validation or compilation error is logged.
- Cause: MetalFX's temporal scaler writes alpha 1.0. The host used its output directly as NVN2 DLSS's RGBA result, so an input alpha of 0.25 or 0.75 became 1.0.
- Fix: when the output format has alpha,
dlss_evalgives the input shader-read usage and the output render-target usage, then draws the input alpha over MetalFX's RGB with an alpha-only write mask. It uses the evaluation's input rectangle and the scaler's output extent, running after the scaler on the real command buffer. The record's output dimensions come from the original network builder and stay unchanged byNetworkResize; taking them instead of the scaler's dimensions skipped alpha restoration in Star Fox's resized network.copy.metal'sfsaclamps the sample position to the input rectangle's texel centers: clamping only to the texture edge would blend padding into a dynamic or offset input's alpha. If the alpha pipeline cannot be made, the existing bilinear fallback preserves every channel instead. - Check:
make -C dm/gfx/tests GAME=040041E0212AE000 check_t_dlss_mfxchecks alpha 0.25 and 0.75 at 2x and 1.5x, then at a second dynamic input size, with the encoding thread off and on and withDM_NVN_BARRIER=game. Before the fix all four output checks read 1.0. All 41 checks pass in each run on an M6 (123 total); the boundary checks inspect every output pixel with different alpha in the input's padding, at the origin and at (17,9), and an original builder size larger than the current output. The crop checks fail without the content clamp; the retained-builder-size case fails when alpha takes its extent from that size. The original 36 checks per run passed on an M4 Max too (PR #2898). - Cost: isolated on an M6 (macOS 27.2, Xcode 27.2), the production alpha draw's encoding block at RGBA16F 960x540 to 1920x1080 costs a median 0.246 ms GPU (range 0.232-0.268 ms), plus 5.7 microseconds CPU draw encoding. Three warm-up batches, then 15 alternating control / 64-draw pairs used four rotating texture pairs filled with varied pixels; GPU commit feedback minus the same submission without the alpha draws gives the per-draw cost. This includes the pass's load, store and barriers, but not first-use pipeline compilation or texture-usage upgrades. It is a synthetic pass measurement, not an in-game frame-rate comparison or a measurement on another device.
- Found on: Fast Fusion: the vehicle selector. Star Fox: the control run exposed the original builder size retained after a network resize.
The DLSS network resized
- Symptom:
[RED] NVN unimplemented function called: nvnDlssNetworkResize (x0=… x1=0x300 x2=0x1b0)at the title. - Cause: NVN2 lets a game resize a DLSS network instead of making a new one. The replay takes each evaluation's sizes from its parameters and textures, so the network keeps nothing of it.
- Fix:
nvnDlssNetworkResizesucceeds, logging the first size (hle_nvn.c). - Found on: Star Fox: 768x432, once; its evaluations run 768x432 to 768x432.
DLSS scalers released under their encoders
- Symptom: a Switch 2 game using DLSS crashes after minutes of play, at a moment it makes a DLSS network again or evaluates one at new sizes (
[nvn] DLSS network …and a newDLSS: MetalFX temporal scaler …line, for example a 1920x972 output), with*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[AGXG17XFamilyMLContext executable]: unrecognized selector sent to instance …'in-[_MTL4MachineLearningCommandEncoder encodeToCommandQueue:]underrec_commit/mtl_sub_commit(the host exits with 134). The class named varies with what took the freed memory, and many runs pass. - Cause:
dlss_scaler_forkeeps one MetalFX scaler per network in 4 slots.nvnDlssNetworkFinalizetells the replay nothing, so the slots were never freed, and the fifth network always took slot 0, dropping its scaler at once (e->sc = nil). The same happened when a network's sizes changed. A Metal 4 command buffer does not retain what is encoded into it: when that scaler had been encoded earlier in the same submission, the commit used a freed object. A standalone program that releases a scaler between its encode and the commit fails the same way, and keeping the scaler until completion makes it pass. The networks were also named by their addresses, so one made again in the same memory with the same sizes kept the old network's scaler and history. - Fix: a replaced scaler is held until the submission completes (
dlss_scaler_drop,defer_obj_release), and a new network takes the slot used least recently.nvnDlssNetworkInitializegives each network a serial, which its evaluations carry instead of its address.nvnDlssNetworkFinalizestill releases nothing: no evaluation names a finalized network's serial again, so its slot is the next one taken (at most 4 scalers stay alive).dm/gfx/tests/t_dlss_scaler.mchecks the slots, the holding and the serials;t_dlss_mfx.mruns a replaced scaler's submission with zombie objects, which fails every time without the holding. - Found on: Fast Fusion, at its 8th network, after about 9 minutes of play (PR #1479).
A game's own upscaler drawn by MetalFX
- Symptom: a Switch 2 game's frame in its heavy scenes is dominated by one compute dispatch between the render-resolution passes and the output-resolution ones: Donkey Kong Bananza's upscaler takes 3.5-5 ms of a 24 ms GPU frame on an M1 in handheld mode (960x540 → 1920x1080,
DM_NVN_GPUPROF), and the game cannot reach its 60 fps interval there. - Cause: the upscaler is the game's own network (agl's NDSR,
agl_ndsr.pck), written for the Switch 2's tensor cores: its HMMA matrix products are emulated (Ampere HMMA through simdgroup_matrix), and its shared-memory matrix loads move their row addresses between lanes with shuffles (41 % of its time on the M1). MetalFX's spatial scaler does the same job, the same sizes, in 0.97 ms. - Fix: an opt-in swap, the player's choice since the look changes. The game's upscaler shaders are the compute shaders its shader map found in an NDSR pack, a source ending in
#NDSR@<offset>(upscaler_keysindm/games/game.py, the header'sDM_GAME_UPSCALER_KEYS). The pack is a library several engines ship under their own names, so the rule names none: agl'sagl_ndsr.pck(Bananza: 24 variants, each one texture in at slot 0 and one image out at slot 1; Splatoon Raiders, Nintendo Switch Sports Resort: 20; Mario Kart World: 30) and its siblingsagl_ndsr_vr.pckandagl_ndsr_vr_light.pck(Ocarina of Time: 37 more), Kirby Air Riders' and Fast Fusion's.ndsrfiles (the same 20 networks in both), Star Fox's pack nested in aVIPRcontainer (Splatoon Raiders' 20), and the pack inside nn::ndve's movie file (Ocarina of Time: 2; the movie's own networks,#NDVE@, are not named). Shaders with the same key are the same code, so a pack shared by several games classifies once for all of them. Naming a shader only lets the host read its colour; the colour and the dispatch checks below decide whether MetalFX draws it; the launcher shows Game's upscaler (DM_UPSCALER:gameby default,metalfx) only for games that have some. Withmetalfx,up_mfx_encodereads the two rectangles from push-constant bank 24 (S.push[1]). Each rectangle contains an origin and an inclusive last texel relative to that origin. The Metal 4 spatial scaler processes the input in the colour mode the shader's code shows (An upscaler's colour read from its code). Each side is the game's own texture where MetalFX can take it as it is: the rectangle covers the whole texture, its format is not sRGB, and the texture has the usages MetalFX asks for. The input goes in its own format (the scaler is made in it; a format MetalFX refuses falls back to RGBA16F;DM_NVN_MFX_DIRECT=0keeps RGBA16F only), unless its colour is square-rooted, which only the copy squares. The output must be private and RGBA16F: MetalFX's own R11G11B10F writes come out about two steps of the format's mantissa low (2.0 as 1.94, 0.5 as 0.484, where the RGBA16F output drawn back gives 1.98 and 0.496), about 2.4 % darker everywhere. Any other side goes through the scaler's own texture, made on first use:copy_t2t_drawdraws the input rectangle into an RGBA16F texture at the origin, or a second draw places the result in the output rectangle, a render pass each. Ocarina of Time's network reads square roots in RGB9E5 (format 93) and writes R11G11B10F (1440x810 → 1920x1080 handheld), so both its copies stay: the input's squares the colour, and the output's avoids MetalFX's dark R11G11B10F writes. On an M6 (a harness of 1,200 such dispatches throughup_mfx_encode, four alternating runs, medians) a dispatch took 340 µs with both copies, 316 µs with the input straight, and 271 µs with both straight; PR #2559 measured both going in game on an M1 at 0.64 and 0.97 ms a frame less, so the input alone is an estimated 0.2-0.4 ms there. On the encoding thread the recording holds a block that encodes the scaler into the real command buffer (rec_cb_blockinnvn_rec.h; NVN2's DLSS on MetalFX goes the same way). Eight scalers (sizes, colour mode and formats) are cached for dynamic resolution and refused formats. The scaler's encoders take no barrier:mfx_orderorders them after the work before them and the next draw pass after them (An encoder of barriers alone orders nothing). Invalid rectangles, shrinking or equal-sized pairs, indirect dispatches and unsupported bindings or scaler sizes keep the game's shader. - Check:
make -C dm/gfx/tests GAME=040074A01BF12000 check_t_upscaler_mfx: a named shader's 960x540 → 1920x1080 dispatch fills the image through MetalFX. A second dispatch converts a cropped R11G11B10F input with a highlight above 1.0 and checks every pixel inside and outside an offset output rectangle. A slow pass writes the input just before the scaler and a pass copies the image right after it, 8 rounds. It runs with the encoding thread off and on, once withDM_NVN_BARRIER=game, and once withDM_NVN_MFX_DIRECT=0. Whole R11G11B10F textures: the input is taken as it is, and the R11G11B10F output is drawn back with its mean within 1.5 % of the colour (MetalFX's own write fails that), into an RGBA16F image both sides go straight, and into an offset rectangle the output is drawn back. Equal sizes and an unnamed shader keep the shader, and withoutDM_UPSCALER=metalfxnothing changes (Metal validation stops MetalFX's Metal 4 scaler on a barrier setting of its own with no public API, so that run is without it).test_game_profile.pychecks the keys taken from a shader map andtest_settings.pythat the launcher offers the choice to Bananza and not to a game without the network. Open: a standalone Metal 4 MetalFX HDR test on M1 intermittently returned non-finite pixels at small input sizes (64x36 and 320x180). The packed-format regression also saw an intermittent colour error at handheld resolution. Check picture quality and frame time against the game's network in a heavy area. The network's own cost is the translator's LDSM / MOVM emulation, open in Ampere HMMA through simdgroup_matrix. - Found on: Ocarina of Time: its networks are in
agl_ndsr_vr.pckandagl_ndsr_vr_light.pck, whichUPSCALER_SOURCEdid not match, so the option did nothing there, not even a log line (issue #1911); with them named (PR #1459),fa3033d05c0a41d6is drawn by MetalFX, 1440x810 → 1920x1080, and on an M2 Air the upscale went from 2.50 to 1.31-1.38 ms and the frame p50 from 27.5-28.2 to 25.5-26.7 ms (handheld, scripted Kokiri Forest route, two runs a side, on a host before the straight input of PR #2559). Donkey Kong Bananza: NDSR7629d857a0a93833in the heavy areas, 1676x943 → 2304x1296 docked (after three passes of its own at the render resolution, which stay), 960x540 → 1920x1080 handheld.
An upscaler's colour read from its code
- Symptom: with
DM_UPSCALER=metalfx, a game's picture is washed out wherever it upscales: lifted shadows and low contrast, the scene only, with the UI drawn after it correct; withDM_UPSCALER=game, or at a size the game does not upscale, it is right. - Cause: the swap ran every variant of agl's NDSR network in MetalFX's HDR mode, taking input and output as linear. That is true only of some. Each variant shows its colour in its sRGB curves: Bananza's pack (header word
0x300) encodes its linear input right after reading it (0.0031308, 1 / 2.4, as floats); Splatoon Raiders' pack (0x40100) has no such step, because the colour it reads is encoded already. Within each pack the output differs by variant: no decode at the end, so the output stays encoded (half of Splatoon Raiders', a third of Bananza's), or a decode to linear (0.04045, 2.4; in Splatoon Raiders' half-float code 0.0404358, 2.3984375 and 0.0774536 for 1 / 12.92). So MetalFX passed Splatoon Raiders' encoded colour through, into an image the following passes read as linear. Ocarina of Time's networks (agl_ndsr_vr.pck,agl_ndsr_vr_light.pck) have no sRGB curve and still convert: a pass before them square-roots the scene colour (gamma 2,MUFU.SQRT, into RGB9E5), and the network writes its result squared with its sign kept,x * |x|(FMUL in_vr, HMUL2 in_vr_light), into R11G11B10F. Taken as one colour space, MetalFX left that result root-encoded: about the square root of the right picture, pale and low in contrast (the picture's mean 146 of 255 against 92, its darkest 5 % at 63 against 10). - Fix: the host reads the colour from each named shader's code when the program loads (
up_mfx_read_colorinprog_get,up_mfx_color): the curves' constants are immediates, whole bytes in the code, and count from 8 uses, far fewer than a curve per channel of every output tile. No profile key, no chain change, no shader rebuild. An encode and a decode in floats are linear input and output: HDR mode, as before. A half-float decode with no encode is sRGB input and linear output: perceptual mode into RGBA8Unorm (the network clamps to 0-1 before its decode, so the range is the same), and the draw into the game's image reads it through an RGBA8Unorm_sRGB view, which decodes it; always through the scaler's textures. Square-rooted input: at least 8 sign-keeping squares (up_mfx_squares: FMUL or HMUL2 of a register by itself,|x|on one side only; the real networks have 32 to 108), no power (up_mfx_has_pow: noMUFU.EX2orMUFU.LG2, which every curve takes wherever its constants come from) and no constant of a curve, each counted alone from 8 uses. The copy into the scaler's RGBA16F texture squares the input (COPY_T2T_SQUARE,copy.metalfsq), never the game's texture straight, and MetalFX runs in HDR mode, so values above 1 keep their range. Any other shape keeps the game's shader, with a log line: a variant whose output stays encoded, a network that squares and then encodes, and a variant whose code shows neither a curve nor a square, since nothing in it says what its colour is (Ocarina of Time's pre-passes square-root withMUFU.SQRTalone). Each colour has its own scaler in the size cache. - Check:
make -C dm/gfx/tests GAME=0400380020056000 check_t_upscaler_mfx: the classifier on synthetic code in each shape, and an sRGB input, full and as a packed subrectangle, comes out decoded, with linear input at the same sizes not decoded. The classifier against the translated shaders of all 44 variants of the two packs: no mismatch (Bananza 16 linear, 8 kept; Splatoon Raiders 10 sRGB, 10 kept). The same check of the square-rooted shape on synthetic code (signs, lanes, RZ, a power or a curve's constant beside the squares), a square-rooted input in R11G11B10F and in RGBA16F that comes out squared through the copy, and the rule against the raw code of Ocarina of Time's 37_vrand_vr_lightcompute shaders: 18 square-rooted (10 and 8;fa3033d05c0a41d6andd99fbeeb53d38847, which the game runs, among them), 12 that encode after the square kept, 7 pre-passes kept. Mario Kart World's 30 by the same rule, from their raw code: 20 linear, 10 kept. Open: Kirby Air Riders' and Fast Fusion's 20 (one set, another version of the library) have not been read, and Star Fox dispatches one of Splatoon Raiders' variants with no curve (ddc729bcdb4c8df9, PR #2340), which keeps its shader; an unknown shape keeps its shader, so the choice may do nothing there yet. - Found on: Splatoon Raiders (#1156), the first level with
c1b8edc09e3313b1and30d8ee33de9dee85: the washed-out picture reproduced, and with the fix the sky and scene means match the game's upscaler within 0.6 of 255 per channel, against about 50 too high before. The square-rooted shape on The Legend of Zelda: Ocarina of Time: washed out on an M5 Ultra with the option on (PR #1459), reproduced on an M5 Pro, and with the squares the picture's means within 1.3 of 255 of the game's upscaler on every channel (darkest 5 %: 9.7 against 10).
Metal 4 does not order operations inside one encoder
- Symptom: tall blue / textured panels that flickered frame to frame: the fountain's vertex shader pushed the water surface to the top of the screen.
- Cause: the host batches consecutive copies, fills and inline uniform updates (
UpdateUniformBuffer) into one compute encoder, and Metal 4 does not order operations inside one encoder. Mario writes the same uniform slot twice in a row each frame (4 bytes of −1, then 16 bytes of wave coefficients); without an intra-encoder barrier the writes occasionally landed in reverse order, the fountain's GPU wave simulation (a 512×1 RGBA16F texture updated by render → copy back → splash pass every frame) ran with −1 as its self coefficient and diverged to ±65504. - Fix:
blit_bufnow insertsbarrierAfterEncoderStageswhen an operation reads or writes a guest range an earlier operation in the same encoder wrote; texture copies always get one. Render passes have their own encoder with full barriers, so they were not affected; compute dispatches share the copy encoder (Compute dispatches share the copy encoder) and are ordered against copies by the same ranges (Compute dispatches that wait for each other). - Check: without the barriers in
blit_barrierthe stripes come back (the switch that turned them off,DM_NVN_BLIT_ORDER=0, has been removed). - Found on: Super Mario Bros. Wonder.
An encoder of barriers alone orders nothing
- Symptom: MetalFX scales a picture whose drawing has not finished (stale or half-drawn input), or the pass after a scaler reads its output before the scaler wrote it: one frame now and then where the GPU is busy. No game has been seen to show it; the tests below show it in every round, or most.
- Cause: MetalFX's Metal 4 scalers open encoders of their own with no barrier, before or after their work, so the host put an encoder before them with a consumer barrier (after the queue's stages, before Blit) and a producer barrier (after Blit, before the queue's stages). Those barriers order the encoder's own blits: with no work between them they order nothing, in another command buffer or in the same one. On an M4 Pro (macOS 27.2) a kernel reading what a slow kernel just before it wrote read stale words in 20 of 20 rounds behind an empty encoder of Blit barriers, as with no encoder at all, and in none behind the same barriers around a one-word copy. On the replay's command buffer this rarely showed, because every encoder the host ends there carries a producer barrier of its own (
m4_end; a draw pass's relaxed end withDM_NVN_BARRIER=game,enc_r_end_pass), which orders a scaler after it: with a slow pass written through those encoders just before a DLSS evaluation, 0 of 8 rounds read stale colour in either barrier mode. Work that ends with no barrier was not ordered: a scaler's own encoders (a scaler reading another's output) and a slow pass ended bare (6-7 of 8 rounds stale;t_present_crop's frame before an in-place present, 8 of 8). So the present's in-place read was ordered in games by the frame's last encoder, and only the test's bare frame raced it. After the scaler, the next draw pass is ordered by its own consumer barrier, which it skips after a relaxed end (g_last_end_relaxed);dlss_eval's empty encoder left that flag set, so withDM_NVN_BARRIER=gamethe first draw pass after DLSS read its output before MetalFX wrote it in 8 of 8 rounds (up_mfx_encodecleared it). - Fix:
mfx_order(nvn_mtl.m), before every MetalFX scaler (the present'sfx_encode,dlss_eval,up_mfx_encode): the encoder between the barriers holds a blit that they carry, the present's copy of its content or else one word of a 16-byte scratch buffer, and on the replay's command buffer it clears the relaxed end, so the next draw pass takes its consumer barrier. - Check:
t_present_crop: a slow kernel draws the window texture in the command buffer before an in-place, direct present; with the empty encoder all 8 rounds read the earlier frame, with the copy none.make -C dm/gfx/tests GAME=040074A01BF12000 check_t_dlss_mfx check_t_upscaler_mfx: a slow draw pass that ends with no barrier writes the scaler's input just before each evaluation or dispatch, and a draw pass copies its output right after (t_mfx_passes.h), 8 rounds, the encoding thread off and on, and once withDM_NVN_BARRIER=game: with the empty encoder both checks fail (the copy's from the stale output; with only the word and not the flag, the copy is stale in 8 of 8 rounds withDM_NVN_BARRIER=game), withmfx_ordernone. - Found on: no game; review of PR #1541, which first read the presented texture in place behind an empty encoder.
Buffer copies through aliased Metal addresses
- Symptom: a buffer copy, inline update or fill completes, but a following copy through another Metal buffer over the same allocation reads stale bytes.
- Cause: Metal buffers over one allocation have distinct GPU addresses. Device visibility alone does not flush their alias caches. Sparse virtual pools also give the same physical bytes distinct guest addresses, so the copy encoder's guest-range dependency checks can miss a conflict entirely; barriers at encoder boundaries cannot order copies within that encoder.
- Fix:
blit_bufmarks encoders containing buffer copies, updates or fills; their start, intra-encoder and end barriers includeMTL4VisibilityOptionResourceAlias. Operations touching a sparse virtual range (nvn_sparse_alias) receive conservative barriers against prior and subsequent operations, since a mapped run can span unrelated physical allocations. Ordinary buffers retain range-based batching. Texture-only and helper encoders keep their existing visibility options. - Check:
make -C dm/gfx/tests GAME=010015100B514000 check_t_copy_aliasexercises two no-copy buffers over one allocation, physical-to-virtual, virtual-to-physical and virtual-to-virtual sparse aliases, copies, inline updates and both fill paths, within one encoder and across encoder boundaries, with direct and deferred encoding and Metal validation. On an M4 Pro, the original host failed 37 of 101 checks; PR #200 alone left 24 failures from missed intra-encoder sparse dependencies; the complete fix passes all 101 in both encoding modes. - Found on: synthetic regression using the sparse mapping mechanism of Monster Hunter Rise; the game and iPhone have not been rerun for this change. The no-copy buffer failure was reported by MacNativeGames (
803128e) in PR #200 and reproduced here.
Inline uniform updates inside a render pass
- Symptom: many render passes with one draw each and high submit time: Metroid Dread's cutscene frames had about 180 passes with one draw each (about 5 ms of submit time per frame on the Mac).
- Cause: the game updates uniforms inline (
CommandBufferUpdateUniformBuffer) between draws, and every copy or update ended the host's render pass. This was correct but cost submit time. - Fix: an inline uniform update inside a pass no longer ends it: it is deferred to the pass end (
DM_NVN_UB_DEFER=0restores the old behaviour), and the draws after it read a shadow (Partial-cover uniform shadows keep passes open); see development.md, Power. - Found on: Metroid Dread.
- Note: 04's Metroid Dread section (at
6a06877) still described the old behaviour ("every copy or update ends the host's render pass"); the deferral came later (development.md's Power section), and it is now the default (ubd_oninnvn_mtl.m, off withDM_NVN_UB_DEFER=0).
Deferred inline updates reach geometry-stage mesh bindings
- Symptom: an inline buffer update is applied after a geometry shader running as a mesh draw, so the shader sees stale uniforms, storage data or indices, or its storage writes are overwritten at the end of the render pass.
- Cause:
geo_mesh_drawpasses a synthetic vertex/fragment-only program anddi = NULLto the normal draw path. Its deferred-update conflict check therefore cannot see the lean geometry kernel's stage-2 buffer bindings or an indexed draw's index buffer, even though the mesh function reads both. - Fix: before the synthetic draw, check the selected lean kernel's stage-2 bindings (
ubd_conflict_sh) and any indexed draw's index buffer range (ubd_hits), landing conflicting updates before encoding the mesh draw. Non-conflicting updates and uniform reads that can use a complete or partial shadow keep their deferral. The compute fallback already lands updates before its geometry dispatch. - Found on: the stage-2 uniform conflict reported in Wolfenstein: Youngblood, issue #1314; reproduced independently in
check_t_geometry_meshwith geometry-stage storage counters and indexed mesh draws (the game's profile and remaining visual issues remain open).
Partial-cover uniform shadows keep passes open
- Symptom: hundreds of render passes a frame and heavy attachment traffic when a game updates a small part of a large uniform block before each draw group.
- Cause: a draw whose uniform binding overlaps an update deferred in the open pass reads a shadow; when the deferred updates cover only part of what the shader can read, the rest must come from somewhere, and the pass used to end there (
nvn_mtl.m, the comment aboveubd_on). - Fix: the shadows take the rest from memory (
ubp_get,DM_NVN_UB_PARTIAL) and the per-shader read extents ofcb_extent.tsv(written by a fulldmsh_build.pyrun) keep those passes open.DM_NVN_UBP_CHECK=1compares every shadow with the GPU's memory. - Found on: The Legend of Zelda: Breath of the Wild (2026-10-21, the user's Great Plateau save, Mac M4 Pro): a frame had about 386 render passes and loaded and stored about 900 MB of attachments (on an iPhone at 60 fps about 55 GB/s, near the memory's bandwidth); the GPU waits for each pass to finish before the next. 220 of the passes ended only because the game updates the first 64 bytes of a 64 KB vertex uniform block (
0x70c38c0000) before each draw group while its shaders read up to 544 bytes of it (the terrain pixel shadereb0afe555b86da79, which indexes the block with an integer made from an interpolated value, reads the whole block). With the fix: 386 → about 165 passes, GPU p50 about 9.3 → 6.5 ms, submit 5.7 → 4.9 ms;DM_NVN_UBP_CHECK=1found every shadow equal to the GPU's memory (968,000 checked). - Note: a storage buffer bound with size 0 once made every partly covered shadow after it in the submission refuse (A storage buffer bound with size 0 counted as a write anywhere). What still splits BotW's big passes (a
DM_NVN_PASSDUMPframe dump): the NintendoWare VFX GPU particles run one compute dispatch per emitter between draws (ten 800x450 half-resolution passes and two G-buffer passes, about 190 MB a frame; the G-buffer ones read the depth being drawn, so they cannot move ahead of the pass), and decals that sample the G-buffer right after the game sets it again. The decals sample targets of their own pass (Metal leaves that undefined; the Mac reads the stored content);DM_NVN_FB_SNAP=allwould snapshot them at a large cost. Tried and dropped:DM_NVN_TBDR=1(since removed; 10–15% fewer stores, more CPU, red ledger lines, and it turns the deferred uniform updates off),DM_NVN_BARRIER=game(no gain), same-target continuation outside TBDR mode (the decals end the pass anyway).
A storage buffer bound with size 0 counted as a write anywhere
- Symptom: a scene runs at 20–27 fps where similar ones hold 60, with the GPU time about three times its usual (draw counts unchanged). The
residency setline showspasses ended to land them for a readin the tens of thousands, every onerefused … other GPU writes, and about three times the usualload-all store-all passes. A burst of 1,200 such refusals at each world load is the short form. - Cause: the partly covered uniform shadows (Partial-cover uniform shadows keep passes open) refuse while another GPU write of the submission may have touched the block. The writes are kept by 4 KB page (
sbw_note). A writable storage buffer whose size the host does not know counted as a write anywhere: it setg_sbw_over, and every partly covered shadow after it in the submission was refused, each refusal ending the pass. A size of 0 counted as unknown, so did a write over 16 MB. Breath of the Wild's GPU particle dispatch9f8116baffddaf81(cs_effect.binvariant 3, 16 bytes a particle) binds its three outputs withnvnCommandBufferBindStorageBuffer(…, address, 0), inside a 10 MB memory pool; the uniform block the draws update (0x70c38c0000) is in another pool. - Fix: such a binding now counts as the rest of the Metal buffer its address falls in (
sbw_len): a device pointer that runs past its buffer is out of bounds on Metal, and the host could not give it the Switch's meaning anyway. A write over 64 pages is kept as an interval (up to 64 a submission, overlapping ones merged; the next submissions see them throughgw_commit), not by page. A write of no known size still stops the tracking. - Found on: The Legend of Zelda: Breath of the Wild (GitHub issues #534 and #598, shrines, MacBook Air M2 and M3). The Shrine of Resurrection save shows the load burst: the 300 frames around the world load had 1,200 refusals and 107 load-all store-all passes, now 0 and 47;
DM_NVN_UBP_CHECK=1found 146,000 shadows equal to the GPU's memory, 0 different. The reporter's log shows the same burst at each load, and 240 refusals a frame in its slow stretches. - Check:
make -C dm/gfx/tests GAME=<id> check_t_sbw(16 checks: the size-0 outputs of that dispatch do not hit the uniform block's pool, a write of no known size still stops the tracking, the interval list's limit, and the next submission's view throughgw_live).
Inline updates of a running submission refused uniform shadows
- Symptom: the
residency setline showspasses ended to land them for a readin the tens of thousands, every onerefused … earlier submission running. The slower the GPU, the more passes, and each pass makes it slower: a scene stays at a very low frame rate once it falls in. - Cause: a partly covered uniform shadow (Partial-cover uniform shadows keep passes open) takes the rest from memory, which refused it while a running submission could still write those pages. Two kinds of write counted. The inline updates of the frame before: a game that updates a block every frame refused it for as long as that frame ran, though the CPU knows those bytes. And any write of 16 MB or more, which counted as a write anywhere.
- Fix: inline updates of running submissions are remembered by byte, each with its fence, and laid over memory in the shadow (
um_put,um_overlay;DM_NVN_UBP_RUNNING=0refuses as before); a slot a running page holds leaves the other page refused as before. A byte counts only while its fence runs, so what the game writes later is not overwritten. Writes of 16 MB or more are kept whole, by range (gww_put, 32 of them; beyond that a write anywhere). - Found on: Splatoon Raiders: its ink query block is updated at 0x00..0x14 and 0x18..0x70 while the shader reads 0x00..0x70, so one unused word leaves it partly covered, before each of about 150 queries a frame;
7866f36373e7writes a 56 MB buffer each frame. 90,000 refusals every 300 frames became none.DM_NVN_UBP_CHECK=1on the first level: 592,000 shadows equal to the GPU's memory, 0 different. - Check:
make -C dm/gfx/tests GAME=<id> check_t_ubp_runningandcheck_t_sbw(fails withDM_NVN_UBP_RUNNING=0).
Counter reports of a running submission refused uniform shadows by page
- Symptom: a scene that holds 60 fps with the GPU at about 5 ms a frame drops for seconds at a time to 35–40 fps, with the GPU at 20–26 ms, after a slow frame such as a load. The
residency setline shows tens of thousands of refusals per 300 frames, every onea report still to land(before this fix they were counted asearlier submission running). - Cause: the host writes a counter report (a timestamp, or a samples-passed result) on the CPU when its submission completes (
post_run): 16 bytes, which the GPU never writes. The report counted as a GPU write of its whole 4 KB page (sbw_note→gw_commit→g_gw/g_gwx), so every partly covered uniform shadow (Partial-cover uniform shadows keep passes open) over that page was refused while the submission ran, and each refusal ended a pass. A game whose reports share a page with its uniform blocks loses nothing while the GPU keeps up. Once one frame falls behind, the extra passes keep the next ones behind too. Samples-passed results did not count at all, so a shadow over one could read it before it landed. - Fix: each report is kept by its own 16 bytes, with its submission's fence, in a ring of 4,096 (
hw_note,hw_live). Its page goes into a table of its own (g_gwr), only so that every other page skips the ring. A shadow is refused only when it overlaps a report still to land; the vertex-stream and conditional-render readers (gw_live) check the same. A submission's reports that do not fit in the ring's finished slots go into the page tables as before.DM_NVN_REPORT_EXACT=0refuses by page as before (still counted asa report still to land). - Found on: Ori and the Will of the Wisps, GitHub issue #1660 (Unity writes two timestamp reports a frame into the page of its uniform blocks). The issue's reporter found the cause and an exact-range fix on an M3 Max, where one start in three stayed at 15–18 fps. On main (Apple M6, windowed, the new-game route into Swallow's Nest, 2026-11-11), the by-page refusal gave 625,330 refusals in 15,000 frames, all over reports, none over other GPU writes; up to 133,767 per 300 frames, with the frame time at 25–28 ms and the GPU at 25–26 ms for about 15 s. The same route with the fix: no refusals, frame time p50 16.67 ms in every 300 frames, GPU p50 at most 6.0 ms.
- Check:
make -C dm/gfx/tests GAME=<id> check_t_ubp_running(two of its checks fail withDM_NVN_REPORT_EXACT=0: a shadow beside a running report on its page is made, one over its bytes is refused, as one over a samples-passed result is, and reports past the ring refuse their page).
A submission past 8,192 queued writes counted as writing everywhere
- Symptom: one scene of a game drops to 1-2 fps and stays there, with the GPU busy 400-600 ms a frame and about ten times the render passes of the scenes before it, many of one draw each on the same target. The
residency setline showspasses ended to land them for a readin the tens of thousands, nearly allrefused … earlier submission running, with someunreadable. A pass dump (DM_NVN_PASSDUMP) namesdraw_→ubd_conflictas the end of those passes (E <pass> pass ends in <function>:<line>). - Cause: the host lists every buffer write a submission queues (copies, fills, inline uniform updates:
pend_add), so that a partly covered uniform shadow (Partial-cover uniform shadows keep passes open) knows what memory does not hold yet. The list held 8,192 writes. Past that the submission counted as a write anywhere (g_pend_over),gw_commitcarried that to later submissions while it ran (g_gw_all), and every partly covered shadow was refused, each refusal ending the pass. The extra passes made the GPU slower, so the overflowing submissions were still running at the next frame's draws and the refusals went on: the drop did not recover until the scene ended. - Fix: the list has no fixed size: its entries and page nodes grow as a submission needs them (
pend_room) and keep that size for the next submissions, so a steady frame allocates nothing, and the update index (g_pend_upd) is 32-bit. The hash has 8,192 buckets instead of 2,048. A write still counts as one anywhere only when the list cannot grow (no memory) or the write runs past the end of the address space. Writes over more than 8 pages had a list of their own, which stopped at 256; they are now indexed in the same hash at a coarser granule (see Handles in uniform buffers written earlier in the same submission). The fixed limit had been raised once before (256 → 8,192, Monster Hunter Rise); raising it again would only have moved the cliff. - Found on: Splatoon Raiders, the third stage of the first boss fight (16 GB MacBook Air M2, docked, 2026-11-05). The stage measures its ink map with about 1,550 occlusion queries a frame, each after 7 inline updates of the query block: 11,010 writes in one submission, against about 2,800 in the game's other fights. Before the fix, frames took 400-1,100 ms, with up to 1,025 render passes, 1,008 of them one-draw passes on the 6400x6400 map, and 173,452 refusals (161,812
earlier submission running, 11,640unreadable). After it, the stage ran at a median of 17.7-19.9 ms a frame, with at most 118 render passes and no refusals. The Mac's swap and the game's footprint (13-14 GB) did not change across the drop: it looked like memory pressure but was not. - Check:
make -C dm/gfx/tests GAME=<id> check_t_ubp_runningqueues the stage's 10,850 updates in one submission (3 of its checks fail with the old limit), then 43,400 (past 32,768, the next fixed limit the first version of the fix had).
An unbound uniform slot reads the zero bank
- Symptom:
stage 0 cb5 has no uniform buffer bound(or another stage and slot, such asstage 0 cb0), once per run. - Cause: the argument buffer kept a null pointer for the unbound slot. The game draws with nothing bound there; the host misses no bind. What the Switch reads from an unbound slot is not known.
- Fix: the slot now reads the all-zero bank, as an unbound texture slot reads the zero texture.
- Diagnostic scope: this warning follows reflected buffer declarations, not executed shader loads. A buffer used only behind an untaken branch can be left unbound deliberately. Check the branch's selector as the draw reads it before diagnosing a missing bind; a targeted
DM_NVN_KEYDUMPand an instrumented offline shader can establish that the slot is unused. - Found on: Paper Mario: The Thousand-Year Door (at the title); Batman: Arkham Knight (
stage 0 cb0, at boot: the first command buffer draws before the game has bound any uniform buffer); Nintendo Switch 2 Welcome Tour (an unused bone-palette slot, verified on the GPU). - Check: a pass dump of the frame (
DM_NVN_PASSDUMP=<frame>, frame 0 for the boot) shows the draw (jline) and its stage'sKline with noB … cbline, and the frame's[nvn]call counts show whether the game calledCommandBufferBindUniformBufferat all.
A uniform slot the game binds empty
- Symptom:
[RED] stage 5 cb1 has no uniform buffer bound: shader … address 0 size 0 (frame 0), once per run; nowstage 5 cb1 is bound empty by the game (address 0, size 0): shader … reads it as 0, once, not red. - Cause: none in the host. The game binds the slot itself with address 0 and size 0: Resident Evil 4 binds compute slot 0 and then slot 1 empty before every dispatch of
4e06df4bbdf9b7c9(a log of each bind's payload at replay, frames 0 to 2), whose cb1 reads it does not use. Every read of a size-0 binding is past its size, which reads 0 on Maxwell as for a binding shorter than the shader's reads (ub_padded), so the zero bank the host binds is what the console reads. - Fix: the replay state keeps which uniform slots a bind has set (
S.ubo_set), andcbuf_slotnotes an empty binding the game made once, without[RED]. A slot never bound (An unbound uniform slot reads the zero bank) and an address in no pool stay red. - Found on: Resident Evil 4 (
stage 5 cb1, frame 0).
Compute dispatches share the copy encoder
- Symptom: GPU time per frame doubles with many small dispatches (Age of Calamity: GPU 9 → 18 ms a frame on the Mac; the iPhone's 15 → 51 ms, 17 fps).
- Cause: each dispatch had a compute encoder of its own with full queue barriers on both sides, a GPU drain per dispatch: about 10 µs of GPU each on the Mac.
- Fix: dispatches now go into the open copy encoder, each after a barrier inside it (as texture copies are,
blit), with the compute argument table set once per encoder (dispatch_enc): about 1.3 µs each. - Found on: Hyrule Warriors: Age of Calamity: after its first cutscene the first battle runs about 900–1,500 small dispatches a frame on the Mac (an iPhone log's call counts suggest more), each after a game barrier, at the same draws and passes; GPU 7.3 → 8.1 ms across the cutscene with the change.
- Note:
DM_NVN_PASSGPU, which times each dispatch, gives each its own encoder again (DM_NVN_DISPATCH_OWN=1did too until it was removed). A barrier before every dispatch is now only where NVN asks for one: Compute dispatches that wait for each other.
Compute histogram clear races its atomic fill
- Symptom: sunlit surfaces stay clipped to white while shaded areas look right; gamma changes do not help. The exposure's average and adapted luminance targets contain NaN, which persists across frames.
- Cause: The game records no NVN barrier between the 256-bin histogram clear and its atomic fill. Both use the same 1,024-byte storage buffer. Metal can run them concurrently, so a late clear can erase counts the fill has added. A short histogram can take the reducer's percentile search past bin 255. Static inspection of the SDK used by 4.04b (NintendoSDK 15.3.0,
d5a1029a57d8cd4fdf4eacad87b0cfd09) found no unconditional wait between ordinary compute dispatches. The launch routine waits for idle when reusing its compute arena. The SDK 10.4 in the local 3.7 shows the same pattern. - Fix checked on 3.7: An opt-in NSO rewrite inserts the missing
nvnCommandBufferBarrier(0x21)just before the game's histogram fill, using the same command-buffer lookup and barrier flags as the game's call before reduction. The host replays both. The patch is bound to the verified 3.7 main build. The corresponding site in 4.04 needs its own verification. - Workaround for 4.04d:
DM_NVN_DISPATCH_BARRIER=fullrestored finite luminance (about 1.4–1.6) and exposure at 60 fps on the reporter's M2 Pro (macOS 27.2.1). Inferring dependencies from bound storage ranges can serialize independent work that shares a buffer, as seen in Kirby Air Riders. - Found on: The Witcher 3, issue #3048. The registered 4.04b contains the same five exposure shaders as the reported 4.04d.
Compute bindings prepare texture copies before the dispatch encoder
- Symptom: with each dispatch in an encoder of its own (
DM_NVN_PASSGPU;DM_NVN_DISPATCH_OWN=1before it was removed) the host crashes in the Metal driver (CRASH sig=11 addr=0x98inAGX::ComputeContext<…>::prepareForEnqueue(bool)) at a compute shader's first read through a texture view of another format; by default (dispatches sharing the copy encoder) that read can see the texture's old pixels. Metal validation reportsCommand buffer already has an open command encoderfor the first. - Cause: resolving a sampled texture binding can upgrade the texture to allow format views and copy the old pixels into the new one (
tex_upgrade, throughblit()).dispatchopened its encoder beforeencode_argsresolved the bindings. With an encoder of its own, the copy opened a second encoder on the same command buffer. With the shared encoder, the copy came after the dispatch's barrier (dispatch_enc), so nothing ordered it before the shader's read. - Fix:
dispatchfills the compute argument table before it opens an encoder of its own or places the shared encoder's barrier, asimage_preparealready does for image writes. Compute bindings only write the argument table, so they need no open encoder; any copy a binding issues then lands before the barrier.dm/gfx/tests/t_dispatch_own.mchecks the pixels and the driver group counts for direct and indirect dispatches, first and cached views, both encoder modes and both encoding threads. - Found on: The Legend of Zelda: Ocarina of Time with
DM_NVN_DISPATCH_OWN=1(since removed) (issue #1743), during the Kokiri Forest load: on an M2 Pro 5 of 5 runs crashed before the fix and 3 of 3 loaded the forest after it. The stale read on the default path is reproduced by the test (M2 Max, M6).
Fragment-ordering barriers between draws that write images
- Symptom: dialog boxes with holes the size of their text, and white specks where text faded.
- Cause: each UI element is drawn into its own layers and then composited into the window image by one draw per layer, all in one attachment-less pass, each a read-modify-write of the image, with
nvnCommandBufferBarrier(ORDER_FRAGMENTS | INVALIDATE_TEXTURE)(bits 0x12) between them. The host took a barrier only as an order for the next pass, and Metal orders nothing between draws of one render pass for shader writes: the text element's composite read the window before the parchment had landed and wrote the old pixels back. - Fix: a barrier with
ORDER_FRAGMENTSorORDER_FRAGMENTS_TILEDnow ends the open pass when a draw in it wrote an image or a storage buffer (swrite_noteinnvn_mtl.m), so the next draw opens a pass behind the full consumer barrier; reflection marks an image binding written when its type has write access (nvn_refl.m, which leftrwunset for images). - Found on: FINAL FANTASY TACTICS - The Ivalice Chronicles.
Draw passes without fragment order read unfinished attachments, and the damage persists
- Symptom: a bright or purple patch grows on a still scene. Presented luma rose from 29 through 66 and 105 to 119, versus 41 in a clean run. The corruption remained visible in both phases of an in-run A/B (
DM_AB). - Cause: the diagnostic switch
DM_NVN_BAR_FRAGremoved the Fragment stage from the end-of-pass barrier and disabled theAll → Fragmentbarrier for aliased resources (resource_vis()includesResourceAlias). Fragments could read an earlier pass's attachment before it was ready. Each luma increase began with the switch on, and later frames carried forward the damaged state. - Fix: keep fragment ordering at both pass boundaries. The end barrier's Fragment stage cost 5–10 µs per pass in the reported M2 comparison. Check the picture in a separate run per arm so corruption from one run cannot affect the other (A/B in one run).
- Found on: The Legend of Zelda: Ocarina of Time, in Castle Town and Zora's Domain on a diagnostic build. The same build with the switch off rendered correctly.
A segment committed after a buffer → texture copy
- Symptom: a texture copied from a staging buffer shows another texture's blocks (Catherine: Full Body's cutscene subtitle band a hard-edged dark box with a magenta stroke through it).
- Cause: the GPU copy read the next texture's blocks: the source was right when recorded and when encoded, but the game's resource thread wrote the next texture into the same staging block before that first submission had been committed, because the host spent a long time building pipelines inside it. On the Switch the GPU runs a submission's copies as soon as the submit returns.
- Fix: a segment is committed at the first pass boundary after any buffer → texture copy (
g_cut_copy,sub_cutinnvn_mtl.m), so the copies run while the host encodes the rest; theresidency setline counts these cuts (N after buffer → texture copies). This cut always happens, whateverDM_NVN_CUTsays. - Found on: Catherine: Full Body: the band is a 32x512 BC3 gradient copied with
nvnCommandBufferCopyBufferToTexture(recorded at the start of a frame,main+0x305e64); the resource thread wrote the next texture into the staging block 64 ms later, and the host spent 300 ms building pipelines inside the submission; a few cuts per 300 frames in this game, only while it loads. - Check: found with
DM_NVN_HILITEon the band's pixel shader,DM_NVN_TEXRAWof the texture (decoded: opaque black and magenta blocks, not a fade) andDM_PROBE_WATCHon the staging address beside a log of the copy's submission completing.
Copies a blit cannot do, drawn
- Symptom: a scaled texture copy skipped with a red line (Metal blits cannot scale); format-changing, depth-stencil and mirrored copies.
- Fix: such copies (a format change, a scaled region or a mirrored one) are drawn (
copy_t2t_draw, Depth16Unorm as well since Kirby Air Riders' far shadow mips), one render pass per layer; a destination made without render-target use is upgraded first (Render-target use added on demand); depth and stencil are written from a fragment shader, stencil through[[stencil]]export from anX32_Stencil8view of the source. - Found on: The Legend of Zelda: Link's Awakening: RG11B10F → RGBA16F every frame, half-size depth-stencil copies, and a scaled
MIRROR_Ycopy of the frame to 1280×720 RGBA8. Super Mario 3D World + Bowser's Fury: one scaled copy when leaving the title (1920×1080 → 1280×720, RGB10A2, flagsENGINE_2D; probably the captured frame for the transition): 04 listed it as open (skipped with a red line);copy_t2t_drawnow draws scaled copies too (its comment innvn_mtl.mnames this one), so it is no longer skipped.
Downsample of a single-sample texture
- Symptom:
[RED] Downsample case not implemented: 320x176 1 samples format 70 → 80x48; a missing bloom. - Cause: the host took
nvnCommandBufferDownsampleonly as a multisample resolve and skipped the rest. - Fix: a single-sample source is drawn into the destination as a whole-level scaling copy with bilinear filtering, converting the format (
copy_t2t, throughcopy_t2t_draw; Copies a blit cannot do, drawn). - Found on: Bayonetta 2: its bloom from a 320x176 target into 80x48 and 48x32 textures, and its 1280x720 BGRA8 frame into an RGBA8 texture of the same size.
Tiled multisample resolves
- Symptom:
[RED] NVN unimplemented function called: nvnCommandBufferTiledDownsample; menus render but the stage is black or incomplete. - Cause: the tiled resolve entry points reached the unimplemented-call stub, leaving their destination textures unchanged. Ordinary
Downsamplealready recorded a resolve. - Fix:
TiledDownsampleandTiledDownsampleTextureViewuse the same recorded resolve as their ordinary counterparts. Texture descriptors and the selected views are copied when recorded; the resolve runs in submission order. Tegra tiled-cache scheduling hints remain host no-ops. This adds no new format, size-conversion or sample-count support to the existing resolve path. - Found on: Ikaruga 1.0.2, reported by hada0127 in issue #592, with a source-only patch. The report's independent SDK audio-layout failure is separate. No repository game profile or current gameplay validation is provided by this change.
Multisample Downsample between different sizes
- Symptom:
[RED] Downsample case not implemented: 1920x1080 4 samples format 92 → 1280x720 1 samples format 92; handheld mode renders black while docked mode works. - Cause: Metal requires a render pass's
resolveTextureto match the multisample source attachment's dimensions, socopy_t2t_enc(DM_COPY_RESOLVE) rejected multisample resolves when the source and destination level sizes differed. A game that allocates its MSAA render target at docked size (1920x1080) and renders handheld frames into the1280x720corner hits this path onnvnCommandBufferDownsample. - Fix: when
s.sampleCount > 1,d.sampleCount == 1,s.pixelFormat == d.pixelFormat, and the source and destination level sizes differ,copy_t2t_encresolves into a cached private staging texture matching(sw, sh, pf)(up to 4 slots, deferred release on eviction) and blits the common(0, 0, min(sw, dw), min(sh, dh))corner unscaled into the destination. - Found on: Digimon Story Time Stranger (issue #872): handheld mode (
DM_OPMODE=0) resolves1920x10804xRG11B10Floatinto1280x7201x every frame. - Check:
make -C dm/gfx/tests GAME=010015100B514000 check_t_tiled_resolve(97 checks underMTL_DEBUG_LAYER=1for bothDM_NVN_ENC_THREAD=0and1, including16x124x →8x61x and8x64x →16x121x unscaled corner checks).
Depth-stencil copies carry the stencil
- Symptom: no ambient occlusion (Mac); on a device the result depends on whatever that memory holds.
- Cause: the depth downsample copy left the stencil as the destination's previous content (at the time, new depth-stencil textures were not zero-filled either).
- Fix: the copy now carries the stencil.
- Found on: The Legend of Zelda: Link's Awakening: the occlusion pass (
aa05724ffa62cb82, a 480×270 R8 target cleared to 1.0) only writes where stencil bit 1 of the quarter-size depth-stencil copy is clear, so on the Mac the mask kept 1.0 everywhere.
Periodic GPU profiles close at frame boundaries
- Symptom:
DM_NVN_GPUPROF=every:1prints no per-frame reports and fills its timestamp heap across frames. - Cause: reporting waited for a submission in an unselected frame. Every frame is selected at interval 1, so that condition never holds.
- Fix: before the next frame's first encoder,
gp_periodic_finishsnapshots the sampled frame's labels and registers a shared-event notification at its last committed fence. The report resolves the heap after all of that frame's segments complete, without a GPU wait or an extra command buffer. The heap cannot be reused while the report is pending. - Found on: review of the measurement tools for The Legend of Zelda: Breath of the Wild; reproduced with synthetic counters and completion events, without game execution.
t_gpuprofchecks consecutive and sparse frame selection, completion ordering and heap ownership; it runs in CPU CI.
GPU profiles stamp only the encoder they began
- Symptom: with
DM_NVN_GPUPROF, the host aborts minutes in on-[AGXG16XFamilyComputeContext_mtlnext writeTimestampWithGranularity:afterStage:intoHeap:atIndex:]: unrecognized selector,up_flushon the stack; or a profiled render pass with a wrong GPU time. - Cause: every encoder end goes through
m4_end, which calledgp_endfor any encoder, including the upload, diagnostics and present encoders, which are not profiled.gp_endclosed whichever main-command-buffer encodergp_beginhad last opened and sent its end stamp to the encoder it was given. An upload flush inside a profiled draw pass sent the render encoder's timestamp selector to the upload compute encoder (the abort); where the kinds matched, the pass lost its own end stamp. - Fix:
gp_beginrecords the encoder it stamped, andgp_endignores any other encoder, so the open pass keeps its label until its own end. - Found on: The Legend of Zelda: Tears of the Kingdom with
DM_NVN_GPUPROF=every:300on the Mac (issue #531; one run in four, about frame 23,000).t_gpuprofends an upload encoder inside a profiled pass; it runs in CPU CI. Not rerun in the game.
An argument block reused after another shader of its stage encoded
- Symptom: none seen in a game. A draw could bind a texture, sampler, storage or uniform buffer from before a binding change: the draw's shader had written its block earlier in the pass, another shader wrote a block on the same stage after the change, and the first shader drew again. PR #2249 found the mechanism by reading (#1898's
56e7ee16). - Cause: a stage's binding changes were flags (
g_args_dirty,g_args_ubo) that whichever shader wrote the stage's next block cleared, so they told the next shader on that stage nothing about its own block. Every path that puts another shader on a stage marks the stages first, and a program switch marks them all, so the one route found is a combined program (bind_stages, stages bound from different programs): when the bound combination was the next of theNCMPring slots to be replaced, a new combination took that slot and came back as the same pointer, andOP_BIND_PROGRAM(np != S.prog) saw no change. It needs more than 64 combinations in use; AI: THE SOMNIUM FILES made more than that in the precompile prediction. - Fix: in
nvn_mtl.m, for every NVN game. A block is valid by generation: each binding change takes the next number of one sequence for every stage (g_args_genfor any binding,g_args_ugenfor what the uniform slots point at only), each block keeps the numbers it was written at (ab_gen,ab_ugen), and it is reused only while both hold, patched when only the uniform one moved. Shaders that take turns on a stage with no binding change keep their blocks.bind_stagesnever gives a new combination the slotS.prognames. - Found on: reading; no game failure reported.
t_args_genruns the sequence (a binding change, another shader's encode, the first shader again), shaders taking turns, a uniform-only change, and the ring slot; without thebind_stageschange its slot checks fail.
An argument block points into another arena after a nested allocation
- Symptom: an argument block or a padded uniform binding reads bytes from another arena after a nested allocation rolls over to a new block. Two synthetic GPU tests return incorrect results without their respective fixes. In a game, incorrect argument addresses can also cause GPU address faults.
- Cause:
encode_args_'s uniform-only patch path (introduced inadaff7356) allocates its argument block, then callscbuf_slot/cbsize_table, which can allocate again.ub_paddedlikewise allocates its padded copy beforeubp_getcan allocate a partial-update shadow. Both then readg_cur_arena->gpu + off: after a rollover, the base names the new arena but the offset belongs to the outer allocation's old arena. The old buffer and CPU pointer remain valid; its GPU address alone is wrong. - Fix: in
nvn_mtl.m, for every NVN game. An allocation returns its own addresses:arena_takegives the slot's offset with its CPU and GPU addresses as of the allocation (arena_at), and every caller that wrote or bound its slot throughg_cur_arena(the argument blocks, the uniform size table, padded uniform copies, the offset and length tables, push constants, driver banks, the border block, fan / quad and 8-bit index expansions) now uses them, so no code outside the allocator readsg_cur_arena.arena_allocremains for callers that address the slot through the buffer it returns. The uniform-only optimization remains enabled. No shader-chain or profile change is needed. - Found on: reading PR #2847, independently reproduced with
make -C dm/gfx/tests GAME=01007EF00011E000 check_t_args_gen(Apple M6, macOS 27.2, Metal validation): 42 checks pass with both fixes; reverting only the argument-block fix fails 2 checks, and reverting only the padded-uniform fix fails 1. Game confirmation open: investigated after Breath of the Wild's Zora's Domain faults (issue #2671); the supplied-save Mac retest passed on both baseline and fixed hosts, so it does not establish that these bugs caused the game crash. The connections to issue #2592 and issue #2700 are also unconfirmed.
Conditional rendering and queries
Conditional rendering evaluated at replay
- Symptom: the 3D scene black (targets cleared again before they are read);
[RED] SetRenderEnableConditional: the host draws anyway; with a game that skips clears under render conditions, scenes black behind the HUD (Mario vs. Donkey Kong's levels, 1.0.1). - Cause: by default the host draws everything a
SetRenderEnableConditionalwould skip. A game that wraps clears inSetRenderEnableConditional(RENDER_IF_NOT_EQUAL, rec)…SetRenderEnable(true): the condition compares the 64-bit counters atrecandrec + 16. A timestamp report puts 0 in the counter field (the time goes in the second field). The host ignored the condition and wrote the time into both fields, so every clear ran. - Fix:
OP_RENDER_CONDis evaluated at replay for every game, from the records in memory; a timestamp report's counter field is 0, as on the GPU. It used to take the profile keyrender_cond, which twelve games had (the black scenes above), while every other game drew its blocks unconditionally; the key is gone, and a profile that still has it is told so when its header is made (dm/games/game.py). A timestamp report replayed earlier in the same submission counts as 0. A condition on a samples-passed result (an occlusion query, written when its submission completes) keeps drawing while that report is in flight, and once it has landed is evaluated from it, as the GPU would at that point in the queue (Occlusion conditions read once landed). A pass dump shows the switches asElines (conditional render … → not drawn) and a skipped clear asc … skipped by conditional rendering. - Found on:
- The Legend of Zelda: Tears of the Kingdom: TOTK wraps nearly every
ClearColor/ClearDepthStencilthis way; each clear is followed byReportCounter(TIMESTAMP_TOP, rec), the CPU setsrecto 1 when a target needs a clear, andrec + 16is never written, so after one clear the two are equal and later conditional clears of that target are skipped. The first tile-lighting round, the half-resolution scene depth the light volumes test against (back facesGREATERagainst a buffer just cleared to 1.0 can never pass) and the light accumulation were all cleared before the composite read them. - Mario vs. Donkey Kong (it skips clears under render conditions, as Tears of the Kingdom and Animal Crossing: New Horizons do).
- Nintendo Switch Sports Resort (Switch 2): drawn unconditionally, its Select User background is grey and the outfits black (in the menus only). The outfits' material reads R and A of a screen-space target the menu blurs under a channel mask of G and B, and those read 0. The background and the lit outfits come back with the conditions evaluated.
- Super Mario Odyssey, with occlusion queries in three rotating slots: evaluated, its smoke route's screenshots are the same as drawn unconditionally (RGB 0.74 and 0.52) at 58.9 / 59.4 fps (
regress.py check, M6, 2026-11-12). - Drawn unconditionally, nothing looked wrong in Big Brain Academy: Brain vs. Brain, DARK SOULS: REMASTERED or Paper Mario: The Thousand-Year Door; evaluated is not checked on them.
- Portal 2: its operands are written by a shader (A condition on a word the GPU writes).
- The Legend of Zelda: Tears of the Kingdom: TOTK wraps nearly every
A condition on a word the GPU writes
- Symptom: objects missing that the game draws under
SetRenderEnableConditional, while a pass dump shows their conditions readingvalues 0 / 0 → not drawnon records no counter report writes. - Cause: an operand that no report of its own writes was read from memory when the condition was encoded. A shader, copy or buffer clear queued before the condition, in the same submission or one still running, had not written it yet: on the GPU it has. Portal 2's D3D9 layer (NVIDIA's occlusion culling,
IDirect3DDevice9::SetOcclusionShape,materialsystem.nro+0xc1130) draws each mesh's bounding shape with a shader that writes a visibility word into a storage buffer bound read-write (a 32 KB buffer of pairs,0xffffwhen visible), and draws the mesh underSetRenderEnableConditional(RENDER_IF_NOT_EQUAL, pair). Read from memory before that shader ran, both words were 0, and the vault's desk, microwave, fridge, lamp, TV, plant and blinds were dropped. - Fix: such an operand is known only when nothing queued before the condition writes its bytes (
rc_valuethroughrc_source, the check the uniform shadows make: an inline update of the submission is known by its bytes; a copy, fill or shader write of the submission, or a GPU write of a submission still running, makes it unknown, and the block draws). Drawing a block the GPU might have skipped costs only GPU time for a culling condition, so unknown keeps drawing. - Found on: Portal 2: its seven conditions in a vault frame read
unknown, drawn, and the furniture is there with the conditions evaluated (2026-11-12, M6). - Check:
make -C dm/gfx/tests GAME=<id> check_t_render_enable_queue(an operand a queued copy or buffer clear writes draws, one nothing writes is decided by memory; the copy and clear cases fail with the operand read from memory).
Occlusion conditions read once landed
- Symptom: GPU time spent on objects the game's occlusion queries culled: a pass dump shows
conditional render … (unknown, drawn)on query records whose submission completed long before. - Cause: every address a samples-passed report ever wrote counted as unknown at replay, landed or not (
rc_occ_has, later the report'sconservativemark), so every draw under an occlusion condition was made. The report table already knows when a report has landed: its submission's fence againstg_rc_complete, with later buffer writes and GPU writes tracked. - Fix: only counter kinds the host does not implement stay conservative (
rc_note); a landed samples-passed result is read like a landed timestamp one (rc_value), and a report still in flight keeps the block drawing. - Found on: The Legend of Zelda: Ocarina of Time: it reports its queries a submission ahead of the conditional draws, so all of them had landed at replay (1.48 million conditions on the Kokiri Forest route, 0 in flight, 42% false). GPU p50 17.06 → 16.44 ms and p95 18.74 → 18.01 ms a frame on a 20-core M4 Pro (two runs each), picture unchanged. Skipping every unknown block instead (the visible ones too) whitened the scene for good: only the evaluated condition is a valid skip.
Report tables that dropped entries
- Symptom: a 3D scene black or missing behind the HUD, only in scenes with many occlusion queries; a pass dump shows conditions reading
values 1 / 0on a record a report of the same submission has just written, and clear-only passes on targets just drawn to. Scenes with fewer queries are fine. - Cause: the reports of a submission were kept in a table of 256, queries and timestamps alike. Once full, a timestamp report was forgotten, its condition read the 1 the CPU wrote, and the clear ran (Conditional rendering evaluated at replay).
- Fix: only timestamp reports are kept per submission, and the query addresses, which are kept apart, are enough for those; both tables grow (
rc_note,rc_occ_add). - Found on: Splatoon Raiders: 285 ink queries a frame in its dialogue scene came before the conditional clears, and the lit scene was wiped: a black screen with only the text on it. The opening cutscene has no such queries, and the pier about 160.
- Check:
make -C dm/gfx/tests GAME=<id> check_t_sbw.
Running-write hash collisions and page-set overflow taint conditional renders
- Symptom: random or sustained black 3D frames while the 2D HUD keeps drawing in busy or wide-view scenes, with no
[RED]lines;DM_NVN_ENC_THREAD=1turns flickering into multi-second black screens, and restarting the game can change whether a session hits it. - Cause: two limits in
nvn_mtl.m's GPU write-hazard tables gave falsegw_live/g_sbw_overhits inrc_source()(A condition on a word the GPU writes), makingOP_RENDER_CONDtreatagl's CPU-written conditional-render reference word (rec + 16) as unknown so itsClearColorwiped the 3D composite target before the upscaler read it: (1) the direct-mapped running-write tables (g_gw,g_gwx,g_gwr) collapsed a slot's page tag to~0ullon any 2-page hash collision, and any later write to a single hot page in that slot whilefence > donekept~0ulllatched permanently until a full GPU drain (continuous with the encode thread); (2) the per-submission page set (g_sbwp) was fixed at 16,384 slots (and 64 wide intervals), overflowing on high-draw scenes with thousands of writable storage buffers and settingg_sbw_over/g_gw_all(which also refusedubp_getpartial uniform shadows). - Fix: replace the direct-mapped running-write tables with 128-byte-aligned 7-way set-associative tables with an independent per-set
over_fencethat later non-overflowing writes never extend, mergeg_gwintog_gwxplus ag_umpage check (um_page_live), sizeg_gwras a compact 1,024-set filter for the 4,096-entry report ring, growg_sbwp/g_sbw_listdynamically at ≤50% load from 16,384 slots (sbw_grow), and widenSBW_WNto 256. - Found on: Donkey Kong Bananza (issue #2699, PR #3185): Freezer / Hilltop / Canyon layers, wide camera angles, and the 3D overview map (~7,500 terrain chunks binding ~15 KB writable SSBOs per submission).
- Check:
make -C dm/gfx/tests GAME=<id> check_t_sbw(7-way collision without tainting an unrelated page, non-latchingover_fenceexpiration,g_umlive-page tracking outsideg_gwx, and 24,000-page dynamic growth withoutg_sbw_overorg_gw_all).
Query slots running out inside a pass
- Symptom:
[RED] visibility slots exhausted. - Cause: the visibility buffer holds 8,192 slots and is bound for a whole pass. A new one came only when a pass began, so a single pass with more queries than were left counted nothing for the rest.
- Fix: the draw that needs a slot when none is left ends the pass, and the next begins with a new buffer.
- Found on: Splatoon Raiders: at the first level's load, one submission with about 9,000 draws.
Occlusion counting for draws no report can see
- Symptom: GPU time on draws that sit between a samples-passed report and the next reset, in games that wrap single draws in queries of their own; a same-process
DM_NVN_VIS_NEED=abrun shows it. - Cause: once counting began (the first reset or report), every draw was encoded in Metal's counting mode with a visibility slot. A reset drops the slots since the last report unread (Samples-passed reports with no reset before them), so the draws between a report and the next reset counted for nothing; NVN's counter costs nothing there, Metal's counting mode does.
- Fix: at each samples-passed reset or report,
vis_need_scan(nvn_mtl.m) looks ahead in replay order (op_next, stepping over indirect multi-draws, which hold no counter op) for the next samples-passed op of the submission. A reset: the draws until then are encoded with counting off and take no slot (draw_; the native task / mesh draws, geometry rasters and wide lines pass there too, and a mesh run is drawn before any counter op). A report, or none found (the submission's end, whose last slots its completion adds; 20,000 ops; a call stack deeper than the cursor's 8): they count as before. Every report reads the same value.DM_NVN_VIS_NEED=0counts every draw again;abalternates it withDM_AB. - Check:
make -C dm/gfx/tests GAME=<id> check_t_vis_need: report → reset, report → report, reset → reset, a report at the submission's end, a multi-draw and called draws between, and the scan itself (a deep call stack keeps counting), with the values compared and the uncounted draws counted; the second run with the switch off leaves none uncounted. - Found on: The Legend of Zelda: Ocarina of Time: a reset, one draw and a report around each queried draw, about 1,800 a frame; Kokiri Forest on an M1 (8-core GPU) about −0.2 ms of GPU time a frame in both A/B polarities (PR #2574); on a base M2 within noise. On a 20-core M4 Pro (
kokiri-still,DM_AB=300, each on-phase against its neighbours) −0.05 ± 0.08 ms and +0.05 ± 0.17 ms in the two polarities: nothing measurable;kokiri-deckwith it on draws the scene whole (the log'sdraws between a samples-passed report and the next reset are not counted).
Samples-passed reports with no reset before them
- Symptom: characters a few metres away drawn as their hats and props only, their bodies missing from the main view while their shadows are there; near characters draw fully. A log line or a probe shows every samples-passed report reading 0.
- Cause: the host started counting samples passed only at
nvnCommandBufferResetCounter(SAMPLES_PASSED), and a report before any reset wrote 0. On the GPU the counter runs from the queue's creation, so a game that never resets it reads end − begin of two reports around each query, and gets the samples between them. Red Dead Redemption never resets it: every query read 0, every character counted as hidden. - Fix: in
nvn_mtl.m(Occlusion queries), for every game, one model of the counter: a running total thatpost_runkeeps in submission order underg_post_mu. A report hands the visibility slots since the previous report to its submission's completion, which adds them to the total and writes it; the slots left at a submission's end are added at its completion (so each slot is read once, while its buffer still belongs to that submission); a reset drops the slots before it and zeroes the total at that point in the queue. Counting starts at the first reset or, with none before it, at the first report (the pass is split there if its encoder had no visibility buffer); the log saysocclusion queries: samples passed reported with no ResetCounter before itonce. Games that reset read the same values as before; each report used to sum every slot since the reset, reading slots of earlier submissions whose visibility buffer the ring could already have handed to a later one: int_render_enable_queue, a reset and a draw in one submission and a half-sized draw and the report in the next read 64 samples instead of 96, the second draw's count twice. The test also checks end − begin across submissions with no reset. - Check: on the change's first version (a separate mode for games that never reset; the same values for them), Red Dead Redemption 1.0.4 (Apple M4, macOS 27.0.1), a recorded replay out of the saloon in Armadillo: the distant characters have their bodies at frames 2,280–2,340, frame time unchanged at 33.3 ms, no
[RED]; played by hand, the same. - Found on: Red Dead Redemption (
01007820196A6000):rage::CharacterVisQueries::TestVisiblitytakes each character's result fromGetOcclusionQueryData, end − begin of two reports around its box (about 35 queries and 324 reports a frame, no reset), and puts a character at or below its threshold in the occluded list, whichrenDrawBucketContainer::AddToDrawListuses to drop its low-detail body.
Vulkan layer
The Vulkan layer (dm/gfx/vk/hle_vk.m) was written for Hades. Super Mario Galaxy exposed gaps in graphics replay, and Re:ZERO exercised compute dispatch and larger descriptor sets.
Vulkan functions looked up by name
- Symptom: the packer selects NVN and finds no shaders. After selecting Vulkan,
ro::LookupSymbolcannot findvkGetInstanceProcAddr, or renderer initialization stops at a missing Vulkan entry point. - Cause: RenderDragon looks up the loader through
nn::ro::LookupSymboland checks the core device functions it loads. In 1.26.62 it also directly calls the extended image-format and surface queries,vkGetDeviceQueue2andvkCmdPipelineBarrier2. - Fix: the packer recognizes the lookup import and the loader, instance and device names. The host searches guest definitions first and falls back to Vulkan definitions it registers. The extended queries share the core query data. Synchronization2 dependencies end the active Metal encoder so later encoders see writes to tracked resources. Blits and resolves honor transfer usage and the requested subresources. A partial non-integer resolve uses a temporary Metal resolve target and copies only the requested rectangle. Full attachment clears use load actions.
- Found on: Minecraft for Nintendo Switch 1.26.62.
RenderDragon's unsigned bone indices
- Symptom: Metal rejects a pipeline with
Vertex attribute a_indices(1) of type int cannot be read using MTLAttributeFormatUShort. The title can continue drawing while an actor's pipeline is missing. - Cause: RenderDragon's skinning shaders declare a scalar
intinput which the game supplies asR16_UINT. The Switch driver accepts that pairing. Reading the bytes asShortwould sign-extend values with bit 15 set. - Fix:
vk_shaders.pyrepairs the material's scalara_indicesinput to unsigned in SPIR-V before translation. Each unsigned load feeds anOpBitcastunder the original signed result ID, preserving the shader's signed arithmetic. The key still hashes the original game bytes. This follows the traced engine layout contract, rather than changing Vulkan vertex-format semantics. One ordinary Metal function is built per vertex shader.t_vk_renderdragonreads back 32-bit values for inputs0x8000and0xffffunder Metal validation. - Found on: Minecraft for Nintendo Switch 1.26.62.
Vulkan triangle fans
- Symptom:
[RED] primitive topology 5 not implemented; a fan draws disconnected triangles or omits its later wedges. - Cause: Metal has no triangle-fan primitive. Selecting its triangle-list topology without expanding the vertices changes primitive assembly.
- Fix: each fan triangle
iis drawn as(i+1, i+2, 0), Vulkan's order, so its first (provoking) vertex is the rim's and flat attributes match.vkCmdDrawindexes one shared, growing list withfirstVertexas the base vertex, which keepsVertexIndexandBaseVertex.vkCmdDrawIndexedfans are converted on the GPU (dm/gfx/msl/vk_fan.metal), as copies earlier in the submission may write their indices: when a render encoder starts (a pass begins, or resumes after a copy inside it), one compute pass converts every indexed fan up to the next command that may end the encoder, into one buffer, and each draws from it by indirect arguments. A restart index ends a fan beforevertexOffsetis added; the conversion compacts the runs and writes the list's length. Index, binding andfirstIndexoffsets, vertex offsets and base instances are kept.t_vk_fancompares fans with explicit lists (pixels, primitive IDs, occlusion counts, GPU-copied indices, restart, base vertex) and checks that fans do not split a pass. - Indirect draws: the draw count, index range and base arguments can come from earlier GPU work. Replay completes that Metal prefix before reading the argument records, sizes the index scratch from their actual counts, then uses the same shared indices or GPU conversion.
t_vk_cmdswrites both kinds of indirect arguments with a GPU transfer and checks that each four-vertex fan covers all 16 pixels of the target. - Cost and limits: a direct draw without indices costs nothing beyond the draw. Direct indexed fans use one compute pass per stretch of a render pass with fans (one thread per triangle or a serial scan with restart). Indirect fans split the pass and wait for the encoded prefix once per indirect command. Games without fan pipelines skip the scan.
- Found on: KINGDOM HEARTS II FINAL MIX's Gummi missions, issue #1026. The collection's profile is not registered here; its other bring-up and loader issues remain separate.
Vulkan shaders generated at run time
- Symptom: no SPIR-V file in the RomFS; SPIRV-Cross refuses a module with "Struct member does not have ArrayStride set".
- Cause: Hagi emits SPIR-V for each GX configuration and creates every pipeline of its pipeline database at boot. Its SPIR-V puts
ArrayStrideon the struct member (OpMemberDecorate) instead of the array type, which NVIDIA's driver accepts and SPIRV-Cross refuses. - Fix:
DM_VK_CAPTURE=<dir>writes the modules;vk_shaders.pyreads capture folders like a RomFS;fix_stridescopies the stride onto the type before translating. - Found on: Super Mario Galaxy (3,089 modules, 4,535 pipelines).
Push constants in the next free buffer slot
- Cause: SPIRV-Cross binds the push constant block at
buffer(0), where the first renumbered uniform buffer goes. - Fix: the translator moves it to the next free buffer slot (
p:0.0=<slot>in the table) and the replay sets the recorded bytes there (setVertexBytes/setFragmentBytes, the pipeline layout's range). - Found on: Super Mario Galaxy.
Descriptor arrays bound to consecutive slots
- Cause: SPIRV-Cross gives an array of n descriptors n consecutive slots.
- Fix: the table says
slot*nand the replay binds element k at slot + k. - Found on: Super Mario Galaxy: the vertex shaders read the Wii's transform memory as arrays of uniform buffers (4 position-matrix blocks, 2 normal, 2 dual-texture) and the fragment shaders 8 combined image samplers.
Descriptors hold the Metal objects they were written with
- Symptom: a crash in
bind_resreading a freed view's texture (Super Mario Galaxy 2 on an iPhone, element 1 of the 8-texture array, when the ship took off after the first galaxy; GitHub issue 68). - Cause: the replay binds every element of an array the shader takes, and a set may still name an image view the game has destroyed (the hardware reads a descriptor only when a draw samples it). The layer's descriptors were pointers to its own view, sampler and buffer structs.
- Fix: a descriptor now holds the texture, sampler state and buffer it was written with (retained), as a hardware descriptor holds a copy of the handle.
- Found on: Super Mario Galaxy 2 (issue 68). Through the opening and the first storybook stage the game allocates 22,785 descriptor sets and frees none, and destroys only 5 image views (and 1,244 images), so a stale element is rare: a Mac run that kept destroyed objects to catch their binds found none there.
Descriptor copies into a binding with immutable samplers
- Symptom: a texture copied into a combined-image-sampler binding with immutable samplers is sampled with the source's sampler (its filtering, addressing, LOD clamps), not the one the layout fixed.
- Cause:
vkUpdateDescriptorSetscopied each descriptor whole (*t = *s), so a copy replaced the sampler state the set's allocation had put in place from the layout. Vulkan's updates, copies as well as writes, change only the image of a combined image sampler whose binding has immutable samplers, and a sampler-only copy into such a binding is not allowed. The write path (desc_write) already kept the sampler. - Fix: copies go through
desc_copyindm/gfx/vk/hle_vk.m: the source descriptor whole, but the destination's sampler stays when its binding has immutable samplers (lbind.imm). A source's immutable sampler is part of its descriptor and is copied into a binding without them.dm/gfx/tests/t_vk_desc.mchecks both directions. - Found on: no game: a report reproduced it in
t_vk_desc.m(source sampler A, destination immutable sampler B; after the copy the destination held A). - Check:
t_vk_descalso copies three elements of an array binding, from element 1, into the last element of an immutable binding and on into the next, mutable binding (consecutive bindings): the immutable element keeps its sampler, the others take the source's image and sampler, and the element not copied into is untouched.
An unwritten secondary blend source
- Symptom: Metal refuses a pipeline with "Fragment shader does not write to render target color(0), index(1) that is required for blending"; the Metal 4 specialization path can instead abort after
MTLCompilerServicecrashes inAGCLLVMStatelessFragmentObject::buildBlendFactor. - Cause: NVN blend state reads source 1, but the fragment shader's output map writes only colour 0. Passing that state directly to Metal asks its blend compiler to read an absent secondary output.
- Fix: for a known output map without colour 1,
pso_descchooses zero for the unwritten secondary source, consistently with the translator's dual-source output initialization (Translator.EmitOutputsInitialization). Source-1 colour / alpha factors become ZERO, and their complements become ONE. The shader, blend equation, blending enable and write mask remain intact. A written secondary source, an unknown output map or a separately specialized fragment is left alone.t_missing_src1compares both Metal pipeline paths against a shader explicitly writing a zero secondary source. - Open: the original GPU's value for an unwritten secondary source has not been measured; zero is the host's defined choice for that missing value.
- Found on: Mario + Rabbids Kingdom Battle.
A written secondary blend source (NVN dual-source blending)
- Symptom: the host aborts on Metal's compiler queue (
findOrCreateComputeFastClearPipeline,[AGX] Failed assertion "error == MTLCompilerErrorNoError") seconds into the game, with or without the pipeline prebuild, whileMTLCompilerServicecrash reports showEXC_BAD_ACCESSinllvm::ExtractElementInstunderAGCLLVMStatelessFragmentObject::buildBlendFactor(AGCLLVMStatelessPSODynamicLibrary::compile). - Cause: target 0 blends with a
SRC1factor and the pixel shader writes outputs 0 and 1. NVN, as Maxwell, takes output 1 as target 0's second source; the translator declares it[[color(1)]], and Metal reads a second source only from[[color(0), index(1)]]. With no such output, Metal 4's blend compiler crashes building the pipeline's colour state (An unwritten secondary blend source left a written output 1 alone). - Fix:
dmsh_entry.pyfs_uintgives every pixel shader'smain0_uin the lazily-loaded side library<key>_bxa bool function constantDMSH_TYPED_DUAL_FC(dm_du,entry_u_dualin the reflection) whenever colours 0 and 1 share a width and every colour >= 1 is typed: withdm_duon, output 1 is returned as[[color(0), index(1)]]and outputs 1..7 are absent (the alpha testdm_atstill runs when enabled).pso_descspecializesmain0_uthroughtyped_fnwhenever target 0 is non-integer and blends with aSRC1factor (pso_reads_src1), and marks attachments 1..7 unwritten, as on Maxwell. A shader without dual-source support blends with zero for the second source, with a red line naming it. This replaces the earlier per-gamedual_want.tsvallowlist,DM_NVN_DUAL_WANTandmain0_dentry point (which originally kept dual-source out of<key>_bbefore<key>_bxexisted, and required playing through every scene to discover shaders — nine profiles had accumulated 542 keys, including Skyward Sword HD's 432 and FINAL FANTASY XII's 27 across two rounds).t_missing_src1andt_typed_outputscheck both Metal pipeline paths. - Found on: Pokémon Legends: Arceus:
f4f36a03b0c6691d(system_resource/gfx2/shader/env/system/ha_post_effects.bnsh, variation 4: RGBA16Float, destination factorSRC1_ALPHA) andff45da02e225f961, in the first minute; FINAL FANTASY XII THE ZODIAC AGE (PR #2736: 7 more/gamedata/nvn/branch_shader/*.fpolimit-break shaders missed by the initial 20-key list prompted moving dual-source intomain0_u).
Dual-source blending from output location 1
- Symptom: Metal refuses the pipeline: "Fragment shader does not write to render target color(0), index(1)".
- Cause: the GX shaders write the second blend source as an ordinary output at location 1 (no
Indexdecoration), and pipelines blend withSRC1factors; NVIDIA's hardware feeds MRT 1 to source 1. - Fix:
vk_shaders.pybuilds a variantvk_<key>_dwith that output at[[color(0), index(1)]], which the host takes for pipelines whose blend reads source 1. Only for outputs 0 and 1 of the same type and none at location 2 or more (SPIR-V compiled by DXC). - Found on: Super Mario Galaxy.
Scaled and three-component vertex formats
- Symptom: Metal's validation aborts on a buffer layout no mapped attribute uses.
- Cause: GX positions and colours arrive as integers read as unnormalized floats (
R16G16B16_SSCALED,R8G8B8A8_USCALED, …) and in three-component formats. - Fix: Metal's integer vertex formats convert to the shader's float type; a buffer layout no mapped attribute uses is left out.
- Found on: Super Mario Galaxy.
Viewport and scissor persist across render passes
- Symptom: menus 1.5x too big in handheld mode (the file-creation dialog cut off at the right edge).
- Cause: Vulkan keeps viewport and scissor across render passes within a command buffer; the layer reset them to the render target at every pass. In handheld mode the game sets a 1280x720 viewport once and draws through several passes into its 1920x1080 swapchain.
- Fix: the layer keeps them across passes, as Vulkan says.
- Found on: Super Mario Galaxy.
Copies inside a render pass
- Symptom:
draw outside a render pass; the rest of the pass was dropped. - Cause: the game copies from its EFB with
vkCmdCopyImagebetweenvkCmdBeginRenderPassandvkCmdEndRenderPass, which NVIDIA's driver runs. - Fix: render passes now start with deferred store actions; a copy stores every attachment and ends the encoder, the next draw resumes the pass with load actions, and the pass's own store actions are set when it really ends.
- Found on: Super Mario Galaxy.
Swapchain pre-transform and layer crop
- Symptom: an assert (a stripped trap,
main+0x4d26e0) when the surface does not listpreTransformINHERIT. - Cause: the game asks for
preTransformINHERIT. In handheld mode it keeps a 1920x1080 swapchain, draws into the top-left 1280x720 and callsvi::SetLayerCropevery frame. - Fix: the surface lists INHERIT; the host keeps the crop (
hle_vi.c) and the Vulkan present shows only that rectangle, in the layer's shape. - Found on: Super Mario Galaxy.
Linear images alias their memory
- Cause: staging images (
VK_IMAGE_TILING_LINEAR, filled by the CPU and copied withvkCmdCopyImage) and one sampled 4x4 image alias their memory as on the Switch. - Fix: the texture is made over the bound
MTLBufferwith Metal's linear row alignment, whichvkGetImageSubresourceLayoutreports. - Found on: Super Mario Galaxy.
Timestamp and occlusion queries
- Timestamps are their submit's completion time; occlusion queries count into a per-submit visibility buffer, copied to the pool when the submit completes.
- Found on: Super Mario Galaxy: two timestamp pools and a 3,072-entry occlusion pool.
Specialization constants
- Symptom: a pipeline with no Metal pipeline state, and its draws missing.
- Cause: SPIRV-Cross keeps each SpecId as a Metal function constant of the same index. Metal builds no pipeline from a function whose constants have not been given.
- Fix: the values in the pipeline's
VkSpecializationInfoare set throughMTLFunctionConstantValues. Any other constant keeps the default the translation wrote (hle_vk.mspec_fn). - Found on: Super Mario 64 (Super Mario 3D All-Stars).
Packed 16-bit and 8-bit formats
- Some packed formats map to a Metal format with the components in another order: A1R5G5B5 → BGR5A1, R5G5B5A1 → A1BGR5, R4G4B4A4 → ABGR4.
- Formats Metal does not have at all (R4G4, B4G4R4A4, B5G6R5, B5G5R5A1) get a wider texture. The host unpacks the texels into it (
conv_unpack). - This works only for linear images that the CPU writes. Before each submit, every converted image whose memory changed since its last unpack is unpacked again (
conv_sync). The textures are small, N64 textures. - Found on: Super Mario 64 (Super Mario 3D All-Stars).
Image clears, dynamic stencil and line width
vkCmdClearColorImageandvkCmdClearDepthStencilImageclear through a render pass of their own (C_CLEARI).- An image made with
TRANSFER_DSTusage also gets render-target usage, so that it can be cleared that way. - Dynamic stencil state:
- the reference is the encoder's;
- the compare and write masks belong to a Metal depth-stencil state, so the pipeline keeps its depth-stencil description and builds one state per set of masks, cached (
C_STENCIL).
- A dynamic line width is ignored: Metal draws 1-pixel lines. NVN's is drawn: Lines wider than a pixel.
- Found on: Super Mario 64 (Super Mario 3D All-Stars), Super Mario Sunshine (Super Mario 3D All-Stars).
Lines wider than a pixel
- Symptom: lines a game draws with
SetLineWidthabove 1 are hairlines: Mario Golf: Super Rush's aiming grid at the tee (width 4 and 5) and its putting grid, whose moving dashes show a green's slope, can hardly be seen. The host loggedSetLineWidth 4.00: Metal has only 1-pixel lines. - Cause: Metal draws lines 1 pixel wide and has no line width; the host dropped the width.
- Fix:
SetLineWidthis recorded (OP_LINE_WIDTH) and kept in the replay's state. A draw of lines, a line loop or a line strip whose width rounds to 2 or more is drawn as a quad per segment (nvn_wline.inc), as OpenGL draws a non-antialiased wide line and as Maxwell does: a parallelogram w pixels across the segment's minor axis in window space, its ends on the major axis, so segments meet without gaps or overlap.- It is the game's draw itself, in its own render pass, with the vertex shader's wide-line entry (
dmsh_pull.py,<entry>_wl, in the pulling library) and 6 vertices a segment. Each vertex finds its segment's two endpoints from its vertex ID and a line block: their places by the primitive (lines, strip, loop), their vertex IDs from the first vertex, or from the index buffer, read on the GPU, plus the base vertex. - It runs the shader's body, as a function, for both endpoints, keeps its own endpoint's outputs and moves its position by half the width, scaled by its w, so the width holds wherever the clipper cuts the quad.
- With multisampling on (a pass of more than one sample, the multisample state enabling it), a segment is instead the rectangle OpenGL draws then: w pixels across the segment, as long as it.
- The segment is clipped first, to w > 0 and to the near plane when depth clipping is on, its outputs interpolated as the clipper would: with a corner behind the eye, the offsets do not combine convexly and the quad spilled past the line (
t_wline.m). - The fragment shader, blending, depth and stencil are the draw's own; culling is off and the polygon offset is the one enabled for lines. A blended line is as heavy as one stroke.
- Indirect arguments are read on the CPU, as the geometry path reads them. A restart index drops the segments it touches: a strip breaks there as OpenGL's does, a line list keeps its pairs (OpenGL starts a new pair after it), and an indexed line loop with restart on stays 1 pixel wide.
- Stays 1 pixel wide, with
[RED] wide line … drawn 1 pixel wide: <reason>: a vertex shader without the entry (no vertex inputs, or a parameter or output the entry cannot pass on). Programs with a geometry or tessellation stage, transform feedback or adjacency keep their own paths, 1 pixel wide. The width is capped at 64.DM_NVN_LINE_WIDTH=0draws every line 1 pixel wide. - The body runs twice a corner, 12 times a segment, so a vertex shader with stores would run them that often; no line-drawing shader seen has any.
- It is the game's draw itself, in its own render pass, with the vertex shader's wide-line entry (
- Found on: Mario Golf: Super Rush: the tee's aiming grid and a green's putting grid, 480 segments a draw (PR #2352 recorded the width and drew the lines as shifted strokes).
Clear values of integer attachments
- Symptom: none seen in a game. An integer colour attachment opened with
VK_ATTACHMENT_LOAD_OP_CLEARwould hold another value than the game's clear value (in the check below, 0 instead of 4,000,000,000 and instead of −5), and a signed integer image cleared byvkCmdClearColorImageto a negative value would holdINT32_MAX. - Cause:
VkClearColorValueis a union, and the format of what is cleared names the member:int32for a signed integer format,uint32for an unsigned one,float32for every other. Metal takes a clear colour as four doubles and converts them to the attachment's type. The render pass's clear (begin_rp) readfloat32for every format, so an integer's bits were taken as a float; the image clear (C_CLEARI) readuint32for both integer kinds, so a negative value became one aboveINT32_MAX. - Fix: both clears take the colour from
fmt_clear_color(hle_vk.m), which reads the member the format names (fmt_is_signed_intfor the signed formats). - Check:
make -C dm/gfx/tests GAME=<id> check_t_vk_clear_intclears anR32_UINT, anR32_SINTand anR32_SFLOATimage each way and reads the texels back; before the fix 3 of its 12 checks failed (the two integer render-pass clears and the signed image clear). - Found on: no game. Found by reading
begin_rpbeside the image clear, then reproduced int_vk_clear_int. Which games clear an integer attachment this way is not known.
What a game tears down that it should not
- Symptom: a crash in
set_freefromvkFreeDescriptorSetsas a game leaves. - Cause: a game frees descriptor sets whose pool it already reset or destroyed, and destroys the images
vkGetSwapchainImagesKHRgave it while it keeps the swap chain. Vulkan forbids both; the console's driver lets them pass. - Fix:
hle_vk.mkeeps the set of descriptor sets that exist, and a free of one that is gone is ignored; a swap chain's image is marked, andvkDestroyImageof it is ignored (the swap chain owns it). - Found on: Super Mario 64 (Super Mario 3D All-Stars), on the way back to the launcher.
Layouts and render passes freed on destroy
- Symptom: host memory that grows with each layout or render pass a game creates and destroys, and a pipeline's dynamic depth-stencil state kept after
vkDestroyPipeline. - Cause:
vkDestroyDescriptorSetLayout,vkDestroyPipelineLayoutandvkDestroyRenderPassdid nothing, because sets, pipelines and recorded commands kept pointers to them.vkDestroyPipelinefreed the struct without clearingdss_dyn, and ARC does not release amalloc'd struct's strong fields. - Fix: Vulkan lets sets and pipelines outlive the layouts they were made with, so a set layout counts its holders (its handle, each set, each pipeline made with it) and the last one frees it. A pipeline copies its push-constant size and set layouts from its pipeline layout, which is then freed on destroy (commands ignore the layout argument). Commands are replayed at
vkQueueSubmitand pipelines copy the attachment formats, so a render pass is freed on destroy, as a framebuffer already was: Vulkan does not let a command buffer that recorded it be submitted again.vkDestroyPipelinereleasesdss_dyn. - Check:
t_vk_descdestroys a set layout and pipeline layout while a set and a pipeline made with them live, uses them, frees the set and destroys the pipeline (the last holder), with a weak reference on the dynamic depth-stencil state; it passes under ASan and Metal validation. - Found on: a code audit. Hades creates and destroys a render pass per pipeline (1,856 in its first minute, about 0.7 MB kept before); it destroys no layout or pipeline in that minute.
Occlusion queries that span render encoders
- Symptom:
[RED] occlusion query outside a render pass or past the buffer; a query's result stays 0. - Cause: Vulkan lets a query begin before a render pass and end after it, and a pass's Metal encoder may be split for a copy. Metal's visibility mode belongs to one encoder.
- Fix: the query running gets a slot of the submit's visibility buffer in every render encoder started while it runs (
occ_startinhle_vk.m), and its result is their sum. - Found on: Super Mario Sunshine (Super Mario 3D All-Stars): Hagi's GX queries at Delfino Airstrip.
VK_EXT_debug_report
- Symptom: a call to address 0 at boot.
- Cause: a game that enables the extension calls its functions without checking the lookup.
- Fix: the layer reports nothing. The callback object is a token that is never called.
- Found on: Super Mario 64 (Super Mario 3D All-Stars).
Attachments opened with LOAD_OP_DONT_CARE
- Symptom: the 3D world black, the HUD drawn over it; the scene's own colour target, read back, holds the whole scene.
- Cause: Vulkan leaves an attachment opened with
VK_ATTACHMENT_LOAD_OP_DONT_CAREundefined; the Switch keeps what the image held, so a game can draw over it. NVIDIA's Vulkan driver, which the game ships (subsdk1, 421.03), has no explicit colour discard on the path examined: render-pass begin and end do nothing for a colour DONT_CARE, and for depth they only drop the ZCULL hints. The macro the driver runs at every begin and end (MME0xB2, macro index 0x59, called with(0x13, 0)and(0x15, 0)) reads its second parameter and exits when it is zero: it sends no method and writes no memory. The submit-time processing of the driver's last-use table is not decoded, so this is what the examined path does (read statically, no console run), not a promise, and no claim about every side effect in the hardware. Re:ZERO's post chain copies the scene into a target, then blends its effects layer over it in the next pass, and draws the HUD over the frame in the swap chain image, each pass opening its colour target with DONT_CARE (its engine's render-target wrapper can only ask for CLEAR or DONT_CARE). The layer opened them withMTLLoadActionDontCare, which starts Apple's tile memory undefined (empty in practice), so the copy and the frame were lost. Switch emulators (Ryujinx, yuzu, Eden, Hydra) never see a load op and always load the game's render targets. - Fix: attachments opened with DONT_CARE are loaded (
load_ainhle_vk.m), colour, depth and stencil alike, as on the Switch. Depth and stencil matter too: Re:ZERO's particle pass reopens the half-res depth with DONT_CARE and STORE, draws nothing, and the pfx pass samples that depth to upsample its effects layer. With depth at Metal's DontCare that pass stores whatever the tiles held: run once with the attachment filled with a pattern and once loaded, it stored a different value in every texel, every frame checked. On an M4 Pro, loading depth and stencil as well cost nothing measurable in Re:ZERO (88 paired cycles, GPU p50 −0.00 ms, quartiles −0.09 … +0.04) for 9 MB more loaded a frame. - Check:
make -C dm/gfx/tests GAME=<id> check_t_vk_dontcareclears an image to red, then blends a transparent triangle over it in a pass that opens it with DONT_CARE, LOAD or CLEAR to green: red, red and green; and reopens a depth-stencil image cleared to 0.25 /0x5awith DONT_CARE in a pass without draws: 0.25 /0x5a. It tests this layer's policy, not Vulkan, which promises nothing for DONT_CARE. The check runs withMTL_DEBUG_LAYER_VALIDATE_LOAD_ACTIONS=1, which fills every DontCare load with a pattern (before the fix the colour case read back magenta, the depth case 0.5 /0xaa), so it does not depend on what the tile memory happens to hold. - Found on: Re:ZERO, from a dump of the map's Vulkan commands and target readbacks.
1D images drawn into
- Symptom: under Metal's API validation (on when Xcode's Run starts the app, or
MTL_DEBUG_LAYER=1), a Vulkan game stops on a validation assertion when it draws or clears into a one-dimensional image, or creates a mipmapped or depth one; without validation it goes on, with undefined results. - Cause: Metal's 1D texture covers less than Vulkan's 1D image: it cannot be a render target, has exactly one mip level (without validation Metal quietly makes a mipmapped one a single level) and has no depth format. The layer made each Vulkan 1D image a Metal 1D texture and attached it to the pass.
- Fix: a 1D image is a one-row 2D texture (2D array for layers), as in the NVN layer (
tex_descinnvn_mtl.m) and in MoltenVK; 1D and 1D-array views are 2D and 2D-array views (vkCreateImage,vkCreateImageViewinhle_vk.m).vk_shaders.pytranslates withspirv-cross --msl-texture-1d-as-2d, which declares a 1D image astexture2d, samples it at the row's centre (float2(x, 0.5), so a clamp-to-border sampler does not blend in the border) and reads it at(x, 0). Drawing, clearing, mip levels, layers and depth then need nothing of their own. Only 1D types change: a game without 1D images gets the same shaders and textures. - Check:
make -C dm/gfx/tests GAME=<id> check_t_vk_1d, under the validation layer: a 512-texel, 3-level, 2-layer 1D colour image cleared to red, then drawn into at level 1 of layer 1 through a 1D view in a pass that clears it to green, reads back green there and red everywhere else; a 1D depth image cleared to 0.25 keeps it through a pass that loads it. With 1D textures the layer aborted at the first image. - Found on: Hades: it draws into a 512x1 colour target about 30 s into play, and under validation the iPhone and the Mac stopped there;
LightAndShadow.fragsamples a 1D shadow map (ShadowMap, the only 1D image of its 74 shaders) (PR 1977).
Not translated in the Vulkan layer: geometry shaders
- Symptom: GX points and lines drawn as one-pixel points and lines.
- Cause: two geometry shaders (GX points and lines expanded to quads) are not translated (Metal has no geometry stage).
- Found on: Super Mario Galaxy.
Vulkan geometry shaders that select a viewport
- Symptom:
shader stage 0x8 not implementedon a shadow pipeline. The draw still runs, with the vertex shader's outputs and viewport zero. - Cause: Metal has no geometry stage. The Vulkan translator skipped the SPIR-V stage even when it emitted the same triangle and only selected a viewport. Command replay also kept just the first viewport and scissor.
- Fix: Prove that the geometry shader emits one triangle with positions and varyings unchanged and writes its viewport index from one input location. When the matching vertex shader writes
InstanceIndexdirectly to that location, all vertices in the primitive agree and a vertex variant can write Metal's[[viewport_array_index]]. The pipeline selects the variant for triangle lists. Replay applies the pipeline's viewport and scissor arrays and retains partial dynamic updates at their original indices. Metal Shading Language, section 5.10 - Check:
check_t_vk_cmdsreads back pixels from two instances routed through two viewports and distinct scissors, with both static state and partial dynamic updates. The shader tests reject changed triangle positions and a vertex-dependent viewport index. - Found on: Re:ZERO,
shadow-render.gs.spv(287e364d4b97a5be).
SPIR-V compiled by DXC
- Symptom:
vk_shaders.pystops withspirv-cross failed: SPIRV-Cross threw an exception: Entry point does not exist.A shader with push constants has nop:row. Metal rejects a generated dual-source variant of a shader with ordinary render targets. - Cause: DXC uses entry-point names such as
PSMain. The tool always tried to renamemain. SPIRV-Cross changes the dots intype.PushConstant.<name>to underscores in MSL, so looking for the reflected type name misses the push-constant argument. A second color output can be a separate render target, such as Re:ZERO'sfloat2beside afloat4. - Fix: Rename the sole entry point reported by reflection and look up the push-constant argument under the sanitized MSL type name. Generate the dual-source variant only when the only color outputs are locations 0 and 1 with the same type.
- Found on: Re:ZERO (
0100D800117F4000, The Forge renderer on Vulkan, SDK 9.5.0). - Check:
test_vk_shaders.pytranslates synthetic SPIR-V for named entry points, 1D sampling, push constants beside a uniform buffer, and dual-source and ordinary color outputs.
Commands reached through the Vulkan loader
- Symptom: Vulkan command lookup returns null for recorded commands. A pipeline requesting a missing fragment shader runs as depth-only and leaves the picture black.
- Cause: the command recorder lacked several operations, and Metal accepts a graphics pipeline without a fragment function.
- Fix: replay indirect draws, buffer fills and updates, resolves, blits, secondary buffers, event set and reset, dynamic blend constants and depth bias, and query copies. Refuse to draw a pipeline whose requested fragment shader is missing and count its skipped draws. Explicit depth-only pipelines still work. The RenderDragon port adds 2D scaled blits and partial resolves.
- Limits: subpass advancement is reported and skipped. Queue submission is serial. GPU waits on events remain unsupported. Partial attachment clears use clear draws.
- Check:
t_vk_cmdsreads results back under Metal validation and distinguishes a missing fragment function from an intentional depth-only pipeline. - Found on: Re:ZERO, PR #1371.
Vulkan partial attachment clears skipped
- Symptom:
vkCmdClearAttachments region requires a partial attachment clear; pixels retain their old color or depth. A 2×2 clear in a 4×4 image changed no pixels instead of four on the Mac. - Cause: replay only implemented whole-attachment clears with Metal load actions. One partial rectangle or a layered framebuffer discarded the entire command, including its other attachments. Metal's default visibility-result reset also erased earlier encoder slots when a pass resumed.
- Fix: retain the load-action path for whole attachments. For partial clears, reuse the precompiled host clear shaders with cached float/uint/int pipelines and exact scissors in load/store helper passes for the selected attachment-view layers. Preserve other pixels, mip levels, layers and depth/stencil aspects, then resume the game's pass with its state restored. Visibility passes accumulate into the submit's zero-initialized buffer so results survive encoder splits. Clears need no transfer usage or game shader. Vulkan clear contract, view-relative layers, Metal visibility results.
- Check:
check_t_vk_clear_attachmentsreads back full and partial typed clears (including0x80000000and0xffffffff), sRGB, multiple rectangles and subpass attachment slots, mip/array views, MSAA, independent depth/stencil planes, secondary-buffer clears, and draw–clear–draw order with preserved scissor and occlusion counts. - Found on: investigated for Minecraft 1.26.62. The host defect was reproduced synthetically; no unsupported-clear call or visible Minecraft failure was reproduced in the tested menu-to-world route.
Vulkan query copies consumed by the GPU
- Symptom: a GPU copy after
vkCmdCopyQueryPoolResultsand a transfer barrier reads the old bytes. The CPU reads the new result after the submission completes. - Cause: the draft replay wrote the destination from a completion callback, after every command in the submission had run. The host gathers Metal visibility counts at completion and uses command-buffer completion time for timestamp queries.
- Fix: collect query writes from the completed Metal prefix when the copy needs its results. Encode the values through a staging buffer at the copy's position so later GPU commands see the write. Results already available can be copied without splitting the command buffer. Finish each logical submission and signal its Vulkan fence at the final Metal command buffer.
- Limits and cost: a copy that needs a pending query in the current Metal command buffer splits and waits for the prefix. Timestamps retain the host's completion-time approximation. Stage-boundary counter sampling returned data through Metal's CPU resolver on the Apple M6, while a GPU resolve in the same command buffer returned zero.
- Check:
t_vk_cmdscompares the query destination with an ordered transfer out of it in the same submission and checks the unavailable entries. - Found on: a synthetic GPU readback while checking PR #1371.
Vulkan compute dispatch
- Symptom:
vkCreateComputePipelinesand dispatch commands are missing, or a clustered-light kernel reads the wrong texture type. - Cause: the Vulkan host previously replayed graphics and transfers. SPIRV-Cross's default texel-buffer emulation uses a 2D texture, while the host binds a native Metal buffer texture.
- Fix: translate compute stages with their reflected workgroup size and native texel buffers. Replay direct and indirect dispatch with separate compute and graphics bindings, and apply push-constant writes only to their declared stages. Close the compute encoder before rendering or blitting. Advertise storage-image formats supported by the Metal read-write texture tier.
- Limits: workgroup sizes selected by specialization constants and nonzero base dispatch groups remain unsupported. A pipeline that exceeds Metal's threadgroup limit is refused.
- Check:
test_vk_shaders.pychecks the workgroup size and texel-buffer type.t_vk_computereads back dispatches, stage-specific push constants, producer-consumer work, and storage images. - Found on: Re:ZERO, PR #1539.
Vulkan shader resource tables truncated
- Symptom: the shader-table loader reports resource entries it cannot parse, and affected draws use missing or stale sampler state. Shadows, reflections or other texture samples can be wrong even though the shader compiled.
- Cause: the host kept only the first 24 resource entries of each shader and continued with that partial list. Buffers, textures and samplers have separate Metal argument tables; their combined metadata count is not a device limit. The draw loop therefore never bound the omitted entries.
- Fix: size each shader's resource list to its complete table row and keep it for the table's lifetime. Read complete lines with
getline. Validate the resource syntax and the host's per-kind slot, set, binding and array ranges; reject an invalid row completely so shader lookup cannot build a pipeline with partial bindings. The generated table format and shaders stay unchanged. - Check:
t_vk_argbufcovers 24–29 entries, a 96-entry row over 4 KB, old and explicit argument-buffer IDs, arrays and dynamic offsets, and rejection without retaining a valid prefix. Its 25-resource GPU draw reads back the final sampler's linear filtering after seeding stale nearest-filter state. - Found on: Minecraft 1.26.62; a synthetic GPU A/B reproduced incorrect pixels under Metal validation on Apple M6.
Vulkan descriptor arrays over Metal's direct limits
- Symptom: shaders with large descriptor arrays exceed Metal's direct slots. An argument buffer with a texture array at Vulkan binding 0 and a sampler at binding 1 can fail Metal compilation with overlapping IDs.
- Cause: one Vulkan array occupies one binding. A Metal argument-buffer array occupies an ID for every element.
- Fix: move sets into Tier 2 argument buffers when direct slots run out. Allocate Metal IDs per set, retain the original Vulkan binding in the shader table, and use the Metal ID to encode the element. Hold descriptors and mark resources resident for each encoder. Re-encode a set when it changes.
- Limits: at most two argument buffers per stage. Combined image samplers in an argument buffer remain unsupported. The device's sampler limit also applies to argument-buffer samplers.
- Check:
test_vk_shaders.pytranslates adjacent Vulkan bindings.t_vk_argbufreads pixels using a table whose Vulkan bindings differ from the Metal IDs, and checks that descriptor updates refresh the encoded data. - Found on: Re:ZERO uses arrays of 512 textures and 64 samplers. The adjacent-binding collision was verified with a synthetic shader.
OpenGL layer
Digimon Story Cyber Sleuth: Complete Edition (Media.Vision's MVGL engine, SDK 6.4.0) and Balatro (LÖVE 11.4, "love-nx", with SDL and LuaJIT) render with NVIDIA's desktop OpenGL 4.5 core profile through EGL, not NVN. The host implements GL itself on Metal (dm/gfx/gl/hle_gl.m), as it does Vulkan for Hades; NVIDIA's GL driver (subsdk0) is not loaded. Balatro's graphics module is LÖVE's own OpenGL backend, so its choices follow what the context reports.
GL resources exceed the direct Metal sampler table
- Symptom:
gl_shaders.pyrejects a fragment shader witha buffer or sampler slot above 15; removing the check lets some compile, while others fail Metal compilation with'sampler' attribute parameter is out of bounds: must be between 0 and 15. - Cause: glslang assigns bindings in one namespace, which
--msl-decoration-bindingcopied into Metal's direct buffer, texture and sampler tables. A uniform block after 16 textures landed at buffer 16 and failed the tool's shared limit check, although fragment buffer 16 is legal. Two other shaders actually read 17 textures with 17 samplers: compacting their bindings cannot fit Metal's 16 direct sampler arguments. The GL host advertises 32 fragment texture units. - Fix: every GL stage uses one Tier 2 argument buffer at buffer 0, with independent IDs for uniform buffers, textures and samplers. The tool gives SPIR-V resources private names before translation, preserving the game's names in the table, and records the IDs from the generated MSL. The host encodes those resources per draw, declares indirect texture and buffer reads to Metal, retains samplers until completion, and snapshots changed default uniforms in transient memory. This also separates every uniform block from vertex stream slots 15–30. Shader-table ABI 2 rejects older direct-slot tables with a rebuild message; rebuild both GL libraries and the host together. All supported Apple GPU families have Tier 2 argument buffers (Apple feature tables).
- Check:
test_gl_shaders.pytranslates 16, 17 and 32 live samplers plus a default uniform block.make -C dm/gfx/tests GAME=010029D00E740000 gl-argumentsgenerates GLSL and its table/library, then checks GPU pixels for 17 distinct sampler states, a sampler shared by both stages, vertex attribute 15, changed uniforms, changed sampler units and changed named-block ranges across three draws in one command buffer, under Metal validation. This target needs glslang and SPIRV-Cross;gl-importskeeps its existing dependencies. - Found on: Fate/hollow ataraxia REMASTERED (
010070E022546000, update v131072, provisional profile):c5b7066d3afd5bfehas 16 samplers and buffer 16;3f4e845c008603d4and469deb981b2bf744also readgPatternMaskTexture, their seventeenth sampler. All three compile with argument buffers for Mac and iPhone. The game has no registered repository note yet.
OpenGL 1.x fixed function
- Symptom: the survey reports no graphics API and the host drops OpenGL draws that have no shader program.
- Cause: the packer expected
glShaderSourceas evidence of desktop OpenGL. In a legacy or compatibility context, client arrays and the current fixed-function state can draw without a program. - Fix: the packer recognizes fixed-function entry points with EGL and no evidence of shaders. It builds an empty guest GL shader library. In a context with fixed function, a draw without a program uses the host's built-in
gl_ff.metalprogram, the client arrays, matrix stacks, unit 0's texture environment and alpha test. Other texture units keep their own matrices and state. Multitexturing, lighting, fog and texture-coordinate generation are outside this implementation. - Found on: UnMetal.
Games that render with desktop OpenGL through EGL
- Symptom:
UNIMPL eglGetDisplay, thenBreakright afternv::InitializeGraphicsandvi::OpenDefaultDisplay(main+0x5ed9d0). - Cause: the game renders with NVIDIA's desktop OpenGL through EGL; its NVN device (made just before) serves only a helper beside the movie player.
- Fix: the host's GL layer (
dm/gfx/gl/hle_gl.m) answers the EGL imports andeglGetProcAddress(the rest of this section). - Found on: Digimon Story Cyber Sleuth: Complete Edition (SDK 6.4.0, Media.Vision's MVGL engine; one boot).
glFlush hands the frame so far to the GPU
- Symptom: the app closes with no message of its own,
[dm] CRASH sig=11 addr=0 pc=0and a guest return address insidemain(Well Dweller:lr=main+0x3409a78, the same address every time);DM_GL_STUBS=1then names the call:[RED] glFlush called: not implemented, returns 0. - Cause:
glFlushis not one of the layer's names, soeglGetProcAddressreturns a null pointer, which the game stores in its own function table and calls when it opens a menu.blrinto address 0 is a signal, not an abort, so nothing else says which function was wanted. A game's loader asks for the whole GL 4.6 name list (Well Dweller: 215 names, mostly 3.3+ features it never calls), so a null pointer by itself is correct; calling one is not. - Fix:
glFlushflushes pending clears and commits the open command buffer without waiting (GLB(glFlush, …)next toglFinishindm/gfx/gl/hle_gl.m), and the calls after it start a new command buffer.DM_GL_STUBS=1remains the way to name a missing one, andDM_GL_MISSES=1prints every name the loader asked for and the layer does not implement. - Check: Well Dweller, the same scripted input that crashed at the pause menu: the OPTIONS, GRAPHICS, STATS and PAGES screens open and the game returns to play (
[gl] frame 15300, 35 draws per frame). - Found on: Well Dweller.
Direct GL imports use the same implementations as the loader
- Symptom:
UNIMPL glCreateShaderreturns 0, followed byUNIMPL glShaderSource,glCompileShader,glGetShaderivandglGetShaderInfoLog; the game crashes insdkwith a null shader handle even though EGL initialized. - Cause: the GL implementations were registered only in
__DATA,swgl, whicheglGetProcAddresssearched. Normal imports search__DATA,swhle; a game that imports GL directly never consulted the GL table and got named unimplemented stubs instead. - Fix:
GLandGLBregister inswhle, andeglGetProcAddresssearches that same table. Both paths retainGLB's big-stack entry; unsupported loader names still return null by default (DM_GL_STUBS=1enables diagnostic stubs).make -C dm/gfx/tests GAME=010014E00DB56000 gl-importsexercises the real import resolver and GL registrations, shader creation and source queries, wrapper addresses and missing names in both diagnostic modes, without game files. - Found on: Darkest Dungeon Complete (
01008F1008DA6000, update v327680, SDK 3.6.0, provisional profile), reported in issue #228. The import failure is reproduced by the regression test; gameplay and run-time shader capture for this title remain unverified.
Compressed OpenGL texture arrays
- Symptom:
DM_GL_MISSES=1listsglCompressedTexImage3DandglCompressedTexSubImage3D, and the game crashes atpc=0right after GL initialisation; withDM_GL_STUBS=1the stubs are called withGL_TEXTURE_2D_ARRAY(0x8c1a) and BC7 sRGB (0x8e8d). - Cause: the GL layer had compressed 2D images and array storage, but no compressed array uploads, and its pending image levels held one layer each.
- Fix: both entry points are in the GL import table and pack their stack arguments before the big-stack entry (
compressed_impl,hle_gl.m);glCompressedTexSubImage2D(a 2D texture or a cube face, one layer) shares the sub-image path. A pending array level holds every layer, each with its own rounded block rows, mips smaller than a block included; the layer count is the same at every level. A sub-image into a texture not made yet goes into the level's pending copy (zeros first when the level was allocated with no data), so the texture is made with every level given before its first use, whatever order the game allocates and fills them in; into a made texture it goes throughtex_write, in command order. An allocation with no data needs no matchingimageSize. Other targets (GL_TEXTURE_3D, cube-map arrays) and compressed formats the layer does not map are the host's gaps: a red line, no GL error. - Limitations: compressed volume and cube-map-array targets and uploads from a pixel-unpack buffer are not implemented.
glTexImage3Dstill gives level 0 only. - Check:
make -C dm/gfx/tests GAME=010014E00DB56000 gl-imports(test_compressed_arrays): BC7 sRGB arrays of two layers and three levels, partial and edge sub-images, an upload after a draw used the texture, immutable storage, levels allocated with no data and filled one after the other, and the red-line gaps. - Found on: Tomb Raider I-III Remastered (
010024601BB16000, v851968, provisional profile), issue #2416. Its startup also exposed inactive uniforms getting GL locations. DOOM 3 streams its DXT images withglCompressedTexSubImage2DARB.
Extensions a GL renderer checks for, and its ARB names
- Symptom: the game aborts about 2 s after
[gl] EGL context: OpenGL 4.5, before it askseglGetProcAddressfor its buffer functions:game called nn::diag abort: Result 0withmain+0x26220in the backtrace, no GL call red, nothing drawn.mainholds strings such asGL_ARB_fragment_program not available. - Cause: the renderer checks a fixed list of extensions in
GL_EXTENSIONSand stops with " not available" when one is missing, although GL 4.5 has every core one in it. It then asks for many functions only by their ARB names (glBindBufferARB,glMapBufferARB,glCompressedTexSubImage2DARB,glVertexAttribPointerARB,glActiveTextureARB), which the layer did not have. - Fix: the layer lists the core extensions a renderer checks for (
GL_ARB_multitexture,GL_ARB_texture_compression,GL_ARB_vertex_buffer_object,GL_ARB_map_buffer_range,GL_ARB_draw_elements_base_vertex,GL_ARB_uniform_buffer_object,GL_ARB_buffer_storage,GL_ARB_sync,GL_ARB_seamless_cube_map) and the two the game needs past them,GL_ATI_separate_stencil(GL two-sided stencil) andGL_ARB_fragment_program. An ARB name of a function GL took into its core gets the core entry where the registry says the two are the same (GL extension names of core functions).ARB_fragment_program's assembly programs have no core counterpart: their entries give names and record nothing, with a red line atglBindProgramARBorglProgramStringARB, andglGetProgramivARBanswers its target's program as within the native limits; DOOM 3 draws with GLSL and never calls them. - Check:
t_gl_imports(test_doom3): each listed extension as a whole name inGL_EXTENSIONSandglGetStringi, ARB names to their core entries, an ARB name of nothing still missing. - Found on: DOOM 3 (id Tech 4, BFG Edition renderer): its required list is
GL_ARB_multitexture,GL_ARB_texture_compressionorGL_EXT_texture_compression_s3tc,GL_ARB_vertex_buffer_object,GL_ARB_map_buffer_range,GL_ARB_draw_elements_base_vertex,GL_ARB_vertex_array_object,GL_ARB_uniform_buffer_object,GL_ARB_buffer_storage,GL_ATI_separate_stencilandGL_ARB_fragment_program, as its "not available" strings say; reported first in issue #1180.
GL extension names of core functions
- Symptom:
DM_GL_MISSES=1lists extension names of functions the layer has, such asglGenFramebuffersEXT,glBindRenderbufferEXTandglCheckFramebufferStatusEXT; a game whose loader takes one of those names for the function jumps to address 0 when it calls it (CRASH sig=11 addr=0 pc=0). - Cause: the layer answered exact names, and ARB names by stripping the suffix, so an extension's name of a function it has got null. A suffix cannot just be stripped: under the bare name GL has another function for some extension names, such as
glVertexAttribPointerNV(5 arguments, against 6),glVertexAttribFormatNV(a stride where the core one takes an offset),glPolygonOffsetEXT(a bias in other units) andglGetProgramivARB(an ARB assembly program asked by its target). - Fix:
gl_lookupanswers an extension name with the entry of the function it is the same as, fromdm/gfx/gl/gl_aliases.h, whichdm/gfx/tools/gl_aliases.pywrites from Khronos'sgl.xml(a command's<alias>) and a reviewed GL ES list (OES_framebuffer_object,OES_texture_3D, the OES blend functions, ANGLE's and NV's ES 3.0 functions), whichgl.xmldoes not cover.gl.xmlleaves outEXT_framebuffer_object's binds, since a bind there makes the object of a nameglGen*never gave; the layer'sglBindFramebufferandglBindRenderbuffermake it, as GL ES's and the compatibility profile's do (and as itsglBindTexturedid), so the list has them. This replaces the ARB rule, which gaveglGetProgramivARBthe GLSLglGetProgramiv. - Check:
t_gl_imports(test_extension_names_and_egl);test_gl_aliases.py(the table sorted, the registry's names in, suffix-only names out). - Found on: Fate/hollow ataraxia REMASTERED (
010070E022546000, update v131072), issue #2818; PR #2819 stripped any vendor suffix. Its loader asks for 3,331 names, theEXT_framebuffer_objectones among them; 113 more of them get their function this way. Over the strings of the other GL games'main(Balatro, DOOM 3, Digimon, Mega Man Legacy Collection, Well Dweller), no name the ARB rule answered lost its function, andglGetProgramivARBwent to an entry of its own.
EGL's current context, per thread
- Symptom: a jump to address 0 after
eglGetProcAddress("eglGetCurrentDisplay"), or a loader that takes the context for lost; a second thread'seglMakeCurrentreturnsEGL_FALSEwithEGL_BAD_ACCESSwhile another thread owns the context. - Cause: a glad loader asks
eglGetProcAddressfor EGL functions too, and callseglGetCurrentDisplay; the layer answered onlyglnames and had noeglGetCurrent*. - Fix:
eglGetProcAddressanswerseglnames from the same table.eglMakeCurrentrecords the calling thread's display, context and draw/read surfaces;eglGetCurrentContext,eglGetCurrentDisplayandeglGetCurrentSurface(EGL_DRAW,EGL_READ) answer that binding. The layer's one context has one owner, protected by a mutex. A conflicting bind returns false withEGL_BAD_ACCESSand leaves both threads' bindings unchanged. Making no context current,eglReleaseThread, or the owning thread's exit releases it for another thread.eglGetErrorreturns and clears only the calling thread's error. - Current limit: multiple and shared contexts are unsupported. Every
eglCreateContextreturns the same handle (0x2), and GL state and command encoding are global, so a second creation does not give another thread an independent context. Keep the ownership check unchanged; revisit multiple contexts only when a real game needs them. - Check:
t_gl_imports(test_extension_names_and_egl). - Found on: Fate/hollow ataraxia REMASTERED, issue #2818.
glGetShaderSource returns the stored shader text
- Symptom: a game jumps to address 0 or takes a dead branch after compiling and linking GLSL shaders, because
glGetShaderSourcewas unimplemented and returned an empty buffer / length 0. - Cause:
glShaderSourcealready stored each shader's source (s->src,s->len) andglGetShaderiv(GL_SHADER_SOURCE_LENGTH)reported its length, butglGetShaderSourcehad no entry indm/gfx/gl/hle_gl.m(even thoughgl_aliases.halready aliasedglGetShaderSourceARBto it). - Fix: implement
glGetShaderSourceindm/gfx/gl/hle_gl.m(SP_CHECK(sh, 0),GL_INVALID_VALUEforsize < 0, safe no-op forsrc == NULLorsize == 0, truncated NUL-terminated copy ofs->src), and haveglGetShaderiv(GL_SHADER_SOURCE_LENGTH)return 0 when no source is set. - Check:
make -C dm/gfx/tests GAME=0100CD801CE5E000 check_t_gl_importschecks full copy, truncation, nulllen, nullsrc, zerosize, empty shader source, andGL_INVALID_VALUE/GL_INVALID_OPERATIONerror reporting. - Found on: Fate/hollow ataraxia REMASTERED, PR #3063.
GL named uniform blocks
- Symptom:
gl_shaders.pyrefuses a shader withuniform block matrices_ubo is not the default block; withDM_GL_STUBS=1the game callsglGetUniformBlockIndexandglUniformBlockBinding. - Cause: the layer had only the default uniform block (loose uniforms, which glslang gathers into
gl_DefaultUniformBlock), not a block the game names and fills from a buffer of its own through a binding point. - Fix:
gl_shaders.pywrites a named block asn:<name>=<id>:<size>in the table. The link merges a program's blocks by name over its stages (prog_t.blk, each at binding point 0);glGetUniformBlockIndexreturns a block's place in that list,glUniformBlockBindingsets its binding point, andglBindBufferRange/glBindBufferBasekeep the buffer and range of each of the 72 binding points (GL 4.5's minimumGL_MAX_UNIFORM_BUFFER_BINDINGS). A draw encodes the range at the block's argument ID in each stage (GL argument buffers,blk_buffer); a range shorter than the block, or a buffer that ends before it, is copied into transient memory with zeros after it, so the shader reads nothing outside the buffer.GL_UNIFORM_BUFFER_OFFSET_ALIGNMENTis 256, as NVIDIA's driver reports. - Check:
t_gl_imports(test_doom3): the merged block, its index and binding, the range itself, a short range and the buffer's end padded with zeros, a deleted buffer reading zeros;test_gl_shaders.py: the table row. - Found on: DOOM 3: its skinned shaders read the joints from
uniform matrices_ubo {vec4 matrices[408];}(6,528 bytes), and the renderer binds only the joints of the model it draws (glBindBufferRangeof a part of a larger buffer).
GL two-sided stencil
- Symptom:
DM_GL_MISSES=1listsglStencilOpSeparateandglStencilFuncSeparate; the game needsGL_ATI_separate_stencilinGL_EXTENSIONS. - Cause: the layer kept one stencil state for both faces.
- Fix: each face has its own function, reference, read and write masks and operations (
stface_t S.st[2]);glStencilFunc/glStencilOp/glStencilMaskset both,glStencilFuncSeparate/glStencilOpSeparate/glStencilMaskSeparate(andATI_separate_stencil's two calls) one or both. They become Metal's front and back stencil descriptors andsetStencilFrontReferenceValue:backReferenceValue:; GL's front faces are Metal's, since the layer reverses the winding with the y flip. A masked clear writes through the front faces' mask, as GL's does. - Check:
t_gl_imports(test_doom3): the faces apart and together,ATI's front and back functions, a depth / stencil state that differs only in its back face, an unknown face. - Found on: DOOM 3: its stencil shadow volumes count front and back faces in one draw, as issue #1180 found; Mars City Hangar's shadows (the stairs, the crates, the marines) draw with this.
GL programs with a vertex shader alone
- Symptom:
program N: a shader is missing from the library, its draws are skippedwith noshader … is not in the libraryline before it; no shadows. - Cause: desktop GL links a program with no fragment shader (its draws rasterize and write depth and stencil, their colour is undefined); the layer needed both stages.
- Fix: such a program links with an empty fragment stage (no uniforms, samplers or blocks), and its pipelines have no fragment function and write no colour.
- Check:
t_gl_imports(test_doom3): the link and a pipeline with a colour attachment and depth / stencil built from a vertex function alone. - Found on: DOOM 3: its shadow volume programs,
shadowandshadow_skinned, are the two render programs with a.vertexsource and no.pixelone; Mars City Hangar has its shadows once they link.
GL frame copies into a texture
- Symptom: with
DM_GL_STUBS=1,glCopyTexImage2Dis called every frame once a level draws. - Cause: the layer had no copy from a framebuffer into a texture.
- Fix:
glCopyTexSubImage2Dcopies a rectangle of the read framebuffer's colour image into a texture level with a blit in command order, after the draws so far (tex_copy); both are stored bottom row first, so the rows go across as they are, and the part outside the framebuffer is left as it was (GL leaves it undefined).glCopyTexImage2Dfirst (re)defines the level at the copy's size in the internal format given (a texture remade at one size keeps its Metal texture); a copy between two formats is a red line. - Check:
t_gl_imports(test_doom3): a copy into a new level and a clipped one at an offset, read back. - Found on: DOOM 3: its renderer copies each frame's lit picture into
_currentRenderand draws it back for the post effects (two copies a frame in Mars City); without the copy that draw covers the screen in black, as issue #1180 found.
GL_UNPACK_SWAP_BYTES
- Symptom:
[RED] glPixelStorei(0xcf0, 1) not implemented; images uploaded after it come out in the wrong colours (red / green bands for RGB565). - Fix:
pixels_convertswaps each 2- or 4-byte element of the source into a copy of its rows (each row without its alignment padding) before the conversion. The packed typesGL_UNSIGNED_INT_2_10_10_10_REVandGL_UNSIGNED_INT_10F_11F_11F_REVeach have one four-byte element per pixel, which determines the source row stride and the swap width. - Check:
t_gl_imports(test_doom3): RGB565 red and green stored big-endian convert to the same colours as stored little-endian.test_packed_uploadsreads both packed 32-bit formats back from Metal across two source rows with padding, with swapping disabled and enabled. - Found on: DOOM 3: its light projection and falloff images are RGB565 stored big-endian, as issue #1180 found.
Smaller GL calls of an id Tech 4 renderer
glIsSync(a sync the layer made and has not deleted),glShadeModel(GL_SMOOTH; GLSL programs interpolate by their own qualifiers,GL_FLATis a red line),glClientActiveTexture(unit 0; no fixed-pipeline arrays),glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)(Metal's triangle fill mode, withGL_POLYGON_OFFSET_LINEas its offset enable; a masked clear always fills),GL_MAX_TEXTURE_COORDS(8),GL_MAX_UNIFORM_BLOCK_SIZE(65,536).GL_TEXTURE_LOD_BIASis the texture's sampler'slodBias(Metal 4, macOS and iOS 26, the host's minimum), clamped to ±15 asGL_MAX_TEXTURE_LOD_BIASsays: the layer used to drop it with a red line, from before Metal had it;t_gl_importsdraws a two-level texture 1:1 and reads level 1 with a bias of 1.- Found on: DOOM 3: it asks for these while it puts its GL state in order and sets a level's sync objects.
Fixed-function caps a GL 1.x renderer turns off
- Symptom:
[RED] glDisable(…) not implementedlines once each before the first draw —0x4000/0x4007(LIGHT0, LIGHT7),0xc60–0xc63(TEXTURE_GEN_S / T / R / Q) and, in a game that sets them,0xb57(COLOR_MATERIAL) and0xba1(NORMALIZE) — while the picture itself is right. - Cause: the fixed pipeline implements texture unit 0 and the alpha test, and
cap_setreports every cap it keeps nothing for, so a renderer written for GL 1.x, which puts the lights, the coordinate generators, colour material and normal normalization in order before its draws, got one line for each switch-off. A cap the layer implements nothing for cannot change a draw when it is switched off; only switching one on can (the shader or the fixed pipeline would have to honour it). - Fix:
cap_setignores the disable of the caps the fixed pipeline does not implement (GL_LIGHT0–7,GL_TEXTURE_GEN_S/T/R/Q,GL_COLOR_MATERIAL,GL_NORMALIZE) and still reports their enable, as theGL_LIGHTING/GL_FOGrule beside it already does. - Check:
t_gl_imports(test_fixed_function_caps) verifies that disabling each of the 14 caps is silent and a subsequent enable still logs a[RED]line for that cap. It checks that the supportedGL_ALPHA_TESTandGL_BLENDcaps still update their state. - Found on: Fate/stay night REMASTERED, which switches off
0x4000and0xc60–0xc63among others: five lines a run before the change, none after (the alpha test, lighting and fog it also switches off are implemented, or already ignored, onmain).
GLSL prefixes in main are no shaders
- Symptom: the NSP script translates
main#0andmain#1and stops at[RED] main#0 (…) does not translate: … 'discard' : not supported in this stage: vertex | … Missing entry point; the game gets no run-time shader capture. - Cause:
mainholds two#version 150strings that are not shaders but the prefix the renderer puts before the GLSL it generates (helper functions:clip,saturate,tex2D…, nomain).profile_guess.pytook any#versionstring for a shader source, so it decided the game's GLSL was all inmain. - Fix:
profile_guess.py(gl_sources, andglsl_sourceswith the sameGL_ENTRY) andgl_shaders.py(nso_strings) count a string as a shader only when it definesmain; DOOM 3 then gets its run-time capture. - Check:
test_profile_guess.pyandtest_gl_shaders.py. - Found on: DOOM 3.
Telling a GL game from an NVN or Vulkan one
- Symptom: the NSP script's provisional profile said Vulkan, and the capture boot crashed in the GL layer.
- Cause:
mainimportsvkGetInstanceProcAddrfor SDL's Vulkan loader, which nothing uses; the game draws with EGL and GL. - Fix:
profile_guess.pypicks GL whenmainimportseglCreateWindowSurfaceand namesglShaderSource. It treatsvkGetInstanceProcAddras Vulkan evidence on its own when the RomFS contains SPIR-V,mainhas no EGL window or NVN loader import, and no loaded NRO imports the NVN loader. Re:ZERO resolves every Vulkan entry point through this loader. - Found on: Digimon Story Cyber Sleuth: Complete Edition:
mainimportsnvnBootstrapLoaderand 13 EGL functions. Its graphics setup (main+0x5ed8f0) makes an NVN device first, which only a helper beside the movie player uses (main+0x528000–+0x52c400: a memory pool and four textures next to the movie's GL textures). TheneglGetDisplay,eglBindAPI(EGL_OPENGL_API), a 4.5 core context, a window surface onvi::CreateLayer(w, h)and a glad loader (main+0x52c460). Of the 22 games extracted here (at the time), only Digimon matches the rule. Balatro (SDK 18.3.2, LÖVE 11.4 on OpenGL with SDL and LuaJIT; one boot):mainimports the EGL functions andvkGetInstanceProcAddr, SDL's Vulkan loader, which nothing calls (subsdk1is NVIDIA's Vulkan driver); Hades and both Galaxies import 99 or 100 Vulkan functions,vkCreateInstanceamong them. - Note: Absolum imports the same EGL functions (SDL3) but renders with NVN and names no GL function.
GL function names in managed strings
- Symptom: the NSP script takes an EGL game for NVN and its shader split finds no shaders.
- Cause: the EGL game names
glShaderSourcein a UTF-16LE managed string. The detector only counted ASCII names. - Fix: the survey and packer both use
gl_name_countto recognize the two encodings on the existing EGL import path. The Vulkan and NVN precedence checks still apply. - Check:
test_profile_guess.pyexercises the survey with a managed name.test_gl_shaders.pyexercises pack-time detection with the same GL loader evidence. - Found on: Slay the Spire 1.0.
Draws from client memory
- Symptom: the game draws thousands of vertices per frame and the window shows text only; a sprite scene is black while its text layer is perfect.
- Cause: the draw reads its vertices from a client-memory array —
glVertexAttribPointerwith no buffer bound, which desktop GL allows and Metal does not. The layer keepsa->off = (uintptr_t)ptr; a->buf = S.array_buf;inh_glVertexAttribPointer, soa->buf == 0marks client memory, anddraw_setupused to drop such draws with one[RED] vertex attribute 0 reads client memory or a buffer with no data (not implemented)line. GameMaker's runner does exactly this for every sprite, background and screen composite; only its text path uses a realGL_ARRAY_BUFFER, which is why the text-only screens looked complete. - Fix:
draw_setupcopies the vertices a draw touches into a transientMTLBuffer(arena_alloc) and binds that instead. The block keeps vertex i at i × stride from its start, as the game's array does, so the draw's first vertex, its indices and its base vertex read the same vertices unchanged; only the range lo..hi is copied:first..first + countforglDrawArrays, the smallest and largest index plus the base vertex forglDrawElements(draw_span, which reads the indices only when a draw has a client-memory array, so draws from vertex buffers cost nothing more), and elements 0..⌈instances / divisor⌉ for a per-instance attribute. A bound buffer with no data still drops with[RED] vertex attribute %d reads a buffer with no data (%u), and a block over 128 MB is RED as well. Dropped draws are counted by reason in the layer's 300-frame line (dropped draws since the last record: … no program, … no pass, … no attribute buffer, … no pipeline). - Check: Well Dweller's dropped-draw counter (
frame … dropped draws since the last record: … no attribute buffer …) went from 11,885 to 0 and its draws from 274 to 22,577 per 300 frames, and the window then showed the same art as the game's own surface. - Found on: Well Dweller (GameMaker Studio 2, SDK 22.2.0). Any GameMaker title whose screens are mostly sprites will hit it; Balatro does not, because LÖVE queues every draw with its own buffers.
NVN in NROs under an SDL main that names GL
- Symptom: the NSP script took the game for an OpenGL one (
main imports EGL and names glShaderSource), the GL shader capture found no shader, and the capture boot stopped with[nvn-mtl] FATAL cannot read the shader mapfromh_nvnQueueSubmitCommandscalled in an NRO (nro8+0xc10d0). - Cause: Portal's
mainis SDL with its EGL video backend; it imports 20 EGL functions and namesglShaderSourcetwice (SDL's GL renderer), but imports no NVN and draws nothing. The renderer is in the Source engine NROs:materialsystem.nro(with the D3D9 layer linked in) andvideo_nx.nroimportnvnBootstrapLoaderand draw with NVN. - Fix:
profile_guess.pyshader_sourcesnow reads the imports of the loose NROs in the RomFS (romfs_nro_imports): when one importsnvnBootstrapLoader, the game is an NVN game whatevermainimports. Digimon keeps the GL rule: it has no NRO. The survey, which has only a RomFS manifest, called Portal 2 an OpenGL game and left GLSLC out of its modules untilnx_extract --manifestalso wrote the RomFS's NROs (romfs_nro/, 60 MB for Portal 2's 21) for it to read the same way. - Found on: Portal; Portal 2 (the survey).
NVN and its own GLSLC under a main that also links EGL
- Symptom: the NSP script took the game for an OpenGL one (
main imports EGL and names glShaderSource) and translated 2 GL shaders; the game boots with sound and answers input, but the window stays black, and the log has[nvn-mtl] [RED] shader … is not in the shader mapfor every shader it makes, with no EGL call at all. - Cause: the engine links both paths.
mainimports 14 EGL functions and namesglShaderSource, but also importsnvnBootstrapLoaderand 8 GLSLC functions (glslcCompileamong them, defined insubsdk2), holds 4 GLSL sources, and keeps the rest in its RomFS.shaderfiles (RIFFSHDR, agl43chunk with#version 450GLSL). On the Mac it draws with NVN and compiles every shader at run time with GLSLC; taken for OpenGL, it got no GLSLC capture. - Fix:
profile_guess.pyshader_sources: amainthat importsnvnBootstrapLoaderandglslcCompile, holds GLSL sources, and loads a module that definesglslcCompileis an NVN game whatever else it links, and gets the GLSLC capture as Three Houses does. Digimon keeps the GL rule (no GLSLC compile of its own); of 16 games extracted here (Super Mario Odyssey, Super Smash Bros. Ultimate, Metroid Dread, Hollow Knight: Silksong, Cuphead, DRAGON BALL FighterZ and others), only Rayman's decision changes.test_nro_graphics.pyhas both cases. - Found on: Rayman 30th Anniversary Edition (
01007C6025688000, 1.0.0, SDK 20.5.15, Digital Eclipse): the capture gets 21 shaders in 30 s, the split makes 42, and it plays with picture and sound at 60 fps.
Which GL functions a game calls
- Symptom: a jump to address 0 right after
glGetFloatv(0xb12)(lr=main+0x2d58c4). - Cause: a GL function the layer did not have (here
glVertexAttrib4fv, LÖVE's default colours). glad askseglGetProcAddressfor every name it knows; the functions the game really calls come from a census of the code's loads outside the loader (dm/tools/loader_census.py). Every other name gets a null pointer, and a jump to address 0 names nothing. - Fix:
DM_GL_STUBS=1gives every name the layer lacks a stub of its own that reports its first call instead;loader_census.pylists what the code calls before the first boot. The stubs andDM_GL_MISSESkeep a copy of each name, since a loader may put every name together in one buffer: with the game's pointer, every stub reported the last name asked. - Found on: Digimon Story Cyber Sleuth: Complete Edition: glad asks for 2,956 names and stores each in a global its code reaches through the GOT; a census of the GOT slots the code loads outside the loader gives the 79 functions the game calls: buffers, vertex arrays, textures (2D and cube, S3TC), framebuffers and renderbuffers, programs with plain
glUniform*,glDrawElements/glDrawArrays, and three compatibility calls (glTexEnvi,glColorTable,glPixelTransferi). No uniform buffers, instancing or buffer mapping. Balatro (SDK 18.3.2; one boot; the missingglVertexAttrib4fvabove): LÖVE's glad stores each pointer straight into a global of its own (no GOT slot per name), and the code reaches those globals through GOT entries that hold their addresses, which it often keeps in callee-saved registers across a loop, or picks between withcsel(glEnableVertexAttribArrayorglDisableVertexAttribArray).loader_census.pyfollows registers in a straight line for that (adrp, add, loads through relocated GOT entries,mov,csel): 2,133 names asked, about 150 called. Fate/hollow ataraxia REMASTERED (issue #2818):CRASH sig=11 addr=0 pc=0 lr=main+0x3bab70cwhen a new game starts isglValidateProgram, which the game calls through its pointer atmain+0x7317660right afterglLinkProgram(main+0x3bab6ec); the stubs named it,glLineWidth, which it calls before its draws, andglClearTexImage(GL 4.4), with which it clears a new texture to one value (lr=main+0x934f48, about 15 s in). The layer has all three: program validation, lines that stay one pixel wide (a red line for any other width), and texture clears of every face, layer and slice of the level. The census finds no loader in itsmain; it puts its names together in one buffer.
GL program validation records the result
- Symptom:
glValidateProgramreports success for a program that has never linked, or for differently typed samplers assigned to one texture unit. - Cause: the entry checked only the object name, and
GL_VALIDATE_STATUSalways returned true. - Fix: validation records a snapshot on the program: it needs a linked executable, valid active sampler units, compatible sampler types on each unit, and sampler counts within the advertised stage and combined limits. A failed validation explains why through
glGetProgramInfoLog; successful validation clears that log. Relinking resets validation, and changing uniforms does not change the last recorded result until the next validation. - Check:
t_gl_imports(test_program_validation,test_fate_calls): unlinked programs, sampler conflicts, valid and out-of-range units, the result's lifetime and the log. - Found on: synthetic cases while reviewing Fate/hollow ataraxia REMASTERED's missing entry.
GL texture clears convert values and keep command order
- Symptom: clearing RGBA8 with float RGBA
{1, 0, 0, 1}gives the first float's bytes instead of opaque red; clearing an attached framebuffer red and then its texture blue leaves it red. - Cause:
glClearTexImageused the upload converter's byte-copy path for unlike source and destination types, and wrote the texture while an earlier framebuffer clear was still deferred. - Fix:
clear_pixeldecodes the source format/type into components and encodes the texture's storage format, including normalization, missing components, channel order, packed and floating formats, and depth/stencil. This single value has no unpack state. NULL means storage zeroes, including alpha. Earlier framebuffer clears are encoded before texture writes, which then use the existing ordered upload path. - Check:
t_gl_imports(test_fate_calls): Metal readback of float-to-RGBA8, BGRA ordering, normalized single-channel data, byte-to-half-float, NULL, unpack-state independence and the two ordered clears. - Found on: synthetic readback cases while reviewing Fate/hollow ataraxia REMASTERED's new texture-clear entry.
GLSL source translated offline and found by hash
- Shaders are GLSL source compiled at run time with
glShaderSource/glCompileShader.gl_shaders.pytranslates them offline: glslang (-V -R: relaxed Vulkan rules gather the loose uniforms into onegl_DefaultUniformBlock, whose member offsets the table lists) → SPIR-V → SPIRV-Cross. The host finds each shader by the hash of its text and its stage. Varyings are matched by name, as GL links them:[[user(locnN)]]becomes[[user(<name>)]], so a vertex and a fragment shader translated apart still meet.--fixup-clipspacemaps GL's clip z to Metal's. - Found on: Digimon Story Cyber Sleuth: Complete Edition: GLSL ES 3.20 source, 1,682
.shadfiles in the MVGL archives (615 distinct) and 37 strings inmain(post effects, FXAA, shadows, the movie's YUV).
GLSL source files named .glsl
- Symptom: every draw is skipped:
[RED] … shader <key> (<n> bytes of GLSL) is not in the library (DM_GL_CAPTURE collects it),program <n>: a shader is missing from the library, its draws are skipped,draw with no usable program, and frame records ofdraws 0. The NSP script translated onlymain's strings and planned no capture, since those count as the game's GLSL. - Cause:
gl_shaders.pyread.vert/.fragfiles and MVGL archives, andprofile_guess.pycounted only those; the game compiles GLSL files named.glsl, as they are. - Fix: both read
.glslfiles too. The name says nothing of the stage, so a.glslfile is translated as each stage that compiles, as a string inmainis. No capture: the files are the shaders, byte for byte what the game compiles. - Found on: Mega Man Legacy Collection: six files in
shaders/nx/(the sprite, CRT and composite shaders, two vertex shaders with the same text), matched byte for byte against a capture. PR #2725 read them as shaders the game puts together at run time and turned the capture on with a profile key.
Standalone GLSL in .vs and .fs files
- Symptom: a game's RomFS contains the GLSL, but the packer starts a shader capture because it overlooks the
.vsand.fsfiles. - Cause: the files use libGDX's extensions. Other engines also use
.fsfor snippets that they combine with generated code. - Fix: the packer and translator use
paired_sourcesto inspect the extracted files. A directory must contain a text source definingmainfor each stage. The translator keeps the original source bytes through the first NUL so their keys match the runtime inputs. The survey has only a manifest, so it defers the decision to the pack step. - Check:
test_gl_shaders.pyexercises the packer and translator with valid pairs, snippets, an.fs-only directory, and separate directories whose names differ only in case. - Found on: Slay the Spire 1.0. Its 14 files yield 11 distinct shaders.
A function body closed with };
- Symptom:
gl_shaders.pyreportsdoes not translate: vert: glslang: ERROR: …: 'extraneous semicolon' : not supported with this profile: es, and the host skips that program's draws. - Cause: GLSL ES has no empty declaration at file scope, so a
;after a function's closing}is an error in glslang; NVIDIA's compiler accepts it. - Fix:
fixups()drops a;right after the}that closes a function body at file scope (a{opened right after a)), and leaves a struct's or a block's};. - Found on: Mega Man Legacy Collection: three of its six
.glslfiles endmainwith};. Reported in PR #2726. - Check:
test_gl_shaders.py.
A sampler the shader never reads
- Symptom: every sprite of a program samples black, while the textures are there; the shader's table row lists two samplers at one slot, such as
t:T0=0:sampler2D t:T1=0:sampler2D. - Cause: SPIRV-Cross leaves out of the MSL a sampler the shader never reads, but
--reflectstill lists it, with the binding glslang gave it, that of a used one. The host bound the unit the unused sampler names (an empty one: the black placeholder) over the used sampler's texture. - Fix:
gl_shaders.pylists only the samplers the MSL takes as[[texture(n)]]parameters. - Found on: Mega Man Legacy Collection:
default_ps.glsldeclaresT1for code under#if 0. Reported in PR #2727. - Check:
test_gl_shaders.py.
Inactive GL uniforms get locations
- Symptom:
glUniform4fvcrashes inuni_writewith a null source during startup. The game skips the upload whenglGetUniformLocationreturns-1. - Cause: SPIRV-Cross's default uniform block layout includes declared members the shader never reads. The shader table exposed all of them, so linking gave unused uniforms valid locations.
- Fix:
gl_shaders.pyuses glslang's active-uniform reflection to select the default block members it exposes. SPIRV-Cross still supplies their Metal offsets, array strides and block size. Rebuild the GL shaders to update the table. - Check:
test_gl_shaders.pychecks that unused uniforms and struct members are omitted and that active arrays and named blocks keep their layout. - Found on: Tomb Raider I–III Remastered 1.1.4 (issue #2416). The startup program gave
uJointsanduLightPoslocations even though neither shader stage read them.
GLSL that NVIDIA's compiler accepts and glslang does not
- Fix-ups on the preprocessed text: the GLSL ES 1.0 functions
textureCube/texture2Din ES 3.20 code (with-Vglslang readstextureCubeas Vulkan's texture type, so a macro cannot rename it),out vec4 gl_Positionredeclared through a macro, andtextureOffsetwith an offset that is not a constant, which becomes a plain sample at P + offset ÷ level 0 size. A string inmainsays nothing of its stage, so it is translated as each stage that compiles. - Found on: Digimon Story Cyber Sleuth: Complete Edition:
textureCube/texture2Din 89 fragment shaders; the redeclaredgl_Positionin the built-in sprite shader; the non-constanttextureOffsetin FXAA; one fragment shader string inmaindefinesvPositionasgl_Position. - GLSL 1.50 as DOOM 3's renderer writes it: built-ins redeclared as plain varyings (
out vec4 gl_Position;,in vec4 gl_FragCoord;,out float gl_FragDepth;) lose the declaration and keep the built-in;out vec4 gl_FragColor;becomes a plain output of the shader's own,dm_FragColor(Vulkan GLSL has nogl_FragColor); the compatibility colour declared as a varying,out vec4 gl_FrontColor;in the vertex shader andin vec4 gl_Color;in the fragment shader, which NVIDIA links as GL's fixed pipeline does, becomes one varying,dm_Color, matched by name;sampleras a name (its helpers takesampler2D sampler), a reserved word in Vulkan GLSL, becomesdm_sampler. A compatibility built-in the shader does not declare is left alone. - Found on: DOOM 3: all 62 shaders of its title and first level (
test_gl_shaders.pyhas a pair written in their form).
A GLSL ES 1.00 name that later GLSL takes
- Symptom:
gl_shaders.pyreportsdoes not translate: frag: glslang: ERROR: …: 'texture' : redefinition, and the scenes those shaders draw are black. - Cause: GLSL ES 1.00 shaders go through glslang as ES 3.10, where
textureis a built-in function andsamplea reserved word; ES 1.00 leaves both free as names (uniform sampler2D texture;). - Fix:
es100()renames them (dm_texture,gm_sample; atexture(call stays, since NVIDIA's compiler takes one in ES 1.00 too). Each translation records only the names it actually rewrites, includingsamplerinfixups(), and chooses a free generated name if the source already uses its preferred one. Table fields and Metal varying tags restore the original names through that map; genuine game identifiers such asdm_texturestay unchanged, including in versioned shaders. The host finds attributes, uniforms and samplers by the game's names, and the shader's key is the hash of the game's own source. - Check:
test_gl_shaders.py. - Found on: Fate/hollow ataraxia REMASTERED, issue #2818: 16 of its 78 captured fragment shaders; 13 of them translate now (62 shaders → 75), and the other 3 need a sampler slot above 15, which the table cannot name. The tables of Well Dweller (93 shaders) and Balatro (35) are the same row for row.
GL shaders put together at run time and captured
- Symptom: in a capture run every program links with no uniforms; the game's first
Shader:sendraises a Lua error and, on the Switch, its error handler quits (Any Lua error quits a LÖVE game). - Cause: LÖVE builds each source in Lua from its header, its built-in code and the game's
.fsfile. None of those programs can link at the start of a fresh capture, which begins without the packaged library. - Fix: Compile missing shaders during capture so LÖVE can link the program and write its uniforms.
- Found on: Balatro: the 35 shaders are all made before the first frame.
GLSL an id Tech 4 renderer makes on first use
- Symptom: a capture run that only boots or plays the game misses shaders:
[RED] … shader … is not in the library (DM_GL_CAPTURE collects it)once play reaches something the capture never drew. - Cause: id Tech 4's BFG renderer converts each render program of its
.resourcescontainers (renderprogs/<name>.vertex/.pixel) to GLSL the first time the renderer or a material uses it; no game file holds the GLSL. - Fix: the NSP script's capture run has the game convert every render program itself.
dm/gfx/tools/idtech4_programs.pyfinds the renderer'sFindVertexShader/FindFragmentShaderinmainfrom its code, not from addresses: the loader is the one function that takes the address of its GLSL cache pathrenderprogs\glsl\%s, its two callers are the per-stage loaders (by the stage they pass,0x8b31or0x8b30), the finders are the callers of one of them alone, and the manager is what the material parser loads intox0frommain's data before calling a finder. It lists every render program in the containers' tables. The host (DM_GL_RENDERPROGS,renderprogs_jobinhle_gl.m) calls each finder once per program on the rendering thread at the first swap after the game has compiled shaders of its own (the manager compiles its built-in programs while the renderer starts, before the first frame), and the game converts and compiles them as on first use, so the capture holds the game's own text. - Check:
test_idtech4_programs.py(a synthetic module laid out as the renderer's code, a synthetic container). - Found on: DOOM 3: 82 programs (42 vertex, 40 fragment) give 66 distinct GLSL texts, since some share their source; the capture has them all at the first frame, about 1 s into a headless boot. A run that played into the first level had 62 of them (all but
motionBlurandstereoInterlace), byte for byte the same.
Desktop GLSL 1.10 and 1.20 from runtime generators
- Symptom: captured desktop GLSL fails with
Desktop shaders for Vulkan SPIR-V require version 140 or higher, an undeclaredgl_TexCoordorgl_Color,cannot convert from 'const int' to 'temp highp float', orsampler/image : type requires declaration of default precision qualifieronsampler3D/texture3D. - Cause: legacy desktop GLSL (
#version 110/120/130) relies onattribute,varying,gl_FragColor,texture3D*, implicitint-to-floatconversions, and desktop samplers without ES precision qualifiers; promoting it to#version 310 esrejected desktop implicit conversions andsampler3D. - Fix: promote explicit desktop versions 110, 120 and 130 to
#version 450 core(while keeping unversioned /#version 100on#version 310 es) and rewritetexture3D/texture3DLod/texture3DProjinOLD_TEX. After preprocessing, make the front colors, fog coordinate and constant-index texture coordinates explicit, with matching names across stages. Constant-index fragment outputs keep their locations. - Limits: this covers the programmable varyings used by MojoShader and desktop
#version 120renderers. Fixed-function vertex inputs, back-face color selection and dynamically indexed legacy arrays are outside this path. - Found on: Timespinner 1.0.0 (PR #1864) and Darkest Dungeon (PR #2034, issue #3021).
Explicit sampler layout(binding) and GL_TEXTURE_SWIZZLE_RGBA
- Symptom: multi-planar movie shaders that declare
layout(binding = 0)/layout(binding = 1)without callingglUniform1isample every plane from texture unit 0 (green NV12 video), andglTexParameteriv(..., GL_TEXTURE_SWIZZLE_RGBA, ...)logs[RED] glTexParameter(0x8e46) not implemented. - Cause:
gl_shaders.pydid not record explicit GLSLlayout(binding = N)sampler units ingl_shaders.tsv, soglLinkProgramalways initialized every sampler to unit 0;hle_gl.mhandled individualGL_TEXTURE_SWIZZLE_R..Aparameters but not the 4-componentGL_TEXTURE_SWIZZLE_RGBAvector form. - Fix:
gl_shaders.pyrecords non-zero explicitlayout(... binding = N ...)sampler bindings as an optional fifth colon-separated field ont:rows (leaving unqualified samplers at 0, distinct from glslang--ambauto-assignments), andglLinkPrograminitializesu->unitfrom that field.glTexParameterivandglTexParameterfvapplyGL_TEXTURE_SWIZZLE_RGBAacross all four channels. - Check:
test_gl_shaders.pyandmake -C dm/gfx/tests GAME=010014E00DB56000 gl-imports gl-arguments. - Found on: Darkest Dungeon (PR #2034, issue #3021).
Embedded main GLSL or .glsl templates suppressing DM_GL_CAPTURE
- Symptom: an OpenGL game boots with audio and advancing frames but shows a black screen, logging only a few shader table entries (from
main) and[RED] vertex/fragment shader <key> is not in the library (DM_GL_CAPTURE collects it)for its game shaders. - Cause:
profile_guess.pyturnedgl_captureoff whenevermaincontained any embedded GLSL string (gl_src > 0) or the RomFS contained any.glslfilename by extension alone, andbuild_ipa_from_nsp.pydid not fall back to capture when offline.glslfiles failed to translate standalone or when a profile providedgl_capture.tsv. - Fix:
profile_guess.pyonly suppressesgl_capturewhen standalone RomFS shader files are present (ignoringgl_srcalone and requiring.glslfiles to definevoid main()), andbuild_ipa_from_nsp.pyhonorsgl_capture.tsvand falls back to MacDM_GL_CAPTUREwhen offline translation yields onlymain's embedded shaders or fails with no translated RomFS shaders. - Check:
test_profile_guess.py,test_gl_shaders.py, andtest_nsp_incremental.py. - Found on: Darkest Dungeon Complete (
01008F1008DA6000, issue #3021).
GL capture compiles missing shaders
- Symptom: a GL capture stops with
vs_flip_loc != -1inMOJOSHADER_glProgramViewportFlip. - Cause: a fresh capture starts without a Metal shader library. The loader needs a uniform location from the linked program before it creates the remaining shaders.
- Fix: the packer starts the Mac host with
DM_GL_CAPTURE_COMPILER. On the first use of a missing source hash and stage, the host runs the same GLSL translator and Mac Metal compiler used by the packer, then loads the function and its reflection. Linking, uniform writes and draws use the regular GL path. The host publishes each captured source after the compile attempt; the packer still builds the final libraries in a batch. - Check:
make -C dm/gfx/tests GAME=010029D00E740000 gl-argumentsexercises a fresh capture with legacy GLSL, compiler failure, rebinding an existing shader, uniform writes and GPU readback. - Found on: Timespinner 1.0.0 (PR #1864).
GL entry points required by FNA
- Symptom: FNA stops during startup with
NoSuitableGraphicsDeviceExceptionand namesglBlendColoras the first missing entry point. - Cause: FNA checks the loader's pointers for its GL device before it renders. The host lacked blend color, indexed masks, range draws, texture and buffer readback, occlusion queries, and framebuffer attachment queries.
- Fix: use Metal's dynamic blend color and reuse existing indexed drawing and pixel readback. Report the default attachment sizes consistently with EGL. Occlusion queries collect the Metal visibility count across the render passes they cover and wait only when a requested result is pending.
- Limits: texture readback covers RGBA8 and BGRA8 with RGBA unsigned-byte output for 2D textures and cube faces. Sample-mask state has no effect on the host's single-sample attachments. Query support here is for occlusion.
- Found on: Timespinner 1.0.0 (PR #1864).
The GL core profile and persistently mapped buffers
- LÖVE reads
GL_CONTEXT_PROFILE_MASK; on a core profile it streams vertices through persistently mapped buffers (glBufferStorage+glMapBufferRangeof a 3-frame ring, aglFenceSyncper frame andglClientWaitSyncthree frames later), on a compatibility one from client memory, which Metal cannot draw from. The layer answers core: the mapping is the sharedMTLBuffer's memory, a fence is the serial of the command buffer being recorded, and a wait on a fence of that command buffer commits it first. The shaders then come as#version 330 core. - Found on: Balatro.
GL uniforms, pipelines and attributes
- Uniforms are CPU copies per stage, set as bytes at a draw after they change; pipelines are cached per program by vertex layout, attachment formats, blend and colour mask; disabled vertex arrays read the attribute's current value (GL's default (0, 0, 0, 1) until
glVertexAttrib4f) through a constant-step buffer. WithoutglBindAttribLocationthe game's attribute index is the Metal one:glGetAttribLocationreturns the shader's own attribute numbers. With it, the layer maps each Metal input to the game's index at the link. - A GLSL
boolis auintin the SPIR-V block;gl_shaders.pykeeps the declared type, as LÖVE'sShader:sendtakes only a boolean for a bool. - Found on: Digimon Story Cyber Sleuth: Complete Edition (no
glBindAttribLocation); Balatro: LÖVE binds VertexPosition, VertexTexCoord, VertexColor and ConstantColor to 0–3 withglBindAttribLocationbefore each link, keeps VertexColor and ConstantColor as disabled arrays and sets their values withglVertexAttrib4f(the draw colour); it lists uniforms withglGetActiveUniform(types as GL enums, arrays asname[0]) and reads their initial values back withglGetUniformfv/iv.
GL active-attribute reflection
- Symptom: a managed loader gets a null
glGetActiveAttribdelegate, and calling it to enumerate the first linked program's vertex attributes throwsNullReferenceException. - Cause: the GL host had attribute locations and reflection metadata but did not expose
glGetActiveAttriborGL_ACTIVE_ATTRIBUTE_MAX_LENGTH. - Fix: both queries use the linked program's vertex table. The enumeration index identifies a table row independently of the bound location. The maximum length includes the terminating NUL. Invalid arguments use the host's GL error flag and leave the result buffers untouched.
- Check:
t_gl_importscalls the registered query after linking and checks count, maximum length, enumeration order, name truncation and errors. - Found on: Slay the Spire 1.0. libGDX's
ShaderProgramenumerates attributes through its MonoGame loader.
GL sampler objects
- Symptom:
UNIMPL glGenSamplers,glSamplerParameteri,glSamplerParameterf,glSamplerParameterfvat boot andUNIMPL glBindSamplerat the first draw; textures sample with their own parameters, not the game's. - Fix: the layer keeps the parameters a GL 3.3 sampler object holds (filters, wraps,
GL_TEXTURE_MIN_LOD/MAX_LOD, the LOD bias, the depth comparison, anisotropy, the border colour) in one struct,samp_p, both in a texture and in a sampler object;glTexParameter*andglSamplerParameter*set it through one function. A sampler bound to a unit (glBindSampler) replaces the texture's parameters for that unit; the texture's levels andGL_TEXTURE_MAX_LEVELstill bound the LOD. Metal samplers are shared, one per distinct set. The comparison's mode and function are kept apart, so a function set before the mode is no longer lost. - Found on: Mega Man Legacy Collection: one sampler object per unit, its filters and wraps set there and none on its textures. Reported in PR #2724.
- Check:
t_gl_imports(test_sampler_objects).
No uniform at location 0
- Symptom: a GL game's pictures are upside down (Mega Man Legacy Collection's warning and title screens), with no red line.
- Cause: GL allows location 0, but a game may take it for "not found": Mega Man Legacy Collection loads
u_flip's location and skips itsglUniform1fwhen it is 0 (main+0x77b28). The layer gave a program's first uniform location 0. - Fix: a location is (uniform index + 1) × 4096 + array element (
uni_loc,uni_ofinhle_gl.m), so none is 0, whatever the program. - Found on: Mega Man Legacy Collection. Reported in PR #2728.
- Check:
t_gl_imports(test_sampler_objectschecks a first uniform's location).
GL vertex attributes with a separate format and binding
- Symptom: the game ends right after EGL starts,
CRASH sig=11 addr=0 pc=0withlrinmain:eglGetProcAddressgave it a null pointer for a GL 4.3 call the layer lacked, which it stored and called. WithDM_GL_STUBS=1it runs on and names them:glVertexAttribFormat,glVertexAttribBinding,glBindVertexBuffer,glBindBufferRange,glMemoryBarrier, andglBindBuffer target 0x8a11(GL_UNIFORM_BUFFER); nothing is drawn. - Cause: GL 4.3 (
ARB_vertex_attrib_binding) splits a vertex array in two: an attribute holds its format, its offset within an element and the index of the buffer binding it reads; a binding holds the buffer, offset, stride and divisor, and every attribute on it follows when it changes. The layer kept one buffer, offset, stride and divisor per attribute, written byglVertexAttribPointer, so it had no place for a binding. - Fix:
dm/gfx/gl/hle_gl.mkeeps a vertex array as GL does: 16 attributes (vattr_t: format, relative offset, binding) and 16 bindings (vbind_t); a draw reads each attribute through its binding (vb_of), so there is one copy of the state.glVertexAttribPointeris GL's shorthand for a format, binding i and that binding's buffer (the array buffer at the call), offset and stride, its stride 0 made the format's packed size at the call (the effective stride), so another attribute on the binding or a later format keeps it;glVertexAttribDivisorfor binding i and its divisor. A game that only uses those two draws as before: each attribute is alone on its own binding. A stride of 0 inglBindVertexBufferis literal, every vertex reading the first element: the pipeline gets a constant fetch (MTLVertexStepFunctionConstant, as for a disabled array), which has no divisor, so the pipeline key leaves it out (vkey_set). A binding given no buffer is not client memory, which onlyglVertexAttribPointerwith no array buffer makes: a draw reading it is skipped with a red line.glDeleteBuffersclears the current vertex array's bindings of the buffer, as GL does. Out-of-range indices, relative offsets past 2047 and negative offsets or strides recordGL_INVALID_VALUE;GL_MAX_VERTEX_ATTRIB_BINDINGS(16) andGL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET(2047) answer.GL_UNIFORM_BUFFERis a generic target of its own, whichglBindBufferRangeandglBindBufferBaseset too; they also set the indexed binding a named uniform block reads (GL named uniform blocks).glMemoryBarrierdoes nothing: no shader writes, the buffers are shared memory, and the command buffers run in order. - Check:
make -C dm/gfx/tests GAME=<id> gl-imports(under the Metal debug layer): attributes following their binding in either order of calls, the effective stride of a pointer against a later format or a second attribute, the divisor's binding, client memory, a deleted buffer, the errors and limits, the uniform buffer target, and a binding's stride 0 drawn through the layer's own pipeline (three points reading three colours, or the first for all, at the binding's offset, with or without a divisor). - Found on: Fire Emblem: Shadow Dragon and the Blade of Light (
0100A12011CC8000, 1.0.0, SDK 10.4.0; its profile is PR #1366):glVertexAttribFormat(0, 2, GL_FLOAT, GL_FALSE, 0)andglVertexAttribBindingat setup,glBindVertexBuffer(0, buffer, 0, 8)every frame beside aglVertexAttribPointerfor the texture coordinates, a 4-byte uniform buffer no shader reads, andglMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT)every frame. With the change, by its author on an M4 Pro: 45 s boots through the logo, the intro and the title into attract mode, 0 red lines, one pipeline.
GL shaders and programs deleted while in use
- Symptom: a program whose shaders were deleted after
glAttachShaderand beforeglLinkProgramlogsprogram N: a shader is missing from the library, its draws are skipped, or links a shader of the wrong stage; draws afterglDeleteProgramof the current program logdraw with no usable program (0). - Cause:
glDeleteShaderfreed the shader at once and its name went to the nextglCreateShader, while a program keeps its shaders by name: a link then found no shader, or another one (a fragment shader as the vertex stage). In GL a shader deleted while attached is only flagged (GL_DELETE_STATUS1), keeps its name, and goes when its last program detaches it or is deleted. LikewiseglDeleteProgramfreed the current program and made none current, where GL keeps it in use until anotherglUseProgram.glDetachShaderwas not implemented. - Fix:
dm/gfx/gl/hle_gl.mcounts each shader's attachments (shader_t.refs; one shader per stage, a new one replaces and releases the old);glDeleteShaderof an attached shader setsdeleted, andshader_releasefrees it with its last attachment (glDetachShader, a replacing attach, the program's own end).glDeleteProgramof the current program setsprog_t.deletedandglUseProgramof another frees it (prog_free, which releases its shaders); any other program goes at once. BothGL_DELETE_STATUSqueries report the flag. A linked program already held what its link took (functions, shader tables, uniforms), so later attach, detach and delete calls leave it drawing as linked.make -C dm/gfx/tests GAME=<id> gl-importschecks the lifetimes through the real entry points. - Found on: no game: the report reproduced it in
t_gl_imports.m(an attached vertex shader deleted, then a new fragment shader took its name and the program's vertex stage resolved to it). Balatro takes the path without the symptom: when LÖVE makes its window again it deletes its first three default programs' shaders while they are attached, then the programs (DM_GL_LOG=1:DeleteShader 1 (attached: flagged)…DeleteProgram 7), so each shader now goes with its program; it never links after deleting a shader, and the title and the tutorial draw the same as before. - Check:
t_gl_importsalso links for real (shaders with their table entries): the linked program keeps both stages' code after its vertex shader is detached and deleted, a relink without that stage fails, and the same shader attached twice is counted once. A second shader of a stage replaces the first and says so once in a red line (desktop GL would link both; the shader tables have one per stage). Since then the layer keeps GL's error flag (glGetErrorreturned 0 always): the shader and program calls recordGL_INVALID_VALUEfor a name with no object,GL_INVALID_OPERATIONfor one of the other kind, a shader attached twice or detached when not attached, andglGetErrorreads and clears the first error since it was last called (one flag, as GL allows). A call or a value the layer does not implement records nothing and keeps its red line, and a link the library cannot serve still reports success (GL_LINK_STATUS), so no game is told of the host's own gaps; the first 8 errors are logged with the call.t_gl_importschecks each case, the first of two errors kept, the flag cleared by the read and left clear by calls that succeed. Balatro from a fresh save into its tutorial (75 s, frame 4,200) recorded none, so itsglGetErroranswered 0 as before. The other calls record nothing on purpose:glBindTexturemakes a texture for a nameglGenTexturesnever gave (as compatibility GL does), which a core context would refuse, and an enum the layer does not take cannot be told from one it does not implement; a game found to read errors there would take the samegl_error/ name check.
GL_RED and GL_RG uploads into four-channel textures
- Symptom: a movie's luma is sharp, but the picture is mostly grey with false colour and a green line near the bottom.
- Cause: Layton's movie player uploads its chroma plane with external format
GL_RG, typeGL_UNSIGNED_BYTE, and internal formatGL_RGB(main+0x2c0858). The host stored RGB as RGBA8 and read three source bytes per texel. The RGBA8 allocation and subimage path instead copied the two channels packed into four-byte destination rows. - Fix: the host expands RED and RG by texel and fills missing colour channels with zero and alpha with one. Both 2D upload entry points use the source type, row length, alignment and byte order. Wider source types use the existing typed pixel conversion.
- Found on: LAYTON'S MYSTERY JOURNEY, v65536 (PR #2955).
- Check:
t_gl_importschecks a padded two-row RG allocation, a byte-swapped 16-bit RED subimage, and float RG uploads into normalized and floating-point storage.
GL textures, swizzles and uploads
- Textures are made on first use from the levels given so far (Digimon's loader defines them level by level). An upload into a texture a pending command buffer may still read is a blit in command order; any other is a CPU write. Metal reads a channel a format lacks as 0 (alpha 1) as GL does, so only luminance / alpha formats get a swizzle: Metal refuses a swizzle on a texture that can be a render target (
Texture swizzling is not compatable with MTLTextureUsageRenderTarget, Digimon's first story scene). glTexStorage2Dmakes every level up front (mipmaps filled byglGenerateMipmapas a blit).glTexStorage3Dmakes 3D and 2D array textures. AGL_TEXTURE_SWIZZLE_*is applied when the texture is made (a swizzled texture cannot be a render target).- Found on: Digimon Story Cyber Sleuth: Complete Edition; Balatro: the game's images are mipmapped; LÖVE makes a 1x1 default texture of each type, 3D and 2D array among them; font glyphs are RG8 with a swizzle of R, R, R, G.
GL buffers orphaned, clears as load actions
glBufferDataon a buffer the GPU may still read gets a newMTLBuffer, as GL drivers orphan it. A whole-framebuffer clear becomes the next pass's load action; a scissored or masked one is a quad.- Found on: Digimon Story Cyber Sleuth: Complete Edition.
A pending GL clear follows the old attachment
- Symptom: scene layers disappear after the game clears a texture and changes the framebuffer's attachment without an intervening draw.
- Cause: a whole-framebuffer clear waits to become a Metal load action. The framebuffer name stays the same, so the clear can land on the replacement image.
- Fix: encode the pending clear before changing an attachment of that framebuffer. Unchanged attachments still allow the clear to fold into the next draw pass.
- Found on: Timespinner 1.0.0 (PR #1864). Empty layers were clearing the texture where the earlier layers had already been composed.
GL framebuffer sRGB conversion
- Symptom: an sRGB framebuffer object still converts colour writes and blend reads with
GL_FRAMEBUFFER_SRGBoff, or the game's window stays dark with it on. In Tomb Raider's Remastered opening cave, nearly the entire image is black. - Cause: Metal applies sRGB conversion through the render attachment's pixel format. The framebuffer object always drew through its original sRGB format, and the window always drew through its raw RGBA8 format. Tomb Raider enables conversion for an ordinary RGBA8 window with no EGL surface attributes.
- Fix: framebuffer objects with sRGB attachments use a linear view while conversion is off. The window uses an sRGB view while conversion is on and presents the stored bytes through its raw view. Changing the enable finishes deferred clears and the active pass before changing formats. New storage invalidates the cached views. Texture sampling keeps its own sRGB decoding, and alpha stays linear.
- Check:
make -C dm/gfx/tests GAME=0100217023F6C000 gl-importsreads pixels from framebuffer objects and the default window with conversion off and on, covering deferred and partial clears, draws, and destination blending. - Found on: Tomb Raider I–III Remastered report #2416, with the opening cave checked in Classic and Remastered modes. The game's startup crash came from inactive uniforms getting GL locations.
GL draws and framebuffers
- Batched quads share one 16-bit index buffer through
glDrawElementsBaseVertex; canvases bind GL_FRAMEBUFFER (read and draw), check completeness, discard depth and stencil after use (glInvalidateFramebuffer) and clear withglClearBufferfv.glBlitFramebuffer(colour, same size) andglReadPixels(RGBA8) are there for multisample resolves andCanvas:newImageData, which the game does not use. - Found on: Balatro.
GL integer vertex inputs and timestamp queries
- Symptom: the GL loader returns null for
glVertexAttribIPointer. A diagnostic run past that call also reaches missingglQueryCounterandglGetQueryObjecti64v. - Cause: the host registered only the floating-point attribute pointer entry point and the occlusion-query entry points.
- Fix:
glVertexAttribIPointeruses the existing unnormalized integer Metal formats and vertex-array bindings.glQueryCounter(GL_TIMESTAMP)ends the current Metal command buffer so its GPU completion time marks all work issued before the call. The 64-bit query read returns the result in nanoseconds. - Found on: Factorio 2.0.76. Its first integer attribute call jumps to address 0 from
main+0x9a89a8in the old host.
GL framebuffer draw and read buffers
- Symptom:
framebuffer attachment 0x8ce1 not implemented,glDrawBuffers of 2 buffers, thenINVALID_VALUEfromglColorMaskion draw buffer 1. - Cause: the host held one color image per framebuffer and conflated shader output location 0 with attachment 0.
- Fix: each framebuffer maps draw locations and its read buffer to up to eight attachments. Metal render passes and pipelines use the draw mapping and per-output write masks. Reads and copies use the selected read attachment. Whole clears use load actions, and masked or scissored clears keep their channel masks and rectangles.
- Found on: Factorio 2.0.76. The validation test reverses two color attachments and reads each after a masked clear.
GL sprite-atlas copies and readback
- Symptom: the game crashes at
main+0x9aa448in atlas loading, then on missing compressed-image queries and readback. The new-game route also callsglCopyTexSubImage3D. - Cause: the host lacked named image copies and compressed texture readback. The renderer stores one packed BC block in each texel of an integer color target. A copy into a compressed image must reinterpret those bytes and scale the destination region to blocks.
- Fix: the host maps unsigned integer image formats and blits matching images directly. For an integer texel and a same-size compressed block, it copies their raw bytes through a Metal buffer in command order. Compressed readback returns the blocks or samples the texture for RGBA8. Framebuffer copies can also write a 3D slice or an array layer.
- Found on: Factorio 2.0.76. A synthetic Metal check copies a BC3 block in both directions and reads the compressed bytes and decoded pixels.
GL texel buffer views
- Symptom: binding
GL_TEXTURE_BUFFERlogs an unsupported target and jumps to address 0 atglTexBuffer. After adding the view, tile transitions still render as black gaps. - Cause: the host lacks a typed view of the bound buffer. SPIRV-Cross generates a two-dimensional texture and
spvTexelBufferCoordby default, while the view is a native Metal texture buffer. - Fix: bind a typed Metal view of the GL buffer's current storage. Request native texture buffers in
gl_shaders.pysosamplerBufferreads the same resource type the host binds. - Found on: Factorio 2.0.76. The translated tile vertex shader now indexes the coordinate table directly and the shoreline renders across tile boundaries.
GL orientation through the lower-left origin
- The layer renders as GL does, bottom row first, through the NVN layer's lower-left origin (
mtl_set_origin_lower_left): flipped viewports, reversed winding, a flipped present. Scissor rectangles andgl_FragCoordneed no change, and render targets read back with GL's texture coordinates. - Found on: Digimon Story Cyber Sleuth: Complete Edition.
GL present paced by the swap interval
- Three window textures go through the NVN layer's present path (
mtl_ext_tex, as the Vulkan swapchain), paced by the swap interval in display-link ticks. - Found on: Digimon Story Cyber Sleuth: Complete Edition: the game sets the interval to 60 ÷ its frame rate before each swap: 1 at the title and in the DigiLab, 2 from the story's opening on.
GL movies decoded by the SDK's movie library
- Found on: Digimon Story Cyber Sleuth: Complete Edition: the USM movies' H.264 is decoded through the SDK's movie library (the host's decoder) into NV12 buffers (3,110,400 bytes a 1920x1080 frame); the game uploads the planes into a
GL_REDand aGL_RGtexture (twoglTexSubImage2Da frame) and converts YUV in its own shader (inmain,SamplerY/SamplerUV).
Image stores into an attachment of their own pass
- Symptom: an image-only fragment draw's writes disappear from the subresource also bound as its color attachment when the pass ends; other image layers retain their writes.
- Cause: a writable image or storage alias marked every attachment written, which retained the tile store. For a loaded color attachment with no raster output or clear, that store writes the old tile contents over the shader's image writes to the same texture. Disabling the unwritten-store optimization did not avoid this correctness fault.
- Fix (resolved in synthetic GPU tests; game validation open): track possible shader writes separately from color-tile writes. A loaded color attachment with possible image/storage writes and no tile writes uses
DontCareat pass end, independently of the optimization switches. Record physical color writes before resetting a merged pipeline's logical-output map; specialized fragments have conservative unknown outputs. Clear load actions and explicit clears executed in the current pass count as tile writes. A clear already landed in a standalone pass does not: marking it as a tile write retained a stale store over the following image-only draw (found while landing #808). Depth/stencil and non-loaded attachments retain their existing decisions. Mixed raster/clear and image writes to the same subresource are outside this proof and still retain the tile store. - Check:
make -C dm/gfx/tests GAME=<id> check_t_image_attachment_storeexecutes literal shaders through production draw replay and reads all four image layers on the GPU, with the unwritten-store optimization on and off. It also checks raster outputs, an earlier raster draw followed by an image-only draw, pending and explicit clears, a standalone clear before an image-only draw, unknown output reflection, a zero channel mask, a nativeDontCare-load control, and physical/logical output mapping. The standalone-clear case failed four checks before tracking the actual clear load action; all 120 checks pass with it.t_unwritten_storeadditionally preserves depth writes with a possible image alias. - Found on: DARK SOULS: REMASTERED, reported and diagnosed by Jacob-Tate in #187, with the original store fix in 34c7453. Independently reproduced with synthetic shaders on an Apple M2 Max, macOS 26.6; no local game or iOS validation.
Unwritten attachment stores without lookahead
- Symptom: read-only depth/stencil attachments are written back after every pass, and the periodic unwritten-store savings counter remains zero with the default configuration.
- Cause:
udc_note_drawandsd_finishreturned early whenDM_NVN_TBDRwas off (the TBDR mode has since been removed). This also disabled the local unwritten-attachment proof, although it does not depend on future sampled-texture readers. The broader lookahead remains disabled because it does not understand bindless readers. - Fix: collect per-pass write facts independently of the lookahead switch and omit only stores of attachments that were loaded and provably unchanged. Clears, depth writes, stencil writes and possible writable image/atomic/storage aliases conservatively retain stores, except for the mandatory image-only color-attachment rule. Lookahead, pass merging and cross-submission invalidation remain disabled.
DM_NVN_UNWRITTEN_DC=0disables optional unwritten-store savings; the image-write preservation rule stays active. - Check:
make -C dm/gfx/tests GAME=<id> check_t_unwritten_storeperforms real GPU readback against a store-all control and literal color/depth/stencil values, with lookahead disabled. It covers read-only depth/stencil, depth writes, stencil writes, pending clears, and writable images (including native image atomics) and both storage-buffer binding forms.t_unwritten_store --benchruns a synthetic 32-pass 1080p workload with balanced on/off order; it is not a game FPS measurement. - Found on: NieR:Automata US 1.0.3, during iPhone factory-combat performance investigation. The change passes the GPU proof and rendering regressions on Mac; iPhone gameplay benefit remains to be measured.
Masked color targets store back during depth-only draws
- Symptom: a depth prepass keeps a color target loaded with its channel mask set to zero. The attachment store ledger in
DM_NVN_GPUPROFstill includes the color target. - Cause:
udc_note_drawcounted a shader output or an enabled channel mask as a write. A raster write needs both. - Fix: use the draw's physical attachment write mask for the existing unwritten-store rule.
draw_color_writesmaps each physical attachment to its logical shader slot before the draw clears the pipeline's mapping. Unknown or specialized shader outputs are treated conservatively.DM_NVN_UNWRITTEN_DC=0provides the store-all control. - Check:
check_t_unwritten_storereads back color, depth and stencil from production draw replay. It checks store bytes and pixels for a masked output, a shader with no color output and a remapped color export. - Found on: The Legend of Zelda: Ocarina of Time.
iOS layouts: portrait, a half-folded Duo, iPad windows
- Symptom: portrait gameplay overlaps the touch controls, touch coordinates land outside the game picture, or a TV's picture renders at 4K again after a layout pass.
- Cause: the front end assumed a landscape screen with the controls over the whole view, so its picture and touch geometry did not follow a portrait screen (an iPad, an iPhone Duo's inner display) or a Duo's fold. On iPadOS the deprecated
UIRequiresFullScreenkept the game out of resizable windows, and a native rotation A/B on the iPhone Duo iOS 27.1 simulator showed that it also blocked upside-down portrait. - Fix:
dm/ios/Sources/DmLayout.hcomputes the picture and controls rectangles from the view's bounds, its safe area and UIKit's division region (UIHingeInteraction, iOS 27.1); front_ios.m lays the views out from them and DmGamepad.m its controls. Landscape keeps the overlay unless the hinge is half open over a horizontal division; portrait puts a fitted 16:9 picture above the controls, at the division or the midpoint. On a Duo in portrait only the top safe-area inset applies. Game touches map through the picture rectangle (with Fill, larger than the view), and a layout change releases held inputs. The phone's orientation list stays landscape (the Duo's inner display follows its bounds), the iPad's has all four and noUIRequiresFullScreen. While a TV shows the picture the phone is all controls (dm_layout_pad_only). The drawable's scale is set in one place,DmGameView layoutSubviews: the screen's pixels, at mostmaxPixelWidthacross, which the TV sets to 1920, so a later layout pass cannot undo the TV's 1080p cap. - Check: the Duo harness tests layout, hit targets, touches, the in-game menu's live settings and the drawable cap in the Simulator with synthetic host state. A physical Duo was tested by the PR #683 author on their fork; full-game tests on a physical iPad and a Duo with this repository's build are open.
- Found on: Pokémon Brilliant Diamond.
The picture laid out in the shape the game presents
- Symptom: with Picture shape at 1.43:1 (
DM_SCREEN_ASPECT) the game renders 1920x1344, but on an iPhone Duo in Fit (the default) the picture comes out smaller than the 16:9 one, with black bars on all four sides; it fills the screen only in Fill. On the Mac a click lands off the point under the pointer (it was mapped on a 16:9 rectangle of the window). - Cause: the front ends assumed a 16:9 picture. iOS sized the game's view to the largest 16:9 rectangle (
DmLayout.hdm_aspect_fit,dm_aspect_fill) and the present then fitted the 1.43:1 frame inside that 16:9 drawable (present_viewport), so the picture was fitted twice; the Mac's mouse-to-touch mapping (front_mac.m) used the same 16:9 rectangle. - Fix: the present reports the shape of the frame it draws (the layer's) whenever its width / height changes (
nvn_mtl.mpresent_now→front.hfront_picture_shape; every graphics API presents there). The iOS front end lays the game's view out in that shape (DmLayout.htakes it as a parameter: the overlay, the split, Fill and the TV alike), so a 1.43:1 picture fills a 1.43:1 screen in Fit and touches are normalized on the picture as drawn; the Mac maps the mouse on the picture's own rectangle. A 16:9 game reports 16:9 and keeps its layout, and a size change of the same shape (1280x720 handheld, 1920x1080 docked) is not reported. - Check: the Duo harness tests the taller picture in Fit, in Fill and on a wider screen, and the production root view following a reported shape and returning to 16:9. Not yet run on a device.
- Found on: Breath of the Wild and Animal Crossing: New Horizons with
DM_SCREEN_ASPECT=1.43.