Skip to content

Metal: overlap the CPU's next frame with the GPU's - #333

Merged
peiikai merged 19 commits into
beta_5from
metal-overlap
Oct 23, 2026
Merged

peiikai merged 19 commits into
beta_5from
metal-overlap

Conversation

@peiikai

@peiikai peiikai commented Oct 23, 2026

Copy link
Copy Markdown
Owner

The game waits every frame on its own just-submitted frame's fence. Metal honoured it with a full wait, so CPU and GPU ran in series. renderer_wait_seq now defers it one frame (at most two frames queued); LARECOMP_GPU_OVERLAP=0 turns it off.

The game's CPU rewrites some storage buffers (light / exposure lists) one frame ahead into memory the frame being drawn still reads. Those are read from a copy (a 16 MB ring in the guest heap range):

  • ranges a draw reads as storage are always copied;
  • compute-only ranges start in place with their pages write-protected; a CPU store marks them (and every range on that page) as copied for good; GPU outputs (skinning) stay in place;
  • level changes re-arm the watch and never demote a copied range.
    Switches: LARECOMP_OVERLAP_SNAP, LARECOMP_OVERLAP_WATCH, LARECOMP_LOG_BINDS; decision log [snap].

Results (M3 Max 5120x1440 MetalFX): CPU busy per frame 10.1 -> 3.2 ms at 2x, steady 60 at 2x; GPU-bound 4x 21.9 -> 29.8 fps. Base M6: steady 60 at 4K (was not holding 60), steady 30 at 8K. Colours, tiles and BowWow match overlap-off on overworld, interior and side-view routes.

Draft: merges with the Vulkan port and the RC plan.

🤖 Generated with Claude Code

peiikai and others added 13 commits October 22, 2026 15:00
…fence waited one frame late)

The game submits a frame, presents it and at once waits on that frame's fence (every nvnSyncWait is on the
newest submission, one call site), so a frame cost CPU + GPU time in series: an M3 Max at 5120x1440 with MetalFX
missed 60 fps with the GPU under half busy. nvnSyncWait now waits for the previously deferred fence and defers
this one, so the CPU builds frame N+1 while the GPU draws frame N (at most two frames queued, a complete fence is
never waited for). The frame timing counters, read a frame before their GPU time is known, report the latest
completed pair's GPU span; counters are kept host side instead of written late into the game's memory.
LARECOMP_GPU_OVERLAP=0: the wait on the fence's own submission, as before.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ironment)

LARECOMP_LOG_BINDS=1: per frame, the guest memory the GPU reads in place (vertex, index, storage buffers, compute
slots, data behind pointers in the uniforms of global-memory shaders) and which of those ranges the game rewrote
by the time the next frame is translated - what a deferred frame fence could race with; memory pools logged with
their flags. LARECOMP_SSBO_PROBE=1: each compute dispatch run synchronously, the storage slots it writes noted
per program. LARECOMP_ASYNC_SHOTS=<from>,<every>,<count>: window images copied on the GPU inside the present and
encoded to PNG on a background thread (build/aframes/), so no CPU wait changes what overlapping work produced.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…read from a copy

