Files
Triforce-Source/nx2/oot_patches.py
ruckus7382sfgsgdf fb26495475 Triforce v0.5.2
The new launcher (Windows and Linux: the game's own look, music and settings, saves and mods pages, smaller updates in parts), benchmark mode (Find my best settings: the game tours four places by itself and writes its results), Quit and Restart in the pause menu under Mods, Squadala! in the Mods menu, battle music above 60 fps, menu text, the controller in the menus with the game in the background, the whole GameBanana list, RX 580 and RX 5000/6000 shader fixes, the pipeline cache kept through an update, async present black flashes, and faster builds.
2026-11-19 10:52:50 -06:00

1068 lines
65 KiB
Python

"""Changes to the lifted C for Ocarina of Time, applied by lift.py after it writes the code (and by hand: python -I nx2/oot_patches.py).
Each is a runtime switch where it can be, so the game's own path stays reachable.
- Dynamic resolution (Lichii's built-in "Max Resolution" patch, main+0x805BD0): the engine's config flag at +0x94 picks the path that
follows the GPU-time controller; with hos_fixed_resolution set it takes the other path, the 3D at full scale. The controller made
a new set of render targets at each size, ~11 images a frame at times, and held the GPU near its budget.
- Text speed (the Insert menu's "Text speed"): f_80b1e140 (main+0xafe140) steps a text pane's letter animation, the
LetterAnimControl of the panes with "LetterAnimOn" user data (dialogue, Navi, signs). Its time argument (s0) moves the
letters' clock (+0x60 += rate +0x4c * time, the rate from the message's speed tag) and the pauses' timer (+0x58 -= time);
hos_text_scale multiplies it, 1.0 as shipped. The auto-advance timer (+0x5c, before) keeps the game's time. A huge
scale shows a page at once (one frame per pause), as the game's own skip on A (+0x72 = 2, f_80794b00) without its flags.
- The fixed path's scale (hos_fixed_scale_bits: the Insert menu's Resolution) reaching the 3D, in the caller f_831f3200
(main+0x31d3200). It recomputes the 3D's scale (+0xe5c = scale * +0xe58 / +0xe50) only while +0xe2c bit 3 is set. The dynamic
path sets it on a level change; the fixed path's flag 1 calls f_831f41d0, whose bit 3 the apply block clears in the same frame,
before any recompute. So the fixed path kept the dynamic path's last scale (0.75 docked: 1536x864 at every setting). Flag 1 now
also asks for the recompute, and on the fixed path the flags +0xe20 bits 3/4 (a hardcoded 0.75 / 0.5 in place of the scale)
are not looked at.
- The OptimizeChangeBank thread's allocations tried again when their heap is full (host/oot_heap_retry.c): f_804566e0's two
calls of f_80522050, its GPU memory (GPU_ALLOC_SITES), and its two tryAllocs of CPU buffers (HEAP_ALLOC_SITES). They went on
with a null pointer and crashed writing through it (issue 1697). The supported build only.
"""
import glob
import os
import re
import sys
import whole_write # (rewrites written beside and moved over: issue 1197)
DECL = "extern volatile int hos_fixed_resolution;\nextern volatile int hos_dynres_runs;\nextern volatile uint32_t hos_fixed_scale_bits;\n"
OLD = "if (!((c->x[8] >> 0) & 1)) { goto L_8082640c; }"
NEW = "if (hos_fixed_resolution || !((c->x[8] >> 0) & 1)) { goto L_8082640c; }\n hos_dynres_runs++;"
LABEL = "L_8082640c:;"
SCALE_OLD = "c->x[9] = 0x3f800000ULL;"
SCALE_NEW = "c->x[9] = hos_fixed_scale_bits;" # (the fixed path's scale, 1.0 as shipped)
DECL2 = "extern volatile int hos_fixed_resolution;\nextern volatile uint64_t hos_res_module;\nextern volatile uint32_t hos_fixed_scale_bits;\n"
APPLY_OLD = "L_831f3efc:;\n c->x[9]=recomp_load32(c,c->x[20] + 3628);"
APPLY_NEW = "L_831f3efc:;\n if (hos_fixed_resolution) { /* (only while +0xe5c is not the chosen scale: a recompute every frame remade the targets) */\n union { uint32_t u; float f; } now = {(uint32_t)recomp_load32(c,c->x[20] + 3676)}, want = {hos_fixed_scale_bits},\n e50 = {(uint32_t)recomp_load32(c,c->x[20] + 3664)}, e58 = {(uint32_t)recomp_load32(c,c->x[20] + 3672)};\n const float d = now.f - (e50.f != 0 ? want.f * e58.f / e50.f : want.f);\n if (d > 1e-4f || d < -1e-4f) c->x[8] |= 8;\n }\n c->x[9]=recomp_load32(c,c->x[20] + 3628);"
FLAGS_OLD = "L_831f3f08:;\n c->x[8]=recomp_load64(c,c->x[20] + 3616);\n"
FLAGS_NEW = FLAGS_OLD + " hos_res_module = c->x[20];\n if (hos_fixed_resolution) c->x[8] &= ~0x18ULL;\n"
def fixed_scale(t):
"""The fixed path's scale reaching the 3D (the Resolution row). (t, 1) when applied here"""
if APPLY_OLD not in t or FLAGS_OLD not in t:
return t, 0
t = t.replace(APPLY_OLD, APPLY_NEW, 1).replace(FLAGS_OLD, FLAGS_NEW, 1)
return t.replace('#include "a64.h"\n', '#include "a64.h"\n' + DECL2, 1), 1
TEXT_DECL = "extern volatile float hos_text_scale;\n"
LIFE_BUILD_ID = "e0f3ccfaf50065ae4ea01eb5aeb13b1a45da3348"
LIFE_HEAD = "void f_804bd8c0(Ctx *__restrict A64_NOESC c) {\n"
MOVE_HEAD = "void f_82c415e0(Ctx *__restrict A64_NOESC c) {\n"
MOVE_ANCHOR = ("if (((c->x[8] >> 1) & 1)) { goto L_82c41748; }\n")
MOVE_MATRIX = "L_82c41778:;\n"
WARP_HEAD = "void f_806d2530(Ctx *__restrict A64_NOESC c) {\n"
WARP_ANCHOR = "{ uint64_t _t = c->x[8]; c->x[30] = 0x806d25c8ULL; A64_ICALL(c, _t); }\n"
VIEW_HEAD = "void f_804e48c0(Ctx *__restrict A64_NOESC c) {\n"
# (the head of the view's loop: a bare label, since nx2/poll.py puts the interrupt poll before each backward goto; with the
# poll after the label in C lifted before that)
VIEW_ANCHORS = ("L_804e5068:;\n", "L_804e5068:; A64_POLL(c);\n")
LIFE_CAS = ("{ uint64_t _a = c->x[13]; uint32_t _e = (uint32_t)c->x[11]; "
"__atomic_compare_exchange_n((uint32_t *)A64_PTR(_a), &_e, (uint32_t)c->x[12], "
"0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); A64_MARK(_a, 4); c->x[11] = (uint64_t)_e; }")
def patch_life(source):
start = source.find(LIFE_HEAD)
if start < 0:
return None
end = source.find("\n}", start)
if end < 0 or source[start:end].count(LIFE_CAS) != 2:
return None
# x19 is the actor. Confirm its type and life pointer before protecting this write.
guard = (" if ((uint32_t)c->x[12] < (uint32_t)c->x[11] && hos_oot_hearts_enabled() &&\n"
" hos_oot_is_player(c, c->x[19]) &&\n"
" c->x[13] == recomp_load64(c,c->x[19] + 7184) + 8)\n"
" c->x[12] = c->x[11];\n")
body = source[start:end].replace(LIFE_CAS, guard + LIFE_CAS)
return (source[:start] + body + source[end:]).replace(
'#include "a64.h"\n', '#include "a64.h"\nextern int hos_oot_hearts_enabled(void);\n'
'extern int hos_oot_is_player(Ctx *c, uint64_t actor);\n', 1)
def patch_movement(source):
start = source.find(MOVE_HEAD)
if start < 0:
return None
end = source.find("\n}", start)
if end < 0 or source[start:end].count(MOVE_ANCHOR) != 1 or source[start:end].count(MOVE_MATRIX) != 1:
return None
bypass = (" hos_oot_lift_player(c, c->x[19]);\n"
+ MOVE_ANCHOR)
body = source[start:end].replace(MOVE_ANCHOR, bypass, 1).replace(
MOVE_MATRIX, MOVE_MATRIX + " hos_oot_flight_pose(c, c->x[19], c->x[25]);\n", 1)
source = source[:start] + body + source[end:]
return source.replace('#include "a64.h"\n', '#include "a64.h"\n'
'extern void hos_oot_lift_player(Ctx *c, uint64_t actor);\n'
'extern void hos_oot_flight_pose(Ctx *c, uint64_t actor, uint64_t matrix);\n', 1)
def patch_flight_rotation(source):
start = source.find(WARP_HEAD)
if start < 0:
return None
end = source.find("\n}", start)
body = source[start:end]
if end < 0 or body.count(WARP_ANCHOR) != 1:
return None
body = body.replace(WARP_ANCHOR, " hos_oot_flight_rotation(c, c->x[0], c->x[1]);\n" + WARP_ANCHOR)
return (source[:start] + body + source[end:]).replace(
'#include "a64.h"\n', '#include "a64.h"\n'
'extern void hos_oot_flight_rotation(Ctx *c, uint64_t controller, uint64_t matrix);\n', 1)
def patch_view(source):
start = source.find(VIEW_HEAD)
if start < 0:
return None
end = source.find("\n}", start)
body = source[start:end]
if end < 0:
return None
for anchor in VIEW_ANCHORS:
if body.count(anchor) == 1:
break
else:
return None
body = body.replace(anchor, anchor + " hos_oot_free_view(c, c->x[20]);\n")
return (source[:start] + body + source[end:]).replace(
'#include "a64.h"\n', '#include "a64.h"\nextern void hos_oot_free_view(Ctx *c, uint64_t view);\n', 1)
# Native mouse look (host/mouse_native.c): the player camera's update, f_80644c80 (a virtual method, the camera in x0), hands
# its camera to the host before anything else, on the game's thread, once a frame; with the menu's Mouse camera on the mouse's
# motion turns the camera's yaw (+0x1a4) and pitch (+0x18c) there, before the camera reads its input.
CAM_HEAD = "void f_80644c80(Ctx *__restrict A64_NOESC c) {\n"
def patch_mouse_camera(source):
start = source.find(CAM_HEAD)
if start < 0:
return None
if "hos_mouse_camera(c->x[0]);" in source: # (made before: a lift patched again)
return source
at = start + len(CAM_HEAD)
source = source[:at] + " hos_mouse_camera(c->x[0]); /* (nx2/oot_patches.py: native mouse look) */\n" + source[at:]
return source.replace('#include "a64.h"\n', '#include "a64.h"\nextern void hos_mouse_camera(uint64_t camera);\n', 1)
MENU_FOCUS_HEAD = "void f_802ed660(Ctx *__restrict A64_NOESC c) {\n"
def patch_menu_focus(source):
"""f_802ed660, a menu screen's handler of a pane getting the focus (host/oot_menu.c), calls
hos_oot_menu_focus first, with the screen, the pane and its caller's return address"""
start = source.find(MENU_FOCUS_HEAD)
if start < 0:
return None
if "hos_oot_menu_focus(c," in source: # (made before: a lift patched again)
return source
at = start + len(MENU_FOCUS_HEAD)
hook = " hos_oot_menu_focus(c, c->x[0], c->x[1], c->x[30]); /* (nx2/oot_patches.py: the menus' focus) */\n"
return (source[:at] + hook + source[at:]).replace(
'#include "a64.h"\n', '#include "a64.h"\nextern void hos_oot_menu_focus(Ctx *c, uint64_t screen, uint64_t pane, uint64_t lr);\n', 1)
MENU_TICK_HEAD = "void f_802f1380(Ctx *__restrict A64_NOESC c) {\n"
def patch_menu_tick(source):
"""f_802f1380, a menu screen's update (each frame, before the screen's UI controller: +56, its vtable's
+16), calls hos_oot_menu_tick first with the screen: the game's menus' mouse (host/oot_menu.c)"""
start = source.find(MENU_TICK_HEAD)
if start < 0:
return None
if "hos_oot_menu_tick(c," in source: # (made before: a lift patched again)
return source
at = start + len(MENU_TICK_HEAD)
hook = " hos_oot_menu_tick(c, c->x[0]); /* (nx2/oot_patches.py: the menus' mouse) */\n"
return (source[:at] + hook + source[at:]).replace(
'#include "a64.h"\n', '#include "a64.h"\nextern void hos_oot_menu_tick(Ctx *c, uint64_t screen);\n', 1)
MOD_SIZE_CALL = "c->x[30] = 0x801b64e4ULL; f_836e3d30(c);\n"
MOD_SIZE_HOOK = (" c->x[0] = hos_mods_table_size(c->x[0], recomp_load64(c, c->x[29] + 24));"
" /* (nx2/oot_patches.py: room for the mods' files, host/mods.c) */\n")
def patch_mod_sizes(source):
"""((Triforce) 11-17) f_801b6340 asks the ResourceSizeTable (RESTBL, f_836e3d30: the CRC of the path, a binary search) how
much memory a file's load needs; the file's resource heap is made that size (f_801b6840). A mod's file served instead of the
game's (host/mods.c) can need more than the table gives it: a model with more materials and shapes than the original fails
its gsys::ModelResource allocations, which the game does not check (the Dark Link mod's Deku Shield and Slingshot: a write
to address 0 on loading a child save). The host raises the size for a mod's file to its real size and room beside it
(hos_mods_table_size); the game's own files keep the table's"""
if MOD_SIZE_CALL not in source:
return source, 0
if "hos_mods_table_size(" in source: # (made before: a lift patched again)
return source, 1
out = source.replace(MOD_SIZE_CALL, MOD_SIZE_CALL + MOD_SIZE_HOOK, 1)
out = out.replace('#include "a64.h"\n', '#include "a64.h"\nextern uint64_t hos_mods_table_size(uint64_t size, uint64_t path);\n', 1)
return out, 1
TEXT_HEAD = "void f_80b1e140(Ctx *__restrict A64_NOESC c) {"
# (the letters' block: past the early returns, the auto-advance timer and the hidden / no-text checks; reached once a call)
TEXT_OLD = ("L_80b1e1b4:;\n"
" c->x[9]=recomp_load16(c,c->x[19] + 110);\n"
"if ((uint32_t)c->x[9] == 0) { goto L_80b1e18c; }\n")
# (the same block in a build with interrupt polls: nx2/poll.py puts the poll before each backward goto, as a block)
TEXT_OLD_POLLED = TEXT_OLD.replace("{ goto L_80b1e18c; }", "{ { A64_POLL(c); goto L_80b1e18c; } }")
TEXT_ADD = (" if (hos_text_scale != 1.0f) { float _t; uint32_t _u; memcpy(&_t,c->vreg[0],4); _t *= hos_text_scale; "
"memcpy(&_u,&_t,4); a64_vset64(c->vreg[0],_u); } /* (nx2/oot_patches.py: text speed) */\n")
TEXT_NEW = TEXT_OLD + TEXT_ADD
def patch_dynres(s):
if OLD not in s:
return None
s = s.replace(OLD, NEW, 1)
at = s.index(LABEL)
scale = s.index(SCALE_OLD, at)
s = s[:scale] + SCALE_NEW + s[scale + len(SCALE_OLD):]
return s.replace('#include "a64.h"\n', '#include "a64.h"\n' + DECL, 1)
# The frame's real time in place of the nominal rate, for a Frame rate cap above 60 (host/nn_vi.c hos_frame_seconds_bits; 0, as
# at a cap of 60: the game's own divide, nothing changes). The engine has two places where its integer nominal rate (+0x2c8 of
# the graphics module) becomes a time step, both a float divide "base / nominal":
# - f_80706be0: the frame's step, base 60.0 (30.0 in the half-rate mode), added to the game clock (the double at
# [x19+0xd58], in 1/60 s) and handed on as the frame's seconds;
# - f_83b6ea90: the global step (60.0 / nominal, a float in .data) the rest of the engine reads.
# The engine's own rate is 60 / <whole display intervals>, never above 60, and its controller puts 60 back over a higher value
# written from outside before either divide runs: above 60 fps every frame still stepped 1/60 s and the game ran fps / 60 times
# too fast. With the host's measured frame time the step is base * seconds, whatever the rate. hos_step_probe: f_80706be0's
# x19, which tells the host the hook is in this build and gives it the game clock for its log (HOS_FPS_LOG=1).
STEP_SITES = (("void f_80706be0(Ctx *__restrict A64_NOESC c) {\n", 8, "\n hos_step_probe = c->x[19];"),
("void f_83b6ea90(Ctx *__restrict A64_NOESC c) {\n", 0, ""))
STEP_OLD = " _v=a64_fpx_div32_div32(c,_a,_b);\n a64_vset64(c->vreg[%d],_v);}"
STEP_HOOK = (" _v=a64_fpx_div32_div32(c,_a,_b);\n"
" { const uint32_t _hs = hos_frame_seconds_bits; if (_hs) { float _base, _secs; uint32_t _w; memcpy(&_base,&_a,4); "
"memcpy(&_secs,&_hs,4); _base *= _secs; memcpy(&_w,&_base,4); _v = _w; } } /* (base * the frame's seconds: nx2/oot_patches.py) */\n"
" a64_vset64(c->vreg[%d],_v);}")
STEP_MARK = "hos_frame_seconds_bits; if (_hs)" # (once per divide with the hook)
STEP_DECL = "extern volatile uint32_t hos_frame_seconds_bits;\nextern volatile uint64_t hos_step_probe;\n"
def patch_frame_seconds(s):
"""The host's frame time at the step divides of f_80706be0 and f_83b6ea90: (s, the sites patched here). A site whose
function is not in the file, is patched already, or whose code differs (another game version) is left as it is."""
done = 0
for head_text, reg, extra in STEP_SITES:
head = s.find(head_text)
if head < 0:
continue
end = s.find("\nvoid f_", head + len(head_text))
body = s[head:end if end >= 0 else len(s)]
old, new = STEP_OLD % reg, STEP_HOOK % reg + extra
if new in body or body.count(old) != 1 or body.count("a64_fpx_div32_div32") != 1:
continue
at = head + body.index(old)
s = s[:at] + new + s[at + len(old):]
done += 1
if done and STEP_DECL not in s:
s = s.replace('#include "a64.h"\n', '#include "a64.h"\n' + STEP_DECL, 1)
return s, done
def unpatch_frame_seconds(s):
"""s without the hook, as the lift wrote it: for a lift where only one of the two divides was found (apply)"""
for _, reg, extra in STEP_SITES:
s = s.replace(STEP_HOOK % reg + extra, STEP_OLD % reg)
return s if STEP_MARK in s else s.replace(STEP_DECL, "", 1) # (a hook of another shape stays, with its declarations)
# A movie's frame count above a 60 cap. The game's movie player counts its updates while a movie plays (f_83b7c710: one more
# at +760 of the player each frame), and a cutscene that shows a movie takes that count as its timeline's frame (f_83b5ec10,
# f_83b5e9a0): the narration, the rumble and the cutscene's end are placed by it. The movie itself follows the clock, so above
# 60 fps those cues ran ahead of the picture, fps / 60 times too fast (issue 1742). The count now grows by the frames' time, as
# the game's clock does (hos_movie_frames, host/nn_vi.c: 1 as before while the host gives no frame time).
MOVIE_HEAD = "void f_83b7c710(Ctx *__restrict A64_NOESC c) {\n"
# (the load and the add alone: the store after them is rewritten by the page marks' pass, which runs after these edits)
MOVIE_OLD = (" c->x[8]=recomp_load32(c,c->x[20] + 760);\n"
" { uint64_t _a=c->x[8], _b=1ULL; uint64_t _r=_a+_b; _r&=0xFFFFFFFFULL; c->x[8]=_r; }\n")
MOVIE_NEW = MOVIE_OLD.replace("_b=1ULL", "_b=hos_movie_frames(c->x[20])")
MOVIE_DECL = "uint32_t hos_movie_frames(uint64_t player);\n"
def patch_movie_frames(s):
"""The movie player's count by the frames' time; None when the file has no such function, s unchanged when the function is
there but its code differs (another game version) or has the patch already."""
head = s.find(MOVIE_HEAD)
if head < 0:
return None
end = s.find("\nvoid f_", head + len(MOVIE_HEAD))
body = s[head:end if end >= 0 else len(s)]
if body.count(MOVIE_OLD) != 1:
return s
at = head + body.index(MOVIE_OLD)
s = s[:at] + MOVIE_NEW + s[at + len(MOVIE_OLD):]
return s if MOVIE_DECL in s else s.replace('#include "a64.h"\n', '#include "a64.h"\n' + MOVIE_DECL, 1)
# Counters that add the frame step, or the step times a whole number, cut to whole frames (host/frame_whole.h). At 60 fps the step
# is 1; under a Frame rate cap above 60 it is the frame's own time, under 1 (0.42 at 144 fps), and the cut is 0 every frame:
# - f_80a87e50, the pick-up indicator above Link's head (a rupee, a Deku Stick): the count it shows (+864) moves toward the
# wallet's (+860) by (int)(step * max(distance / 50, 1)) and the indicator fades when they meet. Cut to 0, it stayed at the old
# count until a door or a talk replaced it (issue 1832).
# - f_800672e0, the water renderer: its ripple simulation runs (int)step times the water's substeps (+76 of the pass) each frame.
# Cut to 0, the rings Link and the actors make in water stood still above 60 fps. Found by atk3001 for Lichii (zortos293/
# Lichii#1152), as ported to Fritchii (Frizti/Fritchii d389685a4, 063dbb741): its remainder is kept per water object (x21).
# - f_803edf70, the time of day: each frame it adds (int)(2 * step) game seconds (+60) to the seconds of the day (+40, a day of
# 86400, then the day count +44). Cut, it added 1 a frame below 120 fps (the day slower: 83% at 100) and 0 above 120, where
# the clock stood still and the sun swung back and forth over the frozen hour.
# hos_frame_whole carries the fractions per counter while the frames' own time is the step, so each moves at the game's rate;
# otherwise it cuts as the game does. A site is added here once it is seen to misbehave in game. (A site's function, its code to
# replace, and the counter's address for its remainder.)
WHOLE_SITES = (
# (the cut alone, the function's one: the multiply before it is a64_fpx_hot_mul32_fma32 in a lift where the function is
# among A64_HOT_FUNCS)
("void f_80a87e50(Ctx *__restrict A64_NOESC c) {@",
" c->x[12]=recomp_fp_to_int(c->vreg[0][0]&UINT64_C(0xffffffff),32,32,1,3,c->fpcr,&c->fpsr);@",
"c->x[19] + 864"),
# (the cut alone, the function's one)
("void f_800672e0(Ctx *__restrict A64_NOESC c) {@",
" c->x[9]=recomp_fp_to_int(c->vreg[0][0]&UINT64_C(0xffffffff),32,32,1,3,c->fpcr,&c->fpsr);@",
"c->x[21]"),
# (the cut with the store after it: the function cuts into x8 the same way once more, in the branch that sets
# the time from another source)
("void f_803edf70(Ctx *__restrict A64_NOESC c) {@",
" c->x[8]=recomp_fp_to_int(c->vreg[0][0]&UINT64_C(0xffffffff),32,32,1,3,c->fpcr,&c->fpsr);@"
" recomp_store32(c,c->x[19] + 60,c->x[8]);@",
"c->x[19] + 60"),
)
WHOLE_SITES = tuple((h.replace("@", "\n"), o.replace("@", "\n"), k) for h, o, k in WHOLE_SITES)
WHOLE_MARK = "/* (the step's whole frames: nx2/oot_patches.py) */"
WHOLE_DECL = "extern uint32_t hos_frame_whole(uint64_t at, uint32_t amount_bits);\n"
def whole_new(old, key):
"""old with its cut to whole frames (the one recomp_fp_to_int) made hos_frame_whole's for the counter at key"""
lines = old.split("\n")
for i, line in enumerate(lines):
if "recomp_fp_to_int(c->vreg[0][0]" in line:
reg = line.split("=", 1)[0]
lines[i] = "%s=hos_frame_whole(%s, (uint32_t)c->vreg[0][0]); %s" % (reg, key, WHOLE_MARK)
return "\n".join(lines)
def patch_whole_frames(s):
"""The counters of WHOLE_SITES take hos_frame_whole's whole frames: (s, the sites patched here). A file without the function,
one patched before, or one whose code differs (another game version) is left as it is."""
done = 0
for head_text, old, key in WHOLE_SITES:
head = s.find(head_text)
if head < 0:
continue
end = s.find("\n}\n", head)
body = s[head:end if end >= 0 else len(s)]
new = whole_new(old, key)
if new in body or body.count(old) != 1:
continue
at = head + body.index(old)
s = s[:at] + new + s[at + len(old):]
done += 1
if done and WHOLE_DECL not in s:
s = s.replace('#include "a64.h"\n', '#include "a64.h"\n' + WHOLE_DECL, 1)
return s, done
# Above a Frame rate cap of 60, two places that need whole 60 fps frames (host/oot_high_fps.h has why and the logic; at a cap of
# 60 the host hands back what the game computed):
# - the sound manager's job, f_80435300 (phase in w2; phase 0 loads the game step, [[slot]]+0x10, and hands it to the sound
# engine): its head asks hos_oot_sound_gate whether to run now (60 Hz above 60 fps, the other phases following phase 0), and
# the step it loads goes through hos_oot_sound_step (a whole one while the gate holds the job). After zortos293/Lichii PR #1289
# (auz466), which does the same as a code patch for the emulator.
# - the physics solver's step count, set each update from the frame step in f_838ceb80 and f_838cfc10 (the same code in both):
# hos_oot_solver_steps rounds it up instead of down, at least 1, so Link stays on moving platforms (issue 1798).
SOUND_HEAD = "void f_80435300(Ctx *__restrict A64_NOESC c) {\n"
SOUND_SLOT = "g_module_base + 0x80435000ULL + (int64_t)75927552" # (the page of the step's pointer, whose +2192 holds it)
SOUND_OLD = (" c->x[8]=" + SOUND_SLOT + ";\n"
" { uint64_t _r = ((uint64_t)0 | ((c->x[0]) << 0)); c->x[19] = _r; }\n"
" c->x[8]=recomp_load64(c,c->x[8] + 2192);\n"
" c->x[8]=recomp_load64(c,c->x[8] + 0);\n"
" { { uint64_t _v=recomp_load32(c,(c->x[8]+16ULL)); a64_vset64(c->vreg[0],_v); } }\n")
SOUND_NEW = SOUND_OLD.replace("uint64_t _v=recomp_load32(c,(c->x[8]+16ULL));",
"uint64_t _v=hos_oot_sound_step((uint32_t)recomp_load32(c,(c->x[8]+16ULL)));")
SOUND_GATE = (" if (!hos_oot_sound_gate(c, (uint32_t)c->x[2], " + SOUND_SLOT + " + 2192)) return;"
" /* (nx2/oot_patches.py: the sound job at 60 Hz above 60 fps) */\n")
SOUND_DECL = "extern int hos_oot_sound_gate(Ctx *c, uint32_t phase, uint64_t slot);\nextern uint32_t hos_oot_sound_step(uint32_t step_bits);\n"
SOLVER_HEADS = ("void f_838ceb80(Ctx *__restrict A64_NOESC c) {\n", "void f_838cfc10(Ctx *__restrict A64_NOESC c) {\n")
# (the cut of frame step * steps a frame + 0.001, then its store into the solver: vreg 0 the float cut, vreg 1 the steps a frame)
SOLVER_OLD = (" c->x[1]=recomp_fp_to_int(c->vreg[0][0]&UINT64_C(0xffffffff),32,32,1,3,c->fpcr,&c->fpsr);\n"
" recomp_store32(c,c->x[0] + 712,c->x[1]);\n")
SOLVER_NEW = SOLVER_OLD.replace(
" recomp_store32(", " c->x[1]=hos_oot_solver_steps((uint32_t)c->x[1], (uint32_t)c->vreg[0][0], (uint32_t)c->vreg[1][0]);"
" /* (nx2/oot_patches.py: solver steps rounded up above 60 fps) */\n recomp_store32(", 1)
SOLVER_DECL = "extern uint32_t hos_oot_solver_steps(uint32_t game, uint32_t scaled_bits, uint32_t per_frame_bits);\n"
# Three more places that go wrong with a frame step under one frame (host/oot_high_fps.h has why and the logic; at a cap of 60 the
# host hands back what the game computes). Found and fixed for this build by NX2navi (its recomp/patches-v111.txt, the sets
# ofollow, owater and orecord: main+0x13d704, +0x13a064, +0x389ac20; +0x3876014, +0x38827f8, +0x632cfc; +0x32926c8, +0x3293410,
# +0x3296b08, +0x3296da4; main is at 0x80020000 here), there as code words, here as hooks in the lifted C:
# - the character controller's three follow-surface updates compare the physics' inverse step with 100.0 and keep a tenth of
# the floor's velocity above it: every update above 100 fps, so a moving platform slid out from under Link. The 100.0 comes
# from hos_oot_floor_cut (100 / the frame's 60 fps frames while that is under one).
# - the two water managers and the interactive floors (the Deku Tree's ground webs) run seconds / (1/60 s), cut to whole,
# fixed steps: none in an update shorter than 1/60 s, so the surfaces stood still above 60 fps. Before the cut the quotient
# goes through hos_oot_sim_steps (x19 the object, each function's x0): the whole steps with the object's remainder kept.
# - the ocarina recorder's clock adds (unsigned)frame step at four places: 0 above 60 fps, so a recording lost its rests.
# hos_oot_record_frames carries the fraction.
FLOOR_HEADS = ("void f_8015d490(Ctx *__restrict A64_NOESC c) {\n", "void f_80159dc0(Ctx *__restrict A64_NOESC c) {\n",
"void f_838baa40(Ctx *__restrict A64_NOESC c) {\n")
# (mov w8, #0x42c80000; fmov s1, w8: the 100.0 of the compare that follows)
FLOOR_OLD = (" c->x[8] = 0x42c80000ULL;\n c->x[8] &= 0xFFFFFFFFULL;\n"
" { a64_vset64(c->vreg[1],0); memcpy(&c->vreg[1][0],&c->x[8],4); }\n")
FLOOR_NEW = FLOOR_OLD.replace("c->x[8] = 0x42c80000ULL;",
"c->x[8] = hos_oot_floor_cut(); /* (nx2/oot_patches.py: a floor's carry above 100 fps) */", 1)
FLOOR_DECL = "extern uint32_t hos_oot_floor_cut(void);\n"
# (a function and the register its cut goes to: fdiv s0, s8, s0 then fcvtzs w<n>, s0, the function's one cut of s0 into that register)
SIM_SITES = (("void f_83895f20(Ctx *__restrict A64_NOESC c) {\n", 8), ("void f_838a2660(Ctx *__restrict A64_NOESC c) {\n", 8),
("void f_80652cb0(Ctx *__restrict A64_NOESC c) {\n", 22))
SIM_OLD = " c->x[%d]=recomp_fp_to_int(c->vreg[0][0]&UINT64_C(0xffffffff),32,32,1,3,c->fpcr,&c->fpsr);\n"
SIM_HOOK = (" a64_vset64(c->vreg[0],hos_oot_sim_steps(c->x[19], (uint32_t)c->vreg[0][0]));"
" /* (nx2/oot_patches.py: fixed steps above 60 fps) */\n")
SIM_DECL = "extern uint32_t hos_oot_sim_steps(uint64_t object, uint32_t quotient_bits);\n"
# (a function and how many times it adds the step to the clock: fcvtzu w8, s0)
RECORD_SITES = (("void f_832b2690(Ctx *__restrict A64_NOESC c) {\n", 1), ("void f_832b32b0(Ctx *__restrict A64_NOESC c) {\n", 1),
("void f_832b6840(Ctx *__restrict A64_NOESC c) {\n", 2))
RECORD_OLD = " c->x[8]=recomp_fp_to_int(c->vreg[0][0]&UINT64_C(0xffffffff),32,32,0,3,c->fpcr,&c->fpsr);\n"
RECORD_NEW = (" c->x[8]=hos_oot_record_frames((uint32_t)c->vreg[0][0]);"
" /* (nx2/oot_patches.py: the ocarina recorder's clock above 60 fps) */\n")
RECORD_DECL = "extern uint32_t hos_oot_record_frames(uint32_t step_bits);\n"
# ((Triforce, 11-18) #bug-tracker "Enemy Music not clearing in dungeon": above 60 fps the battle music kept playing after the last
# enemy was gone; at a cap of 60 it ended. Two places in Link's update f_804caa80 (x19 Link) take the time since one he keeps
# (the float [[x19+144]] less s0) times a constant of the game's (page +2952), cut to whole frames into x8, then step a small
# state of his by that count (against 8 and 4). Above 60 fps the time is under a frame every update, cut to 0, and the state
# never moved on, so the music that waits on it never ended. Found in the lab (a probe over every cut in the 40 functions that
# load the frame step: with all of them carried, then with these two alone, the music ended at 240 fps). A positive amount goes
# through hos_frame_whole (host/frame_whole.h: its fraction carried while the frames' own time is the step, the game's cut at a
# cap of 60), one remainder per place (the keys are ids, not fields: Link + 145 and + 147); a negative one keeps the game's cut.
# Each place is found by its own page constant, then the constant's load and the cut (a hot lift's multiply is
# a64_fpx_hot_*: any lines between).
BATTLE_HEAD = "void f_804caa80(Ctx *__restrict A64_NOESC c) {\n"
BATTLE_CUT = " c->x[8]=recomp_fp_to_int(c->vreg[0][0]&UINT64_C(0xffffffff),32,32,1,3,c->fpcr,&c->fpsr);\n"
BATTLE_SITES = ((" c->x[8]=g_module_base + 0x804cb000ULL + (int64_t)60379136;\n", "c->x[19] + 145"),
(" c->x[8]=g_module_base + 0x804cd000ULL + (int64_t)60370944;\n", "c->x[19] + 147"))
BATTLE_LOAD = " { { uint64_t _v=recomp_load32(c,(c->x[8]+2952ULL)); a64_vset64(c->vreg[1],_v); } }\n"
BATTLE_MARK = "/* (nx2/oot_patches.py: Link's state steps above 60 fps, the battle music's end) */"
BATTLE_NEW = (" { const uint64_t _g=recomp_fp_to_int(c->vreg[0][0]&UINT64_C(0xffffffff),32,32,1,3,c->fpcr,&c->fpsr);"
" c->x[8]=((int32_t)(uint32_t)c->vreg[0][0] > 0) ? hos_frame_whole(%s, (uint32_t)c->vreg[0][0]) : _g; } "
+ BATTLE_MARK + "\n")
def _function(s, head_text):
"""(start, end) of the function whose head is head_text, or None"""
head = s.find(head_text)
if head < 0:
return None
end = s.find("\nvoid f_", head + len(head_text))
return head, end if end >= 0 else len(s)
def patch_sound_job(s):
"""The sound job's gate and step: (s, 1) when the job is in s with them (made now or before), (s, 0) when it is not here or
its code differs (another game version: left as it is)"""
at = _function(s, SOUND_HEAD)
if at is None:
return s, 0
head, end = at
body = s[head:end]
if body.count(SOUND_NEW) == 1 and body.count(SOUND_GATE) == 1:
return s, 1
if body.count(SOUND_OLD) != 1 or SOUND_GATE in body:
return s, 0
body = body.replace(SOUND_OLD, SOUND_NEW, 1)
body = SOUND_HEAD + SOUND_GATE + body[len(SOUND_HEAD):]
s = s[:head] + body + s[end:]
if SOUND_DECL not in s:
s = s.replace('#include "a64.h"\n', '#include "a64.h"\n' + SOUND_DECL, 1)
return s, 1
def patch_solver_steps(s):
"""The solver step count's two places: (s, how many of them are in s with the hook, made now or before)"""
done = 0
for head_text in SOLVER_HEADS:
at = _function(s, head_text)
if at is None:
continue
head, end = at
body = s[head:end]
if body.count(SOLVER_NEW) == 1:
done += 1
elif body.count(SOLVER_OLD) == 1:
s = s[:head] + body.replace(SOLVER_OLD, SOLVER_NEW, 1) + s[end:]
done += 1
if done and SOLVER_DECL not in s:
s = s.replace('#include "a64.h"\n', '#include "a64.h"\n' + SOLVER_DECL, 1)
return s, done
def patch_floor_carry(s):
"""The follow-surface updates' compare: (s, how many of the three are in s with the hook, made now or before)"""
done = 0
for head_text in FLOOR_HEADS:
at = _function(s, head_text)
if at is None:
continue
head, end = at
body = s[head:end]
if body.count(FLOOR_NEW) == 1:
done += 1
elif body.count(FLOOR_OLD) == 1:
s = s[:head] + body.replace(FLOOR_OLD, FLOOR_NEW, 1) + s[end:]
done += 1
if done and FLOOR_DECL not in s:
s = s.replace('#include "a64.h"\n', '#include "a64.h"\n' + FLOOR_DECL, 1)
return s, done
def patch_sim_steps(s):
"""The height-field surfaces' fixed steps: (s, how many of the three places are in s with the hook, made now or before)"""
done = 0
for head_text, reg in SIM_SITES:
at = _function(s, head_text)
if at is None:
continue
head, end = at
body = s[head:end]
old = SIM_OLD % reg
if body.count(SIM_HOOK + old) == 1:
done += 1
elif body.count(old) == 1 and SIM_HOOK not in body:
s = s[:head] + body.replace(old, SIM_HOOK + old, 1) + s[end:]
done += 1
if done and SIM_DECL not in s:
s = s.replace('#include "a64.h"\n', '#include "a64.h"\n' + SIM_DECL, 1)
return s, done
def patch_record_clock(s):
"""The ocarina recorder's clock: (s, how many of its four adds are in s with the hook, made now or before). A function
whose adds are not as many as RECORD_SITES says (another game version) is left as it is."""
done = 0
for head_text, count in RECORD_SITES:
at = _function(s, head_text)
if at is None:
continue
head, end = at
body = s[head:end]
if body.count(RECORD_NEW) == count and RECORD_OLD not in body:
done += count
elif body.count(RECORD_OLD) == count and RECORD_NEW not in body:
s = s[:head] + body.replace(RECORD_OLD, RECORD_NEW) + s[end:]
done += count
if done and RECORD_DECL not in s:
s = s.replace('#include "a64.h"\n', '#include "a64.h"\n' + RECORD_DECL, 1)
return s, done
def patch_battle_steps(s):
"""Link's two state steps of BATTLE_SITES with hos_frame_whole's whole frames: (s, how many are in s with it, made now or
before). A place not found exactly once (another game version, or a lift with other code there) is left as it is."""
at = _function(s, BATTLE_HEAD)
if at is None:
return s, 0
head, end = at
body = s[head:end]
done = 0
for anchor, key in BATTLE_SITES:
new = BATTLE_NEW % key
if new in body:
done += 1
continue
found = [m for m in re.finditer(re.escape(anchor) + r"(?:[^\n]*\n){0,6}?" + re.escape(BATTLE_LOAD)
+ r"(?:[^\n]*\n){0,4}?" + re.escape(BATTLE_CUT), body)]
if len(found) != 1:
continue
m = found[0]
cut_at = m.end() - len(BATTLE_CUT)
body = body[:cut_at] + new + body[m.end():]
done += 1
s = s[:head] + body + s[end:]
if done and WHOLE_DECL not in s:
s = s.replace('#include "a64.h"\n', '#include "a64.h"\n' + WHOLE_DECL, 1)
return s, done
# The sprint button (host/oot_sprint.h has the rules, host/oot_sprint.c the game's addresses; after NX2navi's set "sprint").
# Link sprints while his input flags hold the dash input (bit 4), which the game sets only out of a roll. Two functions load
# those flags and test the bit: his movement update f_804caa80 (to start the sprint and to keep it), and the update of his
# stance and camera f_80c225d0 (the low byte). After each load the host gets the flags and gives them back, with the bit
# while the button's sprint is on. With the Sprint button row off the call returns what it got.
SPRINT_LINK_HEAD = "void f_804caa80(Ctx *__restrict A64_NOESC c) {\n"
SPRINT_LINK_OLD = (" c->x[10]=recomp_load64(c,c->x[19] + 80);\n"
" c->x[9]=recomp_load32(c,c->x[19] + 44);\n"
" c->x[10]=recomp_load64(c,c->x[10] + 0);\n")
SPRINT_LINK_ADD = " c->x[10]=hos_oot_sprint_link(c,c->x[19],c->x[10]); /* (nx2/oot_patches.py: the sprint button) */\n"
SPRINT_STANCE_HEAD = "void f_80c225d0(Ctx *__restrict A64_NOESC c) {\n"
SPRINT_STANCE_OLD = (" c->x[8]=recomp_load64(c,c->x[19] + 80);\n"
" c->x[8]=recomp_load8(c,c->x[8] + 0);\n"
"if (((c->x[8] >> 4) & 1)) { goto L_80c27f54; }\n")
SPRINT_STANCE_NEW = (" c->x[8]=recomp_load64(c,c->x[19] + 80);\n"
" c->x[8]=recomp_load8(c,c->x[8] + 0);\n"
" c->x[8]=hos_oot_sprint_stance(c,c->x[19],c->x[8]); /* (nx2/oot_patches.py: the sprint button) */\n"
"if (((c->x[8] >> 4) & 1)) { goto L_80c27f54; }\n")
SPRINT_DECL = ("extern uint64_t hos_oot_sprint_link(Ctx *c, uint64_t link, uint64_t flags);\n"
"extern uint64_t hos_oot_sprint_stance(Ctx *c, uint64_t link, uint64_t flags);\n")
def patch_sprint(s):
"""The sprint button's two calls: (s, how many of the two are in s, made now or before). A function whose code differs
(another game version) is left as it is."""
done = 0
for head_text, old, new in ((SPRINT_LINK_HEAD, SPRINT_LINK_OLD, SPRINT_LINK_OLD + SPRINT_LINK_ADD),
(SPRINT_STANCE_HEAD, SPRINT_STANCE_OLD, SPRINT_STANCE_NEW)):
at = _function(s, head_text)
if at is None:
continue
head, end = at
body = s[head:end]
if body.count(new) == 1:
done += 1
elif body.count(old) == 1:
s = s[:head] + body.replace(old, new) + s[end:]
done += 1
if done and SPRINT_DECL not in s:
s = s.replace('#include "a64.h"\n', '#include "a64.h"\n' + SPRINT_DECL, 1)
return s, done
# (Triforce) The host's zstd decoder (host/host_zstd.h has what the two functions are and the rules; HOS_HOST_ZSTD, off unless
# set). The game's own zstd, linked into main: f_8010b380 (main+0xeb380) is ZSTD_decompressMultiFrame, f_80115c80 (main+0xf5c80)
# the stream feed its loading threads decode through. At the head of each the host is asked first: it answers the call (x0 the
# result, the function returns) or says 0 and the game's code runs as it is. hos_host_zstd is 0 once the switch was read as off,
# and the call is no longer made. A switch at run time, so that it takes no new translation to turn on or off.
# Only the supported build's: the heads are found by address, and by lines only these two functions have (their shape below), so
# a function of that name with other code (another game version, a changed lift) is left as it is.
# (Triforce) The shapes are matched with the store marks' spellings taken out (_unmarked, below). The page marks of a group of
# stores (a64_lift.mark_groups) are made after these patches (nx2/chunks.py edit_c): a store of a group becomes
# recomp_storeN_sp( and an A64_MARK line follows the group. The lift as it stands on disk has them, these patches see the text
# before them. The stream feed's begin stores (+48 and +0 through x19) are such a group: its shape, read from the lift on disk,
# was never in the text the patch saw, and every build said "found at 1 of 2 places" (the stream feed left out). The lines are
# written as the text is before the marks, the text the patch sees (tests/test_host_zstd.py holds them to that).
ZSTD_SITES = (
("void f_8010b380(Ctx *__restrict A64_NOESC c) {\n", "hos_zstd_multiframe",
# (the eighth argument kept and tested, and the dictionary read from a DDict's +8 and +16)
(" recomp_store64_sp(c,c->x[31] + 104,c->x[7]);\nif (c->x[7] != 0) { goto L_8010fd78; }\n",
"L_8010fd78:;\n c->x[8]=recomp_load64(c,c->x[31] + 104);\n"
" { uint64_t _b=c->x[8]; int64_t _o=8; { uint64_t _p0,_p1; recomp_ldp64(c,(_b+_o),&_p0,&_p1); c->x[5]=_p0; c->x[6]=_p1; } }\n")),
("void f_80115c80(Ctx *__restrict A64_NOESC c) {\n", "hos_zstd_stream",
# (the phase read from the state, the "done" result, the error code asked of zstd, and the stores of a begin. (Triforce)
# And every field host/host_zstd.h reads or writes, at its offset: the output and its room (+8, +16) read in phase 2, the
# DCtx's "bytes expected next" (HZ_DCTX_EXPECTED, 28776) read first there, the workspace (+24) read at the begin before
# the content size goes to +20; the DCtx to +48 and the phase to +0 at its end)
(" c->x[8]=recomp_load8(c,c->x[0] + 0);\n",
" c->x[0] = 0xfffffffdULL;\n",
"c->x[30] = 0x8011629cULL; f_80d5ba00(c);\n",
" c->x[22]=recomp_load64(c,c->x[21] + 28776);\n",
" c->x[23]=recomp_load64(c,c->x[19] + 8);\n"
" { uint64_t _r = (uint64_t)(int64_t)(int32_t)recomp_load32(c,c->x[19] + 16); c->x[2] = _r; }\n",
" c->x[21]=recomp_load64(c,c->x[19] + 24);\n recomp_store32(c,c->x[19] + 20,c->x[8]);\n",
" recomp_store64(c,c->x[19] + 48,c->x[21]);\n recomp_store8(c,c->x[19] + 0,c->x[8]);\n")),
)
ZSTD_HOOK = " if (hos_host_zstd && %s(c)) return; /* (nx2/oot_patches.py: the host's zstd decoder, HOS_HOST_ZSTD) */\n"
ZSTD_DECL = ("extern volatile int hos_host_zstd;\nextern int hos_zstd_multiframe(Ctx *c);\n"
"extern int hos_zstd_stream(Ctx *c);\n")
# (a64_lift.MG_MARK's line, and the _sp spelling of a marked store: mark_groups_lines, stack_stores, frame_stores)
MARK_LINE = re.compile(r"^ A64_MARK\(\(c->x\[\d+\] \+ \(uint64_t\)\(int64_t\)\(-?\d+\)\), \d+\);\n", re.M)
MARK_SP = re.compile(r"\brecomp_(store8|store16|store32|store64|stp32|stp64)_sp\(")
def _unmarked(text):
"""(Triforce) text without the store marks' spellings: a group's A64_MARK lines out, recomp_storeN_sp( as recomp_storeN(.
The code's shape alone, the same before a64_lift.mark_groups and after it (a second run over a finished lift), and with
A64_MARK_EACH, A64_MARK_STACK or A64_MARK_FRAME at lift time. They change only where a store's page is marked, never what
the guest's code does, so a shape can count on everything else"""
return MARK_SP.sub(r"recomp_\1(", MARK_LINE.sub("", text))
def patch_host_zstd(s):
"""The host decoder's two calls: (s, how many of the two heads are in s with their call, made now or before). A function
whose code is not the decoder's (another game version) is left as it is."""
done = 0
for head_text, name, shape in ZSTD_SITES:
at = _function(s, head_text)
if at is None:
continue
head, end = at
body = s[head:end]
hook = ZSTD_HOOK % name
if body.startswith(head_text + hook):
done += 1
elif hook not in body:
plain = _unmarked(body)
if all(plain.count(_unmarked(line)) == 1 for line in shape):
s = s[:head] + head_text + hook + body[len(head_text):] + s[end:]
done += 1
if done and ZSTD_DECL not in s:
s = s.replace('#include "a64.h"\n', '#include "a64.h"\n' + ZSTD_DECL, 1)
return s, done
def patch_text_speed(s):
"""The scale at the head of the letters' block of f_80b1e140; None when the file has no such function, s unchanged when the
function is there but its code differs (another game version)."""
head = s.find(TEXT_HEAD)
if head < 0:
return None
end = s.find("\nvoid f_", head + len(TEXT_HEAD))
body = s[head:end if end >= 0 else len(s)]
for old in (TEXT_OLD_POLLED, TEXT_OLD): # (with the interrupt poll before the block's backward goto, or without: --no-polls)
if old + TEXT_ADD in body: # (applied already: a second run)
return s
if body.count(old) == 1:
break
else:
return s
if body.count("goto L_80b1e1b4;") != 1:
return s
at = head + body.index(old)
s = s[:at] + old + TEXT_ADD + s[at + len(old):]
return s.replace('#include "a64.h"\n', '#include "a64.h"\n' + TEXT_DECL, 1)
# (local, RenoDX port) The scene's colour target, "agl::RenderDisplay(color)": the game picks engine format 26 (R11G11B10F) or 44
# (RGBA16F) at main+0x65234c (0x8067234c; RenoDX's addon.cpp names the place for build e0f3ccfa). RenoDX's tone mapping wants
# RGBA16F, whose values may be negative, with HDR Native: host/nn_vi.c hos_scene_rgba16f says when. The other choice of that
# csel is 44 already, so both become 44 then; the UNORM branch at main+0x6525b0 is left alone.
RGBA16F_DECL = "int hos_scene_rgba16f(void);\n"
RGBA16F_OLD = (" c->x[9] = 0x1aULL;\n c->x[9] &= 0xFFFFFFFFULL;\n"
" { uint64_t _r = (!c->z) ? c->x[10] : c->x[9]; _r &= 0xFFFFFFFFULL; c->x[9] = _r; }\nL_80672354:;")
RGBA16F_NEW = RGBA16F_OLD.replace("c->x[9] = 0x1aULL;", "c->x[9] = hos_scene_rgba16f() ? 0x2cULL : 0x1aULL;", 1)
def patch_scene_format(s):
if RGBA16F_OLD not in s:
return None
return s.replace(RGBA16F_OLD, RGBA16F_NEW, 1).replace('#include "a64.h"\n', '#include "a64.h"\n' + RGBA16F_DECL, 1)
# (from TomShafford/Hookshot 55d68e8cd6 and 65c1998222) f_804566e0's two calls of f_80522050, the GPU memory a model's material
# block is made with, made through host/oot_heap_retry.c hos_oot_gpu_alloc, which calls the game's own and tries a full heap's
# failure again in the heap's parents. f_80522050's other callers stay as they are.
GPU_ALLOC_SITES = (0x80456f1c, 0x80457098) # (the calls' return addresses)
GPU_ALLOC_OLD = "c->x[30] = %#xULL; f_80522050(c);"
GPU_ALLOC_NEW = "c->x[30] = %#xULL; hos_oot_gpu_alloc(c, f_80522050); /* (nx2/oot_patches.py: host/oot_heap_retry.c) */"
GPU_ALLOC_DECL = "void hos_oot_gpu_alloc(Ctx *A64_NOESC c, A64Fn game);\n"
# f_804566e0's tryAllocs of the CPU buffers at its MatBlock's +200 (its bump allocator's memory) and +168, each sized for the
# model (x0 the heap, x1 the size, x2 the alignment): a null result tried in the heap's parents (hos_oot_heap_retry)
HEAP_ALLOC_SITES = (0x80456910, 0x80456da4)
HEAP_ALLOC_OLD = "{ uint64_t _t = c->x[8]; c->x[30] = %#xULL; A64_ICALL(c, _t); }\n"
HEAP_ALLOC_NEW = ("{ const uint64_t _hh = c->x[0], _hn = c->x[1], _ha = c->x[2]; /* (nx2/oot_patches.py: host/oot_heap_retry.c) */\n"
" if (hos_oot_heap_refuse()) c->x[0] = 0;\n"
" else { uint64_t _t = c->x[8]; c->x[30] = %#xULL; A64_ICALL(c, _t); }\n"
" if (!c->x[0]) hos_oot_heap_retry(c, _hh, _hn, _ha, %#xULL); }\n")
HEAP_ALLOC_DECL = "int hos_oot_heap_refuse(void);\nvoid hos_oot_heap_retry(Ctx *c, uint64_t heap, uint64_t size, uint64_t align, uint64_t lr);\n"
def patch_heap_retry(s):
"""The four places above in one file's text: (text, [GPU sites, CPU sites] made now or found made). apply() wants
[2, 2] over the whole lift and warns otherwise"""
found = [0, 0]
decls = []
for kind, sites, old, new, decl in ((0, GPU_ALLOC_SITES, GPU_ALLOC_OLD, GPU_ALLOC_NEW, GPU_ALLOC_DECL),
(1, HEAP_ALLOC_SITES, HEAP_ALLOC_OLD, HEAP_ALLOC_NEW, HEAP_ALLOC_DECL)):
for lr in sites:
o, n = old % lr, (new % lr if kind == 0 else new % (lr, lr))
if n in s:
found[kind] += 1
elif s.count(o) == 1 and s.count('#include "a64.h"\n') == 1:
s = s.replace(o, n, 1)
found[kind] += 1
if decl not in decls:
decls.append(decl)
for decl in decls:
if decl not in s:
s = s.replace('#include "a64.h"\n', '#include "a64.h"\n' + decl, 1)
return s, found
def apply(gen, *, protect_hearts=False, required=False):
"""required: the lift of the supported build (LIFE_BUILD_ID), whole: a missing output-size edit stops it (apply_output_size).
The other patches only warn when their place is not found once."""
import oot_native_resolution # (HOS_SCENE_NATIVE=1: the scene's base scale 1.0; off by default since #849's output resolution)
oot_native_resolution.apply(gen)
done = {"dynamic resolution branch": 0, "text speed block": 0, "fixed path's scale": 0, "movie's frame count": 0}
if protect_hearts: # (the supported build's: these places are its functions)
done["menu focus hook"] = 0
done["menu tick hook"] = 0
done["player heart protection"] = 0
done["player flight"] = 0
done["player flight rotation"] = 0
done["free camera"] = 0
done["mouse camera"] = 0
done["scene colour target format"] = 0 # (local, RenoDX port)
step_sites, step_files = 0, [] # (the divides with the hook, and the files that have it)
whole_sites = 0 # (the counters of WHOLE_SITES with the whole frames: patch_whole_frames)
sound_jobs = solver_sites = 0 # (patch_sound_job, patch_solver_steps: the places found with their hooks)
floor_sites = sim_sites = record_sites = 0 # (patch_floor_carry, patch_sim_steps, patch_record_clock: the same)
battle_sites = 0 # (patch_battle_steps: Link's two state steps)
sprint_sites = 0 # (patch_sprint: its two calls)
zstd_sites = 0 # (patch_host_zstd: its two calls, the supported build's alone)
mod_size_sites = 0 # ((Triforce) patch_mod_sizes: its one call, the supported build's alone)
heap_sites = [0, 0] # (the GPU memory's sites, the CPU buffers': patch_heap_retry, the supported build only)
for path in sorted(glob.glob(os.path.join(glob.escape(gen), "code_*.c"))):
with open(path, encoding="utf-8", newline="") as f:
s = f.read()
out = s
d = patch_dynres(out)
if d is not None:
out = d
done["dynamic resolution branch"] += 1
print("oot_patches: dynamic resolution switch in", os.path.basename(path))
t = patch_text_speed(out)
if t is not None and t != out:
out = t
done["text speed block"] += 1
print("oot_patches: text speed scale in", os.path.basename(path))
focus = patch_menu_focus(out) if protect_hearts else None
if focus is not None:
out = focus
done["menu focus hook"] += 1
print("oot_patches: the menus' focus hook in", os.path.basename(path))
tick = patch_menu_tick(out) if protect_hearts else None
if tick is not None:
out = tick
done["menu tick hook"] += 1
print("oot_patches: the menus' update hook in", os.path.basename(path))
movie = patch_movie_frames(out)
if movie is not None:
if MOVIE_NEW in movie: # (made now, or by an earlier run over this file)
done["movie's frame count"] += 1
if movie != out:
print("oot_patches: the movie's frame count by the frames' time in", os.path.basename(path))
out = movie
out, n = fixed_scale(out)
if n:
done["fixed path's scale"] += 1
print("oot_patches: the fixed path's scale in", os.path.basename(path))
fmt = patch_scene_format(out) if protect_hearts else None
if fmt is not None:
out = fmt
done["scene colour target format"] += 1
print("oot_patches: the scene's colour target format in", os.path.basename(path))
life = patch_life(out) if protect_hearts else None
if life is not None:
out = life
done["player heart protection"] += 1
print("oot_patches: player heart protection in", os.path.basename(path))
move = patch_movement(out) if protect_hearts else None
if move is not None:
out = move
done["player flight"] += 1
print("oot_patches: player flight in", os.path.basename(path))
rotation = patch_flight_rotation(out) if protect_hearts else None
if rotation is not None:
out = rotation
done["player flight rotation"] += 1
print("oot_patches: player flight rotation in", os.path.basename(path))
mouse = patch_mouse_camera(out) if protect_hearts else None
if mouse is not None:
out = mouse
done["mouse camera"] += 1
print("oot_patches: native mouse camera in", os.path.basename(path))
view = patch_view(out) if protect_hearts else None
if view is not None:
out = view
done["free camera"] += 1
print("oot_patches: free camera in", os.path.basename(path))
out, sites = patch_frame_seconds(out)
if STEP_MARK in out: # (made now, or by an earlier run over this file)
step_sites += out.count(STEP_MARK)
step_files.append(path)
if sites:
print("oot_patches: the frame's time at %d step divide(s) in %s" % (sites, os.path.basename(path)))
heap, found = patch_heap_retry(out) if protect_hearts else (out, [0, 0])
heap_sites[0] += found[0]
heap_sites[1] += found[1]
if heap != out:
print("oot_patches: heap-full retries of the OptimizeChangeBank allocations in", os.path.basename(path))
out = heap
out, whole = patch_whole_frames(out)
whole_sites += out.count(WHOLE_MARK) # (made now, or by an earlier run over this file)
if whole:
print("oot_patches: %d frame counter(s) with the step's whole frames in %s" % (whole, os.path.basename(path)))
sound, found = patch_sound_job(out)
sound_jobs += found
if sound != out:
print("oot_patches: the sound job at 60 Hz above 60 fps in", os.path.basename(path))
out = sound
solver, found = patch_solver_steps(out)
solver_sites += found
if solver != out:
print("oot_patches: the solver steps rounded up above 60 fps in", os.path.basename(path))
out = solver
floor, found = patch_floor_carry(out)
floor_sites += found
if floor != out:
print("oot_patches: a floor's carry above 100 fps in", os.path.basename(path))
out = floor
sim, found = patch_sim_steps(out)
sim_sites += found
if sim != out:
print("oot_patches: the water and floor surfaces' fixed steps above 60 fps in", os.path.basename(path))
out = sim
record, found = patch_record_clock(out)
record_sites += found
if record != out:
print("oot_patches: the ocarina recorder's clock above 60 fps in", os.path.basename(path))
out = record
battle, found = patch_battle_steps(out)
battle_sites += found
if battle != out:
print("oot_patches: Link's state steps above 60 fps (the battle music's end) in", os.path.basename(path))
out = battle
sprinted, found = patch_sprint(out)
sprint_sites += found
if sprinted != out:
print("oot_patches: the sprint button in", os.path.basename(path))
out = sprinted
if protect_hearts: # (found by address: the supported build's functions)
zstd, found = patch_host_zstd(out)
zstd_sites += found
if zstd != out:
print("oot_patches: the host's zstd decoder's call(s) in", os.path.basename(path))
out = zstd
sized, found = patch_mod_sizes(out)
mod_size_sites += found
if sized != out:
print("oot_patches: room for the mods' files in", os.path.basename(path))
out = sized
if out != s:
whole_write.write_whole(path, out, newline="")
if sound_jobs != 1: # (without it, above 60 fps sounds and then the music can stop after a few loading zones)
print("oot_patches: WARNING: the sound job was found %d times, not once" % sound_jobs)
if solver_sites != len(SOLVER_HEADS): # (without them, above 60 fps moving platforms can drop Link)
print("oot_patches: WARNING: the solver step count was found at %d of %d places" % (solver_sites, len(SOLVER_HEADS)))
if floor_sites != len(FLOOR_HEADS): # (without them, above 100 fps a moving platform carries Link at a tenth of its speed)
print("oot_patches: WARNING: a floor's carry was found at %d of %d places" % (floor_sites, len(FLOOR_HEADS)))
if sim_sites != len(SIM_SITES): # (without them, above 60 fps the water and web surfaces stand still)
print("oot_patches: WARNING: the surfaces' fixed steps were found at %d of %d places" % (sim_sites, len(SIM_SITES)))
if record_sites != sum(n for _, n in RECORD_SITES): # (without them, above 60 fps a recorded song loses its rests)
print("oot_patches: WARNING: the ocarina recorder's clock was found at %d of %d places"
% (record_sites, sum(n for _, n in RECORD_SITES)))
if battle_sites != len(BATTLE_SITES): # (without them, above 60 fps the battle music keeps playing after the last enemy)
print("oot_patches: WARNING: Link's state steps were found at %d of %d places" % (battle_sites, len(BATTLE_SITES)))
if sprint_sites != 2: # (without them the Sprint button row does nothing)
print("oot_patches: WARNING: the sprint button's calls were found at %d of 2 places" % sprint_sites)
if protect_hearts and mod_size_sites != 1: # (without it a mod's bigger model can crash the game: host/mods.c)
print("oot_patches: WARNING: the resource size table's lookup was found at %d of 1 place" % mod_size_sites)
if protect_hearts and zstd_sites != len(ZSTD_SITES): # (without them HOS_HOST_ZSTD does nothing, or half: host/hos_zstd.c)
print("oot_patches: WARNING: the host's zstd decoder's calls were found at %d of %d places" % (zstd_sites, len(ZSTD_SITES)))
if protect_hearts and heap_sites != [len(GPU_ALLOC_SITES), len(HEAP_ALLOC_SITES)]: # (the supported build's functions)
print("oot_patches: WARNING: the OptimizeChangeBank allocations were found %s times, not once each: a full heap is "
"not tried again" % heap_sites)
for what, n in done.items():
if n != 1:
print("oot_patches: WARNING: the %s was found %d times" % (what, n))
if step_sites != len(STEP_SITES):
# (both or neither: with one divide timed and the other stepping 1/60 s the two clocks of the game would run apart. Without
# the hook the host keeps the rate up to the cap, as before: host/nn_vi.c, hos_step_probe)
for path in step_files:
with open(path, encoding="utf-8", newline="") as f:
s = f.read()
whole_write.write_whole(path, unpatch_frame_seconds(s), newline="")
print("oot_patches: WARNING: the frame's time was found at %d of %d step divides, none patched (a Frame rate cap above 60 "
"keeps the game's own step)" % (step_sites, len(STEP_SITES)))
elif whole_sites != len(WHOLE_SITES): # (the frames' own time without them: the pick-up indicator stays above 60 fps)
print("oot_patches: WARNING: %d of %d frame counters found for the step's whole frames (above 60 fps a counter can stop: "
"the pick-up indicator, the water ripples, the time of day)" % (whole_sites, len(WHOLE_SITES)))
apply_output_size(gen, required=required)
# Output size (host/nn_applet.c hos_output_size: the Insert menu's Output resolution, 2560 x 1440 as shipped):
# - nnMain (f_81222ce0) puts the display size in the framework's create arg (+20/+24, the framework's +156/+160); the window
# textures are made at it.
# - f_810a7b70 sets up the display-size object (B = [[0x84ca29c0]+216]) from a config (x1): its docked size list (+8, first
# 2560 x 1440) is the frame's base (B+244; the frame is the base times the graphics scale's factor, f_806702e0, capped by the
# scale's display class: docked 3840 x 2160 at scale 0). Its first entry asks the host when it differs.
OUT_DECL = "uint32_t hos_output_size(int height);\nuint64_t hos_rt_pool_size(uint64_t game);\n"
OUT_EDITS = [
# (the picture's 2560 x 1440 at 0x81202ee4, not f_831f3200's copy at +0xb68; nx2/oot_wide.py's widescreen size, after it,
# stays over it: host/hos_main.c makes that one at this height)
(" c->x[8] = 0xa00ULL;\n c->x[8] = (c->x[8] & ~(0xFFFFULL<<32)) | (0x5a0ULL<<32);\n"
"{ extern volatile uint64_t hos_wide_out; const uint64_t _s = hos_wide_out; if (_s) c->x[8] = _s; } /* (nx2/oot_wide.py: hos_wide_out) */\n"
" { uint64_t _b=c->x[21]; int64_t _o=20; recomp_store64(c,(_b+_o),c->x[8]); }",
" c->x[8] = hos_output_size(0) | ((uint64_t)hos_output_size(1) << 32);\n"
"{ extern volatile uint64_t hos_wide_out; const uint64_t _s = hos_wide_out; if (_s) c->x[8] = _s; } /* (nx2/oot_wide.py: hos_wide_out) */\n"
" { uint64_t _b=c->x[21]; int64_t _o=20; recomp_store64(c,(_b+_o),c->x[8]); }"),
(" { uint64_t _a=c->x[0], _b=724ULL; uint64_t _r=_a+_b; c->x[21]=_r; }\n"
" { uint64_t _r = ((uint64_t)0 | ((c->x[1]) << 0)); c->x[20] = _r; }\n",
" { uint64_t _a=c->x[0], _b=724ULL; uint64_t _r=_a+_b; c->x[21]=_r; }\n"
" { uint64_t _r = ((uint64_t)0 | ((c->x[1]) << 0)); c->x[20] = _r; }\n"
" if (hos_output_size(0) != 2560 && recomp_load32(c, c->x[20] + 8) == 2560) { recomp_store32(c, c->x[20] + 8, hos_output_size(0)); recomp_store32(c, c->x[20] + 12, hos_output_size(1)); }\n"),
# - f_80ea2f30: the 3D's largest size, ResolutionParam's BaseResolution (or 1920 x 1080 as constants), 3/4 of 2560 x 1440;
# above it the game takes a smaller upscale network (1/3: 1280 x 720 at 4K). Scaled with the output.
("c->x[30] = 0x80ea2ffcULL; f_831cca50(c);\n"
" { uint64_t _b=c->x[0]; int64_t _o=0; { uint64_t _p0,_p1; recomp_ldp32(c,(_b+_o),&_p0,&_p1); c->x[24]=_p0; c->x[25]=_p1; } }\n",
"c->x[30] = 0x80ea2ffcULL; f_831cca50(c);\n"
" { uint64_t _b=c->x[0]; int64_t _o=0; { uint64_t _p0,_p1; recomp_ldp32(c,(_b+_o),&_p0,&_p1); c->x[24]=_p0; c->x[25]=_p1; } }\n"
" if (hos_output_size(0) != 2560) { c->x[24] = (uint32_t)c->x[24] * hos_output_size(0) / 2560; c->x[25] = (uint32_t)c->x[25] * hos_output_size(1) / 1440; }\n"),
(" c->x[8] = 0x44f00000ULL;\n c->x[8] &= 0xFFFFFFFFULL;\n recomp_store32(c,c->x[19] + 3668,c->x[8]);\n"
" c->x[8] = 0x44870000ULL;\n c->x[8] &= 0xFFFFFFFFULL;\n",
" c->x[8] = hos_output_size(0) * 3 / 4;\n { float _f = (float)c->x[8]; uint32_t _u; memcpy(&_u, &_f, 4); c->x[8] = _u; }\n"
" recomp_store32(c,c->x[19] + 3668,c->x[8]);\n"
" c->x[8] = hos_output_size(1) * 3 / 4;\n { float _f = (float)c->x[8]; uint32_t _u; memcpy(&_u, &_f, 4); c->x[8] = _u; }\n"),
# - The render targets' GPU pool: 0x13100000 bytes (the graphics config's +1464, read in f_836ce9d0, which takes its storage from
# the "Graphics" heap and makes a physical pool and a virtual one over it: f_80c4a1c0 -> f_80c49070 -> f_80c49380 -> f_811c9ba0).
# Sized for 2560 x 1440: a 3840x2160 3D at the 4K output ran out of it and the next target came back null (crash in f_8005ed00,
# the pool's allocator, its +0x28 0x13100000). Scaled with the output's pixels (host/nn_applet.c
# hos_rt_pool_size: 687 MB at 3840 x 2160), at the config, so the storage and the pool agree.
("L_836cea54:;\n",
"L_836cea54:;\n"
" if (recomp_load64(c, c->x[19] + 1464) == 0x13100000ULL) recomp_store64(c, c->x[19] + 1464, hos_rt_pool_size(0x13100000ULL));\n"),
# - The "Graphics" heap holds it, made by f_83b7b340 with the other module heaps (twice: 0x34900000 bytes in f_83b7a2c0's first
# pass, then the heap kept, 0x348ffe20; it had under 16 MB to spare): grown by as much as the pool.
("c->x[30] = 0x83b7b440ULL; f_809df710(c);\n",
"if (c->x[0] == 0x34900000ULL || c->x[0] == 0x348ffe20ULL) c->x[0] += hos_rt_pool_size(0x13100000ULL) - 0x13100000ULL;\n"
"c->x[30] = 0x83b7b440ULL; f_809df710(c);\n"),
# - f_83b7b340 then takes each module heap's use (its vtable +120) off the module's budget (the configured size, a table of slots)
# and aborts below zero (f_8351c280): the Graphics heap's use counts as the shipped one.
("{ uint64_t _t = c->x[8]; c->x[30] = 0x83b7b4e0ULL; A64_ICALL(c, _t); }\n",
"{ uint64_t _t = c->x[8]; c->x[30] = 0x83b7b4e0ULL; A64_ICALL(c, _t); }\n"
"{ const uint64_t _b = recomp_load64(c, c->x[21] + (c->x[22] << 3)), _g = hos_rt_pool_size(0x13100000ULL) - 0x13100000ULL; "
"if ((_b == 0x34900000ULL || _b == 0x348ffe20ULL) && c->x[0] > _g) c->x[0] -= _g; }\n"),
# - f_80b72340 (from the graphics init f_836cf4b0) makes a heap of what the Graphics heap can still give, which took the growth as
# well (0x1b6cb48 bytes as shipped, 0x1996cb48 grown) and left too little for the pool: it keeps its shipped size.
("c->x[30] = 0x80b723acULL; f_809df700(c);\n",
"if (c->x[0] > hos_rt_pool_size(0x13100000ULL) - 0x13100000ULL) c->x[0] -= hos_rt_pool_size(0x13100000ULL) - 0x13100000ULL;\n"
"c->x[30] = 0x80b723acULL; f_809df700(c);\n"),
]
def apply_output_size(gen, required=False):
"""required (the supported build's whole lift): each edit must be made, or found made, exactly once, else SystemExit: without
one the Insert menu's Output resolution is ignored, or a 4K output runs out of the render targets' pool. Elsewhere (another
build, part of a lift, by hand) a warning"""
found = [0] * len(OUT_EDITS)
for path in sorted(glob.glob(os.path.join(glob.escape(gen), "code_*.c"))):
with open(path, encoding="utf-8", newline="") as f:
s = f.read()
hit = False
for i, (old, new) in enumerate(OUT_EDITS):
# (every place: each made one, and each old text outside a made one; a new text can hold its old one. A file with
# both is counted for both, and its old ones are left: a second made place or a stray raw one is not once)
made = s.count(new)
raw = (s.replace(new, "\0") if made else s).count(old)
found[i] += made + raw
if raw and not made:
s = s.replace(old, new)
hit = True
if hit:
if OUT_DECL not in s:
s = s.replace('#include "a64.h"\n', '#include "a64.h"\n' + OUT_DECL, 1)
whole_write.write_whole(path, s, newline="")
print("oot_patches: output size in", os.path.basename(path))
if found != [1] * len(OUT_EDITS):
if required:
raise SystemExit("oot_patches: the output size places were found %s times, not once each (OUT_EDITS %s): the "
"lifted C no longer has the text they match" % (found, [i for i, n in enumerate(found) if n != 1]))
print("oot_patches: WARNING: the output size places were found %s times" % found)
if __name__ == "__main__":
apply(sys.argv[1] if len(sys.argv) > 1 else os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "work", "sa", "gen"))