Triforce v0.9.0

Character tab, faster renderer defaults, HD rumble shipped, and the 11-30 bug pass: ending softlock below 60 fps, adult first-night lock, Intel Arc robust buffers, adult map, randomizer load order.
This commit is contained in:
ruckus7382sfgsgdf
2026-11-30 20:55:14 -06:00
parent 8cb23131f9
commit 822ee913bc
86 changed files with 8128 additions and 438 deletions

View File

@@ -262,6 +262,28 @@ static void test_game(void) {
}
}
/* ((Triforce) the Unlimited amiibo uses row: the same figure scanned again and again, each choice right after the game read
the last (the Scan amiibo page sends a figure the game has read again, gpu/vk/vk_menu.cpp names_confirm). The reader side
keeps no count: every touch is read as the first, with the same serial number (the game's own once-a-day check is
host/oot_amiibo_uses.c's) */
static void test_scans_in_a_row(void) {
uint8_t tag[NFP_TAG_INFO_SIZE], model[NFP_MODEL_INFO_SIZE];
const AmiiboTag t = figure();
Nfp n;
nfp_reset(&n);
int64_t now = 1000;
for (int scan = 0; scan < 50; scan++) {
CHECK(nfp_choose(&n, &t) == (scan == 0), "scan %d: the readers are said to change again", scan);
memset(tag, 0, sizeof tag), memset(model, 0, sizeof model);
int calls = 0;
const int64_t from = now;
CHECK(game_task(&n, scan & 1, &now, 500, &calls, tag, model) == 1, "scan %d: the game's task does not read the figure", scan);
CHECK(!memcmp(tag, kUid, 7) && !memcmp(model, kModel, 3), "scan %d: the game is handed another figure", scan);
CHECK(now - from < NFP_HOLD_NS + 100000000, "scan %d: the figure is held longer than the first time", scan);
CHECK(n.said == NFP_SAID_READ && n.holder < 0 && !n.waiting, "scan %d: the figure is not lifted off", scan);
}
}
/* ((Triforce) a Flipper Zero NFC file of the tag: its pages as text; the same figure as the tag's bytes */
static size_t flipper_text(char *out, size_t cap, int pages, int unread_page) {
uint8_t d[540];
@@ -344,6 +366,7 @@ int main(void) {
test_names();
test_readers();
test_game();
test_scans_in_a_row();
if (failures) return printf("%d failures\n", failures), 1;
printf("ok\n");
return 0;

View File

@@ -20,6 +20,14 @@ written) for a handle that is not a listed reader's; the file is opened by a che
its read is bounded; the only file written is the area's, under the amiibo folder's "areas", by the serial number;
nothing names or opens a key; the choice is taken at the pad read; the option ids.
And (Triforce) the System tab's Unlimited amiibo uses row (host/oot_amiibo_uses.c): the same figure read fifty times in a
row through the game's task, each choice right after the last read (the reader side keeps no count); nx2/oot_patches.py's
call at the head of the game's once-a-day check, on a lift of its own making (once, again a no-op, only that function and
only with the calls read there); the host's answer compiled from its source with stubs (Off: 0, nothing of the game read
or written; On: "not used today"); the row Off by default, its option, the renderer's answer and the launcher's copy; the
page sending a figure the game has read again; and the clock's answer that keeps the game's other check (a clock set by
hand) from refusing a figure.
python -I -B tests/test_amiibo.py [--cc gcc]
"""
import argparse
@@ -135,18 +143,128 @@ def check_source():
print("PASS: the SDK's functions answer as before until a figure is chosen, and no key is read")
# ((Triforce) the game's once-a-day check as its lift has it, cut short: its head, today's date, the history's test of a
# figure, its return)
DAY_LIFT = (
'#include "a64.h"\n'
"void f_8328cd20(Ctx *__restrict A64_NOESC c) {\n return;\n}\n"
"void f_8328cd30(Ctx *__restrict A64_NOESC c) {\n"
" uint8_t fn_ = c->n, fz_ = c->z, fc_ = c->c, fv_ = c->v;\n"
"c->x[30] = 0x8328cd74ULL; f_83290a50(c);\n"
" c->x[19]=recomp_load64(c,c->x[8] + 0);\n"
"c->x[30] = 0x8328ce58ULL; f_8328ee40(c);\n"
" return;\n}\n"
"void f_8328ce90(Ctx *__restrict A64_NOESC c) {\n return;\n}\n")
# the host's answer, cut from its file, with stubs: what it asks of the renderer and what it does to the game's registers
DAY_HOST = r"""
#include <stdint.h>
#include <stdio.h>
typedef struct { uint64_t x[32]; } Ctx;
enum { HOS_OPT_AMIIBO_UNLIMITED = %d };
static int row = -1, asked_id = -1, asked_otherwise = -1, logged;
int rx_option(int id, int otherwise) { asked_id = id, asked_otherwise = otherwise; return row < 0 ? otherwise : row; }
void hos_log(const char *fmt, ...) { (void)fmt; logged++; }
%s
int main(void) {
Ctx c;
int bad = 0;
for (int r = -1; r <= 1; r++) { /* (-1: a renderer that does not answer the option: the default) */
for (int i = 0; i < 32; i++) c.x[i] = 0x5500 + i;
row = r, logged = 0;
const int took = hos_oot_amiibo_used_today(&c);
if (asked_id != HOS_OPT_AMIIBO_UNLIMITED || asked_otherwise != 0) bad |= 1;
if (r == 1 && (took != 1 || c.x[0] != 0 || logged != 1)) bad |= 2;
if (r != 1 && (took != 0 || logged)) bad |= 4;
for (int i = r == 1; i < 32; i++) if (c.x[i] != 0x5500ULL + i) bad |= 8;
}
printf(bad ? "bad %%d\n" : "ok\n", bad);
return bad;
}
"""
def menu_row(menu, name):
"""vk_menu.cpp's row of that name: its text from the brace to its end"""
at = menu.index('{TAB_SYSTEM, "%s", ' % name)
return menu[at:menu.index("},\n", at) + 3]
def check_unlimited(cc):
"""(Triforce) The Unlimited amiibo uses row: the patch, the host's answer, the row, its option and the launcher's copy"""
sys.path.insert(0, str(ROOT / "nx2"))
import oot_patches as op
out, n = op.patch_amiibo_uses(DAY_LIFT)
check(n == 1 and out.count(op.AMIIBO_DAY_HEAD + op.AMIIBO_DAY_HOOK) == 1 and out.count(op.AMIIBO_DAY_HOOK) == 1 and
out.count(op.AMIIBO_DAY_DECL) == 1 and out.index(op.AMIIBO_DAY_DECL) < out.index("void f_"),
"the once-a-day check is not called at the head of f_8328cd30, once, declared before the code")
check(op.patch_amiibo_uses(out) == (out, 1), "a second run of the patch changes the lift")
check(out.replace(op.AMIIBO_DAY_HOOK, "").replace(op.AMIIBO_DAY_DECL, "") == DAY_LIFT, "the patch changes more than the call")
other = DAY_LIFT.replace("f_8328cd30", "f_8328cd40")
check(op.patch_amiibo_uses(other) == (other, 0), "another function is patched")
for call in op.AMIIBO_DAY_CALLS: # (another build's function at that address: left as it is)
without = DAY_LIFT.replace(call, " f_80000000(c);\n")
check(op.patch_amiibo_uses(without) == (without, 0), "f_8328cd30 is patched without the call to" + call.strip())
elsewhere = DAY_LIFT.replace(" return;\n}\nvoid f_8328ce90", op.AMIIBO_DAY_HOOK + " return;\n}\nvoid f_8328ce90")
check(op.patch_amiibo_uses(elsewhere) == (elsewhere, 0), "a call away from the function's head is taken as the patch")
patches = (ROOT / "nx2/oot_patches.py").read_text(encoding="utf-8")
apply = patches[patches.index("def apply(gen,"):patches.index("def apply_output_size(")]
check("unlimited, found = patch_amiibo_uses(out)" in apply and "amiibo_sites += found" in apply and
"if protect_hearts and amiibo_sites != 1:" in apply, "the build does not make the call, or does not say when it is not found")
# the host: the row read first; Off, nothing of the game read or written
host = (ROOT / "host/oot_amiibo_uses.c").read_text(encoding="utf-8")
fn = host[host.index("int hos_oot_amiibo_used_today(Ctx *c) {"):]
check(fn.index("if (!rx_option(HOS_OPT_AMIIBO_UNLIMITED, 0)) return 0;") < fn.index("c->x["), "the host reads the game before the row")
check(set(re.findall(r"c->x\[\d+\]", fn)) == {"c->x[0]"} and "recomp_" not in fn and "fopen" not in host and "fwrite" not in host,
"the host touches more of the game than its answer, or writes a file")
api = (ROOT / "gpu/vk/vk_api.h").read_text(encoding="utf-8")
m = re.search(r"enum \{ HOS_OPT_FOV = 200,([^}]*)\};", api)
names = ["HOS_OPT_FOV"] + [w.strip() for w in m.group(1).split(",") if w.strip()]
check("HOS_OPT_AMIIBO_UNLIMITED" in names and api.count("HOS_OPT_AMIIBO_UNLIMITED") == 2, "gpu/vk/vk_api.h: the row's option")
number = 200 + names.index("HOS_OPT_AMIIBO_UNLIMITED")
with tempfile.TemporaryDirectory() as tmp:
src, exe = Path(tmp) / "day.c", Path(tmp) / "day.exe"
src.write_text(DAY_HOST % (number, fn), encoding="utf-8")
subprocess.run([cc, "-std=c11", "-O1", "-Wall", "-Wextra", "-Werror", str(src), "-o", str(exe)], check=True)
run = subprocess.run([str(exe)], capture_output=True, text=True)
check(run.returncode == 0 and run.stdout.strip() == "ok", "the host's answer (Off: the game's own, On: not used today): " + run.stdout)
# the row: the System tab's NFC group, after NFC tag; Off by default; the renderer's answer; the launcher's copy
menu = (ROOT / "gpu/vk/vk_menu.cpp").read_text(encoding="utf-8")
row = menu_row(menu, "Unlimited amiibo uses")
check(row.startswith('{TAB_SYSTEM, "Unlimited amiibo uses", &opts.amiibo_unlimited, 0, 1, 1, tx_onoff,') and row.endswith("nullptr, false, true},\n"),
"vk_menu.cpp: the row is not an Off/On row of opts.amiibo_unlimited")
group = menu[menu.index('MENU_HEADING(TAB_SYSTEM, "NFC")'):menu.index('MENU_HEADING(TAB_SYSTEM, "Online")')]
check(group.index("{TAB_SYSTEM, kNfcTag, ") < group.index(row), "the row is not in the NFC group, after NFC tag")
header = (ROOT / "gpu/vk/vk_menu.h").read_text(encoding="utf-8")
check(re.search(r"^\s*int amiibo_unlimited = 0;", header, re.M), "vk_menu.h: the row is not Off by default")
replay = (ROOT / "gpu/vk/vk_replay.cpp").read_text(encoding="utf-8")
check("if (id == HOS_OPT_AMIIBO_UNLIMITED) return opts.amiibo_unlimited != 0;" in replay, "the renderer does not answer the row's option")
helptext = "".join(re.findall(r'"((?:[^"\\]|\\.)*)"', row[row.index("tx_onoff,"):]))
schema = (ROOT / "launcher/Logic/GameOptions/GameOptionsSchema.cs").read_text(encoding="utf-8")
check('Row(GameOptionTab.System, "NFC", "Unlimited amiibo uses", 0, 1, 1, 0, GameOptionKind.Choice, TxOnoff, false, true,\n'
' "%s"),' % helptext in schema, "the launcher's copy of the row is not the menu's (NFC, Off, the same help)")
# the page sends a figure the game has read again (another touch); a figure's clock check never refuses here
check("const bool away = (said == HOS_AMIIBO_WAITING || said == HOS_AMIIBO_ON_READER) && amiibo_chosen == name;" in menu,
"the Scan amiibo page takes a figure off when it is chosen again after the game read it")
applet = (ROOT / "host/nn_applet.c").read_text(encoding="utf-8")
check("HLE(_ZN2nn4time48CalculateStandardUserSystemClockDifferenceByUserERKNS0_13ClockSnapshotES3_) { RET(0); }" in applet,
"host/nn_applet.c: the clock set by hand is not answered 0 (the game's clock check could refuse a figure)")
print("PASS: Unlimited amiibo uses: the once-a-day check's call, the host's answer, the row Off by default, its launcher copy")
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--cc", default="gcc")
a = p.parse_args()
check_source()
check_unlimited(a.cc)
with tempfile.TemporaryDirectory() as tmp:
exe = Path(tmp) / "amiibo_test.exe"
subprocess.run([a.cc, "-std=c11", "-O1", "-Wall", "-Wextra", "-Werror", str(ROOT / "tests/amiibo_test.c"), "-o", str(exe)], check=True)
run = subprocess.run([str(exe)], capture_output=True, text=True)
if run.returncode or run.stdout.strip() != "ok":
raise SystemExit("FAIL: tests/amiibo_test.c (exit %d)\n%s%s" % (run.returncode, run.stdout, run.stderr))
print("PASS: the dump parser, the infos, the names, the readers' states and the game's task against them")
print("PASS: the dump parser, the infos, the names, the readers' states, the game's task against them and fifty scans in a row")
if __name__ == "__main__":

View File

@@ -119,6 +119,12 @@ def main():
m = re.search(r"void auto_row_set\(const int\* value\) \{(.*?)\n\}", menu, re.S)
if not m or "opts.auto_pc = 0;" not in m.group(1):
raise SystemExit("FAIL: auto_row_set no longer turns Auto Off on a hand change")
# ((11-30) the hardware read asks DLSS's and FSR 4's libraries first: before their probe both answer OK, and Auto chose
# AMD FSR 4 on an RX 580 (rainbow noise))
h = re.search(r"auto_settings::Hardware auto_hardware\(\) \{(.*?)\n\}", menu, re.S)
if not h or not (0 <= h.group(1).find("dlss_probe();") < h.group(1).find("hw.dlss_runs")) or \
not (0 <= h.group(1).find("fsr4_probe();") < h.group(1).find("hw.fsr4_runs")):
raise SystemExit("FAIL: auto_hardware reads whether DLSS and FSR 4 run before their libraries were asked")
with tempfile.TemporaryDirectory(prefix="auto-settings-") as tmp:
src = Path(tmp) / "t.cpp"
src.write_text(C, encoding="utf-8")

View File