With the frame fence deferred, the game's tiled light / shadow lists (its CPU memcpys the list for the next frame
into the buffer the frame being drawn reads, alternating by frame - f_7000fe5960, found with the data watchpoint)
were overwritten while the GPU still read them: screen-aligned tiles without shadow or darkening, in most frames
at 8x4 render scale on an M3 Max. Storage buffer slots in pools the CPU can write are now bound to a copy taken at
translation, in a 16 MB ring at the top of the guest heap range (shaders address storage through the heap buffer;
the game's heap never reaches there). A copy is reused while the guest memory is unchanged (hash), so GPU-written
data stays coherent; the slots a compute program writes stay in place (learned from its first three dispatches,
run to completion), so draws binding its output as vertex data and later dispatches find it where the game put
it. Vertex and index binds starting inside a copied range read the copy. ~100 KB copied and hashed per frame.
LARECOMP_OVERLAP_SNAP=0: off; =2: compute slots always in place (test switches).
Also: LARECOMP_WATCH_ADDR=<lo>,<hi> arms the data watchpoint from the environment and logs each access with its
caller and frame; the diagnostics log buffer-to-buffer copies.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…s (BowWow's body)

A CsProg prepared on the start screen carries no code address of its own, so in the app every compute program
learned under the shared key 0 and took the first program's mask: the skinning outputs counted as inputs and were
snapshotted, and the draw binding them as vertex data read memory the GPU never wrote - BowWow's body missing with
the overlap on. The NVN program's code address keys the table now.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…etected and kept in place

The write masks come from a program's first three dispatches. A slot it writes only later had been snapshotted:
the write landed in the copy, so it shows there - once the dispatch's command buffer has completed, each compute
input copy is compared with the hash its snapshot was taken at (checked on later frames, never waited for); a
difference marks the slot written, retires the copy and logs "[metal] compute <addr> also writes slot N: now kept
in place" once per program and slot. A CPU rewrite changes the original instead and keeps the snapshot.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ter is detected and kept in place"

This reverts commit 79a216c. Its detections put the exposure and light-list
program's slots back in place in gameplay, where their CPU-ahead rewrite races again (a dark, saturated picture);
the code is c50a999's again.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…es, no program probes

The write masks learned from a program's first dispatches decided wrongly whenever those dispatches ran on other
data (the title screen: the exposure program looked like it wrote nothing; gameplay: it also modifies the
skinning outputs), and a mask can't say "copy this slot although the program writes it". Now each storage range
in a CPU-writable pool is probed on its first use in a level: for one frame every binder - compute slot, draw's
storage read - works on a copy, so the GPU can't touch the original; at the next use the original's hash tells:
changed, the CPU rewrites it (the light / exposure lists) and it stays copied; unchanged, it is GPU-only or static
(the skinning outputs) and stays in place, where draws binding it as vertex data from an offset find it. Probed
again on a level change or after 10 s unused; a range no compute slot binds moves to copied on any later change.
No wait anywhere; ~100 KB hashed and copied per frame.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…probed in

A new range entry was stamped with the previous frame, so a second binder in the probe frame - the exposure dispatch
and the draws reading the list the first dispatch wrote - rehashed an original the CPU had not had a frame to touch,
found it unchanged and settled the range in place for good; a compute-bound range in place is never hashed again,
so its CPU-ahead rewrite raced from then on: grid-aligned dark boxes on the beach sand at 4x on an M6 (gone with
the overlap off). Stamped with the probe frame, every binder of that frame shares the copy and the next frame's
use decides.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…on log per range

The hash probe can't see the CPU rewriting the light lists: standing still it writes the same bytes again, and the
boxes come from the GPU reading the list while it is rewritten (an M6 at 4x in the Mysterious Woods, the lists
there bound by draws only). On the title screen the probe also settled the lists in place for good. So a range a
draw reads as storage is copied for good - the compute dispatches that read or modify it work on the same copy -
and only ranges bound by compute slots alone are probed (the skinning outputs stay in place). Each range's
decision is logged once ("[snap] <addr>+<size> ...", the small per-object ranges capped).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…CPU store into it (write watch)

The lists are bound by compute slots alone over most of the overworld, where the exposure program is their only
reader, and no content hash can see the CPU rewriting them with the same bytes (an M6 at 4x: boxes while travelling).
So a range bound only by compute slots now starts in place with its pages write-protected (plat_protect); the first
CPU store into it faults, the handler (dispatch.c rt_fault_watch -> renderer_watch_fault) opens the page and marks the
range, and it is copied from then on. A store to a watched page outside any range only opens the page; pages are
armed again at the range's first bind of a frame. GPU outputs are never stored to by the CPU and stay in place.
A few pages and at most a few faults a frame; LARECOMP_OVERLAP_WATCH=0 falls back to the probe.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ed range on its page

Two holes the M6 showed inside Kanalet Castle and after leaving interiors: the probe-again on a level change (or
10 s unused) reset every range to the hash probe, which demoted the lists - already copied for a draw's storage read
or a caught store - back to in place "unchanged"; and the three lists share a 16 KB page, so the first store on it
opened the page for all of them and only the range holding the address was marked. Now the probe-again applies
only to the hash fallback (the watch off), a watched range just has its pages armed again, and a fault marks
every watched range on the opened page as possibly written (copied: the safe side).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… (as vk-overlap 4edc2f5)

dispatch.c keeps a function pointer, rt_fault_watch_hook(), that the backend registers when its watch turns on;
renderer.m registers renderer_watch_fault there. The weak reference is gone: an undefined weak function reference
doesn't link on Mach-O, and both backends now share one dispatch.c.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
peiikai and others added 4 commits October 23, 2026 01:54
…ffers beside it (BowWow as a companion)

BowWow's body as a companion indoors came apart into spikes with the overlap on. His skinning dispatch
(72a8da0000) writes four 22048-byte outputs per frame (two sets, by frame parity, interleaved in one array);
the CPU never stores into them, but reads them back every frame (f_700102d0f4: the chain) - a GPU output the
CPU consumes. One output's tail shares a 16 KB page with the dispatch's 12-byte parameter blocks (slot 5,
rewritten every frame), and c3580a8's rule - a fault marks every watched range on its page - took the page's
param stores for stores into the output: copied, the dispatch wrote the copy, the CPU kept reading the frozen
original and fed the stale positions back. Nothing on the GPU reads the outputs other than the dispatch itself
(no draw, no pointer, no storage slot: a frame dump and the data watchpoint showed only the CPU read).

Now the fault handler marks the range holding the store, and its page-mates only when that range is at least
256 bytes - the three lists are one contiguous allocation the CPU memcpys in one go (the big list's store opened
the page before the two small lists' stores, which is what c3580a8 covers); a store into a parameter block or
outside every range just opens the page. Verified: BowWow as a companion in the Quadruplets' house (intact in
every captured frame, on and off), Marin and the Rooster as companions indoors (on vs off identical), the
Mysterious Woods at 4x 8x4 (no boxes), the Kanalet route (castle, Ukuku Cave, Tail Cave, Marin's house, Mabe:
no boxes), Match and 2x at 60 fps with the fence wait at 0 and the same GPU time as off.

Also: the copy ring walks past live copies instead of remaking every copy at a wrap (the GPU's own writes into
a copy - the exposure program's into the lists - survive), copies unused for 10 s are released; the one-off
store rule (an initialisation store doesn't copy); diagnostics under LARECOMP_LOG_BINDS (the copy decisions say
whether the store was inside the range, GPU-written copies, the compute slot layout), LARECOMP_LOG_FAULTS=
<from>,<to> (every store fault with its range and storing function), LARECOMP_SAVE_MSL also dumps compute
programs, LARECOMP_WATCH_SIZE (a time-limited data watchpoint on a range of that size: note that a PROT_NONE
page the GPU touches stalls it for seconds), a per-frame mprotect cost line when it exceeds 2 ms, and the
LARECOMP_TEST_COMPANION=<1-4> hook (pets.c) that gives Link that companion two seconds into play.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…any presents the GPU still holds

For the rare black flash that comes with "[metal] nextDrawable blocked 1001ms" (the layer's timeout): the log line
now carries the frame, whether the call returned no drawable, and the number of present command buffers
committed but not completed (each holds a drawable), and a present that would show only the clear (no game image)
is logged. No behaviour change: a timed-out frame is still not presented (the window keeps the last image).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…checked when late, long drawable blocks always logged

For the intermittent stall seen in overlap runs (frames of 80-130 ms with the GPU idle, gpu wait 0, render cpu ~5 ms,
game cpu ~7 ms, persisting once started - abm_on from frame 4437, ab2x_on from 3991; also in an off run, ab4_off,
and in a 20:31 run before today's changes): each such frame came with "[vi] vsync timer late by ~90ms", i.e. the
vsync thread's 16.7 ms wait stretched to ~100 ms - the shape of macOS's timer coalescing for a thread without the
time-constraint policy while the app isn't frontmost. Not reproduced on purpose (taking the focus away with the
policy in place: a flat 60 for 11 minutes), so the next occurrence is made to explain itself at no cost otherwise:
- the late-vsync line now says whether the window had the focus and whether the thread's real-time policy still
  holds (thread_policy_get; when gone it is set again on the spot, and said so);
- the "[slow]" line adds queue wait (this thread waiting for the render thread), vsync/pace wait, presents, and
  the render thread's longest watched wait of the frame (rq_watch: nextDrawable, a GPU wait) - the fields that
  were missing when a frame's time added up to nothing;
- a nextDrawable block of half a second or more is always logged (the 20-line cap was used up by 30-60 ms
  blocks long before the 1 s timeouts of interest).
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…o snapshot table reset (one-frame dim)

The one-frame whole-screen dim (the screen at ~half brightness for one frame, twice three frames apart, on the
path by the Face Shrine - an M3 Max at any resolution, every ~18 s while running): the exposure program (72a8da6000)
keeps its adaptation state in the 2040-byte exposure list it reads and writes, and with the list copied it writes
the copy - the original never holds that state. Whenever the copy was remade from the original the picture showed
the stale exposure for a frame, one per list buffer (parity). What remade them: the snapshot table filled up -
hundreds of 64-byte per-object storage reads a frame from the game's per-frame pools (CPU_UNCACHED | GPU_UNCACHED,
0x12) at changing addresses, one entry each - and starting over re-decided every range ("new" bursts at frames
1097, 2179, 3358 of the user's log; 3283/3284 in the repro, dims at 3283 and 3286).

Now: a draw's storage read from a 0x12 pool is copied into the ring without a table entry (no churn); a full table
evicts the entry bound longest ago instead of dropping every entry; and a compute-bound copy keeps a pristine image
of what it was copied from, so a remake (the CPU changed the original) merges - a byte the GPU changed that the CPU
didn't keeps the GPU's value, everything else is the original's (the CPU's write wins where both changed, as in
place). The ring allocator is shared (ring_take). Verified on the Field_11L repro with every-frame captures:
before, two dips (54 vs 100 mean luminance) in 1100 frames; after, none, no table reset, 60 fps; off: none.

Also: LARECOMP_ASYNC_RAW=1 writes the async frame captures as raw RGBA (keeps up at 60 fps; build/lum.py finds
one-frame dips), and LARECOMP_DYN_COPY=1 (off by default) copies vertex and index ranges from 0x12 pools at
translation - the "[race] ... vertex" rewrites are real (per-frame effect geometry under the previous frame's GPU,
~25 KB a frame to copy) but not this flicker.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@peiikai
peiikai marked this pull request as ready for review October 23, 2026 18:55
peiikai and others added 2 commits October 23, 2026 13:57
…the link register there)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@peiikai
peiikai merged commit 340896c into beta_5 Oct 23, 2026
3 checks passed
@peiikai
peiikai deleted the metal-overlap branch October 23, 2026 19:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant