Triforce v0.7.1

Crash fixes (a load crash from the virtual cores' escape, the upscaler-before-the-bloom crash, out of memory at a file's open), slow motion after a movie fixed, three save files with per-save achievements (ZakyPew), ten more achievements and their own menu group, N64 Classic, native ultrawide output (Kaefergeneral), the community AMD frame-time fixes, the helper threads' calm-scene tuner and benchmark test, update and Linux launcher fixes.
This commit is contained in:
ruckus7382sfgsgdf
2026-11-23 13:12:59 -06:00
parent e6f2f248f2
commit 861702476a
153 changed files with 12615 additions and 1093 deletions

View File

@@ -5,13 +5,18 @@
- On by default (11-22, the owner's word); HOS_ACHIEVEMENTS=0 (triforce_env.txt) turns them off. While off nothing is
read, of the game or of the disk.
- (11-23) The System tab's Achievements group has two rows of them, read from the renderer at each check: Achievements
Off (HOS_OPT_ACH_ON 0) and nothing is asked of the save data or earned, from the next check on, and On again as
soon; Achievement notices Off (HOS_OPT_ACH_NOTICES 0) and one earned is kept, said in the log and told to the list,
without the sound (the menu shows no notice then).
- The lists are read at the game's first present (hos_achievements_frame, host/nvn_native.c): the built-in one, then
achievements.txt in the game folder when there is one. Once the renderer answers they are named to the menu
(HOS_OPT_ACH_TEXT, _ADD, _COUNT: gpu/vk/achievement_rows.h), which lists them on the System tab's Achievements page.
- host/hos_main.c asks once a second at Link's update, on the game's thread, while a save is loaded, and hands over
how the save data is read (hos_achievements_check).
- An achievement earned is written to triforce_achievements.txt in the game folder at once (the file whole, under
another name first), said in the log, and shown: the menu's notice (HOS_OPT_ACH_EARNED) with the system menu's
another name first; while the save files are on, host/save_files.c, in the folder of the file played, so that each
file has what it earned and no other's: earned_file), said in the log, and shown: the menu's notice (HOS_OPT_ACH_EARNED) with the system menu's
decide sound (HOS_MENU_SOUND_SYS_DECIDE, at the Menu sounds row's volume; silent where that row is Off. Not the
item fanfare: most are earned as the game plays that itself). One at a time: a save that earns several at once
shows them one after the other.
@@ -30,6 +35,7 @@
int rx_option(int id, int otherwise);
void rx_option_set(int id, int value);
const char *hos_save_files_dir(int *first); /* host/save_files.c */
#define EARNED_FILE "triforce_achievements.txt"
#define OWN_FILE "achievements.txt"
@@ -60,10 +66,20 @@ static int game_file(char *out, size_t cap, const char *name) {
return snprintf(out, cap, "%.*s%s", (int)(slash + 1 - exe), exe, name) < (int)cap;
}
/* a text file of the game folder whole, its end a 0 (freed by the caller); NULL when it is not there or over `most` */
static char *read_text(const char *name, long most) {
char path[MAX_PATH + 40];
if (!game_file(path, sizeof path, name)) return NULL;
/* ((Triforce) 11-23, his "I don't want achievements to carry across" the save files.) Where the earned ones are kept: the
game folder's triforce_achievements.txt, or, while the save files are on, the one in the folder of the file this run
plays. *inherits: that file is File 1 and may start from the game folder's, which is what it earned before there were
files (read only: the game folder's is left as it is) */
static int earned_file(char *out, size_t cap, int *inherits) {
int first = 0;
const char *dir = hos_save_files_dir(&first);
*inherits = dir && first;
if (!dir) return game_file(out, cap, EARNED_FILE);
return snprintf(out, cap, "%s%c" EARNED_FILE, dir, strchr(dir, '\\') ? '\\' : '/') < (int)cap;
}
/* a text file whole, its end a 0 (freed by the caller); NULL when it is not there or over `most` */
static char *read_text(const char *path, long most) {
FILE *f = fopen(path, "rb");
if (!f) return NULL;
char *text = NULL;
@@ -80,9 +96,10 @@ static char *read_text(const char *name, long most) {
static void earned_save(void) {
static char text[ACH_MAX * (ACH_NAME + 40) + ACH_ORPHANS * ACH_LINE + 200];
char path[MAX_PATH + 40], fresh[MAX_PATH + 48];
char path[MAX_PATH + 160], fresh[MAX_PATH + 168];
int inherits;
const size_t n = ach_earned_write(&list, text, sizeof text);
if (!n || !game_file(path, sizeof path, EARNED_FILE)) return;
if (!n || !earned_file(path, sizeof path, &inherits)) return;
snprintf(fresh, sizeof fresh, "%s.new", path);
FILE *f = fopen(fresh, "wb"); /* (its lines end the same on Windows and Linux) */
const int ok = f && fwrite(text, 1, n, f) == n;
@@ -95,10 +112,13 @@ static void earned_save(void) {
static void lists_read(void) {
int refused = 0;
const int built_in = ach_parse(&list, ACH_BUILTIN, &refused);
char *own = read_text(OWN_FILE, OWN_MOST);
char path[MAX_PATH + 160];
int inherits = 0;
char *own = game_file(path, sizeof path, OWN_FILE) ? read_text(path, OWN_MOST) : NULL;
const int own_n = own ? ach_parse(&list, own, &refused) : 0;
free(own);
char *earned = read_text(EARNED_FILE, OWN_MOST);
char *earned = earned_file(path, sizeof path, &inherits) ? read_text(path, OWN_MOST) : NULL;
if (!earned && inherits && game_file(path, sizeof path, EARNED_FILE)) earned = read_text(path, OWN_MOST);
const int marked = earned ? ach_earned_read(&list, earned) : 0;
free(earned);
hos_log("achievements: %d (%d of " OWN_FILE "%s), %d earned so far%s", list.n, own_n, own ? "" : ", which is not there", marked,
@@ -152,7 +172,8 @@ void hos_achievements_frame(void) {
/* host/hos_main.c, once a second at Link's update while a save is loaded (now_ns: hos_now_ns): what the save data has
earned since the last call is marked, kept and shown */
void hos_achievements_check(AchProbe probe, void *ctx, int64_t now_ns) {
if (!hos_achievements_on()) return;
if (!hos_achievements_on() || !rx_option(HOS_OPT_ACH_ON, 1)) return;
const int quiet = !rx_option(HOS_OPT_ACH_NOTICES, 1);
lock();
if (!ready) ready = 1, lists_read();
int fresh[ACH_MAX];
@@ -162,15 +183,15 @@ void hos_achievements_check(AchProbe probe, void *ctx, int64_t now_ns) {
if (nwaiting < ACH_MAX) waiting[nwaiting++] = fresh[i];
}
if (got) earned_save();
if (nwaiting && named && now_ns >= next_shown) { /* (not before the menu has the list: it shows them by their place in it) */
if (nwaiting && named && (quiet || now_ns >= next_shown)) { /* (not before the menu has the list: it shows them by their place in it) */
const int at = waiting[0];
char day[16];
memmove(waiting, waiting + 1, sizeof waiting[0] * (size_t)--nwaiting);
next_shown = now_ns + SHOWN_MS * 1000000LL;
next_shown = quiet ? now_ns : now_ns + SHOWN_MS * 1000000LL; /* (no notice shown: the next need not wait for it) */
day_of(list.a[at].when, day, sizeof day);
to_menu(day);
rx_option_set(HOS_OPT_ACH_EARNED, at);
hos_menu_sound_play(HOS_MENU_SOUND_SYS_DECIDE, now_ns);
if (!quiet) hos_menu_sound_play(HOS_MENU_SOUND_SYS_DECIDE, now_ns);
}
unlock();
}

View File

@@ -86,7 +86,19 @@ typedef int (*AchProbe)(void *ctx, int kind, const char *what);
"[A Giant's Blade]\nabout: Earn Biggoron's Sword.\nicon: sword\nitem Weapon_Sword_Biggoron\n" \
"[Deep Pockets]\nabout: Carry the Giant's Wallet.\nicon: token green\nitem Item_Wallet_Large\n" \
"[Light Against the Dark]\nabout: Receive the Light Arrow.\nicon: star yellow\nitem Item_Arrow_Light\n" \
"[Twice as Tough]\nabout: Receive Double Defense.\nicon: shield silver\nitem Item_FairyBless_DefenseDouble\n"
"[Twice as Tough]\nabout: Receive Double Defense.\nicon: shield silver\nitem Item_FairyBless_DefenseDouble\n" \
"[Honorary Thief]\nabout: Be handed the Gerudo's Card.\nicon: star red\nitem Item_Token_Gerudo\n" \
"[Read the Fine Print]\nabout: Buy a blade that will not last.\nicon: sword silver\nitem Weapon_Sword_Giant\n" \
"[Something's Buzzing]\nabout: Receive the Stone of Agony.\nicon: gem silver\nitem Item_AgonyStone\n" \
"[Fashion Victim]\nabout: Own both tunics and both pairs of boots.\nicon: shield red\nitem Armor_Adult_Goron\nitem Armor_Adult_Zora\n" \
"item Armor_Adult_HeavyBoot\nitem Armor_Adult_HoverBoot\n" \
"[Jack]\nabout: Carry 10 Magic Beans at once.\nicon: star green\nitem Item_MagicBean 10\n" \
"[Going Nuts]\nabout: Carry 40 Deku Nuts.\nicon: star orange\nitem Item_DekuNut 40\n" \
"[Demolition Permit]\nabout: Carry 40 Bombs and 50 Bombchus.\nicon: shield orange\nitem Item_Bomb 40\nitem Item_Bombchu 50\n" \
"[Three Goddesses]\nabout: Receive Din's Fire, Farore's Wind and Nayru's Love.\nicon: gem yellow\nitem Item_DinFire\n" \
"item Item_FaroreWind\nitem Item_NayruLove\n" \
"[Rain Dance]\nabout: Learn the Song of Storms.\nicon: note blue\nitem Item_Melody_StormSong\n" \
"[Deep End]\nabout: Earn the Golden Scale.\nicon: shield blue\nitem Item_Scale_Gold\n"
/* FNV-1a 32 of a name's bytes */
static inline uint32_t ach_key(const char *name) {

View File

@@ -19,6 +19,7 @@
#include "../gpu/render/rx.h"
void rx_close_asked(void); /* host/rx_backend.c */
#include "../gpu/vk/vk_api.h"
#include "hos_screens.h" /* ((Triforce) the connected screens, for the Output resolution) */
void hos_relaunch_ask(void); /* (host/hos_relaunch.c) */
void hos_bug_capture_key(void); /* (host/bug_capture.c) */
@@ -111,6 +112,86 @@ static void set_fullscreen(HWND w, int on) {
hos_log("display: %s", on ? "fullscreen" : "windowed");
}
/* (Triforce) The monitor the game's window opens on, asked before there is a window (the game takes its output size
first). The window is made at CW_USEDEFAULT: Windows puts it on the monitor the shell started the game from when it names
one (a taskbar or a shortcut on another monitor: STARTUPINFO's hStdOutput is that monitor's handle unless it is a
standard handle), else on the main monitor: NULL here. */
static HMONITOR shell_monitor(void) {
STARTUPINFOW si;
MONITORINFO mi;
memset(&si, 0, sizeof si);
si.cb = sizeof si;
GetStartupInfoW(&si);
mi.cbSize = sizeof mi;
if (!(si.dwFlags & STARTF_USESTDHANDLES) && si.hStdOutput && GetMonitorInfoA((HMONITOR)si.hStdOutput, &mi))
return (HMONITOR)si.hStdOutput;
return NULL;
}
/* Its size in pixels (the process is DPI aware by then, host/hos_main.c), 0 x 0 when the system does not say. A window moved
to another monitor later keeps the picture it started with: the game makes its render targets once, and the present fits
the picture into whatever the window is (gpu/vk/vk_present_rect.h). */
void hos_screen_size(int *w, int *h) {
const HMONITOR shell = shell_monitor();
MONITORINFO mi;
mi.cbSize = sizeof mi;
if (shell && GetMonitorInfoA(shell, &mi)) {
*w = (int)(mi.rcMonitor.right - mi.rcMonitor.left), *h = (int)(mi.rcMonitor.bottom - mi.rcMonitor.top);
return;
}
*w = GetSystemMetrics(SM_CXSCREEN), *h = GetSystemMetrics(SM_CYSCREEN);
}
/* A monitor's own name ("LG ULTRAGEAR": its EDID's, through the display configuration) by its GDI device ("\\.\DISPLAY1"),
UTF-8; "" where there is none (a laptop's panel, a remote session) */
static void screen_name(const char *device, char *out, int cap) {
UINT32 np = 0, nm = 0;
out[0] = 0;
if (GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &np, &nm) != ERROR_SUCCESS || !np) return;
DISPLAYCONFIG_PATH_INFO *paths = (DISPLAYCONFIG_PATH_INFO *)calloc(np, sizeof *paths);
DISPLAYCONFIG_MODE_INFO *modes = (DISPLAYCONFIG_MODE_INFO *)calloc(nm ? nm : 1, sizeof *modes);
if (paths && modes && QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &np, paths, &nm, modes, NULL) == ERROR_SUCCESS) {
for (UINT32 i = 0; i < np && !out[0]; i++) {
DISPLAYCONFIG_SOURCE_DEVICE_NAME src;
DISPLAYCONFIG_TARGET_DEVICE_NAME tgt;
char gdi[64];
memset(&src, 0, sizeof src);
src.header.type = DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, src.header.size = sizeof src;
src.header.adapterId = paths[i].sourceInfo.adapterId, src.header.id = paths[i].sourceInfo.id;
if (DisplayConfigGetDeviceInfo(&src.header) != ERROR_SUCCESS) continue;
if (!WideCharToMultiByte(CP_UTF8, 0, src.viewGdiDeviceName, -1, gdi, sizeof gdi, NULL, NULL) || strcmp(gdi, device)) continue;
memset(&tgt, 0, sizeof tgt);
tgt.header.type = DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME, tgt.header.size = sizeof tgt;
tgt.header.adapterId = paths[i].targetInfo.adapterId, tgt.header.id = paths[i].targetInfo.id;
if (DisplayConfigGetDeviceInfo(&tgt.header) != ERROR_SUCCESS || !tgt.flags.friendlyNameFromEdid) break;
if (!WideCharToMultiByte(CP_UTF8, 0, tgt.monitorFriendlyDeviceName, -1, out, cap, NULL, NULL)) out[0] = 0;
}
}
free(paths), free(modes);
}
struct screen_list {
HosScreen *out;
int cap, n;
HMONITOR shell;
};
static BOOL CALLBACK screen_each(HMONITOR m, HDC dc, LPRECT rect, LPARAM param) {
struct screen_list *l = (struct screen_list *)param;
MONITORINFOEXA mi;
(void)dc, (void)rect;
mi.cbSize = sizeof mi;
if (l->n >= l->cap || !GetMonitorInfoA(m, (MONITORINFO *)&mi)) return TRUE;
HosScreen *s = &l->out[l->n++];
memset(s, 0, sizeof *s);
s->w = (int)(mi.rcMonitor.right - mi.rcMonitor.left), s->h = (int)(mi.rcMonitor.bottom - mi.rcMonitor.top);
s->opens = l->shell ? m == l->shell : (mi.dwFlags & MONITORINFOF_PRIMARY) != 0;
screen_name(mi.szDevice, s->name, (int)sizeof s->name);
return TRUE;
}
/* (host/hos_screens.h) Every connected monitor: its size in pixels, its name, and which one the window opens on */
int hos_screens(HosScreen *out, int cap) {
struct screen_list l = {out, cap, 0, shell_monitor()};
EnumDisplayMonitors(NULL, NULL, screen_each, (LPARAM)&l);
return l.n;
}
static void dpi_aware_thread(void) {
if (getenv("HOS_DPI_UNAWARE")) return;
typedef void *(WINAPI * SetCtx)(void *);
@@ -481,7 +562,7 @@ static DWORD WINAPI display_main(void *p) {
RegisterClassA(&wc);
dpi_aware_thread();
extern float hos_aspect_ratio;
/* (the picture's shape when Monitor's shape set one, wider or narrower than 16:9: 960 x 720 for 4:3, 1720 x 720 for 21:9) */
/* (the picture's shape when it is not 16:9, the Output resolution's own or the Ultrawide row's: 960 x 720 for 4:3, 1728 x 720 for 3840 x 1600) */
int win_w = hos_aspect_ratio > 0.0f ? (int)(720 * hos_aspect_ratio + 0.5f) : 1280, win_h = 720;
if (getenv("HOS_WINDOW_SIZE")) {
int w = 0, h = 0;

View File

@@ -20,7 +20,14 @@
renderer told), so the caches are written. Esc (the window in front) or the window closed by the launcher: written
with "stopped": true.
4. No save is written while it runs (host/nn_fs.c Commit), the hearts are protected (host/hos_main.c), and the player's
devices do not count (host/nn_hid.c): the benchmark's presses count with the window behind other windows. */
devices do not count (host/nn_hid.c): the benchmark's presses count with the window behind other windows.
5. ((Triforce) 11-22) The helper-thread test (HOS_BENCH_HELPERS=1, the launcher's "Start with the helper-thread test"):
each scene is measured twice in a row, its HOS_BENCH_SECONDS with the replay helper threads off and as long with them
on (gpu/vk/vk_replay.cpp par_forced, through HOS_OPT_HELPERS_FORCE: the tuner out of the way), each after its own 1.5 s
of settling. The order turns from scene to scene (off first in the first, third, ...; on first in the second, ...), so
that warming up and a scene that changes favour neither. The scene's own figures are the "off" half's; "helpers" has
both halves, and "helper_test" the threads the test used (0: it could not run, the row's Off or a PC Automatic gives
none; each scene then measured once, the helpers as the options have them). */
#include "hos.h"
#include "hos_paths.h"
#include "hos_bench.h"
@@ -39,6 +46,7 @@ void hos_hid_tap(const char *press); /* host/nn_h
void hos_hid_stick(int lx, int ly, int rx, int ry, int hold_ms);
const char *rx_describe(void); /* host/rx_backend.c */
int rx_option(int id, int otherwise);
void rx_option_set(int id, int value);
void hos_window_close(void); /* host/display.c, host/posix/display_sdl.c */
extern const char *hos_user_dir; /* host/nn_fs.c */
@@ -52,12 +60,20 @@ extern const char *hos_user_dir; /* host/nn_f
#define HIST_BINS 2000 /* (the scene's frame times so far, 0.1 ms each up to 200 ms: the panel's 1% low) */
typedef struct { int action; char name[48]; } Scene;
/* ((Triforce) 11-22) one half of the helper-thread test's scene: its figures as a scene's */
typedef struct {
int frames, npoints;
double seconds, avg, low1, low01, max_ms;
float points[GRAPH_POINTS];
} Half;
typedef struct {
int frames;
double seconds, avg, low1, low01, max_ms;
float points[GRAPH_POINTS];
int npoints;
int scene; /* ((Triforce, 11-19) the scene it measured: a scene skipped before it shifts no name */
int tested, on_first; /* ((Triforce) 11-22) the helper-thread test: measured both ways, and in which order */
Half way[2]; /* (0 off, 1 on) */
} Result;
typedef struct { uint64_t screen, vt; int stage, presses, focus_asks; int64_t press_ns, ask_ns; } Screen;
@@ -90,6 +106,10 @@ static struct {
char error[160];
int written, closing;
int64_t end_ns;
/* ((Triforce) 11-22) the helper-thread test: asked for, the threads it uses (-1 not asked of the renderer yet, 0 none),
the scene's half being measured (0, 1), the way it holds (0 off, 1 on), and the halves measured so far */
int helpers, helper_threads, half, way, way_set;
Half halves[2];
} B = {SRWLOCK_INIT};
int hos_bench_on(void) { return B.on; }
@@ -133,6 +153,9 @@ void hos_bench_init(void) {
parse_scenes(scenes && *scenes ? scenes : "1001:Hyrule Field,1003:Castle Town Market,1000:Kokiri Forest,1007:Lake Hylia");
if (!B.nscenes) parse_scenes("1001:Hyrule Field");
B.slot = B.newest = -1;
const char *helpers = getenv("HOS_BENCH_HELPERS");
B.helpers = helpers && atoi(helpers) != 0;
B.helper_threads = -1;
B.t_start = hos_now_ns();
B.phase = MKWVK_BENCH_BOOT;
B.on = 1;
@@ -254,11 +277,9 @@ static int64_t rank_of(const int64_t *v, int n, double q) {
if (r > n) r = n;
return v[r - 1];
}
static void scene_done(void) { /* (under the lock) */
if (B.nresults >= MAX_SCENES) return;
Result *r = &B.results[B.nresults++];
/* the measured intervals' figures (under the lock; sorts B.iv) */
static void stats_of(Half *r) {
memset(r, 0, sizeof *r);
r->scene = B.scene;
r->frames = B.n;
int64_t sum = 0;
for (int i = 0; i < B.n; i++) sum += B.iv[i];
@@ -283,9 +304,34 @@ static void scene_done(void) { /* (under the lock) */
r->low1 = r->low01 = -1;
}
}
hos_log("benchmark: scene %d of %d, %s: %.1f fps average, 1%% low %.1f, 0.1%% low %.1f, %d frames in %.2f s", B.nresults,
B.nscenes, B.scenes[r->scene].name, r->avg, r->low1, r->low01, r->frames, r->seconds);
}
static int helper_test(void) { return B.helpers && B.helper_threads >= 2; }
static void scene_done(void) { /* (under the lock) */
if (B.nresults >= MAX_SCENES) return;
Result *r = &B.results[B.nresults++];
memset(r, 0, sizeof *r);
r->scene = B.scene;
Half own;
if (helper_test()) { /* (both halves measured: the scene's own figures are the "off" half's) */
r->tested = 1, r->on_first = B.way == 0; /* (the way held now is the second half's) */
r->way[0] = B.halves[0], r->way[1] = B.halves[1];
own = B.halves[0];
} else {
stats_of(&own);
}
r->frames = own.frames, r->seconds = own.seconds, r->avg = own.avg, r->low1 = own.low1, r->low01 = own.low01;
r->max_ms = own.max_ms, r->npoints = own.npoints;
memcpy(r->points, own.points, sizeof r->points);
hos_log("benchmark: scene %d of %d, %s: %.1f fps average, 1%% low %.1f, 0.1%% low %.1f, %d frames in %.2f s%s", B.nresults,
B.nscenes, B.scenes[r->scene].name, r->avg, r->low1, r->low01, r->frames, r->seconds,
r->tested ? " (the helper threads off)" : "");
if (r->tested)
hos_log("benchmark: scene %d of %d, %s, the helper threads on: %.1f fps average, 1%% low %.1f, 0.1%% low %.1f, %d "
"frames in %.2f s; off %.1f (measured %s)", B.nresults, B.nscenes, B.scenes[r->scene].name, r->way[1].avg,
r->way[1].low1, r->way[1].low01, r->way[1].frames, r->way[1].seconds, r->way[0].avg, r->on_first ? "second" : "first");
}
/* ((Triforce) 11-22) a half's figures, as the scene's in the results */
static void json_half(FILE *f, const Half *h);
static void json_text(FILE *f, const char *s) {
fputc('"', f);
for (; s && *s; s++) {
@@ -361,11 +407,21 @@ static void write_results(int stopped) { /* (under the lock; once) */
fprintf(f, ",\"avg\":%.2f,\"low1\":%.2f,\"low01\":%.2f,\"frames\":%d,\"seconds\":%.3f,\"max_ms\":%.2f,\"frametimes_ms\":[",
bench_finite(r->avg), bench_finite(r->low1), bench_finite(r->low01), r->frames, bench_finite(r->seconds), bench_finite(r->max_ms));
for (int p = 0; p < r->npoints; p++) fprintf(f, "%s%.2f", p ? "," : "", bench_finite(r->points[p]));
fprintf(f, "]}");
fprintf(f, "]");
if (r->tested) { /* ((Triforce) 11-22) the helper-thread test's two halves */
fprintf(f, ",\"helpers\":{\"first\":\"%s\",\"off\":", r->on_first ? "on" : "off");
json_half(f, &r->way[0]);
fprintf(f, ",\"on\":");
json_half(f, &r->way[1]);
fprintf(f, "}");
}
fprintf(f, "}");
}
fprintf(f, "],\"skipped\":[");
for (int i = 0; i < B.nskipped; i++) fprintf(f, "%s", i ? "," : ""), json_text(f, B.scenes[B.skipped[i]].name);
fprintf(f, "],\"settings\":");
fprintf(f, "]");
if (B.helpers) fprintf(f, ",\"helper_test\":{\"threads\":%d}", B.helper_threads > 0 ? B.helper_threads : 0);
fprintf(f, ",\"settings\":");
json_settings(f);
fprintf(f, "}\n");
const int ok = fflush(f) == 0;
@@ -377,6 +433,12 @@ static void write_results(int stopped) { /* (under the lock; once) */
hos_log("benchmark: the results could not be moved to %s", B.path);
hos_log_flush();
}
static void json_half(FILE *f, const Half *h) {
fprintf(f, "{\"avg\":%.2f,\"low1\":%.2f,\"low01\":%.2f,\"frames\":%d,\"seconds\":%.3f,\"max_ms\":%.2f,\"frametimes_ms\":[",
bench_finite(h->avg), bench_finite(h->low1), bench_finite(h->low01), h->frames, bench_finite(h->seconds), bench_finite(h->max_ms));
for (int p = 0; p < h->npoints; p++) fprintf(f, "%s%.2f", p ? "," : "", bench_finite(h->points[p]));
fprintf(f, "]}");
}
static void fail(int64_t now, const char *why) { /* (under the lock) */
if (B.phase >= MKWVK_BENCH_DONE) return;
snprintf(B.error, sizeof B.error, "%s", why);
@@ -485,6 +547,7 @@ int hos_bench_link_wants_state(void) {
}
static void go_scene(int64_t now) { /* (under the lock) the next scene's teleport */
B.phase = MKWVK_BENCH_TRAVEL, B.t_phase = now;
B.half = 0, B.way_set = 0; /* ((Triforce) 11-22: the helper-thread test's halves begin again) */
B.want = 1, B.tries = 0, B.resends = 0, B.saw_load = 0, B.retry_ns = 0, B.sent_ns = 0;
hos_log("benchmark: going to %s (scene %d of %d)", B.scenes[B.scene].name, B.scene + 1, B.nscenes);
}
@@ -569,6 +632,18 @@ void hos_bench_present(int64_t now) {
break;
case MKWVK_BENCH_SETTLE:
hos_hid_stick(0, 0, PAN, 0, 250);
if (B.helpers && B.helper_threads < 0) { /* ((Triforce) 11-22) the helper-thread test: what it can use, asked once */
B.helper_threads = rx_option(HOS_OPT_HELPERS_FORCE, 0);
if (helper_test())
hos_log("benchmark: the helper-thread test: each scene with %d helper threads off and on", B.helper_threads);
else
hos_log("benchmark: the helper-thread test cannot run here: no helper threads (the Debug tab's row Off, "
"RX_VK_PARALLEL, or a PC Automatic gives none); each scene measured once");
}
if (helper_test() && !B.way_set) { /* (the scene's first half: off first in the first scene, on first in the next) */
B.way = B.scene % 2, B.way_set = 1, B.t_phase = now;
rx_option_set(HOS_OPT_HELPERS_FORCE, B.way);
}
if (now - B.t_phase >= SETTLE_NS) {
B.phase = MKWVK_BENCH_MEASURE, B.measure_t0 = now, B.n = 0;
memset(B.hist, 0, sizeof B.hist);
@@ -587,6 +662,17 @@ void hos_bench_present(int64_t now) {
B.hist[bin < HIST_BINS ? bin : HIST_BINS]++;
}
if (now - B.measure_t0 >= (int64_t)(B.seconds * 1e9)) {
if (helper_test()) { /* ((Triforce) 11-22) a half measured: the other way next, after its own settling */
stats_of(&B.halves[B.way]);
hos_log("benchmark: %s, the helper threads %s: %.1f fps average over %d frames", B.scenes[B.scene].name,
B.way ? "on" : "off", B.halves[B.way].avg, B.halves[B.way].frames);
if (B.half == 0) {
B.half = 1, B.way ^= 1;
rx_option_set(HOS_OPT_HELPERS_FORCE, B.way);
B.phase = MKWVK_BENCH_SETTLE, B.t_phase = now;
break;
}
}
scene_done();
if (++B.scene >= B.nscenes) {
B.phase = MKWVK_BENCH_DONE, B.end_ns = now;
@@ -607,6 +693,10 @@ void hos_bench_present(int64_t now) {
if (w) GetWindowThreadProcessId(w, &pid);
if (pid == GetCurrentProcessId()) stop(now, "Esc pressed");
}
if (helper_test() && B.phase >= MKWVK_BENCH_DONE && B.way_set >= 0) { /* ((Triforce) 11-22: the tuner decides again) */
rx_option_set(HOS_OPT_HELPERS_FORCE, -1);
B.way_set = -1;
}
ReleaseSRWLockExclusive(&B.lock);
if (close) {
hos_log("benchmark: the game quits");
@@ -631,10 +721,13 @@ int hos_bench_state(MkwVkBench *out) {
const int sc = B.scene < B.nscenes ? B.scene : B.nscenes - 1;
out->scene = B.phase == MKWVK_BENCH_BOOT ? 0 : sc + 1;
snprintf(out->name, sizeof out->name, "%s", B.phase == MKWVK_BENCH_BOOT ? "" : B.scenes[sc].name);
if (helper_test() && B.way_set > 0 && (B.phase == MKWVK_BENCH_SETTLE || B.phase == MKWVK_BENCH_MEASURE))
snprintf(out->name, sizeof out->name, "%.30s, helpers %s", B.scenes[sc].name, B.way ? "on" : "off");
const int64_t now = hos_now_ns();
double frac = 0;
if (B.phase == MKWVK_BENCH_MEASURE) frac = (now - B.measure_t0) / (B.seconds * 1e9);
if (frac > 1) frac = 1;
if (helper_test()) frac = (B.half + frac) / 2; /* ((Triforce) 11-22: a scene is two halves) */
out->progress = B.phase >= MKWVK_BENCH_DONE && B.phase != MKWVK_BENCH_DONE ? (float)B.nresults / B.nscenes
: B.phase == MKWVK_BENCH_DONE ? 1.0f : B.phase == MKWVK_BENCH_BOOT ? 0.0f : (float)((sc + frac) / B.nscenes);
if (B.phase == MKWVK_BENCH_FAILED) snprintf(out->line, sizeof out->line, "%s", B.error);

104
host/hos_l3_home.h Normal file
View File

@@ -0,0 +1,104 @@
/* (Triforce, 11-23) One L3 cache for the frame's two hot threads, on a processor with two or more L3 caches of the same size: AMD's
two-die Ryzen 9 parts (a 5900X or 5950X, a 7900X or 7950X, a 9900X or 9950X), each die of six or eight cores with an L3
of its own. The replay reads what the game's main thread has just written (its command buffers, the uniforms and
vertices it filled), and on those parts the core kept for the replay was the processor's last, on the second die, while
Windows ran the main thread mostly on the first, where its preferred cores are: every line the replay read crossed
from one die's L3 to the other's over the fabric (an RX 6700 XT with a 5900X, 11-22: 12 ms of replay a frame in play).
Here the die of the lowest logical processor the process may use (the first die, where Windows' preferred cores are)
is the home: the core kept for the replay is its last core (host/hos_thread.c last_fastest_core), and the game's main
thread and its presenting thread (where the replay runs) are kept on its other cores (hos_thread_pin). The game's other
threads, the renderer's helper and recorder threads and the driver's stay where Windows puts them, on both dies: NX2navi
measured that the game held to six cores loses more than the shared cache gives (host/hos_x3d.h), and only the two
threads that hand the frame over are held here.
Nothing is done:
- with one L3 (a 5600X, a 5800X3D, a 7800X3D, an Intel processor of either kind);
- with L3 caches of different sizes: a two-die X3D part, which host/hos_x3d.h handles;
- where the home has fewer than HOS_L3_HOME_MIN_CORES cores the process may use (a 3900X's three-core CCXs, a 7900X3D's
six-core die has no home here as its caches differ): the main thread would be left fewer than five cores beside the
replay's;
- with more than one processor group, or a list that puts a processor under two L3 caches.
HOS_L3_HOME=0 turns it off. Plain code over the caches and cores the system lists: tests/test_l3_home.py runs it on
authored topologies. */
#ifndef HOS_L3_HOME_H
#define HOS_L3_HOME_H
#include <stdint.h>
#include <string.h>
#include "hos_x3d.h" /* (HosCache) */
enum {
HOS_L3_HOME_NONE, /* no L3 listed, or a list that contradicts itself */
HOS_L3_HOME_GROUPS, /* more than one processor group */
HOS_L3_HOME_ONE, /* one L3 among the processors the process may use */
HOS_L3_HOME_MIXED, /* L3 caches of different sizes (host/hos_x3d.h) */
HOS_L3_HOME_FEW, /* the home has fewer than HOS_L3_HOME_MIN_CORES cores */
HOS_L3_HOME_USED /* the home: the processors to keep the two threads and the replay's core on */
};
#define HOS_L3_HOME_MIN_CORES 6
typedef struct {
int why; /* HOS_L3_HOME_* */
uint64_t home; /* the allowed logical processors under the home's L3 (FEW, USED) */
uint64_t bytes; /* each L3's size */
int cores; /* the cores in home */
int domains; /* the L3 caches with a processor the process may use */
} HosL3Home;
/* caches: every cache listed (the L3 ones are looked at); cores: each core's logical processors; allowed: the process's
affinity; groups: the active processor groups. The home's mask when it is used (HOS_L3_HOME_USED), else 0 */
static inline uint64_t hos_l3_home_pick(const HosCache *caches, int ncaches, const uint64_t *cores, int ncores,
uint64_t allowed, int groups, HosL3Home *out) {
HosL3Home h = {HOS_L3_HOME_NONE, 0, 0, 0, 0};
*out = h;
if (groups != 1) {
out->why = HOS_L3_HOME_GROUPS;
return 0;
}
uint64_t seen = 0, first = 0;
for (int i = 0; i < ncaches; i++) {
const uint64_t m = caches[i].mask & allowed;
if (caches[i].level != 3 || !m || !caches[i].bytes) continue;
if (seen & m) return 0; /* (a processor under two L3 caches: not a list to act on) */
seen |= m;
if (!h.bytes) h.bytes = caches[i].bytes;
else if (caches[i].bytes != h.bytes) h.why = HOS_L3_HOME_MIXED;
h.domains++;
if (m & (allowed & (0 - allowed))) first = m; /* (the L3 of the lowest allowed logical processor) */
}
out->bytes = h.bytes, out->domains = h.domains;
if (!h.domains) return 0;
if (h.domains < 2) {
out->why = HOS_L3_HOME_ONE;
return 0;
}
if (h.why == HOS_L3_HOME_MIXED || !first) {
out->why = h.why == HOS_L3_HOME_MIXED ? HOS_L3_HOME_MIXED : HOS_L3_HOME_NONE;
return 0;
}
for (int i = 0; i < ncores; i++)
if (cores[i] & first) h.cores++;
out->home = first, out->cores = h.cores;
if (h.cores < HOS_L3_HOME_MIN_CORES) {
out->why = HOS_L3_HOME_FEW;
return 0;
}
out->why = HOS_L3_HOME_USED;
return first;
}
/* The two threads that hand the frame over: the game's main thread (named MainThread at the boot, sead::MainThread once
the game names it) and its presenting thread, where the replay runs (gpu/vk/vk_replay.cpp ReplayPin pins it to the
kept core while it replays and gives back this affinity after) */
static inline int hos_l3_home_thread(const char *name) {
return name && (!strcmp(name, "sead::MainThread") || !strcmp(name, "MainThread") || !strcmp(name, "Presentation Thread"));
}
/* Their affinity, 0 for none set: the home's processors the process may use, without the core kept for the replay; none
where that leaves nothing */
static inline uint64_t hos_l3_home_thread_mask(uint64_t process, uint64_t home, uint64_t reserved) {
const uint64_t m = process & home & ~reserved;
return home ? m : 0;
}
#endif

View File

@@ -16,7 +16,9 @@
#include "../gpu/vk/oot_cheat_items.h"
#include "../gpu/vk/oot_debug_link.h" /* ((Triforce) the Game flags and Cutscenes pages' lines) */
#include "achievements.h" /* ((Triforce) what an achievement asks of the save data: host/achievements.c) */
#include "save_files.h" /* ((Triforce) the title's file select: host/save_files.c) */
#include "../gpu/vk/ultrawide_rows.h" /* ((Triforce) the Ultrawide row's shapes: ultrawide_ratio) */
#include "../gpu/vk/output_sizes.h" /* ((Triforce) the picture for the Output resolution and a shape: output_picture) */
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
@@ -417,6 +419,10 @@ static int env_line_allowed(const char *name, const char *value) {
if (!strncmp(name, "SDL_", 4) && (strstr(name, "_LIB") || strstr(name, "GL_DRIVER"))) return 0;
for (const char *p = name; *p; p++)
if (!((*p >= 'A' && *p <= 'Z') || (*p >= '0' && *p <= '9') || *p == '_')) return 0;
/* ((Triforce, 11-23) HOS_LOG_FILE is a switch, not a file's name: 1, the log into triforce_log.txt whatever stderr is, so
a player whose game is started from a terminal, Steam or a script can have the log file; the file is always the one
beside the game) */
if (!strcmp(name, "HOS_LOG_FILE")) return (value[0] == '0' || value[0] == '1') && !value[1];
/* (hookshot) the switches that name a file to write or a folder take no value here, not even a bare name: one
resolves in the game's folder (HOS_SAMPLE_FILE=triforce_vk.dll emptied the renderer) */
const size_t nl = strlen(name);
@@ -1204,6 +1210,49 @@ static void oot_teleport_followup(Ctx *c) {
events && recomp_load64(c, events + 104) ? 1 : 0);
}
/* ---- (Triforce) A save file's card on the file select (host/save_files.c, on unless HOS_SAVE_FILES=0): what the game's own
load list shows of a save, told from the running game and not read out of the save. Every two seconds at Link's update,
while a save is loaded: the map he is on (Sequence_CurrentBanc, as the teleport reads it), which Spiritual Stones and
medallions he holds (their Pouch names are gpu/vk/oot_cheat_items.h's), and the game's count of his life. Nothing is
written into the game.
His life: the Int of GameData that holds his most life, in quarters of a heart. Its name is not known to this
repository, and none of the game's is taken from its files: the names below are the ones games of this engine have used,
tried once a run, the first the save data has taken, and the log says which (or that none is: the card has no hearts
then) */
static int oot_max_life(Ctx *c) {
static const char *const names[] = {"PlayerStatus.MaxLife", "MaxLife", "Player.MaxLife", "PlayerStatus.MaxHeart", "MaxHeart"};
static uint32_t hash;
static int tried;
const uint64_t mgr = oot_singleton(c, OOT_GAMEDATA_SLOT);
if (!mgr) return 0;
if (!tried) {
tried = 1;
for (unsigned i = 0; i < sizeof names / sizeof names[0] && !hash; i++) {
const uint64_t entry = oot_gd_int(c, mgr, oot_murmur3(names[i]));
if (!entry) continue;
hash = oot_murmur3(names[i]);
hos_log("save files: the card's hearts: the save data's %s is %d", names[i], (int)recomp_load32(c, entry + 0x1c));
}
if (!hash) hos_log("save files: the card's hearts: the save data has none of the names tried for Link's life: no hearts on the cards");
}
const uint64_t entry = hash ? oot_gd_int(c, mgr, hash) : 0;
return entry ? (int)recomp_load32(c, entry + 0x1c) : 0;
}
static void oot_save_card_tick(Ctx *c, int64_t now) {
static const char *const held[SAVE_CARD_ITEMS] = {"Item_Stone_Forest", "Item_Stone_Fire", "Item_Stone_Water", "Item_Medal_Light", "Item_Medal_Forest",
"Item_Medal_Fire", "Item_Medal_Water", "Item_Medal_Spirit", "Item_Medal_Shadow"};
static int64_t next;
if (!hos_save_files_on() || now < next) return;
next = now + 2000000000LL;
if (oot_pouch_count(c, oot_item_names[0]) < 0) return; /* (no save loaded: GameData holds a new game's values) */
char map[64];
int items = 0;
oot_gamedata_string(c, 0x1d6189dau, map, sizeof map); /* Sequence_CurrentBanc */
for (int i = 0; i < SAVE_CARD_ITEMS; i++)
if (oot_item_get(c, held[i]) > 0) items |= 1 << i;
hos_save_card_note(map, items, oot_max_life(c), now);
}
/* ---- (Triforce) Game flags by name and events by name: the Debug tab's two pages ----
After NX2navi's F9 panel (its flags by name and its cutscene starter; that code is not the owner's and none of it
is here: this is written on what the tools above already had of build e0f3ccfa). A flag is a Bool of GameData, which
@@ -1409,6 +1458,7 @@ static void oot_update_player_cheats(Ctx *c, uint64_t actor, uint64_t components
oot_inventory_refresh(c, now);
oot_link_tick(c, actor, now); /* ((Triforce) the Game flags and Cutscenes pages) */
oot_achievements_tick(c, now); /* ((Triforce) host/achievements.c) */
oot_save_card_tick(c, now); /* ((Triforce) host/save_files.c: this save file's card) */
if (action >= OOT_CHEAT_ITEM_ACTION && action < OOT_CHEAT_ITEM_ACTION + 256 * (int)OOT_ITEM_COUNT) {
oot_inventory_edit(c, action);
} else if (action == OOT_AGE_ACTION) {
@@ -2033,6 +2083,7 @@ static int game_main(int argc, char **argv) {
}
#endif
static char beside_image[MAX_PATH], beside_romfs[MAX_PATH], beside_user[MAX_PATH];
const int user_given = hos_user_dir != NULL; /* (--user) */
if (!image) { /* (hookshot) started with nothing, as a game is: everything beside the executable (the builder's folder) */
char dir[MAX_PATH];
const DWORD len = hos_game_path_a(dir, MAX_PATH);
@@ -2052,6 +2103,9 @@ static int game_main(int argc, char **argv) {
#else
if (!hos_user_dir) hos_user_dir = beside_user;
#endif
/* ((Triforce) the title's file select, host/save_files.c: the folder of the file last chosen; off, or a
folder named with --user: the one above) */
if (!user_given) hos_user_dir = hos_save_files_start(dir, hos_user_dir);
}
}
}
@@ -2101,14 +2155,22 @@ static int game_main(int argc, char **argv) {
return 1;
}
hos_mem_init(hos_image_end);
{ /* (hookshot) Widescreen and ultrawide (nx2/oot_wide.py): HOS_ASPECT=<ratio> (2.3889 for 3440x1440), else the Insert menu's
Ultrawide (off unless set: a fixed 16:10, 21:9 or 32:9, ultrawide_ratio). The game's picture takes that shape at its own height (the
{ /* (hookshot) Widescreen and ultrawide (nx2/oot_wide.py): HOS_ASPECT=<ratio> (2.3889 for 3440x1440), else the Output
resolution's own shape when it is not 16:9 (5120 x 1440, 5120 x 2160, Screen or Custom: the picture is that size,
host/nn_applet.c hos_output_ratio, gpu/vk/output_sizes.h), else the Insert menu's Ultrawide (off unless set: a fixed
16:10, 21:9 or 32:9, ultrawide_ratio). The game's picture takes that shape at its own height (the
world wider at the sides on an ultrawide screen, narrower on a 16:10 or 4:3 one), its 16:9 cameras the picture's ratio. Wider
than 16:9 the HUD, menus and movies keep the middle 16:9; narrower they fill the picture's width. Until now the one 16:9
constant in the game's data was changed and the 16:9 picture stretched to the window. */
const char *e = getenv("HOS_ASPECT");
float want = e ? (float)atof(e) : 0.0f;
int sized = 0; /* (the shape is the Output resolution's own: the picture is its size) */
if (!e) {
float hos_output_ratio(void);
want = hos_output_ratio();
sized = want > 0.0f;
}
if (!e && !sized) {
int row = 0, version = 0;
char path[MAX_PATH];
const DWORD len = hos_game_path_a(path, MAX_PATH);
@@ -2138,18 +2200,15 @@ static int game_main(int argc, char **argv) {
/* (a screen narrower than 16:9 too, 16:10 to 5:4: the picture keeps the game's height and is narrower, the
cameras take its ratio, and the HUD fills its width instead of a middle 16:9 wider than the screen. A 4:3 CRT
at the 1440 output: picture 1920 x 1440, scene 1440 x 1080, HUD 100%) */
if (want > game * 1.01 || (want > 1.0f && want < game * 0.99)) {
double r = want > 32.0 / 9.0 ? 32.0 / 9.0 : want < 5.0 / 4.0 ? 5.0 / 4.0 : want;
uint32_t hos_output_size(int height); /* (host/nn_applet.c: the Output resolution's height, 1440 as shipped) */
unsigned oh = hos_output_size(1), ow = (unsigned)(oh * r / 8 + 0.5) * 8; /* (whole multiples of 8 pixels) */
/* (at most 3840 x 2160's pixels, the shape kept: the game's render targets come from a pool sized for its picture
(host/nn_applet.c hos_rt_pool_size), and a 32:9 screen at the 4K output made a 7680 x 2160 one. Its pool at the
output's size ran out as Kokiri Forest loaded (a null pointer, issue 1031); a pool for the whole picture, 1.4 GB,
failed the game's own reservation at boot. 5400 x 1520 there, more than the 5120 x 1440 screens it was seen on) */
if ((double)ow * oh > 3840.0 * 2160.0) {
oh = (unsigned)(sqrt(3840.0 * 2160.0 / r) / 8) * 8;
ow = (unsigned)(oh * r / 8) * 8;
}
uint32_t hos_output_size(int height); /* (host/nn_applet.c: the Output resolution's height, 1440 as shipped) */
unsigned ow = 0, oh = 0;
/* (gpu/vk/output_sizes.h output_picture: whole multiples of 8 pixels. A shape of the row's or HOS_ASPECT's at most
3840 x 2160's pixels, the shape kept: the game's render targets come from a pool sized for its picture
(host/nn_applet.c hos_rt_pool_size), and a 32:9 screen at the 4K output made a 7680 x 2160 one. Its pool at the
output's size ran out as Kokiri Forest loaded (a null pointer, issue 1031); a pool for the whole picture, 1.4 GB,
failed the game's own reservation at boot. 5400 x 1520 there, more than the 5120 x 1440 screens it was seen on.
A size's own shape: that size) */
if (output_picture(hos_output_size(1), want, sized, &ow, &oh)) {
const unsigned sh = oh * 3 / 4, sw = (unsigned)(ow * 0.75 / 8 + 0.5) * 8; /* (the scene, 3/4 of the picture as shipped) */
hos_wide_out = (uint64_t)oh << 32 | ow;
hos_wide_scene = (uint64_t)sh << 32 | sw;

17
host/hos_screens.h Normal file
View File

@@ -0,0 +1,17 @@
/* (Triforce) The connected screens, as the game's window code finds them at the start (host/display.c on Windows,
host/posix/display_sdl.c with SDL elsewhere), for the Output resolution: host/nn_applet.c takes the size of the one the
window opens on for the old Screen value, and the Insert menu lists each one's size as a choice (MkwVkHost.screens,
host/rx_backend.c). Sizes are native pixels. A screen is told to the player by its size and its name; nothing keeps its
place in this list, which changes as screens are plugged in. */
#pragma once
typedef struct HosScreen {
int w, h; /* (pixels) */
int opens; /* (1: the game's window opens on this one) */
char name[64]; /* (the monitor's own name, UTF-8, "" where the system has none: a laptop's panel) */
} HosScreen;
/* The connected screens, at most cap of them: how many were written (0: none known, a run with no window) */
int hos_screens(HosScreen *out, int cap);
/* The size of the one the window opens on, 0 x 0 when it is not known */
void hos_screen_size(int *w, int *h);

View File

@@ -17,6 +17,7 @@ static struct {
void *CreateWindow, *SetWindowPosition, *SetWindowFullscreen, *SetRelativeMouseMode, *GetPrimaryDisplay,
*GetDesktopDisplayMode, *Vulkan_CreateSurface, *PixelSize, *GetKeyboardState, *GetMouseState, *WaitEventTimeout,
*PollEvent, *GetWindowSize, *LoadPNG, *SetWindowIcon, *DestroySurface, *GetWindowDisplay, *GetCurrentDisplayMode;
void *GetDisplays, *GetDisplayName; /* ((Triforce) optional: every display, hos_sdl_displays) */
/* sound */
void *OpenAudioDevice, *PauseAudioDevice, *OpenAudioDeviceStream, *ResumeAudioStreamDevice, *PutAudioStreamData;
/* controllers */
@@ -79,6 +80,9 @@ static int get_all(HMODULE m, int three) {
/* ((Triforce) 11-20) a controller's type and name by its place in the list, for the instruments left out (pad_kind.h) */
*(FARPROC *)&f.JoyTypeOf = GetProcAddress(m, three ? "SDL_GetJoystickTypeForID" : "SDL_JoystickGetDeviceType");
*(FARPROC *)&f.PadNameOf = GetProcAddress(m, three ? "SDL_GetGamepadNameForID" : "SDL_GameControllerNameForIndex");
/* ((Triforce) every connected display and its name: SDL3's list of ids, SDL2's count; without them the main one alone) */
*(FARPROC *)&f.GetDisplays = GetProcAddress(m, three ? "SDL_GetDisplays" : "SDL_GetNumVideoDisplays");
*(FARPROC *)&f.GetDisplayName = GetProcAddress(m, "SDL_GetDisplayName");
if (three) {
GET(SetWindowPosition, "SDL_SetWindowPosition");
GET(GetPrimaryDisplay, "SDL_GetPrimaryDisplay");
@@ -187,6 +191,42 @@ int hos_sdl_desktop_size(int *width, int *height) {
*width = m.w, *height = m.h;
return 1;
}
int hos_sdl_displays(HosSdlDisplay *out, int cap) {
int n = 0;
if (!f.GetDisplays) return 0;
if (version == 3) { /* (SDL_GetDisplays: the ids, freed with SDL_free; SDL_DisplayMode as above) */
int count = 0;
uint32_t *ids = CALL(uint32_t *(*)(int *), GetDisplays)(&count);
/* (the main display first, whatever SDL's order: it is the one hos_sdl_desktop_size reads) */
const uint32_t main_id = CALL(uint32_t (*)(void), GetPrimaryDisplay)();
for (int i = 1; ids && i < count; i++)
if (ids[i] == main_id) ids[i] = ids[0], ids[0] = main_id;
for (int i = 0; ids && i < count && n < cap; i++) {
const uint8_t *m = CALL(const uint8_t *(*)(uint32_t), GetDesktopDisplayMode)(ids[i]);
if (!m) continue;
int w, h;
float density;
memcpy(&w, m + 8, 4), memcpy(&h, m + 12, 4), memcpy(&density, m + 16, 4);
if (!(density > 0)) density = 1;
const char *name = f.GetDisplayName ? CALL(const char *(*)(uint32_t), GetDisplayName)(ids[i]) : NULL;
out[n].w = (int)(w * density + 0.5f), out[n].h = (int)(h * density + 0.5f);
snprintf(out[n].name, sizeof out[n].name, "%s", name ? name : "");
n++;
}
if (ids) CALL(void (*)(void *), Free)(ids);
return n;
}
const int count = CALL(int (*)(void), GetDisplays)(); /* (SDL2: by index, 0 the main display) */
for (int i = 0; i < count && n < cap; i++) {
struct { uint32_t format; int w, h, refresh_rate; void *driverdata; } m;
if (CALL(int (*)(int, void *), GetDesktopDisplayMode)(i, &m)) continue;
const char *name = f.GetDisplayName ? CALL(const char *(*)(int), GetDisplayName)(i) : NULL;
out[n].w = m.w, out[n].h = m.h;
snprintf(out[n].name, sizeof out[n].name, "%s", name ? name : "");
n++;
}
return n;
}
int hos_sdl_refresh_mhz(void *window) {
if (!window || !f.GetWindowDisplay || !f.GetCurrentDisplayMode) return 0;
float hz = 0;

View File

@@ -21,6 +21,10 @@ void *hos_sdl_window(const char *title, int width, int height);
void hos_sdl_fullscreen(void *window, int on); /* (the desktop's mode, borderless) */
void hos_sdl_relative_mouse(void *window, int on);
int hos_sdl_desktop_size(int *width, int *height);
/* ((Triforce) every connected display, the main one first: its desktop size in pixels and its name ("" when SDL has none);
how many were written, at most cap. 0 from an SDL without the calls: hos_sdl_desktop_size still has the main one's) */
typedef struct { int w, h; char name[64]; } HosSdlDisplay;
int hos_sdl_displays(HosSdlDisplay *out, int cap);
int hos_sdl_refresh_mhz(void *window); /* the refresh rate of the window's display in mHz, 0 when not known (the main thread) */
int hos_sdl_vulkan_surface(void *window, void *instance, void *surface_out); /* (VkInstance, VkSurfaceKHR *): 1 if made */
void hos_sdl_pixel_size(void *window, int *width, int *height);

View File

@@ -6,6 +6,7 @@
+0x1F8, so lifted SDK code that reads it inline finds the same thread the HLE knows. */
#include "hos.h"
#include "hos_x3d.h"
#include "hos_l3_home.h" /* ((Triforce, 11-23) one L3 for the main thread, the presenting thread and the replay's core) */
#include "hos_sim_cpu.h" /* ((Triforce, 11-22, OS-49) HOS_SIM_CPU, a lab switch: fewer of the PC's cores */
#include "pace_wait.h" /* ((Triforce) hos_sleep_until_ns: the frame wait to its time) */
#include "short_sleep.h" /* ((Triforce, 11-21) how sleeps under a millisecond wait, by the PC's processors) */
@@ -728,7 +729,7 @@ static uint64_t pick_reserved_core(const uint64_t *masks, const unsigned char *c
has a thread of its own (RX_VK_ASYNC=1): hos_x3d.h hos_x3d_keep_replay_core has the rule and Source A's numbers */
#if defined(_WIN32)
/* (hos_x3d_pick over what Windows lists for the calling thread's processor group) */
static uint64_t x3d_detect(HosX3d *out) {
static uint64_t x3d_detect(HosX3d *out, HosL3Home *home) {
static HosCache caches[1024];
static uint64_t cores[256];
int ncaches = 0, ncores = 0;
@@ -763,9 +764,11 @@ static uint64_t x3d_detect(HosX3d *out) {
}
free(buf);
}
hos_l3_home_pick(caches, ncaches, cores, ncores, (uint64_t)proc, (int)GetActiveProcessorGroupCount(), home); /* (Triforce, 11-23) */
return hos_x3d_pick(caches, ncaches, cores, ncores, (uint64_t)proc, (int)GetActiveProcessorGroupCount(), out);
}
#endif
static uint64_t l3_home_mask; /* ((Triforce, 11-23) hos_l3_home.h: the home, 0 for none; set with hos_x3d_cpus' mask) */
static uint64_t hos_x3d_cpus(void) {
static uint64_t mask = ~0ull;
static SRWLOCK lk = SRWLOCK_INIT;
@@ -774,9 +777,10 @@ static uint64_t hos_x3d_cpus(void) {
mask = 0;
#if defined(_WIN32)
HosX3d x;
HosL3Home h;
const char *e = getenv("HOS_X3D");
const int off = e && *e && !atoi(e);
const uint64_t die = x3d_detect(&x);
const uint64_t die = x3d_detect(&x, &h);
if (x.why == HOS_X3D_USED && !off) mask = die;
if (x.why == HOS_X3D_USED || x.why == HOS_X3D_FEW) /* (a processor with L3 caches of two sizes: said either way) */
hos_log("cpu: logical processors %#llx share the largest L3 cache (%llu MB, against %llu MB), %d cores: %s",
@@ -784,6 +788,18 @@ static uint64_t hos_x3d_cpus(void) {
x.why == HOS_X3D_FEW ? "fewer than 8, so the game's threads are not kept there"
: off ? "not used (HOS_X3D=0)"
: "the game's threads are kept there, and the replay's core when one is kept (HOS_X3D=0: as before)");
/* ((Triforce, 11-23) hos_l3_home.h: with no cache die, the home for the two threads that hand the frame over) */
const char *he = getenv("HOS_L3_HOME");
const int home_off = he && *he && !atoi(he);
if (!mask && h.why == HOS_L3_HOME_USED && !home_off) l3_home_mask = h.home;
if (h.why == HOS_L3_HOME_USED || h.why == HOS_L3_HOME_FEW)
hos_log("cpu: logical processors %#llx share one of %d L3 caches (%llu MB each), %d cores: %s",
(unsigned long long)h.home, h.domains, (unsigned long long)(h.bytes >> 20), h.cores,
h.why == HOS_L3_HOME_FEW ? "fewer than 6, so nothing is kept there"
: mask ? "not used (the cache die is)"
: home_off ? "not used (HOS_L3_HOME=0)"
: "the game's main and presenting threads and the replay's core are kept there, the other threads "
"anywhere (HOS_L3_HOME=0: as before)");
#endif
}
const uint64_t m = mask;
@@ -804,6 +820,7 @@ static uint64_t last_fastest_core(int *cores) {
GROUP_AFFINITY ga;
const WORD group = GetThreadGroupAffinity(GetCurrentThread(), &ga) ? ga.Group : 0;
const uint64_t die = hos_x3d_cpus(); /* (Triforce: the cores of the die the game's threads are kept on, when there is one) */
const uint64_t home = die ? 0 : l3_home_mask; /* ((Triforce, 11-23) or of the home, hos_l3_home.h) */
if (GetLogicalProcessorInformationEx(RelationProcessorCore, NULL, &len) || GetLastError() != ERROR_INSUFFICIENT_BUFFER)
return 0;
char *buf = (char *)malloc(len);
@@ -813,6 +830,7 @@ static uint64_t last_fastest_core(int *cores) {
if (!e->Size) break;
if (e->Relationship == RelationProcessorCore && e->Processor.GroupCount && e->Processor.GroupMask[0].Group == group &&
(!die || ((uint64_t)e->Processor.GroupMask[0].Mask & die)) &&
(!home || ((uint64_t)e->Processor.GroupMask[0].Mask & home)) &&
(!sim_cpu_mask || ((uint64_t)e->Processor.GroupMask[0].Mask & sim_cpu_mask))) { /* ((Triforce, OS-49) inside it) */
masks[n] = (uint64_t)e->Processor.GroupMask[0].Mask;
classes[n] = e->Processor.EfficiencyClass;
@@ -916,6 +934,12 @@ void hos_thread_pin(void *h, const char *name) {
const uint64_t want = hos_x3d_thread_mask((uint64_t)proc, die, reserved);
if (want) SetThreadAffinityMask(h, (DWORD_PTR)want);
}
if (l3_home_mask && hos_l3_home_thread(name)) { /* ((Triforce, 11-23) the main and presenting threads on the home, hos_l3_home.h) */
DWORD_PTR proc = 0, sys = 0;
GetProcessAffinityMask(GetCurrentProcess(), &proc, &sys);
const uint64_t want = hos_l3_home_thread_mask((uint64_t)proc, l3_home_mask, reserved);
if (want) SetThreadAffinityMask(h, (DWORD_PTR)want);
}
static NameSpec pins[24], prios[24];
static int npins = -1, nprios;
static SRWLOCK lk = SRWLOCK_INIT;
@@ -1576,6 +1600,7 @@ static struct {
threads spinning already); grant to run: from vc_grant until the waiter holds vc_lock again, after a spin and after a
sleep (NX2navi's "core grant to run", runtime/kernel.c grant_at) */
int64_t spun, slept, spin_ns, spin_capped, run_spin_ns, run_spin_n, run_sleep_ns, run_sleep_n, run_max_ns;
int64_t pin_waits; /* ((Triforce, 11-23) waits past esc_eq kept to their one core behind a better holder: vc_acquire */
} vc_st;
/* ((Triforce, 11-22, the performance audit's OS-51) the waits since the last present, beside vc_st's 5 s: their time summed
over the threads, how many, the longest. Added to with vc_lock held, taken by the present's look without it
@@ -1669,6 +1694,9 @@ static void vc_stats_locked(int64_t now) {
(long long)vc_st.slept, vc_st.run_spin_n ? vc_st.run_spin_ns / 1e3 / vc_st.run_spin_n : 0.0,
(long long)vc_st.run_spin_n, vc_st.run_sleep_n ? vc_st.run_sleep_ns / 1e3 / vc_st.run_sleep_n : 0.0,
(long long)vc_st.run_sleep_n, vc_st.run_max_ns / 1e3);
if (vc_st.pin_waits) /* ((Triforce, 11-23) vc_acquire: the escapes the one-core rule held back) */
hos_log("vcores: %lld waits held to their one core past the escape, behind a holder of better priority there "
"(HOS_VCORE_PIN_ESCAPE_MS=0: they escape at HOS_VCORE_ESCAPE_EQ_US, as before)", (long long)vc_st.pin_waits);
memset(&vc_st, 0, sizeof vc_st);
vc_st.since = now;
}
@@ -1722,9 +1750,14 @@ static int vc_spin(HosThread *t, int64_t ns) {
return 1;
}
static void vc_acquire(HosThread *t) {
static int64_t esc_better = -1, esc_eq, slice, spin;
static int64_t esc_better = -1, esc_eq, slice, spin, pin_esc;
if (esc_better < 0) {
esc_eq = vc_env_ns("HOS_VCORE_ESCAPE_EQ_US", 250000);
{ /* ((Triforce, 11-23) a waiter held to one core behind a better holder: its escape's backstop, below) */
const char *e = getenv("HOS_VCORE_PIN_ESCAPE_MS");
const long long ms = e && *e ? atoll(e) : 5000;
pin_esc = ms > 0 ? ms * 1000000LL : 0;
}
{ /* ((Triforce) the spin, vc_spin: HOS_VCORE_SPIN_US, up to a second; off where no thread may spin) */
const int64_t s = vc_env_ns("HOS_VCORE_SPIN_US", 250);
spin = !vc_spin_max() || s <= 0 ? 0 : s > 1000000000LL ? 1000000000LL : s;
@@ -1751,6 +1784,7 @@ static void vc_acquire(HosThread *t) {
if (vc_nq < 1024) vc_queue[vc_nq++] = t;
vc_st.waits++;
int spun = 0, slept = 0, ended = 0; /* ((Triforce) the spin tried, a sleep taken, the wait ended in the spin) */
int pin_noted = 0; /* ((Triforce, 11-23) this wait counted in vc_st.pin_waits */
for (;;) {
/* the worst holder worse than t on a core t may use gives it up at its next checkpoint; after
HOS_VCORE_SLICE_US (2000) of waiting, a holder as good as t does too (a time slice: Horizon would leave
@@ -1797,7 +1831,24 @@ static void vc_acquire(HosThread *t) {
break;
}
const int64_t waited = hos_now_ns() - t0;
if (waited > (worst ? esc_better : esc_eq)) {
/* ((Triforce, 11-23) A waiter held to one core, behind a holder of better priority there, does not escape at
esc_eq: Horizon never runs it then, and the game pins threads to another's core so the two never overlap.
0.7.0's load crash in f_80119570 (an effect graph's owner half made, read 0x48 / garbage +0x48) came each time
right after PreActorModelCompose escaped core 1 or 2 while BaseProcCreateAndDeleteThread held it. A backstop
at HOS_VCORE_PIN_ESCAPE_MS (5000; 0: as before) stays for a holder that never gives the core up at all */
int64_t limit = worst ? esc_better : esc_eq;
if (!worst && pin_esc && (m & (m - 1)) == 0) {
const int k = __builtin_ctz(m);
HosThread *h = k < vc_cores() ? vc_owner[k] : NULL;
if (h && h->priority < t->priority) {
limit = pin_esc;
if (waited > esc_eq && !pin_noted) {
pin_noted = 1;
vc_st.pin_waits++;
}
}
}
if (waited > limit) {
vc_dequeue(t);
vc_st.escapes++;
static int logged;

39
host/n64_pace.h Normal file
View File

@@ -0,0 +1,39 @@
/* (Triforce, 11-22) N64 Classic's frame rate (n64-classic-mode-plan.md, step 7): the frames paced at the rate the renderer
asks for (HOS_OPT_N64_FPS: Faithful's 20, or the Remembered page's row; gpu/vk/n64_rules.h fps), in play, with no restart
(nn_vi.c n64_pace_decide, pace_fps).
The host already changes the rate it paces the game by while it runs: 240 while a movie plays at the 60 cap
(movie_pace.h). pace_fps is what the pacing, the game's frame limiter, its rate slot and the real-time step go by, and
the step's average starts again whenever it changes. N64 Classic's rate is one more input to it, asked once a present
beside the movie's. It only ever lowers the rate (a rate at or above the cap is the cap's), and gives way while a movie
plays: the movie player takes one picture a frame at most, so at 20 it would skip pictures. The real-time step stops at
4/60 of a second (15 a second) and the game's rate slot takes 15 and up, so a rate under 15 is not taken. Game time
stays real time. fps_max stays the cap itself, read once, as it does for movies; the vsync event keeps the cap's rate,
as it does while a movie raises the pace.
HOS_N64_PACE=0: the renderer's rate is not taken, the cap's as before. The rules alone, no game and no clock:
tests/test_n64_pace.py compiles them. */
#pragma once
#include <stdlib.h>
/* The lowest rate taken: the real-time step's floor, 4/60 of a second */
#define N64_PACE_LOWEST 15
/* Whether the renderer's rate is taken (HOS_N64_PACE: env, its value or NULL): unset, empty or not a 0, as HOS_MOVIE_PACE
is read */
static inline int n64_pace_on(const char *env) { return !(env && *env && atoi(env) == 0); }
/* The rate N64 Classic paces the frames at this present, 0 none: the renderer's (asked: frames a second, 0 none) where it is
on, no movie plays (movie: a movie player updated in the last quarter second), it is the real-time step's to take, and it
is under the cap (cap: the Frame rate cap's rate); else none */
static inline int n64_pace_rate(int on, int asked, int movie, int cap) {
return on && !movie && asked >= N64_PACE_LOWEST && asked < cap ? asked : 0;
}
/* The rate the frames are paced by: N64 Classic's where it has one, else the one the cap and a movie give (movie_pace_fps) */
static inline int n64_pace_fps(int rate, int paced) { return rate > 0 ? rate : paced; }
/* The present's interval in vsyncs with N64 Classic's rate: 1, for it paces by itself, as a cap under 60 does (the game's
own request for 2 vsyncs a frame would make 20 into 10); else as it was */
static inline int n64_pace_interval(int rate, int interval) { return rate > 0 ? 1 : interval; }

View File

@@ -8,6 +8,9 @@
#include <string.h>
#include <time.h>
#include <windows.h> /* (the exe's folder; the browser build: the Microsoft C runtime's time functions) */
#include "../gpu/vk/output_sizes.h" /* ((Triforce) the Output resolution row's sizes, the menu's too) */
#include "../gpu/vk/ultrawide_rows.h" /* ((Triforce) the Ultrawide row as an old options file holds it: output_res_read) */
#include "hos_screens.h" /* ((Triforce) the connected screens: the one the window opens on, and each one's size for the log) */
static int64_t boot_ns;
@@ -107,37 +110,128 @@ int hos_ini_option(const char *key, int otherwise) { /* (hookshot: the Insert
/* ((Triforce, options_version 7) The Insert menu's handheld profile is the Output resolution row's 1536 x 864: output_res=7,
or HOS_OUTPUT_RES=7. handheld_profile=1 is a file's from before version 7, the row that was, until the menu writes the file
again (gpu/vk/merged_rows.h migrate: it becomes output_res=7) */
static int output_row(void) { return getenv("HOS_OUTPUT_RES") ? atoi(getenv("HOS_OUTPUT_RES")) : ini_option("output_res", 0); }
static int output_size_fields(void) {
return ini_option("output_width", -1) != -1 || ini_option("output_height", -1) != -1 || ini_option("output_custom_size", -1) != -1;
}
static int output_row(void) {
if (getenv("HOS_OUTPUT_RES")) return atoi(getenv("HOS_OUTPUT_RES"));
return output_file_read(ini_option("output_res", 0), ini_option("options_version", 0), 0, output_size_fields());
}
static int handheld(void) {
static int v = -1;
if (v < 0)
v = getenv("HOS_HANDHELD") ? atoi(getenv("HOS_HANDHELD")) != 0 : output_row() == 7 || ini_option("handheld_profile", 0) != 0;
v = getenv("HOS_HANDHELD") ? atoi(getenv("HOS_HANDHELD")) != 0 : output_row() == 7 ||
((output_legacy_file(ini_option("options_version", 0), output_size_fields()) || ini_option("options_version", 0) == 9) &&
ini_option("handheld_profile", 0) != 0);
return v;
}
/* (hookshot) The Insert menu's Output resolution (output_res=, HOS_OUTPUT_RES over it), docked only: 0 the game's 2048 x 1152,
1 2560 x 1440, 2 3840 x 2160, 3 1920 x 1080, 4 5120 x 1440, 5 5120 x 2880, 6 5120 x 2160 ((Triforce) after the others: a
saved number keeps its size). The game's frame is its display size (2560 x 1440 as shipped;
nx2/oot_patches.py apply_output_size asks hos_output_size) times its graphics scale (GetCurrentGraphicsScale: 0 x1, 1 x0.8,
2 x0.667). Here it saw scale 1 (x0 left at the call before's answer), so 2048 x 1152; each explicit size uses x1. */
saved number keeps its size), 7 handheld, 8 Screen, 9 Custom (gpu/vk/output_sizes.h, with the rule: the size is the picture's, the
game's frame 16:9 at its height). The game's frame is its display size (2560 x 1440 as shipped; nx2/oot_patches.py
apply_output_size asks hos_output_size) times its graphics scale (GetCurrentGraphicsScale: 0 x1, 1 x0.8, 2 x0.667). Here it
saw scale 1 (x0 left at the call before's answer), so 2048 x 1152; each explicit size uses x1. A size that is not 16:9
(5120 x 1440, 5120 x 2160, and Screen or Custom of such a shape) is the widescreen picture's (hos_output_ratio,
host/hos_main.c).
The menu lists every connected screen's size as a choice and saves the one chosen as Custom's size (9 with
output_width= and output_height=): a size, which means the same whichever screens are connected at the next start. 8,
Screen, is what an options file from before that has, and HOS_OUTPUT_RES=8: the size of the screen the window opens on,
as it always was; the menu saves it as that size */
static unsigned flex_wh[2][2]; /* (Triforce) Screen's and Custom's sizes as used, 0 x 0 for none: flex_read */
static void flex_read(void) {
static int done;
if (done) return;
done = 1;
int sw = 0, sh = 0;
hos_screen_size(&sw, &sh);
long w = sw, h = sh;
if (!output_size_used(w, h, &flex_wh[0][0], &flex_wh[0][1])) flex_wh[0][0] = flex_wh[0][1] = 0;
else if ((long)flex_wh[0][0] != w || (long)flex_wh[0][1] != h)
hos_log("oe: the screen's %ldx%ld is taken as %ux%u (gpu/vk/output_sizes.h: the sides, the shape and the pixels a picture can have)",
w, h, flex_wh[0][0], flex_wh[0][1]);
const char *e = getenv("HOS_OUTPUT_SIZE");
w = h = 0;
if (e) {
if (!output_parse_size(e, &w, &h)) hos_log("oe: HOS_OUTPUT_SIZE=%s is not <width>x<height>: not taken", e);
} else { /* (the file's two numbers, as the menu reads them: gpu/vk/vk_menu.cpp custom_rows_read) */
w = ini_option("output_width", 0), h = ini_option("output_height", 0);
output_custom_read(&w, &h);
}
if (!output_size_used(w, h, &flex_wh[1][0], &flex_wh[1][1])) flex_wh[1][0] = flex_wh[1][1] = 0;
else if ((long)flex_wh[1][0] != w || (long)flex_wh[1][1] != h)
hos_log("oe: the custom output size %ldx%ld is taken as %ux%u (gpu/vk/output_sizes.h: the sides, the shape and the pixels a picture can have)",
w, h, flex_wh[1][0], flex_wh[1][1]);
}
/* (the log: every connected screen with the size the game would take it at, and whether Custom's size is one of them) */
static void screens_log(int custom) {
HosScreen list[16];
const int n = hos_screens(list, 16);
int found = 0;
for (int i = 0; i < n; i++) {
unsigned w = 0, h = 0;
if (!output_size_used(list[i].w, list[i].h, &w, &h)) continue;
hos_log("oe: screen %dx%d%s%s%s%s", list[i].w, list[i].h, list[i].name[0] ? " \"" : "", list[i].name, list[i].name[0] ? "\"" : "",
list[i].opens ? ", the one the window opens on" : "");
if (custom && w == flex_wh[1][0] && h == flex_wh[1][1]) found = 1;
}
if (custom && n && !found)
hos_log("oe: output resolution Custom %ux%u is no connected screen's size: taken as it is", flex_wh[1][0], flex_wh[1][1]);
}
static unsigned out_wh[2]; /* (the Output resolution's size, the picture's: output_mode) */
static int output_mode(void) {
static int v = -1;
if (v < 0) {
static const char *const names[] = {"2048x1152 (the game's)", "2560x1440", "3840x2160", "1920x1080", "5120x1440", "5120x2880", "5120x2160"};
v = output_row();
if ((unsigned)v >= sizeof names / sizeof *names || handheld()) v = 0; /* (7, the handheld profile's: handheld() sizes it) */
hos_log("oe: output resolution %s", handheld() ? "the handheld profile's (1536x864)" : names[v]);
static const char *const names[] = {"2048x1152 (the game's)", "2560x1440", "3840x2160", "1920x1080", "5120x1440", "5120x2880", "5120x2160", "1536x864 (handheld)", "Screen", "Custom"};
if (getenv("HOS_OUTPUT_RES")) {
v = atoi(getenv("HOS_OUTPUT_RES"));
} else { /* (a file from before options_version 8: 5120 x 1440 and 5120 x 2160 as it had them, output_res_read) */
const int version = ini_option("options_version", 0);
const int row = ultrawide_row_read(ini_option("ultrawide", 0), version, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));
const int saved = ini_option("output_res", 0);
v = output_file_read(saved, version, row, output_size_fields());
if (v != saved) {
if (saved == 7 || saved == 8)
hos_log("oe: output resolution %s (%d) from native 0.5.2: now %d under options_version %d, the same choice",
saved == 7 ? "Screen" : "Custom", saved, v, OUTPUT_OPTIONS_VERSION);
else
hos_log("oe: output resolution %s with Ultrawide on another shape, from before options_version %d: %s now, the same picture",
names[saved], OUTPUT_OPTIONS_VERSION, names[v]);
}
}
if ((unsigned)v > OUTPUT_LAST || handheld()) v = 0;
if (v >= OUTPUT_SCREEN) {
flex_read();
const unsigned *s = flex_wh[v - OUTPUT_SCREEN];
if (!s[1]) { /* (no size: the screen's not known, or HOS_OUTPUT_SIZE is not one) */
hos_log("oe: output resolution %s: %s, so 2560x1440", names[v],
v == OUTPUT_SCREEN ? "the screen's size is not known" : "HOS_OUTPUT_SIZE is not a size");
v = 1;
} else {
out_wh[0] = s[0], out_wh[1] = s[1];
}
}
/* (0, the game's own 2048 x 1152: its display size 2560 x 1440 at its graphics scale x0.8, above) */
if (v < OUTPUT_SCREEN) out_wh[0] = output_fixed_size(v ? v : 1, 0), out_wh[1] = output_fixed_size(v ? v : 1, 1);
if (v >= OUTPUT_SCREEN) hos_log("oe: output resolution %s %ux%u", names[v], out_wh[0], out_wh[1]);
else hos_log("oe: output resolution %s", names[v]);
screens_log(v == OUTPUT_CUSTOM);
if (output_size_shaped(out_wh[0], out_wh[1]))
hos_log("oe: %ux%u is the picture: the game's frame is %ux%u in its middle", out_wh[0], out_wh[1],
output_frame_width(out_wh[1]), out_wh[1]);
}
return v;
}
/* The game's frame: the Output resolution's size, or 16:9 at its height when the size has another shape */
uint32_t hos_output_size(int height) {
switch (output_mode()) {
case 2: return height ? 2160 : 3840;
case 3: return height ? 1080 : 1920;
case 4: return height ? 1440 : 5120;
case 5: return height ? 2880 : 5120;
case 6: return height ? 2160 : 5120; /* ((Triforce) 5120 x 2160) */
default: return height ? 1440 : 2560;
}
output_mode();
if (height) return out_wh[1];
return output_size_shaped(out_wh[0], out_wh[1]) ? output_frame_width(out_wh[1]) : out_wh[0];
}
/* (Triforce, host/hos_main.c) The Output resolution's own shape, width over height, when it is not 16:9: the picture is then
that size, and the Ultrawide row does not apply. 0 for a 16:9 size (the row's shape, or the game's own picture) */
float hos_output_ratio(void) {
output_mode();
return output_size_shaped(out_wh[0], out_wh[1]) ? (float)((double)out_wh[0] / (double)out_wh[1]) : 0.0f;
}
/* (hookshot) The render targets' GPU pool (nx2/oot_patches.py), 0x13100000 bytes as shipped, for 2560 x 1440: a 3840x2160 3D at
the 4K output ran out of it. Scaled with the output's pixels, or the widescreen picture's when it has more (host/hos_main.c:
@@ -153,7 +247,7 @@ uint32_t hos_output_size(int height) {
output with RenoDX HDR boots and played in the world, 17,160 presents at about 50 fps, RenoDX's four shaders in place, no
error from the pool (one short session, not every area; its scene target and each copy are 118 MB there). */
/* ((Triforce, 11-21, the performance audit's TEX-85) Whether the render targets' heap is held to a size, with no room to
give: HOS_RT_POOL_MB set, or the 5120-wide outputs' 900 MB. -1 until hos_rt_pool_size has run. host/shadow_slot.h reserves
give: HOS_RT_POOL_MB set, or a picture limited to the 900 MB cap. -1 until hos_rt_pool_size has run. host/shadow_slot.h reserves
no stepped storage there unless asked to) */
static int rt_pool_pinned = -1;
int hos_rt_pool_pinned(void) { return __atomic_load_n(&rt_pool_pinned, __ATOMIC_RELAXED); }
@@ -166,21 +260,25 @@ uint64_t hos_rt_pool_size(uint64_t game) {
const uint64_t scaled = px > 2560 * 1440 ? (game * px / (2560 * 1440) + 0xfffff) & ~0xfffffULL : game;
const uint64_t minimum = 512ULL << 20, five_k = 900ULL << 20;
/* ((Triforce) and the 5120 x 2160 output: scaled, its pool is 915 MB, more than any pool known to pass the game's reservation
at a 5120-wide output; 900 MB ran the 3D at the full 5120 x 2880, a third more pixels) */
const int is_five_k = hos_output_size(0) == 5120 && hos_output_size(1) >= 2160;
at a 5120-wide output; 900 MB ran the 3D at the full 5120 x 2880, a third more pixels. So any output of more pixels than
3840 x 2160's, whether they are the frame's or the widescreen picture's: a 5120 x 2160 picture has the frame 3840 x 2160,
and scaled for the picture its pool would be those 915 MB (the 1.4 GB of a 7680 x 2160 picture failed the reservation
too, host/hos_main.c). gpu/vk/output_sizes.h keeps a picture to 5120 x 2880's pixels, the most the 900 MB are known to
hold) */
const int is_five_k = px > 3840ull * 2160ull;
extern int hos_scene_rgba16f(void);
/* (local, RenoDX port) the scene's colour target at 8 bytes a pixel in place of 4: room for it and its copies, at 3840 x 2160 33 MB each */
const uint64_t rgba16f = hos_scene_rgba16f() ? 128ULL << 20 : 0;
const uint64_t asked = (e ? strtoull(e, NULL, 0) << 20 : scaled < minimum ? minimum : is_five_k && scaled > five_k ? five_k : scaled) + (e ? 0 : rgba16f);
/* (the 5120 x 2880 output: 900 MB for the whole pool, see above; an explicit HOS_RT_POOL_MB still wins) */
const uint64_t v = !e && is_five_k && asked > five_k ? five_k : asked;
__atomic_store_n(&rt_pool_pinned, e != NULL || v != asked || (is_five_k && scaled > five_k), __ATOMIC_RELAXED); /* ((Triforce, 11-21, TEX-85)) */
__atomic_store_n(&rt_pool_pinned, e != NULL || (is_five_k && v == five_k), __ATOMIC_RELAXED); /* ((Triforce, 11-21, TEX-85)) */
static int logged;
if (!logged++) {
hos_log("applet: render target pool %llu MB (the game's %llu MB)", (unsigned long long)(v >> 20), (unsigned long long)(game >> 20));
if (v != asked)
hos_log("applet: render target pool: %llu MB asked (the %ux%u output), kept to %llu MB: more fails the game's reservation at boot",
(unsigned long long)(asked >> 20), hos_output_size(0), hos_output_size(1), (unsigned long long)(v >> 20));
hos_log("applet: render target pool: %llu MB asked (%llu pixels), kept to %llu MB: more fails the game's reservation at boot",
(unsigned long long)(asked >> 20), (unsigned long long)px, (unsigned long long)(v >> 20));
}
return v;
}

View File

@@ -8,6 +8,8 @@
of guest threads can read one file at once. Results: switchbrew "Error codes" (module 2 = fs). */
#include "hos.h"
#include "stall_host.h" /* ((Triforce, 11-22, OS-51) the host's part of a long frame, counted where it is spent) */
#include "host_alloc.h" /* ((Triforce, 11-23) hos_xcalloc: the handles' allocations wait at the commit limit */
#include "oot_title_movie.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -236,6 +238,7 @@ static void make_dirs(const char *path) { /* every parent of path */
typedef struct { char name[HOS_FS_PATH]; int is_dir; uint64_t size; } ExtraEntry; /* (a listed folder's mod-only entries) */
typedef struct {
HANDLE h; int writable; HANDLE find; WIN32_FIND_DATAA fd; int find_done, is_dir; char path[HOS_FS_PATH];
enum OotMovieFile movie;
ExtraEntry *extras; int nextras, extra_pos;
} Handle;
static Handle *handles[4096];
@@ -244,7 +247,12 @@ static SRWLOCK handle_lock = SRWLOCK_INIT;
static uint64_t new_handle(Handle *h) {
AcquireSRWLockExclusive(&handle_lock);
for (int i = 0; i < 4096; i++)
if (!handles[i]) { handles[i] = h; ReleaseSRWLockExclusive(&handle_lock); return (uint64_t)i + 1; }
if (!handles[i]) {
handles[i] = h;
oot_movie_file_change(h->movie, 1);
ReleaseSRWLockExclusive(&handle_lock);
return (uint64_t)i + 1;
}
ReleaseSRWLockExclusive(&handle_lock);
hos_fatal(NULL, "fs: out of handles");
return 0;
@@ -256,7 +264,10 @@ static Handle *get_handle(Ctx *c, uint64_t id) {
}
static void free_handle(uint64_t id) {
AcquireSRWLockExclusive(&handle_lock);
if (id && id <= 4096) handles[id - 1] = NULL;
if (id && id <= 4096 && handles[id - 1]) {
oot_movie_file_change(handles[id - 1]->movie, -1);
handles[id - 1] = NULL;
}
ReleaseSRWLockExclusive(&handle_lock);
}
@@ -353,7 +364,7 @@ static int tx_mount(const char *name, const char *uid, char *root, size_t cap) {
if (!save_tx_enabled()) return 0;
static int at_exit;
int ok = 0, locked = 1;
char note[256] = "";
char note[HOS_FS_PATH + 384] = ""; /* ((Triforce, 11-23) room for a failed working copy's file and reason: save_tx.h tx_why) */
AcquireSRWLockExclusive(&tx_lock);
const int import_said = tx_import_note[0] != 0;
if (!at_exit) at_exit = 1, atexit(hos_fs_save_finish);
@@ -587,6 +598,9 @@ HLE(_ZN2nn2fs8OpenFileEPNS0_10FileHandleEPKci) {
return;
}
{ void hos_bench_file_opened(const char *guest); hos_bench_file_opened(g); } /* ((Triforce) benchmark mode: which save file loads */
/* ((Triforce) the file select's cards, host/save_files.c: a slot of the save opened to be written is the slot the game
saves in now; nothing while the save files are off) */
if (want_write) { void hos_save_card_wrote(const char *guest_path); hos_save_card_wrote(g); }
/* (mkw-recomp) HOS_NO_MOVIES=1: MKW's WebM movies (cup openings, billboards, emblems) are not found, and the
game goes on without them (decoded by nn_video.c otherwise) */
if (!want_write && getenv("HOS_NO_MOVIES")) {
@@ -624,16 +638,33 @@ HLE(_ZN2nn2fs8OpenFileEPNS0_10FileHandleEPKci) {
if (open_keep_core) away = hos_vcore_away(); /* ((Triforce, 11-21, IO-24) otherwise given up already, above) */
HANDLE h = CreateFileA(path, GENERIC_READ | (want_write ? GENERIC_WRITE : 0), FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
const DWORD open_err = h == INVALID_HANDLE_VALUE ? GetLastError() : 0; /* (before the core is taken back) */
if (away) hos_vcore_back();
if (h == INVALID_HANDLE_VALUE) {
/* ((Triforce, 11-23, ticket "Cannot launch into game after 0.7 update", Linux) a file of a writable mount (the save's)
that is there but would not open answers "not found" all the same. In the report's log the save had no working copy,
the game's save manager looped (some 200,000 core takes a second; an open is one) and the file select never came,
and nothing said which file or why. Said for the first 8 such files */
static volatile LONG there_said;
if (writable && GetFileAttributesA(path) != INVALID_FILE_ATTRIBUTES && InterlockedIncrement(&there_said) <= 8)
hos_log("fs: OpenFile(%s): %s is there but could not be opened for %s (error %lu): the game is told it is not there",
g, path, want_write ? "writing" : "reading", (unsigned long)open_err);
if (hos_trace || fs_trace()) hos_log("fs: OpenFile(%s): not found", g);
RET(R_PATH_NOT_FOUND);
return;
}
Handle *fh = (Handle *)calloc(1, sizeof *fh);
/* ((Triforce, 11-23, ticket 1574276312678408316) at Windows' commit limit this calloc answered NULL and the write
below ended the game as "write 0" inside OpenFile, with no word of the memory; now it waits as the host's other
tables do (host_alloc.h) and, still refused, ends the game saying why */
Handle *fh = (Handle *)hos_xcalloc(1, sizeof *fh);
if (!fh) {
CloseHandle(h);
hos_fatal(c, "fs: OpenFile(%s): out of memory for its handle (Windows is out of RAM and page file)", g);
}
fh->h = h;
fh->writable = want_write;
snprintf(fh->path, sizeof fh->path, "%s", g);
fh->movie = oot_movie_file(fh->path);
G64(ARG(0)) = new_handle(fh);
if (hos_trace || fs_trace()) hos_log("fs: OpenFile(%s)", g);
RET(0);
@@ -854,7 +885,11 @@ HLE(_ZN2nn2fs12GetEntryTypeEPNS0_18DirectoryEntryTypeEPKc) {
/* ---- directories: DirectoryEntry = { char name[0x301]; pad[3]; s8 type at 0x304 (0 directory, 1 file); pad[3]; s64 size at 0x308 } ---- */
static void add_extra(void *arg, const char *name, int is_dir, uint64_t size) {
Handle *dh = (Handle *)arg;
if (!(dh->nextras & 15)) dh->extras = (ExtraEntry *)realloc(dh->extras, sizeof *dh->extras * (size_t)(dh->nextras + 16));
if (!(dh->nextras & 15)) { /* ((Triforce, 11-23) as OpenFile's handle: waits at the commit limit, NULL ends the game saying why) */
ExtraEntry *more = (ExtraEntry *)hos_xrealloc(dh->extras, sizeof *dh->extras * (size_t)(dh->nextras + 16));
if (!more) hos_fatal(NULL, "fs: OpenDirectory: out of memory for the mods' entries (Windows is out of RAM and page file)");
dh->extras = more;
}
ExtraEntry *e = &dh->extras[dh->nextras++];
snprintf(e->name, sizeof e->name, "%s", name);
e->is_dir = is_dir, e->size = size;
@@ -863,7 +898,8 @@ HLE(_ZN2nn2fs13OpenDirectoryEPNS0_15DirectoryHandleEPKci) {
char path[HOS_FS_PATH], pat[HOS_FS_PATH];
if (!host_path(gstr(ARG(1)), path, sizeof path, NULL)) { RET(R_PATH_NOT_FOUND); return; }
snprintf(pat, sizeof pat, "%s\\*", path);
Handle *dh = (Handle *)calloc(1, sizeof *dh);
Handle *dh = (Handle *)hos_xcalloc(1, sizeof *dh); /* ((Triforce, 11-23) as OpenFile's handle, above) */
if (!dh) hos_fatal(c, "fs: OpenDirectory(%s): out of memory for its handle (Windows is out of RAM and page file)", gstr(ARG(1)));
dh->is_dir = (int)ARG(2); /* mode: 1 directories, 2 files, 3 both */
snprintf(dh->path, sizeof dh->path, "%s", pat); /* (for GetDirectoryEntryCount) */
dh->find = FindFirstFileA(pat, &dh->fd);

View File

@@ -6,6 +6,7 @@
#include "step_steady.h" /* ((Triforce) HOS_STEP_STEADY=1: realtime_step) */
#include "pace_steady.h" /* ((Triforce) the Steady frame rate row: steady_period) */
#include "movie_pace.h" /* ((Triforce, 11-22, PRESENT-30) paced at 240 while a movie plays at the 60 cap) */
#include "n64_pace.h" /* ((Triforce, 11-22, N64 Classic) paced at its frame rate: n64_pace_decide, pace_fps */
#include "../gpu/vk/vk_api.h" /* (HOS_OPT_HDR_*: the Insert menu's HDR, answered by the renderer) */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
@@ -294,9 +295,13 @@ void hos_vi_native_acquire(int active) {
fps_max stays the cap itself, which the Steady row, the present interval and the other limiters' hand-off read.
Not with the Steady frame rate row on. HOS_MOVIE_PACE=0: the cap kept through movies, as before */
static int movie_raise;
/* ((Triforce, 11-22, N64 Classic, step 7) the rate it paces the frames at, 0 none (n64_pace.h): n64_pace_decide, once a
present with the movie's decision, so a movie gives way to nothing and the cap stays the cap */
static int n64_rate;
static int pace_fps(void) {
return movie_pace_fps(movie_raise, fps_max());
return n64_pace_fps(n64_rate, movie_pace_fps(movie_raise, fps_max()));
}
static void n64_pace_decide(void); /* (below) */
static void movie_pace_decide(void) {
static int on = -1, steady = -1;
static long long raised;
@@ -312,6 +317,23 @@ static void movie_pace_decide(void) {
if (!raise && movie_raise) hos_log("vi: the movie is over: frames paced at the 60 cap again, after %lld at %d", raised, MOVIE_PACE_FPS), raised = 0;
if (raise) raised++;
movie_raise = raise;
n64_pace_decide(); /* ((Triforce, N64 Classic, step 7) its rate, beside the movie's */
}
/* ((Triforce, 11-22, N64 Classic, step 7) The rate the renderer asks for (HOS_OPT_N64_FPS: Faithful's 20, or the Remembered
page's row; 0 none), taken where n64_pace.h takes it: under the cap, 15 and up, none while a movie plays. HOS_N64_PACE=0:
never. Each change said once */
static void n64_pace_decide(void) {
static int on = -1;
if (on < 0) {
on = n64_pace_on(getenv("HOS_N64_PACE"));
if (!on) hos_log("vi: HOS_N64_PACE=0: N64 Classic's frame rate is not taken, the cap's is");
}
int rx_option(int id, int otherwise);
const int was = n64_rate;
n64_rate = n64_pace_rate(on, on ? rx_option(HOS_OPT_N64_FPS, 0) : 0, movie_plays(), fps_max());
if (n64_rate != was)
hos_log(n64_rate ? "vi: N64 Classic: frames paced at %d (the cap %d)" : "vi: N64 Classic: frames paced at the cap again (%d, the cap %d)",
n64_rate ? n64_rate : fps_max(), fps_max());
}
/* (mkw-recomp) MKW's frame pacer (0x806bcbb0, x19 when it sets the interval: nvn_native.c): its measured frame time
(+0x128, ticks), its running excess (+0x218) and interval (+0x214), logged with the frame rate */
@@ -581,6 +603,9 @@ static void realtime_step(int64_t now) {
faster than real time, so a cap above 60 keeps the real-time step whatever that row says) */
/* (nor under 60: a cap of 30 would be the game at half speed for good) */
if (!rx_option(0, 1) && pace == 60) {
/* (a movie's 240 pacing left the timed step (1/240 s) there: the game's own step again, or the game ran at a quarter
of its speed at a full 60 fps after the first movie, 0.7.0 "extreme slowmo") */
__atomic_store_n(&hos_frame_seconds_bits, 0, __ATOMIC_RELAXED);
int *slot = (int *)GP(mod + 0x2c8);
if (*slot >= 15 && *slot <= 60) *slot = 60;
return;
@@ -821,7 +846,7 @@ void hos_vi_native_presented(void) {
if (ms) hos_sleep_ns(ms * 1000000LL);
}
/* (a cap under 60 paces by itself, whatever interval the game asked for while Monitor's rate was not known yet) */
const int interval = fps_max() < 60 ? 1 : present_interval;
const int interval = n64_pace_interval(n64_rate, fps_max() < 60 ? 1 : present_interval); /* ((N64 Classic) 1 at its rate) */
const int64_t now = hos_now_ns();
{ void hos_bench_present(int64_t now); hos_bench_present(now); } /* ((Triforce) benchmark mode: every present's interval) */
/* ((Triforce) the Steady frame rate row: a period this PC holds in the scene, never shorter than the cap's) */

View File

@@ -2793,6 +2793,8 @@ NV(nvnQueuePresentTexture) {
{ void hos_stall_host_presented(void); hos_stall_host_presented(); }
void hos_mod_cheats_frame(void); /* (Triforce) mod_cheats.c: the mods' cheat files, once a game frame; nothing without one */
hos_mod_cheats_frame();
void hos_save_files_frame(void);
hos_save_files_frame(); /* ((Triforce) host/save_files.c: the title's file select; nothing while it is off) */
void hos_achievements_frame(void);
hos_achievements_frame(); /* ((Triforce) host/achievements.c: its lists read and named to the menu; nothing while it is off) */
}

View File

@@ -14,6 +14,7 @@
HOS_MENU_TRACE=1: the focus changes, the screens and what the mouse does logged. */
#include "hos.h"
#include "guest_bounds.h" /* ((Triforce) hos_range_ok: set_item_key's buffer) */
#include "oot_title_movie.h" /* ((Triforce) oot_menu_screen_tick: a menu open over the title's filled movie) */
/* (Triforce) The game's own Options screen (the layout SystemOption_00; the title's Options and the pause menu's are the one
screen), by its vtable (HOS_MENU_TRACE in a headless run, 2026-11-10: the screen of 15 entries that starts to run when
Options is chosen, from the title and from the pause menu alike, and stops with Back; L and R do nothing on it). While
@@ -284,6 +285,7 @@ static void focus_locked(uint64_t screen, uint64_t pane, uint64_t lr) {
void hos_mouse_game_menu(void); /* (display.c) */
void hos_mouse_game_menu_gone(void);
int hos_mouse_game_pointer(int *x, int *y, int *w, int *h, uint32_t *pressed, int *wheel);
void rx_screen_point(int *x, int *y, int w, int h); /* (rx_backend.c: N64 Classic's TV's curve) */
void hos_hid_tap(const char *press); /* (nn_hid.c) */
void hos_hid_stick(int lx, int ly, int rx, int ry, int hold_ms);
void hos_hid_drag(int dx, int dy, int right); /* (nn_hid.c: as the camera's mouse; the left stick or the right) */
@@ -504,6 +506,8 @@ static void mouse_tick_locked(Ctx *c, uint64_t screen) {
uint32_t pressed;
const int got = hos_mouse_game_pointer(&px, &py, &w, &h, &pressed, &wheel);
if (!got) return;
/* ((Triforce, 11-22, N64 Classic) the game's screens under its TV's curve: the cursor where the curve showed them) */
rx_screen_point(&px, &py, w, h);
const int hidden = got == 2; /* (the cursor hidden while the pad is in use: the wheel only, no pointing) */
const int pause = screen == pause_screen_now();
const float scale = 3840.0f / (float)w > 2160.0f / (float)h ? 3840.0f / (float)w : 2160.0f / (float)h;
@@ -873,6 +877,7 @@ extern volatile LONG64 hos_present_count; /* (display.c: the game's own presen
static Rect mods_entry; /* (the entry's box, as the renderer draws it: under the last button by the pitch) */
static Rect quit_entry; /* ((Triforce, 11-19) Quit's, under Mods by the pitch; empty on the title's list */
static volatile LONG64 mods_entry_ns;
int hos_save_files_on(void); /* ((Triforce) host/save_files.c: on the title the entry under Mods is Save Select then) */
typedef struct { Rect r[16]; uint64_t b[16]; int n, pause; } ModsList;
static void mods_list_entry(int i, uint64_t entry, uint64_t button, void *arg) {
(void)i, (void)entry;
@@ -1018,6 +1023,13 @@ static void mods_list_tick(uint64_t screen, int title, ModsCall *call) {
mods_entry = (Rect){mx - 550, my - pitch / 2, mx + 550, my + pitch / 2};
}
quit_entry = title ? (Rect){0, 0, 0, 0} : (Rect){r.x0, r.y0 - 2 * pitch, r.x1, r.y1 - 2 * pitch};
/* ((Triforce) on the title, while the save files are on (host/save_files.c), the entry under Mods is Save Select: a line
of the title's list as Mods is one, a pitch lower. Its words are Quit's (3 clicked, 4 the mouse onto it): the renderer
knows by the list which of the two it draws there (vk_menu.cpp files_row_shown) */
if (title && hos_save_files_on()) {
const float mx = (r.x0 + r.x1) / 2, my = (r.y0 + r.y1) / 2 - 2 * pitch;
quit_entry = (Rect){mx - 550, my - pitch / 2, mx + 550, my + pitch / 2};
}
if (alpha >= 0.5f) InterlockedExchange64(&mods_entry_ns, (LONG64)now); /* (the mouse's: an entry not shown yet is not there to click) */
rx_option_set(HOS_OPT_MODS_ALPHA, (int)(alpha * 1000.0f + 0.5f));
rx_option_set(HOS_OPT_MODS_X0, (int)r.x0), rx_option_set(HOS_OPT_MODS_X1, (int)r.x1);
@@ -1093,6 +1105,7 @@ static Seen *screen_seen(uint64_t screen, int64_t now) {
void hos_oot_menu_tick(Ctx *c, uint64_t screen) {
if (!screen) return;
if (trace < 0) trace = getenv("HOS_MENU_TRACE") != NULL;
oot_menu_screen_tick(peek64(screen)); /* ((Triforce) the screen's class, each frame it runs: oot_title_movie.h) */
const int64_t now = hos_now_ns();
AcquireSRWLockExclusive(&seen_lock);
Seen *me = screen_seen(screen, now);
@@ -1200,6 +1213,7 @@ void hos_oot_menu_tick(Ctx *c, uint64_t screen) {
static int options_from_pause;
const int64_t now = hos_now_ns();
if (vt == PAUSE_SCREEN_VTABLE) __atomic_store_n(&pause_ran_ns, now, __ATOMIC_RELAXED);
oot_menu_screen_tick(vt); /* ((Triforce) the screen's class, each frame it runs: oot_title_movie.h) */
if (vt != OPTIONS_SCREEN_VTABLE) return;
static int tabs = -1;
if (tabs < 0) {

84
host/oot_title_movie.c Normal file
View File

@@ -0,0 +1,84 @@
/* OoT's title movie draw and its viewport share a thread; file handles and presents do not. */
#include "oot_title_movie.h"
#include <string.h>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
extern volatile LONG64 hos_present_count;
void hos_log(const char *fmt, ...);
enum OotMovieFile oot_movie_file(const char *path) {
const size_t n = strlen(path);
if (n < 5 || _stricmp(path + n - 5, ".webm")) return OOT_MOVIE_NONE;
const char *name = strchr(path, ':');
name = name ? name + 1 : path;
while (*name == '/') ++name;
const char prefix[] = "Event/Movie/Dm_Title_";
return !strncmp(name, prefix, sizeof prefix - 1) && !strchr(name + sizeof prefix - 1, '/')
? OOT_MOVIE_TITLE : OOT_MOVIE_OTHER;
}
static int title_only;
void oot_movie_file_change(enum OotMovieFile kind, int delta) {
/* nn_fs holds handle_lock across each insertion and removal, including duplicate opens. */
static int titles, others;
if (kind == OOT_MOVIE_TITLE) titles += delta;
else if (kind == OOT_MOVIE_OTHER) others += delta;
else return;
__atomic_store_n(&title_only, titles > 0 && others == 0, __ATOMIC_RELEASE);
}
static _Thread_local float pending_ratio;
static LONG64 last_draw = -1;
int hos_movie_cover_begin(float ratio) {
pending_ratio = oot_title_cover_ratio(ratio) && __atomic_load_n(&title_only, __ATOMIC_ACQUIRE) ? ratio : 0;
return pending_ratio != 0;
}
int hos_movie_cover_viewport(uint64_t *y, uint64_t *height) {
if (!pending_ratio) return 0;
const float ratio = pending_ratio;
pending_ratio = 0;
int32_t top = (int32_t)*y, h = (int32_t)*height;
if (!oot_title_movie_cover(ratio, &top, &h)) return 0;
*y = (uint32_t)top;
*height = (uint32_t)h;
__atomic_store_n(&last_draw, __atomic_load_n(&hos_present_count, __ATOMIC_RELAXED), __ATOMIC_RELEASE);
return 1;
}
int oot_movie_cover_recent(void) {
static int logged;
const LONG64 draw = __atomic_load_n(&last_draw, __ATOMIC_ACQUIRE);
const LONG64 now = __atomic_load_n(&hos_present_count, __ATOMIC_RELAXED);
const int covered = draw >= 0 && now - draw <= 2;
if (__atomic_exchange_n(&logged, covered, __ATOMIC_RELAXED) != covered)
hos_log("wide: title movie cover %s", covered ? "on" : "off");
return covered;
}
/* (Triforce) A menu over the filled movie (oot_title_movie.h). The menu screens' updates run on the game's threads, the
question comes from the renderer's: the present it last ran at and its class, each written and read whole */
static LONG64 menu_ran = -1;
static LONG64 menu_class;
void oot_menu_screen_tick(uint64_t screen_class) {
if (!oot_title_menu_class(screen_class)) return;
__atomic_store_n(&menu_class, (LONG64)screen_class, __ATOMIC_RELAXED);
__atomic_store_n(&menu_ran, __atomic_load_n(&hos_present_count, __ATOMIC_RELAXED), __ATOMIC_RELEASE);
}
int oot_menu_backdrop_runs(void) {
return oot_menu_recent(__atomic_load_n(&hos_present_count, __ATOMIC_RELAXED), __atomic_load_n(&menu_ran, __ATOMIC_ACQUIRE));
}
int oot_menu_over_movie(void) {
static int logged;
const int over = oot_menu_backdrop_runs();
/* (each change said, with the screen that told it: a report of a seam beside a menu at the title says which screen
the menu was, or that none of the known ones ran) */
if (__atomic_exchange_n(&logged, over, __ATOMIC_RELAXED) != over)
hos_log("wide: a menu screen %s (class %#llx): menu sides %s", over ? "runs" : "has stopped",
(unsigned long long)__atomic_load_n(&menu_class, __ATOMIC_RELAXED),
over ? "as the Ultrawide menus row asks, over the title movie too" : "off again while the title movie fills the picture");
return over;
}

71
host/oot_title_movie.h Normal file
View File

@@ -0,0 +1,71 @@
#ifndef OOT_TITLE_MOVIE_H
#define OOT_TITLE_MOVIE_H
#include <stdint.h>
enum OotMovieFile { OOT_MOVIE_NONE, OOT_MOVIE_TITLE, OOT_MOVIE_OTHER };
enum OotMovieFile oot_movie_file(const char *path);
void oot_movie_file_change(enum OotMovieFile kind, int delta);
int hos_movie_cover_begin(float ratio);
int hos_movie_cover_viewport(uint64_t *y, uint64_t *height);
int oot_movie_cover_recent(void);
/* (Triforce) A game menu open over the title's filled movie. The filled movie has no menu sides (it is the picture, edge
to edge), but a menu opened over it is drawn as in play: with the Insert menu's Ultrawide menus row on Centred its
backdrop takes the middle 16:9, and the sides beside it are the renderer's (blurred or black). Seen in the game: with the
sides off for the movie's sake the file select's blurred backdrop stood in the middle of the sharp movie, a seam at each
side. So the title alone and a menu over it have to be told apart.
What tells them apart is the game's own menu screens: every menu screen's update calls host/oot_menu.c each frame it
runs (nx2/oot_patches.py patch_menu_tick), with the screen, whose first word is its class. The title's own list
(0x84c106e8, Continue and the rest) is such a screen too and is the title, so "some menu screen runs" will not do.
A menu over the title is one of:
- the system menus' backdrop itself (host/oot_wide_hud.h's keep class 1), where it runs as a screen: the very thing
that is drawn in the middle;
- the screens the title's list opens: the file select, the chosen file's box (host/hos_bench.c names both), and the
game's Options (host/oot_menu.c OPTIONS_SCREEN_VTABLE).
None of them runs while the title alone shows, so the title cannot be taken for a menu. */
static inline int oot_title_menu_class(uint64_t screen_class) {
return screen_class == 0x84c04fb0ULL || /* the pause and system menus' backdrop */
screen_class == 0x84c0eba0ULL || /* the file select */
screen_class == 0x84c0f840ULL || /* the chosen file's box */
screen_class == 0x84c0f108ULL; /* the game's Options */
}
/* host/oot_menu.c, each frame a menu screen runs: its class */
void oot_menu_screen_tick(uint64_t screen_class);
/* 1 while such a menu ran within the last OOT_MENU_PRESENTS presents of the game (its screens run once a frame; a frame
or two can pass between a screen's last update and the last picture that shows it) */
#define OOT_MENU_PRESENTS 3
int oot_menu_over_movie(void);
/* The same without a word in the log: for the renderer, which asks whether the blur of the last picture it sees drawn is
such a menu's centred backdrop or the item wheel's whole one (MkwVkHost.wide_backdrop, gpu/vk/wide_sides_rule.h). The
item wheel is play's: none of these screens runs with it */
int oot_menu_backdrop_runs(void);
static inline int oot_menu_recent(int64_t now, int64_t ran) { return ran >= 0 && now - ran <= OOT_MENU_PRESENTS; }
/* The menu sides' margin the renderer is given (MkwVkHost.wide_menus, host/rx_backend.c): none while the filled title
movie alone shows; the picture's own (hos_wide_margin) in play, and with a menu open over the movie */
static inline float oot_wide_menu_margin(float margin, int movie_covers, int menu_over_it) {
return movie_covers && !menu_over_it ? 0.0f : margin;
}
static inline int oot_title_cover_ratio(float ratio) {
/* Allow the same 1% tolerance as the output shape check: picture widths round to 8 pixels. */
return ratio > 16.0f / 9.0f && ratio <= (12.0f / 5.0f) * 1.01f;
}
/* The SetViewport site at main+0x284824 passes y and height in target pixels and the picture's
hos_wide_ratio. Return 1 with the viewport grown and centred, or 0 with both values untouched.
At 12:5 the crop still shows 800 of 1080 lines; beyond it keep the whole movie in the middle. */
static inline int oot_title_movie_cover(float ratio, int32_t *y, int32_t *height) {
if (!oot_title_cover_ratio(ratio) || *height <= 0)
return 0;
const int64_t covered = (int64_t)((double)*height * ratio * 9 / 16 + 0.5);
const int64_t top = (int64_t)*y - (covered - *height) / 2;
if (covered > INT32_MAX || top < INT32_MIN)
return 0;
*y = (int32_t)top;
*height = (int32_t)covered;
return 1;
}
#endif

View File

@@ -3,7 +3,7 @@
at 0x80794368), and the Ultrawide HUD row's setting.
The Insert menu's "Ultrawide HUD" row (ultrawide_hud= in the options file): 0 the middle, as before; 1 the screen's
edges. HOS_WIDE_HUD=<0|1> over it. Read once, at the start: the hearts', the item slot's and the small map's panes
edges. HOS_WIDE_HUD=<0|1> over it. Read once, at the start: the edge-anchored HUD panes
are moved in the layouts as the game loads them (host/prompts.c build_layouts asks hos_wide_hud_out).
Lab switches: HOS_WIDE_LOG=1 names each screen class the first time its projection is set (its address and where it
was put); HOS_WIDE_SHIFT=<class in hex>=<l|r|m>,... moves whole layouts to a side, to find out what a class draws. */

View File

@@ -11,14 +11,14 @@
(oot_hud_row can also move a whole layout out to one side, which the lab's HOS_WIDE_SHIFT uses to find out what a
screen draws. No layout of the game's is placed that way: see below.)
The Insert menu's "Ultrawide HUD" row on Screen edges puts the hearts and the item slot in the picture's top corners
and the small map at its right edge. Those are moved inside their layouts, by oot_hud_out, because a projection
The Insert menu's "Ultrawide HUD" row on Screen edges places the side HUD, notices, and edge-anchored action states at their
authored offsets from the picture's edges. Those are moved inside their layouts, by oot_hud_out, because a projection
cannot do it: PlayerStatus_00 holds the hearts (on a pane at the grid's top left corner) and the item slot (on one at
its top right) together, and MapMenu_00 is the small map and the pause menu's whole-screen map in one layout, whose
projection is not set again as the menu opens (tried: the menu's map sat off to the right). nx2/prompt_assets.py
HUD_SIDE_PANES lists the panes, host/prompts.c build_layouts writes them as the game loads its layouts, so the row is
read once, at the start. Layouts that follow something in the 3D world (the targeting pointer, an enemy's bar, a
speech balloon) and the action buttons stay in the middle. */
speech balloon) stay in the middle. Only the right-hand action-button state moves. */
#ifndef OOT_WIDE_HUD_H
#define OOT_WIDE_HUD_H
#include <stdint.h>

View File

@@ -11,6 +11,7 @@
the game gets none of it; the capture it had comes back when the menu closes. */
#include "../hos.h"
#include "../hos_sdl.h"
#include "../hos_screens.h" /* ((Triforce) the connected screens, for the Output resolution) */
/* (the window's app id: the applications menu's entry names it as its StartupWMClass, builder/linux/hookshot_builder.py) */
#define HOS_APP_ID "io.github.NotRexed.Hookshot"
@@ -178,6 +179,34 @@ static void menu_mouse(int open) {
captured_before_menu = 0;
}
}
/* ((Triforce) host/hos_screens.h) Every connected display, read once on the main thread in hos_display_init (SDL's video
calls belong to it): SDL's list with the main display first, which is the one the window opens on as far as the host
can say (the compositor places it); from an SDL without the list, the main display alone, by the size already read */
static HosScreen screens[16];
static int screens_n;
static void screens_read(int main_w, int main_h) {
HosSdlDisplay d[16];
const int n = hos_sdl_displays(d, 16);
screens_n = 0;
for (int i = 0; i < n; i++) {
if (d[i].w <= 0 || d[i].h <= 0) continue;
HosScreen *s = &screens[screens_n];
memset(s, 0, sizeof *s);
s->w = d[i].w, s->h = d[i].h, s->opens = screens_n == 0;
snprintf(s->name, sizeof s->name, "%s", d[i].name);
screens_n++;
}
if (!screens_n && main_w > 0 && main_h > 0) {
memset(&screens[0], 0, sizeof screens[0]);
screens[0].w = main_w, screens[0].h = main_h, screens[0].opens = 1;
screens_n = 1;
}
}
int hos_screens(HosScreen *out, int cap) {
const int n = screens_n < cap ? screens_n : cap;
memcpy(out, screens, (size_t)n * sizeof *out);
return n;
}
static int sdl_ready;
int hos_display_owns_sdl(void) { return sdl_ready; } /* (controllers stay on this thread while it runs SDL) */
@@ -205,12 +234,18 @@ int hos_display_init(void) {
fprintf(stderr, "display: SDL_Init: %s: no window\n", hos_sdl_error());
return -1;
}
int w, h;
int w = 0, h = 0;
if (hos_sdl_desktop_size(&w, &h)) hos_posix_window[1] = w, hos_posix_window[2] = h;
screens_read(w, h); /* ((Triforce) every display, on this thread: the game's asks later, hos_screens) */
sdl_ready = 1;
return 1;
}
/* (Triforce) The size, in pixels, of the display the game's window opens on, for the Output resolution
(host/nn_applet.c): the desktop's main display, as hos_display_init read it before the game; 0 x 0 with no SDL or no
display (HOS_HEADLESS). A window on another display keeps the picture it started with, fitted into it. */
void hos_screen_size(int *w, int *h) { *w = hos_posix_window[1], *h = hos_posix_window[2]; }
/* the game's thread, when NVN is up (hos_main.c): the window is made on the main thread, which waits for this */
void hos_display_start(void) {
if (getenv("HOS_HEADLESS") || !sdl_ready) { /* no window: the renderer still draws, offscreen (screenshots) */
@@ -229,7 +264,7 @@ void hos_display_loop(void) {
HosSdlEvent e;
while (!__atomic_load_n(&start_asked, __ATOMIC_ACQUIRE)) hos_sdl_wait_event(&e, 10); /* (nothing to show yet) */
extern float hos_aspect_ratio;
/* (the picture's shape when Monitor's shape set one, wider or narrower than 16:9: 960 x 720 for 4:3, 1720 x 720 for 21:9) */
/* (the picture's shape when it is not 16:9, the Output resolution's own or the Ultrawide row's: 960 x 720 for 4:3, 1728 x 720 for 3840 x 1600) */
int win_w = hos_aspect_ratio > 0.0f ? (int)(720 * hos_aspect_ratio + 0.5f) : 1280, win_h = 720;
if (getenv("HOS_WINDOW_SIZE")) {
int w = 0, h = 0;

View File

@@ -508,7 +508,7 @@ static void ring_places(const int *bind, int place[4]) {
- the ocarina hint's icons moved apart for the wide ones bound (prompts/<face>/hint.bin, nx2/prompt_assets.py HINTS: "HPHN",
u32 count of pad inputs, each one's icon's extra width (f32), u32 panes; each: u32 offset, u8 slot, 3 bytes, f32 x): each
icon the one before's extra further on, the last one where it is;
- the hearts, the item slot and the small map out at a wide picture's sides (prompts/wide.bin, nx2/prompt_assets.py HUD_SIDE_PANES: "HPWD", u32
- the edge-anchored HUD out at a wide picture's sides (prompts/wide.bin, nx2/prompt_assets.py HUD_SIDE_PANES: "HPWD", u32
count; each: u32 offset, i8 side, 3 bytes, f32 x), with the Insert menu's Ultrawide HUD row on Screen edges
(host/oot_wide_hud.h);
none when all are as the game has them (the game's own file) */
@@ -602,7 +602,7 @@ static int build_layouts(char *out, size_t cap) {
snprintf(path, sizeof path, "%sprompts/Common.blarc", dir);
snprintf(keypath, sizeof keypath, "%sprompts/Common.blarc.key", dir);
ok = write_patched(path, out, keypath, h, runs, nruns);
hos_log("prompts: the Talk ring's A B X Y at places %d %d %d %d, the ocarina hint %s, the hearts, item slot and map %s%s",
hos_log("prompts: the Talk ring's A B X Y at places %d %d %d %d, the ocarina hint %s, edge-anchored HUD %s%s",
place[0], place[1], place[2], place[3], xs ? "spread" : "as is", wxs ? "at the picture's sides" : "as is",
ok ? "" : ": could not be written");
}

View File

@@ -3,6 +3,8 @@
executable. Decided at rx_start, before any other rx_* call; a DLL that is missing or finds no usable Vulkan
device leaves the WebGPU renderer in place (logged). */
#include "hos.h"
#include "oot_title_movie.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define WIN32_LEAN_AND_MEAN
@@ -60,6 +62,7 @@ void hos_mic_select(int mode, const char *name, int index);
void hos_bind(int set, int button, int slot, int code);
int hos_prompts_face(void); /* prompts.c */
int hos_prompts_pad_face(void);
#include "hos_screens.h" /* ((Triforce) display.c: the connected screens, for the Insert menu's Output resolution) */
#if defined(A64_WRITE_TRACK) && !defined(__EMSCRIPTEN__)
void hos_mark_written(const void *p, size_t n);
#endif
@@ -275,8 +278,17 @@ static float host_wide_menus(uint32_t keep_mask) { /* (MkwVkHost.wide_menus) *
static int looked;
if (!looked) looked = 1, forced = getenv("HOS_WIDE_KEEP");
hos_wide_keep_mask = forced ? (uint32_t)strtoul(forced, NULL, 16) : keep_mask;
return hos_wide_margin;
/* ((Triforce) no sides beside the filled title movie, but those the row asks for beside a menu opened over it: both
asked every time, each says its own changes in the log) */
int rx_option(int id, int otherwise);
const int covers = oot_movie_cover_recent(), menu = oot_menu_over_movie() || rx_option(HOS_OPT_MODS_MUSIC, 0) == 2;
return oot_wide_menu_margin(hos_wide_margin, covers, menu);
}
static int host_wide_backdrop(void) {
int rx_option(int id, int otherwise);
/* The renderer owns Mods over the title; no guest screen class reports it to oot_menu_screen_tick. */
return oot_menu_backdrop_runs() || rx_option(HOS_OPT_MODS_MUSIC, 0) == 2;
} /* (MkwVkHost.wide_backdrop) */
int hos_mouse_pointer(MkwVkPointer *out); /* display.c, posix/display_sdl.c */
int hos_sdl_gyro_status(void); /* pad_sdl.c */
extern const char *hos_romfs_dir; /* nn_fs.c, set by hos_main.c */
@@ -297,6 +309,18 @@ int hos_vk_take_key_press(int key) {
#define host_take_key_press NULL
#endif
/* ((Triforce) MkwVkHost.screens: the window code's list, as the interface has a screen) */
static int host_screens(MkwVkScreen *out, int cap) {
HosScreen list[16];
int n = hos_screens(list, cap < 16 ? cap : 16);
for (int i = 0; i < n; i++) {
memset(&out[i], 0, sizeof out[i]);
out[i].w = list[i].w > 0 ? (uint32_t)list[i].w : 0, out[i].h = list[i].h > 0 ? (uint32_t)list[i].h : 0;
out[i].opens = list[i].opens;
snprintf(out[i].name, sizeof out[i].name, "%s", list[i].name);
}
return n;
}
static const MkwVkHost vk_host = {
MKWVK_API_VERSION, host_log, hos_guest_base, hos_guest_size, hos_gpu_ptr, nvn_gpu_guest, nvn_gpu_read,
nvn_gpu_write, host_collect, host_free_pages, host_mark_written, hos_ticks, hos_now_ns, nvn_tex_layout,
@@ -304,7 +328,7 @@ static const MkwVkHost vk_host = {
hos_gpu_maps_generation, nvn_vmap_generation, hos_reserved_cpus, host_collect_in, host_guest_alloc,
host_watch_guest_writes, hos_pad_raw, hos_binding, hos_bind, host_aspect_ratio, host_take_key_press,
hos_mouse_pointer, hos_mic_count, hos_mic_name, hos_mic_select, hos_sdl_gyro_status, hos_log_flush, hos_prompts_face,
host_romfs_dir, host_wide_menus, hos_bench_state, hos_prompts_pad_face,
host_romfs_dir, host_wide_menus, hos_bench_state, hos_prompts_pad_face, host_screens, host_wide_backdrop,
};
static const MkwVkRenderer *vk; /* the Vulkan back end, when it was chosen and started */
@@ -704,6 +728,9 @@ int rx_memory_holders(char *out, size_t n) {
}
/* (nvn_native.c: the CPU set an event's value) in order with the submits, for the GPU's waits on it */
int rx_option(int id, int otherwise) { return vk && vk->option ? vk->option(id) : otherwise; }
/* ((Triforce, 11-22, N64 Classic) the cursor under its TV's curve: where the game's picture under it was drawn (vk_api.h
screen_point); as it is without the renderer's answer */
void rx_screen_point(int *x, int *y, int w, int h) { if (vk && vk->screen_point) vk->screen_point(x, y, w, h); }
void rx_option_set(int id, int value) { if (vk && vk->option_set) vk->option_set(id, value); }
void rx_nvn_event_signal(uint64_t gpu, uint32_t value) {
if (vk && vk->nvn_event_signal) vk->nvn_event_signal(gpu, value);

274
host/save_files.c Normal file
View File

@@ -0,0 +1,274 @@
/* (Triforce) Save files, as the Nintendo 64 game had them: the title asks which file to play, and the game's saves and
autosaves live in that file. host/save_files.h has what a file is and the form of triforce_files.txt; this file has
what is the game folder's and the menu's.
- On by default (11-23); HOS_SAVE_FILES=0 (triforce_env.txt) turns it off. While off the game's folder is the one it
always had, and nothing is read or written here. Off too when the folder was named on the command line (--user).
- hos_save_files_start (host/hos_main.c, before the game's memory is made): the folder of the file the last choice
named, which becomes hos_user_dir. The game mounts it at its start, reads its saves once, before its title shows,
and keeps them in memory (tried: files taken out of the mounted folder at the title were still listed and loaded):
so another file is another start, and never a folder changed under a running game.
- hos_save_files_frame (host/nvn_native.c, at each present): once the renderer answers, the files are named to the
menu (HOS_OPT_FILES_TEXT, _ADD, _COUNT: gpu/vk/save_file_rows.h), which asks at the title which to play. A file
chosen that is not this run's (HOS_OPT_FILES_ASK) is written to triforce_files.txt as the next start's, with the
time, and the menu is told (HOS_OPT_FILES_SAID): it restarts the game, as its Restart now does. The start that
follows a choice says so to the menu (which asks at the title all the same: that is where a file is changed again).
- A file's save is never opened here: whether it has one, when it was last written and which of its files holds its
picture are its folder's own (the menu reads the picture out of that file itself). Where it was played last, its
stones, medallions and hearts are told by host/hos_main.c as it is played (hos_save_card_note) and kept beside it,
triforce_card.txt: what the game's own load list shows of a save, without the save's data read. */
#include "hos.h"
#include "hos_paths.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "../gpu/vk/vk_api.h"
#include "save_files.h"
int rx_option(int id, int otherwise);
void rx_option_set(int id, int value);
#define FILES_FILE "triforce_files.txt"
enum { FILES_PATH = MAX_PATH + 64, FILES_MOST = 4096 };
static SaveFiles files;
static int started; /* hos_save_files_start chose a folder: the files are this run's */
static int after_choice; /* this start follows a file's choice */
static char files_path[FILES_PATH]; /* triforce_files.txt */
static char base_dir[FILES_PATH]; /* file 1's folder */
static char user_dir[FILES_PATH]; /* this run's */
/* On unless HOS_SAVE_FILES=0 ((Triforce) 11-23, the owner's word: on by default; File 1 is the folder the game always had, so
a start with no triforce_files.txt plays the saves it always did). Read once */
int hos_save_files_on(void) {
static int on = -1;
if (on < 0) {
const char *e = getenv("HOS_SAVE_FILES");
on = !(e && e[0] == '0' && !e[1]);
}
return on;
}
static void files_read(void) {
static char text[FILES_MOST + 1];
FILE *f = fopen(files_path, "rb");
const size_t n = f ? fread(text, 1, FILES_MOST, f) : 0;
if (f) fclose(f);
text[n] = 0;
for (size_t i = 0; i < n; i++)
if (!text[i]) text[i] = ' ';
save_files_parse(&files, text);
}
/* triforce_files.txt whole, under another name first: 1 written */
static int files_save(void) {
static char text[FILES_MOST];
char fresh[FILES_PATH + 8];
const size_t n = save_files_write(&files, text, sizeof text);
if (!n) return 0;
snprintf(fresh, sizeof fresh, "%s.new", files_path);
FILE *f = fopen(fresh, "wb"); /* (its lines end the same on Windows and Linux) */
const int ok = f && fwrite(text, 1, n, f) == n;
if ((f && fclose(f)) || !ok || !MoveFileExA(fresh, files_path, MOVEFILE_REPLACE_EXISTING)) {
remove(fresh);
hos_log("save files: %s could not be written", files_path);
return 0;
}
return 1;
}
/* host/hos_main.c, at the start, the game's folder known and no --user given: the folder the game saves in this run.
game_dir: the game folder; base_user: the folder the game always had. Off: base_user itself */
const char *hos_save_files_start(const char *game_dir, const char *base_user) {
if (!hos_save_files_on()) return base_user;
if (snprintf(files_path, sizeof files_path, "%s%c%s", game_dir, strchr(game_dir, '\\') ? '\\' : '/', FILES_FILE) >= (int)sizeof files_path ||
!save_files_folder(base_user, 0, base_dir, sizeof base_dir)) {
hos_log("save files: the game folder's path is too long: the game's own folder is used, %s", base_user);
return base_user;
}
files_read();
if (!save_files_folder(base_dir, files.current, user_dir, sizeof user_dir)) files.current = 0, snprintf(user_dir, sizeof user_dir, "%s", base_dir);
after_choice = save_files_chosen_now(&files, (int64_t)time(NULL));
if (files.chosen) { /* (taken: a start after this one asks again) */
files.chosen = 0;
files_save();
}
started = 1;
hos_log("save files: file %d of %d, \"%s\": its saves are in %s%s", files.current + 1, SAVE_FILES, files.names[files.current], user_dir,
after_choice ? " (chosen at the title: the game restarted for it)" : "");
return user_dir;
}
/* ---- the menu's side: gpu/vk/save_file_rows.h ---- */
static void to_menu(const char *text) {
for (const char *p = text; *p; p++) rx_option_set(HOS_OPT_FILES_TEXT, (unsigned char)*p);
}
/* a time as the game's own load list writes a save's: 11/18/2026 1:40 a.m. ("" for none) */
static void game_time(time_t t, char *out, size_t cap) {
const struct tm *tm = t > 0 ? localtime(&t) : NULL;
out[0] = 0;
if (tm) snprintf(out, cap, "%d/%d/%d %d:%02d %s", tm->tm_mon + 1, tm->tm_mday, tm->tm_year + 1900, tm->tm_hour % 12 ? tm->tm_hour % 12 : 12, tm->tm_min,
tm->tm_hour < 12 ? "a.m." : "p.m.");
}
static time_t unix_of(const FILETIME *ft) { /* (a FILETIME: 100 ns since 1601; 0 when it is none) */
const uint64_t v = (uint64_t)ft->dwHighDateTime << 32 | ft->dwLowDateTime;
return v > 116444736000000000ULL ? (time_t)((v - 116444736000000000ULL) / 10000000ULL) : 0;
}
/* What a file's card shows of its save, from its folder alone (no save is opened here): when its account.sav was last
written, in `when` ("" when it has no save yet, or the time cannot be told), and where its slots are, in `picture`: the
start of their caption files' paths, up to the slot's number ("" none). The game keeps a save's picture and its time
in that file, and the menu reads them from there itself (gpu/vk/save_file_rows.h jpeg_in, caption_time). 1 when the
file has a save: a slot, not the account.sav alone */
static int last_saved(int file, char *when, size_t when_cap, char *picture, size_t picture_cap) {
char dir[FILES_PATH], pat[FILES_PATH + 96];
WIN32_FIND_DATAA fd, found;
int saved = 0;
when[0] = picture[0] = 0;
if (!save_files_folder(base_dir, file, dir, sizeof dir)) return 0;
snprintf(pat, sizeof pat, "%s\\save\\*", dir);
HANDLE h = FindFirstFileA(pat, &fd);
if (h == INVALID_HANDLE_VALUE) return 0;
do {
if (fd.cFileName[0] == '.' || strlen(fd.cFileName) > 40) continue;
snprintf(pat, sizeof pat, "%s\\save\\%s\\account.sav", dir, fd.cFileName);
HANDLE a = FindFirstFileA(pat, &found);
if (a == INVALID_HANDLE_VALUE) continue;
FindClose(a);
const time_t t = unix_of(&found.ftLastWriteTime);
game_time(t, when, when_cap);
for (int slot = 0; slot < 12; slot++) { /* (the game looks for slot_00 to slot_11) */
snprintf(pat, sizeof pat, "%s\\save\\%s\\slot_%02d\\caption.sav", dir, fd.cFileName, slot);
HANDLE s = FindFirstFileA(pat, &found);
if (s == INVALID_HANDLE_VALUE) continue;
FindClose(s);
saved = 1;
}
/* ((Triforce) 11-18, his picture of the game's own load list beside the card: "the screenshot doesn't match the last
autosave either nor does the time". The slot written last cannot be told from the disk: the game writes them all
again whenever it saves one. Where the slots are, then, and the menu reads each one's own time out of it) */
if (saved && snprintf(picture, picture_cap, "%s\\save\\%s\\slot_", dir, fd.cFileName) >= (int)picture_cap) picture[0] = 0;
/* ((Triforce) 11-18, his picture: File 2, a new game started and not yet saved, said "Saved game" with no picture. The
game makes account.sav as it starts on a file: a file has a save once it has a slot) */
if (!saved) when[0] = 0;
break;
} while (FindNextFileA(h, &fd));
FindClose(h);
return saved;
}
/* ---- a file's card: host/save_files.h SaveCard ---- */
#define CARD_FILE "triforce_card.txt"
static int card_path(const char *dir, char *out, size_t cap) {
return snprintf(out, cap, "%s%c" CARD_FILE, dir, strchr(dir, '\\') ? '\\' : '/') < (int)cap;
}
/* A file's card as its folder keeps it: nothing of it when the file was not played with this yet */
static void card_of(int file, SaveCard *card) {
char dir[FILES_PATH], path[FILES_PATH + 40], text[512];
memset(card, 0, sizeof *card);
if (!save_files_folder(base_dir, file, dir, sizeof dir) || !card_path(dir, path, sizeof path)) return;
FILE *f = fopen(path, "rb");
if (!f) return;
const size_t n = fread(text, 1, sizeof text - 1, f);
fclose(f);
text[n] = 0;
for (size_t i = 0; i < n; i++)
if (!text[i]) text[i] = ' ';
save_card_parse(card, text);
}
/* ---- the card kept. Two of the game's threads come here, Link's update and whichever one saves: what they share is under
one lock, held for a card's writing and no longer ---- */
static volatile char card_busy;
static SaveCard card_kept; /* what this file's triforce_card.txt has */
static SaveCard card_seen; /* the place, the items and the hearts as last told */
static int card_known, card_told; /* the kept card was read; something was told this run */
static void card_lock(void) {
while (__atomic_test_and_set(&card_busy, __ATOMIC_ACQUIRE)) {}
}
static void card_unlock(void) { __atomic_clear(&card_busy, __ATOMIC_RELEASE); }
/* (with the lock held) the card written into this run's folder, whole, under another name first */
static void card_keep(const SaveCard *card) {
char path[FILES_PATH + 40], fresh[FILES_PATH + 48], text[512];
const size_t n = save_card_write(card, text, sizeof text);
if (!n || !card_path(user_dir, path, sizeof path)) return;
snprintf(fresh, sizeof fresh, "%s.new", path);
FILE *f = fopen(fresh, "wb"); /* (its lines end the same on Windows and Linux) */
const int ok = f && fwrite(text, 1, n, f) == n;
if ((f && fclose(f)) || !ok || !MoveFileExA(fresh, path, MOVEFILE_REPLACE_EXISTING)) {
remove(fresh);
static int said;
if (!said++) hos_log("save files: %s could not be written: this file's card stays as it was", path);
return;
}
card_kept = *card;
}
/* host/nn_fs.c, a file of the save opened to be written (any of the game's threads): a slot's is that slot saved in, now.
Kept at once, with the place, the items and the hearts as last told. ((Triforce) 11-18: it was kept at Link's next
update. He saved from the pause menu, where Link is not updated, and went to the title: the card never had the save.)
The game writes a slot's caption and its progress one after the other: one save, one time */
void hos_save_card_wrote(const char *guest_path) {
const int slot = started ? save_card_slot_of(guest_path) : -1;
if (slot < 0) return;
const int64_t now = (int64_t)time(NULL);
card_lock();
if (!card_known) card_known = 1, card_of(files.current, &card_kept);
SaveCard card = card_told ? card_seen : card_kept;
card.slot1 = slot + 1;
card.saved = card_kept.slot1 == slot + 1 && now >= card_kept.saved && now - card_kept.saved < 10 ? card_kept.saved : now;
if (!save_card_same(&card, &card_kept)) card_keep(&card);
card_unlock();
}
/* host/hos_main.c, every two seconds at Link's update while a save is loaded (the game's thread; now_ns: hos_now_ns): the
map he is on (its own name), the stones and medallions he holds (SAVE_CARD_* bits) and the game's count of his life (0:
not known). What the next save is kept with; and kept by itself when it is not what is kept already, five seconds
apart at most, so that a file played and not saved in has its card too */
void hos_save_card_note(const char *map, int items, int life, int64_t now_ns) {
static int64_t next;
if (!started || !map || !map[0]) return;
SaveCard card;
memset(&card, 0, sizeof card);
save_card_place(map, card.place, sizeof card.place);
card.items = items & ((1 << SAVE_CARD_ITEMS) - 1), card.hearts = save_card_hearts(life);
card_lock();
if (!card_known) card_known = 1, card_of(files.current, &card_kept);
card.slot1 = card_kept.slot1, card.saved = card_kept.saved; /* (the slot saved in last: hos_save_card_wrote's) */
card_seen = card, card_told = 1;
if (now_ns >= next && !save_card_same(&card, &card_kept)) next = now_ns + 5000000000LL, card_keep(&card);
card_unlock();
}
/* host/achievements.c: the folder of the file this run plays, where what that file earned is kept; NULL while the save
files are off (the game folder keeps it then). *first: it is File 1, which was the game's only one before */
const char *hos_save_files_dir(int *first) {
if (!started) return NULL;
*first = files.current == 0;
return user_dir;
}
static void name_files(void) {
for (int i = 0; i < SAVE_FILES; i++) {
char when[32], picture[FILES_PATH + 96], shown[SAVE_CARD_PLACE + 96], made[32] = "";
SaveCard card;
const int saved = last_saved(i, when, sizeof when, picture, sizeof picture);
card_of(i, &card);
game_time((time_t)card.saved, made, sizeof made);
/* (its place, its items, its hearts; then the slot saved in last, -1 not known, and when, as the game writes a time) */
snprintf(shown, sizeof shown, "%s|%x|%d|%d|%s", card.place, (unsigned)card.items, card.hearts, card.slot1 - 1, card.slot1 ? made : "");
to_menu(files.names[i]), to_menu("\n"), to_menu(when), to_menu("\n"), to_menu(picture), to_menu("\n"), to_menu(shown);
rx_option_set(HOS_OPT_FILES_ADD, (saved ? HOS_FILE_SAVED : 0) | (i == files.current ? HOS_FILE_CURRENT : 0));
}
rx_option_set(HOS_OPT_FILES_COUNT, SAVE_FILES | (after_choice ? HOS_FILES_CHOSEN : 0));
}
/* host/nvn_native.c, at each present of the game's: the files named to the menu once it answers, and the file it chose
made the next start's */
void hos_save_files_frame(void) {
static int named; /* (the present's thread alone) */
if (!started) return;
const int ask = rx_option(HOS_OPT_FILES_ASK, -1);
if (ask < 0) return; /* (no renderer that shows them yet) */
if (!named) named = 1, name_files();
if (ask < 1 || ask > SAVE_FILES || ask - 1 == files.current) return;
const int was = files.current;
files.current = ask - 1, files.chosen = (int64_t)time(NULL);
const int kept = files_save();
hos_log("save files: file %d, \"%s\", chosen: %s", ask, files.names[ask - 1], kept ? "the game starts again on it" : "it could not be kept, nothing changes");
files.current = was, files.chosen = 0; /* (this run plays the file it started on, to its end) */
rx_option_set(HOS_OPT_FILES_SAID, kept ? 1 : 2);
}

208
host/save_files.h Normal file
View File

@@ -0,0 +1,208 @@
/* (Triforce) Save files, as the Nintendo 64 game had them: a few files to choose from at the title, each a playthrough of
its own. host/save_files.c has what is the game folder's and the menu's. Nothing of the host is in here:
tests/test_save_files.py compiles it alone.
The game keeps all it saves under one folder (hos_user_dir: account.sav, option.sav and its slot_NN folders, the saves
and the autosaves of one playthrough), which it reads once, at its start, before its title shows. A file is such a
folder: file 1 the folder the game always had ("user"), file N that folder's name with "-N" after it ("user-2"). The
game is started on one of them and knows of no other; another file is another start (host/hos_relaunch.c).
triforce_files.txt in the game folder keeps which, and their names:
current=2 the file the next start plays (1 without the line, or with one that names none)
chosen=1763456789 when a file was chosen for a restart (unix time): the start that follows knows it is that restart
1=Spanky a file's name, SAVE_FILE_NAME bytes at most ("File 1" without the line) */
#ifndef HOS_SAVE_FILES_H
#define HOS_SAVE_FILES_H
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum { SAVE_FILES = 3, SAVE_FILE_NAME = 24, SAVE_FILES_CHOSEN_S = 180 /* (a restart is a few seconds; a start long after it asks again) */ };
typedef struct SaveFiles {
int current; /* 0 to SAVE_FILES - 1 */
int64_t chosen; /* unix time of the choice a restart follows, 0 none */
char names[SAVE_FILES][SAVE_FILE_NAME + 1];
} SaveFiles;
static inline void save_files_defaults(SaveFiles *f) {
memset(f, 0, sizeof *f);
for (int i = 0; i < SAVE_FILES; i++) snprintf(f->names[i], sizeof f->names[i], "File %d", i + 1);
}
/* triforce_files.txt's text read over the defaults. A line that is none of its three is passed over, a file's number that
is none and an empty name are not taken, a name is cut at SAVE_FILE_NAME bytes (never inside a letter) */
static inline void save_files_parse(SaveFiles *f, const char *text) {
save_files_defaults(f);
for (const char *line = text; *line; ) {
const char *end = line;
while (*end && *end != '\n') end++;
size_t n = (size_t)(end - line);
while (n && (line[n - 1] == '\r' || line[n - 1] == ' ' || line[n - 1] == '\t')) n--;
if (n > 8 && !memcmp(line, "current=", 8)) {
const long v = strtol(line + 8, NULL, 10);
if (v >= 1 && v <= SAVE_FILES) f->current = (int)v - 1;
} else if (n > 7 && !memcmp(line, "chosen=", 7)) {
const long long v = strtoll(line + 7, NULL, 10);
f->chosen = v > 0 ? v : 0;
} else if (n > 2 && line[0] >= '1' && line[0] < '1' + SAVE_FILES && line[1] == '=') {
size_t len = n - 2;
if (len > SAVE_FILE_NAME) {
len = SAVE_FILE_NAME;
while (len && ((unsigned char)line[2 + len] & 0xC0) == 0x80) len--;
}
int plain = len > 0;
for (size_t i = 0; i < len; i++) plain &= (unsigned char)line[2 + i] >= 32;
if (plain) memcpy(f->names[line[0] - '1'], line + 2, len), f->names[line[0] - '1'][len] = 0;
}
line = *end ? end + 1 : end;
}
}
/* triforce_files.txt's text written into out: its length, 0 when cap is too small for it */
static inline size_t save_files_write(const SaveFiles *f, char *out, size_t cap) {
int n = snprintf(out, cap, "# The save files (the title's file select): the one the next start plays, and their names.\ncurrent=%d\n", f->current + 1);
if (n < 0 || (size_t)n >= cap) return 0;
size_t at = (size_t)n;
if (f->chosen > 0) {
n = snprintf(out + at, cap - at, "chosen=%lld\n", (long long)f->chosen);
if (n < 0 || (size_t)n >= cap - at) return 0;
at += (size_t)n;
}
for (int i = 0; i < SAVE_FILES; i++) {
n = snprintf(out + at, cap - at, "%d=%s\n", i + 1, f->names[i]);
if (n < 0 || (size_t)n >= cap - at) return 0;
at += (size_t)n;
}
return at;
}
/* A file's folder: file 0 the folder the game always had (base), file N - 1 that name with "-N" after it. 1 when it fits */
static inline int save_files_folder(const char *base, int file, char *out, size_t cap) {
if (file < 0 || file >= SAVE_FILES) return 0;
size_t n = strlen(base);
while (n > 1 && (base[n - 1] == '/' || base[n - 1] == '\\')) n--; /* ("user\" and "user": the same folder) */
const int len = file ? snprintf(out, cap, "%.*s-%d", (int)n, base, file + 1) : snprintf(out, cap, "%.*s", (int)n, base);
return len > 0 && (size_t)len < cap;
}
/* 1 when this start follows a file's choice (now: unix time): the restart the choice asked for */
static inline int save_files_chosen_now(const SaveFiles *f, int64_t now) {
return f->chosen > 0 && now >= f->chosen && now - f->chosen <= SAVE_FILES_CHOSEN_S;
}
/* ---- A file's card on the file select: what the game's own load list shows of a save, kept by the host as it is played ----
The game shows a save's place, hearts, Spiritual Stones and medallions from the save's own data, whose form this
repository does not know and does not read. The same is known while the game runs: host/hos_main.c tells it as the file is
played (hos_save_card_note), and it is kept in the file's folder, triforce_card.txt:
place=Kokiri Forest where Link was (the map's own name, its words set apart)
items=1c9 SAVE_CARD_* bits, hex: the stones and medallions he holds
hearts=7 his heart containers, 0 when they are not known
slot=3 the slot the game saved in last while this file was played (host/nn_fs.c tells: a slot's file
saved=1763456789 opened to be written), and when (unix time): the save whose picture and time the card shows.
The slots' files cannot tell: the game writes them all again when it saves one */
enum { SAVE_CARD_PLACE = 48,
SAVE_CARD_STONES = 3, /* bits 0 to 2: the Spiritual Stones of the forest, of fire, of water */
SAVE_CARD_MEDALS = 6, /* bits 3 to 8: the medallions of light, forest, fire, water, spirit, shadow */
SAVE_CARD_ITEMS = SAVE_CARD_STONES + SAVE_CARD_MEDALS, SAVE_CARD_HEARTS = 20 };
typedef struct SaveCard {
char place[SAVE_CARD_PLACE + 1];
int items, hearts;
int slot1; /* the slot saved in last, and 1; 0 not known */
int64_t saved; /* when, unix time; 0 not known */
} SaveCard;
/* The slot a guest path of the save names ("save:/slot_03/caption.sav": 3), -1 when it names none of slot_00 to slot_11 */
static inline int save_card_slot_of(const char *guest) {
const char *s = guest ? strstr(guest, "slot_") : NULL;
if (!s || s[5] < '0' || s[5] > '9' || s[6] < '0' || s[6] > '9' || (s[7] != '/' && s[7] != '\\')) return -1;
const int slot = (s[5] - '0') * 10 + (s[6] - '0');
return slot < 12 ? slot : -1;
}
/* (a map that is another in each of Link's ages says which at its name's end: the game's own load list does not) */
static inline void save_card_trim_age(char *place) {
const size_t n = strlen(place);
if (n > 6 && (!strcmp(place + n - 6, " Adult") || !strcmp(place + n - 6, " Child"))) place[n - 6] = 0;
}
/* A map's own name as a card shows it: "KokiriForest" is "Kokiri Forest", "Inside_GanonCastle01" "Inside Ganon Castle 01",
"DekuTree_B1F" "Deku Tree B1F". A space before a capital that follows a small letter (or a digit, when it begins a word),
and before a digit that follows a small letter; '_' a space */
static inline void save_card_place(const char *map, char *out, size_t cap) {
size_t n = 0;
for (const char *p = map; *p && n + 2 < cap; p++) {
const unsigned char ch = (unsigned char)*p, before = p > map ? (unsigned char)p[-1] : 0;
const int upper = ch >= 'A' && ch <= 'Z', digit = ch >= '0' && ch <= '9';
const int was_lower = before >= 'a' && before <= 'z', was_digit = before >= '0' && before <= '9';
if (ch == '_' || ch < 32) {
if (n && out[n - 1] != ' ') out[n++] = ' ';
continue;
}
const int word = p[1] >= 'a' && p[1] <= 'z'; /* (a capital that begins a word, not one of a floor's name: B1F) */
if (n && out[n - 1] != ' ' && ((upper && (was_lower || (was_digit && word))) || (digit && was_lower))) out[n++] = ' ';
out[n++] = (char)ch;
}
while (n && out[n - 1] == ' ') n--;
if (cap) out[n] = 0, save_card_trim_age(out);
}
/* Heart containers from the game's own count of Link's life, which it keeps in quarters of a heart: 0 when the number is
not one (not whole hearts, under the three every game starts with, or over SAVE_CARD_HEARTS) */
static inline int save_card_hearts(int life) { return life >= 12 && life <= 4 * SAVE_CARD_HEARTS && life % 4 == 0 ? life / 4 : 0; }
/* triforce_card.txt's text read: what is not one of its lines is passed over, a number that is none is 0 */
static inline void save_card_parse(SaveCard *c, const char *text) {
memset(c, 0, sizeof *c);
for (const char *line = text; *line; ) {
const char *end = line;
while (*end && *end != '\n') end++;
size_t n = (size_t)(end - line);
while (n && (line[n - 1] == '\r' || line[n - 1] == ' ')) n--;
if (n > 6 && !memcmp(line, "place=", 6)) {
size_t len = n - 6 > SAVE_CARD_PLACE ? SAVE_CARD_PLACE : n - 6;
while (len && ((unsigned char)line[6 + len] & 0xC0) == 0x80) len--;
memcpy(c->place, line + 6, len), c->place[len] = 0;
for (size_t i = 0; i < len; i++)
if ((unsigned char)c->place[i] < 32 || c->place[i] == '|') c->place[i] = ' ';
save_card_trim_age(c->place); /* (a card kept before the age was left out) */
} else if (n > 6 && !memcmp(line, "items=", 6)) {
c->items = (int)(strtoul(line + 6, NULL, 16) & ((1u << SAVE_CARD_ITEMS) - 1));
} else if (n > 7 && !memcmp(line, "hearts=", 7)) {
const long v = strtol(line + 7, NULL, 10);
c->hearts = v >= 1 && v <= SAVE_CARD_HEARTS ? (int)v : 0;
} else if (n > 5 && !memcmp(line, "slot=", 5)) {
const long v = line[5] >= '0' && line[5] <= '9' ? strtol(line + 5, NULL, 10) : -1;
c->slot1 = v >= 0 && v < 12 ? (int)v + 1 : 0;
} else if (n > 6 && !memcmp(line, "saved=", 6)) {
const long long v = strtoll(line + 6, NULL, 10);
c->saved = v > 0 ? v : 0;
}
line = *end ? end + 1 : end;
}
}
/* triforce_card.txt's text written into out: its length, 0 when cap is too small for it */
static inline size_t save_card_write(const SaveCard *c, char *out, size_t cap) {
int n = snprintf(out, cap, "# What the file select shows of this save file: where it was played last, the stones and medallions held, the hearts,\n"
"# and the slot the game saved in last.\nplace=%s\nitems=%x\nhearts=%d\n", c->place, (unsigned)c->items, c->hearts);
if (n <= 0 || (size_t)n >= cap) return 0;
if (c->slot1) {
const int more = snprintf(out + n, cap - (size_t)n, "slot=%d\nsaved=%lld\n", c->slot1 - 1, (long long)c->saved);
if (more <= 0 || (size_t)more >= cap - (size_t)n) return 0;
n += more;
}
return (size_t)n;
}
static inline int save_card_same(const SaveCard *a, const SaveCard *b) {
return !strcmp(a->place, b->place) && a->items == b->items && a->hearts == b->hearts && a->slot1 == b->slot1 && a->saved == b->saved;
}
/* host/save_files.c */
void hos_save_card_note(const char *map, int items, int life, int64_t now_ns);
void hos_save_card_wrote(const char *guest_path);
int hos_save_files_on(void);
const char *hos_save_files_dir(int *first);
const char *hos_save_files_start(const char *game_dir, const char *base_user);
void hos_save_files_frame(void);
#endif

View File

@@ -30,6 +30,7 @@
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#define SAVE_TX_BACKUPS 5
#define SAVE_TX_BACKUP_GAP_S 300
@@ -50,6 +51,26 @@ static int tx_crashed(void) {
return save_tx_dead;
}
static time_t tx_now(void) { return save_tx_test_now ? save_tx_test_now : time(NULL); }
/* ((Triforce, 11-23, ticket "Cannot launch into game after 0.7 update", Linux) The first thing a mount's working copy could not
do, said in the mount's note: the log only said "no working copy could be made", never which file or why. Called right
after the call that failed (its error: GetLastError on Windows, errno's text elsewhere) */
static char save_tx_why[HOS_FS_PATH + 128];
static void tx_why(const char *what, const char *path) {
if (save_tx_why[0]) return;
#ifdef _WIN32
const unsigned long e = (unsigned long)GetLastError();
snprintf(save_tx_why, sizeof save_tx_why, "%s %s (error %lu)", what, path, e);
#else
const int e = errno;
snprintf(save_tx_why, sizeof save_tx_why, "%s %s (%s)", what, path, strerror(e));
#endif
}
static void tx_note_add(char *note, size_t cap, const char *what) { /* (after a recovery's note, when there is one) */
if (!note || !cap) return;
const size_t n = strlen(note);
if (n + 1 < cap) snprintf(note + n, cap - n, "%s%s", n ? "; " : "", what);
}
static int tx_exists(const char *p) { return GetFileAttributesA(p) != INVALID_FILE_ATTRIBUTES; }
static int tx_is_dir(const char *p) {
const DWORD a = GetFileAttributesA(p);
@@ -107,9 +128,13 @@ static int tx_empty(const char *dir) { /* 1: a folder with nothing in it */
static int tx_copy_file(const char *src, const char *dst, int flush) {
HANDLE in = CreateFileA(src, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
if (in == INVALID_HANDLE_VALUE) return 0;
if (in == INVALID_HANDLE_VALUE) {
tx_why("cannot open", src);
return 0;
}
HANDLE out = CreateFileA(dst, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (out == INVALID_HANDLE_VALUE) {
tx_why("cannot make", dst);
CloseHandle(in);
return 0;
}
@@ -118,12 +143,12 @@ static int tx_copy_file(const char *src, const char *dst, int flush) {
int ok = buf != NULL;
while (ok) {
DWORD got = 0, put = 0;
if (!ReadFile(in, buf, chunk, &got, NULL)) ok = 0;
if (!ReadFile(in, buf, chunk, &got, NULL)) ok = 0, tx_why("cannot read", src);
else if (!got) break;
else if (!WriteFile(out, buf, got, &put, NULL) || put != got) ok = 0;
else if (!WriteFile(out, buf, got, &put, NULL) || put != got) ok = 0, tx_why("cannot write", dst);
}
free(buf);
if (ok && flush && !FlushFileBuffers(out)) ok = 0;
if (ok && flush && !FlushFileBuffers(out)) ok = 0, tx_why("cannot write out", dst);
CloseHandle(out);
CloseHandle(in);
return ok;
@@ -132,7 +157,10 @@ static int tx_copy_file(const char *src, const char *dst, int flush) {
/* A folder with everything in it, links left out; dst is made. 1: every file copied */
static int tx_copy_tree(const char *src, const char *dst, int flush) {
tx_make_dirs(dst);
if (!tx_is_dir(dst)) return 0;
if (!tx_is_dir(dst)) {
tx_why("cannot make the folder", dst);
return 0;
}
char pat[HOS_FS_PATH];
WIN32_FIND_DATAA fd;
snprintf(pat, sizeof pat, "%s\\*", src);
@@ -144,7 +172,7 @@ static int tx_copy_tree(const char *src, const char *dst, int flush) {
if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) continue;
char a[HOS_FS_PATH], b[HOS_FS_PATH];
if (snprintf(a, sizeof a, "%s\\%s", src, fd.cFileName) >= (int)sizeof a ||
snprintf(b, sizeof b, "%s\\%s", dst, fd.cFileName) >= (int)sizeof b) { ok = 0; continue; }
snprintf(b, sizeof b, "%s\\%s", dst, fd.cFileName) >= (int)sizeof b) { ok = 0; tx_why("a path too long under", src); continue; }
if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ok &= tx_copy_tree(a, b, flush);
else ok &= tx_copy_file(a, b, flush);
} while (FindNextFileA(f, &fd));
@@ -350,19 +378,34 @@ static int save_tx_mount(const SaveTxPaths *p, char *note, size_t cap) {
}
if (tx_crashed()) return 0;
tx_old_away(p, 1, NULL, 0);
save_tx_why[0] = 0;
char why[HOS_FS_PATH + 256];
tx_delete_tree(p->work);
if (tx_exists(p->work)) return 0; /* (a file of it is held open: no second run of the game beside this one's files) */
if (tx_exists(p->work)) { /* (a file of it is held open: no second run of the game beside this one's files) */
tx_why("cannot delete", p->work);
snprintf(why, sizeof why, "the working copy from before could not be deleted: %s", save_tx_why);
tx_note_add(note, cap, why);
return 0;
}
/* (the newest save: a finished commit still waiting, else the committed one) */
const unsigned left = tx_ready_highest(p, ready, sizeof ready);
const char *from = left ? ready : p->save;
if (tx_is_dir(from)) {
if (!tx_copy_tree(from, p->work, 0)) {
snprintf(why, sizeof why, "the save could not be copied to its working copy: %s", save_tx_why[0] ? save_tx_why : "?");
tx_note_add(note, cap, why);
tx_delete_tree(p->work);
return 0;
}
} else tx_make_dirs(p->work);
tx_make_dirs(p->save); /* (the save "exists" from its first mount on, as before: IsSaveDataExisting) */
return tx_is_dir(p->work);
if (!tx_is_dir(p->work)) {
tx_why("cannot make the folder", p->work);
snprintf(why, sizeof why, "the working copy could not be made: %s", save_tx_why);
tx_note_add(note, cap, why);
return 0;
}
return 1;
}
/* Every file of a folder written out to the disk (FlushFileBuffers). 1: all of them */