From f67642dccda5545beea3662293c0d7ac05cc95ea Mon Sep 17 00:00:00 2001 From: humanperzeus <3029935+humanperzeus@users.noreply.github.com> Date: Tue, 10 Nov 2026 10:16:42 +0100 Subject: [PATCH] A NaN colour at alpha 0 is returned as 0, as NVIDIA's blender takes a zero factor: Ocarina of Time's white clouds over the ferns at the camera are gone (chain ee91be81885f) NVIDIA's blender takes a zero factor times anything as 0 (0 x NaN = 0 x Inf = 0, Direct3D's rule), so a pixel shader may write a NaN colour with alpha 0 under SRC_ALPHA / ONE_MINUS_SRC_ALPHA blending and the target keeps its value. Apple's blender multiplies as IEEE does, stores the NaN, and every later pass that reads the target spreads it. Ocarina of Time's half-resolution light shader 5ad65c0eefd09c7f averages hit positions over a fog layer whose density is 0 there (1/0 x 0); the fog pass carried the NaN into the scene and bloom made white clouds over the ferns at the camera. dmsh_rewrite.py blend_zero, called from dmsh_build.py after the entry points that share main0's body: main0 returns a non-finite rgb as 0 where alpha is exactly 0 (dm_az before each `return out;`). A finite output is never changed, the integer entry points (main0_u / main0_m, whose outputs are bits) are left as they are. The guard reaches the text the library is compiled from: dmsh_side.unit keeps a main0 that calls the shared body as it is, and main0's alpha test and logic operation versions and main0_f (dmsh_fetch.fold), which call the body themselves, take the same guard on their result (dmsh_side.az_cols / az_after). A library built without its extra entry points gets the guard in its plain source too (without_extras). Rebuilt on 80fc2ecb, which moved the MSL rewrites into dmsh_rewrite.py; the first version of this PR (review: the guard missed shared-body shaders in unit) is folded in. Tests: test_dmsh_blend_zero.py 12 (the 3 about the shared case fail against the first version), test_dmsh_side 6, test_dmsh_fetch 23, test_dmsh_meshstage 34, test_discard 4, test_dmsh_abi 11, test_dmsh_code_fp 8, test_docs 6, test_nsp_chain 17. Over Ocarina of Time's 22,352 pixel shaders (blend_zero, unit, fold on a full local build's sources): every float entry point reaches the guard in all 22,296 with a float colour output, no integer entry point touched. A full Mac build (42,848 shaders) with this change on 641636e2 compiles; at the spot, a recorded camera route shows clouds in 4 of 12 frames with the guard taken out of the two shaders and in 0 of 12 with it, the fog equally bright. --- dm/games/0400486024DEC000/README.md | 1 + dm/gfx/nvn/dmsh_chain.h | 2 +- dm/gfx/tests/test_dmsh_blend_zero.py | 183 +++++++++++++++++++++++++++ dm/gfx/tools/dmsh_build.py | 5 +- dm/gfx/tools/dmsh_fetch.py | 1 + dm/gfx/tools/dmsh_rewrite.py | 34 +++++ dm/gfx/tools/dmsh_side.py | 27 +++- docs/agents/symptoms.md | 1 + docs/reference/shaders.md | 9 ++ 9 files changed, 258 insertions(+), 5 deletions(-) create mode 100644 dm/gfx/tests/test_dmsh_blend_zero.py diff --git a/dm/games/0400486024DEC000/README.md b/dm/games/0400486024DEC000/README.md index a001444dbb..82acfbadc9 100644 --- a/dm/games/0400486024DEC000/README.md +++ b/dm/games/0400486024DEC000/README.md @@ -111,6 +111,7 @@ From an empty save: at about 45 s `A` (title), `A` (New Game), then the movie. F ## Found on this game +- [A NaN colour at alpha 0 under SRC_ALPHA blending](../../../docs/reference/shaders.md#a-nan-colour-at-alpha-0-under-src_alpha-blending): resolved, white clouds over the ferns at the camera in Kokiri Forest, coming and going as they swayed. The light shader `5ad65c0eefd09c7f` writes NaN at alpha 0 where its fog layer has density 0; NVIDIA's blender drops it, Apple's stored it. - [The 60 Hz link at 40 fps in fullscreen on a ProMotion screen](../../../docs/reference/frame-rate.md#the-60-hz-link-at-40-fps-in-fullscreen-on-a-promotion-screen): 40 fps in fullscreen on an M5 Pro MacBook Pro with the GPU at 10 ms of the 16.7, every present one 120 Hz refresh late and every other display-link tick skipped; the screen's fixed 60 Hz mode held 60.0 fps there and fullscreen now switches to it, with the 120 Hz link (59 fps) for screens with no such mode. - [The shader package and the shader map come from different splits](../../../docs/reference/packing.md#the-shader-package-and-the-shader-map-come-from-different-splits): resolved, a black screen with sound in a build through NX2Apple ([issue #1841](https://github.com/seedds/nxnative/issues/1841)); the present pass was translated from a terrain shader's record. Records now carry their keys, and the shader build finds them by key. - [Native mesh pipelines compiled at their first draw](../../../docs/reference/shaders.md#native-mesh-pipelines-compiled-at-their-first-draw): resolved. The foliage, shadows and enemies drawn with task and mesh shaders stalled at their first draw on a cold Metal cache (59.5 s of builds at the Kokiri Forest entry on an M5 Max, one frame of 42.9 s), as nothing recorded or kept their pipelines; `pso_manifest.tsv` now carries 164 `M` rows (Kokiri Forest, Hyrule Field, Castle Town, Hyrule Castle, and 41 from later play, Death Mountain Trail among it), and with the prepare step they are built before the first frame. Pipelines outside the list still stall once, then go into `pso_user.tsv`. With the first 123 alone, a cold first start (empty Metal cache and pipeline archive, M4 Pro) on a Death Mountain Trail save built 9 and 10 at their first draw in two runs, 2.7 and 4.2 s, frames of 1,775 and 1,657 ms; with all 164, none, worst frame 25.6 and 18.5 ms, the prepare step 29.6 and 29.3 s → 32.1 and 31.0 s. diff --git a/dm/gfx/nvn/dmsh_chain.h b/dm/gfx/nvn/dmsh_chain.h index ae4f248573..97776f84de 100644 --- a/dm/gfx/nvn/dmsh_chain.h +++ b/dm/gfx/nvn/dmsh_chain.h @@ -1,3 +1,3 @@ // Generated file (dm/gfx/tools/dmsh_chain.py --header): the B shader library translation chain version this source tree expects (default options), one for every game; // the host loads only /b-/. Run dmsh_chain.py --header after changing the chain's tools and commit this file with the change -#define DMSH_CHAIN "cb2e91c138e3" +#define DMSH_CHAIN "ee91be81885f" diff --git a/dm/gfx/tests/test_dmsh_blend_zero.py b/dm/gfx/tests/test_dmsh_blend_zero.py new file mode 100644 index 0000000000..4d25f79ba0 --- /dev/null +++ b/dm/gfx/tests/test_dmsh_blend_zero.py @@ -0,0 +1,183 @@ +"""A non-finite rgb at alpha 0 returned as 0 by main0 (dmsh_rewrite.py blend_zero), as NVIDIA's blender takes a zero factor times anything: every return of main0 guarded, the shared body +and the integer entry points left as they are, integer outputs never touched, a second pass a no-op, and the result compiled by Metal's compiler when it is there.""" +from pathlib import Path +import re +import shutil +import subprocess +import sys +import tempfile +import unittest + +TOOLS = Path(__file__).resolve().parents[1] / 'tools' +sys.path.insert(0, str(TOOLS)) +import dmsh_side # noqa: E402 + +import dmsh_fetch # noqa: E402 +import dmsh_rewrite # noqa: E402 +blend_zero = dmsh_rewrite.blend_zero + +HEAD = '#include \n#include \n\nusing namespace metal;\n\n' +# a light shader's shape as spirv-cross writes it: two colour outputs, an early return that writes zeros, a weighted average divided by its weight sum +PLAIN = HEAD + '''struct main0_out +{ + float4 m_79 [[color(0)]]; + float4 m_81 [[color(1)]]; +}; + +struct main0_in +{ + float4 m_83 [[user(locn0)]]; +}; + +fragment main0_out main0(main0_in in [[stage_in]], float4 gl_FragCoord [[position]]) +{ + main0_out out = {}; + float _631 = in.m_83.x; + float _633 = in.m_83.y; + if (_633 < 0.0) + { + out.m_79 = float4(0.0); + out.m_81 = float4(0.0); + return out; + } + float _727 = 1.0 / _633; + float _731 = _727 * _631; + out.m_79 = float4(_731, _731, _731, in.m_83.z); + out.m_81 = float4(_731, 0.0, 0.0, in.m_83.z); + return out; +} +''' + + +def shared_form(msl): # main0's body as dm_body_main0, main0 calling it, and an integer entry point calling it too (what fs_uint gives a shader that writes integer bits) + s = dmsh_side.shared_body(msl) + e = dmsh_side.entry(s, 'main0') + struct = 'struct main0_out_u\n{\n uint4 m_79 [[color(0)]];\n uint4 m_81 [[color(1)]];\n};\n\n' + return s + '\n' + struct + dmsh_side.calling(e, 'main0_u', 'main0_out_u', 'return main0_out_u{as_type(out.m_79), as_type(out.m_81)};') + + +def body_of(msl, name): + e = dmsh_side.entry(msl, name) + return msl[e['head']:e['end']] + + +def fn_body(msl, name): # an entry point's body found by its name alone (entries() refuses a unit's _a and _l, whose parameters take function constants) + m = re.search(r'fragment\s+\w+\s+%s\s*\(' % name, msl) + if not m: return None + b = msl.find('{', dmsh_side._close(msl, m.end(), '(', ')')) + return msl[b:dmsh_side._close(msl, b + 1, '{', '}')] + + +def unit_of(src): # what the library is compiled from: blend_zero on the build's file, then dmsh_side.unit (dmsh_build.py ps_libraries) + out, n = blend_zero(src) + u, info = dmsh_side.unit(out) + return u, info, n + + +class BlendZero(unittest.TestCase): + def test_every_return_of_main0(self): + out, n = blend_zero(PLAIN) + self.assertEqual(n, 2) + b = body_of(out, 'main0') + self.assertEqual(b.count('out.m_79 = dm_az(out.m_79); out.m_81 = dm_az(out.m_81);'), 2) + self.assertEqual(len(re.findall(r'\breturn\b', b)), 2) # the shape other stages check (one return, the last line) is kept + self.assertTrue(re.search(r'\n return out;\n\}$', b)) + self.assertEqual(out.count('float4 dm_az(float4 c)'), 1) + self.assertLess(out.index('dm_az(float4 c)'), out.index('fragment main0_out main0(')) + + def test_shared_body_and_integer_entry_untouched(self): + src = shared_form(PLAIN) + out, n = blend_zero(src) + self.assertEqual(n, 1) # main0 is the calling entry point: one return + self.assertIn('dm_az(out.m_79)', body_of(out, 'main0')) + self.assertNotIn('dm_az', body_of(out, 'main0_u')) # bits for an integer target stay bits + b = dmsh_side.body(out) + self.assertNotIn('dm_az(out', out[b[0]:b[2]]) + + def test_unit_keeps_the_guard_of_a_shared_main0(self): + # the library is compiled from dmsh_side.unit's text, not from the file blend_zero wrote: a shared main0 written again as a plain call of the body lost the guard + u, info, n = unit_of(shared_form(PLAIN)) + self.assertIsNotNone(u, info) + self.assertEqual(sorted(info['alpha'] + info['logic']), ['main0_a', 'main0_l', 'main0_u_a', 'main0_u_l']) + self.assertIn('out.m_79 = dm_az(out.m_79); out.m_81 = dm_az(out.m_81);', fn_body(u, 'main0')) + for name in ('main0_a', 'main0_l'): # main0's alpha test and logic operation versions call the body themselves + self.assertIn('dm_r.m_79 = dm_az(dm_r.m_79); dm_r.m_81 = dm_az(dm_r.m_81);', fn_body(u, name), name) + for name in ('main0_u', 'main0_u_a', 'main0_u_l'): # bits for an integer target stay bits + self.assertNotIn('dm_az', fn_body(u, name), name) + b = dmsh_side.body(u) + self.assertNotIn('dm_az(out', u[b[0]:b[2]]) + + def test_unit_of_a_plain_main0_guards_in_the_body(self): + u, info, n = unit_of(PLAIN) + self.assertIsNotNone(u, info) + b = dmsh_side.body(u) + self.assertEqual(u[b[0]:b[2]].count('out.m_79 = dm_az(out.m_79);'), 2) # main0's body is the body: every entry point that calls it gets the guard there + for name in ('main0', 'main0_a', 'main0_l'): + self.assertIn('dm_body_main0(', fn_body(u, name), name) + self.assertNotIn('dm_az', fn_body(u, name), name) # not twice + + def test_fold_main0_f_of_a_shared_main0(self): + u, info, n = unit_of(shared_form(PLAIN)) + f, meta = dmsh_fetch.fold(u, [], om_only_ok=True) + self.assertIsNotNone(f, meta) + self.assertIn('r.m_79 = dm_az(r.m_79); r.m_81 = dm_az(r.m_81);', fn_body(f, 'main0_f')) + u, info, n = unit_of(PLAIN) + f, meta = dmsh_fetch.fold(u, [], om_only_ok=True) + self.assertIsNotNone(f, meta) + self.assertNotIn('dm_az', fn_body(f, 'main0_f')) # the body it calls carries the guard + b = dmsh_side.body(f) + self.assertIn('dm_az(out.m_79)', f[b[0]:b[2]]) + + def test_without_extras(self): + # a library that does not build with its extra entry points is built from the source before them: a pixel shader's gets the guard there too + self.assertIn('out.m_79 = dm_az(out.m_79);', dmsh_rewrite.without_extras('ps', PLAIN)) + self.assertEqual(dmsh_rewrite.without_extras('vs', PLAIN), PLAIN) + + def test_integer_outputs_only(self): + src = PLAIN.replace('float4 m_79 [[color(0)]];', 'uint4 m_79 [[color(0)]];').replace('float4 m_81 [[color(1)]];', 'uint4 m_81 [[color(1)]];') + self.assertEqual(blend_zero(src), (src, 0)) + + def test_no_main0_out(self): + src = HEAD + 'kernel void main0(uint i [[thread_position_in_grid]]) {}\n' + self.assertEqual(blend_zero(src), (src, 0)) + + def test_second_pass_is_a_no_op(self): + once, _ = blend_zero(PLAIN) + self.assertEqual(blend_zero(once), (once, 0)) + + def test_return_not_on_its_own_line_refused(self): + src = PLAIN.replace(' return out;\n }', ' { return out; }\n }') + self.assertEqual(blend_zero(src), (src, 0)) # all or nothing: an unguarded return would let the NaN through on one path + + def test_guard_semantics(self): + # the helper's rule, evaluated on the CPU the same way: alpha exactly 0 and a non-finite channel -> 0; everything else unchanged + def az(c): + r, g, b, a = c + fix = lambda v: 0.0 if a == 0.0 and (v != v or v in (float('inf'), float('-inf'))) else v + return (fix(r), fix(g), fix(b), a) + nan, inf = float('nan'), float('inf') + self.assertEqual(az((nan, inf, 0.5, 0.0)), (0.0, 0.0, 0.5, 0.0)) + r = az((nan, 1.0, 2.0, 1.0)); self.assertTrue(r[0] != r[0]); self.assertEqual(r[1:], (1.0, 2.0, 1.0)) # alpha 1: the blender keeps a NaN too + self.assertEqual(az((0.25, -3.0, 7.0, 0.0)), (0.25, -3.0, 7.0, 0.0)) # finite at alpha 0: unchanged + self.assertIn('c.w == 0.0f', dmsh_rewrite.BLEND_ZERO) + self.assertIn('isnan(c.xyz) || isinf(c.xyz)', dmsh_rewrite.BLEND_ZERO) + + @unittest.skipUnless(shutil.which('xcrun'), 'no Metal compiler') + def test_compiles(self): + texts = [] + for name, src in (('plain', PLAIN), ('shared', shared_form(PLAIN))): + out, n = blend_zero(src) + self.assertGreater(n, 0) + u, info, _ = unit_of(src) + f, meta = dmsh_fetch.fold(u, [], om_only_ok=True) + texts += [(name, out), (name + '_unit', u), (name + '_fold', f)] # each text a library is compiled from + for name, out in texts: + with tempfile.TemporaryDirectory() as d: + p = Path(d) / f'{name}.metal'; p.write_text(out) + r = subprocess.run(['xcrun', '-sdk', 'macosx', 'metal', '-c', '-O1', '-fpreserve-invariance', '-fwrapv', str(p), '-o', str(Path(d) / f'{name}.air')], + capture_output=True, text=True) + self.assertEqual(r.returncode, 0, r.stderr[:500]) + + +if __name__ == '__main__': + unittest.main() diff --git a/dm/gfx/tools/dmsh_build.py b/dm/gfx/tools/dmsh_build.py index 483a874fa8..a3ca385c84 100644 --- a/dm/gfx/tools/dmsh_build.py +++ b/dm/gfx/tools/dmsh_build.py @@ -799,6 +799,9 @@ def finish(key, w, j, c1): shared = dmsh_side.shared_body(src) if fu or fd else None # they call main0's body; fs_uint and fs_dual give none for a main0 whose shape it does not know if shared: plain = src; open(msl, 'w').write(shared + (fu or '') + (fd or '')) else: fu = fd = None + if j['stage'] == 'ps': # main0 returns a non-finite rgb at alpha 0 as 0, as NVIDIA's blender takes a zero factor (see blend_zero); after the entry points that share main0's body + bz, nbz = dmsh_rewrite.blend_zero(open(msl).read()) + if nbz: open(msl, 'w').write(bz) try: binds = dmsh_reflect.reflect(key, mesh['kind'] if mesh else j['stage'], src, res) # before the compile: a pixel shader's readable-tile version needs its texture slots (ps_libraries) except ValueError as e: return 'reflection failed', str(e)[:160], None side, lost = {}, [] @@ -810,7 +813,7 @@ def compile_targets(): # the selected targets from the same MSL (MSL identical except subprocess.CalledProcessError as e: if not lay and not fu and not fd: return 'metal failed', str(e)[:160], None lost = [name for name, extra in (('layer', lay), ('integer output', fu), ('dual source', fd)) if extra] # kept in the reflection, as a cache hit compiles nothing: every build reports it (shader_regressions.report_losses) - open(msl, 'w').write(plain); lay = fu = fd = None # the layer, integer-output and dual-source entry points are extras: a library that does not build with them is built without + open(msl, 'w').write(dmsh_rewrite.without_extras(j['stage'], plain)); lay = fu = fd = None # the layer, integer-output and dual-source entry points are extras: a library that does not build with them is built without try: compile_targets() except subprocess.CalledProcessError as e: return 'metal failed', str(e)[:160], None clone(msl, os.path.join(out, key + '_b.metal')) diff --git a/dm/gfx/tools/dmsh_fetch.py b/dm/gfx/tools/dmsh_fetch.py index c3c33fb971..cd8675b531 100644 --- a/dm/gfx/tools/dmsh_fetch.py +++ b/dm/gfx/tools/dmsh_fetch.py @@ -267,4 +267,5 @@ def fold(msl, bindings, om_only_ok=False): put = ''.join(f' if (OM_{j}_{k}) out.{n}_at{k} = r.{n};\n' for j, (t, n, c) in enumerate(outs) for k in range(NFB)) main0_f = (f'\nstruct main0_out_f\n{{\n{members}}};\n\n{e["attr"]}fragment main0_out_f main0_f({", ".join(e["params"] + fbs)})\n{{\n' f'{load} main0_out r = dm_body_main0({args});\n main0_out_f out = {{}};\n{put} return out;\n}}\n') + main0_f = dmsh_side.az_after(main0_f, 'r', dmsh_side.az_cols(msl)) # a main0 that calls the shared body guards its result (dmsh_rewrite.py blend_zero): main0_f calls the body too return lead + sig + ''.join(out_parts) + text[pos:] + rest + main0_f, {'calls': calls, 'mixed_regs': mixed, 'outputs': [{'color': c, 'type': t} for t, n, c in outs]} diff --git a/dm/gfx/tools/dmsh_rewrite.py b/dm/gfx/tools/dmsh_rewrite.py index 817109885d..ef8c65d7f4 100644 --- a/dm/gfx/tools/dmsh_rewrite.py +++ b/dm/gfx/tools/dmsh_rewrite.py @@ -495,3 +495,37 @@ def frag_z_snap(msl): body = f'\n float {ZSNAP_WIDTH} = fwidth(gl_FragCoord.z);' + '\n'.join(lines) # in uniform control flow, before anything the body does msl = msl[:first] + body + msl[end - 1:] return msl.replace('using namespace metal;\n', 'using namespace metal;\n\n' + ZSNAP, 1), n + + +# A colour output's rgb where its alpha is exactly 0 and the rgb is not finite. NVIDIA's blender takes a zero factor times anything as 0 (Direct3D's rule: 0 × Inf = 0 × NaN = 0), so a pixel +# shader may leave garbage in the colour of a pixel it means to add nothing to and say so with alpha 0: with SRC_ALPHA blending the target keeps its value. Apple's blender multiplies as IEEE +# does (0 × NaN = NaN), stores the NaN, and every later pass that reads the target spreads it. +# Ocarina of Time's half-resolution light shader 5ad65c0eefd09c7f averages hit positions over a fog layer whose density is 0 there (a positive hit count, a weight sum of 0: 1/0 × 0 = NaN; its +# FMULs carry no .FMZ, so the translation is exact) and writes them with alpha 0 into an RGBA16F light target blended SRC_ALPHA / ONE_MINUS_SRC_ALPHA. The fog pass carried the NaN into the +# scene and bloom turned each into a white cloud over the ferns at the camera, coming and going as they swayed across the fog volume's surface. +# So main0, the entry a pipeline with float colour targets takes, returns a non-finite rgb as 0 where alpha is 0: a finite output is never changed, and neither are the integer entry points +# (main0_u / main0_m: dm_body_main0, dmsh_side.shared_body), whose outputs are bits. Outside SRC_ALPHA blending the change only touches outputs that were NaN or Inf already. +# The guard has to reach the library, not only this file. When main0 calls the shared body, dmsh_side.unit keeps main0 as it is, and main0's alpha test and logic operation versions and +# main0_f (dmsh_fetch.fold), which call the body themselves, take the same guard (dmsh_side.az_cols); a library built without its extra entry points is built from the plain source with +# the guard as well (without_extras) +BLEND_ZERO = ('static inline __attribute__((always_inline)) float4 dm_az(float4 c) // see blend_zero\n' + '{\n return c.w == 0.0f ? float4(select(c.xyz, float3(0.0f), isnan(c.xyz) || isinf(c.xyz)), c.w) : c;\n}\n') +def blend_zero(msl): + """→ (msl with each `return out;` line of main0 preceded by out. = dm_az(out.); for its float4 colour outputs and BLEND_ZERO before main0, the number of returns guarded). + Unchanged (0) when main0 has no float4 colour output, is not of a shape dmsh_side.entry knows, or returns other than on a line of its own""" + st = re.search(r'struct main0_out\s*\{(.*?)\};', msl, re.S) + cols = [nm for ty, nm, at in re.findall(r'^\s*(\w+)\s+(\w+)\s*(\[\[[^\]]*\]\])?;', st.group(1), re.M) if ty == 'float4' and 'color(' in at] if st else [] + if not cols or 'dm_az(' in msl: return msl, 0 + try: e = dmsh_side.entry(msl, 'main0') + except ValueError: return msl, 0 + if not e or e['ret'] != 'main0_out': return msl, 0 + body = msl[e['head']:e['end']] + n = len(re.findall(r'\breturn out;', body)) + guard = ' '.join(f'out.{c} = dm_az(out.{c});' for c in cols) + body, k = re.subn(r'^([ \t]*)return out;$', lambda m: f'{m.group(1)}{guard}\n{m.group(1)}return out;', body, flags=re.M) + if not k or k != n: return msl, 0 + return msl[:e['start']] + BLEND_ZERO + msl[e['start']:e['head']] + body + msl[e['end']:], k + + +def without_extras(stage, plain): # the source a library that does not build with its extra entry points is built from: a pixel shader's with blend_zero's guard, as with them + return blend_zero(plain)[0] if stage == 'ps' else plain diff --git a/dm/gfx/tools/dmsh_side.py b/dm/gfx/tools/dmsh_side.py index 0d9f26f620..fed22261d6 100644 --- a/dm/gfx/tools/dmsh_side.py +++ b/dm/gfx/tools/dmsh_side.py @@ -62,6 +62,24 @@ def entry(msl, name): # one entry point as entries() gives it, None when there # and each entry point is a module of its own in the library anyway (metallib) _BODY = re.compile(r'static (__attribute__\(\(always_inline\)\) )?main0_out dm_body_main0\(') BODY = 'static __attribute__((always_inline)) main0_out dm_body_main0(' +# dmsh_rewrite.py blend_zero guards what main0 returns (out. = dm_az(out.); before each return). When main0 calls the shared body, the guard sits in main0, not in the body, as the +# integer entry points call the body too and their bits must stay bits. Every other float entry point that calls the body itself (main0's alpha test and logic operation versions, here, and +# main0_f, dmsh_fetch.fold) then takes the same guard on its own result (az_cols, az_after) +_AZ = re.compile(r'\bout\.(\w+) = dm_az\(out\.\1\);') + + +def az_cols(msl): # the colours blend_zero guards in a main0 that calls the shared body, in order; [] when main0 does not call it (the guard is then in the body) or has none + try: e = entry(msl, 'main0') + except ValueError: return [] + if not e: return [] + b = msl[e['head']:e['end']] + return list(dict.fromkeys(_AZ.findall(b))) if 'dm_body_main0(' in b else [] + + +def az_after(text, var, cols): # text with the guard on var's colours after its first `main0_out = dm_body_main0(...);` + if not cols: return text + g = ' '.join(f'{var}.{c} = dm_az({var}.{c});' for c in cols) + return re.sub(r'(\bmain0_out %s = dm_body_main0\([^;]*\);)' % re.escape(var), lambda m: m.group(1) + ' ' + g, text, count=1) def body(msl): # dm_body_main0's definition: (its start, the end of its parameter list, the end of its body), None when there is none @@ -95,12 +113,15 @@ def unit(msl) -> tuple[str | None, dict]: if not all(alpha.values()): alpha, no_alpha = {}, 'an entry point without a colour 0' # the host needs one for each of the shader's own (at_fn) logic = {e['name'] + '_l': o for e in es if (o := None if no_logic else dmsh_logic.entry(msl, e))} if not alpha and not logic: return None, {'why': no_alpha or no_logic or 'no colour output'} - thin = [a for a in alpha.values() if a] + [o[0] for o in logic.values()]; targets = set().union(*(o[1] for o in logic.values())) + shared = bool(_BODY.search(msl)) # main0 already calls dm_body_main0 (shared_body): it is kept below as it is + az = az_cols(msl) if shared else [] # blend_zero's guard after main0's call of the body: main0's own alpha test and logic operation versions call the body and take it too + thin = [az_after(a, 'dm_r', az) for a in alpha.values() if a] + [az_after(o[0], 'dm_r', az) for o in logic.values()]; targets = set().union(*(o[1] for o in logic.values())) src, at = [], es[0]['start'] - shared = bool(_BODY.search(msl)) # main0 already calls dm_body_main0 (shared_body): it is made again below as it is for e in es: src += [msl[at:e['start']]] + ([] if shared and e['name'] == 'main0' else [f'static {e["ret"]} dm_body_{e["name"]}({e["decl"]})', msl[e['head']:e['end']]]); at = e['end'] - plain = [f'{e["attr"]}fragment {e["ret"]} {e["name"]}({", ".join(e["params"])})\n{{\n return dm_body_{e["name"]}({e["args"]});\n}}\n' for e in es] + # each entry point as a call of its body; a shared main0 as it is, with what blend_zero put after its call of the body (written as a plain call it lost the guard) + plain = [msl[e['start']:e['end']] + '\n' if shared and e['name'] == 'main0' else + f'{e["attr"]}fragment {e["ret"]} {e["name"]}({", ".join(e["params"])})\n{{\n return dm_body_{e["name"]}({e["args"]});\n}}\n' for e in es] return msl[:es[0]['start']] + dmsh_alpha.HELPER + dmsh_logic.HELPER + dmsh_logic.constants(targets) + ''.join(src) + msl[at:] + '\n' + ''.join(plain + thin), {'alpha': list(alpha), 'logic': list(logic)} diff --git a/docs/agents/symptoms.md b/docs/agents/symptoms.md index f8e2d11d6a..9e68120425 100644 --- a/docs/agents/symptoms.md +++ b/docs/agents/symptoms.md @@ -904,6 +904,7 @@ One line per symptom in the [subsystem references](../reference/): what you see - rows of dark dots along contour lines of alpha-tested surfaces drawn after a depth pre-pass (Tears of the Kingdom: the stone lattice in front of the Great Sky Island start, as reported by MacNativeGames ae8f4f4; not reproduced here). On Switch 2, GPU time: every covered pixel of a shader that writes memory was shaded (PRAGMATA's cabin on an M4 Pro: GPU 19.0 ms a frame, p95 frame 64 ms, a quarter of the frames over 33 ms). → [Early fragment tests from the control section](../reference/shaders.md#early-fragment-tests-from-the-control-section) - a simulation or filter that reads neighbouring texels misbehaves though every constant is right. In the translated MSL a variable is declared with no value and read at once (`int _139; int _141 = _139;`), used as a coordinate. On Ocarina of Time: grass whose blades shift at 10 Hz, with a 6-frame cycle in the depth buffer and a wind velocity texture of strong stripes. → [Dead-code removal dropped a coordinate of a multi-output instruction](../reference/shaders.md#dead-code-removal-dropped-a-coordinate-of-a-multi-output-instruction) - the ground kept stale 32×32 blocks where the G-buffer draw failed the depth test: blocks of a stale image where a depth pre-pass and a later pass with other vertex shaders meet (Odyssey: 32×32 blocks on every fourth frame). With mesh shaders: white shapes on plants for single frames, at other places each frame while the leaves move (Ocarina of Time). → [Position invariance across shaders](../reference/shaders.md#position-invariance-across-shaders) +- white clouds over near geometry, coming and going as it moves (Ocarina of Time: over the ferns at the camera in Kokiri Forest, while they sway). The scene target holds NaN pixels after a fog or lighting pass and bloom spreads each into a white blot; dropping that pass removes them. → [A NaN colour at alpha 0 under SRC_ALPHA blending](../reference/shaders.md#a-nan-colour-at-alpha-0-under-src_alpha-blending) - dark specks flickering in a ground mist, a few pixels each, at different places every frame (Ocarina of Time in Kokiri Forest; the console shows none). Dropping the mist removes them, as does dropping its depth-only pass. → [gl_FragCoord.z against the depth stored for its own surface](../reference/shaders.md#gl_fragcoordz-against-the-depth-stored-for-its-own-surface) - making a pipeline archive prints `Max Unstruct ID 758 in function agc.main in shader 13941 exceeds supported limit`, and one pipeline takes many minutes, in `metal-tt` offline or in the host's prebuild on the device (`Preparing pipelines` holding one count for minutes). The line is a note, not an error: `metal-tt` goes on, exits 0 and writes that pipeline into the archive. → [Front end at -O1: Apple's control-flow lowering](../reference/shaders.md#front-end-at--o1-apples-control-flow-lowering) - the shader build prints `fatal error: bracket nesting level exceeded maximum of 256` and `.metal: does not compile`, and the shader is left out. → [Bracket nesting past the front end's 256](../reference/shaders.md#bracket-nesting-past-the-front-ends-256) diff --git a/docs/reference/shaders.md b/docs/reference/shaders.md index 7092689d33..2069ea4215 100644 --- a/docs/reference/shaders.md +++ b/docs/reference/shaders.md @@ -760,6 +760,15 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md) (Mac): the foliage in Kokiri Forest is drawn twice by two different mesh shaders, a depth pre-pass (depth LESS, no colour) and a colour pass with depth EQUAL and no depth write. Pixels where the colour pass missed EQUAL showed white for one frame; how the white reaches the picture was not traced (the scene target's clear value, alpha 0, is the likely source). Without the mark the wrapper's position was a plain `[[position]]`. With it: no flashes in five 121-frame windows on an M4 Max (14 on main), none in 240 frames at a flashing flower on an M4 Pro. - **Note:** ruled out on the way: the TBDR optimizations, same-pass feedback, the present path. Evaluating the game's conditional rendering on the CPU from earlier frames' results made it worse (the condition belongs to the same frame on the GPU), so the host still ignores the condition there and draws. +### A NaN colour at alpha 0 under SRC_ALPHA blending + +- **Symptom:** white clouds over near geometry, coming and going as it moves (Ocarina of Time: over the ferns at the camera in Kokiri Forest, while they sway). The scene target holds NaN pixels after a fog or lighting pass and bloom spreads each into a white blot; dropping that pass removes them. +- **Cause:** a pixel shader writes a NaN colour with alpha 0 into a target blended SRC_ALPHA / ONE_MINUS_SRC_ALPHA, its way of adding nothing to that pixel. NVIDIA's blender takes a zero factor times anything as 0 (Direct3D's rule: 0 × Inf = 0 × NaN = 0), so the target keeps its value. Apple's blender multiplies as IEEE does (0 × NaN = NaN) and stores the NaN, which every later pass reading the target carries on. The NaN itself is the game's arithmetic and translated exactly: Ocarina of Time's light shader averages hit positions over a fog layer whose density is 0 there, a positive hit count with a weight sum of 0 (1/0 × 0), and its FMULs carry no `.FMZ`. +- **Fix:** `dmsh_rewrite.py` `blend_zero`, called from `dmsh_build.py`: `main0`, the entry point a pipeline with float colour targets takes, returns a non-finite rgb as 0 where alpha is exactly 0 (`dm_az` before each `return out;`). A finite output is never changed; the integer entry points (`main0_u` / `main0_m`, which call `dm_body_main0`) are left as they are, their outputs being bits. Outside SRC_ALPHA blending the rule only touches outputs that were NaN or Inf already. The guard has to reach the text the library is compiled from: when `main0` calls the shared body, the guard sits in `main0`, so `dmsh_side.unit` keeps that `main0` as it is, and the entry points that call the body themselves (`main0_a`, `main0_l`, and `main0_f` from `dmsh_fetch.fold`) take the same guard on their result (`dmsh_side.az_cols`). A library built without its extra entry points gets the guard in its plain source too (`without_extras`). +- **Check:** `python3 dm/gfx/tests/test_dmsh_blend_zero.py`: every return of `main0` guarded, the shared body and the integer entry points untouched, a second pass a no-op; through `dmsh_side.unit` and `dmsh_fetch.fold`, every float entry point of a shared and of a plain shader reaches the guard and the integer ones do not; each text compiled by Metal's compiler. Over Ocarina of Time's 22,352 pixel shaders, the guard reaches every float entry point of the compiled text in all 22,296 that have a float colour output (before this, 9,265 shared-body shaders missed it). +- **Found on:** [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md) (Mac): the half-resolution light shader `5ad65c0eefd09c7f` (a mesh-drawn fog volume, pass 59 of the frame) wrote NaN into its RGBA16F light target in 17,000 to 20,000 pixels, the fog composite `888c1068ac8f7043` carried it into the R11G11B10F scene (70,998 NaN pixels in one frame) and bloom made the clouds. With the rule in that shader alone, 0 of 12 frames of the same replay showed a cloud (8 of 12 before), the fog kept its brightness. +- **Note:** found with `DM_NVN_SNAPRAW` and `DM_NVN_TEXSNAP` (raw floats of every colour target after chosen passes of one frame), then the one shader instrumented in a folder beside the library (`DM_MSL_DIR`; the host reads a file from the folder before the image): the first NaN at `1/w × v` with `w = 0`. Ruled out on the way: the fog volumes (finite, increasing slice by slice), FMZ handling (none in the code), stale uniforms (`DM_NVN_UB_DEFER=0`, `DM_NVN_UBP_CHECK`: 14,000 shadows equal), the depth test (every shaded pixel legitimately in front). The console's blender rule is inferred from Direct3D's, not measured on the console here. + ### gl_FragCoord.z against the depth stored for its own surface - **Symptom:** dark specks flickering in a ground mist, a few pixels each, at different places every frame (Ocarina of Time in Kokiri Forest; the console shows none). Dropping the mist removes them, as does dropping its depth-only pass.