@@ -6,6 +6,8 @@ triforce_options.ini: the defaults (WASD, the arrows, the mouse's left button Y
only while the mouse is captured and only once the click that captured it was let go, key_move_up from the file, a
pad_ line for a keys-only control ignored, a key taken from the control that had it, and Enter with Alt still no key.
The walk key (the Insert menu's Walk key row, tests/test_walk_key.py) is no control's key while it is the walk key.
((Triforce, 11-30) A key some control has, or the walk key, is no sensitivity key (key_is_a_control, sens_key): - bound to A
took a fifth off the mouse's sensitivity at every press.
python -I -B tests/test_bound_keys.py (needs a C compiler)
"""
import shutil
@@ -191,6 +193,26 @@ int main(int argc, char **argv) {
CHECK(!hos_binding_is_default(HOS_SW_B) && !hos_reset_binding(HOS_SW_B) && !hos_reset_binding(HOS_SW_A)); /* (each has the other's) */
hos_bind(HOS_BIND_PAD, HOS_SW_A, 0, -1); /* (cleared: B's default is free) */
CHECK(hos_reset_binding(HOS_SW_B) && hos_reset_binding(HOS_SW_A) && hos_binding_is_default(HOS_SW_A) && hos_binding_is_default(HOS_SW_B));
/* ((Triforce, 11-30) the sensitivity keys (- and =, Num - and Num +) are no shortcut while a control has them, nor while
one is the walk key: bound to A, - took a fifth off the sensitivity at every press (mouse_sens_keys) */
release();
CHECK(key_is_a_control('E') && key_is_a_control(VK_TAB) && key_is_a_control(VK_LBUTTON)); /* (A's, Plus's, Y's) */
CHECK(!key_is_a_control(0xBD) && !key_is_a_control(0x6D) && !key_is_a_control(0xBB) && !key_is_a_control(0x6B));
CHECK(!key_is_a_control(0));
held[0xBD] = 1;
CHECK(sens_key(0xBD)); /* (no control's: the shortcut) */
hos_bind(HOS_BIND_KEY, HOS_SW_A, 1, 0xBD);
CHECK(key_is_a_control(0xBD) && !sens_key(0xBD) && bound_down(HOS_SW_A, 0)); /* (A's alone) */
hos_bind(HOS_BIND_KEY, HOS_SW_A, 1, 0);
CHECK(!key_is_a_control(0xBD) && sens_key(0xBD));
hos_bind(HOS_BIND_KEY, HOS_KEY_OC_NOTE_A, 0, 0x6D); /* (a note row's key, Num -) */
CHECK(key_is_a_control(0x6D));
hos_bind(HOS_BIND_KEY, HOS_KEY_OC_NOTE_A, 0, 0);
walk_vk = 0x6D;
CHECK(key_is_a_control(0x6D));
walk_vk = 0;
CHECK(!key_is_a_control(0x6D));
release();
if (!fails) printf("PASS\n");
return fails != 0;
}
@@ -207,6 +229,8 @@ class BoundKeysTests(unittest.TestCase):
between(hid, "static const char *const bind_names[HOS_KEY_N]", "\nvoid hos_bind("), # (its definition: the live input declares it)
block(hid, "static uint64_t bound_pad_buttons("),
between(hid, "static int mouse_vk_slot(", "static int bound_down("),
block(hid, "static int key_is_a_control(int vk) {"), # ((Triforce, 11-30) the sensitivity keys' rule
block(hid, "static int sens_key("),
between(hid, "int hos_binding_is_default(", "int hos_rebind_control(")] # ((Triforce) the per-control reset)
code = "\n".join(code).replace("GetModuleFileNameA(NULL,", "GetModuleFileNameA(0,")
read = block(hid, "static void read_input(")

View File

@@ -6,10 +6,13 @@ and dispatches on every card, read once into a static of maybe_split, so nothing
now RX_VK_CHUNK when set, else the RX_VK_LAB_AB knob chunk:<n> in its phases, else the driver's default: 120 for every driver
until the lab picks one. (11-26) The lab picked NVIDIA's: 240 (measured in the benchmark's four scenes); every other driver
keeps 120. NVIDIA's driver is the device's driver id (VK_DRIVER_ID_NVIDIA_PROPRIETARY, one id on Windows and Linux), not the
card's vendor: NVK, Dozen and Venus on an NVIDIA card keep 120.
card's vendor: NVK, Dozen and Venus on an NVIDIA card keep 120. (11-29) On NVIDIA's driver a part ends where the game ends its
render pass by default, Threaded rendering or not (barrier_rules.h part_pass_end_default, vk_replay.cpp pass_end_parts): the
counted 240 applies there with RX_VK_PART_PASS_END=0.
Compiles a driver against barrier_rules.h, lab_ab.h and the Vulkan headers and checks:
the default is 240 for NVIDIA's driver, and 120 for NVK, Dozen, Venus, RADV, AMD's, Intel's, any other driver id and none;
the pass-end parts are the default for NVIDIA's driver alone (by its id: not NVK, not any other, not none);
the rule's id for NVIDIA's driver is Vulkan's;
with no knob the size is what the old read gave, for 100,000 random texts of the variable (unset, 0, 120, negative, words,
any number) on random drivers, except unset on NVIDIA's driver (240): the default path splits where it split elsewhere;
@@ -18,7 +21,8 @@ Compiles a driver against barrier_rules.h, lab_ab.h and the Vulkan headers and c
default beside the measured knob chunk:120, and the pass-end parts' test (value_of("chunk", -1) < 0) true only outside it.
And reads vk_replay.cpp: maybe_split has no static size and asks part_draws() at each call, still returns for a size of 0 or
less and still counts ++part_work against it after the tail's test, and takes Threaded rendering's pass-end parts only
outside the knob's phases; part_draws reads the variable once and the knob at each call, asks the rule with the device's
outside the knob's phases; pass_end_parts turns them on by default with Threaded rendering or the rule (the device's driver
id), and its line says which; part_draws reads the variable once and the knob at each call, asks the rule with the device's
driver id (no platform test) and says when Threaded rendering's parts decide instead; barrier_rules.h's comment names NVK,
Threaded rendering's parts and both measurements; the switches table has the row, with NVK, the measured PC, where the size
applies under Threaded rendering and a lab example against 120, and no longer says the in-pass split is on with NVIDIA's
@@ -67,6 +71,13 @@ int main() {
for (const auto& d : kDrivers) CHECK(d.what, br::part_draws_default(d.driver) == d.want);
static_assert(br::kDriverNvidiaProprietary == VK_DRIVER_ID_NVIDIA_PROPRIETARY, "the rule's id for NVIDIA's driver is Vulkan's");
CHECK("the constants", br::kPartDraws == 120 && br::kPartDrawsNvidia == 240);
// ((Triforce, 11-29) the pass-end parts by default, Threaded rendering off: NVIDIA's driver alone, by its id (the drivers
// that run on NVIDIA's cards beside it keep the parts cut by count, as every other driver, until the lab has measured them)
for (const auto& d : kDrivers)
CHECK("the pass-end parts by default on NVIDIA's driver alone", br::part_pass_end_default(d.driver) == (d.driver == VK_DRIVER_ID_NVIDIA_PROPRIETARY));
CHECK("the pass-end parts by default: NVIDIA's driver", br::part_pass_end_default(VK_DRIVER_ID_NVIDIA_PROPRIETARY));
CHECK("the pass-end parts not by default: NVK", !br::part_pass_end_default(VK_DRIVER_ID_MESA_NVK));
CHECK("the pass-end parts not by default: no driver id", !br::part_pass_end_default(0));
// with no knob: the old read, whatever the variable says
uint64_t rng = 0xD1B54A32D192ED03ull;
@@ -130,6 +141,14 @@ def function(text, head):
return text[at:text.index("\n}\n", at)]
def in_order(text, needles, where):
at = 0
for n in needles:
i = text.find(n, at)
check(i >= 0, "%s: %r missing or out of order" % (where, n))
at = i + len(n)
def check_source():
replay = (ROOT / "gpu/vk/vk_replay.cpp").read_text(encoding="utf-8")
split = function(replay, "void maybe_split(VkCommandBuffer& cmd) {")
@@ -158,8 +177,13 @@ def check_source():
# ((Triforce) and once by Threaded rendering's parts, only to step aside when it is set: pass_end_parts)
ends = function(replay, "PassEndParts& pass_end_parts() {")
check(replay.count('getenv("RX_VK_CHUNK")') == 2 and ends.count('getenv("RX_VK_CHUNK")') == 1, "RX_VK_CHUNK is read somewhere else")
check('v.on = e && *e ? atoi(e) != 0 : threaded_on() && !getenv("RX_VK_CHUNK");' in ends,
check('v.on = e && *e ? atoi(e) != 0 : by_default && !getenv("RX_VK_CHUNK");' in ends,
"pass_end_parts' switch changed: the docs say any RX_VK_CHUNK turns Threaded rendering's parts off")
# ((Triforce, 11-29) and NVIDIA's driver has them by default, Threaded rendering or not: the rule asked with the driver id)
check("const bool by_default = threaded_on() || barrier_rules::part_pass_end_default((uint32_t)dev.driver_id);" in ends,
"pass_end_parts' default is not Threaded rendering or the rule's, by the device's driver id")
check('"NVIDIA\'s driver\'s default since 11-29"' in ends and '"Threaded rendering"' in ends,
"pass_end_parts' line does not say why the pass-end parts are on")
check("every RX_VK_CHUNK, as before" not in ends and "default 120;" not in replay,
"vk_replay.cpp still says the counted size is 120 as before")
rules = (ROOT / "gpu/vk/barrier_rules.h").read_text(encoding="utf-8")
@@ -181,8 +205,38 @@ def check_source():
check("(the first part from 32)" in row[0] and "whole submissions" in there,
"the RX_VK_CHUNK row does not say Threaded rendering's first part is from 32 draws, or that RX_VK_CHUNK=0 there gives "
"whole submissions")
# ((Triforce, 11-29) the pass-end parts' own row: its default on NVIDIA's driver, the way back, and where it was measured)
pe = [line for line in dev.splitlines() if line.startswith("| `RX_VK_PART_PASS_END=0` or `=1`,")]
check(len(pe) == 1 and "**on by default on NVIDIA's driver since 11-29**" in pe[0] and "part_pass_end_default" in pe[0] and
"`=0`: counted parts" in pe[0] and "Not measured:" in pe[0] and "RTX 5090" in pe[0],
"docs/development.md: no row for RX_VK_PART_PASS_END with its default on NVIDIA's driver, =0 and where it was measured")
check("parts of 120 draws" not in dev, "docs/development.md still says a part is 120 draws on every card")
check("Unset: `pass` with NVIDIA's driver" not in dev, "docs/development.md still says the in-pass split is on with NVIDIA's driver")
# ((Triforce, 11-29) RX_VK_PART_IDLE / the knob partidle: a part after the first may end from the idle size once the GPU has
# done everything sent. Off unset; asked through part_min_now in place of pe.min, so maybe_split's control flow (and its
# renderer profile) is the same; the GPU looked at every 8th draw at most, below RX_VK_PART_MIN only)
check('v.idle = std::clamp<int64_t>(num("RX_VK_PART_IDLE", 0), 0, v.min);' in ends, "RX_VK_PART_IDLE is not off unset and at most PART_MIN")
split = function(replay, "void maybe_split(VkCommandBuffer& cmd) {")
check("const int64_t need = rec_parts == 0 && pe.first ? pe.first : part_min_now(pe);" in split,
"maybe_split does not ask part_min_now for a later part's size in place of pe.min")
pm = function(replay, "int64_t part_min_now(PassEndParts& pe) {")
# (and RX_VK_PART_RB / partrb: a part that writes back a page the CPU reads back, below PART_MIN only; the binding notes it
# through a call, so the binding's control flow (and its profile) is the same; cleared at each part's end)
# ((11-29, the owner's decision) 32 unset with RX_VK_RB_REC_END=3, the default with these parts; off with another mode set)
check('v.rb = std::clamp<int64_t>(num("RX_VK_PART_RB", range ? 32 : 0), 0, v.min);' in ends,
"RX_VK_PART_RB is not 32 unset with mode 3 (off with another) and at most PART_MIN")
mem = (ROOT / "gpu/vk/vk_memory.cpp").read_text(encoding="utf-8")
bind = function(mem, "BufferRef gpu_buffer_bind(uint64_t gpu, uint64_t size, bool written) {")
check("rb_write_note(p->lo + off, p->lo + wb_end);" in bind and "rb_watched(" not in bind and "part_rb_write" not in bind,
"gpu_buffer_bind does not note a read-back page's write-back through rb_write_note alone (a branch there loses its profile)")
check("part_rb_write.store(false, std::memory_order_relaxed);" in function(mem, "void memory_end_submission(VkCommandBuffer cmd) {"),
"a part's end does not clear the read-back write note")
in_order(pm, ['const int64_t rb = lab_ab::value_of("partrb", pe.rb);',
"if (rb > 0 && n >= rb && n < pe.min && memory_part_rb_write()) {", "return rb;",
'lab_ab::value_of("partidle", pe.idle);', "if (idle <= 0 || n < idle) {", "return pe.min;",
"if (part_idle_now) return idle;", "if (n >= pe.min || (n & 7) != 0 || !rec_timeline) return pe.min;",
"vkGetSemaphoreCounterValue(dev.device, rec_timeline, &done) == VK_SUCCESS && done >= rec_seq;"],
"part_min_now (off at 0, kept for the part once seen, the GPU looked at every 8th draw below PART_MIN)")
def main():

View File

@@ -3,6 +3,7 @@
#include <array>
#include <cmath>
#include <cstdio>
#include <cstring>
#define CHECK(name, condition) do { if (!(condition)) { std::fprintf(stderr, "FAIL %s at line %d\n", name, __LINE__); return 1; } } while (0)
@@ -133,6 +134,151 @@ int main() {
CHECK("none then, none now", da::pair_by_place(stones, {}, 1.0f) == std::vector<int>(4, -1) &&
da::pair_by_place({}, stones, 1.0f).empty());
// copies without a place: their n-th draw the frame before is a guess when the model is drawn more than once (a row of
// trees drawn in another order as the camera turns: a tree's motion pointed at its neighbour)
{
const uint64_t t0 = da::key(0x5000, 0x6000, 300, 0, 0x77, 0), t1 = da::key(0x5000, 0x6000, 300, 0, 0x77, 1);
const uint64_t hill = da::key(0x7000, 0x8000, 9000, 0, 0x77, 0);
const auto none = [](uint64_t) { return false; };
const auto had_second = [&](uint64_t k) { return k == t1; };
const auto same_c = [](const std::vector<char>& a, std::vector<char> b) { return a == b; };
CHECK("a model drawn once, now and before: sure", same_c(da::unsure_copies({hill}, {0}, none), {0}));
CHECK("two copies now, no place: both unsure", same_c(da::unsure_copies({t0, t1, hill}, {0, 0, 0}, none), {1, 1, 0}));
CHECK("one copy now, two the frame before: unsure", same_c(da::unsure_copies({t0, hill}, {0, 0}, had_second), {1, 0}));
CHECK("copies with a place pair by it: sure", same_c(da::unsure_copies({t0, t1}, {1, 1}, none), {0, 0}));
CHECK("one copy with a place, one without: the one without unsure",
same_c(da::unsure_copies({t0, t1}, {1, 0}, none), {0, 1}));
CHECK("none", da::unsure_copies({}, {}, none).empty());
}
// copies without a skin placed by their object's origin (a rock a trail of its kind): a copy that moved among static ones
// keeps its own pairing, static copies whose draw order swapped are not mixed up, and copies that can't be told apart
// (one place, or about equally near) are flagged for the camera's motion
{
const std::vector<P> row_then = {{{0, 0, 0}, 0}, {{10, 0, 0}, 1}, {{20, 0, 0}, 2}};
const auto same_c = [](const std::vector<char>& a, std::vector<char> b) { return a == b; };
// (1) the middle one moves 0.5 (a rock carried), the others stand
const std::vector<P> moved_now = {{{0, 0, 0}, 0}, {{10.5f, 0, 0}, 1}, {{20, 0, 0}, 2}};
const auto p1 = da::pair_by_place(moved_now, row_then, 1.0f);
CHECK("a moving copy among static ones: its own pairing", same(p1, {0, 1, 2}));
CHECK("a moving copy among static ones: sure", same_c(da::ambiguous_by_place(moved_now, row_then, p1), {0, 0, 0}));
// (2) the same copies drawn in another order, none moved
const std::vector<P> swapped_now = {{{20, 0, 0}, 0}, {{0, 0, 0}, 1}, {{10, 0, 0}, 2}};
const auto p2 = da::pair_by_place(swapped_now, row_then, 1.0f);
CHECK("static copies, draw order swapped: each its own", same(p2, {2, 0, 1}));
CHECK("static copies, draw order swapped: sure", same_c(da::ambiguous_by_place(swapped_now, row_then, p2), {0, 0, 0}));
// ... and with one of them moving too
const std::vector<P> both_now = {{{20, 0, 0}, 0}, {{0.4f, 0, 0}, 1}, {{10, 0, 0}, 2}};
const auto p2b = da::pair_by_place(both_now, row_then, 1.0f);
CHECK("swapped and one moving: its own", same(p2b, {2, 0, 1}) &&
same_c(da::ambiguous_by_place(both_now, row_then, p2b), {0, 0, 0}));
// (3) the ambiguous cases: copies at one place; one in the middle of two; two now at one place of one before
const std::vector<P> stacked = {{{5, 5, 5}, 0}, {{5, 5, 5}, 1}};
CHECK("copies at one place: both flagged",
same_c(da::ambiguous_by_place(stacked, stacked, da::pair_by_place(stacked, stacked, 1.0f)), {1, 1}));
const std::vector<P> two_then = {{{0, 0, 0}, 0}, {{0.3f, 0, 0}, 1}}, middle_now = {{{0.15f, 0, 0}, 0}};
CHECK("about equally near two before: flagged",
same_c(da::ambiguous_by_place(middle_now, two_then, da::pair_by_place(middle_now, two_then, 1.0f)), {1}));
const std::vector<P> one_then = {{{5, 5, 5}, 0}};
CHECK("two now at the place of one before: the paired one flagged",
same_c(da::ambiguous_by_place(stacked, one_then, da::pair_by_place(stacked, one_then, 1.0f)), {1, 0}));
CHECK("no pair, nothing to flag", same_c(da::ambiguous_by_place(moved_now, {}, {-1, -1, -1}), {0, 0, 0}) &&
da::ambiguous_by_place({}, {}, {}).empty());
// the doubt limit's factor (kTieFactor 2): a near tie, flagged at 2 and not at 1; a far second copy, never flagged
const std::vector<P> tie_then = {{{0, 0, 0}, 0}, {{2.8f, 0, 0}, 1}}, tie_now = {{{1, 0, 0}, 0}};
const auto p_tie = da::pair_by_place(tie_now, tie_then, 3.0f);
CHECK("a near tie (1.0 moved, another 1.8 away): flagged",
same(p_tie, {0}) && same_c(da::ambiguous_by_place(tie_now, tie_then, p_tie), {1}));
const std::vector<P> far_then = {{{0, 0, 0}, 0}, {{11, 0, 0}, 1}};
const auto p_far = da::pair_by_place(tie_now, far_then, 3.0f);
CHECK("a far second copy (1.0 moved, another 10 away): sure",
same(p_far, {0}) && same_c(da::ambiguous_by_place(tie_now, far_then, p_far), {0}));
// a model over the cap: none placed by origin (all its copies take the camera's motion by unsure_copies), at the cap: placed
{
const auto no_before = [](uint64_t) { return false; };
const auto build = [&](size_t n) {
std::vector<uint64_t> keys;
for (size_t i = 0; i < n; i++) keys.push_back(da::key(0x1000, 0x2000, 96, 0, 0xabc, (int)i % 256));
return keys;
};
const auto count = [](const std::vector<char>& v) { size_t n = 0; for (char c : v) n += c != 0; return n; };
const auto at_cap = build(da::kCopyCap), over_cap = build(da::kCopyCap + 1);
CHECK("a model at the cap: all placed by origin",
count(da::place_by_origin(at_cap, std::vector<char>(at_cap.size(), 1), no_before)) == at_cap.size());
const auto over_placed = da::place_by_origin(over_cap, std::vector<char>(over_cap.size(), 1), no_before);
CHECK("a model over the cap: none placed by origin", count(over_placed) == 0);
const auto flagged = da::unsure_copies(over_cap, over_placed, no_before);
CHECK("a model over the cap: all its copies flagged for the camera's motion", count(flagged) == over_cap.size());
// (a single copy whose 2nd the frame before existed is placed; one whose origin is unreadable is not)
const std::vector<uint64_t> one = {da::key(0x1000, 0x2000, 96, 0, 0xabc, 0)};
const auto had_second = [&](uint64_t k) { return k == da::key(0x1000, 0x2000, 96, 0, 0xabc, 1); };
CHECK("a lone copy with a 2nd before: placed", count(da::place_by_origin(one, {1}, had_second)) == 1);
CHECK("a lone copy, no 2nd before: not", count(da::place_by_origin(one, {1}, no_before)) == 0);
CHECK("an unreadable origin: not placed", count(da::place_by_origin(one, {0}, had_second)) == 0);
// the frame before's 2nd copy was not placed (origin unreadable): its copy is flagged, as without origins
const auto not_placed = [](uint64_t) { return false; };
const auto placed_second = [&](uint64_t k) { return had_second(k); };
CHECK("a 2nd before that was not placed: flagged",
same_c(da::lost_second_copy(one, {1}, had_second, not_placed), {1}));
CHECK("a 2nd before that was placed: not flagged",
same_c(da::lost_second_copy(one, {1}, had_second, placed_second), {0}));
CHECK("no 2nd before, or not placed by origin: not flagged",
same_c(da::lost_second_copy(one, {1}, no_before, not_placed), {0}) &&
same_c(da::lost_second_copy(one, {0}, had_second, not_placed), {0}));
}
// the trace's numbers
const da::Spread constant = da::origin_spread(stacked), spread = da::origin_spread(row_then);
CHECK("origin spread: one place", constant.distinct == 1 && constant.max_gap == 0.0f);
CHECK("origin spread: a row", spread.distinct == 3 && spread.min_gap == 10.0f && spread.max_gap == 20.0f);
}
// a non-skinned draw's place: the translation of its 3x4 row-major world matrix, if that is one
{
const float good[12] = {0, 2, 0, 10, -2, 0, 0, 20, 0, 0, 3, 30}; // rotation-scale (rows 2, 2, 3 long)
float o[3] = {-1, -1, -1};
CHECK("a world matrix: its translation", da::object_place(good, o) && o[0] == 10 && o[1] == 20 && o[2] == 30);
float m[12];
const auto refused = [&](const char* name, int at, float v) {
std::memcpy(m, good, sizeof m);
m[at] = v;
float r[3] = {-1, -1, -1};
const bool no = !da::object_place(m, r) && r[0] == -1;
if (!no) std::fprintf(stderr, "not refused: %s\n", name);
return no;
};
CHECK("NaN refused", refused("nan", 1, std::nanf("")) && refused("nan translation", 7, std::nanf("")));
CHECK("infinity refused", refused("inf", 11, INFINITY));
CHECK("a huge translation refused", refused("huge", 3, 2e5f) && refused("huge neg", 11, -2e5f));
std::memcpy(m, good, sizeof m);
m[4] = m[5] = m[6] = 0;
float r[3];
CHECK("a zero row refused", !da::object_place(m, r));
std::memcpy(m, good, sizeof m);
m[0] = m[1] = m[2] = 0;
m[0] = 1, m[1] = 1.0f; // row 0 (1,1,0) against row 1 (-2,0,0): 45 degrees
CHECK("skewed rows refused", !da::object_place(m, r));
const float k = 0.70710678f;
const float rs[12] = {k, -3 * k, 0, 10, k, 3 * k, 0, 20, 0, 0, 1, 30}; // R(45 deg) * diag(1,3,1): columns orthogonal, rows skewed
const float sr[12] = {k, -k, 0, 10, 3 * k, 3 * k, 0, 20, 0, 0, 1, 30}; // diag(1,3,1) * R: rows orthogonal, columns skewed
CHECK("R*S (orthogonal columns) accepted", da::object_place(rs, r) && r[0] == 10 && r[1] == 20 && r[2] == 30);
CHECK("S*R (orthogonal rows) accepted", da::object_place(sr, r) && r[2] == 30);
const float both[12] = {1, 1, 0, 10, 0, 1, 0, 20, 0, 0, 1, 30}; // rows and columns both skewed 45 degrees
CHECK("skewed in rows and columns refused", !da::object_place(both, r));
// (a short axis alone, kAxisMin: a diagonal matrix is orthogonal both ways, so only the length refuses it)
const float tiny[12] = {0, 2, 0, 10, -2, 0, 0, 20, 0, 0, 1e-5f, 30};
CHECK("a 1e-5 row and column refused for length only", !da::object_place(tiny, r));
const float shortrow[12] = {2, 0, 0, 10, 0, 1e-5f, 0, 20, 0, 0, 2, 30};
CHECK("a short axis refused", !da::object_place(shortrow, r));
const float okdiag[12] = {2, 0, 0, 10, 0, 1e-3f, 0, 20, 0, 0, 2, 30};
CHECK("the same with the axis over kAxisMin accepted", da::object_place(okdiag, r));
// (copies sharing one matrix have one place: stacked, so none is sure and all keep the camera's motion)
std::vector<da::Placed> same(3);
for (auto& c : same) da::object_place(good, c.place);
const auto pr = da::pair_by_place(same, same, 1.0f);
const auto amb = da::ambiguous_by_place(same, same, pr);
CHECK("identical origins: unsure", amb.size() == 3 && amb[0] && amb[1] && amb[2]);
}
// a draw's place: its origin plus its bones' mean translation (copies at one origin, placed by their bones, differ)
const auto pose_of = [](float ox, float oy, float oz, std::vector<std::array<float, 3>> moves) {
std::vector<uint8_t> p(16 + moves.size() * 48, 0);

View File

@@ -231,6 +231,8 @@ int main() {
CHECK(query_used_on(nullptr, "0", "1") && !query_used_on(nullptr, "0", "0") && !query_used_on("0", "0", "2"));
CHECK(keep_all_small_pc(true, 15731 * MB, true) && !keep_all_small_pc(false, 15731 * MB, true));
CHECK(!keep_all_small_pc(true, 15731 * MB, false) && !keep_all_small_pc(true, 20 * GB, true) && !keep_all_small_pc(true, 0, true));
// ((11-30) not on AMD's driver: the RX 580s of 16 GB kept 16,963 pipelines and ran out of RAM)
CHECK(!keep_all_small_pc(true, 15731 * MB, true, true) && keep_all_small_pc(true, 15731 * MB, true, false));
// (11-22: the capture's spares held to 32 MB on a small card or a PC of under 20 GB; a 16 GB PC reports ~15.7 GB)
CHECK(spare_capped(true, 64 * GB) && spare_capped(false, 15731 * MB) && spare_capped(false, 20 * GB - 1));
CHECK(!spare_capped(false, 20 * GB) && !spare_capped(false, 32 * GB) && !spare_capped(false, 0));
@@ -283,7 +285,10 @@ def check_source():
raise SystemExit("the precompile's keep goes by the PC's total RAM, not the RAM the game can have")
if "mem_parts::own_for_keep(ws, cache_read, amd)" not in keep or "pcache_read_ws.load()" not in keep:
raise SystemExit("the precompile's keep counts the pipeline cache's read as room for the pipelines")
small = "if (!e && mem_parts::keep_all_small_pc(discrete, ms.ullTotalPhys, query_on)) {"
small = "if (!e && mem_parts::keep_all_small_pc(discrete, ms.ullTotalPhys, query_on, amd)) {"
if "const bool amd = dev.props.vendorID == 0x1002;" not in keep or \
keep.index("const bool amd = dev.props.vendorID == 0x1002;") > keep.index(small):
raise SystemExit("the small PC's rule is not told whether the driver is AMD's")
if small not in keep or "VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU" not in keep or \
not keep.index("allowed < (6656ull << 20)") < keep.index(small) < keep.index("mem_parts::keep_all_pipelines("):
raise SystemExit("the precompile does not keep every pipeline on a discrete GPU in a PC of under 20 GB (after the card's "

View File

@@ -418,7 +418,7 @@ def main():
parser.add_argument("--cxx", default="g++")
args = parser.parse_args()
menu = (VK / "vk_menu.cpp").read_text(encoding="utf-8")
check('out += "options_version=10\\n";' in definition(menu, "void save"), "save does not write options_version=10")
check('out += "options_version=11\\n";' in definition(menu, "void save"), "save does not write options_version=11")
check("for (const char* dropped : merged_rows::kDropped) mine |= key == dropped;" in definition(menu, "void save"),
"save writes back the lines of the rows that went")
with tempfile.TemporaryDirectory(prefix="merged-rows-") as tmp:

View File

@@ -56,6 +56,19 @@ def main():
("mouse_look_move(invert_x ? -dx : dx, invert ? dy : -dy);", hid)):
if text not in where:
raise SystemExit("the mouse's left and right are not swapped where it is read: " + text)
# ((Triforce, 11-30) every change of the sensitivity is logged with its writer: the file at the start, the host's keys, the
# options' own input at a tick's end, and any other at a tick's start (a player's 0.30 that nobody's log explained)
watch = menu[menu.index("void sens_watch(const char* why) {"):]
watch = watch[:watch.index("\n}\n")]
if "opts.mouse_sens" not in watch or "logf(" not in watch:
raise SystemExit("sens_watch no longer logs the sensitivity's changes")
tick = menu[menu.index("void menu_tick() {"):]
if not tick.startswith('void menu_tick() {\n sens_watch("another writer'):
raise SystemExit("menu_tick does not look for another writer of the sensitivity first")
for need in ("sens_watch(\"the options' input at this tick", 'sens_watch("the host: its - or = key',
'sens_watch("as the options file has it, at the start")'):
if need not in menu:
raise SystemExit("a writer of the sensitivity is not logged: " + need)
if not preset_exempt(menu, "mouse_sens"):
raise SystemExit("a mouse setting turns the quality preset to Custom")
print("PASS: the mouse's settings are the menu's")

View File

@@ -3,8 +3,10 @@
The game's movie player counts its updates while a movie plays, and a cutscene that shows a movie places its narration, its
rumble and its end by that count. The movie's picture and sound follow the clock, so at 120 fps the cues came twice too early:
narration lines started over each other. nx2/oot_patches.py makes the count's step hos_movie_frames(player), and host/nn_vi.c
answers 1 while the host gives no frame time (a cap of 60: as shipped) and the frames' time in 60ths, the rest carried to the
player's next update, while it does (HOS_FPS_MOVIE=0: 1 then too, for comparisons). A game version whose code differs keeps
answers 1 while the host gives no frame time at 60 fps (as shipped), the frames' time in 60ths, the rest carried to the
player's next update, while it does, and (11-30) below 60 fps the game's own step, 60 / its rate: one an update had the ending's
second staff roll end at half its count at 30 fps, its end screen never opened, the game stuck before "The End"
(HOS_FPS_MOVIE=0: 1 always, for comparisons). A game version whose code differs keeps
its own code and the build goes on with a warning.
python -I -B tests/test_movie_frame_count.py [--cc gcc]
@@ -60,6 +62,9 @@ static void ReleaseSRWLockExclusive(SRWLOCK *l) { CHECK(*l); *l = 0; }
volatile uint32_t hos_frame_seconds_bits;
static int movies_seen; /* (each update says a movie plays, for the frame pacing: host/nn_vi.c movie_seen, tests/test_pace_handoff.py) */
static void movie_seen(void) { movies_seen++; }
/* (host/nn_vi.c movie_game_rate: the game's rate under 60, 0 at 60) */
static int game_rate;
static int movie_game_rate(void) { return game_rate; }
@HOST@
/* (the lifted update with the patch, on a small guest: the count at +760 of the player) */
typedef struct { uint64_t x[31]; } Ctx;
@@ -86,6 +91,9 @@ int main(int argc, char **argv) {
seconds(1.0 / 120);
for (int i = 0; i < 600; i++) n = update(0);
CHECK(n == 600);
seconds(0), game_rate = 30; /* (and below 60) */
for (int i = 0; i < 600; i++) n = update(0);
CHECK(n == 1200);
printf("PASS: off\n");
return 0;
}
@@ -168,6 +176,29 @@ int main(int argc, char **argv) {
before = n;
for (int i = 0; i < 10; i++) n = update(0);
CHECK(n - before == 10);
/* (11-30) below 60 fps, no frame time: the game's step, 60 / its rate. At 30 two an update: the ending's second staff roll
(Dm_StaffCredit_0005: 7343 pictures at 60, its end screen opened at frame 6260 of the count) played in 3672 frames ended
its count near 3672 with one an update, the end screen never opened; now at 7344 */
game_rate = 30;
before = n;
for (int i = 0; i < 3672; i++) {
const uint32_t was = n;
n = update(0);
CHECK(n - was == 2);
}
CHECK(n - before == 7344);
game_rate = 48; /* (1.25 an update, the rest carried) */
before = n;
for (int i = 0; i < 400; i++) {
const uint32_t was = n;
n = update(0);
CHECK(n - was == 1 || n - was == 2);
}
CHECK(within(n - before, 500));
game_rate = 0; /* (60 again) */
before = n;
for (int i = 0; i < 10; i++) n = update(0);
CHECK(n - before == 10);
printf("PASS\n");
return 0;
}

241
tests/test_oot_adult_map.py Normal file
View File

@@ -0,0 +1,241 @@
"""Check that an adult who left the Temple of Time without its first walk out gets the map page and the minimap back.
The pause menu's Map page (f_80b47d70, asked by UIMapMenuScreen f_834012c0: "Unavailable right now.", MapMessage_01, when
it answers no) and the HUD's minimap (f_805a2cf0) say yes for the child and, for the adult, only once
HavePlayedEvent.Dm_TimeTemple_0065 is 1 (Bool 0xc1b29b0a; the code reads it as struct HavePlayedEvent 0x2b05cbb9, member
Dm_TimeTemple_0065 0xc367dcdc). The adult Market's map plays that event when Link steps through an Area at the Temple of
Time's door (Market_Adult_Static, Market_Adult_Prefab_50e3's logic); nothing else in the romfs plays it or sets the flag.
An adult who leaves the temple another way (a teleport, the age switch, the no-clip flight) has no maps as an adult for
good (#1576602300313506086). `oot_adult_map_fix`, asked by `oot_inventory_refresh` twice a second while a save is loaded,
sets the flag through the game's own Bool setter (the live value and the save's copy) for an adult outside the Market,
the Chamber of Sages and the dream world, once no event plays, and logs it.
This cuts the real `oot_inventory_refresh`, `oot_first_night_fix` and `oot_adult_map_fix` out of host/hos_main.c and runs
them against made-up save state, with no game and no romfs. Run it with:
python -I tests/test_oot_adult_map.py --cc gcc
"""
import argparse
import os
import re
import subprocess
import tempfile
from pathlib import Path
RUN_ALL_ARGS = ["--cc", "gcc"]
ROOT = Path(__file__).resolve().parents[1]
def murmur3(text):
"""MurmurHash3 x86 32, seed 0: the game's GameData names (as oot_murmur3 in host/hos_main.c)."""
data = text.encode()
h = 0
mask = 0xFFFFFFFF
for i in range(0, len(data) // 4 * 4, 4):
k = int.from_bytes(data[i:i + 4], "little")
k = (k * 0xCC9E2D51) & mask
k = ((k << 15) | (k >> 17)) & mask
k = (k * 0x1B873593) & mask
h ^= k
h = ((h << 13) | (h >> 19)) & mask
h = (h * 5 + 0xE6546B64) & mask
tail = data[len(data) // 4 * 4:]
k = 0
for i in reversed(range(len(tail))):
k ^= tail[i] << (8 * i)
if tail:
k = (k * 0xCC9E2D51) & mask
k = ((k << 15) | (k >> 17)) & mask
k = (k * 0x1B873593) & mask
h ^= k
h ^= len(data)
h ^= h >> 16
h = (h * 0x85EBCA6B) & mask
h ^= h >> 13
h = (h * 0xC2B2AE35) & mask
h ^= h >> 16
return h
NAMES = {
0xC1B29B0A: "HavePlayedEvent.Dm_TimeTemple_0065",
0x2B05CBB9: "HavePlayedEvent",
0xC367DCDC: "Dm_TimeTemple_0065",
0xCEA220D3: "Sequence_IsChildhood",
0x7BDF3694: "Sequence_IsInDreamWorld",
}
FIXTURE = r'''
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct { uint64_t x[32]; } Ctx;
static int played; /* HavePlayedEvent.Dm_TimeTemple_0065, the live value */
static int saved; /* (its copy in the save) */
static int child = 1; /* Sequence_IsChildhood: 1 child, 0 adult */
static int age_known = 1, flag_known = 1;
static int event_playing; /* the game's event manager has an active event */
static const char *map_name = "Market_Child";
static int sets, logs, live_only;
static void hos_log(const char *fmt, ...) { (void)fmt; logs++; }
static void rx_option_set(int id, int value) { (void)id; (void)value; }
static int oot_item_get(Ctx *c, const char *name) { (void)c; (void)name; return 0; }
static int oot_pouch_count(Ctx *c, const char *name) { (void)c; (void)name; return 0; } /* (a save is loaded) */
static int oot_gamedata_bool(Ctx *c, uint32_t hash, int *value) {
(void)c;
if (hash == 0xcea220d3u && age_known) { *value = child; return 1; }
if (hash == 0xc1b29b0au && flag_known) { *value = played; return 1; }
return 0; /* (HrlField_HasEnteredFirstTime_Adult not found: the first night's repair leaves it) */
}
/* (the live byte alone: never for this flag, the save would keep 0) */
__attribute__((unused)) static int oot_gamedata_set_bool(Ctx *c, uint32_t hash, int value) {
(void)c, (void)value;
if (hash == 0xc1b29b0au) live_only++;
return 0;
}
static int oot_gamedata_string(Ctx *c, uint32_t hash, char *buf, size_t size) {
(void)c;
if (hash != 0x1d6189dau) return 0;
snprintf(buf, size, "%s", map_name);
return 1;
}
#define OOT_EVENTMGR_SLOT 0x84c9e090ULL
#define OOT_GAMEDATA_SLOT 0x84c9e180ULL
__attribute__((unused)) static uint64_t oot_singleton(Ctx *c, uint64_t slot) {
(void)c;
return slot == OOT_EVENTMGR_SLOT ? 0x1000 : slot == OOT_GAMEDATA_SLOT ? 0x2000 : 0;
}
__attribute__((unused)) static uint64_t recomp_load64(Ctx *c, uint64_t a) { (void)c; return a == 0x1000 + 104 ? (uint64_t)event_playing : 0; }
/* (the game's SetBool: the live value and the save's copy) */
__attribute__((unused)) static int oot_gd_set(Ctx *c, uint64_t mgr, uint32_t hash, uint32_t value, int is_bool) {
(void)c;
if (mgr != 0x2000 || hash != 0xc1b29b0au || !is_bool) return 0;
sets++;
played = saved = (int)value;
return 1;
}
#define OOT_CHEAT_ITEM_BASE 100
#define OOT_CHEAT_AGE_ID 200
enum { HOS_OPT_SIM_TURF_AREA_TEXT = 410, HOS_OPT_SIM_TURF_AREA };
#define OOT_ITEM_COUNT 2
static const char *const oot_item_names[OOT_ITEM_COUNT] = {"Item_A", "Item_B"};
// FIX
// REFRESH
static void check(const char *what, int want, int want_sets) {
if (played != want || saved != want || sets != want_sets || live_only || (want_sets && logs < want_sets)) {
fprintf(stderr, "FAIL: %s: flag %d saved %d (want %d), sets %d (want %d), logs %d, live-only writes %d\n", what,
played, saved, want, sets, want_sets, logs, live_only);
exit(1);
}
}
static void at(Ctx *c, int64_t *now, int flag, int is_child, const char *map) {
*now += 500000000LL;
played = saved = flag, child = is_child, map_name = map, sets = 0, logs = 0;
oot_inventory_refresh(c, *now);
}
int main(void) {
Ctx c = {0};
int64_t now = 0;
#ifdef SWITCH_OFF
at(&c, &now, 0, 0, "ForestTemple");
check("the switch off leaves the flag", 0, 0);
puts("PASS: HOS_OOT_ADULT_MAP_FIX=0 leaves the flag alone");
return 0;
#else
/* The report's save: an adult in the Forest Temple who never walked out of the Temple of Time's door. */
at(&c, &now, 0, 0, "ForestTemple");
check("an adult in the Forest Temple", 1, 1);
at(&c, &now, 0, 0, "HyruleField_Adult");
check("an adult in Hyrule Field", 1, 1);
at(&c, &now, 0, 0, "IceCavern");
check("an adult in the Ice Cavern", 1, 1);
/* The game's own first walk out is still to come: the Market (the Temple of Time is in it), the Chamber of Sages. */
at(&c, &now, 0, 0, "Market_Adult");
check("an adult in the Market", 0, 0);
at(&c, &now, 0, 0, "SageRoom");
check("an adult in the Chamber of Sages", 0, 0);
at(&c, &now, 0, 0, "DreamWorld");
check("an adult in the dream world", 0, 0);
/* The child's maps never ask for it, and his first walk out is ahead of him. */
at(&c, &now, 0, 1, "KokiriForest_Child");
check("a child", 0, 0);
/* Already played: nothing written. */
at(&c, &now, 1, 0, "ForestTemple");
check("a save that has it", 1, 0);
/* Age or flag not known, no map name: nothing to decide on. */
age_known = 0;
at(&c, &now, 0, 0, "ForestTemple");
check("the age not known", 0, 0);
age_known = 1, flag_known = 0;
at(&c, &now, 0, 0, "ForestTemple");
check("the flag not known", 0, 0);
flag_known = 1;
at(&c, &now, 0, 0, "");
check("no map", 0, 0);
/* An event playing waits for the next refresh. */
event_playing = 1;
at(&c, &now, 0, 0, "ForestTemple");
check("an event playing", 0, 0);
event_playing = 0;
now += 500000000LL;
oot_inventory_refresh(&c, now);
check("after the event", 1, 1);
puts("PASS: an adult outside the Market, the Chamber of Sages and the dream world without the Temple of Time's first "
"walk out gets HavePlayedEvent.Dm_TimeTemple_0065 through the game's setter; the child and the Market are left");
return 0;
#endif
}
'''
def cut(source, pattern, what):
match = re.search(pattern, source, re.M | re.S)
if not match:
raise SystemExit("could not find %s in host/hos_main.c" % what)
return match.group()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cc", default="gcc")
args = parser.parse_args()
for value, name in NAMES.items():
if murmur3(name) != value:
raise SystemExit("FAIL: MurmurHash3(%r) is %#010x, not %#010x" % (name, murmur3(name), value))
host = (ROOT / "host/hos_main.c").read_text(encoding="utf-8")
refresh = cut(host, r"^static void oot_inventory_refresh\(Ctx \*c, int64_t now\) \{.*?^\}", "oot_inventory_refresh")
night = cut(host, r"^static int oot_first_night_fix\(Ctx \*c, const char \*map\) \{.*?^\}", "oot_first_night_fix")
maps = cut(host, r"^static int oot_adult_map_fix\(Ctx \*c, const char \*map\) \{.*?^\}", "oot_adult_map_fix")
if "oot_adult_map_fix(c, map)" not in refresh:
raise SystemExit("FAIL: oot_inventory_refresh does not ask oot_adult_map_fix")
body = FIXTURE.replace("// FIX", night + "\n\n" + maps).replace("// REFRESH", refresh)
with tempfile.TemporaryDirectory(prefix="oot-adult-map-") as tmp:
source = Path(tmp) / "test.c"
source.write_text(body, encoding="utf-8")
env = {k: v for k, v in os.environ.items() if k not in ("HOS_OOT_ADULT_MAP_FIX", "HOS_OOT_FIRST_NIGHT_FIX")}
for name, flags, switch in (("on", [], {}), ("off", ["-DSWITCH_OFF"], {"HOS_OOT_ADULT_MAP_FIX": "0"})):
binary = Path(tmp) / ("test-%s.exe" % name)
subprocess.run([args.cc, "-std=gnu11", "-Wall", "-Wextra", "-Werror"] + flags + [str(source), "-o", str(binary)],
check=True)
subprocess.run([str(binary)], check=True, env=dict(env, **switch))
if __name__ == "__main__":
main()

View File

@@ -1,14 +1,17 @@
"""Check that a save which still holds the first adult night's time lock is repaired outside Hyrule Field.
"""Check that a save holding the first adult night's time lock where the game can never let it go is repaired, and only there.
The game holds the clock at 20:00 while `HrlField_isFirstNightTime_Adult` (MurmurHash3 0x8592aa82) is 1 and quest
0x4dbca27f is not Ready (f_8347c020, called from f_803edf70). The flag is only meaningful in Hyrule Field's first adult
night; a save in the Market, the castle or anywhere else with the flag still 1 can never leave night.
`oot_inventory_refresh` runs twice a second while a save is loaded and reads the map for it, so the repair lives there:
outside Hyrule Field, clear the flag with the game's own Bool and log it once.
The game holds the clock at 20:00 while the Bool 0x8592aa82 is 1 and quest 0x4dbca27f (Meet_DekuTree) is past its step
Ready (f_8347c020, called from f_803edf70). 0x8592aa82 is `HrlField_HasEnteredFirstTime_Adult` by its MurmurHash3 (it was
named HrlField_isFirstNightTime_Adult here, which is 0xf1024b60). Sheik's cutscene sets it the first time Link becomes an
adult (Dm_TimeTemple_0055) and the adult Market's gate into Hyrule Field clears it on arrival
(Dm_SY_BancChangeArrive_HyruleField_02): the night is the adult Market's until then, the game's own. A child holding it
(no child's way out clears it) or an adult in Hyrule Field's map holding it (out without that arrival) is held for good.
`oot_inventory_refresh` runs twice a second while a save is loaded and reads the map and age for it, so the repair lives
there: clear the flag for those two through the game's own Bool setter (the live value and the save's copy: the live byte
alone came back as 1 at the next load) and log it once; an adult anywhere else keeps it.
This cuts the real `oot_inventory_refresh` (and `oot_first_night_fix` when the source has it) out of host/hos_main.c and
runs it against made-up save state, with no game and no romfs. Without the repair the flag stays 1 and the first case
fails; with it the flag is cleared. Run it with:
runs it against made-up save state, with no game and no romfs. Run it with:
python -I tests/test_oot_first_night.py --cc gcc
"""
@@ -30,11 +33,13 @@ FIXTURE = r'''
typedef struct { uint64_t x[32]; } Ctx;
static int flag = 1; /* HrlField_isFirstNightTime_Adult */
static int flag = 1; /* HrlField_HasEnteredFirstTime_Adult, the live value */
static int saved = 1; /* (its copy in the save) */
static int child = 1; /* Sequence_IsChildhood: 1 child, 0 adult */
static int age_known = 1;
static int event_playing; /* the game's event manager has an active event */
static const char *map_name = "Market_Child";
static int cleared;
static int cleared, live_only;
static void hos_log(const char *fmt, ...) { (void)fmt; }
static void rx_option_set(int id, int value) { (void)id; (void)value; }
@@ -42,16 +47,15 @@ static int oot_item_get(Ctx *c, const char *name) { (void)c; (void)name; return
static int oot_pouch_count(Ctx *c, const char *name) { (void)c; (void)name; return 0; } /* (a save is loaded) */
static int oot_gamedata_bool(Ctx *c, uint32_t hash, int *value) {
(void)c;
if (hash == 0xcea220d3u) { *value = child; return 1; }
if (hash == 0xcea220d3u && age_known) { *value = child; return 1; }
if (hash == 0x8592aa82u) { *value = flag; return 1; }
return 0;
}
/* (the live byte alone: never for this flag, the save would keep 1) */
__attribute__((unused)) static int oot_gamedata_set_bool(Ctx *c, uint32_t hash, int value) {
(void)c;
if (hash != 0x8592aa82u) return 0;
if (flag != value) cleared++;
flag = value;
return 1;
(void)c, (void)value;
if (hash == 0x8592aa82u) live_only++;
return 0;
}
static int oot_gamedata_string(Ctx *c, uint32_t hash, char *buf, size_t size) {
(void)c;
@@ -59,10 +63,22 @@ static int oot_gamedata_string(Ctx *c, uint32_t hash, char *buf, size_t size) {
snprintf(buf, size, "%s", map_name);
return 1;
}
/* (the event manager, and its +104: the event playing) */
/* (the event manager, and its +104: the event playing; the game data manager) */
#define OOT_EVENTMGR_SLOT 0x84c9e090ULL
__attribute__((unused)) static uint64_t oot_singleton(Ctx *c, uint64_t slot) { (void)c; return slot == OOT_EVENTMGR_SLOT ? 0x1000 : 0; }
#define OOT_GAMEDATA_SLOT 0x84c9e180ULL
__attribute__((unused)) static uint64_t oot_singleton(Ctx *c, uint64_t slot) {
(void)c;
return slot == OOT_EVENTMGR_SLOT ? 0x1000 : slot == OOT_GAMEDATA_SLOT ? 0x2000 : 0;
}
__attribute__((unused)) static uint64_t recomp_load64(Ctx *c, uint64_t a) { (void)c; return a == 0x1000 + 104 ? (uint64_t)event_playing : 0; }
/* (the game's SetBool: the live value and the save's copy) */
__attribute__((unused)) static int oot_gd_set(Ctx *c, uint64_t mgr, uint32_t hash, uint32_t value, int is_bool) {
(void)c;
if (mgr != 0x2000 || hash != 0x8592aa82u || !is_bool) return 0;
if (flag != (int)value) cleared++;
flag = saved = (int)value;
return 1;
}
#define OOT_CHEAT_ITEM_BASE 100
#define OOT_CHEAT_AGE_ID 200
@@ -75,66 +91,79 @@ static const char *const oot_item_names[OOT_ITEM_COUNT] = {"Item_A", "Item_B"};
// REFRESH
static void check(const char *what, int want_flag, int want_cleared) {
if (flag != want_flag || cleared != want_cleared) {
fprintf(stderr, "FAIL: %s: flag %d (want %d), clears %d (want %d)\n", what, flag, want_flag, cleared, want_cleared);
if (flag != want_flag || saved != want_flag || cleared != want_cleared || live_only) {
fprintf(stderr, "FAIL: %s: flag %d saved %d (want %d), clears %d (want %d), live-only writes %d\n", what, flag, saved,
want_flag, cleared, want_cleared, live_only);
exit(1);
}
}
static void at(Ctx *c, int64_t *now, int set, int is_child, const char *map) {
*now += 500000000LL;
flag = saved = set, child = is_child, map_name = map, cleared = 0;
oot_inventory_refresh(c, *now);
}
int main(void) {
Ctx c = {0};
int64_t now = 0;
#ifdef SWITCH_OFF
/* HOS_OOT_FIRST_NIGHT_FIX=0: the repair is off for the whole run. */
flag = 1, map_name = "Market_Child", cleared = 0;
oot_inventory_refresh(&c, now);
at(&c, &now, 1, 1, "Market_Child");
check("the switch off leaves the flag", 1, 0);
at(&c, &now, 1, 0, "HyruleField_Adult");
check("the switch off leaves the flag in the Field", 1, 0);
puts("PASS: HOS_OOT_FIRST_NIGHT_FIX=0 leaves the flag alone");
return 0;
#else
/* The report's state: the adult first-night flag left set in a save that is in the Market. */
flag = 1, map_name = "Market_Child", cleared = 0;
oot_inventory_refresh(&c, now);
check("the flag is cleared outside Hyrule Field", 0, 1);
/* #1064: a child back from his first adult visit before the gate, in the Market: no child's way out clears it. */
at(&c, &now, 1, 1, "Market_Child");
check("a child in the Market", 0, 1);
at(&c, &now, 1, 1, "HyruleField_Child");
check("a child in the Field", 0, 1);
/* Hyrule Field is where the first night belongs: the repair must not touch it. */
now += 500000000LL;
flag = 1, map_name = "HyruleField", cleared = 0;
oot_inventory_refresh(&c, now);
check("the flag is left alone in Hyrule Field", 1, 0);
/* The report's save: an adult at Lon Lon Ranch, in Hyrule Field's map, held at 20:00 for good. */
at(&c, &now, 1, 0, "HyruleField_Adult");
check("an adult in the Field", 0, 1);
/* The first night itself: an adult in the Market or the Temple of Time keeps it, the gate's arrival clears it. */
at(&c, &now, 1, 0, "Market_Adult");
check("an adult in the Market", 1, 0);
at(&c, &now, 1, 0, "GanonCastle");
check("an adult outside Ganon's castle", 1, 0);
/* Age not known: nothing to decide on. */
age_known = 0;
at(&c, &now, 1, 1, "Market_Child");
check("the age not known", 1, 0);
age_known = 1;
/* A save that is already clear is not written again. */
now += 500000000LL;
flag = 0, map_name = "Market_Child", cleared = 0;
oot_inventory_refresh(&c, now);
at(&c, &now, 0, 1, "Market_Child");
check("a clear flag is left clear", 0, 0);
/* No map name this refresh: nothing to decide on. */
now += 500000000LL;
flag = 1, map_name = "", cleared = 0;
oot_inventory_refresh(&c, now);
at(&c, &now, 1, 1, "");
check("an empty map leaves the flag", 1, 0);
/* An event running (the escape's cutscene, say) leaves the flag for a later refresh. */
now += 500000000LL;
flag = 1, map_name = "Market_Child", event_playing = 1, cleared = 0;
oot_inventory_refresh(&c, now);
/* An event running (the gate's own arrival, say) leaves the flag for a later refresh... */
event_playing = 1;
at(&c, &now, 1, 0, "HyruleField_Adult");
check("an event running leaves the flag", 1, 0);
/* The event over, the next refresh clears it. */
/* ...and the event over, the next refresh clears it, if the event has not. */
now += 500000000LL;
event_playing = 0, cleared = 0;
oot_inventory_refresh(&c, now);
check("after the event it clears", 0, 1);
/* A map change after the Field: the next refresh clears it. */
now += 500000000LL;
flag = 1, map_name = "Market_Child", cleared = 0;
oot_inventory_refresh(&c, now);
check("a later map clears it", 0, 1);
/* Twice a second: a refresh within the half second does nothing. */
flag = saved = 1, cleared = 0;
oot_inventory_refresh(&c, now + 100000000LL);
check("within the half second", 1, 0);
puts("PASS: the first adult night's time lock is cleared outside Hyrule Field, and only there");
puts("PASS: the first adult night's time lock is cleared for a child and for an adult in Hyrule Field, through the "
"game's setter, and kept for an adult in the Market");
return 0;
#endif
}
@@ -155,7 +184,10 @@ def main():
host = (ROOT / "host/hos_main.c").read_text(encoding="utf-8")
refresh = cut(host, r"^static void oot_inventory_refresh\(Ctx \*c, int64_t now\) \{.*?^\}", "oot_inventory_refresh")
fix = re.search(r"^static int oot_first_night_fix\(Ctx \*c, const char \*map\) \{.*?^\}", host, re.M | re.S)
body = FIXTURE.replace("// FIX", fix.group() if fix else "").replace("// REFRESH", refresh)
# (the adult's map repair is asked from the same place: tests/test_oot_adult_map.py checks it; here it finds no flag)
maps = re.search(r"^static int oot_adult_map_fix\(Ctx \*c, const char \*map\) \{.*?^\}", host, re.M | re.S)
fixes = "\n\n".join(m.group() for m in (fix, maps) if m)
body = FIXTURE.replace("// FIX", fixes).replace("// REFRESH", refresh)
with tempfile.TemporaryDirectory(prefix="oot-first-night-") as tmp:
source = Path(tmp) / "test.c"
source.write_text(body, encoding="utf-8")

View File

@@ -648,6 +648,7 @@ int hos_oot_autoload_menu(uint64_t vt, int focused_entry) { (void)vt, (void)focu
void hos_oot_menu_focus(Ctx *c, uint64_t screen, uint64_t pane, uint64_t lr);
void hos_oot_menu_tick(Ctx *c, uint64_t screen);
int hos_oot_options_front(void);
int hos_oot_pause_front(void);
static int fails;
#define CHECK(x) do { if (!(x)) { printf("FAIL line %d: %s\n", __LINE__, #x); fails++; } } while (0)
int main(void) {
@@ -685,13 +686,16 @@ int main(void) {
const uint64_t pause = FAKE_BASE + 0x3000, pause_vt = 0x84c0baa8ULL;
memcpy(GP(pause), &pause_vt, 8);
now_ns += 300000000;
CHECK(!hos_oot_pause_front());
hos_oot_menu_tick(&ctx, pause);
CHECK(told == 2); /* (the pause menu is not the Options screen) */
CHECK(hos_oot_pause_front() && !hos_oot_options_front()); /* ((Triforce, 11-30) nn_hid.c compare_to_play's B on it) */
now_ns += 16000000;
hos_oot_menu_tick(&ctx, options);
CHECK(told == 3 && told_value == 2);
for (int i = 0; i < 60; i++) now_ns += 16000000, hos_oot_menu_tick(&ctx, options);
CHECK(told == 63 && told_value == 2);
CHECK(!hos_oot_pause_front()); /* (its updates stopped under the Options: no B for it while they are in front) */
now_ns += 1000000000; /* (closed, back in play, then the title's Options) */
hos_oot_menu_tick(&ctx, options);
CHECK(told == 64 && told_value == 1);

View File

@@ -91,8 +91,9 @@ def main():
and "output_choice(opts.output_res) == OUTPUT_CUSTOM) &&" in shown, "the Custom size's rows show without Custom chosen")
check("if ((value == &opts.output_width || value == &opts.output_height) && custom_env()) return true;" in menu,
"the Custom size's rows can be changed while HOS_OUTPUT_SIZE sets the size")
# (10: the keys' Plus alone changed, host/nn_hid.c binds_load; the output numbers' schema is OUTPUT_OPTIONS_VERSION, 9, on)
check('out += "options_version=10\\n";' in menu, "the options file is not written as version 10 (output_sizes.h OUTPUT_OPTIONS_VERSION and later)")
# (10: the keys' Plus alone changed, host/nn_hid.c binds_load; 11: Threaded rendering's default alone, vk_menu.cpp menu_init;
# the output numbers' schema is OUTPUT_OPTIONS_VERSION, 9, on)
check('out += "options_version=11\\n";' in menu, "the options file is not written as version 11 (output_sizes.h OUTPUT_OPTIONS_VERSION and later)")
check("#define OUTPUT_OPTIONS_VERSION 9" in (ROOT / "gpu/vk/output_sizes.h").read_text(encoding="utf-8"),
"output_sizes.h: the 5120-wide sizes are not pictures from options_version 8")
check("rows[i].name != kUseWindowSize || (opts.output_res == OUTPUT_CUSTOM && !custom_env())" in shown

View File

@@ -307,6 +307,7 @@ ROWS = (
("Skip opening", "TAB_SYSTEM", "skip_opening", "0", "1", 1, 0, "HOS_OPT_SKIP_OPENING", "Game"),
("Skip title screen", "TAB_SYSTEM", "skip_title", "0", "1", 1, 0, "HOS_OPT_SKIP_TITLE", "Game"),
("Autosave", "TAB_SYSTEM", "autosave", "0", "1", 1, 1, "HOS_OPT_AUTOSAVE", "Saves & reports"),
("Unlimited amiibo uses", "TAB_SYSTEM", "amiibo_unlimited", "0", "1", 1, 0, "HOS_OPT_AMIIBO_UNLIMITED", "NFC"),
("Mute in background", "TAB_AUDIO", "mute_background", "0", "1", 1, 0, "HOS_OPT_MUTE_BACKGROUND", "Sound"),
("Microphone gain", "TAB_AUDIO", "mic_gain", "25", "400", 25, 100, "HOS_OPT_MIC_GAIN", "Microphone"),
)

View File

@@ -29,6 +29,7 @@ struct Gpu {
wr::Parts table;
uint64_t first_noted = 0; // (value_rec: the first part, emplace)
uint64_t range = 0; // ((11-28) the part whose write-back last covered the read's range, 0: none known)
int range_part = -1; // ((11-29) the part (its index) whose submit makes the range known: its write-back copied it)
void submit_up_to(size_t n) {
for (; sent < n && sent < parts.size(); sent++) note(sent);
@@ -36,6 +37,7 @@ struct Gpu {
void note(size_t i) {
table.submitted(value, parts[i], i + 1 == parts.size());
if (!first_noted) first_noted = parts[i];
if ((int)i == range_part) range = parts[i];
}
void begin() {
for (size_t i = 0; i < sent; i++) note(i);
@@ -97,6 +99,20 @@ int main() {
CHECK("mode 2, the CPU only reads it: the first part", !wr::rec_end_applies(wr::kRecEndCpuWritten, false));
CHECK("mode 1: the rule either way", wr::rec_end_applies(wr::kRecEndAll, false) && wr::rec_end_applies(wr::kRecEndAll, true));
CHECK("mode 0: never", !wr::rec_end_applies(wr::kRecEndOff, true));
// ((11-29) mode 3: mode 2's rule for the CPU-written ranges, and the read-only ranges at their part (range_applies))
CHECK("mode 3", wr::rec_end_mode("3") == wr::kRecEndRange && wr::rec_end_on("3"));
// ((11-29, the owner's decision) the reader's default where the parts end at the game's render passes: unset or empty alone
CHECK("unset with the pass-end parts: 3", wr::rec_end_mode(nullptr, wr::kRecEndRange) == wr::kRecEndRange
&& wr::rec_end_mode("", wr::kRecEndRange) == wr::kRecEndRange);
CHECK("set with the pass-end parts: as set", wr::rec_end_mode("2", wr::kRecEndRange) == wr::kRecEndCpuWritten
&& wr::rec_end_mode("0", wr::kRecEndRange) == wr::kRecEndOff
&& wr::rec_end_mode("1", wr::kRecEndRange) == wr::kRecEndAll
&& wr::rec_end_mode("7", wr::kRecEndRange) == wr::kRecEndCpuWritten);
CHECK("mode 3, the CPU writes it: the rule", wr::rec_end_applies(wr::kRecEndRange, true) && !wr::range_applies(wr::kRecEndRange, true));
CHECK("mode 3, the CPU only reads it: its range's part",
!wr::rec_end_applies(wr::kRecEndRange, false) && wr::range_applies(wr::kRecEndRange, false));
CHECK("the range's part in mode 3 alone", !wr::range_applies(wr::kRecEndCpuWritten, false) && !wr::range_applies(wr::kRecEndAll, false)
&& !wr::range_applies(wr::kRecEndOff, false));
// the parts' table: the newest part and whether it ended the recording; an older note changes nothing; a later recording
// under the same value takes the entry over from its first part; nothing for no value or no number; the oldest past the cap
@@ -318,5 +334,111 @@ int main() {
CHECK("random: the old wait ended early at every one of them", old_early == cases_going_on);
std::printf("readback rec end: %d of 20000 reads came before their recording's end; the old wait ended early at all %d\n",
cases_going_on, old_early);
// ((11-29) RX_VK_RB_REC_END=3, readback_range_wait: a range the CPU only reads waits for the part that copied it back. The
// flicker's case: parts end at the game's render passes, the first after ~32 draws; the read comes after the first part's
// submit, its range copied back by the second. The first part's wait read it a frame late (the exposure moved for 15 presents)
{
Gpu g, g0;
g.parts = {10, 11, 12};
g.range_part = 1;
g0 = g;
g.begin(), g0.begin();
const wr::ReadbackWait r = wr::readback_range_wait(g);
CHECK("range: known and done", r.known && r.ok);
CHECK("range: ends at the part that copied it back, not the first, not the last", g.rec_done == 11 && g.hangs == 0);
const wr::ReadbackWait r0 = wr::readback_wait(false, g0);
CHECK("range: the first part's wait ended before it (the frame-late read)", r0.known && g0.rec_done == 10);
}
{ // the range's part submitted already: one wait, for it, nothing sliced
Gpu g;
g.parts = {10, 11, 12};
g.sent = 2;
g.range_part = 0;
g.begin();
const wr::ReadbackWait r = wr::readback_range_wait(g);
CHECK("range known: one wait, for its part", r.known && r.ok && !r.went_on && g.rec_waits == 1 && g.rec_done == 10 && g.slices == 0);
}
{ // no part copies the range back: the recording's end, as the last-part rule
Gpu g;
g.parts = {10, 11, 12};
g.begin();
const wr::ReadbackWait r = wr::readback_range_wait(g);
CHECK("range never copied: the last part", r.known && r.ok && r.went_on && g.rec_done == 12 && g.hangs == 0);
}
{ // an ended recording whose range no part noted (its runs dropped once done): one wait, for the last part
Gpu g;
g.parts = {10, 11, 12};
g.sent = 3;
g.begin();
const wr::ReadbackWait r = wr::readback_range_wait(g);
CHECK("ended, range not noted: one wait", r.known && r.ok && !r.went_on && g.rec_waits == 1 && g.rec_done == 12);
}
{ // the parts not known, the first part is (value_rec): that, as before
Gpu g;
g.parts = {10, 11};
g.first_noted = 10;
const wr::ReadbackWait r = wr::readback_range_wait(g);
CHECK("parts not known: the first part", r.known && r.ok && g.rec_waits == 1 && g.rec_done == 10);
Gpu n;
n.parts = {10, 11};
const wr::ReadbackWait rn = wr::readback_range_wait(n);
CHECK("not known at all: the fallback's", !rn.known && n.rec_waits == 0);
}
{ // the replay stuck before the range's part: slices of the submissions' timeline, ended once it reaches the value
Gpu g;
g.parts = {10, 11, 12};
g.range_part = 2;
g.step = 0;
g.timeline_after = 4;
g.begin();
const wr::ReadbackWait r = wr::readback_range_wait(g);
CHECK("range, stuck: ended by the timeline", r.known && r.ok && r.went_on && r.slices == 4 && g.timeline_at_v && g.hangs == 0);
}
{ // an error ends it, not done
Gpu g;
g.parts = {10, 11, 12};
g.range_part = 1;
g.rec_wait_error_at = 0;
g.begin();
const wr::ReadbackWait r = wr::readback_range_wait(g);
CHECK("range, error: not done", r.known && !r.ok && g.rec_waits == 1);
}
// 20,000 random recordings, the range copied back by one of the parts or by none: never back before the range's part is done
// (none: the last part), never past it but for the timeline, never a wait for a part not submitted, one wait when its part was
// submitted before the read; the first part's wait read it early whenever a later part copied it
int range_later = 0, first_early = 0;
for (int k = 0; k < 20000; k++) {
Gpu g, g0;
const size_t n = 1 + rng() % 8;
uint64_t s = 5000000 + (uint64_t)k * 16;
for (size_t i = 0; i < n; i++) g.parts.push_back(s++);
g.sent = 1 + rng() % n;
g.step = (int)(rng() % 4);
if (g.step == 0) g.timeline_after = 1 + (int)(rng() % 20);
g.range_part = (int)(rng() % (n + 1)) - 1;
g0 = g;
g.begin(), g0.begin();
const size_t sent0 = g.sent;
const wr::ReadbackWait r = wr::readback_range_wait(g);
CHECK("range random: known and done", r.known && r.ok);
CHECK("range random: never a wait for a part not submitted", g.hangs == 0);
CHECK("range random: waits bounded", g.rec_waits <= (int)n + 1);
const uint64_t want = g.range_part < 0 ? g.parts.back() : g.parts[(size_t)g.range_part];
CHECK("range random: never before the range's part is done", g.rec_done >= want || g.timeline_at_v);
CHECK("range random: never past it but for the timeline", g.rec_done == want || g.timeline_at_v);
if (g.range_part >= 0 && (size_t)g.range_part < sent0)
CHECK("range random: its part submitted before the read: one wait", g.rec_waits == 1 && !r.went_on && g.slices == 0);
const wr::ReadbackWait r0 = wr::readback_wait(false, g0);
CHECK("range random old: known", r0.known && r0.ok);
if (g.range_part > 0) {
range_later++;
if (g0.rec_done < want) first_early++;
}
}
CHECK("range random: ranges a later part copied were many", range_later > 5000);
CHECK("range random: the first part's wait read every one of them early", first_early == range_later);
std::printf("readback range wait: %d of 20000 ranges were copied back after the first part; the first part's wait read all %d early\n",
range_later, first_early);
return 0;
}

View File

@@ -11,7 +11,9 @@ to come in a later part.
Compiles and runs the header's rule against a made-up GPU (tests/test_readback_rec_end.cpp: the parts' table, the meter's case,
an ended recording, one part, not known, a stuck replay ended by the timeline, an error, and 20,000 random recordings: never back
before the last part is done, never a wait for a part not submitted; the old wait ends at the first part at every read that came
before the recording's end), and reads the source for what needs the game:
before the recording's end; (11-29) RX_VK_RB_REC_END=3's wait for a range the CPU only reads, readback_range_wait: at the part
that copied the range back, never before it, past it only by the timeline, the last part when none did; 20,000 random recordings
again), and reads the source for what needs the game:
- submit_recording's registration notes every submit, part or end, by the recording's own value, under rec_map_mu;
- readback_rec_wait runs the header's rule by RX_VK_RB_REC_END, looks the tables up under rec_map_mu, flushes the held submits
before it waits on the recordings' timeline (a batched recording's signal goes out only with the batch), and slices the
@@ -56,7 +58,8 @@ def in_order(text, needles, where):
def check_source():
head = (ROOT / "gpu/vk/wb_rec_wait.h").read_text(encoding="utf-8")
for needle in ("struct Parts {", "inline bool rec_end_on(const char* text)", "struct ReadbackWait {",
"ReadbackWait readback_wait(bool rec_end, D& d) {",
"ReadbackWait readback_wait(bool rec_end, D& d) {", "ReadbackWait readback_range_wait(D& d) {",
"inline bool range_applies(int mode, bool cpu_written) { return mode == kRecEndRange && !cpu_written; }",
"void part_submitted(uint64_t value, uint64_t seq, bool part) { submitted(value, seq, !part); }"):
check(needle in head, "gpu/vk/wb_rec_wait.h: %s is missing" % needle)
@@ -72,20 +75,38 @@ def check_source():
"vk_replay.cpp: the parts are noted somewhere past the registration")
on = function(replay, "int rb_rec_end_mode() {")
check('wr::rec_end_mode(getenv("RX_VK_RB_REC_END"))' in on and "static const int v" in on,
check('const char* e = getenv("RX_VK_RB_REC_END");' in on and "static const int v" in on,
"RX_VK_RB_REC_END is not read once through the header's rule")
# ((Triforce, 11-29, the owner's decision) unset: 3 where the parts end at the game's render passes (their first part is
# ~32 draws, and mode 2 read a later part's result a frame late: the brightness pulses), else 2 as before
check("const int m = wr::rec_end_mode(e, parts ? wr::kRecEndRange : wr::kRecEndCpuWritten);" in on
and "const bool parts = pass_end_parts_on();" in on,
"RX_VK_RB_REC_END's default is not 3 with the pass-end parts and 2 with counted parts")
ends = function(replay, "PassEndParts& pass_end_parts() {")
check("rb_rec_end_mode(" not in ends and "rb_rec_end_on(" not in ends,
"pass_end_parts asks the readback mode's reader, which asks pass_end_parts: the two statics would wait on each other")
check('rec_end_mode(getenv("RX_VK_RB_REC_END"), ::mkwvk::wb_rec_wait::kRecEndRange)' in ends
and 'num("RX_VK_PART_RB", range ? 32 : 0)' in ends,
"RX_VK_PART_RB's default does not follow mode 3 (32 there, off with another mode set)")
# ((Triforce, 11-28) mode 2, the default: the last-part rule only where the CPU writes the range after reading it)
fr = function(replay, "bool rb_rec_end_for(uint64_t guest, uint64_t size) {")
check("m == wr::kRecEndCpuWritten && memory_rb_cpu_written(guest, size)" in fr and "return wr::rec_end_applies(m, cpu);" in fr,
"rb_rec_end_for does not ask the memory whether the CPU writes the range (mode 2) through the header's rule")
# ((11-29) mode 3: the same, and a range the CPU only reads at the part that copied it back, by the header's range_applies)
fr = function(replay, "bool rb_rec_end_for(uint64_t guest, uint64_t size, bool* range) {")
check("(m == wr::kRecEndCpuWritten || m == wr::kRecEndRange) && memory_rb_cpu_written(guest, size)" in fr
and "return wr::rec_end_applies(m, cpu);" in fr,
"rb_rec_end_for does not ask the memory whether the CPU writes the range (modes 2 and 3) through the header's rule")
check("*range = wr::range_applies(m, cpu);" in fr, "rb_rec_end_for does not say a read-only range's wait (mode 3) by the header's rule")
mem = (ROOT / "gpu/vk/vk_memory.cpp").read_text(encoding="utf-8")
check(mem.count("memory_rb_cpu_collected(pages, n);") == 2, "the two collections of the CPU's pages do not both note the read-back pages")
check("memory_rb_watch(guest, size);" in function(mem, "void memory_note_readback(uint64_t guest, uint64_t size) {"),
"a readback's pages are not watched for the CPU's writes")
w = function(replay, "bool readback_rec_wait(uint64_t v, uint64_t guest, uint64_t size, int* ok) {")
w = function(replay, "bool readback_rec_wait(uint64_t v, uint64_t guest, uint64_t size, int* ok, bool range) {")
for needle, why in (
("if (!rec_timeline || per_queue_fences_off()) return false;", "it waits by recordings where there are none"),
("::mkwvk::wb_rec_wait::readback_wait(rb_rec_end_on(), calls);", "it does not run the header's rule by the switch"),
("range ? ::mkwvk::wb_rec_wait::readback_range_wait(calls) : ::mkwvk::wb_rec_wait::readback_wait(rb_rec_end_on(), calls);",
"it does not run the header's rule by the switch, or a read-only range's wait (mode 3) by the header's"),
("uint64_t range_seq() { return memory_wb_part_seq(guest, size, v); }",
"the range's part is not the memory's part that copied the range back under v"),
("st_rb_range.fetch_add(1, std::memory_order_relaxed);", "the read-only ranges' waits (mode 3) are not counted"),
("return rec_parts_by_value.of(v);", "it does not look the parts up"),
("const auto it = value_rec.find(v);", "the old lookup is not value_rec's"),
("void flush() { queue_flush_for(FR_WAIT); }", "its looks do not flush the held submits"),
@@ -101,8 +122,10 @@ def check_source():
check("pSemaphores = &rec_timeline;" in rw and "UINT64_MAX" in rw, "the recording's wait is not the recordings' timeline, unbounded")
both = function(replay, "bool readback_recorded_wait(uint64_t v, uint64_t guest, uint64_t size, int* ok) {")
check("return rb_rec_end_for(guest, size) ? readback_rec_wait(v, guest, size, ok) : wait_recorded(v, UINT64_MAX, ok);" in both,
"readback_recorded_wait does not take the rule by the switch (the old wait kept for =0)")
in_order(both, ["bool range = false;",
"if (rb_rec_end_for(guest, size, &range)) return readback_rec_wait(v, guest, size, ok, false);",
"return range ? readback_rec_wait(v, guest, size, ok, true) : wait_recorded(v, UINT64_MAX, ok);"],
"readback_recorded_wait (the rule by the switch, a read-only range at its part for =3, the old wait kept for =0 and 2)")
inv = function(replay, "void invalidate(uint64_t gpu, uint64_t size) {")
check(inv.count("readback_recorded_wait(v, host->gpu_guest(gpu), size, &ok)") == 2, "invalidate's two waits by recordings do not both take the rule")
check("if (!(unforced && readback_recorded_wait(v, host->gpu_guest(gpu), size, &ok))) {" in inv, "the submitting thread's wait does not take the rule")
@@ -120,11 +143,39 @@ def check_source():
gl = function(replay, "void readback_went_on_line() {")
check("st_rb_went_on.exchange(0)" in gl and "(RX_VK_RB_REC_END=0: the first part, as before)" in gl,
"the 3000-readback line does not count the reads that waited past a part")
check("st_rb_range.exchange(0)" in gl and "st_rb_range_later.exchange(0)" in gl,
"the 3000-readback line does not count the read-only ranges' waits (mode 3) and those past the first part")
dev = (ROOT / "docs/development.md").read_text(encoding="utf-8")
rows = [line for line in dev.splitlines() if line.startswith("| `RX_VK_RB_REC_END=0` |")]
check(len(rows) == 1, "docs/development.md: RX_VK_RB_REC_END is not in the switches table once")
check("tests/test_readback_rec_end.py" in rows[0] and "wb_rec_wait.h" in rows[0], "docs/development.md: the row names neither the rule nor its test")
check("`=3`" in rows[0], "docs/development.md: the RX_VK_RB_REC_END row does not say mode 3")
# ((Triforce, 11-29) RX_VK_LATE_PART: the queue's late-page wait at the part that wrote the pages back last, the value's
# wait as before whenever that part is not known; off unless set (or the lab knob latepart))
flush = function(replay, "void late_fix_flush_locked() {")
in_order(flush, ["const uint64_t v = memory_late_fix_pending();", "if (completed() < v && !late_fix_part_wait()) {",
"vk_timeline_wait_sent(v)", "memory_late_fix_apply(UINT64_MAX);"],
"late_fix_flush_locked (the part's wait first, the value's when it was not made, then the fixes)")
pw = function(replay, "bool late_fix_part_wait() {")
in_order(pw, ["if (!rec_timeline || !memory_late_part_on()) return false;", "const uint64_t seq = memory_late_fix_part();",
"if (!seq) {", "wi.pSemaphores = &rec_timeline, wi.pValues = &seq;", "return done;"],
"late_fix_part_wait (off, no timeline or no part known: the value's wait)")
mem_on = function(mem, "bool memory_late_part_on() {")
check('getenv("RX_VK_LATE_PART")' in mem_on and 'lab_ab::on("latepart")' in mem_on and "atoi(e) != 0" in mem_on,
"RX_VK_LATE_PART is not off unless set, with the lab knob latepart")
lp = function(mem, "uint64_t late_pages_part(const std::vector<std::pair<uint32_t, uint32_t>>& slots, uint64_t done) {")
in_order(lp, ["std::lock_guard lk(wb_pages_mu);", "if (wb_runs_lost > done) return 0;", "if (r.value <= done",
"if (b == wb_batch_seq.end()) return 0;", "part = std::max(part, b->second);"],
"late_pages_part (a run cut or a part not submitted: not known)")
fp = function(mem, "uint64_t memory_late_fix_part() {")
check("if (!f.part) return 0;" in fp, "memory_late_fix_part does not give 0 when one pending fix's part is not known")
check("if (memory_late_part_on()) f.part = late_pages_part(f.slots, vk_timeline_completed());" in mem,
"the take does not note a put-off fix's part")
lrows = [line for line in dev.splitlines() if line.startswith("| `RX_VK_LATE_PART=1` |")]
check(len(lrows) == 1 and "off unless set" in lrows[0] and "tests/test_readback_rec_end.py" in lrows[0],
"docs/development.md: no RX_VK_LATE_PART row naming its default and its test")
def main():

View File

@@ -31,12 +31,13 @@ def main():
if "readback_recorded_wait(v, host->gpu_guest(gpu), size, &ok)" not in inv or "wait_recorded(v, UINT64_MAX, ok)" not in rrw:
raise SystemExit("invalidate's readback wait no longer goes through wait_recorded: update this test")
# ((Triforce, 11-27) RX_VK_RB_REC_END: the readback's wait by its own rule, readback_rec_wait, flushes the same way)
rb = body(replay, "bool readback_rec_wait(uint64_t v, uint64_t guest, uint64_t size, int* ok) {")
rb = body(replay, "bool readback_rec_wait(uint64_t v, uint64_t guest, uint64_t size, int* ok, bool range) {")
rw = rb[rb.index("int rec_wait(uint64_t seq) {"):]
flush = rw.find("queue_flush_for(")
if "vkWaitSemaphores(" not in rw or flush < 0 or flush > rw.index("vkWaitSemaphores("):
raise SystemExit("readback_rec_wait waits without sending the held batch: a batched recording's signal never comes")
if "readback_rec_wait(v, guest, size, ok)" not in rrw:
# ((11-29) and the read-only ranges' wait at their part, RX_VK_RB_REC_END=3, the same function)
if "readback_rec_wait(v, guest, size, ok, false)" not in rrw or "readback_rec_wait(v, guest, size, ok, true)" not in rrw:
raise SystemExit("invalidate's readback wait no longer goes through readback_rec_wait: update this test")
print("PASS: wait_recorded and readback_rec_wait send the held batch before they wait")

View File

@@ -15,7 +15,8 @@ out); libopus is compiled by the same C compiler that links it, its paths relati
crates Cargo.lock names, unpacked from the cache (each checked by its Cargo.lock SHA-256, one that is not refused); what
fails the check is not copied out. A Rust download whose SHA-256 is not the pinned one is refused and not kept.
(Triforce) It is built by hand; nx2/build.py copies it beside the game when third_party/renhdrum/ has it, and
(Triforce) The releases build it: setup/pack_tools.ps1 into the tools zip, scripts/linux/appimage.sh into the AppImage
(a pack without it stops unless told); nx2/build.py copies it beside the game when third_party/renhdrum/ has it, and
nx2/make_game.py stages it with the game's other files. third_party/renhdrum holds the source, with its upstream archive
named.
@@ -378,5 +379,19 @@ class Ships(unittest.TestCase):
self.assertIn("SetThreadErrorMode(SEM_FAILCRITICALERRORS", module)
self.assertIn("LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR", module)
def test_the_releases_build_it(self):
# ((11-29) v0.8.0 to v0.8.5.2 shipped the code without the library: git ignores renhdrum.dll, and the tools zip packs
# tracked files. The pack builds it into the tools' third_party/renhdrum/, where build.py looks, and stops without it)
pack = (ROOT / "setup" / "pack_tools.ps1").read_text(encoding="utf-8")
self.assertIn("scripts\\renhdrum.py') build --target windows --llvm-mingw $rhMingw", pack)
self.assertIn("$rhOut = Join-Path $tools 'third_party\\renhdrum\\renhdrum.dll'", pack)
self.assertIn("if (-not $AllowNoRenhdrum) { throw", pack)
self.assertLess(pack.index("$rhOut = "), pack.index("# 5. the zips"))
# (the AppImage: renhdrum.so, the Linux target named, into its tools' third_party/renhdrum/)
image = (ROOT / "scripts" / "linux" / "appimage.sh").read_text(encoding="utf-8")
self.assertIn('scripts/renhdrum.py build --target linux --cache "$B/renhdrum-rust" '
'--out "$T/third_party/renhdrum/renhdrum.so"', image)
self.assertLess(image.index("renhdrum.py build"), image.index("# ---- what it builds with ----"))
if __name__ == "__main__":
unittest.main()

View File

@@ -0,0 +1,142 @@
"""((Triforce, 11-30) The ReShade comparison asked inside the pause menu's Options goes to play first ("ReShade Compare not
taking you to gameplay screen", v0.8.5.2): the game is paused there and its scene draws nothing, so the comparison over its
screens showed the Options and the pause menu.
host/nn_hid.c's compare_to_play is compiled alone with stand-ins for the option and the screens: B once on the Options, once
more only if that screen still runs 1.5 s later, then B on the pause menu, the renderer told 2 once neither has run for
300 ms, 3 when they are still up after 4 s, nothing while nothing is asked. The menu's side is read from the sources: the
Compare row's way there (compare_leaves_menus, not from the title's Options nor with a close question waiting), the host's
word taken, the comparison opened over the game and its Back closing the options, and the option answered by the renderer.
python -I -B tests/test_reshade_compare_play.py (needs a C compiler)
"""
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def block(text, marker):
start = text.index(marker)
end = text.index("{", start) + 1
depth = 1
while depth:
depth += (text[end] == "{") - (text[end] == "}")
end += 1
return text[start:end]
FIXTURE = r"""
#include <stdint.h>
#include <stdio.h>
#include <string.h>
enum { HOS_OPT_COMPARE_PLAY = 432 };
static int option_now, told, told_value, options_up, pause_up, taps;
static int64_t now;
static char last_tap[32];
static int rx_option(int id, int otherwise) { return id == HOS_OPT_COMPARE_PLAY ? option_now : otherwise; }
static void rx_option_set(int id, int value) { if (id == HOS_OPT_COMPARE_PLAY) told++, told_value = value, option_now = value; }
static void hos_hid_tap(const char *press) { taps++, snprintf(last_tap, sizeof last_tap, "%s", press); }
static void hos_log(const char *f, ...) { (void)f; }
int hos_oot_options_front(void) { return options_up; }
int hos_oot_pause_front(void) { return pause_up; }
"""
MAIN = r"""
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
static void run(int64_t ms) { for (int64_t t = 0; t < ms; t += 16) now += 16000000LL, compare_to_play(now); }
int main(void) {
now = 1000000000LL;
options_up = 1;
run(500);
CHECK(taps == 0 && told == 0); /* (nothing asked: nothing pressed) */
option_now = 1; /* (Compare confirmed inside the pause menu's Options) */
run(16);
CHECK(taps == 1 && !strcmp(last_tap, "0:B/80")); /* (B on the Options) */
run(1000);
CHECK(taps == 1); /* (its animation: no second B yet) */
run(600);
CHECK(taps == 2); /* (still up 1.5 s on: the press was lost, once more) */
run(2000);
CHECK(taps == 2); /* (twice at most) */
options_up = 0, pause_up = 1; /* (back on the pause menu) */
run(16);
CHECK(taps == 3 && told == 0); /* (B on the pause menu) */
pause_up = 0; /* (it closed: in play once 300 ms pass with neither screen) */
run(200);
CHECK(told == 0);
run(200);
CHECK(told == 1 && told_value == 2 && taps == 3);
run(1000);
CHECK(told == 1 && taps == 3); /* (the word given: nothing more while it is not asked again) */
/* a second ask whose menus stay up: 3 after 4 s, the comparison where it is */
option_now = 1, options_up = 1, taps = 0;
run(4100);
CHECK(told == 2 && told_value == 3 && taps == 2);
run(1000);
CHECK(told == 2 && taps == 2);
if (!fails) printf("PASS\n");
return fails != 0;
}
"""
def check_sources():
menu = (ROOT / "gpu" / "vk" / "vk_menu.cpp").read_text(encoding="utf-8")
replay = (ROOT / "gpu" / "vk" / "vk_replay.cpp").read_text(encoding="utf-8")
api = (ROOT / "gpu" / "vk" / "vk_api.h").read_text(encoding="utf-8")
hid = (ROOT / "host" / "nn_hid.c").read_text(encoding="utf-8")
menu_c = (ROOT / "host" / "oot_menu.c").read_text(encoding="utf-8")
if "enum { HOS_OPT_COMPARE_PLAY = 432 };" not in api:
raise SystemExit("the option HOS_OPT_COMPARE_PLAY is gone")
if "if (id == HOS_OPT_COMPARE_PLAY) return menu_compare_play();" not in replay:
raise SystemExit("the renderer does not answer HOS_OPT_COMPARE_PLAY: the host never sees the ask")
leaves = block(menu, "bool compare_leaves_menus() {")
for need in ("embed_open", "game_options_from_pause", "!apply_ask()", "!restart_ask()"):
if need not in leaves:
raise SystemExit("compare_leaves_menus lost a condition: " + need)
press = "else if (press[7] && r.name == kReshadeCompare && compare_leaves_menus()) {"
if press not in menu or menu.index(press) > menu.index("else if (press[7] && reshade_menu::act(r.name))"):
raise SystemExit("the Compare row inside the pause menu's Options does not go to play first")
if "compare_play.store(1, std::memory_order_relaxed);" not in menu:
raise SystemExit("the Compare row does not ask the host")
if "if (id == HOS_OPT_COMPARE_PLAY) {" not in menu or "compare_exchange_strong(asked, value" not in menu:
raise SystemExit("the host's word (2 in play, 3 not) is not taken by the menu")
if "reshade_menu::start_comparison();" not in menu or "compare_from_game = ready == 2;" not in menu:
raise SystemExit("the comparison does not open once the host says so")
if "if (!reshade_menu::comparing() && compare_from_game) compare_from_game = false, open_now = false" not in menu:
raise SystemExit("the comparison's Back no longer closes the options it opened over the game")
read = block(hid, "static void read_input(")
if "compare_to_play(hos_now_ns());" not in read:
raise SystemExit("read_input does not run compare_to_play")
if menu_c.count("int hos_oot_pause_front(void) {") != 2:
raise SystemExit("hos_oot_pause_front is not in both halves of host/oot_menu.c")
def main():
check_sources()
compiler = shutil.which("gcc") or shutil.which("clang")
if not compiler:
print("SKIP: no C compiler (the sources checked)")
return
hid = (ROOT / "host" / "nn_hid.c").read_text(encoding="utf-8")
code = FIXTURE + block(hid, "static void compare_to_play(int64_t now) {") + "\n" + MAIN
with tempfile.TemporaryDirectory(prefix="triforce-compare-play-") as tmp:
tmp = Path(tmp)
(tmp / "t.c").write_text(code, encoding="utf-8")
binary = tmp / ("t.exe" if sys.platform == "win32" else "t")
build = subprocess.run([compiler, "-std=gnu11", "-Wall", "-Werror", str(tmp / "t.c"), "-o", str(binary)],
text=True, capture_output=True)
if build.returncode:
raise SystemExit(build.stderr)
run = subprocess.run([str(binary)], text=True, capture_output=True, timeout=30)
if run.returncode:
raise SystemExit(run.stdout + run.stderr)
print("PASS: Compare from the pause menu's Options leaves its menus (B, B), opens over the game, and gives up after 4 s")
if __name__ == "__main__":
main()

102
tests/test_sim_turf_hold.py Normal file
View File

@@ -0,0 +1,102 @@
"""A simulated-turf list that a program reads the game's way never grows past the game's size (11-29 GPU hang).
python -I -B tests/test_sim_turf_hold.py [--cxx clang++]
Cuts `SimTurfPrivate` and `sim_turf_hold` out of gpu/vk/vk_draw.cpp and builds them against the real
gpu/vk/sim_turf_capacity.h, then plays the 11-29 crash at them. His Kokiri Forest edit asked for 132033 of the blade
list's 143360 records; the list grew to 165056, and the pool producer (3de6d86ec7e6720e, left as the game has it by the IR
pass) read record 143359 - i for i past 143359, far outside the buffer: the dispatch never ended, device lost. Checks:
without a hold the list grows (as before: the control); held, it stays at the game's size under the same demand; a list
already grown when the hold comes is made the game's size again at the next install.
"""
from __future__ import annotations
import argparse
import os
import subprocess
import sys
import tempfile
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent)) # (python -I leaves the check's own folder off the path)
from srccut import block # noqa: E402
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
ROOT = Path(__file__).resolve().parents[1]
HARNESS = r"""
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include "sim_turf_capacity.h"
using VkBuffer = void*;
using VmaAllocation = void*;
#define VK_NULL_HANDLE nullptr
namespace Shader::Optimization {
inline constexpr uint32_t kSimTurfBladeCap = 143360;
inline constexpr uint32_t kSimTurfPoolCap = 138240;
}
namespace mkwvk {
@CUT@;
@HOLD@
}
#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); std::exit(1); } } while (0)
int main() {
using mkwvk::SimTurfPrivate;
for (const bool pool : {false, true}) {
const uint32_t stock = pool ? 138240u : 143360u, wanted = pool ? 127000u : 132033u;
{ // the control: nobody reads it the game's way, so it grows as before
SimTurfPrivate g(pool, 1u << 20);
CHECK(g.policy.observe(wanted, 100));
g.policy.installed();
CHECK(g.policy.capacity() > stock);
}
{ // held from the start (the unpatched reader runs every frame long before the demand): it never grows
SimTurfPrivate g(pool, 1u << 20);
mkwvk::sim_turf_hold(g, pool);
CHECK(!g.policy.observe(wanted, 100));
CHECK(!g.policy.observe(1u << 19, 101));
CHECK(g.policy.capacity() == stock && g.policy.target() == stock && g.policy.maximum() == stock);
}
{ // grown first, held after: the next install is the game's size again
SimTurfPrivate g(pool, 1u << 20);
CHECK(g.policy.observe(wanted, 100));
g.policy.installed();
CHECK(g.policy.capacity() > stock);
mkwvk::sim_turf_hold(g, pool);
CHECK(g.policy.target() == stock); // (target != capacity: the producer's next binding resizes)
g.policy.installed();
CHECK(g.policy.capacity() == stock);
CHECK(!g.policy.observe(wanted, 200));
g.policy.limit(1u << 20); // (a reader's larger bound never lifts the hold)
CHECK(!g.policy.observe(wanted, 201) && g.policy.capacity() == stock);
}
}
std::puts("PASS: a simulated-turf list read the game's way stays at the game's size");
}
"""
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cxx", default="clang++")
args = parser.parse_args()
draw = (ROOT / "gpu" / "vk" / "vk_draw.cpp").read_text(encoding="utf-8")
cut = block(draw, "struct SimTurfPrivate {")
hold = block(draw, "void sim_turf_hold(SimTurfPrivate& g, bool pool) {")
with tempfile.TemporaryDirectory(prefix="sim-turf-hold-") as folder:
src = Path(folder) / "sim_turf_hold.cpp"
src.write_text(HARNESS.replace("@CUT@", cut).replace("@HOLD@", hold), encoding="utf-8")
exe = Path(folder) / "sim_turf_hold.exe"
subprocess.run([args.cxx, "-std=c++20", "-I" + str(ROOT / "gpu" / "vk"), str(src), "-o", str(exe)], check=True)
env = os.environ.copy()
env["PATH"] = str(Path(args.cxx).resolve().parent) + os.pathsep + env.get("PATH", "")
subprocess.run([str(exe)], check=True, env=env)
if __name__ == "__main__":
main()

140
tests/test_tex_pack_bc7.py Normal file
View File

@@ -0,0 +1,140 @@
#!/usr/bin/env python3
"""gpu/vk/tex_pack_bc7.h: Evil HD's texture pack as BC7, prepared once (vk_texture.cpp texpack).
Checks the prepared file's header and sizes, the levels, the 2 x 2 halving, the tiers by the card's memory, and that the
encoder writes BC7 mode 6 blocks that keep a flat colour exactly. Compiles a small harness with the C++ compiler given.
python -I -B tests/test_tex_pack_bc7.py [--cxx g++]
"""
import argparse
import os
import subprocess
import sys
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
RUN_ALL_ARGS = ["--cxx", "g++"]
HARNESS = r'''
#include "tex_pack_bc7.h"
#include <cstdio>
static int failures;
#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL %d: %s\n", __LINE__, #x); failures++; } } while (0)
namespace tb = mkwvk::tex_pack_bc7;
// (mode 6: bit 6 of the first byte; the endpoints and p-bits of a flat block decode to its colour at every index)
static void decode6(const uint8_t b[16], uint8_t rgba[4]) {
uint64_t w[2];
std::memcpy(w, b, 16);
auto bits = [&](int pos, int n) -> uint32_t {
uint64_t v = pos < 64 ? (w[0] >> pos) | (pos + n > 64 ? w[1] << (64 - pos) : 0) : w[1] >> (pos - 64);
return (uint32_t)(v & ((1ull << n) - 1));
};
int pos = 7, e[2][4];
for (int c = 0; c < 4; c++) e[0][c] = bits(pos, 7), pos += 7, e[1][c] = bits(pos, 7), pos += 7;
const int p0 = bits(pos, 1), p1 = bits(pos + 1, 1);
pos += 2;
const int idx = bits(pos, 3);
static const int kw[16] = {0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64};
for (int c = 0; c < 4; c++) {
const int a = e[0][c] * 2 + p0, z = e[1][c] * 2 + p1;
rgba[c] = (uint8_t)(((64 - kw[idx]) * a + kw[idx] * z + 32) >> 6);
}
}
int main() {
// sizes and levels
CHECK(tb::level_bytes(4, 4) == 16 && tb::level_bytes(5, 5) == 64 && tb::level_bytes(1, 1) == 16 && tb::level_bytes(2048, 2048) == 4194304);
CHECK(tb::full_levels(2048, 2048) == 12 && tb::full_levels(682, 682) == 10 && tb::full_levels(1, 1) == 1 && tb::full_levels(8, 2) == 4);
CHECK(tb::file_bytes(8, 8, 4) == tb::kHeader + 64 + 16 + 16 + 16);
// the header
uint8_t buf[256] = {};
tb::Header h;
h.w = 8, h.h = 8, h.levels = 4, h.png_size = 123456789012ull;
tb::write_header(buf, h);
tb::Header r;
CHECK(tb::read_header(buf, (size_t)tb::file_bytes(8, 8, 4), &r) && r.w == 8 && r.h == 8 && r.levels == 4 && r.png_size == 123456789012ull);
CHECK(!tb::read_header(buf, (size_t)tb::file_bytes(8, 8, 4) - 1, &r)); // (cut short)
CHECK(!tb::read_header(buf, 10, &r));
h.levels = 5; // (more levels than 8 x 8 has)
tb::write_header(buf, h);
CHECK(!tb::read_header(buf, (size_t)tb::file_bytes(8, 8, 4), &r));
buf[0] ^= 1;
CHECK(!tb::read_header(buf, sizeof buf, &r));
// halving: the mean of 2 x 2, an odd edge's last texel repeated
std::vector<uint8_t> px(3 * 3 * 4);
for (size_t i = 0; i < px.size(); i++) px[i] = (uint8_t)(i * 7);
uint32_t ow = 0, oh = 0;
const auto hv = tb::half(px, 3, 3, &ow, &oh);
CHECK(ow == 1 && oh == 1 && hv.size() == 4);
CHECK(hv[0] == (uint8_t)((0 + 4 * 7 + 12 * 7 + 16 * 7 + 2) / 4));
// the encoder: mode 6, a flat colour kept
std::vector<uint8_t> flat(8 * 8 * 4);
for (size_t i = 0; i < flat.size(); i += 4) flat[i] = 200, flat[i + 1] = 100, flat[i + 2] = 50, flat[i + 3] = 255;
std::vector<uint8_t> out((size_t)tb::level_bytes(8, 8));
tb::encode(flat.data(), 8, 8, out.data());
for (int b = 0; b < 4; b++) {
CHECK(out[b * 16] == 0x40);
uint8_t c[4];
decode6(&out[b * 16], c);
CHECK(std::abs(c[0] - 200) <= 1 && std::abs(c[1] - 100) <= 1 && std::abs(c[2] - 50) <= 1 && c[3] >= 254);
}
// the tiers, by the card's own memory
CHECK(tb::tier_for(12282) == tb::kAll && tb::tier_for(16376) == tb::kAll && tb::tier_for(11000) == tb::kAll);
CHECK(tb::tier_for(10240) == tb::kNoBig && tb::tier_for(8192) == tb::kNoBig && tb::tier_for(6144) == tb::kSmall && tb::tier_for(4096) == tb::kNone);
CHECK(tb::tier_wants(tb::kAll, 1024, 1024) && tb::tier_wants(tb::kNoBig, 512, 1023) && !tb::tier_wants(tb::kNoBig, 1024, 256));
CHECK(tb::tier_wants(tb::kSmall, 511, 256) && !tb::tier_wants(tb::kSmall, 512, 256) && !tb::tier_wants(tb::kNone, 256, 256));
CHECK(tb::tier_env("3") == 3 && tb::tier_env("0") == 0 && tb::tier_env(nullptr) == -1 && tb::tier_env("") == -1 && tb::tier_env("4") == -1 && tb::tier_env("12") == -1);
std::fprintf(stderr, "%s\n", failures ? "failed" : "ok");
return failures ? 1 : 0;
}
'''
def check_source():
tex = (ROOT / "gpu/vk/vk_texture.cpp").read_text(encoding="utf-8")
problems = []
for needle, why in (
('#include "tex_pack_bc7.h"', "vk_texture.cpp does not include the BC7 pack header"),
("if (tex->pack_state == 1 || !texpack::on() || !texpack::ready.load(std::memory_order_acquire)) return VK_NULL_HANDLE;",
"pack_view uses the pack before it is prepared (textures would turn HD one by one)"),
("ci.format = VK_FORMAT_BC7_UNORM_BLOCK;", "the pack's images are not BC7"),
("tb::tier_wants((tb::Tier)tier, fw, fh)", "pack_view does not take the tier"),
("if (now) texpack::prepare_start();", "the prepare does not start when Evil HD is on"),
("tb::tier_for(heap >> 20)", "the tier is not by the card's own memory"),
("? (uint64_t)std::clamp(atoi(getenv(\"RX_VK_TEX_PACK_LINE\")), 20, 98) : 95;", "the emergency line is not 95% by default")):
if needle not in tex:
problems.append(why)
for gone in ("texpack::cap", "kPackBudget", "make_line", "vkCmdBlitImage(cmd, tex->hd"):
if gone in tex:
problems.append("vk_texture.cpp still has the old pack budget or blits: " + gone)
menu = (ROOT / "gpu/vk/vk_menu.cpp").read_text(encoding="utf-8")
if "texpack_prepare_text(t, sizeof t)" not in menu:
problems.append("the menu does not show the prepare's progress")
return problems
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--cxx", default=os.environ.get("CXX", "g++"))
a = p.parse_args()
problems = check_source()
with tempfile.TemporaryDirectory(prefix="tex-pack-bc7-") as tmp:
src, exe = Path(tmp) / "t.cpp", Path(tmp) / "t"
src.write_text(HARNESS, encoding="utf-8")
build = subprocess.run([a.cxx, "-std=c++17", "-O1", "-Wall", "-Wextra", "-Werror", "-I", str(ROOT / "gpu/vk"), str(src), "-o", str(exe)])
if build.returncode:
raise SystemExit("the harness did not compile: see the compiler's output above")
run = subprocess.run([str(exe)], capture_output=True, text=True)
sys.stderr.write(run.stderr)
if run.returncode:
problems.append("the harness failed (above)")
for pr in problems:
print("FAIL: " + pr)
if problems:
return 1
print("PASS: the pack's BC7 files, levels, halving and encoder, and the tiers by the card")
return 0
if __name__ == "__main__":
sys.exit(main())

View File

@@ -1,12 +1,13 @@
"""Threaded rendering (gpu/vk/threaded_rendering.h, vk_main.cpp threaded_choice; no game/GPU).
The rule is compiled from the header and run on made-up PCs: Off (the row's default, 0) and any value that is none of the row's are
The rule is compiled from the header and run on made-up PCs: Off (0) and any value that is none of the row's are
off whatever the CPU; On is both threads whatever the CPU; Auto is both threads from 4 physical cores and off below, off where the
run is not safe, and with no buffer-pool mirrors the recorder thread alone from 6 cores, off below. RX_VK_THREADED's words. The
source: the row is on the Debug tab with Off first, async_on reads the render thread's half only with RX_VK_ASYNC unset, the
recorder's half goes through recorder_auto in pick_device, and the host asks HOS_OPT_RENDER_THREAD only with RX_VK_ASYNC unset.
(11-27) The recorder's hand-off by part is not Threaded rendering's: RX_VK_RECORDER_PARTS=1 alone turns it on (with it the 3D was
drawn with wrong textures on the lab's RX 7900 XT, in v0.8.3 too).
drawn with wrong textures on the lab's RX 7900 XT, in v0.8.3 too). (11-29) The row is Auto (2) by default: a new options
file's, and an older file's (before options_version 11) Off turned into Auto once, at menu_init; the file is written as 11.
python -I -B tests/test_threaded_rendering.py [--cxx clang++]
"""
@@ -69,8 +70,19 @@ def check_source():
menu_h = (ROOT / "gpu/vk/vk_menu.h").read_text(encoding="utf-8")
replay = (ROOT / "gpu/vk/vk_replay.cpp").read_text(encoding="utf-8")
backend = (ROOT / "host/rx_backend.c").read_text(encoding="utf-8")
if "int threaded_rendering = 0;" not in menu_h:
fail("the row's default is no longer Off (0)")
if "int threaded_rendering = 2;" not in menu_h:
fail("the row's default is no longer Auto (2)")
# ((Triforce, 11-29) an older file wrote the old Off default whether chosen or not: its Off becomes Auto once, at the start,
# before threaded_choice reads the row; On or Auto chosen stays, and a file of 11 on keeps what was chosen)
init = menu[menu.index("void menu_init() {"):]
init = init[:init.index("\n}\n")]
if "if (version < 11 && opts.threaded_rendering == 0) opts.threaded_rendering = 2;" not in init:
fail("menu_init no longer turns an older file's Off into Auto")
save = menu[menu.index("void save() {"):]
if 'out += "options_version=11\\n";' not in save[:save.index("\n}\n")]:
fail("save no longer writes options_version=11 (an older file's Off would become Auto at every start)")
if "threaded_choice() {" in menu or "opts.threaded_rendering =" in main:
fail("the row is set somewhere other than menu_init and the menu")
if '{TAB_DEBUG, "Threaded rendering", &opts.threaded_rendering, 0, 2, 1, tx_threaded,' not in menu:
fail("the Threaded rendering row moved or changed")
pick = main[main.index("bool pick_device() {"):main.index("bool create_device() {")]
@@ -85,13 +97,15 @@ def check_source():
fail("async_on no longer reads the row only with RX_VK_ASYNC unset")
rec = (ROOT / "gpu/vk/vk_recorder.h").read_text(encoding="utf-8")
internal = (ROOT / "gpu/vk/vk_internal.h").read_text(encoding="utf-8")
# the design's other pieces: each off unless Threaded rendering (or its own switch) turns it on
# the design's other pieces: each off unless Threaded rendering (or its own switch) turns it on ((Triforce, 11-29) but the
# parts, which NVIDIA's driver has by default too: barrier_rules.h part_pass_end_default, by the device's driver id)
for needle, where in (
('g_parts.store(pe && *pe ? atoi(pe) != 0 : g_parts_default && g_parts_default(), std::memory_order_relaxed);', rec),
("if (!g_parts.load(std::memory_order_relaxed)) return;", rec), # (queue_lock_event: nothing without the hand-off)
("const bool rec_parts_hooks = (::mkwvk::queue_lock_hook = ::mkwvk::rec::queue_lock_event, true);", replay),
("const bool post = rec::parts_wanted() && r.pieces.empty() && !memory_lazy_running();", replay),
('v.on = e && *e ? atoi(e) != 0 : threaded_on() && !getenv("RX_VK_CHUNK");', replay),
("const bool by_default = threaded_on() || barrier_rules::part_pass_end_default((uint32_t)dev.driver_id);", replay),
('v.on = e && *e ? atoi(e) != 0 : by_default && !getenv("RX_VK_CHUNK");', replay),
("const bool v = e && *e ? atoi(e) == 1 : threaded_on();", replay),
("static const bool v = threaded_on();", replay),
("QueueMutex present_mu;", internal)):
@@ -129,8 +143,8 @@ def main():
done = subprocess.run([str(exe)], capture_output=True, text=True, timeout=60, creationflags=flags)
if done.returncode or done.stdout.strip() != "OK":
fail((done.stdout + done.stderr).strip())
print("PASS: Threaded rendering: Off by default and as before, On both threads, Auto by physical cores (the recorder alone "
"without mirrors from 6); the row, the readers and the host's question in place")
print("PASS: Threaded rendering: Auto by default (an older file's Off once), Off as before, On both threads, Auto by physical "
"cores (the recorder alone without mirrors from 6); the row, the readers and the host's question in place")
if __name__ == "__main__":

View File

@@ -20,9 +20,16 @@ This compiles title_tabs.h alone (with game_grid.h) and checks where the tabs la
- the point test: each label's and each icon's middle is its tab, the gap between them and the picture's middle none; with
the save files off there is the one tab, Mods.
And the sources: the tabs are drawn with the game's own icons of what the Switch's X (Mods: the top face button, Y on an Xbox
pad, Triangle on a PlayStation one) and Y (Save Select: the left one, X and Square) are bound to; the pad's own buttons, a
click, or the host's words 6 and 7 (a test's scripted X and Y) choose them; the entry under the title's list is Quit Game.
And the sources: the tabs' prompts name the pad input the Switch's X (Mods: the top face button, Y on an Xbox pad, Triangle
on a PlayStation one) and Y (Save Select: the left one, X and Square) are bound to, as the button test reads it; the pad's
own buttons, a click, or the host's words 6 and 7 (a test's scripted X and Y) choose them; the entry under the title's list
is Quit Game.
((Triforce, 11-30) two players on an Xbox and a PlayStation controller: "The X is supposed to open up the Mod Menu but instead
it is opening up the save selection". The prompt was the Switch button's own code, right only in a font pointed at this run's
controls: in the game's own font, or on a cap without one, the Switch's letter, the other button's name on those pads. Now
the icon of the bound input itself on the face shown (title_tabs.h icon_codes, the font's codes as host/prompts.c and
nx2/prompt_assets.py number them), or that input's name: checked for every face and the layout presets.)
python -I -B tests/test_title_tabs.py [--cxx clang++]
"""
@@ -57,6 +64,7 @@ PROGRAM = r"""
#include <cmath>
#include <cstdio>
#include <cstdint>
#include <string>
#include "title_tabs.h"
using namespace mkwvk;
static int fails;
@@ -121,7 +129,42 @@ static void one(const Case& c) {
unit, m.kx, m.x(l.tab[0].x0), m.x(l.tab[0].x1), m.x(l.tab[1].x0), m.x(l.tab[1].x1), m.y(l.tab[1].y1), px0, py0);
}
// ((Triforce, 11-30) the prompts: each tab's the icon of the pad input its button is bound to, on the face shown. The faces and
// the inputs as gpu/vk/vk_api.h numbers them (HOS_PROMPT_SWITCH .. HOS_PROMPT_STEAMDECK the controllers'; HOS_PAD_SOUTH,
// EAST, WEST, NORTH first), and the layout presets as vk_menu.cpp apply_pad_layout binds the Switch's X and Y
static void prompts_check() {
const char* name = "prompts";
enum { SOUTH, EAST, WEST, NORTH, PADS = 17, FACES = 5, KEYBOARD = 5 };
struct Preset { const char* name; int x, y; } presets[] = {{"Nintendo (Def)", NORTH, WEST}, {"Xbox / PC", WEST, NORTH}, {"Swap Face", NORTH, WEST}};
for (const Preset& p : presets)
for (int face = 0; face < FACES; face++) {
unsigned mods[2], saves[2];
title_tabs::icon_codes(face, p.x, FACES, PADS, mods);
title_tabs::icon_codes(face, p.y, FACES, PADS, saves);
// (the icon is the face's own of the very input menu_tick opens the tab with, never the Switch's X or Y code)
CHECK(mods[0] == 0xF800u + 32u * (unsigned)face + (unsigned)p.x && saves[0] == 0xF800u + 32u * (unsigned)face + (unsigned)p.y);
CHECK(mods[1] == 0xF700u + (unsigned)p.x && saves[1] == 0xF700u + (unsigned)p.y);
CHECK(mods[0] != saves[0] && mods[0] != 0xE042u && saves[0] != 0xE043u);
}
// (the default controls on an Xbox pad: Mods the Y button's icon (the top one); on a PlayStation 5 one Save Select
// Square's (the left one), as the owner asked)
unsigned c[2];
title_tabs::icon_codes(1, NORTH, FACES, PADS, c);
CHECK(c[0] == 0xF800u + 32u + 3u);
title_tabs::icon_codes(3, WEST, FACES, PADS, c);
CHECK(c[0] == 0xF800u + 96u + 2u);
// (no face known, the keys' face, an unbound button, a paddle past the inputs with icons: no code, the input's name instead)
for (int face : {-1, (int)KEYBOARD, 9}) { title_tabs::icon_codes(face, NORTH, FACES, PADS, c); CHECK(c[0] == 0 && c[1] == 0); }
for (int input : {-1, (int)PADS, 21}) { title_tabs::icon_codes(1, input, FACES, PADS, c); CHECK(c[0] == 0 && c[1] == 0); }
// (UTF-8, as ImGui reads it)
char u[4];
CHECK(std::string(title_tabs::utf8(0xF823, u)) == "\xEF\xA0\xA3" && std::string(title_tabs::utf8(0xE042, u)) == "\xEE\x81\x82");
CHECK(std::string(title_tabs::utf8('X', u)) == "X" && std::string(title_tabs::utf8(0xE9, u)) == "\xC3\xA9");
CHECK(!title_tabs::utf8(0, u)[0] && !title_tabs::utf8(0x1F600, u)[0]);
}
int main() {
prompts_check();
static const Case cases[] = {
{"16:9 1920x1080", 1920, 1080, 1920, 1080, 0},
{"16:9 1280x720", 1280, 720, 1280, 720, 0},
@@ -168,11 +211,36 @@ def main():
and "const game_grid::Map m = game_grid::map_of(title_grid);" in tabs,
"the tabs are not placed from the picture's top left corner on the game's grid")
check('static const char* const labels[title_tabs::kTabs] = {"Mods", "Save Select"};' in tabs
and "static const char* const icons[title_tabs::kTabs] = {ui::kIconX, ui::kIconY};" in tabs,
and "static const int buttons[title_tabs::kTabs] = {HOS_SW_X, HOS_SW_Y};" in tabs,
"Mods is not the Switch's X (the top face button) and Save Select its Y (the left one)")
check("const bool pad = game_prompts_pad();" in tabs and "if (!pad || show <= 0) continue;" in tabs
check("const bool pad = game_prompts_pad();" in tabs and "if (!pad || !bound[i] || show <= 0) continue;" in tabs
and "c.d->AddText(c.f.glyph, ipx, at, ui::alpha(ui::kInk, show), icons[i]);" in tabs,
"the prompts under the tabs are not the game's icons, shown with a controller and fading with the list")
# ((Triforce, 11-30) the prompt is the bound input's own, as the button test reads it: its icon on the face shown, else its
# name; never the Switch button's own code (U+E042, U+E043: the Switch's letter in the game's own font) nor its letter)
check("const int input = host && host->binding ? host->binding(HOS_BIND_PAD, buttons[i], 0) : -1;" in tabs
and "bound[i] = hos_pad_bindable(input);" in tabs
and "title_tabs::icon_codes(face, input, HOS_PROMPT_KEYBOARD, HOS_PAD_N, codes);" in tabs
and "c.f.glyph->IsGlyphInFont((ImWchar)code)) title_tabs::utf8(code, icons[i]);" in tabs
and "names[i] = pad_name(input);" in tabs
and "const int face = host && host->prompt_face ? host->prompt_face() : -1;" in tabs,
"a tab's prompt is not the icon (or the name) of the pad input its button is bound to")
check("kIconX" not in tabs and "kIconY" not in tabs and '{"X", "Y"}' not in tabs,
"a tab's prompt is still the Switch button's own icon or letter: the other button's on an Xbox or PlayStation pad")
check('const ui::Prompt p{ui::kKey, "", names[i]};' in tabs and "if (icons[i][0]) {" in tabs,
"without the input's icon in the font the prompt is not its name on a key's cap")
# (the codes as the host and the font builder number them)
prompts = (ROOT / "host" / "prompts.c").read_text(encoding="utf-8")
assets = (ROOT / "nx2" / "prompt_assets.py").read_text(encoding="utf-8")
check("#define FACE_BASE 0xF800" in prompts and "#define FACE_CODES 32" in prompts and "#define PAD_BASE 0xF700" in prompts
and "#define LIVE_FACES HOS_PROMPT_KEYBOARD" in prompts
and "\nFACE_BASE = 0xF800" in assets and "\nFACE_CODES = 32" in assets and "\nPAD_BASE = 0xF700" in assets
and "constexpr unsigned kPadBase = 0xF700;" in header and "constexpr unsigned kFaceBase = 0xF800, kFaceCodes = 32;" in header,
"title_tabs.h's icon codes are not host/prompts.c's and nx2/prompt_assets.py's")
check('PADS = ["south", "east", "west", "north",' in assets, "the font's pad inputs are not in HOS_PAD_* order")
check(all(l in menu for l in ("host->bind(HOS_BIND_PAD, HOS_SW_X, 0, HOS_PAD_NORTH);", "host->bind(HOS_BIND_PAD, HOS_SW_X, 0, HOS_PAD_WEST);",
"host->bind(HOS_BIND_PAD, HOS_SW_Y, 0, HOS_PAD_WEST);", "host->bind(HOS_BIND_PAD, HOS_SW_Y, 0, HOS_PAD_NORTH);")),
"the layout presets the prompts are checked with are not apply_pad_layout's")
check("title_tab_layout = l, title_tab_map = m, title_tab_ns = prof_now();" in tabs, "where the tabs were drawn is not kept for the mouse")
# ((Triforce) the lab's first run: on the owner's 21:9 picture the corner is left of the column, and nothing was drawn)
check(tabs.index("title_tabs::picture_clip(title_grid, m,") < tabs.index("c.d->PushClipRect(ImVec2(clip[0], clip[1]), ImVec2(clip[2], clip[3]), false);")

View File

@@ -3,7 +3,8 @@
vendor_fixes() is compiled with the Vulkan headers and run on the properties of GPUs players have: NVIDIA's driver on
Windows and Linux (and NVK on the same cards), AMD's Windows driver in its two branches (RDNA 1/2: "AMD proprietary
shader compiler"; RDNA 3/4: LLPC), RADV, AMDVLK, Intel's Windows driver on an integrated GPU and on an Arc card, ANV,
llvmpipe. Each fix must be on for the GPUs it is for and off for every other, and NVIDIA's driver must get none: that is
llvmpipe. Each fix must be on for the GPUs it is for and off for every other (robust buffer access: Intel's Windows driver alone,
11-30), and NVIDIA's driver must get none: that is
what keeps the renderer and the translated shaders on NVIDIA as they were. The RX_VK_ switches force each one either way.
Then the source: the device's fixes are made from its properties at device creation, and the translator is told
fetch_bounds, nan_bits and the gather offset (and the program cache's stamp tells the three apart).
@@ -20,29 +21,31 @@ RUN_ALL_ARGS = ["--cxx", "{cxx}", "--headers", "{vulkan_headers}"]
ROOT = Path(__file__).resolve().parents[1]
VK = ROOT / "gpu" / "vk"
# name, vendor, driver id, device type, driverInfo -> fetch_bounds, nan_bits, gather_offset
# name, vendor, driver id, device type, driverInfo -> fetch_bounds, nan_bits, gather_offset, robust_buffers
DEVICES = [
("RTX 3090, NVIDIA's Linux driver", 0x10DE, "NVIDIA_PROPRIETARY", "DISCRETE_GPU", "580.105.08", "000"),
("RTX 4070 laptop, NVIDIA's Windows driver", 0x10DE, "NVIDIA_PROPRIETARY", "DISCRETE_GPU", "581.57", "000"),
("GTX 1650, NVK", 0x10DE, "MESA_NVK", "DISCRETE_GPU", "Mesa 26.0.1", "000"),
("RTX 3090, NVIDIA's Linux driver", 0x10DE, "NVIDIA_PROPRIETARY", "DISCRETE_GPU", "580.105.08", "0000"),
("RTX 4070 laptop, NVIDIA's Windows driver", 0x10DE, "NVIDIA_PROPRIETARY", "DISCRETE_GPU", "581.57", "0000"),
("GTX 1650, NVK", 0x10DE, "MESA_NVK", "DISCRETE_GPU", "Mesa 26.0.1", "0000"),
("RX 6700 XT, AMD's Windows driver (RDNA 2 branch)", 0x1002, "AMD_PROPRIETARY", "DISCRETE_GPU",
"26.10.1 (AMD proprietary shader compiler)", "111"),
"26.10.1 (AMD proprietary shader compiler)", "1110"),
("RX 5700, AMD's Windows driver (RDNA 1 branch)", 0x1002, "AMD_PROPRIETARY", "DISCRETE_GPU",
"25.9.1 (AMD proprietary shader compiler)", "111"),
("RX 9070 XT, AMD's Windows driver (LLPC)", 0x1002, "AMD_PROPRIETARY", "DISCRETE_GPU", "26.10.1 (LLPC)", "101"),
("RX 7600, AMD's Windows driver, no driverInfo", 0x1002, "AMD_PROPRIETARY", "DISCRETE_GPU", "", "101"),
"25.9.1 (AMD proprietary shader compiler)", "1110"),
("RX 9070 XT, AMD's Windows driver (LLPC)", 0x1002, "AMD_PROPRIETARY", "DISCRETE_GPU", "26.10.1 (LLPC)", "1010"),
("RX 7600, AMD's Windows driver, no driverInfo", 0x1002, "AMD_PROPRIETARY", "DISCRETE_GPU", "", "1010"),
("AMD's driver naming another shader compiler", 0x1002, "AMD_PROPRIETARY", "DISCRETE_GPU", "26.10.1 (LLPC shader compiler)",
"101"),
("RX 580, RADV", 0x1002, "MESA_RADV", "DISCRETE_GPU", "Mesa 26.2.5", "101"),
("Steam Deck, RADV", 0x1002, "MESA_RADV", "INTEGRATED_GPU", "Mesa 25.1.0", "101"),
("RX 6800, AMDVLK", 0x1002, "AMD_OPEN_SOURCE", "DISCRETE_GPU", "2025.Q2.1 (LLPC)", "101"),
("UHD Graphics, Intel's Windows driver", 0x8086, "INTEL_PROPRIETARY_WINDOWS", "INTEGRATED_GPU", "101.7088", "101"),
("Iris Xe, Intel's Windows driver", 0x8086, "INTEL_PROPRIETARY_WINDOWS", "INTEGRATED_GPU", "101.7092", "101"),
("Arc B580, Intel's Windows driver", 0x8086, "INTEL_PROPRIETARY_WINDOWS", "DISCRETE_GPU", "101.8132", "101"),
("Iris Xe, ANV", 0x8086, "INTEL_OPEN_SOURCE_MESA", "INTEGRATED_GPU", "Mesa 26.0.1", "101"),
("llvmpipe", 0x10005, "MESA_LLVMPIPE", "CPU", "Mesa 26.0.1 (LLVM 20.1.8)", "100"),
"1010"),
("RX 580, RADV", 0x1002, "MESA_RADV", "DISCRETE_GPU", "Mesa 26.2.5", "1010"),
("Steam Deck, RADV", 0x1002, "MESA_RADV", "INTEGRATED_GPU", "Mesa 25.1.0", "1010"),
("RX 6800, AMDVLK", 0x1002, "AMD_OPEN_SOURCE", "DISCRETE_GPU", "2025.Q2.1 (LLPC)", "1010"),
("UHD Graphics, Intel's Windows driver", 0x8086, "INTEL_PROPRIETARY_WINDOWS", "INTEGRATED_GPU", "101.7088", "1011"),
("Iris Xe, Intel's Windows driver", 0x8086, "INTEL_PROPRIETARY_WINDOWS", "INTEGRATED_GPU", "101.7092", "1011"),
("Arc B580, Intel's Windows driver", 0x8086, "INTEL_PROPRIETARY_WINDOWS", "DISCRETE_GPU", "101.8132", "1011"),
("Arc B570, Intel's Windows driver (the file select's lost device, 11-30)", 0x8086, "INTEL_PROPRIETARY_WINDOWS",
"DISCRETE_GPU", "101.9175", "1011"),
("Iris Xe, ANV", 0x8086, "INTEL_OPEN_SOURCE_MESA", "INTEGRATED_GPU", "Mesa 26.0.1", "1010"),
("llvmpipe", 0x10005, "MESA_LLVMPIPE", "CPU", "Mesa 26.0.1 (LLVM 20.1.8)", "1000"),
]
FIELDS = ['fetch_bounds', 'nan_bits', 'gather_offset']
FIELDS = ['fetch_bounds', 'nan_bits', 'gather_offset', 'robust_buffers']
FIXTURE = r"""
#include <cstdio>
@@ -57,7 +60,7 @@ static const char* get(const char* name) {
return it == env.end() ? nullptr : it->second.c_str();
}
static void print(const char* what, const VendorFixes& x) {
std::printf("%s %d%d%d\n", what, x.fetch_bounds, x.nan_bits, x.gather_offset);
std::printf("%s %d%d%d%d\n", what, x.fetch_bounds, x.nan_bits, x.gather_offset, x.robust_buffers);
}
int main() {
struct D { const char* name; uint32_t vendor; VkDriverId driver; VkPhysicalDeviceType type; const char* info; };
@@ -71,7 +74,7 @@ int main() {
print(d.name, x);
vendor_fixes_env(x, get); // (no switch set: as it was)
print(d.name, x);
const char* names[] = {"RX_VK_FETCH_BOUNDS", "RX_VK_NAN_BITS", "RX_VK_GATHER_OFFSET"};
const char* names[] = {"RX_VK_FETCH_BOUNDS", "RX_VK_NAN_BITS", "RX_VK_GATHER_OFFSET", "RX_VK_ROBUST"};
for (const char* n : names)
for (const char* v : {"0", "1", ""}) {
env.clear();
@@ -101,9 +104,16 @@ def cut(text, marker):
def check_source():
main = (VK / "vk_main.cpp").read_text(encoding="utf-8")
at = main.index("dev.fixes = vendor_fixes(facts);")
for text in ("vendor_fixes_env(dev.fixes,",):
for text in ("vendor_fixes_env(dev.fixes,", "robust = robust || dev.fixes.robust_buffers;",
"robust2.robustBufferAccess2 = robust_ok ? VK_TRUE : VK_FALSE;"):
if main.find(text, at) < 0:
raise SystemExit("FAIL: vk_main.cpp: %s not after the fixes are made" % text)
# ((Triforce, 11-30) the Intel fix decides the device's robustness: robust_ok made once, after it, and the features from it
# before the device)
if main.count("robust_ok = robust &&") != 1 or main.find("robust_ok = robust &&") < at:
raise SystemExit("FAIL: vk_main.cpp: robust_ok is made before the vendor fixes")
if "f.features.robustBufferAccess = robust_ok ? VK_TRUE : VK_FALSE;" not in main[at:main.index("vkCreateDevice(dev.physical, &ci")]:
raise SystemExit("FAIL: vk_main.cpp: robustBufferAccess not set from robust_ok before the device")
if main.index("dev.fixes = vendor_fixes(facts);") > main.index("vkCreateDevice(dev.physical, &ci"):
raise SystemExit("FAIL: the fixes are made after the device")
for field in ("vendor_id = p2.properties.vendorID", "driver_id = drv.driverID", "device_type = p2.properties.deviceType",
@@ -153,7 +163,7 @@ def main():
if line.split()[-1] != want:
failures.append("%s: %s, expected %s" % (name, line.split()[-1], want))
for i, line in enumerate(lines[2:]):
switch, value = ["RX_VK_FETCH_BOUNDS", "RX_VK_NAN_BITS", "RX_VK_GATHER_OFFSET"][i // 3], ["0", "1", ""][i % 3]
switch, value = ["RX_VK_FETCH_BOUNDS", "RX_VK_NAN_BITS", "RX_VK_GATHER_OFFSET", "RX_VK_ROBUST"][i // 3], ["0", "1", ""][i % 3]
got = list(line.split()[-1])
expect = list(want)
if value: