Triforce v0.8.0

Evil HD (SMAA Ultra, 16x filtering, full textures, ambient occlusion with bounce light, sunlight shafts, foliage drawn 4x as far, the remastered texture pack's loader and the launcher's download of it), FSR 3.1 frame generation for every GPU, Intel XeSS, FSR 4 model choice, ReShade presets, Auto (this PC), HUD placement, the options menu in 13 languages, a second input for every control, hold to toggle, DualSense speaker and haptics, NFC from the player's own dumps, the above-60 fps game fixes, the Debug tab's flight and Inventory fixes, the launcher's full settings, and over 250 fixes.
This commit is contained in:
ruckus7382sfgsgdf
2026-11-25 10:21:32 -06:00
parent 861702476a
commit 4fa4f9188b
881 changed files with 179428 additions and 15581 deletions

326
scripts/chain.py Normal file
View File

@@ -0,0 +1,326 @@
"""The frame's critical path from a HOS_CHAIN recording (host/hos_chain.c): each frame walked back from its present.
python -I scripts/chain.py <chain file> [<HOS_SAMPLE_ALL file of the same run>] [top]
From a frame's present, back to the present before it: the presenting thread ran until then; before that it was
blocked in a wait (or asleep); the signal that ended the wait came from another thread, which ran until it sent it;
and so on. Each step's time goes to one of: a thread running (its own work, the replay on the submitting thread, a
driver call: anything that is not a wait), a wake-up (from the signal to the waiter running again), a sleep, or a
wait whose ending signal was not recorded (a timeout, or an object this layer does not see). The sum is the frame.
Prints, a frame on average: the path's time by thread and kind; the hand-offs on it (waiter and where it waited, who
signaled and from where); with samples (HOS_SAMPLE_ALL, same run: its "# t0_ns" line puts them on this clock;
RX_MAPS=<game folder>/bin names the frames as for scripts/crit.py), the functions running on the path.
"""
import bisect, collections, os, struct, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
WAIT, WOKE, SIGNAL, SLEEP, AWAKE, PRESENT = 1, 2, 3, 4, 5, 6
REC = struct.Struct("<qQQHB5x")
def load(path):
names = {}
with open(path, "rb") as f:
if f.readline().strip() != b"HOSCHAIN1":
sys.exit("%s: not a HOS_CHAIN recording" % path)
while True:
line = f.readline().decode("utf-8", "replace").split()
try:
if line[0] == "thread":
# (a thread the game never named is written as "thread <n> ": one word short)
names[int(line[1])] = line[2] if len(line) > 2 else "thread-%s" % line[1]
elif line[0] == "records":
n = int(line[1])
if n < 0:
raise ValueError("negative record count")
break
except (IndexError, ValueError):
sys.exit("%s: invalid HOS_CHAIN header" % path)
data = f.read(n * REC.size)
if len(data) != n * REC.size:
sys.exit("%s: truncated HOS_CHAIN records" % path)
recs = [REC.unpack_from(data, i * REC.size) for i in range(len(data) // REC.size)]
recs.sort(key=lambda r: r[0])
return names, recs
VCORE = 1 << 63 # (keys with this bit: a thread's wait for a virtual core, host/hos_thread.c vc_acquire)
def build(recs):
"""per thread: blocked intervals (sorted by end, none overlapping) as (end, begin, kind, key at the end, lr at the
begin, whether it is a piece after a block inside it); per key: signals (time, thread, lr), sorted; presents by thread. A block inside another (a wait for a
virtual core when a wait's sleep ends, or a sleep's) splits it: the outer wait up to the inner one's start, the
inner one, and the outer again after it"""
open_ = collections.defaultdict(list)
blocks = collections.defaultdict(list)
signals = collections.defaultdict(list)
presents = collections.defaultdict(list)
def kind_of(k, key):
return "sleep" if k == SLEEP else "virtual core" if key & VCORE else "wait"
for t, key, lr, th, kind in recs:
if kind in (WAIT, SLEEP):
open_[th].append([t, kind, key, lr, []])
elif kind in (WOKE, AWAKE):
if not open_[th]:
continue
b, k, _, blr, inner = open_[th].pop()
kd = kind_of(k, key)
at = b
for ib, ie in inner: # (the outer block's pieces around those inside it)
if ib > at:
blocks[th].append((ib, at, kd, key, blr, at != b))
at = ie
if t > at:
blocks[th].append((t, at, kd, key, blr, at != b))
if open_[th]:
open_[th][-1][4].append((b, t))
elif kind == SIGNAL:
signals[key].append((t, th, lr))
elif kind == PRESENT:
presents[th].append(t)
for th in blocks:
blocks[th].sort()
blocks = Blocks(blocks)
return blocks, signals, presents
class Blocks(dict):
def __init__(self, d):
super().__init__(d)
self.ends = {k: [b[0] for b in v] for k, v in d.items()}
def walk(th, t, bound, blocks, signals, out):
"""the path back from (thread th, time t) to bound; out: callbacks"""
ends = blocks.ends
# (a stretch: one thread's part of the path, from the wake-up that started it to the signal that handed the path on)
end_label, end_t = "the present", t
for _ in range(100000):
if t <= bound:
out.stretch(th, "the frame before's present", end_label, end_t - bound)
return
e_list = ends.get(th, [])
i = bisect.bisect_right(e_list, t) - 1
while i >= 0 and blocks[th][i][1] >= t: # (a block that begins after t: not before it)
i -= 1
if i < 0 or e_list[i] <= bound:
out.run(th, bound, t)
out.stretch(th, "the frame before's present", end_label, end_t - bound)
return
e, b, kind, key, blr, after_inner = blocks[th][i]
out.run(th, e, t)
t = e
if kind == "sleep":
out.other(th, "sleep", max(b, bound), e, blr)
t = b
continue
if kind == "virtual core":
# (contention, not a dependency: the holder's work before it gave the core up was not for this thread. The
# time goes to this thread, waiting for a core, with the thread that gave it one; the path goes on here)
sl = signals.get(key, [])
j = bisect.bisect_right(sl, (e, 1 << 30, 0)) - 1
out.core(th, blr, sl[j][1] if j >= 0 and sl[j][0] >= b else None, max(b, bound), e)
t = b
continue
sl = signals.get(key, [])
j = bisect.bisect_right(sl, (e, 1 << 30, 0)) - 1
while j >= 0 and sl[j][1] == th:
j -= 1
if j >= 0 and sl[j][0] >= b:
ts, sth, slr = sl[j]
out.wake(th, blr, sth, slr, max(ts, bound), e, kind)
out.stretch(th, "woken at lr %#x" % blr, end_label, end_t - e)
end_label, end_t = "signal at lr %#x" % slr, ts
th, t = sth, ts
elif after_inner: # (after a wait for a core inside it, no signal: the wait's own end, running)
out.run(th, max(b, bound), e)
t = b
else:
out.other(th, kind + ", no signal seen", max(b, bound), e, blr)
t = b
class Acc:
def __init__(self):
self.by = collections.Counter() # (thread, kind) -> ns
self.hand = collections.Counter() # (waiter, wait lr, signaler, signal lr) -> ns of wake-up
self.handn = collections.Counter()
self.waitat = collections.Counter() # (thread, kind, lr) -> ns
self.segs = [] # running segments (thread, start, end)
self.cores = collections.Counter() # (waiter, the thread that gave it a core or None) -> ns
self.stretches = collections.Counter() # (thread, what started it, what ended it) -> ns
self.nstretch = collections.Counter()
def run(self, th, a, b):
if b > a:
self.by[(th, "running")] += b - a
self.segs.append((th, a, b))
def other(self, th, kind, a, b, lr):
if b > a:
self.by[(th, kind)] += b - a
self.waitat[(th, kind, lr)] += b - a
def wake(self, th, wlr, sth, slr, a, b, kind):
self.by[(th, "signal to running")] += max(0, b - a)
self.hand[(th, wlr, sth, slr)] += max(0, b - a)
self.handn[(th, wlr, sth, slr)] += 1
def stretch(self, th, start, end, ns):
self.stretches[(th, start, end)] += max(0, ns)
self.nstretch[(th, start, end)] += 1
def core(self, th, lr, granter, a, b):
if b > a:
self.by[(th, "waiting for a virtual core")] += b - a
self.cores[(th, granter)] += b - a
def samples_on_path(path, names, segs, top):
import prof
maps = prof.load_symbols()
cache = {}
def name(frame):
if frame not in cache:
mod, _, off = frame.rpartition("+")
r = mod
if mod in maps:
addrs, nm = maps[mod]
i = bisect.bisect_right(addrs, int(off, 16)) - 1
if i >= 0:
r = prof.module_name(mod) + ":" + prof.demangle(nm[i])
cache[frame] = r
return cache[frame]
t0 = at = None
by_thread = collections.defaultdict(list) # sample thread name -> [(ns, frames)]
for line in open(path, encoding="utf-8", errors="replace"):
if line.startswith("# t0_ns "):
if t0 is None:
t0 = int(line.split()[2])
continue
if line.startswith("# at "): # (the next sample's own time: a HOS_CHAIN run's samples have it)
at = int(line.split()[2])
continue
head, _, stack = line.rstrip("\n").partition("|")
ms, _, th = head.partition(" ")
if stack and ms.isdigit() and t0 is not None:
by_thread[th].append((at if at is not None else t0 + int(ms) * 1000000, stack.split(";")))
at = None
if t0 is None:
print("(%s has no \"# t0_ns\" line: a sample file from before HOS_CHAIN)" % path)
return
shared = collections.Counter(names.values())
def match(chain_name): # (only a name one thread has in both: samples carry names, not thread ids)
if shared[chain_name] > 1:
return None
return chain_name if chain_name in by_thread else None
for v in by_thread.values():
v.sort(key=lambda s: s[0])
seg_by = collections.defaultdict(list)
for th, a, b in segs:
seg_by[th].append((a, b))
inner = collections.Counter()
leaf = collections.Counter()
state = collections.Counter() # (thread, working or waiting below the game)
held = collections.Counter() # (thread, the runtime or renderer function it waits in)
n = 0
for th, ss in seg_by.items():
sn = match(names.get(th, "?"))
if not sn:
continue
smp = by_thread[sn]
times = [s[0] for s in smp]
for a, b in ss:
for k in range(bisect.bisect_left(times, a), bisect.bisect_right(times, b)):
frames = [name(f) for f in smp[k][1]]
fn = next((f for f in frames if ":f_" in f or f.startswith("hookshot_vk:")), frames[0])
inner["%s %s" % (sn, fn)] += 1
leaf["%s %s" % (sn, frames[0])] += 1
cpu = not prof.waiting(smp[k][1][0].rpartition("+")[0], frames)
state[(sn, cpu)] += 1
if not cpu:
held["%s %s" % (sn, next((f for f in frames if f.startswith(("hookshot:", "hookshot_vk:"))), frames[0]))] += 1
n += 1
print("-- samples on the path: %d" % n)
if not n:
return
print(" by thread: working (the game, the renderer, libc's copies, the driver's own work) / waiting below the game (a")
print(" host wait the path does not see: a fence, the present, a renderer lock; prof.WAIT_FRAMES)")
for th in sorted({k[0] for k in state}, key=lambda t: -(state[(t, True)] + state[(t, False)]))[:top]:
a, b = state[(th, True)], state[(th, False)]
print(" %5.1f%% %-28s %5.1f%% working, %5.1f%% waiting" % (100.0 * (a + b) / n, th, 100.0 * a / (a + b),
100.0 * b / (a + b)))
print(" waiting in (the innermost runtime or renderer frame):")
for k, c in held.most_common(top):
print(" %5.1f%% %s" % (100.0 * c / n, k))
print(" innermost game or renderer function:")
for k, c in inner.most_common(top):
print(" %5.1f%% %s" % (100.0 * c / n, k))
print(" leaf:")
for k, c in leaf.most_common(top):
print(" %5.1f%% %s" % (100.0 * c / n, k))
def main():
path = sys.argv[1]
spath = sys.argv[2] if len(sys.argv) > 2 and not sys.argv[2].isdigit() else None
top = int(sys.argv[-1]) if sys.argv[-1].isdigit() else 20
names, recs = load(path)
blocks, signals, presents = build(recs)
if not presents:
sys.exit("no presents recorded")
pth = max(presents, key=lambda k: len(presents[k]))
ps = presents[pth]
if len(ps) < 2:
sys.exit("at least two presents on one thread are needed for a frame")
acc = Acc()
frames = 0
for k in range(1, len(ps)):
walk(pth, ps[k], ps[k - 1], blocks, signals, acc)
frames += 1
span = ps[-1] - ps[0]
counts = collections.Counter(names.values())
nm = lambda th: names.get(th, str(th)) + ("#%d" % th if counts[names.get(th)] > 1 else "")
print("%d records, %d threads; %d frames presented by %s, %.2f ms a frame (%.1f fps)" % (
len(recs), len(names), frames, nm(pth), span / 1e6 / max(1, frames), 1e9 * frames / max(1, span)))
tot = sum(acc.by.values())
print("-- the path, a frame (ms): %.2f in all" % (tot / 1e6 / frames))
kinds = collections.Counter()
for (th, kind), ns in acc.by.items():
kinds[kind] += ns
for kind, ns in kinds.most_common():
print(" %7.3f %s" % (ns / 1e6 / frames, kind))
print("-- the path's stretches: a thread, from the wake-up that put it on the path to the signal that handed it on (ms a")
print(" frame; each also holds its waits for a core and its sleeps)")
for (th, a, b), ns in acc.stretches.most_common(top):
print(" %7.3f %5.2f x %-24s from %s to %s" % (ns / 1e6 / frames, acc.nstretch[(th, a, b)] / frames, nm(th), a, b))
print("-- by thread and kind (ms a frame)")
for (th, kind), ns in acc.by.most_common(top):
print(" %7.3f %-28s %s" % (ns / 1e6 / frames, nm(th), kind))
print("-- hand-offs on the path: waiter (where it waited) <- signaler (where it signaled): a frame, wake-up ms")
for key, ns in sorted(acc.handn.items(), key=lambda kv: -kv[1])[:top]:
th, wlr, sth, slr = key
print(" %5.2f x %6.3f ms %s (lr %#x) <- %s (lr %#x)" % (acc.handn[key] / frames, acc.hand[key] / 1e6 / frames,
nm(th), wlr, nm(sth), slr))
print("-- waits for a virtual core on the path (ms a frame): waiter <- the thread that gave the core up")
for (th, g), ns in acc.cores.most_common(top):
print(" %7.3f %s <- %s" % (ns / 1e6 / frames, nm(th), nm(g) if g is not None else "(a core found free)"))
print("-- sleeps and unexplained blocks on the path (ms a frame)")
for (th, kind, lr), ns in acc.waitat.most_common(top):
print(" %7.3f %-28s %s (lr %#x)" % (ns / 1e6 / frames, nm(th), kind, lr))
if spath:
samples_on_path(spath, names, acc.segs, top)
if __name__ == "__main__":
main()

View File

@@ -59,16 +59,203 @@ VARIANTS = [
# each pass as GLSL over the SDK's own GPU headers, and the renderer records them as SPIR-V headers
# beside the upscaler's. The options are the same promises about the same inputs -- the depth is
# reversed and the motion is at the render extent -- because the inputs are the ones the upscaler is
# already given (gpu/vk/vk_fsr3fi.cpp).
# already given (gpu/vk/vk_fsr3fi.cpp). The names are interpolation's own, not the upscaler's: its
# low-resolution motion option is LOW_RES_, where the upscaler's is LOW_RESOLUTION_. A name the SDK
# does not read is dropped without a word, so tests/test_fsr3_shader_options.py checks each one.
FI_OPTIONS = [
"-DFFX_GPU=1",
"-DFFX_GLSL=1",
"-DFFX_FRAMEINTERPOLATION_OPTION_INVERTED_DEPTH=1",
"-DFFX_FRAMEINTERPOLATION_OPTION_LOW_RESOLUTION_MOTION_VECTORS=1",
"-DFFX_FRAMEINTERPOLATION_OPTION_LOW_RES_MOTION_VECTORS=1",
"-DFFX_FRAMEINTERPOLATION_OPTION_JITTERED_MOTION_VECTORS=0",
]
OF_OPTIONS = ["-DFFX_GPU=1", "-DFFX_GLSL=1"]
# (Triforce) Frame interpolation's GPU headers with two changes of ours, made on a copy at compile time: third_party/
# stays AMD's, byte for byte (scripts/check_third_party.py), and what changes is written here, line by line, each one
# found exactly as many times as it says or the script stops. gpu/vk/vk_fsr3fi.cpp fills what the changes read.
#
# 1. A made frame anywhere between the two game frames, not only the midpoint. AMD's passes fix t at 0.5: the vector
# fields keep half the motion, put each vector at the pixel's place half way, and look half a motion back into the
# frame before and half forward into this one. cbFI's padding word (_pad1) carries t instead (0: the frame before, 1:
# this one), and the fields keep half the motion as before, scaled where it is used: 2t of it back to the frame before,
# 2(1 - t) forward to this one, the vector put at the pixel's place 2(1 - t) of it from this frame's, and the blend's
# weights t and 1 - t. At t = 0.5 every scale is 1 and the passes are AMD's.
# 2. The HUD kept where it is (dispatchFlags bit 16, set unless RX_VK_FSR_FG_HUD=0). This game draws its HUD into the
# same picture as the scene and has no HUD-less colour, so AMD's passes moved it with the scene behind it: smeared
# icons and text, a copy of the HUD trailing the camera. A pixel the same in both frames while the scene there moves
# is the HUD (or a flat colour, where the frame's own pixel is right too): it is this frame's pixel. A sample of the
# frame before or this one that lands on such a pixel is the HUD, not the scene behind it, which neither frame shows:
# where only one of the two samples does, the other is taken.
# 3. The HUD marked, not guessed (dispatchFlags bit 17, vk_fsr3fi.cpp kHudMask): the guess above misses the HUD's
# see-through parts (the minimap, the button prompts' backing), its soft edges and anything of it that animates, and
# those still moved with the scene. Where the renderer has it, the colour's alpha says which pixels are
# the HUD (0: vk_framegen.cpp hud_source, what the game drew over its picture after the upscale), in this frame and,
# through the previous source's copy, the frame before: those pixels are what 2. calls the same in both frames.
# 4. HUD-less mode's overlay taken whole. AMD lays the presented frame over the made one where it differs from the
# HUD-less colour, by a factor that grows with the difference, for a HUD-less colour that is only near the presented
# frame's. The renderer's (vk_framegen.cpp hud_source, shaders/fg_hud.comp) is the presented frame's to the bit
# wherever nothing was drawn over the picture, so any difference is the HUD or an effect drawn after the upscale (the
# fairy's glow): AMD's factor took its faint parts (soft edges, a glow's fall-off) at a fraction, the scene behind them
# shown instead, and the made frames had a cut edge around them. Taken whole, they are this frame's.
FI_T = "InterpolationT()"
FI_PATCHES = {
"ffx_frameinterpolation_inpainting.h": [
(" const FfxFloat32 fStaticFactor = CalculateStaticContentFactor(RawRGBToLinear(fCurrentInterpolationSource), "
"RawRGBToLinear(fPresentColor));\n",
" const FfxFloat32 fStaticFactor = 1.0f; // (Triforce) the presented frame's pixel, whole (FI_PATCHES 4)\n", 1),
],
"ffx_frameinterpolation_callbacks_glsl.h": [
(" FfxInt32 _pad1;\n",
" FfxFloat32 fInterpolationT; // (Triforce) the made frame's place: 0 the frame before, 1 this one\n", 1),
(" FfxFloat32 TanHalfFoV()\n {\n return cbFI.fTanHalfFOV;\n }\n",
" FfxFloat32 TanHalfFoV()\n {\n return cbFI.fTanHalfFOV;\n }\n"
"\n"
" // (Triforce) the made frame's place between the frame before (0) and this one (1): AMD's passes fix it at 0.5\n"
" FfxFloat32 InterpolationT()\n {\n return cbFI.fInterpolationT;\n }\n"
" // (the vector fields keep half the motion: the frame before is 2t of it away, this one 2(1 - t))\n"
" FfxFloat32 PrevScale()\n {\n return 2.0f * cbFI.fInterpolationT;\n }\n"
" FfxFloat32 CurrScale()\n {\n return 2.0f * (1.0f - cbFI.fInterpolationT);\n }\n"
" // (Triforce) the HUD kept where it is (vk_fsr3fi.cpp kKeepStatic)\n"
" FfxBoolean KeepStaticPixels()\n {\n return (cbFI.dispatchFlags & (1u << 16)) != 0u;\n }\n"
" // (Triforce) the colour's alpha marks the HUD, 0 where it is (vk_fsr3fi.cpp kHudMask)\n"
" FfxBoolean HudMaskInAlpha()\n {\n return (cbFI.dispatchFlags & (1u << 17)) != 0u;\n }\n", 1),
# (each frame's HUD mark, the alpha of the two interpolation sources: KeepStaticPixels' known HUD)
(" return texelFetch(r_previous_interpolation_source, iPxPos, 0).rgb;\n }\n",
" return texelFetch(r_previous_interpolation_source, iPxPos, 0).rgb;\n }\n"
" // (Triforce) the frame before's HUD mark: 0 the HUD (HudMaskInAlpha)\n"
" FfxFloat32 LoadPreviousBackbufferAlpha(FFX_PARAMETER_IN FfxInt32x2 iPxPos)\n {\n"
" return texelFetch(r_previous_interpolation_source, iPxPos, 0).a;\n }\n", 1),
(" return texelFetch(r_current_interpolation_source, iPxPos, 0).rgb;\n }\n",
" return texelFetch(r_current_interpolation_source, iPxPos, 0).rgb;\n }\n"
" // (Triforce) this frame's HUD mark: 0 the HUD (HudMaskInAlpha)\n"
" FfxFloat32 LoadCurrentBackbufferAlpha(FFX_PARAMETER_IN FfxInt32x2 iPxPos)\n {\n"
" return texelFetch(r_current_interpolation_source, iPxPos, 0).a;\n }\n", 1),
],
"ffx_frameinterpolation_game_motion_vector_field.h": [
(" const FfxFloat32x2 fInterpolatedLocationUv = fUvInScreenSpace + fMotionVectorHalf;\n",
" const FfxFloat32x2 fInterpolatedLocationUv = fUvInScreenSpace + fMotionVectorHalf * CurrScale();\n", 1),
(" const FfxFloat32 fBreakDist = ffxMin(length(fMotionVectorHalf), length(FfxFloat32x2(0.5f, 0.5f)));\n",
" const FfxFloat32 fBreakDist = ffxMin(length(fMotionVectorHalf * CurrScale()), length(FfxFloat32x2(0.5f, 0.5f)));\n", 1),
],
"ffx_frameinterpolation_optical_flow_vector_field.h": [
("GetBilinearSamplingData(fUv + fMotionVectorHalf, GetOpticalFlowSize2());\n",
"GetBilinearSamplingData(fUv + fMotionVectorHalf * CurrScale(), GetOpticalFlowSize2());\n", 1),
],
"ffx_frameinterpolation_reconstruct_previous_depth.h": [
(" ReconstructPrevDepth(iPxPos, 1, fDilatedDepth, fMotionVector * 0.5f, RenderSize());\n",
" ReconstructPrevDepth(iPxPos, 1, fDilatedDepth, fMotionVector * 0.5f * CurrScale(), RenderSize());\n", 1),
],
"ffx_frameinterpolation_disocclusion_mask.h": [
("ComputeDepthClip(0, fDepthUv + gameMv.fMotionVector, fDilatedDepth);\n",
"ComputeDepthClip(0, fDepthUv + gameMv.fMotionVector * PrevScale(), fDilatedDepth);\n", 1),
("ComputeDepthClip(1, fDepthUv - gameMv.fMotionVector, fDilatedDepth);\n",
"ComputeDepthClip(1, fDepthUv - gameMv.fMotionVector * CurrScale(), fDilatedDepth);\n", 1),
],
"ffx_frameinterpolation_common.h": [
# (LoadInpaintedGameFieldMv's and SampleOpticalFlowMotionVectorField's: whether each end is inside the frame)
(" vfElement.bNegOutside = !IsUvInside(fUv - vfElement.fMotionVector);\n",
" vfElement.bNegOutside = !IsUvInside(fUv - vfElement.fMotionVector * CurrScale());\n", 2),
(" vfElement.bPosOutside = !IsUvInside(fUv + vfElement.fMotionVector);\n",
" vfElement.bPosOutside = !IsUvInside(fUv + vfElement.fMotionVector * PrevScale());\n", 2),
],
"ffx_frameinterpolation.h": [
("+gameMv.fMotionVector * fUvLetterBoxScale, DisplaySize());",
"+gameMv.fMotionVector * PrevScale() * fUvLetterBoxScale, DisplaySize());", 1),
("-gameMv.fMotionVector * fUvLetterBoxScale, DisplaySize());",
"-gameMv.fMotionVector * CurrScale() * fUvLetterBoxScale, DisplaySize());", 1),
("+ofMv.fMotionVector * fUvLetterBoxScale, DisplaySize());",
"+ofMv.fMotionVector * PrevScale() * fUvLetterBoxScale, DisplaySize());", 1),
("-ofMv.fMotionVector * fUvLetterBoxScale, DisplaySize());",
"-ofMv.fMotionVector * CurrScale() * fUvLetterBoxScale, DisplaySize());", 1),
(" FfxFloat32 t = 0.5f;\n"
" t += 0.5f * (1 - (fDisocclusionFactor.x));\n"
" t -= 0.5f * (1 - (fDisocclusionFactor.y));\n",
f" FfxFloat32 t = {FI_T};\n"
f" t += (1.0f - {FI_T}) * (1 - (fDisocclusionFactor.x));\n"
f" t -= {FI_T} * (1 - (fDisocclusionFactor.y));\n", 1),
(" fInterpolatedColor = ffxLerp(fPrevColorGame.fRaw, fCurrColorGame.fRaw, ffxSaturate(t));\n",
" fInterpolatedColor = ffxLerp(fPrevColorGame.fRaw, fCurrColorGame.fRaw, ffxSaturate(t));\n"
" TriforceStaticSamples(fUvInScreenSpace, gameMv.fMotionVector * fUvLetterBoxScale, t, fPrevColorGame.fRaw,\n"
" fCurrColorGame.fRaw, fInterpolatedColor);\n", 1),
(" FfxFloat32 ofT = 0.5f;\n", f" FfxFloat32 ofT = {FI_T};\n", 1),
(" ofT = 0.5f;\n", f" ofT = {FI_T};\n", 1),
(" const FfxFloat32x3 ofColor = ffxLerp(fPrevColorOF.fRaw, fCurrColorOF.fRaw, ofT);\n",
" FfxFloat32x3 ofColor = ffxLerp(fPrevColorOF.fRaw, fCurrColorOF.fRaw, ofT);\n"
" TriforceStaticSamples(fUvInScreenSpace, ofMv.fMotionVector * fUvLetterBoxScale, ofT, fPrevColorOF.fRaw,\n"
" fCurrColorOF.fRaw, ofColor);\n", 1),
(" fInterpolatedColor = ffxLerp(ofColor, fInterpolatedColor, ffxSaturate(fGameMvBias));\n }\n}\n",
" fInterpolatedColor = ffxLerp(ofColor, fInterpolatedColor, ffxSaturate(fGameMvBias));\n }\n"
" TriforceStaticPixel(FfxInt32x2(iPxPos), max(gameMv.fVelocity, ofMv.fVelocity), fInterpolatedColor,\n"
" fInPaintingWeight);\n}\n", 1),
# (the two helpers, ahead of computeInterpolatedColor, which calls them)
("void updateInPaintingWeight(inout FfxFloat32 fInPaintingWeight, FfxFloat32 fFactor)\n",
"// (Triforce) The HUD kept where it is: a pixel the same in both frames (to within half an 8-bit step), inside the\n"
"// frame. KeepStaticPixels says whether to look at all\n"
"FfxBoolean TriforceSame(FfxInt32x2 iPx)\n"
"{\n"
" if (!IsInRect(iPx, InterpolationRectBase(), InterpolationRectSize())) return false;\n"
" const FfxFloat32x3 fDiff = abs(LoadPreviousBackbuffer(iPx) - LoadCurrentBackbuffer(iPx));\n"
" return max(fDiff.r, max(fDiff.g, fDiff.b)) <= (0.5f / 255.0f);\n"
"}\n"
"\n"
"// A pixel of the frame before (bCurrent false) or of this one that is the HUD: marked in that frame's alpha where the\n"
"// renderer knows it (HudMaskInAlpha), else one the same in both frames (TriforceSame)\n"
"FfxBoolean TriforceHud(FfxInt32x2 iPx, FfxBoolean bCurrent)\n"
"{\n"
" if (!HudMaskInAlpha()) return TriforceSame(iPx);\n"
" if (!IsInRect(iPx, InterpolationRectBase(), InterpolationRectSize())) return false;\n"
" return (bCurrent ? LoadCurrentBackbufferAlpha(iPx) : LoadPreviousBackbufferAlpha(iPx)) < 0.5f;\n"
"}\n"
"\n"
"// A blend of the two frames' samples (0 < t < 1: both ends seen) where one sample lands on a pixel the same in both\n"
"// frames and the other does not: that one is the HUD, the scene behind it in neither frame, so the other is taken.\n"
"// fMv: the vector the samples were taken with, in UV (half the motion, as the fields keep it)\n"
"void TriforceStaticSamples(FfxFloat32x2 fUv, FfxFloat32x2 fMv, FfxFloat32 t, FfxFloat32x3 fPrev, FfxFloat32x3 fCurr,\n"
" inout FfxFloat32x3 fColor)\n"
"{\n"
" if (!KeepStaticPixels() || t <= 0.0f || t >= 1.0f || length(fMv * DisplaySize()) < 0.5f) return;\n"
" const FfxBoolean bPrev = TriforceHud(FfxInt32x2((fUv + fMv * PrevScale()) * DisplaySize()), false);\n"
" const FfxBoolean bCurr = TriforceHud(FfxInt32x2((fUv - fMv * CurrScale()) * DisplaySize()), true);\n"
" if (bPrev && !bCurr) fColor = fCurr;\n"
" else if (bCurr && !bPrev) fColor = fPrev;\n"
"}\n"
"\n"
"// The made pixel itself: this frame's HUD where it is marked; else the same in both frames while the scene there moves\n"
"// (fVelocity: the larger of the two fields' vectors, in UV) is the HUD, or a flat colour where this frame's pixel is\n"
"// right too: this frame's pixel\n"
"void TriforceStaticPixel(FfxInt32x2 iPx, FfxFloat32 fVelocity, inout FfxFloat32x3 fColor, inout FfxFloat32 fInPaintingWeight)\n"
"{\n"
" if (!KeepStaticPixels()) return;\n"
" if (HudMaskInAlpha() ? !TriforceHud(iPx, true)\n"
" : fVelocity * length(FfxFloat32x2(DisplaySize())) < 0.5f || !TriforceSame(iPx)) return;\n"
" fColor = LoadCurrentBackbuffer(iPx);\n"
" fInPaintingWeight = 0.0f;\n"
"}\n"
"\n"
"void updateInPaintingWeight(inout FfxFloat32 fInPaintingWeight, FfxFloat32 fFactor)\n", 1),
],
}
def patched_fi_headers(tmp):
"""Frame interpolation's GPU headers with FI_PATCHES applied, in tmp/frameinterpolation: the directory that goes
first on the include path, so "frameinterpolation/..." and the headers' own includes of each other find these."""
src = GPU / "frameinterpolation"
dst = Path(tmp) / "patched-gpu" / "frameinterpolation"
shutil.copytree(src, dst)
for name, edits in FI_PATCHES.items():
path = dst / name
text = path.read_text(encoding="utf-8")
for old, new, count in edits:
found = text.count(old)
if found != count:
raise SystemExit(f"fsr3_shaders.py: {name}: expected {count} of {old.strip()[:70]!r}, found {found} "
"(the SDK changed: write the patch again)")
text = text.replace(old, new)
path.write_text(text, encoding="utf-8")
return dst
# (name, the pass file, extra defines). The file is named outright rather than composed: AMD's
# optical-flow v5 passes end "_pass_v5.glsl" and the interpolation pass itself is just
# "ffx_frameinterpolation_pass.glsl", so a composed name is wrong for four of the eighteen.
@@ -157,8 +344,10 @@ def main():
with tempfile.TemporaryDirectory(prefix="fsr3-shaders-") as tmp:
# the upscaler's eleven, then frame interpolation's ten and optical flow's seven
families = [(name, None, pass_name, extra, None, None) for name, pass_name, extra in VARIANTS]
# (frame interpolation's headers patched first: FI_PATCHES. Their directory goes ahead of the SDK's)
fi_headers = patched_fi_headers(tmp)
families += [(name, FI_PASSES / f, None, extra, FI_OPTIONS,
[GPU, GPU / "frameinterpolation", GPU / "opticalflow"])
[fi_headers.parent, GPU, fi_headers, GPU / "opticalflow"])
for name, f, extra in FI_VARIANTS]
families += [(name, OF_PASSES / f, None, extra, OF_OPTIONS, [GPU, GPU / "opticalflow"])
for name, f, extra in OF_VARIANTS]

View File

@@ -0,0 +1,50 @@
"""gpu/vk/spirv_operands.h from SPIR-V's core grammar (SPIRV-Headers, spirv.core.grammar.json): for each opcode, its
operands as one letter each, for code that renames ids in SPIR-V it did not write (gpu/vk/fsr4_tune.h).
python -I scripts/gen_spirv_operands.py <spirv.core.grammar.json> gpu/vk/spirv_operands.h
Letters: T result type, R result, i an id (IdRef, IdScope, IdMemorySemantics), l a literal word, s a literal string,
c a literal number of the instruction's type (the rest of the words), P / Q / q pairs (id id, literal id, id literal),
M MemoryAccess, G ImageOperands, L LoopControl (masks whose parameters are read by their bits), e an enum of one word with no
parameters, X anything else (an instruction with one is not renamed). After a letter: * repeated to the end, ? optional.
"""
import json
import sys
g = json.load(open(sys.argv[1], encoding="utf-8"))
kinds = {k["kind"]: k for k in g["operand_kinds"]}
def letter(kind):
fixed = {"IdResultType": "T", "IdResult": "R", "IdRef": "i", "IdScope": "i", "IdMemorySemantics": "i",
"LiteralInteger": "l", "LiteralExtInstInteger": "l", "LiteralSpecConstantOpInteger": "l", "LiteralFloat": "l",
"LiteralString": "s", "LiteralContextDependentNumber": "c", "PairIdRefIdRef": "P",
"PairLiteralIntegerIdRef": "Q", "PairIdRefLiteralInteger": "q", "MemoryAccess": "M", "ImageOperands": "G",
"LoopControl": "L"}
if kind in fixed:
return fixed[kind]
k = kinds.get(kind)
if k and k.get("category") in ("ValueEnum", "BitEnum"):
if not any(e.get("parameters") for e in k.get("enumerants", [])):
return "e"
return "X"
rows = {}
for ins in g["instructions"]:
s = ""
for o in ins.get("operands", []):
s += letter(o["kind"]) + {"*": "*", "?": "?"}.get(o.get("quantifier", ""), "")
rows[ins["opcode"]] = (ins["opname"], s)
with open(sys.argv[2], "w", encoding="utf-8", newline="\n") as f:
f.write("// Generated by scripts/gen_spirv_operands.py from SPIR-V's core grammar (SPIRV-Headers %s.%s, revision %s): do not edit.\n"
% (g.get("major_version"), g.get("minor_version"), g.get("revision")))
f.write("// Each opcode's operands, one letter each (the script says what they mean); nullptr: an opcode not in the grammar.\n")
f.write("#pragma once\n\n#include <cstdint>\n\nnamespace spirv_operands {\n\n")
f.write("inline const char* of(uint32_t op) {\n switch (op) {\n")
for op in sorted(rows):
name, s = rows[op]
f.write(f' case {op}: return "{s}"; // {name}\n')
f.write(" default: return nullptr;\n }\n}\n\n} // namespace spirv_operands\n")
print(len(rows), "opcodes")

View File

@@ -27,8 +27,11 @@ def classify(gpu: str):
"RTX 30" if re.search(r"rtx ?30\d0", g) else "RTX 20" if re.search(r"rtx ?20\d0", g) else
"GTX 10/16 (no mesh shaders)" if re.search(r"gtx ?1[06]\d0", g) else "NVIDIA other")
return "NVIDIA", cls
if re.search(r"amd|radeon|\brx ?\d|rdna|780m|680m|890m|860m|8060s|z1|steam deck|legion|ally", g):
cls = ("AMD APU / handheld" if re.search(r"780m|680m|890m|860m|8060s|z1|steam deck|legion|ally|apu|vega", g) else
# ((Triforce, 11-24, after Source A's) whole words: "steamdeck" holds "amd", "finally" "ally"; a Deck's Vulkan name is
# "AMD Custom GPU 0932 (RADV VANGOGH)")
handheld = r"\b(780m|680m|890m|860m|8060s|z1|legion|ally)\b|steam ?deck|vangogh|custom gpu 0(405|932)"
if re.search(r"\bamd\b|radeon|\brx ?\d|rdna|" + handheld, g):
cls = ("AMD APU / handheld" if re.search(handheld + r"|\bapu\b|vega", g) else
"RX 9000" if re.search(r"9070|9060", g) else "RX 7000" if re.search(r"7900|7800|7700|7600", g) else
"RX 6000" if re.search(r"6[5-9]\d0|6600|6650|6700|6800|6900", g) else
"RX 5000 or older (no mesh shaders)" if re.search(r"5[5-7]00|rx ?5[78]0|rx ?4[78]0", g) else "AMD other")
@@ -40,7 +43,7 @@ def classify(gpu: str):
def os_of(text: str) -> str:
t = text.lower()
if re.search(r"linux|ubuntu|arch|fedora|steamos|bazzite|cachy|nixos|mint|pop!?_os|steam deck", t):
if re.search(r"linux|ubuntu|arch|fedora|steamos|bazzite|cachy|nixos|mint|pop!?_os|steam ?deck|vangogh", t):
return "Linux / SteamOS"
if re.search(r"windows|win ?1[01]", t):
return "Windows"

View File

@@ -72,6 +72,11 @@ mkdir -p "$T/scripts"
cp scripts/ngx_sdk.py "$T/scripts/"
cp -a gpu/vk gpu/compat gpu/third_party "$T/gpu/"
cp -a third_party/imgui third_party/fonts "$T/third_party/"
# ((Triforce) the ReShade presets' FX compiler and PNG decoder, compiled into the renderer: nx2/reshade_fx.py)
cp -a third_party/reshade_fx third_party/stb_image "$T/third_party/"
# ((Triforce, 11-24) RenHDrum' C header, host/rumble_renhdrum.c includes it (the library itself is the player's own renhdrum.dll / .so))
mkdir -p "$T/third_party/renhdrum"
cp -a third_party/renhdrum/include third_party/renhdrum/LICENSE-MIT third_party/renhdrum/LICENSE-APACHE third_party/renhdrum/NOTICE third_party/renhdrum/PROVENANCE.md "$T/third_party/renhdrum/"
mkdir -p "$T/third_party/zbic" "$T/third_party/a64-kit"
cp -a third_party/zbic/zbic.so third_party/zbic/LICENSE third_party/zbic/PROVENANCE.md "$T/third_party/zbic/"
cp -a third_party/a64-kit/* "$T/third_party/a64-kit/"
@@ -109,6 +114,14 @@ cp third_party/zstd/LICENSE third_party/zstd/PROVENANCE.md "$T/licenses/zstd/"
cp third_party/fonts/libertinus/OFL.txt third_party/fonts/PROVENANCE.md "$T/licenses/libertinus/"
mkdir -p "$T/licenses/fidelityfx"
cp third_party/fidelityfx/LICENSE.md "$T/licenses/fidelityfx/"
# ((Triforce, 11-24) AMD's FidelityFX SDK's shaders, compiled into gpu/vk/shaders' FSR 3.1 headers that every build has:
# scripts/fsr3_shaders.py)
mkdir -p "$T/licenses/fidelityfx-sdk"
cp third_party/fidelityfx-sdk/LICENSE.txt third_party/fidelityfx-sdk/PROVENANCE.md "$T/licenses/fidelityfx-sdk/"
# ((Triforce) the ReShade presets: ReShade's FX compiler (BSD-3-Clause) and stb_image's PNG decoder (MIT), nx2/reshade_fx.py)
mkdir -p "$T/licenses/reshade_fx" "$T/licenses/stb_image"
cp third_party/reshade_fx/LICENSE.md third_party/reshade_fx/PROVENANCE.md "$T/licenses/reshade_fx/"
cp third_party/stb_image/LICENSE third_party/stb_image/PROVENANCE.md "$T/licenses/stb_image/"
# ---- end of the licences ----
# the sysroot: this system's C library (headers, start files, the libraries to link against) and GCC's runtime pieces

View File

@@ -27,6 +27,7 @@ import shutil
import stat
import subprocess
import sys
import tempfile
TITLE = "0400486024DEC000"
NO_ACCOUNT = "0000000000000000"
@@ -39,8 +40,11 @@ Program = collections.namedtuple("Program", "name display folders processes alia
# home folder); the saves are then found under it by LAYOUTS. processes: lower case, without .exe, for the
# running-game check. The sources are in docs/saves.md.
EDEN = {"linux": ["{data}/eden"], "windows": ["{appdata}/eden"]}
# ((Triforce, 11-24, after Source A's) Lichii has a data folder of its own since its build 150, 2026-11-10; a build from before
# keeps its saves in Eden's)
LICHII = {"linux": ["{data}/lichii"] + EDEN["linux"], "windows": ["{appdata}/lichii"] + EDEN["windows"]}
EMULATORS = [
Program("lichii", "Lichii", EDEN, ["lichii"], []),
Program("lichii", "Lichii", LICHII, ["lichii"], []),
Program("frizti", "Frizti (Fritchii)", EDEN, ["lichii", "fritchii"], ["fritchii"]),
Program("orchid", "Orchid", EDEN, ["orchid"], []),
Program("pokedinner", "PokeDinner", EDEN, ["eglantine"], []),
@@ -283,17 +287,17 @@ def list_all(args):
print("Hookshot: %s" % e)
groups = collections.OrderedDict()
for program in EMULATORS:
groups.setdefault(tuple(folders(program)), []).append(program.display)
for tried, displays in groups.items():
# ((Triforce, 11-24) by the folder import and export use, the first of a program's with saves, as locate: the programs
# whose saves are there)
tried = folders(program)
used = next((d for d in tried if os.path.isdir(d) and find_saves(d)), None)
groups.setdefault(used or tuple(tried), []).append(program.display)
for where, displays in groups.items():
title = " / ".join(displays) + (" (one shared folder)" if len(displays) > 1 else "")
shown = False
for d in tried:
found = find_saves(d) if os.path.isdir(d) else {}
if found:
show(title, d, found)
shown = True
if not shown:
print("%s: nothing in %s" % (title, ", ".join(tried) or "(no default folder)"))
if isinstance(where, str):
show(title, where, find_saves(where))
else:
print("%s: nothing in %s" % (title, ", ".join(where) or "(no default folder)"))
if args.folder:
show("Folder", *locate(FOLDER, args.folder, "--from"))
@@ -347,15 +351,87 @@ def copy_saves(src, dst, backup, keep_settings, dry_run):
return
os.makedirs(os.path.dirname(backup), exist_ok=True)
shutil.copytree(dst, backup)
for s in slots(dst):
shutil.rmtree(os.path.join(dst, s))
for s in names: # (links were refused above; copied as links, never followed, all the same)
shutil.copytree(os.path.join(src, s), os.path.join(dst, s), symlinks=True)
for f in files:
shutil.copy2(os.path.join(src, f), os.path.join(dst, f), follow_symlinks=False)
# The new save is copied whole into a folder on the target's disk first, and the target's slots are swapped for it
# by renames only after that worked: a copy that fails (a full disk) leaves the target as it was. The target's slots
# used to be deleted before the copy began, so a copy that failed part way left half a save where a whole one had been.
# (Inside the target, so also when it links to another disk, is a disk of its own or sits in a folder that can't be
# written. The game reads only slot_* and the two .sav files there.)
incoming = tempfile.mkdtemp(prefix=".%s-incoming-" % os.path.basename(os.path.normpath(dst)), dir=dst)
try:
for s in names: # (links were refused above; copied as links, never followed, all the same)
shutil.copytree(os.path.join(src, s), os.path.join(incoming, s), symlinks=True)
for f in files:
shutil.copy2(os.path.join(src, f), os.path.join(incoming, f), follow_symlinks=False)
aside = swap_in(dst, incoming, names + files, slots(dst) + [f for f in files if os.path.lexists(os.path.join(dst, f))],
backup)
except BaseException:
if not remove_tree(incoming):
print("Could not delete %s: delete it by hand" % incoming, file=sys.stderr)
raise
left = [p for p in (incoming, aside) if not remove_tree(p)]
if left:
print("Copied, but could not delete %s: delete %s by hand." % (" and ".join(left), "them" if len(left) > 1 else "it"))
print("Done. Backup of the old %s in %s" % (dst, backup))
def remove_tree(path):
"""Deletes path, also a file in it that is read-only (Windows refuses to delete those). True when it is gone."""
def writable_then_again(func, name, _):
# (the mode it has and this: S_IWRITE alone is Linux's 0200, a folder nobody can list, and one that still cannot be
# deleted would stay so)
os.chmod(name, os.stat(name).st_mode | stat.S_IWRITE)
func(name)
try:
if sys.version_info >= (3, 12):
shutil.rmtree(path, onexc=writable_then_again)
else:
shutil.rmtree(path, onerror=writable_then_again)
except OSError:
pass
return not os.path.lexists(path)
def swap_in(dst, incoming, new, old, backup):
"""Moves the old entries of dst aside and the new ones from incoming into dst, all renames on one disk, and returns the
folder the old ones are in. If one fails the moves are undone, so dst has either all of its old entries or all of the
new ones; when a move back fails too (a file held open on Windows), the others are still put back and the old entries
that could not be stay in that folder, which is named in the error."""
aside = tempfile.mkdtemp(prefix=".%s-old-" % os.path.basename(os.path.normpath(dst)), dir=os.path.dirname(incoming))
moved, placed = [], []
try:
for n in old:
os.replace(os.path.join(dst, n), os.path.join(aside, n))
moved.append(n)
for n in new:
os.replace(os.path.join(incoming, n), os.path.join(dst, n))
placed.append(n)
except BaseException as error:
new_left, old_left = [], []
for n in reversed(placed):
try:
os.replace(os.path.join(dst, n), os.path.join(incoming, n))
except OSError:
new_left.append(n)
for n in reversed(moved):
try:
if os.path.lexists(os.path.join(dst, n)): # (its new one could not be moved out)
raise FileExistsError(n)
os.replace(os.path.join(aside, n), os.path.join(dst, n))
except OSError:
old_left.append(n)
if not new_left and not old_left:
os.rmdir(aside)
raise
left = []
if old_left:
left.append("old ones left in %s: %s" % (aside, ", ".join(sorted(old_left))))
if new_left:
left.append("new ones left in the target: %s" % ", ".join(sorted(new_left)))
raise Fail("copying into %s failed (%s), and so did putting everything back (%s). Close whatever holds those "
"files, then put the old save back from the backup, %s" % (dst, error, "; ".join(left), backup)) from error
return aside
def program_named(name):
for program in EMULATORS:
if name.lower() in [program.name] + program.aliases:

View File

@@ -9,7 +9,7 @@ maps or binaries (on Linux, the game folder).
Prints the functions by inclusive share (in the stack at all) and by self share (the leaf), and the leaf modules.
"""
import bisect, collections, itertools, os, re, stat, subprocess, sys
import bisect, collections, itertools, os, re, shutil, stat, subprocess, sys
from contextlib import ExitStack
from tempfile import TemporaryFile
@@ -25,12 +25,63 @@ def load_map(path, base):
if m:
syms.append((int(m.group(2), 16) - base, m.group(1)))
syms.sort()
return [a for a, _ in syms], [n for _, n in syms]
return [a for a, _ in syms], demangle_all([n for _, n in syms])
def demangler():
"""((Triforce, 11-24, after Source A's) A C++ demangler for the Itanium names of a Windows build's maps (llvm-mingw's, as on
Linux): llvm-cxxfilt or c++filt on the PATH, else HOOKSHOT_MINGW's. None: there is none"""
for name in ("llvm-cxxfilt", "c++filt"):
p = shutil.which(name)
if p:
return p
d = os.environ.get("HOOKSHOT_MINGW", "")
for exe in ("llvm-cxxfilt.exe", "llvm-cxxfilt"):
p = os.path.join(d, "bin", exe) if d else ""
if p and os.path.isfile(p):
return p
return None
def demangle_all(names):
"""((Triforce, 11-24, after Source A's) names with their Itanium C++ names (_Z...) demangled and their parameter lists left
out, as load_elf's nm -C gives them; any other name (C, MSVC's) as it is. Without a demangler (demangler()), all as they
are"""
idx = [i for i, n in enumerate(names) if n.startswith("_Z")]
tool = demangler() if idx else None
if not tool:
return names
try:
r = subprocess.run([tool], input="\n".join(names[i] for i in idx) + "\n", capture_output=True, text=True,
encoding="utf-8", errors="replace", timeout=120)
except (OSError, subprocess.SubprocessError):
return names
out = r.stdout.splitlines()
if r.returncode or len(out) != len(idx):
return names
names = list(names)
for i, n in zip(idx, out):
names[i] = bare(n)
return names
def bare(name):
"""a demangled name without its parameter list (and const, noexcept after it): "ns::f(int) const" -> "ns::f"; one with
none as it is ("(anonymous namespace)" inside a name stays)"""
n = re.sub(r"(\s+(const|volatile|noexcept|&&|&))+$", "", name)
if not n.endswith(")"):
return name
depth = 0
for i in range(len(n) - 1, -1, -1):
depth += {")": 1, "(": -1}.get(n[i], 0)
if depth == 0:
return n[:i] if i else name
return name
# The modules whose frames are Hookshot's own code (the game and the runtime, the renderer): Windows, then Linux
GAME_MODS = ("Triforce.exe", "hookshot.exe", "hookshot") # (Triforce's names first; upstream's kept for its samples)
VK_MODS = ("triforce_vk.dll", "hookshot_vk.dll", "hookshot_vk.so")
GAME_MODS = ("Triforce.exe", "triforce", "hookshot.exe", "hookshot") # (Triforce's names first; the older names kept for their samples)
VK_MODS = ("triforce_vk.dll", "triforce_vk.so", "hookshot_vk.dll", "hookshot_vk.so")
RUN_MODS = GAME_MODS + VK_MODS
@@ -57,7 +108,7 @@ def load_symbols(folder=None):
mp = os.path.join(folder, mod[:-4] + ".map")
if os.path.exists(mp):
maps[mod] = load_map(mp, 0x180000000 if mod.endswith(".dll") else 0x140000000)
for mod in ("hookshot_vk.so", "hookshot"):
for mod in ("triforce_vk.so", "triforce", "hookshot_vk.so", "hookshot"): # ((Triforce, 11-24) its Linux names first
b = os.path.join(folder, mod)
if os.path.isfile(b):
try:

472
scripts/renhdrum.py Normal file
View File

@@ -0,0 +1,472 @@
"""RenHDrum (renhdrum.dll, renhdrum.so on Linux), the library host/rumble_renhdrum.c plays some controllers' vibration
with, built from its source in third_party/renhdrum.
py -3 -I scripts/renhdrum.py build [--target windows|linux] [--llvm-mingw <folder>] [--linker <cc>]
[--cache <folder>] [--out <file>]
py -3 -I scripts/renhdrum.py check <file>
`build` compiles third_party/renhdrum (RenHDrum v0.5.0, MIT OR Apache-2.0) with a pinned Rust (RUST below: each part's
SHA-256 checked, kept in --cache). Its one build dependency, the cc crate (and the two crates cc needs), is downloaded from
crates.io and checked by the SHA-256 its Cargo.lock records; nothing else is asked of the network. Its build.rs compiles
libopus 1.5.2 into the library, from third_party/opus (the same release as RenHDrum's own vendor/opus, which
third_party/renhdrum leaves out), with the same C compiler that links it:
- windows (the default on Windows): x86_64-pc-windows-gnullvm, linked by llvm-mingw, the one the game is built with
(--llvm-mingw, else HOOKSHOT_MINGW), its unwinder linked in and the C runtime Windows' own UCRT, as the game's;
- linux (the default elsewhere): x86_64-unknown-linux-gnu, linked by --linker (default cc) on the system it is for (the
AppImage's C library).
No time stamp and no path of this machine go in: the same source gives the same bytes. Its output (--out, default
third_party/renhdrum/renhdrum.dll or .so, which .gitignore leaves out) is checked as `check` checks it.
(Triforce) Built by hand: Triforce's release scripts do not run it yet. When the file is in third_party/renhdrum/,
nx2/build.py copies it beside the game. A build without it plays every controller's motors or its own HD rumble, as
before.
`check` reads the file's headers only (nothing in it is loaded or run): x86-64, the exports host/rumble_renhdrum.c binds,
and no library a player would have to install (a C++ or unwinder runtime, a VC++ Runtime).
"""
import argparse
import hashlib
import os
import re
import shutil
import struct
import subprocess
import sys
import tarfile
import tempfile
import urllib.request
import zipfile
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
class helpers:
"""(Triforce) the three download and archive helpers this script needs, Python's standard library only"""
@staticmethod
def sha256_file(path):
h = hashlib.sha256()
with open(path, "rb") as f:
for block in iter(lambda: f.read(1 << 20), b""):
h.update(block)
return h.hexdigest()
@staticmethod
def download(url, dest, sha256, timeout=600):
"""url's bytes into dest through dest.part (removed whatever happens) when they have this SHA-256; OSError (no
answer) or ValueError (other bytes) otherwise"""
os.makedirs(os.path.dirname(dest) or ".", exist_ok=True)
part = dest + ".part"
try:
h = hashlib.sha256()
req = urllib.request.Request(url, headers={"User-Agent": "renhdrum-build"})
with urllib.request.urlopen(req, timeout=timeout) as r, open(part, "wb") as f:
for block in iter(lambda: r.read(1 << 20), b""):
h.update(block)
f.write(block)
if h.hexdigest() != sha256:
raise ValueError("%s: sha256 %s, not the pinned %s" % (url, h.hexdigest(), sha256))
os.replace(part, dest)
finally:
if os.path.exists(part):
os.remove(part)
@staticmethod
def extract(archive, folder):
"""A zip's or a tar's members into folder; a tar through the "data" filter where Python has it (3.12)"""
if zipfile.is_zipfile(archive):
with zipfile.ZipFile(archive) as z:
z.extractall(folder)
return
with tarfile.open(archive) as t:
t.extractall(folder, **({"filter": "data"} if hasattr(tarfile, "data_filter") else {}))
SRC = os.path.join(ROOT, "third_party", "renhdrum")
TARGETS = {"windows": "x86_64-pc-windows-gnullvm", "linux": "x86_64-unknown-linux-gnu"}
BUILT = {"windows": "renhdrum.dll", "linux": "librenhdrum.so"} # (cargo's names)
NAMES = {"windows": "renhdrum.dll", "linux": "renhdrum.so"} # (the game's)
RUST_VERSION = "1.99.1"
DIST = "https://static.rust-lang.org/dist/"
# (the parts of a Rust that compiles the crate: rustc and cargo for this system, the target's standard library, and this
# system's own when it is not the target's, for build.rs, which runs here)
RUST = {
"linux": [
("rustc-%s-x86_64-unknown-linux-gnu" % RUST_VERSION, "2ff05ff9c08a90861e7f6e4065b40a8b87463b4576186fd613871c3e37f2091f"),
("cargo-%s-x86_64-unknown-linux-gnu" % RUST_VERSION, "53f3521949404d595efb06a55c12c5658d4ed1c75566f33d3d514eaebe70bd8a"),
],
"windows": [
("rustc-%s-x86_64-pc-windows-gnullvm" % RUST_VERSION, "00eb55f0c1fd330a0f7b82d288b32648b867bd523e55039d69c5914804dd7ad5"),
("cargo-%s-x86_64-pc-windows-gnullvm" % RUST_VERSION, "44753601667a1b201c9e2e4233d8311e2e7d3321273d6041a07e3d4e7966025b"),
],
}
RUST_STD = {
"windows": ("rust-std-%s-x86_64-pc-windows-gnullvm" % RUST_VERSION,
"8ddc26705e13c46530c898524b0d2657b7d416a25e8d9ffe369a97b23a619bf6"),
"linux": ("rust-std-%s-x86_64-unknown-linux-gnu" % RUST_VERSION,
"109b074225bf5b9ea3820890876bfdf4ed161adbfaf94b2b4b5984c85ee5d958"),
}
# (host/rumble_renhdrum.c's RH_FUNCS, each with the renhdrum_ prefix)
EXPORTS = tuple("renhdrum_" + n for n in (
"version", "set_nx2_mode", "dualsense_dsp_create", "dualsense_dsp_destroy", "dualsense_dsp_set_half_target",
"dualsense_dsp_fill_f32", "dualsense_dsp_build_bt_report", "dualsense_dsp_set_speaker",
"dualsense_dsp_build_bt36_report", "tri_trigger_create", "tri_trigger_destroy", "tri_trigger_update",
"tri_trigger_note_action", "hd_haptics_speaker_block", "hd_haptics_trigger_block", "valve_grip_dsp_create_ex",
"valve_grip_build_report", "valve_grip_mode_tick", "valve_grip_mode_off", "xbox_rumble_create",
"xbox_rumble_destroy",
"xbox_rumble_push_half_sample", "xbox_rumble_tick", "engine_create", "engine_destroy", "engine_push_half_sample",
"engine_tick"))
# (Windows' own: present on every Windows 10 and 11, as they are for the game's exe, which llvm-mingw links to the UCRT too)
SYSTEM_IMPORT = re.compile(r"^(kernel32|ntdll|advapi32|bcrypt|bcryptprimitives|userenv|ws2_32|ucrtbase|"
r"api-ms-win-[a-z0-9-]+)\.dll$")
# (every Linux system's own: the C library's parts, and GCC's unwinder, which every desktop system carries)
SYSTEM_NEEDED = re.compile(r"^(libc|libm|libdl|libpthread|librt|libgcc_s|ld-linux-x86-64)\.so\.\d+$")
CRATES = "https://static.crates.io/crates/"
OPUS = os.path.join(ROOT, "third_party", "opus")
# (third_party/opus's files that RenHDrum's vendor/opus does not have: build.rs compiles every .c of celt/, and this one
# is a program of its own, with a main)
OPUS_LEFT_OUT = ("celt/opus_custom_demo.c",)
def shown(path):
try:
return os.path.relpath(path, ROOT)
except ValueError:
return os.path.abspath(path)
def fail(message):
print("renhdrum: " + message, file=sys.stderr)
raise SystemExit(1)
# ---- the file's own headers: no tool, and nothing loaded ----
def pe_info(data):
"""(machine, imported DLL names in lower case, exported names) of a PE image's bytes; SystemExit when it is not one"""
try:
if data[:2] != b"MZ":
raise ValueError("no MZ header")
pe = struct.unpack_from("<I", data, 0x3C)[0]
if data[pe:pe + 4] != b"PE\0\0":
raise ValueError("no PE header")
machine, sections, _, _, _, opt_size, _ = struct.unpack_from("<HHIIIHH", data, pe + 4)
opt = pe + 24
magic = struct.unpack_from("<H", data, opt)[0]
if magic not in (0x10B, 0x20B):
raise ValueError("optional header magic %#x" % magic)
dirs = opt + (112 if magic == 0x20B else 96)
table = opt + opt_size
def at(rva):
for i in range(sections):
_, vsize, vaddr, rawsize, rawptr = struct.unpack_from("<8sIIII", data, table + i * 40)
if vaddr <= rva < vaddr + max(vsize, rawsize):
return rawptr + (rva - vaddr)
raise ValueError("%#x is in no section" % rva)
def name(rva):
start = at(rva)
return data[start:data.index(b"\0", start)].decode("ascii", "replace")
imports = []
rva = struct.unpack_from("<I", data, dirs + 8)[0]
if rva:
off = at(rva)
while len(data[off:off + 20]) == 20 and data[off:off + 20] != b"\0" * 20:
n = struct.unpack_from("<I", data, off + 12)[0]
if n:
imports.append(name(n).lower())
off += 20
exports = []
rva = struct.unpack_from("<I", data, dirs)[0]
if rva:
d = at(rva)
count, names = struct.unpack_from("<I", data, d + 24)[0], struct.unpack_from("<I", data, d + 32)[0]
if names:
base = at(names)
exports = [name(struct.unpack_from("<I", data, base + 4 * i)[0]) for i in range(min(count, 4096))]
return machine, imports, exports
except (struct.error, ValueError, OverflowError) as e:
fail("not a usable PE image (%s)" % e)
def elf_info(data):
"""(machine, DT_NEEDED names, defined dynamic symbols) of a 64-bit little-endian ELF's bytes; SystemExit otherwise"""
try:
if data[:4] != b"\x7fELF" or data[4] != 2 or data[5] != 1:
raise ValueError("not a 64-bit little-endian ELF")
machine = struct.unpack_from("<H", data, 18)[0]
shoff = struct.unpack_from("<Q", data, 40)[0]
shentsize, shnum = struct.unpack_from("<HH", data, 58)
sections = [struct.unpack_from("<IIQQQQIIQQ", data, shoff + i * shentsize) for i in range(shnum)]
def strings(index, off):
base = sections[index][4] + off
return data[base:data.index(b"\0", base)].decode("ascii", "replace")
needed, symbols = [], []
for _, kind, _, _, offset, size, link, _, _, entsize in sections:
if kind == 6: # SHT_DYNAMIC: {d_tag, d_val} pairs, DT_NEEDED = 1
for at in range(offset, offset + size, 16):
tag, val = struct.unpack_from("<qQ", data, at)
if tag == 0:
break
if tag == 1:
needed.append(strings(link, val))
elif kind == 11: # SHT_DYNSYM: Elf64_Sym, 24 bytes; a defined one has a section index (not 0)
for at in range(offset + 24, offset + size, entsize or 24):
name, info, _, shndx = struct.unpack_from("<IBBH", data, at)
if name and shndx:
symbols.append(strings(link, name))
return machine, needed, symbols
except (struct.error, ValueError, IndexError, OverflowError) as e: # (an offset past the file: OverflowError)
fail("not a usable ELF image (%s)" % e)
def problems(data, target=None):
"""What makes the library unusable by host/rumble_renhdrum.c on a player's PC: [] when nothing does. target (windows,
linux): the system it is for, whose format it must be. A Linux library named renhdrum.dll is refused by Windows with a
"Bad Image" box at the game's start (0xc000012f): the release once built one, on its Linux runner with no --target"""
is_elf = data[:4] == b"\x7fELF"
if target == "windows" and is_elf:
return ["a Linux (ELF) library, not a Windows DLL (scripts/renhdrum.py build --target windows)"]
if target == "linux" and not is_elf:
return ["not a Linux (ELF) library (scripts/renhdrum.py build --target linux)"]
if is_elf:
machine, deps, exports = elf_info(data)
ok_machine, own = 62, SYSTEM_NEEDED # (EM_X86_64)
else:
machine, deps, exports = pe_info(data)
ok_machine, own = 0x8664, SYSTEM_IMPORT
out = []
if machine != ok_machine:
out.append("machine %#x, not x86-64" % machine)
out += ["no export %s (host/rumble_renhdrum.c binds it)" % n for n in EXPORTS if n not in exports]
out += ["needs %s, which is not part of the system: a player would need it installed" % i
for i in deps if not own.match(i)]
return out
def cmd_check(a):
if not os.path.isfile(a.file):
fail("%s is not there (py -3 -I scripts/renhdrum.py build makes it)" % shown(a.file))
with open(a.file, "rb") as f:
data = f.read()
# (the game's names: renhdrum.dll on Windows, renhdrum.so on Linux)
target = {".dll": "windows", ".so": "linux"}.get(os.path.splitext(a.file)[1].lower())
deps = elf_info(data)[1] if data[:4] == b"\x7fELF" else pe_info(data)[1]
print("%s: %d bytes, sha256 %s" % (shown(a.file), len(data), hashlib.sha256(data).hexdigest()))
print(" needs: %s" % (", ".join(sorted(deps)) or "(nothing)"))
bad = problems(data, target)
for p in bad:
print(" " + p)
print(" usable" if not bad else " not usable")
return 1 if bad else 0
# ---- the build ----
def host():
import platform
if platform.machine().lower() not in ("x86_64", "amd64"):
fail("Rust is pinned for x86-64 Linux and Windows only, not %s" % platform.machine())
return "windows" if os.name == "nt" else "linux"
def fetch(name, want, cache):
"""<cache>/<name>.tar.xz, downloaded when missing or not the pinned bytes; SystemExit when the download is not them"""
path = os.path.join(cache, name + ".tar.xz")
if not (os.path.isfile(path) and helpers.sha256_file(path) == want):
print("renhdrum: downloading %s.tar.xz" % name, flush=True)
try:
helpers.download(DIST + name + ".tar.xz", path, want, timeout=300)
except (OSError, ValueError) as e:
fail(str(e))
return path
def unpack_component(archive, name, prefix):
"""A Rust dist part's files into prefix: each component folder inside it (rustc/, cargo/, rust-std-<target>/) holds a
tree laid out as the installed one (bin/, lib/), which install.sh would copy; merged here without running it"""
with tempfile.TemporaryDirectory(dir=os.path.dirname(prefix)) as tmp:
helpers.extract(archive, tmp)
top = os.path.join(tmp, name)
with open(os.path.join(top, "components"), encoding="utf-8") as f:
components = f.read().split()
for c in components:
src = os.path.join(top, c)
for dirpath, _, files in os.walk(src):
rel = os.path.relpath(dirpath, src)
for fn in files:
if rel == "." and fn == "manifest.in":
continue
dst = os.path.join(prefix, rel, fn)
os.makedirs(os.path.dirname(dst), exist_ok=True)
shutil.copy2(os.path.join(dirpath, fn), dst)
def toolchain(cache, target):
"""The pinned Rust for target, unpacked once under cache (a folder named by the parts' hashes): its bin/ folder"""
parts = RUST[host()] + [RUST_STD[target]] + ([RUST_STD[host()]] if host() != target else [])
key = hashlib.sha256("".join(h for _, h in parts).encode()).hexdigest()[:16]
prefix = os.path.join(cache, "rust-%s-%s" % (RUST_VERSION, key))
done = os.path.join(prefix, ".complete")
if not os.path.isfile(done):
shutil.rmtree(prefix, ignore_errors=True)
os.makedirs(prefix)
for name, want in parts:
unpack_component(fetch(name, want, cache), name, prefix)
with open(done, "w") as f:
f.write("\n".join(n for n, _ in parts) + "\n")
return os.path.join(prefix, "bin")
def locked_crates(lock):
"""[(name, version, sha256)] of Cargo.lock's crates.io packages (the build's dependencies; the crate itself has none)"""
out = []
for block in lock.split("[[package]]")[1:]:
f = dict(re.findall(r'^(name|version|source|checksum) = "([^"]*)"', block, re.M))
if f.get("source", "").startswith("registry+"):
if not re.fullmatch(r"[0-9a-f]{64}", f.get("checksum", "")):
fail("Cargo.lock's %s %s has no checksum" % (f.get("name"), f.get("version")))
out.append((f["name"], f["version"], f["checksum"]))
elif "source" in f:
fail("Cargo.lock's %s comes from %s, not crates.io" % (f.get("name"), f["source"]))
return out
def vendor_crates(cache, into):
"""Cargo.lock's crates, each downloaded once into cache and checked by its SHA-256, unpacked into into/ as a cargo
directory source (the .cargo-checksum.json cargo asks for, with the package's checksum, which --locked compares)"""
with open(os.path.join(SRC, "Cargo.lock"), encoding="utf-8") as f:
crates = locked_crates(f.read())
os.makedirs(into)
for name, version, want in crates:
archive = os.path.join(cache, "crates", "%s-%s.crate" % (name, version))
if not (os.path.isfile(archive) and helpers.sha256_file(archive) == want):
print("renhdrum: downloading the %s %s crate" % (name, version), flush=True)
os.makedirs(os.path.dirname(archive), exist_ok=True)
try:
helpers.download("%s%s/%s-%s.crate" % (CRATES, name, name, version), archive, want, timeout=300)
except (OSError, ValueError) as e:
fail(str(e))
helpers.extract(archive, into) # (a gzipped tar of <name>-<version>/; checked by its SHA-256 above)
with open(os.path.join(into, "%s-%s" % (name, version), ".cargo-checksum.json"), "w", encoding="utf-8") as f:
f.write('{"files":{},"package":"%s"}' % want)
return crates
def copy_opus(into):
"""third_party/opus's sources as build.rs reads them from vendor/opus (celt, silk, src, include, its licence)"""
for sub in ("celt", "silk", "src", "include"):
shutil.copytree(os.path.join(OPUS, sub), os.path.join(into, sub),
ignore=lambda d, names: [n for n in names
if os.path.relpath(os.path.join(d, n), OPUS).replace(os.sep, "/")
in OPUS_LEFT_OUT])
shutil.copy2(os.path.join(OPUS, "COPYING"), into)
def cmd_build(a):
target = a.target or host()
triple = TARGETS[target]
exe = ".exe" if os.name == "nt" else ""
if target == "windows":
mingw = a.llvm_mingw or os.environ.get("HOOKSHOT_MINGW", "")
linker = os.path.join(mingw, "bin", "x86_64-w64-mingw32-clang" + exe)
if not mingw or not os.path.isfile(linker):
fail("no llvm-mingw: pass --llvm-mingw <folder> or set HOOKSHOT_MINGW (%s is not there)" % (linker or "its clang"))
archiver = os.path.join(mingw, "bin", "llvm-ar" + exe)
else:
linker = shutil.which(a.linker or "cc")
if not linker:
fail("no %s to link with: pass --linker <cc>" % (a.linker or "cc"))
archiver = shutil.which("ar") or "ar"
cache = os.path.abspath(a.cache or os.path.join(ROOT, "build", "renhdrum-rust"))
bin_dir = toolchain(cache, target)
out = os.path.abspath(a.out or os.path.join(SRC, NAMES[target]))
# (the tracked source only, copied out of the tree: target/ and the cargo home are not written into third_party/. One
# fixed folder, emptied first, so two builds of the same source are the same bytes)
work = os.path.join(cache, "work")
shutil.rmtree(work, ignore_errors=True)
try:
crate = os.path.join(work, "renhdrum")
os.makedirs(crate)
for f in ("Cargo.toml", "Cargo.lock", "build.rs"):
shutil.copy2(os.path.join(SRC, f), crate)
shutil.copytree(os.path.join(SRC, "src"), os.path.join(crate, "src"))
copy_opus(os.path.join(crate, "vendor", "opus"))
# (cargo reads crates.io from the downloaded crates only: a cargo directory source, set in its home's config)
home = os.path.join(work, "cargo-home")
vendor_crates(cache, os.path.join(work, "crates"))
os.makedirs(home)
with open(os.path.join(home, "config.toml"), "w", encoding="utf-8") as f:
f.write('[source.crates-io]\nreplace-with = "pinned"\n\n[source.pinned]\ndirectory = "%s"\n'
% os.path.join(work, "crates").replace("\\", "/"))
# (no path of this machine in it. Windows: crt-static links llvm-mingw's unwinder in, not libunwind.dll, which a
# player does not have, the C runtime staying Windows' UCRT; no time stamp in the PE header. Linux: no build id.
# libopus's C: the same compiler, its file names relative to the work folder)
flags = "--remap-path-prefix=%s=renhdrum" % crate
flags += (" -C target-feature=+crt-static -C link-arg=-Wl,--no-insert-timestamp" if target == "windows"
else " -C link-arg=-Wl,--build-id=none")
under = triple.replace("-", "_")
env = dict(os.environ)
env.update({
# (llvm-mingw's bin/ too on Windows: build.rs, built for this system, links with its clang there)
"PATH": os.pathsep.join([bin_dir] + ([os.path.dirname(linker)] if target == "windows" else [])
+ [env.get("PATH", "")]),
"RUSTC": os.path.join(bin_dir, "rustc" + exe),
"CARGO_HOME": home,
"CARGO_TARGET_DIR": os.path.join(work, "target"),
"CARGO_TARGET_%s_LINKER" % under.upper(): linker,
"RUSTFLAGS": flags,
"CC_" + under: linker,
"AR_" + under: archiver,
"CFLAGS_" + under: "-ffile-prefix-map=%s=renhdrum" % work,
})
for k in ("RUSTUP_TOOLCHAIN", "CARGO_BUILD_TARGET", "CARGO_ENCODED_RUSTFLAGS", "CC", "AR", "CFLAGS",
"TARGET_CC", "TARGET_AR", "TARGET_CFLAGS", "CRATE_CC_NO_DEFAULTS"):
env.pop(k, None)
cmd = [os.path.join(bin_dir, "cargo" + exe), "build", "--release", "--locked", "--offline", "--lib",
"--target", triple]
print("renhdrum: %s (Rust %s, linker %s)" % (" ".join(cmd[1:]), RUST_VERSION, linker), flush=True)
if subprocess.run(cmd, cwd=crate, env=env).returncode:
fail("cargo build failed")
built = os.path.join(work, "target", triple, "release", BUILT[target])
if not os.path.isfile(built):
fail("cargo made no %s" % built)
with open(built, "rb") as f:
data = f.read()
bad = problems(data, target)
if bad:
fail("what was built is not usable: " + "; ".join(bad))
os.makedirs(os.path.dirname(out), exist_ok=True)
shutil.copyfile(built, out)
finally:
shutil.rmtree(work, ignore_errors=True)
print("renhdrum: %s, %d bytes, sha256 %s" % (shown(out), len(data), hashlib.sha256(data).hexdigest()))
return 0
def main(argv=None):
for stream in (sys.stdout, sys.stderr):
try:
stream.reconfigure(errors="replace")
except (AttributeError, ValueError):
pass
p = argparse.ArgumentParser(description=__doc__.split("\n")[0])
s = p.add_subparsers(dest="what", required=True)
b = s.add_parser("build", help="build RenHDrum from third_party/renhdrum with the pinned Rust")
b.add_argument("--target", choices=sorted(TARGETS), help="windows or linux (default: this system's)")
b.add_argument("--llvm-mingw", help="windows: llvm-mingw's folder (default: HOOKSHOT_MINGW)")
b.add_argument("--linker", help="linux: the C compiler that links it (default: cc)")
b.add_argument("--cache", help="where the pinned Rust is kept (default: build/renhdrum-rust)")
b.add_argument("--out", help="its path (default: third_party/renhdrum/renhdrum.dll or renhdrum.so)")
b.set_defaults(fn=cmd_build)
c = s.add_parser("check", help="check a renhdrum.dll or .so's headers: x86-64, the exports, the system's libraries only")
c.add_argument("file")
c.set_defaults(fn=cmd_check)
a = p.parse_args(argv)
return a.fn(a)
if __name__ == "__main__":
sys.exit(main())

111
scripts/reshade/check_fx.py Normal file
View File

@@ -0,0 +1,111 @@
"""Build the development-only ReShade FX probe and exercise real ReShade shaders."""
import argparse
import os
from pathlib import Path
import struct
import subprocess
import sys
import tempfile
import zlib
def main():
probe_source = Path(__file__).resolve().parent
root = probe_source.parents[1]
sys.path.insert(0, str(root / "nx2"))
from reshade_fx import write_preprocessor
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--reshade-source", default=root / "third_party" / "reshade_fx", type=Path,
help="ReShade compiler source tree (defaults to vendored sources)")
parser.add_argument("--shader-dir", type=Path, help="optionally test the Shaders directory of reshade-shaders")
parser.add_argument("--spirv-headers", required=True, type=Path, help="include directory containing spirv.hpp")
parser.add_argument("--cxx", default="clang++", help="C++ compiler (LLVM-MinGW on Windows)")
args = parser.parse_args()
bridge = root / "gpu" / "vk" / "reshade"
fx_source = args.reshade_source / "source"
sources = [
fx_source / f"effect_{name}.cpp"
for name in ("codegen_spirv", "expression", "lexer", "parser_exp", "parser_stmt", "symbol_table")
]
windows = os.name == "nt"
with tempfile.TemporaryDirectory(prefix="triforce-fx-") as temp:
tmp = Path(temp)
sources.append(write_preprocessor(fx_source, tmp / "effect_preprocessor.cpp"))
exe = tmp / ("fx_probe.exe" if windows else "fx_probe")
# ReShade's FX code uses filesystem::u8string as a std::string (/Zc:char8_t- with MSVC).
command = [args.cxx, "-std=c++20", "-O0", "-fno-char8_t"]
if windows:
command += ["-municode", "-static", "-include", "share.h"]
for include in (bridge, fx_source, args.spirv_headers, root / "third_party" / "stb_image"):
command += ["-I", str(include)]
subprocess.run([*command, "-o", exe, probe_source / "fx_probe.cpp", bridge / "fx_compile.cpp",
bridge / "fx_files.cpp", bridge / "fx_preset.cpp", bridge / "fx_texture.cpp", *sources], check=True)
fixtures = {
"Daltonize.fx": {"technique Daltonize 1", "uniform Type", "bindings 1 1"},
"LUT.fx": {"technique LUT 1", "uniform fLUT_AmountChroma", "texture texLUT", "bindings 2 2"},
}
for name, expected in fixtures.items() if args.shader_dir else ():
result = subprocess.run([exe, args.shader_dir / name], text=True, capture_output=True, encoding="utf-8")
if result.returncode:
raise SystemExit(f"{name}: probe failed ({result.returncode})\n{result.stderr}")
missing = expected.difference(result.stdout.splitlines())
if missing:
raise SystemExit(f"{name}: missing metadata {sorted(missing)}\n{result.stdout}")
print(f"{name}: techniques, bindings and SPIR-V entry points verified")
shaders = tmp / "Shaders"
shaders.mkdir()
invalid = shaders / "effetto-è.fx"
invalid.write_text('#include "missing.fxh"\n', encoding="utf-8")
result = subprocess.run([exe, invalid], text=True, capture_output=True, encoding="utf-8")
if result.returncode != 1 or "missing.fxh" not in result.stderr:
raise SystemExit(f"Missing include was not reported: {result.stderr}")
print("Missing include: diagnostic verified with a non-ASCII source path")
(tmp / "outside.fxh").write_text('#error OUTSIDE_SHADER_ROOT\n', encoding="utf-8")
invalid.write_text('#define OUTSIDE "../outside.fxh"\n#include OUTSIDE\n', encoding="utf-8")
result = subprocess.run([exe, invalid], text=True, capture_output=True, encoding="utf-8")
if result.returncode != 1 or "could not open included file" not in result.stderr or "OUTSIDE_SHADER_ROOT" in result.stderr:
raise SystemExit(f"Include left the shader root: {result.stderr}")
print("Include confinement: macro-expanded traversal blocked")
preset = tmp / "Preset.ini"
preset.write_text("\ufeffTechniques=A@one.fx,B@two.fx\nTechniqueSorting=B@two.fx,A@one.fx\n"
"PreprocessorDefinitions=SWITCH=1\n[one.fx]\nPreprocessorDefinitions=SWITCH=2\n"
"Amount=0.5\n", encoding="utf-8")
result = subprocess.run([exe, preset], check=True, text=True, capture_output=True, encoding="utf-8")
expected = ["B@two.fx", "A@one.fx", "SWITCH=2", "Amount=0.5"]
if result.stdout.splitlines() != expected:
raise SystemExit(f"Preset metadata differs: {result.stdout}")
print("Preset INI: technique order, local definitions and uniform values verified")
result = subprocess.run([exe, "--builtins"], text=True, capture_output=True, encoding="utf-8")
if result.returncode:
raise SystemExit(f"Built-in effects failed: {result.stderr}")
print("Built-in presets compile their fullscreen shader and supply the expected uniforms")
example = probe_source / "examples" / "TintedHighlights.fx"
result = subprocess.run([exe, example], check=True, text=True, capture_output=True, encoding="utf-8")
if "technique TintedHighlights 2" not in result.stdout.splitlines() or result.stdout.count("bindings 1 1") != 2:
raise SystemExit(f"TintedHighlights: unexpected pass bindings:\n{result.stdout}")
print("TintedHighlights: both graphics passes compile with their texture bindings")
def chunk(kind, data):
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))
png = tmp / "LUT.png"
png.write_bytes(b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 1, 1, 8, 6, 0, 0, 0)) +
chunk(b"IDAT", zlib.compress(bytes([0, 17, 34, 51, 255]))) + chunk(b"IEND", b""))
result = subprocess.run([exe, png], text=True, capture_output=True, encoding="utf-8")
if result.returncode or result.stdout.strip() != "1x1 17 34 51 255":
raise SystemExit(f"PNG input did not retain RGBA values: {result.stdout} {result.stderr}")
print("PNG texture: RGBA values verified")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,44 @@
texture Scene : COLOR;
texture HighlightMask {
Width = BUFFER_WIDTH / 2;
Height = BUFFER_HEIGHT / 2;
Format = RGBA16F;
};
sampler SceneSampler { Texture = Scene; };
sampler MaskSampler { Texture = HighlightMask; };
void Fullscreen(uint id : SV_VertexID, out float4 position : SV_Position, out float2 uv : TEXCOORD0)
{
uv = float2((id << 1) & 2, id & 2);
position = float4(uv * float2(2.0, -2.0) + float2(-1.0, 1.0), 0.0, 1.0);
}
float4 MakeMask(float4 position : SV_Position, float2 uv : TEXCOORD0) : SV_Target
{
float3 rgb = tex2D(SceneSampler, uv).rgb;
float luma = dot(rgb, float3(0.2126, 0.7152, 0.0722));
return float4(smoothstep(0.32, 0.9, luma).xxx, 1.0);
}
float4 MakeTint(float4 position : SV_Position, float2 uv : TEXCOORD0) : SV_Target
{
return float4(float3(0.20, 0.07, 0.01) * tex2D(MaskSampler, uv).r, 0.0);
}
technique TintedHighlights
{
pass Extract {
VertexShader = Fullscreen;
PixelShader = MakeMask;
RenderTarget = HighlightMask;
}
pass Apply {
VertexShader = Fullscreen;
PixelShader = MakeTint;
BlendEnable = true;
SrcBlend = ONE;
DestBlend = ONE;
ColorWriteMask = 7;
}
}

View File

@@ -0,0 +1 @@
Techniques=TintedHighlights@TintedHighlights.fx

View File

@@ -0,0 +1,115 @@
#include "fx_builtin.h"
#include "fx_compile.h"
#include "fx_preset.h"
#include "fx_texture.h"
#include <algorithm>
#include <iostream>
using reshadefx::shader_type;
static constexpr tf::reshade::FxCompileOptions options{1920, 1080, 60000, 1, 28, 8};
static int probe(const std::filesystem::path& path) {
if (path == "--builtins") {
using namespace tf::reshade;
std::string error;
using namespace mkwvk::reshade;
if (clarity_presets.size() != 20 || builtin_preset(0).shader || builtin_preset(user_preset).shader ||
builtin_preset(last_builtin_preset + 1).shader) return 1;
if (supports_color_space(true, false, false) || !supports_color_space(true, true, false) ||
supports_color_space(false, true, false) || !supports_color_space(false, false, false)) return 1;
for (int i = 1; i <= last_builtin_preset; ++i) {
if (i == user_preset) continue;
const auto included = builtin_preset(i);
const auto preset = parse_preset(included.ini, error);
if (!preset || preset->techniques.size() != 1) return 1;
const auto& tech = preset->techniques[0];
if (!supports_color_space(true, preset->linear_hdr, true)) return 1;
const auto validate = [&](const FxCompileOptions& target) {
const auto fx = compile_builtin_fx(included.source(), target, error, tech.shader);
if (!fx) {
std::cerr << error;
return false;
}
const auto technique = std::ranges::find(fx->module.techniques, tech.name, &reshadefx::technique::name);
if (technique == fx->module.techniques.end() || technique->passes.size() != 1 || fx->shaders.size() < 2) return false;
const auto section = preset->shader_options.find(tech.shader);
if (section == preset->shader_options.end()) return fx->module.uniforms.empty();
for (const auto& [name, value] : section->second) {
const auto uniform = std::ranges::find(fx->module.uniforms, name, &reshadefx::uniform::name);
if (uniform == fx->module.uniforms.end() || uniform->type.rows != 1 + std::ranges::count(value, ',')) return false;
}
return true;
};
if (!validate({1920, 1080, 60000, 2, 10, 16}) || (!preset->linear_hdr && !validate(options))) return 1;
}
return 0;
}
if (path.extension() == ".png") {
std::string diagnostics;
const auto pixels = tf::reshade::load_png(path.parent_path(), path.filename(), diagnostics);
if (!pixels) {
std::cerr << diagnostics;
return 1;
}
std::cout << pixels->width << 'x' << pixels->height;
for (auto i : pixels->rgba) std::cout << ' ' << unsigned(i);
std::cout << '\n';
return 0;
}
if (path.extension() == ".ini") {
std::string diagnostics;
const auto preset = tf::reshade::load_preset(path.parent_path(), path.filename(), diagnostics);
if (!preset) {
std::cerr << diagnostics << '\n';
return 1;
}
for (const auto& t : preset->techniques) std::cout << t.name << '@' << t.shader << '\n';
for (const auto& [key, value] : tf::reshade::preset_definitions(*preset, "one.fx"))
std::cout << key << '=' << value << '\n';
for (const auto& [key, value] : preset->shader_options.at("one.fx"))
if (key != "PreprocessorDefinitions") std::cout << key << '=' << value << '\n';
return 0;
}
const std::filesystem::path includes[] = {path.parent_path()};
std::string diagnostics;
const auto effect = tf::reshade::compile_fx(path, includes, options, diagnostics);
std::cerr << diagnostics;
if (!effect) return 1;
const auto has_shader = [&](const std::string& name, shader_type stage) {
return std::ranges::any_of(effect->shaders, [&](const auto& shader) {
return shader.name == name && shader.stage == stage && shader.spirv.size() > 5 &&
shader.spirv.front() == 0x07230203;
});
};
for (const auto& technique : effect->module.techniques) {
std::cout << "technique " << technique.name << ' ' << technique.passes.size() << '\n';
for (const auto& pass : technique.passes) {
const bool valid = pass.cs_entry_point.empty()
? has_shader(pass.vs_entry_point, shader_type::vertex) && has_shader(pass.ps_entry_point, shader_type::pixel)
: has_shader(pass.cs_entry_point, shader_type::compute);
if (!valid) {
std::cerr << "Missing SPIR-V entry point for " << technique.name << '\n';
return 1;
}
std::cout << "bindings " << pass.texture_bindings.size() << ' ' << pass.sampler_bindings.size() << '\n';
}
}
for (const auto& uniform : effect->module.uniforms) std::cout << "uniform " << uniform.name << '\n';
for (const auto& texture : effect->module.textures) std::cout << "texture " << texture.name << '\n';
return 0;
}
#ifdef _WIN32
int wmain(int argc, wchar_t** argv) {
#else
int main(int argc, char** argv) {
#endif
if (argc != 2) {
std::cerr << "Usage: fx_probe <effect.fx>\n";
return 2;
}
return probe(argv[1]);
}

694
scripts/triforce_ctl.py Normal file
View File

@@ -0,0 +1,694 @@
"""A client for the game's control bridge (host/control.c; its first comment is the protocol): start the game with HOS_CONTROL=<socket>, then
steer it and read its state from a shell, a test or a coding agent. Standard library only.
python -I scripts/triforce_ctl.py [--sock S] [--json] COMMAND ...
launch GAME_DIR [--data DIR] [--headless] start the game with the bridge on; prints the socket's path
[--save FOLDER [--slot NN]] a copy of a save folder (one slot of it) as the run's saves
status frame, fps, draws, state, window, version, OoT snapshot
press A+B [--frames 8] [--exclusive] buttons held for some frames (the reply once they are let go)
stick L 0 1 [--frames 60] a stick at x, y (-1 to 1)
sequence '0:A/8,60:A/8' [--hos] steps, <at>:<buttons>[/<frames held>] (--hos: HOS_INPUT_SCRIPT's s and ms)
release [--all] this client's queued inputs let go (and those of clients gone)
shot [out.png] [--after FRAME] a PNG of the next present; prints its path
wait in_play [--timeout 120] also: present --frames N, frame --frame N, state --state S,
loading_start, loading_end, change, map [--map NAME]
teleport [INDEX|MAP] [--arrive SECS] (OoT) the debug teleport: sent or refused; none: the destinations
age [child|adult] [--arrive SECS] (OoT) the Debug tab's Switch age (none: the other age), reloading the map
option get [NAME] / option set NAME VALUE the Options screen's settings
saves / slots [--thumbs DIR] the save folder the game uses; its slots, newest first
watch [--events present,state,log,map,oot] [--every 60] [--log TEXT] [--count N]
[--flags NAME,0xHASH,...] [--changes] oot: watched values and changed flags
mem read ADDR SIZE [--format hex|u8|u16|u32|u64|f32] read guest memory (HOS_CONTROL_MEM=ro or rw)
mem write ADDR HEX write guest memory (HOS_CONTROL_MEM=rw); aliases: ro->r/read, rw->readwrite
record start [FILE] [--route] / record stop an input recording from Link's next update (host/input_movie.c);
none named: <user>/recordings/; --route: no guest words
play start [FILE] [--sync N] [--sync-max M] / play stop a recording given back from Link's next update (none
named: the last made), Link and the camera put back every N-th update
while within M metres (1 and 1; --sync 0: never); status says how it goes
quit the game exits
raw '{"cmd": "status"}' any request
The socket defaults to $HOS_CONTROL. Plain lines by default, --json for the replies as they come. Exit status: 0 done,
1 an error reply, 2 no game or bad usage, 3 a timeout.
"""
import argparse
import contextlib
import json
import math
import os
import re
import socket
import stat
import subprocess
import sys
import tempfile
import time
WINDOWS = os.name == "nt"
class Failed(Exception):
def __init__(self, message, code=1):
super().__init__(message)
self.code = code
def open_windows_pipe(name, timeout):
"""Open a local pipe, retrying only the Windows busy error until the deadline."""
import ctypes
import msvcrt
from ctypes import wintypes
kernel = ctypes.WinDLL("kernel32", use_last_error=True)
create = kernel.CreateFileW
create.argtypes = (wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, wintypes.LPVOID,
wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE)
create.restype = wintypes.HANDLE
kernel.CloseHandle.argtypes = (wintypes.HANDLE,)
deadline = time.monotonic() + timeout
while True:
handle = create(name, 0xC0000000, 0, None, 3, 0, None) # read/write, OPEN_EXISTING
if handle != ctypes.c_void_p(-1).value:
try:
fd = msvcrt.open_osfhandle(handle, os.O_RDWR | os.O_BINARY)
except BaseException:
kernel.CloseHandle(handle)
raise
try:
return os.fdopen(fd, "r+b", buffering=0)
except BaseException:
with contextlib.suppress(OSError):
os.close(fd)
raise
error = ctypes.get_last_error()
if error != 231 or time.monotonic() >= deadline: # ERROR_PIPE_BUSY only
raise ctypes.WinError(error)
time.sleep(min(0.02, max(0, deadline - time.monotonic())))
class Bridge:
"""One connection: requests with ids, replies matched to them, events kept for watch"""
def __init__(self, path, timeout=10.0):
self.path, self.next_id, self.pending = path, 0, b""
try:
if WINDOWS:
name = path if path.startswith("\\\\.\\pipe\\") else "\\\\.\\pipe\\" + path
self.sock = None
self.pipe = open_windows_pipe(name, timeout)
else:
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.settimeout(timeout)
self.sock.connect(path)
except OSError as e:
raise Failed("no game listens on %s (%s)" % (path, e.strerror or e), 2)
def close(self):
(self.sock or self.pipe).close()
def send(self, obj):
data = (json.dumps(obj, separators=(",", ":")) + "\n").encode()
if self.sock:
self.sock.sendall(data)
else:
self.pipe.write(data)
def line(self, timeout):
"""The next line as an object; None when the game went away"""
deadline = time.monotonic() + timeout
while b"\n" not in self.pending:
left = deadline - time.monotonic()
if left <= 0:
raise Failed("no answer from the game in %.0f s" % timeout, 3)
try:
if self.sock:
self.sock.settimeout(left)
chunk = self.sock.recv(65536)
else:
chunk = self._pipe_read(left)
if chunk is None:
continue
except socket.timeout:
raise Failed("no answer from the game in %.0f s" % timeout, 3)
except OSError:
chunk = b""
if not chunk:
return None
self.pending += chunk
text, self.pending = self.pending.split(b"\n", 1)
return json.loads(text.decode("utf-8", "replace"))
def _pipe_read(self, left):
"""(Windows) what the pipe holds, after waiting up to `left` seconds for some: None for nothing yet, b"" when the
bridge's end closed. PeekNamedPipe and then a read of only what is there: a read that blocks would hold the
handle's writes too (one synchronous handle)"""
import ctypes
import msvcrt
handle = msvcrt.get_osfhandle(self.pipe.fileno())
avail = ctypes.c_ulong(0)
end = time.monotonic() + min(left, 0.05)
while True:
if not ctypes.windll.kernel32.PeekNamedPipe(ctypes.c_void_p(handle), None, 0, None, ctypes.byref(avail), None):
return b""
if avail.value:
return self.pipe.read(avail.value)
if time.monotonic() >= end:
return None
time.sleep(0.002)
def request(self, cmd, timeout=None, **args):
"""The reply to one request (events that come meanwhile are dropped). Without a timeout the bridge's own default
holds (for an input: 30 s plus its frames at 10 fps, so a long one can take hours): the client then waits as
long as the bridge can (an hour at most), unless the connection ends"""
self.next_id += 1
rid = self.next_id
req = {"id": rid, "cmd": cmd}
req.update({k: v for k, v in args.items() if v is not None})
if timeout is not None:
req["timeout"] = timeout
self.send(req)
wait = (timeout if timeout is not None else 3600 if cmd in ("press", "stick", "sequence") else 60) + 10
deadline = time.monotonic() + wait
while True: # (one deadline: an event line that comes meanwhile does not start the wait again)
left = deadline - time.monotonic()
if left <= 0 and b"\n" not in self.pending:
raise Failed("no answer from the game in %.0f s" % wait, 3)
msg = self.line(max(0, left))
if msg is None:
if cmd == "quit":
return {"id": rid, "ok": True, "quitting": True}
raise Failed("the game closed the connection", 2)
if msg.get("id") == rid and "ok" in msg:
return msg
def plain_text(text):
"""Text from the game for a terminal: its control characters (an escape sequence in a log line) shown as '?'"""
return "".join("?" if ord(ch) < 0x20 or 0x7f <= ord(ch) < 0xa0 else ch for ch in str(text))
def when(t):
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(t)) if t else "-"
def saves_text(r):
lines = ["%s (account.sav %s, option.sav %s)" % (plain_text(r["path"]), "yes" if r["account"] else "no",
"yes" if r["option"] else "no")]
for sl in r["slots"]:
lines.append("slot_%s %s%s" % (plain_text(sl["slot"]), when(sl["mtime"]), " (newest)" if sl["newest"] else ""))
for f in sorted(sl["files"], key=lambda f: f["name"]):
lines.append(" %-14s %9d %s" % (plain_text(f["name"]), f["size"], when(f["mtime"])))
return "\n".join(lines)
def slots_text(r):
rows = [" slot last written progress caption scene"]
for sl in r["slots"]:
size = {f["name"]: f["size"] for f in sl["files"]}
rows.append("%s %-4s %-19s %9s %9s %s" % ("*" if sl["newest"] else " ", plain_text(sl["slot"]), when(sl["mtime"]),
size.get("progress.sav", "-"), size.get("caption.sav", "-"),
plain_text(sl.get("caption", {}).get("scene", ""))))
rows.append("(* the newest: the one Continue loads)")
return "\n".join(rows)
def write_thumbs(r, folder):
"""Each slot's file-select picture, as the JPEG caption.sav holds, read from the save folder (this PC's). What the game
says is checked first: this client may run outside a sandbox the game is in, so a slot's name is only digits, the
picture a bounded slice of that slot's caption.sav, and nothing is written outside folder"""
os.makedirs(folder, exist_ok=True)
for sl in r["slots"]:
th = sl.get("caption", {}).get("thumbnail")
if not th:
continue
slot, off, size = sl.get("slot"), th.get("offset"), th.get("size")
if not (isinstance(slot, str) and re.fullmatch(r"[0-9]{1,3}", slot) and isinstance(off, int) and
isinstance(size, int) and 0 <= off < (1 << 24) and 0 < size <= (4 << 20)):
raise Failed("slots --thumbs: the game's reply does not look like a save listing: %r" % (sl,), 1)
with open(os.path.join(r["path"], "slot_" + slot, "caption.sav"), "rb") as f:
f.seek(off)
data = f.read(size)
if data[:2] == b"\xff\xd8":
with open(os.path.join(folder, "slot_%s.jpg" % sl["slot"]), "wb") as out:
out.write(data)
def addr_of(text):
try:
return int(text, 0)
except ValueError:
raise Failed("ADDR: a number, or 0x...", 2)
def format_bytes(data, fmt):
import struct
if fmt in (None, "hex"):
return data.hex()
if fmt == "base64":
import base64
return base64.b64encode(data).decode()
sizes = {"u8": ("B", 1), "u16": ("<H", 2), "u32": ("<I", 4), "u64": ("<Q", 8), "f32": ("<f", 4)}
code, n = sizes[fmt]
out = []
for i in range(0, len(data) - n + 1, n):
out.append(struct.unpack(code, data[i:i + n])[0])
return " ".join(("%g" if fmt == "f32" else "%d") % v for v in out)
def connect(a, timeout=10.0):
path = a.sock or os.environ.get("HOS_CONTROL")
if not path:
raise Failed("no socket: give --sock PATH or set HOS_CONTROL (triforce_ctl.py launch GAME_DIR starts a game "
"with the bridge on and prints its socket)", 2)
return Bridge(path, timeout)
def check(reply):
if not reply.get("ok"):
code = 3 if reply.get("error") == "timeout" else 1
raise Failed("%s: %s" % (reply.get("error", "error"), reply.get("message", "")), code)
return reply
def show(a, reply, plain):
if a.json:
print(json.dumps(reply))
else:
print(plain(reply))
def run(a):
if a.command == "launch":
return launch(a)
if a.command == "mem":
a.addr = addr_of(a.addr)
if a.action == "read":
if a.size is None:
raise Failed("mem read ADDR SIZE", 2)
a.size = addr_of(str(a.size))
else:
a.hex = a.hex if a.hex is not None else a.size # write ADDR HEX
if not a.hex:
raise Failed("mem write ADDR HEX", 2)
b = connect(a)
try:
if a.command == "status":
r = check(b.request("status"))
win = r.get("window") or {}
g = r.get("game") or {}
flags = " ".join(n for n, on in (("event", g.get("event")), ("loading", g.get("loading"))) if on)
show(a, r, lambda r: "frame %d fps %.1f state %s draws %s window %s map %s%s %s" % (
r["frame"], r["fps"], r["state"], "-" if r.get("draws") is None else "%.0f" % r["draws"],
"%dx%d" % (win["width"], win["height"]) if win else "-", plain_text(r.get("map") or "-"),
" (%s%s)" % (plain_text(g.get("age", "?")), ", " + flags if flags else "") if g else "",
plain_text(r.get("version", ""))) + ("\ngame " + json.dumps(g, ensure_ascii=True) if g else ""))
elif a.command in ("press", "stick", "sequence"):
args = {"exclusive": True if a.exclusive else None, "wait": False if a.no_wait else None}
if a.command == "press":
args.update(buttons=a.buttons, frames=a.frames, at=a.at)
elif a.command == "stick":
args.update(stick=a.which.upper(), x=a.x, y=a.y, frames=a.frames, at=a.at)
else:
args.update(script=a.script.strip(), units="hos" if a.hos else None)
r = check(b.request(a.command, timeout=a.timeout, **args))
show(a, r, lambda r: "queued %d input(s) at frame %d" % (r["queued"], r["frame"]) if "queued" in r
else "frames %d to %d (now %d)" % (r["start"], r["end"], r["frame"]))
elif a.command == "release":
show(a, check(b.request("release", all=True if a.all else None)),
lambda r: "released %d%s" % (r["released"], " (every client's)" if a.all else ""))
elif a.command == "shot":
path = os.path.abspath(a.path) if a.path else None # (the bridge would take it as the socket folder's)
r = check(b.request("shot", timeout=a.timeout, path=path, after=a.after))
show(a, r, lambda r: r["path"])
elif a.command == "wait":
r = check(b.request("wait", timeout=a.timeout, event=a.event, frames=a.frames, frame=a.frame, state=a.state,
map=a.map))
show(a, r, lambda r: "%s after %d frames (frame %d)%s" % (r["state"], r["waited"], r["frame"],
" map %s" % plain_text(r["map"]) if "map" in r else ""))
elif a.command == "teleport":
to = None if a.to is None else int(a.to) if a.to.isdigit() else a.to
if to is None and (a.arrive or a.no_wait):
raise Failed("teleport: --arrive and --no-wait go with a destination", 2)
r = check(b.request("teleport", to=to, wait=False if a.no_wait else None,
timeout=None if to is None else a.timeout))
if "destinations" in r:
show(a, r, lambda r: "\n".join("%3d %-28s %s" % (d["index"], plain_text(d["child"] or "-"),
plain_text(d["adult"] or "-")) for d in r["destinations"]))
elif not r.get("sent"):
show(a, r, lambda r: "teleport %d asked for (child %s, adult %s): wait map to see it arrive" % (
r["teleport"], plain_text(r["child"] or "-"), plain_text(r["adult"] or "-")))
elif not a.arrive:
show(a, r, lambda r: "teleport %d sent: to %s%s" % (
r["teleport"], plain_text(r.get("map") or "-"),
"" if r.get("accepted", True) else " (but the game's event manager did not take it)"))
else: # (and until the game is in that map: the arrival)
w = check(b.request("wait", timeout=a.arrive, event="map", map=r.get("map")))
show(a, dict(r, arrived=w), lambda r: "teleport %d: in %s after %d frames (frame %d)" % (
r["teleport"], plain_text(w["map"]), w["waited"], w["frame"]))
elif a.command == "age":
r = check(b.request("age", to=a.to, wait=False if a.no_wait else None, timeout=a.timeout))
if r.get("sent") is False:
show(a, r, lambda r: "Link is the %s already" % plain_text(r["age"]))
elif r.get("sent") is None:
show(a, r, lambda r: "age switch to the %s asked for: wait loading_end to see it reload" % plain_text(r["age"]))
elif not a.arrive:
show(a, r, lambda r: "age switch sent: the %s, reloading %s%s" % (
plain_text(r["age"]), plain_text(r.get("map") or "-"),
"" if r.get("accepted", True) else " (but the game's event manager did not take it)"))
else: # (and until the reload's load has ended: in a dungeon the map has the same name for both ages, so
# a wait map would be met before the reload; loading_end counts from the ask, so a load already
# started when it is asked is still waited out)
w = check(b.request("wait", timeout=a.arrive, event="loading_end"))
show(a, dict(r, arrived=w), lambda r: "age switch: the %s, in %s after %d frames (frame %d)" % (
plain_text(r["age"]), plain_text(r.get("map") or "-"), w["waited"], w["frame"]))
elif a.command == "option":
if a.action == "get":
r = check(b.request("option_get", name=a.name))
rows = [r["option"]] if "option" in r else r["options"]
show(a, r, lambda r: "\n".join("%-28s %4d %s%s" % (o["key"], o["value"], plain_text(o["text"]),
" (restart)" if o.get("restart") else "") for o in rows))
else:
if a.value is None:
raise Failed("option set NAME VALUE", 2)
v = {"on": 1, "true": 1, "off": 0, "false": 0}.get(a.value.lower())
if v is None:
try:
v = int(a.value)
except ValueError:
raise Failed("VALUE: a number, on or off", 2)
r = check(b.request("option_set", name=a.name, value=v))
show(a, r, lambda r: "%s %d -> %d (%s)" % (r["option"]["key"], r["was"], r["option"]["value"], r["option"]["text"]))
elif a.command == "mem":
if a.action == "read":
fmt = a.format if a.format in ("hex", "base64") else "hex"
r = check(b.request("mem_read", addr=a.addr, size=a.size, format=fmt))
data = bytes.fromhex(r["data"]) if r["format"] == "hex" else __import__("base64").b64decode(r["data"])
show(a, r, lambda r: format_bytes(data, a.format))
else:
raw = a.hex.lower().replace("0x", "")
try:
bytes.fromhex(raw)
except ValueError:
raise Failed("HEX: an even number of hex digits", 2)
r = check(b.request("mem_write", addr=a.addr, hex=raw))
show(a, r, lambda r: "wrote %d bytes at %d" % (r["wrote"], r["addr"]))
elif a.command == "saves":
r = check(b.request("saves"))
show(a, r, lambda r: saves_text(r))
elif a.command == "slots":
r = check(b.request("saves"))
if a.thumbs:
write_thumbs(r, a.thumbs)
if a.json:
print(json.dumps(r["slots"]))
else:
print(slots_text(r))
elif a.command == "record":
if a.action == "stop":
r = check(b.request("record", action="stop"))
show(a, r, lambda r: ("recorded to %s" if r.get("written") else "stopped: %s was not written (it had not "
"started yet, or could not be)") % plain_text(r.get("path") or "-"))
else:
r = check(b.request("record", action="start", path=a.path, route=True if a.route else None))
show(a, r, lambda r: "recording from Link's next update to %s" % plain_text(r.get("path") or "-"))
elif a.command == "play":
if a.action == "stop":
show(a, check(b.request("play", action="stop")), lambda r: "playback stopped")
else:
r = check(b.request("play", action="start", path=a.path, sync=a.sync, sync_max=a.sync_max))
show(a, r, lambda r: "playback from Link's next update (status: its recorder)")
elif a.command == "quit":
show(a, check(b.request("quit")), lambda r: "quitting")
elif a.command == "raw":
req = json.loads(a.request)
b.next_id += 1
req.setdefault("id", b.next_id)
b.send(req)
while True:
msg = b.line(float(req.get("timeout", 60)) + 10)
if msg is None:
raise Failed("the game closed the connection", 2)
if msg.get("id") == req["id"] and "ok" in msg:
print(json.dumps(msg))
return 0 if msg["ok"] else 1
elif a.command == "watch":
# (--log alone: the log lines only; with --events, those and the log lines)
events = [e for e in (a.events or ("" if a.log else "present,state")).split(",") if e]
if a.log and "log" not in events:
events.append("log")
check(b.request("subscribe", events=events, every=a.every, log=a.log,
flags=a.flags.split(",") if a.flags is not None else None,
changes=True if a.changes else None))
n = 0
while a.count is None or n < a.count:
msg = b.line(3600 * 24)
if msg is None:
return 0
if "event" not in msg:
continue
n += 1
if a.json:
print(json.dumps(msg), flush=True)
elif msg["event"] == "log":
print("log %s" % plain_text(msg["line"]), flush=True)
elif msg["event"] == "state":
print("state frame %d: %s -> %s" % (msg["frame"], msg["from"], msg["state"]), flush=True)
elif msg["event"] == "present":
print("frame %d fps %.1f %s" % (msg["frame"], msg["fps"], msg["state"]), flush=True)
elif msg["event"] == "map":
print("map frame %d: %s -> %s" % (msg["frame"], plain_text(msg["from"] or "-"), plain_text(msg["map"])),
flush=True)
elif msg["event"] == "oot":
print("game " + json.dumps(msg["game"], ensure_ascii=True), flush=True)
else:
print(json.dumps(msg), flush=True)
return 0
finally:
b.close()
# (the one account the runtime has, host/nn_applet.c user_uid: its saves are <data>/triforce/user/save/<this>)
SAVE_USER = "5a3c9e1f0b7d24680000000000000001"
def slot_name(text):
"""03, 3 or slot_03 -> slot_03"""
t = text[5:] if text.lower().startswith("slot_") else text
if not t.isdigit() or len(t) > 2:
raise Failed("--slot: a slot number, 03 or slot_03", 2)
return "slot_%02d" % int(t)
def plain_tree(path):
"""Refused (Failed) when path or anything under it is a link or not a plain file or folder: a save from elsewhere could
hold a link to one of this user's files, which the copy would read and the game then write through"""
for top, dirs, files in os.walk(path):
for n in [top] + [os.path.join(top, d) for d in dirs] + [os.path.join(top, f) for f in files]:
st = os.lstat(n)
if not (stat.S_ISDIR(st.st_mode) or stat.S_ISREG(st.st_mode)):
raise Failed("--save: %s is a link or not a plain file: refused" % n, 2)
def copy_save(src, data, slot=None):
"""A save folder (account.sav, option.sav, slot_NN/) copied to where the game reads it in the data folder; with slot,
that slot alone (so Continue loads it). The source is only read, and holds plain files and folders only (no links).
Returns the destination"""
import shutil
src = os.path.abspath(src)
if os.path.islink(src) or not os.path.isdir(src):
raise Failed("--save: %s is not a folder" % src, 2)
plain_tree(src)
names = os.listdir(src)
slots = sorted(n for n in names if n.startswith("slot_") and os.path.isdir(os.path.join(src, n)))
if not slots or not ({"account.sav", "option.sav"} & set(names)):
raise Failed("--save: %s does not look like a save folder (account.sav or option.sav, and slot_NN folders): "
"it is <data>/triforce/user/save/<user id>" % src, 2)
if slot is not None:
slot = slot_name(slot)
if slot not in slots:
raise Failed("--save: %s has no %s (it has %s)" % (src, slot, ", ".join(slots)), 2)
dest = os.path.join(os.path.abspath(data), "triforce", "user", "save", SAVE_USER)
if os.path.exists(dest) and os.listdir(dest):
raise Failed("--save: %s already holds saves: give an empty --data (or none: the run folder's own)" % dest, 2)
os.makedirs(dest, exist_ok=True)
for n in names:
p = os.path.join(src, n)
if n.startswith("slot_") and os.path.isdir(p):
if slot is None or n == slot:
shutil.copytree(p, os.path.join(dest, n), symlinks=True) # (none: plain_tree; never followed)
elif os.path.isfile(p):
shutil.copy2(p, os.path.join(dest, n), follow_symlinks=False)
return dest
def launch(a):
"""The game in GAME_DIR with HOS_CONTROL set, its socket in a run folder of its own; waits until it answers"""
game = os.path.abspath(a.game_dir)
exe = os.path.join(game, "Triforce.exe" if WINDOWS else "triforce")
if not os.path.isfile(exe):
raise Failed("no game at %s" % exe, 2)
run_dir = os.path.abspath(a.run) if a.run else tempfile.mkdtemp(prefix="triforce-control-",
dir=os.environ.get("XDG_RUNTIME_DIR") or None)
os.makedirs(run_dir, mode=0o700, exist_ok=True)
sock = a.sock or ("triforce-control-%d" % os.getpid() if WINDOWS else os.path.join(run_dir, "control.sock"))
if not WINDOWS:
sock = os.path.abspath(sock) # (the game runs in its own folder: a relative path would be bound there)
env = dict(os.environ, HOS_CONTROL=sock)
if a.slot and not a.save:
raise Failed("--slot goes with --save", 2)
data = a.data or (os.path.join(run_dir, "data") if a.save else None)
if a.save:
if WINDOWS:
raise Failed("--save: Linux only (on Windows the game keeps its saves in its own folder)", 2)
copy_save(a.save, data, a.slot)
if data:
env["XDG_DATA_HOME"] = os.path.abspath(data)
if a.headless:
env["HOS_HEADLESS"] = "1"
for kv in a.env:
if "=" not in kv:
raise Failed("--env NAME=VALUE", 2)
k, v = kv.split("=", 1)
env[k] = v
log = os.path.join(run_dir, "log.txt")
with open(log, "wb") as out:
kw = {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} if WINDOWS else {"start_new_session": True}
p = subprocess.Popen([exe], cwd=game, env=env, stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.STDOUT, **kw)
deadline = time.monotonic() + a.timeout
while True:
if p.poll() is not None:
raise Failed("the game ended (%d) before its bridge answered: %s" % (p.returncode, log), 2)
try:
b = Bridge(sock, 5)
r = b.request("status")
b.close()
if r.get("ok"):
break
except Failed:
pass
if time.monotonic() > deadline:
raise Failed("the game's bridge did not answer in %.0f s: %s" % (a.timeout, log), 3)
time.sleep(0.2)
info = {"socket": sock, "pid": p.pid, "run": run_dir, "log": log}
print(json.dumps(info) if a.json else sock)
return 0
def main(argv=None):
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--sock", help="the bridge's socket (default $HOS_CONTROL)")
p.add_argument("--json", action="store_true", help="the replies as JSON lines")
sub = p.add_subparsers(dest="command", required=True)
def finite_float(text):
value = float(text)
if not math.isfinite(value):
raise argparse.ArgumentTypeError("expected a finite number")
return value
def inputs(q):
q.add_argument("--frames", type=int, default=8)
q.add_argument("--at", type=int, default=0, help="frames from the next controller read")
q.add_argument("--exclusive", action="store_true", help="the player's own devices left out meanwhile")
q.add_argument("--no-wait", action="store_true", help="reply as soon as it is queued")
q.add_argument("--timeout", type=finite_float)
q = sub.add_parser("launch", help="start a game folder with the bridge on")
q.add_argument("game_dir")
q.add_argument("--data", help="XDG_DATA_HOME for the run (its saves)")
q.add_argument("--save", help="a save folder (<data>/triforce/user/save/<user id>) copied in first (Linux); the source is "
"only read")
q.add_argument("--slot", help="with --save: that slot alone (03 or slot_03), so Continue loads it")
q.add_argument("--run", help="the run folder (socket, log, shots); default a new one")
q.add_argument("--headless", action="store_true")
q.add_argument("--env", action="append", default=[], metavar="NAME=VALUE")
q.add_argument("--timeout", type=finite_float, default=600, help="seconds to wait for the bridge (shaders may be prepared first)")
sub.add_parser("status")
q = sub.add_parser("press")
q.add_argument("buttons", help="A, A+B, ZL+LUP, LX=-16000 ...")
inputs(q)
q = sub.add_parser("stick")
q.add_argument("which", choices=["L", "R", "l", "r"])
q.add_argument("x", type=finite_float)
q.add_argument("y", type=finite_float)
inputs(q)
q = sub.add_parser("sequence")
q.add_argument("script", help="<at>:<buttons>[/<frames>],...")
q.add_argument("--hos", action="store_true", help="times in seconds and holds in ms, as HOS_INPUT_SCRIPT")
q.add_argument("--exclusive", action="store_true")
q.add_argument("--no-wait", action="store_true")
q.add_argument("--timeout", type=finite_float)
q = sub.add_parser("release", help="let go of this client's queued inputs and those of clients gone")
q.add_argument("--all", action="store_true", help="every client's, also those still connected")
q = sub.add_parser("shot")
q.add_argument("path", nargs="?")
q.add_argument("--after", type=int, help="the first present after this frame")
q.add_argument("--timeout", type=finite_float)
q = sub.add_parser("wait")
q.add_argument("event", choices=["present", "frame", "in_play", "state", "loading_start", "loading_end", "change", "map"])
q.add_argument("--frames", type=int)
q.add_argument("--frame", type=int)
q.add_argument("--state")
q.add_argument("--map", help="map: until the game is in this map (default: any other map than now)")
q.add_argument("--timeout", type=finite_float, default=60)
q = sub.add_parser("option")
q.add_argument("action", choices=["get", "set"])
q.add_argument("name", nargs="?")
q.add_argument("value", nargs="?")
q = sub.add_parser("watch")
q.add_argument("--events", help="present,state,log,map,oot (default present,state; with --log alone, log)")
q.add_argument("--every", type=int, default=60)
q.add_argument("--log", help="log lines that contain this text (adds log to the events)")
q.add_argument("--count", type=int, help="stop after this many events")
q.add_argument("--flags", help="with --events oot: comma-separated flag names or 0x and eight hex digits")
q.add_argument("--changes", action="store_true", help="with --events oot: changed Bool/Int/Enum/UInt flags")
q = sub.add_parser("mem")
q.add_argument("action", choices=["read", "write"])
q.add_argument("addr", help="a guest address, decimal or 0x...")
q.add_argument("size", nargs="?", help="read: how many bytes")
q.add_argument("hex", nargs="?", help="write: the bytes as hex")
q.add_argument("--format", default="hex", choices=["hex", "base64", "u8", "u16", "u32", "u64", "f32"],
help="read: how to print the bytes")
q = sub.add_parser("teleport", help="(OoT) the debug teleport: a destination's index or map; none lists them")
q.add_argument("to", nargs="?")
q.add_argument("--timeout", type=finite_float, default=10, help="seconds for the game to take it (it does in play)")
q.add_argument("--arrive", type=finite_float, metavar="SECS", help="then wait up to SECS until the game is in the map")
q.add_argument("--no-wait", action="store_true", help="reply once asked, without whether the game took it")
q = sub.add_parser("age", help="(OoT) the Debug tab's Switch age: child or adult (none: the other age)")
q.add_argument("to", nargs="?", choices=["child", "adult"])
q.add_argument("--timeout", type=finite_float, default=10, help="seconds for the game to take it (it does in play)")
q.add_argument("--arrive", type=finite_float, metavar="SECS", help="then wait up to SECS until the map has reloaded (its "
"load ended)")
q.add_argument("--no-wait", action="store_true", help="reply once asked, without whether the game took it")
sub.add_parser("saves", help="the save folder the game uses: its files, newest slot first")
q = sub.add_parser("slots", help="the save slots: last written, sizes, scene; * the newest (Continue's)")
q.add_argument("--thumbs", metavar="DIR", help="each slot's file-select picture written there as slot_NN.jpg")
q = sub.add_parser("record", help="an input recording from Link's next update (host/input_movie.c)")
q.add_argument("action", choices=["start", "stop"])
q.add_argument("path", nargs="?", help="the file (none: <user>/recordings/<date>-<time>-<map>.jsonl)")
q.add_argument("--route", action="store_true", help="no guest words or addresses in it")
q = sub.add_parser("play", help="an input recording given back from Link's next update")
q.add_argument("action", choices=["start", "stop"])
q.add_argument("path", nargs="?", help="the recording (none: the last made)")
q.add_argument("--sync", type=int, help="Link and the camera put back every N-th update where they left it (0: never)")
q.add_argument("--sync-max", type=finite_float, metavar="M", help="metres past which Link is not put back: diverged")
sub.add_parser("quit")
q = sub.add_parser("raw")
q.add_argument("request", help="a JSON request object")
a = p.parse_args(argv)
try:
return run(a)
except Failed as e:
print("triforce_ctl: %s" % e, file=sys.stderr)
return e.code
except (BrokenPipeError, ConnectionResetError):
print("triforce_ctl: the game closed the connection", file=sys.stderr)
return 2
except json.JSONDecodeError as e:
print("triforce_ctl: not JSON: %s" % e, file=sys.stderr)
return 2
if __name__ == "__main__":
sys.exit(main())

View File

@@ -30,7 +30,7 @@ def name(f):
return r
RUN = prof.RUN_MODS + ("nvoglv64.dll",)
RUN = prof.RUN_MODS + ("nvoglv64.dll", "amdvlk64.dll", "amdxc64.dll", "amdxx64.dll", "igvk64.dll", "igxelpicd64.dll") # ((Triforce) AMD's and Intel's Windows drivers too
DRIVERS = ("libnvidia-glcore.so", "libvulkan_radeon.so", "libvulkan_intel.so") # (Linux: the driver's file has its version after .so)
seen, running = collections.Counter(), collections.Counter()
incl, self_ = collections.Counter(), collections.Counter()