Triforce v0.8.5

A Randomizer page in the launcher, a new title screen with Mods and Save Select tabs, scaling changes applied in game, the Jabu-Jabu bars fixed, renderer frame-time work and the brightness-flash fix, and fixes from the 0.8.4 reports.
This commit is contained in:
ruckus7382sfgsgdf
2026-11-28 10:54:41 -06:00
parent 2df08c751e
commit b527e29adb
203 changed files with 18821 additions and 2051 deletions

View File

@@ -19,6 +19,7 @@
#include <tuple>
#include <unordered_map>
#include <vector>
#include "tpltable.h" // ((Triforce, 11-26, C31) the templates' per-thread table, as vk_draw.cpp includes it)
#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); std::exit(1); } } while (0)
@@ -27,9 +28,16 @@ std::string test;
const char* getenv(const char* name) {
if (!std::strcmp(name, "RX_VK_DESC_SET_KEEP") && test == "keep-off") return "0";
if (!std::strcmp(name, "RX_VK_DESC_TEMPLATE") && (test == "template-off" || test == "push-template-off")) return "0";
if (!std::strcmp(name, "RX_VK_TPL_TABLE") && (test == "tpl-table-off" || test == "push-template-old")) return "0";
if (!std::strcmp(name, "RX_VK_TPL_TABLE") && test == "tpl-table-check") return "2";
return nullptr;
}
void logf(const char*, ...) {}
namespace tpltable = ::mkwvk::tpltable;
std::string lab_knob; // ((Triforce, 11-26, C31) the lab's knob on in this phase: none
namespace lab_ab {
bool on(const char* name) { return lab_knob == name; }
} // namespace lab_ab
#define TLS_OBJECT(name, ...) inline __VA_ARGS__& name() { static thread_local __VA_ARGS__ v; return v; }
template <class T> T handle(uintptr_t v) { return reinterpret_cast<T>(v); }
@@ -358,6 +366,15 @@ int run() {
CHECK(pushes == 0 && st_push_tpl.load() == 5);
return 0;
}
if (test == "push-template-old") { // ((Triforce, 11-26, C31) RX_VK_TPL_TABLE=0: the 8 entries, their layout check on what they find)
prog.push = true;
CHECK(bind_descriptors(cmd, G, prog) && tpl_pushes == 1 && tpl_made == 1 && held(cmd, 0) == expected());
CHECK(bind_descriptors(cmd2, G, prog) && tpl_pushes == 2 && tpl_made == 1 && held(cmd2, 0) == expected()); // (found in the 8)
prog.layout = handle<VkPipelineLayout>(0x120); // (the program's layout made again: found, not its layout, so a new template)
CHECK(bind_descriptors(cmd, G, prog) && tpl_pushes == 3 && tpl_made == 2 && tpls_made.rbegin()->second.pipe_layout == prog.layout);
CHECK(st_tpl_locked.load() == 2 && st_tpl_fast.load() == 1 && pushes == 0);
return 0;
}
if (test == "push-template-off") { // (RX_VK_DESC_TEMPLATE=0: the write structs, as before)
prog.push = true;
CHECK(bind_descriptors(cmd, G, prog) && pushes == 1 && tpl_pushes == 0 && tpl_made == 0 && held(cmd, 0) == expected());
@@ -382,6 +399,68 @@ int run() {
CHECK(bind_descriptors(cmd2, G, other) && pushes == 3 && tpl_tries == 2); // (not tried again at every push)
return 0;
}
if (test == "tpl-table" || test == "tpl-table-off" || test == "tpl-table-check") {
// ((Triforce, 11-26, C31; tpltable.h) 40 programs' whole pushes in turn, three times: each program's template is made once
// and found in the thread's table from then on, tpl_mu taken once a program; by the 8 entries before, at most lookups)
static Program many[40];
for (int i = 0; i < 40; i++)
many[i].key = 0x7000 + i, many[i].push = true, many[i].layout = handle<VkPipelineLayout>(0x1000 + i),
many[i].set_layout = handle<VkDescriptorSetLayout>(0x2000 + i);
for (int round = 0; round < 3; round++)
for (int i = 0; i < 40; i++) {
bufs[0].offset = 64 * (round * 40 + i);
CHECK(bind_descriptors(cmd, G, many[i]) && held(cmd, 0) == expected());
CHECK(tpls_made.at(handle<VkDescriptorUpdateTemplate>(0x5000 + i + 1)).pipe_layout == many[i].layout);
}
CHECK(tpl_pushes == 120 && tpl_made == 40 && pushes == 0); // (each through its own template, whichever table)
CHECK(st_tpl_fast.load() + st_tpl_locked.load() == 120);
if (test == "tpl-table-off") { // (RX_VK_TPL_TABLE=0: the 8 entries, as before)
CHECK(st_tpl_locked.load() > 80 && st_tpl_checked.load() == 0);
return 0;
}
CHECK(st_tpl_locked.load() == 40 && st_tpl_fast.load() == 80);
CHECK(st_tpl_checked.load() == (test == "tpl-table-check" ? 80 : 0) && st_tpl_bad.load() == 0); // (=2: each find is the map's)
many[3].layout = handle<VkPipelineLayout>(0x1F00); // (a layout made again: found, not its layout, so the lock and a new template)
CHECK(bind_descriptors(cmd, G, many[3]) && tpl_made == 41 && st_tpl_locked.load() == 41);
CHECK(tpls_made.rbegin()->second.pipe_layout == many[3].layout);
CHECK(bind_descriptors(cmd, G, many[4]) && bind_descriptors(cmd, G, many[3]) && tpl_made == 41 && st_tpl_locked.load() == 41);
CHECK(st_tpl_bad.load() == 0);
lab_knob = "notpltable"; // (the lab's phase: the 8 entries, the same templates)
for (int i = 0; i < 40; i++) CHECK(bind_descriptors(cmd, G, many[i]) && held(cmd, 0) == expected());
CHECK(st_tpl_locked.load() > 41 + 20 && tpl_made == 41);
lab_knob.clear(); // (and back: the table still holds them)
const int64_t locked = st_tpl_locked.load();
for (int i = 0; i < 40; i++) CHECK(bind_descriptors(cmd, G, many[i]) && held(cmd, 0) == expected());
CHECK(st_tpl_locked.load() == locked && tpl_made == 41 && pushes == 0);
// (a program over the push limit: its set template is found the same way, and used only while its set layout is the program's)
Program over;
over.key = 0x7100, over.layout = handle<VkPipelineLayout>(0x1100), over.set_layout = handle<VkDescriptorSetLayout>(0x2100);
bufs[0].offset = 0x8000;
bind(G, cmd, over);
CHECK(tpl_made == 42 && st_tpl_locked.load() == locked + 1 && tpls_made.rbegin()->second.layout == over.set_layout);
bufs[0].offset = 0x8040; // (other descriptors: a new set, written through the template the table finds)
bind(G, cmd, over);
CHECK(tpl_made == 42 && st_tpl_locked.load() == locked + 1 && tpl_updates == 2);
over.set_layout = handle<VkDescriptorSetLayout>(0x2180); // (its set layout made again: found, not its layout, so the lock and a new template)
bufs[0].offset = 0x8080;
bind(G, cmd, over);
CHECK(tpl_made == 43 && st_tpl_locked.load() == locked + 2 && tpls_made.rbegin()->second.layout == over.set_layout);
CHECK(st_tpl_bad.load() == 0);
if (test == "tpl-table-check") { // (an entry that is not the map's, put in the thread's table: the check counts it)
const SetTemplate* real = nullptr;
{
std::lock_guard lk(tpl_mu);
real = push_tpls[0].at(&many[5]).get();
}
static SetTemplate planted;
planted = *real; // (the same template and layouts, at another address: not what the map holds)
tpl_wide().put(tpltable::key_of(&many[5], tpltable::kPushGraphics), &planted);
bufs[0].offset = 0x9000;
CHECK(bind_descriptors(cmd, G, many[5]) && held(cmd, 0) == expected());
CHECK(st_tpl_bad.load() == 1);
}
return 0;
}
std::fprintf(stderr, "no case %s\n", test.c_str());
return 2;
}

View File

@@ -44,10 +44,13 @@ static int rx_option(int id, int otherwise) {
}
static void ask(int id) { asked[nasked++] = id; }
/* (the game's files: what the test put there) */
static struct { const char *rel; const uint8_t *data; uint64_t size; } rom[16];
static int nrom, rom_reads;
static struct { const char *rel; const uint8_t *data; uint64_t size; } rom[32];
static int nrom, rom_reads, rom_odd;
static uint8_t *hos_fs_rom_file(const char *rel, uint64_t most, uint64_t *size) {
rom_reads++;
/* ((Triforce, 11-25) every file asked for is a .bwav of the sounds' folder itself, the environment's too) */
const size_t len = strlen(rel);
rom_odd += strncmp(rel, "Sound/Resource/Stream/", 22) || strpbrk(rel + 22, "/\\:.") != rel + len - 5 || strcmp(rel + len - 5, ".bwav");
for (int i = 0; i < nrom; i++)
if (!strcmp(rom[i].rel, rel) && rom[i].size && rom[i].size <= most) {
uint8_t *copy = (uint8_t *)malloc((size_t)rom[i].size);
@@ -59,6 +62,17 @@ static uint8_t *hos_fs_rom_file(const char *rel, uint64_t most, uint64_t *size)
}
static int load_requests;
static void load_start(void) { load_requests++; } /* (the test reads the files when it says: load_all) */
/* ((Triforce, 11-25) the environment, as the roles' sounds read it: what the test put there) */
static struct { const char *name, *value; } env[16];
static int nenv, env_reads;
static const char *test_env(const char *name) {
env_reads++;
for (int i = 0; i < nenv; i++)
if (!strcmp(env[i].name, name)) return env[i].value;
return NULL;
}
static void put_env(const char *name, const char *value) { env[nenv].name = name, env[nenv].value = value, nenv++; }
#define MENU_SOUND_ENV(name) test_env(name)
static void (*between)(int at);
#define MENU_SOUND_BETWEEN(at) do { if (between) between(at); } while (0)
@@ -421,7 +435,11 @@ static void decode_refusals(void) {
/* ---- the voices and the mix, on sounds put there as they would be after the files are read ---- */
enum { OPEN = HOS_MENU_SOUND_OPEN, CLOSE = HOS_MENU_SOUND_CLOSE, CURSOR = HOS_MENU_SOUND_CURSOR, DECIDE = HOS_MENU_SOUND_DECIDE,
CANCEL = HOS_MENU_SOUND_CANCEL, TAB_LEFT = HOS_MENU_SOUND_TAB_LEFT, TAB_RIGHT = HOS_MENU_SOUND_TAB_RIGHT, FANFARE = HOS_MENU_SOUND_FANFARE,
SYS_CURSOR = HOS_MENU_SOUND_SYS_CURSOR, SYS_DECIDE = HOS_MENU_SOUND_SYS_DECIDE };
SYS_CURSOR = HOS_MENU_SOUND_SYS_CURSOR, SYS_DECIDE = HOS_MENU_SOUND_SYS_DECIDE,
/* ((Triforce, 11-25) whose sound: the settings' tabs', the Mods screen's, the step back to the pause menu's list) */
S_NAV = HOS_MENU_SOUND_SETTINGS_NAVIGATE, S_SEL = HOS_MENU_SOUND_SETTINGS_SELECT, S_BACK = HOS_MENU_SOUND_SETTINGS_BACK,
M_NAV = HOS_MENU_SOUND_MODS_NAVIGATE, M_SEL = HOS_MENU_SOUND_MODS_SELECT, M_BACK = HOS_MENU_SOUND_MODS_BACK,
P_BACK = HOS_MENU_SOUND_PAUSE_BACK, S_ON = HOS_MENU_SOUND_SETTINGS_ON, S_OFF = HOS_MENU_SOUND_SETTINGS_OFF };
#define BLOCK 240
static float bl[BLOCK], br[BLOCK];
static void install(int id, uint32_t frames, float l, float r) { /* (its samples end where nothing can be read) */
@@ -480,7 +498,8 @@ static void voices_and_mix(void) {
hos_menu_sound_play(TAB_LEFT, t0);
CHECK(active() == 0);
}
{ /* a sound is added to what the block holds, at the gain, left and right; the cursor's tick at 0.6 of it */
{ /* a sound is added to what the block holds, at the gain, left and right; ((Triforce, 11-26) the cursor's tick too,
at the whole level, as the game's own cursor sound (it was at 0.6 of it, under the others)) */
hos_menu_sound_play(OPEN, t0);
CHECK(active() == 1 && voice_with(OPEN) == 0);
block(0.8f, 0.1f, -0.1f);
@@ -489,9 +508,9 @@ static void voices_and_mix(void) {
block(0.0f, 0.1f, -0.1f); /* at gain 0 nothing is added, and the sound goes on */
CHECK(block_is(0, BLOCK, 0.1f, -0.1f) && voice_pos(0) == 2 * BLOCK);
quiet();
hos_menu_sound_play(CURSOR, t0 + 500 * kMs); /* (not within 180 ms of the sound before: see below) */
hos_menu_sound_play(CURSOR, t0 + 500 * kMs); /* (not within 45 ms of the sound before: see below) */
block(0.5f, 0.0f, 0.0f);
CHECK(block_is(0, BLOCK, 0.5f * 0.5f * 0.6f, 0.5f * 0.5f * 0.6f));
CHECK(block_is(0, BLOCK, 0.5f * 0.5f, 0.5f * 0.5f));
quiet();
}
{ /* a free voice each, while there is one; then the oldest's */
@@ -539,30 +558,42 @@ static void voices_and_mix(void) {
CHECK(active() == 2);
quiet();
}
{ /* the cursor's tick: not within 180 ms of the sound before it, whatever that was; a decision within 50 ms of a
tick takes the tick's voice */
{ /* ((Triforce, 11-26) the cursor's tick: each move's starts with it and the one before rings on beside it, as the game's
own cursor sound (the owner's clip); an ask within NAV_GAP_NS of the sound before is left out (one press asking
twice). A decision within 50 ms of a tick takes the tick's voice; later, a voice of its own, the tick ringing on */
hos_menu_sound_play(CURSOR, t0 + 1000 * kMs);
CHECK(active() == 1 && voice_with(CURSOR) == 0);
block(1.0f, 0.0f, 0.0f);
hos_menu_sound_play(CURSOR, t0 + 1100 * kMs);
hos_menu_sound_play(CURSOR, t0 + 1179 * kMs);
CHECK(active() == 1 && voice_pos(0) == BLOCK);
hos_menu_sound_play(DECIDE, t0 + 1179 * kMs);
CHECK(active() == 1 && voice_with(DECIDE) == 0 && voice_with(CURSOR) < 0 && voice_pos(0) == 0);
hos_menu_sound_play(CURSOR, t0 + 1300 * kMs); /* (121 ms after the decision) */
CHECK(voice_with(CURSOR) < 0);
hos_menu_sound_play(CURSOR, t0 + 1359 * kMs);
CHECK(voice_with(CURSOR) >= 0);
CHECK(active() == 2 && voice_pos(0) == BLOCK && voice_pos(1) == 0);
hos_menu_sound_play(CURSOR, t0 + 1144 * kMs); /* (44 ms on: the same press's) */
CHECK(active() == 2 && voice_pos(1) == 0);
block(1.0f, 0.0f, 0.0f);
CHECK(block_is(0, BLOCK, 1.0f, 1.0f)); /* (both whole, each at the whole level) */
for (int k = 0; k < 4; k++) block(1.0f, 0.0f, 0.0f);
CHECK(active() == 2 && voice_pos(0) == 6 * BLOCK && voice_pos(1) == 5 * BLOCK); /* (neither cut) */
hos_menu_sound_play(DECIDE, t0 + 1149 * kMs); /* (the first tick 1440 frames in, under 50 ms: the same press's voice) */
CHECK(active() == 2 && voice_with(DECIDE) == 0 && voice_pos(0) == 0 && voice_with(CURSOR) == 1);
hos_menu_sound_play(CURSOR, t0 + 1190 * kMs); /* (41 ms after the decision: left out) */
CHECK(active() == 2);
hos_menu_sound_play(CURSOR, t0 + 1194 * kMs);
CHECK(active() == 3 && voice_pos(2) == 0 && voice_with(DECIDE) == 0); /* (beside the decision, which is not cut) */
quiet();
hos_menu_sound_play(CURSOR, t0 + 3000 * kMs);
hos_menu_sound_play(DECIDE, t0 + 3001 * kMs); /* (the same press's: the tick's voice) */
CHECK(active() == 1 && voice_with(DECIDE) == 0 && voice_with(CURSOR) < 0);
quiet();
hos_menu_sound_play(CURSOR, t0 + 4000 * kMs);
for (int k = 0; k < 10; k++) block(1.0f, 0.0f, 0.0f); /* (50 ms on) */
hos_menu_sound_play(DECIDE, t0 + 3050 * kMs);
hos_menu_sound_play(DECIDE, t0 + 4050 * kMs);
CHECK(active() == 2 && voice_with(CURSOR) == 0 && voice_with(DECIDE) == 1);
block(1.0f, 0.0f, 0.0f), block(1.0f, 0.0f, 0.0f);
CHECK(voice_with(CURSOR) == 0 && voice_pos(0) == 12 * BLOCK); /* (the tick rings on under the decision) */
quiet();
}
{ /* ((Triforce, 11-19) the system menu's: the mouse onto Mods or Quit and its click in one tick, or a stick's flick and
A, is their decide alone, as the options' tick and decision; 50 ms on they both play. Its ticks are not thinned
out by the 180 ms gap, as the game's System list does not thin out its own) */
A, is their decide alone, as the options' tick and decision. ((11-26) Its cursor is a navigation sound as the
ticks are: the next move's plays beside it, and so does a decision 50 ms on) */
install(SYS_CURSOR, 30000, 0.5f, 0.5f), install(SYS_DECIDE, 100, 1.0f, -1.0f);
t0 += 10000 * kMs;
hos_menu_sound_play(SYS_CURSOR, t0);
@@ -570,14 +601,71 @@ static void voices_and_mix(void) {
CHECK(active() == 1 && voice_with(SYS_DECIDE) == 0 && voice_with(SYS_CURSOR) < 0 && voice_pos(0) == 0);
quiet();
hos_menu_sound_play(SYS_CURSOR, t0 + 1000 * kMs);
hos_menu_sound_play(SYS_CURSOR, t0 + 1100 * kMs); /* (100 ms on: heard, restarted) */
CHECK(active() == 1 && voice_with(SYS_CURSOR) == 0 && voice_pos(0) == 0);
block(1.0f, 0.0f, 0.0f);
CHECK(block_is(0, BLOCK, 0.5f, 0.5f));
hos_menu_sound_play(SYS_CURSOR, t0 + 1100 * kMs); /* (100 ms on: heard, the one before ringing on) */
CHECK(active() == 2 && voice_pos(0) == BLOCK && voice_pos(1) == 0);
for (int k = 0; k < 10; k++) block(1.0f, 0.0f, 0.0f);
CHECK(active() == 2 && voice_pos(0) == 11 * BLOCK && voice_pos(1) == 10 * BLOCK);
hos_menu_sound_play(SYS_DECIDE, t0 + 1150 * kMs);
CHECK(active() == 2 && voice_with(SYS_CURSOR) == 0 && voice_with(SYS_DECIDE) == 1);
CHECK(active() == 3 && voice_with(SYS_DECIDE) == 2);
quiet();
sounds[SYS_CURSOR] = sounds[SYS_DECIDE] = (Sound){0};
}
{ /* ((Triforce, 11-26) the settings' tabs' and the Mods screen's own ticks are ticks as the cursor's: at the whole
level, each move's beside the ones before whosever they were, an ask within 45 ms of the sound before left out,
and the decision of the same press takes the tick's voice; a step back after it a voice of its own */
install(S_NAV, 30000, 0.5f, 0.5f), install(M_NAV, 30000, 0.25f, 0.25f);
install(S_SEL, 100, 1.0f, -1.0f), install(P_BACK, 300, 0.25f, 0.25f);
t0 += 10000 * kMs;
hos_menu_sound_play(S_NAV, t0);
block(0.5f, 0.0f, 0.0f);
CHECK(active() == 1 && voice_with(S_NAV) == 0 && block_is(0, BLOCK, 0.5f * 0.5f, 0.5f * 0.5f));
for (int k = 1; k < 20; k++) block(1.0f, 0.0f, 0.0f); /* (100 ms on) */
hos_menu_sound_play(M_NAV, t0 + 100 * kMs);
hos_menu_sound_play(S_NAV, t0 + 140 * kMs); /* (40 ms on: left out) */
CHECK(active() == 2 && voice_with(M_NAV) == 1 && voice_with(S_NAV) == 0 && voice_pos(0) == 20 * BLOCK);
block(1.0f, 0.0f, 0.0f);
CHECK(block_is(0, BLOCK, 0.5f + 0.25f, 0.5f + 0.25f));
hos_menu_sound_play(S_SEL, t0 + 145 * kMs); /* (the Mods screen's tick 45 ms ago, 240 frames in: its voice) */
CHECK(active() == 2 && voice_with(S_SEL) == 1 && voice_with(M_NAV) < 0 && voice_pos(1) == 0);
hos_menu_sound_play(P_BACK, t0 + 145 * kMs); /* (no tick it could take: a voice of its own) */
CHECK(active() == 3 && voice_with(P_BACK) == 2 && voice_with(S_SEL) == 1 && voice_with(S_NAV) == 0);
block(1.0f, 0.0f, 0.0f);
CHECK(block_is(0, 100, 0.5f + 1.0f + 0.25f, 0.5f - 1.0f + 0.25f));
hos_menu_sound_play(M_NAV, t0 + 300 * kMs); /* (a move after the step back: heard beside it) */
CHECK(voice_with(M_NAV) >= 0 && voice_with(P_BACK) == 2 && voice_with(S_NAV) == 0);
quiet();
}
{ /* ((Triforce, 11-26) a direction held on the settings' tabs with the system menu's cursor's own length, 1.6 s, at
the game's own pace (vk_menu.cpp kNavStepNs: a move each 135 ms): each tick plays whole beside the ones before.
Under them a longer sound that started first (the Mods screen's fanfare, 4 s; the options' opening): with no
voice free the next tick takes the oldest tick's voice, never that sound's, and so does a decision. When the
ticks have played out every voice is free again */
install(FANFARE, 192000, 0.125f, 0.125f), install(S_NAV, 76800, 0.5f, 0.5f), install(S_SEL, 100, 1.0f, -1.0f);
t0 += 10000 * kMs;
hos_menu_sound_play(FANFARE, t0);
int most = 0, started = 0, was_started = (int)started_n;
for (int k = 0; k < 720; k++) { /* (3.6 s of blocks, a move each 27 of them: 135 ms) */
if (k % 27 == 0) hos_menu_sound_play(S_NAV, t0 + 50 * kMs + k * 5 * kMs);
const int now_started = (int)started_n;
started += now_started != was_started, was_started = now_started;
block(1.0f, 0.0f, 0.0f);
if (voice_with(FANFARE) != 0 || voice_pos(0) != (k + 1) * BLOCK) { printf("block %d\n", k); CHECK(!"the fanfare plays on under the ticks"); break; }
if (active() - 1 > most) most = active() - 1;
}
CHECK(started == 27 && most == VOICES - 1 && active() == VOICES); /* (a tick each 135 ms; seven at once, beside the fanfare) */
for (int k = 0; k < 20; k++) block(1.0f, 0.0f, 0.0f); /* (100 ms after the last tick: a decision is not that press's) */
hos_menu_sound_play(S_SEL, t0 + 3800 * kMs);
CHECK(active() == VOICES && voice_with(FANFARE) == 0 && voice_with(S_SEL) > 0);
int ticks = 0;
for (int i = 1; i < VOICES; i++) ticks += atomic_load(&voices[i].sound) == S_NAV;
CHECK(ticks == VOICES - 2); /* (the oldest tick gave its voice) */
for (int k = 0; k < 320; k++) block(1.0f, 0.0f, 0.0f); /* (1.6 s on: the ticks and the fanfare are over) */
CHECK(active() == 0);
quiet();
sounds[FANFARE] = sounds[S_NAV] = sounds[M_NAV] = sounds[S_SEL] = sounds[P_BACK] = (Sound){0};
}
{ /* a restart inside the mix, between its read of the voice's place and of its sound: the tick is 240 samples in when
the decision, 100 samples long, takes its voice. The place is the tick's, the sound the decision's: nothing of
it is mixed in this block (240 is past the decision's end, and its samples end where nothing can be read),
@@ -613,7 +701,7 @@ static void voices_and_mix(void) {
block(1.0f, 0.0f, 0.0f);
restart_with = DECIDE, restart_at = 1, between = restart;
block(1.0f, 0.0f, 0.0f);
CHECK(between == NULL && block_is(0, BLOCK, 0.3f, 0.3f)); /* (the tick's block was already added) */
CHECK(between == NULL && block_is(0, BLOCK, 0.5f, 0.5f)); /* (the tick's block was already added, at the whole level) */
CHECK(active() == 1 && voice_with(DECIDE) == 0 && voice_pos(0) == 0);
block(1.0f, 0.0f, 0.0f);
CHECK(block_is(0, 100, 1.0f, -1.0f) && block_is(100, BLOCK, 0.0f, 0.0f) && active() == 0);
@@ -655,6 +743,8 @@ static void rom_seven(void) {
rom_sound(DECIDE, 1000, 8192, -8192), rom_sound(CANCEL, 500, 2048, 2048), rom_sound(TAB_LEFT, 500, 4096, 0);
rom_sound(TAB_RIGHT, 500, 0, 4096), rom_sound(FANFARE, 1500, 8192, 8192); /* ((Triforce) the Mods screen's install done) */
rom_sound(SYS_CURSOR, 600, 2048, 4096), rom_sound(SYS_DECIDE, 700, 4096, 2048); /* ((Triforce, 11-17) the Mods entry's */
/* ((Triforce, 11-25) the system menu's small decide and its cancel: the roles' own, with its cursor above) */
rom_sound(M_SEL, 800, 1024, 8192), rom_sound(S_BACK, 900, 8192, 1024);
}
static void frame(float l, float r) {
for (int i = 0; i < BLOCK; i++) bl[i] = l, br[i] = r;
@@ -676,8 +766,10 @@ static void loading(void) {
rom_put(files[TAB_RIGHT], huge, sizeof huge); /* (more than a sound's file ever has: not taken) */
CHECK(atomic_load(&loaded) == 0);
load_all();
CHECK(atomic_load(&loaded) == 2 && rom_reads == 10);
CHECK(strstr(logged, "menu sounds: 5 of 10 interface sounds from the game's files"));
/* ((Triforce, 11-25) twelve files for the seventeen sounds: the roles' seven are the system menu's cursor, read for
it already, its small decide and its cancel, read once each) */
CHECK(atomic_load(&loaded) == 2 && rom_reads == 12 && rom_odd == 0);
CHECK(strstr(logged, "menu sounds: 5 of 19 interface sounds from the game's files"));
CHECK(strstr(logged, "SE_Sys_Cancel00.bwav is not a BWAV file the options play") && strstr(logged, "left out"));
CHECK(sounds[OPEN].pcm && sounds[OPEN].frames == 2000 && sounds[OPEN].pcm[0] == 0.25f && sounds[OPEN].pcm[3999] == 0.25f);
CHECK(sounds[DECIDE].pcm && sounds[DECIDE].pcm[1] == -0.25f && sounds[TAB_LEFT].pcm && sounds[TAB_LEFT].pcm[1] == 0.0f);
@@ -713,7 +805,7 @@ static void frames_and_events(void) {
frame(0.0f, 0.0f), frame(0.0f, 0.0f);
CHECK(load_requests == 1);
load_all();
CHECK(strstr(logged, "menu sounds: 10 of 10 interface sounds from the game's files") && rom_reads == 10);
CHECK(strstr(logged, "menu sounds: 19 of 19 interface sounds from the game's files") && rom_reads == 12);
frame(0.0f, 0.0f);
CHECK(load_requests == 1 && block_is(0, BLOCK, 0.0f, 0.0f) && active() == 0);
/* a sound asked for is in the very next block, at the row's level, over what the block holds */
@@ -742,17 +834,17 @@ static void frames_and_events(void) {
row_volume = 50;
frame(0.0f, 0.0f);
CHECK(block_is(0, BLOCK, 0.0f, 0.0f));
/* the cursor's tick asked for at every step of a held direction: five a second are heard */
/* the cursor's tick asked for at every step of a held direction, each 15 ms: ((Triforce, 11-25) one starts each 45 ms
(one press asking twice is left out), each beside the ones before ((11-26) as the game's) */
now_ns += 1000 * kMs;
int ticks = 0;
const uint64_t ticks_before = started_n;
for (int k = 0; k < 200; k++, now_ns += 5 * kMs) { /* one second of blocks, a tick asked for at every third */
if (k % 3 == 0) ask(CURSOR);
frame(0.0f, 0.0f);
ticks += voice_with(CURSOR) >= 0 && voice_pos(voice_with(CURSOR)) == BLOCK;
CHECK(asked_at == nasked);
if (nasked > 48) nasked = asked_at = 0;
}
CHECK(ticks == 6); /* (at 0, 180, 360, 540, 720 and 900 ms) */
CHECK(started_n - ticks_before == 23); /* (at 0, 45, 90 ... 990 ms) */
now_ns += 1000 * kMs;
for (int k = 0; k < 40; k++) frame(0.0f, 0.0f);
CHECK(active() == 0);
@@ -763,7 +855,147 @@ static void frames_and_events(void) {
CHECK(asked_at == 8);
frame(0.0f, 0.0f);
CHECK(asked_at == 10);
CHECK(volume_reads > 200 && rom_reads == 10); /* (the files were read once) */
CHECK(volume_reads > 200 && rom_reads == 12); /* (the files were read once) */
}
/* ---- (Triforce, 11-25) whose sound: the settings' tabs, the Mods screen and the step back to the pause menu's System list,
a sound each (the owner: "They should be using the title screen's SFX instead of the in-game Menu SFX"), and the
environment's word for each ---- */
static int file_is(int id, const char *name) {
char want[128];
snprintf(want, sizeof want, "Sound/Resource/Stream/%s.bwav", name);
return !strcmp(files[id], want);
}
static void roles_table(void) {
static const char *const names[] = {"HOS_MENU_SOUND_SETTINGS_NAVIGATE", "HOS_MENU_SOUND_SETTINGS_SELECT", "HOS_MENU_SOUND_SETTINGS_BACK",
"HOS_MENU_SOUND_MODS_NAVIGATE", "HOS_MENU_SOUND_MODS_SELECT", "HOS_MENU_SOUND_MODS_BACK",
"HOS_MENU_SOUND_PAUSE_BACK", "HOS_MENU_SOUND_SETTINGS_ON", "HOS_MENU_SOUND_SETTINGS_OFF"};
/* the nine, after the system menu's two and the last of the sounds; each one's variable has its name */
CHECK(ROLES == 9 && S_NAV == SYS_DECIDE + 1 && P_BACK == S_NAV + 6 && S_ON == P_BACK + 1 && S_OFF + 1 == HOS_MENU_SOUND_N);
/* ((Triforce, 11-25) a toggle's On and Off, as the owner chose them: the small decide, the cancel */
CHECK(file_is(S_ON, "SE_Sys_SysMenu_DecideS00") && file_is(S_OFF, "SE_Sys_SysMenu_Cansel00"));
for (int k = 0; k < ROLES; k++) CHECK(roles[k].id == S_NAV + k && !strcmp(roles[k].env, names[k]));
/* their own files: the system menu's (the title screen's) cursor, decide and cancel, as the owner chose them: the
settings' Select the large decide (the title's Continue's), the Mods screen's the small one */
CHECK(file_is(S_NAV, "SE_Sys_SysMenu_Cursor00") && file_is(M_NAV, "SE_Sys_SysMenu_Cursor00"));
CHECK(file_is(S_SEL, "SE_Sys_SysMenu_DecideL00") && file_is(M_SEL, "SE_Sys_SysMenu_DecideS00"));
CHECK(file_is(S_BACK, "SE_Sys_SysMenu_Cansel00") && file_is(M_BACK, "SE_Sys_SysMenu_Cansel00") && file_is(P_BACK, "SE_Sys_SysMenu_Cansel00"));
/* the others as they were */
CHECK(file_is(CURSOR, "SE_Sys_Cursor00") && file_is(DECIDE, "SE_Sys_Do00") && file_is(CANCEL, "SE_Sys_Cancel00"));
CHECK(file_is(SYS_CURSOR, "SE_Sys_SysMenu_Cursor00") && file_is(SYS_DECIDE, "SE_Sys_SysMenu_DecideL00"));
CHECK(file_is(OPEN, "SE_Sys_PlusMenu_Open00") && file_is(CLOSE, "SE_Sys_PlusMenu_Close00") && file_is(FANFARE, "BGM_ItemGet_Medium"));
CHECK(file_is(TAB_LEFT, "SE_Sys_MinusMenu_TabMove_L00") && file_is(TAB_RIGHT, "SE_Sys_MinusMenu_TabMove_R00"));
for (int id = 1; id < SOUNDS; id++) CHECK(files[id] != NULL);
/* the ticks: the cursor's and the two that are a role's; the system menu's own cursor is not thinned out */
for (int id = 0; id <= SOUNDS; id++) CHECK(is_tick(id) == (id == CURSOR || id == S_NAV || id == M_NAV));
/* a sound's name: letters, digits and _, 1 to 64 */
char name[80];
memset(name, 'a', sizeof name);
name[64] = 0;
CHECK(role_name_ok(name) && role_name_ok("SE_Sys_Cursor00") && role_name_ok("SE_Sys_SysMenu_Cansel00") && role_name_ok("_") && role_name_ok("9"));
name[64] = 'a', name[65] = 0;
CHECK(!role_name_ok(name) && !role_name_ok(""));
CHECK(!role_name_ok("SE_Sys_Cursor00.bwav") && !role_name_ok("..") && !role_name_ok(".") && !role_name_ok("../SE_Sys_Cursor00"));
CHECK(!role_name_ok("Stream/SE_Sys_Cursor00") && !role_name_ok("a\\b") && !role_name_ok("C:a") && !role_name_ok("~"));
CHECK(!role_name_ok("SE Sys") && !role_name_ok(" SE") && !role_name_ok("SE-Sys") && !role_name_ok("%s%n") && !role_name_ok("a\n"));
CHECK(!role_name_ok("caf\xc3\xa9") && !role_name_ok("\x7f") && !role_name_ok("a*") && !role_name_ok("a?"));
CHECK(sizeof role_files[0] == strlen("Sound/Resource/Stream/") + 64 + strlen(".bwav") + 1);
}
static int16_t held_more[2][4000];
static void rom_named(const char *rel, uint32_t frames, int l, int r) { /* (one more of the game's files, by its path) */
for (uint32_t i = 0; i < frames; i++) held_more[0][i] = (int16_t)l, held_more[1][i] = (int16_t)r;
const Chan c[2] = {chan(0, 0, 48000, frames, held_more[0]), chan(0, 1, 48000, frames, held_more[1])};
uint64_t size;
const uint8_t *file = bwav(c, 2, &size);
rom_put(rel, file, size);
}
static void roles_set(void) {
rom_seven();
rom_named("Sound/Resource/Stream/SE_Sys_SysMenu_Error00.bwav", 1200, 4096, -4096);
rom_put("Sound/Resource/Stream/Not_A_Sound.bwav", (const uint8_t *)"not a sound at all, whatever its name says", 42);
/* nothing set: the files as roles_table found them, nothing said of a role, the environment asked once for each */
load_all();
CHECK(env_reads == 9 && !strstr(logged, "HOS_MENU_SOUND_") && rom_reads == 12 && rom_odd == 0);
CHECK(strstr(logged, "menu sounds: 19 of 19 interface sounds from the game's files"));
CHECK(file_is(S_NAV, "SE_Sys_SysMenu_Cursor00") && file_is(S_SEL, "SE_Sys_SysMenu_DecideL00") && file_is(P_BACK, "SE_Sys_SysMenu_Cansel00"));
/* (a file is decoded once: the roles that share it share its samples) */
CHECK(sounds[S_NAV].pcm && sounds[S_NAV].pcm == sounds[SYS_CURSOR].pcm && sounds[M_NAV].pcm == sounds[SYS_CURSOR].pcm);
CHECK(sounds[S_SEL].pcm && sounds[S_SEL].pcm == sounds[SYS_DECIDE].pcm && sounds[M_SEL].pcm && sounds[M_SEL].pcm != sounds[S_SEL].pcm);
CHECK(sounds[S_BACK].pcm && sounds[M_BACK].pcm == sounds[S_BACK].pcm && sounds[P_BACK].pcm == sounds[S_BACK].pcm);
/* each sounds as its file, every one whole ((Triforce, 11-26) the ticks too: they were at 0.6) */
row_volume = 100;
ask(S_SEL), ask(P_BACK);
frame(0.0f, 0.0f);
CHECK(block_is(0, BLOCK, 0.125f + 0.25f, 0.0625f + 0.03125f) && load_requests == 0);
now_ns += 1000 * kMs;
for (int k = 0; k < 4; k++) frame(0.0f, 0.0f);
CHECK(active() == 0);
ask(M_NAV);
frame(0.0f, 0.0f);
CHECK(block_is(0, BLOCK, 0.0625f, 0.125f));
now_ns += 1000 * kMs;
for (int k = 0; k < 3; k++) frame(0.0f, 0.0f);
CHECK(active() == 0);
/* the environment's word, read when the files are (here: again, as a new run would) */
logged[0] = 0, rom_reads = 0, env_reads = 0;
memset(sounds, 0, sizeof sounds);
put_env("HOS_MENU_SOUND_SETTINGS_NAVIGATE", "SE_Sys_Cursor00"); /* the in-game menu's tick again: the cursor's file */
put_env("HOS_MENU_SOUND_SETTINGS_SELECT", ""); /* empty: as not set */
put_env("HOS_MENU_SOUND_SETTINGS_BACK", "../../../triforce_options"); /* not a name: left out, said */
put_env("HOS_MENU_SOUND_MODS_NAVIGATE", "SE_Sys_SysMenu_Cursor00"); /* its own: nothing to say */
put_env("HOS_MENU_SOUND_MODS_SELECT", "SE_Sys_SysMenu_Error00"); /* another of the game's files */
put_env("HOS_MENU_SOUND_MODS_BACK", "SE_Sys_Typo00"); /* a name the game's files do not have: its own, said */
put_env("HOS_MENU_SOUND_PAUSE_BACK", "Not_A_Sound"); /* a file that is not a sound: its own, said */
put_env("HOS_MENU_SOUND_CURSOR", "SE_Sys_Do00"); /* (not a role: never asked for) */
load_all();
CHECK(env_reads == 9 && rom_odd == 0);
CHECK(file_is(S_NAV, "SE_Sys_Cursor00") && sounds[S_NAV].pcm && sounds[S_NAV].pcm == sounds[CURSOR].pcm);
CHECK(strstr(logged, "menu sounds: HOS_MENU_SOUND_SETTINGS_NAVIGATE: Sound/Resource/Stream/SE_Sys_Cursor00.bwav, the environment's "
"(its own: Sound/Resource/Stream/SE_Sys_SysMenu_Cursor00.bwav)"));
CHECK(file_is(S_SEL, "SE_Sys_SysMenu_DecideL00") && !strstr(logged, "HOS_MENU_SOUND_SETTINGS_SELECT"));
CHECK(file_is(S_BACK, "SE_Sys_SysMenu_Cansel00") && sounds[S_BACK].pcm && !strstr(logged, "triforce_options"));
CHECK(strstr(logged, "menu sounds: HOS_MENU_SOUND_SETTINGS_BACK: its value is not a sound's name"));
CHECK(file_is(M_NAV, "SE_Sys_SysMenu_Cursor00") && sounds[M_NAV].pcm == sounds[SYS_CURSOR].pcm && !strstr(logged, "HOS_MENU_SOUND_MODS_NAVIGATE"));
CHECK(file_is(M_SEL, "SE_Sys_SysMenu_Error00") && sounds[M_SEL].pcm && sounds[M_SEL].pcm != sounds[S_SEL].pcm && sounds[M_SEL].frames == 1200);
CHECK(strstr(logged, "menu sounds: HOS_MENU_SOUND_MODS_SELECT: Sound/Resource/Stream/SE_Sys_SysMenu_Error00.bwav, the environment's"));
CHECK(file_is(M_BACK, "SE_Sys_SysMenu_Cansel00") && sounds[M_BACK].pcm && sounds[M_BACK].pcm == sounds[S_BACK].pcm);
CHECK(strstr(logged, "menu sounds: HOS_MENU_SOUND_MODS_BACK: no sound Sound/Resource/Stream/SE_Sys_Typo00.bwav in the game's files: "
"its own, Sound/Resource/Stream/SE_Sys_SysMenu_Cansel00.bwav"));
CHECK(file_is(P_BACK, "SE_Sys_SysMenu_Cansel00") && sounds[P_BACK].pcm == sounds[S_BACK].pcm);
CHECK(strstr(logged, "Sound/Resource/Stream/Not_A_Sound.bwav is not a BWAV file the options play") &&
strstr(logged, "menu sounds: HOS_MENU_SOUND_PAUSE_BACK: no sound Sound/Resource/Stream/Not_A_Sound.bwav in the game's files"));
CHECK(file_is(CURSOR, "SE_Sys_Cursor00") && file_is(DECIDE, "SE_Sys_Do00") && !strstr(logged, "HOS_MENU_SOUND_CURSOR"));
/* (the ten, the small decide (a toggle's On), the cancel, the error sound, and the two that are not there or not a
sound) */
CHECK(rom_reads == 15 && strstr(logged, "menu sounds: 19 of 19 interface sounds from the game's files"));
/* the settings' tick is the in-game menu's now, still a tick; the Mods screen's decide the error sound */
ask(S_NAV);
frame(0.0f, 0.0f);
CHECK(block_is(0, BLOCK, 0.5f, 0.5f));
now_ns += 1000 * kMs;
for (int k = 0; k < 20; k++) frame(0.0f, 0.0f);
CHECK(active() == 0);
ask(M_SEL);
frame(0.0f, 0.0f);
CHECK(block_is(0, BLOCK, 0.125f, -0.125f));
}
static void roles_long(void) { /* a value longer than a name may be, and one of 64: a run of its own (the files are read once) */
static char longer[80], longest[80];
memset(longer, 'b', 65), memset(longest, 'c', 64);
rom_seven();
put_env("HOS_MENU_SOUND_MODS_BACK", longer);
put_env("HOS_MENU_SOUND_PAUSE_BACK", longest);
load_all();
CHECK(file_is(M_BACK, "SE_Sys_SysMenu_Cansel00") && strstr(logged, "menu sounds: HOS_MENU_SOUND_MODS_BACK: its value is not a sound's name"));
/* (64: a name, asked for whole, not in the game's files: its own again) */
char want[200];
snprintf(want, sizeof want, "menu sounds: HOS_MENU_SOUND_PAUSE_BACK: Sound/Resource/Stream/%s.bwav, the environment's", longest);
CHECK(strlen(longest) == 64 && strstr(logged, want));
snprintf(want, sizeof want, "menu sounds: HOS_MENU_SOUND_PAUSE_BACK: no sound Sound/Resource/Stream/%s.bwav in the game's files", longest);
CHECK(strstr(logged, want) && file_is(P_BACK, "SE_Sys_SysMenu_Cansel00"));
CHECK(sounds[P_BACK].pcm && sounds[P_BACK].pcm == sounds[S_BACK].pcm && rom_odd == 0 && rom_reads == 13);
CHECK(strstr(logged, "menu sounds: 19 of 19 interface sounds from the game's files"));
}
/* ---- the end of nn_audio.c's render_frame, cut out as it is: the options' sounds, the Master volume, the 16 bits ---- */
@@ -842,6 +1074,8 @@ int main(int argc, char **argv) {
else if (!strcmp(what, "load")) loading();
else if (!strcmp(what, "frames")) frames_and_events();
else if (!strcmp(what, "master")) master_and_clipping();
else if (!strcmp(what, "roles")) roles_table(), roles_set();
else if (!strcmp(what, "roles-long")) roles_long();
else return printf("no such scenario: %s\n", what), 2;
if (fails) return printf("%s: %d checks failed\n", what, fails), 1;
printf("%s: ok\n", what);

View File

@@ -14,6 +14,7 @@
#include <mutex>
#include <string>
#include <vector>
#include "cpuwordsseen.h" // ((Triforce, 11-26) memory_cpu_owned's table of the words the sets hold: tests/test_cpuwordsseen.py
#define VK_NULL_HANDLE nullptr
#define CHECK(ok) do { if (!(ok)) { std::printf("FAIL:%d %s\n", __LINE__, #ok); fails++; } } while (0)
@@ -36,6 +37,8 @@ static Host* host = &the_host;
std::mutex cpu_words_mu;
std::vector<uint64_t> cpu_words, cpu_words_recent, cpu_words_new;
cpu_words_seen::Table cpu_words_table;
int cpu_words_seen_mode() { return cpu_words_seen::ON; } // (on, as by default)
std::mutex shadow_written_mu;
std::vector<uint32_t> shadow_written_pages, shadow_written_collected_list, shadow_written_by_replay;
bool shadow_written_all = false;

View File

@@ -1245,7 +1245,7 @@ struct Out {
static Out run_tracked(void (*scenario)(), int mode, bool mutate, bool own_thread = false, bool lock = true) {
Out o;
const auto body = [&] {
rec::Arena& a = rec::t_arena;
rec::Arena& a = rec::t_arena();
const uint64_t f0 = a.failures, b0 = a.budget_drains, fb0 = a.fallbacks;
const long live0 = g_aligned_live.load() - (long)a.nchunks;
rec::set_mode(mode);
@@ -1348,7 +1348,7 @@ static int bench(int n) {
} shapes[] = {{"typical draw (push descriptors x3 writes, push constants 96 B, vertex buffers x16, draw)", draw_typical,
draw_typical_direct, 4},
{"cold draw (+ pipeline, 9 writes, 9 dynamic states, index buffer)", draw_cold, nullptr, 16}};
rec::Arena& a = rec::t_arena;
rec::Arena& a = rec::t_arena();
for (const Shape& sh : shapes) {
// (modes: 0 direct (no wrapper), 1 off (the wrapper's branch), 2 sync, 3 deferred: encode and drain timed apart, 4 thread:
// the producer's encode and publish, and its wait at the boundary, timed apart; the recorder's busy time a packet)
@@ -1570,13 +1570,13 @@ static void thread_checks(const std::vector<Call>& ref) {
}
g_delay_ns = 1000; // (the recorder behind the producer: a missed wait shows as a call out of place or on a busy command buffer)
const Out lref = run_tracked(lifecycle, rec::OFF, false);
const uint64_t fb0 = rec::t_arena.fallbacks;
const uint64_t fb0 = rec::t_arena().fallbacks;
g_hold_ms = 50; // (and held at each point the producer must wait: hold())
const Out lt = run_tracked(lifecycle, rec::THREAD, true);
g_hold_ms = 0, g_hold_until_ns = 0;
check_run("thread lifecycle (2 command buffers interleaved; reset, begin, end, submit, wait x2; query read; destruction; caller "
"memory poisoned; driver 1 us a call)", lref.log, lt);
if (rec::t_arena.fallbacks - fb0 != 6) std::printf("FAIL thread lifecycle: %llu fallbacks, 6 expected\n", (unsigned long long)(rec::t_arena.fallbacks - fb0)), failures++;
if (rec::t_arena().fallbacks - fb0 != 6) std::printf("FAIL thread lifecycle: %llu fallbacks, 6 expected\n", (unsigned long long)(rec::t_arena().fallbacks - fb0)), failures++;
// (each thread run with the recorder held at the points the producer must wait: hold(); the direct references without)
const auto held = [](void (*scenario)(), bool lock) {
g_hold_ms = 50;
@@ -1769,16 +1769,16 @@ int main(int argc, char** argv) {
}
same("direct, caller memory reused after each call", ref, run(frame, rec::OFF, true));
if (env_mode != rec::OFF) same("RX_VK_RECORDER from the environment, caller memory reused", ref, run(frame, env_mode, true));
rec::t_arena.packets = 0;
rec::t_arena().packets = 0;
same("sync (packed, run at once), caller memory reused", ref, run(frame, rec::SYNC, true));
if (rec::t_arena.packets != ref.size()) std::printf("FAIL sync: %llu packets for %zu calls\n", (unsigned long long)rec::t_arena.packets, ref.size()), failures++;
if (rec::t_arena.ci || rec::t_arena.used) std::printf("FAIL sync: the arena not rewound\n"), failures++;
if (rec::t_arena().packets != ref.size()) std::printf("FAIL sync: %llu packets for %zu calls\n", (unsigned long long)rec::t_arena().packets, ref.size()), failures++;
if (rec::t_arena().ci || rec::t_arena().used) std::printf("FAIL sync: the arena not rewound\n"), failures++;
same("deferred (packed, run at the drain), caller memory poisoned in between", ref, run(frame, rec::DEFER, true));
if (rec::t_arena.fallbacks) std::printf("FAIL: %llu calls not packed\n", (unsigned long long)rec::t_arena.fallbacks), failures++;
if (rec::t_arena().fallbacks) std::printf("FAIL: %llu calls not packed\n", (unsigned long long)rec::t_arena().fallbacks), failures++;
const std::vector<Call> fref = run(fallbacks, rec::OFF, false);
same("fallback order (pNext chain, inline uniform block, a push template of a size not told), deferred", fref, run(fallbacks, rec::DEFER, false));
if (rec::t_arena.fallbacks != 3) std::printf("FAIL: %llu fallbacks, 3 expected\n", (unsigned long long)rec::t_arena.fallbacks), failures++;
if (rec::t_arena().fallbacks != 3) std::printf("FAIL: %llu fallbacks, 3 expected\n", (unsigned long long)rec::t_arena().fallbacks), failures++;
// ---- defer (step 1.5): the lifecycle, the replay lock, the budgets, an allocation failure, a parallel replay
const Out lref = run_tracked(lifecycle, rec::OFF, false);
@@ -1825,7 +1825,7 @@ int main(int argc, char** argv) {
rec::set_mode(rec::DEFER);
g_mutate = true, g_log.clear();
frame();
const bool at_once = g_log.size() == ref.size() && !rec::t_arena.head;
const bool at_once = g_log.size() == ref.size() && !rec::t_arena().head;
rec::drain();
const std::vector<Call> got = g_log;
rec::set_mode(rec::OFF);

View File

@@ -430,10 +430,12 @@ def main():
check(re.sub(r"\s+", " ", definition(aa, "int upscaler_now")).endswith(
"{ if (fsr3_wanted()) return fsr3_native() ? upscaler_rows::FSR3_AA : upscaler_rows::FSR3; return temporal_mode(); }"),
"vk_aa.cpp's upscaler_now is not what the menu's Upscaler row shows")
# ((Triforce) 11-24: and the Upscaler's Off, which is the game's own here: its SMAA runs, upscaler_now's GAME)
check("if (fsr3_wanted()) return fsr3_native() ? ur::FSR3_AA : ur::FSR3;\n const int t = temporal_mode();\n"
" return t == ur::GAME && opts.dlss == ur::OFF ? (int)ur::OFF : t;" in menu,
"vk_menu.cpp's upscaler() changed: vk_aa.cpp's upscaler_now follows it")
# ((Triforce) 11-24: and the Upscaler's Off, which is the game's own here: its SMAA runs, upscaler_now's GAME. ((11-26) The
# menu's upscaler_of a choice is the same steps: for the applied one (fsr3_wanted, temporal_mode) it is upscaler_now's)
check("if (fsr3_wanted_of(choice, now)) return fsr3_native_of(choice, now) ? ur::FSR3_AA : ur::FSR3;\n"
" const int t = temporal_mode_of(choice, now);\n"
" return t == ur::GAME && choice == ur::OFF ? (int)ur::OFF : t;" in menu,
"vk_menu.cpp's upscaler_of changed: vk_aa.cpp's upscaler_now follows it")
check('getenv("RX_VK_AA")' in aa and 'getenv("RX_VK_AA_KEEP")' in aa, "vk_aa.cpp no longer reads its two switches")
# the game's own chosen and nothing left to free: a dispatch asks a comparison and nothing else
check(re.sub(r"\s+", " ", definition(aa, "bool aa_asked")) ==

101
tests/test_audio_late.py Normal file
View File

@@ -0,0 +1,101 @@
"""The mixer's count of late refills (host/nn_audio.c au_late; no game, no output device).
A playing voice that ran out of the game's wave buffers and is given one again within half a second played silence in
between: the game's audio thread came late. The title screen's sound stuttered with its movie and the log had no line for
it. The two rules are cut out of nn_audio.c unchanged and run: a voice is marked dry at the first mix frame it plays
nothing in and has nothing queued, the mark holds while it stays dry and goes when it plays or has a buffer again; a
buffer appended to a playing, dry voice counts the frames in between, up to half a second (longer is a new sound on the
voice), and nothing for a voice that is not playing or was fed in time. Then the wiring is read: the mixer marks every
voice it renders, the append and a state change clear the mark, the device-behind drop is counted, and the mixer thread
writes one line per 2000 mix frames that had any.
python -I -B tests/test_audio_late.py [--cc gcc]
"""
import argparse
import os
import subprocess
import tempfile
from pathlib import Path
RUN_ALL_ARGS = ["--cc", "gcc"]
ROOT = Path(__file__).resolve().parents[1]
MAIN = r'''
#define CHECK(x) do { if (!(x)) { fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); return 1; } } while (0)
int main(void) {
/* (the mark: 0 while the voice plays or has buffers; the first dry frame, kept while dry) */
CHECK(audio_late_mark(0, 1, 0, 7) == 0 && audio_late_mark(0, 0, 2, 7) == 0 && audio_late_mark(0, 1, 3, 7) == 0);
CHECK(audio_late_mark(0, 0, 0, 7) == 7 && audio_late_mark(7, 0, 0, 8) == 7 && audio_late_mark(7, 0, 0, 900) == 7);
CHECK(audio_late_mark(7, 1, 0, 9) == 0 && audio_late_mark(7, 0, 1, 9) == 0);
/* (the gap: dry at frame 7, fed before frame 8 is mixed = one frame of silence; half a second at most) */
CHECK(audio_late_gap(1, 7, 8) == 1 && audio_late_gap(1, 7, 27) == 20 && audio_late_gap(1, 7, 107) == 100);
CHECK(audio_late_gap(1, 7, 108) == 0 && audio_late_gap(1, 7, 5000) == 0);
CHECK(audio_late_gap(1, 0, 8) == 0); /* fed in time */
CHECK(audio_late_gap(0, 7, 8) == 0); /* not playing: a stopped voice's next sound */
CHECK(audio_late_gap(1, 7, 7) == 0); /* (never: the mixer counts on before an append can run) */
CHECK(AUDIO_LATE_MOST * 5 == 500);
return 0;
}
'''
def check(cond, what):
if not cond:
raise SystemExit("FAIL: " + what)
def block(source, marker):
start = source.find(marker)
check(start >= 0, "%s is missing" % marker)
end = source.index("{", start) + 1
depth = 1
while depth:
depth += (source[end] == "{") - (source[end] == "}")
end += 1
return source[start:end]
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--cc", default=os.environ.get("CC", "gcc"))
args = parser.parse_args()
source = (ROOT / "host/nn_audio.c").read_text(encoding="utf-8")
rules = "\n".join(["#include <stdint.h>", "#include <stdio.h>", "enum { AUDIO_LATE_MOST = 100 };",
block(source, "static inline int64_t audio_late_mark("), block(source, "static inline int64_t audio_late_gap("), MAIN])
check("enum { AUDIO_LATE_MOST = 100 };" in source, "AUDIO_LATE_MOST is not 100 mix frames in nn_audio.c")
with tempfile.TemporaryDirectory() as tmp:
src, exe = Path(tmp) / "audio_late_test.c", Path(tmp) / "audio_late_test.exe"
src.write_text(rules, encoding="utf-8")
built = subprocess.run([args.cc, "-std=c11", "-Wall", "-Werror", "-o", str(exe), str(src)], capture_output=True, text=True)
check(built.returncode == 0, "the rules do not compile:\n" + built.stderr)
ran = subprocess.run([str(exe)], capture_output=True, text=True)
check(ran.returncode == 0, "the rules: " + ran.stderr.strip())
# the wiring
render = block(source, "static void render_voice(")
check("v->dry_at = audio_late_mark(v->dry_at, any, v->nwb, au_mix_frame);" in render, "render_voice does not mark the voice")
apply = block(source, "static void apply(")
append = apply[apply.index("case OP_VOICE_APPEND:"):]
append = append[:append.index("break;")]
check("audio_late_gap(v->state == PLAY_STARTED, v->dry_at, au_mix_frame)" in append, "the append does not count the gap")
check("v->dry_at = 0;" in append, "the append does not clear the mark")
check(append.index("audio_late_gap(") < append.index("v->wb[v->nwb++]"), "the gap is read after the buffer is queued")
state = apply[apply.index("case OP_VOICE_STATE:"):apply.index("case OP_VOICE_APPEND:")]
check("if (v->state != k->i0) v->dry_at = 0;" in state, "a state change does not clear the mark")
output = block(source, "static void output_frame(")
behind = output[output.index("the device is behind"):]
check("out_dropped++;" in behind[:120], "the device-behind drop is not counted")
loop = block(source, "static DWORD WINAPI renderer_main(")
check("++au_mix_frame % 2000 == 0" in loop, "the mixer does not count its frames")
check(loop.index("render_frame(pcm") < loop.index("++au_mix_frame") < loop.index("au_unlock();"),
"the frame count moves outside the mixer's lock (apply() reads it under the lock)")
check("au_late_report(out_dropped), out_dropped = 0;" in loop, "the report is not written from the mixer thread")
report = block(source, "static void au_late_report(")
check("if (au_late.gaps || dropped)" in report and "late refills" in report, "the report writes when there was nothing")
print("ok")
if __name__ == "__main__":
main()

497
tests/test_bakescan.py Normal file
View File

@@ -0,0 +1,497 @@
"""The bake write-back's scan walks a list of the textures it can take, not the whole texture cache (gpu/vk/bakescan.h,
vk_texture.cpp bake_writeback_step, texture_written, forget_gpu; no game, no GPU).
(Triforce, 11-26, the GPU audit's C36.) Every fourth present bake_writeback_step walked every texture of the cache for the
few the GPU drew in one frame and whose texels are not in the game's memory yet (the terrain's normal maps): 1.1% of the
Presentation Thread at Lake Hylia for a walk that finds nothing where the recordings write them back themselves. Now the
textures that can be taken are listed where they become so, and the step walks the list.
This compiles bakescan.h over textures of the test's own and a script of events (drawn, drawn again, sampled, released,
only cleared, a copy lost, destroyed, the image's contents dropped), with the writes of texture_written and the step's
predicate as the source had them:
- at every step the list gives exactly the textures the walk of the whole cache gives (as a set), and every texture the
rule calls armed is listed, at every present;
- a copy lost (wb_written back to 0) is taken again; one not sampled for long is taken once it is sampled again; one
destroyed while listed is not looked at again; one drawn every frame does not stay listed;
- under the step's caps the list takes what is left at the next steps: all of them, each once, as the walk did; one no
step can take (more than 8 MB of storage) does not stop the newer ones in the list, and stops the walk of the whole
cache as before;
- the step looks at the listed ones, not at the cache; the switch's values;
- with RX_VK_BAKE_WRITEBACK=0 or RX_VK_BAKE_SCAN=all (bakescan::kept false) nothing is listed: targets drawn every frame
and a tile leave the list empty, and the walk of the whole cache takes the tile.
And reads the source: the fields the rule reads can make a texture armed only where the list is told (texture_written, the
two places a copy is lost), with nothing that leaves texture_written before it is told, and a texture leaves the cache only
through forget_gpu, which tells it; every place that tells the list calls bake_list_note, which asks bake_list_kept()
first, and texture_written calls it without a branch of its own (its control flow, and so its entry in the renderer's play
profile, as before); the step walks the list unless RX_VK_BAKE_SCAN=all / check or the lab knob nobakescan, and passes
over in the list one no step can take; check mode lists what it counts; the scan's line is printed on its own, its listed
count the settle's; the switch is in the switches table.
python -I -B tests/test_bakescan.py [--cxx clang++]
"""
import argparse
import re
import subprocess
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
VK = ROOT / "gpu" / "vk"
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
def check(ok, why):
if not ok:
raise SystemExit("FAIL: " + why)
def block(text, head):
at = text.index(head)
return text[at:text.index("\n}\n", at) + 3]
def flat(code):
"""code without its comments, its whitespace runs one space"""
return re.sub(r"\s+", " ", re.sub(r"//[^\n]*", "", code)).strip()
FIXTURE = r"""
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <memory>
#include <set>
#include <vector>
#include "bakescan.h"
static int fails = 0;
#define CHECK(x) do { if (!(x)) { std::printf("FAIL:%d %s\n", __LINE__, #x); fails++; } } while (0)
struct Texture {
uint32_t id = 0;
bool gpu_written = false, released = false, only_cleared = false, image = true, wb_listed = false;
uint64_t first_written = 0, last_written = 0, wb_written = 0, last_frame = 0;
uint64_t bytes = 64 << 10, guest_size = 64 << 10, gpu = 0x1000;
};
static std::vector<std::unique_ptr<Texture>> textures; // (the cache)
static bakescan::List<Texture> bake_list;
static bool list_kept = true; // (bake_list_kept(): bakescan::kept of RX_VK_BAKE_WRITEBACK and RX_VK_BAKE_SCAN)
static void note(Texture* t) { // (bake_list_note, which every place that tells the list calls: the list kept, or nothing)
if (list_kept) bake_list.note(t);
}
static uint64_t frame_no = 8;
static uint32_t next_id = 1;
static Texture* make(uint64_t bytes = 64 << 10) {
textures.push_back(std::make_unique<Texture>());
Texture* t = textures.back().get();
t->id = next_id++, t->bytes = t->guest_size = bytes, t->gpu = 0x100000ull * t->id, t->last_frame = frame_no;
return t;
}
// (texture_written's writes of the fields the rule reads, in its order, and its hook last)
static void written(Texture* tex) {
tex->only_cleared = false;
if (!tex->gpu_written || tex->released) tex->first_written = frame_no;
tex->last_written = frame_no;
tex->gpu_written = true;
tex->released = false;
note(tex);
}
static void destroy(Texture* t) { // (texture_sweep: forget_gpu, then out of the cache)
bake_list.forget(t);
for (auto it = textures.begin(); it != textures.end(); ++it)
if (it->get() == t) { textures.erase(it); return; }
}
// (bake_writeback_step's predicate, as the walk of the whole cache had it before the list)
static bool old_takes(const Texture* t) {
if (!t->gpu_written || t->released || t->only_cleared || !t->first_written || t->first_written != t->last_written ||
t->wb_written == t->last_written || frame_no < t->last_written + 4 || frame_no - t->last_frame > 4 ||
t->bytes > (4ull << 20) || t->gpu >= (1ull << 39) || !t->image)
return false;
return true;
}
static bool new_takes(const Texture* t) {
return bakescan::armed(t->gpu_written, t->first_written, t->last_written, t->wb_written) &&
bakescan::ripe(t->released, t->only_cleared, t->last_written, t->last_frame, t->bytes, t->gpu, frame_no) && t->image;
}
static uint64_t looked = 0;
// (a step: what the list gives against what the whole walk gives; then the copies, under the caps, over the list or, with
// whole (RX_VK_BAKE_SCAN=all / check, the knob nobakescan), over the cache as the walk did; the ids taken)
static std::set<uint32_t> step(bool take = true, bool whole = false) {
std::set<uint32_t> by_walk, by_list, taken;
for (const auto& t : textures)
if (old_takes(t.get())) by_walk.insert(t->id);
static std::vector<Texture*> cands;
bake_list.settle(cands);
for (Texture* t : cands)
if (new_takes(t)) by_list.insert(t->id);
CHECK(list_kept ? by_walk == by_list : cands.empty());
std::vector<Texture*> order = cands;
if (whole) {
order.clear();
for (const auto& t : textures) order.push_back(t.get());
}
size_t items = 0;
uint64_t bytes = 0;
for (Texture* t : order) {
looked += !whole;
if (!new_takes(t) || !take) continue;
if (!whole && !bakescan::room(0, 0, t->guest_size)) continue; // (no step can take it: not the newer ones' stop)
if (!bakescan::room(items, bytes, t->guest_size)) break;
t->wb_written = t->last_written, items++, bytes += t->guest_size;
taken.insert(t->id);
}
return taken;
}
static void invariant() { // (what RX_VK_BAKE_SCAN=check counts: armed and not listed; and no list where it is not kept)
for (const auto& t : textures)
CHECK(list_kept ? !bakescan::armed(t->gpu_written, t->first_written, t->last_written, t->wb_written) || t->wb_listed
: !t->wb_listed);
}
static void present(int n = 1) {
for (int i = 0; i < n; i++) frame_no++, invariant();
}
static uint32_t rnd_state = 12345;
static uint32_t rnd(size_t n) {
rnd_state = rnd_state * 1664525u + 1013904223u;
return (rnd_state >> 8) % (uint32_t)n;
}
int main() {
using namespace bakescan;
// the switch
CHECK(mode_of(nullptr) == kList && mode_of("") == kList && mode_of("list") == kList && mode_of("1") == kList);
CHECK(mode_of("all") == kAll && mode_of("check") == kCheck && mode_of("0") == kAll);
// the rule's two halves are the walk's predicate
CHECK(armed(true, 5, 5, 0) && !armed(false, 5, 5, 0) && !armed(true, 0, 0, 7) && !armed(true, 4, 5, 0) && !armed(true, 5, 5, 5));
CHECK(ripe(false, false, 8, 12, 4ull << 20, (1ull << 39) - 1, 12));
CHECK(!ripe(true, false, 8, 12, 1, 1, 12) && !ripe(false, true, 8, 12, 1, 1, 12) && !ripe(false, false, 9, 12, 1, 1, 12));
CHECK(!ripe(false, false, 8, 7, 1, 1, 12) && ripe(false, false, 8, 8, 1, 1, 12) && !ripe(false, false, 8, 13, 1, 1, 12));
CHECK(!ripe(false, false, 8, 12, (4ull << 20) + 1, 1, 12) && !ripe(false, false, 8, 12, 1, 1ull << 39, 12));
CHECK(room(23, 0, 1) && !room(24, 0, 1) && room(0, (8ull << 20) - 4, 4) && !room(0, (8ull << 20) - 4, 5));
CHECK(room(0, 0, 8ull << 20) && !room(0, 0, (8ull << 20) + 1)); // (no step can take more than 8 MB of storage)
// the list kept only where something reads it: not with the write-back off, nor with the walk of the whole cache
CHECK(kept(true, kList) && kept(true, kCheck) && !kept(true, kAll) && !kept(false, kList) && !kept(false, kCheck));
// a cache of many textures the GPU never drew, some targets drawn every frame, and one tile baked once
for (int i = 0; i < 500; i++) make();
std::vector<Texture*> targets;
for (int i = 0; i < 6; i++) targets.push_back(make());
auto frame = [&](int n = 1) {
for (int i = 0; i < n; i++) {
for (Texture* t : targets) written(t), written(t), t->last_frame = frame_no;
present();
}
};
auto to_step = [&] { // (on to the next fourth present, at least four on)
frame(4);
while (frame_no % 4) frame();
};
frame(2);
Texture* tile = make();
written(tile);
CHECK(tile->wb_listed && bake_list.size() <= 1 + targets.size());
// sampled: taken at the first step four presents on, by both
looked = 0;
to_step(), tile->last_frame = frame_no;
CHECK(step() == std::set<uint32_t>{tile->id});
CHECK(looked <= 1 + targets.size()); // (the listed ones, not the 507 of the cache)
to_step(), tile->last_frame = frame_no;
CHECK(step().empty() && !tile->wb_listed);
CHECK(bake_list.size() == 0); // (a target drawn every frame left the list at the first step, and is not listed again)
for (Texture* t : targets) CHECK(!t->wb_listed);
// the copy lost: wb_written back to 0 and the list told (bake_writeback_step's two places): taken again
tile->wb_written = 0, note(tile);
to_step(), tile->last_frame = frame_no;
CHECK(step() == std::set<uint32_t>{tile->id});
// not sampled for long, then sampled again: it stays listed meanwhile, and is taken when it is sampled
Texture* late = make();
written(late), late->last_frame = frame_no - 6; // (a render target not sampled yet)
for (int i = 0; i < 60; i++) {
frame();
if (frame_no % 4 == 0) CHECK(step().empty());
}
CHECK(late->wb_listed);
while (frame_no % 4) frame();
late->last_frame = frame_no;
CHECK(step() == std::set<uint32_t>{late->id});
// released while listed: not taken; made again and drawn (its contents begin anew): taken
Texture* rel = make();
written(rel);
rel->released = true;
to_step(), rel->last_frame = frame_no;
CHECK(step().empty());
written(rel);
CHECK(rel->first_written == rel->last_written);
to_step(), rel->last_frame = frame_no;
CHECK(step() == std::set<uint32_t>{rel->id});
// destroyed while listed: gone from the list, never looked at again
Texture* dead = make();
written(dead);
const uint32_t dead_id = dead->id;
CHECK(dead->wb_listed);
const size_t before = bake_list.size();
destroy(dead);
CHECK(bake_list.size() == before - 1);
to_step();
CHECK(!step().count(dead_id));
// the image's contents dropped (gpu_written false) while listed, then drawn again
Texture* drop = make();
written(drop);
drop->gpu_written = false;
to_step(), drop->last_frame = frame_no;
CHECK(step().empty() && !drop->wb_listed);
written(drop);
CHECK(drop->wb_listed);
to_step(), drop->last_frame = frame_no;
CHECK(step() == std::set<uint32_t>{drop->id});
// drawn in a second frame: no bake, off the list at the next step; too large: listed, never taken
Texture* twice = make();
written(twice), frame(), written(twice);
Texture* big = make(5ull << 20);
written(big);
to_step(), twice->last_frame = big->last_frame = frame_no;
CHECK(step().empty() && !twice->wb_listed && big->wb_listed);
// the caps: 60 tiles baked in one frame, all sampled: 24 a step, all of them in three steps, each once
std::vector<Texture*> tiles;
for (int i = 0; i < 60; i++) tiles.push_back(make()), written(tiles.back());
std::set<uint32_t> all;
size_t steps = 0, total = 0;
for (int i = 0; i < 40 && all.size() < 60; i++) {
frame();
if (frame_no % 4) continue;
for (Texture* t : tiles) t->last_frame = frame_no;
const std::set<uint32_t> s = step();
CHECK(s.size() <= 24);
steps += !s.empty(), total += s.size();
all.insert(s.begin(), s.end());
}
CHECK(all.size() == 60 && total == 60 && steps == 3);
// and by bytes: three of 3 MB, 8 MB a step
std::vector<Texture*> wide;
for (int i = 0; i < 3; i++) wide.push_back(make(3ull << 20)), written(wide.back());
to_step();
for (Texture* t : wide) t->last_frame = frame_no;
CHECK(step().size() == 2);
to_step();
for (Texture* t : wide) t->last_frame = frame_no;
CHECK(step().size() == 1);
// one no step can take (9 MB of storage over 3 MB of texels: ripe, armed, never written back) listed before a tile: the
// list passes over it and takes the tile; it stays listed. The walk of the whole cache (=all, =check, the knob) stops
// at it, as before: a tile after it in the cache waits
Texture* huge = make(3ull << 20);
huge->guest_size = 9ull << 20;
written(huge);
Texture* after = make();
written(after);
to_step(), huge->last_frame = after->last_frame = frame_no;
CHECK(step() == std::set<uint32_t>{after->id} && huge->wb_listed);
Texture* after2 = make();
written(after2);
to_step(), huge->last_frame = after2->last_frame = frame_no;
CHECK(step(true, true).empty() && after2->wb_listed);
to_step(), huge->last_frame = after2->last_frame = frame_no;
CHECK(step() == std::set<uint32_t>{after2->id} && huge->wb_listed);
destroy(huge);
// a script of random events over 40 textures, 4000 presents: the list's step and the whole walk's agree throughout
std::vector<Texture*> pool;
for (int i = 0; i < 40; i++) pool.push_back(make(rnd(8) ? 64 << 10 : 5ull << 20));
uint64_t taken_n = 0;
for (int f = 0; f < 4000; f++) {
for (int e = 0; e < 6; e++) {
Texture*& t = pool[rnd(pool.size())];
switch (rnd(12)) {
case 0: case 1: written(t); break;
case 2: case 3: case 4: case 5: t->last_frame = frame_no; break;
case 6: if (!rnd(3)) t->released = true; break;
case 7: if (!t->gpu_written || t->released) t->only_cleared = true; break; // (vk_xfer.cpp: a clear of a fresh one)
case 8: if (t->wb_written) t->wb_written = 0, note(t); break; // (the copy lost)
case 9: if (!rnd(4)) t->gpu_written = false; break;
case 10: if (!rnd(6)) destroy(t), t = make(); break;
default: if (!rnd(3)) written(t), present(), written(t); break; // (drawn in two frames)
}
}
for (Texture* t : targets) written(t);
present();
if (frame_no % 4 == 0) taken_n += step(rnd(5) != 0).size();
}
CHECK(taken_n > 100); // (the script does reach the step's copies)
CHECK(bake_list.size() <= textures.size());
const size_t listed_end = bake_list.size(), cache_end = textures.size();
// RX_VK_BAKE_WRITEBACK=0 or RX_VK_BAKE_SCAN=all: no list (nothing reads it). A hundred targets drawn every frame and a
// tile leave it empty, and the walk of the whole cache still takes the tile
while (!textures.empty()) destroy(textures.back().get());
CHECK(bake_list.size() == 0);
const uint64_t added = bake_list.added.load();
for (bool writeback : {false, true}) {
list_kept = kept(writeback, writeback ? kAll : kList);
targets.clear();
for (int i = 0; i < 100; i++) targets.push_back(make());
Texture* lone = make();
written(lone);
to_step(), lone->last_frame = frame_no;
CHECK(bake_list.size() == 0 && !lone->wb_listed && bake_list.added.load() == added);
if (writeback) CHECK(step(true, true) == std::set<uint32_t>{lone->id});
while (!textures.empty()) destroy(textures.back().get());
}
if (!fails) std::printf("ok: %llu taken in the script, %zu listed of %zu at its end\n", (unsigned long long)taken_n,
listed_end, cache_end);
return fails != 0;
}
"""
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--cxx", default="clang++")
args = parser.parse_args()
head = VK / "bakescan.h"
check(head.exists(), "gpu/vk/bakescan.h is missing: the bake write-back's scan has no list (it walks the whole texture cache)")
tex = (VK / "vk_texture.cpp").read_text(encoding="utf-8").replace("\r\n", "\n")
check('#include "bakescan.h"' in tex, "vk_texture.cpp does not use the rule")
# the list is told wherever a texture can become one the step takes, where the list is kept
written = block(tex, "void texture_written(Texture* tex, const char* why) {")
at = 0
first = written.find("tex->last_written = frame_no;")
for part in ("tex->last_written = frame_no;", "tex->gpu_written = true;", "tex->released = false;",
"bake_list_note(tex);"):
at = written.find(part, at)
check(at >= 0, "texture_written does not tell the bake list after its writes (missing, or out of order: " + part + ")")
at += len(part)
seg = re.sub(r"//[^\n]*", "", written[first:at])
check(not re.search(r"\b(?:return|goto|throw)\b", seg),
"texture_written can leave between the writes the bake list's rule reads and the list's note: a texture armed and "
"not listed")
check(flat(written[at:]) == "}", "texture_written: the bake list's note is not its last statement")
# (and without a branch of its own there: the gate is in bake_list_note, so that texture_written's control flow, and
# with it its entry in the renderer's play profile, stays v0.8.4's. An if at the call put it at plain -O2)
check(re.search(r"\n bake_note_written\(tex\);[^\n]*\n bake_list_note\(tex\);[^\n]*\n\}\n$", written)
and "bake_list_kept" not in written,
"texture_written: the bake list's note is not an unconditional bake_list_note(tex) after bake_note_written: a "
"branch there changes the function's control flow, and the play profile no longer matches it")
# (every place that tells the list goes through bake_list_note, which asks first whether it is kept: not with
# RX_VK_BAKE_WRITEBACK=0, where nothing walks it, nor with RX_VK_BAKE_SCAN=all, the walk of the whole cache as before)
notes = [m.start() for m in re.finditer(r"\bbake_list\.note\(", tex)]
helper = tex.find("void bake_list_note(Texture* tex) {")
check(helper >= 0, "vk_texture.cpp has no bake_list_note, where the bake list is told")
helper_line = tex[helper:tex.index("\n", helper)]
check(len(notes) == 1 and helper < notes[0] < helper + len(helper_line),
"the bake list is told somewhere else than in bake_list_note (%d places)" % len(notes))
check(flat(helper_line) == "void bake_list_note(Texture* tex) { if (bake_list_kept()) bake_list.note(tex); }",
"bake_list_note does not ask bake_list_kept() before it tells the bake list: fed where nothing reads it")
calls = re.findall(r"\bbake_list_note\((?!Texture\*)", tex)
check(len(calls) == 4, "the places that tell the bake list are not texture_written's, the two lost copies' and the "
"check's (%d)" % len(calls))
check(flat(block(tex, "bool bake_list_kept() {")) ==
"bool bake_list_kept() { static const bool kept = bakescan::kept(bake_writeback_on(), bake_scan_mode()); "
"return kept; }",
"bake_list_kept() is not bakescan::kept of RX_VK_BAKE_WRITEBACK and RX_VK_BAKE_SCAN, read once")
check(re.fullmatch(r'bakescan::Mode bake_scan_mode\(\) \{ static const bakescan::Mode scan = \[\] \{ '
r'const bakescan::Mode m = bakescan::mode_of\(getenv\("RX_VK_BAKE_SCAN"\)\); '
r'if \(m != bakescan::kList && bake_writeback_on\(\)\) logf\([^;]*\); return m; \}\(\); return scan; \}',
flat(block(tex, "bakescan::Mode bake_scan_mode() {"))),
"bake_scan_mode() does not read RX_VK_BAKE_SCAN once and give that")
check(tex.find("bool bake_list_kept();") < tex.find("void bake_list_note(Texture* tex) {") <
tex.find("void texture_written(Texture* tex, const char* why) {"),
"bake_list_kept() and bake_list_note are not declared before texture_written")
forget = block(tex, "void forget_gpu(Texture* tex) {")
check("bake_forget(tex);" in forget, "forget_gpu does not take a destroyed texture off the bake list: a pointer to a freed one")
check(len(re.findall(r"\bforget_gpu\(", tex)) == 2 and tex.count("textures.erase(") == 1,
"a texture leaves the cache somewhere else than texture_sweep's forget_gpu: the bake list must be told there too")
# (the fields the rule's armed() reads: written in texture_written alone, but gpu_written = false (not armed any more:
# the step drops it); wb_written set to last_written or, back to 0, with the list told in the next statement. The
# headers too)
n_wb0 = 0
for path in sorted(VK.glob("*.cpp")) + sorted(VK.glob("*.h")):
src = path.read_text(encoding="utf-8", errors="replace").replace("\r\n", "\n")
inside = written if path.name == "vk_texture.cpp" else ""
for m in re.finditer(r"(?:->|\.)(last_written|first_written|wb_written|gpu_written)\s*=(?!=)\s*([^,;]+)", src):
field, value = m.group(1), m.group(2).strip()
line = src[src.rfind("\n", 0, m.start()) + 1:src.find("\n", m.end())]
where = "%s: %s" % (path.name, line.strip())
lhs = src[max(0, m.start() - 16):m.end(1)]
if field == "gpu_written":
if value == "false":
continue # (not armed any more: the step drops it)
if path.name == "vk_memory.cpp" and re.search(r"(?<![\w.>])(?:p->|p\.|o->second\.)gpu_written$", lhs):
continue # (a pool's field of that name)
if path.name == "vk_texture.cpp" and re.search(r"(?<![\w.>])s\.gpu_written$", lhs) and value == "t.gpu_written":
continue # (a snapshot of another type)
if field == "wb_written":
if value == "0":
n_wb0 += 1
check(re.match(r"[^;]*;\s*bake_list_note\(t\);", src[m.end():]),
"a copy lost puts wb_written back to 0 without telling the bake list next: " + where)
else:
check(value.endswith("last_written"), "wb_written is given something else than last_written: " + where)
else:
check(line in inside, "a field the bake list's rule reads is written outside texture_written: " + where)
check(n_wb0 == 2, "the places a copy is lost (wb_written = 0) are not the two of bake_writeback_step (%d)" % n_wb0)
# the step: the list unless the switch or the lab knob says the whole cache; check mode counts; the status line
step = block(tex, "void bake_writeback_step(uint64_t completed) {")
for part in ("const bakescan::Mode scan = bake_scan_mode();",
'const bool whole = scan != bakescan::kList || lab_ab::on("nobakescan");', "bake_list.settle(listed);",
"bakescan::armed(t->gpu_written, t->first_written, t->last_written, t->wb_written)",
"bakescan::ripe(t->released, t->only_cleared, t->last_written, t->last_frame, t->bytes, t->gpu, frame_no)",
"st_scan_missed"):
check(part in step, "bake_writeback_step: missing " + part)
check(re.search(r"if \(whole\) \{\s*st_scan_all\.fetch_add\(1[^;]*;\s*for \(auto& kv : textures\)\s*"
r"if \(!take\(kv\.second\.get\(\)\)\) break;\s*\} else \{", step),
"bake_writeback_step: RX_VK_BAKE_SCAN=all / check and the knob nobakescan do not walk the whole cache as before")
check(re.search(r"for \(Texture\* t : listed\) \{\s*looked\+\+;\s*if \(!take\(t\)\) break;\s*\}\s*"
r"st_scan_looked\.fetch_add\(looked", step),
"bake_writeback_step: the list's walk, or its count of what it looked at, is not the one checked here")
# (in the list, one no step can take is passed over before the caps' stop; the walk of the whole cache stops at it)
skip = "if (!whole && !bakescan::room(0, 0, t->guest_size)) return true;"
cap = "if (!bakescan::room(nb.items.size(), bytes, t->guest_size)) return false;"
check(skip in step and cap in step and step.index(skip) < step.index(cap),
"bake_writeback_step: a texture no step can take stops every newer one in the list (or the walk of the whole "
"cache passes over it, unlike before)")
# (check mode lists what it counted: each miss counted and logged once)
chk = step[step.index("if (scan == bakescan::kCheck)"):step.index("BakeBatch nb;")]
check(chk.index("st_scan_missed.fetch_add(") < chk.index("bake_list_note(t);"),
"RX_VK_BAKE_SCAN=check counts the same missed texture again at every step")
# (the scan's line on its own, every 600 presents, after the step's settle: not only when something was written back)
at = step.index('"vk: the bake write-back\'s scan: ')
check(step[:at].rstrip().endswith("if (frame_no % 600 == 0)\n logf(") and at > step.index("bake_list.settle(listed);"),
"bake_writeback_step: the scan's line is not printed on its own every 600 presents after the settle")
# (its listed count is the settle's copy: the list's size after the step's copies still held the textures it had just
# taken, which are armed no more and which the next settle drops)
scan_line = step[at:step.index(");\n", at)]
check("%zu listed at this step" in scan_line and "listed.size()" in scan_line and "bake_list.size()" not in scan_line,
"bake_writeback_step: the scan's line counts the list after the step's copies (those it just took included), "
"not what the step's settle kept")
check("bool wb_listed = false;" in (VK / "vk_texture.h").read_text(encoding="utf-8"), "vk_texture.h: Texture has no wb_listed")
dev = (ROOT / "docs" / "development.md").read_text(encoding="utf-8")
check("`RX_VK_BAKE_SCAN=all`" in dev and "nobakescan" in dev, "docs/development.md: RX_VK_BAKE_SCAN is not in the switches table")
row = next((l for l in dev.splitlines() if l.startswith("| `RX_VK_BAKE_SCAN=")), "")
for part in ("`RX_VK_BAKE_SCAN=all` (or `0`)", "`all` or `0`: the walk of the whole cache, and no list, as before",
"`RX_VK_BAKE_WRITEBACK=0` there is no list", "counted and logged, each once", "not released nor only cleared",
"one no step can take", "\"the bake write-back's scan: by the list at N steps",
"so the same textures are taken, but for those the walk does not reach behind such a one"):
check(part in row, "docs/development.md: the RX_VK_BAKE_SCAN row does not say " + part)
check("The same textures are taken;" not in row, "docs/development.md: the RX_VK_BAKE_SCAN row says the same textures "
"are taken, where the list also takes those the walk does not reach behind one no step can take")
with tempfile.TemporaryDirectory(prefix="bakescan-") as tmp:
c, exe = Path(tmp) / "scan.cpp", Path(tmp) / "scan.exe"
c.write_text(FIXTURE, encoding="utf-8")
subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Wno-unused-function", "-Wno-unused-variable", "-Werror",
"-I" + str(VK), str(c), "-o", str(exe)], check=True)
r = subprocess.run([str(exe)], capture_output=True, text=True)
check(r.returncode == 0, "the list against the walk of the whole cache:\n" + r.stdout)
print("PASS: the bake write-back's scan walks its list, and takes what the walk of the whole cache took")
if __name__ == "__main__":
main()

146
tests/test_bench_pan.py Normal file
View File

@@ -0,0 +1,146 @@
"""(Triforce, 11-26) The benchmark's camera turn as a measurement switch (host/hos_bench.c HOS_BENCH_PAN). No game, no GPU:
the source is read, and bench_pan is cut out of it and compiled with a C compiler.
- HOS_BENCH_PAN=<percent> is read once at the benchmark's start into B.pan. bench_pan, compiled, gives PAN (the right stick
at 35%) unset or empty, and for a value that is not a number (nan too) or outside 0-100, which it marks rejected; the
leading number counts (35% is 35), rounded up as PAN is, so 35 gives PAN;
- exactly two places push the stick, one in the settling and one in the measuring, and both push B.pan; the boot and the
travel push none;
- when the variable is set, the push in force is logged once (a rejected value too) and the results have "pan";
- docs/development.md has the row, under "Time and profiles", with HOS_BENCH_SCENES' form and the default scenes, which
are the source's.
python -I -B tests/test_bench_pan.py [--cc clang]
"""
import argparse
import os
import re
import subprocess
import tempfile
from pathlib import Path
RUN_ALL_ARGS = ["--cc", "clang"]
ROOT = Path(__file__).resolve().parents[1]
PAN = 11469
# bench_pan cut from the source, given each value of stdin's lines (unset first): the push and whether it was rejected
HARNESS = r"""
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PAN %(pan)d
%(bench_pan)s
int main(void) {
char line[256];
int rejected = -1, pan = bench_pan(NULL, &rejected);
printf("%%d %%d\n", pan, rejected);
while (fgets(line, sizeof line, stdin)) {
line[strcspn(line, "\r\n")] = 0;
rejected = -1, pan = bench_pan(line, &rejected);
printf("%%d %%d\n", pan, rejected);
}
return 0;
}
"""
# (HOS_BENCH_PAN's value, the push, rejected)
CASES = [
("", PAN, 0),
(" ", PAN, 1), ("x", PAN, 1), ("off", PAN, 1), ('"0"', PAN, 1),
("-1", PAN, 1), ("101", PAN, 1), ("100.5", PAN, 1), ("inf", PAN, 1), ("-inf", PAN, 1),
("nan", PAN, 1), ("-nan", PAN, 1), ("NAN", PAN, 1), ("nan(1)", PAN, 1),
("0", 0, 0), ("-0", 0, 0), ("100", 32767, 0), ("35", PAN, 0), ("35%", PAN, 0), (" 35", PAN, 0),
("50", 16384, 0), ("10", 3277, 0), ("0.5", 164, 0),
]
def check(ok, what):
if not ok:
raise SystemExit("FAIL: " + what)
def function(text, head):
start = text.find(head)
check(start >= 0, "%s is missing" % head.rstrip(" {("))
return text[start:text.index("\n}\n", start) + 3]
def compiled(cc, parse):
"""[(push, rejected)] for unset, then for each of CASES"""
flags = subprocess.CREATE_NO_WINDOW | subprocess.BELOW_NORMAL_PRIORITY_CLASS if os.name == "nt" else 0
with tempfile.TemporaryDirectory(prefix="bench-pan-") as tmp:
src, exe = Path(tmp) / "bench_pan.c", Path(tmp) / "bench_pan.exe"
src.write_text(HARNESS % {"pan": PAN, "bench_pan": parse}, encoding="utf-8")
build = subprocess.run([cc, "-std=gnu11", "-O2", "-Wall", "-Wextra", "-Werror", str(src), "-o", str(exe), "-lm"],
creationflags=flags, capture_output=True, text=True, timeout=120)
check(build.returncode == 0, "bench_pan does not compile:\n" + build.stdout + build.stderr)
run = subprocess.run([str(exe)], input="".join(v + "\n" for v, _, _ in CASES), creationflags=flags,
capture_output=True, text=True, timeout=60)
check(run.returncode == 0, "the bench_pan harness failed:\n" + run.stderr)
return [tuple(int(x) for x in line.split()) for line in run.stdout.splitlines()]
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cc", default="clang")
args = parser.parse_args()
src = (ROOT / "host" / "hos_bench.c").read_text(encoding="utf-8")
pan = re.search(r"#define PAN (\d+)", src)
check(pan and int(pan.group(1)) == PAN, "PAN is the right stick at 35% (11469)")
parse = function(src, "static int bench_pan(const char *e, int *rejected) {")
got = compiled(args.cc, parse)
want = [(PAN, 0)] + [(p, r) for _, p, r in CASES]
check(len(got) == len(want), "the harness printed %d results for %d values" % (len(got), len(want)))
bad = ["%s: %s, not %s" % (v, g, w) for v, g, w in zip(["(unset)"] + [repr(c[0]) for c in CASES], got, want) if g != w]
check(not bad, "bench_pan (push, rejected):\n " + "\n ".join(bad))
init = function(src, "void hos_bench_init(void) {")
for s in ('const char *pan = getenv("HOS_BENCH_PAN");', "B.pan = bench_pan(pan, &B.pan_rejected);",
"B.pan_set = pan && *pan;"):
check(s in init, "hos_bench_init: %r" % s)
check(init.find("B.pan_set =") < init.find("B.on = 1;"), "B.pan is set before the benchmark turns on")
check('"1001:Hyrule Field,1003:Castle Town Market,1000:Kokiri Forest,1007:Lake Hylia"' in init,
"the default scenes are the four the docs row names")
check("int pan;" in src and "int pan_set, pan_rejected;" in src, "the benchmark's state has pan, pan_set, pan_rejected")
# every push: the prototype aside, two, each of B.pan; in the present, one in the settling and one in the measuring
pushes = [a for a in re.findall(r"\bhos_hid_stick\(([^;]*)\);", src) if "int lx" not in a]
check(len(pushes) == 2, "two stick pushes (settling, measuring), found %d: %s" % (len(pushes), pushes))
check(all([x.strip() for x in a.split(",")][2] == "B.pan" for a in pushes), "every stick push uses B.pan, found %s" % pushes)
present = function(src, "void hos_bench_present(int64_t now) {")
marks = ["case MKWVK_BENCH_BOOT:", "case MKWVK_BENCH_TRAVEL:", "case MKWVK_BENCH_SETTLE:", "case MKWVK_BENCH_MEASURE:",
"default:"]
at = [present.find(m) for m in marks]
check(all(i >= 0 for i in at) and at == sorted(at), "hos_bench_present has its phases in order: %s" % marks)
for (a, b), n in zip(zip(at, at[1:]), (0, 0, 1, 1)):
found = present[a:b].count("hos_hid_stick(")
check(found == n, "%s pushes the stick %d times, not %d" % (present[a:a + 40].split(":")[0], found, n))
# the push in force, once with the start's line when the variable is set; and the results' "pan"
told = present[present.find("if (!told) {"):present.find("switch (B.phase)")]
check("if (B.pan_set) {" in told, "the start's line is followed by the push when HOS_BENCH_PAN is set")
for s in ('"benchmark: HOS_BENCH_PAN=%.40s is not a percent from 0 to 100: the right stick at 35%%, as unset"',
'"benchmark: HOS_BENCH_PAN=%.40s: the right stick at %.2f%% (%d of 32767)"'):
check(s in told, "the start logs %s" % s)
results = function(src, "static void write_results(int stopped) {")
check(r'if (B.pan_set) fprintf(f, ",\"pan\":%.2f", B.pan * 100.0 / 32767.0);' in results,
'the results have "pan" when HOS_BENCH_PAN is set')
docs = (ROOT / "docs" / "development.md").read_text(encoding="utf-8")
row = docs.find("| `HOS_BENCH_PAN=<percent>` |")
check(row >= 0, "docs/development.md has the HOS_BENCH_PAN row")
check(docs.find("### Time and profiles") < row < docs.find("### The GPU"), "the row is under Time and profiles")
text = docs[row:docs.index("\n", row)]
for s in ("`HOS_BENCHMARK=<results.json>`", "`HOS_BENCH_SECONDS`", "`HOS_BENCH_SCENES=<action>:<name>,...`",
"unset: Hyrule Field, the Market, Kokiri Forest and Lake Hylia", "one view per scene",
"about 18 s at Camera speed 100", "dead zone", "not a number (`nan` too)", "`benchmark: HOS_BENCH_PAN=`", '`"pan"`'):
check(s in text, "the HOS_BENCH_PAN row says %s" % s)
print("ok: HOS_BENCH_PAN")
if __name__ == "__main__":
main()

483
tests/test_bindspan.py Normal file
View File

@@ -0,0 +1,483 @@
"""A read binding answered from a span of its pool's mirror (gpu/vk/bindspan.h; vk_memory.cpp gpu_buffer_bind; no game,
no GPU).
(Triforce, 11-26, the GPU pass on v0.8.3, C08.) A read binding the memo does not know took the lock-free path at every
draw: the thread's pool table, the pool's fields, an add on Pool::binds, the resident pieces' walk, to find the mirror
the binding before it in the same pool found. The thread now keeps a few spans of guest addresses, each filled by a
binding that path gave the mirror, and a later binding inside one under the same key is given the mirror at once.
Compiles a driver against the header:
- the switch's three values, and any other value as unset; the bindings that never use a span (written, no bytes, outside a submission's uploads,
the three diagnostics / modes that act at every binding);
- a hit inside a span; a miss for a range that crosses its end, for no bytes, for a size that would wrap; a miss after
the stamp, the pool table's generation, the segment, the recording or the imports left overlapping move;
- a hit =check resolves the whole way too is counted as neither a span's answer nor a binding to fold;
- the counted hits are folded into the pool exactly once, when the span is replaced or the key moves, and dropped
(never folded) when the pool table's generation moved;
- eight spans: four pools bound in turn all hit; a ninth pool replaces one, the others stand;
- a mirror in pieces: the span is the run of resident pieces around the binding, cut at the pool's end, never past a
piece without memory, at most kRunMost pieces further each way;
- a model: random pools, whole and in pieces, random bindings; every hit is a binding the whole path's own tests
(the pool's bounds, every piece resident) give the mirror, at the same offset.
Compiles vk_memory.cpp's own bind_span_fill and pools_flag_overlapping (cut from the source; the pool table and the
thread's spans stubbed): an import made beside another (pool_lookup's plan past 1 GB, as in a v0.8.4 log) flags both
and moves the spans' generation once, one beside two flags all three, one beside none flags nothing, an import inside a
larger one and wholly below the new one's start is passed over and the larger one flagged; no span is filled for a
flagged import, one is for an import apart.
Reads the source:
- gpu_buffer_bind: cap_excl_note (not again for =check's whole way), the 1 TB translation, late_deferred_bound and
the memo come before the span; the span before the pool table and the lock; the rule's arguments; the key; the
thread's counts taken at every question; a hit goes into the memo; a span is filled only where the lock-free
path returns the mirror; =check resolves the whole way and returns that;
- RX_VK_BIND_SPAN read once, logged when not the default; the lab's knob read once a submission, in
memory_begin_submission, and no lab question at a binding; the status line, not without mirrors;
- pool_lookup flags an import its plan left overlapping, after the import is in the table;
- what the key relies on: every pieces_set_direct call is followed by a move of pools_gen, a mirror freed moves it,
mirror_upload goes on only with a new mirror_epoch, and mirror_sync is only called where a sync is due;
- the switches table has the row.
python -I -B tests/test_bindspan.py [--cxx clang++]
"""
import argparse
import re
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 as cut_block # noqa: E402
ROOT = Path(__file__).resolve().parents[1]
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
DRIVER = r'''
#include "bindspan.h"
#include <cstdio>
#include <map>
#include <vector>
using namespace mkwvk::bindspan;
static int checks, fails;
static void want(const char* what, bool ok) {
checks++;
if (!ok) fails++, printf("FAIL %s\n", what);
}
struct P { // (a pool, as far as the lock-free path looks at it)
uint64_t lo, hi;
bool pieces;
uint32_t shift;
std::vector<uint64_t> bits;
};
using S = Set<int, P*>;
static std::map<P*, uint32_t> folded;
static int folds;
static const auto fold = [](P* p, uint32_t n) { folded[p] += n, folds++; };
// (vk_memory.cpp pieces_resident, bit by bit)
static bool resident(const P& p, uint64_t off, uint64_t size) {
if (!p.pieces || !size) return true;
for (uint64_t i = off >> p.shift, e = (off + size - 1) >> p.shift; i <= e; i++)
if (!((p.bits[i >> 6] >> (i & 63)) & 1)) return false;
return true;
}
static uint64_t rnd_state = 0x1234567887654321ull;
static uint64_t rnd() {
rnd_state ^= rnd_state << 13, rnd_state ^= rnd_state >> 7, rnd_state ^= rnd_state << 17;
return rnd_state;
}
int main() {
want("the switch: on unless set, 0 off, check", mode(nullptr) == kOn && mode("1") == kOn && mode("0") == kOff && mode("check") == kCheck);
want("any other value, empty included: on, as unset", mode("") == kOn && mode("on") == kOn && mode("true") == kOn &&
mode("2") == kOn && mode("Check") == kOn);
want("a read binding of bytes within a submission's uploads may use a span", eligible(false, 64, true, false, false, false));
want("a written binding never", !eligible(true, 64, true, false, false, false));
want("a binding of no bytes never", !eligible(false, 0, true, false, false, false));
want("outside a submission's uploads (or without mirrors) never", !eligible(false, 64, false, false, false, false));
want("RX_VK_LOG_MIRROR_USE: never", !eligible(false, 64, true, true, false, false));
want("RX_VK_MIRROR_HEAT: never", !eligible(false, 64, true, false, true, false));
want("RX_VK_MIRROR_PIECE_IDLE: never", !eligible(false, 64, true, false, false, true));
want("inside", inside(0x1000, 0x2000, 0x1000, 0x1000) && inside(0x1000, 0x2000, 0x1ff0, 16) && inside(0x1000, 0x2000, 0x1800, 1));
want("crossing the end", !inside(0x1000, 0x2000, 0x1ff0, 17) && !inside(0x1000, 0x2000, 0x2000, 1));
want("before the start", !inside(0x1000, 0x2000, 0xfff, 2));
want("no bytes", !inside(0x1000, 0x2000, 0x1800, 0));
want("no wrap-around for a huge size", !inside(0x1000, 0x2000, 0x1800, ~0ull) && !inside(0x1000, 0x2000, 0x1800, ~0ull - 0x17ff));
{ // a hit, and what ends it
S s;
P a{0x10000, 0x20000, false, 0, {}};
const Key k{7, 3, 0, 100};
want("nothing before a fill", !s.find(k, 0x10040, 64));
s.fill(k, a.lo, a.hi, a.lo, 11, &a, fold);
S::Span* h = s.find(k, 0x10040, 64);
want("a hit inside the span", h && h->buffer == 11 && h->base == a.lo && h->pool == &a);
want("a range crossing the span's end misses", !s.find(k, 0x1ffc0, 65));
want("a range outside misses", !s.find(k, 0x20000, 64) && !s.find(k, 0xffc0, 64));
want("the stamp moved: a miss", !s.find(Key{8, 3, 0, 100}, 0x10040, 64));
want("the pool table's generation moved: a miss", !s.find(Key{7, 4, 0, 100}, 0x10040, 64));
want("an earlier or later segment: a miss", !s.find(Key{7, 3, 1, 100}, 0x10040, 64));
want("the next recording: a miss", !s.find(Key{7, 3, 0, 101}, 0x10040, 64));
want("the key again: a hit again", s.find(k, 0x10040, 64) != nullptr);
uint64_t hits = 7, misses = 7, fills = 7;
want("the thread's counts stay its own for a while", !s.take_counts(&hits, &misses, &fills) && hits == 7 && s.hits == 2 && s.misses == 8 && s.fills == 1);
for (uint64_t i = 0; i < kTakeAt; i++) s.find(k, 0x10040, 64);
want("taken once they are worth it", s.take_counts(&hits, &misses, &fills) && hits == 2 + kTakeAt && misses == 8 && fills == 1);
want("taken once", !s.take_counts(&hits, &misses, &fills) && s.hits == 0 && s.misses == 0 && s.fills == 0);
want("imports left overlapping: a miss", !s.find(Key{7, 3, 0, 100, 1}, 0x10040, 64));
S::Span* c = s.find(k, 0x10040, 64);
const uint32_t pending = c ? c->pending : 0;
if (c) s.checked(c);
want("a checked hit is neither a span's answer nor a binding to fold", c && s.hits == 0 && c->pending == pending - 1);
}
{ // the counted hits: folded once, at a key move with the pools standing
S s;
P a{0x10000, 0x20000, false, 0, {}}, b{0x40000, 0x50000, false, 0, {}};
folded.clear(), folds = 0;
const Key k{7, 3, 0, 100};
s.fill(k, a.lo, a.hi, a.lo, 11, &a, fold);
s.fill(k, b.lo, b.hi, b.lo, 12, &b, fold);
for (int i = 0; i < 5; i++) s.find(k, a.lo + 64 * (uint64_t)i, 64);
for (int i = 0; i < 3; i++) s.find(k, b.lo + 64 * (uint64_t)i, 64);
want("nothing folded at a hit", folds == 0);
const Key k2{9, 3, 0, 101}; // (the next submission, the same pools)
s.fill(k2, a.lo, a.hi, a.lo, 11, &a, fold);
want("folded at the key's move: as many as the hits", folded[&a] == 5 && folded[&b] == 3 && folds == 2);
want("the set is the new key's alone", s.n == 1 && !s.find(k2, b.lo, 64) && s.find(k2, a.lo, 64));
s.fill(k2, b.lo, b.hi, b.lo, 12, &b, fold);
want("a second fill folds nothing twice", folded[&a] == 5 && folded[&b] == 3);
s.fill(k2, a.lo, a.hi, a.lo, 11, &a, fold); // (its span filled again: its one hit folded now)
want("a span filled again folds its hits and stays one span", folded[&a] == 6 && s.n == 2);
}
{ // dropped when the pool table's generation moved: a pool may be gone
S s;
P a{0x10000, 0x20000, false, 0, {}}, b{0x40000, 0x50000, false, 0, {}};
folded.clear(), folds = 0;
const Key k{7, 3, 0, 100};
s.fill(k, a.lo, a.hi, a.lo, 11, &a, fold);
for (int i = 0; i < 9; i++) s.find(k, a.lo, 64);
const Key k2{7 ^ 1, 4, 0, 100};
s.fill(k2, b.lo, b.hi, b.lo, 12, &b, fold);
want("pools_gen moved: the hits are dropped, no pool written", folds == 0);
for (int i = 0; i < 20; i++) { // (and never come back through a slot used again)
P* q = i % 2 ? &a : &b;
s.fill(Key{100 + (uint64_t)i, 4, 0, 100}, q->lo, q->hi, q->lo, 1, q, fold);
}
want("dropped hits never folded later", folds == 0);
}
{ // eight spans
S s;
std::vector<P> pools;
for (uint64_t i = 0; i < 9; i++) pools.push_back(P{0x100000 * (i + 1), 0x100000 * (i + 1) + 0x10000, false, 0, {}});
folded.clear(), folds = 0;
const Key k{7, 3, 0, 100};
for (int i = 0; i < 4; i++) s.fill(k, pools[i].lo, pools[i].hi, pools[i].lo, i, &pools[i], fold);
bool all = true;
for (int r = 0; r < 100; r++)
for (int i = 0; i < 4; i++) {
S::Span* h = s.find(k, pools[i].lo + 16 * (uint64_t)r, 128);
all = all && h && h->buffer == i && h->base == pools[i].lo;
}
want("four pools bound in turn all hit", all);
for (int i = 4; i < 9; i++) s.fill(k, pools[i].lo, pools[i].hi, pools[i].lo, i, &pools[i], fold);
int held = 0;
for (int i = 0; i < 9; i++) held += s.find(k, pools[i].lo, 64) != nullptr;
want("a ninth pool replaces one span, eight stand", s.n == kSpans && held == 8 && s.find(k, pools[8].lo, 64));
want("the replaced span's hits were folded", folds == 1);
}
{ // a mirror in pieces: the resident run
const uint32_t shift = 18; // (256 KB)
const uint64_t piece = 1ull << shift, lo = 0x40000000ull;
P p{lo, lo + 10 * piece + 0x1234, true, shift, {0}}; // (11 pieces, the last one short)
for (int i : {2, 3, 4, 6, 9, 10}) p.bits[0] |= 1ull << i;
uint64_t a = 0, b = 0;
bounds(p.lo, p.hi, 3 * piece + 100, 64, p.bits.data(), p.bits.size(), shift, &a, &b);
want("the run around a binding in piece 3 is pieces 2 to 4", a == lo + 2 * piece && b == lo + 5 * piece);
bounds(p.lo, p.hi, 2 * piece + 100, 2 * piece, p.bits.data(), p.bits.size(), shift, &a, &b);
want("a binding over pieces 2 to 4: the same run", a == lo + 2 * piece && b == lo + 5 * piece);
bounds(p.lo, p.hi, 6 * piece, 64, p.bits.data(), p.bits.size(), shift, &a, &b);
want("a lone resident piece: itself", a == lo + 6 * piece && b == lo + 7 * piece);
bounds(p.lo, p.hi, 10 * piece, 64, p.bits.data(), p.bits.size(), shift, &a, &b);
want("the pool's last, short piece: cut at the pool's end", a == lo + 9 * piece && b == p.hi);
bounds(p.lo, p.hi, 3 * piece, 64, nullptr, 0, 0, &a, &b);
want("a whole mirror: the pool", a == p.lo && b == p.hi);
S s;
const Key k{7, 3, 0, 100};
bounds(p.lo, p.hi, 3 * piece + 100, 64, p.bits.data(), p.bits.size(), shift, &a, &b);
s.fill(k, a, b, p.lo, 5, &p, fold);
want("inside the run: a hit", s.find(k, lo + 4 * piece + 8, 64) != nullptr);
want("reaching into a piece without memory: a miss", !s.find(k, lo + 5 * piece - 8, 64) && !s.find(k, lo + 2 * piece - 1, 2));
want("a piece with memory beyond a gap is not this span's", !s.find(k, lo + 6 * piece, 64));
// (a long run: no further than kRunMost pieces each way)
P big{lo, lo + 512 * piece, true, shift, std::vector<uint64_t>(8, ~0ull)};
bounds(big.lo, big.hi, 200 * piece, 64, big.bits.data(), big.bits.size(), shift, &a, &b);
want("at most kRunMost pieces further each way", a == lo + (200 - kRunMost) * piece && b == lo + (200 + kRunMost + 1) * piece);
uint64_t i0 = 0, i1 = 0;
resident_run(big.bits.data(), 512, 0, 0, &i0, &i1);
want("the run stops at piece 0", i0 == 0 && i1 == kRunMost);
resident_run(big.bits.data(), 512, 511, 511, &i0, &i1);
want("and at the pool's last piece", i0 == 511 - kRunMost && i1 == 511);
}
{ // the model: a hit is always a binding the whole path gives the mirror, at the same offset
const uint32_t shift = 12;
std::vector<P> pools;
for (uint64_t i = 0; i < 12; i++) {
P p{0x1000000 * (i + 1), 0x1000000 * (i + 1) + 0x40000 + (rnd() & 0xfff), i % 3 != 0, shift, {}};
const uint64_t n = (p.hi - p.lo + (1ull << shift) - 1) >> shift;
p.bits.assign((n + 63) / 64, 0);
for (uint64_t j = 0; j < n; j++)
if (rnd() % 8) p.bits[j >> 6] |= 1ull << (j & 63);
pools.push_back(p);
}
S s;
Key k{1, 1, 0, 1};
long hits = 0, fills = 0, wrong = 0;
for (int it = 0; it < 400000; it++) {
if (it % 5000 == 4999) k.stamp++, k.rec_value++; // (the next submission)
P& p = pools[rnd() % pools.size()];
const uint64_t size = 1 + rnd() % 3000;
const uint64_t guest = p.lo - 64 + rnd() % (p.hi - p.lo + 128);
const bool in_pool = guest >= p.lo && guest <= p.hi && size <= p.hi - guest;
const bool mirror = in_pool && resident(p, guest - p.lo, size);
if (S::Span* h = s.find(k, guest, size)) {
hits++;
if (!mirror || h->pool != &p || h->base != p.lo || h->buffer != (int)(&p - pools.data())) wrong++;
} else if (mirror) {
uint64_t a = 0, b = 0;
bounds(p.lo, p.hi, guest - p.lo, size, p.pieces ? p.bits.data() : nullptr, p.bits.size(), shift, &a, &b);
if (!inside(a, b, guest, size)) wrong++; // (its own binding is in its span)
s.fill(k, a, b, p.lo, (int)(&p - pools.data()), &p, fold);
fills++;
}
}
printf("model: %ld hits, %ld fills, %ld wrong\n", hits, fills, wrong);
want("the model: no hit the whole path would not give the mirror", wrong == 0 && hits > 1000 && fills > 100);
}
printf("%d checks, %d failed\n", checks, fails);
return fails != 0;
}
'''
OVERLAP_DRIVER = r'''
#include "bindspan.h"
#include <atomic>
#include <cstdio>
#include <map>
#include <vector>
using namespace mkwvk;
using VkBuffer = int;
struct Pool { // (as far as the two functions look at it)
uint64_t lo = 0, hi = 0;
VkBuffer mirror = 0;
uint32_t binds = 0, piece_shift = 0;
bool mpieces = false, left_overlapping = false;
std::vector<uint64_t> res_bits;
};
static std::map<uint64_t, Pool> imported;
static std::atomic<uint64_t> pools_overlap_gen{0};
static thread_local bindspan::Set<VkBuffer, Pool*> tl_bind_spans;
// (vk_memory.cpp's pools_flag_overlapping and bind_span_fill, cut from the source)
@CUT@
static int fails;
static void want(const char* what, bool ok) {
if (!ok) fails++, std::printf("FAIL %s\n", what);
}
static std::map<uint64_t, Pool>::iterator add(uint64_t lo, uint64_t hi, int mirror) {
Pool p;
p.lo = lo, p.hi = hi, p.mirror = mirror;
return imported.emplace(lo, p).first;
}
int main() {
// (a v0.8.4 log: the import 0x7f71000000..0x7f86000000 stood, a binding from 0x7f70f1bf00 planned 1040 MB, and
// 0x7f70000000..0x7f72000000 was made beside it)
auto q = add(0x7f71000000, 0x7f86000000, 1);
auto below = add(0x7f6e000000, 0x7f70000000, 2); // (ends where the new one starts: apart)
auto above = add(0x7f86000000, 0x7f88000000, 3); // (starts where q ends: apart from the new one)
auto far = add(0x7e00000000, 0x7e01000000, 4); // (more than 1 GB further down)
auto lone = add(0x7f40000000, 0x7f42000000, 5);
want("an import beside none flags nothing", pools_flag_overlapping(lone) == 0 && pools_overlap_gen.load() == 0 &&
!lone->second.left_overlapping);
auto n = add(0x7f70000000, 0x7f72000000, 6);
want("the import made beside another overlaps one", pools_flag_overlapping(n) == 1);
want("both are flagged", n->second.left_overlapping && q->second.left_overlapping);
want("the imports apart are not", !below->second.left_overlapping && !above->second.left_overlapping &&
!far->second.left_overlapping && !lone->second.left_overlapping);
want("the spans' generation moved once", pools_overlap_gen.load() == 1);
auto a = add(0x7f50000000, 0x7f52000000, 7), b = add(0x7f53000000, 0x7f55000000, 8);
auto mid = add(0x7f51000000, 0x7f54000000, 9);
want("one beside two flags all three", pools_flag_overlapping(mid) == 2 && mid->second.left_overlapping &&
a->second.left_overlapping && b->second.left_overlapping && pools_overlap_gen.load() == 2);
// (a small import inside a large one, wholly below the new import's start: passed over, and the large one, which
// starts further down and reaches into the new import, is still found)
auto outer = add(0x7f20000000, 0x7f30000000, 10), inner = add(0x7f21000000, 0x7f22000000, 11);
auto top = add(0x7f2f000000, 0x7f31000000, 12);
want("an import below the new one's start does not end the walk", pools_flag_overlapping(top) == 1 &&
top->second.left_overlapping && outer->second.left_overlapping && !inner->second.left_overlapping &&
pools_overlap_gen.load() == 3);
const bindspan::Key k{7, 3, 0, 100, pools_overlap_gen.load()};
bind_span_fill(k, &q->second, 0x100, 64);
bind_span_fill(k, &n->second, 0x100, 64);
want("no span for an import left overlapping, nor for the one beside it",
tl_bind_spans.n == 0 && !tl_bind_spans.find(k, 0x7f71000100, 64) && !tl_bind_spans.find(k, 0x7f70000100, 64));
bind_span_fill(k, &above->second, 0x100, 64);
want("a span for an import apart", tl_bind_spans.n == 1 && tl_bind_spans.find(k, 0x7f86000100, 64) != nullptr);
std::printf("%s\n", fails ? "overlapping imports: FAILED" : "overlapping imports: flagged, no span for either");
return fails != 0;
}
'''
def block(text, marker):
start = text.index(marker)
at = text.index("{", start) + 1
depth = 1
while depth:
depth += (text[at] == "{") - (text[at] == "}")
at += 1
return text[start:at]
def need(ok, why):
if not ok:
raise SystemExit("FAIL: " + why)
def ordered(text, parts, why):
last = 0
for p in parts:
k = text.find(p, last)
need(k >= 0, why + " (missing, or out of order: " + p + ")")
last = k + len(p)
def check_source():
mem = (ROOT / "gpu/vk/vk_memory.cpp").read_text(encoding="utf-8")
need('#include "bindspan.h"' in mem, "vk_memory.cpp does not include bindspan.h")
mode = block(mem, "static int bind_span_mode() {")
need('static const int m = [] {' in mode and 'const char* e = getenv("RX_VK_BIND_SPAN");' in mode and
"const int v = bindspan::mode(e);" in mode and "if (v != bindspan::kOn)" in mode and "(RX_VK_BIND_SPAN)" in mode,
"the switch is not RX_VK_BIND_SPAN read once and logged when it is not the default")
need('else if (e && e[0] && strcmp(e, "1"))' in mode and "RX_VK_BIND_SPAN=%s not known" in mode,
"an RX_VK_BIND_SPAN value other than 1, 0 or check is not logged")
need("static thread_local bindspan::Set<VkBuffer, Pool*> tl_bind_spans;" in mem, "the spans are not a thread's own")
bind = block(mem, "BufferRef gpu_buffer_bind(")
ordered(bind, ['if (cap_only_gpu() && !tl_bind_span_checking) cap_excl_note(gpu, size, "a buffer binding");',
"if (gpu >= (1ull << 40)) {", "late_deferred_bound(guest, size);",
"bind_memo_hit(guest, size, gpu_bind_stamp(),", "return m.ref;",
"const int span_mode = bind_span_mode();",
"const bool span_ok = span_mode != bindspan::kOff && !tl_bind_span_checking &&",
"bindspan::eligible(written, size, mirror_upload && mirror_on(), mirror_use_on(), mirror_heat_on(), piece_idle_for() != 0) &&",
"!bind_span_lab_off.load(std::memory_order_relaxed);",
"if (span_ok) {",
"span_key = {gpu_bind_stamp(), pools_gen.load(std::memory_order_relaxed), texture_segment(), mem_rec_value,\n"
" pools_overlap_gen.load(std::memory_order_acquire)};",
"bind_span_take();", "if (auto* s = tl_bind_spans.find(span_key, guest, size)) {",
"const BufferRef ref{s->buffer, guest - s->base, size, 0};",
"if (span_mode != bindspan::kCheck) return remember(ref);", "tl_bind_spans.checked(s);",
"tl_bind_span_checking = true;", "const BufferRef whole = gpu_buffer_bind(gpu, size, false);",
"tl_bind_span_checking = false;", "bind_span_checked(ref, whole, guest, span, span_key);", "return whole;",
"TlPool& tl = tl_pool_slot(guest);",
"if (p->last_value < mem_rec_value) p->last_value = mem_rec_value;",
"if (p->mstate == Pool::MIRROR_ON && p->synced_epoch == mirror_epoch && p->sync_seg <= texture_segment()) {",
"if (pieces_resident(p, off, size)) {", "if (span_ok) bind_span_fill(span_key, p, off, size);",
"return remember({p->mirror, off, size, 0});", "ParLock plk;"],
"gpu_buffer_bind does not ask the span after the memo and before the pool table, by the rule, or fill it only "
"where the lock-free path returns the mirror")
need(bind.count("bind_span_fill(") == 1 and bind.count("tl_bind_spans.") == 2, "a span is filled or asked somewhere else in gpu_buffer_bind")
need("lab_ab::on(" not in bind, "gpu_buffer_bind asks the lab at a binding: its string compares run in the knobs' phases alone")
begin = block(mem, "void memory_begin_submission() {")
ordered(begin, ["mirror_upload = true;", 'bind_span_lab_off.store(lab_ab::on("nobindspan"), std::memory_order_relaxed);'],
"the lab knob nobindspan is not read once a submission, where the uploads start")
need(mem.count("bind_span_lab_off.store(") == 1, "the lab knob's flag is written somewhere else too")
need(mem.count("bind_span_fill(") == 2 and mem.count("tl_bind_spans.find(") == 1, "a span is filled or asked outside gpu_buffer_bind")
fill = block(mem, "static void bind_span_fill(")
ordered(fill, ["if (__atomic_load_n(&p->left_overlapping, __ATOMIC_RELAXED)) return;", "if (pieces && p->res_bits.empty()) return;",
"bindspan::bounds(p->lo, p->hi, off, size, pieces ? p->res_bits.data() : nullptr, p->res_bits.size(), p->piece_shift, &lo, &hi);",
"tl_bind_spans.fill(key, lo, hi, p->lo, p->mirror, p,", "__atomic_fetch_add(&q->binds, n, __ATOMIC_RELAXED);"],
"a span is not the pool's or its resident run's, or its hits are not folded into Pool::binds")
need("if (!tl_bind_spans.take_counts(&h, &m, &f)) return;" in block(mem, "static void bind_span_take() {") and
mem.count("take_counts(") == 1, "the thread's counts are not taken in bind_span_take alone")
look = block(mem, "Pool* pool_lookup(uint64_t guest, uint64_t size) {")
ordered(look, ["bool left_overlapping = false;", "auto plan = [&](bool spanned) {", "left_overlapping = false;",
"if (hi - lo > (1ull << 30)) {", "left_overlapping = true;", "return padding_only;",
"imp = imported.emplace(p.lo, p).first;", "if (left_overlapping) pools_flag_overlapping(imp);"],
"pool_lookup does not flag an import its last plan left overlapping, after it is in the table")
need(mem.count("pools_flag_overlapping(") == 2 and mem.count("pools_overlap_gen.fetch_add(") == 1,
"imports are flagged, or the spans' generation moved, somewhere else too")
chk = block(mem, "static void bind_span_checked(")
need("span.buffer == whole.buffer && span.offset == whole.offset && span.size == whole.size && span.address == whole.address" in chk and
"st_span_diffs.fetch_add(1" in chk, "=check does not compare the whole result and count the differences")
report = block(mem, "static void bind_span_report() {")
need("if (mode == bindspan::kOff || !mirror_on()) return;" in report, "the status line is printed without mirrors, all zeros")
need("vk: bind spans (600 submits): %llu read bindings answered from a span, %llu the whole way past the memo" in report and
"%llu differed (RX_VK_BIND_SPAN=check)" in report, "the status line does not give the hits, the misses and =check's differences")
end = block(mem, "void memory_end_submission(VkCommandBuffer cmd) {")
ordered(end, ["if (++n % 600 == 0) {", "bind_span_report();"], "the status line is not in memory_end_submission's 600 submissions")
# what the key relies on
stamp = block(mem, "uint64_t gpu_bind_stamp() {")
need("pools_gen" in stamp and "mirror_epoch" in stamp, "the stamp no longer holds pools_gen and mirror_epoch")
calls = [m.start() for m in re.finditer(r"(?<![A-Za-z0-9_])pieces_set_direct\(", mem)]
need(len(calls) >= 7, "pieces_set_direct's callers were not found")
for at in calls:
if mem.startswith("void ", mem.rfind("\n", 0, at) + 1):
continue # (its definition)
need("pools_gen++" in mem[at:at + 1500],
"a pieces_set_direct call is not followed by a move of pools_gen: a span would keep a piece taken out of its mirror (line %d)"
% (mem.count("\n", 0, at) + 1))
free = block(mem, "void mirror_free(Pool& p")
need("p.mstate = Pool::MIRROR_NONE;\n pools_gen++;" in free, "a mirror freed does not move pools_gen")
need(mem.count("mirror_upload = true;") == 1 and "mirror_epoch++;\n mirror_upload = true;" in mem,
"mirror_upload goes on somewhere else than with a new mirror_epoch")
need(len(re.findall(r"(?<![A-Za-z0-9_])mirror_sync\(", mem)) == 3 and
"if (p->synced_epoch != mirror_epoch || p->sync_seg > texture_segment()) mirror_sync(*p);" in mem and
"if (p.mstate != Pool::MIRROR_ON || p.synced_epoch == mirror_epoch) continue;\n mirror_sync(p);\n p.sync_seg = 0;" in mem,
"mirror_sync is called where no sync is due: a pool's sync_seg could rise within a submission, under a span")
header = (ROOT / "gpu/vk/bindspan.h").read_text(encoding="utf-8")
for word in ("RX_VK_BIND_SPAN=0", "=check", '"nobindspan"', "(Triforce, 11-26", "mirror_upload", "last_value", "resident"):
need(word in header, "bindspan.h's comment no longer says: " + word)
docs = (ROOT / "docs/development.md").read_text(encoding="utf-8")
row = [line for line in docs.splitlines() if line.startswith("| `RX_VK_BIND_SPAN=0`")]
need(len(row) == 1 and "`gpu/vk/bindspan.h`" in row[0] and "`nobindspan`" in row[0] and "`check`" in row[0] and
"vk: bind spans (600 submits)" in row[0], "docs/development.md: the switches table has no RX_VK_BIND_SPAN row")
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--cxx", default="clang++")
args = parser.parse_args()
need((ROOT / "gpu/vk/bindspan.h").is_file(), "gpu/vk/bindspan.h is missing: read bindings have no span rule")
with tempfile.TemporaryDirectory(prefix="bindspan-") as tmp:
cpp, exe = Path(tmp) / "bindspan_test.cpp", Path(tmp) / "bindspan.exe"
cpp.write_text(DRIVER, encoding="utf-8")
subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-I" + str(ROOT / "gpu/vk"), str(cpp), "-o", str(exe)],
check=True)
r = subprocess.run([str(exe)], capture_output=True, text=True)
print(r.stdout.rstrip())
if r.returncode:
raise SystemExit("FAIL: the bind spans' checks failed")
mem = (ROOT / "gpu/vk/vk_memory.cpp").read_text(encoding="utf-8")
cut = "\n".join(cut_block(mem, m, where="gpu/vk/vk_memory.cpp") for m in (
"int pools_flag_overlapping(std::map<uint64_t, Pool>::iterator n) {", "static void bind_span_fill("))
cpp, exe = Path(tmp) / "bindspan_overlap.cpp", Path(tmp) / "bindspan_overlap.exe"
cpp.write_text(OVERLAP_DRIVER.replace("@CUT@", cut), encoding="utf-8")
subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-I" + str(ROOT / "gpu/vk"), str(cpp), "-o", str(exe)],
check=True)
r = subprocess.run([str(exe)], capture_output=True, text=True)
print(r.stdout.rstrip())
if r.returncode:
raise SystemExit("FAIL: vk_memory.cpp's bind_span_fill fills a span for an import left overlapping, or the flags are wrong")
check_source()
print("PASS: a read binding inside a span this thread resolved is given its pool's mirror at once; RX_VK_BIND_SPAN=0 as before, =check both ways")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,91 @@
"""Draws blended over the scene keep the camera's motion for the temporal upscalers (gpu/vk/vk_draw.cpp own_motion and
push_capture; no game).
(2026-11-26) The owner's "white lines": thin white rings and trails round the fireflies of Kokiri Forest under AMD FSR 4,
caught with F8 and F9. The frame's steps were clean up to the scene's last particle draw and the rings were there right
after the upscaler. Every plain draw of triangles into the scene was given a motion of its own (capture_motion), blended
particles among them, so the upscaler moved what is behind each sprite as the sprite moved. A blended draw now gets no
capture slot (the camera's motion stays its motion, as reactive_policy.h has its pixels); RX_VK_DLSS_BLENDED_MOTION=1 gives
them one again, for comparing. This compiles own_motion, cut out as it is, against made-up states, and reads push_capture.
python -I -B tests/test_blended_motion.py [--cxx clang++]
"""
import argparse
import subprocess
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
VK = ROOT / "gpu" / "vk"
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
def check(ok, why):
if not ok:
raise SystemExit("FAIL: " + why)
def function(text, head):
start = text.index(head)
end = text.index("{", start) + 1
depth = 1
while depth:
depth += (text[end] == "{") - (text[end] == "}")
end += 1
return text[start:end]
PROGRAM = r"""
#include <atomic>
#include <cstdio>
#include <cstdlib>
#include <cstring>
struct NvnState { struct { unsigned blend_en = 0; } color; };
static int logged = 0;
static void logf(const char*, ...) { logged++; }
%(own)s
int main(int argc, char**) {
int fails = 0;
NvnState opaque, blended, other;
blended.color.blend_en = 1, other.color.blend_en = 2; // (target 1 blending, target 0 not: target 0 is the scene's)
if (argc > 1) { // (RX_VK_DLSS_BLENDED_MOTION=1 set by the caller: all of them, as before)
if (!own_motion(opaque) || !own_motion(blended) || logged) std::puts("FAIL: the switch does not give blended draws their own"), fails++;
return fails;
}
if (!own_motion(opaque)) std::puts("FAIL: an opaque draw has no motion of its own"), fails++;
if (own_motion(blended)) std::puts("FAIL: a draw blended over the scene has a motion of its own"), fails++;
if (!own_motion(other)) std::puts("FAIL: a draw blending only another target is taken for a blended one"), fails++;
own_motion(blended);
if (logged != 1) std::printf("FAIL: said %%d times, not once\n", logged), fails++;
return fails;
}
"""
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cxx", default="clang++")
args = parser.parse_args()
draw = (VK / "vk_draw.cpp").read_text(encoding="utf-8")
own = function(draw, "static bool own_motion(const NvnState& s) {")
cap = function(draw, "static void push_capture(")
check("if (capture && own_motion(s) && !d.mesh && !d.indirect" in cap, "push_capture gives blended draws a capture slot")
check("temporal_capture_draw(k, &slot);" in cap, "push_capture no longer asks for a slot")
check(draw.index("static bool own_motion(") < draw.index("static void push_capture("), "own_motion is not before push_capture")
guide = (ROOT / "docs" / "development.md").read_text(encoding="utf-8")
check("`RX_VK_DLSS_BLENDED_MOTION=1`" in guide, "docs/development.md has no row for RX_VK_DLSS_BLENDED_MOTION")
with tempfile.TemporaryDirectory(prefix="blended-motion-") as tmp:
src, exe = Path(tmp) / "own.cpp", Path(tmp) / "own.exe"
src.write_text(PROGRAM % {"own": own}, encoding="utf-8")
subprocess.run([args.cxx, "-std=c++20", "-O1", "-w", str(src), "-o", str(exe)], check=True)
env = {k: v for k, v in __import__("os").environ.items() if k != "RX_VK_DLSS_BLENDED_MOTION"}
r = subprocess.run([str(exe)], capture_output=True, text=True, env=env)
check(r.returncode == 0, "own_motion:\n" + r.stdout)
env["RX_VK_DLSS_BLENDED_MOTION"] = "1"
r = subprocess.run([str(exe), "switch"], capture_output=True, text=True, env=env)
check(r.returncode == 0, "own_motion with RX_VK_DLSS_BLENDED_MOTION=1:\n" + r.stdout)
print("PASS: draws blended over the scene keep the camera's motion; the switch gives them their own")
if __name__ == "__main__":
main()

View File

@@ -77,11 +77,12 @@ int main(int argc, char** argv) {
p.asked = true; // (asked, the answer alone counts: a slow hit is a hit)
CHECK(!cold(p));
}
// the sample: 24 answers, 12 cold is cold, 11 warm; 15 answers say nothing, 16 do
CHECK(verdict(tally(sample(12, 12))) == Verdict::Cold && verdict(tally(sample(11, 13))) == Verdict::Warm);
// the sample: 24 answers, 5 cold is cold (a fifth), 4 warm; 15 answers say nothing, 16 do
CHECK(verdict(tally(sample(5, 19))) == Verdict::Cold && verdict(tally(sample(4, 20))) == Verdict::Warm);
CHECK(verdict(tally(sample(13, 17))) == Verdict::Cold); /* (11-27: a player's 13 of 30 missing) */
CHECK(verdict(tally(sample(15, 0, 9))) == Verdict::Unknown && verdict(tally(sample(16, 0, 8))) == Verdict::Cold);
CHECK(verdict(tally(sample(0, 15))) == Verdict::Unknown && verdict(tally(sample(0, 16))) == Verdict::Warm);
CHECK(verdict(tally(sample(8, 8))) == Verdict::Cold && verdict(tally(sample(7, 9))) == Verdict::Warm);
CHECK(verdict(tally(sample(4, 12))) == Verdict::Cold && verdict(tally(sample(3, 13))) == Verdict::Warm);
CHECK(verdict(tally({})) == Verdict::Unknown);
{
const Tally t = tally(sample(5, 7, 3));
@@ -259,10 +260,10 @@ int main(int argc, char** argv) {
CHECK(!run() && !built_check::state_read(state).found);
// the threshold: the first 24 recorded notes are asked (40 notes, under kLook); computes left out here
graphics_cache.clear();
for (uint64_t k = 13; k <= 40; k++) graphics_cache.insert(k); // (1-12 lost: 12 of 24)
CHECK(run(false) && has("12 of 24"));
graphics_cache.insert(12); // (11 of 24)
CHECK(!run(false) && has("11 of 24"));
for (uint64_t k = 6; k <= 40; k++) graphics_cache.insert(k); // (1-5 lost: 5 of 24, a fifth: 11-27)
CHECK(run(false) && has("5 of 24"));
graphics_cache.insert(5); // (4 of 24)
CHECK(!run(false) && has("4 of 24"));
// too few answers: 9 refused leave 15, 8 leave 16
graphics_cache.clear();
for (uint64_t k = 1; k <= 9; k++) refused.insert(k);

322
tests/test_capgap.py Normal file
View File

@@ -0,0 +1,322 @@
"""The left-out ranges' check answered from the gaps it found before (gpu/vk/capgap.h, RX_VK_CAP_EXCL_GAP; vk_memory.cpp
cap_excl_note -> cap_excl_hit_gap; no game, no GPU).
(Triforce, 11-26, the GPU audit's C09.) With RX_VK_CAP_ONLY_GPU=1 every buffer binding, replay read and texture upload
asked a binary search over about 3,000 left-out ranges whether it reaches into them, for a count that is nearly always
not raised. A thread now keeps the last 8 gaps its searches found; a question wholly inside one is "no" without a search.
Compiles a driver against the header and vk_memory.cpp's own ranges_hit (cut from the source):
- random sorted lists (the empty list, ranges from 0, ones with empty ranges, a last range up to ~0) and random
questions (inside gaps, across an edge, a gap's first and last byte, inside ranges, empty, wrapped): the rule's answer
is ranges_hit's at every question, with list changes (and the memo's clear) in between;
- 1,000 ascending questions inside one gap search once; questions going round 8 gaps search 8 times; round 9 gaps
still the same answers;
- questions that reach into a range are searched every time and keep nothing;
- the switch's values.
Compiles vk_memory.cpp's own cap_excl_hit_gap with cap_excl_hit and ranges_hit (cut from the source; the list, its lock
and version, the lab's phase and on() stubbed) and runs it with RX_VK_CAP_EXCL_GAP unset, 0 and check, over list changes
and lab phases (none, another knob's, nocapgap's): every answer is ranges_hit's over the list of the moment; the lab
question is asked once a phase move, not at every question, and never with =0; nocapgap's phases and =0 go by the
search (the memo's counts do not move), the other phases by the memo (counted every 256 questions); check counts no
difference.
Reads the source: cap_excl_note asks cap_excl_hit_gap; that reads RX_VK_CAP_EXCL_GAP once and the lab's "nocapgap",
clears the memo where it takes the list again, uses the search's answer in check mode and counts the differences; the
write-back's clip and mode 2's page count still ask cap_excl_hit, and cap_excl_hit is still the plain search; the 10 s
line carries the counts; the switches table has the row.
python -I -B tests/test_capgap.py [--cxx clang++]
"""
import argparse
import os
import subprocess
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
DRIVER = r'''
#include "capgap.h"
#include <cstdio>
#include <random>
using namespace mkwvk::capgap;
// (vk_memory.cpp's ranges_hit, cut from the source)
@RANGES_HIT@
static int checks, fails;
static void want(const char* what, bool ok) {
checks++;
if (!ok) fails++, printf("FAIL %s\n", what);
}
static std::vector<Range> random_list(std::mt19937_64& rng, int kind) {
std::vector<Range> v;
const int n = kind == 0 ? 0 : (int)(rng() % 40) + 1;
uint64_t at = kind == 1 ? 0 : rng() % 5000;
for (int k = 0; k < n; k++) {
const uint64_t len = kind == 2 && rng() % 4 == 0 ? 0 : rng() % 3000 + 1; // (kind 2: some empty ranges)
v.push_back({at, at + len});
at += len + rng() % 4000 + 1; // (never touching: as ranges_clip leaves them)
}
if (kind == 3 && !v.empty()) v.back().second = ~uint64_t(0);
return v;
}
int main() {
want("the switch", mode(nullptr) == kOn && mode("") == kOn && mode("1") == kOn && mode("0") == kOff &&
mode("check") == kCheck && mode("00") == kOn);
want("use", use(kOn, false) && use(kCheck, false) && !use(kOff, false) && !use(kOn, true) && !use(kCheck, true));
std::mt19937_64 rng(20261126);
long asked = 0, diffs = 0, from_memo = 0, hits = 0;
for (int round = 0; round < 400; round++) {
Memo memo;
std::vector<Range> v;
for (int change = 0; change < 6; change++) {
v = random_list(rng, (round + change) % 4);
memo.clear(); // (the caller's part: with its copy of the list)
const uint64_t top = v.empty() ? 10000 : v.back().first + 6000;
for (int q = 0; q < 300; q++) {
uint64_t lo, hi;
const int how = (int)(rng() % 10);
if (how < 4 || v.empty()) {
lo = rng() % top, hi = lo + rng() % 600 + 1;
} else if (how < 8) { // (at a range's edges: the gap's first and last bytes, one across, one inside)
const Range& r = v[rng() % v.size()];
const uint64_t edge = rng() % 2 ? r.first : r.second;
lo = edge - std::min<uint64_t>(edge, rng() % 3), hi = lo + rng() % 4;
} else if (how == 8) {
lo = rng() % top, hi = lo; // (empty)
} else {
lo = ~uint64_t(0) - rng() % 8, hi = lo + rng() % 16; // (at the top; wraps)
}
bool searched = false;
const bool got = hit(memo, v, lo, hi, &searched), old = ranges_hit(v, lo, hi);
asked++, diffs += got != old, from_memo += !searched, hits += old;
if (got != old && diffs < 5)
printf(" differs: [%llx, %llx) memo %d search %d\n", (unsigned long long)lo, (unsigned long long)hi, got, old);
}
}
}
printf("random: %ld questions, %ld from the memo, %ld reaching into the ranges, %ld differing\n", asked, from_memo, hits, diffs);
want("the rule's answer is ranges_hit's at every random question", diffs == 0);
want("the random questions use the memo and reach into the ranges", from_memo > asked / 10 && hits > asked / 20);
// (10 ranges of 0x1000 every 0x10000: gap g is [g * 0x10000 + 0x1000, (g + 1) * 0x10000))
std::vector<Range> v;
for (uint64_t k = 0; k < 10; k++) v.push_back({k * 0x10000, k * 0x10000 + 0x1000});
{
Memo memo;
int searches = 0, wrong = 0;
for (uint64_t k = 0; k < 1000; k++) {
bool searched = false;
const uint64_t lo = 0x31000 + k * 0x30;
wrong += hit(memo, v, lo, lo + 0x40, &searched) != ranges_hit(v, lo, lo + 0x40);
searches += searched;
}
printf("1000 ascending questions in one gap: %d searches\n", searches);
want("1000 ascending questions inside one gap search once", searches == 1 && wrong == 0);
}
for (int gaps = 8; gaps <= 9; gaps++) {
Memo memo;
int searches = 0, wrong = 0;
for (int k = 0; k < 800; k++) {
bool searched = false;
const uint64_t lo = (uint64_t)(k % gaps) * 0x10000 + 0x2000 + (uint64_t)k;
wrong += hit(memo, v, lo, lo + 0x100, &searched) != ranges_hit(v, lo, lo + 0x100);
searches += searched;
}
printf("800 questions round %d gaps: %d searches\n", gaps, searches);
if (gaps == 8) want("questions going round 8 gaps search 8 times", searches == 8 && wrong == 0);
else want("round 9 gaps the answers are still the search's", wrong == 0 && searches > 8);
}
{
Memo memo;
int searches = 0, said = 0;
bool searched = false;
hit(memo, v, 0x31000, 0x31040, &searched); // (one gap kept)
for (int k = 0; k < 100; k++) {
said += hit(memo, v, 0x3ff00, 0x40010, &searched), searches += searched; // (across the gap's end)
said += hit(memo, v, 0x40800, 0x40900, &searched), searches += searched; // (inside a range)
}
want("questions reaching into a range are searched every time", searches == 200 && said == 200);
int kept = 0;
for (int k = 0; k < kGaps; k++) kept += memo.lo[k] <= memo.hi[k];
want("and keep nothing: the one gap stays alone", kept == 1);
want("the gap's whole extent answers, to its last byte", !hit(memo, v, 0x31000, 0x40000, &searched) && !searched);
memo.clear();
want("a cleared memo searches", !hit(memo, v, 0x31000, 0x31040, &searched) && searched);
}
{
Memo memo;
bool searched = false;
const std::vector<Range> none;
want("the empty list: no, searched once", !hit(memo, none, 5, 9, &searched) && searched);
want("then everything from the memo", !hit(memo, none, 0, ~uint64_t(0), &searched) && !searched);
}
printf("%d checks, %d failed\n", checks, fails);
return fails ? 1 : 0;
}
'''
GAP_DRIVER = r'''
#include "capgap.h"
#include <atomic>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <random>
#include <vector>
using namespace mkwvk;
static void logf(const char*, ...) {}
namespace lab_ab { // (lab_ab.h's phase, and an on() that counts its calls: nocapgap is knob 2)
std::atomic<int> active{0};
static long asked = 0;
static bool on(const char* name) {
asked++;
return active.load(std::memory_order_relaxed) == 2 && !std::strcmp(name, "nocapgap");
}
}
static std::mutex cap_excl_mu;
static std::vector<std::pair<uint64_t, uint64_t>> cap_excl;
static std::atomic<uint64_t> cap_excl_ver{1};
static std::atomic<int64_t> st_gap_memo{0}, st_gap_search{0}, st_gap_diff{0};
// (vk_memory.cpp's ranges_hit, cap_excl_hit and cap_excl_hit_gap, cut from the source)
@CUT@
int main() {
const char* e = std::getenv("RX_VK_CAP_EXCL_GAP");
const bool off = e && !std::strcmp(e, "0");
std::mt19937_64 rng(20261127);
long questions = 0, wrong = 0, by_memo = 0, moves = 0;
int phase = -1;
for (int round = 0; round < 90; round++) {
{ // (a new list, published as capture_union_locked publishes it)
std::vector<std::pair<uint64_t, uint64_t>> v;
uint64_t at = rng() % 5000;
for (int k = 0, n = (int)(rng() % 40); k < n; k++) {
const uint64_t len = rng() % 3000 + 1;
v.push_back({at, at + len});
at += len + rng() % 4000 + 1;
}
std::lock_guard lk(cap_excl_mu);
cap_excl.swap(v);
cap_excl_ver.fetch_add(1, std::memory_order_release);
}
const uint64_t top = cap_excl.empty() ? 10000 : cap_excl.back().second + 6000;
for (int q = 0; q < 1000; q++) {
const int now = (round + (q >= 600)) % 3; // (0: none; 1: another knob's phase; 2: nocapgap's)
if (now != phase) lab_ab::active.store(now, std::memory_order_relaxed), phase = now, moves++;
uint64_t lo = rng() % top, hi = lo + rng() % 600 + 1;
if (q % 50 == 7) hi = lo; // (empty)
const bool got = cap_excl_hit_gap(lo, hi);
wrong += got != ranges_hit(cap_excl, lo, hi);
questions++;
by_memo += !off && phase != 2;
}
}
const long counted = (long)(st_gap_memo.load() + st_gap_search.load());
std::printf("%s: %ld questions, %ld wrong, the lab asked %ld times over %ld phase moves, %ld counted of %ld by the memo, "
"%lld differing\n", e ? e : "unset", questions, wrong, lab_ab::asked, moves, counted, by_memo,
(long long)st_gap_diff.load());
int fails = 0;
if (wrong) fails++, std::printf("FAIL an answer is not ranges_hit's over the list of the moment\n");
if (lab_ab::asked != (off ? 0 : moves))
fails++, std::printf("FAIL the lab knob is asked %ld times, not once a phase move (%ld; never with =0)\n", lab_ab::asked,
off ? 0 : moves);
if (counted != by_memo / 256 * 256)
fails++, std::printf("FAIL the memo counted %ld questions, not the %ld outside nocapgap's phases (by 256)\n", counted, by_memo);
if (st_gap_diff.load()) fails++, std::printf("FAIL check counts differences\n");
return fails;
}
'''
def cut(src, start, end="\n}\n"):
i = src.index(start)
return src[i:src.index(end, i) + len(end)]
def check_source():
src = (ROOT / "gpu/vk/vk_memory.cpp").read_text(encoding="utf-8")
if '#include "capgap.h"' not in src:
raise SystemExit("FAIL: vk_memory.cpp does not include capgap.h")
note = cut(src, "void cap_excl_note(uint64_t gpu, uint64_t n, const char* who) {")
if "if (!g || !cap_excl_hit_gap(g, g + n)) return;" not in note:
raise SystemExit("FAIL: cap_excl_note does not ask cap_excl_hit_gap")
gap = cut(src, "bool cap_excl_hit_gap(uint64_t lo, uint64_t hi) {")
for needle in ('getenv("RX_VK_CAP_EXCL_GAP")', "capgap::mode(e)", 'lab_ab::on("nocapgap")', "return cap_excl_hit(lo, hi);",
"memo.clear();", "capgap::hit(memo, mine, lo, hi, &searched)", "ranges_hit(mine, lo, hi)",
"st_gap_diff.fetch_add(1, std::memory_order_relaxed)"):
if needle not in gap:
raise SystemExit("FAIL: cap_excl_hit_gap no longer has: " + needle)
if "static const capgap::Mode env" not in gap:
raise SystemExit("FAIL: RX_VK_CAP_EXCL_GAP is not read once")
# (the memo is cleared in the branch that takes the list again)
retake = gap[gap.index("if (ver != now) {"):]
retake = retake[:retake.index("}")]
if "mine = cap_excl;" not in retake or "memo.clear();" not in retake:
raise SystemExit("FAIL: the memo is not cleared where the thread takes the left-out ranges again")
# (check mode: the search's answer is the one used)
if "return old;" not in gap:
raise SystemExit("FAIL: check mode does not use the search's answer")
# (cap_excl_hit is still the plain search, and the clip and mode 2 still ask it)
plain = cut(src, "bool cap_excl_hit(uint64_t lo, uint64_t hi) {")
if "return ranges_hit(mine, lo, hi);" not in plain or "capgap" in plain:
raise SystemExit("FAIL: cap_excl_hit is no longer the plain search")
for needle in ("if (excl_clip && cap_excl_hit(p->lo + off, p->lo + wb_end)) {",
"if (cap_excl_hit(g, g + 1)) st_excl_pages.fetch_add(1, std::memory_order_relaxed);"):
if needle not in src:
raise SystemExit("FAIL: vk_memory.cpp no longer has: " + needle)
if src.count("cap_excl_hit_gap(") != 3: # (its declaration, its definition, cap_excl_note)
raise SystemExit("FAIL: cap_excl_hit_gap has a caller besides cap_excl_note")
present = cut(src, "void memory_cap_present() {")
for needle in ("left-out checks in all from the gap memo %lld, searched %lld, differing %lld (RX_VK_CAP_EXCL_GAP)",
"st_gap_memo.load(", "st_gap_search.load(", "st_gap_diff.load("):
if needle not in present:
raise SystemExit("FAIL: the capture's 10 s line no longer has: " + needle)
docs = (ROOT / "docs/development.md").read_text(encoding="utf-8")
row = [l for l in docs.splitlines() if l.startswith("| `RX_VK_CAP_EXCL_GAP=0`")]
if len(row) != 1 or "nocapgap" not in row[0] or "capgap.h" not in row[0] or "=check" not in row[0]:
raise SystemExit("FAIL: docs/development.md has no RX_VK_CAP_EXCL_GAP row with the knob, the header and check")
ranges_hit = cut(src, "bool ranges_hit(const std::vector<std::pair<uint64_t, uint64_t>>& v, uint64_t lo, uint64_t hi) {")
return ranges_hit, "\n".join((ranges_hit, plain, gap))
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--cxx", default="clang++")
args = parser.parse_args()
if not (ROOT / "gpu/vk/capgap.h").exists():
raise SystemExit("FAIL: gpu/vk/capgap.h is missing: the left-out check searches at every question")
ranges_hit, gap_cut = check_source()
with tempfile.TemporaryDirectory(prefix="capgap-") as tmp:
cpp, exe = Path(tmp) / "capgap_test.cpp", Path(tmp) / "capgap.exe"
cpp.write_text(DRIVER.replace("@RANGES_HIT@", ranges_hit), encoding="utf-8")
subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-I" + str(ROOT / "gpu/vk"), str(cpp), "-o", str(exe)],
check=True)
r = subprocess.run([str(exe)], capture_output=True, text=True)
print(r.stdout.rstrip())
if r.returncode:
raise SystemExit("FAIL: the gap memo's checks failed")
cpp, exe = Path(tmp) / "capgap_note.cpp", Path(tmp) / "capgap_note.exe"
cpp.write_text(GAP_DRIVER.replace("@CUT@", gap_cut), encoding="utf-8")
subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-I" + str(ROOT / "gpu/vk"), str(cpp), "-o", str(exe)],
check=True)
env = {k: v for k, v in os.environ.items() if not k.startswith("RX_VK_")}
for value in (None, "0", "check"):
run_env = dict(env, **({"RX_VK_CAP_EXCL_GAP": value} if value is not None else {}))
r = subprocess.run([str(exe)], capture_output=True, text=True, env=run_env)
print(r.stdout.rstrip())
if r.returncode:
raise SystemExit("FAIL: vk_memory.cpp's cap_excl_hit_gap with RX_VK_CAP_EXCL_GAP=%s" % (value or "unset"))
print("PASS: the left-out check is answered from kept gaps with the search's answers; RX_VK_CAP_EXCL_GAP=0 searches as before")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,464 @@
"""A plain draw's capture push is left out while the command buffer is known to hold zeros there (gpu/vk/
capturepushkeep.h, cmd_work.h, vk_work.h, vk_draw.cpp push_capture; no game, no GPU).
(Triforce, 11-26, the GPU audit's C15.) push_capture pushed 16 bytes (where the vertex stage stores its positions: an
address, a first and a count) before every plain draw of every program whose vertex stage captures, and with no temporal
upscaler's chain asking for positions those bytes are zeros for every draw: a vkCmdPushConstants a draw, about 2,000 a
frame at Lake Hylia, each a packet for the recorder. The zeros are pushed once now and kept, per command buffer, until
anything could have changed them. A non-zero address left there would be written through by the next draw, so what
forgets is central: every vkCmdPushConstants and every vkCmdBindPipeline of the renderer (vk_work.h's macros), every
vkBeginCommandBuffer (cmd_work.h work_begun) and every library's direct recording (the recorder's B_DIRECT boundary),
never a list of call sites.
This compiles the rule and replays recordings through it as vk_work.h and push_capture call it: N plain draws push once;
a compute pass's push or bind between two draws, a library's own recording, a new recording of the same command buffer,
a program with other push stages, a draw state reset and a non-zero slot each push again; the first zero after a
non-zero slot is pushed; a program's full block (zeros in the capture's bytes) keeps the next draw's; a command buffer
the table has no room for never keeps; a program with other push stages bound and left without a draw, and a pipeline
carried across a new recording, push again. Check mode's own model (what the bytes hold, by the pushes alone) agrees with the rule in all of them, and
disagrees when the rule is made to keep across a push (the hole a list of call sites would leave). The header's rules
taken out in turn (MUTATIONS) each make it fail.
And reads the source: both macros and the begin go through the rule, and their wrappers call the recorder's route, not
the driver; no file in any folder of gpu/vk pushes or binds past the macros, or above its vk_work.h include (controls:
each such text is caught); push_capture asks the rule, pushes through the macro and notes its own push after; the
program path's bind is the only one after which the zeros are held again; a direct recording's boundary voids them; the
switch, its three values and the log line for any other, the lab knob and the counters (the must-be-0 one exact); the
header's account of what check mode sees; the row in the switches table, with the same account.
python -I -B tests/test_capturepushkeep.py [--cxx clang++]
"""
import argparse
import re
import subprocess
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
VK = ROOT / "gpu" / "vk"
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
def check(ok, why):
if not ok:
raise SystemExit("FAIL: " + why)
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]
def past_macros(name, text):
"""What in a renderer file (name: its path under gpu/vk) pushes or binds past vk_work.h's macros, or sets the kept
capture push outside the draw: the driver's own call named, a call with no vk_work.h include or above it"""
problems = []
code = re.sub(r"//[^\n]*", "", re.sub(r"/\*.*?\*/", "", text, flags=re.S))
for call in ("vkCmdPushConstants", "vkCmdBindPipeline"):
if "rx_" + call in text or "vkx::" + call in text or "pk_" + call in text:
problems.append(f"{name}: a {call} past vk_work.h's macro")
if re.search(r"\b" + call + r"\s*\(", code):
inc = code.find('#include "vk_work.h"')
if inc < 0:
problems.append(f"{name}: calls {call} without vk_work.h's macro")
elif re.search(r"\b" + call + r"\s*\(", code[:inc]):
problems.append(f"{name}: calls {call} above its vk_work.h include")
if name.rsplit("/", 1)[-1] not in ("vk_draw.cpp", "capturepushkeep.h") and (
"program_bound(" in text or "full_pushed(" in text or ".cap.zero_stages" in text):
problems.append(f"{name}: the kept capture push is set outside the draw")
return problems
PROGRAM = r"""
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <initializer_list>
#include "capturepushkeep.h"
namespace k = capturepushkeep;
static int fails = 0;
#define CHECK(x) do { if (!(x)) { std::printf("FAIL:%d %s\n", __LINE__, #x); fails++; } } while (0)
// one command buffer as the renderer sees it: the rule's state, and what a driver would hold in the capture's bytes
struct Cmd {
k::State st;
bool known = true;
uint8_t held[k::kSize];
bool defined = false; // (false: undefined, a new recording)
uint32_t bound = 0; // (the push stages of the program pipeline bound last; 0: none)
int pushes = 0, kept = 0, bad = 0, wrong = 0;
};
static void begin(Cmd& c) { k::begun(c.st), c.defined = false, c.bound = 0; }
// vk_work.h's vkCmdPushConstants: the rule is told, then the driver
static void push(Cmd& c, uint32_t offset, uint32_t size, const uint8_t* v) {
k::any_push(c.st, offset, size, v);
for (uint32_t i = 0; i < size; i++)
if (offset + i >= k::kOffset && offset + i < k::kOffset + k::kSize) c.held[offset + i - k::kOffset] = v[i];
if (offset <= k::kOffset && offset + size >= k::kOffset + k::kSize) c.defined = true;
c.pushes++;
}
static void bind_other(Cmd& c) { k::any_bind(c.st); } // (vk_work.h's vkCmdBindPipeline)
// a library's own recording into it (the recorder's B_DIRECT boundary first): nothing of it is seen, the bytes are anything
static void library(Cmd& c) {
k::direct_recorded();
std::memset(c.held, 0xab, sizeof c.held);
}
// vk_draw.cpp draw's bind of a program's pipeline: through the macro, then what was held before it taken back or not. A
// layout with other push stages is not compatible for push constants: the driver's bytes are undefined after it
static void bind_program(Cmd& c, uint32_t stages, bool from_reset) {
const uint32_t held = c.st.zero_stages;
if (c.bound && c.bound != stages) c.defined = false;
c.bound = stages;
bind_other(c);
k::program_bound(c.st, held, stages, from_reset);
}
// vk_draw.cpp push_constants: a program's whole block, zeros in the capture's bytes
static void full_block(Cmd& c, uint32_t stages) {
uint8_t data[k::kOffset + k::kSize] = {};
data[0] = 0x3f;
push(c, 0, sizeof data, data);
k::full_pushed(c.st, stages);
}
// vk_draw.cpp push_capture, then the draw: what the vertex stage would read must be the slot
static void draw(Cmd& c, k::Mode mode, uint32_t stages, uint64_t address, bool lab_old = false) {
uint8_t data[k::kSize] = {};
std::memcpy(data, &address, 8);
bool skip = false;
if (mode != k::OFF && k::keep(c.st, c.known, stages, data)) {
if (mode == k::CHECK) c.kept++, c.bad += k::check_differs(c.st);
else if (!lab_old) c.kept++, skip = true;
}
if (!skip) {
push(c, k::kOffset, k::kSize, data);
if (mode != k::OFF) k::pushed(c.st, stages, data);
}
if (!c.defined || std::memcmp(c.held, data, k::kSize)) c.wrong++;
}
int main() {
const uint32_t VF = 0x11, VGF = 0x19;
const uint8_t junk[8] = {1, 2, 3, 4, 5, 6, 7, 8};
uint8_t ones[128];
std::memset(ones, 0xee, sizeof ones);
CHECK(k::kOffset == 88 && k::kSize == 16);
// the switch
CHECK(k::mode_of(nullptr) == k::KEEP && k::mode_of("") == k::KEEP && k::mode_of("1") == k::KEEP && k::mode_of("on") == k::KEEP);
CHECK(k::mode_of("0") == k::OFF && k::mode_of("check") == k::CHECK);
for (k::Mode mode : {k::KEEP, k::CHECK, k::OFF}) {
const bool on = mode == k::KEEP;
Cmd c;
begin(c);
// N plain draws of programs with one stage mask: one push
bind_program(c, VF, true);
for (int i = 0; i < 100; i++) {
if (i % 7 == 0) bind_program(c, VF, false); // (another program, the same stages)
draw(c, mode, VF, 0);
}
CHECK(c.pushes == (on ? 1 : 100) && c.kept == (mode == k::OFF ? 0 : 99));
// a compute pass's push between two draws, over the capture's bytes (byte 88 and on) or not: pushed again
int at = c.pushes;
push(c, 0, 104, ones);
draw(c, mode, VF, 0);
CHECK(c.pushes == at + 2);
at = c.pushes;
push(c, 0, 8, junk);
draw(c, mode, VF, 0);
CHECK(c.pushes == at + 2);
draw(c, mode, VF, 0);
CHECK(c.pushes == at + (on ? 2 : 3));
// any other bind (a compute pipeline, the clear's, an actor's): pushed again
at = c.pushes;
bind_other(c);
draw(c, mode, VF, 0);
CHECK(c.pushes == at + 1);
// a program with other push stages: its layout's block is another one
at = c.pushes;
bind_program(c, VGF, false);
draw(c, mode, VGF, 0);
CHECK(c.pushes == at + 1);
draw(c, mode, VGF, 0);
CHECK(c.pushes == at + (on ? 1 : 2));
at = c.pushes;
bind_program(c, VF, false);
draw(c, mode, VF, 0);
CHECK(c.pushes == at + 1);
// the draw state reset (last_pipeline cleared: something was recorded that the macros did not see)
at = c.pushes;
bind_program(c, VF, true);
draw(c, mode, VF, 0);
CHECK(c.pushes == at + 1);
// a slot: pushed, every time, and so is the first zero after it
at = c.pushes;
draw(c, mode, VF, 0x7000000010ull);
draw(c, mode, VF, 0x7000000010ull);
draw(c, mode, VF, 0x7000000020ull);
CHECK(c.pushes == at + 3);
draw(c, mode, VF, 0);
CHECK(c.pushes == at + 4);
draw(c, mode, VF, 0);
CHECK(c.pushes == at + (on ? 4 : 5));
// a program's full block has zeros there: its capture push is kept
at = c.pushes;
full_block(c, VF);
draw(c, mode, VF, 0);
CHECK(c.pushes == at + (on ? 1 : 2));
full_block(c, VF);
draw(c, mode, VF, 0x7000000030ull);
full_block(c, VF);
draw(c, mode, VF, 0);
// the lab knob: pushed in its phases, kept again after
at = c.pushes;
draw(c, mode, VF, 0, true);
draw(c, mode, VF, 0, true);
CHECK(c.pushes == at + 2);
draw(c, mode, VF, 0);
CHECK(c.pushes == at + (on ? 2 : 3));
// a library's recording, with the draw state left as it was: pushed again, and kept after
at = c.pushes;
library(c);
draw(c, mode, VF, 0);
CHECK(c.pushes == at + 1);
draw(c, mode, VF, 0);
CHECK(c.pushes == at + (on ? 1 : 2));
// ... into another command buffer: this one's is void as well (the boundary names none)
at = c.pushes;
k::direct_recorded();
bind_program(c, VF, false);
draw(c, mode, VF, 0);
CHECK(c.pushes == at + 1);
// the command buffer recorded again: nothing is held
at = c.pushes;
begin(c);
bind_program(c, VF, true);
draw(c, mode, VF, 0);
CHECK(c.pushes == at + 1);
// a compute pass (bind, push) with the program's pipeline left bound, as the mirror's pass and the write-back's do
at = c.pushes;
bind_other(c);
push(c, 0, 96, ones);
draw(c, mode, VF, 0);
CHECK(c.pushes == at + 2);
// a program with other push stages bound and left without a draw (its draw skipped right after the bind), then one
// with the first stages again: the zeros are not taken back across the other layout
at = c.pushes;
draw(c, mode, VF, 0);
bind_program(c, VGF, false);
bind_program(c, VF, false);
draw(c, mode, VF, 0);
CHECK(c.pushes == at + (on ? 1 : 2));
// a pipeline carried across a new recording of the command buffer (no bind after the begin): pushed again
at = c.pushes;
begin(c);
draw(c, mode, VF, 0);
CHECK(c.pushes == at + 1);
// every draw read its own slot, and check mode found nothing
CHECK(c.wrong == 0 && c.bad == 0);
}
// a command buffer the table has no room for: never kept
{
Cmd c;
c.known = false;
begin(c);
bind_program(c, VF, true);
draw(c, k::KEEP, VF, 0), draw(c, k::KEEP, VF, 0), draw(c, k::KEEP, VF, 0);
CHECK(c.pushes == 3 && c.kept == 0 && c.wrong == 0);
}
// the rule's answers one by one: stages 0 is "nothing held", never a key
{
k::State s;
const uint8_t zero[k::kSize] = {};
CHECK(!k::keep(s, true, 0, zero) && !k::keep(s, true, VF, zero));
k::pushed(s, VF, zero);
CHECK(k::keep(s, true, VF, zero) && !k::keep(s, false, VF, zero) && !k::keep(s, true, VGF, zero));
uint8_t one[k::kSize] = {};
one[15] = 1;
CHECK(!k::keep(s, true, VF, one));
k::pushed(s, VF, one);
CHECK(!k::keep(s, true, VF, zero));
k::pushed(s, 0, zero);
CHECK(!k::keep(s, true, 0, zero));
}
// check mode's model is the pushes' own: a keep that did not forget at a push over byte 88 is counted
{
Cmd c;
begin(c);
bind_program(c, VF, true);
draw(c, k::CHECK, VF, 0);
draw(c, k::CHECK, VF, 0);
CHECK(c.bad == 0 && c.kept == 1);
const uint32_t held = c.st.zero_stages;
push(c, 0, 104, ones);
CHECK(c.st.zero_stages == 0);
c.st.zero_stages = held; // (the hole)
draw(c, k::CHECK, VF, 0);
CHECK(c.bad == 1 && c.wrong == 0);
// what the model takes the bytes for, push by push
k::State s;
const uint8_t zero[104] = {};
CHECK(k::check_differs(s));
k::any_push(s, 0, 104, zero);
CHECK(!k::check_differs(s));
k::any_push(s, 0, 96, zero); // (a part of them: not known)
CHECK(k::check_differs(s));
k::any_push(s, 88, 16, zero);
CHECK(!k::check_differs(s));
k::any_push(s, 0, 88, ones); // (short of them: they stay)
CHECK(!k::check_differs(s));
k::any_push(s, 104, 8, ones);
CHECK(!k::check_differs(s));
k::any_push(s, 80, 32, ones);
CHECK(k::check_differs(s));
k::any_push(s, 0, 104, zero);
k::begun(s);
CHECK(k::check_differs(s));
}
return fails ? 1 : 0;
}
"""
# (a rule of the header, and what it is replaced by: each must make PROGRAM fail; a parameter left unread is named with
# (void), the build is -Werror)
MUTATIONS = [
("the same push stages for the zeros taken back at a program's bind", "s.zero_stages = !from_reset && held == stages ? held : 0;",
"s.zero_stages = !from_reset ? held : 0; (void)stages;"),
("all the push stages, not one shared", "s.zero_stages = !from_reset && held == stages ? held : 0;",
"s.zero_stages = !from_reset && (held & stages) ? held : 0;"),
("not across a draw state reset", "s.zero_stages = !from_reset && held == stages ? held : 0;",
"s.zero_stages = held == stages ? held : 0; (void)from_reset;"),
("a new recording forgets", "inline void begun(State& s) { s.zero_stages = 0, s.shadow_zero = 0; }",
"inline void begun(State& s) { s.shadow_zero = 0; }"),
("a library's recording voids what is held", "s.zero_stages == stages && s.gen == direct_gen.load(std::memory_order_relaxed) && ",
"s.zero_stages == stages && "),
]
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cxx", default="clang++")
args = parser.parse_args()
check((VK / "capturepushkeep.h").is_file(), "gpu/vk/capturepushkeep.h: there is no rule (every plain draw pushes its capture slot)")
rule = (VK / "capturepushkeep.h").read_text(encoding="utf-8")
check("#include <vulkan" not in rule and "Vk" not in rule.split("#pragma once")[1], "the rule is not apart from Vulkan")
# the command buffer's state holds the rule's, and a begin starts it afresh
cw = (VK / "cmd_work.h").read_text(encoding="utf-8")
check('#include "capturepushkeep.h"' in cw and "capturepushkeep::State cap;" in block(cw, "struct CmdWork {"),
"cmd_work.h: the command buffer's state does not hold the kept capture push")
check("capturepushkeep::begun(w.cap);" in block(cw, "inline VkCommandBuffer work_begun("),
"cmd_work.h work_begun: a new recording does not forget the kept capture push")
# a library's recording past the macros is told by the recorder's boundary
rec = (VK / "vk_recorder.h").read_text(encoding="utf-8")
check("if (k == B_DIRECT) ::capturepushkeep::direct_recorded();" in block(rec, "inline void boundary(Bound k)"),
"vk_recorder.h boundary: a direct recording does not void the kept capture pushes")
# every push and every bind of the renderer is told to the rule, in the macros
vw = (VK / "vk_work.h").read_text(encoding="utf-8")
check("#define vkCmdPushConstants(...) (::mkwvk::capture_keep_vk::push(__VA_ARGS__))" in vw,
"vk_work.h: vkCmdPushConstants does not go through the rule")
check("#define vkCmdBindPipeline(...) (::mkwvk::capture_keep_vk::bind(__VA_ARGS__))" in vw,
"vk_work.h: vkCmdBindPipeline does not go through the rule")
push = block(vw, "inline void push(VkCommandBuffer cmd")
check(push.index("::capturepushkeep::any_push(::mkwvk::cmd_work(cmd).cap, offset, size, values);") <
push.index("::mkwvk::rec::rx_vkCmdPushConstants(cmd, layout, stages, offset, size, values);"),
"vk_work.h: a push is not told to the rule before it is recorded")
bind = block(vw, "inline void bind(VkCommandBuffer cmd")
check(bind.index("::capturepushkeep::any_bind(::mkwvk::cmd_work(cmd).cap);") <
bind.index("::mkwvk::rec::rx_vkCmdBindPipeline(cmd, point, pipeline);"), "vk_work.h: a bind is not told to the rule")
check("::vkx::" not in push and "::vkx::" not in bind, "vk_work.h: a wrapper calls the driver past the recorder")
# no call past the macros: the driver's own push and bind are named by the recorder, the loader and vk_work.h alone, in
# every folder of the renderer (reshade/ records into the game's command buffers too); a call above the vk_work.h include
# is the loader's own function, past the rule
scanned = []
for f in sorted(VK.rglob("*.cpp")) + sorted(VK.rglob("*.h")):
if f.name in ("vk_recorder.h", "vk_loader.h", "vk_work.h") and f.parent == VK:
continue
scanned.append(f.relative_to(VK).as_posix())
problems = past_macros(scanned[-1], f.read_text(encoding="utf-8", errors="replace"))
check(not problems, "; ".join(problems))
check(len(scanned) > 100 and "reshade/fx_runtime.cpp" in scanned,
"the scan for calls past the macros did not read gpu/vk's subfolders (reshade/fx_runtime.cpp)")
for what, name, text in (("the driver's own bind named through vkx::, below the vk_work.h include", "x.cpp",
'#include "vk_work.h"\nvoid f() { ::vkx::vkCmdBindPipeline(cmd, bp, pl); }\n'),
("a push above the vk_work.h include", "x.cpp",
'void f() { vkCmdPushConstants(cmd, l, s, 88, 16, d); }\n#include "vk_work.h"\n'),
("a bind with no vk_work.h", "x.cpp", "void f() { vkCmdBindPipeline (cmd, bp, pl); }\n"),
("the kept push set outside the draw", "x.cpp", "void f() { capturepushkeep::full_pushed(s, 1); }\n")):
check(past_macros(name, text), "the scan for calls past the macros missed " + what)
src = (VK / "vk_draw.cpp").read_text(encoding="utf-8")
check(src.count("capturepushkeep::program_bound(") == 1 and src.count("capturepushkeep::full_pushed(") == 1 and
src.count("capturepushkeep::pushed(") == 1, "vk_draw.cpp: more than the program's bind and the draw's two pushes set what is kept")
draw = block(src, "void draw(")
held = draw.index("const uint32_t cap_held = mkwvk::cmd_work(cmd).cap.zero_stages;")
reset = draw.index("const bool cap_reset = last_pipeline == VK_NULL_HANDLE;")
bound = draw.index("vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pl), last_pipeline = pl;")
back = draw.index("capturepushkeep::program_bound(mkwvk::cmd_work(cmd).cap, cap_held, p.push_stages, cap_reset);")
check(held < bound and reset < bound < back,
"vk_draw.cpp draw: what was held and a reset draw state are not read before the program's bind and given to the rule after it")
cap = block(src, "static void push_capture(")
check("if (!p.captures) return;" in cap, "push_capture: no longer only the capturing programs")
check("const int mode = capture_keep_mode();" in cap, "push_capture does not read the switch")
ask = cap.index("capturepushkeep::keep(w.cap, w.known, p.push_stages, data)")
push_at = cap.index("vkCmdPushConstants(cmd, p.layout, p.push_stages, Shader::Backend::SPIRV::CAPTURE_PUSH_OFFSET, sizeof data, data);")
note = cap.index("capturepushkeep::pushed(mkwvk::cmd_work(cmd).cap, p.push_stages, data);")
check(ask < push_at < note, "push_capture: not asked, pushed through the macro, then noted")
check('lab_ab::on("nocappush")' in cap[ask:push_at], "push_capture: the lab knob nocappush does not push in its phases")
check("capturepushkeep::check_differs(w.cap)" in cap[ask:push_at] and "st_cap_bad.fetch_add(1, std::memory_order_relaxed);" in cap[ask:push_at],
"push_capture: check mode does not count a kept push whose bytes differ, exactly with the helper threads")
doc = src[src.rindex("\n\n", 0, src.index("static void push_capture(")):src.index("static void push_capture(")]
check("B_DIRECT" in doc and "same push stages" in doc and "by construction" in doc,
"push_capture's comment leaves out the libraries' recordings, the bind's rule or what check mode cannot see")
check("st_cap_kept" in cap[ask:push_at] and "st_cap_pushed" in cap[push_at:], "push_capture: kept and pushed are not counted")
check("capturepushkeep::kOffset == Shader::Backend::SPIRV::CAPTURE_PUSH_OFFSET" in cap and
"capturepushkeep::kSize == sizeof data" in cap, "push_capture: the rule's bytes are not pinned to the shader's")
pc = block(src, "void push_constants(")
check(pc.index("vkCmdPushConstants(cmd, p.layout, p.push_stages, 0, kPushSize, data);") <
pc.index("capturepushkeep::full_pushed(mkwvk::cmd_work(cmd).cap, p.push_stages);"),
"push_constants: the whole block's zeros are not noted after its push")
mode = block(src, "int capture_keep_mode(")
check('getenv("RX_VK_CAPTURE_PUSH_KEEP")' in mode and "capturepushkeep::mode_of(" in mode and "logf(" in mode and
"is not 0, 1 or check" in mode, "the switch is not read once by the rule and told when it is not the default")
check("0 by construction" in rule and "test_recorder_sync.py" in rule.split("#pragma once")[0] and "ignores binds" in rule,
"capturepushkeep.h: the header does not say what check mode can and cannot see")
rep = block(src, "void desc_report(")
check("st_cap_kept" in rep and "st_cap_pushed" in rep and "st_cap_bad" in rep and "a frame's capture pushes" in rep,
"the descriptors' report does not carry the capture pushes kept and made")
dev = (ROOT / "docs" / "development.md").read_text(encoding="utf-8")
row = [line for line in dev.splitlines() if line.startswith("| `RX_VK_CAPTURE_PUSH_KEEP=0` or `check` |")]
check(len(row) == 1 and "nocappush" in row[0] and "capturepushkeep.h" in row[0],
"docs/development.md: RX_VK_CAPTURE_PUSH_KEEP is not in the switches table")
for part in ["0 by construction", "ignores binds", "`tests/test_recorder_sync.py`", "`tests/test_capturepushkeep.py`",
"`push_constants`", "Any other value: on (told once)", "neither is v0.8.4's cost"]:
check(len(row) == 1 and part in row[0], "docs/development.md: the RX_VK_CAPTURE_PUSH_KEEP row lacks " + part)
check(len(row) == 1 and "a second model" not in row[0], "docs/development.md: the row still calls the check a second model")
with tempfile.TemporaryDirectory(prefix="capturepushkeep-") as tmp:
c, exe = Path(tmp) / "keep.cpp", Path(tmp) / "keep.exe"
c.write_text(PROGRAM, encoding="utf-8")
subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-I" + str(VK), str(c), "-o", str(exe)], check=True)
r = subprocess.run([str(exe)], capture_output=True, text=True)
check(r.returncode == 0, "the rule as made:\n" + r.stdout)
# (each rule taken out of the header in turn: the program must fail)
for i, (what, old, new) in enumerate(MUTATIONS):
check(rule.count(old) == 1, "the mutation's text is not in the header once: %r" % old)
inc = Path(tmp) / ("m%d" % i)
inc.mkdir()
(inc / "capturepushkeep.h").write_text(rule.replace(old, new), encoding="utf-8")
mexe = Path(tmp) / ("m%d.exe" % i)
b = subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-I" + str(inc), str(c), "-o", str(mexe)],
capture_output=True, text=True)
check(b.returncode == 0, "the mutation does not compile (%s):\n%s" % (what, b.stderr[-2000:]))
r = subprocess.run([str(mexe)], capture_output=True, text=True)
check(r.returncode != 0, "no check fails without: " + what)
print("PASS: a plain draw's capture push is kept while its command buffer holds zeros there, and pushed after anything else "
"(%d mutations caught)" % len(MUTATIONS))
if __name__ == "__main__":
main()

317
tests/test_capunion.py Normal file
View File

@@ -0,0 +1,317 @@
"""The captures' range lists: one union for every caller each time a list changes, its sorts as merges of sorted runs
(gpu/vk/capunion.h; vk_memory.cpp capture_union_take_locked, refresh_pool_ranges_locked; no game, no GPU).
(Triforce, 11-26.) capture_make and capture_ranges_merged each kept a union of the captures' lists of their own, so the
Presentation thread built it twice at every change of a list (three sorts, two clips, the left-out ranges published, each
time), and the pool table's look kept a map of the pools' first captures that only RX_VK_CAPTURE_EAGER reads. The lists
decide which pages a capture takes: a wrong one is stale pages in a mirror, so they must be what they were, byte for byte.
This compiles the header with vk_memory.cpp's own ranges_merged, ranges_clip and capture_union_locked (cut from the
source, the four lists, the left-out ranges, their lock and version and RX_VK_CAP_ONLY_GPU's mode stubbed), so that a
list added to the old union, or a change of its clip or join, fails here until capunion.h follows: over random import,
pool, texture storage and small pool lists (sorted, unsorted, overlapping, touching, with duplicates, empty), with
RX_VK_CAP_ONLY_GPU 0, 1 and 2, the union and the left-out ranges must be the same vectors, and with 0 neither touches the
left-out ranges; merged_runs must be ranges_merged whatever the runs and the cuts, and must not sort runs
that arrive sorted; the shared union is built once a version whoever asks, and again when the version moves; the pools' first
captures are kept only with RX_VK_CAPTURE_EAGER or with the switch off; the switch's values.
And reads the source: both callers take the union through capture_union_take_locked behind their own version, which
copies the shared one; the old capture_union_locked is still there for RX_VK_CAP_UNION_SHARED=0, the lab knob nocapunion
and the check; the left-out ranges are published where the shared union is built; the pool table's look uses the runs and
skips the map by the rule; the counters are in the capture's 10 s line; the switches table has the row.
python -I -B tests/test_capunion.py [--cxx clang++]
"""
import argparse
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 as cut_block # noqa: E402
ROOT = Path(__file__).resolve().parents[1]
VK = ROOT / "gpu" / "vk"
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
def check(ok, why):
if not ok:
raise SystemExit("FAIL: " + why)
def block(text, marker):
check(marker in text, "vk_memory.cpp has no " + marker)
start = text.index(marker)
end = text.index("{", start + len(marker) - 1) + 1
depth = 1
while depth:
depth += (text[end] == "{") - (text[end] == "}")
end += 1
return text[start:end]
PROGRAM = r"""
#include <atomic>
#include <cstdio>
#include <mutex>
#include "capunion.h"
using capunion::Ranges;
static int fails = 0;
static long compared = 0;
static uint64_t rnd_state = 0x853C49E6748FEA9Bull;
static uint64_t rnd() {
rnd_state ^= rnd_state << 13, rnd_state ^= rnd_state >> 7, rnd_state ^= rnd_state << 17;
return rnd_state;
}
static void fail(const char* what) {
if (fails++ < 20) std::printf("FAIL %s\n", what);
}
// ---- the lists as vk_memory.cpp makes them: its own ranges_merged, ranges_clip and capture_union_locked ----
static int g_only_gpu = 1;
static int cap_only_gpu() { return g_only_gpu; }
static Ranges cap_ranges, all_pool_ranges, tex_cap_ranges, pool_cap_ranges, cap_excl;
static std::mutex cap_excl_mu;
static std::atomic<uint64_t> cap_excl_ver{1};
@CUT@
/// capture_union_locked over these lists and RX_VK_CAP_ONLY_GPU's mode: the union; the left-out ranges in excl, and
/// whether they were published (their version moved)
static Ranges vk_union(const Ranges& imports, const Ranges& pools, const Ranges& tex, const Ranges& small, int only_gpu,
Ranges& excl, bool& published) {
cap_ranges = imports, all_pool_ranges = pools, tex_cap_ranges = tex, pool_cap_ranges = small, g_only_gpu = only_gpu;
cap_excl = excl;
const uint64_t ver = cap_excl_ver.load();
Ranges uni = capture_union_locked();
published = cap_excl_ver.load() != ver;
excl = cap_excl;
return uni;
}
// ---- lists ----
static const uint64_t P = 4096;
/// kind 0: sorted, apart; 1: sorted, some touching or overlapping; 2: as 1 with duplicates; 3: unsorted
static Ranges some(int n, int kind, uint64_t base, uint64_t stride) {
Ranges r;
uint64_t at = base + (rnd() % 8) * P;
for (int i = 0; i < n; i++) {
const uint64_t len = (1 + rnd() % 12) * P;
r.push_back({at, at + len});
if (kind >= 2 && rnd() % 5 == 0) r.push_back(r.back());
if (kind >= 1 && rnd() % 4 == 0) at += (rnd() % 3) * (len / 2); // (the next one inside this, at its end, or the same)
else at += len + (kind >= 1 && rnd() % 4 == 0 ? 0 : (1 + rnd() % stride) * P);
}
if (kind == 3)
for (size_t i = r.size(); i > 1; i--) std::swap(r[i - 1], r[rnd() % i]);
return r;
}
static void one_union(const Ranges& imports, const Ranges& pools, const Ranges& tex, const Ranges& small, const char* what) {
for (int only_gpu = 0; only_gpu <= 2; only_gpu++) {
Ranges excl_old{{1, 2}};
bool pub_old = false;
const Ranges uni_old = vk_union(imports, pools, tex, small, only_gpu, excl_old, pub_old);
capunion::Built b;
b.excl = {{7, 9}}; // (left alone when nothing is published)
uint64_t sorts = 0;
capunion::build(imports, pools, tex, small, only_gpu, b, &sorts);
compared++;
if (b.uni != uni_old) fail(what), std::printf(" the union differs (RX_VK_CAP_ONLY_GPU=%d): %zu ranges, %zu before\n", only_gpu, b.uni.size(), uni_old.size());
if (b.excl_made != pub_old) fail(what), std::printf(" the left-out ranges are %spublished (RX_VK_CAP_ONLY_GPU=%d)\n", b.excl_made ? "" : "not ", only_gpu);
if (pub_old && b.excl != excl_old) fail(what), std::printf(" the left-out ranges differ (RX_VK_CAP_ONLY_GPU=%d)\n", only_gpu);
if (!pub_old && excl_old != Ranges{{1, 2}}) fail(what), std::printf(" capture_union_locked touched the left-out ranges with RX_VK_CAP_ONLY_GPU=0\n");
if (!pub_old && b.excl != Ranges{{7, 9}}) fail(what), std::printf(" the left-out ranges were touched with RX_VK_CAP_ONLY_GPU=0\n");
}
}
int main() {
// merged_runs is ranges_merged, whatever the runs and wherever the cuts
for (int t = 0; t < 4000; t++) {
Ranges v;
size_t cut[2] = {0, 0};
for (int run = 0; run < 3; run++) {
const Ranges r = some((int)(rnd() % (t % 7 == 0 ? 200 : 12)), (int)(rnd() % 4), (rnd() % 64) * P, 1 + rnd() % 9);
v.insert(v.end(), r.begin(), r.end());
if (run < 2) cut[run] = v.size();
}
if (t % 5 == 0) cut[0] = rnd() % (v.size() + 3), cut[1] = rnd() % (v.size() + 3); // (any cuts: past the end, out of order)
compared++;
if (capunion::merged_runs(v, cut[0], cut[1], nullptr) != ranges_merged(v)) fail("merged_runs is not ranges_merged");
Ranges j = v;
std::sort(j.begin(), j.end());
capunion::join(j);
if (j != ranges_merged(v)) fail("join is not ranges_merged's join");
}
{ // sorted runs are not sorted again; an unsorted one is, and counted
Ranges a = some(300, 0, 0, 4), b = some(300, 1, 16 * P, 4), c = some(300, 2, 5 * P, 4);
std::sort(b.begin(), b.end()), std::sort(c.begin(), c.end()); // (overlapping and duplicates, in order)
Ranges v = a;
v.insert(v.end(), b.begin(), b.end());
v.insert(v.end(), c.begin(), c.end());
uint64_t sorts = 0;
if (capunion::merged_runs(v, a.size(), a.size() + b.size(), &sorts) != ranges_merged(v)) fail("three sorted runs: not ranges_merged");
if (sorts != 0) fail("three sorted runs were sorted again");
std::swap(v[a.size() + 3], v[a.size() + 200]);
sorts = 0;
if (capunion::merged_runs(v, a.size(), a.size() + b.size(), &sorts) != ranges_merged(v)) fail("an unsorted run: not ranges_merged");
if (sorts != 1) fail("one unsorted run of three: not one sort counted");
}
// the union and the left-out ranges
one_union({}, {}, {}, {}, "no list");
one_union({{16 * P, 32 * P}}, {}, {}, {}, "an import and no pool");
one_union({{16 * P, 32 * P}, {64 * P, 96 * P}}, {{18 * P, 20 * P}, {20 * P, 24 * P}, {70 * P, 71 * P}}, {{30 * P, 40 * P}},
{{18 * P, 20 * P}, {200 * P, 201 * P}}, "pools inside imports");
one_union({{64 * P, 96 * P}, {16 * P, 32 * P}, {16 * P, 32 * P}}, {{0, 300 * P}}, {{30 * P, 40 * P}, {40 * P, 41 * P}}, {},
"imports unsorted, with a duplicate");
for (int t = 0; t < 6000; t++) {
const int big = t % 11 == 0 ? 400 : 14;
// (as the game has them: imports are chunks, the pools small ranges inside and outside them, the texture storage and
// the small pools sorted and merged; and every list in any state)
const int kind = t % 3 == 0 ? (int)(rnd() % 4) : -1;
const Ranges imports = some((int)(rnd() % 8), kind < 0 ? (int)(rnd() % 2) : (int)(rnd() % 4), 0, 40);
Ranges pools = some((int)(rnd() % big), kind < 0 ? 0 : kind, (rnd() % 16) * P, 6);
Ranges tex = some((int)(rnd() % big), kind < 0 ? 0 : (int)(rnd() % 4), (rnd() % 32) * P, 6);
Ranges small = some((int)(rnd() % big), kind < 0 ? 0 : (int)(rnd() % 4), (rnd() % 16) * P, 6);
if (kind < 0) pools = ranges_merged(pools), tex = ranges_merged(tex), small = ranges_merged(small);
one_union(imports, pools, tex, small, "random lists");
}
{ // the game's shape: every list sorted and merged: no run sorted the slow way
Ranges imports = ranges_merged(some(40, 1, 0, 400)), pools = ranges_merged(some(2000, 1, 0, 6)), tex = ranges_merged(some(300, 1, 0, 40)),
small = ranges_merged(some(1500, 1, 0, 8));
capunion::Built b;
uint64_t sorts = 0;
capunion::build(imports, pools, tex, small, 1, b, &sorts);
if (sorts != 0) fail("lists that arrive sorted were sorted again");
Ranges excl;
bool pub = false;
if (b.uni != vk_union(imports, pools, tex, small, 1, excl, pub) || b.excl != excl) fail("the game's shape: the lists differ");
}
{ // one build a version, whoever asks; again when the version moves
capunion::Shared s;
int builds = 0;
uint64_t ver = 1; // (cap_ranges_ver starts at 1: nothing is shared before the first build)
const auto make = [&](Ranges& uni) { builds++, uni = {{ver * P, (ver + 1) * P}}; };
bool built = false;
const Ranges& a = capunion::get(s, ver, make, &built);
if (!built || builds != 1 || a != Ranges{{P, 2 * P}}) fail("the first caller of a version does not build");
built = true;
const Ranges& b = capunion::get(s, ver, make, &built);
if (built || builds != 1 || &a != &b || b != Ranges{{P, 2 * P}}) fail("the second caller of a version builds again");
for (int i = 0; i < 50; i++) capunion::get(s, ver, make, nullptr);
if (builds != 1) fail("a version built more than once");
ver = 2;
const Ranges& c = capunion::get(s, ver, make, &built);
if (!built || builds != 2 || c != Ranges{{2 * P, 3 * P}}) fail("a moved version does not build again");
ver = 1; // (any other version, not only a higher one)
capunion::get(s, ver, make, &built);
if (!built || builds != 3) fail("a version that differs does not build again");
}
// the switch, the knob, the pools' first captures
if (capunion::mode(nullptr) != capunion::ON || capunion::mode("") != capunion::ON || capunion::mode("1") != capunion::ON ||
capunion::mode("0") != capunion::OFF || capunion::mode("check") != capunion::CHECK || capunion::mode("00") != capunion::ON)
fail("RX_VK_CAP_UNION_SHARED: on unless 0, check");
if (!capunion::shared(capunion::ON, false) || !capunion::shared(capunion::CHECK, false) || capunion::shared(capunion::OFF, false) ||
capunion::shared(capunion::ON, true) || capunion::shared(capunion::CHECK, true) || capunion::shared(capunion::OFF, true))
fail("the shared union is on with the switch on or check, and off in the lab knob's phases");
if (capunion::first_seen_needed(0, true) || !capunion::first_seen_needed(0, false) || !capunion::first_seen_needed(1, true) ||
!capunion::first_seen_needed(30, false))
fail("the pools' first captures: kept with RX_VK_CAPTURE_EAGER, or as before with the switch off");
if (fails) std::printf("capunion: FAILED (%d of %ld)\n", fails, compared);
else std::printf("capunion: %ld lists, every one as before\n", compared);
return fails != 0;
}
"""
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--cxx", default="clang++")
args = parser.parse_args()
check((VK / "capunion.h").exists(), "gpu/vk/capunion.h is missing")
mem = (VK / "vk_memory.cpp").read_text(encoding="utf-8")
check('#include "capunion.h"' in mem, "vk_memory.cpp does not include capunion.h")
# the switch and the knob
mode = block(mem, "int cap_union_mode() {")
check('getenv("RX_VK_CAP_UNION_SHARED")' in mode and "static const int v" in mode and "capunion::mode(" in mode and
"if (m != capunion::ON)" in mode and "logf(" in mode, "RX_VK_CAP_UNION_SHARED is not read once, and logged when not the default")
shared = block(mem, "bool cap_union_shared() {")
check('return capunion::shared(cap_union_mode(), lab_ab::on("nocapunion"));' in shared,
"the shared union is not the switch's with the lab knob nocapunion")
# the old union is still there, unchanged, and only the taker and the check call it
old = block(mem, "std::vector<std::pair<uint64_t, uint64_t>> capture_union_locked() {")
for line in ("imp = ranges_merged(std::move(imp));", "keep = ranges_merged(std::move(keep));",
"std::vector<std::pair<uint64_t, uint64_t>> excl = ranges_clip(imp, keep, false);", "cap_excl.swap(excl);",
"if (cap_only_gpu() == 1) imp = ranges_clip(imp, all_pool_ranges, true);", "return ranges_merged(std::move(imp));"):
check(line in old, "capture_union_locked (the path of RX_VK_CAP_UNION_SHARED=0) changed: " + line)
take = block(mem, "void capture_union_take_locked(std::vector<std::pair<uint64_t, uint64_t>>& mine) {")
check(mem.count("capture_union_locked()") == 3 and take.count("capture_union_locked()") == 2,
"capture_union_locked is called elsewhere than by capture_union_take_locked (the switch off, and the check)")
check("if (!cap_union_shared()) {\n mine = capture_union_locked();" in take, "with the switch off a caller does not build its own union, as before")
check("capunion::get(cap_union, cap_ranges_ver," in take, "the shared union is not kept by cap_ranges_ver")
check("capunion::build(cap_ranges, all_pool_ranges, tex_cap_ranges, pool_cap_ranges, cap_only_gpu()," in take,
"the shared union is not built from the four lists and RX_VK_CAP_ONLY_GPU's mode")
check("mine = u;" in take and "return u" not in take and "const std::vector" not in take.split("{")[0],
"a caller does not get its own copy of the shared union (the shared one is read under cap_ranges_mu only)")
# (the left-out ranges: published where the union is built, with their version, under their lock; nowhere else in the taker)
pub = take[take.index("if (b.excl_made) {"):]
pub = pub[:pub.index("}") + 1]
check("std::lock_guard lk(cap_excl_mu);" in pub and "cap_excl.swap(b.excl);" in pub and
"cap_excl_ver.fetch_add(1, std::memory_order_release);" in pub and take.count("cap_excl_ver.fetch_add") == 1 and
take.count("cap_excl.swap(") == 1, "the left-out ranges are not published once, where the shared union is built")
check(take.index("if (b.excl_made) {") < take.index("mine = u;"), "the left-out ranges are published after a caller has the union")
check(take.count("cap_union_differs(") == 4 and "capunion::CHECK" in take, "the check does not count its differences (the union and the left-out ranges, built and reused)")
differs = block(mem, "void cap_union_differs(const char* what, size_t now, size_t before) {")
check("st_cu_diff.fetch_add(1, std::memory_order_relaxed) < 20" in differs and "logf(" in differs, "a difference is not counted, and the first 20 logged")
# the callers: their own version still gates, and the union comes through the taker
make = block(mem, "std::unique_ptr<Capture> capture_make(bool behind) {")
check("if (ver != cap_ranges_ver) {" in make and "ver = cap_ranges_ver;\n capture_union_take_locked(mirrored);" in make and
"texr = tex_cap_ranges;" in make, "capture_make does not take the shared union behind its own version (with its texture ranges)")
merged = block(mem, "const std::vector<std::pair<uint64_t, uint64_t>>& capture_ranges_merged() {")
check("static thread_local std::vector<std::pair<uint64_t, uint64_t>> merged;" in merged and
"ver = cap_ranges_ver;\n capture_union_take_locked(merged);" in merged and "return merged;" in merged,
"capture_ranges_merged does not copy the shared union into the calling thread's own list")
born = block(mem, "void cap_pool_born_now(uint64_t gpu, uint64_t size) {")
check("cap_excl = ranges_clip(cap_excl, {{lo, hi}}, false);" in born and "cap_ranges_ver++;" in born,
"cap_pool_born_now no longer takes a new pool out of the left-out ranges with the lists' version moved")
# the pool table's look
refresh = block(mem, "void refresh_pool_ranges_locked() {")
check("const bool cu = cap_union_shared();" in refresh and
"const bool first_seen = capunion::first_seen_needed(eager_captures(), cu);" in refresh and
"if (first_seen) pool_first_seen.swap(seen);" in refresh, "the pool table's look does not keep the pools' first captures by the rule")
check('cu ? cap_union_merged(std::move(every), cut, "the game\'s pools\' list (all_pool_ranges)") : ranges_merged(std::move(every));' in refresh and
'm = cap_union_merged(std::move(v), whole, "the small pools\' list (pool_cap_ranges)");' in refresh,
"the pool table's look does not merge its lists as sorted runs")
check("if (all != all_pool_ranges) all_pool_ranges = std::move(all), changed = true;" in refresh and
"if (m != pool_cap_ranges) pool_cap_ranges.swap(m), changed = true;" in refresh and "if (changed) cap_ranges_ver++;" in refresh,
"the pool table's look moves the lists' version by another rule")
runs = block(mem, "std::vector<std::pair<uint64_t, uint64_t>> cap_union_merged(std::vector<std::pair<uint64_t, uint64_t>> v, size_t cut, const char* what) {")
check("capunion::merged_runs(" in runs and "ranges_merged(" in runs and "cap_union_differs(what," in runs,
"cap_union_merged has no check against ranges_merged that names its list")
# the counters, in the capture's 10 s line
present = block(mem, "void memory_cap_present() {")
check("RX_VK_CAP_UNION_SHARED=%s" in present and all(c in present for c in ("st_cu_built", "st_cu_reused", "st_cu_own", "st_cu_sorts", "st_cu_diff")),
"the capture's 10 s line does not carry the shared union's counters")
dev = (ROOT / "docs" / "development.md").read_text(encoding="utf-8")
check("| `RX_VK_CAP_UNION_SHARED=0`, `=check` |" in dev and "`nocapunion`" in dev and "tests/test_capunion.py" in dev,
"docs/development.md: RX_VK_CAP_UNION_SHARED is not in the switches table")
# (the old union and the helpers it calls, as they are in the source: compiled against capunion.h's copies below)
real = "\n".join(cut_block(mem, m, where="gpu/vk/vk_memory.cpp") for m in (
"std::vector<std::pair<uint64_t, uint64_t>> ranges_merged(std::vector<std::pair<uint64_t, uint64_t>> v) {",
"std::vector<std::pair<uint64_t, uint64_t>> ranges_clip(const std::vector<std::pair<uint64_t, uint64_t>>& a,",
"std::vector<std::pair<uint64_t, uint64_t>> capture_union_locked() {"))
with tempfile.TemporaryDirectory(prefix="capunion-") as tmp:
src, exe = Path(tmp) / "capunion.cpp", Path(tmp) / "capunion.exe"
src.write_text(PROGRAM.replace("@CUT@", real), encoding="utf-8")
subprocess.run([args.cxx, "-std=c++20", "-O2", "-Wall", "-Wextra", "-Werror", "-I" + str(VK), str(src), "-o", str(exe)], check=True)
r = subprocess.run([str(exe)], capture_output=True, text=True, timeout=300)
print(r.stdout.rstrip())
check(r.returncode == 0, "the shared union's lists are not the lists as before")
print("PASS: one union of the captures' lists a version for every caller, its lists what they were")
if __name__ == "__main__":
main()

View File

@@ -4,19 +4,27 @@ vk_replay.cpp part_draws and maybe_split; no game, no GPU).
(Triforce, 11-22, the performance audit's SYNC-66, after Source B's.) A long submission goes to the GPU in parts of 120 draws
and dispatches on every card, read once into a static of maybe_split, so nothing could compare sizes inside a run. The size is
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.
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.
Compiles a driver against barrier_rules.h and lab_ab.h and checks:
the default is 120 for NVIDIA, AMD, Intel and any other vendor, with RADV or not;
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 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 vendors: the default path splits where it split;
any number) on random drivers, except unset on NVIDIA's driver (240): the default path splits where it split elsewhere;
RX_VK_CHUNK beats the knob and the default; 0 stays 0 (never split); the knob beats the default only in its own phases
(lab_ab.h's value_of with the phase's knob set, another knob's phase, and no phase).
(lab_ab.h's value_of with the phase's knob set, another knob's phase, and no phase), with NVIDIA's 240 and NVK's 120 as the
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; part_draws reads the variable once and the knob at each
call; the switches table has the row and no longer says the in-pass split is on with NVIDIA's driver.
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
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
driver.
python -I -B tests/test_chunk_default.py [--cxx clang++]
python -I -B tests/test_chunk_default.py --headers <Vulkan-Headers/include> [--cxx clang++]
"""
import argparse
import subprocess
@@ -24,11 +32,12 @@ import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
RUN_ALL_ARGS = ["--cxx", "{cxx}", "--headers", "{vulkan_headers}"]
DRIVER = r'''
#include "barrier_rules.h"
#include "lab_ab.h"
#include <vulkan/vulkan_core.h>
#include <cstdio>
namespace br = mkwvk::barrier_rules;
@@ -37,10 +46,27 @@ static int checks, fails;
#define CHECK(what, cond) do { checks++; if (!(cond)) fails++, printf("FAIL %s (line %d)\n", what, __LINE__); } while (0)
int main() {
static const uint32_t kVendors[] = {0x10de, 0x1002, 0x8086, 0x5143, 0x13b5, 0, 0xffffffffu};
for (const uint32_t v : kVendors)
for (int radv = 0; radv < 2; radv++) CHECK("120 for every driver until the lab picks", br::part_draws_default(v, radv != 0) == 120);
CHECK("the constant", br::kPartDraws == 120);
// the device's driver id (dev.driver_id): NVIDIA's own driver has one on Windows and Linux; the drivers that run on NVIDIA's
// cards beside it (NVK, Dozen, Venus) report its vendor, 0x10de, and keep 120 until the lab has measured them
static const struct { const char* what; uint32_t driver; int64_t want; } kDrivers[] = {
{"NVIDIA's driver (one id on Windows and Linux): 240", VK_DRIVER_ID_NVIDIA_PROPRIETARY, 240},
{"NVK on an NVIDIA card: 120", VK_DRIVER_ID_MESA_NVK, 120},
{"Dozen on an NVIDIA card: 120", VK_DRIVER_ID_MESA_DOZEN, 120},
{"Venus on an NVIDIA card: 120", VK_DRIVER_ID_MESA_VENUS, 120},
{"RADV: 120", VK_DRIVER_ID_MESA_RADV, 120},
{"AMD's driver: 120", VK_DRIVER_ID_AMD_PROPRIETARY, 120},
{"AMDVLK: 120", VK_DRIVER_ID_AMD_OPEN_SOURCE, 120},
{"Intel's Windows driver: 120", VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS, 120},
{"Intel's Mesa driver: 120", VK_DRIVER_ID_INTEL_OPEN_SOURCE_MESA, 120},
{"llvmpipe: 120", VK_DRIVER_ID_MESA_LLVMPIPE, 120},
{"MoltenVK: 120", VK_DRIVER_ID_MOLTENVK, 120},
{"no driver id (0): 120", 0, 120},
{"an id from a later header: 120", 0x7fffffffu, 120},
};
constexpr size_t kN = sizeof kDrivers / sizeof *kDrivers;
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);
// with no knob: the old read, whatever the variable says
uint64_t rng = 0xD1B54A32D192ED03ull;
@@ -50,28 +76,42 @@ int main() {
char num[32];
const char* env = kTexts[rnd(sizeof kTexts / sizeof *kTexts)];
if (rnd(3) == 0) snprintf(num, sizeof num, "%lld", (long long)rnd(5000) - 500), env = num;
const uint32_t vendor = kVendors[rnd(sizeof kVendors / sizeof *kVendors)];
const int64_t now = br::part_draws(env != nullptr, env ? atoll(env) : 0, br::part_draws_default(vendor, rnd(2) != 0));
CHECK("with no knob the size is the old read's", now == br::part_draws_before(env));
const uint32_t driver = kDrivers[rnd(kN)].driver;
const int64_t now = br::part_draws(env != nullptr, env ? atoll(env) : 0, br::part_draws_default(driver));
const int64_t was = !env && driver == VK_DRIVER_ID_NVIDIA_PROPRIETARY ? 240 : br::part_draws_before(env);
CHECK("with no knob the size is the old read's (unset on NVIDIA's driver: 240)", now == was);
if (fails) break;
}
CHECK("unset: 120", br::part_draws(false, 0, br::part_draws_default(0x10de, false)) == 120);
const int64_t nvidia = br::part_draws_default(VK_DRIVER_ID_NVIDIA_PROPRIETARY), nvk = br::part_draws_default(VK_DRIVER_ID_MESA_NVK);
CHECK("unset on NVIDIA's driver: 240", br::part_draws(false, 0, nvidia) == 240);
CHECK("unset on NVK: 120", br::part_draws(false, 0, nvk) == 120);
CHECK("unset on AMD's: 120", br::part_draws(false, 0, br::part_draws_default(VK_DRIVER_ID_AMD_PROPRIETARY)) == 120);
CHECK("unset on RADV: 120", br::part_draws(false, 0, br::part_draws_default(VK_DRIVER_ID_MESA_RADV)) == 120);
CHECK("unset on Intel's: 120", br::part_draws(false, 0, br::part_draws_default(VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS)) == 120);
CHECK("RX_VK_CHUNK=120 on NVIDIA's driver: 120", br::part_draws(true, 120, nvidia) == 120);
CHECK("RX_VK_CHUNK beats the knob", br::part_draws(true, 240, 480) == 240);
CHECK("RX_VK_CHUNK=0 stays 0 under a knob", br::part_draws(true, 0, 480) == 0);
CHECK("the knob beats the default", br::part_draws(false, 0, 480) == 480);
// the knob through lab_ab.h, as vk_replay.cpp's part_draws asks it: only in its own phases
CHECK("no RX_VK_LAB_AB: the default", (lab::n_knobs = 0, lab::value_of("chunk", 120)) == 120);
// the knob through lab_ab.h, as vk_replay.cpp's part_draws asks it (the driver's default beside it): only in its own
// phases. The measured A/B, chunk:120 against NVIDIA's 240; and maybe_split's pass-end parts step aside in its phases alone
CHECK("no RX_VK_LAB_AB: the default", (lab::n_knobs = 0, lab::value_of("chunk", nvidia)) == 240);
CHECK("no RX_VK_LAB_AB: the pass-end parts' test passes", lab::value_of("chunk", -1) < 0);
lab::n_knobs = 2;
snprintf(lab::knobs[0].name, sizeof lab::knobs[0].name, "chunk"), lab::knobs[0].value = 480;
snprintf(lab::knobs[0].name, sizeof lab::knobs[0].name, "chunk"), lab::knobs[0].value = 120;
snprintf(lab::knobs[1].name, sizeof lab::knobs[1].name, "rblate"), lab::knobs[1].value = 1;
lab::active.store(0);
CHECK("a phase with no knob: the default", br::part_draws(false, 0, lab::value_of("chunk", 120)) == 120);
CHECK("a phase with no knob on NVIDIA's driver: 240", br::part_draws(false, 0, lab::value_of("chunk", nvidia)) == 240);
CHECK("a phase with no knob on NVK: 120", br::part_draws(false, 0, lab::value_of("chunk", nvk)) == 120);
CHECK("a phase with no knob: the pass-end parts' test passes", lab::value_of("chunk", -1) < 0);
lab::active.store(1);
CHECK("the knob's phase: its number", br::part_draws(false, 0, lab::value_of("chunk", 120)) == 480);
CHECK("the knob's phase, the variable set: the variable", br::part_draws(true, 120, lab::value_of("chunk", 120)) == 120);
CHECK("the knob chunk:120's phase on NVIDIA's driver: 120", br::part_draws(false, 0, lab::value_of("chunk", nvidia)) == 120);
CHECK("the knob's phase on NVK: its number", br::part_draws(false, 0, lab::value_of("chunk", nvk)) == 120);
CHECK("the knob's phase, the variable set: the variable", br::part_draws(true, 480, lab::value_of("chunk", nvidia)) == 480);
CHECK("the knob's phase: the pass-end parts step aside", lab::value_of("chunk", -1) == 120);
lab::active.store(2);
CHECK("another knob's phase: the default", br::part_draws(false, 0, lab::value_of("chunk", 120)) == 120);
CHECK("another knob's phase: the default", br::part_draws(false, 0, lab::value_of("chunk", nvidia)) == 240);
CHECK("another knob's phase: the pass-end parts' test passes", lab::value_of("chunk", -1) < 0);
if (fails) printf("chunk default: FAILED (%d of %d checks)\n", fails, checks);
else printf("chunk default: all %d checks passed\n", checks);
@@ -97,6 +137,8 @@ def check_source():
check(split.startswith("void maybe_split(VkCommandBuffer& cmd) {\n const int64_t every = part_draws();\n"),
"maybe_split does not ask part_draws() at each call")
check('getenv("RX_VK_CHUNK")' not in split, "maybe_split reads RX_VK_CHUNK itself")
check('if (pe.on && !part_end_now && lab_ab::value_of("chunk", -1) < 0) {' in split,
"maybe_split's pass-end parts are no longer left in the knob's phases alone (the docs' Threaded rendering note)")
check("if (tail_on()) return;" in split and
"if (!rec_cur || every <= 0 || ++part_work < every || rec_parts + 1 >= kMaxParts || dump_on()) return;" in split and
split.index("if (tail_on()) return;") < split.index("++part_work < every"),
@@ -104,20 +146,48 @@ def check_source():
part = function(replay, "int64_t part_draws() {")
check('static const char* const env = getenv("RX_VK_CHUNK");' in part and "static const int64_t env_value = env ? atoll(env) : 0;" in part,
"part_draws does not read RX_VK_CHUNK once")
check("barrier_rules::part_draws_default(dev.props.vendorID, radv);" in part, "the default is not asked of the rule with the driver")
check("barrier_rules::part_draws_default((uint32_t)dev.driver_id);" in part and "#if" not in part and "vendorID" not in part,
"the default is not asked of the rule with the device's driver id alone (NVK reports NVIDIA's vendor)")
check("pass_end_parts_on()" in part and "not in force" in part,
"part_draws' line does not say when Threaded rendering's pass-end parts decide instead of the size")
# (with those parts on and RX_VK_CHUNK unset the printed default is never in force: the knob's number decides in its phases)
check("env ? \"; not in force outside the knob's phases: " in part and '"; not in force: a part ends where' in part,
"part_draws' line says the driver's default is in force in the knob's phases under Threaded rendering's parts")
check(part.rstrip().endswith('return barrier_rules::part_draws(env != nullptr, env_value, lab_ab::value_of("chunk", by_driver));'),
"part_draws does not ask the knob at each call, behind the variable")
# ((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,
"pass_end_parts' switch changed: the docs say any RX_VK_CHUNK turns Threaded rendering's parts off")
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")
at = rules.index("RX_VK_CHUNK: how many draws")
note = rules[at:rules.index("constexpr int64_t kPartDraws", at)]
for need in ("NVK", "Threaded rendering", "RX_VK_PART_PASS_END not 1", "RX_VK_PART_PASS_END=0", "v0.8.3", "v0.8.4"):
check(need in note, "barrier_rules.h's part-size comment does not name " + need)
check("a few more reports keep" not in note, "barrier_rules.h's part-size comment still gives the occlusion counts a direction")
dev = (ROOT / "docs/development.md").read_text(encoding="utf-8")
row = [line for line in dev.splitlines() if line.startswith("| `RX_VK_CHUNK=<n>` |")]
check(len(row) == 1 and "**120 on every driver**" in row[0] and "`chunk:<n>`" in row[0], "docs/development.md: no row for RX_VK_CHUNK with its default")
check(len(row) == 1 and "**240 on NVIDIA's driver**" in row[0] and "**120 on every other driver**" in row[0] and
"`chunk:<n>`" in row[0], "docs/development.md: no row for RX_VK_CHUNK with its defaults")
check("NVK" in row[0] and "measured only on" in row[0], "the RX_VK_CHUNK row does not say NVK keeps 120 or where 240 was measured")
check("Threaded rendering" in row[0] and "`RX_VK_PART_PASS_END=0`" in row[0] and "leave `RX_VK_CHUNK` unset" in row[0],
"the RX_VK_CHUNK row does not say its size and its switch back are for parts cut by count, not Threaded rendering's")
check("`RX_VK_LAB_AB=chunk:120,chunk:480`" in row[0] and "chunk:480,chunk:240" not in row[0],
"the RX_VK_CHUNK row's lab example does not compare against the old size")
there = row[0][row[0].index("leave `RX_VK_CHUNK` unset"):row[0].index("The size was read once")]
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")
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")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--headers", type=Path, required=True)
parser.add_argument("--cxx", default="clang++")
args = parser.parse_args()
check_source()
@@ -125,12 +195,13 @@ def main():
src = Path(tmp) / "driver.cpp"
src.write_text(DRIVER, encoding="utf-8")
exe = Path(tmp) / "driver.exe"
subprocess.run([args.cxx, "-std=c++20", "-Wall", "-Wextra", "-Werror", "-I", str(ROOT / "gpu/vk"), str(src), "-o", str(exe)],
subprocess.run([args.cxx, "-std=c++20", "-Wall", "-Wextra", "-Werror", "-I", str(ROOT / "gpu/vk"), "-I", str(args.headers), str(src),
"-o", str(exe)],
check=True)
out = subprocess.run([str(exe)], capture_output=True, text=True)
print(out.stdout, end="")
check(out.returncode == 0, "the rule's checks failed")
print("PASS: a part's size: RX_VK_CHUNK, then the lab knob, then the driver's default, 120 for each")
print("PASS: a part's size: RX_VK_CHUNK, then the lab knob, then the driver's default, 240 on NVIDIA's and 120 for the rest (NVK too)")
if __name__ == "__main__":

409
tests/test_cpuwordsseen.py Normal file
View File

@@ -0,0 +1,409 @@
"""A report word the sets hold already is not noted again (gpu/vk/cpuwordsseen.h; vk_memory.cpp memory_cpu_owned; no game,
no GPU).
(Triforce, 11-26.) Every word of every counter report the replay writes into guest memory is noted (memory_cpu_owned),
so that a mirror's write-back leaves it out (the one-frame dark flashes of 11-07). The same words come every frame, and
each was pushed again, sorted again and searched for in both sets at every part's end (cpu_words_merge). A table of the
words the sets hold (the full address and the sets' generation in each entry) answers that at the note now.
This compiles the header with vk_memory.cpp's own sorted_merge, cpu_words_merge, memory_cpu_owned and cut_cpu_words cut
from the source, and
- asks the table at random against a std::set: it never calls a word known that was not marked since the last
forget(), whatever shares its entry, and two words that share an entry only push each other out;
- runs one fixed run of notes and write-back cuts three times, with the table off (the code as it was), on, and
checking: the same report words frame after frame (some given unaligned), new ones mixed in, words that share a
table entry with them, bursts past 65,536 words (the sets are forgotten) and the same words again after it. At
every cut the two sets together are the words a std::set model holds and the cut runs are the same in all three,
and the check counts no mismatch;
- counts what reaches the merge over frames that only repeat: every word without the table; with it nothing, but for
the few report words another word pushed out of their table entry the frame before, once;
- builds the same file from the source with the table's forget() taken out of the clear: that build must give other
runs than the model, and its check must count mismatches (so the cases mean something).
And reads the source: the sets are cleared in one place and the table forgets there; the three sets are named only in
their declaration and the four functions the program above compiles (the comments left out), so no other code can take
a word out of them; the table is asked, marked and forgotten only by memory_cpu_owned under cpu_words_mu (only its
atomic counters are read elsewhere); the switch is read once (a value other than 1, 0 or check logged) and the lab knob
at each note, the status line has the counters and the switches table has the row.
python -I -B tests/test_cpuwordsseen.py [--cxx clang++]
"""
import argparse
import os
import re
import subprocess
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
VK = ROOT / "gpu" / "vk"
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
def check(ok, why):
if not ok:
raise SystemExit("FAIL: " + why)
def block(text, marker):
check(marker in text, "vk_memory.cpp has no " + marker)
start = text.index(marker)
end = text.index("{", start + len(marker) - 1) + 1
depth = 1
while depth:
depth += (text[end] == "{") - (text[end] == "}")
end += 1
return text[start:end]
def code_only(text):
"""text with its // and /* */ comments blanked (newlines kept, so offsets and lines stay); string and character
literals are left as they are"""
out, i, n = list(text), 0, len(text)
while i < n:
c = text[i]
if c in "\"'":
j = i + 1
while j < n and text[j] != c and text[j] != "\n":
j += 2 if text[j] == "\\" else 1
i = j + 1
elif text.startswith("//", i):
j = text.find("\n", i)
j = n if j < 0 else j
out[i:j] = " " * (j - i)
i = j
elif text.startswith("/*", i):
j = text.find("*/", i + 2)
j = n if j < 0 else j + 2
out[i:j] = [ch if ch == "\n" else " " for ch in text[i:j]]
i = j
else:
i += 1
return "".join(out)
# (where the three sets may be named: their declaration and the four functions PROGRAM compiles and runs)
SET_DECL = "std::vector<uint64_t> cpu_words, cpu_words_recent, cpu_words_new;"
SET_USERS = ("void cpu_words_merge() {", "void memory_cpu_owned(uint64_t guest, uint64_t size) {", "void cut_cpu_words(")
def stray_set_uses(mem):
"""The lines that name cpu_words, cpu_words_recent or cpu_words_new outside SET_DECL and SET_USERS' blocks. An
allowlist, not a list of the calls that remove words: a member call, std::erase_if, std::swap on either side,
std::move or a reference taken elsewhere are all caught, and every edit inside the blocks is run by the program"""
code = code_only(mem)
spans = [(code.index(SET_DECL), code.index(SET_DECL) + len(SET_DECL))]
for marker in SET_USERS:
start = mem.index(marker)
spans.append((start, start + len(block(mem, marker))))
return sorted({code.count("\n", 0, m.start()) + 1 for m in re.finditer(r"\bcpu_words(_recent|_new)?\b", code)
if not any(a <= m.start() < b for a, b in spans)})
PROGRAM = r"""
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <mutex>
#include <set>
#include <string>
#include <vector>
#include "cpuwordsseen.h"
static int fails = 0;
#define CHECK(ok) do { if (!(ok)) { if (fails++ < 20) std::printf("FAIL:%d %s\n", __LINE__, #ok); } } while (0)
struct Pool { uint64_t lo; };
struct VkBufferCopy { uint64_t srcOffset, dstOffset, size; };
std::mutex cpu_words_mu;
bool wb_notes_off() { return false; } // (the mirrors are on here)
std::vector<uint64_t> cpu_words, cpu_words_recent, cpu_words_new;
cpu_words_seen::Table cpu_words_table;
static int g_mode = cpu_words_seen::ON;
int cpu_words_seen_mode() { return g_mode; } // (vk_memory.cpp's reads the switch and the lab knob)
/* ACTUAL */
static uint64_t rnd_state;
static uint64_t rnd() {
rnd_state ^= rnd_state << 13, rnd_state ^= rnd_state >> 7, rnd_state ^= rnd_state << 17;
return rnd_state;
}
using cpu_words_seen::Table;
// another word in w's entry of the table
static uint64_t shares_entry(uint64_t w) {
for (uint64_t c = w + 8;; c += 8)
if (Table::slot(c) == Table::slot(w)) return c;
}
// ---- the table alone, against a set ----
static void table_against_a_set() {
static Table t;
std::set<uint64_t> marked;
rnd_state = 0x9E3779B97F4A7C15ull;
long known = 0, pushed_out = 0;
for (int i = 0; i < 3000000; i++) {
// (300,000 words over 131,072 entries: most entries are shared; half the asks are of 2,000 words that repeat)
const uint64_t w = 0x2000000000ull + (rnd() % 2 ? rnd() % 2000 : rnd() % 300000) * 8;
if (rnd() % 400000 == 0) t.forget(), marked.clear();
if (t.known(w)) {
known++;
CHECK(marked.count(w) == 1); // (never known without being held)
} else {
pushed_out += marked.count(w);
t.mark(w), marked.insert(w);
CHECK(t.known(w));
}
}
CHECK(known > 500000 && pushed_out > 1000);
// two words in one entry: each pushes the other out, neither is taken for the other
const uint64_t a = 0x80001000, b = shares_entry(a);
CHECK(a != b && Table::slot(a) == Table::slot(b));
t.forget();
CHECK(!t.known(a) && !t.known(b));
t.mark(a);
CHECK(t.known(a) && !t.known(b));
t.mark(b);
CHECK(t.known(b) && !t.known(a));
t.forget();
CHECK(!t.known(a) && !t.known(b)); // (the forget takes every word at once)
CHECK(!t.known(0)); // (an entry never written is no word, address 0 neither)
// the switch
using namespace cpu_words_seen;
CHECK(mode(nullptr) == ON && mode("") == ON && mode("1") == ON && mode("0") == OFF && mode("check") == CHECK_BOTH);
CHECK(mode("on") == ON && mode("true") == ON && mode("2") == ON && mode("Check") == ON); // (any other value: as unset)
CHECK(mode_now(ON, false) == ON && mode_now(ON, true) == OFF && mode_now(CHECK_BOTH, false) == CHECK_BOTH &&
mode_now(CHECK_BOTH, true) == OFF && mode_now(OFF, false) == OFF);
CHECK(kSlots >= 65536 * 2); // (the sets hold up to 65,536 words)
// push(): off pushes everything and marks nothing; on pushes a word once; checking pushes all and counts
static Table p;
std::vector<uint64_t> none, big{a};
CHECK(push(p, OFF, a, none, none, none) && !p.known(a) && p.st_noted.load() == 0);
CHECK(push(p, ON, a, none, none, none) && p.known(a));
CHECK(!push(p, ON, a, big, none, none) && p.st_noted.load() == 2 && p.st_known.load() == 1);
CHECK(push(p, CHECK_BOTH, a, big, none, none) && p.st_mismatch.load() == 0); // (held in the big set)
CHECK(push(p, CHECK_BOTH, a, none, big, none) && p.st_mismatch.load() == 0); // (in the recent one)
CHECK(push(p, CHECK_BOTH, a, none, none, big) && p.st_mismatch.load() == 0); // (noted since the merge)
CHECK(push(p, CHECK_BOTH, a, none, none, none) && p.st_mismatch.load() == 1); // (known to the table, held nowhere)
CHECK(p.st_known.load() == 5);
// (off with a word the table knows: the lab knob's phases come after phases that marked words, and must push them all
// as before, counting nothing)
CHECK(p.known(a) && push(p, OFF, a, none, none, none) && p.st_noted.load() == 6 && p.st_known.load() == 5);
}
// ---- memory_cpu_owned and cut_cpu_words: one fixed run, the table off, on and checking ----
struct Result {
std::vector<uint64_t> log; // (at every cut: the sets' size and hash, the cut runs' hash)
std::vector<size_t> reached; // (what reached the merge in each frame that only repeated)
uint64_t noted = 0, known = 0, forgets = 0, mismatch = 0;
int model_differs = 0;
};
static uint64_t hash(uint64_t h, uint64_t v) { return (h ^ v) * 1099511628211ull; }
static Result run(int mode) {
Result r;
g_mode = mode;
cpu_words.clear(), cpu_words_recent.clear(), cpu_words_new.clear();
cpu_words_table.forget(); // (a run starts with empty sets)
const uint64_t noted0 = cpu_words_table.st_noted.load(), known0 = cpu_words_table.st_known.load(),
forgets0 = cpu_words_table.st_forgets.load(), mismatch0 = cpu_words_table.st_mismatch.load();
rnd_state = 0x1234567887654321ull;
const Pool pool{0x80000000};
const uint64_t reports = pool.lo + 0x10000; // (250 reports of 16 bytes: 500 words)
std::set<uint64_t> model;
// memory_cpu_owned as it was, on a set: both sets forgotten at a note that finds more than 65,536 words held
auto note = [&](uint64_t guest, uint64_t size) {
if (model.size() > 65536) model.clear();
for (uint64_t a = guest & ~7ull; a < guest + size; a += 8) model.insert(a);
memory_cpu_owned(guest, size);
};
auto cut = [&] {
std::vector<VkBufferCopy> runs;
for (int k = 0; k < 6; k++) {
const uint64_t at = rnd() % 0x30000, len = 1 + rnd() % 0x4000;
runs.push_back({at, at, len});
}
runs.push_back({0x10000 - 12, 0x10000 - 12, 500 * 8 + 40}); // (over all the reports, from inside a word before them)
cut_cpu_words(pool, runs);
CHECK(cpu_words_new.empty());
std::vector<uint64_t> both(cpu_words);
both.insert(both.end(), cpu_words_recent.begin(), cpu_words_recent.end());
std::sort(both.begin(), both.end());
if (std::adjacent_find(both.begin(), both.end()) != both.end() || both.size() != model.size() ||
!std::equal(both.begin(), both.end(), model.begin()))
r.model_differs++;
uint64_t h = 1469598103934665603ull;
for (uint64_t w : both) h = hash(h, w);
r.log.push_back(both.size()), r.log.push_back(h);
h = 1469598103934665603ull;
for (const VkBufferCopy& c : runs) h = hash(hash(hash(h, c.srcOffset), c.dstOffset), c.size);
r.log.push_back(runs.size()), r.log.push_back(h);
};
for (int frame = 0; frame < 100; frame++) {
const bool only_repeats = frame % 10 >= 6 && frame % 10 <= 8; // (three frames in ten with nothing new)
const size_t new0 = cpu_words_new.size();
for (int i = 0; i < 250; i++) {
// (the same reports every frame; one in sixteen given from inside its first word, which takes a third word in)
if (i % 16 == 5 && !only_repeats) note(reports + 16 * (uint64_t)i + 4, 16);
else note(reports + 16 * (uint64_t)i, 16);
if (only_repeats) continue;
if (rnd() % 8 == 0) note(pool.lo + (rnd() % 0x6000) * 8, 16); // (reports at new addresses)
if (rnd() % 16 == 0) note(shares_entry(reports + 16 * (rnd() % 250)), 8); // (a word in a report word's entry)
if (rnd() % 97 == 0) cut(); // (a part's end with write-backs)
}
if (only_repeats) r.reached.push_back(cpu_words_new.size() - new0);
cut();
if (frame % 25 == 12) // (a burst of new words: the sets pass 65,536 and are forgotten, and the reports come again)
for (int k = 0; k < 9000; k++) {
note(0x90000000ull + (uint64_t)frame * 0x1000000 + (uint64_t)k * 64, 64);
if (k % 1000 == 999) note(reports, 500 * 8), cut();
}
}
r.noted = cpu_words_table.st_noted.load() - noted0, r.known = cpu_words_table.st_known.load() - known0;
r.forgets = cpu_words_table.st_forgets.load() - forgets0, r.mismatch = cpu_words_table.st_mismatch.load() - mismatch0;
return r;
}
int main(int argc, char** argv) {
const std::string test = argc == 2 ? argv[1] : "";
using namespace cpu_words_seen;
if (test == "table") {
table_against_a_set();
} else if (test == "runs") {
const Result off = run(OFF), on = run(ON), both = run(CHECK_BOTH);
CHECK(off.model_differs == 0 && on.model_differs == 0 && both.model_differs == 0);
CHECK(off.log.size() > 400 && off.log == on.log && off.log == both.log);
CHECK(off.noted == 0 && off.known == 0 && off.forgets == 4); // (off: the table is not asked; the sets were forgotten in each burst)
CHECK(on.forgets == off.forgets && both.forgets == off.forgets);
CHECK(on.noted > 300000 && on.known > 60000 && on.mismatch == 0); // (the bursts' words are new; the reports' are known)
CHECK(both.noted == on.noted && both.mismatch == 0);
CHECK(off.reached.size() == 30 && on.reached.size() == 30);
for (size_t i = 0; i < off.reached.size() && i < on.reached.size(); i++) {
CHECK(off.reached[i] == 500); // (as it was: every word again)
// (the first of each three comes after a frame with words in report words' entries: the reports pushed out
// of the table are noted once more, and take their entries back; then nothing reaches the merge)
if (i % 3 == 0) CHECK(on.reached[i] > 0 && on.reached[i] < 60);
else CHECK(on.reached[i] == 0);
}
std::printf("noted %llu known %llu forgets %llu\n", (unsigned long long)on.noted, (unsigned long long)on.known,
(unsigned long long)on.forgets);
} else if (test == "stale") { // (for the build without the forget: what the table on, and the check, make of it)
const Result on = run(ON), both = run(CHECK_BOTH);
std::printf("differs %d mismatch %llu\n", on.model_differs, (unsigned long long)both.mismatch);
return 0;
} else {
std::printf("a known case\n");
return 1;
}
return fails != 0;
}
"""
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--cxx", default="clang++")
args = parser.parse_args()
check((VK / "cpuwordsseen.h").is_file(), "gpu/vk/cpuwordsseen.h is missing: report words are noted again every frame")
head = (VK / "cpuwordsseen.h").read_text(encoding="utf-8")
mem = (VK / "vk_memory.cpp").read_text(encoding="utf-8")
# the rule: an entry is the whole address and the generation, and both are compared
check("#pragma once" in head and "namespace cpu_words_seen {" in head, "cpuwordsseen.h is not the rule header")
check("uint64_t word, stamp;" in head and "return x.stamp == forgets + 1 && x.word == word;" in head,
"a table entry is not known by its whole address and the sets' generation")
check("RX_VK_CPU_WORDS_SEEN" in head and "nowordsseen" in head, "the header does not name its switch and its lab knob")
# the hook: one clear of the sets, the table forgets there; asked and written only inside memory_cpu_owned's lock
check('#include "cpuwordsseen.h"' in mem, "vk_memory.cpp does not include cpuwordsseen.h")
owned = block(mem, "void memory_cpu_owned(uint64_t guest, uint64_t size) {")
clear = "cpu_words.clear(), cpu_words_recent.clear(), cpu_words_table.forget();"
check(mem.count("cpu_words.clear()") == 1 and clear in owned, "the sets are cleared without the table forgetting, or in a second place")
check(mem.count("cpu_words_table.forget()") == 1, "the table forgets somewhere else too")
check(mem.count("cpu_words_recent.clear()") == 2 and
"sorted_merge(cpu_words, cpu_words_recent.data(), cpu_words_recent.data() + cpu_words_recent.size());\n cpu_words_recent.clear();"
in block(mem, "void cpu_words_merge() {"), "the recent set is emptied other than into the big one")
# (no word leaves a set any other way: the sets are named nowhere else, and inside the blocks the words noted since the
# merge are emptied once, at the merge's end, and thinned once, to their unique words)
stray = stray_set_uses(mem)
check(not stray, "vk_memory.cpp names the report word sets outside their declaration and %s (lines %s): a word may leave "
"them without the table forgetting" % (", ".join(m.split("(")[0][5:] for m in SET_USERS), stray))
check(stray_set_uses(mem + "\nvoid stray() {\n std::lock_guard lk(cpu_words_mu);\n cpu_words_new.clear();\n}\n") and
stray_set_uses(mem + "\nvoid stray(std::vector<uint64_t>& x) { std::swap(x, cpu_words); }\n"),
"the scan does not catch a set emptied in another function")
merge = block(mem, "void cpu_words_merge() {")
code = code_only(mem)
check(code.count("cpu_words_new.clear()") == 1 and "cpu_words_new.clear()" in code_only(merge),
"the words noted since the merge are emptied somewhere else than at the merge's end")
unique = [l for l in code.split("\n") if "cpu_words_new.erase(" in l]
check(len(unique) == 1 and "std::unique(cpu_words_new.begin(), cpu_words_new.end())" in unique[0],
"the words noted since the merge are erased other than to their unique words")
push = "if (cpu_words_seen::push(cpu_words_table, seen, a, cpu_words, cpu_words_recent, cpu_words_new)) cpu_words_new.push_back(a);"
lock = "std::lock_guard lk(cpu_words_mu);"
check(mem.count("cpu_words_seen::push(") == 1 and push in owned and owned.index(lock) < owned.index(clear) < owned.index(push),
"memory_cpu_owned does not ask the table for each word, under its lock, after the clear")
rest = code.replace("cpu_words_seen::Table cpu_words_table;", "", 1).replace(clear, "", 1).replace(push, "", 1)
for st in ("st_noted", "st_known", "st_forgets", "st_mismatch"):
rest = rest.replace("cpu_words_table." + st + ".load(std::memory_order_relaxed)", "", 1)
check("cpu_words_table" not in rest, "the table is used other than by memory_cpu_owned's push and forget under "
"cpu_words_mu (only its atomic counters are read elsewhere)")
check("cpu_words_new.push_back(" not in mem.replace(push, ""), "a word is noted past the table")
check("const int seen = cpu_words_seen_mode();" in owned, "memory_cpu_owned does not read the switch's mode at each note")
# the switch read once and logged when not the default; the lab knob at each note
mode = block(mem, "int cpu_words_seen_mode() {")
check(mem.count('getenv("RX_VK_CPU_WORDS_SEEN")') == 1 and "static const int env = [] {" in mode and
'const char* e = getenv("RX_VK_CPU_WORDS_SEEN");' in mode and "const int m = cpu_words_seen::mode(e);" in mode and
"if (m != cpu_words_seen::ON) logf(" in mode,
"RX_VK_CPU_WORDS_SEEN is not read once into a static and logged when not the default")
check('else if (e && e[0] && strcmp(e, "1"))' in mode and "RX_VK_CPU_WORDS_SEEN=%s not known" in mode,
"an RX_VK_CPU_WORDS_SEEN value other than 1, 0 or check is not logged")
check('return cpu_words_seen::mode_now(env, lab_ab::on("nowordsseen"));' in mode, "the lab knob nowordsseen is not read at each note")
# the counters, in the mirror syncs' line
end = block(mem, "void memory_end_submission(VkCommandBuffer cmd) {")
check("report words: %llu asked of the table, %llu known to it and not noted again (noted all the same with =check), the "
"sets forgotten %llu times, %llu check mismatches since the start (RX_VK_CPU_WORDS_SEEN)" in re.sub(r'"\s*\n\s*"', "", end),
"the mirror syncs' line does not carry the report words' counters")
for st in ("st_noted", "st_known", "st_forgets", "st_mismatch"):
check("cpu_words_table." + st + ".load(std::memory_order_relaxed)" in end, "the status line does not read " + st)
row = [l for l in (ROOT / "docs" / "development.md").read_text(encoding="utf-8").split("\n") if l.startswith("| `RX_VK_CPU_WORDS_SEEN=0`")]
check(len(row) == 1 and "`nowordsseen`" in row[0] and "`RX_VK_CPU_WORDS_SEEN=check`" in row[0] and "gpu/vk/cpuwordsseen.h" in row[0]
and "tests/test_cpuwordsseen.py" in row[0], "docs/development.md's switches table has no row for RX_VK_CPU_WORDS_SEEN")
cut = "\n".join(block(mem, m) for m in ("void sorted_merge(", "void cpu_words_merge() {",
"void memory_cpu_owned(uint64_t guest, uint64_t size) {", "void cut_cpu_words("))
stale = cut.replace(", cpu_words_table.forget();", ";") # (the sets cleared, the table left as it was)
check(stale != cut, "the forget is not where the test takes it out")
env = {k: v for k, v in os.environ.items() if not k.startswith("RX_VK_")}
with tempfile.TemporaryDirectory(prefix="cpuwordsseen-") as tmp:
exes = {}
for name, code in (("now", cut), ("stale", stale)):
src, exe = Path(tmp) / (name + ".cpp"), Path(tmp) / (name + ".exe")
src.write_text(PROGRAM.replace("/* ACTUAL */", code), encoding="utf-8", newline="\n")
subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-I", str(VK), str(src), "-o", str(exe)], check=True)
exes[name] = str(exe)
def run(name, case):
return subprocess.run([exes[name], case], env=env, capture_output=True, text=True, timeout=600)
r = run("now", "table")
check(r.returncode == 0, "the table against a set:\n" + r.stdout + r.stderr)
r = run("now", "runs")
check(r.returncode == 0, "the runs with the table off, on and checking:\n" + r.stdout + r.stderr)
counts = r.stdout.strip()
r = run("now", "stale")
check(r.returncode == 0 and r.stdout.strip() == "differs 0 mismatch 0", "the code as it is: " + r.stdout + r.stderr)
r = run("stale", "stale")
check(r.returncode == 0 and r.stdout.startswith("differs "), "the build without the forget:\n" + r.stdout + r.stderr)
differs, mismatch = int(r.stdout.split()[1]), int(r.stdout.split()[3])
check(differs > 0 and mismatch > 0, "without the forget the runs are still right and the check counts nothing: the cases check nothing (" + r.stdout.strip() + ")")
print("PASS: a report word the sets hold is not noted again (" + counts + "); the sets and the cut runs are what they were, "
"over table entries shared and the sets forgotten; a table that does not forget is caught")
if __name__ == "__main__":
main()

View File

@@ -67,7 +67,7 @@ def main():
check("else if (page == 6) draw_names(k);" in function(menu, "void draw_menu(ui::Ctx& c, bool perf_under) {"), "page 6 is not drawn")
tick = menu[menu.index("void menu_tick() {"):]
branch = tick[tick.index("} else if (open_now.load() && page == 6) {"):]
check("if (mouse) names_mouse(ptr, mx, my, press, changed);" in branch[:400] and "names_press(press, tab_left, tab_right, changed);" in branch[:400],
check("if (mouse) names_mouse(ptr, mx, my, moved, press, changed);" in branch[:400] and "names_press(press, tab_left, tab_right, changed);" in branch[:400],
"page 6 does not take the keys and the mouse")
press = function(menu, "void names_press(")
check(press.index("if (press[5] && names_edit) names_edit = false") < press.index("else if (press[5]) page = 0, changed = true;") < press.index("p.empty()"),
@@ -119,7 +119,8 @@ def main():
# the wheel turns the page shown and moves no choice
mouse = function(menu, "void names_mouse(")
wheel = [line for line in mouse.splitlines() if "ptr.wheel" in line]
check(wheel == [" if (ptr.wheel) p.turn_shown(-ptr.wheel), changed = true;"], "the wheel on a name page does something else than turn the page shown")
# ((Triforce, 11-26) not while its slider is held, which has the mouse then (bar_mouse))
check(wheel == [" if (ptr.wheel && !bar) p.turn_shown(-ptr.wheel), changed = true;"], "the wheel on a name page does something else than turn the page shown")
# nothing before a page is opened: the game's files are read, the folder listed and lines made from the pages alone
code = re.sub(r"//[^\n]*", "", menu)

View File

@@ -25,6 +25,15 @@ the draw built, whichever path wrote it. The cases (tests/desc_sets_test.cpp):
push-template-off, push-template-none, push-template-misfit
RX_VK_DESC_TEMPLATE=0, no vkCmdPushDescriptorSetWithTemplateKHR, writes it was not made from or none made (and not
tried again): the write structs, as before
push-template-old
(Triforce, 11-26, C31) RX_VK_TPL_TABLE=0: the 8 entries find a program's push template, and a layout made
again is not taken from them
tpl-table, tpl-table-off, tpl-table-check
(Triforce, 11-26, C31; gpu/vk/tpltable.h) 40 programs pushed whole in turn: each template made once and found in
the thread's table after, tpl_mu taken once a program; a layout made again takes the lock and a new template; the
lab's notpltable phase and RX_VK_TPL_TABLE=0 go by the 8 entries (the lock at most lookups), the same templates;
a set program's template is found in the table too, and a set layout made again takes the lock and a new one;
RX_VK_TPL_TABLE=2 finds each one the map's, and counts an entry put in the table that is not
Each case fails without the rule it names (remove the check from set_kept, and its case stops); the push template's rules are
taken out in turn here (MUTATIONS) and a case must then fail.
python -I -B tests/test_desc_sets.py --headers <Vulkan include folder> [--cxx g++]
@@ -40,7 +49,7 @@ RUN_ALL_ARGS = ["--cxx", "{cxx}", "--headers", "{vulkan_headers}"]
ROOT = Path(__file__).resolve().parents[1]
CASES = ["reuse", "changed", "destroy", "stamp", "recording", "cmd", "bindpoint", "layout", "keep-off", "template", "template-off",
"template-misfit", "template-fail", "template-entries", "push", "push-template", "push-template-off", "push-template-none",
"push-template-misfit"]
"push-template-misfit", "push-template-old", "tpl-table", "tpl-table-off", "tpl-table-check"]
# ((Triforce) the push template's rules, each taken out of vk_draw.cpp: the case named must then fail)
MUTATIONS = [
("the descriptors packed for the push", " template_pack(dw().writes.data(), dw().writes.size(), t->slots, data);\n rec::push_template_bytes(",
@@ -48,6 +57,14 @@ MUTATIONS = [
" rec::push_template_bytes(", "push"),
("the recorder told the bytes", "rec::push_template_bytes(data.size());", "rec::push_template_bytes(0);", "push"),
("a template for each pipeline layout", "if (!t || t->pipe_layout != p.layout) {", "if (!t) {", "push-template"),
# ((Triforce, 11-26, C31) what the thread's wide table finds is used only while its layout is the program's
("the layout check on what the wide table finds", "if (t && t->pipe_layout == p.layout) {", "if (t) {", "push-template"),
("the wide table by default", 'return lab_ab::on("notpltable") ? tpltable::kOld : env;', "return env * 0;", "tpl-table"),
("the set layout check on what the wide table finds", "if (t && t->layout == p.set_layout) {", "if (t) {", "tpl-table"),
("the check's comparison with the map", "if (it == map.end() || it->second.get() != t) {", "if (it == map.end() || !t) {",
"tpl-table-check"),
("the 8 entries' push layout check", "} else if (l.p == &p && l.t && l.t->pipe_layout == p.layout) {", "} else if (l.p == &p && l.t) {",
"push-template-old"),
("writes that fit the push template", " if (!t || !t->tpl || !template_fits(t->sig, dw().writes.data(), dw().writes.size())) return false;\n"
" std::vector<uint8_t>& data = tpl_data();\n template_pack(dw().writes.data(), dw().writes.size(), t->slots, data);\n"
" rec::push_template_bytes(", " if (!t || !t->tpl) return false;\n std::vector<uint8_t>& data = tpl_data();\n"
@@ -102,7 +119,7 @@ def build(cxx, headers, tmp, name, fixture):
cpp, exe = Path(tmp) / (name + ".cpp"), Path(tmp) / (name + ".exe")
cpp.write_text(fixture, encoding="utf-8")
subprocess.run([cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-Wno-missing-field-initializers", "-pthread",
"-I" + str(headers), str(cpp), "-o", str(exe)], check=True)
"-I" + str(headers), "-I" + str(ROOT / "gpu" / "vk"), str(cpp), "-o", str(exe)], check=True)
return exe

View File

@@ -129,15 +129,16 @@ def main():
check("const bool game_black = embed_open || page == kModsRowPage;" in dp,
"dim_page: over play (our own background over the bars) the dim is cut black at the picture's edges")
dm = block(menu, "void draw_menu(ui::Ctx& c, bool perf_under) {")
# ((Triforce) but the tuning bar, page 0 alone, over the game seen whole: no dialog there)
check("if (!embed_open && !row && !tuning && !ui::system_bg(c)) c.d->AddRectFilled(ImVec2(0, 0), ImVec2(c.w, c.h), ui::rgba(8, 5, 2, ui::kDimAlpha));" in dm
# ((Triforce) but the tuning bar, page 0 alone, over the game seen whole: no dialog there. (11-26) Nor Save Select over the
# title, whose picture behind is out of focus in its place (vk_framegen.cpp wide_sides): no dialog opens there either)
check("if (!embed_open && !row && !tuning && !blurred && !ui::system_bg(c)) c.d->AddRectFilled(ImVec2(0, 0), ImVec2(c.w, c.h), ui::rgba(8, 5, 2, ui::kDimAlpha));" in dm
and "const bool tuning = tune_mode && page == 0 && !embed_open && !row;" in dm,
"draw_menu: over play our background no longer covers the whole window (dim_page's one rectangle there is for it)")
ask = block(menu, "void draw_quit_ask(ui::Ctx& c) {")
check("dim_window(c.d, menu_map, menu_grid(menu_window_w, menu_window_h), menu_window_w, menu_window_h, ui::rgba(8, 5, 2, 220));" in ask and
"ui::rgba(8, 5, 2, 220));" not in ask.replace("menu_window_h, ui::rgba(8, 5, 2, 220));", ""),
"Quit's dialog: its dim is one rectangle over the whole window, the bars lifted")
for head, dim in (("void draw_ask(ui::Ctx& c) {", "dim_page(c, ui::rgba(8, 5, 2, 110));"),
for head, dim in (("void draw_ask(ui::Ctx& c) {", "dim_page(c, ui::rgba(8, 5, 2, c.over_game ? 215 : 110));"), # ((11-26) darker over the game's own screen
("void mods_dialog(ui::Ctx& c, const char* title,", "dim_page(c, ui::rgba(8, 5, 2, 120));"),
("void mods_keyboard(ui::Ctx& c) {", "dim_page(c, ui::rgba(8, 5, 2, 120));")):
check(dim in block(menu, head), head + " its dim is not dim_page's")

View File

@@ -219,6 +219,10 @@ def check_source():
("discord_version_parts(", "the version in parts"),
("in_map ? area : \"\"", "no location when Link is not in a map"),
("hos_oot_stats(", "Link's hearts, rupees and tokens"),
# ((Triforce, 11-27) the Discord copy: the control bridge's (hos_oot_current_map) is empty without
# HOS_CONTROL, and no player's status showed the place)
("hos_oot_discord_map(", "the map from the copy kept for Discord"),
("hos_oot_discord_state(", "the age from the copy kept for Discord"),
("sent_at + 15000", "a change sent within 15 s, not more often")):
if token not in rpc:
raise SystemExit(f"host/discord_rpc.c: {what} is gone ({token})")

View File

@@ -115,7 +115,7 @@ def main():
"const bool found_range = dlss_feature::found_range(same_feature, s.feature_exact, s.feature_rw, s.feature_rh, rw, rh);",
"if (found_range) s.range_seen = true;",
'static const bool whole_range = dlss_feature::whole_range(getenv("RX_VK_DLSS_FEATURE_MAX"));',
"dlss_feature::size(aa, whole_range || s.range_seen || opts.resolution == 0, rw, rh, max_w, max_h);",
"dlss_feature::size(aa, whole_range || s.range_seen || applied_resolution() == 0, rw, rh, max_w, max_h);", # ((Triforce, 11-26) as applied
"cp.Feature.InWidth = made.w, cp.Feature.InHeight = made.h, cp.Feature.InTargetWidth = ow, cp.Feature.InTargetHeight = oh;",
"NGX_VULKAN_CREATE_DLSS_EXT(cmd, 1, 1, &s.feature, s.params, &cp);",
"s.feature_rw = made.w, s.feature_rh = made.h, s.feature_ow = ow, s.feature_oh = oh, s.min_rw = min_w, s.min_rh = min_h;",

View File

@@ -0,0 +1,184 @@
"""The file select drawn as the game's own Load list (gpu/vk/vk_game_tex.h make_file_skin, vk_menu.cpp draw_files; no game).
(2026-11-25) The owner, of the file select at 21:9: "It is very broken and it's only optimized for 16:9. I want you to
optimize it for ultra-wide as well. I want you to improve the design, fix up the UI, use the in-game assets, fix the
out-of-place buttons and overlapping prompts." It had the options' layout: the list at the left of the grid, a caption box
at its right (over the title, and over the performance overlay on a wide screen), and a Play button of its own under the
list. This compiles vk_game_tex.h's card and tag makers with made-up textures and checks:
- the card is the game's texture stretched as the game's layout stretches it: 469 texels wider, the picture's part and
the curl's part at their own size, only the part between them stretched;
- its fill is the measured grain's colours, its frame and its rule theirs, its alpha the shape's (or the frame's, where
the frame goes past it); the rule is taken from Frame_00 in its box only;
- the tag is its plate's colour with the rim's over it;
and reads the source: one column in the middle of the grid (draw_menu), the card, the tag, the cursor and the plates from
the game's textures with a drawn fallback for each, no Play button and no caption box, the line about the choice under the
cards, a click on the chosen card plays it, and the prompts kept inside a window narrower than 16:9.
python -I -B tests/test_file_select_cards.py [--cxx clang++]
"""
import argparse
import subprocess
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
VK = ROOT / "gpu" / "vk"
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
def check(ok, why):
if not ok:
raise SystemExit("FAIL: " + why)
def function(text, head):
start = text.index(head)
end = text.index("{", start) + 1
depth = 1
while depth:
depth += (text[end] == "{") - (text[end] == "}")
end += 1
return text[start:end]
PROGRAM = r"""
#include <cstdio>
#include <cstdlib>
#include "vk_game_tex.h"
using namespace mkwvk::game_tex;
static int fails = 0;
static void near(const Image& im, uint32_t x, uint32_t y, const unsigned char* rgb, int a, int tol, const char* what) {
const unsigned char* px = &im.rgba[((size_t)y * im.w + x) * 4];
if (std::abs(px[0] - rgb[0]) > tol || std::abs(px[1] - rgb[1]) > tol || std::abs(px[2] - rgb[2]) > tol || std::abs(px[3] - a) > 1) {
std::printf("FAIL: %s at %u,%u: %d,%d,%d,%d, not %d,%d,%d,%d\n", what, x, y, px[0], px[1], px[2], px[3], rgb[0], rgb[1], rgb[2], a);
fails++;
}
}
static Image blank(uint32_t w, uint32_t h, bool mask) {
Image im;
im.w = w, im.h = h, im.mask = mask;
im.rgba.assign((size_t)w * h * 4, 255);
for (size_t i = 0; i < (size_t)w * h; i++) im.rgba[i * 4 + 3] = 0;
return im;
}
static void set_a(Image& im, uint32_t x, uint32_t y, int a) { im.rgba[((size_t)y * im.w + x) * 4 + 3] = (unsigned char)a; }
int main() {
// the game's textures' size: the shape over all but a margin, a frame line at x 100 (the picture's part), 600 (the
// stretched part) and 900 (the curl's part), across at y 20; Frame_00 the same with a rule at y 156 and a mark outside
// the rule's box (at y 60) that must not show
Image base = blank(997, 283, false), frame = blank(997, 283, true), ruled = blank(997, 283, false);
for (uint32_t y = 18; y < 265; y++)
for (uint32_t x = 12; x < 986; x++) set_a(base, x, y, 255);
for (uint32_t y = 14; y < 268; y++) set_a(frame, 100, y, 255), set_a(frame, 600, y, 255), set_a(frame, 900, y, 255);
for (uint32_t x = 11; x < 989; x++) set_a(frame, x, 20, 255);
set_a(frame, 990, 140, 255); // (past the shape: the frame's own alpha)
for (uint32_t x = 480; x < 720; x++) set_a(ruled, x, 156, 255);
set_a(ruled, 300, 60, 255);
const Image card = make_file_card(base, frame, ruled, nullptr);
if (card.w != 997 + kFileCardMore || card.h != 283 || card.mask) std::printf("FAIL: the card is %ux%u\n", card.w, card.h), fails++;
unsigned char mid[3];
for (int k = 0; k < 3; k++) mid[k] = (unsigned char)((kFileCardLo[k] + kFileCardHi[k]) * 0.5f + 0.5f);
near(card, 200, 140, mid, 255, 1, "the fill (no grain: its middle colour)");
near(card, 100, 140, kFileCardLine, 255, 1, "the frame in the picture's part, where it is");
near(card, 900 + kFileCardMore, 140, kFileCardLine, 255, 1, "the frame in the curl's part, moved by the stretch");
near(card, 990 + kFileCardMore, 140, kFileCardLine, 255, 1, "the frame past the shape");
near(card, 900, 140, mid, 255, 1, "the fill where the curl's part was before the stretch");
// (600 in the stretched part: at 470 + 130 * (714 / 245), about 849, a texel or two wide)
const uint32_t at600 = kFileCardKeepL + (uint32_t)((600.0f - kFileCardKeepL) * (kFileCardKeepR + kFileCardMore - kFileCardKeepL) / (kFileCardKeepR - kFileCardKeepL));
int found = 0;
for (uint32_t x = at600 - 3; x <= at600 + 3; x++) found |= card.rgba[((size_t)140 * card.w + x) * 4] == kFileCardLine[0];
if (!found) std::printf("FAIL: the frame in the stretched part is not near %u\n", at600), fails++;
near(card, 1000, 20, kFileCardLine, 255, 1, "the frame across the stretched part");
near(card, 600, 156, kFileCardRule, 255, 1, "the rule");
near(card, 300, 60, mid, 255, 1, "Frame_00 outside the rule's box");
near(card, 5, 140, mid, 0, 255, "outside the shape (nothing)");
// the tag: its plate's colour, the rim's over it
Image plate = blank(4, 1, true), rim = blank(4, 1, true);
set_a(plate, 0, 0, 255), set_a(plate, 1, 0, 255), set_a(rim, 1, 0, 255), set_a(rim, 2, 0, 128);
const Image tag = make_file_tag(plate, rim);
near(tag, 0, 0, kFileTagFill, 255, 1, "the tag's plate");
near(tag, 1, 0, kFileTagRim, 255, 1, "the tag's rim over its plate");
near(tag, 2, 0, kFileTagRim, 128, 1, "the tag's rim alone");
near(tag, 3, 0, kFileTagFill, 0, 255, "outside the tag");
return fails ? 1 : 0;
}
"""
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cxx", default="clang++")
args = parser.parse_args()
tex = (VK / "vk_game_tex.h").read_text(encoding="utf-8")
ui = (VK / "vk_ui.h").read_text(encoding="utf-8")
menu = (VK / "vk_menu.cpp").read_text(encoding="utf-8")
skin = function(tex, "inline bool make_skin(")
check("make_file_skin(bntx, skin);" in skin, "make_skin does not make the file select's pieces")
files = function(tex, "inline void make_file_skin(")
for made in ('"file_card"', '"file_tag"', '"file_cursor_line"', '"file_cursor_glow"'):
check(made in files, "make_file_skin does not make " + made)
check("return false" not in files and files.count("if (read(") == 3, "a missing piece of the file select is not left out alone")
check('"DataFileImportantStateBase_DataDileImportantStateBase_00", "DataFileImportantStateBase_DataDileImportantStateBase_01"' in skin,
"the plates of the stones and medallions are not taken (by the archive's own spelling)")
draw = function(menu, "void draw_menu(ui::Ctx& c, bool perf_under) {")
check("if (page == kFilesPage) files_columns(k, &cx0, &cx1);" in draw, "the file select's column is not its own")
cols = function(menu, "void files_columns(")
check("-kFilesColumnHalf" in cols and "kFilesColumnHalf, 0).x" in cols, "the file select's column is not in the middle")
page = function(menu, "void draw_files(ui::Ctx& c) {")
for name in ('ui::art("file_card")', 'ui::art("file_tag")', 'ui::art("file_cursor_line")', 'ui::art("file_cursor_glow")'):
check(name in page, "draw_files does not draw " + name)
check("else ui::plate(c, a, b, i == cur);" in page and "} else ui::cursor(c, a, b, k);" in page, "a card or its cursor has no fallback")
# ((2026-11-26) the owner: hover, the game's settings' animations, the opening's, the blur in place of the shade)
check("files_focus[i].step(now, i == files_choice, settle);" in page and "ui::alpha(ui::kCursor, k)" in page and
"ui::glow_layers(c, cursor_glow, a - m, b + m, 150, 120, ui::kCursorGlow, ui::kCursorGlowBase, ui::kCursorGlowHdr, k);" in page,
"a card's cursor does not fade in and out as the game's settings' buttons'")
check("files_screen.step(prof_now(), open_now.load() && page == kFilesPage);" in menu and
"files_blur.store(open_now.load() && page == kFilesPage && files_at_title, std::memory_order_relaxed);" in menu and
"bool menu_backdrop_blurred() { return files_blur.load(std::memory_order_relaxed); }" in menu,
"Save Select's In is not stepped, or the picture behind it over the title not asked out of focus")
framegen = (VK / "vk_framegen.cpp").read_text(encoding="utf-8")
sides = framegen[framegen.index("WideSides wide_sides() {"):]
sides = sides[: sides.index("\n}\n")]
check("if (menu_backdrop_blurred()) {" in sides and "w.x0 = kWholeBlur, w.side = 1;" in sides and
"wide_possible.store(true, std::memory_order_relaxed);" in sides and
"float side_x0(const WideSides& w) { return w.x0 == kWholeBlur ? 2.0f : w.x0; }" in framegen and
"float side_x1(const WideSides& w) { return w.x0 == kWholeBlur ? 3.0f : 1.0f - w.x0; }" in framegen and
framegen.count("side_x0(wide), side_x1(wide)") == 2 and "1.0f - wide.x0" not in framegen,
"the picture behind Save Select is not blurred whole by the sides' own pass")
shader = (VK / "shaders" / "fg_scale.comp").read_text(encoding="utf-8")
check("max(1.0 - smoothstep(x0, x0 + feather, x), smoothstep(x1 - feather, x1, x))" in shader and
"if (pc.side != 0 && pc.x1 > pc.x0) {" in shader, "the window pass's sides do not cover a picture whose edges are past it")
check("caption(" not in page and "columns(c," not in page, "the file select still has the options' caption box")
check("menu_hit::kButton" not in page and "ui::button(" not in page, "the file select still has a Play button of its own")
check("menu_hit::kListLine, i);" in page and "ui::prompt_bar(c, prompts," in page, "the cards are not clicked, or no prompts")
check("CalcWordWrapPosition" in page and "bottom + ui::lu(c, 110)" in page, "what choosing does is not said under the cards")
check("textured_poly(c, pic.texture->GetTexRef(), poly, uv, 6);" in page, "the save's picture is not cut as the game's thumbnail")
plate = function(menu, "void files_plate(")
check("if (!stones && !medals) return;" in plate and "else c.d->AddNgonFilled(" in plate, "the plate is drawn with nothing held, or has no fallback")
tick = function(menu, "void menu_tick() {")
mouse = tick[tick.index("} else if (open_now.load() && page == kFilesPage) {"):]
mouse = mouse[: mouse.index("const auto leave")]
check("if (on_card && (moved || ptr.pressed) && files_choice != hit.index) files_choice = hit.index, changed = true;" in mouse and
"else if (on_card && (ptr.pressed & HOS_MOUSE_LEFT)) press[7] = true;" in mouse,
"the mouse onto a card does not choose it, or a click on the chosen card does not play it")
check("if (!files_screen.ready(prof_now()) && ease_live && !still_files) {" in mouse, "Save Select takes input while its In plays")
check("menu_hit::kButton" not in mouse, "the file select still takes a Play button's click")
bar = function(ui, "inline float prompt_bar(")
check("right = std::min(at(c, 1840, 0).x, c.w - lu(c, 80));" in bar, "the prompts go past a window narrower than 16:9")
with tempfile.TemporaryDirectory(prefix="file-cards-") as tmp:
src, exe = Path(tmp) / "cards.cpp", Path(tmp) / "cards.exe"
src.write_text(PROGRAM, encoding="utf-8")
inc = [VK, ROOT / "gpu" / "third_party" / "suyu", VK / "compat", ROOT / "gpu" / "compat"]
subprocess.run([args.cxx, "-std=c++20", "-O1", "-w", *("-I" + str(p) for p in inc), str(src), "-o", str(exe)], check=True)
r = subprocess.run([str(exe)], capture_output=True, text=True)
check(r.returncode == 0, "the cards as made:\n" + r.stdout)
print("PASS: the file select's cards, tag, cursor and column as the game's Load list")
if __name__ == "__main__":
main()

View File

@@ -124,7 +124,7 @@ def check_source():
"card.vram_mb = asked > 0 ? (uint64_t)asked : device_vram_bytes() >> 20;",
"card.threads = cpu_count();", # ((Triforce, 11-22, OS-49) cpu_count.h
"opts.resolution = ur::snap(upscaler(), choice.row);",
"restart_state.restart_value(restart_slot_of(r), restart_value_of(r));",
"applied_take_row(&opts.resolution);", # ((Triforce, 11-26) in force at once: the row is taken at Apply
'logf("menu: first start: tier 1 ('):
check(part in first, "menu_first_start: missing " + part)
check(first.index("first_start::applies(") < first.index("first_start::choose(card)") < first.index("opts.resolution ="),

View File

@@ -69,6 +69,11 @@ enum { HOS_OPT_FPS_CAP_ROW = 342 }; /* ((Triforce) gpu/vk/vk_api.h: the cap's
static volatile int fps_row_asked = -100;
enum { HOS_OPT_EVIL_HD = 420 }; /* ((Triforce) Evil HD's render distance: host/evil_hd.c, tests/test_evil_hd_foliage.py) */
void hos_evil_hd_tick(int row) { (void)row; }
/* ((Triforce, 11-26) the Render resolution as the menu applies it, each present: none answered here (host/res_follow.h) */
enum { HOS_OPT_RES_HELD = 431 };
#include "res_follow.h"
int hos_rt_pool_pinned(void) { return 0; }
void rx_option_set(int id, int value) { (void)id; (void)value; }
static volatile long long presents;
volatile uint64_t hos_gfx_module = MOD;
volatile int hos_fixed_resolution, hos_dynres_runs;

View File

@@ -39,6 +39,7 @@ def definition(text, name):
FIXTURE = r"""
#include <algorithm>
#include <atomic>
#include <cctype>
#include <cstdio>
#include <cstring>
@@ -71,6 +72,10 @@ bool full_scale(int) { return false; }
namespace mr { constexpr int kMax = 8; }
void restart_values(int*) {}
struct { void note(const int*) {} } restart_state;
/* ((Triforce, 11-26) the rows taken at Apply: their state told of a change, as the restart's */
void apply_values(int*) {}
struct { void note(const int*) {} } apply_state;
std::atomic<int> res_held{0}; /* ((Triforce, 11-26) restart_value_of's Render resolution kept back: none here */
bool can_mic() { return false; }
void mic_chosen() {}
int output_pick; // (the Output device row: its device is told to the host, not run here)

View File

@@ -41,18 +41,25 @@ def main():
# FSR 3.1 runs for either of its values, and as its Native AA for the second (RX_VK_FSR=2 for a run)
fsr3 = (vk / "vk_fsr3.cpp").read_text(encoding="utf-8")
wanted = function(fsr3, "bool fsr3_wanted() {")
check("upscaler_rows::is_fsr3(opts.dlss) && !temporal_env_chosen()" in wanted and "fsr3::supported()" in wanted,
# ((Triforce, 11-26) for a choice of the row (fsr3_wanted_of, fsr3_native_of), the applied one in play: fsr3_wanted)
wanted = function(fsr3, "bool fsr3_wanted_of(int choice, bool now) {")
check("upscaler_rows::is_fsr3(choice) && !temporal_env_chosen()" in wanted and "fsr3::supported()" in wanted,
"fsr3_wanted does not take both of the row's FSR 3.1 values, or drops RX_VK_DLSS / RX_VK_FSR4 over them")
native = function(fsr3, "bool fsr3_native() {")
check("fsr3_wanted() &&" in native and "opts.dlss == upscaler_rows::FSR3_AA" in native and "env >= 2" in native,
native = function(fsr3, "bool fsr3_native_of(int choice, bool now) {")
check("fsr3_wanted_of(choice, now) &&" in native and "choice == upscaler_rows::FSR3_AA" in native and "env >= 2" in native,
"fsr3_native is not the row's Native AA (or RX_VK_FSR=2) where FSR 3.1 runs")
# the game draws the 3D at full scale then, and its dynamic resolution is off: the two answers the host reads at the start
check("bool fsr3_native() { return fsr3_native_of(applied_dlss(), true); }" in fsr3, "fsr3_native is not the applied row's")
# the game draws the 3D at full scale then, and its dynamic resolution is off: the two answers the host reads ((11-26))
# each present, from the row as applied: FSR 3.1's Native AA is upscaler_of's FSR3_AA, which ur::full_scale holds full)
temporal = (vk / "vk_temporal.cpp").read_text(encoding="utf-8")
check(re.search(r"bool temporal_full_scale\(\) \{ return ur::full_scale\(temporal_mode\(\)\) \|\| fsr3_native\(\); \}", temporal),
"temporal_full_scale does not hold the 3D at full scale for FSR 3.1's Native AA")
menu_src = (vk / "vk_menu.cpp").read_text(encoding="utf-8")
check("bool resolution_full() { return ur::full_scale(upscaler_of(applied_dlss(), false)); }" in menu_src and
"if (fsr3_wanted_of(choice, now)) return fsr3_native_of(choice, now) ? ur::FSR3_AA : ur::FSR3;" in menu_src,
"resolution_full does not hold the 3D at full scale for FSR 3.1's Native AA")
replay = (vk / "vk_replay.cpp").read_text(encoding="utf-8")
check("id == 2 ? resolution_auto() && !temporal_full_scale()" in replay and "id == 3 ? (temporal_full_scale() ? 10000 : resolution_scale())" in replay,
check("id == 2 ? resolution_auto() && !resolution_full()" in replay and "id == 3 ? (resolution_full() ? 10000 : resolution_scale())" in replay,
"the renderer no longer answers the host's scale (options 2 and 3) with the full scale of a native AA")
# at full scale the game's upscale is its full-size pass, one of the two the stand-ins know by key: FSR 3.1 is offered it,
# and takes an input as large as the output (it refuses only a smaller output)
@@ -76,23 +83,27 @@ def main():
# the menu: what runs is shown, both of FSR 3.1's are offered where it runs, and the Render resolution row says Native
menu = (vk / "vk_menu.cpp").read_text(encoding="utf-8")
check("int upscaler() {\n if (fsr3_wanted()) return fsr3_native() ? ur::FSR3_AA : ur::FSR3;" in menu, # ((Triforce) 11-24: Off after it)
# ((Triforce, 11-26) for the row's choice, upscaler_of: what it runs as once applied)
check("int upscaler_of(int choice, bool now) {\n if (fsr3_wanted_of(choice, now)) return fsr3_native_of(choice, now) ? ur::FSR3_AA : ur::FSR3;" in menu
and "int upscaler() { return upscaler_of(opts.dlss, true); }" in menu, # ((Triforce) 11-24: Off after it)
"the menu does not show FSR 3.1's Native AA when it runs")
check("ur::fsr3_bits(fsr3::supported())" in function(menu, "unsigned upscalers_available() {"),
"the Upscaler row does not offer both of FSR 3.1's where it runs")
# ((Triforce, options_version 7) the Upscaler row names the engine of each of the seven values; a native AA is the Render
# resolution row's Native (100%) step, upscaler_rows.h step_resolution)
names = function(menu, "const char* tx_upscaler(int) {")
names = function(menu, "const char* upscaler_name(int up) {") # ((Triforce, 11-26) tx_upscaler's, for an upscaler_of
table = re.search(r"static const char\* t\[ur::kUpscalers\] = \{(.*?)\};", names, re.S)
check(table and [n.strip().strip('"') for n in table.group(1).replace("\n", " ").split(",")] ==
["Game", "NVIDIA DLSS", "NVIDIA DLSS", "AMD FSR 3.1", "AMD FSR 4", "AMD FSR 4", "AMD FSR 3.1", "Off", "Intel XeSS", "Intel XeSS"], # ((Triforce) 11-24: Off; Intel XeSS after it)
"tx_upscaler's names are not the ten values' engines in their saved order")
# ((Triforce, FSR4-7) FSR 4 by the version AMD's library runs, fsr4_name, the engine's name too)
check("const int up = ur::engine(std::clamp(upscaler(), 0, ur::kUpscalers - 1));" in names and "return t[up];" in names,
check("up = ur::engine(std::clamp(up, 0, ur::kUpscalers - 1));" in names and "return t[up];" in names,
"tx_upscaler does not name what runs by its engine")
hints = function(menu, "const char* hn_upscaler(int v, int variant) {")
check("v = ur::engine(v);" in hints, "hn_upscaler does not say each value's engine")
check('if (ur::full_scale(up)) return "Native (100%)";' in function(menu, "const char* tx_resolution(int v) {"),
# ((Triforce, 11-26) resolution_name for an upscaler_of: the row's, tx_resolution, and the performance panel's)
check('if (ur::full_scale(up)) return "Native (100%)";' in function(menu, "const char* resolution_name(int up, int v) {") and
"const char* tx_resolution(int v) { return resolution_name(upscaler(), v); }" in menu,
"the Render resolution row does not say Native (100%) with a native AA")
check("if (ur::full_scale(up))" in function(menu, "const char* hn_resolution(int v, int variant) {"),
"the Render resolution row's help has no line for a native AA")

View File

@@ -111,10 +111,13 @@ def checks(temporal, fsr4, menu):
again = function(temporal, "bool fail_again(Engine& k, const char* why) {")
check("k.e->release();" in again and "drop_image(*im);" in again and "k.retry.failed(now_ns())" in again and
"s.last_frame = 0;" in again, "fail_again does not let go what the engine and the chain hold, or count the failure")
# ((Triforce, 11-26) the choice as applied, re-armed, then temporal_mode_of with now: the switches, the stand-ins)
mode = function(temporal, "int temporal_mode() {")
check("rearm_on_choice(v);" in mode and "if (stood_in(v)) return ur::GAME;" in mode,
mode_of = function(temporal, "int temporal_mode_of(int choice, bool now) {")
check("rearm_on_choice(v);" in mode and "if (now && stood_in(v)) return ur::GAME;" in mode_of,
"temporal_mode does not say the game's own for an engine that is off, or a new choice does not try it anew")
check(mode.index("rearm_on_choice(v);") < mode.index("if (dlss > 0)"), "the choice is read after the switches")
check(mode.index("rearm_on_choice(v);") < mode.index("return temporal_mode_of(v, true);") and "if (dlss > 0)" in mode_of,
"the choice is read after the switches")
check("if (waiting(engine)) return fail(" in function(temporal, "bool temporal_upscale(VkCommandBuffer cmd,") and
"waiting(*engine)" in function(temporal, "Texture* temporal_pre_tonemap(VkCommandBuffer cmd) {"),
"the chain does not wait before it tries a failed engine again")
@@ -138,8 +141,9 @@ def checks(temporal, fsr4, menu):
# DLAA, FSR 4's and FSR 3.1's alike (ur::full_scale)
resolution = function(menu, "const char* hn_resolution(int v, int variant) {")
native = resolution[resolution.index("if (ur::full_scale(up))"):resolution.index("const int p = ur::percent(ur::snap(up, v));")]
check("takes its full size at the next start." in native,
"the native AA's help (the Render resolution's Native) does not say the 3D takes its full size at the next start")
# ((Triforce, 11-26) the 3D takes its full size at Apply now, not at the next start: the row's help says Apply)
check("next start" not in native and "the sharpest, and the slowest." in native,
"the native AA's help (the Render resolution's Native) still says the 3D waits for the next start")
# FSR4-3: an RGBA16F picture goes to FSR 4
check("only DLSS takes it" not in chain, "the chain still refuses FSR 4 an RGBA16F (HDR Native) picture")
check("const bool hdr = pre != nullptr || in_format == VK_FORMAT_R16G16B16A16_SFLOAT;" in chain,
@@ -169,10 +173,10 @@ def checks(temporal, fsr4, menu):
"g_named.store(true, std::memory_order_release);" in load, "FSR 4's name is not taken from the version AMD's library runs")
name = function(fsr4, "const char* fsr4_name(bool native_aa) {")
check("g_named.load(std::memory_order_acquire)" in name and "lock" not in name, "fsr4_name waits for the library")
tx = function(menu, "const char* tx_upscaler(int) {")
tx = function(menu, "const char* upscaler_name(int up) {") # ((Triforce, 11-26) tx_upscaler's, and the performance panel's)
check("if (ur::is_fsr4(up)) return fsr4_name(up == ur::FSR4_AA);" in tx, "the Upscaler row always says AMD FSR 4")
# ((Triforce, options_version 7) the row names the engine alone: FSR 4's Native AA is the Render resolution's Native)
check("const int up = ur::engine(std::clamp(upscaler(), 0, ur::kUpscalers - 1));" in tx,
check("up = ur::engine(std::clamp(up, 0, ur::kUpscalers - 1));" in tx,
"the Upscaler row names an engine's native AA, which the Render resolution's Native (100%) says")
check("driver 26.10.1 or newer" in hint,"the help for no FSR 4 here does not name the driver it needs")
@@ -180,7 +184,7 @@ def checks(temporal, fsr4, menu):
MUTATIONS = [
("the old latch", "temporal", 'if (ready < 0) return fail_again(engine, why ? why : "it could not be made");',
'if (ready < 0) { engine.failed = true; return fail(why); }'),
("no stand-in", "temporal", "if (stood_in(v)) return ur::GAME;", ""),
("no stand-in", "temporal", "if (now && stood_in(v)) return ur::GAME;", ""),
("the old native", "temporal", "const bool native = temporal_rules::native_at(ur::full_scale(mode), rw, rh, ow, oh);",
"const bool native = ur::full_scale(mode);"),
("the old HDR refusal", "temporal", " if (!engine.started) engine.started = true, engine.ok = engine.e->start();",

View File

@@ -137,7 +137,7 @@ def main():
menu = (VK / "vk_menu.cpp").read_text(encoding="utf-8")
# 2. the source
pb = block(ui, "inline float prompt_bar(Ctx& c, const Prompt* list, int n) {")
pb = block(ui, "inline float prompt_bar(Ctx& c, const Prompt* list, int n, float* spans = nullptr) {") # ((Triforce, 11-26) spans: the mouse's
check("const float x1 = c.over_game ? std::max(c.w, c.guides_x1) : c.w, past = c.w + lu(c, 4);" in pb,
"prompt_bar: the plate still ends at the column's right edge over the game's Options screen")
check("ImVec2(x1, c.h), rgba(24, 22, 12));" in pb, "prompt_bar: the plate's dark does not reach the game's band's end")

View File

@@ -46,6 +46,7 @@ the switch is in docs/development.md.
import argparse
import ast
import random
import re
import struct
import subprocess
import sys
@@ -734,6 +735,14 @@ def check_patch():
assert patch(out) == (out, 2), what # (a second run)
# (the order of the two: the marks made over the patched lift are what the patch makes of the marked one)
assert marks(patch(LIFTED)[0]) == patch(marked)[0]
# ((Triforce, 11-27) a lift with the flags as locals (nx2/local_flags.py, the default): each call goes after the flags'
# declaration the kit writes after the head, which nx2/split_giants.py takes only as the body's first line. With the
# call above it f_8010b380, 378 KB in such a lift, was left whole as "a top-level declaration")
local = re.sub(r"^(void f_[0-9a-f]+\(Ctx \*__restrict A64_NOESC c\) \{\n)", r"\1" + oot_patches.FLAG_DECL, LIFTED, flags=re.M)
out, n = patch(local)
assert n == 2 and unhooked(out) == local and patch(out) == (out, 2), n
for head, name, _ in oot_patches.ZSTD_SITES:
assert out.count(head + oot_patches.FLAG_DECL + oot_patches.ZSTD_HOOK % name) == 1, ("after the flags' declaration", name)
# (a function at that address whose code is not the decoder's, as in another game version or a changed lift: left as it
# is, whichever of its lines differs or comes twice, before the marks and after them. The lines are written as the lift
# is before the marks: that is the text the patch sees)

View File

@@ -86,7 +86,7 @@ class LauncherColorTests(unittest.TestCase):
self.assertIn('<EmbeddedResource Include="..\\ui\\**\\*" LogicalName="ui/%(RecursiveDir)%(Filename)%(Extension)" />', csproj)
def test_us_spelling(self):
for name in ("app.js", "demo.js", "index.html"):
for name in ("app.js", "demo.js", "index.html", "rando.js"):
text = read(UI / name)
if name.endswith(".js"):
text = without_comments(text)

View File

@@ -48,8 +48,9 @@ def need(text, needle, why):
def check_source(app, bwav, media):
# (the screens' music and fades as before: the page plays the same tracks at the same places)
# ((Triforce, 11-25) the Randomizer page plays the launcher's fairy theme, as Mods and Saves do)
need(app, "const MUSIC = { welcome: null, reveal: 'saria', work: 'temple', done: 'itemget', home: 'fairy', saves: 'fairy', "
"mods: 'fairy', settings: 'fairy', bench: 'fairy', brun: null, playing: null };",
"mods: 'fairy', rando: 'fairy', settings: 'fairy', bench: 'fairy', brun: null, playing: null };",
"launcher/ui/app.js: the music a screen plays changed")
need(app, "if (name === 'done') music('itemget', false, .3);", "launcher/ui/app.js: the fanfare on the done screen changed")
need(app, "music(m, true, name === 'playing' || name === 'brun' ? 2.2 : 1.4);", "launcher/ui/app.js: the fades between screens changed")

720
tests/test_local_flags.py Normal file
View File

@@ -0,0 +1,720 @@
"""NZCV as the lifted functions' locals (nx2/local_flags.py, A64_LOCAL_FLAGS, on by default), against the flags as bytes of
the context (A64_LOCAL_FLAGS=0), on whole functions run natively (game-free).
(Triforce, 11-23, the fps pass's LX-2, after NX2navi 0.11.0-rc4's recomp/flags.py.) The kit's switch makes every c->n,
c->z, c->c and c->v of a function a local, read at its start and written back only where control leaves other than by a
call or a return (a tail call, an indirect jump, an SVC, a trap). The kit's own reader takes any value that is set and
not empty as on, so nx2/local_flags.py puts its rule in that reader's place (a64_lift.local_flags).
The rule: unset, empty or any value but 0 is on, 0 is off. After install() the kit reads it so, and the environment
keeps the value the player set. (11-27) So does a fresh process started after install() that runs nx2/lift.py's module
level, as the lift's emit processes are spawned on Windows: install() wrote "1" or nothing into the environment, and
such a process read nothing as on, so with A64_LOCAL_FLAGS=0 its C had the locals and the lift's a64_fpx.h not their
helpers. And install() stops when the kit's A64_PACKED_FLAGS (one store of the four flags into the context, which the
locals do not see) is on beside the locals.
The run: five functions written here in AArch64 (no memory access: registers and flags alone) go through the kit's
discovery and its write() with a64emit's real translator, once with the switch unset (the default) and once with
A64_LOCAL_FLAGS=0. Every flag reader is there: B.cond, CSEL, CSINC/CSET, CCMP (register and immediate), ADC
and SBCS (the carry in), in 64 and 32 bits, in a loop, and across a tail call (CMP then B into another function that
reads the flags it came with), around a call (flags set before a BL and again after it). Both lifts are compiled into
one driver that runs every function from the same random states (X0-X30, SP and NZCV) and compares X0-X30 and SP after
(NZCV is not compared: it is dead at a return, as nx2/test_leaf.py says). The first lift must hold the locals (fz_) and
the second none. With the switch on the context's flags are written back before the tail call, so the function it
enters reads what its caller set.
And reads the source: nx2/lift.py installs it after vecfp's, A64_LOCAL_FLAGS is an A64_ name (in nx2/make_game.py's lift
key, as nx2/local_flags.py is), nx2/oot_patches.py's scene colour patch has the local form of its Z read, and the
switch is in the switches table. (11-26, on v0.8.3) And the three edits of v0.8.3 that match a flag by its text take the
local form too, each applied once to an authored function in that form and left as it is by a second run: the horse's
jump step test (its FCMP as the code form, a64_fcmp32k, and its branch on fn_), the Camera centering row's anchor (fz_)
and the ocarina wait's mode gate (fz_, with the other gates and hooks of the tick). Without that they are found 0 times
in such a lift, and the build only warns.
(11-26, on v0.8.4) Both lifts go through every pass nx2/lift.py installs, in its order (the module is imported), so the
flags as locals meet the game's other passes and v0.8.4's nx2/nativefp.py, which stays last. A sixth function is float
and on the hot list (A64_HOT_FUNCS): FADD, FMUL, an FCMP read by two CSETs (GT, and HI, which reads its C) and B.cond,
FCVTZS, FMOV and MSR FPCR. Its FCMP is the code form (a64_fcmp32k) with the switch on and a64_fcmp32 with it off;
nativefp must give it the same native names and the same FPCR sync in both lifts; and the run compares V0-V7, FPCR and
FPSR too, from random float states.
(11-27) The authored functions of the flag edits have the flags' declaration after their head, as the kit writes it, and
the cloth's solve gate (counted in lines from the head) is made with it there: a lift of v0.8.4 with the flags as locals
left that gate out, only warning, and the cloth solved at every frame above 60 fps. And both lifts are compiled with
clang's profile counters (-fprofile-instr-generate, to LLVM IR), and every function's control-flow hash, by which the hot
code's -fprofile-instr-use finds its entry in the shipped profile, must be the same in both: the kit's code form of the
FCMP put an else where the lift without the switch has a !, and 652 of v0.8.4's 1384 hot functions were built without
their profile. The FCMP is in nx2/local_flags.py's form (profile_form), and the horse's step patch takes both forms.
(11-27) The horse's step test in each form (nx2/oot_patches.py HORSE_TEST, HORSE_TEST_LOCAL) is the lifted float
function's own FCMP, but for the registers. Two stores through one base around that FCMP share one page mark
(a64_lift.group_marks) in both lifts, and with the switch off the grouped C is the same as before the kit's MG_PLAIN named
a64_fcmp32k and a64_fcmp64k. nx2/oot_patches.py's FLAG_REF is the kit's.
python -I -B tests/test_local_flags.py [--cc clang] [--cxx clang++] [--random 200000]
Skipped (exit 0) on a host that is not x86-64 or has no C or C++ compiler.
"""
import argparse
import os
import platform
import re
import sys
import tempfile
import time
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(ROOT, "tests"))
sys.path.insert(0, os.path.join(ROOT, "nx2"))
import test_fpx_sticky as fs # noqa: E402 (the build helpers the kit's other lifted-code tests use)
RUN_ALL_ARGS = ["--cc", "clang", "--cxx", "{cxx}"]
SEED = 20261123
SWITCH = "A64_LOCAL_FLAGS"
BASE = 0x80000000
EQ, NE, CS, CC, MI, PL, VS, VC, HI, LS, GE, LT, GT, LE = range(14)
XZR = 31
RET = 0xD65F03C0
# ---- an assembler for the few forms used ----------------------------------------------------------------------------
def subs_imm(d, n, imm, sf=1):
return (sf << 31) | 0x71000000 | (imm << 10) | (n << 5) | d
def subs_reg(d, n, m, sf=1):
return (sf << 31) | 0x6B000000 | (m << 16) | (n << 5) | d
def adds_reg(d, n, m, sf=1):
return (sf << 31) | 0x2B000000 | (m << 16) | (n << 5) | d
def adc(d, n, m):
return 0x9A000000 | (m << 16) | (n << 5) | d
def sbcs(d, n, m):
return 0xFA000000 | (m << 16) | (n << 5) | d
def csel(d, n, m, cond, sf=1):
return (sf << 31) | 0x1A800000 | (m << 16) | (cond << 12) | (n << 5) | d
def csinc(d, n, m, cond, sf=1):
return (sf << 31) | 0x1A800400 | (m << 16) | (cond << 12) | (n << 5) | d
def cset(d, cond, sf=1):
return csinc(d, XZR, XZR, cond ^ 1, sf)
def ccmp_reg(n, m, nzcv, cond, sf=1):
return (sf << 31) | 0x7A400000 | (m << 16) | (cond << 12) | (n << 5) | nzcv
def ccmp_imm(n, imm5, nzcv, cond, sf=1):
return (sf << 31) | 0x7A400800 | (imm5 << 16) | (cond << 12) | (n << 5) | nzcv
def movz(d, imm16):
return 0xD2800000 | (imm16 << 5) | d
def add_imm(d, n, imm):
return 0x91000000 | (imm << 10) | (n << 5) | d
def sub_imm(d, n, imm):
return 0xD1000000 | (imm << 10) | (n << 5) | d
def eor(d, n, m):
return 0xCA000000 | (m << 16) | (n << 5) | d
def tst(n, m):
return 0xEA000000 | (m << 16) | (n << 5) | XZR
def fadd_s(d, n, m):
return 0x1E202800 | (m << 16) | (n << 5) | d
def fmul_s(d, n, m):
return 0x1E200800 | (m << 16) | (n << 5) | d
def fcmp_s(n, m):
return 0x1E202000 | (m << 16) | (n << 5)
def fcvtzs_ws(d, n):
return 0x1E380000 | (n << 5) | d
def fmov_ws(d, n):
return 0x1E260000 | (n << 5) | d
def msr_fpcr(t):
return 0xD51B4400 | t
HOT = "f_80000400" # (the float function, on the hot list: nativefp's names go on hot text)
NATIVE = (("scalar", r"\ba64_fpx_nat_\w+\(c,"), ("vector", r"\ba64_vfpx_nat_\w+\(c,"),
("conversion", r"\ba64_nat_(?:fp_to_int|fixed_to_fp)\("), ("block gate", r"A64_NAT_OPEN_BK\("),
("FPCR sync", r"hos_fpcr_sync\(c\)"))
def program():
"""{address: word} of six functions, and their entries. Labels are resolved in a second pass."""
funcs = {
# 0: flags in a loop: every reader, in 64 and 32 bits
0x000: [movz(9, 7),
("L1", subs_imm(9, 9, 1)), adds_reg(2, 0, 1), adc(3, 3, 2), subs_reg(XZR, 0, 1), csel(4, 0, 1, LT),
ccmp_reg(2, 3, 4, NE), csinc(5, 5, 4, HI), subs_reg(XZR, 6, 7, 0), cset(8, GE), sbcs(10, 10, 0),
cset(11, VS), eor(0, 0, 2), ("cbnz", 9, "L1"),
tst(0, 1), ("b.cond", MI, "L2"), add_imm(12, 12, 3),
("L2", subs_reg(XZR, 12, 13)), ("b.cond", GT, "L3"), sub_imm(13, 13, 5),
("L3", RET)],
# 1: a compare, then a tail call that carries the flags into function 2
0x100: [subs_reg(XZR, 0, 1), add_imm(5, 5, 1), ("b", 0x140)],
# 2: reads the flags it is entered with
0x140: [csel(2, 0, 1, GE), ("b.cond", EQ, "M1"), add_imm(3, 3, 1), ("M1", cset(4, HI)), RET],
# 3: flags set before a call and again after it (the AAPCS64 leaves them undefined across it)
0x180: [subs_reg(XZR, 0, 1), ("bl", 0x000), adds_reg(6, 2, 4), csel(7, 6, 5, CC), cset(14, LE), RET],
# 4: 32-bit and immediate compares, a CCMP chain, a TBNZ around a flag setter
0x1C0: [subs_imm(XZR, 0, 10, 0), ccmp_imm(1, 3, 2, LT, 0), csel(2, 0, 1, LE, 0), ("tbnz", 3, 5, "N1"),
subs_reg(4, 4, 5, 0), ("N1", cset(6, MI, 0)), csinc(7, 7, 6, PL), RET],
# 5: float, on the hot list (nativefp's names): FADD, FMUL, an FCMP read by two CSETs (GT, HI) and B.cond, FCVTZS, FMOV,
# MSR FPCR
0x400: [fadd_s(2, 0, 1), fmul_s(3, 2, 0), fcmp_s(3, 1), cset(4, GT), cset(9, HI), ("b.cond", MI, "N2"), add_imm(5, 5, 1),
("N2", fcvtzs_ws(6, 3)), fmov_ws(7, 2), msr_fpcr(8), RET],
}
words, labels, fix = {}, {}, []
for start, items in funcs.items():
at = BASE + start
for it in items:
if isinstance(it, tuple) and isinstance(it[0], str) and it[0].startswith(("L", "M", "N")) and len(it) == 2:
labels[it[0]] = at
it = it[1]
if isinstance(it, tuple):
fix.append((at, it))
words[at] = 0
else:
words[at] = it
at += 4
for at, it in fix:
kind = it[0]
if kind == "b":
words[at] = 0x14000000 | (((BASE + it[1] - at) >> 2) & 0x3FFFFFF)
elif kind == "bl":
words[at] = 0x94000000 | (((BASE + it[1] - at) >> 2) & 0x3FFFFFF)
elif kind == "b.cond":
words[at] = 0x54000000 | ((((labels[it[2]] - at) >> 2) & 0x7FFFF) << 5) | it[1]
elif kind == "cbnz":
words[at] = 0xB5000000 | ((((labels[it[2]] - at) >> 2) & 0x7FFFF) << 5) | it[1]
elif kind == "tbnz":
words[at] = (0x37000000 | ((it[2] >> 5) << 31) | ((it[2] & 31) << 19) |
((((labels[it[3]] - at) >> 2) & 0x3FFF) << 5) | it[1])
return words, sorted(BASE + s for s in funcs)
class Image:
def __init__(self):
self.words, starts = program()
self.entries = set(starts)
self.hooks = {}
self.names = {}
def in_code(self, pc):
return pc in self.words
def word(self, pc):
return self.words[pc]
def read(self, addr, size):
return b"\0" * size
def put(name, value):
if value is None:
os.environ.pop(name, None)
else:
os.environ[name] = value
# a process the lift starts for its emit, as Windows starts it (spawned): a fresh interpreter that runs nx2/lift.py's module
# level again, with the lift's environment as it stands, and says how the kit reads the switch there
FRESH = ("import os, sys; sys.path.insert(0, %r); import lift, a64_lift; "
"print('kit=%%s env=%%r' %% (a64_lift.local_flags(), os.environ.get('A64_LOCAL_FLAGS')))")
def check_rule(local_flags, a64_lift):
"""The rule, as the kit reads it after install() (a64_lift.local_flags), with the environment left as the player set it,
in this process and in a fresh one started after it (11-27: install() wrote "1" or nothing into the environment, and a
spawned emit process, which runs install() again, read nothing as on: with A64_LOCAL_FLAGS=0 its C had the locals and
the a64_fcmp32k calls, the lift's a64_fpx.h not the helper). And the kit's A64_PACKED_FLAGS beside the locals stops it"""
import subprocess
bad = []
saved = {k: os.environ.get(k) for k in (SWITCH, "A64_PACKED_FLAGS")}
try:
put("A64_PACKED_FLAGS", None)
for v, want in ((None, True), ("", True), ("1", True), (" 1 ", True), ("0", False), (" 0 ", False)):
if local_flags.on(v) != want:
bad.append("on(%r) is %s" % (v, local_flags.on(v)))
put(SWITCH, v)
local_flags.install()
if a64_lift.local_flags() != want:
bad.append("after install with %r the kit reads %s" % (v, a64_lift.local_flags()))
if os.environ.get(SWITCH) != v:
bad.append("install with %r leaves %r in the environment" % (v, os.environ.get(SWITCH)))
if local_flags.report().startswith("flags: N, Z, C and V as each function's locals") != want:
bad.append("the lift's line with %r is %r" % (v, local_flags.report()))
if v in (None, "0", "1"):
r = subprocess.run([sys.executable, "-I", "-B", "-c", FRESH % os.path.join(ROOT, "nx2")], capture_output=True,
text=True, timeout=300)
got, said = (r.stdout.strip().splitlines() or [""])[-1], "kit=%s env=%r" % (want, v)
if r.returncode or got != said:
bad.append("a fresh process after install with %r says %r, not %r (exit %d) %s"
% (v, got, said, r.returncode, r.stderr.strip()[-300:]))
for packed, local, stops in (("1", None, True), ("0", "1", True), ("1", "0", False), ("", None, False)):
put("A64_PACKED_FLAGS", packed)
put(SWITCH, local)
try:
local_flags.install()
said = None
except SystemExit as e:
said = str(e)
if stops != (said is not None) or (said and not ("A64_PACKED_FLAGS" in said and SWITCH + "=0" in said)):
bad.append("install with A64_PACKED_FLAGS=%r and %s=%r: %s" % (packed, SWITCH, local, said or "no stop"))
finally:
for k, v in saved.items():
put(k, v)
if bad:
raise SystemExit("local flags: the rule: " + "; ".join(bad))
def lift(a64_lift, out_dir, value):
"""The kit's discovery and write() over the authored functions, with the switch at value (None: unset) and install() run"""
import local_flags
saved = os.environ.get(SWITCH)
saved_hot = os.environ.get("A64_HOT_FUNCS")
hot_list = os.path.join(os.path.dirname(out_dir), "hot_funcs.txt")
with open(hot_list, "w") as f:
f.write(HOT + "\n")
os.environ["A64_HOT_FUNCS"] = hot_list
try:
if value is None:
os.environ.pop(SWITCH, None)
else:
os.environ[SWITCH] = value
local_flags.install()
if a64_lift.local_flags() != local_flags.on(value):
raise SystemExit("local flags: with %s=%r the kit reads %s" % (SWITCH, value, a64_lift.local_flags()))
L = a64_lift.Lifter(Image())
L.discover()
if sorted(L.funcs) != sorted(Image().entries):
raise SystemExit("local flags: discovered %s" % sorted("%x" % e for e in L.funcs))
files = L.write(out_dir)
finally:
if saved is None:
os.environ.pop(SWITCH, None)
else:
os.environ[SWITCH] = saved
if saved_hot is None:
os.environ.pop("A64_HOT_FUNCS", None)
else:
os.environ["A64_HOT_FUNCS"] = saved_hot
text = ""
for f in (files if isinstance(files, list) else sorted(os.listdir(out_dir))):
p = f if os.path.isabs(f) else os.path.join(out_dir, f)
if os.path.basename(p).startswith("code_") and p.endswith(".c"):
with open(p, encoding="utf-8") as fh:
text += fh.read()
return text
DRIVER = r"""
#include "a64.h"
#include <stdio.h>
#include <stdlib.h>
#define F(x) void f_##x(Ctx *A64_NOESC c); void g_##x(Ctx *A64_NOESC c);
F(80000000) F(80000100) F(80000140) F(80000180) F(800001c0) F(80000400)
void hos_fpcr_follow(void) {} /* (the host's MXCSR following FPCR.FZ, and MSR FPCR's sync: the same for both lifts) */
void hos_fpcr_sync(Ctx *A64_NOESC c) { (void)c; }
typedef void (*Fn)(Ctx *A64_NOESC);
static const struct { const char *name; Fn now, old; } FN[] = {
{"loop", f_80000000, g_80000000}, {"tail call", f_80000100, g_80000100}, {"entered with flags", f_80000140, g_80000140},
{"around a call", f_80000180, g_80000180}, {"32-bit and immediates", f_800001c0, g_800001c0},
{"float (hot, native)", f_80000400, g_80000400}};
static uint64_t rs = 1;
static uint64_t rnd(void) { rs ^= rs << 13; rs ^= rs >> 7; rs ^= rs << 17; return rs; }
static uint64_t rval(void) { /* small numbers, near the sign and wrap edges, and any */
static const uint64_t edge[] = {0, 1, 2, 3, 5, 10, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF, 0x100000000ull,
0x7FFFFFFFFFFFFFFFull, 0x8000000000000000ull, 0xFFFFFFFFFFFFFFFFull, 0xFFFFFFFFFFFFFFFEull};
switch (rnd() % 4) {
case 0: return edge[rnd() % (sizeof edge / sizeof edge[0])];
case 1: return rnd() % 16;
case 2: return edge[rnd() % (sizeof edge / sizeof edge[0])] + (rnd() % 5) - 2;
default: return rnd();
}
}
static uint64_t rfloat(void) { /* a float's bits: zeros, ones, infinities, NaNs, the normal and subnormal edges, and any */
static const uint32_t e[] = {0, 0x80000000u, 0x3f800000u, 0xbf800000u, 0x7f800000u, 0xff800000u, 0x7fc00000u,
0x7fa00000u, 0x00800000u, 0x00000001u, 0x807fffffu, 0x7f7fffffu, 0x4b000000u, 0xcf000000u};
switch (rnd() % 3) {
case 0: return e[rnd() % (sizeof e / sizeof e[0])];
case 1: return 0x3f000000u + (uint32_t)(rnd() % 0x02000000u);
default: return (uint32_t)rnd();
}
}
int main(int argc, char **argv) {
const long n = atol(argv[1]);
rs = strtoull(argv[2], NULL, 10) | 1;
long bad = 0, checks = 0;
for (long i = 0; i < n; i++)
for (unsigned f = 0; f < sizeof FN / sizeof FN[0]; f++) {
Ctx a, b;
memset(&a, 0, sizeof a);
for (int r = 0; r < 32; r++) a.x[r] = rval();
a.n = rnd() & 1, a.z = rnd() & 1, a.c = rnd() & 1, a.v = rnd() & 1;
for (int r = 0; r < 8; r++) a.vreg[r][0] = rfloat() | (rnd() << 32), a.vreg[r][1] = rnd();
b = a;
FN[f].now(&a);
FN[f].old(&b);
checks++;
if (memcmp(a.x, b.x, sizeof a.x) || memcmp(a.vreg, b.vreg, sizeof a.vreg) || a.fpcr != b.fpcr || a.fpsr != b.fpsr) {
if (bad++ < 10) {
printf("mismatch: %s, state %ld:", FN[f].name, i);
if (memcmp(a.vreg, b.vreg, sizeof a.vreg)) printf(" V registers differ");
if (a.fpcr != b.fpcr || a.fpsr != b.fpsr) printf(" FPCR/FPSR %llx/%llx (locals) %llx/%llx (context)",
(unsigned long long)a.fpcr, (unsigned long long)a.fpsr, (unsigned long long)b.fpcr,
(unsigned long long)b.fpsr);
for (int r = 0; r < 32; r++)
if (a.x[r] != b.x[r]) printf(" x%d %llx (locals) %llx (context)", r, (unsigned long long)a.x[r],
(unsigned long long)b.x[r]);
printf("\n");
}
}
}
printf("total checks=%ld bad=%ld\n", checks, bad);
return bad ? 1 : 0;
}
"""
def import_lift_passes():
"""Every pass nx2/lift.py installs, in its order (importing the module installs them), with v0.8.4's float options at
their defaults (A64_NATIVE_FP, A64_FPX_EASY: nativefp reads them as it installs)"""
saved = {k: os.environ.pop(k, None) for k in ("A64_NATIVE_FP", "A64_FPX_EASY", "A64_NATIVE_FP_COLD")}
try:
import importlib
importlib.import_module("lift") # (nx2/lift.py: nx2 is on the path)
finally:
for k, v in saved.items():
if v is not None:
os.environ[k] = v
import nativefp
if not (nativefp._installed and nativefp.native_fp()):
raise SystemExit("local flags: importing nx2/lift.py did not install nativefp with A64_NATIVE_FP on")
def function_text(text, name):
"""One lifted function's text, from its head to the next function's"""
at = text.find("void %s(" % name)
if at < 0:
raise SystemExit("local flags: %s is not in the lift" % name)
end = text.find("\nvoid f_", at + 1)
return text[at:end if end > 0 else len(text)]
# clang's record of a function's profile counters in LLVM IR: the hash of its name, then the hash of its control flow, by
# which -fprofile-instr-use matches the function to a profile's entry (a static function's name after its file's)
PROFD = re.compile(r"^@__profd_(?:\S*?\.c_)?([fg])_([0-9a-f]{8}) = [^\n]*?\} \{ i64 -?\d+, i64 (-?\d+),", re.M)
def profile_hashes(cc, tmp):
"""Each lifted function's control-flow hash in the two lifts (code_now.c, code_old.c with g_ names), as clang computes
it for -fprofile-instr-generate and -use: {address: [with the flags as locals, without]}"""
got = {}
for name, prefix in (("now", "f"), ("old", "g")):
ll = os.path.join(tmp, "code_%s.ll" % name)
fs.build([cc] + fs.target_flags(cc, tmp) + ["-march=x86-64-v3", "-O0", "-S", "-emit-llvm", "-fprofile-instr-generate",
"-D_CRT_SECURE_NO_WARNINGS", "-Wno-everything", "-I" + os.path.join(fs.KIT, "rt"),
"-I" + tmp, os.path.join(tmp, "code_%s.c" % name), "-o", ll],
"the %s lift with profile counters" % name)
with open(ll, encoding="utf-8", errors="replace") as f:
ir = f.read()
found = [m for m in PROFD.finditer(ir) if m.group(1) == prefix]
if not found:
sample = re.search(r"^@__profd_.*$", ir, re.M)
raise SystemExit("local flags: no profile counters of the %s lift's functions in its LLVM IR (%s)"
% (name, sample.group(0)[:200] if sample else "no __profd_ record"))
for m in found:
got.setdefault(m.group(2), [None, None])[name == "old"] = int(m.group(3))
return got
def check_marks(a64_lift, tmp, fcmp, old_text):
"""(11-27) The page marks (a64_lift.group_marks, the lift's last step, nx2/chunks.py edit_c): two stores through one base
with the float function's FCMP between them, as each lift wrote it, share one mark. The kit's MG_PLAIN knew a64_fcmp32
and a64_fcmp64 but not a64_fcmp32k and a64_fcmp64k, so with the flags as locals every scalar FCMP ended a group, and each
store kept its own mark. With the switch off the grouped C is the same, byte for byte, as with MG_PLAIN before them"""
def function(line):
return ("void f_80000800(Ctx *__restrict A64_NOESC c) {\n recomp_store32(c,c->x[19] + 24,c->x[2]);\n" + line
+ "\n recomp_store32(c,c->x[19] + 28,c->x[3]);\n return;\n}\n")
for name, (line,) in sorted(fcmp.items()):
path = os.path.join(tmp, "marks_%s.c" % name)
with open(path, "w", newline="\n") as f:
f.write(function(line))
st = {}
a64_lift.group_marks([path], st)
if (st.get("groups"), st.get("grouped_stores")) != (1, 2):
raise SystemExit("local flags: two stores through one base around the FCMP of the %s lift (%s) are grouped as %s: "
"a64_lift.MG_PLAIN does not take its helpers" % (name, line.strip()[:60], dict(st)))
now = a64_lift.MG_PLAIN
before = re.compile(now.pattern.replace("fcmp32k?|fcmp64k?", "fcmp32|fcmp64"))
if before.pattern == now.pattern:
raise SystemExit("local flags: a64_lift.MG_PLAIN does not name a64_fcmp32k and a64_fcmp64k")
text = old_text + function(fcmp["old"][0])
grouped = []
try:
for plain in (now, before):
a64_lift.MG_PLAIN = plain
a64_lift._mg_plain.clear()
grouped.append(a64_lift.mark_groups(text))
finally:
a64_lift.MG_PLAIN = now
a64_lift._mg_plain.clear()
if grouped[0] != grouped[1] or grouped[0] == text:
raise SystemExit("local flags: with %s=0 the grouped C differs from the C grouped with MG_PLAIN as it was" % SWITCH)
def generate(cxx, tmp, flags):
"""The two lifts (code_now.c, code_old.c with g_ names), the kit's runtime C, in tmp. Returns the C files"""
dll = os.path.join(tmp, "a64emit.dll" if os.name == "nt" else "liba64emit.so")
fs.build([cxx, "-std=c++20", "-O0", "-shared", "-Wno-everything", "-o", dll, os.path.join(fs.KIT, "lift", "a64emit.cpp")]
+ flags + ([] if os.name == "nt" else ["-fPIC"]), "a64emit")
import kit # noqa: F401 (a64-kit on the path)
import build_emit
build_emit.build = lambda force=False: dll # (not a64emit.dll beside the source)
import a64_lift
import a64_rtgen
import a64emit
import local_flags
import oot_patches
check_rule(local_flags, a64_lift)
import_lift_passes()
out = []
natives = {}
fcmp = {}
texts = {}
try:
a64_rtgen.write(tmp)
for name, value in (("now", None), ("old", "0")):
d = os.path.join(tmp, name)
text = lift(a64_lift, d, value)
hot = function_text(text, HOT)
texts[name] = text
natives[name] = [len(re.findall(rx, hot)) for _, rx in NATIVE]
if ("a64_fcmp32k(" in hot) != (value is None) or ("a64_fcmp32(" in hot) != (value is not None):
raise SystemExit("local flags: the float function's FCMP with %s=%r is not the %s form:\n%s"
% (SWITCH, value, "code (a64_fcmp32k)" if value is None else "a64_fcmp32", hot))
if value is None and ("if (!_fk) " not in hot or "if (_fk) " in hot):
raise SystemExit("local flags: the float function's FCMP is the kit's code form, not the hot profile's "
"control flow (nx2/local_flags.py profile_form):\n%s" % hot)
# (11-27) nx2/oot_patches.py's horse step test in this lift's form is the lift's own FCMP (its registers 3 and 1 in
# place of the horse's 10 and 9): a PGO_FCMP written with other spaces would leave it out of the lift, and the
# build only warns
form = oot_patches.HORSE_TEST_LOCAL if value is None else oot_patches.HORSE_TEST
want = form.split("\n", 1)[1].lstrip().replace("c->vreg[10]", "c->vreg[3]").replace("c->vreg[9]", "c->vreg[1]")
if want not in hot:
raise SystemExit("local flags: nx2/oot_patches.py's horse step test %r is not the lift's FCMP with %s=%r:\n%s"
% (want, SWITCH, value, hot))
fcmp[name] = [ln for ln in hot.split("\n") if "a64_fcmp32" in ln]
if len(fcmp[name]) != 1:
raise SystemExit("local flags: the float function's FCMP is not one line:\n%s" % hot)
if value is None:
if "fz_" not in text or not re.search(r"c->n = fn_; c->z = fz_; c->c = fc_; c->v = fv_; TAILCALL\(", text):
raise SystemExit("local flags: the default lift has no flag locals, or no write-back before its tail call")
else:
if re.search(r"\bf[nzcv]_\b", text):
raise SystemExit("local flags: with %s=0 the lift still has flag locals" % SWITCH)
text = re.sub(r"\bf_([0-9a-f]{8})\b", r"g_\1", text)
path = os.path.join(tmp, "code_%s.c" % name)
with open(path, "w", newline="\n") as f:
f.write(text)
out.append(path)
if natives["now"] != natives["old"]:
raise SystemExit("local flags: nativefp's names on the hot float function differ with the flags as locals: %s"
% "; ".join("%s %d (locals) %d (context)" % (k, a, b)
for (k, _), a, b in zip(NATIVE, natives["now"], natives["old"]) if a != b))
if not all(natives["now"][i] for i, (k, _) in enumerate(NATIVE) if k in ("scalar", "conversion", "FPCR sync")):
raise SystemExit("local flags: nativefp left the hot float function without its native names (%s)"
% ", ".join("%s %d" % (k, n) for (k, _), n in zip(NATIVE, natives["now"])))
check_marks(a64_lift, tmp, fcmp, texts["old"])
finally:
if a64emit._lib is not None: # (unloaded, so the folder can go)
import _ctypes
(_ctypes.FreeLibrary if os.name == "nt" else _ctypes.dlclose)(a64emit._lib._handle)
a64emit._lib = None
for d in ("now", "old"): # (each lift's a64_fpx.h is the same header but for its FCMP helpers: the first one serves)
if os.path.exists(os.path.join(tmp, d, "a64_fpx.h")) and not os.path.exists(os.path.join(tmp, "a64_fpx.h")):
with open(os.path.join(tmp, d, "a64_fpx.h"), encoding="utf-8") as src, \
open(os.path.join(tmp, "a64_fpx.h"), "w", newline="\n") as dst:
dst.write(src.read())
rt_c = [os.path.join(tmp, f) for f in sorted(os.listdir(tmp)) if f.startswith("a64_") and f.endswith(".c")]
if len(rt_c) != 1:
raise SystemExit("local flags: a64_rtgen wrote %s, not one C file" % rt_c)
driver = os.path.join(tmp, "local_flags_test.c")
with open(driver, "w", newline="\n") as f:
f.write(DRIVER)
return out + rt_c + [driver]
def check_sources():
with open(os.path.join(ROOT, "nx2", "lift.py"), encoding="utf-8") as f:
lift_py = f.read()
at = [lift_py.find(p) for p in ("import local_flags", "vecfp.install()", "local_flags.install()", "def main():")]
if min(at) < 0 or not at[1] < at[2] < at[3]:
raise SystemExit("local flags: nx2/lift.py does not install nx2/local_flags.py at module level after vecfp's")
nf = lift_py.find("\nnativefp.install()")
if not at[2] < nf < at[3] or re.search(r"^\w+\.install\(\)", lift_py[nf + 1:at[3]].split("\n", 1)[1], re.M):
raise SystemExit("local flags: nx2/lift.py does not install nativefp after local_flags, and last")
with open(os.path.join(ROOT, "nx2", "make_game.py"), encoding="utf-8") as f:
make_game = f.read()
if 'if k.startswith(("A64_", "OOT_", "RX_"))' not in make_game or not SWITCH.startswith("A64_"):
raise SystemExit("local flags: nx2/make_game.py's lift_key no longer takes the A64_ variables: %s is not in the key"
% SWITCH)
not_keyed = re.search(r"^LIFT_KEY_NOT = \((.*?)\) #", make_game, re.S | re.M)
if not not_keyed or '"local_flags.py"' in not_keyed.group(1):
raise SystemExit("local flags: nx2/local_flags.py must stay a file of the lift key")
import oot_patches
for old in (oot_patches.RGBA16F_OLD, oot_patches.RGBA16F_OLD_LOCAL):
s = '#include "a64.h"\nvoid f_80672300(Ctx *c) {\n' + old + "\n}\n"
got = oot_patches.patch_scene_format(s)
if not got or "hos_scene_rgba16f() ? 0x2cULL : 0x1aULL" not in got or oot_patches.RGBA16F_DECL not in got:
raise SystemExit("local flags: nx2/oot_patches.py's scene colour patch does not take %r" % old[-60:])
if "(!fz_)" not in oot_patches.RGBA16F_OLD_LOCAL or "c->z" in oot_patches.RGBA16F_OLD_LOCAL:
raise SystemExit("local flags: the scene colour patch's local form does not read fz_")
check_flag_edits(oot_patches)
with open(os.path.join(ROOT, "docs", "development.md"), encoding="utf-8") as f:
if "| `A64_LOCAL_FLAGS=0` |" not in f.read():
raise SystemExit("local flags: docs/development.md: A64_LOCAL_FLAGS is not in the switches table")
def check_flag_edits(o):
"""(11-26, on v0.8.3) The edits that match a flag by its text, on authored functions as a lift with the flags as locals
writes them (the flags' declaration after the head, the kit's localize_regs): each made once, and a second run changes
nothing. (11-27, on v0.8.4) And the cloth's solve gate, whose place is counted in lines from the head: the declaration is
no line of the job's own (counted, it left the gate out of the lift, and the cloth solved at every frame above 60 fps)."""
if o.local_form("if (!c->n) { x = c->x[3]; c->vreg[2][0] = c->c; }") != "if (!fn_) { x = c->x[3]; c->vreg[2][0] = fc_; }":
raise SystemExit("local flags: nx2/oot_patches.py local_form is not the kit's rule (only c->n, z, c and v)")
with open(os.path.join(ROOT, "third_party", "a64-kit", "lift", "a64_lift.py"), encoding="utf-8") as f:
kit = f.read()
if 'fdecl = "\\n' + o.FLAG_DECL.rstrip("\n") + '"' not in kit:
raise SystemExit("local flags: nx2/oot_patches.py FLAG_DECL is not the declaration the kit's localize_regs writes")
if 'FLAG_REF = re.compile(r"%s")' % o.FLAG_REF.pattern not in kit:
raise SystemExit("local flags: nx2/oot_patches.py FLAG_REF is not the kit's (a64_lift.FLAG_REF): local_form would "
"write other text than localize_regs")
d = o.FLAG_DECL
# the cloth's solve job: its gate before the first store, which follows the head, the flags' declaration and a hint
for name, pre, want in (("with the flags as locals", d, 1), ("with the flags in the context", "", 1),
("a store that is not the job's first line", d + " c->x[1] = 0;\n", 0)):
cloth = ('#include "a64.h"\n' + o.CLOTH_SOLVE_HEAD + pre + " /* nop/hint */\n" + o.CLOTH_SOLVE_OLD
+ " c->x[0] = 1;\n return;\n}\n")
got, n = o.patch_cloth_solve(cloth)
made = n == 1 and got.count(o.CLOTH_SOLVE_NEW + o.CLOTH_SOLVE_OLD) == 1 and o.CLOTH_SOLVE_DECL in got
if (want and not made) or (not want and (n or got != cloth)):
raise SystemExit("local flags: the cloth's solve gate %s: %s, wanted %s" % (name, "made" if n else "left out",
"made" if want else "left out"))
if want and o.patch_cloth_solve(got) != (got, 1):
raise SystemExit("local flags: the cloth's solve gate is not left as it is by a second run (%s)" % name)
# the Movement speed tool's four places, one of which (f_80964bf0's) is the head and the line after it
speed = '#include "a64.h"\n'
for head in dict.fromkeys(h for h, _, _ in o.SPEED_PLACES):
speed += head + d + "".join(a[len(h):] if a.startswith(h) else a for h, a, _ in o.SPEED_PLACES if h == head)
speed += " return;\n}\n"
got, n = o.patch_cct_speed(speed)
if n != len(o.SPEED_PLACES) or got.count("hos_oot_cct_speed(c, c->x[0], ") != len(o.SPEED_PLACES):
raise SystemExit("local flags: the Movement speed tool's places in a lift with the flags as locals: %d of %d"
% (n, len(o.SPEED_PLACES)))
if o.patch_cct_speed(got) != (got, len(o.SPEED_PLACES)):
raise SystemExit("local flags: the Movement speed tool's calls are not left as they are by a second run (local form)")
# the horse's jump state machine: the step test (the FCMP's code form) and its branch on fn_
if "c->n" in o.HORSE_BRANCH_LOCAL or "a64_fcmp32k(" not in o.HORSE_TEST_LOCAL or "a64_fcmp32(" in o.HORSE_TEST_LOCAL:
raise SystemExit("local flags: the horse's jump test has no local form")
for rest in ("fn_=(uint8_t)(_fk&1); fz_=(uint8_t)(_fk>>1&1); if (!_fk) { fn_ = 0; } }\n", # (nx2/local_flags.py's form)
"if (_fk) { fn_=(uint8_t)(_fk&1); fz_=(uint8_t)(_fk>>1&1); } else { fn_ = 0; } }\n"): # (the kit's)
horse = ('#include "a64.h"\n' + o.HORSE_HEAD + d + " c->x[0] = 0;\n" + o.HORSE_TEST_LOCAL + rest
+ o.HORSE_BRANCH_LOCAL + " c->x[0] = 1;\nL_82c5ae48:;\n}\n")
got, n = o.patch_horse_jump(horse)
if n != 1 or got.count(o.HORSE_SKIP + o.HORSE_BRANCH_LOCAL) != 1 or o.HORSE_DECL not in got:
raise SystemExit("local flags: the horse's jump step patch does not take a lift with the flags as locals (%s)"
% rest.strip())
if o.patch_horse_jump(got) != (got, 1):
raise SystemExit("local flags: the horse's jump step patch is not left as it is by a second run (local form)")
# the Camera centering row's anchor (fz_)
cam = ('#include "a64.h"\n' + o.CAM_HEAD + d + "L_80645ad8:;\n c->x[8]=recomp_load32(c,c->x[19] + 516);\n"
"if (fz_) { { A64_POLL(c); goto L_80645ad8; } }\ngoto L_806492c4;\n" + o.CAM_FOLLOW_ANCHOR_LOCAL
+ "c->x[30] = 0x80647218ULL; f_80649970(c);\n{ A64_POLL(c); goto L_80645ad8; }\nL_806492c4:;\n}\n")
got, n = o.patch_camera_centering(cam)
if n != 1 or got.count(o.CAM_FOLLOW_ANCHOR_LOCAL + o.CAM_FOLLOW_HOOK) != 1 or o.CAM_FOLLOW_DECL not in got:
raise SystemExit("local flags: the Camera centering row's patch does not take a lift with the flags as locals")
if o.patch_camera_centering(got) != (got, 1):
raise SystemExit("local flags: the Camera centering row's patch is not left as it is by a second run (local form)")
# the ocarina wait: the tick's mode gate (fz_) with its other gates and hooks
if "c->z" in o.OC_TICK_GATES_LOCAL[0][0] or "(!fz_)" not in o.OC_TICK_GATES_LOCAL[0][0]:
raise SystemExit("local flags: the ocarina wait's mode gate has no local form")
oc = ('#include "a64.h"\n' + o.OC_ENTRY_HEAD + "\n" + o.OC_ENTRY_OLD + "\nA64_IJUMP(c, c->x[2]); return;\n}\n"
+ o.OC_TICK_HEAD + "\n" + d + o.OC_TICK_OLD + "\n" + o.OC_TICK_GATES_LOCAL[0][0] + "\n" + o.OC_TICK_GATES_LOCAL[1][0]
+ "\nL_828a92f8:; A64_POLL(c);\n" + o.OC_TICK_GATES_LOCAL[2][0] + "\nL_828a937c:; A64_POLL(c);\n" + o.OC_DONE_OLD
+ "\n" + o.OC_RESET_OLD + "\nL_828a92e4:; A64_POLL(c);\nreturn;\n}\n"
+ "void f_828a94e0(Ctx *__restrict A64_NOESC c) {\nreturn;\n}\n")
got = o.patch_ocarina_wait(oc)
news = [o.OC_ENTRY_NEW, o.OC_TICK_NEW, o.OC_DONE_NEW, o.OC_RESET_NEW] + [new for _, new in o.OC_TICK_GATES_LOCAL]
if got is None or any(got.count(new) != 1 for new in news) or o.OC_DECL not in got:
raise SystemExit("local flags: the ocarina wait's patch does not take a lift with the flags as locals")
if o.patch_ocarina_wait(got) != got:
raise SystemExit("local flags: the ocarina wait's patch is not left as it is by a second run (local form)")
def main():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--cc")
p.add_argument("--cxx")
p.add_argument("--random", type=int, default=200000)
a = p.parse_args()
check_sources()
if platform.machine().lower() not in ("x86_64", "amd64"):
fs.skip("not an x86-64 host: %s" % platform.machine())
cc = fs.compiler(a.cc, "CC", ("clang", "gcc", "cc"), "clang")
cxx = fs.compiler(a.cxx, "CXX", ("clang++", "g++", "c++"), "clang++")
if not cc or not cxx:
fs.skip("no C compiler" if not cc else "no C++ compiler")
t0 = time.time()
with tempfile.TemporaryDirectory(prefix="triforce-local-flags-") as tmp:
sources = generate(cxx, tmp, fs.target_flags(cxx, tmp))
hashes = profile_hashes(cc, tmp)
differ = sorted("f_%s" % a for a, pair in hashes.items() if None in pair or pair[0] != pair[1])
if len(hashes) < 6 or differ:
raise SystemExit("FAIL: local flags: with the flags as locals clang hashes the control flow of %s differently "
"(%d functions): the hot code built with the shipped profile would leave theirs out"
% (", ".join(differ) or "none", len(hashes)))
exe = os.path.join(tmp, "local_flags_test.exe")
fs.build([cc] + fs.target_flags(cc, tmp) + ["-march=x86-64-v3"] + fs.FLAGS +
["-D_CRT_SECURE_NO_WARNINGS", "-Wno-everything", "-I" + os.path.join(fs.KIT, "rt"), "-I" + tmp]
+ sources + ["-o", exe], "the driver")
r = fs.run([exe, str(a.random), str(SEED)], timeout=1200)
print(r.stdout.rstrip())
total = re.search(r"total checks=(\d+) bad=(\d+)", r.stdout)
if r.returncode or not total or total.group(2) != "0":
raise SystemExit("FAIL: local flags: the lift with the flags as locals left other registers or float state (exit %d)"
% r.returncode)
print("PASS: six functions (one float, hot) lifted with %s on (the default) and off leave the same X0-X30, SP, V0-V7, FPCR and FPSR from %s states, "
"and clang hashes the control flow of all %d alike (%.0f s)" % (SWITCH, total.group(1), len(hashes), time.time() - t0))
if __name__ == "__main__":
main()

View File

@@ -94,7 +94,10 @@ class MarkGroupsTests(unittest.TestCase):
" { uint64_t _p0,_p1; recomp_ldp64(c,(c->x[20]+16ULL),&_p0,&_p1); c->x[0]=_p0; c->x[1]=_p1; }",
" { uint64_t _v=0; memcpy(&_v,&c->vreg[3][0],8); a64_vset64(c->vreg[1],_v); }",
" { extern volatile uint64_t hos_wide_out; const uint64_t _s = hos_wide_out; if (_s) c->x[8] = _s; }",
" c->x[9] = UINT64_C(1) << 3;", " /* ic ivau: no self-modifying code */"):
" c->x[9] = UINT64_C(1) << 3;", " /* ic ivau: no self-modifying code */",
# ((Triforce, 11-27) a scalar FCMP with the flags as locals: nx2/local_flags.py's form and the kit's)
" { const uint32_t _fk = a64_fcmp32k(c,c->vreg[3],c->vreg[1]); fn_=(uint8_t)(_fk&1); if (!_fk) { fn_=0; } }",
" { const uint32_t _fk = a64_fcmp64k(c,c->vreg[3],a64_vzero); if (_fk) { fz_=1; } else { fz_=0; } }"):
out = run(" recomp_store32(c,c->x[21] + 0,c->x[1]);", plain, " recomp_store32(c,c->x[21] + 4,c->x[2]);",
" return;")
self.assertEqual(out[3], mark(21, 0, 8), plain)

273
tests/test_menu_apply.py Normal file
View File

@@ -0,0 +1,273 @@
"""(Triforce, 11-26) The options' Apply: the rows that took a restart and now change in play. The owner: "Every option that
requires a restart should be changed in game without having to restart unless if the setting has to have the game be
restarted. I want you to implement an apply option in the menu ... If the player tries to back out without applying the
settings, they should get a pop-up that asks them to apply these settings. Same prompt as the Restart pop up."
What it checks:
- host/res_follow.h, compiled and run: the Render resolution's scale as the menu applies it, each present (fixed to fixed,
Auto and back, a smaller one, the pool held to its size at a 5K picture, the same scale asked again, before the renderer
answers, HOS_RES_SCALE's place).
- The renderer reads the three rows taken at Apply as applied (vk_menu.h applied_dlss and its kin), never as the rows are
being stepped: the upscaler's engine (vk_temporal.cpp, vk_fsr3.cpp, vk_draw.cpp), DLSS's feature size (vk_dlss.cpp), the
upscale before the bloom, read each time (vk_temporal.cpp pre_wanted), and the host's options 2 and 3 (vk_replay.cpp), by the
applied choice alone (no stand-in, no N64 Classic: they would remake the game's targets back and forth).
- host/nn_vi.c takes the options each present: no value read once at the start; Steady pacing from the row each present
(steady_mode), its set made again on a change and the renderer told when it is off.
- The menu: the rows' flags (none of the three takes a restart, Frame pacing neither), the state (apply_init, set_row's note,
menu_apply), the guide (Apply first among them while a row waits, on the tuning bar too, a click on it, the key and the
button bound to the Switch's X), the question (Apply's before the restart question, on the same page, with Later and Apply
Now; then the restart question if one waits), and the texts in every one of the menu's languages.
No game, no GPU.
python -I -B tests/test_menu_apply.py [--cc gcc]
"""
import argparse
import re
import subprocess
import sys
import tempfile
from pathlib import Path
RUN_ALL_ARGS = ["--cc", "gcc"]
ROOT = Path(__file__).resolve().parents[1]
VK = ROOT / "gpu" / "vk"
FOLLOW_TEST = r"""
#include "res_follow.h"
#include <assert.h>
#include <stdio.h>
int main(void) {
/* before the renderer answers: nothing taken, the game's own 1.0 stays */
ResFollow f = {-1, 0, 0};
assert(res_follow(&f, -1, -1, 0) == RES_SAME && f.scale == -1 && f.largest == 0);
/* the start: fixed 50%, taken; the largest is it */
assert(res_follow(&f, 0, 5000, 0) == RES_TAKE && f.scale == 5000 && f.largest == 5000);
assert(res_follow(&f, 0, 5000, 0) == RES_SAME); /* (each present after: nothing new) */
/* Apply 100%, the pool not held: taken at once */
assert(res_follow(&f, 0, 10000, 0) == RES_TAKE && f.scale == 10000 && f.largest == 10000);
/* Apply 33%: taken, the largest stays */
assert(res_follow(&f, 0, 3333, 0) == RES_TAKE && f.scale == 3333 && f.largest == 10000);
/* Apply Auto: the dynamic path's; the fixed scale stays as it was for the way back */
assert(res_follow(&f, 1, 0, 0) == RES_SAME && f.scale == 3333);
/* back to fixed 67%: taken */
assert(res_follow(&f, 0, 6667, 0) == RES_TAKE && f.scale == 6667);
/* a 5K picture, the pool held to its 900 MB: the start's 50% */
ResFollow k = {-1, 0, 0};
assert(res_follow(&k, 0, 5000, 1) == RES_TAKE && k.largest == 5000);
/* 100% asked: kept for the next start, said once */
assert(res_follow(&k, 0, 10000, 1) == RES_HOLD && k.held == 10000 && k.scale == 5000);
assert(res_follow(&k, 0, 10000, 1) == RES_SAME && k.held == 10000);
/* 33% asked: smaller, taken; nothing kept back */
assert(res_follow(&k, 0, 3333, 1) == RES_TAKE && k.scale == 3333 && k.held == 0);
/* back up to 50%, the start's: no larger than the largest, taken */
assert(res_follow(&k, 0, 5000, 1) == RES_TAKE && k.scale == 5000);
/* 67% asked, then back to the scale in force: kept, then freed */
assert(res_follow(&k, 0, 6667, 1) == RES_HOLD && k.held == 6667);
assert(res_follow(&k, 0, 5000, 1) == RES_FREE && k.held == 0 && k.scale == 5000);
/* held, then Auto: freed */
assert(res_follow(&k, 0, 6667, 1) == RES_HOLD);
assert(res_follow(&k, 1, 0, 1) == RES_FREE && k.held == 0);
/* a 5K picture that started on Auto: the largest is the dynamic path's 75%; 67% is taken, 100% kept back */
ResFollow a = {-1, 0, 0};
assert(res_follow(&a, 1, 0, 1) == RES_SAME && a.largest == 7500);
assert(res_follow(&a, 0, 6667, 1) == RES_TAKE && a.scale == 6667);
assert(res_follow(&a, 0, 10000, 1) == RES_HOLD && a.scale == 6667);
puts("res_follow: all checks passed");
return 0;
}
"""
def function(source, start):
at = source.find(start)
if at < 0:
raise SystemExit("%s is missing" % start)
body = source[at:]
return body[:body.index("\n}\n")]
def check(ok, why):
if not ok:
raise SystemExit("FAIL: " + why)
def row(menu, start):
at = menu.find(start)
check(at >= 0, "the row " + start + " is missing")
return menu[at:menu.index("},", at)]
def renderer():
temporal = (VK / "vk_temporal.cpp").read_text(encoding="utf-8")
mode = function(temporal, "int temporal_mode() {")
check("const int v = applied_dlss();" in mode and "rearm_on_choice(v);" in mode and "return temporal_mode_of(v, true);" in mode,
"temporal_mode does not run the Upscaler as applied")
mode_of = function(temporal, "int temporal_mode_of(int choice, bool now) {")
check("opts.dlss" not in mode_of and "if (now) v = n64_rules::upscaler(n64_in_front(), v);" in mode_of and
"if (now && stood_in(v)) return ur::GAME;" in mode_of and "if (fsr3_wanted_of(choice, now)) return ur::GAME;" in mode_of,
"temporal_mode_of does not leave the stand-ins out without now")
check("int v = applied_dlss();" in function(temporal, "int temporal_stood_in() {"), "temporal_stood_in reads the row as stepped")
pre = function(temporal, "bool pre_wanted(int mode) {")
check("applied_upscale_pre() != 0" in pre and "static const bool on" not in pre and "upscale_pre_at_start" not in pre,
"Upscale before bloom is not read each time, as applied")
fsr3 = (VK / "vk_fsr3.cpp").read_text(encoding="utf-8")
check("bool fsr3_wanted() { return fsr3_wanted_of(applied_dlss(), true); }" in fsr3 and
"bool fsr3_native() { return fsr3_native_of(applied_dlss(), true); }" in fsr3, "FSR 3.1 does not run as applied")
wanted = function(fsr3, "bool fsr3_wanted_of(int choice, bool now) {")
check("opts.dlss" not in wanted and "upscaler_rows::is_fsr3(choice)" in wanted and "if (now && n64_rules::upscaler(" in wanted,
"fsr3_wanted_of does not read its choice")
check("opts.dlss" not in function(fsr3, "bool fsr3_native_of(int choice, bool now) {"), "fsr3_native_of reads the row")
dlss = (VK / "vk_dlss.cpp").read_text(encoding="utf-8")
check("s.range_seen || applied_resolution() == 0" in dlss and "opts.resolution" not in dlss, "DLSS's feature reads the row as stepped")
draw = (VK / "vk_draw.cpp").read_text(encoding="utf-8")
off = function(draw, "static bool upscale_off_on() {")
check("applied_dlss() == upscaler_rows::OFF" in off and "opts.dlss" not in off, "the Upscaler's Off is not as applied")
for name, src in (("vk_temporal.cpp", temporal), ("vk_fsr3.cpp", fsr3), ("vk_draw.cpp", draw)):
check(not re.search(r"\bopts\.dlss\b", re.sub(r"//[^\n]*", "", src)), name + " reads the Upscaler row as it is being stepped")
replay = (VK / "vk_replay.cpp").read_text(encoding="utf-8")
check("id == 2 ? resolution_auto() && !resolution_full() : id == 3 ? (resolution_full() ? 10000 : resolution_scale())" in replay,
"the host's options 2 and 3 are not the Render resolution as applied")
check("if (id == HOS_OPT_STEADY_ROW) return menu_steady_row();" in replay, "the host is not told the Steady row")
api = (VK / "vk_api.h").read_text(encoding="utf-8")
check("enum { HOS_OPT_STEADY_ROW = 430 };" in api and "enum { HOS_OPT_RES_HELD = 431 };" in api, "the two options' numbers")
check("#define MKWVK_API_VERSION 25" in api, "the options need no new function: MKWVK_API_VERSION stays")
def host():
vi = (ROOT / "host" / "nn_vi.c").read_text(encoding="utf-8")
check('#include "res_follow.h"' in vi, "nn_vi.c does not take res_follow.h")
step = function(vi, "static void realtime_step(int64_t now) {")
check("dyn_at_start" not in step and "if (scale < 0) scale = rx_option(3, -1);" not in step,
"realtime_step still reads the Render resolution once, at the start")
check("const int asked = rx_option(2, -1);" in step and "res_dyn = asked;" in step and
"hos_fixed_resolution = !pulsed && res_dyn == 0 && hos_dynres_runs >= from;" in step,
"realtime_step does not follow Auto as applied")
check("res_follow(&follow, res_dyn, asked, pinned)" in step and "hos_rt_pool_pinned()" in step and
"rx_option_set(HOS_OPT_RES_HELD, asked);" in step and "memcpy((void *)&hos_fixed_scale_bits, &v, 4);" in step,
"realtime_step does not take the applied scale, or keep a larger one back where the pool is held")
check(step.index("res_follow(") < step.index('getenv("HOS_RES_SCALE")) { float v'), "HOS_RES_SCALE no longer goes over the row")
mode = function(vi, "static int steady_mode(void) {")
check("rx_option(HOS_OPT_STEADY_ROW, -1)" in mode and 'getenv("HOS_FPS_STEADY")' in mode and
'hos_ini_option("steady_frame_rate", PACE_STEADY_OFF)' in mode, "steady_mode does not follow the row, the switch over it")
check("steady = steady_mode();" in function(vi, "static void movie_pace_decide(void) {"), "the movie pacing reads Steady once")
period = function(vi, "static int64_t steady_period(int64_t base, int64_t now) {")
check("const int want = steady_mode();" in period and "pace_steady_reset(&steady);" in period and
"rx_option_set(HOS_OPT_PACE_STEADY, 0);" in period and "mode = want, cap = 0, frames = 0;" in period and
"if (mode < 0) {" not in period, "steady_period does not make its set again on a change in play")
def menu():
src = (VK / "vk_menu.cpp").read_text(encoding="utf-8")
hdr = (VK / "vk_menu.h").read_text(encoding="utf-8")
for f in ("int applied_dlss();", "int applied_resolution();", "int applied_upscale_pre();", "bool resolution_full();",
"int menu_steady_row();"):
check(f in hdr, "vk_menu.h does not declare " + f)
check("int applied_rows[3] = {Options().dlss, Options().resolution, Options().upscale_pre};" in src, "the applied values")
check("bool applies(const Row& r) { return r.value == &opts.dlss || r.value == &opts.resolution || r.value == &opts.upscale_pre; }"
in src, "the rows taken at Apply")
# (the rows: none of the three takes a restart now, nor Frame pacing; each help says Apply)
for start, help_end in (('{TAB_GRAPHICS, "Upscaler", &opts.dlss,', 'Takes effect after Apply.", hn_upscaler'),
('{TAB_GRAPHICS, "Render resolution", &opts.resolution,', 'Takes effect after Apply.", hn_resolution'),
('{TAB_GRAPHICS, "Upscale before bloom", &opts.upscale_pre,', 'Takes effect after Apply.", nullptr, false, true')):
entry = row(src, start)
check(help_end in entry and not re.search(r",\s*true$", entry.split("hn_")[0] if "hn_" in entry else ""),
start + " is not a row taken at Apply")
check(row(src, '{TAB_GRAPHICS, "Frame pacing", &merged.pacing,').rstrip().endswith("hn_pacing"), "Frame pacing still takes a restart")
value_of = function(src, "int restart_value_of(const Row& r) {")
check("merged.pacing" not in value_of and "ur::full_scale(opts.dlss)" not in value_of and
"if (r.value == &opts.resolution) return res_held.load(std::memory_order_relaxed) != 0;" in value_of,
"restart_value_of: the Render resolution takes a restart only while the host keeps a larger 3D back")
check("if (id == HOS_OPT_RES_HELD) {" in function(src, "void menu_option_set(int id, int value) {"), "the host's word is not kept")
# (the state)
check("apply_init();" in function(src, "void menu_init() {"), "menu_init does not take the file's choice as what runs")
check("apply_state.note(now);" in function(src, "void set_row("), "set_row does not tell the Apply state of a change")
ap = function(src, "void menu_apply(const char* why) {")
check("applied_take(was);" in ap and "save();" in ap and "apply_state.later = false;" in ap, "menu_apply does not take the choice")
take = function(src, "void applied_take(unsigned mask) {")
check("__atomic_store_n(to, *rows[i].value, __ATOMIC_RELAXED);" in take and "apply_state.start[slot] = *rows[i].value;" in take,
"applied_take does not store what runs")
check("applied_take_row(&opts.resolution);" in function(src, "void menu_first_start() {"), "a first start's Render resolution waits")
check("applied_take_row(&opts.dlss), applied_take_row(&opts.resolution);" in function(src, "void auto_start() {"),
"Auto (this PC)'s choice for new hardware waits for Apply at the start")
check("applied_take_row(&opts.resolution);" in function(src, "void auto_tick() {"), "Auto (this PC)'s tuning waits for a restart")
# (what runs for the host and the performance panel: the applied rows, the choice alone)
check("bool resolution_auto() { return applied_resolution() == 0; }" in src and
"bool resolution_full() { return ur::full_scale(upscaler_of(applied_dlss(), false)); }" in src, "resolution_*")
check("ur::snap(upscaler_of(applied_dlss(), false), applied_resolution())" in function(src, "int resolution_scale() {"),
"resolution_scale is not the Render resolution as applied")
perf = function(src, "const char* perf_upscaling_text(char* out, size_t n) {")
check("upscaler_of(applied_dlss(), true)" in perf and "resolution_name(up, applied_resolution())" in perf,
"the performance panel shows the rows as stepped")
check("int upscaler() { return upscaler_of(opts.dlss, true); }" in src, "the rows do not show the choice")
# (the guide)
opt = function(src, "void draw_options(ui::Ctx& c) {")
check("prompt_list[0] = {ui::kApply, \"Apply\"}, prompts_n++;" in opt and "const bool to_apply = apply_pending() != 0;" in opt and
"menu_hit::kButton, kApplyGuide" in opt and "row_pending(r)" in opt and "apply_line(c, kHintPt * s, cap_w - 20 * s)" in opt,
"the options' page has no Apply guide, its click or its rows' marks")
check("apply_changed(selr) ? kNoteApply" in opt, "the caption does not say a row waits for Apply")
bar = function(src, "void draw_tune_bar(ui::Ctx& c) {")
check("list[0] = {ui::kApply, \"Apply\"}, n++;" in bar and "kApplyGuide" in bar, "the tuning bar has no Apply")
tick = function(src, "void menu_tick() {")
check("menu_bound_key(HOS_SW_X, 0), menu_bound_key(HOS_SW_X, 1), (int)VK_SPACE, (int)'F'" in tick and
"host->binding(HOS_BIND_PAD, HOS_SW_X, 0)" in tick and
"pad(pad_apply)" in tick, "Apply's key and button are not the Switch's X as bound")
check("hit.part == menu_hit::kButton && hit.index == kApplyGuide" in tick and 'menu_apply("the guide");' in tick and
"apply_pending()" in tick, "page 0 does not apply on the guide")
check('if (!strcmp(key, "APPLY")) apply_press = true;' in tick, "RX_VK_MENU_SCRIPT has no APPLY")
# (the question)
first = tick[tick.index("auto ask_first = [&] {"):]
first = first[:first.index("};")]
check(first.index("apply_ask()") < first.index("restart_ask()") and "page = 5" in first, "Apply's question is not asked first")
later = tick[tick.index("auto later = [&] {"):]
later = later[:later.index("\n };")]
check("apply_state.choose_later(now);" in later and "ask_kind = kQuestionRestart, ask_sel = 0" in later,
"Apply's Later does not go on to the restart question")
check("press[5] && ask_first()" in tick and "open_now.load() && ask_first()" in tick, "closing does not ask first")
now = tick[tick.index("press[7] && ask_kind == kQuestionApply"):]
now = now[:now.index("} else if (press[7]) {")]
check('menu_apply("the question\'s Apply Now");' in now and "if (restart_ask()) ask_kind = kQuestionRestart" in now,
"Apply Now does not apply, then ask about the restart")
ask = function(src, "void draw_ask(ui::Ctx& c) {")
for need in ('"Apply Settings"', 'i18n::tr("Apply ")', '"Apply Now"', '"Later"', "apply_list_shown(i18n::tr(\" and \"))"):
check(need in ask, "the question has no " + need)
# (inside the game's own Options screen the game's list showed through under the question's text: darker there)
check("dim_page(c, ui::rgba(8, 5, 2, c.over_game ? 215 : 110));" in ask, "the question does not dim the game's own screen")
ui = (VK / "vk_ui.h").read_text(encoding="utf-8")
check("kClear, kApply };" in ui and "case kApply: return icon(x, c.apply_icon);" in ui and
"if (pr.g == kApply && !c.pad) return key(x, c.key_apply);" in ui, "vk_ui.h has no Apply guide")
def languages():
table = (VK / "menu_i18n.h").read_text(encoding="utf-8")
names = re.findall(r"inline constexpr Entry (k\w+)\[\] = \{\n(.*?)\n\};", table, re.S)
check(len(names) == 13, "the menu's 13 languages")
for name, body in names:
for text in ("Apply Settings", "Apply ", "Apply Now", "The game goes on where it is. The picture may pause for a moment.",
"Apply needed: ", "Takes effect after Apply",
"What draws the 3D up to the Output resolution. Takes effect after Apply."):
check(' {"%s", "' % text in body, "%s: %r is not translated" % (name, text))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cc", default="gcc")
args = parser.parse_args()
renderer()
host()
menu()
languages()
with tempfile.TemporaryDirectory(prefix="menu-apply-") as tmp:
src = Path(tmp) / "res_follow_test.c"
src.write_text(FOLLOW_TEST, encoding="utf-8")
exe = Path(tmp) / ("res-follow" + (".exe" if sys.platform == "win32" else ""))
subprocess.run([args.cc, "-std=c11", "-Wall", "-Wextra", "-Werror", "-I", str(ROOT / "host"), str(src), "-o", str(exe)], check=True)
subprocess.run([str(exe)], check=True)
print("PASS: the options' Apply")
if __name__ == "__main__":
main()

View File

@@ -76,6 +76,9 @@ def sources():
press = press[:press.index("\n}\n")]
if "if (bit == HOS_MOUSE_LEFT && hos_oot_options_front()) InterlockedOr(&ptr_pressed, bit);" not in press:
raise SystemExit("display.c: the game's Options screen's clicks do not reach the tabs over its header")
# ((Triforce) and the title's: its Mods and Save Select tabs at the top left are the renderer's (draw_title_tabs))
if "else if (bit == HOS_MOUSE_LEFT && hos_oot_title_tabs()) InterlockedOr(&ptr_pressed, bit);" not in press:
raise SystemExit("display.c: the title's clicks do not reach its tabs at the top left")
def main():

View File

@@ -0,0 +1,393 @@
"""The options' page slider under the mouse: the scroll bar beside a list (gpu/vk/vk_menu.cpp scroll_bar; the dark track with
the gold thumb at the left of a tab's rows, of the Controls page, of the teleport list and of the Mods cards, and at the right
of a mod's description) only showed how far the list was scrolled. (Triforce) The owner: "I want you to make that accessible
for mouse. So when a player clicks that, it should be able to move up or down. How a normal touch slider should work."
The arithmetic is gpu/vk/vk_menu_hit.h's Bar, with no ImGui and no Vulkan, compiled here alone; with it are compiled, cut
out of vk_menu.cpp by their text: scroll_rows (where a rows' list stands), what scroll_bar records of the bar it draws,
bar_scroll (where each list keeps its place) and bar_mouse (the press, the hold and the letting go). No game. Checked:
- the bar that is recorded is the bar that is drawn: its thumb's top and bottom are the picture's, at any place of the list;
- it is taken hold of a little either side of the thin track and past its ends, not beside a list that fits its view, and
a control drawn after it (a card whose edge it reaches) keeps its own hit;
- a press on the thumb moves nothing; held, the list follows the cursor in proportion, between two rows too and without
easing (the thumb stays under the cursor), to the list's ends and no further, wherever the cursor goes, off the bar too;
- let go, a rows' list comes to whole rows; the selection has not moved, and the next move of it by the keys or the pad
brings it into view exactly as it does after the wheel;
- a press on the track off the thumb brings the thumb's middle under the cursor, the list with it, and is held the same
way; a click shorter than a tick still takes the list there;
- a short thumb (a long list of cards) is taken hold of a little either side of itself without the list moving;
- the cards' lists stop following the choice, as after the wheel, and the description's follows too;
- the bar the cursor is on, or holds, is the one drawn brighter; a list no longer drawn lets go;
- none of it is a sound: nothing the sounds are told of changes (menu_sound_events.h sound_of), as with the wheel.
And the source is read for the rest: every scroll bar drawn has its list's number, every page that draws one gives its
mouse to bar_mouse first and leaves the wheel, the rows and the cards alone while one is held, and a bar held is let go
with the button on any page and when the menu shuts.
python -I -B tests/test_menu_page_slider.py [--cxx g++]
"""
import argparse
import re
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 between, block # noqa: E402
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
ROOT = Path(__file__).resolve().parents[1]
MENU = ROOT / "gpu" / "vk" / "vk_menu.cpp"
def check(ok, why):
if not ok:
raise SystemExit("FAIL: " + why)
FIXTURE = r'''#include "@ROOT@/gpu/vk/vk_menu_hit.h"
#include "@ROOT@/gpu/vk/menu_sound_events.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <utility>
#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); std::exit(1); } } while (0)
// ---- what the menu's own lines stand on, here: the pointer, the units, the lists' places ----
enum { HOS_MOUSE_LEFT = 1, HOS_MOUSE_RIGHT = 2 };
struct MkwVkPointer { int x, y, width, height; unsigned held, pressed; int wheel; };
typedef unsigned ImU32;
namespace ui {
struct Ctx { float s; bool over_game; };
inline float lu(const Ctx& c, float units) { return units * c.s / 3; }
}
namespace mkwvk {
enum { kSlots = 10 };
menu_hit::Map hits;
float scroll_at[kSlots], scroll_want[kSlots];
int wheel_rows[kSlots], scrolled_to[kSlots] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
float teleport_scroll_px = 0, teleport_want_px = 0, mods_scroll_px = 0, mods_want_px = 0, mods_desc_px = 0;
bool teleport_follow = true, mods_follow = true;
int inventory_page = 0, names_shown = 0; // ((Triforce, 11-26) the paged pages' page, a step of their sliders)
void names_slider_to(int page) { names_shown = page; }
@STATE@
float ease_step = 1;
@SCROLL_ROWS@
@BAR_SCROLL@
@BAR_MOUSE@
/// (scroll_bar's own lines, from its track to the bar it records; the picture's thumb given back)
void record_bar(ui::Ctx& c, float x, float top, float bottom, int n, int shown, float first, int id, float* thumb0, float* thumb1) {
@BAR_RECORD@
(void)w;
*thumb0 = y0, *thumb1 = y1;
}
} // namespace mkwvk
using namespace mkwvk;
static bool near(float a, float b, float tol = 0.001f) { return std::fabs(a - b) <= tol; }
static ui::Ctx ctx{2, false}; // (a 1440-high window: 2 pixels a point, a unit two thirds of a pixel)
static const float kX = 58, kTop = 653, kBottom = 861; // (the bar's middle line and its list's span: its track 653 to 861)
static float thumb0, thumb1;
/// A drawing of a tab's rows: where scroll_rows has them (8 fit), and their bar recorded as scroll_bar records it
static float draw_rows(int slot, int n, int sel) {
int shown = 0;
const float first = scroll_rows(slot, n, sel, 0, 800, 100, &shown);
CHECK(shown == 8);
hits.clear(0, 0, 2560, 1440);
record_bar(ctx, kX, kTop, kBottom, n, shown, first, slot, &thumb0, &thumb1);
hits.add(138, 200, 1354, 280, menu_hit::kRow, 0); // (a row, right of the bar: drawn after it)
return first;
}
/// A tick of the mouse: the buttons, the cursor; what bar_mouse says, and whether it asked for another drawing
static bool redraw;
static bool tick(unsigned held, unsigned pressed, float x, float y) {
MkwVkPointer ptr{};
ptr.held = held, ptr.pressed = pressed;
redraw = false;
return bar_mouse(ptr, (int)y, hits.at(x, y), redraw);
}
int main() {
using menu_hit::Bar;
// ---- the arithmetic alone: a track 600 to 808 beside 26 rows of which 8 show: 8 pixels a row, a thumb of 64 ----
{
Bar b{3, 600, 808, 26, 8, 9, 0};
CHECK(b.scrolls() && near(b.most(), 18) && near(b.length(), 64));
CHECK(near(b.thumb(0), 600) && near(b.thumb(9), 672) && near(b.thumb(18) + b.length(), 808));
CHECK(near(b.first_at(672), 9) && near(b.first_at(676), 9.5f));
CHECK(near(b.first_at(-1000), 0) && near(b.first_at(5000), 18)); // (held to the list's ends)
// (on the thumb, 672 to 736: held where the cursor is, and the press alone moves nothing)
CHECK(near(b.grab(700), 28) && near(b.drag(700, b.grab(700)), 9));
CHECK(near(b.grab(672), 0) && near(b.grab(735.5f), 63.5f));
CHECK(near(b.drag(716, 28), 11) && near(b.drag(684, 28), 7)); // (16 pixels down or up: two rows)
CHECK(near(b.drag(-50, 28), 0) && near(b.drag(3000, 28), 18));
// (off the thumb: its middle comes under the cursor)
CHECK(near(b.grab(650), 32) && near(b.grab(736), 32) && near(b.grab(671.9f), 32));
const float f = b.drag(650, b.grab(650));
CHECK(near(f, 2.25f) && near(b.thumb(f) + b.length() / 2, 650));
CHECK(near(b.drag(604, 32), 0) && near(b.drag(806, 32), 18)); // (near an end: the end)
// (a list that fits its view, or a track without a length: nowhere to scroll to)
Bar fits{3, 600, 808, 8, 8, 0, 0}, flat{3, 600, 600, 26, 8, 0, 0};
CHECK(!fits.scrolls() && fits.most() == 0 && fits.first_at(700) == 0 && fits.drag(700, 10) == 0);
CHECK(!flat.scrolls() && flat.first_at(700) == 0);
// (a long list of cards in pixels: the thumb under 7 pixels; taken hold of 16 either side of its middle, nothing moved)
Bar cards{101, 600, 808, 30000, 1000, 12000, 16};
CHECK(near(cards.thumb(12000), 683.2f) && cards.length() < 7);
const float mid = cards.thumb(12000) + cards.length() / 2;
CHECK(near(cards.drag(mid + 12, cards.grab(mid + 12)), 12000, 0.5f) && near(cards.drag(mid - 15, cards.grab(mid - 15)), 12000, 0.5f));
CHECK(near(cards.grab(mid + 20), cards.length() / 2)); // (further off: the thumb comes to the cursor)
CHECK(near(cards.drag(mid + 20, cards.grab(mid + 20)), 12000 + 20 * 30000 / 208.0f, 1));
}
// ---- the record: the bar as drawn, its box, what is drawn after it ----
{
menu_hit::Map m;
m.clear(0, 0, 2560, 1440);
m.add_bar(34, 82, Bar{2, 653, 861, 26, 8, 0, 16}, 8);
m.add(82, 690, 600, 760, menu_hit::kListLine, 7); // (a card whose left edge the bar's box reaches)
CHECK(m.bars == 1 && m.bar_of(2) && m.bar_of(2)->y1 == 861 && !m.bar_of(3));
menu_hit::Hit h = m.at(58, 700);
CHECK(h.part == menu_hit::kScroll && h.index == 2);
CHECK(m.at(34, 700).part == menu_hit::kScroll && m.at(81.5f, 700).part == menu_hit::kScroll); // (either side of the thin track)
CHECK(m.at(33, 700).part == menu_hit::kNone && m.at(82, 500).part == menu_hit::kNone);
CHECK(m.at(58, 646).part == menu_hit::kScroll && m.at(58, 868).part == menu_hit::kScroll); // (a little past its ends)
CHECK(m.at(58, 644).part == menu_hit::kNone && m.at(58, 870).part == menu_hit::kNone);
CHECK(m.at(82, 700).part == menu_hit::kListLine && m.at(81.5f, 700).part == menu_hit::kScroll); // (the card keeps its own)
m.add(40, 690, 70, 710, menu_hit::kButton, 1); // (drawn after it, over it: on top)
CHECK(m.at(58, 700).part == menu_hit::kButton && m.at(58, 720).part == menu_hit::kScroll);
// (no hit: a list that fits its view, a bar without a number; no more than kBars; gone with the next drawing)
const int boxes = m.n;
m.add_bar(34, 82, Bar{4, 653, 861, 8, 8, 0, 16}, 8);
m.add_bar(34, 82, Bar{-1, 653, 861, 26, 8, 0, 16}, 8);
CHECK(m.bars == 1 && m.n == boxes && !m.bar_of(4) && !m.bar_of(-1));
for (int i = 0; i < menu_hit::Map::kBars + 3; i++) m.add_bar(900, 940, Bar{10 + i, 100, 200, 26, 8, 0, 16}, 8);
CHECK(m.bars == menu_hit::Map::kBars && m.n == boxes + menu_hit::Map::kBars - 1);
m.clear(0, 0, 2560, 1440);
CHECK(m.bars == 0 && !m.bar_of(2) && m.at(58, 700).part == menu_hit::kNone);
}
// ---- a tab's rows: 26 of which 8 fit, the bar's track 653 to 861 (scroll_bar's own: 312 units about its list's middle) ----
const int slot = 2, n = 26;
ease_step = 0.25f; // (a quarter of the way a drawing, as at 60 a second)
CHECK(draw_rows(slot, n, 0) == 0);
CHECK(hits.bars == 1 && hits.bar_of(slot) && near(hits.bar_of(slot)->y0, 653) && near(hits.bar_of(slot)->y1, 861));
CHECK(near(thumb0, 653) && near(thumb1, 717));
for (float first : {0.0f, 3.0f, 5.5f, 18.0f}) { // (the bar recorded is the bar drawn: its thumb the picture's)
float t0 = 0, t1 = 0;
hits.clear(0, 0, 2560, 1440);
record_bar(ctx, kX, kTop, kBottom, n, 8, first, slot, &t0, &t1);
const Bar* b = hits.bar_of(slot);
CHECK(b && near(b->thumb(b->first), t0) && near(b->thumb(b->first) + b->length(), t1) && near(b->first, first));
CHECK(near(b->reach, 16));
}
{ // (taken hold of 36 units either side of its middle line, 24 pixels here, and 12 units past its ends)
CHECK(draw_rows(slot, n, 0) == 0);
CHECK(hits.at(kX - 24, 700).part == menu_hit::kScroll && hits.at(kX + 23.5f, 700).part == menu_hit::kScroll);
CHECK(hits.at(kX - 25, 700).part == menu_hit::kNone && hits.at(kX + 24, 700).part == menu_hit::kNone);
CHECK(hits.at(kX, 645).part == menu_hit::kScroll && hits.at(kX, 868.5f).part == menu_hit::kScroll);
CHECK(hits.at(kX, 644).part == menu_hit::kNone);
// (a list that fits: no bar to take; over the game's own list it is drawn whole, and still none to take)
float t0, t1;
hits.clear(0, 0, 2560, 1440);
ui::Ctx over{2, true};
record_bar(over, kX, kTop, kBottom, 1, 1, 0, slot, &t0, &t1);
CHECK(hits.bars == 0 && hits.at(kX, 700).part == menu_hit::kNone && near(t0, 653) && near(t1, 861));
}
// (the cursor on it: lit, and drawn again for that; off it: not)
CHECK(draw_rows(slot, n, 0) == 0);
CHECK(!tick(0, 0, 500, 240) && bar_hover == -1 && !redraw);
CHECK(!tick(0, 0, kX, 700) && bar_hover == slot && redraw && bar_held == -1);
CHECK(!tick(0, 0, kX, 701) && bar_hover == slot && !redraw);
CHECK(!tick(0, 0, 500, 240) && bar_hover == -1 && redraw);
// (a press on the thumb: held, and nothing moves)
CHECK(tick(1, 1, kX, 700) && bar_held == slot && bar_hover == slot && near(bar_grab, 47) && redraw);
CHECK(scroll_want[slot] == 0 && draw_rows(slot, n, 0) == 0);
CHECK(tick(1, 0, kX, 700) && !redraw); // (held still: nothing to draw again)
// (40 pixels down: 5 rows, at once though the easing is a quarter a drawing; 4 more: between two rows)
CHECK(tick(1, 0, kX, 740) && redraw && near(draw_rows(slot, n, 0), 5) && near(thumb0, 693));
CHECK(tick(1, 0, kX, 744) && near(draw_rows(slot, n, 0), 5.5f) && near(thumb0, 697));
CHECK(scrolled_to[slot] == 0); // (the selection: not moved, not asked into view)
// (the cursor far off the bar, over a row, off the menu: still held, to the list's end and no further)
CHECK(hits.at(700, 240).part == menu_hit::kRow);
CHECK(tick(1, 0, 700, 240) && near(draw_rows(slot, n, 0), 0));
CHECK(tick(1, 0, 5000, 5000) && near(draw_rows(slot, n, 0), 18) && near(thumb1, 861));
CHECK(tick(1, 0, kX, 744) && near(draw_rows(slot, n, 0), 5.5f));
// (let go: whole rows, eased there; the bar still lit under the cursor)
CHECK(!tick(0, 0, kX, 744) && bar_held == -1 && bar_hover == slot && redraw);
float at = draw_rows(slot, n, 0);
CHECK(at > 5.5f && at < 6 && scroll_want[slot] == 6);
ease_step = 1;
CHECK(draw_rows(slot, n, 0) == 6);
// (the selection is where it was, out of view above; Down then brings the next row into view, with its row of context)
CHECK(draw_rows(slot, n, 1) == 0);
{ // (...which is what the wheel does: six notches from the same place, then Down)
const int other = 4;
CHECK(draw_rows(other, n, 0) == 0 && draw_rows(other, n, 0) == 0);
wheel_rows[other] -= 6;
CHECK(draw_rows(other, n, 0) == 6 && draw_rows(other, n, 1) == 0);
}
// (the selection moved by the keys while the bar is held: the rows stay with the cursor, and it comes into view after)
CHECK(draw_rows(slot, n, 1) == 0);
CHECK(tick(1, 1, kX, 700) && tick(1, 0, kX, 780) && near(draw_rows(slot, n, 1), 10));
CHECK(near(draw_rows(slot, n, 20), 10) && tick(1, 0, kX, 781) && near(draw_rows(slot, n, 20), 10.125f));
CHECK(!tick(0, 0, kX, 781) && draw_rows(slot, n, 20) == 14); // (20 and its row of context: 14 to 21 in view)
// ---- a press on the track off the thumb: the thumb's middle under the cursor, the rows with it; held the same way ----
CHECK(draw_rows(slot, n, 0) == 0 && near(thumb1, 717));
CHECK(tick(1, 1, kX, 801) && bar_held == slot && near(bar_grab, 32));
CHECK(near(draw_rows(slot, n, 0), 14.5f) && near((thumb0 + thumb1) / 2, 801));
CHECK(tick(1, 0, kX, 793) && near(draw_rows(slot, n, 0), 13.5f)); // (and drawn along from there)
CHECK(!tick(0, 0, kX, 793) && draw_rows(slot, n, 0) == 14);
CHECK(tick(1, 1, kX, 660) && near(draw_rows(slot, n, 0), 0)); // (above it, near the track's top: the list's top)
CHECK(!tick(0, 0, kX, 660) && draw_rows(slot, n, 0) == 0);
CHECK(tick(1, 1, kX, 866) && near(draw_rows(slot, n, 0), 18)); // (just past the track's foot: the list's end)
CHECK(!tick(0, 0, kX, 866) && draw_rows(slot, n, 0) == 18);
// (a click shorter than a tick, pressed and let go between two reads: the list goes there all the same)
CHECK(tick(0, 1, kX, 757) && bar_held == slot);
CHECK(near(draw_rows(slot, n, 0), 9)); // (the track's middle: the list's)
CHECK(!tick(0, 0, kX, 757) && bar_held == -1 && draw_rows(slot, n, 0) == 9);
// (a press off the bar takes nothing; nor the right button on it)
CHECK(!tick(1, 1, 700, 240) && bar_held == -1 && draw_rows(slot, n, 0) == 9);
CHECK(!tick(2, 2, kX, 700) && bar_held == -1 && draw_rows(slot, n, 0) == 9);
// (held, and its list no longer drawn, another tab's in its place: let go, the other not moved)
CHECK(tick(1, 1, kX, 700) && bar_held == slot);
scroll_want[5] = scroll_at[5] = 0;
CHECK(draw_rows(5, n, 0) == 0);
CHECK(!tick(1, 0, kX, 800) && bar_held == -1 && draw_rows(5, n, 0) == 0);
CHECK(!tick(1, 0, kX, 800) && bar_held == -1); // (the button still down from before: no press of this bar)
// ---- the cards' lists, in pixels: at once, and the cards no longer follow the choice, as after the wheel ----
{
float t0, t1;
auto draw = [&](int id, float total, float view, float at) {
hits.clear(0, 0, 2560, 1440);
record_bar(ctx, kX, kTop, kBottom, (int)total, (int)view, at, id, &t0, &t1);
};
CHECK(!tick(0, 0, 500, 240));
const float rows_want = scroll_want[slot], other_want = scroll_want[5];
draw(kBarTeleport, 3000, 1000, 0); // (thumb 653 to 722.3)
CHECK(hits.at(kX, 700).part == menu_hit::kScroll && hits.at(kX, 700).index == kBarTeleport);
CHECK(tick(1, 1, kX, 700) && bar_held == kBarTeleport && teleport_scroll_px == 0 && !teleport_follow);
CHECK(tick(1, 0, kX, 752) && near(teleport_scroll_px, 750, 0.01f) && teleport_want_px == teleport_scroll_px);
draw(kBarTeleport, 3000, 1000, teleport_scroll_px);
CHECK(near(t0, 705));
CHECK(tick(1, 0, kX, 2000) && near(teleport_scroll_px, 2000, 0.01f));
CHECK(!tick(0, 0, kX, 2000) && near(teleport_scroll_px, 2000, 0.01f));
CHECK(scroll_want[slot] == rows_want && scroll_want[5] == other_want); // (no rows' list touched)
draw(kBarMods, 30000, 1000, 0);
float d0, d1;
record_bar(ctx, 2400, 900, 1300, 2000, 400, 0, kBarModsDesc, &d0, &d1); // (the Mods screen's second: the description's)
CHECK(hits.bars == 2 && hits.at(kX, 757).index == kBarMods && hits.at(2400, 1100).index == kBarModsDesc);
CHECK(tick(1, 1, kX, 757) && bar_held == kBarMods && !mods_follow && near(mods_scroll_px, 14500, 1) && mods_want_px == mods_scroll_px);
CHECK(mods_desc_px == 0 && !tick(0, 0, kX, 757));
CHECK(tick(1, 1, 2400, 1150) && bar_held == kBarModsDesc && mods_desc_px > 0 && near(mods_scroll_px, 14500, 1));
CHECK(!tick(0, 0, 2400, 1150) && bar_held == -1);
}
// ---- no sound: nothing the sounds are told of changes by it, as with the wheel; and it is not a row's slider drawn along ----
{
menu_sound::State s;
s.open = true, s.tab = 2, s.cursor = 3, s.value = 50;
menu_sound::Input press, hold, none;
press.click = true;
CHECK(menu_sound::sound_of(s, s, press) == menu_sound::kNone);
CHECK(menu_sound::sound_of(s, s, hold) == menu_sound::kNone && menu_sound::sound_of(s, s, none) == menu_sound::kNone);
}
std::printf("PASS: the page slider: the bar drawn is the bar taken, held and drawn along, its track clicked\n");
return 0;
}
'''
def fixture(menu):
state = re.search(r"constexpr int kBarTeleport = [^\n]*\nint bar_held = -1;[^\n]*\nfloat bar_grab = 0;[^\n]*\nint bar_hover = -1;[^\n]*\n", menu)
check(state, "the page sliders' state (kBarTeleport, bar_held, bar_grab, bar_hover) is not where the check cuts it")
bar = block(menu, "void scroll_bar(")
record = between(bar, " const float mid = ", " const bool live")
check("hits.add_bar(" in record and "const float y0 = " in record and "const menu_hit::Bar bar{id, " in record,
"scroll_bar does not record the bar from the numbers it draws the thumb with")
parts = {"@ROOT@": ROOT.as_posix(), "@STATE@": state.group(0), "@SCROLL_ROWS@": block(menu, "float scroll_rows("),
"@BAR_SCROLL@": block(menu, "void bar_scroll("), "@BAR_MOUSE@": block(menu, "bool bar_mouse("), "@BAR_RECORD@": record}
text = FIXTURE
for mark, part in parts.items():
text = text.replace(mark, part)
return text
def sources(menu):
hit = (ROOT / "gpu" / "vk" / "vk_menu_hit.h").read_text(encoding="utf-8")
check("#include" not in hit, "vk_menu_hit.h includes something: it is plain arithmetic, and this check compiles it alone")
# (every scroll bar drawn has its list's number: one drawn without is a bar the mouse cannot take)
calls = re.findall(r"^[^/\n]*\bscroll_bar\(c, [^;]*\);", menu, re.M)
calls = [c for c in calls if not c.lstrip().startswith("void ")]
numbers = [re.search(r", (\w+)\);$", c).group(1) for c in calls]
# ((Triforce, 11-26) and the Debug tab's paged pages': the Inventory's, a name page's (and its empty page's, still)
check(sorted(numbers) == ["cur_tab", "kBarInventory", "kBarMods", "kBarModsDesc", "kBarNames", "kBarNames", "kBarTeleport", "kControlsSlot"],
"the scroll bars drawn and their lists' numbers: %s" % numbers)
check("scroll_rows(cur_tab, listed, sel_at, top, bottom, pitch, &shown)" in menu and
"scroll_rows(kControlsSlot, n, csel, top, bottom, pitch, &shown)" in menu,
"a rows' list's bar no longer has the number of its slot of scroll_at")
bar = block(menu, "void scroll_bar(")
check("live && id == bar_held ?" in bar and "live && id == bar_hover ?" in bar and bar.count("lit") >= 3,
"the bar under the cursor, or held, is not drawn brighter")
# (a rows' list while its bar is held: where the cursor has it; the wheel's lines as they were)
rows = block(menu, "float scroll_rows(")
check("else if (bar_held == slot) {" in rows and "return at = want;" in rows, "scroll_rows eases or rounds a list whose bar is held")
check("want -= (float)wheel;" in rows and "want = std::round(std::clamp(want, 0.0f, (float)(n - fit)));" in rows,
"scroll_rows: the wheel's and the selection's scrolling changed")
# (each page that draws one: bar_mouse first, and while it holds one the rest of the mouse is nothing's)
tick = menu[menu.index("void menu_tick() {"):]
check("if (drag_row < 0 && bar_mouse(ptr, my, hit, changed)) hit = menu_hit::Hit{}, ptr.wheel = 0;" in tick,
"the tabs' rows do not give the mouse to their page slider (or give it while a row's slider is held)")
check(tick.index("bar_mouse(ptr, my, hit, changed)) hit = menu_hit::Hit{}, ptr.wheel = 0;\n const int ht =") <
tick.index("} else if (on_row && (moved || ptr.pressed) && hit.index != sel) {"),
"the tabs' rows: a row is chosen under the cursor before the page slider has the mouse")
controls = between(tick, "} else if (open_now.load() && page == 1) {", "} else if (open_now.load() && page == 4) {",
unique=False)
check("if (bar_mouse(ptr, my, hit, changed)) hit = menu_hit::Hit{}, ptr.wheel = 0;\n const bool option =" in controls,
"the Controls page does not give the mouse to its page slider first")
teleport = block(menu, "void teleport_mouse(")
check("const bool bar = bar_mouse(ptr, my, hit, changed);\n if (bar) hit = menu_hit::Hit{};" in teleport and
"if (ptr.wheel && !bar) teleport_wheel += ptr.wheel" in teleport, "the teleport list does not give the mouse to its page slider first")
mods = block(menu, "void mods_tick(")
check("const bool bar = !dialog && !mods_kbd && bar_mouse(ptr, my, hit, changed);\n if (bar) hit = menu_hit::Hit{};" in mods and
"if (ptr.wheel && !bar) (mx >= mods_desc_x0 ? mods_desc_wheel : mods_wheel) += ptr.wheel" in mods,
"the Mods screen does not give the mouse to its page sliders first, or gives it under a dialog")
# ((Triforce, 11-26) the Inventory and the name pages' sliders, a page a step, take the mouse first as the teleport list's)
for head in ("void inventory_mouse(", "void names_mouse("):
page = block(menu, head)
check("const bool bar = bar_mouse(ptr, my, hit, changed);\n if (bar) hit = menu_hit::Hit{};" in page and "if (ptr.wheel && !bar)" in page,
head + " does not give the mouse to its page slider first")
bars = block(menu, "void bar_scroll(")
check("else if (id == kBarInventory) inventory_page = std::max(0, (int)std::lround(first));" in bars and
"else if (id == kBarNames) names_slider_to(std::max(0, (int)std::lround(first)));" in bars,
"a paged page's slider does not turn its pages")
check(menu.count("bar_mouse(ptr, my, hit, changed)") == 6, "a page's bar_mouse added or gone: this check names six")
# (let go with the button wherever the menu is by then, and when it shuts)
check("if (bar_held >= 0 && !(ptr.held & HOS_MOUSE_LEFT)) bar_held = -1, changed = true;" in tick,
"a page slider held is not let go with the button on every page")
check(tick.index("if (bar_held >= 0 && !(ptr.held & HOS_MOUSE_LEFT)) bar_held = -1") < tick.index("if (reshade_menu::comparing()) {"),
"a page slider is let go only after the pages have had the tick")
shut = between(tick, "if (!now_open) {", "if (now_open != told && app_window()) {")
check("bar_held = bar_hover = -1;" in shut, "a page slider held as the menu shuts stays held")
# (not a sound: the sounds' input is told of a row's slider alone, and their state has no list's place in it)
check("in.click = (ptr.pressed & HOS_MOUSE_LEFT) != 0, in.drag = drag_row >= 0;" in tick, "the sounds are told of the page slider's hold")
state = block(menu, "static menu_sound::State sound_state() {")
check(not re.search(r"scroll|bar_held|bar_hover", state), "a list's place is part of what the sounds are told of")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cxx", default="g++")
args = parser.parse_args()
menu = MENU.read_text(encoding="utf-8")
sources(menu)
with tempfile.TemporaryDirectory(prefix="menu-page-slider-") as tmp:
src, exe = Path(tmp) / "fixture.cpp", Path(tmp) / "fixture"
src.write_text(fixture(menu), encoding="utf-8")
subprocess.run([args.cxx, "-std=c++20", "-Wall", "-Wextra", "-Werror", str(src), "-o", str(exe)], check=True)
subprocess.run([str(exe)], check=True)
print("PASS: the options' page slider under the mouse")
if __name__ == "__main__":
main()

View File

@@ -79,10 +79,10 @@ def function(source, start):
def sources():
menu = (ROOT / "gpu" / "vk" / "vk_menu.cpp").read_text(encoding="utf-8")
# ((Triforce, options_version 7) the handheld profile is an Output resolution; the merged rows take a restart for what of
# them is read at the start: restart_value_of)
# them is read at the start: restart_value_of. ((11-26) Frame pacing's Steady changes at once now, and the Upscaler, the
# Render resolution and Upscale before bloom are taken at Apply: tests/test_menu_apply.py)
for row in ('"GPU device", &opts.gpu_device', '"Output resolution", &opts.output_res', '"Aspect ratio", &opts.ultrawide',
'"Robust buffers", &opts.robust', '"HDR", &merged.hdr', '"Frame generation", &merged.framegen',
'"Frame pacing", &merged.pacing'):
'"Robust buffers", &opts.robust', '"HDR", &merged.hdr', '"Frame generation", &merged.framegen'):
at = menu.find(row)
if at < 0:
raise SystemExit("vk_menu.cpp: a row that takes a restart is missing: " + row)

View File

@@ -14,6 +14,12 @@ own (menu_sound.c's state is the process's):
- frames: the sounds the options asked for, in the next block, in order, at the row's level; nothing read or played
with the row at 0 or without a renderer
- master: the sounds in the front left and right, under the Master volume, the block held at the 16 bits' ends
- roles, roles-long ((Triforce, 11-25) the owner: "They should be using the title screen's SFX instead of the in-game Menu
SFX"): the settings' tabs, the Mods screen and the step back to the pause menu's System list have a sound each, the
system menu's cursor, small decide and cancel; the variable of the environment that names another for each (a sound's
bare name alone; one that is not a name, not in the game's files or not a sound leaves the role its own, said in the
log); a file two sounds name is read once. In voices: their ticks are ticks, and a direction held with a tick of
1.6 s takes the oldest tick's voice, never a longer sound's
The source is read too: render_frame adds the sounds after the game's limiter and before the Master volume; the file
reader goes through the mods' table; the two option ids are 135 and 136 (tests/test_menu_sound_events.py has the
@@ -30,7 +36,7 @@ import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SCENARIOS = ("decode", "voices", "load", "frames", "master")
SCENARIOS = ("decode", "voices", "load", "frames", "master", "roles", "roles-long")
def check(cond, what):
@@ -64,6 +70,14 @@ def main():
"hos_fs_rom_file does not look in the mods' table first, or takes any path")
check("hos_fs_rom_file(files[id], FILE_MOST, &size)" in sound and "CreateThread(NULL, 0, load_main" in sound,
"menu_sound.c does not read the files through nn_fs.c on a thread of its own")
# ((Triforce, 11-25) the roles' sounds from the environment: read where the files are, a name held to the sounds' folder)
check("const char *name = MENU_SOUND_ENV(roles[k].env);" in sound and "#define MENU_SOUND_ENV(name) getenv(name)" in sound and
"if (!role_name_ok(name)) {" in sound and
'snprintf(role_files[k], sizeof role_files[k], "Sound/Resource/Stream/%s.bwav", name);' in sound,
"menu_sound.c does not read a role's sound from the environment as a bare name of the sounds' folder")
load = sound[sound.index("static void load_all(void) {"):]
check(load.index("roles_from_env();") < load.index("load_sound(id)") < load.index("atomic_store_explicit(&loaded, 2"),
"the environment's sounds are not set before the files are read")
check(re.search(r"enum \{ HOS_OPT_MENU_SOUND = 135, HOS_OPT_MENU_SOUND_VOLUME \};", api),
"vk_api.h's options for the sounds are not 135 and 136")
for i in range(135, 140):

View File

@@ -15,6 +15,11 @@ ear, as the Motion page is (its row and its Back take their press for themselves
Copy Faithful and Reset to defaults a decide. Read in vk_menu.cpp: sound_state gives it its own page, and those two rows keep
their press for the sound.)
((Triforce, 11-25) the owner: "The SFX are incorrect. They should be using the title screen's SFX instead of the in-game Menu
SFX." sound_of names the cursor, decide and cancel as before; sound_for says whose it is, the settings' tabs' or the Mods
screen's (or the pause menu's System list's, a step back onto it), a sound each, and menu_tick asks for that one.
tests/test_menu_sound_roles.py has the Mods screen's own calls and the files.)
python -I -B tests/test_menu_sound_events.py [--cxx g++]
"""
import argparse
@@ -163,6 +168,43 @@ int main() {
CHECK(sound_of(on_page(rows(2, 0), 5), closed(), In().confirm_()) == kDecide);
std::puts("sound_of: NX2navi's mapping, the game's own Options screen, the pages and modes");
/* ((Triforce, 11-25) whose sound: the cursor, decide and cancel sound_of names are the settings' tabs' own, or the Mods
screen's when the tick found it shown; its cancel onto the pause menu's System list is that list's step back. The
others, and none, as they are; none of the seven is one sound_of names by itself */
CHECK(sound_for(kCursor, false, false) == kSettingsNavigate && sound_for(kDecide, false, false) == kSettingsSelect);
CHECK(sound_for(kCancel, false, false) == kSettingsBack && sound_for(kCancel, false, true) == kSettingsBack);
CHECK(sound_for(kCursor, true, false) == kModsNavigate && sound_for(kDecide, true, false) == kModsSelect);
CHECK(sound_for(kCancel, true, false) == kModsBack && sound_for(kCancel, true, true) == kPauseBack);
CHECK(sound_for(kCursor, true, true) == kModsNavigate && sound_for(kDecide, true, true) == kModsSelect);
for (int s : {kNone, kOpen, kClose, kTabLeft, kTabRight, kFanfare, kSysCursor, kSysDecide})
CHECK(sound_for(s, false, false) == s && sound_for(s, true, false) == s && sound_for(s, true, true) == s);
CHECK(sound_for(sound_of(rows(1, 2), rows(1, 3), In().move_()), false, false) == kSettingsNavigate);
CHECK(sound_for(sound_of(rows(1, 2, 0), rows(1, 2, 1), In().confirm_()), false, false) == kSettingsSelect);
CHECK(sound_for(sound_of(on_page(rows(3, 4), 1, 6), rows(3, 4), In().back_()), false, false) == kSettingsBack);
/* (the Mods screen, page 8: A on a card; Back onto the entries under the game's list, page 9, the pause menu's or the title's) */
CHECK(sound_for(sound_of(on_page(rows(4, 0), 8), on_page(rows(4, 0), 8), In().confirm_()), true, false) == kModsSelect);
CHECK(sound_for(sound_of(on_page(rows(4, 0), 8), on_page(rows(4, 0), 9), In().back_()), true, true) == kPauseBack);
CHECK(sound_for(sound_of(on_page(rows(4, 0), 8), on_page(rows(4, 0), 9), In().back_()), true, false) == kModsBack);
CHECK(sound_for(sound_of(rows(2, 3), closed(), In().toggle_()), false, false) == kClose);
CHECK(sound_for(sound_of(rows(1, 0), rows(2, 0), In().tr()), false, false) == kTabRight);
CHECK(kSettingsNavigate == kSysDecide + 1 && kSettingsSelect == kSettingsNavigate + 1 && kSettingsBack == kSettingsSelect + 1);
CHECK(kModsNavigate == kSettingsBack + 1 && kModsSelect == kModsNavigate + 1 && kModsBack == kModsSelect + 1);
CHECK(kPauseBack == kModsBack + 1 && kSettingsOn == kPauseBack + 1 && kSettingsOff == kSettingsOn + 1 && kLast == kSettingsOff);
{ /* ((Triforce, 11-25) a toggle switched: On or Off by its value now; a row that is no toggle, another row, or no change
keeps the sound it had; the Mods screen's and the other sounds as they are */
State off = rows(1, 2, 0), on = rows(1, 2, 1);
off.toggle = on.toggle = true;
CHECK(toggle_sound(sound_for(sound_of(off, on, In().confirm_()), false, false), off, on) == kSettingsOn);
CHECK(toggle_sound(sound_for(sound_of(on, off, In().confirm_()), false, false), on, off) == kSettingsOff);
CHECK(toggle_sound(sound_for(sound_of(off, on, In().r()), false, false), off, on) == kSettingsOn);
CHECK(toggle_sound(kSettingsSelect, off, off) == kSettingsSelect && toggle_sound(kSettingsNavigate, off, rows(1, 3, 1)) == kSettingsNavigate);
State plain_b = rows(1, 2, 0), plain_a = rows(1, 2, 1);
CHECK(toggle_sound(kSettingsSelect, plain_b, plain_a) == kSettingsSelect);
CHECK(toggle_sound(kModsSelect, off, on) == kModsSelect && toggle_sound(kSettingsBack, off, on) == kSettingsBack);
CHECK(toggle_sound(kTabRight, off, on) == kTabRight);
}
std::puts("sound_for: the settings' tabs', the Mods screen's, the pause menu's step back");
/* the queue: one of the sounds (1 to kLast), in order; 16 wait, a 17th is dropped; a stale one is not played */
Queue q;
CHECK(!q.put(kNone, 0) && !q.put(-1, 0) && !q.put(kLast + 1, 0) && q.take(0) == kNone);
@@ -172,9 +214,14 @@ int main() {
CHECK(q.take(2000) == kNone);
/* ((Triforce) 11-19) the Mods entry's and screen's own: the system menu's cursor and decide, and the fanfare, are queued
and taken as the others are (they were dropped: the entry under the title's list made no sound) */
CHECK(kFanfare == kTabRight + 1 && kSysCursor == kFanfare + 1 && kSysDecide == kSysCursor + 1 && kLast == kSysDecide);
CHECK(kFanfare == kTabRight + 1 && kSysCursor == kFanfare + 1 && kSysDecide == kSysCursor + 1 && kLast > kSysDecide);
CHECK(q.put(kSysCursor, 1000) && q.put(kSysDecide, 1000) && q.put(kFanfare, 1000));
CHECK(q.take(1000) == kSysCursor && q.take(1000) == kSysDecide && q.take(1000) == kFanfare);
/* ((Triforce, 11-25) and the nine that say whose sound it is (a toggle's On and Off the last two), the last of them the
queue's last */
for (int s = kSettingsNavigate; s <= kSettingsOff; s++) CHECK(q.put(s, 1000));
for (int s = kSettingsNavigate; s <= kSettingsOff; s++) CHECK(q.take(1000) == s);
CHECK(!q.put(kSettingsOff + 1, 1000));
CHECK(q.take(2000) == kNone);
CHECK(q.put(kCursor, 0) && q.put(kDecide, kStaleNs) && q.put(kCancel, kStaleNs + 10));
CHECK(q.take(kStaleNs + 1) == kDecide); /* (the cursor a quarter second and more ago: dropped) */
@@ -268,7 +315,16 @@ def main():
tick = block(menu, "void menu_tick() {")
before = tick.index("const menu_sound::State sound_before = sound_state();")
check(before < tick.index("bool press[K_N] = {};"), "menu_tick does not take the options' state before its input")
put = tick.index("if (opts.menu_sounds > 0) sound_queue.put(menu_sound::sound_of(sound_before, sound_state(), in), prof_now());")
# ((Triforce, 11-25) whose sound it is: sound_for over sound_of's, the Mods screen's when the tick found it shown, its Back
# onto the pause menu's System list that list's)
# ((Triforce, 11-25) and a toggle switched: its On or its Off, toggle_sound over it)
put = tick.index("if (opts.menu_sounds > 0) sound_queue.put(menu_sound::toggle_sound(sound, sound_before, after), prof_now());")
check(tick.index("const int sound = menu_sound::sound_for(menu_sound::sound_of(sound_before, after, in), on_mods, to_pause);") < put,
"menu_tick does not name the sound before it asks for it")
check("const bool on_mods = sound_before.page == kModsPage;" in tick and
"const bool to_pause = after.open && after.page == kModsRowPage && mods_back_sound() == HOS_MENU_SOUND_PAUSE_BACK;" in tick and
tick.index("const bool on_mods = sound_before.page == kModsPage;") < put,
"menu_tick does not say whose cursor, decide and cancel it asks for (the settings' tabs', the Mods screen's, the pause menu's)")
check(tick.index("else if (press[7] && share_row(r)) share_press(") < put < tick.index("names_tick();"),
"the sound is not told after the tick's input (and with the Menu sounds row above 0 alone)")
check(tick.count("sound_queue.put(") == 1, "menu_tick puts a sound in more than one place")
@@ -281,6 +337,10 @@ def main():
check("menu_sound::kSysCursor == HOS_MENU_SOUND_SYS_CURSOR" in menu and "menu_sound::kSysDecide == HOS_MENU_SOUND_SYS_DECIDE" in menu
and "menu_sound::kFanfare == HOS_MENU_SOUND_FANFARE" in menu and "menu_sound::kLast + 1 == HOS_MENU_SOUND_N" in menu,
"vk_menu.cpp does not hold the Mods entry's sounds (the fanfare, the system menu's cursor and decide) against vk_api.h's")
for ours, theirs in (("kSettingsNavigate", "SETTINGS_NAVIGATE"), ("kSettingsSelect", "SETTINGS_SELECT"), ("kSettingsBack", "SETTINGS_BACK"),
("kModsNavigate", "MODS_NAVIGATE"), ("kModsSelect", "MODS_SELECT"), ("kModsBack", "MODS_BACK"),
("kPauseBack", "PAUSE_BACK")): # ((Triforce, 11-25) whose sound it is)
check("menu_sound::%s == HOS_MENU_SOUND_%s" % (ours, theirs) in menu, "vk_menu.cpp does not hold %s against vk_api.h's" % ours)
# ((Triforce, 11-22, N64 Classic) the Remembered page: its own page to the ear, and its two actions' press kept for the sound
check("constexpr int kSoundPageN64 = 10;" in menu, "vk_menu.cpp: the Remembered page has no page of its own to the ear (10)")
state = block(menu, "static menu_sound::State sound_state() {")

View File

@@ -0,0 +1,209 @@
"""Whose sound: the settings' tabs, the Mods screen and the step back to the pause menu's System list have a sound each
(the owner: "The SFX are incorrect. They should be using the title screen's SFX instead of the in-game Menu SFX."), the
system menu's cursor, small decide and cancel unless the environment names another for one of the seven:
HOS_MENU_SOUND_SETTINGS_NAVIGATE, _SETTINGS_SELECT, _SETTINGS_BACK the Triforce settings tabs
HOS_MENU_SOUND_MODS_NAVIGATE, _MODS_SELECT, _MODS_BACK the Mods screen
HOS_MENU_SOUND_PAUSE_BACK Back out of the Mods screen onto the pause menu's
System list, Cancel and B on Quit's dialog
Read in the source: the seven are sounds of their own in vk_api.h, after the system menu's two; host/menu_sound.c has a
file and a variable of the same name for each; the Mods screen's input (vk_menu.cpp mods_tick) asks for the Mods screen's
three and never for the in-game menu's cursor, decide and cancel, which nothing in vk_menu.cpp asks for any more; Quit's
dialog and the step back out of the Mods screen onto the pause menu's list ask for the pause menu's; docs/development.md
has the variables' row.
Compiled and run: triforce_env.txt takes the seven names with a sound's bare name (host/hos_main.c env_line_allowed, cut
out as it is, with menu_sound.c's own name check): every value the game takes for a role can be written there, and no
value that names a folder or a path is one the game takes.
tests/menu_sound_test.c (tests/test_menu_sound.py, "roles" and "voices") has the host's side run: the files, the
environment's word, the ticks; tests/test_menu_sound_events.py has sound_for and the queue.
python -I -B tests/test_menu_sound_roles.py [--cc gcc]
"""
import argparse
import re
import subprocess
import sys
import tempfile
from pathlib import Path
RUN_ALL_ARGS = ["--cc", "gcc"]
ROOT = Path(__file__).resolve().parents[1]
ROLES = ("SETTINGS_NAVIGATE", "SETTINGS_SELECT", "SETTINGS_BACK", "MODS_NAVIGATE", "MODS_SELECT", "MODS_BACK", "PAUSE_BACK",
"SETTINGS_ON", "SETTINGS_OFF") # ((Triforce, 11-25) a toggle switched On, Off)
OWN = {"NAVIGATE": "SE_Sys_SysMenu_Cursor00", "SELECT": "SE_Sys_SysMenu_DecideS00", "BACK": "SE_Sys_SysMenu_Cansel00",
"SETTINGS_SELECT": "SE_Sys_SysMenu_DecideL00", "SETTINGS_ON": "SE_Sys_SysMenu_DecideS00", "SETTINGS_OFF": "SE_Sys_SysMenu_Cansel00"} # (the owner's pick: the settings' Select is the title's Continue's)
own_of = lambda role: OWN.get(role) or OWN[role.split("_")[1]]
IN_GAME = ("HOS_MENU_SOUND_CURSOR", "HOS_MENU_SOUND_DECIDE", "HOS_MENU_SOUND_CANCEL")
def check(cond, what):
if not cond:
raise SystemExit("FAIL: " + what)
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]
PROGRAM = r'''#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CHECK(x) do { if (!(x)) { fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); exit(1); } } while (0)
@MOST@
@NAME_OK@
@ALLOWED@
static const char *const names[] = {@NAMES@};
/* (a sound's name, and what is not one) */
static const char *const values[] = {
"SE_Sys_Cursor00", "SE_Sys_Do00", "SE_Sys_Cancel00", "SE_Sys_SysMenu_Cursor00", "SE_Sys_SysMenu_DecideS00", "SE_Sys_SysMenu_DecideL00",
"SE_Sys_SysMenu_Cansel00", "SE_Sys_SysMenu_Error00", "BGM_ItemGet_Medium", "a", "_", "0", "1", "Z9_z",
"@A64@", /* (64 characters) */
"@A64@a", /* (65) */
"", ".", "..", "~", "~user", "SE_Sys_Cursor00.bwav", "../SE_Sys_Cursor00", "..\\SE_Sys_Cursor00", "Stream/SE_Sys_Cursor00",
"/SE_Sys_Cursor00", "\\SE_Sys_Cursor00", "C:SE_Sys_Cursor00", "C:\\Games\\x", "//server/share", "SE Sys", "SE-Sys", "a.b", "a,b", "a*",
"%s%n", "caf\xc3\xa9"};
int main(void) {
int taken = 0;
CHECK(sizeof names / sizeof *names == 9);
for (size_t n = 0; n < sizeof names / sizeof *names; n++) {
const size_t len = strlen(names[n]);
/* (not one of the names the file leaves out: a file's or a folder's, whatever its value) */
CHECK(strcmp(names[n] + len - 5, "_FILE") && strcmp(names[n] + len - 4, "_DIR") && !strncmp(names[n], "HOS_MENU_SOUND_", 15));
for (size_t v = 0; v < sizeof values / sizeof *values; v++) {
const int ok = role_name_ok(values[v]);
/* every name the game takes for a role can be written in triforce_env.txt */
if (ok && !env_line_allowed(names[n], values[v])) { fprintf(stderr, "%s=%s is left out of the file\n", names[n], values[v]); return 1; }
/* and nothing with a folder in it, a drive, a dot or a home is a name */
if (ok && (strpbrk(values[v], "/\\:.~") || !*values[v] || strlen(values[v]) > 64)) { fprintf(stderr, "%s is taken as a name\n", values[v]); return 1; }
taken += ok;
}
CHECK(env_line_allowed(names[n], "SE_Sys_Cursor00") && !env_line_allowed(names[n], "../SE_Sys_Cursor00") &&
!env_line_allowed(names[n], "C:\\Games\\x") && !env_line_allowed(names[n], "Stream/SE_Sys_Cursor00"));
}
CHECK(taken == 9 * 15); /* (the fourteen names and the one of 64; none of the rest) */
CHECK(role_name_ok(values[14]) && strlen(values[14]) == 64 && !role_name_ok(values[15]) && strlen(values[15]) == 65);
puts("triforce_env.txt takes the nine variables with a sound's bare name; a path is never a name");
return 0;
}
'''
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--cc", default="gcc")
a = p.parse_args()
api = (ROOT / "gpu" / "vk" / "vk_api.h").read_text(encoding="utf-8")
menu = (ROOT / "gpu" / "vk" / "vk_menu.cpp").read_text(encoding="utf-8")
sound = (ROOT / "host" / "menu_sound.c").read_text(encoding="utf-8")
main_c = (ROOT / "host" / "hos_main.c").read_text(encoding="utf-8")
guide = (ROOT / "docs" / "development.md").read_text(encoding="utf-8")
# the seven: sounds of their own, after the system menu's two and before the count
enum = block(api, "enum { HOS_MENU_SOUND_OPEN = 1")
ids = re.findall(r"\bHOS_MENU_SOUND_\w+", re.sub(r"/\*.*?\*/", "", enum, flags=re.S))
check(ids[-10:] == ["HOS_MENU_SOUND_" + r for r in ROLES] + ["HOS_MENU_SOUND_N"] and ids[-11] == "HOS_MENU_SOUND_SYS_DECIDE" and
len(ids) == len(set(ids)) == 20, "vk_api.h: the seven sounds are not the last, after the system menu's decide: %s" % ids)
# each with its own file, the system menu's, and the variable of its own name
for r in ROLES:
check(' [HOS_MENU_SOUND_%s] = "Sound/Resource/Stream/%s.bwav",\n' % (r, own_of(r)) in sound,
"host/menu_sound.c: HOS_MENU_SOUND_%s is not the system menu's %s" % (r, own_of(r)))
check(' {HOS_MENU_SOUND_%s, "HOS_MENU_SOUND_%s"},\n' % (r, r) in sound, "host/menu_sound.c: no variable for HOS_MENU_SOUND_%s" % r)
# (the array's own braces, not the struct's: block() would stop at "{ int id; const char *env; }")
table = sound[sound.index("static const struct { int id; const char *env; } roles[] = {"):]
table = table[:table.index("\n};\n")]
check(re.findall(r'"(HOS_\w+)"', table) == ["HOS_MENU_SOUND_" + r for r in ROLES], "host/menu_sound.c: the roles are not the seven, in the sounds' order")
for was, name in zip(IN_GAME, ("SE_Sys_Cursor00", "SE_Sys_Do00", "SE_Sys_Cancel00")): # (the in-game menu's stay what they were)
check(' [%s] = "Sound/Resource/Stream/%s.bwav",\n' % (was, name) in sound, "host/menu_sound.c: %s is no longer %s" % (was, name))
# the Mods screen's input: its own three, the fanfare and the categories' moves; never the in-game menu's or the settings'
tick = block(menu, "void mods_tick(bool* press, bool tab_left, bool tab_right, bool mouse, bool moved, const MkwVkPointer& ptr, int mx, int my, bool& changed) {")
asked = re.findall(r"mods_sound\(([^;]*)\);", tick)
check(len(asked) >= 20, "mods_tick: the Mods screen's sounds are not asked for where they were (%d)" % len(asked))
allowed = {"HOS_MENU_SOUND_MODS_NAVIGATE", "HOS_MENU_SOUND_MODS_SELECT", "HOS_MENU_SOUND_MODS_BACK", "HOS_MENU_SOUND_FANFARE",
"HOS_MENU_SOUND_TAB_LEFT", "HOS_MENU_SOUND_TAB_RIGHT"}
for arg in asked:
named = set(re.findall(r"HOS_MENU_SOUND_\w+", arg))
check(named <= allowed and (named or arg == "mods_back_sound()"), "mods_tick asks for a sound that is not the Mods screen's: mods_sound(%s)" % arg)
for kind in ("NAVIGATE", "SELECT", "BACK"):
check(any("HOS_MENU_SOUND_MODS_" + kind in arg for arg in asked), "mods_tick never asks for the Mods screen's " + kind.lower())
# (Not now on the warning leaves the screen: the step back's sound is the list's it goes back to)
check(" mods_sound(mods_back_sound());\n mods_back(changed);\n" in tick,
"mods_tick: Not now does not sound as the step back onto the list the Mods screen was opened from")
# the step back onto the pause menu's System list: where mods_back goes while that list is there, and not the title's
check("int mods_back_sound() { return mods_list_fresh() && !mods_title_list() ? HOS_MENU_SOUND_PAUSE_BACK : HOS_MENU_SOUND_MODS_BACK; }" in menu,
"vk_menu.cpp: the step back out of the Mods screen is not the pause menu's onto its list alone")
check("if (mods_list_fresh() && !mods_title_list()) page = kModsRowPage;" in block(menu, "void mods_back(bool& changed) {") and
"bool mods_title_list() { return (mods_list_bits.load(std::memory_order_relaxed) & HOS_MODS_LIST_TITLE) != 0; }" in menu,
"vk_menu.cpp: mods_back or mods_title_list changed: mods_back_sound tells the pause menu's list by them")
whole = block(menu, "void menu_tick() {")
rows = whole[whole.index("} else if (open_now.load() && page == kModsRowPage) {"):whole.index("} else if (open_now.load() && page == kModsPage) {")]
check(rows.count("HOS_MENU_SOUND_PAUSE_BACK") == 2 and "quit_cancel(), mods_sound(HOS_MENU_SOUND_PAUSE_BACK)" in rows and
"mods_sound(quit_sel == 2 ? HOS_MENU_SOUND_PAUSE_BACK : HOS_MENU_SOUND_SYS_DECIDE);" in rows,
"Quit's dialog: Cancel and B do not ask for the pause menu's step back")
# (the entries under the game's lists keep the system menu's cursor and decide)
check(set(re.findall(r"HOS_MENU_SOUND_\w+", rows)) == {"HOS_MENU_SOUND_PAUSE_BACK", "HOS_MENU_SOUND_SYS_CURSOR", "HOS_MENU_SOUND_SYS_DECIDE"},
"the entries under the game's lists ask for a sound that is not the system menu's or the pause menu's step back")
# nothing in the options asks for the in-game menu's three by name any more (held against menu_sound_events.h's alone)
for was in IN_GAME:
check(len(re.findall(r"\b%s\b" % was, menu)) == 1, "vk_menu.cpp asks for the in-game menu's %s" % was)
check("const int sound = menu_sound::sound_for(menu_sound::sound_of(sound_before, after, in), on_mods, to_pause);" in whole and
"sound_queue.put(menu_sound::toggle_sound(sound, sound_before, after), prof_now());" in whole and
whole.count("s.toggle = r.value && r.text == tx_onoff;") == 0 and
menu.count("s.toggle = r.value && r.text == tx_onoff;") == 2,
"menu_tick does not ask for the sound of whose cursor, decide or cancel it is")
# the ticks: the cursor's and the two roles', replaced by the decision of the same press. ((Triforce, 11-26) the
# navigation sounds, the ticks and the system menu's cursor, as the game's own (the owner's clip): each plays whole beside
# the ones before it, at the whole level, never thinned out but for one press asking twice)
play = block(sound, "void hos_menu_sound_play(int id, int64_t now_ns) {")
mix = block(sound, "void hos_menu_sound_mix(float *left, float *right, uint32_t frames, float gain) {")
check("return id == HOS_MENU_SOUND_CURSOR || id == HOS_MENU_SOUND_SETTINGS_NAVIGATE || id == HOS_MENU_SOUND_MODS_NAVIGATE;" in
block(sound, "static int is_tick(int id) {"), "host/menu_sound.c: the roles' two ticks are not ticks")
check("static int is_nav(int id) { return is_tick(id) || id == HOS_MENU_SOUND_SYS_CURSOR; }" in sound and
"#define NAV_GAP_NS 45000000ll" in sound and "CURSOR_GAP_NS" not in sound,
"host/menu_sound.c: the navigation sounds are not the ticks and the system menu's cursor, or are still thinned out")
check("if (is_nav(id) && now_ns - atomic_load(&last_start_ns) < NAV_GAP_NS) return;" in play and
"if (at >= 0 && (was == id || is_nav(was)) && AT_FRAME(at) < 2400) {" in play and
"NAV_FADE" not in sound and ".fade" not in sound and "CURSOR_GAIN" not in sound and
"left[i] += src[2 * (size_t)i] * gain;" in mix,
"host/menu_sound.c: a navigation sound is cut short by the next sound, or a tick is not at the whole level")
check("if (pick < 0) pick = nav >= 0 ? nav : oldest;" in play,
"host/menu_sound.c: with no voice free a navigation sound's is not the first to go")
# the guide's row
row = [ln for ln in guide.splitlines() if ln.startswith("| `HOS_MENU_SOUND_SETTINGS_NAVIGATE=<sound>`")]
check(len(row) == 1, "docs/development.md has no row for the sounds' variables")
for r in ROLES:
check("`HOS_MENU_SOUND_%s" % r in row[0].split(" | ")[0], "docs/development.md's row does not name HOS_MENU_SOUND_%s" % r)
for name in OWN.values():
check("`%s`" % name in row[0], "docs/development.md's row does not say %s" % name)
most = re.search(r"^#define ROLE_NAME_MOST 64$", sound, re.M)
check(most, "host/menu_sound.c: a sound's name is no longer 64 characters at most")
src = PROGRAM.replace("@MOST@", most.group(0)).replace("@NAME_OK@", block(sound, "static int role_name_ok(const char *name) {")) \
.replace("@ALLOWED@", block(main_c, "static int env_line_allowed(")) \
.replace("@NAMES@", ", ".join('"HOS_MENU_SOUND_%s"' % r for r in ROLES)).replace("@A64@", "a" * 64)
with tempfile.TemporaryDirectory(prefix="menu-sound-roles-") as tmp:
c, exe = Path(tmp) / "roles.c", Path(tmp) / "roles.exe"
c.write_text(src, encoding="utf-8")
subprocess.run([a.cc, "-std=c11", "-Wall", "-Wextra", "-Werror", str(c), "-o", str(exe)], check=True)
r = subprocess.run([str(exe)], capture_output=True, text=True)
sys.stdout.write(r.stdout)
check(r.returncode == 0, "roles.c: " + r.stderr.strip())
print("PASS: the settings' tabs', the Mods screen's and the pause menu's own sounds, and the environment's names for them")
if __name__ == "__main__":
main()

View File

@@ -113,7 +113,9 @@ def main():
# the background: inside the game's Options screen, its own; over play, the System screens' shade and noise
# (v0.5.1: draw_menu takes perf_under, and over the Mods entry (row) dims nothing)
draw = function(menu, "void draw_menu(ui::Ctx& c, bool perf_under) {")
check("if (!embed_open && !row && !tuning && !ui::system_bg(c)) c.d->AddRectFilled(" in draw, # ((Triforce) not the tuning bar
# ((Triforce) not the tuning bar; (11-26) not Save Select over the title either, whose picture behind is out of focus)
check("if (!embed_open && !row && !tuning && !blurred && !ui::system_bg(c)) c.d->AddRectFilled(" in draw and
"const bool blurred = files_blur.load(std::memory_order_relaxed) && page == kFilesPage;" in draw,
"draw_menu dims the game's own Options screen, or not the System screens' way over play")
check(draw.count("AddRectFilled(ImVec2(0, 0), ImVec2(c.w, c.h)") == 1, "draw_menu dims the window more than once")
check("ui::column_bg(k, cx0, cx1, k.over_game);" in draw and "k.over_game = embed_open;" in draw,
@@ -147,6 +149,26 @@ def main():
'"tab_select", make_tinted(*tab, kTabBlack, kTabWhite)',
'"plate_row", make_plate(*shape, *grain, skin.get("BtnThinBase_04"), kPlateBlack, kPlateWhite, kPlateLine)'):
check(made in skin, "make_skin does not make " + made.split(",")[0])
# ((Triforce, 11-26) the cursors' glows as the game's, fitted to the lab's SDR shots: the Options rows' falloff 1.35, the
# System list's own cursor (CmnBtnCursor*, for our buttons) 1.25, optional; their colours and strengths in vk_ui.h)
check('&line.img, &glow.img, 1.35f);' in skin and 'make_cursor(cmn_line, cmn_glow, &cl.img, &cg.img, 1.25f);' in skin and
'if (el && eg && bntx.decode(*el, cmn_line)' in skin, "make_skin does not make the cursors with the game's falloffs")
check("std::pow(std::clamp(g / 0.36f, 0.0f, 1.0f), falloff)" in function(tex, "inline void make_cursor("),
"make_cursor's glow does not take the falloff it is given")
check("rgba(163, 184, 255)" in ui and "constexpr ImU32 kCmnCursorGlow = rgba(125, 161, 255);" in ui and
"kCursorGlowBase = 0.76f, kCmnCursorGlowBase = 0.68f, kCursorGlowBreath = 0.08f;" in ui,
"the cursors' glows are not the game's measured ones")
# ((Triforce, 11-26) with HDR on, the glows in two layers fitted to the game's as RenoDX codes it: the overlay blends on
# HDR10's PQ codes, where one layer came out narrow and grey; with SDR once, as measured)
check("constexpr GlowLayer kCursorGlowHdr[2] = {{rgba(144, 174, 255), 0.698f}, {rgba(143, 159, 255), 0.690f}};" in ui and
"constexpr GlowLayer kCmnCursorGlowHdr[2] = {{rgba(85, 116, 255), 0.627f}, {rgba(110, 159, 254), 0.622f}};" in ui,
"the glows' HDR layers are not the fitted ones")
layers = function(ui, "inline void glow_layers(")
check("if (!c.hdr10) {" in layers and "nine(c, t, a, b, bx, by, alpha(col, s * k));" in layers and
"const float r = s / (base + kCursorGlowBreath * 0.5f) * k;" in layers and
"for (const GlowLayer& l : hdr) nine(c, t, a, b, bx, by, alpha(l.col, l.a * r));" in layers,
"glow_layers does not draw once with SDR and the two layers, breathing, with HDR on")
check("c.hdr10 = dev.hdr;" in function(menu, "ui::Ctx ui_ctx("), "ui_ctx does not say when the overlay blends on HDR10's codes")
plate = function(ui, "inline void value_plate(")
check('skin(on ? "value_plate_on" : "value_plate")' in plate and "alpha(IM_COL32_WHITE, k)" in plate,
"value_plate does not draw the baked plates untinted")

View File

@@ -101,7 +101,7 @@ def main():
for name, code in (("now", cut), ("before", before)):
src, exe = Path(tmp) / (name + ".cpp"), Path(tmp) / (name + ".exe")
src.write_text(fixture.replace("/* ACTUAL */", code), encoding="utf-8")
subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Wno-unused-function", str(src), "-o", str(exe)], check=True)
subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Wno-unused-function", "-I", str(VK), str(src), "-o", str(exe)], check=True)
exes[name] = str(exe)
def run(name, case):

View File

@@ -86,6 +86,11 @@ static int on_last = 1;
static int64_t now_ns = 1000000000LL; /* (a read each 16 ms: read_once) */
int64_t hos_now_ns(void) { return now_ns; }
int hos_oot_mods_down(void) { return on_last; }
/* ((Triforce) the title's tabs: what the host's own presses of this read are, and whether the title's list is there (1, and 2
with the save files on) */
static uint64_t script_now;
static int title_tabs;
int hos_oot_title_tabs(void) { return title_tabs; }
%(enum)s;
%(func)s
/* one read: the buttons and stick the devices and the script give; what the game is given */
@@ -147,7 +152,35 @@ static void down_held_from_above(int above_ms, int ms, int stick, int want_ms) {
CHECK(!(presses & HOS_MODS_PRESS_DOWN)); /* (the repeat's Down onto Mods is no press of the entry's: the menu repeats on) */
}
}
/* ((Triforce) the title's tabs, Mods and Save Select at the top left: a scripted X is Mods' (the word 6) and a scripted Y Save
Select's (7), told once a press and not given to the game; off the title, with the save files off (Y), or pressed by a
device (not a host's own press: the renderer reads the pad itself) they are the game's as they were */
static void scripted_tabs(void) {
reset();
on_last = 0, title_tabs = 3;
script_now = 1ULL << B_X, read_once(1ULL << B_X, 0);
CHECK(entered == 6 && !(game >> B_X & 1));
entered = 0, read_once(1ULL << B_X, 0); /* (held: no second word) */
CHECK(entered == 0);
script_now = 0, read_once(0, 0);
script_now = 1ULL << B_Y, read_once(1ULL << B_Y, 0);
CHECK(entered == 7 && !(game >> B_Y & 1));
entered = 0, script_now = 0, read_once(0, 0);
title_tabs = 1; /* (no save files: Y is the game's) */
script_now = 1ULL << B_Y, read_once(1ULL << B_Y, 0);
CHECK(entered == 0 && (game >> B_Y & 1));
script_now = 0, read_once(0, 0);
title_tabs = 0; /* (not the title) */
script_now = 1ULL << B_X, read_once(1ULL << B_X, 0);
CHECK(entered == 0 && (game >> B_X & 1));
script_now = 0, read_once(0, 0);
title_tabs = 3; /* (a key or a pad's button, not the script's: not told here) */
read_once(1ULL << B_X | 1ULL << B_Y, 0);
CHECK(entered == 0 && (game >> B_X & 1) && (game >> B_Y & 1));
read_once(0, 0), title_tabs = 0;
}
int main(void) {
scripted_tabs();
down_held_from_above(500, 1000, 0, 500 + 83); /* (the game's repeat onto the last button at 500 ms: a step after it) */
down_held_from_above(500, 1000, 1, 500 + 83); /* (the stick's) */
down_held_from_above(16, 300, 0, -1); /* (a 300 ms press from the button above: the game's move only) */
@@ -246,6 +279,8 @@ static int fails;
static int64_t now = 9000000000LL;
int64_t prof_now() { return now; }
std::atomic<int64_t> mods_list_ns{0}, mods_list_frame{0};
static bool title_list = true; // ((Triforce, 11-26) the title's list first, as before)
bool mods_title_list() { return title_list; }
%(state)s
%(age)s
%(fresh)s
@@ -265,6 +300,17 @@ int main() {
CHECK(mods_list_fresh() && mods_list_age() == 100000000);
now += 60000000;
CHECK(!mods_list_fresh());
// ((Triforce, 11-26) the pause menu's System list: gone at the third game frame without a report, however soon (the
// owner's Mods and Quit left on the game after the menu closed); a slow frame of its is no list gone, as before)
title_list = false;
mods_list_frame.store(game_frames.load()), mods_list_ns.store(now);
game_frames += 2, now += 8000000;
CHECK(mods_list_fresh());
game_frames += 1, now += 4000000;
CHECK(!mods_list_fresh() && mods_list_age() == 12000000);
mods_list_frame.store(game_frames.load()), mods_list_ns.store(now);
now += 235000000, game_frames += 1;
CHECK(mods_list_fresh() && mods_list_age() == 0);
if (!fails) std::puts("the list's age");
return fails ? 1 : 0;
}
@@ -362,14 +408,15 @@ def main():
block(win, "static void mods_list_tick(uint64_t screen, int title, ModsCall *call) {"),
"the list's frame does not note the game's presents")
age = block(menu, "int64_t mods_list_age() {")
fresh = re.search(r"^bool mods_list_fresh\(\) \{[^\n]*\}$", menu, re.M)
check(fresh is not None, "mods_list_fresh is not the list's age against 150 ms")
fresh = block(menu, "bool mods_list_fresh() {")
check("return mods_list_age() < 150000000LL;" in fresh and "if (!mods_title_list() && mods_list_ns.load(std::memory_order_relaxed) &&" in fresh,
"mods_list_fresh is not the list's age against 150 ms, the pause menu's list gone at its third frame without a report")
game_frames = re.search(r"^std::atomic<int64_t> game_frames\{0\};", menu, re.M)
check(game_frames is not None, "game_frames is not where mods_list_age reads it")
with tempfile.TemporaryDirectory(prefix="mods-entry-input-") as tmp:
run(args.cxx, fill(HID_FIXTURE, enum=enum, func=func), "hid", tmp, "c")
run(args.cxx, fill(MENU_HOST_FIXTURE, state=state, func=down), "oot", tmp, "c")
run(args.cxx, fill(AGE_FIXTURE, state=game_frames.group(0), age=age, fresh=fresh.group(0)), "age", tmp, "c++")
run(args.cxx, fill(AGE_FIXTURE, state=game_frames.group(0), age=age, fresh=fresh), "age", tmp, "c++")
run(args.cxx, KEYS_FIXTURE, "keys", tmp, "c++")
# the menu: the host's report of the directions held (each read), repeated as a pad's held direction
@@ -382,7 +429,10 @@ def main():
check("const bool mods_here = page == kModsRowPage || page == kModsPage;" in rep and "(host_held >> (i - 1) & 1)" in rep and
"t - mods_held_ns.load(std::memory_order_relaxed) < 250000000LL" in rep,
"a direction a test's script holds on Mods is not repeated as a pad's")
check("next_repeat[i] = t + 350000000LL" in rep and "33000000LL : 83000000LL" in rep, "the repeat's rate changed")
# ((Triforce, 11-26) Up and Down at the game's own pace, 330 ms then each 135 ms (the owner's clip); Left and Right as before)
check("next_repeat[i] = t + first_ns(i)" in rep and "dir <= 2 ? kNavFirstNs : 350000000LL" in rep and
"dir <= 2 ? kNavStepNs : held > 1500000000LL ? 33000000LL : 83000000LL" in rep and
"constexpr int64_t kNavFirstNs = 330000000LL, kNavStepNs = 135000000LL;" in menu, "the repeat's rate changed")
# (the keys bound to the game's D-pad, movement and A on the entries: pressed and held as the menu's own, the Down that
# came onto Mods taken away with the pad's)
keys = tick[tick.index("uint32_t game_keys = 0, game_keys_new = 0;"):tick.index("// holding an arrow or the D-pad repeats it")]
@@ -403,7 +453,7 @@ def main():
"the game keys are read after the tabs are taken from the menu's keys")
# ((a review of beb9b9e) the held Down's repeat onto Mods, word 5: the menu repeats on from it at the step)
check("entered_by_down = enter == 1 || enter == 5;" in tick and "mods_down_repeat_ns = enter == 5 ? prof_now() : 0;" in tick and
"held_since[i] = t - 350000000LL, next_repeat[i] = t + 83000000LL, mods_down_repeat_ns = 0;" in rep,
"held_since[i] = t - first_ns(i), next_repeat[i] = t + step_ns(i, first_ns(i)), mods_down_repeat_ns = 0;" in rep,
"the menu does not go on repeating a held Down that came onto Mods by repeat")
check("held[i] || (game_keys >> i & 1) ||" in rep, "a game key held on Mods does not repeat")
check(tick.index("press[i] |= (game_keys_new >> i & 1) != 0;") < tick.index("if (entered_by_down) press[2] = false;"),

View File

@@ -109,8 +109,10 @@ def main():
draw = function(menu, "void draw_menu(ui::Ctx& c, bool perf_under) {")
first, dim = draw.index("const int vtx_page = c.d->VtxBuffer.Size;"), draw.index("ui::system_bg(c)")
check(first < dim, "the page's first vertex is taken after its background: the background would come at once")
fade = "for (int i = vtx_page; mods_in < 1 && i < c.d->VtxBuffer.Size; i++)"
check(fade in draw and "if (i < perf0 || i >= perf1) c.d->VtxBuffer[i].col = ui::alpha(c.d->VtxBuffer[i].col, mods_in);" in draw,
# ((Triforce, 11-26) Save Select's In the same way, its own Page (files_screen))
fade = "for (int i = vtx_page; page_in < 1 && i < c.d->VtxBuffer.Size; i++)"
check(fade in draw and "if (i < perf0 || i >= perf1) c.d->VtxBuffer[i].col = ui::alpha(c.d->VtxBuffer[i].col, page_in);" in draw and
"const float page_in = page == kFilesPage ? files_screen.alpha(prof_now(), !ease_live || still_in) : mods_in;" in draw,
"the page is not faded by the In's amount, or the Full panel fades with it")
check(draw.index("panel_between(c.d);") < draw.index(fade) < draw.index("put_on_grid(c.d, vtx0, cmd0, menu_map, window_clip, perf0, perf1);"),
"the fade is not over the whole page: after the panel's layer is merged, before the page is put on its grid")

View File

@@ -520,19 +520,38 @@ def main():
check("m.kx = cw > 0 ? g.w / cw : 1.0f;" in grid and "float x(float px) const { return ox + px * kx; }" in grid,
"the game's grid narrower than 16:9 is not squeezed across")
row = function(menu, "void draw_mods_row(ui::Ctx& c, bool sel) {")
check("draw_title_mods(c, sel, cx, cy, k, pitch);" in row and "(x1 - x0) / 60.0f" in row,
check("draw_title_mods(c, sel && !tab_decides, cx, cy, k, pitch);" in row and "(x1 - x0) / 60.0f" in row,
"draw_mods_row does not draw the title's entry as the part, at the list's scale")
# the input: Decide before the Mods screen, its sound once at the press
# the input: Decide first, its sound once at the press. ((Triforce) The entry under the title's list is Quit Game now: its
# Decide, then the game ends. Mods is a tab at the top left, chosen by its button, a click or the host's word 6: the same
# Decide on its tab, then the Mods screen)
tick = function(menu, "void menu_tick() {")
check("else if (mods_title_list()) mods_decide_ns = prof_now(), mods_sound(HOS_MENU_SOUND_SYS_DECIDE), changed = true;" in tick,
check("else if (mods_title_list()) mods_decide_ns = prof_now(), title_decide = 1, mods_sound(HOS_MENU_SOUND_SYS_DECIDE), changed = true;" in tick,
"A on the title's entry does not play Decide with the system menu's sound")
check("const bool decide = enter == 2 && mods_title_list();" in tick and "if (decide) mods_decide_ns = prof_now();" in tick,
check("const bool decide = enter == 2 && mods_title_list();" in tick and "if (decide) mods_decide_ns = prof_now(), title_decide = 1;" in tick,
"a click on the title's entry does not play Decide")
go = function(menu, "bool title_tab_go(int tab) {")
check("if (tab == 0) title_decide = 0, mods_decide_ns = prof_now();" in go and "page = kModsRowPage" in go
and "mods_sound(HOS_MENU_SOUND_SYS_DECIDE), tick_sound_done = true;" in go and go.index("if (!title_tabs_live()") < go.index("open_now = true"),
"Mods' tab does not play Decide with the system menu's sound, or can be chosen while it is not there")
live = function(menu, "bool title_tabs_live() {")
check("if (!mods_title_list() || !mods_list_fresh()" in live and "shown >= 0 && shown < 0.5f" in live
and "return !open_now.load() || (page == kModsRowPage && !mods_decide_ns && !quit_ask);" in live,
"the title's tabs can be chosen off the title, before its list shows, or under a page of ours")
decide = tick[tick.index("page == kModsRowPage && mods_decide_ns) {"):]
decide = decide[:decide.index("} else if (open_now.load() && page == kModsRowPage) {")]
check("prof_now() - mods_decide_ns >= mods_entry::kDecideNs" in decide and "page = kModsPage" in decide and
"mods_decided = true" in decide and "press[" not in decide, "the Mods screen does not open after Decide, or input is taken meanwhile")
check(decide.index("if (title_decide == 1) {") < decide.index("end_game(false), quit_ended = true, open_now = false, page = 0") < decide.index("page = kModsPage"),
"Quit Game's Decide does not end the game, or opens the Mods screen")
part = function(menu, "void draw_title_mods(ui::Ctx& c, bool sel, float cx, float cy, float k, float pitch) {")
check("if (f > 0 && show > 0 && !title_corner) {" in part and "!title_entry && title_decide == 1 ? now - mods_decide_ns : -1" in part
and 'const char* title_label = "Quit Game";' in menu,
"a tab is drawn with the entry's band and filigree, the entry flashes for Mods' Decide, or is not Quit Game")
back = function(menu, "void mods_back(bool& changed) {")
check("if (mods_list_fresh() && !mods_title_list()) page = kModsRowPage;" in back and "else open_now = false, page = 0, mods_sound(mods_back_sound()), tick_sound_done = true;" in back,
"Back from the Mods screen on the title leaves a cursor of ours on its list")
check("if (!mods_decided) mods_sound(HOS_MENU_SOUND_SYS_DECIDE);" in tick and "mods_decided = false;" in tick,
"the decide sound plays again when the Mods screen opens after Decide")
check("my < e[1] && my > e[1] - (quit_here ? 6 : 4) * e[4]) mods_row_sel = 0, press[1] = true;" in tick,

View File

@@ -130,6 +130,11 @@ static volatile int fps_row_asked = -100;
enum { HOS_OPT_N64_FPS = 61 };
enum { HOS_OPT_EVIL_HD = 420 }; /* ((Triforce) Evil HD's render distance: host/evil_hd.c, tests/test_evil_hd_foliage.py) */
void hos_evil_hd_tick(int row) { (void)row; }
/* ((Triforce, 11-26) the Steady row and the Render resolution as the menu applies them: none answered here, the file's row) */
enum { HOS_OPT_STEADY_ROW = 430, HOS_OPT_RES_HELD = 431 };
#include "res_follow.h"
int hos_rt_pool_pinned(void) { return 0; }
void rx_option_set(int id, int value) { (void)id; (void)value; }
static volatile long long presents;
volatile uint64_t hos_gfx_module = MOD;
volatile int hos_fixed_resolution, hos_dynres_runs;
@@ -258,8 +263,9 @@ def main():
check("const int raise = movie_pace_raise(on, fps_max(), steady != PACE_STEADY_OFF, movie_plays());" in decide
and "movie_raise = raise;" in decide, "the decision is not the rule's, from the cap, the Steady row and the movie's stamp")
steady = block(vi, "static int64_t steady_period(int64_t base, int64_t now) {")
for read in ('getenv("HOS_FPS_STEADY");', 'e && *e ? atoi(e) : hos_ini_option("steady_frame_rate", PACE_STEADY_OFF);'):
check(read in decide and read in steady, "the decision does not read the Steady frame rate row as steady_period does: " + read)
# ((Triforce, 11-26) both by steady_mode, the row as it is now each present: tests/test_menu_apply.py)
check("steady = steady_mode();" in decide and "const int want = steady_mode();" in steady,
"the decision does not read the Steady frame rate row as steady_period does: steady_mode")
check("if (cap != fps_max()) {" in steady and "pace_fps()" not in steady, "the Steady frame rate row no longer goes by the cap itself")
check("return seen && hos_now_ns() - seen < 250000000LL;" in block(vi, "static int movie_plays(void) {"),
"a movie no longer plays for a quarter second after its player's update")
@@ -290,7 +296,7 @@ def main():
movie = vi[vi.index("static volatile LONG64 movie_seen_ns;"):vi.index("static int pace_handed(void) {")]
host = "\n".join([block(vi, "static int fps_cap_of("), block(vi, "static int fps_max(void) {"), movie, "static int movie_raise;",
"static int n64_rate;", block(vi, "static int pace_fps(void) {"), block(vi, "static void n64_pace_decide(void) {"),
decide, block(vi, "static float text_scale("),
block(vi, "static int steady_mode(void) {"), decide, block(vi, "static float text_scale("),
block(vi, "static int realtime_rate("), step])
with tempfile.TemporaryDirectory(prefix="movie-pace-") as tmp:
src, exe = Path(tmp) / "rules.c", Path(tmp) / "rules.exe"

View File

@@ -127,12 +127,16 @@ def check_draw():
def check_asides():
temporal = (VK / "vk_temporal.cpp").read_text(encoding="utf-8")
mode = function(temporal, "int temporal_mode() {")
in_order(mode, ["v = n64_rules::upscaler(n64_in_front(), v);", "if (!chain_engine(v)) return ur::GAME;"],
# ((Triforce, 11-26) in temporal_mode_of, with now: temporal_mode's, the frames'. Without it the choice's own, which the
# 3D's size follows (vk_menu.cpp resolution_full): N64 Classic's pass does not remake the game's targets)
if "return temporal_mode_of(v, true);" not in function(temporal, "int temporal_mode() {"):
fail("temporal_mode does not ask with now")
mode = function(temporal, "int temporal_mode_of(int choice, bool now) {")
in_order(mode, ["if (now) v = n64_rules::upscaler(n64_in_front(), v);", "if (!chain_engine(v)) return ur::GAME;"],
"temporal_mode: DLSS and FSR 4 no longer step aside for N64 Classic's 3D pass, over the switches too")
fsr3 = function((VK / "vk_fsr3.cpp").read_text(encoding="utf-8"), "bool fsr3_wanted() {")
fsr3 = function((VK / "vk_fsr3.cpp").read_text(encoding="utf-8"), "bool fsr3_wanted_of(int choice, bool now) {")
in_order(fsr3, ["if (env == 0) return false;",
"if (n64_rules::upscaler(n64_in_front(), upscaler_rows::FSR3) != upscaler_rows::FSR3) return false;",
"if (now && n64_rules::upscaler(n64_in_front(), upscaler_rows::FSR3) != upscaler_rows::FSR3) return false;",
"return (env > 0 ||"], "fsr3_wanted: FSR 3.1 no longer steps aside for N64 Classic's 3D pass")
aa = (VK / "vk_aa.cpp").read_text(encoding="utf-8")
choice = function(aa, "int choice_now() {")

View File

@@ -101,6 +101,7 @@ enum { HOS_OPT_N64_FPS = 61 };
static int n64_asked; /* (the renderer's answer: vk_replay.cpp, n64_rules.h fps) */
int rx_option(int id, int otherwise) { return id == HOS_OPT_N64_FPS ? n64_asked : otherwise; }
int hos_ini_option(const char *key, int otherwise) { (void)key; return otherwise; }
enum { HOS_OPT_STEADY_ROW = 430 }; /* ((Triforce, 11-26) the Steady row as it is now: not answered here, the file's */
static volatile long long presents;
@HOST@
/* a present: the clock on by a frame, the decision as hos_vi_native_presented takes it */
@@ -171,7 +172,8 @@ def main():
movie = vi[vi.index("static volatile LONG64 movie_seen_ns;"):vi.index("static int pace_handed(void) {")]
host = "\n".join([block(vi, "static int fps_cap_of("), block(vi, "static int fps_max(void) {"), movie, "static int movie_raise;",
"static int n64_rate;", block(vi, "static int pace_fps(void) {"), n64, decide])
"static int n64_rate;", block(vi, "static int pace_fps(void) {"), n64, block(vi, "static int steady_mode(void) {"),
decide])
with tempfile.TemporaryDirectory(prefix="n64-pace-") as tmp:
src, exe = Path(tmp) / "rules.c", Path(tmp) / "rules.exe"
src.write_text(RULES, encoding="utf-8")

View File

@@ -143,7 +143,9 @@ def main():
"(value == &opts.n64_classic && n64_env_set())",
"(n64_rem_row(value) >= 0 && n64_rules::row_fixed(n64_rules::rows_of(opts.n64_rem), n64_rem_row(value)))"):
check(need in fixed, "row_fixed: %s is gone" % need)
for fn in ("const char* tx_upscaler(int) {", "const char* tx_aa(int v) {"):
# ((Triforce, 11-26) the Upscaler's name for an upscaler_of: the row's, tx_upscaler, and the performance panel's)
check("const char* tx_upscaler(int) { return upscaler_name(upscaler()); }" in menu, "tx_upscaler is not upscaler_name's")
for fn in ("const char* upscaler_name(int up) {", "const char* tx_aa(int v) {"):
body = block(menu, fn)
check(body.split("{", 1)[1].lstrip().startswith('if (n64_in_front() != n64_rules::OFF) return "N64 Classic";'),
"%s does not say N64 Classic while its 3D pass draws" % fn)

View File

@@ -470,7 +470,7 @@ def main():
check(dp.index("panel_merge(c.d);") < dp.index("dim_window(c.d, menu_map, game_black ? menu_grid(w, h) : game_grid::Place{}, w, h, col);") <
dp.index("panel_over(c.d);"),
"dim_page: the dim is not the whole window's over the page and its header, under the Full panel")
for head, dim in (("void draw_ask(ui::Ctx& c) {", "dim_page(c, ui::rgba(8, 5, 2, 110));"),
for head, dim in (("void draw_ask(ui::Ctx& c) {", "dim_page(c, ui::rgba(8, 5, 2, c.over_game ? 215 : 110));"), # ((11-26) darker over the game's own screen
("void mods_dialog(ui::Ctx& c, const char* title,", "dim_page(c, ui::rgba(8, 5, 2, 120));"),
("void mods_keyboard(ui::Ctx& c) {", "dim_page(c, ui::rgba(8, 5, 2, 120));")):
body = block(menu, head)

View File

@@ -501,7 +501,10 @@ def check_source():
vi = (ROOT / "host/nn_vi.c").read_text(encoding="utf-8")
check('#include "pace_steady.h"' in vi, "host/nn_vi.c does not include host/pace_steady.h")
steady = block(vi, "static int64_t steady_period(int64_t base, int64_t now) {")
check('getenv("HOS_FPS_STEADY")' in steady and 'hos_ini_option("steady_frame_rate", PACE_STEADY_OFF)' in steady,
# ((Triforce, 11-26) by steady_mode: HOS_FPS_STEADY, else the row as it is now each present, else the file's
mode = block(vi, "static int steady_mode(void) {")
check("const int want = steady_mode();" in steady and 'getenv("HOS_FPS_STEADY")' in mode and
'hos_ini_option("steady_frame_rate", PACE_STEADY_OFF)' in mode and "rx_option(HOS_OPT_STEADY_ROW, -1)" in mode,
"steady_period does not read HOS_FPS_STEADY over the row's steady_frame_rate")
check("if (mode == PACE_STEADY_OFF) return base;" in steady, "the row off does not leave the cap's period as before")
check("pace_steady_measure(interval, own + held, other, &took, &need);" in steady and "pace_steady_feed(&steady, took, need, interval)" in steady,
@@ -548,15 +551,16 @@ def check_source():
"a hold on the present thread is counted as the presenting thread's")
menu = (ROOT / "gpu/vk/vk_menu.cpp").read_text(encoding="utf-8")
# ((Triforce, options_version 7) Steady frame rate is the Frame pacing row's two Steady values (merged_rows.h); its value keeps
# its key, steady_frame_rate, in a row no tab shows, and the Frame pacing row takes the restart for it)
# its key, steady_frame_rate, in a row no tab shows. ((11-26) It changes at once now: the host reads it each present)
row = re.search(r'\{TAB_HIDDEN, "Steady frame rate", &opts\.steady_fps, 0, 2, 1, tx_steady_fps, nullptr\},', menu)
check(row is not None, "the Steady frame rate's value is not kept under its key, 0 to 2")
pacing = re.search(r'\{TAB_GRAPHICS, "Frame pacing", &merged\.pacing, 0, 3, 1, tx_pacing,(.*?)\n hn_pacing, true\},', menu, re.S)
check(pacing is not None, "the Graphics tab has no Frame pacing row of four values taking a restart")
pacing = re.search(r'\{TAB_GRAPHICS, "Frame pacing", &merged\.pacing, 0, 3, 1, tx_pacing,(.*?)\n hn_pacing\},', menu, re.S)
check(pacing is not None, "the Graphics tab has no Frame pacing row of four values, changed at once")
check(menu.index('"Frame rate cap", &opts.fps_cap') < menu.index('"Frame pacing", &merged.pacing'),
"the Frame pacing row is not in the Frame rate cap's group")
check("if (r.value == &merged.pacing) return opts.steady_fps;" in block(menu, "int restart_value_of(const Row& r) {"),
"the Frame pacing row asks for a restart for more than its Steady values")
check("merged.pacing" not in block(menu, "int restart_value_of(const Row& r) {") and
"if (id == HOS_OPT_STEADY_ROW) return menu_steady_row();" in replay,
"the Frame pacing row still asks for a restart, or the host is not told its Steady")
check('return v == 1 ? "Any rate" : v == 2 ? "Refresh steps" : "Off";' in block(menu, "const char* tx_steady_fps(int v) {"),
"the row's values are not Off, Any rate, Refresh steps")
check("opts.steady_fps" not in block(menu, "const char* ini_key(const Row& r) {"), "the row's key is not its name's, steady_frame_rate")

View File

@@ -131,11 +131,18 @@ def main():
# the cursor and the button with an amount
cursor = function(ui, "inline void cursor(Ctx& c, ImVec2 a, ImVec2 b, float k = 1) {")
check("if (k <= 0) return;" in cursor and "(0.50f + 0.35f * c.pulse) * k" in cursor and "alpha(kCursor, k)" in cursor,
check("if (k <= 0) return;" in cursor and "glow_layers(c, glow, a - m, b + m, 150, 80, kCursorGlow, kCursorGlowBase, kCursorGlowHdr, k);" in cursor and
"alpha(kCursor, k)" in cursor,
"the cursor's line and glow are not drawn with its amount")
button = function(ui, "inline void button(Ctx& c, ImVec2 a0, ImVec2 b0, const char* label, float focus) {")
check("if (focus > 0) cursor(c, a0 + ImVec2(lu(c, 8), lu(c, 8)), b0 - ImVec2(lu(c, 8), lu(c, 8)), focus);" in button,
"the button does not draw its cursor with its amount")
# ((Triforce, 11-26) the System list's own cursor (CmnBtnCursor*), its line outside the plate's edge, the bluer glow; the
# Options rows' where those textures are missing)
check("if (focus > 0) cmn_cursor(c, a0, b0, focus);" in button, "the button does not draw its cursor with its amount")
cmn = function(ui, "inline void cmn_cursor(Ctx& c, ImVec2 a, ImVec2 b, float k = 1) {")
check("if (k <= 0) return;" in cmn and "glow_layers(c, glow, a - m, b + m, 140, 90, kCmnCursorGlow, kCmnCursorGlowBase, kCmnCursorGlowHdr, k);" in cmn and
"alpha(kCursor, k)" in cmn and
"cursor(c, a + ImVec2(lu(c, 8), lu(c, 8)), b - ImVec2(lu(c, 8), lu(c, 8)), k);" in cmn,
"the System list's cursor is not drawn with its amount, or has no fallback")
check("inline void button(Ctx& c, ImVec2 a0, ImVec2 b0, const char* label, bool sel) { button(c, a0, b0, label, sel ? 1.0f : 0.0f); }" in ui,
"the other buttons (draw_ask's) no longer draw their cursor whole")
@@ -214,21 +221,31 @@ def main():
check("press[7] = false" in wait and "press[5]" in wait and "press[2]" in wait, "the dialog takes presses while its In plays")
check("if (mods_row_sel == 1) quit_open(), mods_sound(HOS_MENU_SOUND_SYS_DECIDE), changed = true;" in rows,
"A on Quit does not open its dialog with its In and the system menu's decide")
check("if (quit_sel == 2) quit_cancel();" in rows and "quit_cancel(), mods_sound(HOS_MENU_SOUND_CANCEL)" in rows,
"Cancel and B do not close the dialog with its Out")
# ((Triforce, 11-25) with the pause menu's step back, a sound of its own: the system menu's cancel unless set)
check("if (quit_sel == 2) quit_cancel();" in rows and "quit_cancel(), mods_sound(HOS_MENU_SOUND_PAUSE_BACK)" in rows and
"mods_sound(quit_sel == 2 ? HOS_MENU_SOUND_PAUSE_BACK : HOS_MENU_SOUND_SYS_DECIDE);" in rows,
"Cancel and B do not close the dialog with its Out (and the pause menu's step back)")
check("quit_ask = true" not in tick and "quit_ask = false" not in tick, "the dialog is opened or closed past its In and Out")
check("else if (!after.open && !quit_ended) mods_sound(HOS_MENU_SOUND_SYS_CURSOR);" in tick and "quit_ended = true" in rows,
"Quit Game's decide is followed by the cursor's sound")
# (the sounds reach the host: the queue takes the system menu's)
check("constexpr int kFanfare = 8, kSysCursor = 9, kSysDecide = 10, kLast = kSysDecide;" in events and "sound > kLast" in events,
check("constexpr int kFanfare = 8, kSysCursor = 9, kSysDecide = 10;" in events and "kSettingsOn = 18, kSettingsOff = 19, kLast = kSettingsOff;" in events and
"sound > kLast" in events,
"the sounds' queue drops the system menu's cursor and decide")
# the host: the stick's Down onto Mods where the menu's bits have it; the system tick replaced by its decide
check("const int down = (int)(buttons >> B_DOWN & 1) || stick[1] < -16384;" in hid and "if (s[1] < -16384) menu |= 1ULL << HOS_PAD_LS_DOWN;" in hid,
"the stick's Down onto Mods is not where the menu's pad bits have it (a later read is a Down of the entry's)")
play = function(sound, "void hos_menu_sound_play(int id, int64_t now_ns) {")
check("was == HOS_MENU_SOUND_SYS_CURSOR" in play, "the system menu's tick is not replaced by the decide of the same press")
check("if (id == HOS_MENU_SOUND_CURSOR && now_ns - atomic_load(&last_start_ns) < CURSOR_GAP_NS) return;" in play,
# ((Triforce, 11-25) the system menu's cursor is a navigation sound (is_nav): the decide of the same press takes its voice)
check("(was == id || is_nav(was)) && AT_FRAME(at) < 2400" in play and
"static int is_nav(int id) { return is_tick(id) || id == HOS_MENU_SOUND_SYS_CURSOR; }" in sound,
"the system menu's tick is not replaced by the decide of the same press")
# ((Triforce, 11-25) the ticks: the cursor's, the settings' tabs' and the Mods screen's; not the system menu's own, which is
# a navigation sound at the whole level. A navigation sound is left out only within 45 ms of the sound before (one press
# asking twice): the 180 ms gap thinned a quick run down a list out of step with its moves)
check("if (is_nav(id) && now_ns - atomic_load(&last_start_ns) < NAV_GAP_NS) return;" in play and "#define NAV_GAP_NS 45000000ll" in sound and
"return id == HOS_MENU_SOUND_CURSOR || id == HOS_MENU_SOUND_SETTINGS_NAVIGATE || id == HOS_MENU_SOUND_MODS_NAVIGATE;" in sound,
"the options' tick gap changed")
with tempfile.TemporaryDirectory(prefix="pause-mods-anim-") as tmp:

769
tests/test_pickwide.py Normal file
View File

@@ -0,0 +1,769 @@
"""A draw's program by a wider memo in front of program_for (gpu/vk/pickwide.h; vk_shader.cpp program_for_wide, vk_draw.cpp
draw and dry_draw_program; no game, no GPU).
(Triforce, 11-26, the GPU audit's C02.) program_for's pair of last picks compares ub_generation(), which every inline uniform
update moves, and holds two programs; a draw that misses hashes its inputs, finds its pick, reads every answer's handle and,
where one differs, reads them all again with their types compared. The memo in front of it holds 32 programs a thread, lets a
program whose answers are all in c2 of their own stages stand across uniform updates, and asks a program whose textures moved
in one pass over its answers. program_for itself is in the translation stamp and is not touched.
Compiles a driver against the header:
- the switch's values (a number other than 0 on, any word but check off), the lab's phase, the rules RX_VK_PICK_BIND_GEN
and RX_VK_DEFERRED_LATE leave;
- A, B, C, A with their textures unchanged and a buffer bound between them: the fourth stands (a pair held two); A, B, A
of handle programs: A is kept and takes one pass;
- a uniform update between two draws of a c2-only program: stands; of a handle program (mask ~0): does not; nor with the
pair's old rule or with deferred binds;
- a stage outside the mask rebound: stands; one inside it: does not; a slot registered anew: does not;
- other vertex inputs, colour types or stage words: another entry;
- one pass: every handle read once; a slot seen and checked at its version is not asked again; a slot rebound to a texture
of the same type costs one compare; another type, or a version moved to another type, fails; an unbound slot takes any
and is asked once it is bound; the verdict is still_valid's on a random walk of binds, registrations and types;
- the table: one entry for one program object and inputs, the way not used last replaced;
- a program only noted (program_for's, at a draw that went to it) does not stand and has nothing of it read; found by its
first pass, it stands.
Runs a model of the hook over the real rule, in the default mode's shape (the full pick asked only where the memo has no
answer, its program noted and walked at its next draw), against a model of program_for's full pick asked at every draw in a
world of its own (its kept program while it is of the bound textures' types, else the first variant that is): the same
variant at every draw of a random stream. And the cost the review of the first version found: three programs of one set
drawn in turn, every draw program_for's, read no answer at all in the memo (the first version walked each of them at every
draw, a third walk on top of the full pick's two); two programs in turn are walked once each, at their second draw. And one
program object drawn with three sets of vertex inputs in turn: every draw program_for's (the set is by the serial alone).
Compiles the hook itself (vk_shader.cpp, its counters to program_wide_stats, cut out by its text) over stubs, with
RX_VK_PICK_WIDE=check: program_for's program drawn at every draw; a helper thread's differences and wrong variants reach the
frame line's totals at once, its compares with them, although it records nothing more (they waited for its next 256th pick
before); a nopickwide phase's first pick adds what the thread held; no program from program_for is logged as such.
Reads the source: program_for_wide in a part of vk_shader.cpp outside the translation stamp, nothing of it inside (the stamp's
text, as nx2/build.py takes it, does not name it); the switch read once and logged, the lab's knob, the two older switches;
the memo's program used only ready and not failed; a full pick's program only noted where it is picked (no pass, no mask,
no canonical types there) and kept once its first pass, at its next draw, found it valid; check mode returns program_for's;
draw() and dry_draw_program ask it for graphics programs, and nothing else does; the status line, with check mode's totals
shown once a difference or a compare is counted; the switches table's row.
python -I -B tests/test_pickwide.py [--cxx clang++]
"""
import argparse
import ast
import hashlib
import json
import os
import subprocess
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
OUT_MARK = "// ---- (Triforce) Outside the translation stamp"
IN_MARK = "// ---- (Triforce) Inside the translation stamp again"
DRIVER = r'''
#include "pickwide.h"
#include <cstdio>
#include <map>
#include <random>
#include <vector>
using namespace mkwvk::pickwide;
static int checks, fails;
static void want(const char* what, bool ok) {
checks++;
if (!ok) fails++, printf("FAIL %s\n", what);
}
// A state as the hook reads it
struct State {
uint64_t serial = 1, sig = 11, bind = 100, reg = 5, ub = 9;
int nvattr = 2;
uint32_t vattr[16]{};
uint8_t ct[8]{};
uint64_t tex_gen[kStages]{};
Now now() const { return {serial, sig, bind, reg, ub, nvattr, vattr, ct, tex_gen}; }
};
// The world one_pass asks: the handle each answer reads, the slots' versions and types
struct World {
std::vector<uint32_t> handle; // (an answer's)
std::map<uint32_t, uint32_t> version; // (a slot's)
std::map<uint32_t, uint8_t> type; // (a slot's)
int reads = 0, asked = 0;
bool valid(const std::vector<uint8_t>& canon) const { // (still_valid: every bound answer of the variant's type)
for (size_t i = 0; i < handle.size(); i++)
if (handle[i] && type.at(handle[i] & kSlotBits) != canon[i]) return false;
return true;
}
};
static bool pass(Entry& e, World& w, Walk* walk = nullptr) {
return one_pass(e, w.handle.size(), [&](size_t i) { return w.reads++, w.handle[i]; },
[&](uint32_t id) { return w.version[id]; },
[&](size_t i, uint32_t h) { return w.asked++, w.type[h & kSlotBits] == e.canon[i]; }, walk);
}
int main() {
want("the switch: unset on, 1 on, 0 off, check", mode(nullptr) == Mode::On && mode("1") == Mode::On && mode("0") == Mode::Off &&
mode("check") == Mode::Check);
want("a number other than 0 is on, any word but check off", mode("2") == Mode::On && mode("on") == Mode::Off &&
mode("Check") == Mode::Off && mode("") == Mode::Off);
want("the lab's phase is off", in_phase(Mode::On, true) == Mode::Off && in_phase(Mode::Check, true) == Mode::Off &&
in_phase(Mode::On, false) == Mode::On && in_phase(Mode::Check, false) == Mode::Check &&
in_phase(Mode::Off, false) == Mode::Off);
const Rules all = rules(false, false), old_pair = rules(true, false), late = rules(false, true);
want("the rules", all.by_tex && all.free_ub && !old_pair.by_tex && !old_pair.free_ub && late.by_tex && !late.free_ub);
{ // A, B, C, A: three programs, a buffer bound and a uniform updated between them, the textures as they were
Table t;
State s;
int pa = 0, pb = 0, pc = 0;
const void* progs[3] = {&pa, &pb, &pc};
for (int k = 0; k < 3; k++) {
s.serial = 100 + k, s.sig = 1000 + k, s.bind++, s.ub++;
want("first sight: no entry", find(t, s.now()) == nullptr);
take(place(t, s.now()), s.now(), progs[k], 1u << 1);
}
s.serial = 100, s.sig = 1000, s.bind++, s.ub++;
Entry* e = find(t, s.now());
want("A after B and C is still kept", e && e->p == &pa);
want("and stands past the binds and the update", e && stands(*e, s.now(), all) == Stand::PastUpdate);
want("the pair's old rule: it does not", e && stands(*e, s.now(), old_pair) == Stand::No);
want("deferred binds: it does not", e && stands(*e, s.now(), late) == Stand::No);
}
{ // A, B, A, two handle programs (mask ~0): A is kept, but binding B and A again moved bind_gen, so A takes one pass
Table t;
State s;
World w; // (A's two answers, their textures as they were throughout)
w.handle = {5, 6};
for (uint32_t id : {5u, 6u}) w.version[id] = 1, w.type[id] = 1;
int pa = 0, pb = 0;
Entry& a = place(t, s.now());
take(a, s.now(), &pa, kNotC2);
a.canon = {1, 1};
pass(a, w); // (the pass it was found by)
s.serial = 200, s.sig = 2000, s.bind++;
take(place(t, s.now()), s.now(), &pb, kNotC2);
s.serial = 1, s.sig = 11, s.bind++;
Entry* e = find(t, s.now());
want("a handle program drawn after another one: kept, and does not stand", e && e->p == &pa && stands(*e, s.now(), all) == Stand::No);
w.reads = w.asked = 0;
want("its one pass: valid, each handle read once, no type compared again", e && pass(*e, w) && w.reads == 2 && w.asked == 0);
if (e) restamp(*e, s.now());
want("and it stands from there", e && stands(*e, s.now(), all) == Stand::Bound);
}
{ // the three ways an entry stands, and what ends each
Table t;
State s;
int p = 0;
s.tex_gen[1] = 40, s.tex_gen[0] = 30;
Entry& e = place(t, s.now());
take(e, s.now(), &p, 1u << 1);
want("nothing bound, nothing updated", stands(e, s.now(), all) == Stand::Bound && stands(e, s.now(), old_pair) == Stand::Bound);
s.bind++;
want("bound anew, its stage's textures the same", stands(e, s.now(), all) == Stand::Textures && stands(e, s.now(), late) == Stand::Textures);
want("the pair's old rule: not across a bind", stands(e, s.now(), old_pair) == Stand::No);
s.ub++;
want("a uniform updated: a c2-only program stands", stands(e, s.now(), all) == Stand::PastUpdate);
State same_bind = s;
same_bind.bind = e.bind;
want("a uniform updated and nothing bound: stands by its textures", stands(e, same_bind.now(), all) == Stand::PastUpdate);
s.tex_gen[0] = ++s.bind;
want("a stage outside its mask rebound: stands", stands(e, s.now(), all) == Stand::PastUpdate);
s.tex_gen[1] = ++s.bind;
want("a stage of its mask rebound: does not", stands(e, s.now(), all) == Stand::No);
want("but it is of these inputs: one pass", same_inputs(e, s.now()) && find(t, s.now()) == &e);
restamp(e, s.now());
want("found valid: stands from here", stands(e, s.now(), all) == Stand::Bound);
s.reg++;
want("a slot registered anew: does not stand", stands(e, s.now(), all) == Stand::No && same_inputs(e, s.now()));
restamp(e, s.now());
Entry handles = e;
handles.amask = kNotC2;
want("a handle program: nothing bound, nothing updated", stands(handles, s.now(), all) == Stand::Bound);
s.ub++;
want("a handle program does not stand past a uniform update", stands(handles, s.now(), all) == Stand::No);
want("the c2-only one does", stands(e, s.now(), all) == Stand::PastUpdate);
s.ub--, s.bind++;
want("a handle program does not stand past a bind", stands(handles, s.now(), all) == Stand::No);
Entry none = e;
none.amask = 0;
s.ub++, s.tex_gen[1] = ++s.bind;
want("a program that asks nothing stands whatever is bound", stands(none, s.now(), all) == Stand::PastUpdate);
State o = s;
o.vattr[3] = 7;
want("other vertex inputs: another entry", !same_inputs(e, o.now()) && find(t, o.now()) == nullptr && stands(e, o.now(), all) == Stand::No);
o = s, o.ct[0] = 2;
want("other colour types: another entry", !same_inputs(e, o.now()) && stands(e, o.now(), all) == Stand::No);
o = s, o.nvattr = 3;
want("another count of vertex inputs: another entry", !same_inputs(e, o.now()));
o = s, o.sig++;
want("other stage words: another entry", !same_inputs(e, o.now()));
drop(e);
want("dropped: nothing kept", !same_inputs(e, s.now()) && find(t, s.now()) == nullptr);
}
{ // noted, then found: a program program_for gave is not walked where it is picked
Table t;
State s;
int p = 0, q = 0;
Entry& e = place(t, s.now());
e.canon = {7, 7}, e.stamps = {1, 1, 2, 2}, e.ok = {1, 1}, e.amask = 1u << 1, e.walked = true; // (what an older program left)
note(e, s.now(), &p);
want("noted: of these inputs, found again", same_inputs(e, s.now()) && find(t, s.now()) == &e && e.p == &p);
want("noted: not walked, no mask, its next pass asks every answer", !e.walked && e.amask == kNotC2 && e.stamps.empty() && e.ok.empty());
want("a noted program does not stand, nothing bound or updated since", stands(e, s.now(), all) == Stand::No &&
stands(e, s.now(), old_pair) == Stand::No);
s.bind++, s.ub++, s.tex_gen[1] = s.bind;
found(e, s.now(), 1u << 1);
want("found by its first pass: it stands from there", e.walked && e.amask == 1u << 1 && stands(e, s.now(), all) == Stand::Bound);
s.ub++;
want("and past a uniform update", stands(e, s.now(), all) == Stand::PastUpdate);
note(e, s.now(), &q);
want("noted anew (program_for gave another): it does not stand", e.p == &q && stands(e, s.now(), all) == Stand::No);
Entry both;
take(both, s.now(), &p, 1u << 1);
want("take is note and found", both.walked && both.p == &p && stands(both, s.now(), all) == Stand::Bound);
}
{ // one pass
World w;
w.handle = {5, 6 | 3u << 20, 0, 7};
for (uint32_t id : {0u, 5u, 6u, 7u, 8u, 9u}) w.version[id] = 1, w.type[id] = 1;
w.type[9] = 0x81; // (an integer texture)
Entry e;
e.canon = {1, 1, 1, 1};
Walk k;
want("a fresh entry: valid", pass(e, w, &k));
want("every handle read once, every bound answer asked", w.reads == 4 && w.asked == 3 && k.answers == 4 && k.moved == 4 && k.checked == 3);
w.reads = w.asked = 0;
want("the same textures again: valid", pass(e, w, &k));
want("each handle read once, none asked again", w.reads == 4 && w.asked == 0 && k.moved == 0 && k.checked == 0);
w.handle[0] = 8, w.reads = w.asked = 0;
want("a slot rebound to a texture of the same type: valid", pass(e, w, &k));
want("one read an answer, one compare", w.reads == 4 && w.asked == 1 && k.moved == 1 && k.checked == 1);
w.handle[1] = 6 | 9u << 20, w.reads = w.asked = 0;
want("another sampler, the same slot: valid, nothing asked", pass(e, w, &k) && w.asked == 0 && k.moved == 0);
w.handle[2] = 7, w.reads = w.asked = 0;
want("the unbound answer bound: asked once", pass(e, w, &k) && w.asked == 1);
w.handle[2] = 0;
want("unbound again: takes any", pass(e, w, &k));
w.handle[3] = 9, w.reads = w.asked = 0;
want("an integer texture where the variant has a float one: not valid", !pass(e, w, &k) && k.checked == 1);
want("and not valid again (nothing is taken on trust after a failure)", !pass(e, w));
w.handle[3] = 7;
want("back to the float one: valid", pass(e, w));
w.version[7] = 2, w.type[7] = 0x81, w.asked = 0;
want("its slot registered anew as an integer one: not valid", !pass(e, w) && w.asked == 1);
w.version[7] = 3, w.type[7] = 1, w.asked = 0;
want("and anew as a float one: valid, asked once", pass(e, w) && w.asked == 1);
// (slot 0 with a sampler is a bound handle: it is asked although an unbound answer left slot 0's stamp there)
w.handle[2] = 0;
pass(e, w);
w.type[0] = 0x81, w.handle[2] = 1u << 20, w.asked = 0;
want("slot 0 named with a sampler after the answer was unbound: asked, not valid", !pass(e, w) && w.asked == 1);
w.handle[2] = 0;
fresh(e);
w.reads = w.asked = 0;
want("fresh: every bound answer asked again", pass(e, w) && w.reads == 4 && w.asked == 3);
Entry empty;
World nothing;
want("a program that asks nothing is valid", pass(empty, nothing) && nothing.reads == 0);
// the verdict is still_valid's, over a random walk of binds, registrations and types
std::mt19937 rng(20261126);
World r;
r.handle.assign(6, 0);
for (uint32_t id = 0; id < 12; id++) r.version[id] = 1, r.type[id] = (uint8_t)(rng() % 3 ? 1 : 0x81);
Entry m;
m.canon.assign(6, 1);
int agree = 0, valid_n = 0, reads_ok = 1;
for (int step = 0; step < 20000; step++) {
const unsigned what = rng() % 10;
if (what < 6) r.handle[rng() % 6] = rng() % 5 ? (rng() % 12) | (rng() % 4) << 20 : 0;
else if (what < 8) { const uint32_t id = rng() % 12; r.version[id]++, r.type[id] = (uint8_t)(rng() % 3 ? 1 : 0x81); }
else if (what == 8) fresh(m);
r.reads = 0;
const bool got = pass(m, r), should = r.valid(m.canon);
agree += got == should, valid_n += should;
if (got && r.reads != 6) reads_ok = 0;
}
want("one pass says what still_valid says, 20000 steps", agree == 20000 && valid_n > 500 && valid_n < 19500);
want("a valid pass reads each handle exactly once", reads_ok == 1);
}
{ // the table
Table t;
State s;
int p[40];
std::vector<uint64_t> in_set0;
for (uint64_t serial = 1; in_set0.size() < 3; serial++)
if (set_of(serial) == set_of(1)) in_set0.push_back(serial);
for (int k = 0; k < 2; k++) {
s.serial = in_set0[k];
take(place(t, s.now()), s.now(), &p[k], 0);
}
s.serial = in_set0[0];
want("two programs of one set are both kept", find(t, s.now()) && find(t, s.now())->p == &p[0]);
s.serial = in_set0[2];
take(place(t, s.now()), s.now(), &p[2], 0);
s.serial = in_set0[0];
want("a third replaces the one not used last", find(t, s.now()) && find(t, s.now())->p == &p[0]);
s.serial = in_set0[1];
want("which is gone", find(t, s.now()) == nullptr);
s.serial = in_set0[0];
Entry& again = place(t, s.now());
want("the same inputs are kept in the entry they have", again.p == &p[0]);
take(again, s.now(), &p[5], 0);
int n = 0;
for (auto& set : t.e)
for (Entry& e : set) n += same_inputs(e, s.now());
want("one entry for one program object and inputs", n == 1 && find(t, s.now())->p == &p[5]);
drop(*find(t, s.now()));
s.serial = in_set0[1];
take(place(t, s.now()), s.now(), &p[6], 0);
s.serial = in_set0[2];
want("an empty way is taken before a kept program is replaced", find(t, s.now()) && find(t, s.now())->p == &p[2]);
int sets[kSets] = {};
for (uint64_t serial = 0x5000; serial < 0x5000 + 64; serial++) sets[set_of(serial)]++;
int used = 0;
for (int k : sets) used += k > 0;
want("serials spread over the sets", used >= 12 && set_of(~0ull) < (unsigned)kSets);
clear(t);
n = 0;
for (auto& set : t.e)
for (Entry& e : set) n += e.p != nullptr;
want("cleared", n == 0);
}
{ // The hook's model, in the default mode's shape (the full pick asked only where the memo has no answer), against the
// full pick asked at every draw in a world of its own (RX_VK_PICK_WIDE=0): the same variant at every draw.
// A program object has variants by its answers' types; the full pick keeps one for its key and returns it while it is
// of the bound textures' types, else the first variant that is (made when there is none).
struct Variant { std::vector<uint8_t> canon; };
struct Object {
uint64_t serial;
size_t nanswers;
uint32_t amask;
std::vector<Variant*> variants;
Variant* kept; // (the full pick's Pick::p)
};
struct Scene {
uint32_t slot_of[4] = {1, 2, 3, 4}; // (stage 1's bound textures, one an answer)
std::map<uint32_t, uint32_t> version;
std::map<uint32_t, uint8_t> type;
State s;
};
struct Counts { int memo = 0, first = 0, by_pass = 0, full = 0, unkept = 0, reads = 0; };
auto valid = [](Scene& sc, const Object& o, const Variant& v) {
for (size_t i = 0; i < o.nanswers; i++)
if (sc.slot_of[i] && sc.type[sc.slot_of[i]] != v.canon[i]) return false;
return true;
};
auto full_pick = [&](Scene& sc, Object& o) { // (program_for past its pair)
if (!o.kept || !valid(sc, o, *o.kept)) {
o.kept = nullptr;
for (Variant* v : o.variants)
if (!o.kept && valid(sc, o, *v)) o.kept = v;
if (!o.kept) {
Variant* v = new Variant;
for (size_t i = 0; i < o.nanswers; i++) v->canon.push_back(sc.slot_of[i] ? sc.type[sc.slot_of[i]] : 1);
o.variants.push_back(v), o.kept = v;
}
}
return o.kept;
};
auto wide = [&](Scene& sc, Table& t, Object& o, Counts& c) -> const Variant* { // (program_for_wide, RX_VK_PICK_WIDE unset)
const Now now = sc.s.now();
auto walk = [&](Entry& e) {
return one_pass(e, o.nanswers, [&](size_t i) { return c.reads++, sc.slot_of[i]; },
[&](uint32_t id) { return sc.version[id]; }, [&](size_t i, uint32_t h) { return sc.type[h] == e.canon[i]; });
};
Entry* e = find(t, now);
if (e) {
const Variant* const p = static_cast<const Variant*>(e->p);
if (!e->walked) { // (noted at its last draw: its first pass)
e->canon = p->canon;
if (walk(*e)) return found(*e, now, o.amask), c.first++, p;
drop(*e), e = nullptr, c.unkept++;
} else if (stands(*e, now, all) != Stand::No) {
return c.memo++, p;
} else if (walk(*e)) {
return restamp(*e, now), c.by_pass++, p;
}
}
c.full++;
const Variant* const v = full_pick(sc, o);
note(e ? *e : place(t, now), now, v); // (nothing of it read here)
return v;
};
auto index_of = [](const Object& o, const Variant* v) {
for (size_t i = 0; i < o.variants.size(); i++)
if (o.variants[i] == v) return (int)i;
return -1;
};
std::mt19937 rng(8303);
std::vector<Object> olds, news; // (the same program objects in the two worlds: each world's picks are its own)
for (int k = 0; k < 9; k++) olds.push_back({(uint64_t)(0x7000 + k * 13), (size_t)(k % 4), k % 3 == 2 ? kNotC2 : 1u << 1, {}, nullptr});
news = olds;
Scene sc;
for (uint32_t id = 0; id < 10; id++) sc.version[id] = 1, sc.type[id] = (uint8_t)(id % 3 ? 1 : 0x81);
Table t;
Counts c;
int differ = 0, unbound = 0;
for (int step = 0; step < 60000; step++) {
State& s = sc.s;
const unsigned what = rng() % 16;
if (what < 3) s.bind++; // (a buffer bound)
else if (what < 7) s.ub++; // (a uniform updated)
else if (what < 9) sc.slot_of[rng() % 4] = rng() % 10, s.tex_gen[1] = ++s.bind; // (a texture bound in stage 1, or none)
else if (what == 9) s.tex_gen[0] = ++s.bind; // (one in a stage no answer reads)
else if (what == 10) { const uint32_t id = rng() % 10; sc.version[id]++, sc.type[id] = (uint8_t)(rng() % 3 ? 1 : 0x81), s.reg++; }
const size_t k = rng() % olds.size();
s.serial = olds[k].serial, s.sig = olds[k].serial * 3;
for (size_t i = 0; i < olds[k].nanswers; i++) unbound += sc.slot_of[i] == 0;
const Variant* const mine = wide(sc, t, news[k], c); // (before the old world's pick: neither sees the other's)
const Variant* const theirs = full_pick(sc, olds[k]);
const int a = index_of(news[k], mine), b = index_of(olds[k], theirs);
differ += a < 0 || a != b || mine->canon != theirs->canon || !valid(sc, news[k], *mine);
}
want("the memo's variant is the full pick's, and of the bound textures' types, at every draw of 60000", differ == 0);
want("with answers unbound among them (more than one variant can be valid)", unbound > 1000);
want("and most draws never reach the full pick", c.memo > 10000 && c.by_pass > 5000 && c.memo + c.by_pass + c.first > 50000 && c.full > 100);
want("a noted program is walked at its next draw, once", c.first > 50 && c.first + c.unkept <= c.full);
printf("model: %d by the memo, %d by one pass, %d by a first pass, %d full, %d noted and not kept\n", c.memo, c.by_pass, c.first,
c.full, c.unkept);
// programs drawn once before their entries are replaced: program_for's, and no answer read in the memo
std::vector<uint64_t> one_set;
for (uint64_t serial = 0x9000; one_set.size() < 3; serial++)
if (set_of(serial) == set_of(0x9000)) one_set.push_back(serial);
for (int n = 2; n <= 3; n++) {
std::vector<Object> o;
for (int k = 0; k < n; k++) o.push_back({one_set[k], 3, 1u << 1, {}, nullptr});
Scene still;
for (uint32_t id = 0; id < 10; id++) still.version[id] = 1, still.type[id] = 1;
Table tt;
Counts cc;
for (int draw = 0; draw < 300; draw++) {
Object& x = o[draw % n];
still.s.serial = x.serial, still.s.sig = x.serial * 3, still.s.ub++; // (a uniform updated before every draw)
wide(still, tt, x, cc);
}
if (n == 3)
want("three programs of one set in turn: every draw program_for's, and no answer read in the memo",
cc.full == 300 && cc.reads == 0 && cc.first == 0 && cc.memo == 0 && cc.by_pass == 0);
else
want("two in turn: each noted once, walked once at its second draw, then the memo's",
cc.full == 2 && cc.first == 2 && cc.reads == 6 && cc.memo == 296 && cc.by_pass == 0 && cc.unkept == 0);
}
{ // one program object drawn with three sets of vertex inputs in turn: the set is by the serial alone, so the three take
// its two ways in turn and none is answered by the memo (what pickwide.h says of it)
Object x{0x9100, 3, 1u << 1, {}, nullptr};
Scene still;
for (uint32_t id = 0; id < 10; id++) still.version[id] = 1, still.type[id] = 1;
Table tt;
Counts cc;
for (int draw = 0; draw < 300; draw++) {
still.s.serial = x.serial, still.s.sig = x.serial * 3, still.s.vattr[0] = (uint32_t)(draw % 3), still.s.ub++;
wide(still, tt, x, cc);
}
want("one program object with three sets of vertex inputs in turn: every draw program_for's",
cc.full == 300 && cc.memo == 0 && cc.first == 0 && cc.by_pass == 0);
}
}
if (fails) printf("pickwide: FAILED (%d of %d checks)\n", fails, checks);
else printf("pickwide: all %d checks passed\n", checks);
return fails != 0;
}
'''
# The hook itself (vk_shader.cpp's part from the counters to program_wide_stats, cut out by its text) over stubs of what it
# reads of the stamp's side, run with RX_VK_PICK_WIDE=check: what reaches the frame line's totals, and when
HOOK_STUBS = r'''
#include <atomic>
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <thread>
#include <vector>
#include "lab_ab.h"
#include "pickwide.h"
namespace mkwvk {
constexpr int kNvnStages = 8;
inline constexpr int kProgramWideStats = 10;
enum class ProgramKind { Graphics, Compute, Mesh };
struct ProgramObject { uint64_t serial = 1; };
struct NvnState {
bool has_prog = true;
ProgramObject prog;
uint64_t bind_gen = 100;
int nvattr = 2;
uint32_t vattr[16]{};
uint64_t tex_gen[kNvnStages]{};
};
struct Program {
struct Answer { uint8_t type; bool image; int at; };
std::atomic<bool> ready{true};
bool failed = false;
std::vector<Answer> answers;
uint64_t key = 0, variant = 0;
};
// (the world: an answer's handle, a slot's type, program_for's program, the last line logged)
uint32_t handle_of[4];
uint8_t type_of[16];
const Program* full_pick;
char last_log[512];
uint64_t prog_stage_sig(const ProgramObject& p) { return p.serial * 3; }
uint64_t registrations_generation() { return 5; }
uint64_t ub_generation() { return 9; }
uint32_t answer_stage_mask(const Program&) { return 1u << 1; }
uint32_t answer_handle(const NvnState&, const Program&, const Program::Answer& a) { return handle_of[a.at]; }
uint32_t texture_slot_version(int) { return 1; }
uint8_t answer_of(uint32_t handle, bool) { return type_of[handle & 15]; }
uint8_t canonical_answer(const Program&, const Program::Answer&, uint8_t type) { return type; }
const Program* program_for(const NvnState&, ProgramKind, const uint8_t*) { return full_pick; }
void logf(const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
vsnprintf(last_log, sizeof last_log, fmt, ap);
va_end(ap);
}
} // namespace mkwvk
'''
HOOK_MAIN = r'''
using namespace mkwvk;
static int checks, fails;
static void want(const char* what, bool ok) {
checks++;
if (!ok) fails++, printf("FAIL %s\n", what);
}
struct Totals { // (what the frame line reads)
int64_t n[kProgramWideStats];
Totals() { program_wide_stats(n); }
int64_t since(const Totals& was, int k) const { return n[k] - was.n[k]; }
};
int main() {
std::strcpy(lab_ab::knobs[0].name, "nopickwide");
lab_ab::n_knobs = 1;
Program p1, p2, p3;
for (Program* p : {&p1, &p2, &p3}) p->answers = {{1, false, 0}}, p->key = 0x77; // (one answer, a float texture's)
p1.variant = 1, p2.variant = 2, p3.variant = 3, p3.answers[0].type = 0x81;
handle_of[0] = 3, type_of[3] = 1;
const uint8_t ct[8] = {};
{ // a helper thread finds a difference and a wrong variant, then records nothing more (the tuner keeps to the replay
// thread, or the run ends): its counts are in the totals all the same, its compares with them
const Totals was;
const Program* got[5] = {};
std::thread([&] {
NvnState s;
full_pick = &p1;
got[0] = program_for_wide(s, ct); // (no entry: program_for's, noted)
got[1] = program_for_wide(s, ct); // (its first pass: kept; program_for's is the same)
full_pick = &p2;
got[2] = program_for_wide(s, ct); // (the memo's stands; program_for gives another variant, of the same types)
got[3] = program_for_wide(s, ct); // (that one noted in its place: its first pass, the same)
type_of[3] = 0x81, full_pick = &p3; // (an integer texture in the slot, no generation moved: what check mode is for)
got[4] = program_for_wide(s, ct); // (the memo's stands, and is not of the bound texture's type)
}).join();
const Totals now;
want("check mode draws program_for's at every draw", got[0] == &p1 && got[1] == &p1 && got[2] == &p2 && got[3] == &p2 && got[4] == &p3);
want("a thread's differences reach the totals at once", now.since(was, PW_DIFFER) == 2 && now.since(was, PW_WRONG) == 1);
want("and its compares with them", now.since(was, PW_COMPARED) == 4);
printf("hook: %lld compared, %lld differences, %lld not of the types\n", (long long)now.since(was, PW_COMPARED),
(long long)now.since(was, PW_DIFFER), (long long)now.since(was, PW_WRONG));
}
{ // a nopickwide phase begins: what the thread counted before it reaches the totals at its first pick in the phase
type_of[3] = 1, full_pick = &p1;
const Totals was;
std::thread([&] {
NvnState s;
s.prog.serial = 2;
for (int k = 0; k < 4; k++) program_for_wide(s, ct); // (noted, kept, the memo's twice: three compared, the same)
lab_ab::active.store(1);
program_for_wide(s, ct);
lab_ab::active.store(0);
}).join();
const Totals now;
want("a change of mode adds what the thread held", now.since(was, PW_COMPARED) == 3 && now.since(was, PW_FULL) == 1 &&
now.since(was, PW_DIFFER) == 0);
}
{ // program_for gives no program where the memo has one: the draw is left out, and the log says so
type_of[3] = 1;
const Totals was;
std::thread([&] {
NvnState s;
s.prog.serial = 3;
full_pick = &p1;
program_for_wide(s, ct), program_for_wide(s, ct);
full_pick = nullptr;
want("no program from program_for: none drawn", program_for_wide(s, ct) == nullptr);
}).join();
const Totals now;
want("counted as a difference, not as a wrong variant", now.since(was, PW_DIFFER) == 1 && now.since(was, PW_WRONG) == 0);
want("logged as no program, not as one not ready", std::strstr(last_log, "no program") && !std::strstr(last_log, "not ready"));
}
if (fails) printf("pickwide hook: FAILED (%d of %d checks)\n", fails, checks);
else printf("pickwide hook: all %d checks passed\n", checks);
return fails != 0;
}
'''
def block(text, marker):
start = text.index(marker)
at = text.index("{", start) + 1
depth = 1
while depth:
depth += (text[at] == "{") - (text[at] == "}")
at += 1
return text[start:at]
def need(ok, why):
if not ok:
raise SystemExit("FAIL: " + why)
def ordered(text, parts, why):
last = 0
for p in parts:
k = text.find(p, last)
need(k >= 0, why + " (missing, or out of order: " + p + ")")
last = k + len(p)
def stamp_text(rel, data):
"""A file as the translation stamp takes it (nx2/build.py translation_text)"""
build = ROOT / "nx2" / "build.py"
tree = ast.parse(build.read_text(encoding="utf-8"), filename=str(build))
functions = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name in ("strip_comments", "translation_text")]
need(len(functions) == 2, "nx2/build.py: strip_comments and translation_text are not there to run")
ns = {"os": os, "hashlib": hashlib, "json": json, "__file__": str(build)}
exec(compile(ast.Module(body=functions, type_ignores=[]), str(build), "exec"), ns)
return ns["translation_text"](rel, data).decode("utf-8")
def check_source():
raw = (ROOT / "gpu/vk/vk_shader.cpp").read_bytes()
shader = raw.decode("utf-8").replace("\r\n", "\n")
# (outside the translation stamp: between the last "Outside" mark and its "Inside again", and nothing of it in the stamp's text)
at = shader.find("const Program* program_for_wide(const NvnState& s, const uint8_t color_types[8]) {")
need(at >= 0, "vk_shader.cpp: program_for_wide is missing")
need(shader.rfind(OUT_MARK, 0, at) > shader.rfind(IN_MARK, 0, at) and shader.find(IN_MARK, at) > 0,
"vk_shader.cpp: program_for_wide is inside the translation stamp: every player's program and pipeline caches would start again")
stamped = stamp_text("vk_shader.cpp", raw)
for name in ("pickwide", "program_for_wide", "program_wide_stats", "pw_", "RX_VK_PICK_WIDE", "lab_ab"):
need(name not in stamped, "vk_shader.cpp: the translation stamp's text names %s" % name)
need("const Program* program_for(const NvnState& s, ProgramKind kind, const uint8_t color_types[8]) {" in stamped and
"thread_local ProgFast prog_fast[2];" in stamped and "if (still_valid(s, *pk.p)) {" in stamped,
"vk_shader.cpp: program_for, its pair and its two walks are no longer what RX_VK_PICK_WIDE=0 goes back to")
part = shader[shader.rfind(OUT_MARK, 0, at):shader.find(IN_MARK, at)]
need('#include "pickwide.h"' in part and '#include "lab_ab.h"' in part, "vk_shader.cpp: pickwide.h and lab_ab.h are not included outside the stamp")
mode = block(part, "pickwide::Mode pw_mode() {")
need('static const pickwide::Mode env = [] {' in mode and 'pickwide::mode(getenv("RX_VK_PICK_WIDE"))' in mode and
'return pickwide::in_phase(env, lab_ab::on("nopickwide"));' in mode and "logf(" in mode and "if (m != pickwide::Mode::On)" in mode,
"the switch is not RX_VK_PICK_WIDE read once and logged when not the default, with the lab's nopickwide knob")
walk = block(part, "bool pw_pass(")
need("pickwide::one_pass(" in walk and "answer_handle(s, p, p.answers[i])" in walk and "texture_slot_version((int)id)" in walk and
"canonical_answer(p, a, answer_of(h, a.image)) == e.canon[i]" in walk and walk.count("answer_handle(") == 1,
"pw_pass does not read each answer's handle once and compare canonical types, as still_valid does")
canon = block(part, "void pw_canon(")
need("e.canon[i] = canonical_answer(p, p.answers[i], p.answers[i].type);" in canon and "e.canon.resize(p.answers.size());" in canon,
"pw_canon does not keep the variant's own types canonical, as still_valid compares them")
wide = block(part, "const Program* program_for_wide(")
need('pickwide::rules(getenv("RX_VK_PICK_BIND_GEN") != nullptr, getenv("RX_VK_DEFERRED_LATE") != nullptr)' in wide,
"RX_VK_PICK_BIND_GEN and RX_VK_DEFERRED_LATE do not keep ub_generation in the rule")
need("static_assert(pickwide::kStages == kNvnStages" in wide, "the header's stages are not asserted to be NvnState's")
ordered(wide, ["const pickwide::Mode mode = pw_mode();",
"if (mode == pickwide::Mode::Off || !s.has_prog) return program_for(s, ProgramKind::Graphics, color_types);",
"const pickwide::Now now{s.prog.serial, prog_stage_sig(s.prog), s.bind_gen, registrations_generation(), ub_generation(), s.nvattr,",
"s.vattr, color_types, s.tex_gen};",
"pickwide::find(t, now)",
"if (!p->ready.load(std::memory_order_acquire) || p->failed) {",
"} else if (!e->walked) {",
"pw_canon(*p, *e);",
"const bool ok = pw_pass(s, *p, *e, &w);",
"if (ok) pickwide::found(*e, now, answer_stage_mask(*p)), mine = p,",
"else pickwide::drop(*e), e = nullptr, pw_mine[PW_UNKEPT]++;",
"pickwide::stands(*e, now, rules)",
"pw_pass(s, *p, *e, &w)", "pickwide::restamp(*e, now)",
"if (mine && mode == pickwide::Mode::On) return mine;",
"const Program* const full = program_for(s, ProgramKind::Graphics, color_types);",
"if (full && full->ready.load(std::memory_order_acquire) && !full->failed) {",
"pickwide::note(e ? *e : pickwide::place(t, now), now, full);",
"return full;"],
"program_for_wide does not ask the memo, then one pass, then program_for, and keep only a program a pass found valid")
# (a draw that went to program_for only notes its program: the pass, the mask and the canonical types are its next draw's.
# Walked where it is picked, a program drawn once before its entry is replaced pays a third walk on top of the full pick's two)
tail = wide[wide.index("const Program* const full = program_for("):]
noted = tail[tail.index("if (full && full->ready.load(std::memory_order_acquire) && !full->failed) {"):]
need("pw_pass(" not in noted and "pw_canon(" not in noted and "answer_stage_mask(" not in noted and "pickwide::take(" not in wide,
"program_for_wide walks a program where program_for picked it: the miss path is dearer than the pick it stands in front of")
need(wide.count("answer_stage_mask(") == 1 and wide.count("pw_pass(") == 3 and tail.count("pw_pass(") == 1,
"program_for_wide: the passes are no longer a noted entry's first, a kept entry's, and check mode's probe")
rule = (ROOT / "gpu/vk/pickwide.h").read_text(encoding="utf-8").replace("\r\n", "\n")
need("if (!same_inputs(e, n) || !e.walked || e.reg != n.reg) return Stand::No;" in rule,
"pickwide.h: a program only noted stands without a pass ever having found it of the bound textures' types")
need(wide.count("return mine;") == 1 and wide.count("program_for(s, ProgramKind::Graphics, color_types)") == 2,
"program_for_wide returns the memo's program somewhere else than in the mode that is on (check mode draws program_for's)")
need("pickwide::clear(" in wide and "pw_mode_was" in wide, "a thread's memo is not cleared when the mode changes (a lab phase)")
header = (ROOT / "gpu/vk/vk_shader.h").read_text(encoding="utf-8")
need("const Program* program_for_wide(const NvnState& s, const uint8_t color_types[8]);" in header, "vk_shader.h does not declare program_for_wide")
draw = (ROOT / "gpu/vk/vk_draw.cpp").read_text(encoding="utf-8").replace("\r\n", "\n")
body = block(draw, "void draw(VkCommandBuffer cmd, NvnState& s, const DrawArgs& d) {")
ordered(body, ["PROF_HOT(PROF_PROGRAM);", "if (d.mesh) cp = program_for(s, ProgramKind::Mesh, types);", "else cp = program_for_wide(s, types);"],
"draw() does not ask the wide memo for its graphics program")
dry = block(draw, "uint64_t dry_draw_program(void* ctx) {")
need("q.mesh ? program_for(*q.s, ProgramKind::Mesh, types) : program_for_wide(*q.s, types)" in dry,
"the dry pass picks its graphics programs past the memo: the picks' kept programs would move behind it")
need(draw.count("program_for_wide(") == 2, "the memo is asked somewhere else than draw()'s and the dry pass's graphics picks")
replay = (ROOT / "gpu/vk/vk_replay.cpp").read_text(encoding="utf-8").replace("\r\n", "\n")
need("program_wide_stats(" in replay and "program picks by the wide memo" in replay and "past a uniform update" in replay and
"a noted program's first" in replay and "RX_VK_PICK_WIDE=check" in replay, "vk_replay.cpp: the status line does not count the memo's picks and check mode's differences")
line = replay[replay.index("program_wide_stats(pw);"):]
line = line[:line.index("std::memcpy(l_pw, pw, sizeof l_pw);")]
need("if (pw[6] || pw[7])" in line, "vk_replay.cpp: check mode's totals are shown only once a compare reached them, not at a difference")
docs = (ROOT / "docs/development.md").read_text(encoding="utf-8")
row = [l for l in docs.splitlines() if l.startswith("| `RX_VK_PICK_WIDE=0` or `check`")]
need(len(row) == 1 and "`gpu/vk/pickwide.h`" in row[0] and "`nopickwide`" in row[0] and "program picks by the wide memo" in row[0] and
"only noted" in row[0],
"docs/development.md: the switches table has no RX_VK_PICK_WIDE row with its knob and its counter line")
def hook_source():
"""The hook's part of vk_shader.cpp, from its counters to program_wide_stats, over HOOK_STUBS"""
shader = (ROOT / "gpu/vk/vk_shader.cpp").read_text(encoding="utf-8").replace("\r\n", "\n")
at = shader.index("const Program* program_for_wide(const NvnState& s, const uint8_t color_types[8]) {")
part = shader[shader.rfind(OUT_MARK, 0, at):shader.find(IN_MARK, at)]
start = part.rindex("namespace {", 0, part.index("enum PwCount"))
return HOOK_STUBS + "namespace mkwvk {\n" + part[start:] + "} // namespace mkwvk\n" + HOOK_MAIN
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--cxx", default="clang++")
args = parser.parse_args()
need((ROOT / "gpu/vk/pickwide.h").is_file(), "gpu/vk/pickwide.h is missing (the wide memo's rule)")
with tempfile.TemporaryDirectory(prefix="pickwide-") as tmp:
cpp, exe = Path(tmp) / "pickwide_test.cpp", Path(tmp) / "pickwide.exe"
cpp.write_text(DRIVER, encoding="utf-8")
subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-I" + str(ROOT / "gpu/vk"), str(cpp), "-o", str(exe)],
check=True)
r = subprocess.run([str(exe)], capture_output=True, text=True)
print(r.stdout.rstrip())
if r.returncode:
raise SystemExit("FAIL: the wide memo's checks failed")
cpp, exe = Path(tmp) / "pickwide_hook.cpp", Path(tmp) / "pickwide_hook.exe"
cpp.write_text(hook_source(), encoding="utf-8")
subprocess.run([args.cxx, "-std=c++20", "-O1", "-pthread", "-Wall", "-Wextra", "-Werror", "-I" + str(ROOT / "gpu/vk"), str(cpp),
"-o", str(exe)], check=True)
r = subprocess.run([str(exe)], capture_output=True, text=True, env=dict(os.environ, RX_VK_PICK_WIDE="check"))
print(r.stdout.rstrip())
if r.returncode:
raise SystemExit("FAIL: the hook's checks failed")
check_source()
print("PASS: a draw's program comes from the wide memo in front of program_for, outside the translation stamp; RX_VK_PICK_WIDE=0 as before")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,203 @@
// tests/test_readback_rec_end.py: gpu/vk/wb_rec_wait.h's readback wait (Parts, readback_wait, rec_end_on) against a made-up GPU.
// A recording made in parts writes back at each part's end, under its one value; a readback waits for that value on the
// recordings' timeline. The old wait named the first part; the rule waits for the last.
#include "../gpu/vk/wb_rec_wait.h"
#include <cstdint>
#include <cstdio>
#include <random>
#include <vector>
#define CHECK(name, condition) do { if (!(condition)) { std::fprintf(stderr, "FAIL %s at line %d\n", name, __LINE__); return 1; } } while (0)
namespace wr = mkwvk::wb_rec_wait;
// One recording of value V made in parts while a readback waits: parts[i] is part i's number on the recordings' timeline, the last
// one ends the recording. `sent` parts are submitted when the read comes; the replay submits the next one each time the reader
// waits, flushes or slices, `step` parts at a time (0: the replay is stuck, the recording never ends). The GPU runs every part
// submitted, so a wait for a submitted part comes back with it done; a wait for one never submitted is a hang (counted).
struct Gpu {
uint64_t value = 100;
std::vector<uint64_t> parts;
size_t sent = 1;
int step = 1;
uint64_t rec_done = 0; // (the recordings' timeline)
bool timeline_at_v = false; // (the submissions' timeline at the value: only once the recording's last part is done)
int timeline_after = -1; // (slices until the submissions' timeline reaches the value with the recording stuck; -1 never)
int rec_wait_error_at = -1; // (the n-th recording wait gives an error)
int rec_waits = 0, flushes = 0, slices = 0, hangs = 0;
wr::Parts table;
uint64_t first_noted = 0; // (value_rec: the first part, emplace)
void submit_up_to(size_t n) {
for (; sent < n && sent < parts.size(); sent++) note(sent);
}
void note(size_t i) {
table.submitted(value, parts[i], i + 1 == parts.size());
if (!first_noted) first_noted = parts[i];
}
void begin() {
for (size_t i = 0; i < sent; i++) note(i);
}
void replay_goes_on() { submit_up_to(sent + (size_t)step); }
bool ended() const { return sent == parts.size(); }
// the calls readback_wait makes
uint64_t first_part() { return first_noted; }
wr::Parts::Entry look() { return table.of(value); }
int rec_wait(uint64_t seq) {
rec_waits++;
if (rec_wait_error_at >= 0 && rec_waits > rec_wait_error_at) return 2;
if (seq > parts[sent - 1]) { // (never submitted: the wait would never come back)
hangs++;
return 2;
}
if (seq > rec_done) rec_done = seq;
if (ended() && rec_done >= parts.back()) timeline_at_v = true;
replay_goes_on();
return 0;
}
void flush() {
flushes++;
replay_goes_on();
}
int slice() {
slices++;
if (timeline_after >= 0 && slices >= timeline_after) { // (the replay ended it and the GPU ran it meanwhile)
submit_up_to(parts.size());
rec_done = parts.back();
timeline_at_v = true;
}
if (timeline_at_v) return 0;
replay_goes_on();
return 1;
}
};
int main() {
// the switch: on unset or empty; set, it is its number (atoi, as the renderer's other switches: a word reads as 0, off)
CHECK("unset: on", wr::rec_end_on(nullptr));
CHECK("empty: on", wr::rec_end_on(""));
CHECK("0: off", !wr::rec_end_on("0"));
CHECK("00: off", !wr::rec_end_on("00"));
CHECK("1: on", wr::rec_end_on("1"));
CHECK("2: on", wr::rec_end_on("2"));
CHECK("a word: off", !wr::rec_end_on("off"));
// 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
wr::Parts t;
CHECK("not known", t.of(7).seq == 0 && !t.of(7).ended);
t.submitted(7, 10, false);
CHECK("a part", t.of(7).seq == 10 && !t.of(7).ended);
t.submitted(7, 11, false), t.submitted(7, 12, true);
CHECK("its end", t.of(7).seq == 12 && t.of(7).ended);
t.submitted(7, 11, false);
CHECK("an older note after a newer one: nothing", t.of(7).seq == 12 && t.of(7).ended);
t.submitted(7, 20, false);
CHECK("a later recording under the value: from its first part, going on", t.of(7).seq == 20 && !t.of(7).ended);
t.submitted(0, 30, true), t.submitted(8, 0, true);
CHECK("no value or no number: nothing noted", t.by_value.size() == 1);
t.cap = 3;
for (uint64_t v = 40; v < 44; v++) t.submitted(v, 100 + v, true);
CHECK("cap held", t.by_value.size() == 3 && t.of(7).seq == 0 && t.of(40).seq == 0 && t.of(43).seq == 143);
// the meter's case: a recording in three parts (10, 11, 12), the read after the first one's submit. The old wait stops at
// the first part, with the last two (and the write-back they make) still to come: the read got the CPU's 0
{
Gpu g;
g.parts = {10, 11, 12};
g.begin();
const wr::ReadbackWait r = wr::readback_wait(false, g);
CHECK("old: known", r.known && r.ok);
CHECK("old: ends at the first part, before the last", g.rec_done == 10 && g.rec_done < g.parts.back());
}
{
Gpu g;
g.parts = {10, 11, 12};
g.begin();
const wr::ReadbackWait r = wr::readback_wait(true, g);
CHECK("rule: known and done", r.known && r.ok);
CHECK("rule: its recording went on past the part first found", r.went_on);
CHECK("rule: ends with the last part done", g.rec_done == 12);
CHECK("rule: no wait for a part never submitted", g.hangs == 0);
}
// an ended recording: its last part, one wait, as the old wait's one
{
Gpu g;
g.parts = {10, 11, 12};
g.sent = 3;
g.begin();
const wr::ReadbackWait r = wr::readback_wait(true, g);
CHECK("ended: one wait for the last part", r.known && r.ok && !r.went_on && g.rec_waits == 1 && g.rec_done == 12 && g.slices == 0);
}
// a recording in one part: the same as the old wait
{
Gpu g;
g.parts = {10};
g.begin();
const wr::ReadbackWait r = wr::readback_wait(true, g);
CHECK("one part: one wait", r.known && r.ok && !r.went_on && g.rec_waits == 1 && g.rec_done == 10);
}
// not known at all (not recorded yet): the caller's fallback, nothing waited
{
Gpu g;
g.parts = {10, 11};
const wr::ReadbackWait r = wr::readback_wait(true, g);
const wr::ReadbackWait r0 = wr::readback_wait(false, g);
CHECK("not known: the fallback's", !r.known && !r0.known && g.rec_waits == 0 && g.slices == 0);
}
// the replay stuck with the recording going on: slices of the submissions' timeline, ended once it reaches the value
{
Gpu g;
g.parts = {10, 11, 12};
g.step = 0;
g.timeline_after = 5;
g.begin();
const wr::ReadbackWait r = wr::readback_wait(true, g);
CHECK("stuck: ended by the timeline", r.known && r.ok && r.went_on && r.slices == 5 && g.timeline_at_v);
}
// an error (a lost device) ends the wait, not done
{
Gpu g;
g.parts = {10, 11, 12};
g.rec_wait_error_at = 1;
g.begin();
const wr::ReadbackWait r = wr::readback_wait(true, g);
CHECK("error: not done", r.known && !r.ok && g.rec_waits == 2);
}
// 20,000 random recordings: 1 to 8 parts, the read after 1 to all of them are submitted, the replay going on 0 to 3 parts at
// each call (0: stuck, the timeline reaching the value after some slices). The rule never ends before the last part is done
// (or the timeline at the value), never waits for a part not submitted, and never takes more waits than parts plus one; the
// old wait ends at the first part whenever the read came before the recording ended
std::mt19937_64 rng(20261127);
int old_early = 0, cases_going_on = 0;
for (int k = 0; k < 20000; k++) {
Gpu g, g0;
const size_t n = 1 + rng() % 8;
uint64_t s = 1000 + (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);
g0 = g;
g.begin(), g0.begin();
const bool going_on = g.sent < n;
cases_going_on += going_on;
const wr::ReadbackWait r = wr::readback_wait(true, g);
CHECK("random: known and done", r.known && r.ok);
CHECK("random: never before the last part is done", g.rec_done == g.parts.back() || g.timeline_at_v);
CHECK("random: never a wait for a part not submitted", g.hangs == 0);
CHECK("random: went on exactly when the read came before the end", r.went_on == going_on);
CHECK("random: waits bounded", g.rec_waits <= (int)n + 1);
const wr::ReadbackWait r0 = wr::readback_wait(false, g0);
CHECK("random old: known", r0.known && r0.ok && g0.rec_waits == 1);
if (going_on && g0.rec_done < g0.parts.back()) old_early++;
}
CHECK("random: the reads before a recording's end were many", cases_going_on > 10000);
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);
return 0;
}

View File

@@ -0,0 +1,136 @@
"""A readback waits for the LAST part of the recording that writes it back (gpu/vk/wb_rec_wait.h readback_wait, vk_replay.cpp
readback_rec_wait and invalidate; RX_VK_RB_REC_END). No game, no GPU.
The owner's random brightness changes (11-27): in a still view the picture flashed brighter for a frame and stepped down, a few
times a minute, on v0.8.4 as on the GPU pass. Each flash came one present after the game read its exposure meter back as all
zeros after a wait for its write-back, with the GPU's done value still below the write-back's value. A recording made in parts
writes back at each part's end, all under the recording's one value; the readback's wait looked that value up in value_rec, which
keeps the FIRST part. A read between the first part's submit and the last one's came back with the CPU's 0, the GPU's sum still
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:
- 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
submissions' timeline 1 ms at a time;
- invalidate's two waits by recordings (the submitting thread's and the replay thread's) take the rule, the old wait kept for =0;
- the zero diagnostic says the writer's recording's parts, the 3000-readback line counts the reads that waited past a part, and
the switch is in the development guide;
- invalidate and submit_recording's registration gain calls only, no if, ?: or !: the renderer's play profile matches a function
by a hash of its control flow, and the first form of this change left both at plain -O2 (invalidate is called ~460,000 times
in a benchmark run). The branches are in readback_recorded_wait, readback_zero_line, readback_went_on_line and Parts.
python -I -B tests/test_readback_rec_end.py [--cxx g++]
"""
import argparse
import subprocess
import tempfile
from pathlib import Path
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
ROOT = Path(__file__).resolve().parents[1]
def check(ok, what):
if not ok:
raise SystemExit("FAIL: " + what)
def function(text, head):
at = text.index(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():
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) {",
"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)
replay = (ROOT / "gpu/vk/vk_replay.cpp").read_text(encoding="utf-8")
check("::mkwvk::wb_rec_wait::Parts rec_parts_by_value;" in replay, "vk_replay.cpp: the recordings' parts table is missing")
sub = function(replay, "void submit_recording(")
reg = sub[sub.index("const auto register_recording = [&] {"):]
reg = reg[:reg.index("\n };\n")]
# (a call with part as it is: a `!` here would change the registration's control-flow hash and lose its profile)
in_order(reg, ["std::lock_guard mk(rec_map_mu);", "rec_parts_by_value.part_submitted(r.value, seq, part);"],
"submit_recording's registration (every part and the end, by the recording's value, under the lock)")
check(replay.count("rec_parts_by_value.part_submitted(") == 1 and "rec_parts_by_value.submitted(" not in replay,
"vk_replay.cpp: the parts are noted somewhere past the registration")
on = function(replay, "bool rb_rec_end_on() {")
check('::mkwvk::wb_rec_wait::rec_end_on(getenv("RX_VK_RB_REC_END"))' in on and "static const bool v" in on,
"RX_VK_RB_REC_END is not read once through the header's rule")
w = function(replay, "bool readback_rec_wait(uint64_t v, int* ok) {")
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"),
("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"),
("const VkResult res = vkWaitSemaphores(dev.device, &wi, ::mkwvk::wb_rec_wait::kSliceNs);",
"the slices are not 1 ms waits on the submissions' timeline"),
("st_rb_went_on.fetch_add(1, std::memory_order_relaxed)", "the reads that waited past a part are not counted")):
check(needle in w, "vk_replay.cpp readback_rec_wait: " + why)
check(w.count("std::lock_guard mk(rec_map_mu);") == 2, "readback_rec_wait reads a table without rec_map_mu")
rw = w[w.index("int rec_wait(uint64_t seq) {"):]
rw = rw[:rw.index("\n }\n")]
check(0 <= rw.index("queue_flush_for(FR_WAIT);") < rw.index("vkWaitSemaphores("),
"readback_rec_wait waits on the recordings' timeline before it flushes the held submits: a batched signal never comes")
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, int* ok) {")
check("return rb_rec_end_on() ? readback_rec_wait(v, 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)")
inv = function(replay, "void invalidate(uint64_t gpu, uint64_t size) {")
check(inv.count("readback_recorded_wait(v, &ok)") == 2, "invalidate's two waits by recordings do not both take the rule")
check("if (!(unforced && readback_recorded_wait(v, &ok))) {" in inv, "the submitting thread's wait does not take the rule")
check("while (completed() < v && !readback_recorded_wait(v, &ok) && async_wait_step(v)) {}" in inv,
"the replay thread's wait does not take the rule")
for needle in ("readback_rec_wait(", "wait_recorded(", "rb_rec_end_on(", "rec_parts_by_value", "st_rb_went_on"):
check(needle not in inv, "invalidate holds %s itself: its branches change invalidate's control-flow hash, and the "
"renderer's play profile no longer matches it (keep them in the helpers)" % needle)
check("readback_zero_line((long long)presents_now, gpu, size, f0, v, (int)behind0, (int)w);" in inv,
"the zero diagnostic is not readback_zero_line")
check("readback_went_on_line();" in inv[inv.index("if (++calls % 3000 == 0) {"):], "the 3000-readback line does not call readback_went_on_line")
zl = function(replay, "void readback_zero_line(")
check("its recording's first part %llu, newest %llu%s" in zl and "e = rec_parts_by_value.of(v);" in zl
and "std::lock_guard mk(rec_map_mu);" in zl, "the zero diagnostic does not say the writer's recording's parts")
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")
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")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cxx", default="g++")
args = parser.parse_args()
check_source()
with tempfile.TemporaryDirectory(prefix="readback-rec-end-") as tmp:
exe = Path(tmp) / "readback-rec-end"
subprocess.run([args.cxx, "-std=c++20", "-Wall", "-Wextra", "-Werror",
str(ROOT / "tests/test_readback_rec_end.cpp"), "-o", str(exe)], check=True)
subprocess.run([str(exe)], check=True)
print("PASS: a readback waits for the last part of the recording that writes it back")
if __name__ == "__main__":
main()

View File

@@ -25,9 +25,20 @@ def main():
flush = wait.find("queue_flush_for(")
if flush < 0 or flush > wait.index("vkWaitSemaphores("):
raise SystemExit("wait_recorded waits without sending the held batch: a batched recording's signal never comes")
if "wait_recorded(v, UINT64_MAX, &ok)" not in body(replay, "void invalidate(uint64_t gpu, uint64_t size) {"):
# ((Triforce, 11-27) invalidate reaches it through readback_recorded_wait, kept out of invalidate for its renderer profile)
inv = body(replay, "void invalidate(uint64_t gpu, uint64_t size) {")
rrw = body(replay, "bool readback_recorded_wait(uint64_t v, int* ok) {")
if "readback_recorded_wait(v, &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")
print("PASS: wait_recorded sends the held batch before it waits")
# ((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, int* ok) {")
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, ok)" 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")
if __name__ == "__main__":

View File

@@ -104,7 +104,9 @@ C_COMMENT_OR_STRING = re.compile(r'//[^\n]*|/\*.*?\*/|"(?:\\.|[^"\\\n])*"|\'(?:\
UI_RECORD_CALL = re.compile(r"\bui\s*::\s*record(?:_to)?\s*\(")
NGX_RECORD_CALL = re.compile(r"\bNGX_VULKAN_\w+_EXT\s*\(") # (NVIDIA NGX's create/evaluate: its own commands into cmd)
FFX_RECORD_CALL = re.compile(r"\bl\s*\.\s*dispatch\s*\(") # (AMD FidelityFX's ffxDispatch, through its loaded pointer: its own commands into cmd)
OPAQUE_RECORD_CALL = re.compile(UI_RECORD_CALL.pattern + "|" + NGX_RECORD_CALL.pattern + "|" + FFX_RECORD_CALL.pattern)
XESS_RECORD_CALL = re.compile(r"\bl\s*\.\s*execute\s*\(") # (Intel XeSS's xessVKExecute, through its loaded pointer: its own commands into cmd)
OPAQUE_RECORD_CALL = re.compile(UI_RECORD_CALL.pattern + "|" + NGX_RECORD_CALL.pattern + "|" + FFX_RECORD_CALL.pattern + "|" +
XESS_RECORD_CALL.pattern)
B_DIRECT_BEFORE = re.compile(r"::\s*mkwvk\s*::\s*rec\s*::\s*boundary\s*\(\s*::\s*mkwvk\s*::\s*rec\s*::\s*B_DIRECT\s*\)\s*;\Z")
@@ -155,6 +157,17 @@ def check_sources():
% (sorted(set(macros) - set(calls)), sorted(set(calls) - set(macros))))
for f, body in macros.items():
# ((Triforce, P4) the commands that do GPU work pass their arguments through RX_WORK_ON, which counts the command buffer)
# ((Triforce, 11-26, C15) a push and a bind are told to capturepushkeep.h first, in capture_keep_vk's wrappers, which
# call the packer's route with the same arguments, each evaluated once)
kept = {"vkCmdPushConstants": "push", "vkCmdBindPipeline": "bind"}.get(f)
if kept and body.strip() == "(::mkwvk::capture_keep_vk::%s(__VA_ARGS__))" % kept:
wrapper = work[work.index("inline void %s(VkCommandBuffer cmd" % kept):]
wrapper = wrapper[:wrapper.index("\n}\n")]
if "::mkwvk::rec::rx_%s(cmd, " % f not in wrapper:
problems.append("vk_work.h: %s's wrapper does not call its packer" % f)
if "::vkx::" in wrapper:
problems.append("vk_work.h: %s's wrapper calls the driver directly" % f)
continue
if "::mkwvk::rec::rx_%s(__VA_ARGS__)" % f not in body and "::mkwvk::rec::rx_%s(RX_WORK_ON(__VA_ARGS__))" % f not in body:
problems.append("vk_work.h: %s does not call its packer: %s" % (f, body))
if "::vkx::" in body:
@@ -254,6 +267,13 @@ def check_sources():
problems.append("vk_fsr4.cpp: no ffxDispatch call (l.dispatch) found: update FFX_RECORD_CALL")
elif not direct_unbounded(fsr4.replace(B_DIRECT_STMT, "", 1), "vk_fsr4.cpp", FFX_RECORD_CALL):
problems.append("the B_DIRECT check missed an ffxDispatch recording without its boundary")
# (Intel XeSS records into cmd through xessVKExecute: after a B_DIRECT boundary; control: that boundary removed)
xess = (VK / "vk_xess.cpp").read_text(encoding="utf-8")
problems += direct_unbounded(xess, "vk_xess.cpp", XESS_RECORD_CALL)
if not XESS_RECORD_CALL.search(blank_comments(xess)):
problems.append("vk_xess.cpp: no xessVKExecute call (l.execute) found: update XESS_RECORD_CALL")
elif not direct_unbounded(xess.replace(B_DIRECT_STMT, "", 1), "vk_xess.cpp", XESS_RECORD_CALL):
problems.append("the B_DIRECT check missed an xessVKExecute recording without its boundary")
# (and any other recording vk_work.h does not see must be registered: every hand-written note_work() follows a known one)
for path in sorted(VK.glob("*.cpp")):
problems += opaque_unregistered(path.read_text(encoding="utf-8"), path.name)
@@ -289,6 +309,8 @@ def build(cxx, headers, out, recorder_text, name, extra=(), work_text=None):
(d / h).write_text((VK / h).read_text(encoding="utf-8"), encoding="utf-8")
(d / "lock_census.h").write_text((VK / "lock_census.h").read_text(encoding="utf-8"), encoding="utf-8") # ((Triforce, THREAD-68) vk_recorder.h's)
(d / "new_wait.h").write_text((VK / "new_wait.h").read_text(encoding="utf-8"), encoding="utf-8") # ((Triforce, OS-04) vk_recorder.h's)
# ((Triforce, 11-26, C15) vk_recorder.h's and cmd_work.h's: the capture push a command buffer holds)
(d / "capturepushkeep.h").write_text((VK / "capturepushkeep.h").read_text(encoding="utf-8"), encoding="utf-8")
(d / "vk_recorder.h").write_text(recorder_text, encoding="utf-8")
exe = d / "recorder_sync_test.exe"
cmd = [cxx, "-std=c++20", "-O2", "-Wall", "-Wextra", "-Werror", "-Wno-unused-function", "-Wno-missing-field-initializers", "-DVK_NO_PROTOTYPES",
@@ -382,6 +404,8 @@ def exit_test(cxx, headers, out, recorder_text, name):
(d / h).write_text((VK / h).read_text(encoding="utf-8"), encoding="utf-8")
(d / "lock_census.h").write_text((VK / "lock_census.h").read_text(encoding="utf-8"), encoding="utf-8") # ((Triforce, THREAD-68) vk_recorder.h's)
(d / "new_wait.h").write_text((VK / "new_wait.h").read_text(encoding="utf-8"), encoding="utf-8") # ((Triforce, OS-04) vk_recorder.h's)
# ((Triforce, 11-26, C15) vk_recorder.h's and cmd_work.h's: the capture push a command buffer holds)
(d / "capturepushkeep.h").write_text((VK / "capturepushkeep.h").read_text(encoding="utf-8"), encoding="utf-8")
(d / "vk_recorder.h").write_text(recorder_text, encoding="utf-8")
src = str(ROOT / "tests" / "recorder_exit_test.cpp")
flags = ["-std=c++20", "-O2", "-Wall", "-Wextra", "-Werror", "-DVK_NO_PROTOTYPES", "-D_CRT_SECURE_NO_WARNINGS"]
@@ -455,7 +479,7 @@ def main():
broken(rec, "c[i].pImageInfo = e.dup(w[i].pImageInfo, w[i].descriptorCount);",
"c[i].pImageInfo = w[i].pImageInfo;", "push descriptors"), work_h, ("sync", None)),
("fallback without the drain (order)",
broken(rec, " else drain();\n t_arena.fallbacks++;", " t_arena.fallbacks++;", "fallback"), work_h, ("sync", None)),
broken(rec, " else drain();\n t_arena().fallbacks++;", " t_arena().fallbacks++;", "fallback"), work_h, ("sync", None)),
("defer: no drain before vkEndCommandBuffer",
rec, no_wait(work_h, "vkEndCommandBuffer"), (None, None)),
("defer: the replay lock let go without a drain",

View File

@@ -38,11 +38,17 @@ def main():
#include <mutex>
#include <set>
#include <vector>
#include "cpuwordsseen.h"
struct Pool { uint64_t lo; };
struct VkBufferCopy { uint64_t srcOffset, dstOffset, size; };
std::mutex cpu_words_mu;
bool wb_notes_off() { return false; } // ((Triforce, 11-22, MEM-51) the mirrors are on here: tests/test_mirror_bookkeeping.py has the case without
std::vector<uint64_t> cpu_words, cpu_words_recent, cpu_words_new; // (the big and the recent sorted sets, and noted since: vk_memory.cpp)
// ((Triforce, 11-26) the table of the words the sets hold, on as by default: tests/test_cpuwordsseen.py has its cases. The
// cases here empty the sets by hand and tell the table (reset, check), so it never knows a word the sets do not hold; it
// does not hear of the words they put in by hand, so it only knows fewer words than the sets hold)
cpu_words_seen::Table cpu_words_table;
int cpu_words_seen_mode() { return cpu_words_seen::ON; }
#define CHECK(ok) do { if (!(ok)) { std::fprintf(stderr, "failed line %d\n", __LINE__); std::exit(1); } } while (0)
''' + helper + r'''
// after a merge: both sets sorted with no repeats, no word in both, nothing left noted, and together exactly the words in want
@@ -63,6 +69,7 @@ void reset() {
cpu_words.clear();
cpu_words_recent.clear();
cpu_words_new.clear();
cpu_words_table.forget(); // (the sets emptied by hand: the table forgets with them, as memory_cpu_owned's clear does)
}
// owned: words noted since the last merge; kept: words merged before (in the big set already)
void check(uint64_t start, uint64_t end, std::initializer_list<uint64_t> owned, std::initializer_list<uint64_t> kept = {}) {
@@ -70,6 +77,7 @@ void check(uint64_t start, uint64_t end, std::initializer_list<uint64_t> owned,
cpu_words.clear();
cpu_words_recent.clear();
cpu_words_new.clear();
cpu_words_table.forget();
std::set<uint64_t> owned_words;
for (uint64_t offset : kept) cpu_words.push_back(pool.lo + offset), owned_words.insert(pool.lo + offset);
std::sort(cpu_words.begin(), cpu_words.end());
@@ -197,7 +205,7 @@ int main() {
cpp = Path(tmp) / 'fixture.cpp'
exe = Path(tmp) / 'fixture.exe'
cpp.write_text(fixture, encoding='utf-8')
subprocess.run([args.cxx, '-std=c++20', '-Wall', '-Wextra', '-Werror', str(cpp), '-o', str(exe)], check=True)
subprocess.run([args.cxx, '-std=c++20', '-Wall', '-Wextra', '-Werror', '-I', str(ROOT / 'gpu' / 'vk'), str(cpp), '-o', str(exe)], check=True)
# (memory_cpu_owned does nothing with RX_VK_WB_REPORTS set: not from the caller's environment)
env = {k: v for k, v in os.environ.items() if k != 'RX_VK_WB_REPORTS'}
subprocess.run([str(exe)], check=True, env=env)

View File

@@ -80,6 +80,9 @@ void auto_row_set(const int*) {}
namespace mr { constexpr int kMax = 8; }
void restart_values(int*) {}
struct { void note(const int*) {} } restart_state;
/* ((Triforce, 11-26) the rows taken at Apply: their state told of a change, as the restart's */
void apply_values(int*) {}
struct { void note(const int*) {} } apply_state;
%(is_slider)s
%(stops)s
%(snap)s

View File

@@ -139,41 +139,52 @@ def check_sources():
"save_files.done(value);", "save_files.said(value);"):
check(line in setter, "the menu does not take the host's files: " + line)
tick = block(menu, "void menu_tick() {")
# the title: no page opens by itself; Save Select, an entry under Mods on the title's list, opens the file select
check("files_offered" not in menu and tick.count("files_open(true)") == 2, "the file select opens by itself, or not from Save Select alone")
shown = block(menu, "bool files_row_shown(")
# the title: no page opens by itself. ((Triforce) Save Select is a tab at the title's top left beside Mods, chosen by its
# button, a click or the host's word 7 (a test's scripted Y): the file select opens at once, and Back gives the game its
# list again. It was an entry under Mods on the title's list, where Quit Game is now)
go = block(menu, "bool title_tab_go(int tab) {")
check("files_offered" not in menu and "files_open(true)" not in tick and go.count("files_open(true)") == 1
and "(tab == 1 && !files_tab_shown())" in go, "the file select opens by itself, or not from Save Select's tab alone")
shown = block(menu, "bool files_tab_shown(")
check("save_files.shown() > 0" in shown and "HOS_MODS_LIST_TITLE" in shown, "Save Select shows off the title, or before the host named the files")
# (0.7.0: the title's entries are the game's own part, and the System list has Quit under Mods. Save Select is that second
# entry on the title: the same part a pitch lower, mods_row_sel 1, the host's words 3 and 4)
entry = block(menu, "void draw_title_files(")
check(entry.index("std::swap(title_anim, files_title_anim);") < entry.index('title_label = "Save Select", title_entry = 1;') < entry.index("draw_title_mods(c, sel, cx, cy, k, pitch);")
< entry.index('title_label = "Mods", title_entry = 0;') and entry.count("std::swap(title_anim, files_title_anim);") == 2,
"Save Select is not the title's own entry with its own label and animation, or leaves Mods' changed")
tabs = block(menu, "void draw_title_tabs(ui::Ctx& c, bool decide) {")
check('static const char* const labels[title_tabs::kTabs] = {"Mods", "Save Select"};' in tabs and "const int n = files_tab_shown() ? 2 : 1;" in tabs
and tabs.index("std::swap(title_anim, title_tab_anim[i]);") < tabs.index("title_label = labels[i], title_entry = 1, title_corner = true;")
< tabs.index("draw_title_mods(c, sel,") < tabs.index('title_label = "Quit Game", title_entry = 0, title_corner = false;')
and tabs.count("std::swap(title_anim, title_tab_anim[i]);") == 2,
"Save Select is not a tab of the title's own words with its own label and animation, or leaves the entry's changed")
part = block(menu, "void draw_title_mods(ui::Ctx& c, bool sel, float cx, float cy, float k, float pitch) {")
check("const char* const label = title_label;" in part and "menu_hit::kButton, title_entry);" in part
and part.index("if (title_entry) return;") < part.index("mods_entry_px[0] ="), "Save Select has Mods' label, hit or place")
and part.index("if (title_corner) return;") < part.index("hits.add(") and part.index("if (title_entry) return;") < part.index("mods_entry_px[0] ="),
"a tab has the entry's label, hit or place")
row = block(menu, "void draw_mods_row(ui::Ctx& c, bool sel) {")
check("if (files_row_shown()) draw_title_files(c, sel && mods_row_sel == 1, cx, cy - pitch, k, pitch), sel = sel && mods_row_sel == 0;" in row
and row.index("draw_title_files(") < row.index("draw_title_mods(c, sel, cx, cy, k, pitch);"),
"Save Select is not drawn a pitch under the title's Mods, the cursor on one of the two")
check(row.index("draw_title_mods(c, sel && !tab_decides, cx, cy, k, pitch);") < row.index("draw_title_tabs(c, tab_decides);"),
"the title's entry and its tabs are not drawn together")
cursor = tick[tick.index("} else if (open_now.load() && page == kModsRowPage) {"):tick.index("} else if (open_now.load() && page == kModsPage) {")]
a_files, down_files = "} else if (press[7] && files_here && mods_row_sel == 1) {", "} else if (press[2] && files_here && mods_row_sel == 0) {"
check("const bool files_here = files_row_shown();" in cursor and "if (!quit_here && !files_here) mods_row_sel = 0;" in cursor
and cursor.index(a_files) < cursor.index(down_files) < cursor.index("} else if (press[7]) { // (A: Mods opens; on Quit its dialog)")
and cursor.index(down_files) < cursor.index("} else if (press[1] && mods_row_sel == 1) {") < cursor.index("} else if (press[1] || press[5]"),
"the cursor does not move between Mods and Save Select, or A on Save Select opens Mods or Quit's dialog")
# (the Down that brought the cursor onto Mods is not also the entries' own: 0.7.0's entered_by_down)
check("files_here" not in cursor and "if (!quit_here) mods_row_sel = 0;" in cursor
and cursor.index("} else if (press[7]) {") < cursor.index("} else if (press[1] && mods_row_sel == 1) {") < cursor.index("} else if (press[1] || press[5]"),
"the title's list still has a second entry under Quit Game")
# (the Down that brought the cursor onto the entry is not also the entries' own: 0.7.0's entered_by_down)
check(tick.index("if (entered_by_down) press[2] = false;") < tick.index("} else if (open_now.load() && page == kModsRowPage) {"),
"the Down that comes onto Mods goes on to Save Select at once")
"the Down that comes onto the entry goes on at once")
enter = tick[tick.index("bool entered_by_down = false;"):tick.index("if (!open_now.load() || page != kModsPage) {")]
check(enter.index("if (enter == 3 && !mods_title_list()) quit_open();") < enter.index("if (enter == 3 && files_row_shown()) files_open(true);"),
"a click on Save Select does not open the file select, or opens Quit's dialog on the title")
check(enter.index("if (enter == 6 || enter == 7) {") < enter.index("if (!title_tab_go(enter - 6))") < enter.index("if (enter == 3 && !mods_title_list()) quit_open();")
and "files_open" not in enter and "!(mods_title_list() && (enter == 3 || enter == 4))" in enter,
"the host's word for Save Select's tab is not taken, or a click under the title's entry opens something")
pad = tick[tick.index("if (title_tabs_live()) {"):tick.index("auto later = [&] {")]
check("host->binding(HOS_BIND_PAD, i ? HOS_SW_Y : HOS_SW_X, 0)" in pad and "(pad_press >> p & 1)" in pad
and "title_tabs::at(title_tab_layout, title_tab_map.back_x((float)ix), title_tab_map.back_y((float)iy))" in pad
and "if (go >= 0 && title_tab_go(go)) {" in pad and "if (!title_tab_read) tp.pressed = 0;" in pad,
"Save Select's tab is not opened by the pad's own button bound to Y or by a click on it, or takes a click from before it came")
back = tick[tick.index("} else if (open_now.load() && page == kFilesPage) {"):tick.index("} else if (open_now.load() && page == kAchPage) {")]
check("if (files_at_title && !play) open_now = false, page = 0," in back and "kModsRowPage" not in back,
"Back from the title's file select leaves the menu open with a cursor of its own")
mouse = read("host", "oot_menu.c")
list_tick = block(mouse, "static void mods_list_tick(uint64_t screen, int title, ModsCall *call) {")
check(list_tick.index("quit_entry = title ? (Rect){0, 0, 0, 0} :") < list_tick.index("if (title && hos_save_files_on()) {")
< list_tick.index("quit_entry = (Rect){mx - 550, my - pitch / 2, mx + 550, my + pitch / 2};")
and "my = (r.y0 + r.y1) / 2 - 2 * pitch;" in list_tick and "files_entry" not in mouse,
"the host has no box for Save Select under the title's Mods, or has one with the save files off")
check("quit_entry = title ? (Rect){0, 0, 0, 0} :" in list_tick and "if (title && hos_save_files_on())" not in list_tick and "files_entry" not in mouse
and "InterlockedExchange(&mods_entry_title, title);" in list_tick
and "return 1 | (hos_save_files_on() ? 2 : 0);" in block(mouse, "int hos_oot_title_tabs(void) {"),
"the host still has a box for Save Select under the title's list, or offers its tab with the save files off")
check("(page == kFilesPage && files_at_title)" in block(menu, "int menu_mods_selected("), "the game is given input while the title's file select is open")
word = tick[tick.index("if (const int said = save_files.take_said()) {"):]
word = word[:word.index("if (!open_now.load() || page != kModsPage)")]

View File

@@ -15,7 +15,8 @@ page marks over them.
keys' order are those of one process;
- a worker that raises, one that dies, one that does not answer and one whose lifter class was set up otherwise than the
lift's process each end the lift with SystemExit and what was said, soon, and leave no lifted file behind; so does a
process failing at the page marks;
process failing at the page marks, and (Triforce, 11-27) one without nx2/local_flags.py's wrap of the kit's FCMP form
or that reads the flags' switch otherwise;
- a lift that ends on an error of its own while the page marks are being made leaves every file whole and marked;
- the processes of a lift that was stopped from outside end by themselves;
- HOOKSHOT_LIFT_JOBS chooses the count, 1 is one process, the default is half the processors (at most 8, one a GB), and
@@ -398,6 +399,32 @@ def test_failures(tmp, one):
same("a lift after the failures", one, lift(os.path.join(tmp, "after"), 3))
def flags_off():
"""(a spawned process's setup) the flags in the context there, where the lift's process has them as locals"""
os.environ["A64_LOCAL_FLAGS"] = "0"
def test_flags_setup(tmp):
"""(Triforce, 11-27) nx2/local_flags.py's wrap of the kit's vectorize_fcmp, and the flags' form as a process reads it, are
part of what a worker is compared on: a worker without the wrap would write the kit's FCMP form, one that read the flags'
switch otherwise the other form, where the lift's process writes a64_fpx.h for its own (a link error, or other C)"""
import local_flags
with mock.patch.object(a64_lift, "vectorize_fcmp", a64_lift.vectorize_fcmp), \
mock.patch.object(a64_lift, "local_flags", a64_lift.local_flags), \
mock.patch.object(local_flags, "_installed", False), mock.patch.dict(os.environ):
os.environ.pop("A64_LOCAL_FLAGS", None)
local_flags.install()
folder = os.path.join(tmp, "flags-wrap")
got = lift(folder, 3)
failed("a worker without nx2/local_flags.py's wrap", got, "local_flags.install.<locals>.vectorize_fcmp", "setup")
check("a worker without nx2/local_flags.py's wrap: lifted files are left", lifted(folder) == [])
folder = os.path.join(tmp, "flags-off")
got = lift(folder, 3, setup=(poll.install, authored_translator, local_flags.install, flags_off))
failed("a worker that reads the flags' switch otherwise", got, "in the context (local_flags.kit_reads)",
"as locals (local_flags.kit_reads)", "A64_LOCAL_FLAGS is not the lift's")
check("a worker that reads the flags' switch otherwise: lifted files are left", lifted(folder) == [])
def alive(pid):
if os.name == "nt":
import ctypes
@@ -576,6 +603,7 @@ def main():
test_order_of_answers()
one = test_the_same_c(tmp)
test_failures(tmp, one)
test_flags_setup(tmp)
test_abandoned_marks(tmp, one)
test_orphans(tmp)
test_jobs()

View File

@@ -4,7 +4,9 @@ Text checks: what is cut (pieces of about the size asked, every label in exactly
gotos into other pieces become returns of the label's id with their interrupt poll kept, guest returns and tail calls
become ids the dispatcher turns into `return` and TAILCALL), what is left whole and why (a top-level declaration, a label
inside a block, a literal, a goto to a label the function lacks, a function too small or below the size asked), and
build.py's switch (on at 8 KB unless HOOKSHOT_SPLIT_GIANTS says otherwise).
build.py's switch (on at 8 KB unless HOOKSHOT_SPLIT_GIANTS says otherwise). (Triforce, 11-27) And a giant with
nx2/oot_patches.py's hook at its head (the mouse look's, in the player camera's update) is cut with its guest locals:
the hook goes after their lines.
Compiled checks (Clang: the build compiles lifted code with clang on every OS, nx2/build.py `toolchain.find("clang")`),
each a function compiled whole and split into one program against the build's own guest model (nx2/rtgen.py's a64.h),
@@ -297,6 +299,26 @@ def real_text_checks():
"%s: a piece never loads its locals from the context" % what)
def head_hook_checks():
"""(Triforce, 11-27) A hook nx2/oot_patches.py puts at a function's head goes after the guest locals' lines the kit
writes there, which split_text takes only as the body's first lines (locals_of): with the mouse look's hook above the
flags' declaration, the player camera's update (f_80644c80, 632 KB with the flags as locals, the default) was left
whole as "a top-level declaration", its pieces' profile unused"""
import oot_patches
name = "f_%08x" % MAIN
for env, what in LOCALS_ENVS + (({}, "no locals"),):
text, _, _ = emit_real(7, 40, env, below=False)
cam = '#include "a64.h"\n' + text.replace("void %s(" % name, "void f_80644c80(", 1)
got = oot_patches.patch_mouse_camera(cam)
hook = " hos_mouse_camera(c->x[0]);"
check(got is not None and got.count(hook) == 1 and oot_patches.patch_mouse_camera(got) == got,
"%s: the mouse look's hook is made once, and a second run changes nothing" % what)
notes = []
o, s = SG.split_text(got, piece_kb=1, min_kb=0, only={"f_80644c80"}, notes=notes)
check(s["functions_split"] == 1 and s["functions_split_with_locals"] == (1 if env else 0) and o.count(hook) == 1,
"%s: the camera's update with the mouse look's hook is cut: %s %s" % (what, notes, dict(s)))
# ---- the compile_one integration (3) and the text checks -----------------------------------------------------------
def text_checks():
rng = random.Random(1)
@@ -636,6 +658,7 @@ def main():
a = ap.parse_args()
text_checks()
real_text_checks()
head_hook_checks()
cc = find_cc(a.cc)
if not cc:
check(False, "no Clang to compile with (%s): the build compiles lifted code with clang; give --cc, $CC, PATH or "

View File

@@ -407,8 +407,10 @@ def main():
presented = vi[vi.index("void hos_vi_native_presented(void) {"):]
presented = presented[:re.search(r"^}", presented, re.M).end()]
# (with the 1% low's sort, which the cut-out present calls)
code = "\n".join((region, block(vi, "void hos_vi_native_acquire(int active) {"), steady, block(vi, "static int cmp_i64_desc("), presented))
source = PREFIX.replace("@IDS@", ids.group(0) + "\n" + cap.group(0)) + code + SUFFIX
# ((Triforce, 11-26) and the Steady row as it is now each present (steady_mode): not answered here, the file's mode_asked
code = "\n".join((region, block(vi, "void hos_vi_native_acquire(int active) {"), block(vi, "static int steady_mode(void) {"), steady,
block(vi, "static int cmp_i64_desc("), presented))
source = PREFIX.replace("@IDS@", ids.group(0) + "\n" + cap.group(0) + "\nenum { HOS_OPT_STEADY_ROW = 430 };") + code + SUFFIX
env = {k: v for k, v in os.environ.items() if not k.startswith(("HOS_", "RX_"))}
with tempfile.TemporaryDirectory(prefix="steady-period-") as tmp:
c, exe = Path(tmp) / "fixture.c", Path(tmp) / "fixture"

View File

@@ -44,7 +44,8 @@ static const char* fixture_getenv(const char* name) {
namespace Shader { namespace Backend { namespace SPIRV { static bool mma_software = true; } } }
using VkCommandBuffer = int;
using VkImageView = int;
constexpr int VK_IMAGE_VIEW_TYPE_2D=2, VK_FORMAT_B10G11R11_UFLOAT_PACK32=7, VK_FORMAT_UNDEFINED=0, VK_FORMAT_E5B9G9R9_UFLOAT_PACK32=9;
constexpr int VK_IMAGE_VIEW_TYPE_2D=2, VK_FORMAT_B10G11R11_UFLOAT_PACK32=7, VK_FORMAT_UNDEFINED=0, VK_FORMAT_E5B9G9R9_UFLOAT_PACK32=9,
VK_FORMAT_R16G16B16A16_SFLOAT=97;
enum class ViewUse { Storage, Sample };
struct Desc { unsigned count=1; int format=23; };
struct Info { std::vector<Desc> texture_descriptors, image_descriptors; bool uses_cooperative_matrix=false; };
@@ -100,6 +101,8 @@ static bool typed_upscale(VkCommandBuffer cmd,VkImageView input,VkImageView outp
++upscale_calls;forwarded_cmd=cmd;forwarded_input=input;forwarded_output=output;forwarded_texture=out;
forwarded_level=level;forwarded_key=key;forwarded_text=text;forwarded_temporal=temporal;return upscale_result;
}
/* ((Triforce, 11-26) the RGBA16F scene's 3/4 network (vk_draw.cpp wide_upscale): never reached here, every picture B10G11R11 */
static bool wide_upscale(VkCommandBuffer,VkImageView,Texture*,uint32_t,uint64_t,const char*,bool){return false;}
/* ((Triforce, 11-22, N64 Classic) its 3D pass on (vk_n64.cpp n64_3d_now), and the pass itself (vk_draw.cpp n64_upscale),
spied as typed_upscale is: it too is refused outside the recording lock */
static bool n64_now;

View File

@@ -5,6 +5,8 @@ off whatever the CPU; On is both threads whatever the CPU; Auto is both threads
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).
python -I -B tests/test_threaded_rendering.py [--cxx clang++]
"""
@@ -87,7 +89,7 @@ def check_source():
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)
("::mkwvk::rec::g_parts_default = [] { return threaded_on(); }", replay),
("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 v = e && *e ? atoi(e) == 1 : threaded_on();", replay),
@@ -95,6 +97,12 @@ def check_source():
("QueueMutex present_mu;", internal)):
if needle not in where:
fail("a piece of the design moved or changed: " + needle)
# ((Triforce, 11-27) the recorder's hand-off by part is RX_VK_RECORDER_PARTS=1's alone: with Threaded rendering it drew the 3D
# with wrong textures on the lab's RX 7900 XT, in v0.8.3 too)
if "g_parts_default =" in replay:
fail("Threaded rendering (or anything) turns the recorder's hand-off by part on again: vk_replay.cpp rec_parts_hooks")
if "the recorder thread by part" in (ROOT / "gpu/vk/threaded_rendering.h").read_text(encoding="utf-8"):
fail("the start's line still says the recorder thread takes parts")
fn = backend[backend.index("int rx_async_replay(void) {"):backend.index("void rx_nvn_submit_waits(")]
if fn.index('getenv("RX_VK_ASYNC")') > fn.index("HOS_OPT_RENDER_THREAD"):
fail("rx_async_replay asks the renderer before RX_VK_ASYNC")

231
tests/test_title_tabs.py Normal file
View File

@@ -0,0 +1,231 @@
"""The title's tabs, Mods and Save Select at the picture's top left with their buttons' prompts under them, and Quit Game under
the title's list (gpu/vk/title_tabs.h, vk_menu.cpp draw_title_tabs, title_tab_go and menu_tick; host/oot_menu.c, nn_hid.c,
display.c; no game).
(Triforce) The owner: "I want you to move the mod tab and the save select tab to the top left of the screen. I want there to be
a button prompt below the tabs, such as, for example, an Xbox controller. The player should select Y to open the mod menu. And
X to open the save select. Triangle for mods and Square for save select for PlayStation. PC should be able to select those tabs
by mouse optimize those placements for every aspect ratio", and "Add a quit game option below the Options tab". They were
entries under the title's list (Mods under Options, Save Select under Mods), reached with Down.
This compiles title_tabs.h alone (with game_grid.h) and checks where the tabs land in the window's pixels:
- in every shape (a 16:9, 21:9, 32:9, 16:10 and 4:3 picture filling its window; the owner's 3416 x 1440 picture in a
3440 x 1440 window; a 21:9 picture between bars in a 16:9 window; a 16:9 picture between bars in a 21:9 window; no picture
known yet) both tabs are inside the picture (never in a bar) and inside the window, a margin in from the picture's own top
left corner, in its left third and top fifth (clear of the title's logo and list), side by side without overlap;
- their size follows the picture's height (2160 units down it) as the title's own words do, and is squeezed across with the
game's layouts on a picture narrower than 16:9;
- with a controller the box a click counts in reaches under the icon; without one it ends under the label;
- 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.
python -I -B tests/test_title_tabs.py [--cxx clang++]
"""
import argparse
import subprocess
import sys
import tempfile
from pathlib import Path
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
ROOT = Path(__file__).resolve().parents[1]
VK = ROOT / "gpu" / "vk"
def check(cond, what):
if not cond:
raise SystemExit("FAIL: " + what)
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]
PROGRAM = r"""
#include <cmath>
#include <cstdio>
#include <cstdint>
#include "title_tabs.h"
using namespace mkwvk;
static int fails;
#define CHECK(x) do { if (!(x)) { std::printf("FAIL:%d %s (%s)\n", __LINE__, #x, name); fails++; } } while (0)
struct Case { const char* name; uint32_t pw, ph, ww, wh; double aspect; };
// the tabs of one case, in the window's pixels
struct Win { float x0, y0, x1, y1, lx, ly, ix, iy; };
static Win to_window(const title_tabs::Tab& t, const game_grid::Map& m) {
return {m.x(t.x0), m.y(t.y0), m.x(t.x1), m.y(t.y1), m.x(t.label_x), m.y(t.label_y), m.x(t.icon_x), m.y(t.icon_y)};
}
static void one(const Case& c) {
const char* name = c.name;
const game_grid::Place g = game_grid::of(c.pw, c.ph, c.ww, c.wh, c.aspect);
const game_grid::Map m = game_grid::map_of(g);
const float unit = g.h / 2160.0f;
// (the labels at the title's size: "Mods" about 150 units wide, "Save Select" about 330; the icons 84)
const float lw[2] = {150 * unit, 330 * unit}, iw[2] = {84 * unit, 84 * unit};
const float left = title_tabs::picture_left(g, m), top = title_tabs::picture_top(g, m);
// (the picture in the window: the grid itself while none is known)
const float px0 = g.picture ? g.pic_x : g.x, py0 = g.picture ? g.pic_y : g.y;
const float pw = g.picture ? g.pic_w : g.w, ph = g.picture ? g.pic_h : g.h;
for (int icons = 0; icons < 2; icons++) {
const title_tabs::Layout l = title_tabs::place(left, top, unit, lw, iw, 2, icons != 0);
CHECK(l.n == 2);
Win w[2] = {to_window(l.tab[0], m), to_window(l.tab[1], m)};
for (int i = 0; i < 2; i++) {
CHECK(w[i].x0 >= px0 + 1 && w[i].y0 >= py0 + 1); // (a margin in from the picture's corner)
CHECK(w[i].x1 <= px0 + pw / 3 && w[i].y1 <= py0 + ph / 5); // (its left third, its top fifth)
CHECK(w[i].x0 >= 0 && w[i].y0 >= 0 && w[i].x1 <= (float)c.ww && w[i].y1 <= (float)c.wh);
CHECK(w[i].x1 - w[i].x0 > 40 * unit * m.kx && w[i].y1 - w[i].y0 > 60 * unit); // (a box to click)
CHECK(w[i].lx > w[i].x0 && w[i].lx < w[i].x1 && w[i].ly > w[i].y0 && w[i].ly < w[i].y1);
CHECK(std::fabs((w[i].ly - py0) - title_tabs::kTop * unit) < 1.5f); // (the same place down every picture)
// (the point test, in the column's pixels as menu_tick has the mouse)
CHECK(title_tabs::at(l, l.tab[i].label_x, l.tab[i].label_y) == i);
if (icons) {
CHECK(title_tabs::at(l, l.tab[i].icon_x, l.tab[i].icon_y) == i);
CHECK(std::fabs(w[i].ix - w[i].lx) < 0.01f && w[i].iy > w[i].ly + title_tabs::kText * 0.5f * unit);
CHECK(w[i].y1 > w[i].iy + title_tabs::kIcon * 0.5f * unit - 0.5f); // (the box reaches under the icon)
} else {
CHECK(title_tabs::at(l, l.tab[i].icon_x, l.tab[i].icon_y + title_tabs::kIcon * 0.5f * unit) == -1);
}
}
CHECK(w[0].x1 < w[1].x0); // (side by side, a gap between)
CHECK(title_tabs::at(l, (l.tab[0].x1 + l.tab[1].x0) * 0.5f, l.tab[0].label_y) == -1);
CHECK(title_tabs::at(l, m.back_x(px0 + pw * 0.5f), m.back_y(py0 + ph * 0.5f)) == -1);
CHECK(std::fabs((w[0].x0 - px0) - (title_tabs::kLeft - title_tabs::kPadX) * unit * m.kx) < 1.5f);
// (the clip they are drawn in is the whole picture, in the window too, and holds both tabs whole)
float cx0, cy0, cx1, cy1;
title_tabs::picture_clip(g, m, &cx0, &cy0, &cx1, &cy1);
CHECK(std::fabs(m.x(cx0) - px0) < 0.5f && std::fabs(m.y(cy0) - py0) < 0.5f && std::fabs(m.x(cx1) - (px0 + pw)) < 0.5f && std::fabs(m.y(cy1) - (py0 + ph)) < 0.5f);
for (int i = 0; i < 2; i++) CHECK(l.tab[i].x0 >= cx0 && l.tab[i].x1 <= cx1 && l.tab[i].y0 >= cy0 && l.tab[i].y1 <= cy1);
// (the save files off: Mods alone, where it was)
const title_tabs::Layout one_tab = title_tabs::place(left, top, unit, lw, iw, 1, icons != 0);
CHECK(one_tab.n == 1 && one_tab.tab[0].x0 == l.tab[0].x0 && one_tab.tab[0].x1 == l.tab[0].x1);
CHECK(title_tabs::at(one_tab, l.tab[1].label_x, l.tab[1].label_y) == -1);
}
const title_tabs::Layout l = title_tabs::place(left, top, unit, lw, iw, 2, true);
std::printf("%-34s unit %.3f kx %.3f: Mods %4.0f..%4.0f, Save Select %4.0f..%4.0f, down to %3.0f (picture from %4.0f, %3.0f)\n", c.name,
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);
}
int main() {
static const Case cases[] = {
{"16:9 1920x1080", 1920, 1080, 1920, 1080, 0},
{"16:9 1280x720", 1280, 720, 1280, 720, 0},
{"21:9 3440x1440", 3440, 1440, 3440, 1440, 0},
{"the owner's 3416x1440 in 3440x1440", 3416, 1440, 3440, 1440, 0},
{"32:9 5120x1440", 5120, 1440, 5120, 1440, 0},
{"16:10 1920x1200", 1920, 1200, 1920, 1200, 0},
{"4:3 1440x1080", 1440, 1080, 1440, 1080, 0},
{"21:9 picture in 1600x900", 3440, 1440, 1600, 900, 0},
{"16:9 picture in 3440x1440", 2560, 1440, 3440, 1440, 0},
{"no picture yet, 1600x900", 0, 0, 1600, 900, 0},
{"no picture yet, 3440x1440", 0, 0, 3440, 1440, 0},
};
for (const Case& c : cases) one(c);
{ // (the size against the picture: twice the height, twice the tabs; a 16:10 picture's are squeezed across)
const char* name = "sizes";
const game_grid::Place a = game_grid::of(1280, 720, 1280, 720, 0), b = game_grid::of(2560, 1440, 2560, 1440, 0);
CHECK(std::fabs(b.h / 2160.0f - 2 * (a.h / 2160.0f)) < 1e-4f);
const game_grid::Place n = game_grid::of(1920, 1200, 1920, 1200, 0);
CHECK(game_grid::map_of(n).kx < 0.95f && game_grid::map_of(b).kx == 1.0f);
}
std::printf(fails ? "FAILED\n" : "ok\n");
return fails ? 1 : 0;
}
"""
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cxx", default="clang++")
args = parser.parse_args()
header = (VK / "title_tabs.h").read_text(encoding="utf-8")
check("#include <imgui" not in header and "vulkan" not in header.split("#pragma once")[1], "title_tabs.h is not free of ImGui and Vulkan")
menu = (VK / "vk_menu.cpp").read_text(encoding="utf-8")
host = (ROOT / "host" / "oot_menu.c").read_text(encoding="utf-8")
hid = (ROOT / "host" / "nn_hid.c").read_text(encoding="utf-8")
window = (ROOT / "host" / "display.c").read_text(encoding="utf-8")
# the drawing: from the picture's own corner, on the grid the title's entry is drawn on; the icons the game's own of the
# bindings (X the top face button: Mods; Y the left one: Save Select); the tabs' place kept for the mouse
tabs = block(menu, "void draw_title_tabs(ui::Ctx& c, bool decide) {")
check("title_tabs::place(title_tabs::picture_left(title_grid, m), title_tabs::picture_top(title_grid, m), unit, lw, iw, n, pad);" in tabs
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,
"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
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")
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);")
< tabs.index("const title_tabs::Tab& t = l.tab[i];") < tabs.index("c.d->PopClipRect();")
and tabs.count("PushClipRect") == tabs.count("PopClipRect") == 1,
"the tabs are drawn in the window's clip rectangle in the column's pixels: left of the column on a wide picture, not at all")
check("const float px = ui::lu(c, kTitleText * ui::kType)" in tabs.replace("unit = ui::lu(c, 1), ", "")
and "constexpr float kText = 52;" in header and "kTitleText = 65 * 0.8f" in menu,
"the tabs' words are not the size of the title's own entries")
for caller, line in (("void draw_mods_row_shut(ui::Ctx& c) {", "title_grid = g;"), ("void draw_menu(ui::Ctx& c, bool perf_under) {", "title_grid = g;")):
check(line in block(menu, caller), "the tabs' grid is not told by " + caller)
# the input: the pad's own buttons bound to X and Y, the mouse over them and its click, the first read's click left out
tick = block(menu, "void menu_tick() {")
live = tick[tick.index("if (title_tabs_live()) {"):tick.index("auto later = [&] {")]
check("host->binding(HOS_BIND_PAD, i ? HOS_SW_Y : HOS_SW_X, 0)" in live and "if (hos_pad_bindable(p) && (pad_press >> p & 1)) go = i, pad_last = true;" in live,
"the tabs are not opened by the pad's own buttons the Switch's X and Y are bound to")
check("HOS_BIND_KEY" not in live, "a key or a mouse button bound to X or Y opens a tab (the left mouse button is Y by default)")
check("if (pad_press || under < 0) hover = -1;" in live and "else if (tab_moved || (tp.pressed & HOS_MOUSE_LEFT)) hover = under;" in live
and "if (go < 0 && on && (tp.pressed & HOS_MOUSE_LEFT) && under >= 0) go = under, pad_last = false;" in live,
"the mouse over a tab does not light it, or a click on one does not choose it")
check("if (!title_tab_read) tp.pressed = 0;" in live and "title_tab_read = false;" in tick[tick.index("auto later = [&] {") - 400:tick.index("auto later = [&] {")],
"a click from before the title's list came is taken as a tab's")
check("for (int i = 0; i < K_N; i++) press[i] = false;" in live, "the press that chose a tab is also the page's it opens")
check("} else if (!tick_sound_done && (sound_before.open || !after.open || after.page != kModsRowPage)) {" in tick
and "tick_sound_done = false;" in tick, "a tab chosen sounds a second time, by what the tick changed")
# the host: Quit Game alone under the title's list; the tabs told to the window (clicks) and the scripted presses
list_tick = block(host, "static void mods_list_tick(uint64_t screen, int title, ModsCall *call) {")
check("mods_entry = (Rect){mx - 550, my - pitch / 2, mx + 550, my + pitch / 2};" in list_tick
and "quit_entry = title ? (Rect){0, 0, 0, 0} :" in list_tick and "hos_save_files_on()" not in list_tick,
"the title's list has not the one entry under its last button")
there = block(host, "int hos_oot_title_tabs(void) {")
check("InterlockedCompareExchange(&mods_entry_title, 0, 0)" in there and "return 1 | (hos_save_files_on() ? 2 : 0);" in there
and "int hos_oot_title_tabs(void) { return 0; }" in host, "the host does not say the title's tabs are there, or its other half has no word")
check("else if (bit == HOS_MOUSE_LEFT && hos_oot_title_tabs()) InterlockedOr(&ptr_pressed, bit);" in block(window, "static void game_menu_press(LPARAM lp, LONG bit) {"),
"the window does not keep the title's clicks for its tabs")
mods_input = block(hid, "static void mods_input(uint64_t *buttons_io, int32_t stick[4]) {")
check("const uint64_t taps = script_now, fresh = taps & ~taps_was;" in mods_input
and "script_now = *buttons;" in block(hid, "static void read_input(uint64_t *buttons, int32_t stick[4]) {")
and "if ((fresh >> B_X & 1) && (tabs & 1)) rx_option_set(HOS_OPT_MODS_ENTER, 6), buttons &= ~(1ULL << B_X);" in mods_input
and "else if ((fresh >> B_Y & 1) && (tabs & 2)) rx_option_set(HOS_OPT_MODS_ENTER, 7), buttons &= ~(1ULL << B_Y);" in mods_input,
"a test's scripted X or Y on the title is not its tab's word")
with tempfile.TemporaryDirectory(prefix="title-tabs-") as tmp:
src, exe = Path(tmp) / "tabs.cpp", Path(tmp) / "tabs.exe"
src.write_text(PROGRAM, encoding="utf-8")
subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-I" + str(VK), str(src), "-o", str(exe)], check=True)
r = subprocess.run([str(exe)], capture_output=True, text=True)
check(r.returncode == 0, "the tabs' places:\n" + r.stdout)
print(r.stdout.strip())
print("PASS: the title's tabs at the picture's top left in every shape; Quit Game under the title's list")
if __name__ == "__main__":
sys.exit(main())

262
tests/test_tpltable.py Normal file
View File

@@ -0,0 +1,262 @@
"""The descriptor templates' wide per-thread table (gpu/vk/tpltable.h; vk_draw.cpp set_template, push_template; no game, no GPU).
(Triforce, 11-26, the GPU audit's C31, its part (a).) A program's set template and push template were found through a
per-thread table of 8 entries by the program's address; a frame pushes the descriptors of far more programs than 8, so
most lookups took the global tpl_mu and searched a std::unordered_map (0.8% of the Presentation Thread's time at Lake
Hylia, 1.1% in the Market). The table is now 512 sets of 2 entries by a multiplicative hash of the address and the
template's kind; the entries, the layout check and the locked path behind a miss are what they were.
Compiles a driver against the header: the switch's values (another value by its leading number); 64 programs taken in
turn miss once each and never again (the 8-entry table by the old index misses on most lookups); 300 programs a fixed
0x2c0 apart miss on a few lookups in a hundred at most, but a fixed stride is not a frame (at this one the hash
spreads them evenly, at 0x110 apart nearly every lookup misses); 300 programs at scattered addresses miss on about 12
lookups in a hundred after the first round (printed; the bound, 20, only catches a table that stopped spreading keys;
busy frames took the lock on about 10% in a play test); a program's three kinds are three entries; an entry put again
is replaced in place; a third key in a set puts the oldest out, and what is put out is not found again; an empty table
finds nothing; the table is 16 KB.
Reads the source:
- vk_draw.cpp: the header included; RX_VK_TPL_TABLE read once (tpl_table_env), logged when not the default and when
not a value it knows, the lab's knob notpltable over it (tpl_table_mode); set_template and push_template look in the table before tpl_mu, keep the layout check on what they
find, put what the locked path gave, and keep the 8 entries for the switch's 0; the check mode asks the map under
the lock and logs a difference by the check's name; the counters are in the frame statistics' line, labelled by the switch (not the lab's phase) and saying
that under the check every find took the lock too;
- vk_shader.h, vk_shader.cpp (stamp files): untouched by the name;
- the switches table has the row, with the check's values, the busy frames' share of locked lookups and when a
thread's table is made and freed.
python -I -B tests/test_tpltable.py [--cxx clang++]
"""
import argparse
import subprocess
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
DRIVER = r'''
#include "tpltable.h"
#include <cstdio>
#include <memory>
#include <vector>
using namespace mkwvk::tpltable;
static int checks, fails;
static void want(const char* what, bool ok) {
checks++;
if (!ok) fails++, printf("FAIL %s\n", what);
}
// the callers' use of the table: found, or the locked path (counted) and put
static int locked;
static const void* lookup(Table& tab, uintptr_t key, const void* t) {
if (const void* got = tab.find(key)) return got;
locked++;
tab.put(key, t);
return t;
}
// the 8 entries before, by the old index
struct Old { uintptr_t p; const void* t; };
static const void* lookup_old(Old* last, uintptr_t p, const void* t) {
Old& l = last[old_slot(p)];
if (l.p == p && l.t) return l.t;
locked++;
l = {p, t};
return t;
}
int main() {
want("the switch: on unless set otherwise", mode(nullptr) == kWide && mode("1") == kWide && mode("") == kWide && mode("x") == kWide);
want("the switch: 0 is the 8 entries, 2 the check", mode("0") == kOld && mode("2") == kCheck && mode("3") == kWide);
want("the switch: check is the check too", mode("check") == kCheck && mode("checked") == kWide && mode("Check") == kWide);
want("the switch: another value by its leading number, a 0 only when it starts the value",
mode("02") == kCheck && mode("+2") == kCheck && mode("2x") == kCheck && mode("00") == kOld && mode("0x") == kOld &&
mode(" 0") == kWide && mode("-0") == kWide && mode("1x") == kWide);
want("the old index is what it was", old_slot(0x1000) == 0 && old_slot(0x1040) == 1 && old_slot(0x11c0) == 7 && old_slot(0x1200) == 0 &&
kOldSlots == 8);
want("512 sets of 2, 16 bytes an entry", kSets == 512 && kWays == 2 && sizeof(Entry) == 16 && sizeof(Table) == 16 * 1024);
auto tab = std::make_unique<Table>();
static int tpl[4096]; // (the templates: any distinct addresses)
want("an empty table finds nothing", !tab->find(key_of((const void*)0x1e4a5c00040, kSet)));
// 64 programs 0x1c0 apart (a heap's spacing for one size), taken in turn three times
std::vector<uintptr_t> progs;
for (int i = 0; i < 64; i++) progs.push_back((uintptr_t)0x1e4a5c00040 + (uintptr_t)i * 0x1c0);
locked = 0;
bool right = true;
for (int round = 0; round < 3; round++)
for (int i = 0; i < 64; i++) right &= lookup(*tab, key_of((const void*)progs[i], kPushGraphics), &tpl[i]) == &tpl[i];
want("64 programs in turn: each its own template", right);
want("64 programs in turn: one locked lookup each, none after the first round", locked == 64);
Old last[kOldSlots] = {};
locked = 0;
for (int round = 0; round < 3; round++)
for (int i = 0; i < 64; i++) right &= lookup_old(last, progs[i], &tpl[i]) == &tpl[i];
want("the 8 entries before: locked on most lookups", right && locked > 150);
// 300 programs 0x2c0 apart, three rounds. A fixed stride is not a frame's programs: at this stride (and at 0x1c0) the
// multiplicative hash spreads them evenly over the sets and none locks again, at 0x110 or 0x130 apart nearly every lookup
// locks. The scattered case below is nearer a frame
tab = std::make_unique<Table>();
locked = 0;
for (int round = 0; round < 3; round++)
for (int i = 0; i < 300; i++) {
const uintptr_t p = (uintptr_t)0x2b7f0a31000 + (uintptr_t)i * 0x2c0;
right &= lookup(*tab, key_of((const void*)p, kPushGraphics), &tpl[i]) == &tpl[i];
}
want("300 programs: every lookup its own template", right);
want("300 programs: under 5 in 100 lookups locked after the first round", locked >= 300 && locked - 300 < 600 * 5 / 100);
printf(" (300 programs, 900 lookups: %d locked after the first round)\n", locked - 300);
// 300 programs at scattered addresses (a fixed generator), three rounds: a set keeps two keys, first in, first out, so a set
// that three or more keys fall in misses on each of them every round. About 12 in 100 lookups after the first round lock
// here; busy frames' statistics in a play test showed about 10% (21% at worst). The bound only catches a table that
// stopped spreading keys; it is no promise for a frame
std::vector<uintptr_t> scattered;
uint64_t seed = 0x243f6a8885a308d3ull;
for (int i = 0; i < 300; i++) {
seed = seed * 6364136223846793005ull + 1442695040888963407ull;
scattered.push_back((uintptr_t)0x20000000000 + (uintptr_t)(seed >> 32) * 0x40);
}
tab = std::make_unique<Table>();
locked = 0;
for (int round = 0; round < 3; round++)
for (int i = 0; i < 300; i++) right &= lookup(*tab, key_of((const void*)scattered[i], kPushGraphics), &tpl[i]) == &tpl[i];
want("300 scattered programs: every lookup its own template", right);
want("300 scattered programs: some locked after the first round, under 20 in 100", locked > 300 && locked - 300 < 600 * 20 / 100);
printf(" (300 scattered programs, 900 lookups: %d locked after the first round)\n", locked - 300);
// a program's kinds are entries of their own
tab = std::make_unique<Table>();
const void* prog = (const void*)0x1e4a5c00040;
want("the kinds make three keys", key_of(prog, kSet) != key_of(prog, kPushGraphics) && key_of(prog, kPushGraphics) != key_of(prog, kPushCompute) &&
key_of(prog, kSet) != key_of(prog, kPushCompute) && kPushCompute == kPushGraphics + 1);
tab->put(key_of(prog, kSet), &tpl[0]), tab->put(key_of(prog, kPushGraphics), &tpl[1]), tab->put(key_of(prog, kPushCompute), &tpl[2]);
want("each kind finds its own", tab->find(key_of(prog, kSet)) == &tpl[0] && tab->find(key_of(prog, kPushGraphics)) == &tpl[1] &&
tab->find(key_of(prog, kPushCompute)) == &tpl[2]);
// an entry put again is replaced where it is; a third key in a set puts the oldest out, for good
tab = std::make_unique<Table>();
const uintptr_t a = key_of(prog, kPushGraphics);
std::vector<uintptr_t> same; // (other keys of a's set)
for (uintptr_t p = 0x1e4a5c00040 + 0x40; same.size() < 3; p += 0x40)
if (set_of(key_of((const void*)p, kPushGraphics)) == set_of(a)) same.push_back(key_of((const void*)p, kPushGraphics));
tab->put(a, &tpl[10]);
tab->put(same[0], &tpl[11]);
want("two keys of a set are both found", tab->find(a) == &tpl[10] && tab->find(same[0]) == &tpl[11]);
tab->put(a, &tpl[12]); // (its template made again: the locked path gave another)
want("put again: the new template, the neighbour kept", tab->find(a) == &tpl[12] && tab->find(same[0]) == &tpl[11]);
int held = 0;
for (const Entry& e : tab->e) held += e.key == a;
want("put again: one entry for the key", held == 1);
tab->put(same[1], &tpl[13]);
want("a third key: the newest stays with one of the two", tab->find(same[1]) == &tpl[13] &&
(tab->find(a) == &tpl[12]) + (tab->find(same[0]) == &tpl[11]) == 1);
tab->put(same[2], &tpl[14]);
want("a fourth: the first two are out, and nothing old is found for them", !tab->find(a) && !tab->find(same[0]) &&
tab->find(same[1]) == &tpl[13] && tab->find(same[2]) == &tpl[14]);
int used = 0;
for (const Entry& e : tab->e) used += e.key != 0;
want("and no other set was written", used == 2);
if (fails) printf("tpltable: FAILED (%d of %d checks)\n", fails, checks);
else printf("tpltable: all %d checks passed\n", checks);
return fails != 0;
}
'''
def block(text, marker):
start = text.index(marker)
at = text.index("{", start) + 1
depth = 1
while depth:
depth += (text[at] == "{") - (text[at] == "}")
at += 1
return text[start:at]
def need(ok, why):
if not ok:
raise SystemExit("FAIL: " + why)
def ordered(text, parts, why):
last = 0
for p in parts:
k = text.find(p, last)
need(k >= 0, why + " (missing, or out of order: " + p + ")")
last = k + len(p)
def check_source():
draw = (ROOT / "gpu/vk/vk_draw.cpp").read_text(encoding="utf-8")
need('#include "tpltable.h"' in draw, "vk_draw.cpp does not include tpltable.h")
need("TLS_OBJECT(tpl_wide, tpltable::Table)" in draw, "vk_draw.cpp has no per-thread wide table (TLS_OBJECT(tpl_wide, tpltable::Table))")
need("static_assert(alignof(Program) >= 4" in draw, "nothing says a program's address leaves the kind's two bits free")
need("int tpl_table_env() {" in draw, "vk_draw.cpp has no tpl_table_env (the switch read once, apart from the lab's knob)")
env = block(draw, "int tpl_table_env() {")
ordered(env, ["static const int env", 'getenv("RX_VK_TPL_TABLE")', "tpltable::mode(asked)", "logf(", "is not 0, 1, 2 or check",
"return env;"], "the switch is not RX_VK_TPL_TABLE read once and logged, an unknown value told")
mode = block(draw, "int tpl_table_mode() {")
need("tpl_table_env()" in mode and 'return lab_ab::on("notpltable") ? tpltable::kOld : env;' in mode and "getenv" not in mode,
"the table in force is not the switch's with the lab's notpltable knob over it")
for name, kind, valid in [("const SetTemplate* set_template(", "tpltable::kSet", "t->layout == p.set_layout"),
("const SetTemplate* push_template(", "tpltable::kPushGraphics + k", "t->pipe_layout == p.layout")]:
body = block(draw, name)
ordered(body, ["const int wide = tpl_table_mode();", "tpltable::key_of(&p, " + kind + ")", "tpltable::old_slot((uintptr_t)&p)", "if (wide) {", "tpl_wide().find(key)",
"if (t && " + valid + ") {", "count_add(st_tpl_fast, 1);", "if (wide == tpltable::kCheck) tpl_check(", "return t;",
"} else if (l.p == &p && l.t && l." + valid + ") {", "count_add(st_tpl_locked, 1);", "std::lock_guard lk(tpl_mu);",
"if (wide) tpl_wide().put(key, t.get());", "else l = {&p, t.get()};", "return t.get();"],
"%s does not look in the wide table before tpl_mu with the layout check, count, and put what the lock gave" % name.strip("("))
need(body.count("std::lock_guard lk(tpl_mu);") == 1, name + " takes tpl_mu elsewhere")
check = block(draw, "void tpl_check(")
ordered(check, ["std::lock_guard lk(tpl_mu);", "map.find(&p)", "count_add(st_tpl_checked, 1);", "count_add(st_tpl_bad, 1);",
'"vk: descriptor template check: '],
"the check mode does not ask the map under the lock, count what came out otherwise and log it by its name (not by one value)")
report = block(draw, "void desc_report(double frames) {")
need("a frame's descriptor templates:" in report and "st_tpl_fast.load()" in report and "st_tpl_locked.load()" in report and
"st_tpl_checked.load()" in report and "st_tpl_bad.load()" in report,
"the frame statistics have no line of the templates' lookups")
need("const int tm = tpl_table_env();" in report and "tpl_table_mode()" not in report and "each one found took the lock too" in report,
"the templates' line is not labelled by the switch, or does not say the check takes the lock at every find")
# (stamp files: this change is a side table, nothing on Program)
for stamp in ["gpu/vk/vk_shader.h", "gpu/vk/vk_shader.cpp"]:
need("tpltable" not in (ROOT / stamp).read_text(encoding="utf-8"), stamp + ", a stamp file, names tpltable")
docs = (ROOT / "docs/development.md").read_text(encoding="utf-8")
row = [line for line in docs.splitlines() if line.startswith("| `RX_VK_TPL_TABLE=0`")]
need(len(row) == 1 and "`gpu/vk/tpltable.h`" in row[0] and "`notpltable`" in row[0] and "a frame's descriptor templates" in row[0] and
"`RX_VK_TPL_TABLE=2`" in row[0], "docs/development.md: the switches table has no RX_VK_TPL_TABLE row")
need(row[0].startswith("| `RX_VK_TPL_TABLE=0` or `2` (`check`) |"), "docs/development.md: the RX_VK_TPL_TABLE row's head lacks the check")
for part, why in [("about 10% of them", "that busy frames still take the lock on about 10% of lookups"),
("8 entries a kind of template", "that there were 8 entries a kind of template"),
("made at its first lookup and freed when the thread ends", "when a thread's table is made and freed"),
("`RX_VK_TPL_TABLE=2` or `check`", "check as a value of the check"),
("so every lookup takes it", "that the check takes the lock at every lookup"),
("the table's template is still the one used", "which template the check uses"),
("labelled by the switch", "what labels the counters' line")]:
need(part in row[0], "docs/development.md: the RX_VK_TPL_TABLE row does not say " + why)
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--cxx", default="clang++")
args = parser.parse_args()
need((ROOT / "gpu/vk/tpltable.h").is_file(), "gpu/vk/tpltable.h is not there: the templates' table is the 8 entries behind tpl_mu")
with tempfile.TemporaryDirectory(prefix="tpltable-") as tmp:
cpp, exe = Path(tmp) / "tpltable_test.cpp", Path(tmp) / "tpltable.exe"
cpp.write_text(DRIVER, encoding="utf-8")
subprocess.run([args.cxx, "-std=c++20", "-Wall", "-Wextra", "-Werror", "-I" + str(ROOT / "gpu/vk"), str(cpp), "-o", str(exe)],
check=True)
r = subprocess.run([str(exe)], capture_output=True, text=True)
print(r.stdout.rstrip())
if r.returncode:
raise SystemExit("FAIL: the template table's checks failed")
check_source()
print("PASS: the descriptor templates are found in a per-thread table of 512 sets of 2; RX_VK_TPL_TABLE=0 is the 8 entries as before")
if __name__ == "__main__":
main()

816
tests/test_uboonly.py Normal file
View File

@@ -0,0 +1,816 @@
"""A draw that only bound uniform buffers anew resolves its user uniform buffers alone, and only where a whole build of its
descriptors would have given the same (gpu/vk/uboonly.h; vk_draw.cpp ubo_only_build and draw; no game, no GPU).
(Triforce, 11-26.) draw() keeps the last descriptors only while bind_gen is the same, and every uniform buffer bind moves it,
so the next draw of the same program with one per-object uniform buffer ran the whole build_descriptors. Now it resolves the
user uniform buffers (through kept_uniform, as the build does) and leaves the rest of the thread's last build as it is.
1. A driver compiled against the header:
- the switch's values; the mode in a draw (off with the per-binding reuse off or checked, the signature skip on, snapshots,
RX_VK_BANK_GEN_OFF, a dump, the upscaler's second recording, a strict draw, one that may not defer, the lab's phase);
- the plan of a program (Maker): the user uniform buffers' places in the build's order, the descriptors beside them; a
texture handle read through a handle program or from c3 on, a storage buffer named in c3 on, written, a table, a run-time
pointer's, a turf list, the miss binding, a texel buffer, a storage image, a constant buffer past c18, compute, the mesh
fallback, RenoDX's, a stage past 4: never; a plan made again for another program in its slot keeps its lists' room and
is what a new plan would be;
- the rule on a model of build_descriptors (the banks' cache by the stages' generations, desc_keep.h's take and keep for the
rest): only uniform buffer slot 2 moved: that one alone is resolved and the rest is what a whole build makes; a texture
bound between two draws: a whole build; a stamp moved, a slot registered anew, a dispatch's build in between, a build
whose bind failed, a result dropped, a sampler or bank missing: a whole build; a mirror made while the uniform buffers
resolve: a whole build follows;
- 30000 random draws of four programs (and a fifth built by a dispatch's stand-in) with every input and stamp moved at
random: each uniform-buffers-only build equals the whole build of the same state, descriptor for descriptor. This is the
only place the default mode's chain (a build of the uniform buffers alone over another) is compared: in check every such
draw is followed by a whole build, so check compares only the first build after a whole one.
2. Mutations of the header (each rule taken out in turn) make the driver fail.
3. The source: the hook in draw() (the rule before the build, the whole build otherwise, the stamps read before it, the
bookkeeping after the bind), ubo_only_build (the program's key first, every user uniform buffer through kept_uniform, the
stamps again after them, the sampled textures read again, counted only when it is used: not in check), the plan made as
sig_shape reads a program, the switch read once with what turns it off and a value it does not know told, the lab's knob,
the counters' line, and the switches table's row (with what check does not try).
python -I -B tests/test_uboonly.py [--cxx clang++] [--no-mutations]
"""
import argparse
import re
import shutil
import subprocess
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
DRIVER = r'''
#include "uboonly.h"
#include <cstdio>
#include <random>
#include <vector>
using namespace uboonly;
using desc_keep::Stamps;
static int checks, fails;
static void want(const char* what, bool ok) {
checks++;
if (!ok) fails++, printf("FAIL %s\n", what);
}
// ---- a model of build_descriptors and of the uniform-buffers-only build, over the real rule and desc_keep.h ----
enum ItemKind { BANK0, BANK2, C1, UBO, SSBO, SSBO_WRITTEN, TEX, TEX_FROM_C3 };
struct Item { int kind; uint32_t index; }; // (UBO: the constant buffer index; TEX: the stage's texture slot)
struct MStage { int nvn; std::vector<Item> items; }; // (in the build's order: constant buffers, storage buffers, textures)
struct MProg { int id; std::vector<MStage> stages; Plan plan; };
static void make_plan(MProg& p) {
Maker m(p.plan);
m.begin(&p, false, false, false);
for (const MStage& st : p.stages) {
m.stage(st.nvn);
for (const Item& it : st.items) switch (it.kind) {
case BANK0: m.cbuf(0); break;
case BANK2: m.cbuf(2); break;
case C1: m.cbuf(1); break;
case UBO: m.cbuf(it.index); break;
case SSBO: m.storage(1, false, false, false, 0, 0x100); break;
case SSBO_WRITTEN: m.storage(1, true, false, false, 0, 0x100); break;
case TEX: m.texture(1, false, 2, false, 0); break;
case TEX_FROM_C3: m.texture(1, false, 3, false, 0); break;
}
}
m.end();
}
struct Out {
uint64_t a = 0, b = 0, c = 0;
bool operator==(const Out& o) const { return a == o.a && b == o.b && c == o.c; }
};
enum : uint64_t { BANKBUF = 0x1000, C1BUF = 0x2000, POOL = 0x3000, STREAM = 0x4000, SSBUF = 0x5000 };
struct World {
// the stamps, the registrations and the state's bindings
Stamps st;
uint64_t reg = 1;
uint32_t slotver[8]{};
uint64_t bind_gen = 1, tex_gen[8]{}, ssbo_gen[8]{};
uint64_t ubo[8][16]{}; // (an address; odd: one copied into the recording's stream, never kept)
uint32_t tex[8][4]{}; // (handles; 0: none)
uint64_t ssbo[8]{};
bool mirror_next = false; // (the next uniform buffer resolved makes a mirror: the bind stamp moves)
// the recording thread's
std::array<desc_keep::Prog, desc_keep::kSlots> kept;
struct Bank { bool on = false; uint64_t gen = 0, at = 0; } bank[2][8];
uint64_t bank_at = 0, stream_at = 0;
std::vector<Out> bufs, imgs; // (dw())
const void* built_for = nullptr;
Last last;
int ubo_resolves = 0;
// draw()'s bookkeeping
bool last_valid = false;
const void* last_prog = nullptr;
uint64_t last_bind = 0, last_ub = 0, last_reg = 0, last_destroy = 0;
};
static Out ubo_out(World& w, MProg& p, size_t j, int nvn, uint32_t index) { // (kept_uniform)
desc_keep::Elem& e = desc_keep::prog_of(w.kept, &p, p.plan.n).e[j];
const uint64_t addr = w.ubo[nvn][index - 3];
Stamps now;
now.rec = w.st.rec, now.bind = w.st.bind, now.ub = w.st.ub;
if (desc_keep::take(e, desc_keep::kUbo, addr, 64, 0, now)) return {e.out[0], e.out[1], e.out[2]};
w.ubo_resolves++;
Out o;
if (!addr) {
desc_keep::drop(e);
return o;
}
if (addr & 1) o = {STREAM, w.stream_at += 64, 64}, desc_keep::drop(e);
else o = {POOL, addr * 16 + w.st.bind * 3 + w.st.ub * 5, 64}, desc_keep::keep(e, desc_keep::kUbo, addr, 64, 0, now, o.a, o.b, o.c);
if (w.mirror_next) w.mirror_next = false, w.st.bind++;
return o;
}
static void whole_build(World& w, MProg& p) { // (build_descriptors)
w.bufs.clear(), w.imgs.clear();
w.built_for = &p;
desc_keep::Prog& kp = desc_keep::prog_of(w.kept, &p, p.plan.n);
size_t j = 0;
for (size_t si = 0; si < p.stages.size(); si++) {
const int nvn = p.stages[si].nvn;
for (const Item& it : p.stages[si].items) {
desc_keep::Elem& e = kp.e[j];
switch (it.kind) {
case BANK0: case BANK2: { // (uniform_range's cache: by the stage's generation)
World::Bank& c = w.bank[it.kind == BANK2][nvn];
const uint64_t gen = it.kind == BANK2 ? w.tex_gen[nvn] : w.ssbo_gen[nvn];
if (!c.on || c.gen != gen) c = {true, gen, ++w.bank_at};
w.bufs.push_back({BANKBUF, c.at, 16});
break;
}
case C1: {
Stamps now;
now.rec = w.st.rec;
const uint64_t in = (uint64_t)p.id * 8 + si + 1;
if (!desc_keep::take(e, desc_keep::kC1, in, 0, 0, now))
desc_keep::keep(e, desc_keep::kC1, in, 0, 0, now, C1BUF, w.st.rec * 100 + in, 16);
w.bufs.push_back({e.out[0], e.out[1], e.out[2]});
break;
}
case UBO: w.bufs.push_back(ubo_out(w, p, j, nvn, it.index)); break;
case SSBO: case SSBO_WRITTEN: {
const uint64_t addr = w.ssbo[nvn];
Stamps now;
now.rec = w.st.rec, now.bind = w.st.bind;
const bool kept = it.kind == SSBO;
if (kept && desc_keep::take(e, desc_keep::kSsbo, addr, 64, 0, now)) {
w.bufs.push_back({e.out[0], e.out[1], e.out[2]});
break;
}
const Out o = addr ? Out{SSBUF, addr * 8 + w.st.bind * 1000003 + w.st.rec * 7, 64} : Out{};
if (kept && addr) desc_keep::keep(e, desc_keep::kSsbo, addr, 64, 0, now, o.a, o.b, o.c);
else desc_keep::drop(e);
w.bufs.push_back(o);
break;
}
case TEX: case TEX_FROM_C3: {
const uint32_t handle = it.kind == TEX ? w.tex[nvn][it.index] : (uint32_t)((w.ubo[nvn][0] >> 1) % 7);
if (!handle) { // (no result kept: the dummy and its sampler each time)
w.imgs.push_back({5 + w.st.samp * 1000, 1, 0});
break;
}
Stamps now;
now.samp = w.st.samp, now.destroy = w.st.destroy, now.dummy = w.st.dummy, now.epoch = w.st.epoch;
const uint32_t version = w.slotver[handle];
if (!desc_keep::take(e, desc_keep::kTex, handle, 0, version, now))
desc_keep::keep(e, desc_keep::kTex, handle, 0, version, now, handle * 31 + w.st.samp * 1000,
handle * 1000003ull + version * 7 + w.st.destroy * 13 + w.st.epoch * 17 + w.st.dummy * 19, handle);
w.imgs.push_back({e.out[0], e.out[1], e.out[2]});
break;
}
}
j++;
}
}
}
static Why try_fast(World& w, MProg& p) { // (ubo_only_build, up to the uniform buffers)
return decide(w.last, p.plan, &p, w.built_for, w.last_valid && w.last_prog == &p, w.tex_gen, w.ssbo_gen, [&] { return w.st; }, w.reg,
[&](const Stamps& now) {
if (w.bufs.size() != p.plan.nbuf || w.imgs.size() != p.plan.nimg) return false;
return stands(p.plan, desc_keep::prog_of(w.kept, &p, p.plan.n).e, now, [&](uint32_t slot) { return w.slotver[slot]; },
[&](uint32_t at) { return w.bufs[at].a == 0; }, [&](uint32_t at) { return w.imgs[at].a == 0; });
});
}
static long mismatches, fasts, compared;
enum { REUSED = 100, MIRROR = 101 };
/// draw()'s descriptors: kept, the uniform buffers alone (checked against the whole build of the same state), or whole.
/// bind_ok: bind_descriptors did not leave the draw out
static int draw(World& w, MProg& p, bool bind_ok = true) {
if (w.last_valid && w.last_prog == &p && w.last_bind == w.bind_gen && w.last_ub == w.st.ub && w.last_reg == w.reg &&
w.last_destroy == w.st.destroy)
return REUSED;
World pre = w;
int why = try_fast(w, p);
bool fast = false;
if (why == kFast) {
for (const Ubo& u : p.plan.ubos) w.bufs[u.buf] = ubo_out(w, p, u.j, p.stages[u.stage].nvn, u.index);
fast = still(w.last, w.st);
if (fast) {
whole_build(pre, p);
compared++;
if (!(pre.bufs == w.bufs) || !(pre.imgs == w.imgs)) mismatches++;
} else {
why = MIRROR;
}
}
if (!fast) {
const Stamps before = w.st;
whole_build(w, p);
built(w.last, &p, w.tex_gen, w.ssbo_gen, before, 0, 0);
}
if (!bind_ok) return why;
if (fast) {
fasts++;
w.last_bind = w.bind_gen, w.last_ub = w.st.ub;
} else {
w.last_valid = true, w.last_prog = &p, w.last_bind = w.bind_gen, w.last_ub = w.st.ub, w.last_reg = w.reg;
w.last_destroy = w.st.destroy;
bound(w.last, &p);
}
return why;
}
static void bind_ubo(World& w, int nvn, uint32_t index, uint64_t addr) {
if (w.ubo[nvn][index - 3] != addr) w.bind_gen++;
w.ubo[nvn][index - 3] = addr;
}
static void bind_tex(World& w, int nvn, uint32_t slot, uint32_t handle) {
if (w.tex[nvn][slot] != handle) w.bind_gen++, w.tex_gen[nvn] = w.bind_gen;
w.tex[nvn][slot] = handle;
}
static void bind_ssbo(World& w, int nvn, uint64_t addr) {
if (w.ssbo[nvn] != addr) w.bind_gen++, w.ssbo_gen[nvn] = w.bind_gen;
w.ssbo[nvn] = addr;
}
static void new_recording(World& w) { // (draw_begin_recording)
w.st.rec++;
w.last_valid = false;
for (auto& row : w.bank)
for (auto& c : row) c = World::Bank{};
}
static void world_begin(World& w) {
for (int s = 0; s < 2; s++) {
for (uint32_t i = 3; i < 7; i++) w.ubo[s][i - 3] = 0x1000 * (s + 1) + 0x10 * i;
for (uint32_t t = 0; t < 4; t++) w.tex[s][t] = 1 + (s + t) % 6;
w.ssbo[s] = 0x9000 + s * 0x100;
}
}
static std::vector<Item> vertex_items() {
return {{BANK0, 0}, {C1, 0}, {BANK2, 0}, {UBO, 3}, {UBO, 4}, {SSBO, 0}, {TEX, 0}, {TEX, 1}};
}
static std::vector<Item> fragment_items() {
return {{BANK2, 0}, {UBO, 3}, {UBO, 5}, {TEX, 0}, {TEX, 1}, {TEX, 2}};
}
static bool impure(void (*f)(Maker&)) {
Plan plan;
Maker m(plan);
m.begin(&plan, false, false, false);
m.stage(0);
m.cbuf(3);
f(m);
m.end();
return !plan.pure && plan.ubos.empty() && plan.rest.empty();
}
int main() {
// the switch and the mode in a draw
want("the switch: on unless 0, check", mode_of(nullptr) == 1 && mode_of("1") == 1 && mode_of("") == 1 && mode_of("0") == 0 &&
mode_of("check") == 2 && mode_of("00") == 1);
Now n;
want("on by default", mode_now(n) == 1);
n.mode = 2;
want("check stays check", mode_now(n) == 2);
{
Now a = n; a.mode = 0; want("off with the switch", mode_now(a) == 0);
a = n; a.lab_off = true; want("off in the lab's phase", mode_now(a) == 0);
a = n; a.keep_mode = 0; want("off with the per-binding reuse off", mode_now(a) == 0);
a = n; a.keep_mode = 2; want("off with the per-binding reuse checked", mode_now(a) == 0);
a = n; a.sig_mode = 1; want("off with the signature skip on", mode_now(a) == 0);
a = n; a.snapshot = true; want("off with uniform buffer snapshots (Intel)", mode_now(a) == 0);
a = n; a.bank_gen_off = true; want("off with the banks kept by bind_gen", mode_now(a) == 0);
a = n; a.dump = true; want("off in a dump", mode_now(a) == 0);
a = n; a.retarget = true; want("off in the upscaler's second recording", mode_now(a) == 0);
a = n; a.strict = true; want("off for a strict draw", mode_now(a) == 0);
a = n; a.may_defer = false; want("off for a draw that may not leave textures for later", mode_now(a) == 0);
}
// the plan
MProg A{1, {{0, vertex_items()}, {1, fragment_items()}}, {}};
make_plan(A);
const Plan& pa = A.plan;
want("a plain program is taken", pa.pure && pa.prog == &A && pa.stages == 3 && pa.n == 14 && pa.nbuf == 9 && pa.nimg == 5);
want("its user uniform buffers, in the build's order",
pa.ubos.size() == 4 && pa.ubos[0].stage == 0 && pa.ubos[0].index == 3 && pa.ubos[0].j == 3 && pa.ubos[0].buf == 3 &&
pa.ubos[1].stage == 0 && pa.ubos[1].index == 4 && pa.ubos[1].j == 4 && pa.ubos[1].buf == 4 && pa.ubos[2].stage == 1 &&
pa.ubos[2].index == 3 && pa.ubos[2].j == 9 && pa.ubos[2].buf == 7 && pa.ubos[3].stage == 1 && pa.ubos[3].index == 5 &&
pa.ubos[3].j == 10 && pa.ubos[3].buf == 8);
bool rest_ok = pa.rest.size() == 10;
if (rest_ok) {
const Rest want_rest[10] = {{desc_keep::kNone, 0, 0}, {desc_keep::kC1, 1, 1}, {desc_keep::kNone, 2, 2}, {desc_keep::kSsbo, 5, 5},
{desc_keep::kTex, 6, 0}, {desc_keep::kTex, 7, 1}, {desc_keep::kNone, 8, 6}, {desc_keep::kTex, 11, 2},
{desc_keep::kTex, 12, 3}, {desc_keep::kTex, 13, 4}};
for (int i = 0; i < 10; i++)
rest_ok &= pa.rest[i].kind == want_rest[i].kind && pa.rest[i].j == want_rest[i].j && pa.rest[i].at == want_rest[i].at;
}
want("the descriptors beside them: banks, c1, the storage buffer, the textures, each at its place", rest_ok);
want("a handle read from c3 is never taken", impure([](Maker& m) { m.texture(1, false, 3, false, 0); }));
want("nor one from c4, nor a secondary word from c3", impure([](Maker& m) { m.texture(1, false, 4, false, 0); }) &&
impure([](Maker& m) { m.texture(1, false, 2, true, 3); }));
want("a secondary word that is not read does not count", !impure([](Maker& m) { m.texture(1, false, 2, false, 7); }));
want("a handle program's texture is never taken", impure([](Maker& m) { m.texture(1, true, 2, false, 0); }) &&
impure([](Maker& m) { m.texture(64, true, 0, false, 0); }));
want("a storage buffer named in c3 on", impure([](Maker& m) { m.storage(1, false, false, false, 3, 0x40); }) &&
impure([](Maker& m) { m.storage(1, false, false, false, 4, 0); }));
want("a storage buffer named in c0, c1 or c2 is taken", !impure([](Maker& m) { m.storage(1, false, false, false, 0, 0x100); }) &&
!impure([](Maker& m) { m.storage(1, false, false, false, 1, 0x20); }) &&
!impure([](Maker& m) { m.storage(1, false, false, false, 2, 0x20); }));
want("a written storage buffer", impure([](Maker& m) { m.storage(1, true, false, false, 0, 0x100); }));
want("a storage buffer table", impure([](Maker& m) { m.storage(3, false, false, false, 0, 0x880); }));
want("a run-time pointer's", impure([](Maker& m) { m.storage(1, false, true, false, 0, 0x100); }));
want("a turf list", impure([](Maker& m) { m.storage(1, false, false, true, 0, 0x100); }));
want("the miss binding", impure([](Maker& m) { m.storage(1, false, false, false, 0, 0xff0); }));
want("a texel buffer", impure([](Maker& m) { m.texel(1); }));
want("a storage image", impure([](Maker& m) { m.image(1); }));
want("a constant buffer past c18", impure([](Maker& m) { m.cbuf(19); }) && !impure([](Maker& m) { m.cbuf(18); }));
want("a compute, task or mesh stage", impure([](Maker& m) { m.stage(5); }) && impure([](Maker& m) { m.stage(6); }) &&
impure([](Maker& m) { m.stage(7); }) && impure([](Maker& m) { m.stage(-1); }) &&
!impure([](Maker& m) { m.stage(4); }));
{
Plan plan;
Maker m(plan);
m.begin(&plan, true, false, false), m.stage(0), m.cbuf(3), m.end();
const bool compute = !plan.pure;
m.begin(&plan, false, true, false), m.stage(0), m.cbuf(3), m.end();
const bool fallback = !plan.pure;
m.begin(&plan, false, false, true), m.stage(0), m.cbuf(3), m.end();
const bool renodx = !plan.pure;
m.begin(&plan, false, false, false), m.end();
const bool empty = !plan.pure;
m.begin(&plan, false, false, false), m.stage(0), m.cbuf(3), m.end();
want("compute, the mesh fallback, RenoDX's, a program with no stage: never; and the maker begins anew",
compute && fallback && renodx && empty && plan.pure && plan.ubos.size() == 1 && plan.n == 1);
}
{ // a slot another program took over: the plan made again in place, its lists' room kept (nothing allocated), every field anew
Plan plan, fresh;
Maker m(plan), f(fresh);
m.begin(&plan, false, false, false), m.stage(0), m.stage(1);
for (uint32_t i = 3; i < 19; i++) m.cbuf(i);
m.cbuf(1), m.storage(1, false, false, false, 0, 0x100), m.texture(6, false, 2, false, 0), m.end();
want("the first program's plan", plan.pure && plan.stages == 3 && plan.ubos.size() == 16 && plan.rest.size() == 8 && plan.n == 24 &&
plan.nbuf == 18 && plan.nimg == 6);
const Ubo* const ubos = plan.ubos.data();
const Rest* const rest = plan.rest.data();
const size_t room = plan.ubos.capacity(), rest_room = plan.rest.capacity();
m.begin(&fresh, false, false, false), m.stage(2), m.cbuf(4), m.texture(1, false, 0, false, 0), m.end();
f.begin(&fresh, false, false, false), f.stage(2), f.cbuf(4), f.texture(1, false, 0, false, 0), f.end();
want("made again in place: the lists' room kept", plan.ubos.data() == ubos && plan.rest.data() == rest && plan.ubos.capacity() == room &&
plan.rest.capacity() == rest_room);
bool same = plan.prog == fresh.prog && plan.pure == fresh.pure && plan.stages == fresh.stages && plan.n == fresh.n &&
plan.nbuf == fresh.nbuf && plan.nimg == fresh.nimg && plan.ubos.size() == fresh.ubos.size() &&
plan.rest.size() == fresh.rest.size();
for (size_t i = 0; same && i < plan.ubos.size(); i++)
same = plan.ubos[i].stage == fresh.ubos[i].stage && plan.ubos[i].index == fresh.ubos[i].index && plan.ubos[i].j == fresh.ubos[i].j &&
plan.ubos[i].buf == fresh.ubos[i].buf;
for (size_t i = 0; same && i < plan.rest.size(); i++)
same = plan.rest[i].kind == fresh.rest[i].kind && plan.rest[i].j == fresh.rest[i].j && plan.rest[i].at == fresh.rest[i].at;
want("made again in place: every field as a new plan's", same && fresh.pure && fresh.stages == 4 && fresh.n == 2);
m.begin(&plan, false, false, false), m.stage(0), m.texel(1), m.end();
want("an impure program after it: nothing of the others left", !plan.pure && plan.ubos.empty() && plan.rest.empty() && plan.n == 1 &&
plan.stages == 1 && plan.nbuf == 0 && plan.nimg == 0);
}
// the generations and the stamps
{
uint64_t t0[5] = {1, 2, 3, 4, 5}, s0[5] = {6, 7, 8, 9, 10}, t1[5] = {1, 2, 3, 4, 5}, s1[5] = {6, 7, 8, 9, 10};
want("the same generations", gens_same(0x1f, t0, s0, t1, s1));
t1[1] = 99;
want("a texture bound to a stage of the program", !gens_same(3, t0, s0, t1, s1) && gens_same(1, t0, s0, t1, s1));
t1[1] = 2, s1[0] = 99;
want("a storage buffer bound to a stage of the program", !gens_same(3, t0, s0, t1, s1) && gens_same(2, t0, s0, t1, s1));
Stamps a, b;
want("the same stamps", stamps_same(a, b));
b.ub = 7;
want("the inline updates' generation is the uniform buffers' own", stamps_same(a, b));
b = a, b.rec = 1; const bool rec = !stamps_same(a, b);
b = a, b.bind = 1; const bool bind = !stamps_same(a, b);
b = a, b.samp = 1; const bool samp = !stamps_same(a, b);
b = a, b.destroy = 1; const bool destroy = !stamps_same(a, b);
b = a, b.dummy = 1; const bool dummy = !stamps_same(a, b);
b = a, b.epoch = 1; const bool epoch = !stamps_same(a, b);
want("every other stamp stops it", rec && bind && samp && destroy && dummy && epoch);
}
// the rule on the model
MProg B{2, {{0, vertex_items()}, {1, fragment_items()}}, {}}; // (the same shape: another program)
MProg C{3, {{0, {{BANK2, 0}, {UBO, 3}, {UBO, 4}, {TEX_FROM_C3, 0}, {TEX, 1}}}, {1, fragment_items()}}, {}}; // (a handle in c3)
MProg D{4, {{0, {{BANK0, 0}, {UBO, 3}, {SSBO_WRITTEN, 0}}}, {1, fragment_items()}}, {}}; // (writes a storage buffer)
MProg E{5, {{0, vertex_items()}, {1, fragment_items()}}, {}}; // (a dispatch's stand-in: built, never bound by a draw)
make_plan(B), make_plan(C), make_plan(D), make_plan(E);
want("the handle from c3 and the written storage buffer make their programs whole builds", !C.plan.pure && !D.plan.pure && B.plan.pure);
{
World w;
world_begin(w);
want("a program's first draw builds whole", draw(w, A) == kOther && w.bufs.size() == 9 && w.imgs.size() == 5);
want("nothing bound: kept as before", draw(w, A) == REUSED);
const std::vector<Out> bufs0 = w.bufs, imgs0 = w.imgs;
const int r0 = w.ubo_resolves;
bind_ubo(w, 1, 5, 0x7770); // (the fragment stage's slot 2)
want("only uniform buffer slot 2 moved: the uniform buffers alone", draw(w, A) == kFast && mismatches == 0 && compared == 1);
bool others = w.imgs == imgs0 && w.bufs.size() == bufs0.size();
for (size_t i = 0; others && i < w.bufs.size(); i++) others = i == 8 ? !(w.bufs[i] == bufs0[i]) : w.bufs[i] == bufs0[i];
want("exactly that one resolved, the rest as they were", w.ubo_resolves == r0 + 1 && others);
bind_ubo(w, 0, 3, 0x7781); // (an odd address: a copy in the stream, never kept)
const int r1 = w.ubo_resolves;
want("a stream copy: the uniform buffers alone", draw(w, A) == kFast && w.ubo_resolves == r1 + 1 && w.bufs[3].a == STREAM);
bind_ubo(w, 1, 5, 0x7790);
want("and it is made again by the next such build, as a whole build does", draw(w, A) == kFast && w.ubo_resolves == r1 + 3 &&
mismatches == 0);
bind_tex(w, 1, 2, 3);
bind_ubo(w, 1, 5, 0x77a0);
want("a texture bound between two draws: a whole build", draw(w, A) == kBound);
bind_ubo(w, 1, 5, 0x77b0);
want("then the uniform buffers alone again", draw(w, A) == kFast);
bind_tex(w, 4, 0, 3);
bind_ubo(w, 1, 5, 0x77c0);
want("a texture bound to a stage the program has not: still alone", draw(w, A) == kFast);
bind_ssbo(w, 0, 0x9990);
want("a storage buffer bound: a whole build", draw(w, A) == kBound);
for (int k = 0; k < 6; k++) {
bind_ubo(w, 0, 4, 0x8000 + 0x10 * k);
if (k == 0) w.st.bind++;
if (k == 1) w.st.samp++;
if (k == 2) w.st.destroy++;
if (k == 3) w.st.dummy++;
if (k == 4) w.st.epoch++;
if (k == 5) new_recording(w);
const int why = draw(w, A);
want("a stamp moved: a whole build", k == 5 ? why == kOther : why == kStale);
bind_ubo(w, 0, 4, 0x8008 + 0x10 * k);
want("and alone again after it", draw(w, A) == kFast);
}
bind_ubo(w, 0, 4, 0x8100);
w.st.ub++;
want("an inline update: the uniform buffers alone, resolved again", draw(w, A) == kFast && mismatches == 0);
bind_ubo(w, 0, 4, 0x8110);
w.reg++, w.slotver[7]++;
want("a slot registered that the program does not sample: alone, after a walk", draw(w, A) == kFast);
bind_ubo(w, 0, 4, 0x8120);
w.reg++, w.slotver[w.tex[1][0]]++;
want("a slot it samples registered anew: a whole build", draw(w, A) == kStale);
bind_ubo(w, 0, 4, 0x8130);
want("alone again", draw(w, A) == kFast);
whole_build(w, E); // (a dispatch builds its own over the draw's)
bind_ubo(w, 0, 4, 0x8140);
want("a dispatch's build in between: a whole build", draw(w, A) == kOther);
bind_ubo(w, 0, 4, 0x8150);
want("another program's draw in between: a whole build", draw(w, B) == kOther && draw(w, A) == kOther);
bind_ubo(w, 0, 4, 0x8160);
bind_tex(w, 0, 0, 2);
want("a whole build whose bind failed is not stood on", draw(w, A, false) == kBound);
bind_ubo(w, 0, 4, 0x8170);
want("(the next draw builds whole)", draw(w, A) == kOther);
bind_ubo(w, 0, 4, 0x8180);
w.mirror_next = true;
want("a mirror made while the uniform buffers resolve: the whole build follows", draw(w, A) == MIRROR);
bind_ubo(w, 0, 4, 0x8190);
want("then alone again", draw(w, A) == kFast);
bind_tex(w, 1, 0, 6);
w.mirror_next = true;
want("a whole build with a mirror made under it", draw(w, A) == kBound);
bind_ubo(w, 0, 4, 0x8198);
want("is not stood on: its stamps moved while it resolved", draw(w, A) == kStale);
bind_ubo(w, 0, 4, 0x81a0);
want("then alone", draw(w, A) == kFast);
bind_tex(w, 1, 1, 0);
bind_ubo(w, 0, 4, 0x81b0);
draw(w, A);
bind_ubo(w, 0, 4, 0x81c0);
want("a texture with no handle (the dummy): alone", draw(w, A) == kFast && w.imgs[3].b == 1);
draw(w, C);
bind_ubo(w, 0, 4, 0x81d0);
want("the program with a handle in c3: whole, always", draw(w, C) == kImpure);
bind_ubo(w, 0, 3, 0x81e4);
want("(its texture follows the uniform buffer)", draw(w, C) == kImpure);
draw(w, D);
bind_ubo(w, 0, 3, 0x81f0);
want("the program that writes a storage buffer: whole, always", draw(w, D) == kImpure);
want("every uniform-buffers-only build was the whole build's", mismatches == 0 && compared == fasts && fasts >= 14);
}
{ // stands, on its own: what a build dropped, and what is missing
World w;
world_begin(w);
draw(w, A);
std::vector<desc_keep::Elem> kept = desc_keep::prog_of(w.kept, &A, pa.n).e;
const auto ver = [&](uint32_t slot) { return w.slotver[slot]; };
const auto none = [](uint32_t) { return false; };
Stamps now = w.st;
want("a whole build's results stand", stands(pa, kept, now, ver, none, none));
want("not for another count of descriptors", !stands(pa, std::vector<desc_keep::Elem>(pa.n + 1), now, ver, none, none));
auto k2 = kept;
desc_keep::drop(k2[5]);
want("a storage buffer dropped", !stands(pa, k2, now, ver, none, none));
k2 = kept, desc_keep::drop(k2[1]);
want("c1 dropped", !stands(pa, k2, now, ver, none, none));
k2 = kept, k2[5].kind = desc_keep::kUbo;
want("another kind's result", !stands(pa, k2, now, ver, none, none));
k2 = kept, desc_keep::drop(k2[3]), desc_keep::drop(k2[10]);
want("a uniform buffer dropped does not matter: it is asked again", stands(pa, k2, now, ver, none, none));
k2 = kept, desc_keep::drop(k2[6]);
want("a texture with nothing kept and its sampler there: the dummy", stands(pa, k2, now, ver, none, none));
want("a sampler missing", !stands(pa, kept, now, ver, none, [](uint32_t at) { return at == 2; }));
want("a bank not made", !stands(pa, kept, now, ver, [](uint32_t at) { return at == 6; }, none) &&
stands(pa, kept, now, ver, [](uint32_t at) { return at == 3 || at == 1; }, none));
Stamps later = now;
later.epoch++;
want("a texture kept at another epoch", !stands(pa, kept, later, ver, none, none));
later = now, later.bind++;
want("a storage buffer kept at another bind stamp", !stands(pa, kept, later, ver, none, none));
later = now, later.rec++;
want("c1 kept in another recording", !stands(pa, kept, later, ver, none, none));
w.slotver[w.tex[0][1]]++;
want("a slot's version moved", !stands(pa, kept, now, ver, none, none));
want("never for a program that is not taken", !stands(C.plan, desc_keep::prog_of(w.kept, &C, C.plan.n).e, now, ver, none, none));
Last l;
want("no build yet: no candidate", !candidate(l, &A, &A, true));
built(l, &A, w.tex_gen, w.ssbo_gen, now, 2, 1);
want("built, not bound yet: no candidate", !candidate(l, &A, &A, true) && l.dummies == 2 && l.dummies_known == 1);
bound(l, &B);
want("another program bound: none", !candidate(l, &A, &A, true));
bound(l, &A);
want("bound: a candidate", candidate(l, &A, &A, true));
want("not with another program's build in dw(), nor other bookkeeping, nor for another program",
!candidate(l, &A, &E, true) && !candidate(l, &A, &A, false) && !candidate(l, &B, &B, true) && !candidate(l, nullptr, nullptr, true));
forget(l);
want("forgotten: none", !candidate(l, &A, &A, true));
}
{ // random: every input and stamp moved, five programs
World w;
world_begin(w);
std::mt19937 rng(20261126);
MProg* progs[5] = {&A, &B, &C, &D, &E};
MProg* at = &A;
const long before = fasts;
long stale = 0, boundn = 0, mirrors = 0;
for (int i = 0; i < 30000; i++) {
const uint32_t r = rng() % 100;
const int s = (int)(rng() % 2);
if (r < 50) bind_ubo(w, s, 3 + rng() % 4, 0x1000 + (rng() % 64) * 2 + (rng() % 9 == 0));
else if (r < 56) bind_tex(w, s, rng() % 4, rng() % 7);
else if (r < 59) bind_ssbo(w, s, 0x9000 + (rng() % 5) * 0x40);
else if (r < 61) new_recording(w);
else if (r < 63) w.st.bind++;
else if (r < 66) w.st.ub++;
else if (r < 68) w.st.samp++;
else if (r < 70) w.st.destroy++;
else if (r < 72) w.st.dummy++;
else if (r < 74) w.st.epoch++;
else if (r < 78) w.reg++, w.slotver[1 + rng() % 6]++;
else if (r < 80) w.mirror_next = true;
else if (r < 82) whole_build(w, E); // (a dispatch)
if (rng() % 4 == 0) at = progs[rng() % 4];
const int why = draw(w, *at, rng() % 20 != 0);
stale += why == kStale, boundn += why == kBound, mirrors += why == MIRROR;
}
want("random draws: each uniform-buffers-only build equals the whole build of the same state", mismatches == 0);
want("random draws: the rule is taken, and every way out of it too",
fasts - before > 1500 && stale > 100 && boundn > 100 && mirrors > 10);
printf("random: %ld uniform-buffers-only builds of 30000 draws (%ld stale, %ld bound, %ld mirrors)\n", fasts - before, stale, boundn,
mirrors);
}
// the check's buffer compare
want("check: the same buffer", buffer_same(false, 5, 16, 64, false, 5, 16, 64, false, true));
want("check: another offset", !buffer_same(false, 5, 16, 64, false, 5, 32, 64, false, true) &&
!buffer_same(true, 5, 16, 64, false, 5, 32, 64, false, true));
want("check: a uniform buffer copied twice into the stream: its range and bytes", buffer_same(true, 5, 16, 64, true, 5, 96, 64, true, true) &&
!buffer_same(true, 5, 16, 64, true, 5, 96, 64, true, false) &&
!buffer_same(true, 5, 16, 64, true, 5, 96, 128, true, true));
want("check: not for a buffer beside them, nor a copy against a pool's range",
!buffer_same(false, 5, 16, 64, true, 5, 96, 64, true, true) && !buffer_same(true, 5, 16, 64, true, 6, 96, 64, false, true) &&
!buffer_same(true, 0, 0, 64, true, 5, 96, 64, true, true));
if (fails) printf("uboonly: FAILED (%d of %d checks)\n", fails, checks);
else printf("uboonly: all %d checks passed\n", checks);
return fails != 0;
}
'''
# (a rule of the header, and what it is replaced by: each must make the driver fail)
MUTATIONS = [
("(tex_was[k] != tex_now[k] || ssbo_was[k] != ssbo_now[k])", "(ssbo_was[k] != ssbo_now[k])", "a texture bound to the program's stage"),
("(tex_was[k] != tex_now[k] || ssbo_was[k] != ssbo_now[k])", "(tex_was[k] != tex_now[k])", "a storage buffer bound to the program's stage"),
("return a.rec == b.rec && a.bind == b.bind && ", "return a.bind == b.bind && ", "a new recording"),
("a.rec == b.rec && a.bind == b.bind && ", "a.rec == b.rec && ", "the bind stamp"),
("a.samp == b.samp && ", "", "the samplers' generation"),
("a.destroy == b.destroy && ", "", "a texture destroyed"),
("a.dummy == b.dummy && a.epoch == b.epoch;", "a.epoch == b.epoch;", "a texture left for later"),
("a.dummy == b.dummy && a.epoch == b.epoch;", "a.dummy == b.dummy;", "the next submission's epoch"),
(" if (!stamps_same(l.at, now)) return kStale;\n", "", "the stamps since the whole build"),
(" if (l.walked && l.reg == reg_gen) return kFast;", " if (l.walked) return kFast;", "a slot registered anew after the walk"),
(" if (k == desc_keep::kTex && e.version != slot_version((uint32_t)(e.in[0] & 0xFFFFF))) return false;\n", " (void)slot_version;\n", "a slot's version"),
(" if (e.kind != k || e.at != desc_keep::stamps_of(k, now)) return false;", " if (e.at != desc_keep::stamps_of(k, now)) return false;",
"a result dropped"),
(" if (sampler_missing(r.at)) return false;\n", " (void)sampler_missing;\n", "a sampler missing"),
(" if (buffer_missing(r.at)) return false;\n", " (void)buffer_missing;\n", "a bank not made"),
("return prog && l.prog == prog && l.bound && built_for == prog && last_same;", "return prog && l.prog == prog && l.bound && last_same;",
"another build in dw()"),
("return prog && l.prog == prog && l.bound && built_for == prog && last_same;", "return prog && l.prog == prog && built_for == prog && last_same;",
"a whole build that was not bound"),
(" return stamps_same(l.at, after);\n}", " (void)l, (void)after;\n return true;\n}", "a mirror made while the uniform buffers resolve"),
(" if (cbuf_index >= 3 || (has_secondary && secondary_cbuf_index >= 3)) ok = false;",
" (void)cbuf_index, (void)has_secondary, (void)secondary_cbuf_index;", "a handle read from c3 on"),
(" if (handle_program) ok = false;", " (void)handle_program;", "a handle program"),
(" if (cbuf_index >= 3) ok = false;", "", "a storage buffer named in c3 on"),
(" if (count != 1 || written || native_bounds", " (void)written;\n if (count != 1 || native_bounds", "a written storage buffer"),
(" if (nvn_stage < 0 || nvn_stage >= kStages) ok = false;", " if (nvn_stage < 0 || nvn_stage >= 8) ok = false;", "a task or mesh stage"),
(" ok = !compute && !fallback && !renodx;", " ok = !compute && !renodx; (void)fallback;", "the mesh fallback"),
(" if (n.dump || n.retarget || n.strict || !n.may_defer) return 0;", " if (n.dump || n.retarget || n.strict) return 0;",
"a draw that may not leave textures for later"),
(" if (n.keep_mode != 1 || n.sig_mode != 0 || n.snapshot || n.bank_gen_off) return 0;", " if (n.keep_mode != 1 || n.sig_mode != 0 || n.bank_gen_off) return 0;",
"uniform buffer snapshots (Intel)"),
(" p.ubos.clear(), p.rest.clear(); // (their room kept: a slot another program takes over allocates nothing)\n"
" p.prog = prog, p.pure = false, p.stages = 0, p.n = p.nbuf = p.nimg = 0;\n", " p = Plan{};\n p.prog = prog;\n",
"the lists' room kept when another program takes the slot"),
("p.prog = prog, p.pure = false, p.stages = 0, p.n", "p.prog = prog, p.pure = false, p.n", "a plan's stages made anew"),
]
def block(text, marker):
start = text.index(marker)
at = text.index("{", start) + 1
depth = 1
while depth:
depth += (text[at] == "{") - (text[at] == "}")
at += 1
return text[start:at]
def need(ok, why):
if not ok:
raise SystemExit("FAIL: " + why)
def ordered(text, parts, why):
last = 0
for p in parts:
k = text.find(p, last)
need(k >= 0, why + " (missing, or out of order: " + p + ")")
last = k + len(p)
def check_source():
draw_cpp = (ROOT / "gpu/vk/vk_draw.cpp").read_text(encoding="utf-8")
need('#include "uboonly.h"' in draw_cpp, "vk_draw.cpp does not include uboonly.h")
mode = block(draw_cpp, "int ubo_only_mode() {")
ordered(mode, ["static const int mode = [] {", 'const char* const value = getenv("RX_VK_DESC_UBO_ONLY");',
"n.mode = uboonly::mode_of(value);", 'logf("vk: RX_VK_DESC_UBO_ONLY=%s is not 0, 1 or check: on", value);',
"n.keep_mode = desc_keep_mode(), n.sig_mode = desc_sig_mode(), n.snapshot = ub_snapshot_wanted();",
'n.bank_gen_off = getenv("RX_VK_BANK_GEN_OFF") != nullptr;', "const int m = uboonly::mode_now(n);", "if (m != 1)",
'logf("vk: uniform-buffer-only descriptor builds %s%s%s"', "return m;"],
"the switch is not RX_VK_DESC_UBO_ONLY read once, off with what the rule does not hold under, and said when not on")
now = block(draw_cpp, "int ubo_only_now(bool strict) {")
ordered(now, ["n.mode = ubo_only_mode();", "if (!n.mode) return 0;", 'n.lab_off = lab_ab::on("nouboonly");',
"n.dump = dump_on(), n.retarget = pre_retarget_on, n.strict = strict, n.may_defer = draw_may_defer;",
"return uboonly::mode_now(n);"],
"the mode in a draw does not read the lab's knob, the dump, the upscaler's second recording and the draw's deferral")
plan = block(draw_cpp, "const uboonly::Plan& ubo_only_plan(const Program& p) {")
ordered(plan, ["if (plan.prog == &p) return plan;", "if (!p.ready.load(std::memory_order_acquire)) {",
"m.begin(&p, p.compute, p.fallback, p.renodx != 0);", "for (const Stage& st : p.stages) {", "m.stage(st.nvn_stage);",
"for (const auto& d : info.constant_buffer_descriptors)", "for (uint32_t k = 0; k < d.count; k++) m.cbuf(d.index + k);",
"for (const auto& d : info.storage_buffers_descriptors)",
"m.storage(d.count, d.is_written, info.native_global_bounds, Shader::IsSimTurfStorage(d), d.cbuf_index, d.cbuf_offset);",
"for (const auto& d : info.texture_buffer_descriptors) m.texel(d.count);",
"for (const auto& d : info.image_buffer_descriptors) m.texel(d.count);", "for (const auto& d : info.texture_descriptors)",
"m.texture(d.count, d.handle_program != ~0U, d.cbuf_index, d.has_secondary, d.secondary_cbuf_index);",
"for (const auto& d : info.image_descriptors) m.image(d.count);", "m.end();"],
"the plan is not made from the program's lists in build_descriptors' order")
# (the build's own order, which the plan's places stand on: constant buffers, storage buffers, texel buffers, textures, images)
build = block(draw_cpp, "void build_descriptors(")
ordered(build, ["for (const auto& d : info.constant_buffer_descriptors) {", "for (const auto& d : info.storage_buffers_descriptors) {",
"texel_views(info.texture_buffer_descriptors", "texel_views(info.image_buffer_descriptors",
"for (const auto& d : info.texture_descriptors) {", "for (const auto& d : info.image_descriptors) {"],
"build_descriptors walks a stage's lists in another order than the plan's")
need("ub_prog_key = p.key;" in build and "dwr.prog = &p;" in build, "build_descriptors no longer sets the program's key and the writer's program")
stamps = block(draw_cpp, "desc_keep::Stamps ubo_only_stamps() {")
for part in ["now.rec = desc_rec", "now.bind = gpu_bind_stamp();", "now.samp = sampler_registrations_generation()",
"now.destroy = texture_destroy_generation();", "now.dummy = texture_dummy_generation()", "now.epoch = texture_epoch();"]:
need(part in stamps, "the stamps read for the rule lack " + part)
fn = block(draw_cpp, "bool ubo_only_build(")
lines = [line for line in fn.split("\n")[1:] if line.strip()]
need(lines[0].strip().startswith("auto& dwr = dw();") and len(re.findall(r"(?<![A-Za-z0-9_])dw\(\)", fn)) == 1,
"ubo_only_build does not take dw() once, at its top")
ordered(fn, ["if (!uboonly::candidate(l, &p, dwr.prog, last_same)) return false;", "const uboonly::Plan& plan = ubo_only_plan(p);",
"uboonly::decide(l, plan, &p, dwr.prog, last_same, s.tex_gen, s.ssbo_gen, ubo_only_stamps, reg_gen,",
"if (dwr.bufs.size() != plan.nbuf || dwr.imgs.size() != plan.nimg) return false;",
"uboonly::stands(plan, desc_keep::prog_of(kept_descs(), &p, plan.n).e, now,",
"return texture_slot_version((int)slot);", "dwr.bufs[at].buffer == VK_NULL_HANDLE", "dwr.imgs[at].sampler == VK_NULL_HANDLE",
"if (why != uboonly::kFast) {", "return false;", "ub_prog_key = p.key;",
"for (const uboonly::Ubo& u : plan.ubos) dwr.bufs[u.buf] = kept_uniform(&kp, u.j, s, p.stages[u.stage], u.index);",
"if (!uboonly::still(l, ubo_only_stamps())) {", "return false;", "sampled.clear();", "for (const void* t : built_textures())",
"if (static_cast<const Texture*>(t)->gpu_written) sampled.push_back(static_cast<const Texture*>(t));", "if (check) {",
"uo_check_armed = true;", "return false;", "count_add(st_uo_fast, 1), count_add(st_uo_ubos, (int64_t)plan.ubos.size());",
"return true;"],
"ubo_only_build: the rule, the key, every user uniform buffer through kept_uniform, the stamps again, the sampled textures")
need("build_descriptors(" not in fn and "uniform_range(" not in fn and "texture_view_of(" not in fn,
"ubo_only_build resolves something itself")
built = block(draw_cpp, "void ubo_only_built(")
ordered(built, ["if (uo) uboonly::built(uo_last, &p, s.tex_gen, s.ssbo_gen, before, dummies, dummies_known);", "else uboonly::forget(uo_last);",
"if (uo_check_armed) ubo_only_compare(p);"], "a whole build is not what the next draws' rule stands on, or is with the rule off")
cmp_fn = block(draw_cpp, "void ubo_only_compare(")
for part in ["count_add(st_uo_checked, 1);", "uboonly::buffer_same(", "c.imgs[i].sampler != dwr.imgs[i].sampler || c.imgs[i].imageView != dwr.imgs[i].imageView",
"c.sampled != draw_sampled()", "count_add(st_uo_bad, 1);", '"vk: uniform-buffer-only build check:']:
need(part in cmp_fn, "the check does not compare or count: " + part)
draw = block(draw_cpp, "void draw(VkCommandBuffer")
need(len(re.findall(r"(?<![A-Za-z0-9_])dw\(\)", draw)) == 4, "draw no longer has its four dw() (tests/test_tls_once.py)")
ordered(draw, ["const bool same_desc = same_gens || (sig_hit && sig_mode == 1);", "bool uo_fast = false;", "if (!same_desc) {",
"count_add(st_dk_builds, 1);", "const int uo = no_reuse ? 0 : ubo_only_now(strict);",
"uo_fast = uo && ubo_only_build(s, p, last_desc_valid && last_desc_prog == &p, reg_gen, uo == 2);", "if (!uo_fast) {",
"const desc_keep::Stamps uo_at = uo ? ubo_only_stamps() : desc_keep::Stamps{};", "build_descriptors(s, p, true, scene);",
"ubo_only_built(s, p, uo, uo_at, desc_dummies - dummies0, desc_dummies_known - known0);",
"if (!same_desc) gfx_sampled() = draw_sampled();",
"if (!bind_descriptors(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, p)) SKIP_HERE();", "if (uo_fast) {",
"last_desc_bind = s.bind_gen, last_desc_ub = ub_gen;", "} else {",
"last_desc_valid = true, last_desc_prog = &p, last_desc_bind = s.bind_gen, last_desc_reg = reg_gen;",
"last_desc_fp() = desc_fp()", "uboonly::bound(uo_last, &p);"],
"draw: the rule before the build, the whole build otherwise with the stamps read before it, the bookkeeping after the bind")
need(draw_cpp.count("build_descriptors(s, p, true, scene);") == 1, "a draw builds whole in more than one place")
need(draw_cpp.count("ubo_only_build(") == 2 and draw_cpp.count("uo_last") == block(draw_cpp, "bool ubo_only_build(").count("uo_last") +
built.count("uo_last") + draw.count("uo_last") + 1, "something else reads or sets the thread's last whole build")
report = block(draw_cpp, "void desc_report(double frames) {")
for part in ["st_uo_fast.load()", "st_uo_ubos.load()", "st_uo_same.load()", "st_uo_impure.load()", "st_uo_bound.load()", "st_uo_stale.load()",
"st_uo_checked.load()", "st_uo_bad.load()", "vk: a frame's uniform-buffer-only builds: %.0f of %.0f builds", "ubo_only_mode()"]:
need(part in report, "the frame statistics' line lacks " + part)
need(re.search(r"std::atomic<int64_t> st_uo_fast\{0\}", draw_cpp), "the counters are not relaxed atomics of the file")
header = (ROOT / "gpu/vk/uboonly.h").read_text(encoding="utf-8")
need("RX_VK_DESC_UBO_ONLY" in header and '"nouboonly"' in header and "(Triforce, 11-26)" in header, "the header's comment lacks the switch or the knob")
docs = (ROOT / "docs/development.md").read_text(encoding="utf-8")
row = [line for line in docs.splitlines() if line.startswith("| `RX_VK_DESC_UBO_ONLY=0` or `check` |")]
need(len(row) == 1 and "`gpu/vk/uboonly.h`" in row[0] and "`nouboonly`" in row[0] and "a frame's uniform-buffer-only builds" in row[0],
"docs/development.md: the switches table has no RX_VK_DESC_UBO_ONLY row with the header, the knob and the line")
lines = docs.splitlines()
need(lines[lines.index(row[0]) - 1].startswith("| `RX_VK_DESC_SIG=0` or `check` |"), "the row is not beside the descriptor switches")
for part, why in [("never over a build of the uniform buffers alone", "what check does not try (the default mode's chain)"),
("`tests/test_uboonly.py` alone", "that the chain is tried by the test alone"),
("resolves its user uniform buffers twice", "that check resolves the uniform buffers twice"),
("`RX_VK_DESC_SIG=1` or `check` (the signature skip, off by default)", "the signature skip's values that turn the rule off"),
("only stages 0 to 4 (no task or mesh stage) and set programs as well as push ones", "the stages and programs the rule takes"),
("nor the miss binding", "the miss binding"),
("any other integrated GPU whose pools have no VRAM mirror", "where uniform buffers are snapshots besides Intel"),
("only their uniform buffers count as resolved or taken", "what such builds add to the descriptors' line"),
("Any other value: on (told once)", "a value it does not know")]:
need(part in row[0], "docs/development.md: the RX_VK_DESC_UBO_ONLY row does not say " + why)
def compile_run(cxx, include, cpp, exe, quiet):
# (a mutation may leave a parameter unread: only that is let through)
r = subprocess.run([cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror"] + (["-Wno-unused-parameter"] if quiet else []) +
["-I" + str(include), str(cpp), "-o", str(exe)], capture_output=quiet, text=True)
if r.returncode:
return None, r.stderr or ""
try:
r = subprocess.run([str(exe)], capture_output=True, text=True, timeout=300)
except subprocess.TimeoutExpired:
return 1, "timed out"
return r.returncode, r.stdout
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--cxx", default="clang++")
parser.add_argument("--no-mutations", action="store_true", help="the driver and the source only")
args = parser.parse_args()
with tempfile.TemporaryDirectory(prefix="uboonly-") as tmp:
tmp = Path(tmp)
cpp = tmp / "uboonly_test.cpp"
cpp.write_text(DRIVER, encoding="utf-8")
rc, out = compile_run(args.cxx, ROOT / "gpu/vk", cpp, tmp / "uboonly.exe", False)
if rc is None:
raise SystemExit("FAIL: the driver does not compile against gpu/vk/uboonly.h")
print(out.rstrip())
if rc:
raise SystemExit("FAIL: the uniform-buffers-only build's checks failed")
survived = []
if not args.no_mutations:
header = (ROOT / "gpu/vk/uboonly.h").read_text(encoding="utf-8")
for i, (old, new, what) in enumerate(MUTATIONS):
need(header.count(old) == 1, "the mutation's text is not in the header once: %r" % old)
inc = tmp / ("m%d" % i)
inc.mkdir()
shutil.copy(ROOT / "gpu/vk/desc_keep.h", inc / "desc_keep.h")
(inc / "uboonly.h").write_text(header.replace(old, new), encoding="utf-8")
rc, out = compile_run(args.cxx, inc, cpp, tmp / ("m%d.exe" % i), True)
if rc is None:
raise SystemExit("FAIL: the mutation does not compile (%s):\n%s" % (what, out[-2000:]))
if rc == 0:
survived.append(what)
if survived:
raise SystemExit("FAIL: no check fails without: " + "; ".join(survived))
check_source()
print("PASS: a draw that only bound uniform buffers anew resolves those alone where a whole build would give the same (%d mutations "
"caught); RX_VK_DESC_UBO_ONLY=0 builds whole as before" % (0 if args.no_mutations else len(MUTATIONS)))
if __name__ == "__main__":
main()

118
tests/test_ui_hdr_renodx.py Normal file
View File

@@ -0,0 +1,118 @@
"""The overlays on an HDR10 window coded as RenoDX's encoder codes the game's own menus (gpu/vk/vk_imgui.cpp UiHdr,
ui_hdr_now, hdr10_of; no game).
(2026-11-26) The owner, of our options beside the game's own with HDR Native and RenoDX (PsychoV35, Color space DCI-P3):
"washed out ... correct the shading to be exactly the same color and shading of the vanilla options". RenoDX's encoder
(its zelda-oot-oz output shader) codes the finished picture, the game's menus in it, at the UI brightness row's nits, its
colours as the Color space row says (Display P3: more saturated), after the Gamma correction row's power, unless its tone
mapper and colour space are both Vanilla. The overlays were always at Paper white, BT.709, the sRGB curve. This compiles
the three, cut out of vk_imgui.cpp as they are, and checks:
- without RenoDX, or with both its rows Vanilla: Paper white, BT.709, the sRGB curve, as before;
- with RenoDX and PsychoV35: the UI brightness row's white;
- Color space DCI-P3: an orange's blue lower than BT.709's (more saturated), white the same code;
- Gamma correction 2.2: a dark brown's codes lower (darker shadows), white the same code.
python -I -B tests/test_ui_hdr_renodx.py [--cxx clang++]
"""
import argparse
import subprocess
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
VK = ROOT / "gpu" / "vk"
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
def check(ok, why):
if not ok:
raise SystemExit("FAIL: " + why)
def function(text, head):
start = text.index(head)
end = text.index("{", start) + 1
depth = 1
while depth:
depth += (text[end] == "{") - (text[end] == "}")
end += 1
if text[end:end + 1] == ";":
end += 1
return text[start:end]
PROGRAM = r"""
#include <algorithm>
#include <cmath>
#include <cstdio>
typedef unsigned int ImU32;
#define IM_COL32_R_SHIFT 0
#define IM_COL32_G_SHIFT 8
#define IM_COL32_B_SHIFT 16
#define IM_COL32_A_MASK 0xFF000000u
#define IM_COL32_WHITE 0xFFFFFFFFu
struct Opts { int hdr_white = 200, hdr = 2, rdx_space = 0, rdx_tonemap = 0, rdx_ui_white = 200, rdx_gamma = 0; } opts;
static bool renodx = true;
bool renodx_chosen() { return renodx; }
%(ui)s
static ImU32 rgb(int r, int g, int b) { return 0xFF000000u | (ImU32)b << 16 | (ImU32)g << 8 | (ImU32)r; }
static int ch(ImU32 c, int k) { return (int)(c >> (8 * k) & 0xFF); }
int main() {
int fails = 0;
const ImU32 orange = rgb(211, 144, 37), brown = rgb(48, 34, 21), white = rgb(255, 255, 255);
// (Vanilla and Vanilla: as before)
opts.rdx_tonemap = 0, opts.rdx_space = 0, opts.hdr_white = 300, opts.rdx_ui_white = 100;
UiHdr u = ui_hdr_now();
if (u.white != 300 || u.p3 || u.gamma != 0) std::puts("FAIL: RenoDX with its Vanilla rows is not as before"), fails++;
renodx = false, opts.rdx_tonemap = 1, opts.rdx_space = 2;
u = ui_hdr_now();
if (u.white != 300 || u.p3 || u.gamma != 0) std::puts("FAIL: without RenoDX the rows count"), fails++;
renodx = true, opts.hdr = 1;
u = ui_hdr_now();
if (u.white != 300 || u.p3) std::puts("FAIL: the SDR picture made HDR takes RenoDX's rows"), fails++;
opts.hdr = 2, opts.hdr_white = 200, opts.rdx_ui_white = 200, opts.rdx_space = 1;
u = ui_hdr_now();
if (u.white != 200 || u.p3) std::puts("FAIL: PsychoV35, BT.709: not the UI brightness, BT.709"), fails++;
const ImU32 o709 = hdr10_of(orange, u), w709 = hdr10_of(white, u), b709 = hdr10_of(brown, u);
opts.rdx_space = 2;
u = ui_hdr_now();
if (!u.p3) std::puts("FAIL: Color space DCI-P3 not taken"), fails++;
const ImU32 op3 = hdr10_of(orange, u), wp3 = hdr10_of(white, u);
if (!(ch(op3, 2) < ch(o709, 2) && ch(op3, 0) > ch(o709, 0)))
std::printf("FAIL: P3's orange not more saturated: %d,%d,%d against %d,%d,%d\n", ch(op3, 0), ch(op3, 1), ch(op3, 2), ch(o709, 0), ch(o709, 1), ch(o709, 2)), fails++;
for (int k = 0; k < 3; k++)
if (std::abs(ch(wp3, k) - ch(w709, k)) > 1) std::puts("FAIL: white is not white in P3"), fails++;
opts.rdx_space = 1, opts.rdx_gamma = 1;
u = ui_hdr_now();
const ImU32 b22 = hdr10_of(brown, u), w22 = hdr10_of(white, u);
if (u.gamma != 2.2f || !(ch(b22, 0) < ch(b709, 0))) std::puts("FAIL: gamma 2.2 does not darken the shadows"), fails++;
if (ch(w22, 0) != ch(w709, 0)) std::puts("FAIL: gamma 2.2 moved white"), fails++;
opts.rdx_ui_white = 400, opts.rdx_gamma = 0;
u = ui_hdr_now();
if (!(ch(hdr10_of(white, u), 0) > ch(w709, 0))) std::puts("FAIL: the UI brightness does not raise white"), fails++;
return fails;
}
"""
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cxx", default="clang++")
args = parser.parse_args()
imgui = (VK / "vk_imgui.cpp").read_text(encoding="utf-8")
ui = "\n".join([function(imgui, "struct UiHdr {"), function(imgui, "UiHdr ui_hdr_now() {"), function(imgui, "ImU32 hdr10_of(ImU32 c, const UiHdr& u) {")])
check("static const float kP3[9] = {0.753833f, 0.198597f, 0.047570f" in ui, "hdr10_of has no Display P3 to Rec. 2020 matrix")
check("const UiHdr u = ui_hdr_now();" in function(imgui, "void hdr10(ImDrawData* dd) {"), "the draw lists are not coded by ui_hdr_now")
check(imgui.count("hdr10_texel(c, u)") == 1, "the textures are not coded by ui_hdr_now")
with tempfile.TemporaryDirectory(prefix="ui-hdr-") as tmp:
src, exe = Path(tmp) / "ui.cpp", Path(tmp) / "ui.exe"
src.write_text(PROGRAM.replace("%(ui)s", ui), encoding="utf-8")
subprocess.run([args.cxx, "-std=c++20", "-O1", "-w", str(src), "-o", str(exe)], check=True)
r = subprocess.run([str(exe)], capture_output=True, text=True)
check(r.returncode == 0, "the overlays' HDR coding:\n" + r.stdout)
print("PASS: the overlays on an HDR10 window coded as RenoDX codes the game's menus")
if __name__ == "__main__":
main()

View File

@@ -58,7 +58,7 @@ using VkSampleCountFlagBits = uint32_t;
using VkImageLayout = uint32_t;
using VkFilter = uint32_t;
constexpr uint32_t VK_FORMAT_UNDEFINED = 0, VK_FORMAT_B10G11R11_UFLOAT_PACK32 = 122,
VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 = 123, VK_FORMAT_R8G8B8A8_UNORM = 37;
VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 = 123, VK_FORMAT_R8G8B8A8_UNORM = 37, VK_FORMAT_R16G16B16A16_SFLOAT = 97;
constexpr uint32_t VK_IMAGE_TYPE_2D = 1, VK_IMAGE_ASPECT_COLOR_BIT = 1, VK_SAMPLE_COUNT_1_BIT = 1,
VK_IMAGE_LAYOUT_GENERAL = 1, VK_FILTER_LINEAR = 1;
constexpr uint32_t VK_FORMAT_FEATURE_BLIT_SRC_BIT = 1, VK_FORMAT_FEATURE_BLIT_DST_BIT = 2,
@@ -203,6 +203,8 @@ bool fsr3_upscale(VkCommandBuffer, uint64_t, bool known, Texture *in, VkImageVie
fsr3_calls++;
return true;
}
/* ((Triforce, 11-26) the RGBA16F scene's squared upscale (vk_draw.cpp wide_upscale): no picture here is RGBA16F */
static bool wide_upscale(VkCommandBuffer, VkImageView, Texture *, uint32_t, uint64_t, const char *, bool) { return false; }
static bool typed_upscale(VkCommandBuffer, VkImageView input, VkImageView output, Texture *t,
uint32_t level, uint64_t, const char *, bool temporal) {
assert(input == (VkImageView)101 && output == (VkImageView)102 && t == &dst && level == 0 &&

View File

@@ -94,10 +94,10 @@ def check_source():
order = [stand.find(n) for n in (
"const bool off = upscale_off_on();",
"upscale_off::choose(taau_key(p.key), off, gameplay_network(p.key), shaped, n64);",
"if (!ch.stand_in) return false;",
"if (!ch.stand_in && !wide) return false;", # ((Triforce, 11-26) the RGBA16F scene's 3/4 network too: wide_upscale
"if (ch.by_shape) {",
"if (!in || in->format != VK_FORMAT_E5B9G9R9_UFLOAT_PACK32) return false;",
"if (!out || out->format != VK_FORMAT_B10G11R11_UFLOAT_PACK32) return false;",
"if (!ch.stand_in || !out || out->format != VK_FORMAT_B10G11R11_UFLOAT_PACK32) return false;",
"done = typed_upscale(cmd, dw().imgs[0].imageView, dw().imgs[ntex].imageView, out, level, p.key, keys, ch.temporal);",
"if (done) hudless_after_dispatch(cmd, p.key);")]
if min(order) < 0 or order != sorted(order):

View File

@@ -127,16 +127,16 @@ def main():
if "| `RX_VK_DLSS_CNN_VRAM=1` |" not in (ROOT / "docs" / "development.md").read_text(encoding="utf-8"):
raise SystemExit("docs/development.md has no row for RX_VK_DLSS_CNN_VRAM")
temporal = (ROOT / "gpu" / "vk" / "vk_temporal.cpp").read_text(encoding="utf-8")
mode = function(temporal, "int temporal_mode() {")
mode = function(temporal, "int temporal_mode_of(int choice, bool now) {") # ((Triforce, 11-26) temporal_mode's, for a choice)
if "dlss_why() != DLSS_OK" not in mode or "fsr4_why() != FSR_OK" not in mode:
raise SystemExit("temporal_mode asks for an engine where it cannot run (DLAA or FSR 4's native AA would hold the 3D at "
"full scale for nothing)")
if "std::clamp(" in mode:
raise SystemExit("temporal_mode clamps the row's value: FSR 3.1 (3) would run on the chain")
if "fsr3_wanted()" not in mode:
if "fsr3_wanted_of(choice, now)" not in mode:
raise SystemExit("temporal_mode runs DLSS or FSR 4 while FSR 3.1 upscales (two upscalers, two jitters)")
fsr3 = (ROOT / "gpu" / "vk" / "vk_fsr3.cpp").read_text(encoding="utf-8")
if "!temporal_env_chosen()" not in function(fsr3, "bool fsr3_wanted() {"):
if "!temporal_env_chosen()" not in function(fsr3, "bool fsr3_wanted_of(int choice, bool now) {"):
raise SystemExit("fsr3_wanted: a saved FSR 3.1 drops RX_VK_DLSS / RX_VK_FSR4, which go over the row")
chosen = function(temporal, "bool temporal_env_chosen() {")
if "dlss_why() == DLSS_OK" not in chosen or "fsr4_why() == FSR_OK" not in chosen:

View File

@@ -53,7 +53,7 @@ def cut(source):
typedef(source, "AVCodecContext *ctx;", "} Dec;"),
])
calls = "\n".join(block(source, marker) for marker in (
"static void dec_submit(Ctx *c) {", "static void dec_flush(Ctx *c, const char *what) {",
"static void dec_submit(Ctx *c) {", "static void flush_locked(Dec *d) {", "static void dec_flush(Ctx *c, const char *what) {",
"static void dec_acquire(Ctx *c) {"))
return types, calls

View File

@@ -166,12 +166,15 @@ def main():
vf.check(told in init and init.index(rule) < init.index("avcodec_open2(") < init.index(told) < init.index("av1_notice"),
"Media Foundation is no longer the fallback of a libdav1d that does not open, with the notice last")
nxt = vf.block(video, "static void decode_next(Dec *d) {")
vf.check("const int64_t began = hos_now_ns();" in nxt and "const int64_t took = hos_now_ns() - began;" in nxt
and "video_movie_decoded(&d->movie, took);" in nxt
and nxt.index("began = hos_now_ns()") < nxt.index("mf_av1_decode(") < nxt.index("took = hos_now_ns() - began"),
# ((Triforce, 11-22) the decode itself is decode_one's now and its count decode_done's, shared with the decode-ahead worker)
done = vf.block(video, "static void decode_done(Dec *d, int end, int64_t ns, int live) {")
vf.check("const int64_t t0 = hos_now_ns();" in nxt and "decode_done(d, end, hos_now_ns() - t0, 1);" in nxt
and nxt.index("t0 = hos_now_ns()") < nxt.index("decode_one(d, n);") < nxt.index("decode_done(d, end, hos_now_ns() - t0, 1);")
and "video_movie_decoded(&d->movie, ns);" in done
and "mf_av1_decode(" in vf.block(video, "static void decode_one(Dec *d, Pending *n) {"),
"decode_next does not time each submission")
vf.check("d->movie.pictures++;" in vf.block(video, "static void queue_frame(Dec *d, const AVFrame *f) {"),
"queue_frame does not count the movie's pictures")
vf.check("d->movie.pictures++" in done and "movie" not in vf.block(video, "static void queue_frame(Dec *d, const AVFrame *f) {"),
"decode_done does not count the movie's pictures, or queue_frame counts them without the decoder's lock")
vf.check("d->movie.skipped += skipped;" in vf.block(video, "static void dec_acquire(Ctx *c) {"),
"the catch-up does not count what it skipped for the movie's line")
end = vf.block(video, "static void movie_end(Dec *d) {")
@@ -180,7 +183,7 @@ def main():
"movie_end does not log the line and start the counts again")
flush = vf.block(video, "static void dec_flush(Ctx *c, const char *what) {")
vf.check("movie_end(d);" in flush and
flush.index("AcquireSRWLockExclusive(&d->lock);") < flush.index("movie_end(d);") < flush.index("pending_free(d);"),
flush.index("AcquireSRWLockExclusive(&d->lock);") < flush.index("movie_end(d);") < flush.index("flush_locked(d);"),
"a Stop or a Flush does not end the movie's line under the decoder's lock")
vf.check("movie_end(d);" in vf.block(video, "static void dec_finalize(Ctx *c) {"), "the decoder's end does not end the movie's line")
dev = (vf.ROOT / "docs" / "development.md").read_text(encoding="utf-8")

View File

@@ -135,14 +135,17 @@ def main():
args = parser.parse_args()
video = vf.video_source()
vf.check('#include "video_catchup.h"' in video and "VideoPace pace;" in vf.block(video, "typedef struct {\n AVCodecContext *ctx;"),
vf.check('#include "video_catchup.h"' in video and " VideoPace pace;" in video,
"nn_video.c does not keep the movie's pace in its decoder")
vf.check("video_pace_picture(&d->pace, f->pts);" in vf.block(video, "static void queue_frame(Dec *d, const AVFrame *f) {"),
"queue_frame does not give each picture's time to the gap")
nxt = vf.block(video, "static void decode_next(Dec *d) {")
vf.check("const int64_t pictures = d->movie.pictures;" in nxt
and "if (d->movie.pictures != pictures) video_pace_decoded(&d->pace, took);" in nxt,
"decode_next does not keep what a decode that gave a picture took")
# ((Triforce, 11-22) with the pictures decoded ahead queue_frame runs on the worker without the decoder's lock, so the
# pace is counted where the decode's pictures are taken under it: decode_done, for the worker and for decode_next)
done = vf.block(video, "static void decode_done(Dec *d, int end, int64_t ns, int live) {")
vf.check("video_pace_picture(&d->pace, d->out[i].pts);" in done and "pace" not in vf.block(video, "static void queue_frame(Dec *d, const AVFrame *f) {"),
"decode_done does not give each picture's time to the gap, or queue_frame touches the pace without the lock")
vf.check("if (d->nout) video_pace_decoded(&d->pace, ns);" in done and "if (live) {" in done,
"decode_done does not keep what a decode that gave a picture took")
vf.check("decode_done(d, end, hos_now_ns() - t0, 1);" in vf.block(video, "static void decode_next(Dec *d) {"),
"decode_next no longer counts its decode")
vf.check("memset(&d->pace, 0, sizeof d->pace);" in vf.block(video, "static void movie_end(Dec *d) {"),
"a movie's end does not start the pace again")
acquire = vf.block(video, "static void dec_acquire(Ctx *c) {")
@@ -153,7 +156,7 @@ def main():
vf.check(stop in acquire, "the catch-up does not ask the rule with the time this acquire has spent")
loop = acquire[acquire.index("for (int guard = 0;"):]
loop = loop[:loop.index("if (skipped && video_log())")]
vf.check(loop.count("decode_next(d);") == 1 and loop.index("if (!d->phead) break;") < loop.index(stop) < loop.index("decode_next(d);"),
vf.check(loop.count("decode_next(d);") == 1 and loop.index("if (d->worker || !d->phead) break;") < loop.index(stop) < loop.index("decode_next(d);"),
"the catch-up decodes ahead before it asks the rule")
vf.check('getenv("HOS_VIDEO_NO_CATCHUP")' in acquire and "guard < 600" in acquire, "the catch-up lost its switch or its guard")
dev = (vf.ROOT / "docs" / "development.md").read_text(encoding="utf-8")

View File

@@ -0,0 +1,493 @@
"""A movie's pictures are decoded ahead of the game by a host thread of the decoder's (host/nn_video.c; no game, no decoder).
The pictures were decoded in the game's Acquire...DecoderOutputBuffer call: 3-13 ms each for the title screen's 1080p AV1
movie, single ones 80-200 ms, several in a row when the movie was behind its clock (728 ms in one call), and the movie
stuttered wherever a scene loads over it. Each decoder now has a host thread that decodes the submissions ahead and keeps
a few pictures queued. Checked here, in three parts:
1. the rules, cut out of nn_video.c unchanged and run: how many pictures are kept ahead (HOS_VIDEO_DECODE_AHEAD: unset
or 1 six, 0 none, 2 and more that many, two places of the queue left over), when the worker decodes the next
submission (the stream's end at once, a picture only below the count: never into a queue that has it), and when a
picture is behind the movie's clock (the catch-up's 25 ms);
2. the wiring, read: the worker lets the decoder's lock go before it decodes and takes it after; the decoding functions
touch neither the lock's fields nor guest memory; mf_av1_decode and avcodec_send_packet are called nowhere else; the
worker waits for room in a full queue instead of dropping; a flush takes the decoder from the worker first (counts
the flush, holds new decodes off, waits for the one in flight) and the close ends the worker before anything is
freed; with a worker the acquire decodes nothing, the catch-up included, and wakes the worker for the room it made;
the switch, the pictures-taken line and the development guide;
3. the threads, run (Windows: SRW locks and condition variables as the runtime uses them): the worker, the wait of an
acquire, the flush and the close are cut out of nn_video.c unchanged and driven by a stand-in decoder (random time,
frames held back, several pictures from one submission) and a stand-in game that submits, takes, flushes and closes
as dec_submit, dec_acquire, dec_flush and dec_finalize do. Every picture must come out once, in order, the
last one with the last flag, none of a flushed stream after its flush, never two threads in the decoder, nothing
leaked, and the run must end (a deadlock is a failure after two minutes). Run with 2, 6 and 14 pictures ahead.
python -I -B tests/test_video_decode_ahead.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]
RULES_MAIN = r'''
#define CHECK(x) do { if (!(x)) { fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); return 1; } } while (0)
int main(void) {
/* (the count: unset and 1 are the default, 0 and no number are off, the queue keeps two places) */
CHECK(VIDEO_AHEAD_PICTURES == 12 && VIDEO_AHEAD_PICTURES <= MAX_QUEUE - 2);
CHECK(video_ahead_count(NULL, MAX_QUEUE) == 12 && video_ahead_count("1", MAX_QUEUE) == 12);
CHECK(video_ahead_count("0", MAX_QUEUE) == 0 && video_ahead_count("", MAX_QUEUE) == 0);
CHECK(video_ahead_count("off", MAX_QUEUE) == 0 && video_ahead_count("-3", MAX_QUEUE) == 0);
CHECK(video_ahead_count("2", MAX_QUEUE) == 2 && video_ahead_count("12", MAX_QUEUE) == 12);
CHECK(video_ahead_count("14", 16) == 14 && video_ahead_count("15", 16) == 14 && video_ahead_count("999", 16) == 14);
CHECK(video_ahead_count(NULL, 8) == 6 && video_ahead_count(NULL, 6) == 4 && video_ahead_count(NULL, 3) == 1);
CHECK(video_ahead_count(NULL, 2) == 0 && video_ahead_count("5", 0) == 0);
/* (the worker: the end at once, a picture below the count only, nothing without a submission) */
for (int ahead = 1; ahead <= MAX_QUEUE - 2; ahead++)
for (int q = 0; q <= MAX_QUEUE; q++) {
CHECK(video_ahead_decode(1, 0, q, ahead) == (q < ahead));
CHECK(video_ahead_decode(1, 1, q, ahead) == 1);
CHECK(video_ahead_decode(0, 0, q, ahead) == 0 && video_ahead_decode(0, 1, q, ahead) == 0);
}
/* (late: the picture at 1.000 s was due at 5.000 s; at 5.100 s the picture of 1.100 s is due) */
const int64_t ms = 1000000, cp = 1000 * ms, cn = 5000 * ms, now = 5100 * ms;
CHECK(VIDEO_LATE_NS == 25 * ms);
CHECK(!video_picture_late(1100 * ms, cp, cn, now, VIDEO_LATE_NS));
CHECK(!video_picture_late(1075 * ms, cp, cn, now, VIDEO_LATE_NS)); /* 25 ms behind: not yet */
CHECK(video_picture_late(1075 * ms - 1, cp, cn, now, VIDEO_LATE_NS));
CHECK(video_picture_late(1000 * ms, cp, cn, now, VIDEO_LATE_NS));
CHECK(!video_picture_late(1200 * ms, cp, cn, now, VIDEO_LATE_NS)); /* decoded ahead: never late */
CHECK(!video_picture_late(cp, cp, cn, cn, VIDEO_LATE_NS)); /* the clock's own picture, at its time */
return 0;
}
'''
# (the stand-ins of the threads' fixture, before the parts cut out of nn_video.c)
STRESS_HEAD = r'''
#include <windows.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SLOTS 16
#define CHECK(x) do { if (!(x)) { fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); fflush(stderr); ExitProcess(1); } } while (0)
static volatile LONG live; /* allocations not freed yet */
static void *t_calloc(size_t a, size_t b) { void *p = calloc(a, b); CHECK(p); InterlockedIncrement(&live); return p; }
static void *t_realloc(void *p, size_t n) { if (!p) InterlockedIncrement(&live); p = realloc(p, n); CHECK(p); return p; }
static void t_free(void *p) { if (p) InterlockedDecrement(&live); free(p); }
#define calloc t_calloc
#define realloc t_realloc
#define free t_free
typedef struct AVCodecContext AVCodecContext;
typedef struct AVFrame AVFrame;
typedef struct AVPacket { int64_t pts; int size; } AVPacket; /* (size: the stream the packet is of) */
static void av_packet_free(AVPacket **p) { free(*p); *p = NULL; }
static int64_t hos_now_ns(void) {
LARGE_INTEGER f, c;
QueryPerformanceFrequency(&f), QueryPerformanceCounter(&c);
return (int64_t)(c.QuadPart / f.QuadPart * 1000000000LL + c.QuadPart % f.QuadPart * 1000000000LL / f.QuadPart);
}
/* (as the runtime's with virtual cores, host/hos_thread.c: after the wait the lock is let go while a core is taken again) */
static int hos_cv_sleep(void *cv, void *lk, unsigned ms) {
const BOOL r = SleepConditionVariableSRW((PCONDITION_VARIABLE)cv, (PSRWLOCK)lk, ms, 0);
ReleaseSRWLockExclusive((PSRWLOCK)lk);
SwitchToThread();
AcquireSRWLockExclusive((PSRWLOCK)lk);
return r;
}
static int hos_vcore_away(void) { return 0; }
static void hos_vcore_back(void) {}
static void hos_host_thread_register_self(const char *name) { (void)name; }
static void hos_thread_pin(void *h, const char *name) { (void)h, (void)name; }
static void hos_log(const char *fmt, ...) { (void)fmt; }
static void spin_us(int us) {
const int64_t until = hos_now_ns() + (int64_t)us * 1000;
while (hos_now_ns() < until) YieldProcessor();
}
static unsigned rnd(unsigned *s) { return (*s = *s * 1664525u + 1013904223u) >> 8; }
'''
# (the stand-in decoder and game, after them)
STRESS_MAIN = r'''
/* the stand-in decoder: one thread in it at a time (in_decoder), a random time for each submission, the frames of a
stream held back by (stream % 5) submissions, so one submission gives none, one or, at the end, several pictures */
static volatile LONG in_decoder;
static struct { int64_t pts; int stream; } held[8];
static int nheld;
static unsigned dec_rnd = 7;
static void emit(Dec *d) {
Picture p;
memset(&p, 0, sizeof p);
p.nv12 = (uint8_t *)calloc(1, 16);
p.w = held[0].stream, p.h = 1, p.pts = held[0].pts;
memmove(held, held + 1, (size_t)--nheld * sizeof held[0]);
CHECK(out_push(d, &p));
}
static void decode_one(Dec *d, Pending *n) {
CHECK(InterlockedExchange(&in_decoder, 1) == 0);
spin_us((int)(rnd(&dec_rnd) % 120));
if (n->pkt) {
held[nheld].pts = n->pkt->pts, held[nheld].stream = n->pkt->size, nheld++;
while (nheld > n->pkt->size % 5) emit(d);
} else {
while (nheld) emit(d);
}
av_packet_free(&n->pkt);
free(n);
CHECK(InterlockedExchange(&in_decoder, 0) == 1);
}
static void avcodec_flush_buffers(AVCodecContext *c) { (void)c; CHECK(0); }
static void mf_av1_flush(void *m) { /* (the flush has the decoder: the worker is not in it) */
(void)m;
CHECK(InterlockedExchange(&in_decoder, 1) == 0);
nheld = 0;
CHECK(InterlockedExchange(&in_decoder, 0) == 1);
}
''' + "__CUT_AFTER_DECODER__" + r'''
/* the stand-in game, as dec_submit, dec_acquire, dec_flush and dec_finalize use the parts above */
static void submit(Dec *d, int stream, int64_t pts, int last) {
AcquireSRWLockExclusive(&d->lock);
AVPacket *pkt = (AVPacket *)calloc(1, sizeof *pkt);
pkt->pts = pts, pkt->size = stream;
pending_push(d, pkt);
if (last) pending_push(d, NULL);
if (d->worker) WakeAllConditionVariable(&d->work);
ReleaseSRWLockExclusive(&d->lock);
}
static int64_t longest_wait;
static int take(Dec *d, Picture *got) { /* 1: the oldest picture; 0: none (the end, or nothing submitted) */
AcquireSRWLockExclusive(&d->lock);
const int64_t waited = ahead_wait(d);
if (waited > longest_wait) longest_wait = waited;
CHECK(d->qn >= 0 && d->qn <= MAX_QUEUE);
if (!d->qn) {
CHECK(!d->phead && !d->decoding && !d->uncommitted); /* (none is on its way) */
ReleaseSRWLockExclusive(&d->lock);
return 0;
}
CHECK(d->qn > 1 || !tail_unsettled(d));
*got = d->queue[d->qhead];
memset(&d->queue[d->qhead], 0, sizeof d->queue[0]);
d->qhead = (d->qhead + 1) % MAX_QUEUE, d->qn--;
if (d->worker) WakeAllConditionVariable(&d->work);
ReleaseSRWLockExclusive(&d->lock);
return 1;
}
static void flush(Dec *d) {
AcquireSRWLockExclusive(&d->lock);
flush_locked(d);
CHECK(!d->qn && !d->phead && !d->eos && !d->hold);
ReleaseSRWLockExclusive(&d->lock);
}
static void finalize(Dec *d) {
ahead_close(d);
CHECK(!d->worker && !d->nout && !d->decoding);
pending_free(d);
for (int i = 0; i < d->qn; i++) picture_free(&d->queue[(d->qhead + i) % MAX_QUEUE]);
free(d->out);
free(d);
}
int main(int argc, char **argv) {
const int want_ahead = argc > 1 ? atoi(argv[1]) : 12;
unsigned s = 12345u + (unsigned)want_ahead;
int stream = 0;
long pictures = 0, flushes = 0, ends = 0;
for (int dec = 0; dec < 4; dec++) {
Dec *d = (Dec *)calloc(1, sizeof *d);
InitializeSRWLock(&d->lock);
d->mf = d; /* (any address: the stand-in decoder is the one above) */
ahead_start(d);
CHECK(d->worker && d->ahead == want_ahead);
for (int round = 0; round < 120; round++) {
stream++;
const int n = 1 + (int)(rnd(&s) % 150), delay = stream % 5;
const int flush_at = rnd(&s) % 4 == 0 ? (int)(rnd(&s) % (unsigned)(n + 1)) : -1;
const int slow = rnd(&s) % 3 == 0; /* (a game that takes slower than the worker decodes: the queue at its count) */
int submitted = 0, taken = 0, flushed = 0;
while (taken < n && !flushed) {
for (int k = 1 + (int)(rnd(&s) % (rnd(&s) % 2 ? 60u : 400u)); k > 0 && submitted < n; k--, submitted++)
submit(d, stream, submitted, submitted == n - 1);
/* (only pictures that will come: one more would wait 100 ms for a submission, as an acquire does) */
const int avail = submitted == n ? n : submitted > delay ? submitted - delay : 0;
int upto = taken + 1 + (int)(rnd(&s) % 30);
if (upto > avail) upto = avail;
while (taken < upto && !flushed) {
if (taken == flush_at) {
flush(d), flushed = 1, flushes++;
break;
}
Picture p;
CHECK(take(d, &p));
CHECK(p.w == stream); /* (no picture of a stream flushed or ended before) */
CHECK(p.pts == taken); /* (none dropped, none out of order, none twice) */
CHECK(p.last == (taken == n - 1)); /* (the last one, and only it, with its flag) */
CHECK(p.nv12 && !p.rgba);
picture_free(&p);
taken++, pictures++;
if (slow) spin_us((int)(rnd(&s) % 200));
}
}
if (!flushed) { /* (after the last picture: the end, at once) */
Picture p;
const int64_t t0 = hos_now_ns();
CHECK(!take(d, &p));
CHECK(hos_now_ns() - t0 < 50000000);
AcquireSRWLockExclusive(&d->lock);
CHECK(d->eos);
ReleaseSRWLockExclusive(&d->lock);
ends++;
}
}
stream++;
if (dec < 2) { /* (the close with the worker at work: a stream submitted and not taken) */
for (int i = 0; i < 40 + dec * 30; i++) submit(d, stream, i, 0);
if (dec & 1) spin_us(2000);
} else {
/* (a full queue: with the most pictures ahead, a stream whose 4 held frames come out at its end finds room
for 2 of them. The worker waits with the other 2 and drops nothing: they are queued as the game takes
(dec 2), and a close that finds the worker waiting ends it (dec 3)) */
const int n = MAX_QUEUE + 2;
while (stream % 5 != 4) stream++;
for (int i = 0; i < n; i++) submit(d, stream, i, i == n - 1);
if (want_ahead == MAX_QUEUE - 2)
for (int tries = 0;; tries++) {
AcquireSRWLockExclusive(&d->lock);
const int there = d->qn == MAX_QUEUE && d->uncommitted == 2 && d->eos && !d->decoding;
ReleaseSRWLockExclusive(&d->lock);
if (there) break;
CHECK(tries < 10000);
Sleep(1);
}
for (int i = 0; dec == 2 && i <= n; i++) {
Picture p;
if (i == n) {
CHECK(!take(d, &p));
break;
}
CHECK(take(d, &p) && p.w == stream && p.pts == i && p.last == (i == n - 1));
picture_free(&p);
}
}
finalize(d);
CHECK(nheld <= 4);
nheld = 0; /* (the stand-in decoder's frames of the closed stream: it kept no memory for them) */
}
CHECK(live == 0);
CHECK(pictures > 10000 && flushes > 50 && ends > 200 && !video_picture_late(0, 0, 0, 0, VIDEO_LATE_NS));
printf("%ld pictures, %ld flushes, %ld ends, longest wait %.1f ms\n", pictures, flushes, ends, (double)longest_wait / 1e6);
return 0;
}
'''
def check(cond, what):
if not cond:
raise SystemExit("FAIL: " + what)
def block(source, marker):
start = source.find(marker)
check(start >= 0, "%s is missing" % marker)
end = source.index("{", start) + 1
depth = 1
while depth:
depth += (source[end] == "{") - (source[end] == "}")
end += 1
return source[start:end]
def line_of(source, pattern):
found = re.search(pattern, source, re.M)
check(found is not None, "%s is missing" % pattern)
return found.group(0)
def build_and_run(cc, tmp, name, source, flags, runs):
src, exe = Path(tmp) / (name + ".c"), Path(tmp) / (name + ".exe")
src.write_text(source, encoding="utf-8")
built = subprocess.run([cc, *flags, "-o", str(exe), str(src)], capture_output=True, text=True)
check(built.returncode == 0, "%s does not compile:\n%s" % (name, built.stderr))
out = []
for args, env in runs:
try:
ran = subprocess.run([str(exe), *args], capture_output=True, text=True, timeout=120, env=env)
except subprocess.TimeoutExpired:
raise SystemExit("FAIL: %s %s did not end in 120 s: the worker and the game's calls wait for each other"
% (name, " ".join(args))) from None
check(ran.returncode == 0, "%s %s: %s" % (name, " ".join(args), ran.stderr.strip() or "exit %d" % ran.returncode))
out.append(ran.stdout.strip())
return out
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--cc", default=os.environ.get("CC", "gcc"))
args = parser.parse_args()
video = (ROOT / "host/nn_video.c").read_text(encoding="utf-8")
# ---- 1. the rules
max_queue = line_of(video, r"^#define MAX_QUEUE \d+")
check(int(max_queue.split()[2]) >= 8, "the queue is shorter than the count's default needs")
rules = "\n".join([line_of(video, r"^enum \{ VIDEO_AHEAD_PICTURES = 12, VIDEO_LATE_NS = 25000000 \};"),
block(video, "static inline int video_ahead_count("), block(video, "static inline int video_ahead_decode("),
block(video, "static inline int video_picture_late(")])
with tempfile.TemporaryDirectory() as tmp:
build_and_run(args.cc, tmp, "video_ahead_rules",
"\n".join(["#include <stdint.h>", "#include <stdio.h>", "#include <stdlib.h>", max_queue, rules, RULES_MAIN]),
["-std=c11", "-Wall", "-Werror"], [([], None)])
# ---- 2. the wiring
worker = block(video, "static DWORD WINAPI decode_ahead_main(LPVOID arg) {")
order = [worker.find(part) for part in (
"if (d->hold || !video_ahead_decode(d->phead != NULL, d->phead && !d->phead->pkt, d->qn, d->ahead)) {",
"Pending *n = pending_pop(d);", "const uint32_t gen = d->gen;", "d->decoding = 1, d->ending = end;",
"ReleaseSRWLockExclusive(&d->lock);", "decode_one(d, n);", "AcquireSRWLockExclusive(&d->lock);\n decode_done(",
"d->decoding = d->ending = 0;", "d->uncommitted = d->nout;", "WakeAllConditionVariable(&d->idle);",
"while (i < d->nout && gen == d->gen && !d->closing) {", "if (d->qn == MAX_QUEUE) {",
"SleepConditionVariableSRW(&d->work, &d->lock, INFINITE, 0);\n continue;", "queue_push(d, &d->out[i++]);",
"for (; i < d->nout; i++) picture_free(&d->out[i]);", "d->nout = d->uncommitted = 0;")]
check(all(i >= 0 for i in order), "the worker's steps changed (step %d)" % (order.index(-1) + 1 if -1 in order else 0))
check(order == sorted(order), "the worker's steps are out of order: the lock let go, the decode, the lock, the queue")
between = worker[worker.index("d->decoding = 1, d->ending = end;"):worker.index("decode_done(")]
check(between.count("ReleaseSRWLockExclusive(&d->lock);") == 1 and between.count("AcquireSRWLockExclusive(&d->lock);") == 1
and between.index("ReleaseSRWLockExclusive") < between.index("decode_one(d, n);") < between.index("AcquireSRWLockExclusive"),
"the worker holds the decoder's lock across the decode")
check("decode_done(d, end && gen == d->gen, ns, gen == d->gen);" in worker, "a flushed stream's end still ends the stream after it")
check(worker.count("picture_free(") == 1, "the worker frees a picture somewhere else than after a flush or the close")
check("while (!d->closing) {" in worker and worker.rstrip().endswith("return 0;\n}"), "the worker does not end at the close")
guest = ("GP(", "G64(", "G32(", "ARG(", "hos_guest_range", "HOS_WRITTEN", "hos_vcore", "hos_cv_sleep", "hos_sleep_ns")
check(not any(g in worker for g in guest), "the worker touches guest memory or a virtual core")
one = block(video, "static void decode_one(Dec *d, Pending *n) {")
check(one.count("mf_av1_decode(") == 2 and video.count("mf_av1_decode(") == 3, "mf_av1_decode is called outside decode_one")
check(one.count("avcodec_send_packet(") == video.count("avcodec_send_packet(") == 3, "avcodec_send_packet is called outside decode_one")
check(video.count("avcodec_receive_frame(") == 1 and "avcodec_receive_frame(" in block(video, "static void drain(Dec *d) {"),
"avcodec_receive_frame is called outside drain")
shared = ("d->lock", "d->queue", "d->qn", "d->qhead", "d->phead", "d->ptail", "d->eos", "d->st_", "d->slot", "d->busy", "d->clock",
"d->decoding", "d->gen", "d->hold", "d->uncommitted")
for name in ("static void decode_one(Dec *d, Pending *n) {", "static void queue_frame(Dec *d, const AVFrame *f) {",
"static void mf_picture(", "static void drain(Dec *d) {", "static int out_push(Dec *d, Picture *p) {"):
part = block(video, name)
check(not any(f in part for f in shared), "%s reads or writes what the decoder's lock guards" % name.split("(")[0])
check(not any(g in part for g in guest), "%s touches guest memory or a virtual core" % name.split("(")[0])
check("out_push(d, &p)" in block(video, "static void queue_frame(Dec *d, const AVFrame *f) {"),
"a decoded frame does not go to the decoding thread's own list")
check(video.count("decode_one(") == 3, "decode_one is called from elsewhere (definition, decode_next, the worker expected)")
check(video.count("queue_push(") == 3, "queue_push is called from elsewhere (definition, decode_next, the worker expected)")
stop, go = block(video, "static void ahead_stop(Dec *d) {"), block(video, "static void ahead_go(Dec *d) {")
check(stop.index("d->gen++, d->hold++;") < stop.index("WakeAllConditionVariable(&d->work);")
< stop.index("while (d->decoding) hos_cv_sleep(&d->idle, &d->lock, 20);"),
"a flush does not count itself, hold new decodes off and wait for the decode in flight")
check(go.index("d->hold--;") < go.index("WakeAllConditionVariable(&d->work);"), "the worker is not let on after a flush")
flush = block(video, "static void flush_locked(Dec *d) {")
steps = [flush.find(part) for part in ("ahead_stop(d);", "if (d->ctx) avcodec_flush_buffers(d->ctx);", "else mf_av1_flush(d->mf);",
"pending_free(d);", "picture_free(&d->queue[", "d->qhead = d->qn = 0;", "ahead_go(d);")]
check(all(i >= 0 for i in steps) and steps == sorted(steps), "the flush touches the decoder or the queue before it has the decoder")
check(not any(w in flush for w in ("ReleaseSRWLock", "hos_cv_sleep", "hos_sleep_ns")),
"the flush lets the lock go between taking the decoder and giving it back")
check(video.count("avcodec_flush_buffers(") == 2 and video.count("mf_av1_flush(") == 2,
"the decoder is flushed outside flush_locked and decode_one")
outer = block(video, "static void dec_flush(Ctx *c, const char *what) {")
check(outer.index("AcquireSRWLockExclusive(&d->lock);") < outer.index("flush_locked(d);") < outer.index("ReleaseSRWLockExclusive(&d->lock);"),
"dec_flush does not flush under the decoder's lock")
close = block(video, "static void ahead_close(Dec *d) {")
check(close.index("d->closing = 1;") < close.index("WakeAllConditionVariable(&d->work);") < close.index("ReleaseSRWLockExclusive(&d->lock);")
< close.index("WaitForSingleObject(d->worker, INFINITE);") < close.index("CloseHandle(d->worker);"),
"the close does not end the worker and wait for it, with the lock let go")
final = block(video, "static void dec_finalize(Ctx *c) {")
steps = [final.find(part) for part in ("set_host(ARG(0), DEC_MAGIC, NULL);", "ahead_close(d);", "pending_free(d);", "free(d->out);",
"avcodec_free_context(&d->ctx);", "mf_av1_close(d->mf);", "\n free(d);")]
check(all(i >= 0 for i in steps) and steps == sorted(steps), "the decoder is freed before its worker has ended")
start = block(video, "static void ahead_start(Dec *d) {")
check(start.index("d->ahead = decode_ahead();") < start.index("if (!d->ahead) return;")
< start.index("d->worker = CreateThread(NULL, 0, decode_ahead_main, d, 0, NULL);"), "the switch does not keep the worker from starting")
check("SetThreadPriority" not in video, "the worker's priority is changed (normal is the rule)")
switch = block(video, "static int decode_ahead(void) {")
check('video_ahead_count(getenv("HOS_VIDEO_DECODE_AHEAD"), MAX_QUEUE)' in switch, "HOS_VIDEO_DECODE_AHEAD is not read")
init = block(video, "static void dec_init_sized(Ctx *c, enum AVCodecID id, const char *what, int w, int h) {")
check(init.index("d->frame = av_frame_alloc();") < init.index("if (d->ctx || d->mf) ahead_start(d);") < init.index("set_host(ARG(0), DEC_MAGIC, d);"),
"the worker starts after the game can find the decoder, or before the decoder is whole")
check(video.count("d->worker = ") == 2, "d->worker changes after the start (the start and the close expected)")
wait = block(video, "static int64_t ahead_wait(Dec *d) {")
check("if (d->qn > 1 || (d->qn == 1 && !tail_unsettled(d))) break;" in wait, "an acquire may take a picture whose last flag is not settled")
check("const int coming = d->qn || d->phead || d->decoding || d->uncommitted;" in wait and
"if (!coming && (d->eos || d->stopped || t0 >= idle_until)) break;" in wait, "an acquire gives up on a picture that is on its way, or waits at the end")
check("hos_cv_sleep(&d->idle, &d->lock, 2);" in wait and "decode_next" not in wait and "decode_pending" not in wait and "decode_one" not in wait,
"the wait decodes, or does not let the lock go")
tail = block(video, "static int tail_unsettled(const Dec *d) {")
check("return d->ending || (!d->decoding && !d->uncommitted && d->phead && !d->phead->pkt);" in tail, "the unsettled-tail rule changed")
body = block(video, "static void dec_acquire(Ctx *c) {")
check(body.index("if (d->worker) {") < body.index("waited_ns = ahead_wait(d);") < body.index("} else {") < body.index("decode_pending(d);"),
"with a worker the acquire still decodes")
catch = body[body.index("for (int guard = 0;"):body.index("d->st_skipped += skipped;")]
check(catch.index("if (d->worker || !d->phead) break;") < catch.index("decode_next(d);"), "the catch-up decodes in the call with a worker")
check(body.count("decode_next(d);") == 1 and body.count("decode_pending(d);") == 2, "the acquire decodes somewhere else")
check("if (!video_picture_late(d->queue[d->qhead].pts, d->clock_pts, d->clock_ns, now, late)) break;" in catch,
"the catch-up's rule is not the one tested")
check(catch.index("if (d->worker && d->qn == 2 && tail_unsettled(d)) break;") < catch.index("picture_free(&d->queue[d->qhead]);"),
"the catch-up may leave a picture whose last flag is not settled as the one to go out")
check("const int idle = !d->eos && !d->phead && !d->decoding && !d->uncommitted;" in body,
"a buffer is called idle while the worker has a picture on its way")
check(body.index("picture_free(p);") < body.index("if (d->worker) WakeAllConditionVariable(&d->work);") < body.rindex("ReleaseSRWLockExclusive(&d->lock);"),
"the acquire does not wake the worker for the room it made")
check("const int64_t call_ns = d->worker ? waited_ns : d->st_ns - call_ns0;" in body and "if (call_ns > 0) d->st_waited++;" in body
and "else d->st_ready++;" in body, "the acquires are not counted as ready or waited")
line = body[body.index("if (d->st_taken >= 600"):]
for part in ('d->worker ? "decoded ahead by a host thread (HOS_VIDEO_DECODE_AHEAD)" : "in the game\'s call"', "found their picture ready",
"waited for it", "(long long)d->st_ready, (long long)d->st_waited", "d->st_ready = d->st_waited = 0;"):
check(part in line[:1800], "the pictures-taken line lost: " + part)
submit = block(video, "static void dec_submit(Ctx *c) {")
check(submit.index("pending_push(d, NULL);") < submit.index("if (d->worker) WakeAllConditionVariable(&d->work);")
< submit.rindex("ReleaseSRWLockExclusive(&d->lock);"), "a submission does not wake the worker")
check(submit.index("memcpy(pkt->data, data, (size_t)ARG(3));") < submit.index("pending_push(d, pkt);"),
"a submission's data is not copied before the worker can have it")
guide = (ROOT / "docs/development.md").read_text(encoding="utf-8")
check("| `HOS_VIDEO_DECODE_AHEAD=0`" in guide and "tests/test_video_decode_ahead.py" in guide, "docs/development.md does not name HOS_VIDEO_DECODE_AHEAD")
# ---- 3. the threads
if os.name != "nt":
print("ok (the threads' fixture was not run: it is written for Windows' SRW locks)")
return
dec = block(video, "typedef struct {\n /* ((Triforce) The decoder:")
check(video[video.index(dec) + len(dec):].startswith(" Dec;"), "the decoder's struct is not cut whole")
dec += " Dec;"
types = [line_of(video, r"^typedef struct \{ uint8_t \*rgba, \*nv12; .*\} Picture;"),
line_of(video, r"^typedef struct Pending \{ .*\} Pending;"), max_queue, rules, dec]
before = [block(video, f) for f in ("static void picture_free(Picture *p) {", "static void pending_free(Dec *d) {",
"static int out_push(Dec *d, Picture *p) {", "static void queue_push(Dec *d, const Picture *p) {",
"static Pending *pending_pop(Dec *d) {", "static void decode_done(Dec *d, int end, int64_t ns, int live) {",
"static void pending_push(Dec *d, AVPacket *pkt) {")]
after = [block(video, f) for f in ("static int decode_ahead(void) {", "static int tail_unsettled(const Dec *d) {",
"static DWORD WINAPI decode_ahead_main(LPVOID arg) {", "static void ahead_start(Dec *d) {",
"static void ahead_close(Dec *d) {", "static void ahead_stop(Dec *d) {", "static void ahead_go(Dec *d) {",
"static void flush_locked(Dec *d) {", "static int64_t ahead_wait(Dec *d) {")]
# ((Triforce, 11-22, on v0.7.0) the decoder's record keeps v0.7.0's movie counts, pace and input limit too: their
# headers before the fixture's own calloc and free, and the ready event's room (input_room) as nothing: no game here
head = "".join('#include "%s"\n' % (ROOT / "host" / h).as_posix()
for h in ("video_movie.h", "video_catchup.h", "video_input.h")) + STRESS_HEAD
types.append("static void input_room(Dec *d) { (void)d; }")
source = "\n".join([head, *types, *before, STRESS_MAIN.replace("__CUT_AFTER_DECODER__", "\n".join(after))])
with tempfile.TemporaryDirectory() as tmp:
runs = []
for count in ("2", "12", "14"):
env = dict(os.environ)
env["HOS_VIDEO_DECODE_AHEAD"] = "1" if count == "12" else count
runs.append(([count], env))
for out in build_and_run(args.cc, tmp, "video_ahead_threads", source, ["-std=gnu11", "-O1", "-Wall", "-Werror"], runs):
print(" " + out)
print("ok")
if __name__ == "__main__":
main()

View File

@@ -174,7 +174,7 @@ def main():
and "hos_system_event_signal_held(d->ready);" in room and "hos_system_event_signal(" not in room,
"input_room does not set a cleared event once there is room, without a checkpoint")
vf.check("d->npending++;" in vf.block(video, "static void pending_push(Dec *d, AVPacket *pkt) {")
and "d->npending--;" in vf.block(video, "static void decode_next(Dec *d) {")
and "d->npending--;" in vf.block(video, "static Pending *pending_pop(Dec *d) {")
and "d->npending = 0;" in vf.block(video, "static void pending_free(Dec *d) {"),
"the count of pending submissions is not kept where the list changes")
@@ -191,7 +191,8 @@ def main():
"dec_submit does not look for room before its last unlock")
flush = vf.block(video, "static void dec_flush(Ctx *c, const char *what) {")
vf.check(re.search(r"input_room\(d\);[^\n]*\n\s+ReleaseSRWLockExclusive\(&d->lock\);", flush) is not None
and flush.index("pending_free(d);") < flush.index("input_room(d);"),
and flush.index("flush_locked(d);") < flush.index("input_room(d);")
and "pending_free(d);" in vf.block(video, "static void flush_locked(Dec *d) {"),
"a Stop or a Flush does not set the event again before it lets the lock go")
acquire = vf.block(video, "static void dec_acquire(Ctx *c) {")
exits = re.findall(r"input_room\(d\);[^\n]*\n\s+ReleaseSRWLockExclusive\(&d->lock\);\n\s+if \(away\) hos_vcore_back\(\);", acquire)

View File

@@ -0,0 +1,71 @@
"""(Triforce, 11-26) The game's gameplay upscale with RenoDX's RGBA16F scene and the game's own upscaler (gpu/vk/vk_draw.cpp
wide_upscale). On the lab's RX 7900 XT with the owner's settings, Render resolution 75% and Auto (the 3/4 network,
fd029a317a9a4b94) drew a black 3D, and 67% and 50% (their networks left out on that card, 6676619641320ba7 and 72ba090c70fe2614)
a 3D veiled in white: upscale_stub's plain blit copied the network's input, the square root of the scene colour, as it is. The
same at a fresh start. Now the stand-in's own pass (shaders/taau_upscale.comp, which squares it back) draws them into an
R11G11B10F scratch image, blitted into the RGBA16F picture.
What it checks: wide_upscale is for a run whose scene is RGBA16F alone, with RX_VK_WIDE_UPSCALE=0 over it; it squares through
typed_upscale into an R11G11B10F image at the output's size and blits that into the output's level; taau_stand_in gives it the
3/4 network when that network's output is RGBA16F (not with the upscaler Off or N64 Classic, whose own stand-ins go first); and
upscale_stub gives it an RGBA16F network's pass before the plain blit, under the lock it holds. The shader squares its input.
No game, no GPU.
python -I -B tests/test_wide_upscale.py
"""
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
VK = ROOT / "gpu" / "vk"
def check(ok, why):
if not ok:
raise SystemExit("FAIL: " + why)
def function(src, head):
at = src.find(head)
check(at >= 0, head + " is missing")
body = src[at:]
return body[:body.index("\n}\n")]
def main():
draw = (VK / "vk_draw.cpp").read_text(encoding="utf-8")
wide = function(draw, "static bool wide_upscale(VkCommandBuffer cmd, VkImageView input_view, Texture* out, uint32_t level, "
"uint64_t key, const char* keys,\n bool temporal) {")
check("!temporal_scene_format(VK_FORMAT_R16G16B16A16_SFLOAT)" in wide and 'getenv("RX_VK_WIDE_UPSCALE")' in wide and
"out->format != VK_FORMAT_R16G16B16A16_SFLOAT" in wide, "wide_upscale is not for an RGBA16F scene's picture alone")
check("ic.format = VK_FORMAT_B10G11R11_UFLOAT_PACK32;" in wide and
"VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT" in wide, "the scratch image is not R11G11B10F, stored and blitted from")
order = [wide.index(p) for p in ("typed_upscale(cmd, input_view, scratch.view, nullptr, 0, key, keys, temporal, w, h)",
"full_barrier(cmd);", "vkCmdBlitImage(cmd, scratch.image, VK_IMAGE_LAYOUT_GENERAL, out->image",
"texture_written(out);")]
check(order == sorted(order), "wide_upscale does not square into the scratch image, then blit it into the picture")
check("bl.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, level, 0, 1};" in wide, "the blit is not into the output's level")
check("texture_frame_no() - old[i].frame < 120" in wide, "a scratch image of another size is given back before work in flight is done")
typed = function(draw, "static bool typed_upscale(VkCommandBuffer cmd, VkImageView input_view, VkImageView output_view,\n"
" Texture* out, uint32_t level, uint64_t key, const char* keys, bool temporal, uint32_t out_w, uint32_t out_h) {")
check("out_w ? out_w : std::max(1u, out->width >> level)" in typed and "if (temporal && out) probe_image(" in typed,
"typed_upscale does not take a size of its own for a scratch image")
stand = function(draw, "bool taau_stand_in(VkCommandBuffer cmd, const NvnState& s, const Program& p) {")
check("const bool wide = p.key == 0xfd029a317a9a4b94ull && !off && !n64;" in stand and "if (!ch.stand_in && !wide) return false;" in stand and
"if (wide && out && out->format == VK_FORMAT_R16G16B16A16_SFLOAT) {" in stand and
'wide_upscale(cmd, dw().imgs[0].imageView, out, level, p.key, "fd029a317a9a4b94, RGBA16F", true)' in stand,
"taau_stand_in does not give the 3/4 network's RGBA16F picture to wide_upscale")
check(stand.index("wide_upscale(") < stand.index("if (!ch.stand_in || !out || out->format != VK_FORMAT_B10G11R11_UFLOAT_PACK32) return false;"),
"the RGBA16F stand-in comes after the SDR one's refusal")
stub = function(draw, "bool upscale_stub(VkCommandBuffer cmd, const NvnState& s, uint64_t key) {")
check('wide_upscale(cmd, input_view, dst, 0, key, "a network left out, RGBA16F", false)' in stub and
stub.index("ParLock lk;\n VkFormatProperties fs{}, fd{};") < stub.index("wide_upscale(") < stub.index("vkCmdBlitImage(cmd, src->image"),
"upscale_stub does not give an RGBA16F network's pass to wide_upscale before the plain blit, under its lock")
shader = (VK / "shaders" / "taau_upscale.comp").read_text(encoding="utf-8")
check("vec3 c = s * s;" in shader, "the stand-in's pass no longer squares the network's input back")
check("| `RX_VK_WIDE_UPSCALE=0` |" in (ROOT / "docs" / "development.md").read_text(encoding="utf-8"),
"docs/development.md has no row for RX_VK_WIDE_UPSCALE")
print("PASS: the RGBA16F scene's gameplay upscale, squared back")
if __name__ == "__main__":
main()

View File

@@ -29,6 +29,7 @@
#include "vk_menu.h"
#include "vk_dlss.h"
#include "vk_fsr4.h"
#include "upscaler_rows.h" // ((Triforce, 11-26) fsr3_wanted_of's values)
// ---- what vk_menu.cpp takes from the rest of the back end: stand-ins ----
namespace mkwvk {
@@ -76,6 +77,11 @@ framegen_rows::Held held() { return framegen_rows::HELD_NONE; } // ((Triforce)
}
bool fsr3_wanted() { return false; }
int temporal_mode() { return 0; }
// ((Triforce, 11-26) a choice of the Upscaler row as it would run (the rows', before Apply): FSR 3.1 where the row says it,
// the chain's engines none here (no DLSS or FSR 4 in this build), the row's Off as Off)
bool fsr3_wanted_of(int choice, bool) { return choice == upscaler_rows::FSR3 || choice == upscaler_rows::FSR3_AA; }
bool fsr3_native_of(int choice, bool) { return choice == upscaler_rows::FSR3_AA; }
int temporal_mode_of(int, bool) { return 0; }
int temporal_stood_in() { return 0; } // ((Triforce, FSR4-1) no engine stood in for
bool temporal_sharpens_3d() { return false; } // ((Triforce, S1) the game's own upscaler: Sharpness at the window
void pipeline_cache_save(bool) {}

View File

@@ -73,7 +73,20 @@ static void mf_av1_flush(void *m) { (void)m; }
#include "../host/video_movie.h" /* (the Dec cut out keeps a movie's counts: VideoMovie) */
#include "../host/video_catchup.h" /* (and its pictures' pace: VideoPace, the catch-up's rule) */
#include "../host/video_input.h" /* (and the submissions' limit: its rule and result) */
/* ((Triforce, 11-22) the decoder record also keeps the decode-ahead worker's state (nn_video.c "decode ahead"): none runs
here (d->worker stays NULL), so the acquire decodes in the call, which is what this fixture watches */
typedef void *HANDLE;
typedef struct { int unused; } CONDITION_VARIABLE;
static void WakeAllConditionVariable(CONDITION_VARIABLE *cv) { (void)cv; }
enum { VIDEO_LATE_NS = 25000000 };
static inline int video_picture_late(int64_t pts, int64_t clock_pts, int64_t clock_ns, int64_t now, int64_t late) {
return pts + late < clock_pts + (now - clock_ns);
}
#include "video_acquire_types.inc"
static int64_t ahead_wait(Dec *d) { (void)d; return 0; } /* (never called without a worker) */
static int tail_unsettled(const Dec *d) { (void)d; return 0; }
static void ahead_stop(Dec *d) { (void)d; }
static void ahead_go(Dec *d) { (void)d; }
static void pending_push(Dec *d, AVPacket *pkt) { (void)d, (void)pkt; }
static void pending_free(Dec *d) { d->phead = d->ptail = NULL; }

View File

@@ -25,7 +25,17 @@ static int si_boxes, si_threads;
#undef CreateThread
#define MessageBoxA(window, text, title, type) (si_boxes++, 0)
#define ShellExecuteA(window, verb, file, args, dir, show) ((void)0)
#define CreateThread(security, stack, fn, arg, flags, id) (si_threads++, (void)(fn), (HANDLE)NULL)
/* ((Triforce, 11-22) si_threads counts the notice's threads, which is what the tests ask about; a decoder's decode-ahead
worker (nn_video.c ahead_start) is another function: counted apart and, as any thread here, not made, so every decoder
decodes in the game's calls) */
static int si_workers;
static DWORD WINAPI av1_notice(LPVOID unused);
static inline HANDLE si_no_thread(LPTHREAD_START_ROUTINE fn) {
if (fn == av1_notice) si_threads++;
else si_workers++;
return NULL;
}
#define CreateThread(security, stack, fn, arg, flags, id) si_no_thread(fn)
#endif
/* ---- hos.h ---- */
@@ -71,6 +81,12 @@ static int64_t hos_now_ns(void) { return si_now; }
static void hos_sleep_ns(int64_t ns) { si_now += ns; }
static int hos_vcore_away(void) { return 0; }
static void hos_vcore_back(void) {}
/* ((Triforce, 11-22) the decode-ahead worker's calls (nn_video.c "decode ahead"). CreateThread above gives no thread, so no
decoder has a worker here and the acquire decodes in the call, as these tests watch it; the two below are never reached) */
static void hos_thread_pin(HANDLE thread, const char *name) { (void)thread, (void)name; }
static int hos_cv_sleep(void *cv, void *lk, unsigned ms) {
return SleepConditionVariableSRW((PCONDITION_VARIABLE)cv, (PSRWLOCK)lk, ms, 0);
}
static uint64_t si_sys = 0x30000;
static uint64_t hos_sys_alloc(uint64_t size, uint64_t align) {
(void)align;