Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions dm/games/0400486024DEC000/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion dm/gfx/nvn/dmsh_chain.h
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
// Generated file (dm/gfx/tools/dmsh_chain.py --header): the B shader library translation chain version this source tree expects (default options), one for every game;
// the host loads only <library dir>/b-<V>/. Run dmsh_chain.py --header after changing the chain's tools and commit this file with the change
#define DMSH_CHAIN "cb2e91c138e3"
#define DMSH_CHAIN "ee91be81885f"
183 changes: 183 additions & 0 deletions dm/gfx/tests/test_dmsh_blend_zero.py
Original file line number Diff line number Diff line change
@@ -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 <metal_stdlib>\n#include <simd/simd.h>\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<uint4>(out.m_79), as_type<uint4>(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()
5 changes: 4 additions & 1 deletion dm/gfx/tools/dmsh_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {}, []
Expand All @@ -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'))
Expand Down
1 change: 1 addition & 0 deletions dm/gfx/tools/dmsh_fetch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]}
34 changes: 34 additions & 0 deletions dm/gfx/tools/dmsh_rewrite.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.<m> = dm_az(out.<m>); 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
Loading
Loading