Merge remote-tracking branch 'origin/dev' into distant-detail-merge

# Conflicts:
#	recomp/patches-v121.txt
#	recomp/patches-v143.txt
#	runtime/cfg.c
#	runtime/ui/menu.cpp
#	totk.ini.example
This commit is contained in:
ProSep committed 2026-11-04 00:08:28 +01:00
commit 4403a3f8ea
186 files changed
+20879 -1287

No files matched your search

+400
View File
@@ -0,0 +1,400 @@
// Amiibo dump loader and Horizon OS NFP state emulation.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "amiibo.h"
#include "host.h"
#include "platform/platform.h"
static PlatMutex g_amiibo_lock = PLAT_MUTEX_INIT;
// 540-byte raw NTAG215 binary dump
static uint8_t g_dump[AMIIBO_DUMP_SIZE];
static bool g_has_dump = false;
static AmiiboInfo g_info;
static bool g_device_present = true;
static bool g_detecting = false;
static bool g_tag_present = false;
static bool g_mounted = false;
static bool g_auto_remove = true;
static float g_auto_remove_delay_s = 2.5f;
static uint64_t g_tap_timestamp_ns = 0;
static bool g_timer_active = false;
static bool amiibo_validate_dump(const uint8_t *data, uint64_t size) {
if (size != AMIIBO_DUMP_SIZE) {
return false;
}
// NTAG215 Capability Container (CC) at page 3 (offset 0x0C). An amiibo's is F1 10 FF EE, not the E1 of a plain
// NDEF tag (3dbrew, "Amiibo"); the CC is not encrypted, so encrypted dumps carry it too.
static const uint8_t amiibo_cc[4] = {0xF1, 0x10, 0xFF, 0xEE};
if (memcmp(data + 0x0C, amiibo_cc, sizeof amiibo_cc)) {
return false;
}
// UID sanity: UID (bytes 0..2 and 4..7) cannot be all zeroes or all 0xFF.
if ((data[0] == 0 && data[1] == 0 && data[2] == 0 && data[4] == 0 &&
data[5] == 0 && data[6] == 0 && data[7] == 0) ||
(data[0] == 0xFF && data[1] == 0xFF && data[2] == 0xFF && data[4] == 0xFF &&
data[5] == 0xFF && data[6] == 0xFF && data[7] == 0xFF)) {
return false;
}
// ISO 14443-3 / NTAG215 Bit Check Character (BCC) verification.
// Page 0 byte 3 (BCC0) = 0x88 ^ UID[0] ^ UID[1] ^ UID[2]
// Page 2 byte 0 (BCC1) = UID[3] ^ UID[4] ^ UID[5] ^ UID[6]
uint8_t bcc0 = (uint8_t)(0x88 ^ data[0] ^ data[1] ^ data[2]);
uint8_t bcc1 = (uint8_t)(data[4] ^ data[5] ^ data[6] ^ data[7]);
if (data[3] != bcc0 || data[8] != bcc1) {
return false;
}
return true;
}
// The 7-byte UID of an NTAG215 dump: bytes 0..2, then 4..7. Byte 3 is the check byte BCC0.
static void copy_uid(uint8_t out[7], const uint8_t *dump) {
memcpy(out, dump, 3);
memcpy(out + 3, dump + 4, 4);
}
static void parse_dump_info(const char *path) {
memset(&g_info, 0, sizeof(g_info));
if (path) {
snprintf(g_info.path, sizeof(g_info.path), "%s", path);
const char *slash = strrchr(path, '\\');
const char *fslash = strrchr(path, '/');
const char *name = slash ? slash + 1 : (fslash ? fslash + 1 : path);
if (slash && fslash) {
name = (slash > fslash ? slash : fslash) + 1;
}
snprintf(g_info.filename, sizeof(g_info.filename), "%s", name);
}
copy_uid(g_info.uuid, g_dump);
g_info.uuid_len = 7;
// Amiibo ID at offset 0x54 (8 bytes, 3dbrew "Amiibo"): character ID and variant, figure type, model number
// (big-endian), series, format version 02
memcpy(g_info.character_id, g_dump + 0x54, 3);
g_info.nfp_type = g_dump[0x57];
g_info.numbering_id = ((uint16_t)g_dump[0x58] << 8) | g_dump[0x59];
g_info.series_id = g_dump[0x5A];
g_info.version = g_dump[0x5B];
}
void amiibo_init(void) {
plat_mutex_lock(&g_amiibo_lock);
g_device_present = true;
g_detecting = false;
g_tag_present = false;
g_mounted = false;
g_has_dump = false;
g_timer_active = false;
memset(g_dump, 0, sizeof(g_dump));
memset(&g_info, 0, sizeof(g_info));
plat_mutex_unlock(&g_amiibo_lock);
}
void amiibo_set_device_present(bool present) {
plat_mutex_lock(&g_amiibo_lock);
g_device_present = present;
plat_mutex_unlock(&g_amiibo_lock);
}
bool amiibo_is_device_present(void) {
plat_mutex_lock(&g_amiibo_lock);
bool res = g_device_present;
plat_mutex_unlock(&g_amiibo_lock);
return res;
}
// While the game waits for a tag it stops and starts detection again several times a second (tens with the menu open),
// so the log names the first few and then a count every 200th start.
static uint64_t g_detect_starts;
static uint64_t g_detect_stop_ns; // the last stop: the menu holds "searching" across the game's restarts
void amiibo_start_detection(void) {
plat_mutex_lock(&g_amiibo_lock);
g_detecting = true;
uint64_t n = ++g_detect_starts;
if (n <= 3) rt_log("amiibo: start detection");
else if (n % 200 == 0) rt_log("amiibo: detection started %llu times so far", (unsigned long long)n);
plat_mutex_unlock(&g_amiibo_lock);
}
void amiibo_stop_detection(void) {
plat_mutex_lock(&g_amiibo_lock);
if (g_detecting) g_detect_stop_ns = plat_now_ns();
g_detecting = false;
if (g_detect_starts <= 3) rt_log("amiibo: stop detection");
plat_mutex_unlock(&g_amiibo_lock);
}
bool amiibo_is_detecting(void) {
plat_mutex_lock(&g_amiibo_lock);
bool res = g_detecting;
plat_mutex_unlock(&g_amiibo_lock);
return res;
}
bool amiibo_mount(void) {
plat_mutex_lock(&g_amiibo_lock);
if (!g_device_present || !g_tag_present) {
plat_mutex_unlock(&g_amiibo_lock);
return false;
}
g_mounted = true;
rt_log("amiibo: mounted tag '%s'", g_info.filename[0] ? g_info.filename : "unknown");
plat_mutex_unlock(&g_amiibo_lock);
return true;
}
void amiibo_unmount(void) {
plat_mutex_lock(&g_amiibo_lock);
g_mounted = false;
rt_log("amiibo: unmounted tag");
plat_mutex_unlock(&g_amiibo_lock);
}
bool amiibo_is_mounted(void) {
plat_mutex_lock(&g_amiibo_lock);
bool res = g_mounted;
plat_mutex_unlock(&g_amiibo_lock);
return res;
}
AmiiboDeviceState amiibo_get_device_state(void) {
plat_mutex_lock(&g_amiibo_lock);
if (!g_device_present) {
plat_mutex_unlock(&g_amiibo_lock);
return AMIIBO_DEV_STATE_UNAVAILABLE;
}
if (g_mounted) {
plat_mutex_unlock(&g_amiibo_lock);
return AMIIBO_DEV_STATE_TAG_MOUNTED;
}
if (g_tag_present) {
plat_mutex_unlock(&g_amiibo_lock);
return AMIIBO_DEV_STATE_TAG_FOUND;
}
if (g_detecting) {
plat_mutex_unlock(&g_amiibo_lock);
return AMIIBO_DEV_STATE_SEARCHING;
}
plat_mutex_unlock(&g_amiibo_lock);
return AMIIBO_DEV_STATE_INITIALIZED;
}
AmiiboDeviceState amiibo_get_reader_state(void) {
AmiiboDeviceState state = amiibo_get_device_state();
if (state != AMIIBO_DEV_STATE_INITIALIZED) return state;
plat_mutex_lock(&g_amiibo_lock);
bool recent = g_detect_stop_ns && plat_now_ns() - g_detect_stop_ns < 1000000000ull;
plat_mutex_unlock(&g_amiibo_lock);
return recent ? AMIIBO_DEV_STATE_SEARCHING : state;
}
bool amiibo_load_file(const char *path) {
if (!path || !*path) return false;
uint64_t size = 0;
uint8_t *data = plat_file_read(path, &size);
if (!data) {
rt_log("amiibo: failed to read file: %s", path);
return false;
}
if (size != AMIIBO_DUMP_SIZE) {
rt_log("amiibo: invalid dump size (%llu bytes, expected exactly %d): %s",
(unsigned long long)size, AMIIBO_DUMP_SIZE, path);
free(data);
return false;
}
if (!amiibo_validate_dump(data, size)) {
rt_log("amiibo: dump failed NTAG215 structure sanity checks: %s", path);
free(data);
return false;
}
plat_mutex_lock(&g_amiibo_lock);
memcpy(g_dump, data, AMIIBO_DUMP_SIZE);
g_has_dump = true;
parse_dump_info(path);
plat_mutex_unlock(&g_amiibo_lock);
free(data);
rt_log("amiibo: loaded dump '%s' (char_id: %02x%02x%02x, series: %02x, num: %04x)",
g_info.filename, g_info.character_id[0], g_info.character_id[1], g_info.character_id[2],
g_info.series_id, g_info.numbering_id);
return true;
}
void amiibo_tap_tag(void) {
plat_mutex_lock(&g_amiibo_lock);
if (!g_has_dump) {
plat_mutex_unlock(&g_amiibo_lock);
return;
}
g_tag_present = true;
g_tap_timestamp_ns = plat_now_ns();
if (g_auto_remove) {
g_timer_active = true;
}
rt_log("amiibo: tag tapped on reader ('%s')", g_info.filename);
plat_mutex_unlock(&g_amiibo_lock);
}
bool amiibo_scan_and_tap(const char *path) {
if (!amiibo_load_file(path)) return false;
amiibo_tap_tag();
return true;
}
void amiibo_remove_tag(void) {
plat_mutex_lock(&g_amiibo_lock);
if (g_tag_present || g_mounted) {
g_tag_present = false;
g_mounted = false;
g_timer_active = false;
rt_log("amiibo: tag removed from reader");
}
plat_mutex_unlock(&g_amiibo_lock);
}
void amiibo_tick(void) {
plat_mutex_lock(&g_amiibo_lock);
if (g_timer_active && g_tag_present) {
uint64_t now = plat_now_ns();
uint64_t diff = now > g_tap_timestamp_ns ? now - g_tap_timestamp_ns : 0;
uint64_t limit_ns = (uint64_t)(g_auto_remove_delay_s * 1000000000.0f);
if (diff >= limit_ns) {
g_tag_present = false;
g_mounted = false;
g_timer_active = false;
rt_log("amiibo: auto-removed tag after %.1fs timeout", (double)g_auto_remove_delay_s);
}
}
plat_mutex_unlock(&g_amiibo_lock);
}
void amiibo_set_auto_remove(bool enable) {
plat_mutex_lock(&g_amiibo_lock);
g_auto_remove = enable;
if (!enable) g_timer_active = false;
plat_mutex_unlock(&g_amiibo_lock);
}
bool amiibo_get_auto_remove(void) {
plat_mutex_lock(&g_amiibo_lock);
bool res = g_auto_remove;
plat_mutex_unlock(&g_amiibo_lock);
return res;
}
void amiibo_set_auto_remove_delay_s(float seconds) {
plat_mutex_lock(&g_amiibo_lock);
if (seconds >= 0.5f && seconds <= 10.0f) g_auto_remove_delay_s = seconds;
plat_mutex_unlock(&g_amiibo_lock);
}
float amiibo_get_auto_remove_delay_s(void) {
plat_mutex_lock(&g_amiibo_lock);
float res = g_auto_remove_delay_s;
plat_mutex_unlock(&g_amiibo_lock);
return res;
}
bool amiibo_has_tag(void) {
plat_mutex_lock(&g_amiibo_lock);
bool res = g_has_dump && g_tag_present;
plat_mutex_unlock(&g_amiibo_lock);
return res;
}
const AmiiboInfo *amiibo_get_current_info(void) {
return &g_info;
}
const uint8_t *amiibo_get_raw_data(void) {
return g_dump;
}
void amiibo_get_tag_info(void *out_tag_info) {
plat_mutex_lock(&g_amiibo_lock);
uint8_t *out = (uint8_t *)out_tag_info;
memset(out, 0, 0x58);
// UUID: offset 0x00, 10 bytes max
copy_uid(out, g_dump);
out[0x0A] = 7; // UUID length
// Protocol at offset 0x20: TypeA = 1
*(uint32_t *)(out + 0x20) = 1;
// TagType at offset 0x24: Type2 / NTAG215 = 2
*(uint32_t *)(out + 0x24) = 2;
plat_mutex_unlock(&g_amiibo_lock);
}
void amiibo_get_model_info(void *out_model_info) {
plat_mutex_lock(&g_amiibo_lock);
uint8_t *out = (uint8_t *)out_model_info;
memset(out, 0, 0x40);
// nn::nfp::ModelInfo from the amiibo ID at 0x54: character ID and variant in the tag's byte order, series, model
// number little-endian (big-endian on the tag), figure type. The game tells figures of one character apart by the
// model number.
memcpy(out + 0x00, g_dump + 0x54, 3); // character ID, variant
out[0x03] = g_dump[0x5A]; // series
out[0x04] = g_dump[0x59]; // model number
out[0x05] = g_dump[0x58];
out[0x06] = g_dump[0x57]; // figure type
plat_mutex_unlock(&g_amiibo_lock);
}
void amiibo_get_common_info(void *out_common_info) {
plat_mutex_lock(&g_amiibo_lock);
uint8_t *out = (uint8_t *)out_common_info;
memset(out, 0, 0x40);
// Last write date: 0x00..0x03
out[0x00] = 0xE7; out[0x01] = 0x07; // 2023, u16 little-endian
out[0x02] = 0x05; out[0x03] = 0x0C; // May 12
// Write counter: 0x04..0x05
out[0x04] = 0x00; out[0x05] = 0x01;
// Version: 0x06
out[0x06] = 0x02;
// Application area size: 0x08..0x0B = 0xD8 (216 bytes)
*(uint32_t *)(out + 0x08) = 0xD8;
plat_mutex_unlock(&g_amiibo_lock);
}
void amiibo_get_register_info(void *out_register_info) {
plat_mutex_lock(&g_amiibo_lock);
uint8_t *out = (uint8_t *)out_register_info;
memset(out, 0, 0x100);
// Mii CharInfo at 0x00..0x57 (dummy valid mii)
out[0x00] = 0x03; // version 3
// First write date at 0x58..0x5B
out[0x58] = 0xE7; out[0x59] = 0x07; // 2023, u16 little-endian
out[0x5A] = 0x05; out[0x5B] = 0x0C;
// Amiibo Name at 0x5C: copy up to 40 bytes NUL-terminated
const char *name = g_info.filename[0] ? g_info.filename : "Amiibo";
snprintf((char *)(out + 0x5C), 0x29, "%s", name);
plat_mutex_unlock(&g_amiibo_lock);
}
int amiibo_get_application_area(void *out_buf, uint32_t max_size) {
plat_mutex_lock(&g_amiibo_lock);
if (!g_has_dump || !out_buf) {
plat_mutex_unlock(&g_amiibo_lock);
return 0;
}
uint32_t to_copy = max_size < 0xD8 ? max_size : 0xD8;
// Decrypted/payload application area starts at offset 0xDC (or 0x0A0..0x178 in raw dump)
if (0xDC + to_copy <= AMIIBO_DUMP_SIZE) {
memcpy(out_buf, g_dump + 0xDC, to_copy);
} else {
memset(out_buf, 0, to_copy);
}
plat_mutex_unlock(&g_amiibo_lock);
return (int)to_copy;
}
+87
View File
@@ -0,0 +1,87 @@
// Amiibo loader and state management subsystem (540-byte NTAG215 binary dumps).
#pragma once
#include <stdbool.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define AMIIBO_DUMP_SIZE 540
// Device state corresponding to nn::nfp / nn::nfc DeviceState
typedef enum {
AMIIBO_DEV_STATE_INITIALIZED = 0,
AMIIBO_DEV_STATE_SEARCHING = 1,
AMIIBO_DEV_STATE_TAG_FOUND = 2,
AMIIBO_DEV_STATE_TAG_REMOVED = 3,
AMIIBO_DEV_STATE_TAG_MOUNTED = 4,
AMIIBO_DEV_STATE_UNAVAILABLE = 5
} AmiiboDeviceState;
// Amiibo identification info
typedef struct {
uint8_t uuid[10];
uint8_t uuid_len;
uint8_t character_id[3];
uint8_t series_id;
uint16_t numbering_id;
uint8_t nfp_type;
uint8_t version;
char path[512];
char filename[128];
} AmiiboInfo;
// Subsystem lifecycle
void amiibo_init(void);
// Hardware / device emulation status
void amiibo_set_device_present(bool present);
bool amiibo_is_device_present(void);
// Tag detection & lifecycle
void amiibo_start_detection(void);
void amiibo_stop_detection(void);
bool amiibo_is_detecting(void);
// Tag mounting
bool amiibo_mount(void);
void amiibo_unmount(void);
bool amiibo_is_mounted(void);
// State query
AmiiboDeviceState amiibo_get_device_state(void);
// The state the menu shows: searching also within a second after a stop, since the game restarts detection many times
// a second while it waits for a tag. The game reads amiibo_get_device_state.
AmiiboDeviceState amiibo_get_reader_state(void);
// File loading & triggering actions
bool amiibo_load_file(const char *path);
bool amiibo_scan_and_tap(const char *path);
void amiibo_tap_tag(void);
void amiibo_remove_tag(void);
// Timer tick called during menu / frame updates
void amiibo_tick(void);
// Options
void amiibo_set_auto_remove(bool enable);
bool amiibo_get_auto_remove(void);
void amiibo_set_auto_remove_delay_s(float seconds);
float amiibo_get_auto_remove_delay_s(void);
// Tag inspection
bool amiibo_has_tag(void);
const AmiiboInfo *amiibo_get_current_info(void);
const uint8_t *amiibo_get_raw_data(void);
// Horizon OS buffers extraction (called by NFP IPC/override services)
void amiibo_get_tag_info(void *out_tag_info);
void amiibo_get_model_info(void *out_model_info);
void amiibo_get_common_info(void *out_common_info);
void amiibo_get_register_info(void *out_register_info);
int amiibo_get_application_area(void *out_buf, uint32_t max_size);
#ifdef __cplusplus
}
#endif
+7 -4
View File
@@ -22,8 +22,11 @@ struct AudioEffectDsp {
};
static int channel_ok(unsigned n) { return n==1 || n==2 || n==4 || n==6; }
static unsigned sample_count(unsigned rate, float ms) { return (unsigned)nearbyintf(rate*ms); }
/* The reference DelayLine wraps at CurrentSampleCount-1, including when its
backing allocation is larger. Preserve this timing for sample comparisons. */
/* The ring has `count` slots. The reference DelayLine wraps its cursor at
CurrentSampleCount-1 while its taps index modulo CurrentSampleCount, so once
per turn every tap reads a slot that is never written (a one-sample dropout
per tap, audible as grain). The cursor and the taps share one ring length here;
each delay is one sample longer than the reference. */
static void line_set(DelayLine *d, unsigned n) { d->count=n<d->max?n:d->max; d->at=0; }
static void line_init(DelayLine *d, unsigned rate, float ms) {
d->max=sample_count(rate,ms); d->data=calloc((size_t)d->max+1,sizeof(float));
@@ -32,12 +35,12 @@ static void line_init(DelayLine *d, unsigned rate, float ms) {
static float line_read(const DelayLine *d) { return d->data[d->at]; }
static float line_update(DelayLine *d,float v) {
float old=line_read(d);d->data[d->at++]=v;
if(d->at >= (d->count?d->count-1:0))d->at=0;
if(d->at >= d->count)d->at=0;
return old;
}
static float line_tap(const DelayLine *d,unsigned sample,int offset) {
int at=(int)d->at-(int)sample-offset;
if(at<0)at+=(int)d->count;
if(d->count){at%=(int)d->count;if(at<0)at+=(int)d->count;}
if(at<0 || (unsigned)at>d->max)rt_fatal("audio effect delay tap bounds");
return d->data[at];
}
+144 -46
View File
@@ -5,10 +5,11 @@
//
// Per 5 ms frame the render thread (audren.c, renderer lock held) decodes every started voice (PCM8/16/24/32, float,
// DSP-ADPCM) along the sample path the voice clock consumes, resamples it linearly, runs the voice biquads, scales it
// into its destination mix, folds the submixes, runs the mix effects and writes the device sink's stereo mix into a
// single-producer single-consumer ring. The SDL audio thread drains that ring without taking any lock: an empty ring
// into its destination mix, folds the submixes, runs the mix effects and writes the device sink's mix (stereo, or 5.1
// with TOTK_AUDIO_CHANNELS, output_channels) into a single-producer single-consumer ring. The SDL audio thread drains
// that ring without taking any lock: an empty ring
// plays silence and never blocks the render thread or the guest. TOTK_AUDIO=none (or TOTK_AUDIO_OFF) mixes without a
// device; TOTK_AUDIO_PREFILL_MS (0..500, default 20) is the queued audio the output waits for after start or underrun.
// device; TOTK_AUDIO_PREFILL_MS (0..500, default 20, 60 on Linux) is the queued audio the output waits for after start or underrun.
// The device's clock paces the render thread, as the audio hardware paces the Switch's DSP (audio_mixer_pace_ns): a
// frame is rendered when the ring holds less than the output target, max(prefill, two device periods), so the queue and
// the delay from the game to the speakers stay there and the host and device clocks cannot drift apart. LASRecomp and
@@ -32,7 +33,8 @@
#include "ipc.h"
#define MAX_FRAME 1024
#define RING_FRAMES 16384 // stereo frames, about 340 ms at 48 kHz
#define RING_FRAMES 16384 // output frames, about 340 ms at 48 kHz
#define OUT_MAX 6 // output channels at most: 5.1
#define QUEUE_SLACK_MS 40 // queued audio above the target plus the device's request that ring_pull skips
#define STALL_MS 50 // the device took nothing this long (at least 4 periods): the timer paces
#define SPLITTER_UNUSED 0xffffffffu
@@ -51,7 +53,8 @@ typedef struct Mixer {
int *offset; // first mix buffer of each mix id
SplitInfo *split; int nsplit; SplitDest *dest; int ndest;
SDL_AudioStream *stream; int device_ok, rate;
float ring[RING_FRAMES * 2];
int channels; // output channels, 2 or 6 (output_channels)
float ring[RING_FRAMES * OUT_MAX];
_Atomic uint64_t wr, rd, underruns, overruns, missing_frames, callback_frames, callback_nonzero, skipped_frames;
_Atomic int playing; int ready; // ready: the callback's own state
int target, period; // output target and device period, frames (output_open)
@@ -61,7 +64,7 @@ typedef struct Mixer {
EffectState *effect; int *effect_order; unsigned effect_reported;
uint64_t *sink_address; uint32_t *sink_size, *sink_offset, *sink_old, *sink_written;
unsigned reported; // one-time reports
float voice_scratch[6][MAX_FRAME], filter_scratch[MAX_FRAME], output_scratch[MAX_FRAME * 2];
float voice_scratch[6][MAX_FRAME], filter_scratch[MAX_FRAME], output_scratch[MAX_FRAME * OUT_MAX];
double level_sum, level_peak; uint64_t level_count, level_frames; int first_sound_logged;
int prefill; // render blocks
} Mixer;
@@ -90,16 +93,47 @@ static void report_once(Mixer *m, unsigned bit, const char *msg, int value) {
// ---- output: SDL3 audio stream fed from the ring
// How much audio the output waits for before it starts, and again after an underrun: TOTK_AUDIO_PREFILL_MS rounded up
// to whole 5 ms render blocks. Returns -1 for a value outside 0..500 ms.
// The Linux default is higher: at 20 ms PipeWire's queue (max(prefill, two 1024-sample periods)) underran
// thousands of times within minutes in busy scenes, and 60 ms removed the underruns.
#ifdef __linux__
#define PREFILL_DEFAULT_MS 60
#else
#define PREFILL_DEFAULT_MS 20
#endif
static int prefill_blocks_for(const char *e) {
if (!e || !*e) return 4;
if (!e || !*e) return PREFILL_DEFAULT_MS / 5;
char *end;
double ms = strtod(e, &end);
if (end == e || *end || !(ms >= 0) || ms > 500) return -1;
return (int)ceil(ms / 5.0);
}
// Fills `frames` stereo frames from the ring (zeros for what is missing). Lock-free; runs on SDL's audio thread.
// TOTK_AUDIO_CHANNELS: the output channels of this run, decided once. stereo gives 2; 5.1 gives 6 (FL FR C LFE RL RR,
// the device sink's order and SDL's); auto gives 6 when the default playback device has at least six channels (a 5.1
// or 7.1 speaker setup in Windows; SDL places 5.1 on 7.1) and 2 otherwise. IAudioDevice reports the same count to the
// game (GetActiveChannelCount), which picks its sink layout from it. TOTK_AUDIO=none: 2, without touching SDL.
static int output_channels(void) {
static _Atomic int decided;
int n = atomic_load(&decided);
if (n) return n;
const char *want = cfg_value("TOTK_AUDIO_CHANNELS"), *mode = cfg_get("TOTK_AUDIO");
if ((mode && !strcmp(mode, "none")) || cfg_get("TOTK_AUDIO_OFF")) n = 2;
else if (!strcmp(want, "5.1")) n = 6;
else if (!strcmp(want, "stereo")) n = 2;
else {
SDL_AudioSpec dev = {0};
n = SDL_InitSubSystem(SDL_INIT_AUDIO) && SDL_GetAudioDeviceFormat(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &dev, NULL) &&
dev.channels >= 6 ? 6 : 2;
rt_log("audio: TOTK_AUDIO_CHANNELS=auto: the default device has %d channels, output %s", dev.channels,
n == 6 ? "5.1" : "stereo");
}
int expected = 0;
return atomic_compare_exchange_strong(&decided, &expected, n) ? n : expected;
}
// Fills `frames` output frames from the ring (zeros for what is missing). Lock-free; runs on SDL's audio thread.
static void ring_pull(Mixer *m, float *out, uint32_t frames) {
const int oc = m->channels;
atomic_fetch_add(&m->callback_frames, frames);
unsigned epoch = atomic_load_explicit(&m->stop_epoch, memory_order_acquire);
uint64_t rd = atomic_load(&m->rd), wr = atomic_load_explicit(&m->wr, memory_order_acquire), have = wr - rd;
@@ -114,7 +148,7 @@ static void ring_pull(Mixer *m, float *out, uint32_t frames) {
m->ready = 0;
}
if (!atomic_load_explicit(&m->playing, memory_order_acquire)) {
memset(out, 0, (size_t)frames * 2 * sizeof(float));
memset(out, 0, (size_t)frames * oc * sizeof(float));
m->ready = 0;
atomic_store_explicit(&m->rd, wr, memory_order_release);
return;
@@ -124,7 +158,7 @@ static void ring_pull(Mixer *m, float *out, uint32_t frames) {
if (prefill > RING_FRAMES) prefill = RING_FRAMES;
if (!m->ready) {
if (have < prefill) {
memset(out, 0, (size_t)frames * 2 * sizeof(float));
memset(out, 0, (size_t)frames * oc * sizeof(float));
return;
}
m->ready = 1;
@@ -140,13 +174,16 @@ static void ring_pull(Mixer *m, float *out, uint32_t frames) {
uint64_t nonzero = 0;
for (uint32_t i = 0; i < n; i++) {
uint64_t k = (rd + i) % RING_FRAMES;
out[2 * i] = m->ring[2 * k];
out[2 * i + 1] = m->ring[2 * k + 1];
if (out[2 * i] != 0 || out[2 * i + 1] != 0) nonzero++;
int sound = 0;
for (int c = 0; c < oc; c++) {
out[oc * i + c] = m->ring[oc * k + c];
sound |= out[oc * i + c] != 0;
}
nonzero += sound;
}
atomic_fetch_add(&m->callback_nonzero, nonzero);
if (n < frames) {
memset(out + 2 * n, 0, (size_t)(frames - n) * 2 * sizeof(float));
memset(out + (size_t)oc * n, 0, (size_t)(frames - n) * oc * sizeof(float));
atomic_fetch_add(&m->underruns, 1);
atomic_fetch_add(&m->missing_frames, frames - n);
m->ready = 0;
@@ -157,15 +194,16 @@ static void ring_pull(Mixer *m, float *out, uint32_t frames) {
static void SDLCALL sdl_pull(void *user, SDL_AudioStream *stream, int additional, int total) {
(void)total;
Mixer *m = user;
float tmp[2 * 1024];
float tmp[OUT_MAX * 1024];
const uint32_t frame_bytes = (uint32_t)m->channels * sizeof(float);
atomic_store_explicit(&m->pulled_ns, kern_now_ns(), memory_order_release);
while (additional > 0) {
uint32_t frames = (uint32_t)additional / (2 * sizeof(float));
uint32_t frames = (uint32_t)additional / frame_bytes;
if (!frames) break;
if (frames > 1024) frames = 1024;
ring_pull(m, tmp, frames);
if (!SDL_PutAudioStreamData(stream, tmp, (int)(frames * 2 * sizeof(float)))) break;
additional -= (int)(frames * 2 * sizeof(float));
if (!SDL_PutAudioStreamData(stream, tmp, (int)(frames * frame_bytes))) break;
additional -= (int)(frames * frame_bytes);
}
}
@@ -179,7 +217,7 @@ static void output_open(Mixer *m, int rate) {
rt_log("audio: SDL audio init failed (%s): mixing without sound", SDL_GetError());
return;
}
SDL_AudioSpec spec = {SDL_AUDIO_F32, 2, rate};
SDL_AudioSpec spec = {SDL_AUDIO_F32, m->channels, rate};
m->stream = SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &spec, sdl_pull, m);
if (!m->stream) {
rt_log("audio: no output device (%s): mixing without sound", SDL_GetError());
@@ -192,7 +230,7 @@ static void output_open(Mixer *m, int rate) {
return;
}
m->device_ok = 1;
SDL_AudioSpec dev;
SDL_AudioSpec dev = {0};
int period = 0;
if (!SDL_GetAudioDeviceFormat(SDL_GetAudioStreamDevice(m->stream), &dev, &period) || period <= 0) period = m->frame;
m->period = period;
@@ -201,8 +239,9 @@ static void output_open(Mixer *m, int rate) {
uint64_t period_ns = (uint64_t)period * 1000000000ull / (uint64_t)rate;
m->stall_ns = 4 * period_ns > STALL_MS * 1000000ull ? 4 * period_ns : STALL_MS * 1000000ull;
const char *name = SDL_GetAudioDeviceName(SDL_GetAudioStreamDevice(m->stream));
rt_log("audio: SDL device '%s' opened, %d Hz stereo float, prefill %d ms, device period %d frames; the device paces "
"rendering at %.1f ms queued", name ? name : "?", rate, m->prefill * 5, period, m->target * 1000.0 / rate);
rt_log("audio: SDL device '%s' opened, %d Hz %s float (device %d channels), prefill %d ms, device period %d frames; "
"the device paces rendering at %.1f ms queued", name ? name : "?", rate, m->channels == 6 ? "5.1" : "stereo",
dev.channels, m->prefill * 5, period, m->target * 1000.0 / rate);
}
int64_t audio_mixer_pace_ns(AudioRenderer *r, uint64_t now) {
@@ -217,7 +256,8 @@ int64_t audio_mixer_pace_ns(AudioRenderer *r, uint64_t now) {
}
// Render thread only.
static void output_push(Mixer *m, const float *lr, int frames) {
static void output_push(Mixer *m, const float *out, int frames) {
const int oc = m->channels;
uint64_t wr = atomic_load(&m->wr), rd = atomic_load_explicit(&m->rd, memory_order_acquire);
if (m->device_ok && wr + (uint64_t)frames - rd > RING_FRAMES) { // device stalled: drop this frame
atomic_fetch_add(&m->overruns, 1);
@@ -225,24 +265,51 @@ static void output_push(Mixer *m, const float *lr, int frames) {
}
for (int i = 0; i < frames; i++) {
uint64_t k = (wr + (uint64_t)i) % RING_FRAMES;
m->ring[2 * k] = lr[2 * i];
m->ring[2 * k + 1] = lr[2 * i + 1];
memcpy(&m->ring[oc * k], &out[oc * i], (size_t)oc * sizeof(float));
}
atomic_store_explicit(&m->wr, wr + (uint64_t)frames, memory_order_release);
if (!m->device_ok) atomic_store(&m->rd, wr + (uint64_t)frames); // no device: the ring only keeps the latest frames
}
// TOTK_AUDIO_DUMP=<path>: the sink mix before the clamp as raw interleaved float32 stereo, and every 5 s one log line with
// how many frames were rendered less than 1 ms after the one before (a burst refill). File writes on the render thread:
// for diagnosis only.
static void sink_dump(const float *raw, int frames) {
static FILE *f;
static int opened;
static uint64_t last, window_start, total, bursts;
if (!opened) {
opened = 1;
const char *path = cfg_get("TOTK_AUDIO_DUMP");
if (path && *path) f = fopen(path, "wb");
}
if (!f) return;
fwrite(raw, sizeof(float), (size_t)frames * 2, f);
uint64_t now = kern_now_ns();
total++;
if (last && now - last < 1000000ull) bursts++;
last = now;
if (!window_start) window_start = now;
if (now - window_start >= 5000000000ull) {
rt_log("audio: dump: %llu frames in %.1f s, %llu rendered under 1 ms after the previous", (unsigned long long)total,
(now - window_start) / 1e9, (unsigned long long)bursts);
total = bursts = 0;
window_start = now;
fflush(f);
}
}
// Level meter (TOTK_TRACE=audio): one line per 5 s of output, and the first nonzero frame.
static void level_note(AudioRenderer *r, Mixer *m, const float *lr, int frames) {
static void level_note(AudioRenderer *r, Mixer *m, const float *out, int frames) {
if (!(rt_trace & RT_TRACE_AUDIO)) return;
int sound = 0;
for (int k = 0; k < 2 * frames; k++) {
double x = lr[k];
for (int k = 0; k < m->channels * frames; k++) {
double x = out[k];
m->level_sum += x * x;
if (fabs(x) > m->level_peak) m->level_peak = fabs(x);
if (x != 0) sound = 1;
}
m->level_count += 2 * (uint64_t)frames;
m->level_count += (uint64_t)m->channels * (uint64_t)frames;
m->level_frames += (uint64_t)frames;
if (sound && !m->first_sound_logged) {
m->first_sound_logged = 1;
@@ -290,9 +357,10 @@ void audio_mixer_open(AudioRenderer *r) {
const char *pe = cfg_get("TOTK_AUDIO_PREFILL_MS");
m->prefill = prefill_blocks_for(pe);
if (m->prefill < 0) {
rt_log("audio: TOTK_AUDIO_PREFILL_MS=%s is not 0..500 ms: using 20", pe);
m->prefill = 4;
rt_log("audio: TOTK_AUDIO_PREFILL_MS=%s is not 0..500 ms: using %d", pe, PREFILL_DEFAULT_MS);
m->prefill = PREFILL_DEFAULT_MS / 5;
}
m->channels = output_channels();
r->mixer = m;
atomic_store(&m->playing, r->state == 0);
output_open(m, r->param.sample_rate);
@@ -505,8 +573,25 @@ static void walk_step(Walk *w) { /* the same transitions as advance_voice in a
walk_skip_empty(w);
}
/* Decodes `frames` output samples per channel into out[c][k]; the renderer advances the voice afterwards by the same amount. */
static double voice_step(const AudioRenderer *r, const ServerVoice *v) {
return v->in.sample_rate * (v->in.pitch > 0 ? v->in.pitch : 1.0) / r->param.sample_rate;
}
/* Source samples the voice consumes over `frames` output samples, counted with the exact accumulation voice_render steps by
(float rounding makes `fraction + seconds * rate * pitch` differ from it by one sample on some frames, a seam click);
leaves the fractional position in v->fraction. */
uint64_t audio_voice_consumed(const AudioRenderer *r, ServerVoice *v, int frames) {
const double step = voice_step(r, v);
double frac = v->fraction;
uint64_t consumed = 0;
for (int k = 0; k < frames; k++) {
frac += step;
while (frac >= 1.0) { frac -= 1.0; consumed++; }
}
v->fraction = frac;
return consumed;
}
static void voice_render(AudioRenderer *r, ServerVoice *v, float out[6][MAX_FRAME], int frames) {
const double step = v->in.sample_rate * (v->in.pitch > 0 ? v->in.pitch : 1.0) / r->param.sample_rate;
const double step = voice_step(r, v);
Walk w = {v, v->index, v->offset, v->loops_done, {0}, 0, v->adpcm.history[0], v->adpcm.history[1], v->adpcm.buffer, v->adpcm.at};
memcpy(w.valid, v->valid, sizeof w.valid);
walk_skip_empty(&w);
@@ -545,6 +630,7 @@ static void mix_aux(AudioRenderer *r, int mix, const AudrenEffectIn *e) {
uint8_t *send=ipc_guest(p.send_info,128+(uint64_t)p.capacity*4), *ret=ipc_guest(p.return_info,128+(uint64_t)p.capacity*4);
uint32_t *sh=(uint32_t *)(send+64),*rh=(uint32_t *)(ret+64); int32_t *sd=(int32_t *)(send+128),*rd=(int32_t *)(ret+128);
uint32_t wr=sh[1],read=rh[0],total=p.channels*(uint32_t)m->frame;
if(e->enabled) report_once(m,6,"auxiliary effect in use, channels",(int)p.channels);
for(unsigned c=0;c<p.channels;c++) {
if(p.input[c]>=r->mixes[mix].buffer_count || p.output[c]>=r->mixes[mix].buffer_count)rt_fatal("auxiliary effect mix buffer");
float *input=mixbuf(m,m->offset[mix]+p.input[c]),*output=mixbuf(m,m->offset[mix]+p.output[c]);
@@ -793,30 +879,42 @@ void audio_mixer_render(AudioRenderer *r, double seconds) {
if (r->sinks[i].type == SINK_DEVICE && !sink) sink = &r->sinks[i];
else if (r->sinks[i].type == SINK_CIRCULAR){mix_circular_sink(r,i);circular=1;}
} else {m->sink_address[i]=0;m->sink_size[i]=m->sink_offset[i]=m->sink_old[i]=m->sink_written[i]=0;}
float *lr=m->output_scratch;
memset(lr, 0, sizeof(float) * 2 * (size_t)frames);
const int oc = m->channels;
float *out=m->output_scratch;
memset(out, 0, sizeof(float) * (size_t)oc * (size_t)frames);
if (sink && sink->input_count >= 1 && sink->input_count <= 6) {
if (!(m->reported & (1u << 6))) {
m->reported |= 1u << 6;
rt_log("audio: device sink has %u inputs, output %s", sink->input_count, oc == 6 ? "5.1" : "stereo");
}
const float gain = host_volume() * atomic_load(&device_volume) * (r->mixes[0].in_use ? r->mixes[0].volume : 1.0f);
const float *ch[6] = {0};
float raw[2 * MAX_FRAME];
for (uint32_t c = 0; c < sink->input_count; c++) if (sink->inputs[c] >= 0 && sink->inputs[c] < m->nbuf) ch[c] = mixbuf(m, sink->inputs[c]);
for (int k = 0; k < frames; k++) {
float l, rr;
if (sink->input_count >= 6) { /* FL FR C LFE RL RR -> stereo */
float s[OUT_MAX] = {0}; /* FL FR C LFE RL RR */
if (sink->input_count >= 6 && oc == 6) {
for (int c = 0; c < 6; c++) s[c] = ch[c] ? ch[c][k] : 0;
} else if (sink->input_count >= 6) { /* 5.1 -> stereo; the LFE is left out, as the Switch's downmix does */
float ff = sink->downmix_enabled ? sink->downmix[0] : 1.0f, cf = sink->downmix_enabled ? sink->downmix[1] : 0.7071f, sf = sink->downmix_enabled ? sink->downmix[2] : 0.7071f;
float C = ch[2] ? ch[2][k] : 0;
l = ff * (ch[0] ? ch[0][k] : 0) + cf * C + sf * (ch[4] ? ch[4][k] : 0);
rr = ff * (ch[1] ? ch[1][k] : 0) + cf * C + sf * (ch[5] ? ch[5][k] : 0);
} else if (sink->input_count >= 2) { l = ch[0] ? ch[0][k] : 0; rr = ch[1] ? ch[1][k] : 0; }
else l = rr = ch[0] ? ch[0][k] : 0;
l *= gain; rr *= gain;
lr[2 * k] = l > 1 ? 1 : l < -1 ? -1 : l; lr[2 * k + 1] = rr > 1 ? 1 : rr < -1 ? -1 : rr;
s[0] = ff * (ch[0] ? ch[0][k] : 0) + cf * C + sf * (ch[4] ? ch[4][k] : 0);
s[1] = ff * (ch[1] ? ch[1][k] : 0) + cf * C + sf * (ch[5] ? ch[5][k] : 0);
} else if (sink->input_count >= 2) { s[0] = ch[0] ? ch[0][k] : 0; s[1] = ch[1] ? ch[1][k] : 0; }
else s[0] = s[1] = ch[0] ? ch[0][k] : 0;
raw[2 * k] = s[0] * gain; raw[2 * k + 1] = s[1] * gain; /* TOTK_AUDIO_DUMP: the front pair before clipping */
for (int c = 0; c < oc; c++) {
float x = s[c] * gain;
out[oc * k + c] = x > 1 ? 1 : x < -1 ? -1 : x;
}
}
sink_dump(raw, frames);
} else if (!sink && !circular) report_once(m, 5, "no device sink in use", r->param.sink_count);
level_note(r, m, lr, frames);
output_push(m, lr, frames);
level_note(r, m, out, frames);
output_push(m, out, frames);
}
// ---- IAudioDevice: one stereo output device
// ---- IAudioDevice: one output device, stereo or 5.1 (output_channels)
static const char device_name[] = "AudioTvOutput";
static void put_name(const IpcBuffer *b, IpcResponse *rs, int pointer) {
@@ -855,7 +953,7 @@ void audio_device_handler(IpcSession *s, const IpcRequest *rq, IpcResponse *rs)
put_name(&b, rs, pointer);
return;
}
case 5: { int32_t n = 2; IPC_OUT(rs, n); return; } // GetActiveChannelCount
case 5: { int32_t n = output_channels(); IPC_OUT(rs, n); return; } // GetActiveChannelCount
case 4: case 11: case 12: { // QueryAudioDeviceSystemEvent, ...InputEvent, ...OutputEvent
uint32_t ev = __atomic_load_n(&change_event, __ATOMIC_ACQUIRE);
if (!ev) {
+2 -2
View File
@@ -24,8 +24,8 @@ static void delay_set(Delay *d, unsigned n) { if (n > d->cap) rt_fatal("reverb d
static void delay_init(Delay *d, unsigned khz, float ms) { d->cap = samples(khz, ms); d->data = calloc(d->cap + 1, sizeof(float)); if (!d->data) rt_fatal("reverb delay allocation"); delay_set(d, d->cap); }
static float delay_update(Delay *d, float v) {
d->data[d->write++] = v; float out = d->data[d->read++];
if (d->read >= d->cap) d->read = 0;
if (d->write >= d->cap) d->write = 0;
if (d->read > d->cap) d->read = 0;
if (d->write > d->cap) d->write = 0;
return out;
}
static float delay_tap(const Delay *d, unsigned at) { int i = (int)d->write - (int)at - 1; if (i < 0) i += (int)d->cap + 1; return d->data[i]; }
+21 -6
View File
@@ -318,11 +318,9 @@ static void request_update(AudioRenderer *r, const uint8_t *input, uint64_t in_s
// ---- render tick: one frame each time the output device has taken the ring below its target (audio_mixer_pace_ns),
// or every sample_count / sample_rate seconds of the host clock without a device, while stopped or while it stalls
static void advance_voice(AudioRenderer *r, ServerVoice *v, double out_seconds) {
static void advance_voice(AudioRenderer *r, ServerVoice *v) {
if (!v->in.in_use || v->state != SV_STARTED || !v->in.sample_rate) return;
double want = v->fraction + out_seconds * v->in.sample_rate * (v->in.pitch > 0 ? v->in.pitch : 1.0);
uint64_t samples = (uint64_t)want;
v->fraction = want - (double)samples;
uint64_t samples = audio_voice_consumed(r, v, (int)r->param.sample_count);
while (samples && v->valid[v->index]) {
AudrenWaveBuffer *b = &v->buffers[v->index];
uint64_t length = (uint64_t)(b->end - b->start), left = length - v->offset;
@@ -354,7 +352,19 @@ static void render_thread(void *p) {
plat_thread_priority(PLAT_PRIO_HIGHEST);
const uint64_t frame_ns = (uint64_t)r->param.sample_count * 1000000000ull / (uint64_t)r->param.sample_rate;
const double frame = (double)r->param.sample_count / r->param.sample_rate;
uint64_t next = kern_now_ns();
// When the device pulls a period (1024 samples on PipeWire, 4-5 frames) the ring drops below its target
// and the frames would otherwise render back to back. On hardware the DSP renders one frame every 5 ms and
// the game's audio thread works in between; AUX effects need that time to fill the return ring, or mix_aux
// reads stale samples and the frame clicks at its seams. Device-paced frames stay at least 4/5 of a frame
// apart, which still refills a period well before the device drains it. Linux only: on Windows SDL pulls
// 480-sample periods, and a sink dump (TOTK_AUDIO_DUMP) of the bursts there showed no more seam spikes than
// chance, so a wait on this thread buys nothing.
#ifdef __linux__
const uint64_t gap_ns = frame_ns * 4 / 5;
#else
const uint64_t gap_ns = 0;
#endif
uint64_t next = kern_now_ns(), last = 0;
while (plat_cas32(&r->running, 0, 0)) {
uint64_t now = kern_now_ns();
int64_t pace = audio_mixer_pace_ns(r, now);
@@ -362,6 +372,10 @@ static void render_thread(void *p) {
plat_wait_ns((uint64_t)pace);
continue;
}
if (pace == 0 && last && now - last < gap_ns) {
plat_wait_ns(gap_ns - (now - last));
continue;
}
if (pace == 0) {
next = now + frame_ns; // where the timer goes on if the device stops pacing
} else {
@@ -369,11 +383,12 @@ static void render_thread(void *p) {
else if (now - next > 100000000ull) next = now; // fell far behind (debugger, sleep): resynchronise
next += frame_ns;
}
last = kern_now_ns();
plat_mutex_lock(&r->lock);
if (r->state == 0) {
voices_prepare(r);
audio_mixer_render(r, frame);
for (int i = 0; i < r->param.voice_count; i++) advance_voice(r, &r->voices[i], frame);
for (int i = 0; i < r->param.voice_count; i++) advance_voice(r, &r->voices[i]);
r->elapsed_frames++;
uint64_t given = r->stop_released + r->empty_played + r->flushed;
if ((rt_trace & RT_TRACE_IPC) && given != r->logged_released && r->elapsed_frames % 1000 == 0) {
+1
View File
@@ -184,5 +184,6 @@ void audio_mixer_render(AudioRenderer *r, double seconds); // after audio_voic
// many ns (the ring is at its target), -1 leaves the pace to the render thread's timer (no device, renderer stopped,
// device stalled).
int64_t audio_mixer_pace_ns(AudioRenderer *r, uint64_t now);
uint64_t audio_voice_consumed(const AudioRenderer *r, ServerVoice *v, int frames); // source samples over one frame; advances v->fraction
int audio_buffer_empty(const AudrenWaveBuffer *b); // no samples to decode: played as soon as it is reached
void audio_device_handler(IpcSession *s, const IpcRequest *rq, IpcResponse *rs); // IAudioDevice
+11 -7
View File
@@ -4,7 +4,7 @@
// The boot driver: the guest main thread runs the game's own nn::init::Start
// with three host callbacks, the second of which runs DT_INIT of main, subsdk0 and sdk; Start then calls nnMain.
// --boot checks two checkpoints on the way and ends at the first nvnBootstrapLoader call, at the return address of
// each in main (1.1.1, 1.2.1, 1.4.3):
// each in main (1.1.0, 1.2.1, 1.4.3):
// SetFocusHandlingMode main+0xeb8c14 (1.2.1: +0xe7a954, 1.4.3: +0xbdb48c) in nnMain, every module's constructor
// flag reads 2
// nvnBootstrapLoader main+0xebcdec (1.2.1: +0xe7eb2c, 1.4.3: +0xbe0360) in the graphics bring-up; logs the
@@ -15,27 +15,29 @@
#include <string.h>
#include "cfg.h"
#include "cheats.h"
#include "fs.h"
#include "gfx.h"
#include "mods.h"
#include "nvn_api.h"
#include "platform/platform.h"
#include "vk.h"
#include "platform/platform.h"
#define SYM_INIT_START "_ZN2nn4init5StartEmmPFvvES2_S2_"
// main: return addresses of nnMain's SetFocusHandlingMode call (1.1.1 and 1.2.1 from this port's analysis of main;
// main: return addresses of nnMain's SetFocusHandlingMode call (1.1.0 and 1.2.1 from this port's analysis of main;
// 1.4.3 from MacNativeGames' scripts/verify_boot.py) and of the first nvnBootstrapLoader call, per game version.
#define CHECKPOINT_RET (RT_V143 ? 0xbdb48cull : RT_V111 ? 0xeb8c14ull : 0xe7a954ull)
#define NVN_RET (RT_V143 ? 0xbe0360ull : RT_V111 ? 0xebcdecull : 0xe7eb2cull)
#define CHECKPOINT_RET (RT_V143 ? 0xbdb48cull : RT_V110 ? 0xeb8c14ull : 0xe7a954ull)
#define NVN_RET (RT_V143 ? 0xbe0360ull : RT_V110 ? 0xebcdecull : 0xe7eb2cull)
#define CTOR_DONE 2 // a module's constructor flag after its DT_INIT ran the init_array
// The init_array sizes (1.1.1 and 1.2.1: counted in the modules; 1.4.3: DT_INIT_ARRAYSZ); MacNativeGames' boot check
// The init_array sizes (1.1.0 and 1.2.1: counted in the modules; 1.4.3: DT_INIT_ARRAYSZ); MacNativeGames' boot check
// expects the same. The three tables carry the same rows, so cb_module_inits walks them by the size of one.
typedef struct { const char *name; uint64_t entries; } InitCount;
static const InitCount inits_111[] = {{"main", 10668}, {"subsdk0", 45}, {"sdk", 116}};
static const InitCount inits_110[] = {{"main", 10668}, {"subsdk0", 45}, {"sdk", 116}};
static const InitCount inits_121[] = {{"main", 10673}, {"subsdk0", 45}, {"sdk", 116}};
static const InitCount inits_143[] = {{"main", 10717}, {"subsdk0", 45}, {"sdk", 83}};
#define expected_inits (RT_V143 ? inits_143 : RT_V111 ? inits_111 : inits_121)
#define expected_inits (RT_V143 ? inits_143 : RT_V110 ? inits_110 : inits_121)
static volatile int32_t inits_done, checkpoint_seen;
uint64_t rt_guest_start_ns;
@@ -342,8 +344,10 @@ void rt_boot(void) {
PlatThread *warm = plat_thread_new(prewarm_main, NULL, "prewarm");
ldr_load(rt_config()->exefs);
rt_patches_init();
mods_exefs_switch(); // after the patch sets' settings: an enabled mod's ExeFS patches on
frame_step_init();
res_init();
cheats_init(); // after the patch sets: a cheat's set follows its setting
cb_addr[0] = hostfn_register("<rtld loader_ready>", cb_loader_ready);
cb_addr[1] = hostfn_register("<rtld module_inits>", cb_module_inits);
cb_addr[2] = hostfn_register("<rtld module_finis>", cb_module_finis);
+159
View File
@@ -0,0 +1,159 @@
// Camera speed: TOTK_STICK_SENS (0.1 to 3, default 1, read at start) multiplies the game's own right-stick camera speeds.
// The game's Options menu offers five camera sensitivities, Very Low to Very High; their turn rates are the array
// StickSensitivity {0.8, 1.2, 1.6, 2.0, 2.4} in Component/PlayerCameraParam/PlayerCamera.game__component__
// PlayerCameraParam.bgyml inside Pack/Actor/PlayerCamera.pack.zs. romfs.c serves a copy of that pack with every entry
// multiplied (cam_pack_build), so the setting raises the camera's top speed as well as its speed at a partial tilt, at
// any of the five sensitivities. The mouse camera reaches the game as a right-stick deflection (input.c, mouse_camera),
// which divides it by the same factor (cam_speed_applied), so TOTK_MOUSE_SENS alone sets the mouse's speed.
//
// The pack is a SARC archive compressed with the dictionary pack.zsdic of Pack/ZsDic.pack.zs. A float in a BYML array
// is stored in the array itself, so the multiplied values take the bytes of the old ones and no offset moves.
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <zstd.h>
#include "cfg.h"
#include "host.h"
#define MEMBER "Component/PlayerCameraParam/PlayerCamera.game__component__PlayerCameraParam.bgyml"
#define MAX_RAW (64u << 20)
static float applied = 1.0f;
float cam_speed_wanted(void) {
double v = cfg_double("TOTK_STICK_SENS");
return (float)(v < 0.1 ? 0.1 : v > 3 ? 3 : v);
}
float cam_speed_applied(void) { return applied; }
static int u32_at(const uint8_t *p, size_t n, size_t off, uint32_t *v) {
if (off > n || n - off < 4) return 0;
memcpy(v, p + off, 4);
return 1;
}
// SARC member `name` of the archive p[0..n): its start and size; 0 when it is not there.
static int sarc_member(const uint8_t *p, size_t n, const char *name, size_t *at, size_t *size) {
uint32_t data;
uint16_t head, count, bom;
if (n < 0x14 || memcmp(p, "SARC", 4)) return 0;
memcpy(&head, p + 4, 2);
memcpy(&bom, p + 6, 2);
if (bom != 0xfeff || !u32_at(p, n, 12, &data) || head + 12u > n || memcmp(p + head, "SFAT", 4)) return 0;
memcpy(&count, p + head + 6, 2);
size_t names = head + 12 + (size_t)count * 16;
if (names + 8 > n || memcmp(p + names, "SFNT", 4)) return 0;
names += 8;
for (unsigned i = 0; i < count; i++) {
uint32_t attr, lo, hi;
size_t e = head + 12 + (size_t)i * 16;
if (!u32_at(p, n, e + 4, &attr) || !u32_at(p, n, e + 8, &lo) || !u32_at(p, n, e + 12, &hi)) return 0;
size_t s = names + (size_t)(attr & 0xffffff) * 4, len = strlen(name);
if (!(attr >> 24) || s + len + 1 > n || memcmp(p + s, name, len + 1)) continue;
if (lo > hi || data + (size_t)hi > n) return 0;
*at = data + lo;
*size = hi - lo;
return 1;
}
return 0;
}
// The StickSensitivity floats of the BYML p[0..n), multiplied by k; their count, 0 when the file has no such array.
static int scale_sensitivity(uint8_t *p, size_t n, float k, float was[8]) {
uint32_t keys, root, head;
if (n < 16 || memcmp(p, "YB", 2) || !u32_at(p, n, 4, &keys) || !u32_at(p, n, 12, &root) ||
!u32_at(p, n, root, &head) || (head & 0xff) != 0xc1 || !u32_at(p, n, keys, &head) || (head & 0xff) != 0xc2)
return 0;
uint32_t nkeys = head >> 8;
if (!u32_at(p, n, root, &head)) return 0;
for (uint32_t i = 0; i < head >> 8; i++) {
uint32_t e, at, arr, ah;
if (!u32_at(p, n, root + 4 + 8 * (size_t)i, &e) || (e & 0xffffff) >= nkeys ||
!u32_at(p, n, keys + 4 + 4 * (size_t)(e & 0xffffff), &at))
return 0;
const char *name = (const char *)p + keys + at;
if (keys + at + sizeof "StickSensitivity" > n || strcmp(name, "StickSensitivity")) continue;
if (e >> 24 != 0xc0 || !u32_at(p, n, root + 8 + 8 * (size_t)i, &arr) || !u32_at(p, n, arr, &ah) ||
(ah & 0xff) != 0xc0)
return 0;
uint32_t count = ah >> 8;
size_t vals = arr + 4 + ((count + 3) & ~3u);
if (!count || count > 8 || vals + 4 * (size_t)count > n) return 0;
for (uint32_t j = 0; j < count; j++)
if (p[arr + 4 + j] != 0xd2) return 0;
for (uint32_t j = 0; j < count; j++) {
float v;
memcpy(&v, p + vals + 4 * j, 4);
was[j] = v;
v *= k;
memcpy(p + vals + 4 * j, &v, 4);
}
return (int)count;
}
return 0;
}
int cam_pack_build(const void *in, size_t n, const void *zsdic, size_t zsdic_n, void **out, size_t *out_n) {
float k = cam_speed_wanted();
*out = NULL;
if (k == 1.0f) return 0;
int ok = 0;
uint8_t *dics = NULL, *raw = NULL;
ZSTD_DDict *dd = NULL;
ZSTD_CDict *cd = NULL;
void *z = NULL;
// The dictionaries: Pack/ZsDic.pack.zs is a SARC compressed without one.
unsigned long long dn = ZSTD_getFrameContentSize(zsdic, zsdic_n);
size_t dic_at, dic_n;
if (dn == ZSTD_CONTENTSIZE_UNKNOWN || dn == ZSTD_CONTENTSIZE_ERROR || dn > MAX_RAW || !(dics = malloc((size_t)dn)) ||
ZSTD_decompress(dics, (size_t)dn, zsdic, zsdic_n) != dn ||
!sarc_member(dics, (size_t)dn, "pack.zsdic", &dic_at, &dic_n)) {
rt_log("camera speed: no pack.zsdic in Pack/ZsDic.pack.zs; the camera keeps its own speed");
goto done;
}
unsigned long long rn = ZSTD_getFrameContentSize(in, n);
unsigned id = ZSTD_getDictID_fromFrame(in, n);
dd = ZSTD_createDDict(dics + dic_at, dic_n);
if (!dd || id != ZSTD_getDictID_fromDDict(dd) || rn == ZSTD_CONTENTSIZE_UNKNOWN ||
rn == ZSTD_CONTENTSIZE_ERROR || rn > MAX_RAW || !(raw = malloc((size_t)rn))) {
rt_log("camera speed: Pack/Actor/PlayerCamera.pack.zs is not a pack.zsdic frame with a size; the camera keeps its "
"own speed");
goto done;
}
ZSTD_DCtx *dctx = ZSTD_createDCtx();
size_t got = dctx ? ZSTD_decompress_usingDDict(dctx, raw, (size_t)rn, in, n, dd) : 0;
ZSTD_freeDCtx(dctx);
size_t at, size;
float was[8];
int count = !ZSTD_isError(got) && got == rn && sarc_member(raw, (size_t)rn, MEMBER, &at, &size)
? scale_sensitivity(raw + at, size, k, was) : 0;
if (!count) {
rt_log("camera speed: no StickSensitivity array in %s; the camera keeps its own speed", MEMBER);
goto done;
}
cd = ZSTD_createCDict(dics + dic_at, dic_n, 9);
size_t cap = ZSTD_compressBound((size_t)rn), zn = 0;
ZSTD_CCtx *cctx = cd ? ZSTD_createCCtx() : NULL;
if (cctx && (z = malloc(cap))) zn = ZSTD_compress_usingCDict(cctx, z, cap, raw, (size_t)rn, cd);
ZSTD_freeCCtx(cctx);
if (!z || !zn || ZSTD_isError(zn)) goto done;
*out = z;
*out_n = zn;
z = NULL;
ok = 1;
rt_log("camera speed: x%.2f, StickSensitivity %.2f %.2f %.2f %.2f %.2f -> %.2f %.2f %.2f %.2f %.2f", k, was[0],
count > 1 ? was[1] : 0, count > 2 ? was[2] : 0, count > 3 ? was[3] : 0, count > 4 ? was[4] : 0, was[0] * k,
count > 1 ? was[1] * k : 0, count > 2 ? was[2] * k : 0, count > 3 ? was[3] * k : 0,
count > 4 ? was[4] * k : 0);
done:
free(z);
free(raw);
free(dics);
ZSTD_freeDDict(dd);
ZSTD_freeCDict(cd);
return ok;
}
void cam_pack_served(void) { applied = cam_speed_wanted(); }
+85 -27
View File
@@ -30,27 +30,35 @@ static int save_ok = 1; // the last cfg_save_to wrote (o
// Every name the runtime reads (and the patch sets in generated/), without the prefix. A file key outside this list is
// logged as unknown. A new variable goes here too, or its ini key logs a harmless "unknown key" line.
static const char *const known[] = {
"AB", "ANISO", "APP_POOL", "ASPECT", "ASPECT_PATCH", "ASSUME_FOCUS", "ASTC", "ASTC_BC", "ASTC_TIME", "ASYNC_PREEMPT", "AUDIO", "AUDIO_OFF", "AUDIO_PREFILL_MS",
"AB", "AMIIBO_DIR", "ANISO", "APP_POOL", "ASPECT", "ASPECT_PATCH", "ASSUME_FOCUS", "ASTC", "ASTC_BC", "ASTC_TIME", "ASYNC_PREEMPT", "AUDIO", "AUDIO_CHANNELS", "AUDIO_OFF", "AUDIO_PREFILL_MS",
"BACKGROUND_WINDOW", "BIND_A", "BIND_B", "BIND_DOWN", "BIND_L", "BIND_LCLICK", "BIND_LEFT", "BIND_LSTICK_DOWN", "BIND_LSTICK_LEFT",
"BIND_LSTICK_RIGHT", "BIND_LSTICK_UP", "BIND_MINUS",
"BIND_PLUS", "BIND_R", "BIND_RCLICK", "BIND_RIGHT", "BIND_RSTICK_DOWN", "BIND_RSTICK_LEFT", "BIND_RSTICK_RIGHT", "BIND_RSTICK_UP",
"BIND_SKIP", "BIND_STATS", "BIND_UP", "BIND_X", "BIND_Y",
"BIND_ZL", "BIND_ZR", "BLOCK_VIEWS_3D", "CLOTH_REALTIME", "COLOR_BRIGHTNESS", "COLOR_CONTRAST", "COLOR_GAMMA", "COLOR_PRESET", "COLOR_SATURATION", "CORE_DIAG", "CRIT", "CRIT_OUT", "DESC_TEMPLATE", "DEVICE_PROFILE", "DUMP", "DUMP_BUF", "DUMP_DIR", "DUMP_LOG",
"EXEFS", "FEEDBACK", "FIX_C0", "FIX_ZERO", "FLIGHT", "FLIGHT_AT", "FLIGHT_DIR", "FLIGHT_FRAMES", "FLIGHT_SPIKE_MS",
"FLIGHT_THUMBS", "FOV", "FOV_PATCH", "FPS60", "FPS_LIMIT", "FREEZE_IDLE", "FREE_CORES", "FULLSCREEN", "GPL", "GPL_DRAW_BUILD", "GPU",
"GPU_INDEX", "GPU_NAME", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "LANG", "LIB_PREBUILD",
"LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LOCALE", "LOD_DETAIL", "LOD_GUARD", "LOD_STEADY", "MEMORY", "MENU_LANG", "MENU_TEST",
"MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MOTION", "MOUSE_SENS", "MOVIE_HOST", "MOVIE_PACE",
"ONE_PER_CORE", "OPERATION_MODE", "OUTPUT_RES", "PAD_LAYOUT", "PATCH_OUTPUT", "PATCH_SCENE", "PERF_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_MEMO", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT",
"BIND_ZL", "BIND_ZR", "BLOCK_VIEWS_3D", "CLOTH_REALTIME", "COLOR_BRIGHTNESS", "COLOR_CONTRAST", "COLOR_GAMMA",
"COLOR_PRESET", "COLOR_SATURATION", "CONTACT_DEBUG", "CONTACT_SHADOWS", "CORE_DIAG", "CRIT", "CRIT_OUT",
"DESC_TEMPLATE", "DEVICE_PROFILE", "DISCORD_APP_ID", "DISCORD_IMAGE", "DISCORD_RPC", "DLAA", "DLAA_JITTER", "DLAA_MV", "DLAA_MASKDEBUG", "DLAA_MVDEBUG", "DLAA_OBJMV", "DLAA_SURVEY", "DLAA_TIMES", "DLSS", "DLSS_CHAR_MASK", "DLSS_PRESET", "DLSS_REACTIVE", "DUMP", "DUMP_BUF", "DUMP_DIR",
"DUMP_LOG", "EXEFS", "FEEDBACK", "FIX_C0", "FIX_ZERO", "FLIGHT", "FLIGHT_AT", "FLIGHT_DIR", "FLIGHT_FRAMES",
"FLIGHT_SPIKE_MS", "FLIGHT_THUMBS", "FOV", "FOV_PATCH", "FPS60", "FPS_LIMIT", "FREEZE_IDLE", "FREE_CORES",
"FULLSCREEN", "FXAA", "GPL", "GPL_DRAW_BUILD", "GPU", "GPU_INDEX", "GPU_NAME", "HDR", "HDR_GAME_NITS", "HDR_HUE",
"HDR_PEAK_NITS", "HDR_UI_NITS", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "LANG", "LIB_PREBUILD",
"LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LOCALE", "LOD_DETAIL", "LOD_GUARD", "LOD_STEADY", "LSTICK_DEADZONE", "MEMORY", "MENU_LANG", "MENU_TEST",
"MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MODS_DIR", "MODS_DISABLED", "MODS_ORDER", "MODS_REBUILD", "MOTION", "MOUSE_SENS", "MOVIE_HOST", "MOVIE_PACE",
"MVOBJ_ALL", "MVOBJ_BANKS", "MVOBJ_EQUAL", "MVOBJ_EXACT", "MVOBJ_EXEC", "MVOBJ_NOC4", "MVOBJ_ONLY", "MVOBJ_TIMES", "MVPREV_CHECK", "MVPREV_GROW", "MVPREV_SKIP", "MVPREV_TRUST", "MV_CHECK",
"MV_SURVEY",
"ONE_PER_CORE", "OPERATION_MODE", "OUTPUT_RES", "PAD_LAYOUT", "PASS_CRUMBS", "PATCH_OUTPUT", "PATCH_SCENE", "PCSS", "PCSS_K", "PERF_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_MEMO", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT",
"PREWARM_XLATE", "PROBE_MOVIE", "PROBE_MOVIE_SHOT", "PROFILE", "PROFILE_CHAINS", "PROFILE_DIR", "PROFILE_FRAMES",
"PROFILE_MAIN", "PROFILE_RENDER", "PUSH_SKIP", "PUSH_STAGE", "RDOC", "RDOC_DIR", "RDOC_DLL", "REALTIME", "REC_END", "REEXEC",
"PROFILE_MAIN", "PROFILE_RENDER", "PROMPTS", "PUSH_SKIP", "PUSH_STAGE", "RDOC", "RDOC_DIR", "RDOC_DLL", "REALTIME", "REC_END", "REEXEC",
"RENDER_SCALE", "REPLAY_ASYNC",
"REPLAY_CHECK", "RESOLVE_CHECK", "ROMFS", "ROMFS_INDEX", "ROMFS_MMAP", "ROMFS_MODS", "ROMFS_PATCHES",
"ROMFS_PROOF_DIR", "ROMFS_VERIFY", "RUMBLE", "RUMBLE_CURVE", "RUMBLE_STRENGTH", "RUMBLE_TRIGGERS", "SHADER_CACHE",
"SHADER_MEMO", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR", "SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_US", "STICK_DEADZONE", "SWKBD_ANSWER",
"SWKBD_TEST", "TEST_PAD", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_MEMO", "TEX_VRAM_PRESSURE", "TIMER_1MS", "TRACE", "UBO_SNAPSHOT", "UPSCALER", "VK_DYN_A2C", "VK_DYN_VERTEX", "VK_NO_FLOAT64",
"REPLAY_CHECK", "RESOLVE_CHECK", "RESTART_WAIT", "ROMFS", "ROMFS_INDEX", "ROMFS_MMAP", "ROMFS_MODS", "ROMFS_PATCHES",
"ROMFS_PROOF_DIR", "ROMFS_VERIFY", "RSTICK_DEADZONE", "RUMBLE", "RUMBLE_CURVE", "RUMBLE_STRENGTH", "RUMBLE_TRIGGERS", "SHADER_CACHE",
"SHADER_MEMO", "SHADOW_RANGE", "SHADOW_RES", "SHADOW_SCALE", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR",
"SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_US", "STICK_DEADZONE", "STICK_SENS",
"SWKBD_ANSWER",
"SWKBD_TEST", "TEST_PAD", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_MEMO", "TEX_VRAM_PRESSURE", "TIMER_1MS", "TRACE", "TXD_TRANSPOSE", "UBO_SNAPSHOT", "UPSCALER", "VK_DYN_A2C", "VK_DYN_VERTEX", "VK_NO_FLOAT64",
"VK_PRESENT", "VK_RECORDER", "VK_SSBO_ALIGN", "VK_SUBGROUP", "VK_SUBGROUP_PIN", "VK_VALIDATION", "VOLUME", "VRAM_HEADROOM", "VS_OUTS",
"WB_EXACT", "WB_FENCE_LIMIT", "WINDOW_SIZE", "XLATE", "XLATE_ID", "XLATE_PROCS", "ZSTD_CHECK", "ZSTD_NATIVE",
"WALK_KEY", "WALK_SCALE", "WB_EXACT", "WB_FENCE_LIMIT", "WINDOW_SIZE", "XLATE", "XLATE_ID", "XLATE_KEEP", "XLATE_PROCS",
"ZSTD_CHECK", "ZSTD_NATIVE",
};
// The totk.ini section a key cfg_set may write goes to when the file lacks it (totk.ini.example's sections).
@@ -62,12 +70,20 @@ static const struct { const char *key, *section; } sections[] = {
{"SHARPNESS", "display"}, {"ASPECT", "display"}, {"FOV", "display"}, {"ANISO", "display"},
{"LOD_DETAIL", "display"}, {"LOD_STEADY", "display"}, {"COLOR_PRESET", "display"},
{"COLOR_BRIGHTNESS", "display"}, {"COLOR_CONTRAST", "display"}, {"COLOR_SATURATION", "display"},
{"COLOR_GAMMA", "display"},
{"COLOR_GAMMA", "display"}, {"HDR", "display"}, {"HDR_PEAK_NITS", "display"}, {"HDR_GAME_NITS", "display"},
{"HDR_UI_NITS", "display"}, {"HDR_HUE", "display"}, {"SHADOW_RES", "display"},
{"DLAA", "display"}, {"DLSS", "display"}, {"DLSS_PRESET", "display"}, {"DLSS_CHAR_MASK", "display"}, {"FXAA", "display"},
{"DEVICE_PROFILE", "display"}, {"ASSUME_FOCUS", "display"},
{"DISCORD_RPC", "discord"}, {"DISCORD_APP_ID", "discord"}, {"DISCORD_IMAGE", "discord"},
{"SHADOW_SCALE", "display"}, {"SHADOW_RANGE", "display"}, {"CONTACT_SHADOWS", "display"},
{"PCSS", "display"},
{"MODS_DIR", "mods"}, {"MODS_ORDER", "mods"}, {"MODS_DISABLED", "mods"}, {"MODS_REBUILD", "mods"},
{"MENU_LANG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"},
{"VOLUME", "audio"},
{"VOLUME", "audio"}, {"AUDIO_CHANNELS", "audio"},
{"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"},
{"PAD_LAYOUT", "input"}, {"STICK_DEADZONE", "input"}, {"MOUSE_SENS", "input"}, {"INPUT_RECORD", "input"},
{"PAD_LAYOUT", "input"}, {"PROMPTS", "input"}, {"STICK_DEADZONE", "input"}, {"LSTICK_DEADZONE", "input"}, {"RSTICK_DEADZONE", "input"},
{"STICK_SENS", "input"},
{"MOUSE_SENS", "input"}, {"WALK_KEY", "input"}, {"WALK_SCALE", "input"}, {"INPUT_RECORD", "input"},
{"BIND_A", "input"}, {"BIND_B", "input"}, {"BIND_X", "input"}, {"BIND_Y", "input"}, {"BIND_LCLICK", "input"},
{"BIND_RCLICK", "input"}, {"BIND_L", "input"}, {"BIND_R", "input"}, {"BIND_ZL", "input"}, {"BIND_ZR", "input"},
{"BIND_PLUS", "input"}, {"BIND_MINUS", "input"}, {"BIND_LEFT", "input"}, {"BIND_UP", "input"},
@@ -82,8 +98,9 @@ static const struct { const char *key, *section; } sections[] = {
{"BIND_SKIP", "performance"}, {"SHADER_MEMO", "performance"}, {"PIPE_MEMO", "performance"}, {"TEX_MEMO", "performance"}, {"DESC_TEMPLATE", "performance"},
{"PUSH_SKIP", "performance"}, {"SPLIT_DRAWS", "performance"}, {"SPLIT_US", "performance"}, {"VK_VALIDATION", "performance"},
{"VK_DYN_VERTEX", "performance"}, {"VK_DYN_A2C", "performance"}, {"VK_SUBGROUP_PIN", "performance"},
{"TRACE", "diagnostics"}, {"FLIGHT", "diagnostics"}, {"FLIGHT_SPIKE_MS", "diagnostics"},
{"TRACE", "diagnostics"}, {"FLIGHT", "diagnostics"}, {"PASS_CRUMBS", "diagnostics"}, {"FLIGHT_SPIKE_MS", "diagnostics"},
{"WB_FENCE_LIMIT", "diagnostics"}, {"WB_EXACT", "diagnostics"},
{"MV_SURVEY", "diagnostics"},
};
// The settings the menu shows: the value in effect when the key is unset, and what the key accepts. The only place a
@@ -98,37 +115,57 @@ static const CfgMeta metas[] = {
{"PERF_OVERLAY", "off", "off|fps|full", LIVE},
{"OUTPUT_RES", "1920x1080", NULL, RESTART}, {"RENDER_SCALE", "game", "game|50|67|75|100|125|150|200", RESTART},
{"UPSCALER", "fsr", "fsr|bilinear", LIVE}, {"SHARPNESS", "80", "0..100", LIVE},
{"DLAA", "0", "0|1", RESTART}, {"DLSS", "dlaa", "dlaa|quality|balanced|performance|ultra_performance", LIVE},
{"DLSS_PRESET", "default", "default|k|j", LIVE},
{"DLSS_CHAR_MASK", "65", "0|35|65|100", LIVE}, {"FXAA", "1", "0|1", LIVE},
{"ASPECT", "fit", "fit|stretch", LIVE}, {"FOV", "100", "70..140", LIVE},
{"ANISO", "16", "game|2|4|8|16", RESTART}, // vk_texture.c sampler_features
{"ANISO", "game", "game|2|4|8|16", RESTART}, // vk_texture.c sampler_features
{"LOD_DETAIL", "0", "0|1", RESTART}, {"LOD_STEADY", "0", "0|1", RESTART}, // patch sets lod and steady (1.2.1)
// colour adjustment (vk_color.c); the preset is the menu's, the four values are what the present uses
{"COLOR_PRESET", "default", "default|vivid|clarity|custom", LIVE}, {"COLOR_BRIGHTNESS", "0", "-30..30", LIVE},
{"COLOR_CONTRAST", "100", "70..150", LIVE}, {"COLOR_SATURATION", "100", "50..200", LIVE},
{"COLOR_GAMMA", "1", "0.8..1.2", LIVE},
// HDR output (vk_hdr.c): on at start (the tonemap shader is swapped as shaders load); the nits apply at once
{"HDR", "0", "0|1", RESTART}, {"HDR_PEAK_NITS", "1000", "400..10000", LIVE}, {"HDR_GAME_NITS", "203", "80..500", LIVE},
{"HDR_UI_NITS", "203", "80..500", LIVE}, {"HDR_HUE", "80", "0..100", LIVE},
{"DEVICE_PROFILE", "auto", "auto|desktop|deck", RESTART},
{"SHADOW_RES", "game", "game|256|512|768|1024|1536|2048", RESTART},
{"SHADOW_SCALE", "1", "1..4", RESTART},
{"SHADOW_RANGE", "100", "50..400", RESTART}, {"CONTACT_SHADOWS", "0", "0..100", RESTART},
{"PCSS", "0", "0..200", RESTART},
// Game
{"FPS_LIMIT", "60", "30|40|45|60|90|120|144|display", LIVE}, {"FPS60", "1", "0|1", LIVE},
{"REALTIME", "1", "0|1", RESTART}, {"CLOTH_REALTIME", "1", "0|1", RESTART},
{"MODS_REBUILD", "auto", "auto|off", RESTART},
{"HIGHFPS_FIX", "1", "0|1", RESTART},
{"LANG", "", "ja|en-US|fr|de|it|es|zh-CN|ko|nl|pt|ru|zh-TW|en-GB|fr-CA|es-419|zh-Hans|zh-Hant|pt-BR", RESTART},
{"OPERATION_MODE", "docked", "docked|handheld", RESTART},
{"ASSUME_FOCUS", "1", "0|1", LIVE}, // read on every focus change (ov_system.c)
// Sound, Controls, Menu
{"VOLUME", "100", "0..100", LIVE},
{"VOLUME", "100", "0..100", LIVE}, {"AUDIO_CHANNELS", "stereo", "auto|stereo|5.1", RESTART},
{"MOTION", "1", "0|1", LIVE}, {"RUMBLE_STRENGTH", "130", "0..300", LIVE}, {"RUMBLE_CURVE", "0.6", "0.2..1.5", LIVE},
{"RUMBLE_TRIGGERS", "0", "0|1", LIVE}, {"PAD_LAYOUT", "auto", "auto|nintendo|xbox|xbox_prompts", LIVE},
{"STICK_DEADZONE", "8", "0..50", LIVE}, {"MOUSE_SENS", "1", "0..10", LIVE},
{"MENU_LANG", "", "en|ru", LIVE},
{"RUMBLE_TRIGGERS", "0", "0|1", LIVE}, {"PAD_LAYOUT", "auto", "auto|nintendo|xbox", LIVE},
{"PROMPTS", "nintendo", "nintendo|xbox", RESTART},
{"STICK_DEADZONE", "8", "0..50", LIVE}, {"STICK_SENS", "1", "0.1..3", RESTART},
{"LSTICK_DEADZONE", "", "0..50", LIVE}, {"RSTICK_DEADZONE", "", "0..50", LIVE},
{"MOUSE_SENS", "1", "0..10", LIVE},
{"WALK_KEY", "none", NULL, LIVE}, {"WALK_SCALE", "0.51", "0.2..0.9", LIVE},
{"MENU_LANG", "", "en|ru|pt-BR|zh-Hans", LIVE},
{"AMIIBO_DIR", "", NULL, LIVE},
// Discord Rich Presence (discord_rpc.c): off by default, the Menu tab of the settings menu switches it.
{"DISCORD_RPC", "0", "0|1", LIVE},
{"DISCORD_APP_ID", "1567232599846293504", NULL, LIVE},
{"DISCORD_IMAGE", "totk_512x512", NULL, LIVE},
// Advanced: scheduling
{"ASYNC_PREEMPT", "1", "0|1|2", RESTART}, {"REPLAY_ASYNC", "0", "0|1", RESTART},
{"ASYNC_PREEMPT", "1", "0|1|2", RESTART}, {"REPLAY_ASYNC", "1", "0|1", RESTART},
{"FREE_CORES", "0", "0|1", RESTART}, {"TIMER_1MS", "1", "0|1", RESTART},
// shaders and pipelines
{"PIPE_WAIT", "default", "default|draw", RESTART}, {"PIPE_SKIP", "fullscreen", "strict|any|fullscreen", RESTART},
{"LIB_PREBUILD", "1", "0|1", RESTART}, {"LIB_PREBUILD_THREADS", "", "1..64", RESTART},
{"PIPE_PREBUILD", "1", "0|1", RESTART}, {"PREWARM_XLATE", "", "1..64", RESTART}, {"GPL", "", "0|1", RESTART},
{"PIPE_PREBUILD", "1", "0|1", RESTART}, {"PREWARM_XLATE", "", "1..64", RESTART}, {"GPL", "1", "0|1", RESTART},
// textures and memory
{"ASTC", "auto", "auto|gpu|native|cpu", RESTART}, {"MEMORY", "auto", "auto|import|mirror|verify", RESTART},
{"TEX_ALIAS", "1", "0|1", RESTART}, {"TEX_VRAM_PRESSURE", "90", "0..100", RESTART}, {"ASTC_BC", "0", "0|1", RESTART}, {"ZSTD_NATIVE", "1", "0|1", RESTART}, {"ZSTD_CHECK", "0", "0|1", RESTART},
{"TEX_ALIAS", "1", "0|1", RESTART}, {"TEX_VRAM_PRESSURE", "90", "0..100", RESTART}, {"ASTC_BC", "", "0|1", RESTART}, {"ZSTD_NATIVE", "1", "0|1", RESTART}, {"ZSTD_CHECK", "0", "0|1", RESTART},
// render fixes
{"LOD_GUARD", "1", "0|1", RESTART}, {"FIX_C0", "1", "0|1", RESTART}, {"FIX_ZERO", "1", "0|1", RESTART},
{"BIND_SKIP", "1", "0|1", RESTART}, {"SHADER_MEMO", "1", "0|1", RESTART}, {"PIPE_MEMO", "1", "0|1", RESTART}, {"TEX_MEMO", "1", "0|1", RESTART},
@@ -141,13 +178,14 @@ static const CfgMeta metas[] = {
// diagnostics
{"TRACE", "", NULL, RESTART}, {"FLIGHT", "0", "0|1", RESTART}, {"FLIGHT_SPIKE_MS", "100", "0..60000", RESTART},
{"WB_FENCE_LIMIT", "65536", "0..1073741824", RESTART}, {"WB_EXACT", "1", "0|1", RESTART},
{"PASS_CRUMBS", "", "0|1", RESTART}, // vk_crumbs.c pass marks; unset: VK_AMD_buffer_marker only
{"INPUT_RECORD", "", NULL, RESTART},
};
static int is_known(const char *key) {
for (size_t i = 0; i < sizeof known / sizeof *known; i++)
if (!strcmp(known[i], key)) return 1;
return 0;
return !strncmp(key, "CHEAT_", 6); // cheats.c and the cheat patch sets (tools/cheats.py)
}
static void clear(void) {
@@ -185,6 +223,24 @@ static void add(char *key, char *value, int line) {
entries[n_entries++] = (CfgEntry){strdup(key), strdup(value), 0, 0};
}
// 0.1.9 had the Xbox prompts as a pad layout: pad_layout = xbox_prompts is pad_layout = nintendo with prompts = xbox.
// Read as those two, which the menu shows and the next cfg_save writes; a prompts line of the file's own wins. The
// value still works from the environment (input_pad_layout_pick, input_prompts_pick).
static void migrate(void) {
CfgEntry *layout = NULL, *prompts = NULL;
for (int i = 0; i < n_entries; i++) {
if (!strcmp(entries[i].key, "PAD_LAYOUT")) layout = &entries[i];
if (!strcmp(entries[i].key, "PROMPTS")) prompts = &entries[i];
}
if (!layout || strcasecmp(layout->value, "xbox_prompts")) return;
free(layout->value);
layout->value = strdup("nintendo");
layout->dirty = 1;
if (!prompts && n_entries < CFG_MAX_KEYS) entries[n_entries++] = (CfgEntry){strdup("PROMPTS"), strdup("xbox"), 1, 0};
rt_log("cfg: totk.ini pad_layout = xbox_prompts is read as pad_layout = nintendo and prompts = %s",
prompts ? prompts->value : "xbox");
}
int cfg_load(const char *path) {
clear();
uint64_t size = 0;
@@ -208,6 +264,7 @@ int cfg_load(const char *path) {
p = eol + 1;
}
free(data);
migrate();
return 1;
}
@@ -466,6 +523,7 @@ static void puts_(Out *o, const char *s) { put(o, s, strlen(s)); }
static const char *section_of(const char *key) {
for (size_t i = 0; i < sizeof sections / sizeof *sections; i++)
if (!strcmp(sections[i].key, key)) return sections[i].section;
if (!strncmp(key, "CHEAT_", 6)) return "cheats"; // cheats.c: one key per cheat of the cheat file
return NULL;
}
+67 -3
View File
@@ -1,4 +1,5 @@
// --probe-cfg: totk.ini parsing, the environment override and a missing file (cfg.c). Needs no game files.
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
@@ -272,6 +273,22 @@ int probe_cfg(void) {
"pad stick: a square gate's corner stays on the unit circle");
input_pad_stick(0, 32767 / 2 + 1, 0.2f, st);
CHECK(abs(st[1] - 32767 * 3 / 8) <= 3, "pad stick: half deflection past a 20% zone is (0.5 - 0.2) / 0.8 of full");
plat_setenv("TOTK_STICK_DEADZONE", "12");
plat_setenv("TOTK_LSTICK_DEADZONE", NULL);
plat_setenv("TOTK_RSTICK_DEADZONE", NULL);
CHECK(fabsf(input_pad_deadzone(0) - 0.12f) < 1e-6f && fabsf(input_pad_deadzone(1) - 0.12f) < 1e-6f,
"pad dead zone: both sticks follow stick_deadzone while lstick/rstick are unset");
plat_setenv("TOTK_RSTICK_DEADZONE", "20");
CHECK(fabsf(input_pad_deadzone(0) - 0.12f) < 1e-6f && fabsf(input_pad_deadzone(1) - 0.20f) < 1e-6f,
"pad dead zone: rstick_deadzone sets the right stick alone");
plat_setenv("TOTK_LSTICK_DEADZONE", "80");
CHECK(fabsf(input_pad_deadzone(0) - 0.5f) < 1e-6f, "pad dead zone: clamped to 50%");
plat_setenv("TOTK_STICK_DEADZONE", NULL);
plat_setenv("TOTK_LSTICK_DEADZONE", NULL);
plat_setenv("TOTK_RSTICK_DEADZONE", NULL);
CHECK(input_stick_percent(32767, 0) > 99.99 && input_stick_percent(32767, 0) < 100.01 &&
input_stick_percent(0, 0) == 0 && fabs(input_stick_percent(3000, -4000) - 5000 * 100.0 / 32767) < 1e-9,
"stick percent: an axis's end is 100%, the centre 0%, round in between");
// Gamepad layouts (input_map.c)
CHECK(input_pad_layout_pick("auto", 1) == PAD_LAYOUT_NINTENDO && input_pad_layout_pick(NULL, 0) == PAD_LAYOUT_XBOX,
"pad layout: automatic is Nintendo for an east button labelled A, Xbox otherwise");
@@ -279,7 +296,30 @@ int probe_cfg(void) {
"pad layout: a set layout wins over the labels");
CHECK(input_pad_layout_pick("xbox_prompts", 0) == PAD_LAYOUT_NINTENDO &&
input_pad_layout_pick("Xbox_Prompts", 1) == PAD_LAYOUT_NINTENDO,
"pad layout: Xbox prompts keep the Nintendo positions (only the prompts change, romfs.c overlay_init)");
"pad layout: 0.1.9's xbox_prompts keeps the Nintendo positions (only the prompts change, romfs.c overlay_init)");
// Button prompts (input_map.c)
CHECK(input_prompts_pick(NULL, "auto") == PROMPTS_NINTENDO && input_prompts_pick("", "xbox") == PROMPTS_NINTENDO &&
input_prompts_pick("Xbox", "nintendo") == PROMPTS_XBOX && input_prompts_pick("nintendo", "xbox") == PROMPTS_NINTENDO,
"prompts: the game's own unless set to Xbox");
CHECK(input_prompts_pick(NULL, "xbox_prompts") == PROMPTS_XBOX && input_prompts_pick("nintendo", "xbox_prompts") == PROMPTS_NINTENDO,
"prompts: 0.1.9's pad_layout = xbox_prompts means Xbox while prompts is unset");
CHECK(!input_prompts_folder(PROMPTS_NINTENDO, "nintendo") && !input_prompts_folder(PROMPTS_NINTENDO, "xbox"),
"prompts: the game's own need no folder");
CHECK(EQ(input_prompts_folder(PROMPTS_XBOX, "nintendo"), "romfs-patches-xbox") &&
EQ(input_prompts_folder(PROMPTS_XBOX, "xbox_prompts"), "romfs-patches-xbox") &&
EQ(input_prompts_folder(PROMPTS_XBOX, "xbox"), "romfs-patches-xbox-label") &&
EQ(input_prompts_folder(PROMPTS_XBOX, "auto"), "romfs-patches-xbox-label") &&
EQ(input_prompts_folder(PROMPTS_XBOX, NULL), "romfs-patches-xbox-label"),
"prompts: the face buttons by position for the Nintendo layout, by label for xbox and auto");
// romfs-patches-xbox shows A as B (tests/romfs_prompts_test.py checks the folders' contents). It is right exactly
// where the layout puts A on the east button, which an Xbox pad labels B.
input_map_reset();
static const char *const layouts[] = {"nintendo", "xbox", "auto", "xbox_prompts"};
for (int i = 0; i < 4; i++) {
int a_east = input_map_pad_buttons((uint8_t[PAD_COUNT]){[PAD_EAST] = 1}, input_pad_layout_pick(layouts[i], 0)) == 1ull << B_A;
CHECK(a_east == EQ(input_prompts_folder(PROMPTS_XBOX, layouts[i]), "romfs-patches-xbox"),
"prompts: the folder names A as B exactly when the layout puts A on the button labelled B");
}
uint8_t pd[PAD_COUNT] = {0};
pd[PAD_SOUTH] = pd[PAD_NORTH] = 1;
CHECK(input_map_pad_buttons(pd, PAD_LAYOUT_NINTENDO) == (1ull << B_B | 1ull << B_X) &&
@@ -370,6 +410,24 @@ int probe_cfg(void) {
plat_setenv("TOTK_FREE_CORES", "1");
CHECK(cfg_bool("TOTK_FREE_CORES") == 1, "free_cores 1: on");
plat_setenv("TOTK_FREE_CORES", NULL);
// 0.1.9's pad_layout = xbox_prompts (cfg.c migrate): read as the Nintendo layout with the Xbox prompts, saved so
plat_setenv("TOTK_PAD_LAYOUT", NULL);
plat_setenv("TOTK_PROMPTS", NULL);
static const char old_layout[] = "[input]\r\npad_layout = xbox_prompts\r\n";
CHECK(plat_file_write(path, old_layout, sizeof old_layout - 1) && cfg_load(path) == 1 &&
EQ(cfg_get("TOTK_PAD_LAYOUT"), "nintendo") && EQ(cfg_get("TOTK_PROMPTS"), "xbox"),
"0.1.9's pad_layout = xbox_prompts reads as nintendo with prompts = xbox");
CHECK(cfg_save_to(path) == 1, "the read pad layout and prompts save");
uint64_t saved_n = 0;
char *saved = (char *)plat_file_read(path, &saved_n);
CHECK(saved && strstr(saved, "pad_layout = nintendo") && strstr(saved, "prompts = xbox") && !strstr(saved, "xbox_prompts"),
"the next save writes the pad layout and the prompts");
free(saved);
static const char old_layout_own[] = "[input]\r\npad_layout = xbox_prompts\r\nprompts = nintendo\r\n";
CHECK(plat_file_write(path, old_layout_own, sizeof old_layout_own - 1) && cfg_load(path) == 1 &&
EQ(cfg_get("TOTK_PAD_LAYOUT"), "nintendo") && EQ(cfg_get("TOTK_PROMPTS"), "nintendo"),
"a prompts line of the file's own wins over 0.1.9's pad_layout = xbox_prompts");
plat_file_delete(path);
cfg_load("cfg-probe-missing.ini");
int listed = 0;
for (int i = 0; cfg_meta_at(i); i++) {
@@ -383,9 +441,10 @@ int probe_cfg(void) {
int ok = 0;
if (!m->values) ok = 1;
else if (strstr(m->values, "..")) {
long lo = strtol(m->values, NULL, 10), hi = strtol(strstr(m->values, "..") + 2, NULL, 10);
// strtod: ranges such as 0.2..0.9 have fractional ends
double lo = strtod(m->values, NULL), hi = strtod(strstr(m->values, "..") + 2, NULL);
double d = strtod(m->def, NULL);
ok = d >= (double)lo && d <= (double)hi;
ok = d >= lo && d <= hi;
} else {
size_t dl = strlen(m->def);
for (const char *v = m->values; *v;) {
@@ -397,6 +456,11 @@ int probe_cfg(void) {
if (!ok) fprintf(stderr, "FAIL cfg: default '%s' of %s is not one of its values '%s'\n", m->def, m->key, m->values), fails++;
}
CHECK(listed >= 30, "the defaults table was walked");
// cfg_meta answers with the first row of a key: a second row would be dead, and Reset would visit the key twice
for (int i = 0; cfg_meta_at(i); i++)
for (int j = i + 1; cfg_meta_at(j); j++)
if (!strcmp(cfg_meta_at(i)->key, cfg_meta_at(j)->key))
fprintf(stderr, "FAIL cfg: %s has two rows in the defaults table\n", cfg_meta_at(i)->key), fails++;
printf("probe-cfg: %s\n", fails ? "FAIL" : "ok");
return fails ? 1 : 0;
}
+667
View File
@@ -0,0 +1,667 @@
// Cheats of the mods' Atmosphere cheat files (cheats.h). Each enabled mod the port can use (mods.h) may hold
// <build id>.txt in its cheats folder, the build id the first 8 bytes of main's NSO build id, as Atmosphere and the
// emulators name it; the file name's case does not matter. Each cheat's switch is the setting TOTK_CHEAT_<hash>
// (cheat_<hash> under [cheats] in totk.ini), the hash FNV-1a 32 of "<mod folder name>/<cheat name>", so two mods'
// cheats of one name keep their own switches.
//
// Code cheats (opcode 0 writes into main's code) cannot be applied here: the game's code is lifted C. tools/cheats.py
// turns the code cheats of every mod into patch sets cheat_<hash> when the game is built and writes
// build-cache\cheats.status next to totk.exe, one line per cheat: name hash, content hash, kind, buttons, note
// (tools/cheats.py has the format). A cheat whose status line is missing or has another content hash was added or
// edited after the build: a data cheat runs anyway, a code cheat waits for the setup to run again.
//
// Data cheats run in a VM after Atmosphere's dmnt cheat VM (opcodes 0-A; the 0xC.. and 0xF.. extensions are not
// supported), every presented frame while their switch is on, with registers cleared before each cheat. Memory is the
// guest's, mapped at its own addresses: main's image is written with its pages made writable for the write (read-only
// data included, as dmnt writes through the debugger), everything else after mem_query says the guest may read or write
// it. Buttons are input_poll's HidNpadButton bits, the same as the cheat format's key masks; they read 0 while the menu
// is open.
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include "cfg.h"
#include "cheats.h"
#include "host.h"
#include "input.h"
#include "mods.h"
#include "platform/platform.h"
#ifdef _WIN32
#define SEP "\\"
#else
#define SEP "/"
#endif
enum { STATUS_MAX = 160, OPS_PER_RUN = 1 << 20 };
typedef struct {
CheatInfo info;
uint32_t *words;
int n;
int dup; // 1 for the first cheat of its name in its file, 2 for the next ...
uint32_t content; // FNV-1a 32 of its words as tools/cheats.py writes them
int set; // patch set, -1 none
volatile int32_t on;
char note[STATUS_MAX];
} Cheat;
static Cheat *g_cheats;
static int g_n, g_cap, g_vm; // g_vm: some cheat needs cheats_frame
static char g_file[64]; // "<build id>.txt"
static char g_dir[PLAT_PATH_MAX]; // the folder of totk.exe, with a trailing separator
static int g_files; // mods whose file was read
static uint64_t g_main, g_main_size, g_code_end; // main's image; its code with the padding up to .rodata
static uint32_t fnv(const char *s, size_t n) {
uint32_t h = 0x811C9DC5u;
for (size_t i = 0; i < n; i++) h = (h ^ (uint8_t)s[i]) * 0x01000193u;
return h;
}
// The folder of the executable, with a trailing separator.
static int exe_dir(char *out, size_t n) {
if (!plat_exe_path(out, n)) return 0;
char *cut = plat_last_sep(out);
if (!cut) return 0;
cut[1] = 0;
return 1;
}
static int build_id(char out[17]) {
char path[PLAT_PATH_MAX];
snprintf(path, sizeof path, "%s/main", rt_config()->exefs);
PlatFile *f = plat_file_open(path);
if (!f) return 0;
uint8_t head[0x48];
int ok = plat_file_pread(f, head, sizeof head, 0) == sizeof head && !memcmp(head, "NSO0", 4);
plat_file_close(f);
for (int i = 0; ok && i < 8; i++) snprintf(out + 2 * i, 3, "%02X", head[0x40 + i]);
return ok;
}
// ---- opcodes
// Words of the opcode at w (left words remain), 0 when it is cut short.
static int op_len(const uint32_t *w, int left) {
uint32_t f = w[0];
int t = f >> 28, width = (f >> 24) & 0xF, n;
switch (t) {
case 0: case 1: n = width == 8 ? 4 : 3; break;
case 2: case 8: n = 1; break;
case 3: n = width == 0 ? 2 : 1; break;
case 4: case 6: n = 3; break;
case 5: case 7: n = 2; break;
case 9: n = 1 + (((f >> 8) & 0xF) ? (width == 8 ? 2 : 1) : 0); break;
case 0xA: n = ((f >> 8) & 0xF) == 2 || ((f >> 8) & 0xF) == 4 || ((f >> 8) & 0xF) == 5 ? 2 : 1; break;
default: n = 1; break;
}
return n <= left ? n : 0;
}
// NULL when the VM runs the opcode, else why not (tools/cheats.py vm_ok).
static const char *vm_unsupported(const uint32_t *w, char *buf, int n) {
uint32_t f = w[0];
int t = f >> 28, width = (f >> 24) & 0xF;
if (t > 0xA || (t == 5 && ((f >> 12) & 0xF) > 1) || (t == 0xA && ((f >> 8) & 0xF) > 5)) {
snprintf(buf, n, "opcode %08X is not supported", f);
return buf;
}
if ((t <= 1 || t == 5 || t == 6 || t == 7 || t == 9 || t == 0xA) && width != 1 && width != 2 && width != 4 &&
width != 8) {
snprintf(buf, n, "opcode %08X has a bad width", f);
return buf;
}
return NULL;
}
// The kind of a cheat the build did not see: heading, data, rebuild (it writes main's code) or unsupported.
static CheatKind classify(Cheat *c) {
int ops = 0, ends = 0;
for (int i = 0; i < c->n;) {
int len = op_len(c->words + i, c->n - i);
if (!len) {
snprintf(c->note, sizeof c->note, "opcode %08X is cut short", c->words[i]);
return CHEAT_UNSUPPORTED;
}
uint32_t f = c->words[i];
ops++;
ends += f >> 28 == 2;
if (f >> 28 == 0 && ((f >> 20) & 0xF) == 0) {
uint64_t off = ((uint64_t)(f & 0xFF) << 32) | c->words[i + 1];
if (off < g_code_end - g_main) return CHEAT_REBUILD;
}
if (vm_unsupported(c->words + i, c->note, sizeof c->note)) return CHEAT_UNSUPPORTED;
i += len;
}
return ops == ends && ops <= 1 ? CHEAT_HEADING : CHEAT_DATA;
}
// ---- guest memory
static uint64_t region(int m) {
const RtGuestLayout *l = mem_layout();
switch (m) {
case 0: return g_main;
case 1: return l->heap.base;
case 2: return l->alias.base;
case 3: return l->aslr.base;
default: return 0;
}
}
static int in_main(uint64_t a, unsigned n) { return a >= g_main && a + n <= g_main + g_main_size; }
static int guest_ok(uint64_t a, unsigned n, uint32_t perm) {
if (in_main(a, n)) return 1;
RtMemoryInfo mi;
if (mem_query(a, &mi) || !mi.state || (mi.perm & perm) != perm) return 0;
return a + n <= mi.base + mi.size;
}
static int rd(uint64_t a, int width, uint64_t *v) {
if (!a || !guest_ok(a, (unsigned)width, 1)) return 0;
uint64_t x = 0;
memcpy(&x, (const void *)(uintptr_t)a, (size_t)width);
*v = x;
return 1;
}
// Writes n bytes into main's image a page at a time: a read-only page is writable for its part of the copy only.
static void wr_main(uint64_t a, const uint8_t *from, int n) {
while (n > 0) {
uint64_t page = a & ~0xFFFull, end;
int k = (int)(page + 0x1000 - a);
if (k > n) k = n;
int prot = plat_mem_state(page, page + 0x1000, &end);
if (prot != PLAT_PROT_READ && prot != PLAT_PROT_RW) return;
if (prot == PLAT_PROT_READ && !plat_mem_protect(page, 0x1000, PLAT_PROT_RW)) return;
memcpy((void *)(uintptr_t)a, from, (size_t)k);
if (prot == PLAT_PROT_READ) plat_mem_protect(page, 0x1000, PLAT_PROT_READ);
a += (uint64_t)k;
from += k;
n -= k;
}
}
static void wr(uint64_t a, int width, uint64_t v) {
uint64_t now;
if (!rd(a, width, &now) || !memcmp(&now, &v, (size_t)width)) return; // unchanged: no write, no protection change
void *p = (void *)(uintptr_t)a;
if (in_main(a, (unsigned)width)) {
wr_main(a, (const uint8_t *)&v, width);
} else if (guest_ok(a, (unsigned)width, 2)) {
memcpy(p, &v, (size_t)width); // a frozen region thaws on the write (memory.c)
}
}
static uint64_t masked(int width, uint64_t v) { return width >= 8 ? v : v & ((1ull << (8 * width)) - 1); }
static uint64_t arith(int op, uint64_t a, uint64_t b) {
switch (op) {
case 0: return a + b;
case 1: return a - b;
case 2: return a * b;
case 3: return b < 64 ? a << b : 0;
case 4: return b < 64 ? a >> b : 0;
case 5: return a & b;
case 6: return a | b;
case 7: return ~a;
case 8: return a ^ b;
default: return a; // 9: move
}
}
static int compare(int cond, uint64_t a, uint64_t b) {
switch (cond) {
case 1: return a > b;
case 2: return a >= b;
case 3: return a < b;
case 4: return a <= b;
case 5: return a == b;
case 6: return a != b;
default: return 0;
}
}
// From i (after a failed condition, or an else reached while running), the opcode to continue at: after the
// matching else (else_ok) or end.
static int skip(const uint32_t *w, int n, int i, int else_ok) {
int depth = 0;
while (i < n) {
int len = op_len(w + i, n - i);
if (!len) return n;
uint32_t f = w[i];
int t = f >> 28;
i += len;
if (t == 1 || t == 8) depth++;
else if (t == 2 && ((f >> 24) & 0xF) == 0 && depth-- == 0) return i;
else if (t == 2 && depth == 0 && else_ok) return i;
}
return n;
}
static uint64_t imm64(const uint32_t *w) { return (uint64_t)w[0] << 32 | w[1]; }
static void run(const Cheat *c, uint64_t keys) {
uint64_t r[16] = {0};
int loop[16] = {0};
const uint32_t *w = c->words;
int n = c->n, budget = OPS_PER_RUN;
for (int i = 0; i < n && budget-- > 0;) {
int len = op_len(w + i, n - i);
if (!len) return;
uint32_t f = w[i];
int t = f >> 28, width = (f >> 24) & 0xF, x = (f >> 20) & 0xF, y = (f >> 16) & 0xF, z = (f >> 12) & 0xF;
uint64_t rel = ((uint64_t)(f & 0xFF) << 32) | (len > 1 ? w[i + 1] : 0), v;
switch (t) {
case 0: // 0TMR00AA AAAAAAAA V..: store a value at region M + A + register R
wr(region(x) + rel + r[y], width, width == 8 ? imm64(w + i + 2) : w[i + 2]);
break;
case 1: // 1TMC00AA AAAAAAAA V..: if (region M + A) <cond C> V
if (!rd(region(x) + rel, width, &v) || !compare(y, v, width == 8 ? imm64(w + i + 2) : w[i + 2])) {
i = skip(w, n, i + len, 1);
continue;
}
break;
case 2: // 20000000 end, 21000000 else: an else reached while running skips to the end
if (width == 1) {
i = skip(w, n, i + len, 0);
continue;
}
break;
case 3: // 300R0000 VVVVVVVV loop start, 310R0000 loop end
if (width == 0) {
r[y] = w[i + 1];
loop[y] = i + len;
} else if (r[y] && --r[y]) {
i = loop[y];
continue;
}
break;
case 4: // 400R0000 V V: register R = V
r[y] = imm64(w + i + 1);
break;
case 5: // 5TMRI0AA AAAAAAAA: R = (I ? R : region M) + A, read
if (!rd(z ? r[y] + rel : region(x) + rel, width, &v)) return; // a broken pointer chain: nothing more
r[y] = v;
break;
case 6: { // 6T0RIor0 V V: store V at R (+ register r); I: R += width
uint64_t a = r[y] + (((f >> 8) & 0xF) ? r[(f >> 4) & 0xF] : 0);
wr(a, width, imm64(w + i + 1));
if (z) r[y] += (uint64_t)width;
break;
}
case 7: // 7T0RC000 VVVVVVVV: R = R <op C> V
r[y] = masked(width, arith(z, r[y], w[i + 1]));
break;
case 8: // 8kkkkkkk: if the buttons are held
if ((keys & (f & 0x0FFFFFFF)) != (f & 0x0FFFFFFF)) {
i = skip(w, n, i + len, 1);
continue;
}
break;
case 9: { // 9TCRS0s0 / 9TCRS100 V..: R = S <op C> (s or V)
uint64_t b = (f >> 8) & 0xF ? (width == 8 ? imm64(w + i + 1) : w[i + 1]) : r[(f >> 4) & 0xF];
r[y] = masked(width, arith(x, r[z], b));
break;
}
case 0xA: { // ATSRIOxa (aaaaaaaa): store register S at an address of type O
int o = (f >> 8) & 0xF, m = (f >> 4) & 0xF;
uint64_t imm = ((uint64_t)(f & 0xF) << 32) | (len > 1 ? w[i + 1] : 0), a;
switch (o) {
case 0: a = r[y]; break;
case 1: a = r[y] + r[m]; break;
case 2: a = r[y] + imm; break;
case 3: a = region(m) + r[y]; break;
case 4: a = region(m) + imm; break;
default: a = region(m) + r[y] + imm; break;
}
wr(a, width, r[x]);
if (z) r[y] += (uint64_t)width;
break;
}
default:
return;
}
i += len;
}
}
// ---- the file
static char *read_text(const char *path) {
uint64_t n = 0;
char *s = (char *)plat_file_read(path, &n);
if (s && n >= 3 && !memcmp(s, "\xEF\xBB\xBF", 3)) memmove(s, s + 3, (size_t)n - 2); // a UTF-8 BOM
return s;
}
static void add_word(Cheat *c, uint32_t v, int *cap) {
if (c->n == *cap) {
*cap = *cap ? *cap * 2 : 16;
c->words = (uint32_t *)realloc(c->words, sizeof *c->words * (size_t)*cap);
if (!c->words) rt_fatal("cheats: out of memory");
}
c->words[c->n++] = v;
}
// Appends the cheats of one mod's file; mod: the mod's folder name (kept).
static void parse(char *s, const char *mod) {
int first = g_n, wcap = 0;
for (char *line = s; line && *line;) {
char *end = strchr(line, '\n'), *next = end ? end + 1 : NULL;
if (end) *end = 0;
while (*line == ' ' || *line == '\t') line++;
size_t len = strlen(line);
while (len && (line[len - 1] == '\r' || line[len - 1] == ' ' || line[len - 1] == '\t')) line[--len] = 0;
if (len >= 2 && (line[0] == '[' || line[0] == '{') && (line[len - 1] == ']' || line[len - 1] == '}')) {
if (g_n == g_cap) {
g_cap = g_cap ? g_cap * 2 : 32;
g_cheats = (Cheat *)realloc(g_cheats, sizeof *g_cheats * (size_t)g_cap);
if (!g_cheats) rt_fatal("cheats: out of memory");
}
Cheat *c = &g_cheats[g_n++];
memset(c, 0, sizeof *c);
line[len - 1] = 0;
char *name = line + 1;
while (*name == ' ' || *name == '\t') name++;
size_t k = strlen(name);
while (k && (name[k - 1] == ' ' || name[k - 1] == '\t')) name[--k] = 0;
c->info.name = strdup(name);
c->info.mod = mod;
c->info.kind = line[0] == '{' ? CHEAT_MASTER : CHEAT_HEADING;
c->set = -1;
c->dup = 1; // a repeated name gets "#2", "#3" ... (tools/cheats.py parse)
for (int j = first; j < g_n - 1; j++) c->dup += !strcmp(g_cheats[j].info.name, c->info.name);
wcap = 0;
} else if (g_n > first) {
for (char *tok = strtok(line, " \t"); tok; tok = strtok(NULL, " \t")) {
char *e;
unsigned long v = strtoul(tok, &e, 16);
if (e - tok == 8 && !*e) add_word(&g_cheats[g_n - 1], (uint32_t)v, &wcap);
}
}
line = next;
}
}
// The file g_file in folder, its name in any case, into out; 0 when there is none.
typedef struct {
const char *dir;
char *out;
size_t cap;
int found;
} FindFile;
static int find_cb(const char *name, int kind, uint64_t size, void *ctx) {
(void)size;
FindFile *f = (FindFile *)ctx;
if (kind == PLAT_FS_FILE && !strcasecmp(name, g_file) &&
snprintf(f->out, f->cap, "%s/%s", f->dir, name) < (int)f->cap)
f->found = 1;
return !f->found;
}
static int find_file(const char *folder, char *out, size_t cap) {
FindFile f = {folder, out, cap, 0};
plat_fs_list(folder, find_cb, &f);
return f.found;
}
// The status line of key, its fields split in place; 0 when none.
static int status_of(char *status, const char *key, char **fields) {
for (char *line = status; line && *line;) {
char *end = strchr(line, '\n'), *next = end ? end + 1 : NULL;
if (!strncmp(line, key, 8) && line[8] == '\t') {
static char copy[512];
size_t n = end ? (size_t)(end - line) : strlen(line);
if (n >= sizeof copy) n = sizeof copy - 1;
memcpy(copy, line, n);
copy[n] = 0;
if (n && copy[n - 1] == '\r') copy[n - 1] = 0;
int k = 0;
fields[k++] = copy;
for (char *p = copy; *p && k < 5; p++)
if (*p == '\t') *p = 0, fields[k++] = p + 1;
while (k < 5) fields[k++] = (char *)"";
return 1;
}
line = next;
}
return 0;
}
// The menu's font has no numero sign (U+2116), which cheat names often start with: they show "No" instead.
static void plain_name(char *s) {
for (char *p; (p = strstr(s, "\xE2\x84\x96")) != NULL;) {
p[0] = 'N', p[1] = 'o';
memmove(p + 2, p + 3, strlen(p + 3) + 1);
}
}
// ---- rebuild: code cheats and ExeFS patches the build lacks
// The setup writes build-cache\rebuild.txt (installer/steps.py write_rebuild_command), the command that starts its
// window in rebuild mode on this install folder, one argument per line. When an enabled mod has code cheats this build
// lacks (CHEAT_REBUILD) or ExeFS patch files it lacks (mods_exefs_pending), the game runs it and exits; the setup lifts
// and compiles them in and starts the game again.
// build-cache\rebuild.skip holds the key of the cheats a rebuild was started for: a rebuild that failed or was
// cancelled leaves them unbuilt, and the same set does not start it again. TOTK_MODS_REBUILD=off never starts it.
// Scripted runs (--seconds, --boot) never start it.
static void rebuild_if_needed(const char *dir) {
uint32_t key = 0x811C9DC5u;
int need = 0;
for (int i = 0; i < g_n; i++) {
const Cheat *c = &g_cheats[i];
if (c->info.kind != CHEAT_REBUILD) continue;
need++;
key = (key ^ fnv(c->info.key, strlen(c->info.key))) * 0x01000193u;
key = (key ^ c->content) * 0x01000193u;
}
int patches = mods_exefs_pending(&key);
if (!need && !patches) return;
char cmd_path[PLAT_PATH_MAX + 64], skip_path[PLAT_PATH_MAX + 64], skip[16] = "", want[16];
snprintf(cmd_path, sizeof cmd_path, "%sbuild-cache" SEP "rebuild.txt", dir);
snprintf(skip_path, sizeof skip_path, "%sbuild-cache" SEP "rebuild.skip", dir);
snprintf(want, sizeof want, "%08X", key);
char *old = read_text(skip_path);
if (old) snprintf(skip, sizeof skip, "%.8s", old);
free(old);
const char *why = !strcmp(cfg_value("TOTK_MODS_REBUILD"), "off") ? "mods_rebuild = off"
: rt_config()->seconds || rt_config()->boot ? "a scripted run"
: !strcmp(skip, want) ? "the last rebuild for them failed or was cancelled"
: NULL;
char *cmd = why ? NULL : read_text(cmd_path);
if (!why && !cmd) why = "no build-cache/rebuild.txt (a build without the setup)";
if (why) {
rt_log("cheats: %d code cheats and %d ExeFS patch files are not built into the game; no rebuild: %s", need,
patches, why);
free(cmd);
return;
}
const char *argv[32];
int argc = 0;
for (char *line = cmd; line && *line && argc < 31;) {
char *end = strchr(line, '\n'), *next = end ? end + 1 : NULL;
if (end) *end = 0;
size_t n = strlen(line);
if (n && line[n - 1] == '\r') line[n - 1] = 0;
if (*line) argv[argc++] = line;
line = next;
}
argv[argc] = NULL;
if (argc < 2 || !plat_file_write(skip_path, want, strlen(want))) {
rt_log("cheats: %d code cheats and %d ExeFS patch files are not built into the game; cannot start the "
"rebuild (%s)", need, patches, cmd_path);
free(cmd);
return;
}
rt_log("cheats: %d code cheats and %d ExeFS patch files are not built into the game; starting the rebuild: %s",
need, patches, argv[0]);
int ok = plat_spawn(argv, dir);
free(cmd);
if (!ok) {
rt_log("cheats: the rebuild did not start; the game starts with the code it has");
return;
}
prof_write(); // plat_exit runs no atexit handlers
plat_exit(0);
}
void cheats_init(void) {
const RtLoaded *m = ldr_count() ? ldr_module(0) : NULL;
char dir[PLAT_PATH_MAX], bid[17], path[2400]; // path: a mod's cheats folder (ModInfo.cheats) + the file
if (!m || !exe_dir(dir, sizeof dir) || !build_id(bid)) return;
snprintf(g_dir, sizeof g_dir, "%s", dir);
g_main = m->base;
g_main_size = m->size;
g_code_end = m->base + ((m->text_end + 0xFFF) & ~0xFFFull);
snprintf(g_file, sizeof g_file, "%s.txt", bid);
mods_scan();
for (int k = 0; k < mods_count(); k++) { // the Mods tab's order, top first
const ModInfo *mod = mods_at(k);
if (!mod->enabled || mod->problem != MOD_OK || !mod->cheats[0] || !find_file(mod->cheats, path, sizeof path))
continue;
char *text = read_text(path);
if (!text) {
rt_log("cheats: %s: cannot read %s", mod->name, path);
continue;
}
parse(text, strdup(mod->name));
free(text);
g_files++;
}
if (!g_files) {
rt_log("cheats: no enabled mod holds cheats/%s", g_file);
rebuild_if_needed(dir); // an enabled mod's ExeFS patches may still wait for it
return;
}
snprintf(path, sizeof path, "%sbuild-cache" SEP "cheats.status", dir);
char *status = read_text(path);
int counts[CHEAT_UNSUPPORTED + 1] = {0}, seen_dups = 0;
for (int i = 0; i < g_n; i++) {
Cheat *c = &g_cheats[i];
char named[900];
snprintf(named, sizeof named, c->dup > 1 ? "%s/%s#%d" : "%s/%s", c->info.mod, c->info.name, c->dup);
seen_dups += c->dup > 1;
char key[9], content[9];
snprintf(key, sizeof key, "%08X", fnv(named, strlen(named)));
size_t tn = (size_t)c->n * 9 + 1, tl = 0;
char *t = (char *)malloc(tn);
if (!t) rt_fatal("cheats: out of memory");
t[0] = 0;
for (int k = 0; k < c->n; k++) tl += (size_t)snprintf(t + tl, tn - tl, k ? " %08X" : "%08X", c->words[k]);
c->content = fnv(t, tl);
snprintf(content, sizeof content, "%08X", c->content);
free(t);
snprintf(c->info.key, sizeof c->info.key, "TOTK_CHEAT_%s", key);
int master = c->info.kind == CHEAT_MASTER;
char *f[5];
CheatKind kind;
if (status && status_of(status, key, f) && !strcmp(f[1], content)) {
const char *k = f[2];
kind = !strcmp(k, "code") ? CHEAT_CODE : !strcmp(k, "key") ? CHEAT_KEY : !strcmp(k, "master") ? CHEAT_MASTER
: !strcmp(k, "restore") ? CHEAT_RESTORE : !strcmp(k, "heading") ? CHEAT_HEADING
: !strcmp(k, "data") ? CHEAT_DATA : CHEAT_UNSUPPORTED;
c->info.buttons = (uint32_t)strtoul(f[3], NULL, 16);
snprintf(c->note, sizeof c->note, "%s", f[4]);
if (kind == CHEAT_CODE || kind == CHEAT_KEY || kind == CHEAT_MASTER) {
char set[32];
snprintf(set, sizeof set, "cheat_%08x", fnv(named, strlen(named)));
c->set = rt_patch_set(set);
if (c->set < 0 && kind != CHEAT_MASTER) kind = CHEAT_REBUILD;
}
} else {
kind = classify(c);
}
if (master && kind == CHEAT_DATA) kind = CHEAT_MASTER; // a data master code: the VM, always on
c->info.kind = kind;
c->info.note = c->note;
const char *v = cfg_get(c->info.key);
c->on = kind == CHEAT_MASTER || (v && *v && strcmp(v, "0") != 0);
if (kind == CHEAT_KEY && c->set >= 0) rt_patch_switch(c->set, 0); // on while the buttons are held
if (kind == CHEAT_KEY || kind == CHEAT_DATA || (kind == CHEAT_MASTER && c->set < 0)) g_vm = 1;
counts[kind]++;
}
free(status);
rebuild_if_needed(dir);
for (int i = 0; i < g_n; i++) plain_name((char *)g_cheats[i].info.name); // the hashes above read the file's bytes
int on = 0;
for (int i = 0; i < g_n; i++) on += g_cheats[i].on && g_cheats[i].info.kind != CHEAT_HEADING;
rt_log("cheats: %s in %d mods: %d cheats, %d on; %d code, %d while buttons are held, %d data, %d master, "
"%d restore, %d headings, %d wait for a rebuild, %d not supported%s",
g_file, g_files, g_n, on, counts[CHEAT_CODE], counts[CHEAT_KEY], counts[CHEAT_DATA], counts[CHEAT_MASTER],
counts[CHEAT_RESTORE], counts[CHEAT_HEADING], counts[CHEAT_REBUILD], counts[CHEAT_UNSUPPORTED],
seen_dups ? " (repeated names numbered)" : "");
}
int cheats_rebuild_pending(void) {
char path[PLAT_PATH_MAX + 64];
snprintf(path, sizeof path, "%sbuild-cache" SEP "rebuild.txt", g_dir);
uint32_t key = 0;
int need = mods_exefs_pending(&key);
for (int i = 0; i < g_n && !need; i++) need = g_cheats[i].info.kind == CHEAT_REBUILD;
return need && g_dir[0] && plat_file_exists(path);
}
void cheats_rebuild_allow(void) {
char path[PLAT_PATH_MAX + 64];
snprintf(path, sizeof path, "%sbuild-cache" SEP "rebuild.skip", g_dir);
plat_fs_unlink(path);
}
int cheats_count(void) { return g_n; }
const CheatInfo *cheats_info(int i) { return i >= 0 && i < g_n ? &g_cheats[i].info : NULL; }
int cheats_on(int i) { return i >= 0 && i < g_n && g_cheats[i].on; }
const char *cheats_file(void) { return g_file; }
void cheats_set(int i, int on) {
if (i < 0 || i >= g_n) return;
Cheat *c = &g_cheats[i];
if (c->info.kind != CHEAT_CODE && c->info.kind != CHEAT_KEY && c->info.kind != CHEAT_DATA) return;
plat_xchg32(&c->on, on != 0);
if (c->info.kind == CHEAT_CODE) rt_patch_switch(c->set, on); // CHEAT_KEY: cheats_frame follows the buttons
cfg_set(c->info.key, on ? "1" : "0");
rt_log("cheats: %s/%s %s", c->info.mod, c->info.name, on ? "on" : "off");
}
void cheats_frame(uint64_t frame) {
if (!g_vm || frame < 60) return; // the game polls its input (and starts SDL) before this
uint64_t keys = 0;
int32_t lx, ly, rx, ry;
input_poll(&keys, &lx, &ly, &rx, &ry); // 0 while the menu is open
for (int i = 0; i < g_n; i++) {
Cheat *c = &g_cheats[i];
switch (c->info.kind) {
case CHEAT_KEY:
if (c->set >= 0) {
int want = c->on && (keys & c->info.buttons) == c->info.buttons;
if (rt_patch_enabled(c->set) != want) rt_patch_switch(c->set, want);
}
break;
case CHEAT_DATA:
if (c->on) run(c, keys);
break;
case CHEAT_MASTER:
if (c->set < 0) run(c, keys);
break;
default:
break;
}
}
}
const char *cheats_buttons(uint32_t mask, char *buf, int n) {
static const char *const names[] = {"A", "B", "X", "Y", "Left stick press", "Right stick press", "L", "R", "ZL",
"ZR", "+", "-", "D-pad left", "D-pad up", "D-pad right", "D-pad down",
"Left stick left", "Left stick up", "Left stick right", "Left stick down",
"Right stick left", "Right stick up", "Right stick right", "Right stick down"};
int k = 0;
buf[0] = 0;
for (int b = 0; b < 24; b++)
if (mask & (1u << b)) k += snprintf(buf + k, (size_t)(n > k ? n - k : 0), "%s%s", k ? " + " : "", names[b]);
return buf;
}
+48
View File
@@ -0,0 +1,48 @@
// Cheats of the mods' Atmosphere cheat files (cheats.c): mods\<mod>\cheats\<build id>.txt of each enabled mod,
// switched from the menu's Cheats tab. A cheat that writes the game's instructions is a code patch set that tools/cheats.py built into the game
// (switched with rt_patch_switch); one that writes data runs in the cheat VM every presented frame.
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
CHEAT_HEADING, // no opcodes: a title or a group label
CHEAT_CODE, // a patch set
CHEAT_KEY, // a patch set on while the buttons are held
CHEAT_DATA, // the cheat VM
CHEAT_MASTER, // {master}: always on
CHEAT_RESTORE, // writes the original instructions back: nothing to do
CHEAT_REBUILD, // writes instructions, but the game was built without this version of it
CHEAT_UNSUPPORTED, // note says why
} CheatKind;
typedef struct {
const char *name; // UTF-8, as in the file
const char *mod; // the mod's folder name; cheats come grouped by mod, in the Mods tab's order
const char *note; // why it is unsupported ("" otherwise)
CheatKind kind;
uint32_t buttons; // CHEAT_KEY: HidNpadButton mask
char key[24]; // its setting, TOTK_CHEAT_<hash of "<mod>/<name>">
} CheatInfo;
void cheats_init(void); // after rt_patches_init: reads the mods' files and their build status
int cheats_count(void);
// 1 when a cheat of an enabled mod waits for a rebuild (CHEAT_REBUILD) and the setup left its rebuild command.
int cheats_rebuild_pending(void);
// The next start rebuilds again for cheats whose last rebuild failed or was cancelled (the menu restarts after it).
void cheats_rebuild_allow(void);
const CheatInfo *cheats_info(int i);
int cheats_on(int i); // the player's switch (1 for a master cheat)
void cheats_set(int i, int on); // switches at once and sets the cheat's setting (the menu saves totk.ini)
const char *cheats_file(void); // "<build id>.txt", the name the files have for this game version
// Every presented frame (the present path): the data cheats' VM and the button state of CHEAT_KEY cheats.
void cheats_frame(uint64_t frame);
// The button names of a mask ("ZL + Right stick left"), into buf.
const char *cheats_buttons(uint32_t mask, char *buf, int n);
#ifdef __cplusplus
}
#endif
+156
View File
@@ -0,0 +1,156 @@
// Generated by tools/build_shaders.py from runtime/shaders/contact_shadow.comp; do not edit.
// source sha256 b452a1920e59c4d83b2c994b0c6573cc1e479f7032a1310a7432d11c5c2e9908
#pragma once
#include <stdint.h>
static const uint32_t contact_shadow_spv[] = {
0x07230203, 0x00010300, 0x000d000b, 0x000001b1, 0x00000000, 0x00020011, 0x00000001, 0x00020011,
0x00000031, 0x0006000b, 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e,
0x00000000, 0x00000001, 0x0006000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x00000069,
0x00060010, 0x00000004, 0x00000011, 0x00000008, 0x00000008, 0x00000001, 0x00030047, 0x00000027,
0x00000002, 0x00050048, 0x00000027, 0x00000000, 0x00000023, 0x00000000, 0x00050048, 0x00000027,
0x00000001, 0x00000023, 0x00000010, 0x00050048, 0x00000027, 0x00000002, 0x00000023, 0x00000020,
0x00050048, 0x00000027, 0x00000003, 0x00000023, 0x00000030, 0x00040047, 0x00000069, 0x0000000b,
0x0000001c, 0x00040047, 0x00000088, 0x00000021, 0x00000000, 0x00040047, 0x00000088, 0x00000022,
0x00000000, 0x00040047, 0x0000013f, 0x00000021, 0x00000001, 0x00040047, 0x0000013f, 0x00000022,
0x00000000, 0x00040047, 0x0000015c, 0x0000000b, 0x00000019, 0x00020013, 0x00000002, 0x00030021,
0x00000003, 0x00000002, 0x00030016, 0x00000006, 0x00000020, 0x00040017, 0x00000007, 0x00000006,
0x00000002, 0x00040017, 0x0000000a, 0x00000006, 0x00000003, 0x0004002b, 0x00000006, 0x0000001b,
0x40000000, 0x0004002b, 0x00000006, 0x0000001d, 0x3f800000, 0x00040015, 0x00000020, 0x00000020,
0x00000000, 0x0004002b, 0x00000020, 0x00000021, 0x00000000, 0x00040017, 0x00000026, 0x00000006,
0x00000004, 0x0006001e, 0x00000027, 0x00000026, 0x00000026, 0x00000026, 0x00000026, 0x00040020,
0x00000028, 0x00000009, 0x00000027, 0x0004003b, 0x00000028, 0x00000029, 0x00000009, 0x00040015,
0x0000002a, 0x00000020, 0x00000001, 0x0004002b, 0x0000002a, 0x0000002b, 0x00000000, 0x00040020,
0x0000002c, 0x00000009, 0x00000006, 0x0004002b, 0x00000020, 0x00000030, 0x00000001, 0x0004002b,
0x00000020, 0x0000003f, 0x00000002, 0x0004002b, 0x00000006, 0x00000043, 0x3f000000, 0x0004002b,
0x00000006, 0x00000059, 0x4253ee82, 0x0004002b, 0x00000006, 0x0000005b, 0x3d897143, 0x0004002b,
0x00000006, 0x0000005c, 0x3bbf4590, 0x0005002c, 0x00000007, 0x0000005d, 0x0000005b, 0x0000005c,
0x00040017, 0x00000064, 0x0000002a, 0x00000002, 0x00040017, 0x00000067, 0x00000020, 0x00000003,
0x00040020, 0x00000068, 0x00000001, 0x00000067, 0x0004003b, 0x00000068, 0x00000069, 0x00000001,
0x00040017, 0x0000006a, 0x00000020, 0x00000002, 0x00020014, 0x0000006e, 0x0004002b, 0x0000002a,
0x00000072, 0x00000002, 0x00090019, 0x00000085, 0x00000006, 0x00000001, 0x00000000, 0x00000000,
0x00000000, 0x00000001, 0x00000000, 0x0003001b, 0x00000086, 0x00000085, 0x00040020, 0x00000087,
0x00000000, 0x00000086, 0x0004003b, 0x00000087, 0x00000088, 0x00000000, 0x0004002b, 0x00000006,
0x0000008f, 0x00000000, 0x0004002b, 0x00000006, 0x00000092, 0x3f7fbe77, 0x0004002b, 0x00000006,
0x0000009e, 0x42a00000, 0x00040020, 0x000000a8, 0x00000009, 0x00000026, 0x0004002b, 0x0000002a,
0x000000b4, 0x00000001, 0x0004002b, 0x00000020, 0x000000b5, 0x00000003, 0x0004002b, 0x00000006,
0x000000bb, 0x3ecccccd, 0x0004002b, 0x00000006, 0x000000bc, 0x40400000, 0x0004002b, 0x00000006,
0x000000c0, 0x3e19999a, 0x0004002b, 0x00000006, 0x000000c2, 0x3c23d70a, 0x0004002b, 0x00000006,
0x000000cb, 0x3e800000, 0x0004002b, 0x0000002a, 0x000000da, 0x00000010, 0x0004002b, 0x00000006,
0x000000e6, 0xbd4ccccd, 0x0005002c, 0x00000007, 0x000000f0, 0x0000008f, 0x0000008f, 0x00040017,
0x000000f1, 0x0000006e, 0x00000002, 0x0005002c, 0x00000007, 0x000000f8, 0x0000001d, 0x0000001d,
0x0004002b, 0x00000006, 0x00000114, 0x3ca3d70a, 0x0004002b, 0x00000006, 0x00000116, 0x3b03126f,
0x0004002b, 0x00000006, 0x0000012b, 0x42200000, 0x0004002b, 0x0000002a, 0x00000137, 0x00000003,
0x00090019, 0x0000013d, 0x00000006, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000002,
0x00000008, 0x00040020, 0x0000013e, 0x00000000, 0x0000013d, 0x0004003b, 0x0000013e, 0x0000013f,
0x00000000, 0x0004002b, 0x00000020, 0x0000015b, 0x00000008, 0x0006002c, 0x00000067, 0x0000015c,
0x0000015b, 0x0000015b, 0x00000030, 0x0005002c, 0x00000007, 0x000001ad, 0x00000043, 0x00000043,
0x0004002b, 0x00000006, 0x000001af, 0x3dcccccd, 0x0004002b, 0x00000006, 0x000001b0, 0x3d800000,
0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x000300f7,
0x0000015d, 0x00000000, 0x000300fb, 0x00000021, 0x0000015e, 0x000200f8, 0x0000015e, 0x0004003d,
0x00000067, 0x0000006b, 0x00000069, 0x0007004f, 0x0000006a, 0x0000006c, 0x0000006b, 0x0000006b,
0x00000000, 0x00000001, 0x0004007c, 0x00000064, 0x0000006d, 0x0000006c, 0x00050051, 0x0000002a,
0x00000071, 0x0000006d, 0x00000000, 0x00060041, 0x0000002c, 0x00000073, 0x00000029, 0x00000072,
0x00000021, 0x0004003d, 0x00000006, 0x00000074, 0x00000073, 0x0004006e, 0x0000002a, 0x00000075,
0x00000074, 0x000500af, 0x0000006e, 0x00000076, 0x00000071, 0x00000075, 0x000400a8, 0x0000006e,
0x00000077, 0x00000076, 0x000300f7, 0x00000079, 0x00000000, 0x000400fa, 0x00000077, 0x00000078,
0x00000079, 0x000200f8, 0x00000078, 0x00050051, 0x0000002a, 0x0000007b, 0x0000006d, 0x00000001,
0x00060041, 0x0000002c, 0x0000007c, 0x00000029, 0x00000072, 0x00000030, 0x0004003d, 0x00000006,
0x0000007d, 0x0000007c, 0x0004006e, 0x0000002a, 0x0000007e, 0x0000007d, 0x000500af, 0x0000006e,
0x0000007f, 0x0000007b, 0x0000007e, 0x000200f9, 0x00000079, 0x000200f8, 0x00000079, 0x000700f5,
0x0000006e, 0x00000080, 0x00000076, 0x0000015e, 0x0000007f, 0x00000078, 0x000300f7, 0x00000082,
0x00000000, 0x000400fa, 0x00000080, 0x00000081, 0x00000082, 0x000200f8, 0x00000081, 0x000200f9,
0x0000015d, 0x000200f8, 0x00000082, 0x0004003d, 0x00000086, 0x00000089, 0x00000088, 0x00040064,
0x00000085, 0x0000008b, 0x00000089, 0x0007005f, 0x00000026, 0x0000008c, 0x0000008b, 0x0000006d,
0x00000002, 0x0000002b, 0x00050051, 0x00000006, 0x0000008d, 0x0000008c, 0x00000000, 0x000500bc,
0x0000006e, 0x00000090, 0x0000008d, 0x0000008f, 0x000500be, 0x0000006e, 0x00000093, 0x0000008d,
0x00000092, 0x000500a6, 0x0000006e, 0x00000094, 0x00000090, 0x00000093, 0x000300f7, 0x00000096,
0x00000000, 0x000400fa, 0x00000094, 0x00000095, 0x00000096, 0x000200f8, 0x00000095, 0x000200f9,
0x0000015d, 0x000200f8, 0x00000096, 0x00060041, 0x0000002c, 0x0000009a, 0x00000029, 0x0000002b,
0x0000003f, 0x0004003d, 0x00000006, 0x0000009b, 0x0000009a, 0x00050085, 0x00000006, 0x0000009c,
0x0000008d, 0x0000009b, 0x000500ba, 0x0000006e, 0x0000009f, 0x0000009c, 0x0000009e, 0x000300f7,
0x000000a1, 0x00000000, 0x000400fa, 0x0000009f, 0x000000a0, 0x000000a1, 0x000200f8, 0x000000a0,
0x000200f9, 0x0000015d, 0x000200f8, 0x000000a1, 0x0004006f, 0x00000007, 0x000000a5, 0x0000006d,
0x00050081, 0x00000007, 0x000000a7, 0x000000a5, 0x000001ad, 0x00050041, 0x000000a8, 0x000000a9,
0x00000029, 0x00000072, 0x0004003d, 0x00000026, 0x000000aa, 0x000000a9, 0x0007004f, 0x00000007,
0x000000ab, 0x000000aa, 0x000000aa, 0x00000002, 0x00000003, 0x00050085, 0x00000007, 0x000000ac,
0x000000a7, 0x000000ab, 0x0005008e, 0x00000007, 0x00000167, 0x000000ac, 0x0000001b, 0x00050083,
0x00000007, 0x00000169, 0x00000167, 0x000000f8, 0x00050051, 0x00000006, 0x0000016b, 0x00000169,
0x00000000, 0x00050085, 0x00000006, 0x0000016d, 0x0000016b, 0x0000009c, 0x00060041, 0x0000002c,
0x0000016e, 0x00000029, 0x0000002b, 0x00000021, 0x0004003d, 0x00000006, 0x0000016f, 0x0000016e,
0x00050088, 0x00000006, 0x00000170, 0x0000016d, 0x0000016f, 0x00050051, 0x00000006, 0x00000172,
0x00000169, 0x00000001, 0x0004007f, 0x00000006, 0x00000173, 0x00000172, 0x00050085, 0x00000006,
0x00000175, 0x00000173, 0x0000009c, 0x00060041, 0x0000002c, 0x00000176, 0x00000029, 0x0000002b,
0x00000030, 0x0004003d, 0x00000006, 0x00000177, 0x00000176, 0x00050088, 0x00000006, 0x00000178,
0x00000175, 0x00000177, 0x0004007f, 0x00000006, 0x0000017a, 0x0000009c, 0x00060050, 0x0000000a,
0x0000017b, 0x00000170, 0x00000178, 0x0000017a, 0x00060041, 0x0000002c, 0x000000b6, 0x00000029,
0x000000b4, 0x000000b5, 0x0004003d, 0x00000006, 0x000000b7, 0x000000b6, 0x00050085, 0x00000006,
0x000000ba, 0x0000009c, 0x000001af, 0x0008000c, 0x00000006, 0x000000bd, 0x00000001, 0x0000002b,
0x000000ba, 0x000000bb, 0x000000bc, 0x00050085, 0x00000006, 0x000000be, 0x000000b7, 0x000000bd,
0x00050085, 0x00000006, 0x000000c3, 0x0000009c, 0x000000c2, 0x00050081, 0x00000006, 0x000000c4,
0x000000c0, 0x000000c3, 0x00050085, 0x00000006, 0x000000c8, 0x000000be, 0x000001b0, 0x00050094,
0x00000006, 0x0000017f, 0x000000a5, 0x0000005d, 0x0006000c, 0x00000006, 0x00000180, 0x00000001,
0x0000000a, 0x0000017f, 0x00050085, 0x00000006, 0x00000181, 0x00000059, 0x00000180, 0x0006000c,
0x00000006, 0x00000182, 0x00000001, 0x0000000a, 0x00000181, 0x00050081, 0x00000006, 0x000000d0,
0x000000cb, 0x00000182, 0x00050085, 0x00000006, 0x000000d1, 0x000000c8, 0x000000d0, 0x000200f9,
0x000000d4, 0x000200f8, 0x000000d4, 0x000700f5, 0x00000006, 0x000001a7, 0x000000d1, 0x000000a1,
0x00000129, 0x000000d7, 0x000700f5, 0x0000002a, 0x000001a6, 0x0000002b, 0x000000a1, 0x00000126,
0x000000d7, 0x000500b1, 0x0000006e, 0x000000db, 0x000001a6, 0x000000da, 0x000400f6, 0x000000d6,
0x000000d7, 0x00000000, 0x000400fa, 0x000000db, 0x000000d5, 0x000000d6, 0x000200f8, 0x000000d5,
0x00050041, 0x000000a8, 0x000000de, 0x00000029, 0x000000b4, 0x0004003d, 0x00000026, 0x000000df,
0x000000de, 0x0008004f, 0x0000000a, 0x000000e0, 0x000000df, 0x000000df, 0x00000000, 0x00000001,
0x00000002, 0x0005008e, 0x0000000a, 0x000000e2, 0x000000e0, 0x000001a7, 0x00050081, 0x0000000a,
0x000000e3, 0x0000017b, 0x000000e2, 0x00050051, 0x00000006, 0x000000e5, 0x000000e3, 0x00000002,
0x000500be, 0x0000006e, 0x000000e7, 0x000000e5, 0x000000e6, 0x000300f7, 0x000000e9, 0x00000000,
0x000400fa, 0x000000e7, 0x000000e8, 0x000000e9, 0x000200f8, 0x000000e8, 0x000200f9, 0x000000d6,
0x000200f8, 0x000000e9, 0x0004007f, 0x00000006, 0x00000188, 0x000000e5, 0x00050051, 0x00000006,
0x0000018a, 0x000000e3, 0x00000000, 0x00050085, 0x00000006, 0x0000018b, 0x00000043, 0x0000018a,
0x00050085, 0x00000006, 0x0000018e, 0x0000018b, 0x0000016f, 0x00050088, 0x00000006, 0x00000190,
0x0000018e, 0x00000188, 0x00050081, 0x00000006, 0x00000191, 0x00000043, 0x00000190, 0x00050051,
0x00000006, 0x00000193, 0x000000e3, 0x00000001, 0x00050085, 0x00000006, 0x00000194, 0x00000043,
0x00000193, 0x00050085, 0x00000006, 0x00000197, 0x00000194, 0x00000177, 0x00050088, 0x00000006,
0x00000199, 0x00000197, 0x00000188, 0x00050083, 0x00000006, 0x0000019a, 0x00000043, 0x00000199,
0x00050050, 0x00000007, 0x0000019b, 0x00000191, 0x0000019a, 0x000500b8, 0x000000f1, 0x000000f2,
0x0000019b, 0x000000f0, 0x0004009a, 0x0000006e, 0x000000f3, 0x000000f2, 0x000400a8, 0x0000006e,
0x000000f4, 0x000000f3, 0x000300f7, 0x000000f6, 0x00000000, 0x000400fa, 0x000000f4, 0x000000f5,
0x000000f6, 0x000200f8, 0x000000f5, 0x000500ba, 0x000000f1, 0x000000f9, 0x0000019b, 0x000000f8,
0x0004009a, 0x0000006e, 0x000000fa, 0x000000f9, 0x000200f9, 0x000000f6, 0x000200f8, 0x000000f6,
0x000700f5, 0x0000006e, 0x000000fb, 0x000000f3, 0x000000e9, 0x000000fa, 0x000000f5, 0x000300f7,
0x000000fd, 0x00000000, 0x000400fa, 0x000000fb, 0x000000fc, 0x000000fd, 0x000200f8, 0x000000fc,
0x000200f9, 0x000000d6, 0x000200f8, 0x000000fd, 0x0004003d, 0x00000086, 0x00000100, 0x00000088,
0x0007004f, 0x00000007, 0x00000104, 0x000000aa, 0x000000aa, 0x00000000, 0x00000001, 0x00050085,
0x00000007, 0x00000105, 0x0000019b, 0x00000104, 0x0004006e, 0x00000064, 0x00000106, 0x00000105,
0x00040064, 0x00000085, 0x00000107, 0x00000100, 0x0007005f, 0x00000026, 0x00000108, 0x00000107,
0x00000106, 0x00000002, 0x0000002b, 0x00050051, 0x00000006, 0x00000109, 0x00000108, 0x00000000,
0x00050085, 0x00000006, 0x0000010c, 0x00000109, 0x0000009b, 0x00050083, 0x00000006, 0x00000112,
0x00000188, 0x0000010c, 0x00050085, 0x00000006, 0x00000117, 0x0000009c, 0x00000116, 0x00050081,
0x00000006, 0x00000118, 0x00000114, 0x00000117, 0x000500ba, 0x0000006e, 0x00000119, 0x00000112,
0x00000118, 0x000500b8, 0x0000006e, 0x0000011c, 0x00000112, 0x000000c4, 0x000500a7, 0x0000006e,
0x0000011d, 0x00000119, 0x0000011c, 0x000300f7, 0x0000011f, 0x00000000, 0x000400fa, 0x0000011d,
0x0000011e, 0x0000011f, 0x000200f8, 0x0000011e, 0x0004006f, 0x00000006, 0x00000121, 0x000001a6,
0x00050085, 0x00000006, 0x00000122, 0x00000121, 0x000001b0, 0x00050083, 0x00000006, 0x00000123,
0x0000001d, 0x00000122, 0x000200f9, 0x000000d6, 0x000200f8, 0x0000011f, 0x000200f9, 0x000000d7,
0x000200f8, 0x000000d7, 0x00050080, 0x0000002a, 0x00000126, 0x000001a6, 0x000000b4, 0x00050081,
0x00000006, 0x00000129, 0x000001a7, 0x000000c8, 0x000200f9, 0x000000d4, 0x000200f8, 0x000000d6,
0x000b00f5, 0x00000006, 0x000001aa, 0x0000008f, 0x000000d4, 0x0000008f, 0x000000e8, 0x0000008f,
0x000000fc, 0x00000123, 0x0000011e, 0x0008000c, 0x00000006, 0x0000012d, 0x00000001, 0x00000031,
0x0000012b, 0x0000009e, 0x0000009c, 0x00050083, 0x00000006, 0x0000012e, 0x0000001d, 0x0000012d,
0x00060041, 0x0000002c, 0x00000130, 0x00000029, 0x0000002b, 0x000000b5, 0x0004003d, 0x00000006,
0x00000131, 0x00000130, 0x00050085, 0x00000006, 0x00000133, 0x00000131, 0x000001aa, 0x00050085,
0x00000006, 0x00000135, 0x00000133, 0x0000012e, 0x00050083, 0x00000006, 0x00000136, 0x0000001d,
0x00000135, 0x00060041, 0x0000002c, 0x00000138, 0x00000029, 0x00000137, 0x00000021, 0x0004003d,
0x00000006, 0x00000139, 0x00000138, 0x000500ba, 0x0000006e, 0x0000013a, 0x00000139, 0x00000043,
0x000300f7, 0x0000013c, 0x00000000, 0x000400fa, 0x0000013a, 0x0000013b, 0x0000013c, 0x000200f8,
0x0000013b, 0x0004003d, 0x0000013d, 0x00000140, 0x0000013f, 0x00070050, 0x00000026, 0x00000143,
0x00000136, 0x00000136, 0x00000136, 0x0000001d, 0x00040063, 0x00000140, 0x0000006d, 0x00000143,
0x000200f9, 0x0000015d, 0x000200f8, 0x0000013c, 0x000500be, 0x0000006e, 0x00000146, 0x00000136,
0x00000092, 0x000300f7, 0x00000148, 0x00000000, 0x000400fa, 0x00000146, 0x00000147, 0x00000148,
0x000200f8, 0x00000147, 0x000200f9, 0x0000015d, 0x000200f8, 0x00000148, 0x0004003d, 0x0000013d,
0x0000014c, 0x0000013f, 0x00050062, 0x00000026, 0x0000014e, 0x0000014c, 0x0000006d, 0x0004003d,
0x0000013d, 0x0000014f, 0x0000013f, 0x0008004f, 0x0000000a, 0x00000152, 0x0000014e, 0x0000014e,
0x00000000, 0x00000001, 0x00000002, 0x0005008e, 0x0000000a, 0x00000154, 0x00000152, 0x00000136,
0x00050051, 0x00000006, 0x00000156, 0x0000014e, 0x00000003, 0x00050051, 0x00000006, 0x00000157,
0x00000154, 0x00000000, 0x00050051, 0x00000006, 0x00000158, 0x00000154, 0x00000001, 0x00050051,
0x00000006, 0x00000159, 0x00000154, 0x00000002, 0x00070050, 0x00000026, 0x0000015a, 0x00000157,
0x00000158, 0x00000159, 0x00000156, 0x00040063, 0x0000014f, 0x0000006d, 0x0000015a, 0x000200f9,
0x0000015d, 0x000200f8, 0x0000015d, 0x000100fd, 0x00010038,
};
+1 -1
View File
@@ -109,7 +109,7 @@ EXCL(16, uint16_t)
EXCL(32, uint32_t)
EXCL(64, uint64_t)
// Exclusive pair of two X registers: one 16-byte-aligned 128-bit access (cmpxchg16b; x86-64-v3 has CX16).
// Exclusive pair of two X registers: one 16-byte-aligned 128-bit access (cmpxchg16b; x86-64-v2 has CX16).
// A pair of two W registers is a 64-bit exclusive and uses ldx64/stx64.
static inline __uint128_t ldxp128(Cpu *c, uint64_t a) {
__uint128_t v = __atomic_load_n((__uint128_t *)(uintptr_t)a, __ATOMIC_ACQUIRE);
+259
View File
@@ -0,0 +1,259 @@
// Discord Rich Presence: "Playing TotK Recomp" with the elapsed play time in the player's Discord status, through
// the local IPC of a running Discord client (platform.h's plat_ipc_*). Nothing leaves the machine but the activity
// itself, and nothing is sent while TOTK_DISCORD_RPC is off (the default: the status is information about the
// player's session). TOTK_DISCORD_APP_ID names the application whose name and artwork Discord shows — the default
// is the project's own application, registered as "TotK Recomp"; a player who wants their own name or
// art registers an application at discord.com/developers and puts its id in totk.ini — and TOTK_DISCORD_IMAGE the
// key of its uploaded art asset.
//
// One host thread owns the connection and never holds a virtual core (kernel.c: host work runs without one). It
// re-reads the settings when cfg_version changes (a menu change reaches it within half a second), connects to the
// first of Discord's discord-ipc-0..9 pipes that answers, and writes the activity again every 60 s: that write is
// the keep-alive, and one that fails closes the connection and tries again 15 s later. Discord clears the status by
// itself when the process ends and the pipe closes, so there is no shutdown path. Every answer frame is read and
// discarded: unread, they would fill the pipe's buffer and block the client's writes.
//
// The protocol is the documented IPC one (discord-rpc's src/rpc_connection.h): a frame is <opcode u32 little
// endian><length u32><length bytes of JSON>, with Handshake 0, Frame 1, Close 2, Ping 3 and Pong 4. The handshake
// (opcode 0) carries {"v":1,"client_id":...} and is answered by a Ready frame (opcode 1); every command,
// SET_ACTIVITY here, is a frame (opcode 1) answered by one, and a Ping the client sends is echoed as a Pong. A
// client that speaks another numbering (an early arRPC did) answers the handshake with a Close. --probe-discord
// runs the same exchange once, without the game and without the setting being on.
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cfg.h"
#include "host.h"
#include "platform/platform.h"
enum { OP_HANDSHAKE = 0, OP_FRAME = 1, OP_CLOSE = 2, OP_PING = 3, OP_PONG = 4 };
#define APP_ID_CAP 24 // a Discord snowflake: at most 20 digits
#define IMAGE_KEY_CAP 64
#define ANSWER_CAP 8192 // the Ready frame carries the client's config; a few KiB
// A settings value that fits the JSON below without escaping: the app id is digits, an asset key letters, digits,
// '_' and '-' (what Discord's developer portal accepts for an asset key).
static int valid_app_id(const char *s) {
size_t n = strlen(s);
if (!n || n > 20) return 0;
for (const char *p = s; *p; p++)
if (*p < '0' || *p > '9') return 0;
return 1;
}
static int valid_image_key(const char *s) {
size_t n = strlen(s);
if (!n || n >= IMAGE_KEY_CAP) return 0;
for (const char *p = s; *p; p++)
if ((*p < 'a' || *p > 'z') && (*p < 'A' || *p > 'Z') && (*p < '0' || *p > '9') && *p != '_' && *p != '-')
return 0;
return 1;
}
// The setting's value, or its default when the value does not fit the protocol (logged: the player sees why their
// own app does not show). Called on the presence thread and by the probe, after cfg_version changed or once.
static void read_setting(const char *name, char *out, size_t cap, int (*valid)(const char *)) {
const char *v = cfg_value(name);
if (valid(v)) {
snprintf(out, cap, "%s", v);
return;
}
snprintf(out, cap, "%s", cfg_meta(name)->def);
rt_log("discord: %s does not fit what the Rich Presence protocol takes; using %s", name + strlen("TOTK_"), out);
}
static void le32(uint8_t *at, uint32_t v) {
at[0] = (uint8_t)v, at[1] = (uint8_t)(v >> 8), at[2] = (uint8_t)(v >> 16), at[3] = (uint8_t)(v >> 24);
}
static int write_frame(PlatIpc *p, uint32_t op, const char *json) {
uint8_t head[8];
le32(head, op);
le32(head + 4, (uint32_t)strlen(json));
return plat_ipc_write(p, head, sizeof head) && plat_ipc_write(p, json, strlen(json));
}
// One frame off the wire, its 8-byte header in as many reads as the peer made, then its payload; a payload longer
// than cap-1 fills buf with its first cap-1 bytes and the rest is still consumed. *op gets the opcode; buf is
// NUL-terminated. 1 on a whole frame, 0 when the deadline passed, -1 when the connection broke.
static int read_one_frame(PlatIpc *p, uint32_t *op, char *buf, size_t cap, uint64_t deadline) {
uint8_t head[8];
size_t got = 0;
while (got < sizeof head) {
uint32_t left = deadline > plat_now_ms() ? (uint32_t)(deadline - plat_now_ms()) : 0;
int n = plat_ipc_read(p, head + got, sizeof head - got, left);
if (n < 0) return -1;
if (!n) {
if (plat_now_ms() >= deadline) return 0;
continue;
}
got += (size_t)n;
}
*op = head[0] | head[1] << 8 | head[2] << 16 | (uint32_t)head[3] << 24;
uint32_t len = head[4] | head[5] << 8 | head[6] << 16 | (uint32_t)head[7] << 24;
size_t taken = 0;
while (taken < len) {
size_t want = len - taken > cap - 1 ? cap - 1 : len - taken;
uint32_t left = deadline > plat_now_ms() ? (uint32_t)(deadline - plat_now_ms()) : 0;
int n = plat_ipc_read(p, buf, want, left);
if (n < 0) return -1;
if (!n) {
if (plat_now_ms() >= deadline) return 0;
continue;
}
taken += (size_t)n;
}
buf[taken < cap - 1 ? taken : cap - 1] = 0;
return 1;
}
// The next frame that is not a Ping: a Ping the client sent to see we are alive is echoed as a Pong with its own
// payload, a Close (the client told us it is done) counts as a broken connection so the caller connects again
// later. Same return values as read_one_frame; the deadline covers the whole exchange.
static int read_frame(PlatIpc *p, uint32_t *op, char *buf, size_t cap, uint32_t ms) {
uint64_t deadline = plat_now_ms() + ms;
for (;;) {
int r = read_one_frame(p, op, buf, cap, deadline);
if (r != 1) return r;
if (*op == OP_PING) {
uint8_t head[8];
size_t n = strlen(buf);
le32(head, OP_PONG);
le32(head + 4, (uint32_t)n);
if (!plat_ipc_write(p, head, sizeof head) || !plat_ipc_write(p, buf, n)) return -1;
continue;
}
if (*op == OP_CLOSE) return -1;
return 1;
}
}
// The first of Discord's pipes that completes a handshake. NULL when no client is running or none answered in time;
// the caller tries again later.
static PlatIpc *connect_client(const char *app_id) {
for (int i = 0; i < 10; i++) {
char name[32], json[160];
snprintf(name, sizeof name, "discord-ipc-%d", i);
PlatIpc *p = plat_ipc_connect(name);
if (!p) continue;
snprintf(json, sizeof json, "{\"v\":1,\"client_id\":\"%s\"}", app_id);
if (!write_frame(p, OP_HANDSHAKE, json)) {
plat_ipc_close(p);
continue;
}
uint32_t op = 0;
char answer[ANSWER_CAP];
if (read_frame(p, &op, answer, sizeof answer, 2000) == 1 && op == OP_FRAME) return p; // the Ready event
plat_ipc_close(p); // this pipe answered but not with a Ready frame in 2 s: the next may belong to a client
}
return NULL;
}
static uint32_t next_nonce(void) {
static volatile int32_t n;
return (uint32_t)plat_inc32(&n);
}
// The activity as one SET_ACTIVITY frame: the game update and the port version as the details line ("Game 1.4.3 ·
// Recomp 0.3.7": the port version without its +commit suffix, the art's hover text keeps the full one; the dot goes
// as a JSON escape), the process's start as the timestamp Discord counts the elapsed time from, and the application's
// art asset. 1 when the client answered (a slow answer that ran out of the 2 s read is fine: the next drain takes
// it), 0 when the connection broke.
static int send_activity(PlatIpc *p, const char *image) {
char json[512];
int v = rt_game_version;
uint64_t start = (plat_unix_time_ns() - plat_process_uptime_ns()) / 1000000000ull;
int port_len = (int)strcspn(rt_port_version, "+");
snprintf(json, sizeof json,
"{\"cmd\":\"SET_ACTIVITY\",\"nonce\":\"%u\",\"args\":{\"pid\":%lu,\"activity\":{\"details\":\"Game "
"%d.%d.%d \\u00b7 Recomp %.*s\",\"timestamps\":{\"start\":%llu},\"assets\":{\"large_image\":\"%s\","
"\"large_text\":\"TotK Recomp %s\"}}}}",
next_nonce(), (unsigned long)plat_process_id(), v / 100, v / 10 % 10, v % 10, port_len, rt_port_version,
(unsigned long long)start, image, rt_port_version);
if (!write_frame(p, OP_FRAME, json)) return 0;
uint32_t op = 0;
char answer[ANSWER_CAP];
return read_frame(p, &op, answer, sizeof answer, 2000) >= 0;
}
// ---- the presence thread
static void discord_main(void *arg) {
(void)arg;
unsigned seen = 0;
char app_id[APP_ID_CAP], image[IMAGE_KEY_CAP];
read_setting("TOTK_DISCORD_APP_ID", app_id, sizeof app_id, valid_app_id);
read_setting("TOTK_DISCORD_IMAGE", image, sizeof image, valid_image_key);
PlatIpc *ipc = NULL;
uint64_t retry_at = 0, send_at = 0;
int said_no_client = 0;
for (;;) {
unsigned v = cfg_version();
if (v != seen) { // the settings changed (the menu writes them): pick the new ones up at once
seen = v;
read_setting("TOTK_DISCORD_APP_ID", app_id, sizeof app_id, valid_app_id);
read_setting("TOTK_DISCORD_IMAGE", image, sizeof image, valid_image_key);
if (ipc) plat_ipc_close(ipc), ipc = NULL; // the new app id needs a new handshake; the image is resent
said_no_client = 0;
}
if (!cfg_bool("TOTK_DISCORD_RPC")) {
if (ipc) plat_ipc_close(ipc), ipc = NULL;
plat_sleep_ms(500);
continue;
}
if (!ipc && plat_now_ms() >= retry_at) {
ipc = connect_client(app_id);
if (!ipc) {
retry_at = plat_now_ms() + 15000;
if (!said_no_client)
rt_log("discord: no client is running; trying again every 15 s while the setting is on");
said_no_client = 1;
} else {
rt_log("discord: connected (app %s)", app_id);
send_at = 0;
said_no_client = 0;
}
}
if (ipc && plat_now_ms() >= send_at) {
if (send_activity(ipc, image)) {
send_at = plat_now_ms() + 60000;
} else {
rt_log("discord: the connection broke; reconnecting");
plat_ipc_close(ipc);
ipc = NULL;
retry_at = plat_now_ms() + 15000;
}
}
plat_sleep_ms(500);
}
}
void discord_init(void) {
if (!plat_thread_spawn(discord_main, NULL, "discord", 0)) rt_log("discord: cannot start the presence thread");
}
// ---- --probe-discord: the exchange above without the game and the setting; needs no game files
int probe_discord(void) {
static int fails;
#define CHECK(c, what) do { if (!(c)) { fails++; fprintf(stderr, "FAIL discord: %s\n", what); } } while (0)
char app_id[APP_ID_CAP], image[IMAGE_KEY_CAP];
read_setting("TOTK_DISCORD_APP_ID", app_id, sizeof app_id, valid_app_id);
read_setting("TOTK_DISCORD_IMAGE", image, sizeof image, valid_image_key);
PlatIpc *p = connect_client(app_id);
if (!p) {
fprintf(stderr, "discord: probe skipped: no client on discord-ipc-0..9\n");
return 0;
}
fprintf(stderr, "discord: connected (app %s)\n", app_id);
CHECK(send_activity(p, image), "SET_ACTIVITY written and answered");
fprintf(stderr, "discord: activity set; the status shows it for ten seconds, then the connection closes\n");
plat_sleep_ms(10000);
plat_ipc_close(p);
fprintf(stderr, "discord: probe %s\n", fails ? "FAILED" : "passed");
return fails != 0;
#undef CHECK
}
+1
View File
@@ -52,6 +52,7 @@ void rt_fatal(const char *fmt, ...) {
double proc, used, limit;
plat_commit_info(&proc, &used, &limit);
rt_log("fatal: memory commit: this process %.0f MB, the system %.0f of %.0f MB", proc, used, limit);
kern_free_cores_note();
fflush(stdout);
fflush(stderr);
_Exit(70);
+66
View File
@@ -0,0 +1,66 @@
// Generated by tools/make_dlaa_mask.py: DLSS's reactive mask pass (vk_dlaa.c mask_pass). Do not edit.
#pragma once
#include <stdint.h>
static const uint32_t dlaa_mask_spv[] = {
0x07230203, 0x00010000, 0x00000000, 0x00000055, 0x00000000, 0x00020011, 0x00000001, 0x00020011,
0x00000031, 0x0006000b, 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e,
0x00000000, 0x00000001, 0x0006000f, 0x00000005, 0x00000002, 0x6e69616d, 0x00000000, 0x0000001b,
0x00060010, 0x00000002, 0x00000011, 0x00000008, 0x00000008, 0x00000001, 0x00040047, 0x0000001b,
0x0000000b, 0x0000001c, 0x00040047, 0x00000018, 0x00000022, 0x00000000, 0x00040047, 0x00000018,
0x00000021, 0x00000000, 0x00040047, 0x00000019, 0x00000022, 0x00000000, 0x00040047, 0x00000019,
0x00000021, 0x00000001, 0x00040047, 0x0000001a, 0x00000022, 0x00000000, 0x00040047, 0x0000001a,
0x00000021, 0x00000002, 0x00030047, 0x0000001a, 0x00000019, 0x00030047, 0x00000015, 0x00000002,
0x00050048, 0x00000015, 0x00000000, 0x00000023, 0x00000000, 0x00020013, 0x00000003, 0x00030021,
0x00000004, 0x00000003, 0x00020014, 0x00000005, 0x00030016, 0x00000006, 0x00000020, 0x00040015,
0x00000007, 0x00000020, 0x00000001, 0x00040015, 0x00000008, 0x00000020, 0x00000000, 0x00040017,
0x00000009, 0x00000006, 0x00000002, 0x00040017, 0x0000000a, 0x00000006, 0x00000003, 0x00040017,
0x0000000b, 0x00000006, 0x00000004, 0x00040017, 0x0000000c, 0x00000007, 0x00000002, 0x00040017,
0x0000000d, 0x00000008, 0x00000002, 0x00040017, 0x0000000e, 0x00000008, 0x00000003, 0x00090019,
0x0000000f, 0x00000006, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0x00000000,
0x0003001b, 0x00000010, 0x0000000f, 0x00090019, 0x00000011, 0x00000006, 0x00000001, 0x00000000,
0x00000000, 0x00000000, 0x00000002, 0x0000000f, 0x00040020, 0x00000012, 0x00000000, 0x00000010,
0x00040020, 0x00000013, 0x00000000, 0x00000011, 0x00040020, 0x00000014, 0x00000001, 0x0000000e,
0x0003001e, 0x00000015, 0x0000000b, 0x00040020, 0x00000016, 0x00000009, 0x00000015, 0x00040020,
0x00000017, 0x00000009, 0x0000000b, 0x0004002b, 0x00000007, 0x0000001d, 0x00000000, 0x0004002b,
0x00000006, 0x0000001e, 0x00000000, 0x0004002b, 0x00000006, 0x0000001f, 0x3f800000, 0x0004002b,
0x00000006, 0x00000020, 0x38d1b717, 0x0004003b, 0x00000012, 0x00000018, 0x00000000, 0x0004003b,
0x00000012, 0x00000019, 0x00000000, 0x0004003b, 0x00000013, 0x0000001a, 0x00000000, 0x0004003b,
0x00000014, 0x0000001b, 0x00000001, 0x0004003b, 0x00000016, 0x0000001c, 0x00000009, 0x00050036,
0x00000003, 0x00000002, 0x00000000, 0x00000004, 0x000200f8, 0x00000021, 0x00050041, 0x00000017,
0x00000024, 0x0000001c, 0x0000001d, 0x0004003d, 0x0000000b, 0x00000025, 0x00000024, 0x0004003d,
0x0000000e, 0x00000026, 0x0000001b, 0x0007004f, 0x0000000d, 0x00000027, 0x00000026, 0x00000026,
0x00000000, 0x00000001, 0x00050051, 0x00000008, 0x00000028, 0x00000026, 0x00000000, 0x00040070,
0x00000006, 0x00000029, 0x00000028, 0x00050051, 0x00000008, 0x0000002a, 0x00000026, 0x00000001,
0x00040070, 0x00000006, 0x0000002b, 0x0000002a, 0x00050051, 0x00000006, 0x0000002c, 0x00000025,
0x00000000, 0x00050051, 0x00000006, 0x0000002d, 0x00000025, 0x00000001, 0x000500b8, 0x00000005,
0x0000002e, 0x00000029, 0x0000002c, 0x000500b8, 0x00000005, 0x0000002f, 0x0000002b, 0x0000002d,
0x000500a7, 0x00000005, 0x00000030, 0x0000002e, 0x0000002f, 0x000300f7, 0x00000023, 0x00000000,
0x000400fa, 0x00000030, 0x00000022, 0x00000023, 0x000200f8, 0x00000022, 0x0004007c, 0x0000000c,
0x00000031, 0x00000027, 0x0004003d, 0x00000010, 0x00000032, 0x00000018, 0x00040064, 0x0000000f,
0x00000033, 0x00000032, 0x0007005f, 0x0000000b, 0x00000034, 0x00000033, 0x00000031, 0x00000002,
0x0000001d, 0x0008004f, 0x0000000a, 0x00000035, 0x00000034, 0x00000034, 0x00000000, 0x00000001,
0x00000002, 0x0004003d, 0x00000010, 0x00000036, 0x00000019, 0x00040064, 0x0000000f, 0x00000037,
0x00000036, 0x0007005f, 0x0000000b, 0x00000038, 0x00000037, 0x00000031, 0x00000002, 0x0000001d,
0x0008004f, 0x0000000a, 0x00000039, 0x00000038, 0x00000038, 0x00000000, 0x00000001, 0x00000002,
0x00050083, 0x0000000a, 0x0000003a, 0x00000039, 0x00000035, 0x0006000c, 0x0000000a, 0x0000003b,
0x00000001, 0x00000004, 0x0000003a, 0x00050051, 0x00000006, 0x0000003c, 0x0000003b, 0x00000000,
0x00050051, 0x00000006, 0x0000003d, 0x0000003b, 0x00000001, 0x00050051, 0x00000006, 0x0000003e,
0x0000003b, 0x00000002, 0x0007000c, 0x00000006, 0x0000003f, 0x00000001, 0x00000028, 0x0000003c,
0x0000003d, 0x0007000c, 0x00000006, 0x00000040, 0x00000001, 0x00000028, 0x0000003f, 0x0000003e,
0x00050051, 0x00000006, 0x00000041, 0x00000039, 0x00000000, 0x00050051, 0x00000006, 0x00000042,
0x00000039, 0x00000001, 0x00050051, 0x00000006, 0x00000043, 0x00000039, 0x00000002, 0x0007000c,
0x00000006, 0x00000044, 0x00000001, 0x00000028, 0x00000041, 0x00000042, 0x0007000c, 0x00000006,
0x00000045, 0x00000001, 0x00000028, 0x00000044, 0x00000043, 0x00050051, 0x00000006, 0x00000046,
0x00000035, 0x00000000, 0x00050051, 0x00000006, 0x00000047, 0x00000035, 0x00000001, 0x00050051,
0x00000006, 0x00000048, 0x00000035, 0x00000002, 0x0007000c, 0x00000006, 0x00000049, 0x00000001,
0x00000028, 0x00000046, 0x00000047, 0x0007000c, 0x00000006, 0x0000004a, 0x00000001, 0x00000028,
0x00000049, 0x00000048, 0x0007000c, 0x00000006, 0x0000004b, 0x00000001, 0x00000028, 0x00000045,
0x0000004a, 0x0007000c, 0x00000006, 0x0000004c, 0x00000001, 0x00000028, 0x0000004b, 0x00000020,
0x00050088, 0x00000006, 0x0000004d, 0x00000040, 0x0000004c, 0x00050051, 0x00000006, 0x0000004e,
0x00000025, 0x00000002, 0x00050051, 0x00000006, 0x0000004f, 0x00000025, 0x00000003, 0x00050083,
0x00000006, 0x00000050, 0x0000004d, 0x0000004e, 0x00050085, 0x00000006, 0x00000051, 0x00000050,
0x0000004f, 0x0008000c, 0x00000006, 0x00000052, 0x00000001, 0x0000002b, 0x00000051, 0x0000001e,
0x0000001f, 0x00070050, 0x0000000b, 0x00000053, 0x00000052, 0x00000052, 0x00000052, 0x00000052,
0x0004003d, 0x00000011, 0x00000054, 0x0000001a, 0x00040063, 0x00000054, 0x00000031, 0x00000053,
0x000200f9, 0x00000023, 0x000200f8, 0x00000023, 0x000100fd, 0x00010038
};
+162
View File
@@ -0,0 +1,162 @@
// Generated by tools/build_shaders.py from runtime/shaders/dlaa_mv.comp; do not edit.
// source sha256 e96a6d2d0cec26c47a76280363077c5982919bedc984f20ae9f1d185dc6ae674
#pragma once
#include <stdint.h>
static const uint32_t dlaa_mv_spv[] = {
0x07230203, 0x00010300, 0x000d000b, 0x0000019a, 0x00000000, 0x00020011, 0x00000001, 0x00020011,
0x00000031, 0x0006000b, 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e,
0x00000000, 0x00000001, 0x0006000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x00000036,
0x00060010, 0x00000004, 0x00000011, 0x00000008, 0x00000008, 0x00000001, 0x00040047, 0x00000036,
0x0000000b, 0x0000001c, 0x00030047, 0x00000041, 0x00000002, 0x00050048, 0x00000041, 0x00000000,
0x00000023, 0x00000000, 0x00050048, 0x00000041, 0x00000001, 0x00000023, 0x00000008, 0x00050048,
0x00000041, 0x00000002, 0x00000023, 0x00000010, 0x00050048, 0x00000041, 0x00000003, 0x00000023,
0x00000014, 0x00040047, 0x0000005d, 0x00000021, 0x00000000, 0x00040047, 0x0000005d, 0x00000022,
0x00000000, 0x00040047, 0x00000086, 0x00000006, 0x00000010, 0x00030047, 0x00000087, 0x00000002,
0x00050048, 0x00000087, 0x00000000, 0x00000023, 0x00000000, 0x00040047, 0x00000089, 0x00000021,
0x00000002, 0x00040047, 0x00000089, 0x00000022, 0x00000000, 0x00040047, 0x0000009d, 0x00000006,
0x00000010, 0x00030047, 0x0000009e, 0x00000002, 0x00050048, 0x0000009e, 0x00000000, 0x00000023,
0x00000000, 0x00040047, 0x000000a0, 0x00000021, 0x00000003, 0x00040047, 0x000000a0, 0x00000022,
0x00000000, 0x00030047, 0x000000e7, 0x00000019, 0x00040047, 0x000000e7, 0x00000021, 0x00000001,
0x00040047, 0x000000e7, 0x00000022, 0x00000000, 0x00040047, 0x000000f6, 0x00000021, 0x00000004,
0x00040047, 0x000000f6, 0x00000022, 0x00000000, 0x00030047, 0x00000101, 0x00000019, 0x00040047,
0x00000101, 0x00000021, 0x00000007, 0x00040047, 0x00000101, 0x00000022, 0x00000000, 0x00030047,
0x0000012a, 0x00000018, 0x00040047, 0x0000012a, 0x00000021, 0x00000006, 0x00040047, 0x0000012a,
0x00000022, 0x00000000, 0x00030047, 0x0000013b, 0x00000019, 0x00040047, 0x0000013b, 0x00000021,
0x00000005, 0x00040047, 0x0000013b, 0x00000022, 0x00000000, 0x00040047, 0x00000146, 0x0000000b,
0x00000019, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00030016, 0x00000006,
0x00000020, 0x00040017, 0x00000007, 0x00000006, 0x00000004, 0x00040018, 0x00000009, 0x00000007,
0x00000004, 0x0004002b, 0x00000006, 0x00000015, 0x3f800000, 0x0004002b, 0x00000006, 0x00000016,
0x00000000, 0x00040015, 0x0000002f, 0x00000020, 0x00000001, 0x00040017, 0x00000030, 0x0000002f,
0x00000002, 0x00040015, 0x00000033, 0x00000020, 0x00000000, 0x00040017, 0x00000034, 0x00000033,
0x00000003, 0x00040020, 0x00000035, 0x00000001, 0x00000034, 0x0004003b, 0x00000035, 0x00000036,
0x00000001, 0x00040017, 0x00000037, 0x00000033, 0x00000002, 0x00020014, 0x0000003b, 0x0004002b,
0x00000033, 0x0000003c, 0x00000000, 0x00040017, 0x00000040, 0x00000006, 0x00000002, 0x0006001e,
0x00000041, 0x00000040, 0x00000040, 0x00000006, 0x00000006, 0x00040020, 0x00000042, 0x00000009,
0x00000041, 0x0004003b, 0x00000042, 0x00000043, 0x00000009, 0x0004002b, 0x0000002f, 0x00000044,
0x00000000, 0x00040020, 0x00000045, 0x00000009, 0x00000006, 0x0004002b, 0x00000033, 0x0000004d,
0x00000001, 0x00090019, 0x0000005a, 0x00000006, 0x00000001, 0x00000000, 0x00000000, 0x00000000,
0x00000001, 0x00000000, 0x0003001b, 0x0000005b, 0x0000005a, 0x00040020, 0x0000005c, 0x00000000,
0x0000005b, 0x0004003b, 0x0000005c, 0x0000005d, 0x00000000, 0x0004002b, 0x00000006, 0x00000067,
0x3f000000, 0x0004002b, 0x0000002f, 0x0000006a, 0x00000001, 0x00040020, 0x0000006b, 0x00000009,
0x00000040, 0x0004002b, 0x00000006, 0x00000075, 0x40000000, 0x0004002b, 0x00000033, 0x00000085,
0x00000010, 0x0004001c, 0x00000086, 0x00000007, 0x00000085, 0x0003001e, 0x00000087, 0x00000086,
0x00040020, 0x00000088, 0x00000002, 0x00000087, 0x0004003b, 0x00000088, 0x00000089, 0x00000002,
0x0004002b, 0x0000002f, 0x0000008a, 0x00000003, 0x0004002b, 0x0000002f, 0x0000008b, 0x00000004,
0x0004002b, 0x0000002f, 0x0000008c, 0x00000005, 0x0004002b, 0x0000002f, 0x0000008d, 0x00000006,
0x00040020, 0x0000008f, 0x00000002, 0x00000007, 0x0004001c, 0x0000009d, 0x00000007, 0x00000085,
0x0003001e, 0x0000009e, 0x0000009d, 0x00040020, 0x0000009f, 0x00000002, 0x0000009e, 0x0004003b,
0x0000009f, 0x000000a0, 0x00000002, 0x0005002c, 0x00000040, 0x000000b4, 0x00000016, 0x00000016,
0x0004002b, 0x00000006, 0x000000b9, 0x2b8cbccc, 0x0004002b, 0x00000006, 0x000000c7, 0x358637bd,
0x00090019, 0x000000e5, 0x00000006, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000002,
0x00000007, 0x00040020, 0x000000e6, 0x00000000, 0x000000e5, 0x0004003b, 0x000000e6, 0x000000e7,
0x00000000, 0x0004002b, 0x0000002f, 0x000000ee, 0x00000002, 0x0004003b, 0x0000005c, 0x000000f6,
0x00000000, 0x0004002b, 0x00000006, 0x000000fc, 0x3e808081, 0x00090019, 0x000000ff, 0x00000006,
0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000002, 0x0000000f, 0x00040020, 0x00000100,
0x00000000, 0x000000ff, 0x0004003b, 0x00000100, 0x00000101, 0x00000000, 0x0004002b, 0x0000002f,
0x00000119, 0xffffffff, 0x0004003b, 0x00000100, 0x0000012a, 0x00000000, 0x0005002c, 0x00000030,
0x00000131, 0x00000044, 0x00000044, 0x0004003b, 0x00000100, 0x0000013b, 0x00000000, 0x0004002b,
0x00000033, 0x00000145, 0x00000008, 0x0006002c, 0x00000034, 0x00000146, 0x00000145, 0x00000145,
0x0000004d, 0x0005002c, 0x00000040, 0x00000197, 0x00000067, 0x00000067, 0x0005002c, 0x00000030,
0x00000199, 0x0000006a, 0x0000006a, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003,
0x000200f8, 0x00000005, 0x000300f7, 0x00000147, 0x00000000, 0x000300fb, 0x0000003c, 0x00000148,
0x000200f8, 0x00000148, 0x0004003d, 0x00000034, 0x00000038, 0x00000036, 0x0007004f, 0x00000037,
0x00000039, 0x00000038, 0x00000038, 0x00000000, 0x00000001, 0x0004007c, 0x00000030, 0x0000003a,
0x00000039, 0x00050051, 0x0000002f, 0x0000003f, 0x0000003a, 0x00000000, 0x00060041, 0x00000045,
0x00000046, 0x00000043, 0x00000044, 0x0000003c, 0x0004003d, 0x00000006, 0x00000047, 0x00000046,
0x0004006e, 0x0000002f, 0x00000048, 0x00000047, 0x000500af, 0x0000003b, 0x00000049, 0x0000003f,
0x00000048, 0x000400a8, 0x0000003b, 0x0000004a, 0x00000049, 0x000300f7, 0x0000004c, 0x00000000,
0x000400fa, 0x0000004a, 0x0000004b, 0x0000004c, 0x000200f8, 0x0000004b, 0x00050051, 0x0000002f,
0x0000004f, 0x0000003a, 0x00000001, 0x00060041, 0x00000045, 0x00000050, 0x00000043, 0x00000044,
0x0000004d, 0x0004003d, 0x00000006, 0x00000051, 0x00000050, 0x0004006e, 0x0000002f, 0x00000052,
0x00000051, 0x000500af, 0x0000003b, 0x00000053, 0x0000004f, 0x00000052, 0x000200f9, 0x0000004c,
0x000200f8, 0x0000004c, 0x000700f5, 0x0000003b, 0x00000054, 0x00000049, 0x00000148, 0x00000053,
0x0000004b, 0x000300f7, 0x00000056, 0x00000000, 0x000400fa, 0x00000054, 0x00000055, 0x00000056,
0x000200f8, 0x00000055, 0x000200f9, 0x00000147, 0x000200f8, 0x00000056, 0x0004003d, 0x0000005b,
0x0000005e, 0x0000005d, 0x00040064, 0x0000005a, 0x00000060, 0x0000005e, 0x0007005f, 0x00000007,
0x00000061, 0x00000060, 0x0000003a, 0x00000002, 0x00000044, 0x00050051, 0x00000006, 0x00000062,
0x00000061, 0x00000000, 0x0004006f, 0x00000040, 0x00000066, 0x0000003a, 0x00050081, 0x00000040,
0x00000069, 0x00000066, 0x00000197, 0x00050041, 0x0000006b, 0x0000006c, 0x00000043, 0x0000006a,
0x0004003d, 0x00000040, 0x0000006d, 0x0000006c, 0x00050083, 0x00000040, 0x0000006e, 0x00000069,
0x0000006d, 0x00050051, 0x00000006, 0x00000071, 0x0000006e, 0x00000000, 0x00050088, 0x00000006,
0x00000074, 0x00000071, 0x00000047, 0x00050085, 0x00000006, 0x00000076, 0x00000074, 0x00000075,
0x00050083, 0x00000006, 0x00000077, 0x00000076, 0x00000015, 0x00050051, 0x00000006, 0x00000079,
0x0000006e, 0x00000001, 0x00060041, 0x00000045, 0x0000007a, 0x00000043, 0x00000044, 0x0000004d,
0x0004003d, 0x00000006, 0x0000007b, 0x0000007a, 0x00050088, 0x00000006, 0x0000007c, 0x00000079,
0x0000007b, 0x00050085, 0x00000006, 0x0000007d, 0x0000007c, 0x00000075, 0x00050083, 0x00000006,
0x0000007e, 0x00000015, 0x0000007d, 0x00050085, 0x00000006, 0x00000080, 0x00000062, 0x00000075,
0x00050083, 0x00000006, 0x00000081, 0x00000080, 0x00000015, 0x00070050, 0x00000007, 0x00000082,
0x00000077, 0x0000007e, 0x00000081, 0x00000015, 0x00060041, 0x0000008f, 0x00000090, 0x00000089,
0x00000044, 0x0000008a, 0x0004003d, 0x00000007, 0x00000091, 0x00000090, 0x00060041, 0x0000008f,
0x00000093, 0x00000089, 0x00000044, 0x0000008b, 0x0004003d, 0x00000007, 0x00000094, 0x00000093,
0x00060041, 0x0000008f, 0x00000096, 0x00000089, 0x00000044, 0x0000008c, 0x0004003d, 0x00000007,
0x00000097, 0x00000096, 0x00060041, 0x0000008f, 0x00000099, 0x00000089, 0x00000044, 0x0000008d,
0x0004003d, 0x00000007, 0x0000009a, 0x00000099, 0x00070050, 0x00000009, 0x00000167, 0x00000091,
0x00000094, 0x00000097, 0x0000009a, 0x00040054, 0x00000009, 0x00000168, 0x00000167, 0x00060041,
0x0000008f, 0x000000a2, 0x000000a0, 0x00000044, 0x0000008a, 0x0004003d, 0x00000007, 0x000000a3,
0x000000a2, 0x00060041, 0x0000008f, 0x000000a5, 0x000000a0, 0x00000044, 0x0000008b, 0x0004003d,
0x00000007, 0x000000a6, 0x000000a5, 0x00060041, 0x0000008f, 0x000000a8, 0x000000a0, 0x00000044,
0x0000008c, 0x0004003d, 0x00000007, 0x000000a9, 0x000000a8, 0x00060041, 0x0000008f, 0x000000ab,
0x000000a0, 0x00000044, 0x0000008d, 0x0004003d, 0x00000007, 0x000000ac, 0x000000ab, 0x00070050,
0x00000009, 0x00000183, 0x000000a3, 0x000000a6, 0x000000a9, 0x000000ac, 0x00040054, 0x00000009,
0x00000184, 0x00000183, 0x0006000c, 0x00000009, 0x000000b0, 0x00000001, 0x00000022, 0x00000168,
0x00050091, 0x00000007, 0x000000b2, 0x000000b0, 0x00000082, 0x00050051, 0x00000006, 0x000000b7,
0x000000b2, 0x00000003, 0x0006000c, 0x00000006, 0x000000b8, 0x00000001, 0x00000004, 0x000000b7,
0x000500ba, 0x0000003b, 0x000000ba, 0x000000b8, 0x000000b9, 0x000300f7, 0x000000bc, 0x00000000,
0x000400fa, 0x000000ba, 0x000000bb, 0x000000bc, 0x000200f8, 0x000000bb, 0x00070050, 0x00000007,
0x000000c2, 0x000000b7, 0x000000b7, 0x000000b7, 0x000000b7, 0x00050088, 0x00000007, 0x000000c3,
0x000000b2, 0x000000c2, 0x00050091, 0x00000007, 0x000000c4, 0x00000184, 0x000000c3, 0x00050051,
0x00000006, 0x000000c6, 0x000000c4, 0x00000003, 0x000500ba, 0x0000003b, 0x000000c8, 0x000000c6,
0x000000c7, 0x000300f7, 0x000000ca, 0x00000000, 0x000400fa, 0x000000c8, 0x000000c9, 0x000000ca,
0x000200f8, 0x000000c9, 0x0007004f, 0x00000040, 0x000000cd, 0x000000c4, 0x000000c4, 0x00000000,
0x00000001, 0x00050050, 0x00000040, 0x000000d0, 0x000000c6, 0x000000c6, 0x00050088, 0x00000040,
0x000000d1, 0x000000cd, 0x000000d0, 0x00050051, 0x00000006, 0x000000d4, 0x000000d1, 0x00000000,
0x00050085, 0x00000006, 0x000000d5, 0x000000d4, 0x00000067, 0x00050081, 0x00000006, 0x000000d6,
0x000000d5, 0x00000067, 0x00050085, 0x00000006, 0x000000d9, 0x000000d6, 0x00000047, 0x00050051,
0x00000006, 0x000000db, 0x000000d1, 0x00000001, 0x00050085, 0x00000006, 0x000000dc, 0x000000db,
0x00000067, 0x00050083, 0x00000006, 0x000000dd, 0x00000067, 0x000000dc, 0x00050085, 0x00000006,
0x000000e0, 0x000000dd, 0x0000007b, 0x00050050, 0x00000040, 0x000000e1, 0x000000d9, 0x000000e0,
0x00050083, 0x00000040, 0x000000e4, 0x000000e1, 0x0000006e, 0x000200f9, 0x000000ca, 0x000200f8,
0x000000ca, 0x000700f5, 0x00000040, 0x00000190, 0x000000b4, 0x000000bb, 0x000000e4, 0x000000c9,
0x000200f9, 0x000000bc, 0x000200f8, 0x000000bc, 0x000700f5, 0x00000040, 0x0000018f, 0x000000b4,
0x00000056, 0x00000190, 0x000000ca, 0x0004003d, 0x000000e5, 0x000000e8, 0x000000e7, 0x00050051,
0x00000006, 0x000000eb, 0x0000018f, 0x00000000, 0x00050051, 0x00000006, 0x000000ec, 0x0000018f,
0x00000001, 0x00070050, 0x00000007, 0x000000ed, 0x000000eb, 0x000000ec, 0x00000016, 0x00000016,
0x00040063, 0x000000e8, 0x0000003a, 0x000000ed, 0x00050041, 0x00000045, 0x000000ef, 0x00000043,
0x000000ee, 0x0004003d, 0x00000006, 0x000000f0, 0x000000ef, 0x000500bc, 0x0000003b, 0x000000f1,
0x000000f0, 0x00000016, 0x000300f7, 0x000000f3, 0x00000000, 0x000400fa, 0x000000f1, 0x000000f2,
0x000000f3, 0x000200f8, 0x000000f2, 0x000200f9, 0x00000147, 0x000200f8, 0x000000f3, 0x0004003d,
0x0000005b, 0x000000f7, 0x000000f6, 0x00040064, 0x0000005a, 0x000000f9, 0x000000f7, 0x0007005f,
0x00000007, 0x000000fa, 0x000000f9, 0x0000003a, 0x00000002, 0x00000044, 0x00050051, 0x00000006,
0x000000fb, 0x000000fa, 0x00000001, 0x000500ba, 0x0000003b, 0x000000fd, 0x000000fb, 0x000000fc,
0x000600a9, 0x00000006, 0x000000fe, 0x000000fd, 0x00000015, 0x00000016, 0x0004003d, 0x000000ff,
0x00000102, 0x00000101, 0x00070050, 0x00000007, 0x00000105, 0x000000fe, 0x000000fe, 0x000000fe,
0x000000fe, 0x00040063, 0x00000102, 0x0000003a, 0x00000105, 0x00050041, 0x00000045, 0x00000107,
0x00000043, 0x0000008a, 0x0004003d, 0x00000006, 0x00000108, 0x00000107, 0x000500ba, 0x0000003b,
0x00000109, 0x00000108, 0x00000067, 0x000300f7, 0x0000010b, 0x00000000, 0x000400fa, 0x00000109,
0x0000010a, 0x0000010b, 0x000200f8, 0x0000010a, 0x00050081, 0x00000040, 0x0000010f, 0x0000006e,
0x0000018f, 0x0006000c, 0x00000040, 0x00000110, 0x00000001, 0x00000008, 0x0000010f, 0x0004006e,
0x00000030, 0x00000111, 0x00000110, 0x00050041, 0x0000006b, 0x00000113, 0x00000043, 0x00000044,
0x0004003d, 0x00000040, 0x00000114, 0x00000113, 0x0004006e, 0x00000030, 0x00000115, 0x00000114,
0x00050082, 0x00000030, 0x00000117, 0x00000115, 0x00000199, 0x000200f9, 0x0000011a, 0x000200f8,
0x0000011a, 0x000700f5, 0x00000006, 0x00000193, 0x00000016, 0x0000010a, 0x00000196, 0x0000011d,
0x000700f5, 0x0000002f, 0x00000191, 0x00000119, 0x0000010a, 0x0000013a, 0x0000011d, 0x000500b3,
0x0000003b, 0x00000120, 0x00000191, 0x0000006a, 0x000400f6, 0x0000011c, 0x0000011d, 0x00000000,
0x000400fa, 0x00000120, 0x0000011b, 0x0000011c, 0x000200f8, 0x0000011b, 0x000200f9, 0x00000122,
0x000200f8, 0x00000122, 0x000700f5, 0x00000006, 0x00000196, 0x00000193, 0x0000011b, 0x00000136,
0x00000123, 0x000700f5, 0x0000002f, 0x00000194, 0x00000119, 0x0000011b, 0x00000138, 0x00000123,
0x000500b3, 0x0000003b, 0x00000128, 0x00000194, 0x0000006a, 0x000400f6, 0x00000124, 0x00000123,
0x00000000, 0x000400fa, 0x00000128, 0x00000123, 0x00000124, 0x000200f8, 0x00000123, 0x0004003d,
0x000000ff, 0x0000012b, 0x0000012a, 0x00050050, 0x00000030, 0x0000012f, 0x00000194, 0x00000191,
0x00050080, 0x00000030, 0x00000130, 0x00000111, 0x0000012f, 0x0008000c, 0x00000030, 0x00000133,
0x00000001, 0x0000002d, 0x00000130, 0x00000131, 0x00000117, 0x00050062, 0x00000007, 0x00000134,
0x0000012b, 0x00000133, 0x00050051, 0x00000006, 0x00000135, 0x00000134, 0x00000000, 0x0007000c,
0x00000006, 0x00000136, 0x00000001, 0x00000028, 0x00000196, 0x00000135, 0x00050080, 0x0000002f,
0x00000138, 0x00000194, 0x0000006a, 0x000200f9, 0x00000122, 0x000200f8, 0x00000124, 0x000200f9,
0x0000011d, 0x000200f8, 0x0000011d, 0x00050080, 0x0000002f, 0x0000013a, 0x00000191, 0x0000006a,
0x000200f9, 0x0000011a, 0x000200f8, 0x0000011c, 0x000200f9, 0x0000010b, 0x000200f8, 0x0000010b,
0x000700f5, 0x00000006, 0x00000192, 0x00000016, 0x000000f3, 0x00000193, 0x0000011c, 0x0004003d,
0x000000ff, 0x0000013c, 0x0000013b, 0x0007000c, 0x00000006, 0x00000140, 0x00000001, 0x00000028,
0x000000fe, 0x00000192, 0x00050085, 0x00000006, 0x00000143, 0x00000140, 0x000000f0, 0x00070050,
0x00000007, 0x00000144, 0x00000143, 0x00000143, 0x00000143, 0x00000143, 0x00040063, 0x0000013c,
0x0000003a, 0x00000144, 0x000200f9, 0x00000147, 0x000200f8, 0x00000147, 0x000100fd, 0x00010038,
};
+246
View File
@@ -0,0 +1,246 @@
// Correctly rounded fma/fmaf for x86-64 builds without FMA3: the -march=x86-64-v2 build (docs/building.md).
//
// runtime/simd.h lowers AArch64 FMADD/FMSUB and the RECPS/RSQRTS helpers to __builtin_elementwise_fma, which clang
// turns into a call to fma/fmaf when the target has no FMA instruction. The C runtime is not a substitute: on CPUs
// without FMA3 the UCRT's software fallback is documented as rounding incorrectly by up to half an ulp, while the FP
// lowering needs the single rounding the ARM instruction gives. This file supplies it.
//
// Adapted from musl src/math/fma.c and src/math/fmaf.c (MIT, Copyright (c) 2005-2020 Rich Felker and contributors).
// The result is rounded in the MXCSR rounding mode the caller set (simd.h simd_rm_enter), and MXCSR FTZ and DAZ are
// honoured as the hardware FMA would, so runtime/simd.h's fast paths keep their assumptions: denormal inputs read as
// zero and denormal results as zero under FPCR.FZ, without a trip through the slow path.
//
// The definitions exist only where the compiler would emit the calls. A -march=x86-64-v3 build defines __FMA__ and
// emits vfmadd instead, so this file contributes nothing there.
#include <stdint.h>
#if defined(__x86_64__) && !defined(__FMA__)
#include <float.h>
#include <immintrin.h>
#define MXCSR_DAZ 0x0040u
#define MXCSR_FTZ 0x8000u
static double fma_flush_d(double x) {
union { double f; uint64_t i; } u = {x};
if (!(u.i & 0x7ff0000000000000ull) && (u.i & 0x000fffffffffffffull)) u.i &= 0x8000000000000000ull;
return u.f;
}
static float fma_flush_f(float x) {
union { float f; uint32_t i; } u = {x};
if (!(u.i & 0x7f800000u) && (u.i & 0x007fffffu)) u.i &= 0x80000000u;
return u.f;
}
// ---- float: the exact product fits in a double, so one extra term and a round-to-odd step decide the float
// rounding. Halfway and tiny results are the only ones where rounding the double first can change the float result.
float fmaf(float x, float y, float z) {
unsigned csr = _mm_getcsr();
if (csr & MXCSR_DAZ) x = fma_flush_f(x), y = fma_flush_f(y), z = fma_flush_f(z);
double xy = (double)x * y; // exact
union { double r; uint64_t i; } u = {xy + z};
int e = u.i >> 52 & 0x7ff;
int halfway = (u.i & 0x1fffffff) == 0x10000000;
int tiny = e <= 0x3ff - 126 && e >= 0x3ff - 149;
if (halfway || tiny) {
if (e != 0x7ff) {
// r+t is the exact sum in nearest rounding; otherwise t keeps its sign and whether it is zero, which
// is all the round-to-odd step needs. An odd sticky bit makes the final conversion round once, in
// whichever mode MXCSR asks for.
int s = u.i >> 63;
double t = s == (xy < z) ? xy - u.r + z : z - u.r + xy;
if (t) {
u.i -= s ^ (t < 0);
u.i |= 1;
}
}
}
float r = (float)u.r;
if (csr & MXCSR_FTZ) r = fma_flush_f(r);
return r;
}
// ---- double: the significands are multiplied and aligned as integers, then converted back with one rounding.
#define ASUINT64(x) ((union { double f; uint64_t i; }){x}).i
#define ZEROINFNAN (0x7ff - 0x3ff - 52 - 1)
struct fma_num { uint64_t m; int e; int sign; };
static struct fma_num fma_normalize(double x) {
uint64_t ix = ASUINT64(x);
int e = ix >> 52;
int sign = e & 0x800;
e &= 0x7ff;
if (!e) {
ix = ASUINT64(x * 0x1p63);
e = ix >> 52 & 0x7ff;
e = e ? e - 63 : 0x800;
}
ix &= (1ull << 52) - 1;
ix |= 1ull << 52;
ix <<= 1;
e -= 0x3ff + 52 + 1;
return (struct fma_num){ix, e, sign};
}
static void fma_mul(uint64_t *hi, uint64_t *lo, uint64_t x, uint64_t y) {
uint64_t xlo = (uint32_t)x, xhi = x >> 32;
uint64_t ylo = (uint32_t)y, yhi = y >> 32;
uint64_t t1 = xlo * ylo;
uint64_t t2 = xlo * yhi + xhi * ylo;
uint64_t t3 = xhi * yhi;
*lo = t1 + (t2 << 32);
*hi = t3 + (t2 >> 32) + (t1 > *lo);
}
// scalbn from musl src/math/scalbn.c (MIT): the fma's final scaling, kept here so the result does not depend on the
// C runtime's version. Its multiplications honour MXCSR like any other host FP operation.
static double fma_scalbn(double x, int n) {
union { double f; uint64_t i; } u;
double y = x;
if (n > 1023) {
y *= 0x1p1023;
n -= 1023;
if (n > 1023) {
y *= 0x1p1023;
n -= 1023;
if (n > 1023) n = 1023;
}
} else if (n < -1022) {
// Make sure the final n < -53, so the subnormal range rounds only once.
y *= 0x1p-1022 * 0x1p53;
n += 1022 - 53;
if (n < -1022) {
y *= 0x1p-1022 * 0x1p53;
n += 1022 - 53;
if (n < -1022) n = -1022;
}
}
u.i = (uint64_t)(0x3ff + n) << 52;
return y * u.f;
}
double fma(double x, double y, double z) {
#pragma STDC FENV_ACCESS ON
unsigned csr = _mm_getcsr();
if (csr & MXCSR_DAZ) x = fma_flush_d(x), y = fma_flush_d(y), z = fma_flush_d(z);
struct fma_num nx = fma_normalize(x), ny = fma_normalize(y), nz = fma_normalize(z);
if (nx.e >= ZEROINFNAN || ny.e >= ZEROINFNAN) return x * y + z;
if (nz.e >= ZEROINFNAN) {
if (nz.e > ZEROINFNAN) return x * y; // z == 0
return z;
}
uint64_t rhi, rlo, zhi, zlo;
fma_mul(&rhi, &rlo, nx.m, ny.m);
// Align the exponents: shift z left by kz and r right by kr with kz + kr == d.
int e = nx.e + ny.e;
int d = nz.e - e;
if (d > 0) {
if (d < 64) {
zlo = nz.m << d;
zhi = nz.m >> (64 - d);
} else {
zlo = 0;
zhi = nz.m;
e = nz.e - 64;
d -= 64;
if (d == 0) {
} else if (d < 64) {
rlo = rhi << (64 - d) | rlo >> d | !!(rlo << (64 - d));
rhi = rhi >> d;
} else {
rlo = 1;
rhi = 0;
}
}
} else {
zhi = 0;
d = -d;
if (d == 0) {
zlo = nz.m;
} else if (d < 64) {
zlo = nz.m >> d | !!(nz.m << (64 - d));
} else {
zlo = 1;
}
}
int sign = nx.sign ^ ny.sign;
int samesign = !(sign ^ nz.sign);
int nonzero = 1;
if (samesign) {
rlo += zlo;
rhi += zhi + (rlo < zlo);
} else {
uint64_t t = rlo;
rlo -= zlo;
rhi = rhi - zhi - (t < rlo);
if (rhi >> 63) {
rlo = -rlo;
rhi = -rhi - !!rlo;
sign = !sign;
}
nonzero = !!rhi;
}
// Keep the top 63 bits in rhi; the last bit is sticky.
if (nonzero) {
e += 64;
d = __builtin_clzll(rhi) - 1;
rhi = rhi << d | rlo >> (64 - d) | !!(rlo << d);
} else if (rlo) {
d = __builtin_clzll(rlo) - 1;
if (d < 0)
rhi = rlo >> 1 | (rlo & 1);
else
rhi = rlo << d;
} else {
return x * y + z; // exact +-0
}
e -= d;
int64_t i = rhi;
if (sign) i = -i;
double r = i; // |r| is in [0x1p62, 0x1p63]
if (e < -1022 - 62) {
// The result is subnormal before rounding.
if (e == -1022 - 63) {
double c = 0x1p63;
if (sign) c = -c;
if (r == c) {
// The smallest normal after rounding: whether it underflows depends on the architecture. A double
// to float conversion imitates the before-rounding rule the guest has.
float fltmin = 0x0.ffffff8p-63 * FLT_MIN * r;
r = DBL_MIN / FLT_MIN * fltmin;
return (csr & MXCSR_FTZ) ? fma_flush_d(r) : r;
}
// One bit is lost when scaled: add another top bit so the conversion rounds only once if inexact.
if (rhi << 53) {
i = rhi >> 1 | (rhi & 1) | 1ull << 62;
if (sign) i = -i;
r = i;
r = 2 * r - c;
// Raise underflow portably, so the compiler cannot optimize the expression away.
double tiny = DBL_MIN / FLT_MIN * r;
r += (double)(tiny * tiny) * (r - r);
}
} else {
// Only round once when scaled.
d = 10;
i = (rhi >> d | !!(rhi << (64 - d))) << d;
if (sign) i = -i;
r = i;
}
}
r = fma_scalbn(r, e);
if (csr & MXCSR_FTZ) r = fma_flush_d(r);
return r;
}
#endif
+18
View File
@@ -0,0 +1,18 @@
// The host's own folder dialog, for menu pages that point at a folder (the Amiibo tab): folder_pick_win.cpp with Win32,
// folder_pick_sdl.c with SDL. The menu has no text entry, so a folder is chosen here or by walking the page's list.
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
// done gets the chosen folder (UTF-8) or NULL when the player cancelled or the host has no dialog.
typedef void (*FolderPickDone)(const char *path, void *ctx);
// Opens the dialog at start (may be relative or missing) and returns at once; done runs later on another thread, once.
// The caller keeps one dialog open at a time.
void folder_pick(const char *start, FolderPickDone done, void *ctx);
#ifdef __cplusplus
}
#endif
+42
View File
@@ -0,0 +1,42 @@
// The SDL front end of folder_pick.h: SDL_ShowOpenFolderDialog (the desktop portal, else zenity), started on the window
// thread, which runs SDL's event loop that delivers the portal's answer.
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <SDL3/SDL.h>
#include "folder_pick.h"
#include "host.h"
#include "input_sdl.h"
typedef struct {
char start[PATH_MAX]; // absolute, or empty: the dialog's own default
FolderPickDone done;
void *ctx;
} PickReq;
static void SDLCALL on_pick(void *userdata, const char *const *list, int filter) {
(void)filter;
PickReq *r = userdata;
if (!list) rt_log("folder_pick: the folder dialog failed (%s)", SDL_GetError());
r->done(list && list[0] ? list[0] : NULL, r->ctx);
free(r);
}
static void show(void *arg) {
PickReq *r = arg;
SDL_ShowOpenFolderDialog(on_pick, r, gfx_window_sdl(), r->start[0] ? r->start : NULL, false);
}
void folder_pick(const char *start, FolderPickDone done, void *ctx) {
PickReq *r = calloc(1, sizeof *r);
if (!r) {
done(NULL, ctx);
return;
}
r->done = done;
r->ctx = ctx;
if (start && *start && !realpath(start, r->start)) r->start[0] = 0;
gfx_window_sdl_run(show, r);
}
+84
View File
@@ -0,0 +1,84 @@
// The Win32 front end of folder_pick.h: the shell's folder dialog (IFileOpenDialog with FOS_PICKFOLDERS), owned by the
// game window, on a thread of its own so the present thread that draws the menu keeps running.
#include <windows.h>
#include <shobjidl.h>
#include <stdlib.h>
#include <string>
extern "C" {
#include "folder_pick.h"
#include "host.h"
#include "input_win.h"
#include "platform/platform.h"
}
struct PickReq {
std::string start;
FolderPickDone done;
void *ctx;
};
static std::wstring wide(const std::string &utf8) {
int n = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, NULL, 0);
std::wstring w(n > 0 ? n : 1, L'\0');
if (n > 0) MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, &w[0], n);
w.resize(wcslen(w.c_str()));
return w;
}
static std::string utf8(const wchar_t *w) {
int n = WideCharToMultiByte(CP_UTF8, 0, w, -1, NULL, 0, NULL, NULL);
std::string s(n > 0 ? n : 1, '\0');
if (n > 0) WideCharToMultiByte(CP_UTF8, 0, w, -1, &s[0], n, NULL, NULL);
s.resize(strlen(s.c_str()));
return s;
}
// The dialog wants an absolute folder that exists; anything else leaves it at the shell's last folder.
static void set_start(IFileOpenDialog *d, const std::string &start) {
wchar_t full[MAX_PATH * 2];
if (start.empty() || !GetFullPathNameW(wide(start).c_str(), MAX_PATH * 2, full, NULL)) return;
IShellItem *item = NULL;
if (SUCCEEDED(SHCreateItemFromParsingName(full, NULL, IID_PPV_ARGS(&item)))) {
d->SetFolder(item);
item->Release();
}
}
static void pick_main(void *arg) {
PickReq *r = (PickReq *)arg;
std::string chosen;
HRESULT co = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
IFileOpenDialog *d = NULL;
HRESULT hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&d));
if (SUCCEEDED(hr)) {
FILEOPENDIALOGOPTIONS opt = 0;
d->GetOptions(&opt);
d->SetOptions(opt | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST);
set_start(d, r->start);
hr = d->Show(gfx_window_handle());
IShellItem *item = NULL;
if (SUCCEEDED(hr) && SUCCEEDED(hr = d->GetResult(&item))) {
PWSTR path = NULL;
if (SUCCEEDED(hr = item->GetDisplayName(SIGDN_FILESYSPATH, &path))) {
chosen = utf8(path);
CoTaskMemFree(path);
}
item->Release();
}
d->Release();
}
if (FAILED(hr) && hr != HRESULT_FROM_WIN32(ERROR_CANCELLED)) rt_log("folder_pick: the folder dialog failed (0x%08lx)", (unsigned long)hr);
r->done(chosen.empty() ? NULL : chosen.c_str(), r->ctx);
if (SUCCEEDED(co)) CoUninitialize();
delete r;
}
extern "C" void folder_pick(const char *start, FolderPickDone done, void *ctx) {
PickReq *r = new PickReq{start ? start : "", done, ctx};
if (!plat_thread_spawn(pick_main, r, "folder dialog", 0)) {
rt_log("folder_pick: cannot start the dialog thread");
done(NULL, ctx);
delete r;
}
}
+31 -11
View File
@@ -11,8 +11,20 @@
// game speed is right only when frames take exactly their interval. With the set realtime both read the patch page
// instead: +0 ratio = seconds * 30, +4 seconds (1.4.3: +8 interval = seconds * 60, the producer's nominal interval
// before its half-step coefficient), the moving average of the last 5 display intervals, at most 1/15 s
// (slower frames slow the game down, as on the console), no lower bound, so a higher frame-rate cap only changes the
// pacer (frame_step_cap_ns, TOTK_FPS_LIMIT). The set cloth gives hair and cloth the same clock and needs realtime.
// (slower frames slow the game down, as on the console) and at least 1/240 s, so a higher frame-rate cap only changes
// the pacer (frame_step_cap_ns, TOTK_FPS_LIMIT). The set cloth gives hair and cloth the same clock and needs realtime.
//
// The floor: with a shorter step (ratio below 0.125) 1.4.3 aborts within seconds of some save loads (issue #241, a
// 280 Hz monitor): Havok's hkDefaultMemoryImpl reports "Out of memory" for the buffer the physics pre-solve (profiler
// scope "TtPreSolve") resizes in main+0x1261630. Forced steps on the Depths save: 1/240 s plays, 1/244 s and shorter
// abort; the field, sky island and fight saves play at 1/280 s, the town save aborts after about 800 frames. The
// same short steps also crash a physics worker reading that buffer's contacts: an access violation in main+0x1292560
// or its caller main+0x1286870 (narrowphase contact setup, reached from the grid task main+0x12f1ea0), reading a
// Havok body's shape at body+0x78 as null or garbage (issues #29 and #92, 240 Hz monitors with fps_limit = display).
// Steps drawn from 1/252..1/230 s crash the Depths load there in seconds; 1/240..1/230 s plays. The frame limit
// stops at 240 too (LIMIT_MAX_HZ), so the floor only catches the average dipping under 1/240 s at that limit: a
// present late by less than a period keeps the pacer's phase (nvn_api_obj.c, pace), so the next display interval is
// shorter than the period. No limit makes the game run slower than the clock.
//
// The sample is the display time the pacer gives each present (nvnQueuePresentTexture), so the step follows the
// frames as shown, pacing waits included. With the step on, the pacer ignores the game's interval and holds a frame
@@ -47,6 +59,7 @@
#define STEP_MAX_S (1.0 / 15.0) // longest step; a longer frame slows the game down
#define STEP_RESET_S 0.25 // a gap this long (loading, a debugger) restarts the average
#define STEP_FIRST_S (1.0 / 60.0)
#define STEP_MIN_S (1.0 / 240.0) // shortest step; a shorter one makes the game's physics run out of memory
static _Atomic uint64_t *step_word; // patch page +0: ratio (low float), seconds (high float)
static double step_now = STEP_FIRST_S; // the step the patch page holds: what the game steps each frame
@@ -90,14 +103,15 @@ void frame_step_init(void) {
int frame_step_realtime(void) { return step_word != NULL; }
// The frame limit (menu, TOTK_FPS_LIMIT, live): 30, 60, 90, 120, 144, any whole rate from 30 to 360, or display (the
// refresh rate of the window's monitor). Unset, the older TOTK_FPS60=0 still means 30. A limit of 30 switches the set
// The frame limit (menu, TOTK_FPS_LIMIT, live): 30, 60, 90, 120, 144, any whole rate from 30 to 240, or display (the
// refresh rate of the window's monitor, at most 240). A higher number gives 240, the rate of the shortest step the
// game survives (STEP_MIN_S). Unset, the older TOTK_FPS60=0 still means 30. A limit of 30 switches the set
// fps60 off (the shipping minimum interval 2), every other limit switches it on; the controller reads its minimum
// interval from the patched sites each frame. With the real-time step the pacer holds frames to the limit; above 60
// only the pacer changes, as the step has no lower bound. Without it the game steps whole 60 Hz vsyncs and the pacer
// only the pacer changes, as the step's floor is the limit's ceiling. Without it the game steps whole 60 Hz vsyncs and the pacer
// follows the game's interval, so the limit stops at 60.
#define LIMIT_MIN_HZ 30
#define LIMIT_MAX_HZ 360
#define LIMIT_MAX_HZ 240 // 1 / STEP_MIN_S
static int fps60_set = -2;
static unsigned limit_seen;
static int limit_read;
@@ -109,8 +123,13 @@ static int limit_parse(void) {
if (!strcmp(e, "display")) return 0;
char *end;
long n = strtol(e, &end, 10);
if (!*end && n >= LIMIT_MIN_HZ && n <= LIMIT_MAX_HZ) return (int)n;
rt_log("frame rate: TOTK_FPS_LIMIT=%s is not 30..360 or display; 60", e);
if (!*end && n > LIMIT_MAX_HZ) {
rt_log("frame rate: TOTK_FPS_LIMIT=%s is above %d, where the game's physics runs out of memory; %d", e,
LIMIT_MAX_HZ, LIMIT_MAX_HZ);
return LIMIT_MAX_HZ;
}
if (!*end && n >= LIMIT_MIN_HZ) return (int)n;
rt_log("frame rate: TOTK_FPS_LIMIT=%s is not %d..%d or display; 60", e, LIMIT_MIN_HZ, LIMIT_MAX_HZ);
return 60;
}
@@ -161,13 +180,13 @@ static uint64_t read_ptr(uint64_t a) {
uint64_t p = 0;
return read_guest(a, &p, 8) ? p : 0;
}
// 1.2.1: [main+0x4728538] (1.1.1: [main+0x4630a68], 1.4.3: [main+0x3add238]) +0x1e8 scene, its component 13 lists the
// 1.2.1: [main+0x4728538] (1.1.0: [main+0x4630a68], 1.4.3: [main+0x3add238]) +0x1e8 scene, its component 13 lists the
// resident actors; the one named "Player" has its position at +0x2b4 (MacNativeGames world_survey.c, game_version.h
// TOTK_GAME_V121/V143). The 1.1.1 slot was measured from its own dereference chain: 181 scene accesses in that build
// TOTK_GAME_V121/V143). The 1.1.0 slot was measured from its own dereference chain: 181 scene accesses in that build
// read it, and one of them reproduces this walk (the 14-component check, component 13, the 0x70 stride and the name
// compare) instruction for instruction.
static int player_pos(float xyz[3]) {
uint64_t module = read_ptr(MOD_MAIN_BASE + (RT_V143 ? 0x3add238 : RT_V111 ? 0x4630a68 : 0x4728538)),
uint64_t module = read_ptr(MOD_MAIN_BASE + (RT_V143 ? 0x3add238 : RT_V110 ? 0x4630a68 : 0x4728538)),
scene = module ? read_ptr(module + 0x1e8) : 0;
int32_t count = 0;
if (!scene || !read_guest(scene + 0x50, &count, 4) || count < 14 || count > 256) return 0;
@@ -258,6 +277,7 @@ void frame_step_present(uint64_t display_ns, int interval) {
double sum = 0;
for (unsigned i = 0; i < sample_count; i++) sum += samples[i];
step = sum / sample_count;
if (step < STEP_MIN_S) step = STEP_MIN_S;
step_store((float)step);
}
}
+9 -2
View File
@@ -38,8 +38,15 @@ uint64_t romfs_file_count(void); // files in the index
const char *romfs_entry(uint64_t i, uint64_t *offset, uint64_t *size); // path, image offset and size of index row i
const char *romfs_image_path(void); // the romfs.bin path fs_init opened
size_t romfs_overlay_count(void);
int romfs_xbox_prompts_ready(void); // romfs-patches-xbox was there at start
int romfs_xbox_prompts_active(void); // and was loaded (pad_layout = xbox_prompts at start)
int romfs_patches_loaded(void); // a romfs-patches manifest gave at least one file
// The button prompts (input_prompts_folder): the folder loaded at start, NULL for the game's own prompts; whether a
// folder had a manifest at start; and why the folder the settings asked for at start was not loaded (ROMFS_PROMPTS_OK
// for any other folder: it was not asked for).
enum { ROMFS_PROMPTS_OK, ROMFS_PROMPTS_MISSING, ROMFS_PROMPTS_FAILED, ROMFS_PROMPTS_SHAPE, ROMFS_PROMPTS_MODS,
ROMFS_PROMPTS_PATCHES };
const char *romfs_prompts(void);
int romfs_prompts_ready(const char *folder);
int romfs_prompts_off(const char *folder);
const char *romfs_overlay(size_t k, const char **file, uint64_t *size, int *is_added); // RomFS path of overlay k
void fs_trace(const char *what, const char *path); // TOTK_TRACE=fs: one line per open
+48 -5
View File
@@ -125,12 +125,30 @@ static void make_dirs(const char *p) {
if (!make_dir(buf)) rt_fatal("fs: cannot create directory %s", buf);
}
// Remove a directory tree; a link (reparse point, symbolic link) is removed as a link, never followed. 0 also when
// The first path remove_tree could not delete and the OS error code, for the message of a fatal.
static char remove_failed[1100];
static int remove_error;
static void remove_note(const char *path) {
if (*remove_failed) return;
snprintf(remove_failed, sizeof remove_failed, "%s", path);
remove_error = plat_fs_os_error();
}
// Remove a directory tree; a link (symbolic link, junction) is removed as a link, never followed. 0 also when
// nothing is there.
static int remove_tree(const char *path) {
int kind = plat_fs_kind(path);
if (kind == PLAT_FS_MISSING) return 0;
if (kind == PLAT_FS_FILE) return plat_fs_unlink(path) ? -1 : 0;
if (kind == PLAT_FS_FILE) {
if (!plat_fs_unlink(path)) return 0;
remove_note(path);
return -1;
}
if (kind == PLAT_FS_LINK) { // a link to a file goes by unlink, a link to a directory by rmdir
if (!plat_fs_unlink(path) || !plat_fs_rmdir(path)) return 0;
remove_note(path);
return -1;
}
int bad = 0;
if (kind == PLAT_FS_DIR) {
Listing l;
@@ -142,7 +160,23 @@ static int remove_tree(const char *path) {
}
listing_free(l.e, l.n);
}
return bad | (plat_fs_rmdir(path) ? -1 : 0);
if (plat_fs_rmdir(path)) {
remove_note(path);
bad |= -1;
}
return bad;
}
// remove_tree, tried again every 50 ms for up to 2 s while another process (the previous run still exiting, a virus
// scanner, a sync client) holds a file in the tree. The failing path and its OS error stay in remove_failed.
#define MOVE_TRIES 40 // 2 s, also move_dir's
static int remove_tree_retry(const char *path) {
for (int i = 0;; i++) {
*remove_failed = 0;
if (!remove_tree(path)) return 0;
if (i == MOVE_TRIES) return -1;
plat_sleep_ms(50);
}
}
// ---- save transactions
@@ -190,7 +224,6 @@ static int exists(const char *p) { return plat_fs_kind(p) != PLAT_FS_MISSING; }
// Rename a directory, durably; retried every 50 ms, tries times in all, while another process (a virus scanner, the
// indexer) holds a file in it. 0 on success.
#define MOVE_TRIES 40 // 2 s
static int move_dir(const char *from, const char *to, int tries) {
for (int i = 0; i < tries; i++) {
int e = plat_fs_rename(from, to, 1);
@@ -446,7 +479,8 @@ static void save_recover(void) {
did = swap_in() ? "a finished commit still waits in save-tx; the game loads it from there"
: "completed a finished commit";
if (exists(work_root)) {
if (remove_tree(work_root)) rt_fatal("fs: cannot delete the old save working copy");
if (remove_tree_retry(work_root))
rt_fatal("fs: cannot delete the old save working copy: %s (OS error %d)", remove_failed, remove_error);
if (!strcmp(did, "nothing to recover"))
did = "deleted the last run's working copy (changes after its last Commit)";
}
@@ -1575,6 +1609,15 @@ static void probe_save_tx(const uint64_t *uid) {
CALL(S_UNMOUNT, U("ro"));
CHECK(RES(S_DELETE_FILE, U(a)) == 0 && RES(S_DELETE_FILE, U(b)) == 0 && tx_commit() == 0 &&
tx_read_committed("tx_a.sav") == -1, "Commit of deletions");
// a run that left read-only folders and files in the working copy (attributes another emulator's save carried):
// the next start deletes them and names the failing path if it cannot
char *ro_dir = join(work_root, "ro_dir"), *ro_file = join(ro_dir, "ro.sav");
CHECK(!plat_fs_mkdir(ro_dir) && plat_file_write(ro_file, "x", 1) && plat_file_set_readonly(ro_file, 1) &&
plat_file_set_readonly(ro_dir, 1), "read-only leftovers in the working copy");
probe_restart(uid);
CHECK(!exists(ro_dir), "the next start deleted a working copy with read-only folders");
free(ro_dir);
free(ro_file);
printf("save tx: uncommitted writes visible to the game and dropped by a restart and by Unmount, commits kept; a "
"crash at each of %d commit steps recovers to the old save %d times, the new one %d times, mixed %d "
"times; %d backups\n", steps, olds, news, mixed, backups);
+10 -1
View File
@@ -35,6 +35,8 @@ typedef struct { // the translator's a
uint8_t attr_type[32], frag_out_type[8]; // GFX_TYPE_*
uint16_t local[3]; uint32_t shared_bytes;
uint8_t depth_minus_w;
uint8_t mvprev; // VS: also write last frame's position (patch 0015,
// vk_mvprev.c); packed as bit 7 of the depth_minus_w byte
} GfxShaderAnswers;
typedef struct GfxShader GfxShader; // SPIR-V words + parsed reflection; owned by the cache
const GfxShader *gfx_shader_get(int stage, const uint8_t *control, const uint8_t *code, uint64_t code_size,
@@ -73,6 +75,12 @@ size_t gfx_shader_warm_list(GfxWarmEnt **out); // malloc'd; recorde
const GfxShader *gfx_shader_load_private(const uint8_t iid[32], int *owned);
void gfx_shader_release_private(const GfxShader *s);
const uint32_t *gfx_shader_spirv(const GfxShader *s, uint64_t *words);
// A shader of the runtime's own (SPIR-V and a .res.json text as the translator writes them), outside the cache and
// never freed; its key is the sha256 of both. NULL when the SPIR-V is malformed.
const GfxShader *gfx_shader_own(const uint32_t *spirv, uint64_t words, const char *res_json);
// vk_hdr.c: with TOTK_HDR=1, replaces a fragment shader's SPIR-V (malloc'd, *words long) by the HDR tonemap when it is
// the game's tonemap; gfx_shader.c calls it for every fragment shader entering the cache.
void vk_hdr_shader_swap(uint32_t **spirv, uint64_t *words);
uint64_t gfx_shader_failures(void); // failed translations; feeds GfxStats.shader_failures
// Reflection: parsed once per shader from the translator's .res.json and the SPIR-V before it enters the cache.
enum { GFX_RES_UBO, GFX_RES_SSBO, GFX_RES_TEX, GFX_RES_IMG, GFX_RES_KINDS };
@@ -94,7 +102,8 @@ int gfx_shader_stage(const GfxShader *s); // GFX_STAGE_VS, GFX
int gfx_shader_resources(const GfxShader *s, int kind, const GfxShaderRes **res); // count of GFX_RES_* kind; array in *res
uint32_t gfx_shader_slot_mask(const GfxShader *s); // texture/image slots whose type its translation read
uint32_t gfx_shader_inputs(const GfxShader *s, GfxShaderIo io[32]); // Input Locations (VS attributes, FS varyings) as a mask
uint32_t gfx_shader_outputs(const GfxShader *s, GfxShaderIo io[32]); // Output Locations (VS varyings, FS colour targets)
uint32_t gfx_shader_outputs(const GfxShader *s, GfxShaderIo io[32]);
uint32_t gfx_shader_mvprev_banks(const GfxShader *s); // a last-frame variant: the banks (bit n: cn) its position reads // Output Locations (VS varyings, FS colour targets)
void gfx_shader_local_size(const GfxShader *s, uint32_t local[3]); // CS: the LocalSize execution mode; 1, 1, 1 otherwise
// ---- back end (gfx_null.c, vk_*.c). Called by the NVN front end (nvn_api_*.c, nvn_ext.c) on guest threads.
+54 -16
View File
@@ -23,9 +23,9 @@
#include "gfx.h"
#include "gfx_wsys.h"
#include "nvn_api.h"
#include "platform/platform.h"
#include "ui/menu.h"
#include "vk.h"
#include "platform/platform.h"
#define FRAMES 2
#define MAX_IMAGES 16
@@ -40,6 +40,7 @@ void vk_queue_unlock(void) { plat_rmutex_unlock(&g_ql); }
// ---- window state shared with the back end
static VkSurfaceKHR g_surface;
static volatile int32_t g_dirty; // the window was resized; swapchain stale
static volatile int32_t g_restart; // gfx_window_request_restart: closing the window starts the game again
static volatile int32_t g_focused = 1;
static volatile int32_t g_focus_msgs;
static PlatRMutex g_start_lock; // gfx_window_start / vsync start
@@ -47,25 +48,43 @@ static int g_started;
void gfx_window_mark_dirty(void) { plat_xchg32(&g_dirty, 1); }
// The window gained or lost the focus: the game hears it as nn::oe's focus state and a notification message.
// The window gained or lost the focus: the game hears it as nn::oe's focus state and a notification message. The line
// carries the local wall time, the only one in the log: when a GPU hang takes the whole system down, the log ends
// without an error, and this time set against the driver's entry in the Windows event log (nvlddmkm 153, Display 4101)
// tells whether an alt-tab or an overlay came before the hang or followed it.
void gfx_window_focus_changed(int in) {
plat_xchg32(&g_focused, in);
oe_set_focus(in); // pinned to 1 by TOTK_ASSUME_FOCUS inside
oe_push_message(OE_MSG_FOCUS_STATE_CHANGED);
plat_inc32(&g_focus_msgs);
rt_log("gfx: window %s the focus", in ? "gained" : "lost");
struct tm t;
plat_local_time(&t);
rt_log("gfx: window %s the focus at %04d-%02d-%02d %02d:%02d:%02d local time", in ? "gained" : "lost",
t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec);
}
// The window was closed: the process ends with it, as in MNG, once a save Commit still running in the background is
// done.
// done. After gfx_window_request_restart the executable then starts again with the same command line and environment
// (plat_restart), and the new process waits until this one is gone (main.c) before it moves the log and opens the
// RomFS and the saves.
void gfx_window_closed(void) {
rt_log("gfx: window closed; exiting");
int restart = plat_cas32(&g_restart, 0, 0) != 0;
rt_log("gfx: window closed; %s", restart ? "restarting" : "exiting");
fs_save_flush();
vk_pipeline_save();
prof_write(); // plat_exit runs no atexit handlers
if (restart) {
plat_setenv("TOTK_REEXEC", NULL); // the new process counts its own address-space retries (memory.c)
if (!plat_restart()) rt_log("gfx: the restart could not start the game again");
}
plat_exit(0);
}
void gfx_window_request_restart(void) {
plat_xchg32(&g_restart, 1);
gfx_window_request_close();
}
// TOTK_FULLSCREEN=1: borderless window over the monitor. TOTK_WINDOW_SIZE=<w>x<h>: client area of the window (the
// swapchain follows the window; the game image is scaled to it).
int gfx_cfg_fullscreen(void) { return cfg_bool("TOTK_FULLSCREEN"); }
@@ -93,6 +112,7 @@ double gfx_window_refresh_hz(void) { return plat_cas32(&g_rate_mhz, 0, 0) / 1000
static PlatRMutex g_pl;
static VkSwapchainKHR g_sc;
static VkFormat g_sc_fmt;
static int g_sc_hdr; // HDR10 (TOTK_HDR, vk_hdr.c): PQ code values in Rec. 2020
static VkExtent2D g_sc_ext;
static int g_scaler; // the last present: 0 the game image 1:1, 1 scaled by the blit, 2 by FSR
static uint32_t g_sc_n;
@@ -292,9 +312,9 @@ static int create_swapchain(void) {
if (nf > 64) nf = 64;
vkGetPhysicalDeviceSurfaceFormatsKHR(c->phys, g_surface, &nf, fmts);
if (!nf) return 0;
// UNORM: the blit writes the bytes the game wrote (no sRGB encode).
// UNORM: the blit writes the bytes the game wrote (no sRGB encode). TOTK_HDR: HDR10 when the surface offers it.
VkSurfaceFormatKHR sf = fmts[0];
int found = 0;
int hdr = vk_hdr_surface_format(fmts, nf, &sf), found = hdr;
for (uint32_t i = 0; i < nf && !found; i++)
if (fmts[i].format == VK_FORMAT_B8G8R8A8_UNORM && fmts[i].colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { sf = fmts[i]; found = 1; }
for (uint32_t i = 0; i < nf && !found; i++)
@@ -328,6 +348,9 @@ static int create_swapchain(void) {
}
if (old) vkDestroySwapchainKHR(c->device, old, NULL);
g_sc_fmt = sf.format;
g_sc_hdr = hdr;
vk_hdr_set_active(hdr);
if (hdr) vk_hdr_metadata(g_sc, 1);
g_sc_ext = ext;
g_sc_n = MAX_IMAGES;
vkGetSwapchainImagesKHR(c->device, g_sc, &g_sc_n, g_sc_img);
@@ -411,12 +434,14 @@ static int ensure_thumbs(void) {
}
g_th_ptr = info.pMappedData;
}
if (g_th_img && g_th_fmt != g_sc_fmt) {
// an HDR10 swapchain blits into RGBA8: its PQ codes, flat-looking but readable as bytes
VkFormat tf = g_sc_hdr ? VK_FORMAT_R8G8B8A8_UNORM : g_sc_fmt;
if (g_th_img && g_th_fmt != tf) {
vmaDestroyImage(c->vma, g_th_img, g_th_img_alloc); // the previous present's fence was waited for: idle
g_th_img = VK_NULL_HANDLE;
}
if (!g_th_img) {
VkImageCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .imageType = VK_IMAGE_TYPE_2D, .format = g_sc_fmt,
VkImageCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .imageType = VK_IMAGE_TYPE_2D, .format = tf,
.extent = {FLIGHT_THUMB_W, FLIGHT_THUMB_H, 1}, .mipLevels = 1, .arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT,
@@ -428,7 +453,7 @@ static int ensure_thumbs(void) {
rt_log("gfx: flight thumbnails off: no %ux%u image", FLIGHT_THUMB_W, FLIGHT_THUMB_H);
return 0;
}
g_th_fmt = g_sc_fmt;
g_th_fmt = tf;
}
return 1;
}
@@ -502,7 +527,8 @@ static void save_capture(const char *path) {
uint8_t *px = malloc(n);
if (!px) return;
int bgra = g_sc_fmt == VK_FORMAT_B8G8R8A8_UNORM || g_sc_fmt == VK_FORMAT_B8G8R8A8_SRGB;
for (size_t i = 0; i < n; i += 4) {
if (g_sc_hdr) vk_hdr_to_srgb8(g_cap_ptr, px, n / 4, g_sc_fmt == VK_FORMAT_A2R10G10B10_UNORM_PACK32);
else for (size_t i = 0; i < n; i += 4) {
px[i] = g_cap_ptr[i + (bgra ? 2 : 0)];
px[i + 1] = g_cap_ptr[i + 1];
px[i + 2] = g_cap_ptr[i + (bgra ? 0 : 2)];
@@ -554,6 +580,7 @@ static void present_image(VkImage src, VkImageLayout layout, VkFormat fmt, int w
if (r != VK_SUCCESS && r != VK_SUBOPTIMAL_KHR) goto out; // lost, not ready: skip the frame
if (r == VK_SUBOPTIMAL_KHR) plat_xchg32(&g_dirty, 1);
vkResetFences(c->device, 1, &g_fence[slot]);
if (g_sc_hdr) vk_hdr_metadata(g_sc, 0); // a changed peak or white goes to the display
if (g_th_pending[slot]) { // that fence has signalled: the thumbnail its submission wrote is complete
g_th_tag[g_th_pending[slot] % (uint64_t)g_th_n] = g_th_pending[slot];
g_th_pending[slot] = 0;
@@ -568,7 +595,8 @@ static void present_image(VkImage src, VkImageLayout layout, VkFormat fmt, int w
window_settings_live();
// The menu overlay: laid out before recording (its first frame starts the ImGui back end and uploads the font)
const char *menu_shot = NULL;
MenuTarget mt = {c->instance, c->phys, c->device, c->gfx_family, c->gfx_queue, g_sc_fmt, g_sc_ext.width,
MenuTarget mt = {c->instance, c->phys, c->device, c->gfx_family, c->gfx_queue,
g_sc_hdr ? VK_FORMAT_R8G8B8A8_UNORM : g_sc_fmt, g_sc_ext.width,
g_sc_ext.height, cw, ch, g_scaler};
int overlay = g_sc_view[idx] &&
menu_overlay_frame(__atomic_load_n(&gfx_counters.frames, __ATOMIC_RELAXED), &mt, &menu_shot);
@@ -596,8 +624,10 @@ static void present_image(VkImage src, VkImageLayout layout, VkFormat fmt, int w
VK_PIPELINE_STAGE_2_TRANSFER_BIT, VK_ACCESS_2_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_2_TRANSFER_BIT,
VK_ACCESS_2_TRANSFER_WRITE_BIT);
}
// Colour adjustment (TOTK_COLOR_*, vk_color.c): an adjusted copy of the crop takes the game image's place below
VkImage graded = general ? vk_color_record(cb, slot, src, fmt, rect) : VK_NULL_HANDLE;
// Colour adjustment (TOTK_COLOR_*, vk_color.c), or on an HDR10 swapchain the PQ encode (vk_hdr.c; the adjustment is
// for SDR): a copy of the crop takes the game image's place below
VkImage graded = !general ? VK_NULL_HANDLE : g_sc_hdr ? vk_hdr_encode(cb, slot, src, fmt, rect)
: vk_color_record(cb, slot, src, fmt, rect);
const int grect[4] = {0, 0, cw, ch};
VkImage psrc = graded ? graded : src;
VkFormat pfmt = graded ? VK_FORMAT_R16G16B16A16_SFLOAT : fmt;
@@ -623,18 +653,24 @@ static void present_image(VkImage src, VkImageLayout layout, VkFormat fmt, int w
VkImageLayout last = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
VkPipelineStageFlags2 last_stage = VK_PIPELINE_STAGE_2_TRANSFER_BIT;
VkAccessFlags2 last_write = VK_ACCESS_2_TRANSFER_WRITE_BIT;
// HDR10: the menu goes into vk_hdr.c's RGBA8 image, which is then blended onto the swapchain image at the HUD's white
VkImageView menu_view = overlay && g_sc_hdr ? vk_hdr_ui_target(cb, g_sc_ext.width, g_sc_ext.height) : VK_NULL_HANDLE;
if (overlay && g_sc_hdr && !menu_view) overlay = 0;
if (overlay) {
sync_barrier(cb, dst, last, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, last_stage, last_write,
VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT,
VK_ACCESS_2_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT);
VkRenderingAttachmentInfo ca = {.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO, .imageView = g_sc_view[idx],
VkRenderingAttachmentInfo ca = {.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO,
.imageView = menu_view ? menu_view : g_sc_view[idx],
.imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD, .storeOp = VK_ATTACHMENT_STORE_OP_STORE};
.loadOp = menu_view ? VK_ATTACHMENT_LOAD_OP_CLEAR : VK_ATTACHMENT_LOAD_OP_LOAD,
.storeOp = VK_ATTACHMENT_STORE_OP_STORE};
VkRenderingInfo ri = {.sType = VK_STRUCTURE_TYPE_RENDERING_INFO, .renderArea = {{0, 0}, g_sc_ext}, .layerCount = 1,
.colorAttachmentCount = 1, .pColorAttachments = &ca};
vkCmdBeginRendering(cb, &ri);
menu_overlay_draw(cb);
vkCmdEndRendering(cb);
if (menu_view) vk_hdr_ui_compose(cb, g_sc_view[idx], g_sc_fmt, g_sc_ext.width, g_sc_ext.height);
last = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
last_stage = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT;
last_write = VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT;
@@ -728,6 +764,8 @@ void gfx_window_release_vk(void) {
menu_vk_release();
vk_fsr_release();
vk_color_release();
vk_hdr_release();
vk_contact_release();
free_capture();
free_thumbs();
for (int i = 0; i < FRAMES; i++) {
+101 -3
View File
@@ -86,6 +86,7 @@ struct GfxShader {
uint32_t in_mask, out_mask; // user Locations of Input / Output variables
GfxShaderIo in[32], out[32];
uint32_t local[3];
uint32_t mvprev_banks; // .res.json "mvprev_banks" (patch 0015), 0 none
};
static PlatMutex cache_lock = PLAT_MUTEX_INIT; // memory cache
@@ -589,6 +590,26 @@ static GfxShader *disk_load_from(const uint8_t key[32], const uint8_t *iid, int
s->reflection = (char *)res;
s->reflection_size = res_size;
reflect(s);
if (s->stage == GFX_STAGE_FS) vk_hdr_shader_swap(&s->spirv, &s->words); // the in-memory copy; the cache keeps its own
return s;
}
const GfxShader *gfx_shader_own(const uint32_t *spirv, uint64_t words, const char *res_json) {
if (words < 5 || spirv[0] != 0x07230203 || !spirv_complete(spirv, words) ||
!reflection_valid(res_json, strlen(res_json)))
return NULL;
GfxShader *s = calloc(1, sizeof *s);
if (!s) return NULL;
size_t rn = strlen(res_json);
uint8_t *buf = malloc(words * 4 + rn);
s->spirv = malloc(words * 4), s->reflection = malloc(rn + 1);
if (!buf || !s->spirv || !s->reflection) rt_fatal("gfx_shader: out of memory");
memcpy(buf, spirv, words * 4), memcpy(buf + words * 4, res_json, rn);
rt_sha256(buf, words * 4 + rn, s->key);
free(buf);
memcpy(s->spirv, spirv, words * 4), memcpy(s->reflection, res_json, rn + 1);
s->words = words, s->reflection_size = rn;
reflect(s);
return s;
}
@@ -758,18 +779,81 @@ out:
free(loc), free(packed), free(ttype), free(tcomps), free(pointee);
}
// Every gradient sample (OpImageSampleExplicitLod with Grad) whose two gradients are each built from two components gets
// them transposed, dx = (a, c) and dy = (b, d) from dx = (a, b) and dy = (c, d), by two new OpCompositeConstruct before
// it. TotK's shaders fill a TXD's gradient registers per coordinate (du/dx, du/dy, dv/dx, dv/dy), and the translator
// (Ryujinx, InstEmitTexture EmitTxd) builds dx = (first two registers), dy = (last two) = (du/dx, du/dy) and
// (dv/dx, dv/dy): a mip level chosen from the wrong derivatives, too sharp on terrain faces turned across the screen,
// which crawled in patches that followed the faces (1.4.3, the Depths). TOTK_TXD_TRANSPOSE=0 turns it off.
// Applied to the SPIR-V after it is loaded, so the shader cache is untouched.
enum { OP_COMPOSITE_CONSTRUCT = 80, OP_SAMPLE_EXPLICIT = 88, IO_GRAD = 4 };
static void patch_txd_transpose(GfxShader *s) {
static int on = -1;
static volatile int32_t n_logged;
if (on < 0) {
const char *e = cfg_get("TOTK_TXD_TRANSPOSE");
on = !(e && *e == '0');
}
uint32_t *w = s->spirv;
uint64_t n = s->words;
if (!on || n < 5) return;
uint32_t bound = w[3] < (1u << 20) ? w[3] : (1u << 20);
uint64_t *cc = calloc(bound, sizeof *cc); // word index of a 2-constituent OpCompositeConstruct defining the id
int found = 0;
if (!cc) return;
for (uint64_t i = 5; i < n;) {
uint32_t op = w[i] & 0xffff, len = w[i] >> 16;
if (!len || i + len > n) goto out;
if (op == OP_COMPOSITE_CONSTRUCT && len == 5 && w[i + 2] < bound) cc[w[i + 2]] = i;
if (op == OP_SAMPLE_EXPLICIT && len >= 8 && w[i + 5] == IO_GRAD && w[i + 6] < bound && w[i + 7] < bound &&
cc[w[i + 6]] && cc[w[i + 7]] && w[cc[w[i + 6]] + 1] == w[cc[w[i + 7]] + 1])
found++;
i += len;
}
if (!found) goto out;
uint32_t *o = malloc((n + (uint64_t)found * 10) * sizeof *o);
if (!o) goto out;
uint64_t k = 0;
uint32_t next = w[3];
for (uint64_t i = 0; i < 5; i++) o[k++] = w[i];
for (uint64_t i = 5; i < n;) {
uint32_t op = w[i] & 0xffff, len = w[i] >> 16;
if (op == OP_SAMPLE_EXPLICIT && len >= 8 && w[i + 5] == IO_GRAD && w[i + 6] < bound && w[i + 7] < bound &&
cc[w[i + 6]] && cc[w[i + 7]] && w[cc[w[i + 6]] + 1] == w[cc[w[i + 7]] + 1]) {
const uint32_t *dx = w + cc[w[i + 6]], *dy = w + cc[w[i + 7]]; // [hdr, type, id, a, b], [hdr, type, id, c, d]
uint32_t ndx = next++, ndy = next++;
o[k++] = 5u << 16 | OP_COMPOSITE_CONSTRUCT, o[k++] = dx[1], o[k++] = ndx, o[k++] = dx[3], o[k++] = dy[3];
o[k++] = 5u << 16 | OP_COMPOSITE_CONSTRUCT, o[k++] = dx[1], o[k++] = ndy, o[k++] = dx[4], o[k++] = dy[4];
for (uint32_t j = 0; j < len; j++) o[k++] = w[i + j];
o[k - len + 6] = ndx, o[k - len + 7] = ndy;
} else {
for (uint32_t j = 0; j < len; j++) o[k++] = w[i + j];
}
i += len;
}
o[3] = next;
free(s->spirv);
s->spirv = o, s->words = k;
if (plat_inc32(&n_logged) <= 4) rt_log("gfx_shader: %d gradient samples now read their derivatives per coordinate", found);
out:
free(cc);
}
static void reflect(GfxShader *s) {
static const char *const kinds[GFX_RES_KINDS] = {"cbufs", "sbufs", "textures", "images"};
const char *js = s->reflection;
char stage[8];
json_str(js, js + strlen(js), "stage", stage, sizeof stage);
s->stage = !strcmp(stage, "cs") ? GFX_STAGE_CS : !strcmp(stage, "ps") ? GFX_STAGE_FS : GFX_STAGE_VS;
s->mvprev_banks = (uint32_t)json_int(js, js + strlen(js), "mvprev_banks", 0);
for (int k = 0; k < GFX_RES_KINDS; k++) {
int count = json_objects(js, kinds[k], NULL, s, k);
s->res[k] = calloc(count ? count : 1, sizeof *s->res[k]);
json_objects(js, kinds[k], add_res, s, k);
}
reflect_spirv(s);
patch_txd_transpose(s);
}
// ---- use masks (see the cache key at the top)
@@ -974,7 +1058,7 @@ static size_t pack_answers(uint8_t *o, const GfxShaderAnswers *a) {
memcpy(p, a->frag_out_type, 8), p += 8;
for (int i = 0; i < 3; i++) *p++ = (uint8_t)a->local[i], *p++ = (uint8_t)(a->local[i] >> 8);
put_u32(&p, a->shared_bytes);
*p++ = a->depth_minus_w;
*p++ = (uint8_t)(a->depth_minus_w | (a->mvprev ? 0x80 : 0));
return (size_t)(p - o);
}
@@ -1006,6 +1090,7 @@ static void mask_answers(const GfxShaderAnswers *a, const UseMask *m, GfxShaderA
if (m->fouts >> i & 1) o->frag_out_type[i] = a->frag_out_type[i];
memcpy(o->local, a->local, sizeof o->local);
o->shared_bytes = a->shared_bytes;
o->mvprev = a->mvprev; // another translation, not an answer the use mask covers
}
// The cache key of an input id under the current translator.
@@ -1085,6 +1170,7 @@ static size_t build_request(char *o0, const char *hex, const char *stage, const
if (!strcmp(stage, "ps") && (control[0x718] & 1)) o += sprintf(o, ",\"early_fragment_tests\":true");
int si = !strcmp(stage, "vs") ? 0 : !strcmp(stage, "cs") ? 2 : 1; // gfx_shader_set_host answers
if (!host_f64) o += sprintf(o, ",\"softfloat64\":true");
if (a && a->mvprev && !strcmp(stage, "vs")) o += sprintf(o, ",\"mvprev\":true");
if (host_sbuf) o += sprintf(o, ",\"sbuf_align\":%u", host_sbuf);
if (host_sg[si] != 32) o += sprintf(o, ",\"subgroup\":%u", host_sg[si]);
if (host_gather) o += sprintf(o, ",\"gather_bias\":%u", host_gather);
@@ -1287,8 +1373,18 @@ static const GfxShader *translate_one(const Req *r, int stage, const uint8_t *co
if (!req) return plat_file_delete(code_path), fail("out of memory", hex);
build_request(req, hex, r->stage_name, code_path, r->c1, r->c1_len, a, control);
int ok = svc_request(req, reply, sizeof reply);
// TOTK_XLATE_KEEP=1: a last-frame variant's job stays as <key>.job (one request line) with its code, to run the
// translator on by hand (totk_xlate --serve < <key>.job)
static int keep = -1;
if (keep < 0) keep = rt_knob("XLATE_KEEP", "0");
int kept = keep && a && a->mvprev;
if (kept) {
char job_path[PATH_CAP + 80];
snprintf(job_path, sizeof job_path, "%s/%s.job", cache_dir, hex);
write_file(job_path, req, strlen(req));
}
free(req);
plat_file_delete(code_path);
if (!kept) plat_file_delete(code_path);
if (!ok) return fail("translator unavailable", hex);
if (strncmp(reply, "ok ", 3)) {
plat_file_delete(spv_path), plat_file_delete(res_path);
@@ -1643,6 +1739,8 @@ uint32_t gfx_shader_inputs(const GfxShader *s, GfxShaderIo io[32]) {
return s->in_mask;
}
uint32_t gfx_shader_mvprev_banks(const GfxShader *s) { return s->mvprev_banks; }
uint32_t gfx_shader_outputs(const GfxShader *s, GfxShaderIo io[32]) {
if (io) memcpy(io, s->out, sizeof s->out);
return s->out_mask;
@@ -1732,7 +1830,7 @@ static void unpack_answers(const uint8_t *p, GfxShaderAnswers *a) {
memcpy(a->frag_out_type, p, 8), p += 8;
for (int i = 0; i < 3; i++) a->local[i] = (uint16_t)(p[0] | p[1] << 8), p += 2;
memcpy(&a->shared_bytes, p, 4), p += 4;
a->depth_minus_w = *p;
a->depth_minus_w = *p & 0x7f, a->mvprev = *p >> 7;
}
// Reads a record file's body (after its header) into *body; 0 when absent, and a file with another header is removed.
+3 -3
View File
@@ -53,9 +53,9 @@ static int hexval(char c) { return c <= '9' ? c - '0' : (c | 32) - 'a' + 10; }
// parent of totk.exe that has one with a jobs.json, the running game version's first, then the others' (any census
// serves a probe). 1 with that folder in dir.
int probe_census_dir(char *dir, size_t n) {
const char *const versions[3] = {RT_V111 ? "v111" : RT_V143 ? "v143" : "v121",
RT_V111 ? "v121" : RT_V143 ? "v121" : "v143",
RT_V111 ? "v143" : RT_V143 ? "v111" : "v111"};
const char *const versions[3] = {RT_V110 ? "v110" : RT_V143 ? "v143" : "v121",
RT_V110 ? "v121" : RT_V143 ? "v121" : "v143",
RT_V110 ? "v143" : RT_V143 ? "v110" : "v110"};
for (int v = 0; v < 3; v++) {
char exe[PLAT_PATH_MAX * 2];
int len = plat_exe_path(exe, sizeof exe);
+1
View File
@@ -131,6 +131,7 @@ static int present_and_check(Source *s, int first, int i, int *w_out, int *h_out
}
int probe_window(void) {
vk_hdr_off(); // the checks read 8-bit swapchain pixels
if (!menu_font_check()) return fail("the menu's font check takes a damaged font or refuses a good one");
gfx_window_start();
VkCtx *c = vk_ctx();
+2
View File
@@ -64,6 +64,8 @@ double gfx_window_sdl_density(void) { return __atomic_load_n(&g_density_milli, _
SDL_Window *gfx_window_sdl(void) { return g_win; }
void gfx_window_sdl_run(void (*fn)(void *arg), void *arg) { run_on_window(fn, arg); }
// ---- settings: size and fullscreen
static char g_applied_size[32];
static int g_applied_fs;
+23 -4
View File
@@ -279,6 +279,24 @@ static LRESULT CALLBACK wnd_proc(HWND h, UINT m, WPARAM w, LPARAM l) {
return DefWindowProcW(h, m, w, l);
}
// Brings the game window to the front. Windows refuses SetForegroundWindow to a process that was not the last to get
// input, which is the case for a game started by a frontend; attaching this thread's input queue to the foreground
// window's thread for the call is the documented way around it. The window is not left topmost.
static void raise_window(HWND h) {
HWND fg = GetForegroundWindow();
DWORD me = GetCurrentThreadId(), other = fg ? GetWindowThreadProcessId(fg, NULL) : 0;
int attached = other && other != me && AttachThreadInput(me, other, TRUE);
ShowWindow(h, IsIconic(h) ? SW_RESTORE : SW_SHOW);
BringWindowToTop(h);
SetForegroundWindow(h);
SetActiveWindow(h);
if (attached) AttachThreadInput(me, other, FALSE);
if (GetForegroundWindow() != h) { // still refused: a topmost toggle puts it above the others without keeping it there
SetWindowPos(h, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
SetWindowPos(h, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
}
static void window_main(void *arg) {
(void)arg;
HINSTANCE inst = GetModuleHandleW(NULL);
@@ -293,10 +311,10 @@ static void window_main(void *arg) {
int cw, ch, ow, oh;
cfg_window_size(&cw, &ch);
outer_size(NULL, cw, ch, &ow, &oh);
// The window opens behind the user's windows without taking focus: it shows the game's blank loading frames for a
// while, and must not cover what the player works on meanwhile. The game still counts itself in focus until the
// first WM_ACTIVATEAPP, so loading goes on, and keyboard input waits for the foreground (input_win.c). Its taskbar
// button flashes until it is brought up, and TOTK_FULLSCREEN waits for that first activation.
// The window opens behind the user's windows first and is then raised (raise_window): a game started by a frontend
// has no other way to reach it. The game counts itself in focus until the first WM_ACTIVATEAPP, so loading goes on,
// and keyboard input waits for the foreground (input_win.c). If Windows still refuses the foreground, the taskbar
// button flashes, and TOTK_FULLSCREEN waits for the first activation.
// TOTK_BACKGROUND_WINDOW=1 (test runs): no flashing, never fullscreen at start, and F11 keeps the window's place.
int background = g_background = cfg_get("TOTK_BACKGROUND_WINDOW") && atoi(cfg_get("TOTK_BACKGROUND_WINDOW"));
g_hwnd = CreateWindowExW(0, wc.lpszClassName, L"TotK Recomp", WND_STYLE, CW_USEDEFAULT, CW_USEDEFAULT, ow, oh, NULL,
@@ -315,6 +333,7 @@ static void window_main(void *arg) {
outer_size(g_hwnd, cw, ch, &ow, &oh);
SetWindowPos(g_hwnd, HWND_BOTTOM, 0, 0, ow, oh, SWP_NOMOVE | SWP_NOACTIVATE | SWP_SHOWWINDOW);
if (!background) {
raise_window(g_hwnd); // a frontend's player may have no way to reach a window left behind
FLASHWINFO fw = {.cbSize = sizeof fw, .hwnd = g_hwnd, .dwFlags = FLASHW_TRAY | FLASHW_TIMERNOFG};
FlashWindowEx(&fw);
g_fs_pending = cfg_fullscreen();
+97
View File
@@ -0,0 +1,97 @@
// Generated by tools/build_shaders.py from runtime/shaders/hdr_encode.comp; do not edit.
// source sha256 08e1d94f9041b32d4183286db39941eec9cde41412babb197c0303fd64bb07a7
#pragma once
#include <stdint.h>
static const uint32_t hdr_encode_spv[] = {
0x07230203, 0x00010300, 0x000d000b, 0x000000dd, 0x00000000, 0x00020011, 0x00000001, 0x0006000b,
0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001,
0x0006000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x0000004c, 0x00060010, 0x00000004,
0x00000011, 0x00000008, 0x00000008, 0x00000001, 0x00040047, 0x0000004c, 0x0000000b, 0x0000001c,
0x00030047, 0x00000053, 0x00000002, 0x00050048, 0x00000053, 0x00000000, 0x00000023, 0x00000000,
0x00050048, 0x00000053, 0x00000001, 0x00000023, 0x00000008, 0x00050048, 0x00000053, 0x00000002,
0x00000023, 0x00000010, 0x00040047, 0x00000064, 0x00000021, 0x00000000, 0x00040047, 0x00000064,
0x00000022, 0x00000000, 0x00030047, 0x0000009c, 0x00000019, 0x00040047, 0x0000009c, 0x00000021,
0x00000001, 0x00040047, 0x0000009c, 0x00000022, 0x00000000, 0x00040047, 0x000000a7, 0x0000000b,
0x00000019, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00030016, 0x00000006,
0x00000020, 0x00040017, 0x00000007, 0x00000006, 0x00000003, 0x0004002b, 0x00000006, 0x00000015,
0x3d6147ae, 0x0004002b, 0x00000006, 0x0000001b, 0x4019999a, 0x0006002c, 0x00000007, 0x0000001c,
0x0000001b, 0x0000001b, 0x0000001b, 0x0004002b, 0x00000006, 0x0000001f, 0x3d25aee6, 0x0006002c,
0x00000007, 0x00000020, 0x0000001f, 0x0000001f, 0x0000001f, 0x00020014, 0x00000021, 0x00040017,
0x00000022, 0x00000021, 0x00000003, 0x0004002b, 0x00000006, 0x0000002c, 0x00000000, 0x0004002b,
0x00000006, 0x0000002d, 0x3f800000, 0x0004002b, 0x00000006, 0x00000031, 0x3e232000, 0x0006002c,
0x00000007, 0x00000032, 0x00000031, 0x00000031, 0x00000031, 0x0004002b, 0x00000006, 0x00000034,
0x3f560000, 0x0004002b, 0x00000006, 0x00000035, 0x4196d000, 0x0004002b, 0x00000006, 0x0000003a,
0x41958000, 0x0004002b, 0x00000006, 0x00000040, 0x429db000, 0x0006002c, 0x00000007, 0x00000041,
0x00000040, 0x00000040, 0x00000040, 0x00040015, 0x00000045, 0x00000020, 0x00000001, 0x00040017,
0x00000046, 0x00000045, 0x00000002, 0x00040015, 0x00000049, 0x00000020, 0x00000000, 0x00040017,
0x0000004a, 0x00000049, 0x00000003, 0x00040020, 0x0000004b, 0x00000001, 0x0000004a, 0x0004003b,
0x0000004b, 0x0000004c, 0x00000001, 0x00040017, 0x0000004d, 0x00000049, 0x00000002, 0x00040017,
0x00000052, 0x00000006, 0x00000004, 0x0005001e, 0x00000053, 0x00000046, 0x00000046, 0x00000052,
0x00040020, 0x00000054, 0x00000009, 0x00000053, 0x0004003b, 0x00000054, 0x00000055, 0x00000009,
0x0004002b, 0x00000045, 0x00000056, 0x00000001, 0x00040020, 0x00000057, 0x00000009, 0x00000046,
0x00040017, 0x0000005a, 0x00000021, 0x00000002, 0x00090019, 0x00000061, 0x00000006, 0x00000001,
0x00000000, 0x00000000, 0x00000000, 0x00000001, 0x00000000, 0x0003001b, 0x00000062, 0x00000061,
0x00040020, 0x00000063, 0x00000000, 0x00000062, 0x0004003b, 0x00000063, 0x00000064, 0x00000000,
0x0004002b, 0x00000045, 0x00000067, 0x00000000, 0x0006002c, 0x00000007, 0x0000006e, 0x0000002c,
0x0000002c, 0x0000002c, 0x0004002b, 0x00000045, 0x00000070, 0x00000002, 0x0004002b, 0x00000049,
0x00000071, 0x00000002, 0x00040020, 0x00000072, 0x00000009, 0x00000006, 0x0004002b, 0x00000006,
0x00000075, 0x3f000000, 0x00040018, 0x00000080, 0x00000007, 0x00000003, 0x0004002b, 0x00000006,
0x00000081, 0x3f209d49, 0x0004002b, 0x00000006, 0x00000082, 0x3d8d844d, 0x0004002b, 0x00000006,
0x00000083, 0x3c86594b, 0x0006002c, 0x00000007, 0x00000084, 0x00000081, 0x00000082, 0x00000083,
0x0004002b, 0x00000006, 0x00000085, 0x3ea89a02, 0x0004002b, 0x00000006, 0x00000086, 0x3f6b645a,
0x0004002b, 0x00000006, 0x00000087, 0x3db43958, 0x0006002c, 0x00000007, 0x00000088, 0x00000085,
0x00000086, 0x00000087, 0x0004002b, 0x00000006, 0x00000089, 0x3d315b57, 0x0004002b, 0x00000006,
0x0000008a, 0x3c3ac711, 0x0004002b, 0x00000006, 0x0000008b, 0x3f65460b, 0x0006002c, 0x00000007,
0x0000008c, 0x00000089, 0x0000008a, 0x0000008b, 0x0006002c, 0x00000080, 0x0000008d, 0x00000084,
0x00000088, 0x0000008c, 0x0004002b, 0x00000049, 0x00000091, 0x00000000, 0x0004002b, 0x00000049,
0x00000095, 0x00000001, 0x00090019, 0x0000009a, 0x00000006, 0x00000001, 0x00000000, 0x00000000,
0x00000000, 0x00000002, 0x00000002, 0x00040020, 0x0000009b, 0x00000000, 0x0000009a, 0x0004003b,
0x0000009b, 0x0000009c, 0x00000000, 0x0004002b, 0x00000049, 0x000000a6, 0x00000008, 0x0006002c,
0x0000004a, 0x000000a7, 0x000000a6, 0x000000a6, 0x00000095, 0x0006002c, 0x00000007, 0x000000d1,
0x0000002d, 0x0000002d, 0x0000002d, 0x0006002c, 0x00000007, 0x000000d3, 0x00000015, 0x00000015,
0x00000015, 0x0006002c, 0x00000007, 0x000000d6, 0x00000034, 0x00000034, 0x00000034, 0x0004002b,
0x00000006, 0x000000d7, 0x3d9e8391, 0x0006002c, 0x00000007, 0x000000d8, 0x000000d7, 0x000000d7,
0x000000d7, 0x0004002b, 0x00000006, 0x000000d9, 0x3f72a76f, 0x0006002c, 0x00000007, 0x000000da,
0x000000d9, 0x000000d9, 0x000000d9, 0x0004002b, 0x00000006, 0x000000db, 0x38d1b717, 0x0006002c,
0x00000007, 0x000000dc, 0x000000db, 0x000000db, 0x000000db, 0x00050036, 0x00000002, 0x00000004,
0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x000300f7, 0x000000a8, 0x00000000, 0x000300fb,
0x00000091, 0x000000a9, 0x000200f8, 0x000000a9, 0x0004003d, 0x0000004a, 0x0000004e, 0x0000004c,
0x0007004f, 0x0000004d, 0x0000004f, 0x0000004e, 0x0000004e, 0x00000000, 0x00000001, 0x0004007c,
0x00000046, 0x00000050, 0x0000004f, 0x00050041, 0x00000057, 0x00000058, 0x00000055, 0x00000056,
0x0004003d, 0x00000046, 0x00000059, 0x00000058, 0x000500af, 0x0000005a, 0x0000005b, 0x00000050,
0x00000059, 0x0004009a, 0x00000021, 0x0000005c, 0x0000005b, 0x000300f7, 0x0000005e, 0x00000000,
0x000400fa, 0x0000005c, 0x0000005d, 0x0000005e, 0x000200f8, 0x0000005d, 0x000200f9, 0x000000a8,
0x000200f8, 0x0000005e, 0x0004003d, 0x00000062, 0x00000065, 0x00000064, 0x00050041, 0x00000057,
0x00000068, 0x00000055, 0x00000067, 0x0004003d, 0x00000046, 0x00000069, 0x00000068, 0x00050080,
0x00000046, 0x0000006a, 0x00000050, 0x00000069, 0x00040064, 0x00000061, 0x0000006b, 0x00000065,
0x0007005f, 0x00000052, 0x0000006c, 0x0000006b, 0x0000006a, 0x00000002, 0x00000067, 0x0008004f,
0x00000007, 0x0000006d, 0x0000006c, 0x0000006c, 0x00000000, 0x00000001, 0x00000002, 0x0007000c,
0x00000007, 0x0000006f, 0x00000001, 0x00000028, 0x0000006d, 0x0000006e, 0x00060041, 0x00000072,
0x00000073, 0x00000055, 0x00000070, 0x00000071, 0x0004003d, 0x00000006, 0x00000074, 0x00000073,
0x000500ba, 0x00000021, 0x00000076, 0x00000074, 0x00000075, 0x000300f7, 0x00000078, 0x00000000,
0x000400fa, 0x00000076, 0x00000077, 0x00000078, 0x000200f8, 0x00000077, 0x0008000c, 0x00000007,
0x0000007c, 0x00000001, 0x0000002b, 0x0000006f, 0x0000006e, 0x000000d1, 0x00050085, 0x00000007,
0x000000b2, 0x0000007c, 0x000000d8, 0x00050081, 0x00000007, 0x000000b5, 0x0000007c, 0x000000d3,
0x00050085, 0x00000007, 0x000000b7, 0x000000b5, 0x000000da, 0x0007000c, 0x00000007, 0x000000b8,
0x00000001, 0x0000001a, 0x000000b7, 0x0000001c, 0x000500ba, 0x00000022, 0x000000ba, 0x0000007c,
0x00000020, 0x000600a9, 0x00000007, 0x000000bb, 0x000000ba, 0x000000b8, 0x000000b2, 0x000200f9,
0x00000078, 0x000200f8, 0x00000078, 0x000700f5, 0x00000007, 0x000000d0, 0x0000006f, 0x0000005e,
0x000000bb, 0x00000077, 0x00050091, 0x00000007, 0x0000008f, 0x0000008d, 0x000000d0, 0x0007000c,
0x00000007, 0x00000090, 0x00000001, 0x00000028, 0x0000008f, 0x0000006e, 0x00060041, 0x00000072,
0x00000092, 0x00000055, 0x00000070, 0x00000091, 0x0004003d, 0x00000006, 0x00000093, 0x00000092,
0x0005008e, 0x00000007, 0x00000094, 0x00000090, 0x00000093, 0x00060041, 0x00000072, 0x00000096,
0x00000055, 0x00000070, 0x00000095, 0x0004003d, 0x00000006, 0x00000097, 0x00000096, 0x00060050,
0x00000007, 0x00000098, 0x00000097, 0x00000097, 0x00000097, 0x0007000c, 0x00000007, 0x00000099,
0x00000001, 0x00000025, 0x00000094, 0x00000098, 0x0004003d, 0x0000009a, 0x0000009d, 0x0000009c,
0x00050085, 0x00000007, 0x000000c1, 0x00000099, 0x000000dc, 0x0008000c, 0x00000007, 0x000000c4,
0x00000001, 0x0000002b, 0x000000c1, 0x0000006e, 0x000000d1, 0x0007000c, 0x00000007, 0x000000c5,
0x00000001, 0x0000001a, 0x000000c4, 0x00000032, 0x0005008e, 0x00000007, 0x000000c7, 0x000000c5,
0x00000035, 0x00050081, 0x00000007, 0x000000c9, 0x000000d6, 0x000000c7, 0x0005008e, 0x00000007,
0x000000cb, 0x000000c5, 0x0000003a, 0x00050081, 0x00000007, 0x000000cd, 0x000000d1, 0x000000cb,
0x00050088, 0x00000007, 0x000000ce, 0x000000c9, 0x000000cd, 0x0007000c, 0x00000007, 0x000000cf,
0x00000001, 0x0000001a, 0x000000ce, 0x00000041, 0x00050051, 0x00000006, 0x000000a2, 0x000000cf,
0x00000000, 0x00050051, 0x00000006, 0x000000a3, 0x000000cf, 0x00000001, 0x00050051, 0x00000006,
0x000000a4, 0x000000cf, 0x00000002, 0x00070050, 0x00000052, 0x000000a5, 0x000000a2, 0x000000a3,
0x000000a4, 0x0000002d, 0x00040063, 0x0000009d, 0x00000050, 0x000000a5, 0x000200f9, 0x000000a8,
0x000200f8, 0x000000a8, 0x000100fd, 0x00010038,
};
+36
View File
@@ -0,0 +1,36 @@
// Generated by tools/build_shaders.py from runtime/shaders/hdr_fullscreen.vert; do not edit.
// source sha256 3474de7753260cdbc5df61bbd96074c566f98c9be15be4791ae7cbea32542b03
#pragma once
#include <stdint.h>
static const uint32_t hdr_fullscreen_spv[] = {
0x07230203, 0x00010300, 0x000d000b, 0x0000002c, 0x00000000, 0x00020011, 0x00000001, 0x0006000b,
0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001,
0x0008000f, 0x00000000, 0x00000004, 0x6e69616d, 0x00000000, 0x00000009, 0x0000000c, 0x0000001d,
0x00040047, 0x00000009, 0x0000001e, 0x00000000, 0x00040047, 0x0000000c, 0x0000000b, 0x0000002a,
0x00030047, 0x0000001b, 0x00000002, 0x00050048, 0x0000001b, 0x00000000, 0x0000000b, 0x00000000,
0x00050048, 0x0000001b, 0x00000001, 0x0000000b, 0x00000001, 0x00050048, 0x0000001b, 0x00000002,
0x0000000b, 0x00000003, 0x00050048, 0x0000001b, 0x00000003, 0x0000000b, 0x00000004, 0x00020013,
0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00030016, 0x00000006, 0x00000020, 0x00040017,
0x00000007, 0x00000006, 0x00000002, 0x00040020, 0x00000008, 0x00000003, 0x00000007, 0x0004003b,
0x00000008, 0x00000009, 0x00000003, 0x00040015, 0x0000000a, 0x00000020, 0x00000001, 0x00040020,
0x0000000b, 0x00000001, 0x0000000a, 0x0004003b, 0x0000000b, 0x0000000c, 0x00000001, 0x0004002b,
0x0000000a, 0x0000000e, 0x00000001, 0x0004002b, 0x0000000a, 0x00000010, 0x00000002, 0x00040017,
0x00000017, 0x00000006, 0x00000004, 0x00040015, 0x00000018, 0x00000020, 0x00000000, 0x0004002b,
0x00000018, 0x00000019, 0x00000001, 0x0004001c, 0x0000001a, 0x00000006, 0x00000019, 0x0006001e,
0x0000001b, 0x00000017, 0x00000006, 0x0000001a, 0x0000001a, 0x00040020, 0x0000001c, 0x00000003,
0x0000001b, 0x0004003b, 0x0000001c, 0x0000001d, 0x00000003, 0x0004002b, 0x0000000a, 0x0000001e,
0x00000000, 0x0004002b, 0x00000006, 0x00000020, 0x40000000, 0x0004002b, 0x00000006, 0x00000022,
0x3f800000, 0x0004002b, 0x00000006, 0x00000025, 0x00000000, 0x00040020, 0x00000029, 0x00000003,
0x00000017, 0x0005002c, 0x00000007, 0x0000002b, 0x00000022, 0x00000022, 0x00050036, 0x00000002,
0x00000004, 0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x0004003d, 0x0000000a, 0x0000000d,
0x0000000c, 0x000500c4, 0x0000000a, 0x0000000f, 0x0000000d, 0x0000000e, 0x000500c7, 0x0000000a,
0x00000011, 0x0000000f, 0x00000010, 0x0004006f, 0x00000006, 0x00000012, 0x00000011, 0x000500c7,
0x0000000a, 0x00000014, 0x0000000d, 0x00000010, 0x0004006f, 0x00000006, 0x00000015, 0x00000014,
0x00050050, 0x00000007, 0x00000016, 0x00000012, 0x00000015, 0x0003003e, 0x00000009, 0x00000016,
0x0004003d, 0x00000007, 0x0000001f, 0x00000009, 0x0005008e, 0x00000007, 0x00000021, 0x0000001f,
0x00000020, 0x00050083, 0x00000007, 0x00000024, 0x00000021, 0x0000002b, 0x00050051, 0x00000006,
0x00000026, 0x00000024, 0x00000000, 0x00050051, 0x00000006, 0x00000027, 0x00000024, 0x00000001,
0x00070050, 0x00000017, 0x00000028, 0x00000026, 0x00000027, 0x00000025, 0x00000022, 0x00050041,
0x00000029, 0x0000002a, 0x0000001d, 0x0000001e, 0x0003003e, 0x0000002a, 0x00000028, 0x000100fd,
0x00010038,
};
+290
View File
@@ -0,0 +1,290 @@
// Generated by tools/build_shaders.py from runtime/shaders/hdr_tonemap.frag; do not edit.
// source sha256 a09ae2b13d844bb6a136d2c3cf38b3ec571191775a4c2f0b43a586bd355381fa
#pragma once
#include <stdint.h>
static const uint32_t hdr_tonemap_spv[] = {
0x07230203, 0x00010300, 0x0008000b, 0x0000018a, 0x00000000, 0x00020011, 0x00000001, 0x0006000b,
0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001,
0x0007000f, 0x00000004, 0x00000004, 0x6e69616d, 0x00000000, 0x00000053, 0x00000181, 0x00030010,
0x00000004, 0x00000007, 0x00030003, 0x00000002, 0x000001c2, 0x00040005, 0x00000004, 0x6e69616d,
0x00000000, 0x00050005, 0x0000000a, 0x76727563, 0x31662865, 0x0000003b, 0x00030005, 0x00000009,
0x00000078, 0x00050005, 0x00000010, 0x76727563, 0x76283365, 0x003b3366, 0x00030005, 0x0000000f,
0x00000078, 0x00050005, 0x00000014, 0x6378616d, 0x33667628, 0x0000003b, 0x00030005, 0x00000013,
0x00000063, 0x00030005, 0x00000016, 0x00003079, 0x00040005, 0x0000002e, 0x61726170, 0x0000006d,
0x00040005, 0x00000034, 0x61726170, 0x0000006d, 0x00040005, 0x00000039, 0x61726170, 0x0000006d,
0x00030005, 0x0000004b, 0x00000078, 0x00050005, 0x0000004f, 0x745f7066, 0x6263745f, 0x0000385f,
0x00030005, 0x00000053, 0x00007675, 0x00050005, 0x0000005c, 0x745f7066, 0x6263745f, 0x0000415f,
0x00030005, 0x00000064, 0x00000077, 0x00030005, 0x00000067, 0x00003143, 0x00040006, 0x00000067,
0x00000000, 0x00000076, 0x00040005, 0x00000069, 0x635f7066, 0x00000031, 0x00030005, 0x0000006f,
0x00000067, 0x00030005, 0x00000071, 0x00003343, 0x00040006, 0x00000071, 0x00000000, 0x00000076,
0x00040005, 0x00000073, 0x635f7066, 0x00000033, 0x00040005, 0x00000076, 0x656d6167, 0x00000000,
0x00060005, 0x00000079, 0x70707553, 0x4274726f, 0x65666675, 0x00000072, 0x00040006, 0x00000079,
0x00000000, 0x00646170, 0x00040006, 0x00000079, 0x00000001, 0x00726468, 0x00060005, 0x0000007b,
0x70707573, 0x5f74726f, 0x66667562, 0x00007265, 0x00040005, 0x00000089, 0x6b616570, 0x00000000,
0x00030005, 0x00000094, 0x006d756c, 0x00030005, 0x000000a6, 0x00726473, 0x00040005, 0x000000ab,
0x6c5f7962, 0x00006d75, 0x00040005, 0x000000b2, 0x61726170, 0x0000006d, 0x00030005, 0x000000bb,
0x00000063, 0x00040005, 0x000000bd, 0x61726170, 0x0000006d, 0x00030005, 0x000000c7, 0x00000073,
0x00040005, 0x000000c8, 0x61726170, 0x0000006d, 0x00030005, 0x000000cc, 0x0000006e, 0x00030005,
0x000000d1, 0x0000006d, 0x00040005, 0x000000d2, 0x61726170, 0x0000006d, 0x00030005, 0x000000d5,
0x00000064, 0x00040005, 0x000000e4, 0x64617267, 0x00000065, 0x00040005, 0x000000fa, 0x5f726473,
0x00000063, 0x00030005, 0x00000115, 0x00006d73, 0x00040005, 0x00000116, 0x61726170, 0x0000006d,
0x00030005, 0x00000119, 0x00006473, 0x00030005, 0x00000139, 0x00657568, 0x00030005, 0x0000013d,
0x00006379, 0x00030005, 0x00000144, 0x00007379, 0x00040005, 0x00000159, 0x61726170, 0x0000006d,
0x00030005, 0x00000160, 0x00706f74, 0x00040005, 0x00000161, 0x61726170, 0x0000006d, 0x00040005,
0x00000164, 0x65656e6b, 0x00000000, 0x00030005, 0x0000016c, 0x00000072, 0x00040005, 0x00000181,
0x6f6c6f63, 0x00000072, 0x00040047, 0x0000004f, 0x00000021, 0x00000001, 0x00040047, 0x0000004f,
0x00000022, 0x00000000, 0x00040047, 0x00000053, 0x0000001e, 0x00000000, 0x00040047, 0x0000005c,
0x00000021, 0x00000002, 0x00040047, 0x0000005c, 0x00000022, 0x00000000, 0x00040047, 0x00000066,
0x00000006, 0x00000010, 0x00030047, 0x00000067, 0x00000002, 0x00050048, 0x00000067, 0x00000000,
0x00000023, 0x00000000, 0x00040047, 0x00000069, 0x00000021, 0x00000003, 0x00040047, 0x00000069,
0x00000022, 0x00000000, 0x00040047, 0x00000070, 0x00000006, 0x00000010, 0x00030047, 0x00000071,
0x00000002, 0x00050048, 0x00000071, 0x00000000, 0x00000023, 0x00000000, 0x00040047, 0x00000073,
0x00000021, 0x00000004, 0x00040047, 0x00000073, 0x00000022, 0x00000000, 0x00040047, 0x00000078,
0x00000006, 0x00000010, 0x00030047, 0x00000079, 0x00000002, 0x00050048, 0x00000079, 0x00000000,
0x00000023, 0x00000000, 0x00050048, 0x00000079, 0x00000001, 0x00000023, 0x000005a0, 0x00040047,
0x0000007b, 0x00000021, 0x00000000, 0x00040047, 0x0000007b, 0x00000022, 0x00000000, 0x00040047,
0x00000181, 0x0000001e, 0x00000000, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002,
0x00030016, 0x00000006, 0x00000020, 0x00040020, 0x00000007, 0x00000007, 0x00000006, 0x00040021,
0x00000008, 0x00000006, 0x00000007, 0x00040017, 0x0000000c, 0x00000006, 0x00000003, 0x00040020,
0x0000000d, 0x00000007, 0x0000000c, 0x00040021, 0x0000000e, 0x0000000c, 0x0000000d, 0x00040021,
0x00000012, 0x00000006, 0x0000000d, 0x0004002b, 0x00000006, 0x00000017, 0x3e28aeed, 0x0004002b,
0x00000006, 0x00000019, 0x3e3851ec, 0x00020014, 0x0000001a, 0x0004002b, 0x00000006, 0x0000001f,
0x3f800000, 0x0004002b, 0x00000006, 0x00000026, 0x3f55d445, 0x00040015, 0x0000002f, 0x00000020,
0x00000000, 0x0004002b, 0x0000002f, 0x00000030, 0x00000000, 0x0004002b, 0x0000002f, 0x00000035,
0x00000001, 0x0004002b, 0x0000002f, 0x0000003a, 0x00000002, 0x00090019, 0x0000004c, 0x00000006,
0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0x00000000, 0x0003001b, 0x0000004d,
0x0000004c, 0x00040020, 0x0000004e, 0x00000000, 0x0000004d, 0x0004003b, 0x0000004e, 0x0000004f,
0x00000000, 0x00040017, 0x00000051, 0x00000006, 0x00000004, 0x00040020, 0x00000052, 0x00000001,
0x00000051, 0x0004003b, 0x00000052, 0x00000053, 0x00000001, 0x00040017, 0x00000054, 0x00000006,
0x00000002, 0x0004002b, 0x00000006, 0x00000059, 0x461c4000, 0x0006002c, 0x0000000c, 0x0000005a,
0x00000059, 0x00000059, 0x00000059, 0x0004003b, 0x0000004e, 0x0000005c, 0x00000000, 0x00040020,
0x00000063, 0x00000007, 0x00000051, 0x0004002b, 0x0000002f, 0x00000065, 0x00001000, 0x0004001c,
0x00000066, 0x00000051, 0x00000065, 0x0003001e, 0x00000067, 0x00000066, 0x00040020, 0x00000068,
0x00000002, 0x00000067, 0x0004003b, 0x00000068, 0x00000069, 0x00000002, 0x00040015, 0x0000006a,
0x00000020, 0x00000001, 0x0004002b, 0x0000006a, 0x0000006b, 0x00000000, 0x00040020, 0x0000006c,
0x00000002, 0x00000051, 0x0004001c, 0x00000070, 0x00000051, 0x00000065, 0x0003001e, 0x00000071,
0x00000070, 0x00040020, 0x00000072, 0x00000002, 0x00000071, 0x0004003b, 0x00000072, 0x00000073,
0x00000002, 0x0004002b, 0x0000002f, 0x00000077, 0x0000005a, 0x0004001c, 0x00000078, 0x00000051,
0x00000077, 0x0004001e, 0x00000079, 0x00000078, 0x00000051, 0x00040020, 0x0000007a, 0x00000002,
0x00000079, 0x0004003b, 0x0000007a, 0x0000007b, 0x00000002, 0x0004002b, 0x0000006a, 0x0000007c,
0x00000001, 0x00040020, 0x0000007d, 0x00000002, 0x00000006, 0x0004002b, 0x00000006, 0x00000080,
0x00000000, 0x0004002b, 0x00000006, 0x00000097, 0x3e99096c, 0x0006002c, 0x0000000c, 0x000000c5,
0x00000080, 0x00000080, 0x00000080, 0x0004002b, 0x00000006, 0x000000d8, 0x3f2aaaab, 0x0006002c,
0x0000000c, 0x00000108, 0x0000001f, 0x0000001f, 0x0000001f, 0x0004002b, 0x00000006, 0x0000013f,
0x3e59b3d0, 0x0004002b, 0x00000006, 0x00000140, 0x3f371759, 0x0004002b, 0x00000006, 0x00000141,
0x3d93dd98, 0x0006002c, 0x0000000c, 0x00000142, 0x0000013f, 0x00000140, 0x00000141, 0x0004002b,
0x00000006, 0x0000014a, 0x3727c5ac, 0x0004002b, 0x00000006, 0x00000157, 0x3f000000, 0x0004002b,
0x00000006, 0x00000158, 0x3fc00000, 0x00040020, 0x00000180, 0x00000003, 0x00000051, 0x0004003b,
0x00000180, 0x00000181, 0x00000003, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003,
0x000200f8, 0x00000005, 0x0004003b, 0x0000000d, 0x0000004b, 0x00000007, 0x0004003b, 0x00000063,
0x00000064, 0x00000007, 0x0004003b, 0x00000063, 0x0000006f, 0x00000007, 0x0004003b, 0x00000007,
0x00000076, 0x00000007, 0x0004003b, 0x00000007, 0x00000082, 0x00000007, 0x0004003b, 0x00000007,
0x00000089, 0x00000007, 0x0004003b, 0x00000007, 0x0000008d, 0x00000007, 0x0004003b, 0x00000007,
0x00000094, 0x00000007, 0x0004003b, 0x00000007, 0x000000a6, 0x00000007, 0x0004003b, 0x0000000d,
0x000000ab, 0x00000007, 0x0004003b, 0x0000000d, 0x000000ae, 0x00000007, 0x0004003b, 0x00000007,
0x000000b2, 0x00000007, 0x0004003b, 0x0000000d, 0x000000bb, 0x00000007, 0x0004003b, 0x0000000d,
0x000000bd, 0x00000007, 0x0004003b, 0x00000007, 0x000000c7, 0x00000007, 0x0004003b, 0x0000000d,
0x000000c8, 0x00000007, 0x0004003b, 0x0000000d, 0x000000cc, 0x00000007, 0x0004003b, 0x00000007,
0x000000d1, 0x00000007, 0x0004003b, 0x0000000d, 0x000000d2, 0x00000007, 0x0004003b, 0x00000007,
0x000000d5, 0x00000007, 0x0004003b, 0x00000007, 0x000000e4, 0x00000007, 0x0004003b, 0x0000000d,
0x000000fa, 0x00000007, 0x0004003b, 0x0000000d, 0x000000fd, 0x00000007, 0x0004003b, 0x00000007,
0x00000115, 0x00000007, 0x0004003b, 0x0000000d, 0x00000116, 0x00000007, 0x0004003b, 0x00000007,
0x00000119, 0x00000007, 0x0004003b, 0x00000007, 0x00000139, 0x00000007, 0x0004003b, 0x00000007,
0x0000013d, 0x00000007, 0x0004003b, 0x00000007, 0x00000144, 0x00000007, 0x0004003b, 0x0000000d,
0x00000159, 0x00000007, 0x0004003b, 0x00000007, 0x00000160, 0x00000007, 0x0004003b, 0x0000000d,
0x00000161, 0x00000007, 0x0004003b, 0x00000007, 0x00000164, 0x00000007, 0x0004003b, 0x00000007,
0x0000016c, 0x00000007, 0x0004003d, 0x0000004d, 0x00000050, 0x0000004f, 0x0004003d, 0x00000051,
0x00000055, 0x00000053, 0x0007004f, 0x00000054, 0x00000056, 0x00000055, 0x00000055, 0x00000000,
0x00000001, 0x00050057, 0x00000051, 0x00000057, 0x00000050, 0x00000056, 0x0008004f, 0x0000000c,
0x00000058, 0x00000057, 0x00000057, 0x00000000, 0x00000001, 0x00000002, 0x0007000c, 0x0000000c,
0x0000005b, 0x00000001, 0x00000025, 0x00000058, 0x0000005a, 0x0004003d, 0x0000004d, 0x0000005d,
0x0000005c, 0x0004003d, 0x00000051, 0x0000005e, 0x00000053, 0x0007004f, 0x00000054, 0x0000005f,
0x0000005e, 0x0000005e, 0x00000000, 0x00000001, 0x00050057, 0x00000051, 0x00000060, 0x0000005d,
0x0000005f, 0x0008004f, 0x0000000c, 0x00000061, 0x00000060, 0x00000060, 0x00000000, 0x00000001,
0x00000002, 0x00050081, 0x0000000c, 0x00000062, 0x0000005b, 0x00000061, 0x0003003e, 0x0000004b,
0x00000062, 0x00060041, 0x0000006c, 0x0000006d, 0x00000069, 0x0000006b, 0x0000006b, 0x0004003d,
0x00000051, 0x0000006e, 0x0000006d, 0x0003003e, 0x00000064, 0x0000006e, 0x00060041, 0x0000006c,
0x00000074, 0x00000073, 0x0000006b, 0x0000006b, 0x0004003d, 0x00000051, 0x00000075, 0x00000074,
0x0003003e, 0x0000006f, 0x00000075, 0x00060041, 0x0000007d, 0x0000007e, 0x0000007b, 0x0000007c,
0x00000030, 0x0004003d, 0x00000006, 0x0000007f, 0x0000007e, 0x000500ba, 0x0000001a, 0x00000081,
0x0000007f, 0x00000080, 0x000300f7, 0x00000084, 0x00000000, 0x000400fa, 0x00000081, 0x00000083,
0x00000087, 0x000200f8, 0x00000083, 0x00060041, 0x0000007d, 0x00000085, 0x0000007b, 0x0000007c,
0x00000030, 0x0004003d, 0x00000006, 0x00000086, 0x00000085, 0x0003003e, 0x00000082, 0x00000086,
0x000200f9, 0x00000084, 0x000200f8, 0x00000087, 0x0003003e, 0x00000082, 0x0000001f, 0x000200f9,
0x00000084, 0x000200f8, 0x00000084, 0x0004003d, 0x00000006, 0x00000088, 0x00000082, 0x0003003e,
0x00000076, 0x00000088, 0x00060041, 0x0000007d, 0x0000008a, 0x0000007b, 0x0000007c, 0x00000035,
0x0004003d, 0x00000006, 0x0000008b, 0x0000008a, 0x000500ba, 0x0000001a, 0x0000008c, 0x0000008b,
0x0000001f, 0x000300f7, 0x0000008f, 0x00000000, 0x000400fa, 0x0000008c, 0x0000008e, 0x00000092,
0x000200f8, 0x0000008e, 0x00060041, 0x0000007d, 0x00000090, 0x0000007b, 0x0000007c, 0x00000035,
0x0004003d, 0x00000006, 0x00000091, 0x00000090, 0x0003003e, 0x0000008d, 0x00000091, 0x000200f9,
0x0000008f, 0x000200f8, 0x00000092, 0x0003003e, 0x0000008d, 0x0000001f, 0x000200f9, 0x0000008f,
0x000200f8, 0x0000008f, 0x0004003d, 0x00000006, 0x00000093, 0x0000008d, 0x0003003e, 0x00000089,
0x00000093, 0x00050041, 0x00000007, 0x00000095, 0x0000004b, 0x00000030, 0x0004003d, 0x00000006,
0x00000096, 0x00000095, 0x00050085, 0x00000006, 0x00000098, 0x00000096, 0x00000097, 0x00050041,
0x00000007, 0x00000099, 0x0000004b, 0x00000035, 0x0004003d, 0x00000006, 0x0000009a, 0x00000099,
0x00050041, 0x00000007, 0x0000009b, 0x00000064, 0x00000030, 0x0004003d, 0x00000006, 0x0000009c,
0x0000009b, 0x00050085, 0x00000006, 0x0000009d, 0x0000009a, 0x0000009c, 0x00050081, 0x00000006,
0x0000009e, 0x00000098, 0x0000009d, 0x00050041, 0x00000007, 0x0000009f, 0x0000004b, 0x0000003a,
0x0004003d, 0x00000006, 0x000000a0, 0x0000009f, 0x00050041, 0x00000007, 0x000000a1, 0x00000064,
0x00000035, 0x0004003d, 0x00000006, 0x000000a2, 0x000000a1, 0x00050085, 0x00000006, 0x000000a3,
0x000000a0, 0x000000a2, 0x00050081, 0x00000006, 0x000000a4, 0x0000009e, 0x000000a3, 0x0007000c,
0x00000006, 0x000000a5, 0x00000001, 0x00000028, 0x000000a4, 0x00000080, 0x0003003e, 0x00000094,
0x000000a5, 0x0004003d, 0x00000006, 0x000000a7, 0x00000094, 0x0004007f, 0x00000006, 0x000000a8,
0x000000a7, 0x0006000c, 0x00000006, 0x000000a9, 0x00000001, 0x0000001b, 0x000000a8, 0x00050083,
0x00000006, 0x000000aa, 0x0000001f, 0x000000a9, 0x0003003e, 0x000000a6, 0x000000aa, 0x0004003d,
0x00000006, 0x000000ac, 0x00000094, 0x000500ba, 0x0000001a, 0x000000ad, 0x000000ac, 0x00000080,
0x000300f7, 0x000000b0, 0x00000000, 0x000400fa, 0x000000ad, 0x000000af, 0x000000b8, 0x000200f8,
0x000000af, 0x0004003d, 0x0000000c, 0x000000b1, 0x0000004b, 0x0004003d, 0x00000006, 0x000000b3,
0x00000094, 0x0003003e, 0x000000b2, 0x000000b3, 0x00050039, 0x00000006, 0x000000b4, 0x0000000a,
0x000000b2, 0x0004003d, 0x00000006, 0x000000b5, 0x00000094, 0x00050088, 0x00000006, 0x000000b6,
0x000000b4, 0x000000b5, 0x0005008e, 0x0000000c, 0x000000b7, 0x000000b1, 0x000000b6, 0x0003003e,
0x000000ae, 0x000000b7, 0x000200f9, 0x000000b0, 0x000200f8, 0x000000b8, 0x0004003d, 0x0000000c,
0x000000b9, 0x0000004b, 0x0003003e, 0x000000ae, 0x000000b9, 0x000200f9, 0x000000b0, 0x000200f8,
0x000000b0, 0x0004003d, 0x0000000c, 0x000000ba, 0x000000ae, 0x0003003e, 0x000000ab, 0x000000ba,
0x0004003d, 0x0000000c, 0x000000bc, 0x000000ab, 0x0004003d, 0x0000000c, 0x000000be, 0x0000004b,
0x0003003e, 0x000000bd, 0x000000be, 0x00050039, 0x0000000c, 0x000000bf, 0x00000010, 0x000000bd,
0x0004003d, 0x00000006, 0x000000c0, 0x000000a6, 0x0004003d, 0x00000006, 0x000000c1, 0x000000a6,
0x00050085, 0x00000006, 0x000000c2, 0x000000c0, 0x000000c1, 0x00060050, 0x0000000c, 0x000000c3,
0x000000c2, 0x000000c2, 0x000000c2, 0x0008000c, 0x0000000c, 0x000000c4, 0x00000001, 0x0000002e,
0x000000bc, 0x000000bf, 0x000000c3, 0x0007000c, 0x0000000c, 0x000000c6, 0x00000001, 0x00000028,
0x000000c4, 0x000000c5, 0x0003003e, 0x000000bb, 0x000000c6, 0x0004003d, 0x0000000c, 0x000000c9,
0x000000bb, 0x0003003e, 0x000000c8, 0x000000c9, 0x00050039, 0x00000006, 0x000000ca, 0x00000014,
0x000000c8, 0x0007000c, 0x00000006, 0x000000cb, 0x00000001, 0x00000028, 0x000000ca, 0x0000001f,
0x0003003e, 0x000000c7, 0x000000cb, 0x0004003d, 0x0000000c, 0x000000cd, 0x000000bb, 0x0004003d,
0x00000006, 0x000000ce, 0x000000c7, 0x00060050, 0x0000000c, 0x000000cf, 0x000000ce, 0x000000ce,
0x000000ce, 0x00050088, 0x0000000c, 0x000000d0, 0x000000cd, 0x000000cf, 0x0003003e, 0x000000cc,
0x000000d0, 0x0004003d, 0x0000000c, 0x000000d3, 0x000000cc, 0x0003003e, 0x000000d2, 0x000000d3,
0x00050039, 0x00000006, 0x000000d4, 0x00000014, 0x000000d2, 0x0003003e, 0x000000d1, 0x000000d4,
0x00050041, 0x00000007, 0x000000d6, 0x000000cc, 0x00000030, 0x0004003d, 0x00000006, 0x000000d7,
0x000000d6, 0x00050085, 0x00000006, 0x000000d9, 0x000000d7, 0x000000d8, 0x00050041, 0x00000007,
0x000000da, 0x000000cc, 0x00000035, 0x0004003d, 0x00000006, 0x000000db, 0x000000da, 0x00050041,
0x00000007, 0x000000dc, 0x000000cc, 0x0000003a, 0x0004003d, 0x00000006, 0x000000dd, 0x000000dc,
0x00050081, 0x00000006, 0x000000de, 0x000000db, 0x000000dd, 0x00050041, 0x00000007, 0x000000df,
0x00000064, 0x0000003a, 0x0004003d, 0x00000006, 0x000000e0, 0x000000df, 0x00050085, 0x00000006,
0x000000e1, 0x000000de, 0x000000e0, 0x00050081, 0x00000006, 0x000000e2, 0x000000d9, 0x000000e1,
0x00050083, 0x00000006, 0x000000e3, 0x000000e2, 0x0000001f, 0x0003003e, 0x000000d5, 0x000000e3,
0x00050041, 0x00000007, 0x000000e5, 0x0000006f, 0x00000035, 0x0004003d, 0x00000006, 0x000000e6,
0x000000e5, 0x0004003d, 0x00000006, 0x000000e7, 0x000000d5, 0x0004003d, 0x00000006, 0x000000e8,
0x000000d5, 0x00050085, 0x00000006, 0x000000e9, 0x000000e7, 0x000000e8, 0x00050083, 0x00000006,
0x000000ea, 0x0000001f, 0x000000e9, 0x00050085, 0x00000006, 0x000000eb, 0x000000e6, 0x000000ea,
0x00050041, 0x00000007, 0x000000ec, 0x0000006f, 0x00000030, 0x0004003d, 0x00000006, 0x000000ed,
0x000000ec, 0x00050081, 0x00000006, 0x000000ee, 0x000000eb, 0x000000ed, 0x0003003e, 0x000000e4,
0x000000ee, 0x0004003d, 0x00000006, 0x000000ef, 0x000000c7, 0x0004003d, 0x0000000c, 0x000000f0,
0x000000cc, 0x0004003d, 0x00000006, 0x000000f1, 0x000000d1, 0x00060050, 0x0000000c, 0x000000f2,
0x000000f1, 0x000000f1, 0x000000f1, 0x00050083, 0x0000000c, 0x000000f3, 0x000000f0, 0x000000f2,
0x0004003d, 0x00000006, 0x000000f4, 0x000000e4, 0x0005008e, 0x0000000c, 0x000000f5, 0x000000f3,
0x000000f4, 0x0004003d, 0x00000006, 0x000000f6, 0x000000d1, 0x00060050, 0x0000000c, 0x000000f7,
0x000000f6, 0x000000f6, 0x000000f6, 0x00050081, 0x0000000c, 0x000000f8, 0x000000f5, 0x000000f7,
0x0005008e, 0x0000000c, 0x000000f9, 0x000000f8, 0x000000ef, 0x0003003e, 0x000000bb, 0x000000f9,
0x0004003d, 0x00000006, 0x000000fb, 0x00000094, 0x000500ba, 0x0000001a, 0x000000fc, 0x000000fb,
0x00000080, 0x000300f7, 0x000000ff, 0x00000000, 0x000400fa, 0x000000fc, 0x000000fe, 0x00000105,
0x000200f8, 0x000000fe, 0x0004003d, 0x0000000c, 0x00000100, 0x0000004b, 0x0004003d, 0x00000006,
0x00000101, 0x000000a6, 0x0004003d, 0x00000006, 0x00000102, 0x00000094, 0x00050088, 0x00000006,
0x00000103, 0x00000101, 0x00000102, 0x0005008e, 0x0000000c, 0x00000104, 0x00000100, 0x00000103,
0x0003003e, 0x000000fd, 0x00000104, 0x000200f9, 0x000000ff, 0x000200f8, 0x00000105, 0x0004003d,
0x0000000c, 0x00000106, 0x0000004b, 0x0003003e, 0x000000fd, 0x00000106, 0x000200f9, 0x000000ff,
0x000200f8, 0x000000ff, 0x0004003d, 0x0000000c, 0x00000107, 0x000000fd, 0x0004003d, 0x0000000c,
0x00000109, 0x0000004b, 0x0004007f, 0x0000000c, 0x0000010a, 0x00000109, 0x0006000c, 0x0000000c,
0x0000010b, 0x00000001, 0x0000001b, 0x0000010a, 0x00050083, 0x0000000c, 0x0000010c, 0x00000108,
0x0000010b, 0x0004003d, 0x00000006, 0x0000010d, 0x000000a6, 0x0004003d, 0x00000006, 0x0000010e,
0x000000a6, 0x00050085, 0x00000006, 0x0000010f, 0x0000010d, 0x0000010e, 0x00060050, 0x0000000c,
0x00000110, 0x0000010f, 0x0000010f, 0x0000010f, 0x0008000c, 0x0000000c, 0x00000111, 0x00000001,
0x0000002e, 0x00000107, 0x0000010c, 0x00000110, 0x00060050, 0x0000000c, 0x00000112, 0x00000080,
0x00000080, 0x00000080, 0x00060050, 0x0000000c, 0x00000113, 0x0000001f, 0x0000001f, 0x0000001f,
0x0008000c, 0x0000000c, 0x00000114, 0x00000001, 0x0000002b, 0x00000111, 0x00000112, 0x00000113,
0x0003003e, 0x000000fa, 0x00000114, 0x0004003d, 0x0000000c, 0x00000117, 0x000000fa, 0x0003003e,
0x00000116, 0x00000117, 0x00050039, 0x00000006, 0x00000118, 0x00000014, 0x00000116, 0x0003003e,
0x00000115, 0x00000118, 0x00050041, 0x00000007, 0x0000011a, 0x000000fa, 0x00000030, 0x0004003d,
0x00000006, 0x0000011b, 0x0000011a, 0x00050085, 0x00000006, 0x0000011c, 0x0000011b, 0x000000d8,
0x00050041, 0x00000007, 0x0000011d, 0x000000fa, 0x00000035, 0x0004003d, 0x00000006, 0x0000011e,
0x0000011d, 0x00050041, 0x00000007, 0x0000011f, 0x000000fa, 0x0000003a, 0x0004003d, 0x00000006,
0x00000120, 0x0000011f, 0x00050081, 0x00000006, 0x00000121, 0x0000011e, 0x00000120, 0x00050041,
0x00000007, 0x00000122, 0x00000064, 0x0000003a, 0x0004003d, 0x00000006, 0x00000123, 0x00000122,
0x00050085, 0x00000006, 0x00000124, 0x00000121, 0x00000123, 0x00050081, 0x00000006, 0x00000125,
0x0000011c, 0x00000124, 0x00050083, 0x00000006, 0x00000126, 0x00000125, 0x0000001f, 0x0003003e,
0x00000119, 0x00000126, 0x0004003d, 0x0000000c, 0x00000127, 0x000000fa, 0x0004003d, 0x00000006,
0x00000128, 0x00000115, 0x00060050, 0x0000000c, 0x00000129, 0x00000128, 0x00000128, 0x00000128,
0x00050083, 0x0000000c, 0x0000012a, 0x00000127, 0x00000129, 0x00050041, 0x00000007, 0x0000012b,
0x0000006f, 0x00000035, 0x0004003d, 0x00000006, 0x0000012c, 0x0000012b, 0x0004003d, 0x00000006,
0x0000012d, 0x00000119, 0x0004003d, 0x00000006, 0x0000012e, 0x00000119, 0x00050085, 0x00000006,
0x0000012f, 0x0000012d, 0x0000012e, 0x00050083, 0x00000006, 0x00000130, 0x0000001f, 0x0000012f,
0x00050085, 0x00000006, 0x00000131, 0x0000012c, 0x00000130, 0x00050041, 0x00000007, 0x00000132,
0x0000006f, 0x00000030, 0x0004003d, 0x00000006, 0x00000133, 0x00000132, 0x00050081, 0x00000006,
0x00000134, 0x00000131, 0x00000133, 0x0005008e, 0x0000000c, 0x00000135, 0x0000012a, 0x00000134,
0x0004003d, 0x00000006, 0x00000136, 0x00000115, 0x00060050, 0x0000000c, 0x00000137, 0x00000136,
0x00000136, 0x00000136, 0x00050081, 0x0000000c, 0x00000138, 0x00000135, 0x00000137, 0x0003003e,
0x000000fa, 0x00000138, 0x00060041, 0x0000007d, 0x0000013a, 0x0000007b, 0x0000007c, 0x0000003a,
0x0004003d, 0x00000006, 0x0000013b, 0x0000013a, 0x0008000c, 0x00000006, 0x0000013c, 0x00000001,
0x0000002b, 0x0000013b, 0x00000080, 0x0000001f, 0x0003003e, 0x00000139, 0x0000013c, 0x0004003d,
0x0000000c, 0x0000013e, 0x000000bb, 0x00050094, 0x00000006, 0x00000143, 0x0000013e, 0x00000142,
0x0003003e, 0x0000013d, 0x00000143, 0x0004003d, 0x0000000c, 0x00000145, 0x000000fa, 0x00050094,
0x00000006, 0x00000146, 0x00000145, 0x00000142, 0x0003003e, 0x00000144, 0x00000146, 0x0004003d,
0x00000006, 0x00000147, 0x00000139, 0x000500ba, 0x0000001a, 0x00000148, 0x00000147, 0x00000080,
0x0004003d, 0x00000006, 0x00000149, 0x00000144, 0x000500ba, 0x0000001a, 0x0000014b, 0x00000149,
0x0000014a, 0x000500a7, 0x0000001a, 0x0000014c, 0x00000148, 0x0000014b, 0x000300f7, 0x0000014e,
0x00000000, 0x000400fa, 0x0000014c, 0x0000014d, 0x0000014e, 0x000200f8, 0x0000014d, 0x0004003d,
0x0000000c, 0x0000014f, 0x000000bb, 0x0004003d, 0x0000000c, 0x00000150, 0x000000fa, 0x0007000c,
0x0000000c, 0x00000151, 0x00000001, 0x00000028, 0x00000150, 0x000000c5, 0x0004003d, 0x00000006,
0x00000152, 0x0000013d, 0x0004003d, 0x00000006, 0x00000153, 0x00000144, 0x00050088, 0x00000006,
0x00000154, 0x00000152, 0x00000153, 0x0005008e, 0x0000000c, 0x00000155, 0x00000151, 0x00000154,
0x0004003d, 0x00000006, 0x00000156, 0x00000139, 0x0004003d, 0x0000000c, 0x0000015a, 0x000000bb,
0x0003003e, 0x00000159, 0x0000015a, 0x00050039, 0x00000006, 0x0000015b, 0x00000014, 0x00000159,
0x0008000c, 0x00000006, 0x0000015c, 0x00000001, 0x00000031, 0x00000157, 0x00000158, 0x0000015b,
0x00050085, 0x00000006, 0x0000015d, 0x00000156, 0x0000015c, 0x00060050, 0x0000000c, 0x0000015e,
0x0000015d, 0x0000015d, 0x0000015d, 0x0008000c, 0x0000000c, 0x0000015f, 0x00000001, 0x0000002e,
0x0000014f, 0x00000155, 0x0000015e, 0x0003003e, 0x000000bb, 0x0000015f, 0x000200f9, 0x0000014e,
0x000200f8, 0x0000014e, 0x0004003d, 0x0000000c, 0x00000162, 0x000000bb, 0x0003003e, 0x00000161,
0x00000162, 0x00050039, 0x00000006, 0x00000163, 0x00000014, 0x00000161, 0x0003003e, 0x00000160,
0x00000163, 0x0004003d, 0x00000006, 0x00000165, 0x00000089, 0x00050085, 0x00000006, 0x00000166,
0x00000157, 0x00000165, 0x0003003e, 0x00000164, 0x00000166, 0x0004003d, 0x00000006, 0x00000167,
0x00000160, 0x0004003d, 0x00000006, 0x00000168, 0x00000164, 0x000500ba, 0x0000001a, 0x00000169,
0x00000167, 0x00000168, 0x000300f7, 0x0000016b, 0x00000000, 0x000400fa, 0x00000169, 0x0000016a,
0x0000016b, 0x000200f8, 0x0000016a, 0x0004003d, 0x00000006, 0x0000016d, 0x00000089, 0x0004003d,
0x00000006, 0x0000016e, 0x00000164, 0x00050083, 0x00000006, 0x0000016f, 0x0000016d, 0x0000016e,
0x0003003e, 0x0000016c, 0x0000016f, 0x0004003d, 0x00000006, 0x00000170, 0x00000164, 0x0004003d,
0x00000006, 0x00000171, 0x0000016c, 0x0004003d, 0x00000006, 0x00000172, 0x00000160, 0x0004003d,
0x00000006, 0x00000173, 0x00000164, 0x00050083, 0x00000006, 0x00000174, 0x00000172, 0x00000173,
0x0004007f, 0x00000006, 0x00000175, 0x00000174, 0x0004003d, 0x00000006, 0x00000176, 0x0000016c,
0x00050088, 0x00000006, 0x00000177, 0x00000175, 0x00000176, 0x0006000c, 0x00000006, 0x00000178,
0x00000001, 0x0000001b, 0x00000177, 0x00050083, 0x00000006, 0x00000179, 0x0000001f, 0x00000178,
0x00050085, 0x00000006, 0x0000017a, 0x00000171, 0x00000179, 0x00050081, 0x00000006, 0x0000017b,
0x00000170, 0x0000017a, 0x0004003d, 0x00000006, 0x0000017c, 0x00000160, 0x00050088, 0x00000006,
0x0000017d, 0x0000017b, 0x0000017c, 0x0004003d, 0x0000000c, 0x0000017e, 0x000000bb, 0x0005008e,
0x0000000c, 0x0000017f, 0x0000017e, 0x0000017d, 0x0003003e, 0x000000bb, 0x0000017f, 0x000200f9,
0x0000016b, 0x000200f8, 0x0000016b, 0x0004003d, 0x0000000c, 0x00000182, 0x000000bb, 0x0007000c,
0x0000000c, 0x00000183, 0x00000001, 0x00000028, 0x00000182, 0x000000c5, 0x0004003d, 0x00000006,
0x00000184, 0x00000076, 0x0005008e, 0x0000000c, 0x00000185, 0x00000183, 0x00000184, 0x00050051,
0x00000006, 0x00000186, 0x00000185, 0x00000000, 0x00050051, 0x00000006, 0x00000187, 0x00000185,
0x00000001, 0x00050051, 0x00000006, 0x00000188, 0x00000185, 0x00000002, 0x00070050, 0x00000051,
0x00000189, 0x00000186, 0x00000187, 0x00000188, 0x00000080, 0x0003003e, 0x00000181, 0x00000189,
0x000100fd, 0x00010038, 0x00050036, 0x00000006, 0x0000000a, 0x00000000, 0x00000008, 0x00030037,
0x00000007, 0x00000009, 0x000200f8, 0x0000000b, 0x0004003b, 0x00000007, 0x00000016, 0x00000007,
0x0004003b, 0x00000007, 0x0000001c, 0x00000007, 0x0003003e, 0x00000016, 0x00000017, 0x0004003d,
0x00000006, 0x00000018, 0x00000009, 0x000500bc, 0x0000001a, 0x0000001b, 0x00000018, 0x00000019,
0x000300f7, 0x0000001e, 0x00000000, 0x000400fa, 0x0000001b, 0x0000001d, 0x00000024, 0x000200f8,
0x0000001d, 0x0004003d, 0x00000006, 0x00000020, 0x00000009, 0x0004007f, 0x00000006, 0x00000021,
0x00000020, 0x0006000c, 0x00000006, 0x00000022, 0x00000001, 0x0000001b, 0x00000021, 0x00050083,
0x00000006, 0x00000023, 0x0000001f, 0x00000022, 0x0003003e, 0x0000001c, 0x00000023, 0x000200f9,
0x0000001e, 0x000200f8, 0x00000024, 0x0004003d, 0x00000006, 0x00000025, 0x00000016, 0x0004003d,
0x00000006, 0x00000027, 0x00000009, 0x00050083, 0x00000006, 0x00000028, 0x00000027, 0x00000019,
0x00050085, 0x00000006, 0x00000029, 0x00000026, 0x00000028, 0x00050081, 0x00000006, 0x0000002a,
0x00000025, 0x00000029, 0x0003003e, 0x0000001c, 0x0000002a, 0x000200f9, 0x0000001e, 0x000200f8,
0x0000001e, 0x0004003d, 0x00000006, 0x0000002b, 0x0000001c, 0x000200fe, 0x0000002b, 0x00010038,
0x00050036, 0x0000000c, 0x00000010, 0x00000000, 0x0000000e, 0x00030037, 0x0000000d, 0x0000000f,
0x000200f8, 0x00000011, 0x0004003b, 0x00000007, 0x0000002e, 0x00000007, 0x0004003b, 0x00000007,
0x00000034, 0x00000007, 0x0004003b, 0x00000007, 0x00000039, 0x00000007, 0x00050041, 0x00000007,
0x00000031, 0x0000000f, 0x00000030, 0x0004003d, 0x00000006, 0x00000032, 0x00000031, 0x0003003e,
0x0000002e, 0x00000032, 0x00050039, 0x00000006, 0x00000033, 0x0000000a, 0x0000002e, 0x00050041,
0x00000007, 0x00000036, 0x0000000f, 0x00000035, 0x0004003d, 0x00000006, 0x00000037, 0x00000036,
0x0003003e, 0x00000034, 0x00000037, 0x00050039, 0x00000006, 0x00000038, 0x0000000a, 0x00000034,
0x00050041, 0x00000007, 0x0000003b, 0x0000000f, 0x0000003a, 0x0004003d, 0x00000006, 0x0000003c,
0x0000003b, 0x0003003e, 0x00000039, 0x0000003c, 0x00050039, 0x00000006, 0x0000003d, 0x0000000a,
0x00000039, 0x00060050, 0x0000000c, 0x0000003e, 0x00000033, 0x00000038, 0x0000003d, 0x000200fe,
0x0000003e, 0x00010038, 0x00050036, 0x00000006, 0x00000014, 0x00000000, 0x00000012, 0x00030037,
0x0000000d, 0x00000013, 0x000200f8, 0x00000015, 0x00050041, 0x00000007, 0x00000041, 0x00000013,
0x00000030, 0x0004003d, 0x00000006, 0x00000042, 0x00000041, 0x00050041, 0x00000007, 0x00000043,
0x00000013, 0x00000035, 0x0004003d, 0x00000006, 0x00000044, 0x00000043, 0x00050041, 0x00000007,
0x00000045, 0x00000013, 0x0000003a, 0x0004003d, 0x00000006, 0x00000046, 0x00000045, 0x0007000c,
0x00000006, 0x00000047, 0x00000001, 0x00000028, 0x00000044, 0x00000046, 0x0007000c, 0x00000006,
0x00000048, 0x00000001, 0x00000028, 0x00000042, 0x00000047, 0x000200fe, 0x00000048, 0x00010038,
};
+73
View File
@@ -0,0 +1,73 @@
// Generated by tools/build_shaders.py from runtime/shaders/hdr_ui.frag; do not edit.
// source sha256 59cfbb1ab5393fdb743016cbf75a085ee8a05929c7ea67a69b4ab77f26a14303
#pragma once
#include <stdint.h>
static const uint32_t hdr_ui_spv[] = {
0x07230203, 0x00010300, 0x000d000b, 0x000000be, 0x00000000, 0x00020011, 0x00000001, 0x0006000b,
0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001,
0x0007000f, 0x00000004, 0x00000004, 0x6e69616d, 0x00000000, 0x0000004f, 0x00000068, 0x00030010,
0x00000004, 0x00000007, 0x00040047, 0x0000004b, 0x00000021, 0x00000000, 0x00040047, 0x0000004b,
0x00000022, 0x00000000, 0x00040047, 0x0000004f, 0x0000001e, 0x00000000, 0x00040047, 0x00000068,
0x0000001e, 0x00000000, 0x00030047, 0x0000007b, 0x00000002, 0x00050048, 0x0000007b, 0x00000000,
0x00000023, 0x00000000, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00030016,
0x00000006, 0x00000020, 0x00040017, 0x00000007, 0x00000006, 0x00000003, 0x0004002b, 0x00000006,
0x00000015, 0x3d6147ae, 0x0004002b, 0x00000006, 0x0000001b, 0x4019999a, 0x0006002c, 0x00000007,
0x0000001c, 0x0000001b, 0x0000001b, 0x0000001b, 0x0004002b, 0x00000006, 0x0000001f, 0x3d25aee6,
0x0006002c, 0x00000007, 0x00000020, 0x0000001f, 0x0000001f, 0x0000001f, 0x00020014, 0x00000021,
0x00040017, 0x00000022, 0x00000021, 0x00000003, 0x0004002b, 0x00000006, 0x0000002c, 0x00000000,
0x0004002b, 0x00000006, 0x0000002d, 0x3f800000, 0x0004002b, 0x00000006, 0x00000031, 0x3e232000,
0x0006002c, 0x00000007, 0x00000032, 0x00000031, 0x00000031, 0x00000031, 0x0004002b, 0x00000006,
0x00000034, 0x3f560000, 0x0004002b, 0x00000006, 0x00000035, 0x4196d000, 0x0004002b, 0x00000006,
0x0000003a, 0x41958000, 0x0004002b, 0x00000006, 0x00000040, 0x429db000, 0x0006002c, 0x00000007,
0x00000041, 0x00000040, 0x00000040, 0x00000040, 0x00040017, 0x00000045, 0x00000006, 0x00000004,
0x00090019, 0x00000048, 0x00000006, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000001,
0x00000000, 0x0003001b, 0x00000049, 0x00000048, 0x00040020, 0x0000004a, 0x00000000, 0x00000049,
0x0004003b, 0x0000004a, 0x0000004b, 0x00000000, 0x00040017, 0x0000004d, 0x00000006, 0x00000002,
0x00040020, 0x0000004e, 0x00000001, 0x0000004d, 0x0004003b, 0x0000004e, 0x0000004f, 0x00000001,
0x00040015, 0x00000052, 0x00000020, 0x00000000, 0x00040020, 0x00000067, 0x00000003, 0x00000045,
0x0004003b, 0x00000067, 0x00000068, 0x00000003, 0x00040018, 0x00000069, 0x00000007, 0x00000003,
0x0004002b, 0x00000006, 0x0000006a, 0x3f209d49, 0x0004002b, 0x00000006, 0x0000006b, 0x3d8d844d,
0x0004002b, 0x00000006, 0x0000006c, 0x3c86594b, 0x0006002c, 0x00000007, 0x0000006d, 0x0000006a,
0x0000006b, 0x0000006c, 0x0004002b, 0x00000006, 0x0000006e, 0x3ea89a02, 0x0004002b, 0x00000006,
0x0000006f, 0x3f6b645a, 0x0004002b, 0x00000006, 0x00000070, 0x3db43958, 0x0006002c, 0x00000007,
0x00000071, 0x0000006e, 0x0000006f, 0x00000070, 0x0004002b, 0x00000006, 0x00000072, 0x3d315b57,
0x0004002b, 0x00000006, 0x00000073, 0x3c3ac711, 0x0004002b, 0x00000006, 0x00000074, 0x3f65460b,
0x0006002c, 0x00000007, 0x00000075, 0x00000072, 0x00000073, 0x00000074, 0x0006002c, 0x00000069,
0x00000076, 0x0000006d, 0x00000071, 0x00000075, 0x0006002c, 0x00000007, 0x00000079, 0x0000002c,
0x0000002c, 0x0000002c, 0x0003001e, 0x0000007b, 0x00000045, 0x00040020, 0x0000007c, 0x00000009,
0x0000007b, 0x0004003b, 0x0000007c, 0x0000007d, 0x00000009, 0x00040015, 0x0000007e, 0x00000020,
0x00000001, 0x0004002b, 0x0000007e, 0x0000007f, 0x00000000, 0x0004002b, 0x00000052, 0x00000080,
0x00000000, 0x00040020, 0x00000081, 0x00000009, 0x00000006, 0x0006002c, 0x00000007, 0x000000b2,
0x0000002d, 0x0000002d, 0x0000002d, 0x0006002c, 0x00000007, 0x000000b4, 0x00000015, 0x00000015,
0x00000015, 0x0006002c, 0x00000007, 0x000000b7, 0x00000034, 0x00000034, 0x00000034, 0x0004002b,
0x00000006, 0x000000b8, 0x3d9e8391, 0x0006002c, 0x00000007, 0x000000b9, 0x000000b8, 0x000000b8,
0x000000b8, 0x0004002b, 0x00000006, 0x000000ba, 0x3f72a76f, 0x0006002c, 0x00000007, 0x000000bb,
0x000000ba, 0x000000ba, 0x000000ba, 0x0004002b, 0x00000006, 0x000000bc, 0x38d1b717, 0x0006002c,
0x00000007, 0x000000bd, 0x000000bc, 0x000000bc, 0x000000bc, 0x00050036, 0x00000002, 0x00000004,
0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x0004003d, 0x00000049, 0x0000004c, 0x0000004b,
0x0004003d, 0x0000004d, 0x00000050, 0x0000004f, 0x00050057, 0x00000045, 0x00000051, 0x0000004c,
0x00000050, 0x00050051, 0x00000006, 0x00000056, 0x00000051, 0x00000003, 0x000500bc, 0x00000021,
0x00000057, 0x00000056, 0x0000002c, 0x000300f7, 0x00000059, 0x00000000, 0x000400fa, 0x00000057,
0x00000058, 0x00000059, 0x000200f8, 0x00000058, 0x000100fc, 0x000200f8, 0x00000059, 0x0008004f,
0x00000007, 0x0000005d, 0x00000051, 0x00000051, 0x00000000, 0x00000001, 0x00000002, 0x00060050,
0x00000007, 0x00000060, 0x00000056, 0x00000056, 0x00000056, 0x00050088, 0x00000007, 0x00000061,
0x0000005d, 0x00000060, 0x0008000c, 0x00000007, 0x00000064, 0x00000001, 0x0000002b, 0x00000061,
0x00000079, 0x000000b2, 0x00050085, 0x00000007, 0x00000091, 0x00000064, 0x000000b9, 0x00050081,
0x00000007, 0x00000094, 0x00000064, 0x000000b4, 0x00050085, 0x00000007, 0x00000096, 0x00000094,
0x000000bb, 0x0007000c, 0x00000007, 0x00000097, 0x00000001, 0x0000001a, 0x00000096, 0x0000001c,
0x000500ba, 0x00000022, 0x00000099, 0x00000064, 0x00000020, 0x000600a9, 0x00000007, 0x0000009a,
0x00000099, 0x00000097, 0x00000091, 0x00050091, 0x00000007, 0x00000078, 0x00000076, 0x0000009a,
0x0007000c, 0x00000007, 0x0000007a, 0x00000001, 0x00000028, 0x00000078, 0x00000079, 0x00060041,
0x00000081, 0x00000082, 0x0000007d, 0x0000007f, 0x00000080, 0x0004003d, 0x00000006, 0x00000083,
0x00000082, 0x0005008e, 0x00000007, 0x00000084, 0x0000007a, 0x00000083, 0x00050085, 0x00000007,
0x000000a0, 0x00000084, 0x000000bd, 0x0008000c, 0x00000007, 0x000000a3, 0x00000001, 0x0000002b,
0x000000a0, 0x00000079, 0x000000b2, 0x0007000c, 0x00000007, 0x000000a4, 0x00000001, 0x0000001a,
0x000000a3, 0x00000032, 0x0005008e, 0x00000007, 0x000000a6, 0x000000a4, 0x00000035, 0x00050081,
0x00000007, 0x000000a8, 0x000000b7, 0x000000a6, 0x0005008e, 0x00000007, 0x000000aa, 0x000000a4,
0x0000003a, 0x00050081, 0x00000007, 0x000000ac, 0x000000b2, 0x000000aa, 0x00050088, 0x00000007,
0x000000ad, 0x000000a8, 0x000000ac, 0x0007000c, 0x00000007, 0x000000ae, 0x00000001, 0x0000001a,
0x000000ad, 0x00000041, 0x00050051, 0x00000006, 0x00000089, 0x000000ae, 0x00000000, 0x00050051,
0x00000006, 0x0000008a, 0x000000ae, 0x00000001, 0x00050051, 0x00000006, 0x0000008b, 0x000000ae,
0x00000002, 0x00070050, 0x00000045, 0x0000008c, 0x00000089, 0x0000008a, 0x0000008b, 0x00000056,
0x0003003e, 0x00000068, 0x0000008c, 0x000100fd, 0x00010038,
};
+21 -2
View File
@@ -57,6 +57,9 @@ typedef struct {
int have_gpu, have_vram, vram_exact;
uint64_t gpu_ns, gpu_parts, gpu_missed; // busy time, submission parts timed, parts left untimed
uint64_t vram_used, vram_budget;
int have_idle; // calibrated timestamps: the idle split below is filled
uint64_t idle_ns, starved_ns, queued_ns; // GPU idle between timed parts; of it, before the part was submitted; submit to start
uint64_t idle_gaps, max_gap_ns; // gaps over 0.5 ms; the longest
} PerfGpu;
extern void (*perf_gpu_stats)(PerfGpu *out);
// The performance overlay (perfmon.c): mode 0 off, 1 fps, 2 full. While it is on, perf_present hands every frame to
@@ -184,14 +187,16 @@ typedef struct { const char *file, *sha256; } RtFileHash;
extern const RtFileHash rt_exefs_sha256[]; // tools/data/expected-<version>.json "exefs_sha256"
extern const int rt_exefs_sha256_count;
extern const char rt_default_exefs[], rt_default_romfs[], rt_default_profile[];
extern const int rt_game_version; // the game build: 111 (1.1.1), 121 (1.2.1) or 143 (1.4.3)
extern const int rt_game_version; // the game build: 110 (1.1.0), 121 (1.2.1) or 143 (1.4.3)
extern const char rt_port_version[]; // VERSION at the build's root: 0.1.0, 0.1.0+973c626 in a release
#define RT_V111 (rt_game_version == 111) // 1.1.1: its own boot constants and data slots
#define RT_V110 (rt_game_version == 110) // 1.1.0: its own boot constants and data slots
#define RT_V143 (rt_game_version >= 143)
// ---- kernel (kernel.c)
typedef struct RtThread RtThread;
Cpu *kern_cpu(void); // current guest thread's Cpu, NULL on host threads
void kern_free_cores_note(void); // for crash reports: logs that free_cores = 1 lifted the
// virtual core gate, nothing when the gate is on
uint32_t kern_main_thread(Cpu **cpu); // main thread object and Cpu for the calling host thread
// (main.npdm: 1 MiB stack at the top of the stack region,
// priority 44, core 0); on the main thread: its handle
@@ -242,6 +247,13 @@ void account_uid(uint64_t out[2]); // the local user's n
// ---- movies (ov_movie.c)
void movie_tick(Cpu *c); // at every present, on the presenting guest thread: hands
// decoded movie frames over when due, signals their events
// ---- camera speed (camera_speed.c): TOTK_STICK_SENS
float cam_speed_wanted(void); // the factor TOTK_STICK_SENS asks for, 0.1 to 3
float cam_speed_applied(void); // the factor in effect: 1 until romfs.c serves the pack
int cam_pack_build(const void *in, size_t n, const void *zsdic, size_t zsdic_n, void **out, size_t *out_n);
// Pack/Actor/PlayerCamera.pack.zs with the camera speeds
// multiplied, malloc'd; 0 = factor 1 or cannot (logged)
void cam_pack_served(void); // romfs.c serves the multiplied pack
// ---- game resolution (resolution.c): TOTK_OUTPUT_RES, TOTK_RENDER_SCALE
uint64_t res_heap_extra_bytes(void); // added to the application pool (mem_init), 2 MiB steps
uint64_t res_heap_extra_kib(void); // added to the HeapDef texture heap and its parent; 0 = none
@@ -249,6 +261,10 @@ int res_heapdef_build(const void *in, size_t n, void **out, size_t *out_n); //
// the grown heaps, malloc'd; 0 = cannot (logged)
void res_heapdef_served(void); // romfs.c serves the grown table
void res_init(void); // after rt_patches_init: the patch page and the sets
float res_dlss_lod_bias(void); // TOTK_DLSS upscaling: texture LOD bias (<= 0)
int res_dlss_mode(const char *mode); // TOTK_DLSS changed while running: new scene size
void res_fn_hit(uint64_t addr, uint64_t x0); // main.c fnprof_hit: catches the renderer at start
void res_present(Cpu *c); // nvnQueuePresentTexture: applies a pending scene size
void res_sizes(unsigned out[2], unsigned scene[2]); // the output and scene sizes in effect (the game's own
// until res_init switched the sets on)
int res_is_16x9(unsigned w, unsigned h); // within 1% of 16:9 (the test res_init and romfs.c share)
@@ -295,6 +311,9 @@ void rt_boot(void); // boot.c
// process exit code.
int probe_cfg(void); // cfg_probe.c
int probe_dpi(void); // dpi_probe_win.c (Windows only)
int probe_mods(void); // mods_probe.c
void discord_init(void); // discord_rpc.c: the Rich Presence thread, game runs only
int probe_discord(void); // discord_rpc.c
int probe_loader(void), probe_kernel(void), probe_ipc(void), probe_services(void), probe_fs(void);
int probe_gfx_abi(void); // gfx_abi_probe.c
int probe_vkdevice(void); // vk_device.c
+1 -1
View File
@@ -121,7 +121,7 @@ __attribute__((noinline, noreturn, cold)) static void bad_entry(Cpu *c) {
}
// kern_host_track: the call counted in the thread's host depth. Not a tail call, so the host stack holds this frame
// while fn runs; longjmp out of fn (ExitThread) leaves the depth raised on a thread that ends.
// while fn runs; the jump out of fn (ExitThread) leaves the depth raised on a thread that ends.
__attribute__((noinline)) static void hostfn_tracked(Cpu *c, GuestFn fn) {
void *t = c->thread;
int *d = kern_host_depth(t);
+109 -17
View File
@@ -236,7 +236,56 @@ static float mouse_sens_get(void) {
}
// The mouse camera as a right-stick sample, held for the whole presented frame. Under `lock`.
// ---- walk key: the keyboard's stick samples scaled down while a key is held (TOTK_WALK_KEY, TOTK_WALK_SCALE)
// A keyboard key is all or nothing, so every keyboard-driven stick sample is +/-32767 and the game only ever sees a
// full tilt. Holding this key scales those two samples, which gives the half tilt a gamepad gets from its analog range,
// so the keyboard can walk as well as run. yuzu and eden do the same with their modifier and modifier_scale settings.
// Only the keyboard is scaled: the gamepad's axes and the mouse camera sample their own values.
static int walk_key = KEY_NONE; // TOTK_WALK_KEY as a KEY_*, KEY_NONE = off; live (cfg_version)
static float walk_scale = 0.51f; // TOTK_WALK_SCALE, 0.2 to 0.9; live (cfg_version)
static unsigned walk_seen = ~0u;
// The ini takes the key names the Controls tab writes; a hand-written line may spell them in any case.
static int name_matches(const char *name, const char *key) {
for (; *name && *key; name++, key++) {
unsigned char a = (unsigned char)*name, b = (unsigned char)*key;
if (a >= 'A' && a <= 'Z') a = (unsigned char)(a - 'A' + 'a');
if (b >= 'A' && b <= 'Z') b = (unsigned char)(b - 'A' + 'a');
if (a != b) return 0;
}
return *name == *key;
}
static void walk_get(void) {
unsigned ver = cfg_version();
if (ver == walk_seen) return;
walk_seen = ver;
const char *name = cfg_value("TOTK_WALK_KEY"); // "none" (the default) turns the key off
int key = KEY_NONE;
if (*name && !name_matches(name, "none")) {
for (int k = KEY_A; k < KEY_COUNT && key == KEY_NONE; k++)
if (input_key_name(k) && name_matches(name, input_key_name(k))) key = k;
if (key == KEY_NONE) rt_log("input: walk_key: unknown key '%s', the keyboard sticks keep their full tilt", name);
}
// 0.51 rather than 0.5: a keyboard sample is 32767, and 32767 * 0.5 = 16383 falls one short of stick_bits'
// STICK_DIR (16384), which would leave the game's stick-direction bits clear while the walk key is held. The value
// in the settings table carries that default; this code only rejects what the table's range does not allow.
const char *sv = cfg_value("TOTK_WALK_SCALE");
char *end;
double d = strtod(sv, &end);
double s = end == sv || *end || !(d >= 0.2 && d <= 0.9) ? strtod(cfg_meta("TOTK_WALK_SCALE")->def, NULL) : d;
if (key != walk_key || (float)s != walk_scale) {
walk_key = key;
walk_scale = (float)s;
rt_log("input: walk key %s, keyboard sticks at %.0f%% of their tilt (mouse and gamepad unchanged)",
key != KEY_NONE ? input_key_name(key) : "off", s * 100);
}
}
// The mouse camera as a right-stick sample, held for the whole presented frame. Under `lock`. The sample is divided by
// the camera speed factor the game runs with (camera_speed.c, cam_speed_applied), which multiplies every right-stick
// turn rate, so TOTK_MOUSE_SENS alone sets the mouse's speed; below 1 the sample stays within the stick's range, so the
// mouse's top speed drops with the factor.
static void mouse_camera(int32_t out[2]) {
static uint64_t frame = ~0ull, t0;
static int32_t held[2];
@@ -259,20 +308,23 @@ static void mouse_camera(int32_t out[2]) {
held[0] = held[1] = 0; // frames stopped: do not hold a deflection
}
}
out[0] = held[0];
out[1] = held[1];
double k = cam_speed_applied(), x = held[0] / k, y = held[1] / k, len = sqrt(x * x + y * y);
if (len > STICK_MAX) x *= STICK_MAX / len, y *= STICK_MAX / len;
out[0] = (int32_t)lround(x);
out[1] = (int32_t)lround(y);
}
static float stick_dead = -1; // TOTK_STICK_DEADZONE as a fraction of full deflection; live (cfg_version)
static float stick_dead[2] = {-1, -1}; // input_pad_deadzone of the left and right stick; live (cfg_version)
static unsigned stick_dead_seen;
static float stick_dead_get(void) {
static float stick_dead_get(int s) {
unsigned ver = cfg_version();
if (stick_dead >= 0 && ver == stick_dead_seen) return stick_dead;
stick_dead_seen = ver;
double v = cfg_double("TOTK_STICK_DEADZONE");
stick_dead = (float)(v < 0 ? 0 : v > 50 ? 50 : v) / 100.f;
return stick_dead;
if (stick_dead[0] < 0 || ver != stick_dead_seen) {
stick_dead_seen = ver;
stick_dead[0] = input_pad_deadzone(0);
stick_dead[1] = input_pad_deadzone(1);
}
return stick_dead[s];
}
// One gamepad stick through the dead zone; SDL's Y grows downwards, the Switch's upwards.
@@ -425,12 +477,26 @@ static int pad_read(uint64_t *b, int32_t sl[2], int32_t sr[2]) {
uint8_t pd[PAD_COUNT] = {0};
if (!pad_physical(pd)) return 0;
*b |= input_map_pad_buttons(pd, pad_layout_get());
float dead = stick_dead_get();
stick(SDL_GAMEPAD_AXIS_LEFTX, SDL_GAMEPAD_AXIS_LEFTY, dead, sl);
stick(SDL_GAMEPAD_AXIS_RIGHTX, SDL_GAMEPAD_AXIS_RIGHTY, dead, sr);
stick(SDL_GAMEPAD_AXIS_LEFTX, SDL_GAMEPAD_AXIS_LEFTY, stick_dead_get(0), sl);
stick(SDL_GAMEPAD_AXIS_RIGHTX, SDL_GAMEPAD_AXIS_RIGHTY, stick_dead_get(1), sr);
return 1;
}
int input_pad_stick_percent(double pct[2]) {
int ok = 0;
pct[0] = pct[1] = 0;
plat_mutex_lock(&lock);
if (state == 1 && pad && SDL_GamepadConnected(pad)) { // the game's poll keeps the state fresh (SDL_UpdateGamepads)
pct[0] = input_stick_percent(SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_LEFTX),
SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_LEFTY));
pct[1] = input_stick_percent(SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_RIGHTX),
SDL_GetGamepadAxis(pad, SDL_GAMEPAD_AXIS_RIGHTY));
ok = 1;
}
plat_mutex_unlock(&lock);
return ok;
}
static void poll_merged(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry) {
uint64_t b = 0;
int32_t sl[2] = {0, 0}, sr[2] = {0, 0};
@@ -456,9 +522,13 @@ static void poll_merged(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx
was_captured = cap;
b |= input_map_buttons(down);
int32_t k[2];
walk_get();
int walk = walk_key != KEY_NONE && down[walk_key];
input_map_stick(down, 0, k);
if (walk) k[0] = (int32_t)(k[0] * walk_scale), k[1] = (int32_t)(k[1] * walk_scale);
pick(&sl[0], &sl[1], k[0], k[1]);
input_map_stick(down, 1, k);
if (walk) k[0] = (int32_t)(k[0] * walk_scale), k[1] = (int32_t)(k[1] * walk_scale);
pick(&sr[0], &sr[1], k[0], k[1]);
mouse_camera(k);
pick(&sr[0], &sr[1], k[0], k[1]);
@@ -486,6 +556,12 @@ static void poll_merged(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx
// g_block: 0 off, 1 text entry open, 2 closed, waiting for the release. The cursor is released while it is open.
static volatile int32_t g_block;
static volatile int32_t g_menu; // the in-game menu, the same way (input_menu)
// When g_block and g_menu last went to 2 (plat_now_ns). The wait for the release ends after RELEASE_WAIT_NS even with
// something held: an input that never reads as released (a button another program holds down, a key whose release
// went to another window, a stick that rests outside its dead zone) would otherwise keep the game deaf until restart
// (#462, #494). A press that closed the menu is let go well within the wait; one still held after it is meant.
static volatile uint64_t g_block_closed, g_menu_closed;
#define RELEASE_WAIT_NS 1000000000ull
int input_cursor_allowed(void) {
const char *in = cfg_get("TOTK_INPUT");
@@ -493,6 +569,7 @@ int input_cursor_allowed(void) {
}
void input_block(int on) {
if (!on) __atomic_store_n(&g_block_closed, plat_now_ns(), __ATOMIC_RELEASE);
plat_xchg32(&g_block, on ? 1 : 2);
ikb_cursor_update();
}
@@ -500,20 +577,35 @@ void input_block(int on) {
// The in-game menu (ui/menu.cpp) blocks the game's input the same way: g_menu 0 closed, 1 open, 2 closed, waiting for
// the release. The cursor is released while it is open, for the menu's mouse.
void input_menu(int open) {
if (!open) __atomic_store_n(&g_menu_closed, plat_now_ns(), __ATOMIC_RELEASE);
plat_xchg32(&g_menu, open ? 1 : 2);
if (!open) ikb_menu_closed(); // the capture before Esc comes back
ikb_cursor_update();
}
// 1 while flag (g_block, g_menu) blocks the game's input; state 2 ends at the first poll with nothing held.
static int blocked(volatile int32_t *flag, uint64_t buttons) {
// 1 while flag (g_block, g_menu) blocks the game's input; state 2 ends at the first poll with nothing held, or with
// something still held RELEASE_WAIT_NS after closed. A stick axis counts as held as well: with the walk key the
// keyboard's sticks move part way without setting a direction bit, so a gate that watched the buttons alone would let
// that movement through the moment the menu or the text entry closes.
static int blocked(volatile int32_t *flag, volatile uint64_t *closed, const char *what, uint64_t buttons,
const int32_t *axes) {
int32_t k = *flag;
return k && !(k == 2 && !buttons && plat_cas32(flag, 0, 2) == 2);
if (k != 2) return k != 0;
int held = buttons != 0;
for (int i = 0; i < 4; i++) held |= axes[i] != 0;
if (held && plat_now_ns() - __atomic_load_n(closed, __ATOMIC_ACQUIRE) < RELEASE_WAIT_NS) return 1;
if (plat_cas32(flag, 0, 2) != 2) return *flag != 0; // reopened meanwhile
if (held)
rt_log("input: the %s closed 1 s ago and input is still held (buttons %#llx, sticks %d %d %d %d); the game "
"gets it from now on", what, (unsigned long long)buttons, axes[0], axes[1], axes[2], axes[3]);
return 0;
}
void input_poll(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry) {
poll_merged(buttons, lx, ly, rx, ry);
int text = blocked(&g_block, *buttons), menu = blocked(&g_menu, *buttons);
const int32_t axes[4] = {*lx, *ly, *rx, *ry};
int text = blocked(&g_block, &g_block_closed, "text entry", *buttons, axes),
menu = blocked(&g_menu, &g_menu_closed, "menu", *buttons, axes);
if (!text && !menu) return;
*buttons = 0; *lx = *ly = *rx = *ry = 0;
}
+4
View File
@@ -21,6 +21,10 @@ int input_overlay_gate(int *held, uint64_t *buttons); // L3+R3: 1 in the poll
int input_pad_read(uint64_t *buttons, int32_t *lx, int32_t *ly);
// The gamepad layout in effect (PAD_LAYOUT_*, input_map.h; TOTK_PAD_LAYOUT, live); -1 without a gamepad. Any thread.
int input_pad_layout(void);
// How far the open gamepad's left (pct[0]) and right (pct[1]) sticks are from the centre now, in percent of full
// deflection, before the dead zone: the menu shows it on the dead zone rows, so a drifting stick's resting value can be
// read off. 0 (and both 0) without a connected gamepad. Any thread.
int input_pad_stick_percent(double pct[2]);
// The label on a face button of the open gamepad (input_map.h PAD_SOUTH..PAD_NORTH, as SDL reports it); PAD_LABEL_NONE for another
// button, an unknown label or no gamepad. Any thread.
enum { PAD_LABEL_NONE, PAD_LABEL_A, PAD_LABEL_B, PAD_LABEL_X, PAD_LABEL_Y, PAD_LABEL_CROSS, PAD_LABEL_CIRCLE,
+22
View File
@@ -288,6 +288,18 @@ int input_pad_layout_pick(const char *setting, int east_labelled_a) {
return east_labelled_a ? PAD_LAYOUT_NINTENDO : PAD_LAYOUT_XBOX;
}
int input_prompts_pick(const char *prompts, const char *pad_layout) {
if (prompts && *prompts) return !strcasecmp(prompts, "xbox") ? PROMPTS_XBOX : PROMPTS_NINTENDO;
return pad_layout && !strcasecmp(pad_layout, "xbox_prompts") ? PROMPTS_XBOX : PROMPTS_NINTENDO;
}
const char *input_prompts_folder(int prompts, const char *pad_layout) {
if (prompts != PROMPTS_XBOX) return NULL;
// The folders are read at start, before a pad is open: auto counts as Xbox, as for a pad without Nintendo labels.
// A Nintendo-labelled pad under auto plays by label too (its A is on the button labelled A), so it matches as well.
return input_pad_layout_pick(pad_layout, 0) == PAD_LAYOUT_NINTENDO ? "romfs-patches-xbox" : "romfs-patches-xbox-label";
}
uint64_t input_map_pad_buttons(const uint8_t down[PAD_COUNT], int layout) {
const PadBinding *t = input_map.pads[layout];
uint64_t b = 0;
@@ -334,6 +346,16 @@ void input_pad_stick(int32_t x, int32_t y, float dead, int32_t out[2]) {
out[1] = (int32_t)lrint(fmax(-1, fmin(1, fy * k)) * STICK_MAX);
}
float input_pad_deadzone(int stick) {
const char *own = stick ? "TOTK_RSTICK_DEADZONE" : "TOTK_LSTICK_DEADZONE", *set = cfg_get(own);
double v = cfg_double(set && *set ? own : "TOTK_STICK_DEADZONE");
return (float)(v < 0 ? 0 : v > 50 ? 50 : v) / 100.f;
}
double input_stick_percent(int32_t x, int32_t y) {
return sqrt((double)x * x + (double)y * y) * 100.0 / STICK_MAX;
}
// Minus and Plus held together open or close the menu. *held: latched from the poll where both go down until neither is
// down (the caller keeps it). Every poll of the latch reports neither to the game, so releasing one button first does not
// leak the other; Minus alone before Plus reaches the game unchanged. With the menu open the game sees a neutral pad.
+22 -4
View File
@@ -80,11 +80,23 @@ int input_map_bind(const char *button, const char *list);
// Applies the TOTK_BIND_<action> settings (cfg_get) over the defaults: at start, and again when one of them changes.
void input_map_configure(void);
// The layout for a TOTK_PAD_LAYOUT value: "nintendo" or "xbox" (any case); "xbox_prompts" is the Nintendo layout with
// the A/B and X/Y prompts swapped (runtime/romfs.c overlay_init), so the buttons map as "nintendo". Anything else
// ("auto", NULL) picks Nintendo when the pad's east button is labelled A (a Switch Pro Controller, a GuliKit) and Xbox
// otherwise.
// The layout for a TOTK_PAD_LAYOUT value: "nintendo" or "xbox" (any case); "xbox_prompts", 0.1.9's name for the Nintendo
// layout with the Xbox prompts, maps the buttons as "nintendo". Anything else ("auto", NULL) picks Nintendo when the
// pad's east button is labelled A (a Switch Pro Controller, a GuliKit) and Xbox otherwise.
int input_pad_layout_pick(const char *setting, int east_labelled_a);
// Button prompts (TOTK_PROMPTS): the controller whose buttons the game's prompts show. Nintendo: the game's own. Xbox:
// LB RB LT RT, Menu, View and a d-pad cross for the other buttons, and the face buttons named by the label of the
// button the pad layout presses (runtime/romfs.c overlay_init, tools/make_romfs_patches.py --prompts).
enum { PROMPTS_NINTENDO, PROMPTS_XBOX };
// The prompts for a TOTK_PROMPTS value ("nintendo" or "xbox", any case). Unset or empty: Xbox while the pad layout
// setting is "xbox_prompts", else Nintendo.
int input_prompts_pick(const char *prompts, const char *pad_layout);
// The folder next to romfs-index.bin that holds those prompts for a TOTK_PAD_LAYOUT value, NULL for the game's own. The
// Nintendo layout plays an Xbox pad by position, so its folder names the face buttons the other way round
// (romfs-patches-xbox: the right button does A and is labelled B); xbox and auto put every Switch button on the button
// labelled with its letter (auto picks the layout per pad by its labels), so they share romfs-patches-xbox-label.
const char *input_prompts_folder(int prompts, const char *pad_layout);
// down[pad] != 0 for the gamepad inputs held. Returns the Switch button bits (0..15) the layout's pad table presses.
uint64_t input_map_pad_buttons(const uint8_t down[PAD_COUNT], int layout);
@@ -100,6 +112,12 @@ void input_mouse_stick(int32_t dx, int32_t dy, double dt_s, float sens, int32_t
// 0..0.5): inside the circle the stick reads 0, and the rest of the travel is scaled to start at 0 at the edge, so a
// drifting stick rests at 0 and full deflection still reaches full. The result stays inside the unit square.
void input_pad_stick(int32_t x, int32_t y, float dead, int32_t out[2]);
// The dead zone of gamepad stick 0 (left) or 1 (right) for input_pad_stick, as a fraction of full deflection:
// TOTK_LSTICK_DEADZONE or TOTK_RSTICK_DEADZONE when set, else TOTK_STICK_DEADZONE (both sticks), percent clamped to 0..50.
float input_pad_deadzone(int stick);
// How far a stick (x, y in -32768..32767) is from the centre, in percent of full deflection (100 at an axis's end; a
// square gate's corner reads more).
double input_stick_percent(int32_t x, int32_t y);
// ---- the remapping rows' edits, on a copy of input_map. Pure.
// action's keys (table order) / its gamepad buttons in layout, at most max; returns how many.
+1
View File
@@ -11,6 +11,7 @@ extern "C" {
// gfx_window_sdl.c
SDL_Window *gfx_window_sdl(void); // the game window, NULL before gfx_window_start; any thread
double gfx_window_sdl_density(void); // pixels per window unit (mouse positions are in units); any thread
void gfx_window_sdl_run(void (*fn)(void *arg), void *arg); // runs fn on the window thread and waits; any thread
// input_sdl.c
void input_sdl_window(SDL_Window *w); // the game window was created
+2
View File
@@ -11,6 +11,7 @@
#include "audren.h"
#include "host.h"
#include "ipc.h"
#include "nfp.h"
#include "platform/platform.h"
#define CMIF_IN_MAGIC 0x49434653u // "SFCI"
@@ -25,6 +26,7 @@ enum { T_CLOSE = 2, T_REQUEST = 4, T_CONTROL = 5, T_REQUEST_CTX = 6, T_CONTROL_C
// Services sm: hands out. Anything else is a named fatal.
static const struct { const char *name; IpcHandler handler; } services[] = {
{"audren:u", audren_manager_handler},
{"nfp:user", nfp_user_manager_handler},
};
static volatile int32_t g_live;
+145 -91
View File
@@ -8,10 +8,6 @@
// Cpu. The SDK's nn::os runs as lifted code; only the kernel under it is the host. Every wait hangs on one global lock
// G with one condition variable per thread; wake order is the kernel's: lower priority value first, then first come.
// Semantics follow the public Horizon kernel (KConditionVariable, KAddressArbiter, KSynchronization).
#ifdef _WIN32
#define __USE_MINGW_SETJMP_NON_SEH // setjmp(b) = _setjmp(b, NULL): longjmp restores registers, no SEH unwinding
#endif
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -77,7 +73,7 @@ struct RtThread {
uint64_t cseq;
RtThread *cnext;
uint8_t *tlr, *tls;
jmp_buf exit_jmp; // the thread start; ExitThread longjmps to it
PlatJmp exit_jmp; // the thread start; ExitThread jumps back to it
// fibers
PlatFiber *base_fiber; // the host thread as a host fiber, after the first switch
Fiber *fiber; // current guest fiber, NULL on the thread's own context
@@ -296,7 +292,13 @@ static uint32_t block_inner(RtThread *t, int kind, int64_t ns) {
// and gives it up only where Horizon would switch threads (waits, sleep, yield, exit, blocking host calls); a free
// core goes to the best waiting thread. A waiter better than a holder asks one holder to give its core up (core_kick),
// which it does at its next SVC or indirect call (kern_checkpoint, rt_dispatch), as Horizon runs the better thread at
// once; guest code without either keeps the core until it reaches one. TOTK_FREE_CORES=1 turns the gate off.
// once; guest code without either keeps the core until it reaches one.
//
// free_cores = 1 (TOTK_FREE_CORES) turns the gate off, for experiments only: the game does not run that way. A thread
// that holds no core reports its ideal core to GetCurrentProcessorNumber, so the game's job workers all report core 0
// and run its per-core code at once: on 1.2.1 two of them add the same per-core NVN control memory, which retires the
// command handle the other just recorded, and CallCommands finds no recording at start (#212); 1.4.3 corrupts a heap
// in main+0x82e00 or hangs at the title menu. The start log and every crash report say so (kern_free_cores_note).
static RtThread *g_core_owner[NCORE], *g_core_wait;
static int g_cores_on = -1, g_held_max;
@@ -307,14 +309,21 @@ static int cores_enabled(void) {
if (g_cores_on < 0) {
g_cores_on = !cfg_bool("TOTK_FREE_CORES"); // "0" keeps the gate, like unset
if (!g_cores_on)
rt_log("kernel: virtual core gate off (TOTK_FREE_CORES): guest threads run without the limit of one per "
"core that the game's per-core data needs; for experiments only, the game can fail");
rt_log("kernel: WARNING: free_cores = 1 (TOTK_FREE_CORES) turns the virtual core gate off. This is an "
"experimental mode and the game crashes or hangs in it, usually at start. Set free_cores = 0 in "
"totk.ini to play");
diag_init();
ap_init();
}
return g_cores_on;
}
void kern_free_cores_note(void) {
if (!g_cores_on)
rt_log("fatal: free_cores = 1 was on: the game crashes in this experimental mode; set free_cores = 0 in "
"totk.ini before reporting this crash");
}
static int core_allowed(const RtThread *t, int c) { return (int)((t->mask >> c) & 1); }
// ---- asynchronous preemption (TOTK_ASYNC_PREEMPT, on unless 0)
@@ -406,6 +415,18 @@ static int ap_disabled(const RtThread *t) { return g_ap > 0 && ap_tlr(t)[0]; }
// in kern_ap_yield and jumps back to kern_ap_rip(), whose value it first stores in the return slot it reserved at
// entry, so a stack walk sees the interrupted function as its caller. No ret: the jump keeps call/return pairs
// balanced. The waiter never writes the owner's stack.
// An x86-64-v2 build (no __AVX__) saves XMM0-15 with SSE moves into the same 32-byte slots instead: its game code
// keeps nothing in the upper YMM halves, and the CPUs it is for have no VEX encoding, so a vmovdqa there faults with
// an illegal instruction the first time a core is interrupted.
#ifdef __AVX__
#define AP_VMOV "vmovdqa"
#define AP_V "%ymm"
#define AP_VZEROUPPER " vzeroupper\n"
#else
#define AP_VMOV "movdqa"
#define AP_V "%xmm"
#define AP_VZEROUPPER ""
#endif
#ifdef _WIN32
__asm__(".text\n"
".globl kern_ap_stub\n"
@@ -437,48 +458,48 @@ __asm__(".text\n"
".seh_setframe %rbp, 0\n"
".seh_endprologue\n"
" andq $-32, %rsp\n"
" subq $576, %rsp\n" // 0: shadow space, 32: MXCSR saved, 36: MXCSR default, 64: YMM0-15
" vmovdqa %ymm0, 64(%rsp)\n"
" vmovdqa %ymm1, 96(%rsp)\n"
" vmovdqa %ymm2, 128(%rsp)\n"
" vmovdqa %ymm3, 160(%rsp)\n"
" vmovdqa %ymm4, 192(%rsp)\n"
" vmovdqa %ymm5, 224(%rsp)\n"
" vmovdqa %ymm6, 256(%rsp)\n"
" vmovdqa %ymm7, 288(%rsp)\n"
" vmovdqa %ymm8, 320(%rsp)\n"
" vmovdqa %ymm9, 352(%rsp)\n"
" vmovdqa %ymm10, 384(%rsp)\n"
" vmovdqa %ymm11, 416(%rsp)\n"
" vmovdqa %ymm12, 448(%rsp)\n"
" vmovdqa %ymm13, 480(%rsp)\n"
" vmovdqa %ymm14, 512(%rsp)\n"
" vmovdqa %ymm15, 544(%rsp)\n"
" subq $576, %rsp\n" // 0: shadow space, 32: MXCSR saved, 36: MXCSR default, 64: YMM0-15 (XMM0-15 without AVX)
" " AP_VMOV " " AP_V "0, 64(%rsp)\n"
" " AP_VMOV " " AP_V "1, 96(%rsp)\n"
" " AP_VMOV " " AP_V "2, 128(%rsp)\n"
" " AP_VMOV " " AP_V "3, 160(%rsp)\n"
" " AP_VMOV " " AP_V "4, 192(%rsp)\n"
" " AP_VMOV " " AP_V "5, 224(%rsp)\n"
" " AP_VMOV " " AP_V "6, 256(%rsp)\n"
" " AP_VMOV " " AP_V "7, 288(%rsp)\n"
" " AP_VMOV " " AP_V "8, 320(%rsp)\n"
" " AP_VMOV " " AP_V "9, 352(%rsp)\n"
" " AP_VMOV " " AP_V "10, 384(%rsp)\n"
" " AP_VMOV " " AP_V "11, 416(%rsp)\n"
" " AP_VMOV " " AP_V "12, 448(%rsp)\n"
" " AP_VMOV " " AP_V "13, 480(%rsp)\n"
" " AP_VMOV " " AP_V "14, 512(%rsp)\n"
" " AP_VMOV " " AP_V "15, 544(%rsp)\n"
" stmxcsr 32(%rsp)\n"
" movl $0x1f80, 36(%rsp)\n"
" ldmxcsr 36(%rsp)\n"
" cld\n"
" vzeroupper\n"
AP_VZEROUPPER
" call kern_ap_rip\n"
" movq %rax, 72(%rbp)\n" // the return slot: rbp + 8 pushes + pushfq
" call kern_ap_yield\n"
" ldmxcsr 32(%rsp)\n"
" vmovdqa 64(%rsp), %ymm0\n"
" vmovdqa 96(%rsp), %ymm1\n"
" vmovdqa 128(%rsp), %ymm2\n"
" vmovdqa 160(%rsp), %ymm3\n"
" vmovdqa 192(%rsp), %ymm4\n"
" vmovdqa 224(%rsp), %ymm5\n"
" vmovdqa 256(%rsp), %ymm6\n"
" vmovdqa 288(%rsp), %ymm7\n"
" vmovdqa 320(%rsp), %ymm8\n"
" vmovdqa 352(%rsp), %ymm9\n"
" vmovdqa 384(%rsp), %ymm10\n"
" vmovdqa 416(%rsp), %ymm11\n"
" vmovdqa 448(%rsp), %ymm12\n"
" vmovdqa 480(%rsp), %ymm13\n"
" vmovdqa 512(%rsp), %ymm14\n"
" vmovdqa 544(%rsp), %ymm15\n"
" " AP_VMOV " 64(%rsp), " AP_V "0\n"
" " AP_VMOV " 96(%rsp), " AP_V "1\n"
" " AP_VMOV " 128(%rsp), " AP_V "2\n"
" " AP_VMOV " 160(%rsp), " AP_V "3\n"
" " AP_VMOV " 192(%rsp), " AP_V "4\n"
" " AP_VMOV " 224(%rsp), " AP_V "5\n"
" " AP_VMOV " 256(%rsp), " AP_V "6\n"
" " AP_VMOV " 288(%rsp), " AP_V "7\n"
" " AP_VMOV " 320(%rsp), " AP_V "8\n"
" " AP_VMOV " 352(%rsp), " AP_V "9\n"
" " AP_VMOV " 384(%rsp), " AP_V "10\n"
" " AP_VMOV " 416(%rsp), " AP_V "11\n"
" " AP_VMOV " 448(%rsp), " AP_V "12\n"
" " AP_VMOV " 480(%rsp), " AP_V "13\n"
" " AP_VMOV " 512(%rsp), " AP_V "14\n"
" " AP_VMOV " 544(%rsp), " AP_V "15\n"
" movq %rbp, %rsp\n"
" popq %rbp\n"
" popq %r11\n"
@@ -516,48 +537,48 @@ __asm__(".text\n"
" pushq %rbp\n"
" movq %rsp, %rbp\n"
" andq $-32, %rsp\n"
" subq $576, %rsp\n" // 32: MXCSR saved, 36: MXCSR default, 64: YMM0-15
" vmovdqa %ymm0, 64(%rsp)\n"
" vmovdqa %ymm1, 96(%rsp)\n"
" vmovdqa %ymm2, 128(%rsp)\n"
" vmovdqa %ymm3, 160(%rsp)\n"
" vmovdqa %ymm4, 192(%rsp)\n"
" vmovdqa %ymm5, 224(%rsp)\n"
" vmovdqa %ymm6, 256(%rsp)\n"
" vmovdqa %ymm7, 288(%rsp)\n"
" vmovdqa %ymm8, 320(%rsp)\n"
" vmovdqa %ymm9, 352(%rsp)\n"
" vmovdqa %ymm10, 384(%rsp)\n"
" vmovdqa %ymm11, 416(%rsp)\n"
" vmovdqa %ymm12, 448(%rsp)\n"
" vmovdqa %ymm13, 480(%rsp)\n"
" vmovdqa %ymm14, 512(%rsp)\n"
" vmovdqa %ymm15, 544(%rsp)\n"
" subq $576, %rsp\n" // 32: MXCSR saved, 36: MXCSR default, 64: YMM0-15 (XMM0-15 without AVX)
" " AP_VMOV " " AP_V "0, 64(%rsp)\n"
" " AP_VMOV " " AP_V "1, 96(%rsp)\n"
" " AP_VMOV " " AP_V "2, 128(%rsp)\n"
" " AP_VMOV " " AP_V "3, 160(%rsp)\n"
" " AP_VMOV " " AP_V "4, 192(%rsp)\n"
" " AP_VMOV " " AP_V "5, 224(%rsp)\n"
" " AP_VMOV " " AP_V "6, 256(%rsp)\n"
" " AP_VMOV " " AP_V "7, 288(%rsp)\n"
" " AP_VMOV " " AP_V "8, 320(%rsp)\n"
" " AP_VMOV " " AP_V "9, 352(%rsp)\n"
" " AP_VMOV " " AP_V "10, 384(%rsp)\n"
" " AP_VMOV " " AP_V "11, 416(%rsp)\n"
" " AP_VMOV " " AP_V "12, 448(%rsp)\n"
" " AP_VMOV " " AP_V "13, 480(%rsp)\n"
" " AP_VMOV " " AP_V "14, 512(%rsp)\n"
" " AP_VMOV " " AP_V "15, 544(%rsp)\n"
" stmxcsr 32(%rsp)\n"
" movl $0x1f80, 36(%rsp)\n"
" ldmxcsr 36(%rsp)\n"
" cld\n"
" vzeroupper\n"
AP_VZEROUPPER
" call kern_ap_rip\n"
" movq %rax, 88(%rbp)\n" // the return slot: rbp + 10 pushes + pushfq
" call kern_ap_yield\n"
" ldmxcsr 32(%rsp)\n"
" vmovdqa 64(%rsp), %ymm0\n"
" vmovdqa 96(%rsp), %ymm1\n"
" vmovdqa 128(%rsp), %ymm2\n"
" vmovdqa 160(%rsp), %ymm3\n"
" vmovdqa 192(%rsp), %ymm4\n"
" vmovdqa 224(%rsp), %ymm5\n"
" vmovdqa 256(%rsp), %ymm6\n"
" vmovdqa 288(%rsp), %ymm7\n"
" vmovdqa 320(%rsp), %ymm8\n"
" vmovdqa 352(%rsp), %ymm9\n"
" vmovdqa 384(%rsp), %ymm10\n"
" vmovdqa 416(%rsp), %ymm11\n"
" vmovdqa 448(%rsp), %ymm12\n"
" vmovdqa 480(%rsp), %ymm13\n"
" vmovdqa 512(%rsp), %ymm14\n"
" vmovdqa 544(%rsp), %ymm15\n"
" " AP_VMOV " 64(%rsp), " AP_V "0\n"
" " AP_VMOV " 96(%rsp), " AP_V "1\n"
" " AP_VMOV " 128(%rsp), " AP_V "2\n"
" " AP_VMOV " 160(%rsp), " AP_V "3\n"
" " AP_VMOV " 192(%rsp), " AP_V "4\n"
" " AP_VMOV " 224(%rsp), " AP_V "5\n"
" " AP_VMOV " 256(%rsp), " AP_V "6\n"
" " AP_VMOV " 288(%rsp), " AP_V "7\n"
" " AP_VMOV " 320(%rsp), " AP_V "8\n"
" " AP_VMOV " 352(%rsp), " AP_V "9\n"
" " AP_VMOV " 384(%rsp), " AP_V "10\n"
" " AP_VMOV " 416(%rsp), " AP_V "11\n"
" " AP_VMOV " 448(%rsp), " AP_V "12\n"
" " AP_VMOV " 480(%rsp), " AP_V "13\n"
" " AP_VMOV " 512(%rsp), " AP_V "14\n"
" " AP_VMOV " 544(%rsp), " AP_V "15\n"
" movq %rbp, %rsp\n"
" popq %rbp\n"
" popq %r11\n"
@@ -1435,10 +1456,10 @@ static void thread_finish(RtThread *t) {
unlock();
}
// ExitThread: back to the thread start with a non-unwinding longjmp; no SEH unwinding through lifted frames.
// (__builtin_setjmp is not usable: on Win64 LLVM saves the frame address, which is not rbp when the frame register
// is offset, and the landing code then reads its locals through the wrong base.)
static __attribute__((noreturn)) void exit_now(RtThread *t) { longjmp(t->exit_jmp, 1); }
// ExitThread: back to the thread start with plat_jmp_go, which unwinds nothing: no SEH unwinding through lifted
// frames. (__builtin_setjmp is not usable: on Win64 LLVM saves the frame address, which is not rbp when the frame
// register is offset, and the landing code then reads its locals through the wrong base.)
static __attribute__((noreturn)) void exit_now(RtThread *t) { plat_jmp_go(&t->exit_jmp); }
// The calling host thread, for ap_try (TOTK_ASYNC_PREEMPT) and dg_sample (TOTK_CORE_DIAG).
static PlatIntr *ap_open_self(void) {
@@ -1460,7 +1481,7 @@ static void thread_main(void *p) {
unlock();
Cpu *c = t->cpu;
c->sp = t->stack_top & ~15ull;
if (!setjmp(t->exit_jmp)) {
if (!plat_jmp_save(&t->exit_jmp)) {
rt_call(c, t->entry, 1, t->arg);
char d[128];
rt_fatal("guest thread %#x: entry %s returned (Horizon threads end with ExitThread)", t->handle,
@@ -1520,7 +1541,7 @@ static void guest_main(void *p) {
void (*fn)(Cpu *) = (void (*)(Cpu *))p;
Cpu *c;
kern_main_thread(&c);
if (!setjmp(tcur->exit_jmp)) fn(c);
if (!plat_jmp_save(&tcur->exit_jmp)) fn(c);
thread_finish(tcur);
return;
}
@@ -1879,7 +1900,9 @@ int kern_svc(Cpu *c, uint32_t imm) {
if (type != 0) {
int32_t nv = val + 1;
if (type == 2) {
if (cnt <= 0) nv = nw > 0 ? val - 1 : val + 1;
// Waking all (count <= 0) with waiters subtracts 2, not 1 (mesosphere
// KAddressArbiter::SignalAndModifyByWaitingCountIfEqual; yuzu, LAS Recomp and nxnative agree).
if (cnt <= 0) nv = nw > 0 ? val - 2 : val + 1;
else nv = nw == 0 ? val + 1 : nw <= cnt ? val - 1 : val;
}
uint32_t e = (uint32_t)val;
@@ -1943,8 +1966,13 @@ int kern_svc(Cpu *c, uint32_t imm) {
int idx = -1;
lock();
g_sync_calls++;
// Horizon's order (mesosphere KSynchronizationObject::Wait): a signalled object, then timeout 0, then a pending
// CancelSynchronization. The cancel is for the next wait that would block: a poll or a wait on a signalled
// object leaves it pending. A cancel that wakes this wait (CancelSynchronization wakes it with R_CANCELLED; a
// signal wakes it with -1 to look again) ends it cancelled, signalled objects or not.
uint32_t woke = 0;
for (;;) {
if (t->cancel) {
if (woke == R_CANCELLED) {
t->cancel = 0;
r = R_CANCELLED;
break;
@@ -1960,6 +1988,15 @@ int kern_svc(Cpu *c, uint32_t imm) {
r = R_OK;
break;
}
if (ns == 0) {
r = R_TIMEOUT;
break;
}
if (t->cancel) {
t->cancel = 0;
r = R_CANCELLED;
break;
}
int64_t left = ns;
if (ns > 0) {
uint64_t spent = kern_now_ns() - start;
@@ -1971,7 +2008,8 @@ int kern_svc(Cpu *c, uint32_t imm) {
}
t->wobj = n ? hs[0] | (uint64_t)n << 32 : 0;
g_sync_blocks++;
if (block(t, W_SYNC, left) == R_TIMEOUT) {
woke = block(t, W_SYNC, left);
if (woke == R_TIMEOUT) {
r = R_TIMEOUT;
break;
}
@@ -1986,7 +2024,7 @@ int kern_svc(Cpu *c, uint32_t imm) {
RtThread *t = h_get((uint32_t)x[0], O_THREAD);
if (t) {
t->cancel = 1;
if (t->wkind == W_SYNC) wake(t, (uint32_t)-1);
if (t->wkind == W_SYNC) wake(t, R_CANCELLED);
}
unlock();
x[0] = t ? R_OK : R_BAD_HANDLE;
@@ -2047,10 +2085,19 @@ void kern_event_signal(uint32_t hw) {
// System events of host services: the SDK's own nn::os::CreateSystemEvent creates the kernel event (SVC 0x45) on a
// guest thread; the writable handle is kept, so any thread (host audio tick included) can signal it later.
// The guest may destroy such an event and attach the same SystemEventType again: the game does that with the nfp
// activate and deactivate events before each detection. nn::os::DestroySystemEvent zeroes the state byte at +0x28
// (0 not initialised, 1 event, 2 inter-process event; nn::os::TryWaitSystemEvent aborts on 0) and closes both
// handles, so a kept handle counts only while that byte is nonzero.
#define SE_STATE 0x28
static struct { uint64_t ev; uint32_t wh; } g_se[512];
static int g_nse;
static PlatMutex g_se_lock = PLAT_MUTEX_INIT;
static int se_live(uint64_t ev) {
return __atomic_load_n((const uint8_t *)(uintptr_t)(ev + SE_STATE), __ATOMIC_RELAXED) != 0;
}
static uint32_t se_find(uint64_t ev) {
plat_mutex_lock_shared(&g_se_lock);
uint32_t wh = 0;
@@ -2060,8 +2107,9 @@ static uint32_t se_find(uint64_t ev) {
return wh;
}
// A bound event the guest destroyed since is created again and its table entry takes the new writable handle.
void kern_bind_system_event(Cpu *c, uint64_t ev, int autoclear) {
if (se_find(ev)) return;
if (se_find(ev) && se_live(ev)) return;
if (!tcur || !c) rt_fatal("kern_bind_system_event(%#llx) on a host thread", (unsigned long long)ev);
static uint64_t create, getw;
if (!create) {
@@ -2073,15 +2121,21 @@ void kern_bind_system_event(Cpu *c, uint64_t ev, int autoclear) {
if (r) rt_fatal("kern_bind_system_event: CreateSystemEvent(%#llx) failed %#x", (unsigned long long)ev, r);
uint32_t wh = (uint32_t)rt_call(c, getw, 1, ev);
plat_mutex_lock(&g_se_lock);
if (g_nse == (int)(sizeof g_se / sizeof *g_se)) rt_fatal("kern_bind_system_event: table full");
g_se[g_nse].ev = ev;
g_se[g_nse++].wh = wh;
int i = 0;
while (i < g_nse && g_se[i].ev != ev) i++;
if (i == g_nse) {
if (g_nse == (int)(sizeof g_se / sizeof *g_se)) rt_fatal("kern_bind_system_event: table full");
g_se[g_nse++].ev = ev;
}
g_se[i].wh = wh;
plat_mutex_unlock(&g_se_lock);
}
// An event not bound yet is bound on the spot with manual clear, which needs a guest thread.
// An event not bound yet is bound on the spot with manual clear, which needs a guest thread. A bound event the guest
// destroyed is not signalled: its handles are closed and the kernel hands their numbers to new objects.
void kern_signal_system_event(uint64_t ev) {
uint32_t wh = se_find(ev);
if (wh && !se_live(ev)) return;
if (!wh) {
kern_bind_system_event(kern_cpu(), ev, 0);
wh = se_find(ev);
+40 -4
View File
@@ -305,9 +305,18 @@ static void test_arbiter(Cpu *c) {
CHECK(sig(c, 2, 5, 0) == 0 && g_arb == 6, "signal type 2, no waiter, count 0: value %d (want 6)", (int32_t)g_arb);
ArbJob jc = {.type = 2, .value = 6, .timeout = -1};
h = arb_spawn(c, &jc);
CHECK(sig(c, 2, 6, -1) == 0 && g_arb == 5, "signal type 2, 1 waiter, count -1: value %d (want 5)", (int32_t)g_arb);
// Waking all (count <= 0) with waiters subtracts 2 (mesosphere KAddressArbiter::SignalAndModifyByWaitingCountIfEqual).
CHECK(sig(c, 2, 6, -1) == 0 && g_arb == 4, "signal type 2, 1 waiter, count -1: value %d (want 4)", (int32_t)g_arb);
join(c, h);
CHECK(ja.r == 0 && jb.r == 0 && jc.r == 0, "wait type 2 results %#x %#x %#x", ja.r, jb.r, jc.r);
g_arb = 6;
ArbJob jd = {.type = 2, .value = 6, .timeout = -1}, je = jd;
uint32_t hd = arb_spawn(c, &jd), he = arb_spawn(c, &je);
CHECK(sig(c, 2, 6, 0) == 0 && g_arb == 4, "signal type 2, 2 waiters, count 0: value %d (want 4)", (int32_t)g_arb);
join(c, hd);
join(c, he);
CHECK(ja.r == 0 && jb.r == 0 && jc.r == 0 && jd.r == 0 && je.r == 0, "wait type 2 results %#x %#x %#x %#x %#x", ja.r,
jb.r, jc.r, jd.r, je.r);
g_arb = 5;
CHECK(sig(c, 2, 7, 1) == KERN_R_BAD_STATE, "signal type 2 with a different value");
// timeout, invalid type
uint64_t t0 = kern_now_ns();
@@ -320,11 +329,17 @@ static void test_arbiter(Cpu *c) {
}
// ---- events
typedef struct { uint32_t h, r, idx; int64_t timeout; volatile int delay, go; } EvJob;
// pre: a first wait on h0 with timeout t0 (result r0, index idx0) before the wait on h.
typedef struct { uint32_t h, r, idx, h0, r0, idx0; int64_t timeout, t0; volatile int delay, go; int pre; } EvJob;
static void event_waiter(Cpu *c) {
EvJob *j = arg_p(c, 0);
while (j->delay && !j->go) sleep_ms(c, 1);
if (j->pre) {
uint32_t h0[1] = {j->h0};
j->r0 = sv(c, 0x18, 0, ga(h0), 1, (uint64_t)j->t0);
j->idx0 = (uint32_t)c->x[1];
}
uint32_t hs[1] = {j->h};
j->r = sv(c, 0x18, 0, ga(hs), 1, (uint64_t)j->timeout);
j->idx = (uint32_t)c->x[1];
@@ -375,6 +390,26 @@ static void test_events(Cpu *c) {
join(c, h);
CHECK(g.r == KERN_R_CANCELLED, "wait after a cancel: %#x", g.r);
// A pending cancel is for the next WaitSynchronization that would block (mesosphere KSynchronizationObject::Wait:
// signalled objects first, then timeout 0, then the cancel): a poll times out and a wait on a signalled object
// succeeds, both leaving it pending; the next blocking wait ends cancelled. The blocking waits have a 500 ms
// timeout, so a cancel used up too early shows as a timeout instead of a hang.
CHECK(sv(c, 0x11, hw2, 0, 0, 0) == 0, "SignalEvent of the second event");
EvJob p = {.h = hr, .timeout = 500000000, .delay = 1, .pre = 1, .h0 = hr, .t0 = 0};
EvJob q = {.h = hr, .timeout = 500000000, .delay = 1, .pre = 1, .h0 = hr2, .t0 = -1};
EvJob *pq[2] = {&p, &q};
for (int i = 0; i < 2; i++) {
h = create(c, a_event_waiter, pq[i], 44, -2);
start(c, h);
CHECK(sv(c, 0x19, h, 0, 0, 0) == 0, "CancelSynchronization before the %s", i ? "signalled wait" : "poll");
pq[i]->go = 1;
join(c, h);
}
CHECK(p.r0 == KERN_R_TIMEOUT, "poll (timeout 0) with a cancel pending: %#x (want timeout)", p.r0);
CHECK(p.r == KERN_R_CANCELLED, "blocking wait after the poll: %#x (want cancelled)", p.r);
CHECK(q.r0 == 0 && q.idx0 == 0, "wait on a signalled event with a cancel pending: %#x (want success)", q.r0);
CHECK(q.r == KERN_R_CANCELLED, "blocking wait after the signalled wait: %#x (want cancelled)", q.r);
uint32_t sw = kern_event_new(), sr = kern_event_readable(sw);
CHECK(wait1(c, sr, 0) == KERN_R_TIMEOUT, "service event before the signal");
kern_event_signal(sw);
@@ -382,7 +417,8 @@ static void test_events(Cpu *c) {
uint32_t handles[] = {sr, sw, hr2, hw2, hr, hw};
for (unsigned i = 0; i < 6; i++) CHECK(sv(c, 0x16, handles[i], 0, 0, 0) == 0, "CloseHandle %#x", handles[i]);
CHECK(sv(c, 0x16, hr, 0, 0, 0) == KERN_R_BAD_HANDLE, "CloseHandle twice");
printf("events: signal, clear, reset, two handles, cancel while waiting and before, service events, 10 ms "
printf("events: signal, clear, reset, two handles, cancel while waiting and before, a pending cancel kept by a poll "
"and a signalled wait, service events, 10 ms "
"timeout after %.2f ms: %s\n", ms, failures == before ? "ok" : "FAIL");
}
+4 -4
View File
@@ -552,8 +552,8 @@ uint64_t ldr_plt_stub(const char *module, const char *name) {
}
// ---- --probe-loader
// Expected values, measured on the 1.1.1, 1.2.1 and 1.4.3 modules; the 1.4.3 relocation totals match the ones
// MacNativeGames' port notes give for that version. 1.1.1 shares subsdk0 and sdk with 1.2.1 down to every count.
// Expected values, measured on the 1.1.0, 1.2.1 and 1.4.3 modules; the 1.4.3 relocation totals match the ones
// MacNativeGames' port notes give for that version. 1.1.0 shares subsdk0 and sdk with 1.2.1 down to every count.
typedef struct {
const char *name;
uint64_t kinds[K_COUNT], total, sym_import, sym_own;
@@ -564,7 +564,7 @@ static const Expect expect_121[] = {
{"subsdk0", {1623, 12820, 1030, 3924}, 19397, 6576, 11198, 667, {9, 0, 654}, 4, 0x30, 45},
{"sdk", {10917, 13976, 1207, 8932}, 35032, 16, 24099, 13, {8, 0, 0}, 5, 0x30, 116},
};
static const Expect expect_111[] = {
static const Expect expect_110[] = {
{"main", {508604, 1412, 32, 639}, 510687, 2083, 0, 673, {0, 16, 645}, 12, 0x30, 10668},
{"subsdk0", {1623, 12820, 1030, 3924}, 19397, 6576, 11198, 667, {9, 0, 654}, 4, 0x30, 45},
{"sdk", {10917, 13976, 1207, 8932}, 35032, 16, 24099, 13, {8, 0, 0}, 5, 0x30, 116},
@@ -574,7 +574,7 @@ static const Expect expect_143[] = {
{"subsdk0", {3424, 10927, 905, 3817}, 19073, 6557, 9092, 663, {9, 0, 654}, 0, 0x20, 45},
{"sdk", {15013, 10135, 1079, 7832}, 34059, 10, 19036, 8, {8, 0, 0}, 0, 0x400, 83},
};
#define expect (RT_V143 ? expect_143 : RT_V111 ? expect_111 : expect_121)
#define expect (RT_V143 ? expect_143 : RT_V110 ? expect_110 : expect_121)
static int failures;
#define CHECK(cond, ...) do { if (!(cond)) { failures++; printf(" FAIL: " __VA_ARGS__); putchar('\n'); } } while (0)
+51 -8
View File
@@ -2,8 +2,10 @@
//
// totk.exe [--exefs DIR] [--romfs DIR] [--profile DIR] <mode>
// --selftest layout, dispatch table and host-function registry; needs no game files
// --probe-mods the mods folder scan, order and switches (mods.c); needs no game files
// --probe-loader load and relocate the modules, check them against the measured 1.2.1 values
// --probe-kernel, --probe-ipc, --probe-services, --probe-fs host probes
// --probe-discord the Rich Presence IPC exchange; skips without a Discord client; no game files
// --probe-dpi the process DPI awareness (per-monitor v2) and the primary monitor's size; no game files
// --probe-gfx-abi NVN object layouts against nvn.h's reserved sizes; needs no game files
// --probe-nvn, --probe-nvn-tex, --probe-window, --probe-shader, --probe-vkmem, --probe-vkexec graphics probes
@@ -152,8 +154,8 @@ static RtConfig cfg;
const RtConfig *rt_config(void) { return &cfg; }
// ---- runtime services the generated code calls (cpu.h)
volatile int g_fnprof = 0;
void fnprof_hit(uint64_t addr, uint64_t lr, uint64_t x0) { (void)addr, (void)lr, (void)x0; }
volatile int g_fnprof = 0; // resolution.c switches it on until the game sets its render size (res_fn_hit)
void fnprof_hit(uint64_t addr, uint64_t lr, uint64_t x0) { (void)lr, res_fn_hit(addr, x0); }
void rt_brk(Cpu *c, uint32_t imm, uint64_t pc) {
char at[128], lr[128];
@@ -217,16 +219,21 @@ static void crash_handler(const PlatCrash *x) {
if (plat_xchg32(&busy, 1)) plat_exit(71);
char d[160];
uintptr_t rip = x->rip;
rt_logf("FATAL: %s (%#x) at host %p (totk+%#llx)", x->what, x->code, (void *)rip, (unsigned long long)x->offset);
rt_logf("FATAL: %s (%#x) at host %p (", x->what, x->code, (void *)rip);
if (x->module && !*x->module) rt_logf("outside every module)");
else rt_logf("%s+%#llx)", x->module ? x->module : "totk", (unsigned long long)x->offset);
if (x->access >= 0)
rt_logf(", %s address %#llx", x->access == 1 ? "writing" : x->access == 8 ? "executing" : "reading",
(unsigned long long)x->addr);
rt_log_raw("\n", 1);
uint64_t f = lifted_function(rip);
uint64_t f = x->module ? 0 : lifted_function(rip);
if (f) rt_logf(" in lifted function f_%llx = %s\n", (unsigned long long)f, ldr_describe(f, d, sizeof d));
for (int i = 0; i < x->nframes; i++) { // abort and invalid parameter: where the host code called it
// abort and invalid parameter: where the host code called it; a fault in another module: the host calls that led
// into it
uintptr_t exe = plat_exe_base();
for (int i = 0; i < x->nframes; i++) {
uint64_t g = lifted_function(x->frames[i]);
rt_logf(" host frame %2d: totk+%#llx", i, (unsigned long long)(x->frames[i] - (rip - x->offset)));
rt_logf(" host frame %2d: totk+%#llx", i, (unsigned long long)(x->frames[i] - exe));
if (g) rt_logf(" in lifted function f_%llx", (unsigned long long)g);
rt_log_raw("\n", 1);
}
@@ -246,6 +253,7 @@ static void crash_handler(const PlatCrash *x) {
} else {
rt_logf(" not on a guest thread\n");
}
kern_free_cores_note();
fflush(stderr);
plat_exit(71);
}
@@ -259,11 +267,22 @@ static double now_s(void) { return (double)plat_now_ns() / 1e9; }
static volatile int host_probe_hits;
static void host_probe(Cpu *c) { host_probe_hits++; c->x[0] = 42; }
// The instruction set build_game.py --cpu compiled for: v3 (AVX2/FMA/BMI2, the default) or v2 (SSE4.2/POPCNT).
#ifndef RT_CPU_LEVEL
#define RT_CPU_LEVEL 3
#endif
static void check_cpu(void) {
__builtin_cpu_init();
#if RT_CPU_LEVEL >= 3
int ok = __builtin_cpu_supports("avx2") && __builtin_cpu_supports("fma") && __builtin_cpu_supports("bmi2");
printf("cpu: x86-64-v3 (AVX2, FMA, BMI2) %s\n", ok ? "present" : "MISSING");
CHECK(ok, "the lifted code is built for x86-64-v3");
#else
int ok = __builtin_cpu_supports("sse4.2") && __builtin_cpu_supports("popcnt");
printf("cpu: x86-64-v2 (SSE4.2, POPCNT) %s\n", ok ? "present" : "MISSING");
CHECK(ok, "the lifted code is built for x86-64-v2");
#endif
}
// Layout: ascending, no overlap, below 2^39, and inside the window mem_init reserved.
@@ -426,11 +445,27 @@ static int selftest(void) {
return failures ? 1 : 0;
}
// --probe-crash-call and --probe-crash-null crash on purpose, to check the report of a fault outside this executable.
// call: strlen in the C runtime library (ucrtbase.dll, libc.so.6) reads address 8, the way a driver faults inside a
// call the host made; the report names the library and the host frames that called it. null: a call through a null
// function pointer, which leaves rip at 0, outside every module. Both end with exit code 71 and a FATAL line in the
// log.
static size_t (*volatile probe_strlen)(const char *) = strlen;
static void (*volatile probe_null)(void);
static int probe_crash(int null) {
if (null) probe_null();
else printf("%zu\n", probe_strlen((const char *)(uintptr_t)8));
printf("probe-crash: still running, the crash did not happen\n");
return 1;
}
static int usage(const char *argv0) {
fprintf(stderr, "usage: %s [--exefs DIR] [--romfs DIR] [--profile DIR] [--selftest | --probe-loader | "
"--probe-cfg | --probe-dpi | --probe-kernel | --probe-ipc | --probe-services | --probe-fs | --probe-gfx-abi | "
"--probe-cfg | --probe-dpi | --probe-mods | --probe-kernel | --probe-ipc | --probe-services | --probe-fs | --probe-gfx-abi | "
"--probe-nvn | --probe-nvn-tex | --probe-window | --probe-shader | --probe-vkmem | "
"--probe-vkexec | --probe-astc | --probe-movie | --prepare-shaders | --warm-shaders | --boot |--seconds S [--shot PNG]]\n", argv0);
"--probe-vkexec | --probe-astc | --probe-movie | --probe-crash-call | --probe-crash-null | --probe-discord | "
"--prepare-shaders | --warm-shaders | --boot |--seconds S [--shot PNG]]\n", argv0);
return 2;
}
@@ -468,6 +503,9 @@ static void portable_paths(RtConfig *c) {
int main(int argc, char **argv) {
mem_init(); // first: claim the guest address space before anything else can land there; reads totk.ini
// A restart from the settings menu (gfx_present.c gfx_window_closed) starts this process while the one it replaces
// is still exiting: its log, RomFS and saves are free once it is gone.
if (plat_restart_wait(30000) < 0) rt_log("restart: the previous process still runs after 30 s; starting anyway");
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
plat_crash_hook(crash_handler);
@@ -510,15 +548,20 @@ int main(int argc, char **argv) {
log_open(!mode);
if (!mode) {
cfg.boot = cfg.seconds > 0; // --seconds starts the game like --boot, with its checkpoints
discord_init(); // the Rich Presence thread (discord_rpc.c); it reads totk.ini itself and idles while off
rt_boot();
return 0;
}
if (!strcmp(mode, "--selftest")) return selftest();
if (!strcmp(mode, "--probe-loader")) return probe_loader();
if (!strcmp(mode, "--probe-crash-call")) return probe_crash(0);
if (!strcmp(mode, "--probe-crash-null")) return probe_crash(1);
if (!strcmp(mode, "--probe-cfg")) return probe_cfg();
#ifdef _WIN32
if (!strcmp(mode, "--probe-dpi")) return probe_dpi(); // the Win32 DPI awareness of totk.manifest
#endif
if (!strcmp(mode, "--probe-mods")) return probe_mods();
if (!strcmp(mode, "--probe-discord")) return probe_discord();
if (!strcmp(mode, "--probe-kernel")) return probe_kernel();
if (!strcmp(mode, "--probe-ipc")) return probe_ipc();
if (!strcmp(mode, "--probe-services")) return probe_services();
+457
View File
@@ -0,0 +1,457 @@
// Player mods: the scan of the mods folder, its order and switches (mods.h).
//
// One subfolder per mod, as emulators take them. The RomFS root is the first of <mod>/romfs, <mod>/romfslite (TKMM's
// name for it when it bypasses Atmosphere's RomFS build), <mod>/atmosphere/contents/<title>/romfs,
// <mod>/contents/<title>/romfs and <mod>/<title>/romfs that exists; the ExeFS and cheats folders likewise. A mod is
// listed whatever it holds; what the port cannot use is its problem, shown in the menu and logged, and never stops the
// start. romfs.c serves the RomFS files of the enabled mods, the top one winning a path.
//
// The order and the switches are totk.ini keys (cfg.c): TOTK_MODS_ORDER lists names top first, separated by '|' (a
// Windows file name cannot hold '|'; a folder whose name does on Linux is listed as unusable); a folder it does not name
// goes below the named ones, by name. TOTK_MODS_DISABLED lists the switched-off names. The menu changes the list in
// place and writes both keys; the scan's state is kept to tell the menu a restart is due.
//
// ExeFS patch files: an .ips or .pchtxt file in the exefs folder or in atmosphere/exefs_patches/<name>/ is for the game
// when its build id is main's (an IPS file's name, a pchtxt file's @nsobid line); others are another version's and
// counted. The setup builds every mod's files into patch sets and writes build-cache/exefs.status next to totk.exe
// (tools/exefs_patches.py has the format): a file whose line is missing or has another content hash waits for the
// rebuild at start (cheats.c), and its mod stays off until then.
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include "cfg.h"
#include "host.h"
#include "mods.h"
#include "platform/platform.h"
#define TITLE "0100F2C0115B6000"
#define MAX_MODS 512
static ModInfo *mods;
static int nmods;
static char dir[2048];
static char start_order[MAX_MODS][256]; // names in the scan's order and their switches, for mods_changed
static int start_enabled[MAX_MODS];
// 1 when a file lies anywhere under path.
static int has_file_cb(const char *name, int kind, uint64_t size, void *ctx);
static int has_file(const char *path) {
struct { const char *path; int found; } c = {path, 0};
plat_fs_list(path, has_file_cb, &c);
return c.found;
}
static int has_file_cb(const char *name, int kind, uint64_t size, void *ctx) {
(void)size;
struct { const char *path; int found; } *c = ctx;
if (kind == PLAT_FS_FILE) {
c->found = 1;
} else if (kind == PLAT_FS_DIR) {
char sub[2100];
if (snprintf(sub, sizeof sub, "%s/%s", c->path, name) < (int)sizeof sub) c->found = has_file(sub);
}
return !c->found;
}
// The first of the emulator and Atmosphere places of <mod>/<part> that is a folder, into out ("" none).
static void find_root(const char *mod, const char *part, char *out, size_t cap) {
static const char *const forms[] = {"%s/%s", "%s/atmosphere/contents/" TITLE "/%s", "%s/contents/" TITLE "/%s",
"%s/" TITLE "/%s"};
for (size_t i = 0; i < sizeof forms / sizeof *forms; i++) {
if (snprintf(out, cap, forms[i], mod, part) < (int)cap && plat_dir_exists(out)) return;
}
out[0] = 0;
}
static int ends_with_ci(const char *s, const char *tail) {
size_t n = strlen(s), t = strlen(tail);
return n >= t && !strcasecmp(s + n - t, tail);
}
// What the ExeFS folder holds: MOD_EXEFS for patches (.ips, .pchtxt), MOD_SUBSDK for code modules (subsdk* plugins, a
// replaced main). main.npdm alone is the process's metadata, not code: it counts as neither.
static int exefs_cb(const char *name, int kind, uint64_t size, void *ctx) {
(void)size;
int *k = ctx;
if (kind != PLAT_FS_FILE) return 1;
if (ends_with_ci(name, ".ips") || ends_with_ci(name, ".pchtxt")) *k |= MOD_EXEFS;
else if (!strncasecmp(name, "subsdk", 6) || !strcasecmp(name, "main")) *k |= MOD_SUBSDK;
return 1;
}
// MOD_CHEATS when the cheats folder holds an Atmosphere cheat file (<build id>.txt).
static int cheats_cb(const char *name, int kind, uint64_t size, void *ctx) {
(void)size;
if (kind == PLAT_FS_FILE && ends_with_ci(name, ".txt")) *(int *)ctx |= MOD_CHEATS;
return 1;
}
// 1 when name is one of the '|'-separated names of list.
static int listed(const char *list, const char *name) {
size_t n = strlen(name);
for (const char *p = list; p && *p;) {
const char *bar = strchr(p, '|');
size_t len = bar ? (size_t)(bar - p) : strlen(p);
if (len == n && !memcmp(p, name, n)) return 1;
p = bar ? bar + 1 : NULL;
}
return 0;
}
// The position of name in the '|'-separated list, or -1.
static int list_pos(const char *list, const char *name) {
size_t n = strlen(name);
int k = 0;
for (const char *p = list; p && *p; k++) {
const char *bar = strchr(p, '|');
size_t len = bar ? (size_t)(bar - p) : strlen(p);
if (len == n && !memcmp(p, name, n)) return k;
p = bar ? bar + 1 : NULL;
}
return -1;
}
static const char *order_list; // TOTK_MODS_ORDER while sorting
static int by_order(const void *a, const void *b) {
const ModInfo *x = a, *y = b;
int px = list_pos(order_list, x->name), py = list_pos(order_list, y->name);
if (px >= 0 && py >= 0) return px - py;
if (px >= 0 || py >= 0) return px >= 0 ? -1 : 1;
return strcmp(x->name, y->name);
}
static const char *problem_name(ModProblem p) {
switch (p) {
case MOD_EMPTY: return "empty";
case MOD_PLUGIN: return "has a code module (subsdk or main), not supported; the whole mod stays off";
case MOD_EXEFS_LATER: return "ExeFS patches wait for a rebuild of the game code; the whole mod stays off";
case MOD_EXEFS_UNSUPPORTED: return "an ExeFS patch file cannot be applied; the whole mod stays off";
case MOD_EXEFS_OTHER: return "its ExeFS patches are for another game version";
case MOD_BAD_NAME: return "its folder name holds '|', which the order list uses; rename the folder";
default: return "ok";
}
}
// ---- ExeFS patch files
static uint32_t fnv(const void *p, size_t n) {
uint32_t h = 0x811C9DC5u;
for (size_t i = 0; i < n; i++) h = (h ^ ((const uint8_t *)p)[i]) * 0x01000193u;
return h;
}
const char *mods_main_build_id(void) {
static char bid[65];
static int read;
if (read) return bid;
read = 1;
char path[2100];
snprintf(path, sizeof path, "%s/main", rt_config()->exefs);
PlatFile *f = plat_file_open(path);
uint8_t head[0x60];
int ok = f && plat_file_pread(f, head, sizeof head, 0) == sizeof head && !memcmp(head, "NSO0", 4);
if (f) plat_file_close(f);
for (int i = 0; ok && i < 32; i++) snprintf(bid + 2 * i, 3, "%02x", head[0x40 + i]);
return bid;
}
// 1 when hex (any case; trailing zeros left out or not) names main's build id; also when main's is unknown.
static int same_build(const char *hex, size_t n) {
const char *bid = mods_main_build_id();
if (!*bid) return 1;
if (!n || n > 64) return 0;
for (size_t i = 0; i < 64; i++) {
char c = i < n ? hex[i] : '0';
if (c >= 'A' && c <= 'F') c = (char)(c - 'A' + 'a');
if (c != bid[i]) return 0;
}
return 1;
}
// build-cache/exefs.status next to totk.exe, read once; "" when there is none.
static const char *exefs_status(void) {
static char *text;
if (text) return text;
char path[2100];
uint64_t n = 0;
if (plat_exe_path(path, sizeof path)) {
char *cut = strrchr(path, '/'), *back = strrchr(path, '\\');
if (back > cut) cut = back;
if (cut) snprintf(cut + 1, sizeof path - (size_t)(cut + 1 - path), "build-cache/exefs.status");
text = (char *)plat_file_read(path, &n);
}
if (!text) text = calloc(1, 1);
return text;
}
// The status line of key: its kind, built-in sets and note, NUL-terminated copies; 0 when none.
static int status_line(const char *key, const char *content, char *kind, char *over, char *note) {
char want[20];
snprintf(want, sizeof want, "%s\t%s\t", key, content);
for (const char *line = exefs_status(); *line;) {
const char *end = strchr(line, '\n');
size_t len = end ? (size_t)(end - line) : strlen(line);
if (len > 18 && !memcmp(line, want, 18)) {
char copy[600];
snprintf(copy, sizeof copy, "%.*s", (int)(len < sizeof copy ? len : sizeof copy - 1), line + 18);
char *t1 = strchr(copy, '\t'), *t2 = t1 ? strchr(t1 + 1, '\t') : NULL;
if (!t1 || !t2) return 0;
*t1 = *t2 = 0;
char *r = strchr(t2 + 1, '\r');
if (r) *r = 0;
snprintf(kind, 16, "%s", copy);
snprintf(over, 256, "%s", strcmp(t1 + 1, "-") ? t1 + 1 : "");
snprintf(note, 256, "%s", t2 + 1);
return 1;
}
line = end ? end + 1 : line + len;
}
return 0;
}
typedef struct {
ModInfo *m;
const char *folder, *rel; // the folder listed and its path in the mod
int unsupported;
} ExefsWalk;
// One file of an exefs folder: its build, then its status line.
static int exefs_file_cb(const char *leaf, int kind, uint64_t size, void *ctx) {
(void)size;
ExefsWalk *w = ctx;
ModInfo *m = w->m;
int ips = ends_with_ci(leaf, ".ips");
if (kind != PLAT_FS_FILE || (!ips && !ends_with_ci(leaf, ".pchtxt"))) return 1;
m->kind |= MOD_EXEFS;
char path[4300], rel[600];
snprintf(path, sizeof path, "%s/%s", w->folder, leaf);
snprintf(rel, sizeof rel, "%s/%s/%s", m->name, w->rel, leaf);
uint64_t n = 0;
char *data = (char *)plat_file_read(path, &n);
if (!data) {
rt_log("mods: %s: cannot read %s", m->name, path);
return 1;
}
int for_main;
if (ips) {
for_main = same_build(leaf, strlen(leaf) - 4);
} else {
char *id = NULL; // after "@nsobid-" at the start of a line
for (char *p = data; !id && p && data + n - p > 8;) {
if (!memcmp(p, "@nsobid-", 8)) id = p + 8;
p = memchr(p, '\n', (size_t)(data + n - p));
if (p) p++;
}
size_t len = 0;
while (id && id + len < data + n && isxdigit((unsigned char)id[len])) len++;
for_main = id && same_build(id, len);
}
char key[9], content[9], kind_s[16], over[256], note[256];
snprintf(key, sizeof key, "%08X", fnv(rel, strlen(rel)));
snprintf(content, sizeof content, "%08X", fnv(data, (size_t)n));
free(data);
if (!for_main) {
m->other_version++;
return 1;
}
if (!status_line(key, content, kind_s, over, note)) {
m->pending++;
m->pending_key = (m->pending_key ^ fnv(key, 8)) * 0x01000193u;
m->pending_key = (m->pending_key ^ fnv(content, 8)) * 0x01000193u;
return 1;
}
if (!strcmp(kind_s, "unsupported")) {
if (!w->unsupported) snprintf(m->note, sizeof m->note, "%s: %s", leaf, note);
w->unsupported = 1;
} else if (!strcmp(kind_s, "code") && m->nsets < (int)(sizeof m->sets / sizeof *m->sets)) {
m->sets[m->nsets++] = (uint32_t)strtoul(key, NULL, 16);
size_t k = strlen(m->overrides);
if (*over) snprintf(m->overrides + k, sizeof m->overrides - k, "%s%s", k ? "," : "", over);
} else if (!strcmp(kind_s, "other")) {
m->other_version++;
}
return 1;
}
// atmosphere/exefs_patches/<name>/ of a mod: each <name> folder's files.
static int exefs_patches_cb(const char *leaf, int kind, uint64_t size, void *ctx) {
(void)size;
ExefsWalk *w = ctx;
if (kind != PLAT_FS_DIR) return 1;
char folder[4300], rel[600];
snprintf(folder, sizeof folder, "%s/%s", w->folder, leaf);
snprintf(rel, sizeof rel, "atmosphere/exefs_patches/%s", leaf);
ExefsWalk sub = {w->m, folder, rel, 0};
plat_fs_list(folder, exefs_file_cb, &sub);
w->unsupported |= sub.unsupported;
return 1;
}
// The ExeFS patch files of mod m (folder path): 1 when one cannot be applied.
static int exefs_check(ModInfo *m, const char *path) {
ExefsWalk w = {m, m->exefs, m->exefs + strlen(path) + 1, 0};
if (m->exefs[0]) plat_fs_list(m->exefs, exefs_file_cb, &w);
char patches[2200];
snprintf(patches, sizeof patches, "%s/atmosphere/exefs_patches", path);
ExefsWalk at = {m, patches, "", 0};
if (plat_dir_exists(patches)) plat_fs_list(patches, exefs_patches_cb, &at);
return w.unsupported || at.unsupported;
}
// One mod folder of the scan.
static int scan_cb(const char *name, int kind, uint64_t size, void *ctx) {
(void)size;
const char *disabled = ctx;
if (kind != PLAT_FS_DIR) return 1;
if (nmods == MAX_MODS) {
rt_log("mods: more than %d folders in %s; the rest are left out", MAX_MODS, dir);
return 0;
}
ModInfo *m = &mods[nmods];
memset(m, 0, sizeof *m);
char path[2100];
if (snprintf(m->name, sizeof m->name, "%s", name) >= (int)sizeof m->name ||
snprintf(path, sizeof path, "%s/%s", dir, name) >= (int)sizeof path) {
rt_log("mods: %s: name too long, left out", name);
return 1;
}
find_root(path, "romfs", m->romfs, sizeof m->romfs);
if (!m->romfs[0]) find_root(path, "romfslite", m->romfs, sizeof m->romfs);
find_root(path, "exefs", m->exefs, sizeof m->exefs);
find_root(path, "cheats", m->cheats, sizeof m->cheats);
if (m->romfs[0] && has_file(m->romfs)) m->kind |= MOD_ROMFS;
if (m->exefs[0]) plat_fs_list(m->exefs, exefs_cb, &m->kind);
if (m->cheats[0]) plat_fs_list(m->cheats, cheats_cb, &m->kind);
int unsupported = exefs_check(m, path);
// a mod whose code part the port cannot use is off as a whole: its RomFS files may expect that code
m->problem = strchr(m->name, '|') ? MOD_BAD_NAME
: m->kind & MOD_SUBSDK ? MOD_PLUGIN
: unsupported ? MOD_EXEFS_UNSUPPORTED
: m->pending ? MOD_EXEFS_LATER
: m->nsets || m->kind & (MOD_ROMFS | MOD_CHEATS) ? MOD_OK
: m->kind & MOD_EXEFS ? MOD_EXEFS_OTHER
: MOD_EMPTY;
m->enabled = !listed(disabled, m->name);
nmods++;
return 1;
}
void mods_scan(void) {
static int done;
if (done) return;
done = 1;
const char *d = cfg_get("TOTK_MODS_DIR");
if (d && *d) {
snprintf(dir, sizeof dir, "%s", d);
} else {
char exe[2048];
if (!plat_exe_path(exe, sizeof exe)) return;
char *cut = strrchr(exe, '/'), *back = strrchr(exe, '\\');
if (back > cut) cut = back;
if (!cut) return;
*cut = 0;
snprintf(dir, sizeof dir, "%s/mods", exe);
}
if (!plat_dir_exists(dir)) {
rt_log("mods: no folder %s", dir);
return;
}
mods = calloc(MAX_MODS, sizeof *mods);
if (!mods) return;
plat_fs_list(dir, scan_cb, (void *)cfg_get("TOTK_MODS_DISABLED"));
order_list = cfg_get("TOTK_MODS_ORDER");
qsort(mods, nmods, sizeof *mods, by_order);
order_list = NULL;
for (int i = 0; i < nmods; i++) {
snprintf(start_order[i], sizeof start_order[i], "%s", mods[i].name);
start_enabled[i] = mods[i].enabled;
const ModInfo *m = &mods[i];
rt_log("mods: %s: %s,%s%s%s%s%s, %s%s%s", m->name, m->enabled ? "on" : "off", m->kind & MOD_ROMFS ? " romfs" : "",
m->kind & MOD_EXEFS ? " exefs" : "", m->kind & MOD_SUBSDK ? " subsdk" : "",
m->kind & MOD_CHEATS ? " cheats" : "", m->kind ? "" : " no files", problem_name(m->problem),
m->note[0] ? ": " : "", m->note);
}
rt_log("mods: %d folders in %s", nmods, dir);
}
void mods_exefs_switch(void) {
mods_scan();
for (int i = 0; i < nmods; i++) {
const ModInfo *m = &mods[i];
if (!start_enabled[i] || m->problem != MOD_OK || !m->nsets) continue;
for (int k = 0; k < m->nsets; k++) {
char name[32];
snprintf(name, sizeof name, "mod_%08x", m->sets[k]);
int set = rt_patch_set(name);
if (set >= 0) rt_patch_switch(set, 1);
else rt_log("mods: %s: patch set %s is not in this build", m->name, name);
}
char over[256];
snprintf(over, sizeof over, "%s", m->overrides);
for (char *s = strtok(over, ","); s; s = strtok(NULL, ",")) {
int set = rt_patch_set(s);
if (set >= 0) rt_patch_switch(set, 0);
rt_log("mods: %s replaces the port's patch set %s; it stays off", m->name, s);
}
rt_log("mods: %s: %d ExeFS patch files on", m->name, m->nsets);
}
}
int mods_exefs_pending(uint32_t *key) {
int n = 0;
for (int i = 0; i < nmods; i++) {
if (!start_enabled[i] || mods[i].problem != MOD_EXEFS_LATER) continue;
n += (int)mods[i].pending;
*key = (*key ^ mods[i].pending_key) * 0x01000193u;
}
return n;
}
const char *mods_dir(void) { return dir; }
int mods_count(void) { return nmods; }
ModInfo *mods_at(int i) { return i >= 0 && i < nmods ? &mods[i] : NULL; }
// TOTK_MODS_ORDER as every listed name top first; TOTK_MODS_DISABLED as the switched-off names. A name holding '|'
// would split into two; it is left out of both (its mod is unusable anyway).
static void write_keys(void) {
size_t cap = (size_t)nmods * 257 + 1;
char *order = calloc(cap, 1), *off = calloc(cap, 1);
if (order && off) {
for (int i = 0; i < nmods; i++) {
if (mods[i].problem == MOD_BAD_NAME) continue;
if (*order) strcat(order, "|");
strcat(order, mods[i].name);
if (!mods[i].enabled) {
if (*off) strcat(off, "|");
strcat(off, mods[i].name);
}
}
cfg_set("TOTK_MODS_ORDER", order);
cfg_set("TOTK_MODS_DISABLED", off);
}
free(order);
free(off);
}
void mods_set_enabled(int i, int on) {
if (i < 0 || i >= nmods) return;
mods[i].enabled = on != 0;
write_keys();
}
void mods_move(int i, int delta) {
int j = i + delta;
if (i < 0 || i >= nmods || j < 0 || j >= nmods || i == j) return;
ModInfo t = mods[i];
mods[i] = mods[j];
mods[j] = t;
write_keys();
}
int mods_changed(void) {
for (int i = 0; i < nmods; i++)
if (strcmp(mods[i].name, start_order[i]) || mods[i].enabled != start_enabled[i]) return 1;
return 0;
}
+57
View File
@@ -0,0 +1,57 @@
// Player mods (mods.c): one folder per mod under mods/ next to totk.exe (TOTK_MODS_DIR), unpacked as emulators take
// them: <mod>/romfs, <mod>/exefs and <mod>/cheats, the Atmosphere layout (atmosphere/contents/<title id>/romfs,
// atmosphere/exefs_patches/<name>/*.ips) or TKMM's merged output (romfs or romfslite, exefs, cheats). ExeFS patch
// files (.ips, .pchtxt) for the game's main are patch sets the setup builds into the game (tools/exefs_patches.py),
// switched with their mod (mods_exefs_switch). The list is scanned once at start (romfs.c overlay_init);
// its order and switches live in totk.ini [mods] (TOTK_MODS_ORDER: names top first, separated by '|';
// TOTK_MODS_DISABLED: names switched off). The top mod wins a file two mods replace.
#pragma once
#include <stdint.h>
enum { MOD_ROMFS = 1, MOD_EXEFS = 2, MOD_SUBSDK = 4, MOD_CHEATS = 8 }; // ModInfo.kind bits
typedef enum {
MOD_OK,
MOD_EMPTY, // no RomFS file, no ExeFS patch, no cheat file
MOD_PLUGIN, // has code modules (exefs/subsdk*, a replaced exefs/main): the port has no module loader, so the
// whole mod stays off (its RomFS files may expect that code)
MOD_EXEFS_LATER, // has ExeFS patches for this game's main that the game was built without: the rebuild at the
// next start builds them in; the whole mod stays off until then
MOD_EXEFS_UNSUPPORTED, // an ExeFS patch file the port cannot apply (note says why): the whole mod stays off
MOD_EXEFS_OTHER, // only ExeFS patches, all for another game version
MOD_BAD_NAME, // its folder name holds '|', the separator of the order keys
} ModProblem;
typedef struct {
char name[256]; // folder name, UTF-8
char romfs[2048]; // UTF-8 path of its RomFS root; "" none
char exefs[2048]; // UTF-8 path of its ExeFS folder; "" none
char cheats[2048]; // UTF-8 path of its cheats folder; "" none
int kind, enabled;
ModProblem problem;
uint32_t replaced, added, overridden; // romfs.c: files served (replacing / added), files a higher mod serves
uint32_t other_version; // files for another game version (RomFS *.Product.<n>.*, ExeFS patches
// for another build), not used
char overridden_by[256]; // the first higher mod that took one of its files
char note[256]; // MOD_EXEFS_UNSUPPORTED: why
uint32_t pending, pending_key; // ExeFS patch files the build lacks; FNV-1a of their names and contents
int nsets;
uint32_t sets[16]; // the built patch sets mod_<hash> of its ExeFS patch files
char overrides[256]; // the port's own patch sets its patches replace, comma separated
} ModInfo;
void mods_scan(void); // once; later calls return at once
const char *mods_dir(void); // the folder scanned (default: <dir of totk.exe>/mods)
int mods_count(void);
ModInfo *mods_at(int i); // 0 = top of the order; NULL out of range
// Menu edits (present path). They change the list mods_at shows and write TOTK_MODS_ORDER / TOTK_MODS_DISABLED with
// cfg_set; romfs.c used the start state, so they apply at the next start.
void mods_set_enabled(int i, int on);
void mods_move(int i, int delta); // -1 up, +1 down; nothing at the ends
int mods_changed(void); // 1 when the order or a switch differs from the start
// After rt_patches_init: the patch sets of the enabled mods' ExeFS patches on, the port's own sets they replace off.
void mods_exefs_switch(void);
// The ExeFS patch files of the enabled mods that the build lacks, their FNV-1a mixed into *key (cheats.c starts the
// rebuild for them).
int mods_exefs_pending(uint32_t *key);
// The hex of the game main's build id (64 digits), "" when exefs/main cannot be read.
const char *mods_main_build_id(void);
+130
View File
@@ -0,0 +1,130 @@
// --probe-mods: the mods folder scan, its order and switches (mods.c). Builds a mods folder of its own next to totk.exe,
// scans it and removes it. Needs no game files.
#include <stdio.h>
#include <string.h>
#include "cfg.h"
#include "host.h"
#include "mods.h"
#include "platform/platform.h"
static int fails;
#define CHECK(c, what) do { if (!(c)) { fails++; fprintf(stderr, "FAIL mods: %s\n", what); } } while (0)
#define EQ(a, b) ((a) && !strcmp((a), (b)))
// root/rel as a file of a few bytes (rel ends in '/': a folder), with every folder above it.
static void put(const char *root, const char *rel) {
char p[2048];
snprintf(p, sizeof p, "%s/%s", root, rel);
char *slash = strrchr(p, '/');
*slash = 0;
plat_file_mkdir_p(p);
*slash = '/';
if (slash[1]) plat_file_write(p, "probe", 5);
}
static int remove_cb(const char *name, int kind, uint64_t size, void *ctx);
static void remove_tree(const char *dir) {
plat_fs_list(dir, remove_cb, (void *)dir);
plat_fs_rmdir(dir);
}
static int remove_cb(const char *name, int kind, uint64_t size, void *ctx) {
(void)size;
char sub[2048];
snprintf(sub, sizeof sub, "%s/%s", (const char *)ctx, name);
if (kind == PLAT_FS_DIR) remove_tree(sub);
else plat_fs_unlink(sub);
return 1;
}
// s ends in tail, either path separator matching either.
static int ends_with(const char *s, const char *tail) {
size_t n = strlen(s), t = strlen(tail);
if (n < t) return 0;
for (size_t i = 0; i < t; i++) {
char a = s[n - t + i], b = tail[i];
if (a == '\\') a = '/';
if (b == '\\') b = '/';
if (a != b) return 0;
}
return 1;
}
int probe_mods(void) {
char root[1024];
if (!plat_exe_path(root, sizeof root)) return 1;
char *cut = strrchr(root, '/'), *back = strrchr(root, '\\');
if (back > cut) cut = back;
if (!cut) return 1;
strcpy(cut + 1, "mods-probe");
remove_tree(root);
plat_file_mkdir_p(root);
static const char *const files[] = {
"A/romfs/x.bin", "B/atmosphere/contents/0100F2C0115B6000/romfs/x.bin",
"C/contents/0100F2C0115B6000/romfs/y.bin", "D/exefs/main.pchtxt", "E/exefs/subsdk9", "F/romfs/",
"G/romfs/z.bin", "G/exefs/1234.ips", "Ultra \xD0\x96/romfs/u.bin",
"H/romfs/h.bin", "H/exefs/subsdk9", "I/romfs/i.bin", "I/exefs/main", "J/cheats/0123456789ABCDEF.txt",
"K/romfslite/k.bin", "L/romfs/l.bin", "L/cheats/0123456789ABCDEF.txt", "L/exefs/main.npdm",
};
for (size_t i = 0; i < sizeof files / sizeof *files; i++) put(root, files[i]);
// an IPS file for this game's main (any file counts as one when main cannot be read), in Atmosphere's layout
char ips[160];
snprintf(ips, sizeof ips, "M/atmosphere/exefs_patches/x/%s.ips", *mods_main_build_id() ? mods_main_build_id() : "0");
put(root, ips);
cfg_set("TOTK_MODS_DIR", root);
cfg_set("TOTK_MODS_ORDER", "B|A|Gone");
cfg_set("TOTK_MODS_DISABLED", "C");
mods_scan();
static const char *const order[] = {"B", "A", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"Ultra \xD0\x96"};
enum { N = sizeof order / sizeof *order };
CHECK(mods_count() == N, "fourteen mod folders");
int in_order = mods_count() == N;
for (int i = 0; in_order && i < N; i++) in_order = EQ(mods_at(i)->name, order[i]);
CHECK(in_order, "order: mods_order first, the rest by name");
if (mods_count() == N && in_order) {
ModInfo *a = mods_at(1), *b = mods_at(0), *c = mods_at(2), *d = mods_at(3), *e = mods_at(4), *f = mods_at(5),
*g = mods_at(6), *hm = mods_at(7), *im = mods_at(8), *jm = mods_at(9), *km = mods_at(10),
*lm = mods_at(11), *mm = mods_at(12), *u = mods_at(13);
CHECK(hm->kind == (MOD_ROMFS | MOD_SUBSDK) && hm->problem == MOD_PLUGIN, "RomFS + subsdk plugin: unusable");
CHECK(im->kind == (MOD_ROMFS | MOD_SUBSDK) && im->problem == MOD_PLUGIN, "RomFS + replaced exefs/main");
CHECK(ends_with(b->romfs, "B/atmosphere/contents/0100F2C0115B6000/romfs"), "Atmosphere RomFS root");
CHECK(ends_with(c->romfs, "C/contents/0100F2C0115B6000/romfs"), "contents RomFS root");
CHECK(ends_with(a->romfs, "A/romfs") && a->kind == MOD_ROMFS && a->problem == MOD_OK, "plain RomFS mod");
CHECK(!c->enabled && a->enabled && b->enabled && g->enabled && u->enabled, "mods_disabled switches C off");
CHECK(d->kind == MOD_EXEFS && d->problem == MOD_EXEFS_OTHER && d->other_version == 1,
"ExeFS patch mod without a build id: another version's");
CHECK(e->problem == MOD_PLUGIN, "subsdk-only mod is a plugin mod");
CHECK(f->problem == MOD_EMPTY, "empty RomFS folder");
CHECK(g->kind == (MOD_ROMFS | MOD_EXEFS) && g->problem == MOD_OK && g->other_version == 1,
"RomFS + another version's ExeFS patch: the RomFS is used");
CHECK(mm->kind == MOD_EXEFS && mm->problem == MOD_EXEFS_LATER && mm->pending == 1,
"an ExeFS patch for main the build lacks waits for the rebuild");
CHECK(jm->kind == MOD_CHEATS && jm->problem == MOD_OK && ends_with(jm->cheats, "J/cheats"),
"cheats-only mod");
CHECK(km->kind == MOD_ROMFS && km->problem == MOD_OK && ends_with(km->romfs, "K/romfslite"), "TKMM romfslite");
CHECK(lm->kind == (MOD_ROMFS | MOD_CHEATS) && lm->problem == MOD_OK, "RomFS + cheats, main.npdm is no code");
CHECK(u->kind == MOD_ROMFS && ends_with(u->romfs, "Ultra \xD0\x96/romfs"), "Unicode folder name");
CHECK(!mods_changed(), "nothing changed after the scan");
mods_move(1, -1);
CHECK(EQ(mods_at(0)->name, "A") && EQ(mods_at(1)->name, "B"), "move up");
CHECK(EQ(cfg_get("TOTK_MODS_ORDER"), "A|B|C|D|E|F|G|H|I|J|K|L|M|Ultra \xD0\x96"),
"order written without the gone name");
mods_move(0, -1);
CHECK(EQ(mods_at(0)->name, "A"), "move up at the top does nothing");
mods_move(N - 1, 1);
CHECK(EQ(mods_at(N - 1)->name, "Ultra \xD0\x96"), "move down at the bottom does nothing");
mods_set_enabled(2, 1);
const char *dis = cfg_get("TOTK_MODS_DISABLED");
CHECK(mods_at(2)->enabled && (!dis || !*dis), "switching C on empties mods_disabled");
mods_set_enabled(0, 0);
CHECK(EQ(cfg_get("TOTK_MODS_DISABLED"), "A"), "switching A off writes it");
CHECK(mods_changed(), "changes seen");
}
remove_tree(root);
printf("mods: %s\n", fails ? "FAIL" : "ok");
return fails ? 1 : 0;
}
+230
View File
@@ -0,0 +1,230 @@
// Horizon OS nfp:user IPC service implementation (nn::nfp::detail::IUserManager & IUser).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "amiibo.h"
#include "host.h"
#include "ipc.h"
#include "kernel.h"
#include "nfp.h"
// Simulated NFC device handle: ID 1
static const uint8_t g_device_handle[8] = { 1, 0, 0, 0, 0, 0, 0, 0 };
typedef struct {
uint32_t activate_event; // writable handle
uint32_t deactivate_event; // writable handle
uint32_t avail_event; // writable handle
} NfpUserState;
static void nfp_user_close(void *p) {
NfpUserState *st = p;
if (st) {
if (st->activate_event) kern_handle_close(st->activate_event);
if (st->deactivate_event) kern_handle_close(st->deactivate_event);
if (st->avail_event) kern_handle_close(st->avail_event);
free(st);
}
rt_log("nfp: IUser session closed");
}
// Handler for nn::nfp::detail::IUser
static void nfp_user_handler(IpcSession *s, const IpcRequest *rq, IpcResponse *rs) {
NfpUserState *st = (NfpUserState *)s->state;
switch (rq->cmd) {
case 0: { // InitializeNfp(u64 aruid, u64 m_pid, pid, buffer<unknown, 5>)
rt_log("nfp: Initialize");
rs->result = 0;
return;
}
case 1: { // FinalizeNfp()
rt_log("nfp: Finalize");
amiibo_stop_detection();
amiibo_unmount();
rs->result = 0;
return;
}
case 2: { // ListDevicesNfp() -> (s32 total_out, buffer<DeviceHandle, 0xa>)
int32_t count = amiibo_is_device_present() ? 1 : 0;
IPC_OUT(rs, count);
if (count > 0 && rq->nb > 0 && rq->b[0].size >= sizeof(g_device_handle)) {
void *dst = ipc_guest(rq->b[0].addr, sizeof(g_device_handle));
memcpy(dst, g_device_handle, sizeof(g_device_handle));
}
rs->result = 0;
return;
}
case 3: { // StartDetectionNfp(DeviceHandle)
amiibo_start_detection();
if (amiibo_has_tag() && st && st->activate_event) {
kern_event_signal(st->activate_event);
}
rs->result = 0;
return;
}
case 4: { // StopDetectionNfp(DeviceHandle)
amiibo_stop_detection();
rs->result = 0;
return;
}
case 5: { // MountNfp(DeviceHandle, u32 ModelType, u32 MountTarget)
if (!amiibo_has_tag()) {
rs->result = 0x8073u; // Device/Tag not found
return;
}
amiibo_mount();
rs->result = 0;
return;
}
case 6: { // UnmountNfp(DeviceHandle)
amiibo_unmount();
if (st && st->deactivate_event) {
kern_event_signal(st->deactivate_event);
}
rs->result = 0;
return;
}
case 7: { // OpenApplicationAreaNfp(DeviceHandle, u32 access_id)
if (!amiibo_is_mounted()) {
rs->result = 0x927Fu; // not mounted
return;
}
rs->result = 0;
return;
}
case 8: { // GetApplicationAreaNfp(DeviceHandle) -> (u32 size, buffer<data, 0x6>)
if (!amiibo_is_mounted()) {
rs->result = 0x927Fu;
return;
}
uint32_t area_size = 0xD8;
if (rq->nb > 0 && rq->b[0].size > 0) {
void *dst = ipc_guest(rq->b[0].addr, rq->b[0].size);
area_size = (uint32_t)amiibo_get_application_area(dst, (uint32_t)rq->b[0].size);
}
IPC_OUT(rs, area_size);
rs->result = 0;
return;
}
case 13: { // GetTagInfoNfp(DeviceHandle) -> buffer<TagInfo, 0x1a>
if (!amiibo_has_tag() && !amiibo_is_mounted()) {
rs->result = 0x8073u;
return;
}
if (rq->nb > 0 && rq->b[0].size >= 0x58) {
void *dst = ipc_guest(rq->b[0].addr, 0x58);
amiibo_get_tag_info(dst);
}
rs->result = 0;
return;
}
case 14: { // GetRegisterInfoNfp(DeviceHandle) -> buffer<RegisterInfo, 0x1a>
if (!amiibo_is_mounted()) {
rs->result = 0x927Fu;
return;
}
if (rq->nb > 0 && rq->b[0].size >= 0x100) {
void *dst = ipc_guest(rq->b[0].addr, 0x100);
amiibo_get_register_info(dst);
}
rs->result = 0;
return;
}
case 15: { // GetCommonInfoNfp(DeviceHandle) -> buffer<CommonInfo, 0x1a>
if (!amiibo_is_mounted()) {
rs->result = 0x927Fu;
return;
}
if (rq->nb > 0 && rq->b[0].size >= 0x40) {
void *dst = ipc_guest(rq->b[0].addr, 0x40);
amiibo_get_common_info(dst);
}
rs->result = 0;
return;
}
case 16: { // GetModelInfoNfp(DeviceHandle) -> buffer<ModelInfo, 0x1a>
if (!amiibo_is_mounted()) {
rs->result = 0x927Fu;
return;
}
if (rq->nb > 0 && rq->b[0].size >= 0x40) {
void *dst = ipc_guest(rq->b[0].addr, 0x40);
amiibo_get_model_info(dst);
}
rs->result = 0;
return;
}
case 17: { // GetActivateEventHandleNfp(DeviceHandle) -> handle<copy>
if (st && st->activate_event) {
rs->copy[rs->ncopy++] = kern_event_readable(st->activate_event);
}
rs->result = 0;
return;
}
case 18: { // GetDeactivateEventHandleNfp(DeviceHandle) -> handle<copy>
if (st && st->deactivate_event) {
rs->copy[rs->ncopy++] = kern_event_readable(st->deactivate_event);
}
rs->result = 0;
return;
}
case 19: { // GetStateNfp() -> u32 state
uint32_t state = 1; // Initialized
IPC_OUT(rs, state);
rs->result = 0;
return;
}
case 20: { // GetDeviceStateNfp(DeviceHandle) -> u32 device_state
uint32_t dev_state = (uint32_t)amiibo_get_device_state();
IPC_OUT(rs, dev_state);
rs->result = 0;
return;
}
case 21: { // GetNpadIdNfp(DeviceHandle) -> u32 npad_id
uint32_t npad_id = 0; // Handheld / Player 1
IPC_OUT(rs, npad_id);
rs->result = 0;
return;
}
case 22: { // GetApplicationAreaSizeNfp(DeviceHandle) -> u32 size
uint32_t size = 0xD8;
IPC_OUT(rs, size);
rs->result = 0;
return;
}
case 23: { // GetAvailabilityChangeEventHandleNfp() -> handle<copy>
if (st && st->avail_event) {
rs->copy[rs->ncopy++] = kern_event_readable(st->avail_event);
}
rs->result = 0;
return;
}
default:
ipc_unimplemented(s, rq);
}
}
// Handler for nn::nfp::detail::IUserManager (nfp:user)
void nfp_user_manager_handler(IpcSession *s, const IpcRequest *rq, IpcResponse *rs) {
switch (rq->cmd) {
case 0: { // CreateUserInterface() -> move handle to IUser
NfpUserState *st = calloc(1, sizeof(*st));
if (!st) rt_fatal("nfp: failed to allocate user state");
st->activate_event = kern_event_new();
st->deactivate_event = kern_event_new();
st->avail_event = kern_event_new();
// Signal availability immediately so game detects reader
kern_event_signal(st->avail_event);
uint32_t user_session = ipc_session_new("nfp:IUser", nfp_user_handler, st, nfp_user_close);
rs->move[rs->nmove++] = user_session;
rs->result = 0;
rt_log("nfp: created IUser session handle %#x", user_session);
return;
}
default:
ipc_unimplemented(s, rq);
}
}
+14
View File
@@ -0,0 +1,14 @@
// Nintendo Figurine Platform (nfp:user) Horizon OS IPC service emulation.
#pragma once
#include "ipc.h"
#ifdef __cplusplus
extern "C" {
#endif
// sm: handler for "nfp:user" (nn::nfp::detail::IUserManager)
void nfp_user_manager_handler(IpcSession *s, const IpcRequest *rq, IpcResponse *rs);
#ifdef __cplusplus
}
#endif
+104 -5
View File
@@ -75,15 +75,114 @@ static void put_hdr(uint8_t *p, uint32_t op, uint32_t size) {
memcpy(p, &h, sizeof h);
}
// 1.4.3 initializes and finalizes command buffers about 2000 times a second while a scene loads and several times a
// frame in play, and its two largest per-frame recordings take 1-2 MiB. Freeing the recording buffer at Finalize made
// every new recording grow again from 64 KiB through up to five reallocations and copies, the last ones fresh 1-2 MiB
// blocks the heap takes from the system: new commit and zero-filled pages twice a frame. Those growths were most of the
// process's new commit requests, so when the system ran short for a moment (a Depths load at render scale 200 on 16 GB)
// a 1 MiB growth was the allocation that failed. Finalized buffers therefore wait in a small pool for the next
// recording, and a failed allocation waits for memory instead of ending the game (realloc_wait).
#define POOL_SLOTS 16
#define POOL_MAX_BYTES ((size_t)4 << 20) // a larger buffer (a recording that inlined a big one) goes back to the heap
static PlatMutex pool_lock = PLAT_MUTEX_INIT;
static struct { uint8_t *p; size_t size; } pool[POOL_SLOTS];
static uint32_t npool;
// The largest pooled buffer and its size, or NULL: the largest, so the big per-frame recordings stop growing once the
// pool holds enough buffers of their size.
static uint8_t *pool_take(size_t *size) {
uint8_t *p = NULL;
plat_mutex_lock(&pool_lock);
if (npool) {
uint32_t best = 0;
for (uint32_t i = 1; i < npool; i++)
if (pool[i].size > pool[best].size) best = i;
p = pool[best].p;
*size = pool[best].size;
pool[best] = pool[--npool];
}
plat_mutex_unlock(&pool_lock);
return p;
}
// Keeps a finalized buffer when the pool has room or holds a smaller one (which is freed instead).
static void pool_put(uint8_t *p, size_t size) {
if (!p) return;
if (size <= POOL_MAX_BYTES) {
plat_mutex_lock(&pool_lock);
if (npool < POOL_SLOTS) {
pool[npool].p = p;
pool[npool++].size = size;
p = NULL;
} else {
uint32_t small = 0;
for (uint32_t i = 1; i < npool; i++)
if (pool[i].size < pool[small].size) small = i;
if (pool[small].size < size) {
uint8_t *drop = pool[small].p;
pool[small].p = p;
pool[small].size = size;
p = drop;
}
}
plat_mutex_unlock(&pool_lock);
}
free(p);
}
static void pool_drain(void) {
plat_mutex_lock(&pool_lock);
while (npool) free(pool[--npool].p);
plat_mutex_unlock(&pool_lock);
}
// realloc that waits out a short commit shortage: Windows refuses commit beyond the current limit while it grows a
// system-managed page file, so the same request succeeds a moment later, and a stall of some frames is better than
// ending the game. Frees the pooled buffers first. NULL only after about 30 s without memory; the caller ends the game.
// Never called with a lock held.
static void *realloc_wait(void *old, size_t n, const char *what) {
void *p = realloc(old, n);
if (p) return p;
pool_drain();
static uint32_t reports;
int report = __atomic_fetch_add(&reports, 1, __ATOMIC_RELAXED) < 8;
if (report) {
double proc, used, limit;
plat_commit_info(&proc, &used, &limit);
rt_log("nvn: %s of %zu bytes failed (memory commit: this process %.0f MB, the system %.0f of %.0f MB); waiting "
"for memory", what, n, proc, used, limit);
}
uint64_t t0 = plat_now_ms();
while (plat_now_ms() - t0 < 30000) {
plat_sleep_ms(10);
if ((p = realloc(old, n))) {
if (report)
rt_log("nvn: %s of %zu bytes succeeded after %llu ms", what, n,
(unsigned long long)(plat_now_ms() - t0));
return p;
}
}
return NULL;
}
static void cmd_reserve(cmd_t *o, size_t need) {
if (o->seg && o->cur + need + OP_RESERVE <= o->end) return;
if (!o->seg) { // the first record since Initialize: a pooled buffer when one waits
size_t size = 0;
uint8_t *p = pool_take(&size);
if (p) {
o->seg = o->cur = p;
o->end = p + size;
if (need + OP_RESERVE <= size) return;
}
}
size_t used = o->seg ? (size_t)(o->cur - o->seg) : 0;
size_t cap = o->seg ? (size_t)(o->end - o->seg) : 0;
if (!cap) cap = 64 << 10;
while (used + need + OP_RESERVE > cap) cap *= 2;
uint8_t *b = realloc(o->seg, cap);
// A block this size fails only without commit (the fatal report states it) or when seg is no block of ours: a
// command buffer object the game overwrote or copied shows a wrong magic or more used than its old size.
uint8_t *b = realloc_wait(o->seg, cap, "command recording buffer");
// Still failing after the wait: the system has no commit left (the fatal report states it), or seg is no block of
// ours: a command buffer object the game overwrote or copied shows a wrong magic or more used than its old size.
if (!b)
rt_fatal("nvn: command recording buffer of %zu bytes (command buffer %p, magic %#x, buffer %p of %zu bytes, %zu "
"used, %zu asked)", cap, (void *)o, o->magic, (void *)o->seg, o->seg ? (size_t)(o->end - o->seg) : 0,
@@ -235,7 +334,7 @@ static uint64_t copy_touch(uint64_t handle, uint64_t now, const char *what) {
// into one host block of its exact size. One allocation and one copy: growing the copy record by record cost the
// game's main thread about 1 ms a frame in reallocations and small copies (1.4.3, field).
static uint8_t *flatten_recording(const uint8_t *p, size_t n) {
uint8_t *out = malloc(sizeof(copy_prefix) + n);
uint8_t *out = realloc_wait(NULL, sizeof(copy_prefix) + n, "command copy");
if (!out) rt_fatal("nvn: command copy allocation");
memcpy(out + sizeof(copy_prefix), p, n);
for (size_t at = 0;;) { // the records stay checked: a corrupt one stops here, not in the replay
@@ -334,7 +433,7 @@ NVN_API(nvnCommandBufferInitialize) {
// void nvnCommandBufferFinalize(NVNcommandBuffer *cmd): handles outlive their recorder
NVN_API(nvnCommandBufferFinalize) {
cmd_t *o = cmd_of(c);
free(o->seg);
pool_put(o->seg, (size_t)(o->end - o->seg));
o->seg = o->cur = o->end = NULL;
o->magic = 0;
cb_set_disabled(o, CB_NO_COMMAND | CB_NO_CONTROL, 0);
+8 -3
View File
@@ -197,6 +197,7 @@ NVN_API(nvnTextureInitialize) {
o->magic = NVN_TEX_MAGIC;
o->d = s->d;
o->pool = s->pool;
o->pool_flags = s->pool ? (uint16_t)s->pool->flags : 0;
o->off = s->off;
o->has_layout = s->has_layout;
memcpy(o->layout, s->layout, 8);
@@ -323,8 +324,11 @@ NVN_API(nvnTextureReadTexelsStrided) { read_texels(c, 1); }
NVN_API(nvnTextureWriteTexels) { write_texels(c, 0); }
NVN_API(nvnTextureWriteTexelsStrided) { write_texels(c, 1); }
// void nvnTexture{Flush,Invalidate}Texels(const NVNtexture *t, const NVNtextureView *v, const NVNcopyRegion *r): texel
// access is coherent
NVN_API(nvnTextureFlushTexels) { (void)c; }
// access is coherent; flush marks the storage as written for re-upload
NVN_API(nvnTextureFlushTexels) {
const tex_t *t = arg_p(c, 0);
if (t && t->mem && !nvn_gpu_only((uintptr_t)t->mem)) nvn_guest_written((uintptr_t)t->mem, t->L.size);
}
NVN_API(nvnTextureInvalidateTexels) { (void)c; }
// ---------- Samplers
@@ -633,7 +637,7 @@ NVN_API(nvnWindowSetCrop) {
// ---------- Present pacing
// The vsync thread ticks at a fixed 60 Hz whatever the monitor does, so one game frame lasts `interval` ticks. With
// the real-time frame step (frame_rate.c) game speed does not depend on the interval, so a frame is shown when it is
// ready, at most at the frame limit (TOTK_FPS_LIMIT: 30 to 360 per second or the monitor's rate): holding it to the
// ready, at most at the frame limit (TOTK_FPS_LIMIT: 30 to 240 per second or the monitor's rate): holding it to the
// 2nd or 3rd tick would only add latency and 50 ms frames.
#define VSYNC_HZ 60ull
static uint64_t present_period(const win_t *o) {
@@ -695,6 +699,7 @@ NVN_API(nvnQueuePresentTexture) {
win_t *o = arg_p(c, 1);
int idx = (int)arg_x(c, 2);
movie_tick(c); // ov_movie.c: hand over decoded movie frames that are due; needs the core, so before the wait
res_present(c); // resolution.c: a DLSS mode change sets the game's render size again, between frames
NVN_BLOCKING();
if (o->magic != NVN_WIN_MAGIC || idx < 0 || idx >= o->ntex || idx >= 4 || !o->tex[idx])
rt_fatal("nvn: QueuePresentTexture of image %d on window %p", idx, (void *)o);
+3
View File
@@ -48,6 +48,9 @@ typedef struct {
} tex_builder_t; FITS(tex_builder_t, NVNtextureBuilder);
typedef struct {
uint32_t magic; nvn_texdesc d; uint8_t has_layout, layout[8];
uint16_t pool_flags; // the pool's flags at Initialize (in the padding): a game may finalize and free
// the pool object while the back end still looks the texture up, and the
// driver keeps no pointer to it either
nvn_texlayout L; uint8_t *mem; pool_t *pool; int64_t off;
uint64_t serial; // Initialization serial: the back end uses it to find its texture in the host table (the game may copy the object by value, so object pointers cannot be stored)
} tex_t; FITS(tex_t, NVNtexture);
+108 -21
View File
@@ -12,6 +12,7 @@
#include <string.h>
#include <time.h>
#include "amiibo.h"
#include "cfg.h"
#include "fs.h"
#include "gfx.h"
@@ -25,6 +26,7 @@
#define CHILD_ENV "TOTK_PROBE_SERVICES_CHILD"
#define TRY_WAIT_SYSTEM_EVENT "_ZN2nn2os18TryWaitSystemEventEPNS0_15SystemEventTypeE"
#define DESTROY_SYSTEM_EVENT "_ZN2nn2os18DestroySystemEventEPNS0_15SystemEventTypeE"
typedef struct { const char *key, *name; int fatal; uint64_t addr; int bound, calls; } Ov;
static Ov ovs[] = {
@@ -348,6 +350,13 @@ static int event_works(uint64_t ev, int autoclear) {
return !before && after && again == !autoclear;
}
// A manual-clear system event an override signalled when binding it: set, and still set on a second wait.
static int event_set(uint64_t ev) {
static uint64_t try_wait;
if (!try_wait && !(try_wait = ldr_symbol(TRY_WAIT_SYSTEM_EVENT))) rt_fatal("probe-services: no %s", TRY_WAIT_SYSTEM_EVENT);
return (uint8_t)rt_call(gc, try_wait, 1, ev) && (uint8_t)rt_call(gc, try_wait, 1, ev);
}
static void probe_applet(void) {
uint8_t *report = guest_alloc(0x100);
uint64_t uid[2] = {1, 2};
@@ -357,21 +366,65 @@ static void probe_applet(void) {
"AddInternetConnectionStatus");
CHECK(CALL("nfp.Initialize", 0) == 0 && (uint32_t)CALL("nfp.GetState", 0) == 1, "nfp initialize");
uint8_t handles[64];
int32_t count = 7;
CHECK((uint32_t)CALL("nfp.ListDevices", U(handles), U(&count), 4) == 0x8073 && count == 0, "nfp ListDevices");
int32_t count = 0;
CHECK((uint32_t)CALL("nfp.ListDevices", U(handles), U(&count), 4) == 0 && count == 1, "nfp ListDevices");
uint64_t ev = U(guest_alloc(0x100));
CHECK(CALL("nfp.AttachAvailabilityChangeEvent", ev) == 0, "AttachAvailabilityChangeEvent");
int nfp_event = event_works(ev, 0);
CHECK(nfp_event, "the nfp availability event does not work as a manual-clear system event");
// The emulated reader is there from the start (amiibo.c), so the availability event is set when it is attached.
int nfp_event = event_set(ev);
CHECK(nfp_event, "the nfp availability event is not set for the emulated reader, or clears itself");
CHECK((uint32_t)CALL("nfp.GetDeviceState", U(handles)) == 0, "nfp device state");
static const char *const none[] = {"nfp.Mount", "nfp.GetNpadId", "nfp.AttachActivateEvent", "nfp.AttachDeactivateEvent",
"nfp.StartDetection", "nfp.StopDetection", "nfp.GetTagInfo", "nfp.GetModelInfo"};
static const char *const none[] = {"nfp.Mount", "nfp.GetTagInfo", "nfp.GetModelInfo"};
uint8_t out[0x100];
for (size_t i = 0; i < sizeof none / sizeof *none; i++) {
int first_is_handle = !strcmp(none[i], "nfp.Mount") || strstr(none[i], "Detection");
int first_is_handle = !strcmp(none[i], "nfp.Mount");
uint64_t r = first_is_handle ? CALL(none[i], U(handles), 0, 0) : CALL(none[i], U(out), U(handles));
CHECK((uint32_t)r == 0x8073, "%s: %#x, not device-not-found", none[i], (uint32_t)r);
}
CHECK((uint32_t)CALL("nfp.GetNpadId", U(out), U(handles)) == 0, "nfp GetNpadId");
uint64_t activate = U(guest_alloc(0x100)), deactivate = U(guest_alloc(0x100));
CHECK(CALL("nfp.AttachActivateEvent", activate, U(handles)) == 0, "nfp AttachActivateEvent");
CHECK(CALL("nfp.AttachDeactivateEvent", deactivate, U(handles)) == 0, "nfp AttachDeactivateEvent");
CHECK(event_works(activate, 0), "the nfp activate event is set without an amiibo on the reader");
CHECK((uint32_t)CALL("nfp.StartDetection", U(handles)) == 0, "nfp StartDetection");
CHECK((uint32_t)CALL("nfp.StopDetection", U(handles)) == 0, "nfp StopDetection");
// The game attaches again before each detection: DestroySystemEvent on the attached event, then Attach* on the
// same SystemEventType. Both events must work again afterwards.
static uint64_t destroy;
if (!destroy && !(destroy = ldr_symbol(DESTROY_SYSTEM_EVENT))) rt_fatal("probe-services: no %s", DESTROY_SYSTEM_EVENT);
rt_call(gc, destroy, 1, activate);
rt_call(gc, destroy, 1, deactivate);
CHECK(CALL("nfp.AttachActivateEvent", activate, U(handles)) == 0, "nfp AttachActivateEvent again");
CHECK(CALL("nfp.AttachDeactivateEvent", deactivate, U(handles)) == 0, "nfp AttachDeactivateEvent again");
int reattached = event_works(activate, 0) && event_works(deactivate, 0);
CHECK(reattached, "the nfp events do not work after DestroySystemEvent and a second Attach");
CHECK((uint32_t)CALL("nfp.StartDetection", U(handles)) == 0, "nfp StartDetection again");
// An amiibo's NTAG215 header: UID with its two check bytes, static lock 0F E0, capability container F1 10 FF EE.
// The loader takes it and refuses the same file with a plain NDEF container (E1).
static const uint8_t head[16] = {0x04, 0x11, 0x22, 0x88 ^ 0x04 ^ 0x11 ^ 0x22, 0x33, 0x44, 0x55, 0x66,
0x33 ^ 0x44 ^ 0x55 ^ 0x66, 0x48, 0x0F, 0xE0, 0xF1, 0x10, 0xFF, 0xEE};
uint8_t dump[AMIIBO_DUMP_SIZE] = {0};
memcpy(dump, head, sizeof head);
// Link (Archer): character 0x0100, variant 0, figure type 0, model number 0x0353, series 9, format 02
static const uint8_t id[8] = {0x01, 0x00, 0x00, 0x00, 0x03, 0x53, 0x09, 0x02};
memcpy(dump + 0x54, id, sizeof id);
const char *dump_path = "probe-amiibo.bin";
int amiibo_ok = plat_file_write(dump_path, dump, sizeof dump) && amiibo_load_file(dump_path);
// TagInfo carries the 7-byte UID without its check byte; ModelInfo has the series at 3, the model number
// little-endian at 4 and the figure type at 6
uint8_t ti[0x58], mi[0x40];
amiibo_get_tag_info(ti);
amiibo_get_model_info(mi);
static const uint8_t want_uid[7] = {0x04, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66};
static const uint8_t want_model[7] = {0x01, 0x00, 0x00, 0x09, 0x53, 0x03, 0x00};
CHECK(amiibo_ok && !memcmp(ti, want_uid, 7) && ti[0x0A] == 7, "amiibo TagInfo UID %02x %02x %02x %02x %02x %02x %02x",
ti[0], ti[1], ti[2], ti[3], ti[4], ti[5], ti[6]);
CHECK(amiibo_ok && !memcmp(mi, want_model, 7), "amiibo ModelInfo %02x %02x %02x %02x %02x %02x %02x", mi[0], mi[1],
mi[2], mi[3], mi[4], mi[5], mi[6]);
dump[0x0C] = 0xE1;
amiibo_ok = amiibo_ok && plat_file_write(dump_path, dump, sizeof dump) && !amiibo_load_file(dump_path);
plat_fs_unlink(dump_path);
CHECK(amiibo_ok, "the amiibo loader refuses a dump with the amiibo capability container, or takes a plain NDEF one");
CHECK(CALL("nfp.Finalize", 0) == 0 && (uint32_t)CALL("nfp.GetState", 0) == 0, "nfp finalize");
CALL("err.ShowError", 0x2a8);
CALL("nndiagStartup", 0);
@@ -380,8 +433,9 @@ static void probe_applet(void) {
CALL("err.InitializeContextWriterApi", 0);
CALL("pctl.Initialize", 0);
CALL("diag.InitializeApplicationAbortObserver", 0);
printf("applet/prepo/nfp/err: launch parameter none, volume balance, play reports local, no NFC device, "
"availability event (bound through the SDK's CreateSystemEvent) %s\n", nfp_event ? "ok" : "FAILED");
printf("applet/prepo/nfp/err: launch parameter none, volume balance, play reports local, an NFC reader without "
"an amiibo, availability event (bound through the SDK's CreateSystemEvent) %s, activate and deactivate events "
"destroyed and attached again %s\n", nfp_event ? "ok" : "FAILED", reattached ? "ok" : "FAILED");
}
static void probe_account(void) {
@@ -811,17 +865,23 @@ static void probe_fonts(void) {
(unsigned long long)size, path);
}
// The host catalog (ui_text.c): every menu id has its own English and Russian text, the software keyboard keeps its
// game-language rows, and menu_text follows TOTK_MENU_LANG.
// The host catalog (ui_text.c): every menu id has its own English, Russian, Brazilian Portuguese and Simplified
// Chinese text, the software keyboard keeps its game-language rows, and menu_text follows TOTK_MENU_LANG.
static void probe_menu_text(void) {
static const char *const langs[] = {"en", "ja", "fr", "de", "it", "es", "nl", "pt", "ru", "zh-Hans", "zh-Hant", "ko"};
static const char *const langs[] = {"en", "ja", "fr", "de", "it", "es", "nl", "pt", "ru", "zh-Hans", "zh-Hant", "ko",
"pt-BR"};
for (int id = UI_MENU_FIRST; id <= UI_MENU_LAST_ID; id++) {
CHECK(ui_text_defined("en", (UiTextId)id) && ui_text_defined("ru", (UiTextId)id), "menu text id %d lacks en or ru", id);
CHECK(*ui_text_in("en", (UiTextId)id) && *ui_text_in("ru", (UiTextId)id), "menu text id %d is empty", id);
CHECK(ui_text_defined("en", (UiTextId)id) && ui_text_defined("ru", (UiTextId)id) &&
ui_text_defined("pt-BR", (UiTextId)id), "menu text id %d lacks en, ru or pt-BR", id);
CHECK(*ui_text_in("en", (UiTextId)id) && *ui_text_in("ru", (UiTextId)id) && *ui_text_in("pt-BR", (UiTextId)id),
"menu text id %d is empty", id);
// the description pane keeps the whole text and a note after it (option_rows.cpp desc_set)
CHECK(strlen(ui_text_in("en", (UiTextId)id)) + 256 < UI_DESC_BYTES &&
strlen(ui_text_in("ru", (UiTextId)id)) + 256 < UI_DESC_BYTES, "menu text id %d is too long for the "
"description pane", id);
strlen(ui_text_in("ru", (UiTextId)id)) + 256 < UI_DESC_BYTES &&
strlen(ui_text_in("pt-BR", (UiTextId)id)) + 256 < UI_DESC_BYTES &&
strlen(ui_text_in("zh-Hans", (UiTextId)id)) + 256 < UI_DESC_BYTES,
"menu text id %d is too long for the description pane", id);
CHECK(ui_text_defined("zh-Hans", (UiTextId)id), "menu text id %d lacks Simplified Chinese", id);
}
CHECK(!ui_text_defined("en", UI_TEXT_COUNT) && !*ui_text_in("ru", UI_TEXT_COUNT), "an id past the catalog gives text");
// other languages fall back to English for the menu, and keep their own keyboard texts
@@ -829,22 +889,49 @@ static void probe_menu_text(void) {
CHECK(!strcmp(ui_text_in("ru", UI_SWKBD_OK), "ОК") && !strcmp(ui_text_in("de", UI_SWKBD_CANCEL), "Abbrechen") &&
!strcmp(ui_text_in("en", UI_SWKBD_OK), "OK"), "keyboard texts changed");
// language names: the same string in every row
for (int id = UI_MENU_LANGNAME_EN; id <= UI_MENU_LANGNAME_KO; id++)
for (int id = UI_MENU_LANGNAME_EN; id <= UI_MENU_LANGNAME_ES_419; id++)
for (size_t i = 1; i < sizeof langs / sizeof *langs; i++)
CHECK(!strcmp(ui_text_in(langs[i], (UiTextId)id), ui_text_in("en", (UiTextId)id)), "language name %d differs in %s", id, langs[i]);
CHECK(!strcmp(ui_text_in("en", UI_MENU_LANGNAME_RU), "Русский"), "Russian is not shown as Russian");
// game language list: pt-BR only where the build ships USpt; the Switch variants are entries of their own
{
UiGameLang gl[16];
int n121 = ui_text_game_langs(121, gl, 16), has[16] = {0};
for (int i = 0; i < n121; i++) CHECK(strcmp(gl[i].code, "pt-BR"), "1.2.1 game language list offers pt-BR");
int n143 = ui_text_game_langs(143, gl, 16), pt = 0;
for (int i = 0; i < n143; i++) {
pt |= !strcmp(gl[i].code, "pt-BR");
for (int j = 0; j < i; j++) CHECK(strcmp(gl[i].code, gl[j].code), "duplicate game language %s", gl[i].code);
}
CHECK(pt && n143 == n121 + 1, "1.4.3 game language list lacks pt-BR");
static const char *const want[] = {"en-GB", "fr-CA", "es-419"};
for (int w = 0; w < 3; w++)
for (int i = 0; i < n143; i++) has[w] |= !strcmp(gl[i].code, want[w]);
CHECK(has[0] && has[1] && has[2], "game language list lacks en-GB, fr-CA or es-419");
}
// the overlay formats keep their conversions
CHECK(strstr(ui_text_in("ru", UI_MENU_OV_GAME_PCT), "%.0f%%") && strstr(ui_text_in("ru", UI_MENU_OV_MAX_MS), "%.1f"),
CHECK(strstr(ui_text_in("ru", UI_MENU_OV_GAME_PCT), "%.0f%%") && strstr(ui_text_in("ru", UI_MENU_OV_MAX_MS), "%.1f") &&
strstr(ui_text_in("ru", UI_MENU_OV_LOW1), "%.0f") && strstr(ui_text_in("ru", UI_MENU_OV_LOW01), "%.0f"),
"overlay format lost its conversion");
CHECK(strstr(ui_text_in("pt-BR", UI_MENU_OV_GAME_PCT), "%.0f%%") &&
strstr(ui_text_in("pt-BR", UI_MENU_OV_MAX_MS), "%.1f") &&
strstr(ui_text_in("pt-BR", UI_MENU_OV_LOW1), "%.0f") && strstr(ui_text_in("zh-Hans", UI_MENU_OV_LOW01), "%.0f"), "pt-BR overlay format lost its conversion");
// a Brazilian game language gets the Brazilian keyboard row, Portugal's Portuguese keeps its own
CHECK(!strcmp(ui_text_lang("pt-BR"), "pt-BR") && !strcmp(ui_text_lang("pt"), "pt") &&
strcmp(ui_text_in("pt-BR", UI_SWKBD_PROMPT), ui_text_in("pt", UI_SWKBD_PROMPT)), "pt-BR keyboard row not used");
// menu_text follows the setting live
cfg_set("TOTK_MENU_LANG", "ru");
CHECK(menu_text(UI_MENU_CONTINUE) == ui_text_in("ru", UI_MENU_CONTINUE), "menu_text ignores MENU_LANG=ru");
cfg_set("TOTK_MENU_LANG", "pt-BR");
CHECK(menu_text(UI_MENU_CONTINUE) == ui_text_in("pt-BR", UI_MENU_CONTINUE), "menu_text ignores MENU_LANG=pt-BR");
cfg_set("TOTK_MENU_LANG", "en");
CHECK(menu_text(UI_MENU_CONTINUE) == ui_text_in("en", UI_MENU_CONTINUE), "menu_text did not follow MENU_LANG=en");
cfg_set("TOTK_MENU_LANG", "zh-Hans");
CHECK(menu_text(UI_MENU_TITLE) == ui_text_in("zh-Hans", UI_MENU_TITLE), "menu_text ignores MENU_LANG=zh-Hans");
cfg_set("TOTK_MENU_LANG", "");
const char *sys = plat_ui_language();
int ru = !strncmp(sys, "ru", 2);
CHECK(menu_text(UI_MENU_CONTINUE) == ui_text_in(ru ? "ru" : "en", UI_MENU_CONTINUE), "menu_text auto ignores the system language");
const char *sys_lang = ui_text_lang(plat_ui_language());
const char *auto_lang = ui_text_defined(sys_lang, UI_MENU_TITLE) ? sys_lang : "en";
CHECK(menu_text(UI_MENU_CONTINUE) == ui_text_in(auto_lang, UI_MENU_CONTINUE), "menu_text auto ignores the system language");
}
static void probe_main(Cpu *c) {
+112 -13
View File
@@ -19,6 +19,7 @@
#include <string.h>
#include <time.h>
#include "amiibo.h"
#include "cfg.h"
#include "fs.h"
#include "host.h"
@@ -266,26 +267,124 @@ static void ov_report_save(Cpu *c) { // Result PlayReport::Save() and Save(con
}
static void ov_result_ok(Cpu *c) { ret_x(c, 0); } // RequestImmediateTransmission, AddInternetConnectionStatus
// nn::nfp: no NFC reader
// nn::nfp: NFC reader & amiibo support
static volatile int32_t nfp_state;
static void ov_nfp_initialize(Cpu *c) { plat_xchg32(&nfp_state, 1); ret_x(c, 0); }
static void ov_nfp_finalize(Cpu *c) { plat_xchg32(&nfp_state, 0); ret_x(c, 0); }
static void ov_nfp_finalize(Cpu *c) {
plat_xchg32(&nfp_state, 0);
amiibo_stop_detection();
amiibo_unmount();
ret_x(c, 0);
}
static void ov_nfp_state(Cpu *c) { ret_x(c, (uint64_t)nfp_state); }
// Result ListDevices(DeviceHandle *out, int *count, int max)
static void ov_nfp_list(Cpu *c) {
void *out = arg_p(c, 0);
int32_t *count = arg_p(c, 1);
if (count) *count = 0;
ret_x(c, NFP_R_DEVICE_NOT_FOUND);
int32_t max = (int32_t)arg_x(c, 2);
if (!amiibo_is_device_present()) {
if (count) *count = 0;
ret_x(c, NFP_R_DEVICE_NOT_FOUND);
return;
}
if (out && max > 0) {
static const uint8_t dev[8] = { 1, 0, 0, 0, 0, 0, 0, 0 };
memcpy(out, dev, sizeof dev);
}
if (count) *count = 1;
ret_x(c, 0);
}
// Result AttachAvailabilityChangeEvent(os::SystemEventType *event)
static void ov_nfp_availability(Cpu *c) {
uint64_t ev = arg_x(c, 0);
if (!ev) rt_fatal("nn::nfp::AttachAvailabilityChangeEvent: null event");
kern_bind_system_event(c, ev, 0);
kern_signal_system_event(ev);
ret_x(c, 0);
}
// DeviceState GetDeviceState(const DeviceHandle &)
static void ov_nfp_device_state(Cpu *c) {
(void)c;
ret_x(c, (uint64_t)amiibo_get_device_state());
}
// Result Mount(const DeviceHandle &, ModelType, MountTarget)
static void ov_nfp_mount(Cpu *c) {
(void)c;
if (!amiibo_has_tag()) {
ret_x(c, NFP_R_DEVICE_NOT_FOUND);
return;
}
amiibo_mount();
ret_x(c, 0);
}
// Result GetNpadId(u32 *npad_id, const DeviceHandle &)
static void ov_nfp_get_npad_id(Cpu *c) {
uint32_t *npad = arg_p(c, 0);
if (npad) *npad = 0; // Handheld / Player 1
ret_x(c, 0);
}
// Result AttachActivateEvent(os::SystemEventType *event, const DeviceHandle &)
static void ov_nfp_attach_activate(Cpu *c) {
uint64_t ev = arg_x(c, 0);
if (ev) {
kern_bind_system_event(c, ev, 0);
if (amiibo_has_tag()) kern_signal_system_event(ev);
}
ret_x(c, 0);
}
// Result AttachDeactivateEvent(os::SystemEventType *event, const DeviceHandle &)
static void ov_nfp_attach_deactivate(Cpu *c) {
uint64_t ev = arg_x(c, 0);
if (ev) {
kern_bind_system_event(c, ev, 0);
}
ret_x(c, 0);
}
// Result StartDetection(const DeviceHandle &)
static void ov_nfp_start_detection(Cpu *c) {
(void)c;
amiibo_start_detection();
ret_x(c, 0);
}
// Result StopDetection(const DeviceHandle &)
static void ov_nfp_stop_detection(Cpu *c) {
(void)c;
amiibo_stop_detection();
ret_x(c, 0);
}
// Result GetTagInfo(TagInfo *out, const DeviceHandle &)
static void ov_nfp_get_tag_info(Cpu *c) {
void *out = arg_p(c, 0);
if (!amiibo_has_tag() && !amiibo_is_mounted()) {
ret_x(c, NFP_R_DEVICE_NOT_FOUND);
return;
}
if (out) amiibo_get_tag_info(out);
ret_x(c, 0);
}
// Result GetModelInfo(ModelInfo *out, const DeviceHandle &)
static void ov_nfp_get_model_info(Cpu *c) {
void *out = arg_p(c, 0);
if (!amiibo_is_mounted() && !amiibo_has_tag()) {
ret_x(c, NFP_R_DEVICE_NOT_FOUND);
return;
}
if (out) amiibo_get_model_info(out);
ret_x(c, 0);
}
static void ov_nfp_no_device(Cpu *c) { ret_x(c, NFP_R_DEVICE_NOT_FOUND); }
static void ov_nfp_device_state(Cpu *c) { ret_x(c, 0); } // DeviceState GetDeviceState(const DeviceHandle &): none
// void err::ShowError(Result): the game's error dialog, logged
static void ov_show_error(Cpu *c) {
@@ -795,14 +894,14 @@ HOST_OVERRIDE("_ZN2nn3nfp8GetStateEv", ov_nfp_state);
HOST_OVERRIDE("_ZN2nn3nfp11ListDevicesEPNS0_12DeviceHandleEPii", ov_nfp_list);
HOST_OVERRIDE("_ZN2nn3nfp29AttachAvailabilityChangeEventEPNS_2os15SystemEventTypeE", ov_nfp_availability);
HOST_OVERRIDE("_ZN2nn3nfp14GetDeviceStateERKNS0_12DeviceHandleE", ov_nfp_device_state);
HOST_OVERRIDE("_ZN2nn3nfp5MountERKNS0_12DeviceHandleENS0_9ModelTypeENS0_11MountTargetE", ov_nfp_no_device);
HOST_OVERRIDE("_ZN2nn3nfp9GetNpadIdEPjRKNS0_12DeviceHandleE", ov_nfp_no_device);
HOST_OVERRIDE("_ZN2nn3nfp19AttachActivateEventEPNS_2os15SystemEventTypeERKNS0_12DeviceHandleE", ov_nfp_no_device);
HOST_OVERRIDE("_ZN2nn3nfp21AttachDeactivateEventEPNS_2os15SystemEventTypeERKNS0_12DeviceHandleE", ov_nfp_no_device);
HOST_OVERRIDE("_ZN2nn3nfp14StartDetectionERKNS0_12DeviceHandleE", ov_nfp_no_device);
HOST_OVERRIDE("_ZN2nn3nfp13StopDetectionERKNS0_12DeviceHandleE", ov_nfp_no_device);
HOST_OVERRIDE("_ZN2nn3nfp10GetTagInfoEPNS0_7TagInfoERKNS0_12DeviceHandleE", ov_nfp_no_device);
HOST_OVERRIDE("_ZN2nn3nfp12GetModelInfoEPNS0_9ModelInfoERKNS0_12DeviceHandleE", ov_nfp_no_device);
HOST_OVERRIDE("_ZN2nn3nfp5MountERKNS0_12DeviceHandleENS0_9ModelTypeENS0_11MountTargetE", ov_nfp_mount);
HOST_OVERRIDE("_ZN2nn3nfp9GetNpadIdEPjRKNS0_12DeviceHandleE", ov_nfp_get_npad_id);
HOST_OVERRIDE("_ZN2nn3nfp19AttachActivateEventEPNS_2os15SystemEventTypeERKNS0_12DeviceHandleE", ov_nfp_attach_activate);
HOST_OVERRIDE("_ZN2nn3nfp21AttachDeactivateEventEPNS_2os15SystemEventTypeERKNS0_12DeviceHandleE", ov_nfp_attach_deactivate);
HOST_OVERRIDE("_ZN2nn3nfp14StartDetectionERKNS0_12DeviceHandleE", ov_nfp_start_detection);
HOST_OVERRIDE("_ZN2nn3nfp13StopDetectionERKNS0_12DeviceHandleE", ov_nfp_stop_detection);
HOST_OVERRIDE("_ZN2nn3nfp10GetTagInfoEPNS0_7TagInfoERKNS0_12DeviceHandleE", ov_nfp_get_tag_info);
HOST_OVERRIDE("_ZN2nn3nfp12GetModelInfoEPNS0_9ModelInfoERKNS0_12DeviceHandleE", ov_nfp_get_model_info);
HOST_OVERRIDE("_ZN2nn3err9ShowErrorENS_6ResultE", ov_show_error);
HOST_OVERRIDE("nndiagStartup", ov_diag_startup);
+8
View File
@@ -183,6 +183,9 @@ static uint64_t ft_frame(uint64_t frame, uint64_t now, uint64_t d) {
// process memory, and which side holds the frame back. pace: the frame waited for pacing (vsync, the frame limiter) at
// least 15% of the window; gpu: the GPU was busy for 80% of the frame interval or more (without timestamps: threads
// waited for fences for half the interval or more); cpu otherwise.
// With calibrated timestamps a third line splits the GPU's idle time between timed parts: the part was submitted only
// after the previous one had ended (the GPU waited for the CPU's replay or the game), or it was already queued (untimed
// work such as uploads and presents ran there, or a wait held it).
static void perf_gpu_line(uint64_t frame, double interval_ms, double pace_share, uint64_t n) {
PerfGpu g;
memset(&g, 0, sizeof g);
@@ -205,6 +208,11 @@ static void perf_gpu_line(uint64_t frame, double interval_ms, double pace_share,
rt_log("perf: frame %llu: %s; fence wait per frame: render thread %.2f ms, other threads %.2f ms; %s; ram working set "
"%.0f MiB, private %.0f MiB; bound: %s",
(unsigned long long)frame, gs, rw, ow, vs, ws, priv, bound);
if (g.have_gpu && g.have_idle)
rt_log("perf: frame %llu: gpu idle per frame %.2f ms between timed parts: %.2f ms waiting for the next submission, "
"%.2f ms with it queued (untimed work or waits); %.1f gaps over 0.5 ms, longest %.2f ms; submit to start avg %.2f ms",
(unsigned long long)frame, g.idle_ns / 1e6 / n, g.starved_ns / 1e6 / n, (g.idle_ns - g.starved_ns) / 1e6 / n,
(double)g.idle_gaps / n, g.max_gap_ns / 1e6, g.gpu_parts ? g.queued_ns / 1e6 / g.gpu_parts : 0.0);
}
int rt_ab(void) {
+36
View File
@@ -32,6 +32,14 @@ static float g_ring[PERF_HISTORY];
static uint64_t g_ring_at[PERF_HISTORY]; // when each frame ended
static int g_ring_n, g_ring_pos;
// The lows: a histogram of the frame times (perf.c's 0.25 ms bins) over the last LOW_SLICES seconds, kept as one slice
// per second so the oldest second drops out whole. Per frame: one increment. The percentiles are read twice a second.
#define LOW_BINS 1024
#define LOW_SLICES 10
static uint16_t g_low_hist[LOW_SLICES][LOW_BINS];
static int g_low_cur;
static uint64_t g_low_t0;
// The per-frame counters, summed since t0 (the overlay's lines are averages over half a second).
static struct {
uint64_t t0, frames, gpu0;
@@ -47,6 +55,14 @@ void perfmon_frame(uint64_t now, uint64_t interval_ns, const uint64_t *wait_ns,
g_ring_at[g_ring_pos] = now;
g_ring_pos = (g_ring_pos + 1) % PERF_HISTORY;
if (g_ring_n < PERF_HISTORY) g_ring_n++;
if (now - g_low_t0 >= 1000000000ull) { // the next second: its slice starts empty
g_low_cur = (g_low_cur + 1) % LOW_SLICES;
memset(g_low_hist[g_low_cur], 0, sizeof g_low_hist[0]);
g_low_t0 = now;
}
uint64_t bin = interval_ns / 250000ull;
uint16_t *h = &g_low_hist[g_low_cur][bin < LOW_BINS ? bin : LOW_BINS - 1];
if (*h < 65535) (*h)++;
}
g_win.frames++;
g_win.replay += replay_ns / 1e6;
@@ -76,9 +92,27 @@ static void frames_summary(PerfStats *s, uint64_t now) { // (lock held)
}
}
// The fps of the slowest 1% and 0.1% of the frames in the window (the bin's upper edge, as perf.c's summary does); -1
// when the window holds too few frames. (lock held)
static void lows_summary(PerfStats *s) {
uint32_t total = 0;
for (int k = 0; k < LOW_SLICES; k++)
for (int b = 0; b < LOW_BINS; b++) total += g_low_hist[k][b];
s->low1_fps = s->low01_fps = -1;
if (total < 100) return;
uint32_t cut1 = (total + 99) / 100, cut01 = (total + 999) / 1000, acc = 0;
for (int b = LOW_BINS - 1; b >= 0 && s->low1_fps < 0; b--) {
for (int k = 0; k < LOW_SLICES; k++) acc += g_low_hist[k][b];
float fps = 1000.0f / ((b + 1) * 0.25f);
if (s->low01_fps < 0 && acc >= cut01) s->low01_fps = fps;
if (acc >= cut1) s->low1_fps = fps;
}
}
// Every half second: the window's sums as per-frame averages into g_stats, and a new window. (lock held)
static void counters_summary(uint64_t now) {
if (now - g_win.t0 < 500000000ull) return;
lows_summary(&g_stats);
uint64_t gpu = perf_gpu_busy_total();
if (g_win.t0 && g_win.frames) {
double n = (double)g_win.frames;
@@ -342,6 +376,8 @@ void perfmon_mode(int mode) {
}
if (!mode) { // the next start begins a new graph and a new counter window
g_ring_n = g_ring_pos = 0;
memset(g_low_hist, 0, sizeof g_low_hist);
g_low_t0 = 0;
memset(&g_win, 0, sizeof g_win);
}
plat_mutex_unlock(&g_lock);
+2
View File
@@ -17,6 +17,8 @@ extern "C" {
typedef struct {
// the game's frames (presents), over the last second
float fps, frame_ms_avg, frame_ms_max;
// fps of the slowest 1% and 0.1% of the frames over the last ten seconds (-1: too few frames yet)
float low1_fps, low01_fps;
float frame_ms[PERF_HISTORY]; // oldest first
// CPU: the whole machine and this process, percent of all logical processors
char cpu_name[64];
+189 -6
View File
@@ -9,6 +9,7 @@
#include <linux/fs.h>
#include <linux/futex.h>
#include <linux/userfaultfd.h>
#include <poll.h>
#include <pthread.h>
#include <sched.h>
#include <signal.h>
@@ -21,9 +22,11 @@
#include <sys/prctl.h>
#include <sys/random.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/uio.h>
#include <sys/un.h>
#include <sys/utsname.h>
#include <sys/wait.h>
#include <time.h>
@@ -915,8 +918,9 @@ uint64_t plat_mem_written(uint64_t addr, uint64_t n, uint64_t *pages, uint64_t m
}
// One handler for the synchronous faults. A SIGSEGV whose page-fault error code has the write bit set goes to the
// write-fault hook first (memory.c thaws a frozen region); a fault in this executable's code then goes to the crash
// hook (main.c); anything else gets the default action. Runs on the thread's signal stack.
// write-fault hook first (memory.c thaws a frozen region); any other fault, in this executable or in a library (Mesa,
// SDL), then goes to the crash hook (main.c), which reports it and ends the process. Without a crash hook the fault
// gets the default action. Runs on the thread's signal stack.
static int (*fault_hook)(uint64_t addr);
static void (*crash_fn)(const PlatCrash *c);
@@ -926,10 +930,17 @@ static void fault_handler(int sig, siginfo_t *si, void *uc) {
if (sig == SIGSEGV && fault_hook && (err & 2) && fault_hook((uint64_t)(uintptr_t)si->si_addr)) return;
uintptr_t rip = (uintptr_t)u->uc_mcontext.gregs[REG_RIP];
Dl_info at, self;
if (crash_fn && dladdr((void *)rip, &at) && dladdr((void *)plat_crash_hook, &self) && at.dli_fbase == self.dli_fbase) {
if (crash_fn) {
int found = dladdr((void *)rip, &at) && at.dli_fname;
PlatCrash c = {sig == SIGSEGV ? "access violation" : sig == SIGBUS ? "bus error"
: sig == SIGILL ? "illegal instruction" : "arithmetic exception",
(uint32_t)sig, rip, rip - (uintptr_t)self.dli_fbase, -1, 0};
(uint32_t)sig, rip, found ? rip - (uintptr_t)at.dli_fbase : rip, -1, 0};
if (!found) {
c.module = "";
} else if (!dladdr((void *)plat_crash_hook, &self) || at.dli_fbase != self.dli_fbase) {
const char *n = strrchr(at.dli_fname, '/');
c.module = n ? n + 1 : at.dli_fname;
}
if (sig == SIGSEGV || sig == SIGBUS)
c.access = (err & 16) ? 8 : (err & 2) ? 1 : 0, c.addr = (uint64_t)(uintptr_t)si->si_addr;
crash_fn(&c);
@@ -1037,6 +1048,8 @@ const void *plat_file_map(PlatFile *f) {
return v == MAP_FAILED ? NULL : v;
}
int plat_fs_os_error(void) { return errno; }
static int fs_err(int e) {
switch (e) {
case ENOENT: case ENOTDIR: return PLAT_FS_NOT_FOUND;
@@ -1180,8 +1193,10 @@ size_t plat_getenv(const char *name, char *out, size_t cap) {
// Cached per thread: plat_rmutex_lock asks on every acquire, hundreds of thousands of times a second in play, and
// gettid is a full syscall on Linux (Windows reads GetCurrentThreadId from the TEB). A thread's id never changes, and
// the runtime starts child processes with posix_spawn only, so no forked copy inherits a stale id.
uint32_t plat_thread_id(void) {
// the runtime starts child processes with posix_spawn only, so no forked copy inherits a stale id. noinline: a fiber
// may resume on another thread (platform.h), and a caller that inlined this could keep the address of tid it computed
// before a plat_fiber_switch; as a call it reads the slot of the thread it runs on.
__attribute__((noinline)) uint32_t plat_thread_id(void) {
static __thread uint32_t tid;
if (!tid) tid = (uint32_t)syscall(SYS_gettid);
return tid;
@@ -1247,6 +1262,8 @@ int plat_os_version(char *out, size_t cap) {
return snprintf(out, cap, "%s (Linux %s)", name, u.release) < (int)cap;
}
int plat_is_wine(void) { return 0; }
int plat_stderr_path(char *out, size_t cap) {
struct stat st;
if (fstat(2, &st) || !S_ISREG(st.st_mode)) return 0;
@@ -1648,3 +1665,169 @@ long plat_child_read(PlatChild *c, void *buf, size_t cap) {
while (k < 0 && errno == EINTR);
return (long)k;
}
// ---- local IPC (platform.h): Discord's Rich Presence Unix domain socket
struct PlatIpc { int fd; };
PlatIpc *plat_ipc_connect(const char *name) {
const char *dirs[] = {getenv("DISCORD_IPC_PATH"), getenv("XDG_RUNTIME_DIR"), getenv("TMPDIR"), "/tmp"};
for (size_t d = 0; d < sizeof dirs / sizeof *dirs; d++) {
if (!dirs[d] || !*dirs[d]) continue;
char path[sizeof ((struct sockaddr_un *)0)->sun_path];
if ((size_t)snprintf(path, sizeof path, "%s/%s", dirs[d], name) >= sizeof path) continue;
int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
if (fd < 0) return NULL;
struct sockaddr_un sa = {0};
sa.sun_family = AF_UNIX;
strcpy(sa.sun_path, path);
if (connect(fd, (struct sockaddr *)&sa, sizeof sa) == 0) {
PlatIpc *p = malloc(sizeof *p);
if (!p) {
close(fd);
return NULL;
}
p->fd = fd;
return p;
}
close(fd); // nothing listens at this path: the next directory may have it
}
return NULL;
}
int plat_ipc_read(PlatIpc *p, void *buf, size_t n, uint32_t ms) {
struct pollfd pf = {.fd = p->fd, .events = POLLIN};
int r = poll(&pf, 1, (int)ms);
if (r <= 0) return r < 0 && errno != EINTR ? -1 : 0;
ssize_t got = recv(p->fd, buf, n, 0);
return got > 0 ? (int)got : -1; // 0 bytes: the peer closed the socket
}
int plat_ipc_write(PlatIpc *p, const void *buf, size_t n) {
const uint8_t *at = buf;
while (n) {
ssize_t put = send(p->fd, at, n, MSG_NOSIGNAL); // a closed peer is an error, not a SIG_PIPE
if (put <= 0) {
if (put < 0 && errno == EINTR) continue;
return 0;
}
at += put, n -= put;
}
return 1;
}
void plat_ipc_close(PlatIpc *p) {
if (!p) return;
close(p->fd);
free(p);
}
// ---- restart
// TOTK_RESTART_WAIT names the process that called plat_restart, as its id and start time (field 22 of /proc/<pid>/stat,
// clock ticks after boot): a process that has only reused the id is not waited for. Waiting keeps the new process off
// the old one's files (the log it moves at start, the saves) until the old one is gone. The new process gets no
// descriptor past stderr (glibc 2.34's closefrom file action), and the default signal mask and dispositions, whatever
// the calling thread had.
#define RESTART_WAIT "TOTK_RESTART_WAIT"
// The start time of process pid (field 22 of its /proc stat line), 0 when it is gone.
static unsigned long long process_start(int pid) {
char path[64], buf[1024];
snprintf(path, sizeof path, "/proc/%d/stat", pid);
FILE *f = fopen(path, "r");
if (!f) return 0;
size_t n = fread(buf, 1, sizeof buf - 1, f);
fclose(f);
buf[n] = 0;
char *p = strrchr(buf, ')'); // the command name may hold spaces
unsigned long long start = 0;
if (!p || sscanf(p + 2, "%*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %*u %*u %*d %*d %*d %*d %*d %*d %llu",
&start) != 1)
return 0;
return start;
}
// glibc 2.34 added posix_spawn_file_actions_addclosefrom_np, and the release links against the Steam Runtime's 2.31: a
// weak reference, used when the running glibc has it. Without it the child inherits the open descriptors.
extern int posix_spawn_file_actions_addclosefrom_np(posix_spawn_file_actions_t *fa, int from) __attribute__((weak));
static void spawn_close_from(posix_spawn_file_actions_t *fa, int from) {
if (posix_spawn_file_actions_addclosefrom_np) posix_spawn_file_actions_addclosefrom_np(fa, from);
}
int plat_restart(void) {
// the arguments, NUL-separated, from /proc/self/cmdline
static char args[16384];
char *argv[256];
int argc = 0;
FILE *f = fopen("/proc/self/cmdline", "rb");
size_t n = f ? fread(args, 1, sizeof args - 1, f) : 0;
if (f) fclose(f);
args[n] = 0;
for (size_t i = 0; i < n && argc < 255; i += strlen(args + i) + 1) argv[argc++] = args + i;
argv[argc] = NULL;
char exe[PATH_MAX], wait[64];
if (!argc || !plat_exe_path(exe, sizeof exe)) return 0;
snprintf(wait, sizeof wait, "%d.%llu", (int)getpid(), process_start((int)getpid()));
posix_spawn_file_actions_t fa;
posix_spawn_file_actions_init(&fa);
spawn_close_from(&fa, 3);
posix_spawnattr_t at;
posix_spawnattr_init(&at);
sigset_t none, all;
sigemptyset(&none);
sigfillset(&all);
posix_spawnattr_setsigmask(&at, &none);
posix_spawnattr_setsigdefault(&at, &all);
posix_spawnattr_setflags(&at, POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF);
setenv(RESTART_WAIT, wait, 1);
pid_t pid;
int e = posix_spawn(&pid, exe, &fa, &at, argv, environ);
unsetenv(RESTART_WAIT);
posix_spawnattr_destroy(&at);
posix_spawn_file_actions_destroy(&fa);
return e == 0;
}
int plat_spawn(const char *const *argv, const char *cwd) {
posix_spawn_file_actions_t fa;
posix_spawn_file_actions_init(&fa);
spawn_close_from(&fa, 3);
posix_spawn_file_actions_addchdir_np(&fa, cwd);
posix_spawnattr_t at;
posix_spawnattr_init(&at);
sigset_t none, all;
sigemptyset(&none);
sigfillset(&all);
posix_spawnattr_setsigmask(&at, &none);
posix_spawnattr_setsigdefault(&at, &all);
posix_spawnattr_setflags(&at, POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSID);
pid_t pid;
int e = posix_spawn(&pid, argv[0], &fa, &at, (char *const *)argv, environ);
posix_spawnattr_destroy(&at);
posix_spawn_file_actions_destroy(&fa);
return e == 0;
}
int plat_restart_wait(uint32_t timeout_ms) {
const char *v = getenv(RESTART_WAIT);
if (!v) return 0;
int pid = 0;
unsigned long long start = 0;
int ok = sscanf(v, "%d.%llu", &pid, &start) == 2 && pid > 0 && start;
unsetenv(RESTART_WAIT); // the processes this one starts do not wait again
if (!ok) return 0;
// The descriptor is taken first: a start time that still matches then proves it is that process, not a new one with
// the id. It reads as ready once the process has exited, reaped or not.
int fd = (int)syscall(SYS_pidfd_open, pid, 0);
if (fd < 0) return 0; // already gone
int r = 0;
if (process_start(pid) == start) {
struct pollfd p = {fd, POLLIN, 0};
do r = poll(&p, 1, (int)timeout_ms);
while (r < 0 && errno == EINTR);
r = r > 0 ? 1 : -1;
}
close(fd);
return r;
}
+56 -9
View File
@@ -61,6 +61,23 @@ void plat_fiber_unself(void); // the calling thread stops being a fi
PlatFiber *plat_fiber_new(size_t stack, void (*fn)(void *arg), void *arg);
void plat_fiber_switch(PlatFiber *to); // from the fiber the calling thread runs
void plat_fiber_free(PlatFiber *f); // a fiber nobody runs
// A jump back to a point saved earlier on the same thread, without unwinding the frames in between (no SEH, no C++
// cleanups): the kernel's ExitThread leaves the lifted frames this way. plat_jmp_save returns 0 when it saves and 1
// when plat_jmp_go comes back to it; the function that called it must still be running. It keeps the callee-saved
// registers and the floating-point control state. On Windows this is not the C runtime's setjmp: a non-unwinding
// setjmp leaves the buffer's frame 0, and the C runtime's longjmp ends the process with 0xc0000409 (fast fail 13) on
// such a buffer when Control Flow Guard is on for the process, which Exploit protection can force on any program.
#ifdef _WIN32
typedef struct { uint64_t gpr[10]; uint32_t mxcsr, fpcw; uint64_t pad; uint8_t xmm[160]; } PlatJmp;
int plat_jmp_save(PlatJmp *j) __attribute__((returns_twice, nothrow));
_Noreturn void plat_jmp_go(PlatJmp *j);
#else
#include <setjmp.h>
typedef struct { jmp_buf b; } PlatJmp;
#define plat_jmp_save(j) setjmp((j)->b)
#define plat_jmp_go(j) longjmp((j)->b, 1)
#endif
// Scheduling priority, Windows' seven levels: of the calling thread, or of t. On Linux a thread lowered without the
// right to raise its priority again (CAP_SYS_NICE, or an RLIMIT_NICE of 20) could never return to normal, and the
// runtime lowers threads that later take shared locks at normal priority; without that right every change is skipped
@@ -201,19 +218,25 @@ void plat_mem_fault_hook(int (*fn)(uint64_t addr));
// replaces this process with it (Linux). Environment changes made before the call are passed on.
_Noreturn void plat_reexec(void);
// A crash in this executable's own code (an access violation, an illegal instruction, a division by zero, a stack
// overflow) goes to fn, which reports it and must end the process. Faults in other modules (drivers) are left to the
// OS. The write-fault hook above runs first. On Windows abort() (a failed assert, std::terminate) and an invalid
// parameter to a C runtime function go there too, with the host frames in this executable: the C runtime ends the
// process for both with 0xc0000409 and no exception.
// A crash goes to fn, which reports it and must end the process. The write-fault hook above runs first.
// - A fault in this executable's own code (an access violation, an illegal instruction, a division by zero, a stack
// overflow) is reported as it happens.
// - A fault in another module (a GPU driver, a system library) is reported only when nothing handles it: on Windows
// from the unhandled-exception filter, with the return addresses in this executable on the faulting thread's stack,
// so the report shows which host call ran into the driver; on Linux from the signal handler, without frames. Drivers
// that raise and catch their own exceptions never reach fn.
// - On Windows abort() (a failed assert, std::terminate) and an invalid parameter to a C runtime function go there
// too, with the host frames in this executable: the C runtime ends the process for both with 0xc0000409 and no
// exception.
typedef struct {
const char *what; // "access violation", "illegal instruction", ...
uint32_t code; // the Windows exception code or the signal number
uintptr_t rip, offset; // the faulting instruction, and its offset in the executable
uintptr_t rip, offset; // the faulting instruction, and its offset in its module
int access; // the data access that faulted: 0 read, 1 write, 8 execute; -1 when not an access
uint64_t addr; // its address when access >= 0
int nframes; // abort and invalid parameter: return addresses in this executable, innermost first
uintptr_t frames[16]; // (rip is frames[0]); 0 for a fault, whose rip is exact
int nframes; // return addresses in this executable, innermost first: for abort and invalid parameter
uintptr_t frames[16]; // (rip is frames[0]) and for a fault in another module; 0 for a fault in this one
const char *module; // the module holding rip: NULL for this executable, "" for none (a jump to address 0)
} PlatCrash;
void plat_crash_hook(void (*fn)(const PlatCrash *c));
int plat_mem_read(uint64_t addr, void *out, size_t n); // copies n bytes, 0 instead of faulting on unmapped memory
@@ -299,8 +322,9 @@ enum { PLAT_FS_OK, PLAT_FS_NOT_FOUND, PLAT_FS_EXISTS, PLAT_FS_NOT_EMPTY, PLAT_FS
enum { PLAT_FS_MISSING = -1, PLAT_FS_FILE, PLAT_FS_DIR, PLAT_FS_LINK }; // plat_fs_kind; LINK: a symbolic link or
// reparse point, never followed
int plat_fs_kind(const char *path);
int plat_fs_os_error(void); // the OS error code (GetLastError, errno) of this thread's last failed plat_fs_* call
int plat_fs_mkdir(const char *path); // PLAT_FS_EXISTS when something is there
int plat_fs_rmdir(const char *path); // an empty directory, or a link to one
int plat_fs_rmdir(const char *path); // an empty directory (a read-only one too), or a link to one
int plat_fs_unlink(const char *path); // a file or a link; a read-only one too
// Renames a file or directory; never replaces (PLAT_FS_EXISTS). durable: the change is on the disk at return.
int plat_fs_rename(const char *from, const char *to, int durable);
@@ -350,6 +374,7 @@ uint32_t plat_thread_id(void); // id of the calling t
int plat_font_path(const char *lang, char *out, size_t cap);
// The operating system and its build ("Windows 10.0.28000") into out; 0 when unknown.
int plat_os_version(char *out, size_t cap);
int plat_is_wine(void); // 1 when the Windows build runs under Wine; 0 elsewhere
// The file the process's stderr (the log) goes to, as a UTF-8 path; 0 when stderr is not a file (a console, a pipe).
int plat_stderr_path(char *out, size_t cap);
@@ -393,3 +418,25 @@ PlatChild *plat_child_start(const char *exe, const char *arg, uint32_t *err);
void plat_child_stop(PlatChild *c); // kills the child and frees c
int plat_child_write(PlatChild *c, const void *data, size_t n); // 1 when all n bytes were written
long plat_child_read(PlatChild *c, void *buf, size_t cap); // bytes read (at least 1); 0 or negative: pipe broke
// ---- local IPC: a stream connection to another program of this machine, one listen location per name (Discord's
// Rich Presence, discord_rpc.c). On Windows the named pipe \\.\pipe\<name>; on Linux the Unix domain socket
// <dir>/<name> with <dir> the first of $DISCORD_IPC_PATH, $XDG_RUNTIME_DIR, $TMPDIR and /tmp that has one.
typedef struct PlatIpc PlatIpc;
PlatIpc *plat_ipc_connect(const char *name); // NULL when nothing listens under that name
// Up to n bytes, waiting at most ms for the first of them: bytes read, 0 none in time, -1 the connection broke.
// The rest of what the peer wrote may still be in its buffer: a caller that needs a whole frame loops.
int plat_ipc_read(PlatIpc *p, void *buf, size_t n, uint32_t ms);
int plat_ipc_write(PlatIpc *p, const void *buf, size_t n); // 1 when all n bytes were written, 0 the connection broke
void plat_ipc_close(PlatIpc *p);
// ---- restart: this program again, in a new process that starts once this one is gone
// Starts this executable again with the same command line, environment and working folder, and no handle of this
// process. 1 when it started; the caller then exits.
int plat_restart(void);
// Starts argv[0] with the arguments argv[1..] (NULL-terminated, UTF-8) in folder cwd, detached from this process: no
// console, no handle of this one. 1 when it started (the setup window that rebuilds the game, runtime/cheats.c).
int plat_spawn(const char *const *argv, const char *cwd);
// In a process plat_restart started: waits, at most timeout_ms, until the process that started it has exited. 1 after
// the wait, -1 on timeout, 0 when there is nothing to wait for (not started by plat_restart, or that process is gone).
int plat_restart_wait(uint32_t timeout_ms);
+306 -5
View File
@@ -199,6 +199,69 @@ void plat_fiber_free(PlatFiber *f) {
free(f);
}
// plat_jmp_save / plat_jmp_go: PlatJmp holds rbx, rbp, rdi, rsi, r12-r15, the caller's rsp and the return address at
// 0..72, MXCSR at 80, the x87 control word at 84 and xmm6-xmm15 from 96, the Win64 callee-saved state. Both are leaf
// code that does not move rsp before it leaves, so they need no unwind data.
_Static_assert(sizeof(PlatJmp) == 256 && __builtin_offsetof(PlatJmp, xmm) == 96, "plat_jmp_save layout");
__asm__(".text\n"
".globl plat_jmp_save\n"
".def plat_jmp_save; .scl 2; .type 32; .endef\n"
".p2align 4\n"
"plat_jmp_save:\n"
" movq %rbx, 0(%rcx)\n"
" movq %rbp, 8(%rcx)\n"
" movq %rdi, 16(%rcx)\n"
" movq %rsi, 24(%rcx)\n"
" movq %r12, 32(%rcx)\n"
" movq %r13, 40(%rcx)\n"
" movq %r14, 48(%rcx)\n"
" movq %r15, 56(%rcx)\n"
" leaq 8(%rsp), %rdx\n" // the caller's rsp after this call returns
" movq %rdx, 64(%rcx)\n"
" movq (%rsp), %rdx\n"
" movq %rdx, 72(%rcx)\n"
" stmxcsr 80(%rcx)\n"
" fnstcw 84(%rcx)\n"
" movdqu %xmm6, 96(%rcx)\n"
" movdqu %xmm7, 112(%rcx)\n"
" movdqu %xmm8, 128(%rcx)\n"
" movdqu %xmm9, 144(%rcx)\n"
" movdqu %xmm10, 160(%rcx)\n"
" movdqu %xmm11, 176(%rcx)\n"
" movdqu %xmm12, 192(%rcx)\n"
" movdqu %xmm13, 208(%rcx)\n"
" movdqu %xmm14, 224(%rcx)\n"
" movdqu %xmm15, 240(%rcx)\n"
" xorl %eax, %eax\n"
" ret\n"
".globl plat_jmp_go\n"
".def plat_jmp_go; .scl 2; .type 32; .endef\n"
".p2align 4\n"
"plat_jmp_go:\n"
" movq 0(%rcx), %rbx\n"
" movq 8(%rcx), %rbp\n"
" movq 16(%rcx), %rdi\n"
" movq 24(%rcx), %rsi\n"
" movq 32(%rcx), %r12\n"
" movq 40(%rcx), %r13\n"
" movq 48(%rcx), %r14\n"
" movq 56(%rcx), %r15\n"
" ldmxcsr 80(%rcx)\n"
" fldcw 84(%rcx)\n"
" movdqu 96(%rcx), %xmm6\n"
" movdqu 112(%rcx), %xmm7\n"
" movdqu 128(%rcx), %xmm8\n"
" movdqu 144(%rcx), %xmm9\n"
" movdqu 160(%rcx), %xmm10\n"
" movdqu 176(%rcx), %xmm11\n"
" movdqu 192(%rcx), %xmm12\n"
" movdqu 208(%rcx), %xmm13\n"
" movdqu 224(%rcx), %xmm14\n"
" movdqu 240(%rcx), %xmm15\n"
" movq 64(%rcx), %rsp\n"
" movl $1, %eax\n"
" jmpq *72(%rcx)\n");
int plat_thread_spawn(PlatThreadFn fn, void *arg, const char *name, size_t stack) {
PlatThread *t = plat_thread_new_ex(fn, arg, name, stack);
if (t) plat_thread_detach(t);
@@ -602,6 +665,76 @@ __attribute__((noinline)) static void crash_from_runtime(const char *what, uint3
crash_fn(&c);
}
// The name a DLL records for itself in its export directory ("amdvlk64.dll"). Read from its mapped headers, not through
// the loader, whose lock another thread may hold when the process crashes.
static const char *image_name(const char *base) {
const IMAGE_NT_HEADERS64 *nt = (const void *)(base + ((const IMAGE_DOS_HEADER *)base)->e_lfanew);
const IMAGE_DATA_DIRECTORY *d = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
if (!d->VirtualAddress || !d->Size) return "unnamed module";
return base + ((const IMAGE_EXPORT_DIRECTORY *)(base + d->VirtualAddress))->Name;
}
// The return addresses in [lo, lo + size) on the crashed thread's stack, innermost first: unwinds the faulting context
// with the x64 unwind tables; a function without a table entry (a leaf, or address 0 after a call through a null
// pointer) has its return address on top of the stack. The walk stops at return address 0 (the thread's first frame)
// and when the stack pointer leaves the thread's stack, so a damaged stack ends it instead of faulting.
static int frames_in(const CONTEXT *at, uintptr_t lo, uintptr_t size, uintptr_t *out, int max) {
CONTEXT c = *at;
ULONG_PTR low, high;
GetCurrentThreadStackLimits(&low, &high);
int n = 0;
for (int i = 0; i < 256 && n < max && (c.Rip || !i) && c.Rsp >= low && c.Rsp + 8 <= high; i++) {
DWORD64 img;
RUNTIME_FUNCTION *fe = RtlLookupFunctionEntry(c.Rip, &img, NULL);
if (fe) {
void *data;
DWORD64 frame;
RtlVirtualUnwind(UNW_FLAG_NHANDLER, img, c.Rip, fe, &c, &data, &frame, NULL);
} else {
c.Rip = *(const DWORD64 *)c.Rsp;
c.Rsp += 8;
}
if (c.Rip - lo < size) out[n++] = (uintptr_t)c.Rip;
}
return n;
}
// The last-chance filter: an exception no handler took, in any module. crash_veh reports faults in this executable as
// they happen; this one catches the rest, which used to end the process with no line in the log: a fault in a GPU
// driver's own thread or in a driver call (vkQueueSubmit, vkAllocateMemory), a C++ exception a library let escape, a
// call through a null pointer (rip 0, outside every module). Windows calls it only after every handler declined, so
// the exceptions drivers raise and catch themselves never get here; it costs nothing until a crash.
static LONG WINAPI crash_filter(EXCEPTION_POINTERS *ep) {
const EXCEPTION_RECORD *er = ep->ExceptionRecord;
DWORD code = er->ExceptionCode;
uintptr_t rip = (uintptr_t)ep->ContextRecord->Rip;
PlatCrash c = {code == EXCEPTION_ACCESS_VIOLATION ? "access violation"
: code == EXCEPTION_ILLEGAL_INSTRUCTION ? "illegal instruction"
: code == EXCEPTION_INT_DIVIDE_BY_ZERO ? "integer division by zero"
: code == EXCEPTION_PRIV_INSTRUCTION ? "privileged instruction"
: code == EXCEPTION_STACK_OVERFLOW ? "stack overflow"
: code == EXCEPTION_IN_PAGE_ERROR ? "in-page error"
: code == EXCEPTION_BREAKPOINT ? "breakpoint"
: code == 0xe06d7363u ? "C++ exception"
: code == 0xc0000374u ? "heap corruption" // STATUS_HEAP_CORRUPTION
: "unhandled exception",
(uint32_t)code, rip, 0, -1, 0};
if (code == EXCEPTION_ACCESS_VIOLATION && er->NumberParameters >= 2)
c.access = (int)er->ExceptionInformation[0], c.addr = er->ExceptionInformation[1];
void *base = NULL;
RtlPcToFileHeader((void *)rip, &base);
MODULEINFO mi;
uintptr_t exe = (uintptr_t)GetModuleHandleW(NULL);
c.offset = rip - (uintptr_t)base;
if (!base) c.module = "";
else if ((uintptr_t)base != exe) c.module = image_name(base);
if (c.module && GetModuleInformation(GetCurrentProcess(), (HMODULE)exe, &mi, sizeof mi))
c.nframes = frames_in(ep->ContextRecord, exe, mi.SizeOfImage, c.frames,
(int)(sizeof c.frames / sizeof *c.frames));
crash_fn(&c);
return EXCEPTION_CONTINUE_SEARCH;
}
static void abort_signal(int sig) { crash_from_runtime("abort", (uint32_t)sig); }
static void invalid_parameter(const wchar_t *expr, const wchar_t *func, const wchar_t *file, unsigned line,
@@ -613,6 +746,7 @@ static void invalid_parameter(const wchar_t *expr, const wchar_t *func, const wc
void plat_crash_hook(void (*fn)(const PlatCrash *c)) {
crash_fn = fn;
AddVectoredExceptionHandler(0, crash_veh);
SetUnhandledExceptionFilter(crash_filter); // replaces the C runtime's filter; crash_fn never returns
signal(SIGABRT, abort_signal);
_set_invalid_parameter_handler(invalid_parameter);
}
@@ -803,7 +937,11 @@ const void *plat_file_map(PlatFile *f) {
return v;
}
static __thread DWORD fs_last_error;
int plat_fs_os_error(void) { return (int)fs_last_error; }
static int fs_err(DWORD e) {
fs_last_error = e;
switch (e) {
case ERROR_FILE_NOT_FOUND: case ERROR_PATH_NOT_FOUND: case ERROR_DIRECTORY: return PLAT_FS_NOT_FOUND;
case ERROR_FILE_EXISTS: case ERROR_ALREADY_EXISTS: return PLAT_FS_EXISTS;
@@ -813,12 +951,28 @@ static int fs_err(DWORD e) {
}
}
// A symbolic link or junction is a link: removed as a link, never followed. Any other reparse point (OneDrive's cloud
// placeholders, deduplicated files) is an ordinary file or directory whose content the file system fetches on access.
static int fs_kind_of(const WIN32_FIND_DATAW *fd) {
DWORD a = fd->dwFileAttributes;
if (a & FILE_ATTRIBUTE_REPARSE_POINT && (fd->dwReserved0 == IO_REPARSE_TAG_SYMLINK || fd->dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT))
return PLAT_FS_LINK;
return a & FILE_ATTRIBUTE_DIRECTORY ? PLAT_FS_DIR : PLAT_FS_FILE;
}
int plat_fs_kind(const char *path) {
wchar_t w[WPATH];
if (!widen(path, w, WPATH)) return PLAT_FS_MISSING;
DWORD a = GetFileAttributesW(w);
if (a == INVALID_FILE_ATTRIBUTES) return PLAT_FS_MISSING;
return a & FILE_ATTRIBUTE_REPARSE_POINT ? PLAT_FS_LINK : a & FILE_ATTRIBUTE_DIRECTORY ? PLAT_FS_DIR : PLAT_FS_FILE;
if (!(a & FILE_ATTRIBUTE_REPARSE_POINT)) return a & FILE_ATTRIBUTE_DIRECTORY ? PLAT_FS_DIR : PLAT_FS_FILE;
// the reparse tag comes with the find data only; FindFirstFileW is asked only here, since it fails on a path
// with a trailing separator and reads wildcards
WIN32_FIND_DATAW fd;
HANDLE h = FindFirstFileW(w, &fd);
if (h == INVALID_HANDLE_VALUE) return PLAT_FS_LINK;
FindClose(h);
return fs_kind_of(&fd);
}
int plat_fs_mkdir(const char *path) {
@@ -830,7 +984,15 @@ int plat_fs_mkdir(const char *path) {
int plat_fs_rmdir(const char *path) {
wchar_t w[WPATH];
if (!widen(path, w, WPATH)) return PLAT_FS_ERROR;
return RemoveDirectoryW(w) ? PLAT_FS_OK : fs_err(GetLastError());
if (RemoveDirectoryW(w)) return PLAT_FS_OK;
DWORD e = GetLastError(), a = GetFileAttributesW(w);
if (e == ERROR_ACCESS_DENIED && a != INVALID_FILE_ATTRIBUTES && (a & FILE_ATTRIBUTE_READONLY)) {
// a read-only directory (copied over from another emulator's save folder) refuses RemoveDirectoryW
SetFileAttributesW(w, a & ~(DWORD)FILE_ATTRIBUTE_READONLY);
if (RemoveDirectoryW(w)) return PLAT_FS_OK;
e = GetLastError();
}
return fs_err(e);
}
int plat_fs_unlink(const char *path) {
@@ -975,9 +1137,7 @@ int plat_fs_list(const char *dir, int (*cb)(const char *name, int kind, uint64_t
if (!wcscmp(fd.cFileName, L".") || !wcscmp(fd.cFileName, L"..")) continue;
char name[1024];
if (!WideCharToMultiByte(CP_UTF8, 0, fd.cFileName, -1, name, sizeof name, NULL, NULL)) continue;
DWORD a = fd.dwFileAttributes;
int kind = a & FILE_ATTRIBUTE_REPARSE_POINT ? PLAT_FS_LINK : a & FILE_ATTRIBUTE_DIRECTORY ? PLAT_FS_DIR
: PLAT_FS_FILE;
int kind = fs_kind_of(&fd);
if (!cb(name, kind, (uint64_t)fd.nFileSizeHigh << 32 | fd.nFileSizeLow, ctx)) break;
} while (FindNextFileW(h, &fd));
FindClose(h);
@@ -1128,6 +1288,11 @@ int plat_os_version(char *out, size_t cap) {
return 1;
}
int plat_is_wine(void) {
HMODULE nt = GetModuleHandleW(L"ntdll.dll");
return nt && GetProcAddress(nt, "wine_get_version") != NULL;
}
int plat_stderr_path(char *out, size_t cap) {
HANDLE h = GetStdHandle(STD_ERROR_HANDLE);
wchar_t w[WPATH];
@@ -1458,3 +1623,139 @@ long plat_child_read(PlatChild *c, void *buf, size_t cap) {
if (!ReadFile(c->out, buf, (DWORD)cap, &got, NULL)) return -1;
return (long)got;
}
// ---- local IPC (platform.h): Discord's Rich Presence named pipe
struct PlatIpc { HANDLE h; };
PlatIpc *plat_ipc_connect(const char *name) {
wchar_t wname[128], path[152];
if (!widen(name, wname, 128)) return NULL;
swprintf(path, 152, L"\\\\.\\pipe\\%ls", wname);
HANDLE h = CreateFileW(path, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (h == INVALID_HANDLE_VALUE) return NULL; // no listener, or the pipe is busy: the caller retries later
PlatIpc *p = malloc(sizeof *p);
if (!p) {
CloseHandle(h);
return NULL;
}
p->h = h;
return p;
}
int plat_ipc_read(PlatIpc *p, void *buf, size_t n, uint32_t ms) {
uint64_t deadline = plat_now_ms() + ms;
for (;;) {
DWORD have = 0;
if (!PeekNamedPipe(p->h, NULL, 0, NULL, &have, NULL)) return -1; // the writer closed the pipe
if (have) {
DWORD got = 0;
if (!ReadFile(p->h, buf, have < n ? have : (DWORD)n, &got, NULL) || !got) return -1;
return (int)got;
}
if (plat_now_ms() >= deadline) return 0;
plat_sleep_ms(5);
}
}
int plat_ipc_write(PlatIpc *p, const void *buf, size_t n) {
const uint8_t *at = buf;
while (n) {
DWORD put = 0;
if (!WriteFile(p->h, at, n > (1u << 30) ? 1u << 30 : (DWORD)n, &put, NULL) || !put) return 0;
at += put, n -= put;
}
return 1;
}
void plat_ipc_close(PlatIpc *p) {
if (!p) return;
CloseHandle(p->h);
free(p);
}
// ---- restart
// TOTK_RESTART_WAIT names the process that called plat_restart, as its id and creation time: a process that has only
// reused the id is not waited for. Waiting keeps the new process off the old one's files (the log it moves at start,
// the saves) until the old one is gone; no handle is inherited, so none of them stays open in the new one either.
#define RESTART_WAIT "TOTK_RESTART_WAIT"
static uint64_t process_created(HANDLE h) {
FILETIME c, e, k, u;
return GetProcessTimes(h, &c, &e, &k, &u) ? ft64(c) : 0;
}
int plat_restart(void) {
char wait[48];
snprintf(wait, sizeof wait, "%lu.%llu", GetCurrentProcessId(), (unsigned long long)process_created(GetCurrentProcess()));
plat_setenv(RESTART_WAIT, wait);
STARTUPINFOW si = {.cb = sizeof si};
PROCESS_INFORMATION pi;
wchar_t *cmd = _wcsdup(GetCommandLineW()); // CreateProcessW may write its command line
BOOL ok = cmd && CreateProcessW(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
free(cmd);
plat_setenv(RESTART_WAIT, NULL);
if (!ok) return 0;
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return 1;
}
// One argument of a command line as CommandLineToArgvW reads it back: in quotes, a backslash run doubled before a quote
// and at the end, a quote escaped.
static size_t quote_arg(const wchar_t *a, wchar_t *out, size_t cap, size_t at) {
#define PUT(c) do { if (at + 1 < cap) out[at] = (c); at++; } while (0)
PUT(L'"');
for (const wchar_t *p = a;; p++) {
size_t slashes = 0;
while (*p == L'\\') p++, slashes++;
size_t times = !*p || *p == L'"' ? 2 : 1;
for (size_t k = 0; k < slashes * times; k++) PUT(L'\\');
if (!*p) break;
if (*p == L'"') PUT(L'\\');
PUT(*p);
}
PUT(L'"');
PUT(L' ');
#undef PUT
return at;
}
int plat_spawn(const char *const *argv, const char *cwd) {
enum { CMD = 32768 };
wchar_t *cmd = calloc(CMD, sizeof *cmd), *arg = malloc(WPATH * sizeof *arg), *dir = malloc(WPATH * sizeof *dir);
int ok = cmd && arg && dir && argv[0] && widen(cwd, dir, WPATH);
size_t at = 0;
for (int i = 0; ok && argv[i]; i++) {
ok = widen(argv[i], arg, WPATH);
if (ok) at = quote_arg(arg, cmd, CMD, at);
}
ok = ok && at < CMD && at > 0;
if (ok) cmd[at - 1] = 0; // the last separator
STARTUPINFOW si = {.cb = sizeof si};
PROCESS_INFORMATION pi;
ok = ok && CreateProcessW(NULL, cmd, NULL, NULL, FALSE, DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP, NULL, dir, &si,
&pi);
if (ok) {
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}
free(cmd);
free(arg);
free(dir);
return ok;
}
int plat_restart_wait(uint32_t timeout_ms) {
char v[48];
if (!plat_getenv(RESTART_WAIT, v, sizeof v)) return 0;
plat_setenv(RESTART_WAIT, NULL); // the processes this one starts do not wait again
unsigned long pid = 0;
unsigned long long created = 0;
if (sscanf(v, "%lu.%llu", &pid, &created) != 2) return 0;
HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (!h) return 0; // already gone
int r = process_created(h) != created ? 0 : WaitForSingleObject(h, timeout_ms) == WAIT_OBJECT_0 ? 1 : -1;
CloseHandle(h);
return r;
}
+201 -9
View File
@@ -27,6 +27,9 @@
// rewritten table (res_heapdef_build) in place of the original; memory.c adds the amount to the application pool, so
// no other heap shrinks. Without the rewritten table (a RomFS that lacks it, a format this code does not know) the
// patch sets stay off and the game keeps its own sizes.
#ifndef _WIN32
#include <dirent.h>
#endif
#include <math.h>
#include <stdint.h>
#include <stdio.h>
@@ -36,6 +39,7 @@
#include "cfg.h"
#include "host.h"
#include "platform/platform.h"
#define BASE_W 1920
#define BASE_H 1080
@@ -43,6 +47,7 @@
#define SCENE_H 900
#define DTA_KIB 113664u // DynamicTextureAllocatorMem, shipped
#define SCENE_MAX 4096 // per side, as MacNativeGames' TOTK_RENDER_RES
#define SHADOW_BASE 960 // the sun shadow map's base size (its cascades: a D16 array of 4 layers)
static struct {
int decided;
@@ -50,8 +55,71 @@ static struct {
int scene_set; // the scene differs from the game's 5/6 of the output
int heapdef_ok; // romfs.c serves the grown HeapDef
int on; // res_init switched the patch sets on
unsigned shadow; // fixed sun shadow map size (TOTK_SHADOW_RES), 0: the game's own
double dlss_k; // TOTK_DLSS quality/balanced/performance/ultra_performance: the scene's share of the output, else 0
double base_k; // the scene's share without a DLSS mode (render_scale, or the game's 5/6)
unsigned hw, hh; // the largest scene a DLSS mode change can ask for: the heap is sized for it
int live; // 1.4.3 with DLSS able to run: the DLSS mode can change while the game runs
} R;
// The scene size is decided before the device exists, so NGX cannot be asked yet. NGX loads DLSS from nvngx_dlss.dll
// next to totk.exe on Windows, libnvidia-ngx-dlss.so.<version> next to totk on Linux (vk_dlaa.c vk_dlaa_init):
// without that file DLSS never runs, and a DLSS mode would leave the game's plain scaling at 50..67 % of the output.
static int dlss_dll(void) {
#ifdef _WIN32
char exe[1024], path[1024 + 32];
if (!plat_exe_path(exe, sizeof exe)) return 1;
char *last = plat_last_sep(exe);
if (!last) return 1;
snprintf(path, sizeof path, "%.*s/nvngx_dlss.dll", (int)(last - exe), exe);
return plat_file_exists(path);
#else
char exe[1024];
if (!plat_exe_path(exe, sizeof exe)) return 1;
char *last = plat_last_sep(exe);
if (!last) return 1;
*last = 0;
DIR *d = opendir(exe);
if (!d) return 1;
int found = 0;
for (struct dirent *e; !found && (e = readdir(d));)
found = !strncmp(e->d_name, "libnvidia-ngx-dlss.so.", 22);
closedir(d);
return found;
#endif
}
// The scene size for a share k of the output, within SCENE_MAX per side.
static void scene_for(double k, unsigned *w, unsigned *h) {
double sw = R.ow * k, sh = R.oh * k;
double fit = fmin(1.0, fmin(SCENE_MAX / sw, SCENE_MAX / sh));
*w = (unsigned)(sw * fit + 0.5);
*h = (unsigned)(sh * fit + 0.5);
}
// The scene's share of the output for a TOTK_DLSS mode; 0 for dlaa (the scene keeps base_k), while DLSS/DLAA is off
// (the mode the menu still holds would shrink the scene for the plain upscaler) and where DLSS cannot run (dlss_dll).
static double dlss_share(const char *m) {
static const struct { const char *name; double k; } dlss[] = {
{"quality", 2.0 / 3.0}, {"balanced", 0.58}, {"performance", 0.5}, {"ultra_performance", 1.0 / 3.0}};
static int dll = -1;
if (!cfg_bool("TOTK_DLAA")) return 0;
for (int i = 0; i < (int)(sizeof dlss / sizeof dlss[0]); i++)
if (!strcmp(m, dlss[i].name)) {
if (dll < 0 && !(dll = dlss_dll())) {
#ifdef _WIN32
rt_log("resolution: DLSS %s needs nvngx_dlss.dll next to totk.exe, which is missing: the scene follows "
"render_scale", m);
#else
rt_log("resolution: DLSS %s needs libnvidia-ngx-dlss.so.<version> next to totk, which is missing: the "
"scene follows render_scale", m);
#endif
}
return dll ? dlss[i].k : 0;
}
return 0;
}
static void decide(void) {
if (R.decided) return;
R.decided = 1;
@@ -78,24 +146,45 @@ static void decide(void) {
rt_log("resolution: TOTK_RENDER_SCALE=%s is not game or a percentage 25..400; game", s);
}
}
double sw = R.ow * k, sh = R.oh * k;
double fit = fmin(1.0, fmin(SCENE_MAX / sw, SCENE_MAX / sh));
if (fit < 1.0) R.scene_set = 1;
R.sw = (unsigned)(sw * fit + 0.5);
R.sh = (unsigned)(sh * fit + 0.5);
// A DLSS mode other than dlaa sets the scene size instead. On 1.4.3 with DLSS able to run (DLAA on, the DLL there)
// the mode can change while the game runs (res_dlss_mode): the scene patch is then always on and the heap is sized
// for the largest scene the modes ask for. Everyone else keeps the game's own scene size and its dynamic resolution
// unless render_scale or a DLSS mode asks for another, and a heap sized for that scene alone.
R.base_k = k;
R.live = RT_V143 && cfg_bool("TOTK_DLAA") && dlss_dll();
const char *m = cfg_value("TOTK_DLSS");
R.dlss_k = dlss_share(m);
if (R.dlss_k) rt_log("resolution: DLSS %s: the scene at %.0f %% of the output (render_scale ignored)", m, R.dlss_k * 100);
double sk = R.dlss_k ? R.dlss_k : k;
if (R.live || R.dlss_k || R.ow * sk > SCENE_MAX || R.oh * sk > SCENE_MAX) R.scene_set = 1;
scene_for(sk, &R.sw, &R.sh);
if (R.live) scene_for(fmax(k, 2.0 / 3.0), &R.hw, &R.hh);
else R.hw = R.sw, R.hh = R.sh;
const char *sr = cfg_value("TOTK_SHADOW_RES");
if (strcmp(sr, "game")) {
unsigned n = (unsigned)atoi(sr);
if (n >= 256 && n <= 4096 && !(n & 7)) R.shadow = n;
else rt_log("resolution: TOTK_SHADOW_RES=%s is not game or a size 256..4096 (a multiple of 8); game", sr);
}
}
// Texture heap for a sun shadow map above the base size: the four layers of 2 bytes, three maps in flight (the engine
// makes the array anew each frame).
static uint64_t shadow_kib(void) {
return R.shadow > SHADOW_BASE ? ((uint64_t)R.shadow * R.shadow - SHADOW_BASE * SHADOW_BASE) * 8 * 3 / 1024 : 0;
}
static int bigger(void) {
decide();
return R.ow != BASE_W || R.oh != BASE_H || R.scene_set;
return R.ow != BASE_W || R.oh != BASE_H || R.scene_set || shadow_kib();
}
uint64_t res_heap_extra_kib(void) {
if (!bigger()) return 0;
double grow = fmax(0.0, (double)R.ow * R.oh / (BASE_W * BASE_H) - 1.0) +
fmax(0.0, (double)R.sw * R.sh / (SCENE_W * SCENE_H) - 1.0);
if (grow <= 0) return 0;
return (uint64_t)ceil(DTA_KIB * (1.0 + grow) / 1024.0) * 1024 - DTA_KIB;
fmax(0.0, (double)R.hw * R.hh / (SCENE_W * SCENE_H) - 1.0);
uint64_t kib = grow > 0 ? (uint64_t)ceil(DTA_KIB * (1.0 + grow) / 1024.0) * 1024 - DTA_KIB : 0;
return kib + ((shadow_kib() + 1023) & ~1023ull); // whole MiB
}
uint64_t res_heap_extra_bytes(void) { return ((res_heap_extra_kib() << 10) + 0x1fffff) & ~0x1fffffull; }
@@ -190,12 +279,50 @@ int res_heapdef_build(const void *in, size_t n, void **out, size_t *out_n) {
void res_heapdef_served(void) { R.heapdef_ok = 1; }
// ---- sun shadow map size: each frame the engine sizes its shadow cascades to the area they cover, down to about 400 near
// the ground, which draws foliage shadows blocky, and each change of size moves the shadow texels, so leaf shadows jump.
// A fixed size (the shadow set, recomp/patches-v121.txt) keeps them still and sharper. Page +92.
static void shadow_init(uint8_t *page) {
if (!R.shadow) {
rt_log("resolution: sun shadow map sized by the game (TOTK_SHADOW_RES=game)");
return;
}
int set = rt_patch_set("shadow");
if (set < 0) {
rt_log("resolution: the generated C has no shadow patch set: the game sizes its shadow map");
return;
}
int32_t n = (int32_t)R.shadow;
memcpy(page + 92, &n, 4);
rt_patch_switch(set, 1);
rt_log("resolution: sun shadow map %ux%u (TOTK_SHADOW_RES)", R.shadow, R.shadow);
}
// ---- start: the patch page and the sets
static uint64_t pack(unsigned w, unsigned h) { return (uint64_t)h << 32 | w; }
// TOTK_SHADOW_RANGE (percent, 50 to 400; 100 = the game's): the sun's shadow cascades end at 20, 40, 80 and 160 m.
// Other values multiply those distances through the cascade patch set (recomp/patches-v143.txt), so the sharp first
// cascade reaches further and the visible steps between cascades move away from the player, at the cost of shadow
// texels per metre (TOTK_SHADOW_SCALE pays that back).
static void res_shadow_range(void) {
int pct = cfg_int("TOTK_SHADOW_RANGE"), set = rt_patch_set("cascade");
if (pct == 100) return;
if (set < 0) {
rt_log("resolution: the generated C has no cascade patch set; shadow_range stays 100");
return;
}
float k = (float)(pct < 50 ? 50 : pct > 400 ? 400 : pct) / 100.0f, d[4] = {20 * k, 40 * k, 80 * k, 160 * k};
memcpy((uint8_t *)rt_patch_page() + 64, d, sizeof d);
rt_patch_switch(set, 1);
rt_log("resolution: shadow cascades end at %g, %g, %g and %g m", d[0], d[1], d[2], d[3]);
}
void res_init(void) {
res_shadow_range();
if (!bigger()) {
rt_log("resolution: the game's own (output 1920x1080, scene 1600x900)");
shadow_init(rt_patch_page());
return;
}
int output = rt_patch_set("output"), scene = rt_patch_set("scene");
@@ -220,6 +347,7 @@ void res_init(void) {
rt_patch_switch(output, R.ow != BASE_W || R.oh != BASE_H);
rt_patch_switch(scene, scene_on);
R.on = 1;
if (R.live) g_fnprof = 1; // until the game sets its render size: res_fn_hit, or res_present gives up
// Another shape than 16:9 (more than 1% off): the camera takes the output's ratio (recomp/patches-v121.txt and
// patches-v143.txt, set aspect), so a 21:9 output shows more of the world at the sides instead of a stretched 16:9 view. The HUD's layouts
// for that shape come from romfs-patches-<w>x<h> (romfs.c overlay_init, tools/make_romfs_patches.py --aspect).
@@ -238,10 +366,18 @@ void res_init(void) {
} else {
rt_patch_switch(aspect, 0); // the page holds no ratio
}
shadow_init(page);
rt_log("resolution: output %ux%u, scene %ux%u%s; texture heap +%llu KiB", R.ow, R.oh, R.sw, R.sh,
scene_on ? "" : " (the game's own 5/6 of the output)", (unsigned long long)res_heap_extra_kib());
}
// DLSS upscaling: textures are sampled for the output's resolution, not the scene's (NVIDIA's DLSS guide: a mip bias
// of log2(render / output)), so their detail survives the scaling. 0 without a DLSS mode.
float res_dlss_lod_bias(void) {
decide();
return R.dlss_k ? (float)log2(R.dlss_k) : 0.0f;
}
// 16:9 within 1% (1366x768 counts): the shape the game's own layouts and camera are made for.
int res_is_16x9(unsigned w, unsigned h) {
double rel = ((double)w / h) / ((double)BASE_W / BASE_H);
@@ -282,6 +418,62 @@ void res_wanted(unsigned out[2]) {
out[0] = R.ow, out[1] = R.oh;
}
// A TOTK_DLSS change while the game runs (vk_dlaa.c, at a present): the new scene size goes to the patch page, where
// the game reads it when it sets its render size (main+0x585e48). 1.4.3 does that once, at start: its renderer setup
// (main+0x7000e67028) calls main+0x585bd0(renderer, force), which picks the console mode's sizes and flags the render
// targets for re-creation. The setup call is caught through the function-entry hook (res_fn_hit, on only until then),
// and the next nvnQueuePresentTexture on the game's thread calls it again with force set (res_present), between frames
// as at start. The heap was sized for the largest scene a mode asks for. 1 when the size changed.
#define SET_RENDER_SIZE 0x7000585bd0ull
static uint64_t renderer; // x0 of the game's own call of SET_RENDER_SIZE
static volatile int size_pending; // the page holds a size the game has not set yet
void res_fn_hit(uint64_t addr, uint64_t x0) {
if (addr != SET_RENDER_SIZE) return;
renderer = x0;
g_fnprof = 0;
rt_log("resolution: renderer at %#llx; the scene size can change while the game runs", (unsigned long long)x0);
}
void res_present(Cpu *c) {
// The hook runs on every guest function entry while it waits: should the game set its render size before
// res_init or never, it stops after 1800 presents (half a minute at 60 fps) and modes change at the next start.
static unsigned waited;
if (g_fnprof && !renderer && ++waited == 1800) {
g_fnprof = 0;
rt_log("resolution: the game's render size setup was not seen; DLSS modes change at the next start");
}
if (!size_pending || !renderer) return;
size_pending = 0;
Cpu keep = *c; // the guest's registers as at the present call: the setup runs as if it never happened
rt_call(c, SET_RENDER_SIZE, 2, (uint64_t)renderer, (uint64_t)1);
memcpy(c->x, keep.x, sizeof c->x);
memcpy(c->v, keep.v, sizeof c->v);
c->nzcv = keep.nzcv, c->fpsr = keep.fpsr;
rt_log("resolution: the game set the scene size %ux%u", R.sw, R.sh);
}
int res_dlss_mode(const char *m) {
decide();
double k = dlss_share(m);
if (k == R.dlss_k || !R.on) return 0;
if (!RT_V143 || !renderer) {
rt_log("resolution: DLSS %s takes effect at the next start (the game set its render size already)", m);
return 0;
}
R.dlss_k = k;
unsigned w, h;
scene_for(k ? k : R.base_k, &w, &h);
if (w == R.sw && h == R.sh) return 0;
double s = RT_V143 ? (double)R.ow / BASE_W : 1.0;
float sc[2] = {(float)(w / s), (float)(h / s)};
memcpy((uint8_t *)rt_patch_page() + 16, sc, sizeof sc);
R.sw = w, R.sh = h;
size_pending = 1;
rt_log("resolution: DLSS %s: scene %ux%u", m, w, h);
return 1;
}
void res_sizes(unsigned out[2], unsigned scene[2]) {
decide();
out[0] = R.on ? R.ow : BASE_W, out[1] = R.on ? R.oh : BASE_H;
+236
View File
@@ -0,0 +1,236 @@
// The resource size table (restbl.h). Layout of a decompressed RESTBL, little-endian:
//
// "RESTBL", u32 version (1), u32 name length (160), u32 hashed count, u32 named count
// hashed entries {u32 crc32 of the key, u32 size}, sorted by the hash
// named entries {char key[name length], u32 size}: the keys whose hash collides with another key's
//
// A key is a RomFS path without .zs or .mc. The estimates come from the 1.4.3 table against its own files: most types
// need the decompressed size plus at most 8 KiB (headers, alignment); a few need a multiple of it (bfres 1.5, bkres
// 2.05, bgyml 3.85, asb 1.4, bstar 1.2, bphsc 1.1). A type the table does not list takes 1.5 times its size plus 8 KiB.
#include <stdlib.h>
#include <string.h>
#include "restbl.h"
typedef struct { uint32_t hash, size; } Hashed;
struct Restbl {
uint32_t version, name_len;
Hashed *hashed;
size_t nhashed, hashed_cap;
uint8_t *named; // named entries as in the file: key (name_len bytes, NUL padded) then u32 size
size_t nnamed;
};
static uint32_t rd32(const uint8_t *p) { return p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24; }
static void wr32(uint8_t *p, uint32_t v) {
for (int i = 0; i < 4; i++) p[i] = (uint8_t)(v >> 8 * i);
}
static uint32_t crc32_of(const char *s) {
uint32_t c = ~0u;
for (; *s; s++) {
c ^= (uint8_t)*s;
for (int k = 0; k < 8; k++) c = c >> 1 ^ (0xEDB88320u & (0u - (c & 1)));
}
return ~c;
}
Restbl *restbl_parse(const uint8_t *data, size_t n) {
if (n < 22 || memcmp(data, "RESTBL", 6)) return NULL;
uint32_t version = rd32(data + 6), name_len = rd32(data + 10), nh = rd32(data + 14), nn = rd32(data + 18);
if (!name_len || name_len > 4096 || (uint64_t)nh * 8 + (uint64_t)nn * (name_len + 4) != n - 22) return NULL;
Restbl *t = calloc(1, sizeof *t);
if (!t) return NULL;
t->version = version, t->name_len = name_len;
t->hashed = malloc(((size_t)nh + 1) * sizeof *t->hashed);
t->named = malloc((size_t)nn * (name_len + 4) + 1);
if (!t->hashed || !t->named) {
restbl_free(t);
return NULL;
}
for (uint32_t i = 0; i < nh; i++) t->hashed[i] = (Hashed){rd32(data + 22 + i * 8), rd32(data + 26 + i * 8)};
t->nhashed = t->hashed_cap = nh;
if (!t->hashed_cap) t->hashed_cap = 1;
memcpy(t->named, data + 22 + (size_t)nh * 8, (size_t)nn * (name_len + 4));
t->nnamed = nn;
return t;
}
void restbl_free(Restbl *t) {
if (!t) return;
free(t->hashed);
free(t->named);
free(t);
}
const char *restbl_key(const char *path, char *buf, size_t n) {
size_t len = strlen(path);
if (len >= 3 && (!strcmp(path + len - 3, ".zs") || !strcmp(path + len - 3, ".mc"))) len -= 3;
if (len >= n) len = n - 1;
memcpy(buf, path, len);
buf[len] = 0;
return buf;
}
// The named entry of key, or NULL.
static uint8_t *named_of(const Restbl *t, const char *key) {
size_t len = strlen(key);
if (len >= t->name_len) return NULL;
for (size_t i = 0; i < t->nnamed; i++) {
uint8_t *e = t->named + i * (t->name_len + 4);
if (!memcmp(e, key, len + 1)) return e;
}
return NULL;
}
// The position of hash in the hashed entries, or where it would go.
static size_t hashed_at(const Restbl *t, uint32_t hash) {
size_t lo = 0, hi = t->nhashed;
while (lo < hi) {
size_t m = lo + (hi - lo) / 2;
if (t->hashed[m].hash < hash) lo = m + 1;
else hi = m;
}
return lo;
}
int restbl_get(const Restbl *t, const char *key, uint32_t *size) {
const uint8_t *e = named_of(t, key);
if (e) {
*size = rd32(e + t->name_len);
return 1;
}
uint32_t h = crc32_of(key);
size_t i = hashed_at(t, h);
if (i < t->nhashed && t->hashed[i].hash == h) {
*size = t->hashed[i].size;
return 1;
}
return 0;
}
// The hashed entry of hash raised to size (added when missing); 1 when the table changed.
static int raise_hash(Restbl *t, uint32_t h, uint32_t size) {
size_t i = hashed_at(t, h);
if (i < t->nhashed && t->hashed[i].hash == h) {
if (t->hashed[i].size >= size) return 0;
t->hashed[i].size = size;
return 1;
}
if (t->nhashed == t->hashed_cap) {
size_t cap = t->hashed_cap * 2;
Hashed *grown = realloc(t->hashed, cap * sizeof *grown);
if (!grown) return 0;
t->hashed = grown, t->hashed_cap = cap;
}
memmove(t->hashed + i + 1, t->hashed + i, (t->nhashed - i) * sizeof *t->hashed);
t->hashed[i] = (Hashed){h, size};
t->nhashed++;
return 1;
}
int restbl_raise(Restbl *t, const char *key, uint32_t size) {
uint8_t *e = named_of(t, key);
if (!e) return raise_hash(t, crc32_of(key), size);
if (rd32(e + t->name_len) >= size) return 0;
wr32(e + t->name_len, size);
return 1;
}
int restbl_merge(Restbl *t, const Restbl *base, const Restbl *shipped) {
int raised = 0;
for (size_t i = 0; i < shipped->nhashed; i++) {
Hashed s = shipped->hashed[i];
size_t k = hashed_at(base, s.hash);
if (k < base->nhashed && base->hashed[k].hash == s.hash && base->hashed[k].size >= s.size) continue;
raised += raise_hash(t, s.hash, s.size);
}
if (shipped->name_len != t->name_len) return raised;
for (size_t i = 0; i < shipped->nnamed; i++) {
const uint8_t *e = shipped->named + i * (shipped->name_len + 4);
char key[4097];
memcpy(key, e, shipped->name_len);
key[shipped->name_len] = 0;
uint32_t size = rd32(e + shipped->name_len), have;
if (restbl_get(base, key, &have) && have >= size) continue;
uint8_t *mine = named_of(t, key);
if (mine) {
if (rd32(mine + t->name_len) < size) wr32(mine + t->name_len, size), raised++;
continue;
}
uint8_t *grown = realloc(t->named, (t->nnamed + 1) * (t->name_len + 4));
if (!grown) return raised;
t->named = grown;
memcpy(t->named + t->nnamed * (t->name_len + 4), e, t->name_len + 4);
t->nnamed++;
raised++;
}
return raised;
}
int restbl_take(Restbl *t, const Restbl *from, const char *const *keys, size_t n) {
int raised = 0;
for (size_t i = 0; i < n; i++) {
uint32_t size;
if (restbl_get(from, keys[i], &size)) raised += restbl_raise(t, keys[i], size);
}
return raised;
}
uint8_t *restbl_write(const Restbl *t, size_t *n) {
size_t size = 22 + t->nhashed * 8 + t->nnamed * (t->name_len + 4);
uint8_t *out = malloc(size);
if (!out) return NULL;
memcpy(out, "RESTBL", 6);
wr32(out + 6, t->version);
wr32(out + 10, t->name_len);
wr32(out + 14, (uint32_t)t->nhashed);
wr32(out + 18, (uint32_t)t->nnamed);
for (size_t i = 0; i < t->nhashed; i++) {
wr32(out + 22 + i * 8, t->hashed[i].hash);
wr32(out + 26 + i * 8, t->hashed[i].size);
}
memcpy(out + 22 + t->nhashed * 8, t->named, t->nnamed * (t->name_len + 4));
*n = size;
return out;
}
// ---- estimates
// The factor a type's entry needs over its decompressed size (1000 = 1.0); 0 for a type the table never lists.
static unsigned type_factor(const char *key) {
static const struct { const char *ext; unsigned f; } types[] = {
{"bfres", 1500}, {"bkres", 2050}, {"bgyml", 3850}, {"asb", 1400}, {"bstar", 1200}, {"bphsc", 1100},
{"byml", 1000}, {"txtg", 1000}, {"pack", 1000}, {"bntx", 1000}, {"bphsh", 1000}, {"vsts", 1000},
{"ainb", 1000}, {"bphnm", 1000}, {"bars", 1000}, {"chunk", 1000}, {"bfevfl", 1000}, {"quad", 1000},
{"baev", 1000}, {"bcul", 1000}, {"crbin", 1000}, {"wbr", 1000}, {"bhtmp", 1000}, {"dpi", 1000},
{"cai", 1000}, {"png", 1000}, {"cutinfo", 1000}, {"blwp", 1000}, {"sarc", 1000}, {"tscb", 1000},
{"bfsha", 1000}, {"jpg", 1000}, {"beco", 1000}, {"bfarc", 1000}, {"blarc", 1000}, {"belnk", 1000},
{"genvb", 1000}, {"bnsh", 1000}, {"bslnk", 1000}, {"baatarc", 1000}, {"bagst", 1000},
{"bwav", 0}, {"webm", 0},
};
const char *leaf = strrchr(key, '/') ? strrchr(key, '/') + 1 : key, *dot = strrchr(leaf, '.');
if (!dot) return 1500;
for (size_t i = 0; i < sizeof types / sizeof *types; i++)
if (!strcmp(dot + 1, types[i].ext)) return types[i].f;
return 1500;
}
static uint32_t clamp32(uint64_t v) { return v > 0xFFFFFFF0u ? 0xFFFFFFF0u : (uint32_t)v; }
uint32_t restbl_estimate(const char *key, uint64_t size) {
unsigned f = type_factor(key);
if (!f) return 0;
uint64_t e = (size * f + 999) / 1000 + 8192;
return clamp32((e + 4095) & ~(uint64_t)4095);
}
uint32_t restbl_grow(const char *key, uint32_t entry, uint64_t old, uint64_t new_size, int scaled) {
if (new_size <= old) return entry;
if (scaled) return clamp32(old ? ((uint64_t)entry * new_size + old - 1) / old : restbl_estimate(key, new_size * 8));
unsigned f = type_factor(key);
if (!f) return entry;
uint64_t e = entry + ((new_size - old) * f + 999) / 1000;
return clamp32((e + 31) & ~(uint64_t)31);
}
+33
View File
@@ -0,0 +1,33 @@
// The game's resource size table (restbl.c): System/Resource/ResourceSizeTable.Product.<n>.Nin_NX_NVN.rsizetable.zs, a
// zstd-compressed RESTBL. The game sizes the buffer it loads a file into from the file's entry, so a mod file larger
// than the original needs a larger entry, and a file a mod adds needs one of its own. romfs.c merges the tables the
// mods ship and raises the entries of the files they serve (romfs.c restbl_overlay).
#pragma once
#include <stddef.h>
#include <stdint.h>
typedef struct Restbl Restbl;
// The table of a decompressed RESTBL (copied); NULL when it is not one.
Restbl *restbl_parse(const uint8_t *data, size_t n);
void restbl_free(Restbl *t);
// The table's key of a RomFS path: the path without a trailing .zs or .mc, into buf.
const char *restbl_key(const char *path, char *buf, size_t n);
// 1 with *size when key has an entry.
int restbl_get(const Restbl *t, const char *key, uint32_t *size);
// The entry of key raised to size (added when missing); 1 when the table changed.
int restbl_raise(Restbl *t, const char *key, uint32_t size);
// Every entry of shipped larger than base's (or missing from base) raised in t; the number of entries raised.
int restbl_merge(Restbl *t, const Restbl *base, const Restbl *shipped);
// Each entry of from whose key one of keys[0..n) names, raised in t; the number raised.
int restbl_take(Restbl *t, const Restbl *from, const char *const *keys, size_t n);
// The table as a decompressed RESTBL (malloc'd); NULL when out of memory.
uint8_t *restbl_write(const Restbl *t, size_t *n);
// The entry a file of the key's type and decompressed size needs when the game has none for it; 0 for a type the
// table never lists (streamed sound and video).
uint32_t restbl_estimate(const char *key, uint64_t size);
// The entry of a file the game lists with `entry` for its own copy of old bytes, now new bytes: raised by the growth
// times the type's factor, never lowered. scaled: the sizes are compressed ones (a mesh codec .mc file), whose entry
// grows in proportion.
uint32_t restbl_grow(const char *key, uint32_t entry, uint64_t old, uint64_t new_size, int scaled);
+514 -71
View File
@@ -17,18 +17,33 @@
// TOTK_ROMFS_MODS; unset or "0" = none. A missing path, a size or hash mismatch or a changed original stops the start.
// An overlay file is opened when the game opens it; its identity (volume, file id, size, last write) is kept from the
// start check, and an open that finds another file there stops the game.
//
// Player mods (mods.c): the files under each enabled mod's RomFS root are overlays too, checked by identity only (no
// hash, no manifest). A path several overlays give is served by one: a player mod higher in the order beats a lower
// one, any player mod beats the TOTK_ROMFS_MODS manifest, which beats romfs-patches (overlay_contest). A mod path that
// matches a RomFS path only without case is served under the RomFS spelling.
//
// The resource size table: with a player mod enabled, the game's table is rebuilt at start with the tables the mods
// ship merged in and the entries of the mods' files raised to what they need (restbl_overlay), and served from
// <profile>/mods/ in place of the game's or a mod's table.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include "cfg.h"
#include "fs.h"
#include "host.h"
#include "input_map.h"
#include "mods.h"
#include "romfs_config.h"
#include "romfs_path.h"
#include "platform/platform.h"
#include "restbl.h"
#include "sha256.h"
#include <zstd.h>
#define NH 65536 // RomFS handle slots
#define READ_CHUNK (64u << 20) // largest single read
#define HASH_CHUNK (8u << 20)
@@ -38,7 +53,9 @@ typedef struct { uint64_t offset, size; uint32_t name, len; } Entry;
_Static_assert(sizeof(Entry) == 24, "index entry layout");
typedef struct { uint32_t volume, pad; uint64_t file_id, size, write_time, create_time; } Identity; // no padding
typedef struct { uint64_t index, size; char *path, *name; Identity id; } Overlay;
// prio: which overlay serves a path two of them give (the higher); romfs-patches 0, the TOTK_ROMFS_MODS manifest 1, a
// player mod 2 + its distance from the bottom of the order. mod: its index in mods_at + 1, 0 for any other overlay.
typedef struct { uint64_t index, size; char *path, *name; Identity id; int prio, mod; } Overlay;
static uint8_t *index_bytes;
static size_t index_size;
@@ -56,6 +73,7 @@ static Overlay *overlays; // sorted by RomFS index after overlay_init
static size_t noverlay, overlay_cap;
static char **added; // RomFS paths of the added files, sorted; added[k] is index file_count + k
static size_t nadded;
static int patches_loaded; // a romfs-patches manifest gave a file (romfs_patches_loaded)
static void need(int c, const char *m) {
if (!c) rt_fatal("RomFS: %s", m);
@@ -204,8 +222,8 @@ static uint32_t overlay_slot(uint64_t i) {
// ---- overlays
// Loads and checks one overlay folder. A failed check stops the game, except with optional set (the Xbox prompts
// folder): the folder is dropped, the reason logged, and 0 returned. Returns 1 when the folder is loaded or has no
// manifest.
static int overlay_load(const char *dir, int optional) {
// manifest. prio: the Overlay field (0 for the port's own folders, 1 for the TOTK_ROMFS_MODS manifest).
static int overlay_load(const char *dir, int optional, int prio) {
#define BAD(...) do { if (!optional) rt_fatal(__VA_ARGS__); rt_log(__VA_ARGS__); goto bad; } while (0)
char path[2100];
need(snprintf(path, sizeof path, "%s/manifest.tsv", dir) < (int)sizeof path, "overlay path");
@@ -262,7 +280,8 @@ static int overlay_load(const char *dir, int optional) {
}
char *copy = strdup(file), *rel = strdup(name);
need(copy && rel, "overlay path copy");
overlays[noverlay++] = (Overlay){i, size, copy, rel, id};
overlays[noverlay++] = (Overlay){i, size, copy, rel, id, prio, 0};
if (!prio) patches_loaded = 1;
if (noverlay - first <= 16)
rt_log("RomFS overlay: %s (%llu bytes) %s", name, size, add ? "is added" : "replaces the original");
}
@@ -283,6 +302,207 @@ bad:
#undef BAD
}
// ---- player mods (mods.c): every file under an enabled mod's RomFS root, by identity (no hash: a texture pack is
// gigabytes and the player changes it at will; romfs_open still stops on a file that changed after the start)
static uint32_t *folded; // RomFS indices sorted by name ignoring ASCII case; built on the first mod path that misses
static int folded_order(const void *a, const void *b) {
return strcasecmp(entry_name(entry(*(const uint32_t *)a)), entry_name(entry(*(const uint32_t *)b)));
}
// The RomFS index of name, or of the RomFS path equal to it but for case (a mod made on Windows, where an emulator's
// folder lookup ignores case); UINT64_MAX for a path the RomFS lacks.
static uint64_t index_any_case(const char *name) {
uint64_t i = lower(name);
if (i < file_count && !strcmp(entry_name(entry(i)), name)) return i;
if (!folded) {
folded = malloc(file_count * sizeof *folded);
need(folded != NULL, "case-folded index");
for (uint64_t k = 0; k < file_count; k++) folded[k] = (uint32_t)k;
qsort(folded, file_count, sizeof *folded, folded_order);
}
uint64_t lo = 0, hi = file_count;
while (lo < hi) {
uint64_t m = lo + (hi - lo) / 2;
if (strcasecmp(entry_name(entry(folded[m])), name) < 0) lo = m + 1;
else hi = m;
}
return lo < file_count && !strcasecmp(entry_name(entry(folded[lo])), name) ? folded[lo] : UINT64_MAX;
}
static void overlay_push(Overlay o) {
if (noverlay == overlay_cap) {
overlay_cap = overlay_cap ? overlay_cap * 2 : 16;
overlays = realloc(overlays, overlay_cap * sizeof *overlays);
need(overlays != NULL, "overlay table");
}
overlays[noverlay++] = o;
}
// 1 when path names a file of one game version only (Product.<n> in a name: the resource size table, the actor
// database and other version-bound files); the RomFS lacking it means it is another version's.
static int other_version(const char *path) {
for (const char *p = strstr(path, ".Product."); p; p = strstr(p + 1, ".Product.")) {
const char *d = p + strlen(".Product.");
if (*d >= '0' && *d <= '9') return 1;
}
return 0;
}
// ---- the resource size table's inputs: the tables the overlays carry, before overlay_contest keeps one of them
static char restbl_rel[256]; // the RomFS path of the game's table, "" when it has none
typedef struct {
char *file;
int mod, other; // mod: ModInfo index + 1, 0 for the port's folders; other: made for another game version
} Shipped;
static Shipped *shipped;
static size_t nshipped;
static int ends_with(const char *s, const char *tail) {
size_t n = strlen(s), k = strlen(tail);
return n >= k && !strcmp(s + n - k, tail);
}
// 1 when rel is a resource size table of any game version.
static int is_restbl(const char *rel) {
return !strncmp(rel, "System/Resource/ResourceSizeTable.", 34) && ends_with(rel, ".rsizetable.zs");
}
static void shipped_add(const char *file, int mod, int other) {
Shipped *grown = realloc(shipped, (nshipped + 1) * sizeof *shipped);
char *copy = strdup(file);
need(grown && copy, "resource size table list");
shipped = grown;
shipped[nshipped++] = (Shipped){copy, mod, other};
}
// The game's table: the one System/Resource/ResourceSizeTable.*.rsizetable.zs of the RomFS.
static void restbl_find(void) {
for (uint64_t i = lower("System/Resource/ResourceSizeTable."); i < file_count; i++) {
const char *n = entry_name(entry(i));
if (strncmp(n, "System/Resource/ResourceSizeTable.", 34)) break;
if (is_restbl(n) && strlen(n) < sizeof restbl_rel) {
snprintf(restbl_rel, sizeof restbl_rel, "%s", n);
return;
}
}
}
// The tables the overlays carry for this game version, every one of them (overlay_contest keeps one).
static void restbl_collect(void) {
for (size_t k = 0; k < noverlay; k++)
if (restbl_rel[0] && !strcmp(overlays[k].name, restbl_rel)) shipped_add(overlays[k].path, overlays[k].mod, 0);
}
typedef struct { int k, prio; const char *dir, *rel; } ModWalk;
static void mod_walk(int k, int prio, const char *dir, const char *rel);
// One entry of a mod's RomFS folder (mod_walk).
static int mod_walk_cb(const char *leaf, int kind, uint64_t size, void *ctx) {
(void)size;
const ModWalk *w = ctx;
ModInfo *m = mods_at(w->k);
char file[4200], path[4200];
if (snprintf(file, sizeof file, "%s/%s", w->dir, leaf) >= (int)sizeof file ||
snprintf(path, sizeof path, "%s%s%s", w->rel, *w->rel ? "/" : "", leaf) >= (int)sizeof path) {
rt_log("mods: %s: path too long under %s; left out", m->name, w->dir);
return 1;
}
if (kind == PLAT_FS_DIR) {
mod_walk(w->k, w->prio, file, path);
return 1;
}
if (kind != PLAT_FS_FILE) return 1;
if (!romfs_path_valid_relative(path)) {
rt_log("mods: %s: %s is not a RomFS path; left out", m->name, path);
return 1;
}
uint64_t i = index_any_case(path);
if (i == UINT64_MAX && other_version(path)) {
if (is_restbl(path)) shipped_add(file, w->k + 1, 1); // its entries for this mod's files still apply
m->other_version++;
return 1;
}
PlatFile *f = open_read(file);
if (!f) {
rt_log("mods: %s: cannot open %s; left out", m->name, file);
return 1;
}
Identity id = identity_of(f);
plat_file_close(f);
char *copy = strdup(file), *rp = strdup(i == UINT64_MAX ? path : entry_name(entry(i)));
need(copy && rp, "overlay path copy");
overlay_push((Overlay){i == UINT64_MAX ? ADDED : i, id.size, copy, rp, id, w->prio, w->k + 1});
return 1;
}
// The files under dir (a mod's RomFS root; rel: the RomFS path of dir, "" at the root) as overlays of mod k.
static void mod_walk(int k, int prio, const char *dir, const char *rel) {
ModWalk w = {k, prio, dir, rel};
plat_fs_list(dir, mod_walk_cb, &w);
}
// What overlays compete on: the RomFS index, an added file's path; the higher prio first.
static int contest_order(const void *a, const void *b) {
const Overlay *x = a, *y = b;
if (x->index != y->index) return (x->index > y->index) - (x->index < y->index);
int c = x->index == ADDED ? strcmp(x->name, y->name) : 0;
return c ? c : y->prio - x->prio;
}
static const char *owner_name(const Overlay *o) {
return o->mod ? mods_at(o->mod - 1)->name : o->prio ? "romfs_mods" : "the port's patches";
}
// One overlay per path: the highest prio serves it; the others are dropped and counted on their mod.
static void overlay_contest(void) {
if (!noverlay) return;
qsort(overlays, noverlay, sizeof *overlays, contest_order);
size_t kept = 0;
for (size_t k = 0; k < noverlay; k++) {
Overlay *o = &overlays[k], *w = kept ? &overlays[kept - 1] : NULL;
if (w && w->index == o->index && (o->index != ADDED || !strcmp(w->name, o->name))) {
if (o->mod) {
ModInfo *m = mods_at(o->mod - 1);
m->overridden++;
if (!m->overridden_by[0]) snprintf(m->overridden_by, sizeof m->overridden_by, "%s", owner_name(w));
} else if (w->mod) {
rt_log("RomFS overlay: %s from mod %s replaces the one of %s", o->name, owner_name(w), owner_name(o));
}
free(o->path);
free(o->name);
continue;
}
if (o->mod) {
if (o->index == ADDED) mods_at(o->mod - 1)->added++;
else mods_at(o->mod - 1)->replaced++;
}
overlays[kept++] = *o;
}
noverlay = kept;
}
static void mods_overlay_init(void) {
mods_scan();
int n = mods_count();
for (int k = 0; k < n; k++) {
const ModInfo *m = mods_at(k);
// a mod with ExeFS patches waits for the rebuild that applies them: half of a mod is worse than none
if (m->enabled && (m->kind & MOD_ROMFS) && m->problem == MOD_OK) mod_walk(k, 2 + (n - k), m->romfs, "");
}
}
static void mods_overlay_log(void) {
for (int k = 0; k < mods_count(); k++) {
const ModInfo *m = mods_at(k);
if (!m->enabled || !(m->kind & MOD_ROMFS) || m->problem != MOD_OK) continue;
rt_log("mods: %s: %u files served (%u replaced, %u added), %u overridden%s%s, %u for another game version",
m->name, m->replaced + m->added, m->replaced, m->added, m->overridden, m->overridden ? " by " : "",
m->overridden_by, m->other_version);
}
}
static int overlay_order(const void *a, const void *b) {
uint64_t x = ((const Overlay *)a)->index, y = ((const Overlay *)b)->index;
return (x > y) - (x < y);
@@ -292,7 +512,7 @@ static int added_order(const void *a, const void *b) {
return strcmp((*(Overlay *const *)a)->name, (*(Overlay *const *)b)->name);
}
// Number the added files in path order after the RomFS's own (file_count + k); two overlays adding one path stop.
// Number the added files in path order after the RomFS's own (file_count + k); overlay_contest left one per path.
static void added_init(void) {
Overlay **list = NULL;
for (size_t k = 0; k < noverlay; k++)
@@ -306,8 +526,6 @@ static void added_init(void) {
added = malloc(nadded * sizeof *added);
need(added != NULL, "added files");
for (size_t k = 0; k < nadded; k++) {
if (k && !strcmp(list[k]->name, list[k - 1]->name))
rt_fatal("RomFS overlay: %s and %s both add %s", list[k - 1]->path, list[k]->path, list[k]->name);
list[k]->index = file_count + k;
added[k] = list[k]->name;
}
@@ -315,40 +533,46 @@ static void added_init(void) {
rt_log("RomFS overlay: %zu files added to the RomFS", nadded);
}
// The HeapDef table a bigger game resolution needs (resolution.c): its texture heap and that heap's parent grow. The
// base is an overlay that replaces the table (a mod's heap sizes stay), else the RomFS original; the grown table is
// written to <profile>/resolution/ and served in the base's place.
#define HEAPDEF "System/HeapSize/Product.Nin_NX_NVN.HeapDef.byml.zs"
static void heapdef_overlay(void) {
if (!res_heap_extra_kib()) return;
uint64_t i = lower(HEAPDEF);
if (i >= file_count || strcmp(entry_name(entry(i)), HEAPDEF)) {
rt_log("RomFS: %s missing; the game keeps its own resolution", HEAPDEF);
return;
// RomFS file `rel` as the game would read it: from an overlay that replaces it (*base), else from the image. malloc'd;
// NULL when it is missing, unreadable or 16 MiB or more (logged with `keeps`, what the game does without it).
static void *read_served(const char *rel, Overlay **base, size_t *n, const char *keeps) {
uint64_t i = lower(rel);
*base = NULL;
if (i >= file_count || strcmp(entry_name(entry(i)), rel)) {
rt_log("RomFS: %s missing; %s", rel, keeps);
return NULL;
}
Overlay *base = NULL;
for (size_t k = 0; k < noverlay; k++)
if (overlays[k].index == i) base = &overlays[k];
PlatFile *f = base ? open_read(base->path) : image;
uint64_t off = base ? 0 : entry(i).offset, n = base ? base->size : entry(i).size;
void *in = n && n < (16u << 20) && f ? malloc((size_t)n) : NULL;
int ok = in && read_at(f, in, (uint32_t)n, off) == (int64_t)n;
if (base && f) plat_file_close(f);
void *out = NULL;
size_t out_n = 0;
ok = ok && res_heapdef_build(in, (size_t)n, &out, &out_n);
free(in);
if (!ok) return;
if (overlays[k].index == i) *base = &overlays[k];
PlatFile *f = *base ? open_read((*base)->path) : image;
uint64_t off = *base ? 0 : entry(i).offset, size = *base ? (*base)->size : entry(i).size;
void *in = size && size < (16u << 20) && f ? malloc((size_t)size) : NULL;
int ok = in && read_at(f, in, (uint32_t)size, off) == (int64_t)size;
if (*base && f) plat_file_close(f);
if (!ok) {
free(in);
rt_log("RomFS: cannot read %s; %s", rel, keeps);
return NULL;
}
*n = (size_t)size;
return in;
}
// Serves out[0..out_n) (malloc'd, freed here) in place of RomFS file `rel` and of an overlay that replaces it (base):
// written to <profile>/<sub>/<file name of rel>. `what` names the change in the log. 0 when it cannot be written.
static int serve_generated(const char *rel, Overlay *base, void *out, size_t out_n, const char *sub, const char *what,
const char *keeps) {
char dir[2100], file[2200];
need(snprintf(dir, sizeof dir, "%s/resolution", rt_config()->profile) < (int)sizeof dir, "resolution path");
need(snprintf(file, sizeof file, "%s/Product.Nin_NX_NVN.HeapDef.byml.zs", dir) < (int)sizeof file, "resolution path");
const char *leaf = strrchr(rel, '/') ? strrchr(rel, '/') + 1 : rel;
need(snprintf(dir, sizeof dir, "%s/%s", rt_config()->profile, sub) < (int)sizeof dir, "generated overlay path");
need(snprintf(file, sizeof file, "%s/%s", dir, leaf) < (int)sizeof file, "generated overlay path");
plat_file_mkdir_p(dir);
ok = plat_file_write(file, out, out_n);
int ok = plat_file_write(file, out, out_n);
free(out);
PlatFile *r = ok ? open_read(file) : NULL;
if (!r) {
rt_log("RomFS: cannot write %s; the game keeps its own resolution", file);
return;
rt_log("RomFS: cannot write %s; %s", file, keeps);
return 0;
}
Identity id = identity_of(r);
plat_file_close(r);
@@ -365,31 +589,217 @@ static void heapdef_overlay(void) {
overlays = realloc(overlays, overlay_cap * sizeof *overlays);
need(overlays != NULL, "overlay table");
}
char *rel = strdup(HEAPDEF);
need(rel != NULL, "overlay path copy");
overlays[noverlay++] = (Overlay){i, out_n, copy, rel, id};
char *name = strdup(rel);
need(name != NULL, "overlay path copy");
overlays[noverlay++] = (Overlay){lower(rel), out_n, copy, name, id};
}
rt_log("RomFS overlay: %s (%zu bytes, grown heaps) replaces %s", file, out_n, base ? "the mod's table" : "the original");
res_heapdef_served();
rt_log("RomFS overlay: %s (%zu bytes, %s) replaces %s", file, out_n, what, base ? "the mod's file" : "the original");
return 1;
}
static int xbox_prompts_ready; // romfs-patches-xbox/manifest.tsv was next to romfs-index.bin at start
static int xbox_prompts_active; // and overlay_init loaded it
// ---- the resource size table (restbl.c)
int romfs_xbox_prompts_ready(void) { return xbox_prompts_ready; }
int romfs_xbox_prompts_active(void) { return xbox_prompts_active; }
// The decompressed size of a file's bytes as the game unpacks them: the content size its zstd frame records (.zs;
// the game's files and zstd's own tools write it), four times the bytes for a frame without one, else its size.
static uint64_t content_size(PlatFile *f, uint64_t off, uint64_t size, const char *rel) {
if (!ends_with(rel, ".zs") || !f) return size;
uint8_t head[18];
uint32_t n = size < sizeof head ? (uint32_t)size : (uint32_t)sizeof head;
if (read_at(f, head, n, off) != n) return size;
unsigned long long c = ZSTD_getFrameContentSize(head, n);
return c == ZSTD_CONTENTSIZE_ERROR ? size : c == ZSTD_CONTENTSIZE_UNKNOWN ? size * 4 : c;
}
// A table from its zstd bytes; NULL when they are not one.
static Restbl *restbl_unpack(const void *z, size_t n) {
unsigned long long raw = ZSTD_getFrameContentSize(z, n);
if (raw == ZSTD_CONTENTSIZE_UNKNOWN || raw == ZSTD_CONTENTSIZE_ERROR || raw > (64u << 20)) return NULL;
uint8_t *d = malloc((size_t)raw ? (size_t)raw : 1);
size_t got = d ? ZSTD_decompress(d, (size_t)raw, z, n) : 0;
Restbl *t = d && !ZSTD_isError(got) && got == raw ? restbl_parse(d, (size_t)raw) : NULL;
free(d);
return t;
}
// With a player mod (or the TOTK_ROMFS_MODS manifest) serving files: the game's table with every shipped table of this
// version merged in (an entry larger than the game's wins), the entries a mod's table for another version gives for
// that mod's files, and each served mod file's entry raised to what its size needs (restbl_grow for a file the game
// has, restbl_estimate for an added one). Never lowers the game's entries.
static void restbl_overlay(void) {
int player = 0;
for (size_t k = 0; k < noverlay; k++) player |= overlays[k].mod || overlays[k].prio == 1;
if (!player || !restbl_rel[0]) return;
static const char keeps[] = "mod files that grew may fail to load";
double t0 = now_s();
uint64_t gi = lower(restbl_rel);
Entry ge = entry(gi);
void *gz = ge.size < (64u << 20) ? malloc((size_t)ge.size) : NULL;
Restbl *base = NULL, *out = NULL;
if (gz && read_at(image, gz, (uint32_t)ge.size, ge.offset) == (int64_t)ge.size) {
base = restbl_unpack(gz, (size_t)ge.size);
out = restbl_unpack(gz, (size_t)ge.size);
}
free(gz);
if (!base || !out) {
rt_log("RomFS: cannot read the resource size table %s; %s", restbl_rel, keeps);
restbl_free(base);
restbl_free(out);
return;
}
int tables = 0, merged = 0, raised = 0, estimated = 0;
for (size_t s = 0; s < nshipped; s++) {
uint64_t n = 0;
void *z = plat_file_read(shipped[s].file, &n);
Restbl *t = z ? restbl_unpack(z, (size_t)n) : NULL;
free(z);
if (!t) {
rt_log("RomFS: %s is not a resource size table; left out", shipped[s].file);
continue;
}
tables++;
if (!shipped[s].other) {
merged += restbl_merge(out, base, t);
} else { // another version's table: only the entries of the files its mod serves
for (size_t k = 0; k < noverlay; k++) {
char key[4200];
const char *kp = restbl_key(overlays[k].name, key, sizeof key);
if (overlays[k].mod == shipped[s].mod) merged += restbl_take(out, t, &kp, 1);
}
}
restbl_free(t);
}
Overlay *served = NULL;
for (size_t k = 0; k < noverlay; k++) {
Overlay *o = &overlays[k];
if (o->index == gi) served = o;
if ((!o->mod && o->prio != 1) || o->index == gi) continue;
char key[4200];
restbl_key(o->name, key, sizeof key);
int mc = ends_with(o->name, ".mc");
PlatFile *f = open_read(o->path);
uint64_t now = mc ? o->size : content_size(f, 0, o->size, o->name);
if (f) plat_file_close(f);
uint32_t entry_size, want;
if (o->index != ADDED) {
if (!restbl_get(base, key, &entry_size)) continue; // the game sizes it without the table (streamed)
Entry e = entry(o->index);
uint64_t was = mc ? e.size : content_size(image, e.offset, e.size, o->name);
want = restbl_grow(key, entry_size, was, now, mc);
} else {
want = restbl_estimate(key, mc ? now * 8 : now); // a mesh codec file unpacks to several times its size
estimated += want != 0;
}
raised += want && restbl_raise(out, key, want);
}
restbl_free(base);
if (!merged && !raised && !served) {
restbl_free(out);
rt_log("RomFS: resource size table: the mods' files fit the game's entries (%.0f ms)", (now_s() - t0) * 1000);
return;
}
size_t rn = 0, zn = 0;
uint8_t *raw = restbl_write(out, &rn);
restbl_free(out);
size_t cap = raw ? ZSTD_compressBound(rn) : 0;
void *z = raw ? malloc(cap) : NULL;
if (z) zn = ZSTD_compress(z, cap, raw, rn, 3);
free(raw);
if (!z || ZSTD_isError(zn)) {
free(z);
rt_log("RomFS: cannot pack the merged resource size table; %s", keeps);
return;
}
if (serve_generated(restbl_rel, served, z, zn, "mods", "merged resource sizes", keeps))
rt_log("RomFS: resource size table: %d tables merged (%d entries), %d entries raised for mod files (%d "
"added files estimated), %.0f ms", tables, merged, raised, estimated, (now_s() - t0) * 1000);
}
// The HeapDef table a bigger game resolution needs (resolution.c): its texture heap and that heap's parent grow. The
// base is an overlay that replaces the table (a mod's heap sizes stay), else the RomFS original; the grown table is
// written to <profile>/resolution/ and served in the base's place.
#define HEAPDEF "System/HeapSize/Product.Nin_NX_NVN.HeapDef.byml.zs"
static void heapdef_overlay(void) {
if (!res_heap_extra_kib()) return;
static const char keeps[] = "the game keeps its own resolution";
Overlay *base;
size_t n;
void *in = read_served(HEAPDEF, &base, &n, keeps), *out = NULL;
size_t out_n = 0;
int ok = in && res_heapdef_build(in, n, &out, &out_n);
free(in);
if (ok && serve_generated(HEAPDEF, base, out, out_n, "resolution", "grown heaps", keeps)) res_heapdef_served();
}
// The player camera's pack with its stick speeds multiplied by TOTK_STICK_SENS (camera_speed.c). The base is an
// overlay that replaces the pack (a mod's camera stays), else the RomFS original; the dictionary is the RomFS's own.
#define CAMPACK "Pack/Actor/PlayerCamera.pack.zs"
static void camera_overlay(void) {
if (cam_speed_wanted() == 1.0f) return;
static const char keeps[] = "the camera keeps its own speed";
Overlay *base, *dic_base;
size_t n, dn;
void *in = read_served(CAMPACK, &base, &n, keeps), *out = NULL;
void *dic = in ? read_served("Pack/ZsDic.pack.zs", &dic_base, &dn, keeps) : NULL;
size_t out_n = 0;
int ok = in && dic && cam_pack_build(in, n, dic, dn, &out, &out_n);
free(in);
free(dic);
if (ok && serve_generated(CAMPACK, base, out, out_n, "camera", "camera speed", keeps)) cam_pack_served();
}
// The button prompts' folders (input_prompts_folder) and whether each had a manifest next to romfs-index.bin at start;
// the one the settings asked for at start, the one overlay_init loaded (NULL: the game's own prompts) and why the first
// did not load (ROMFS_PROMPTS_*). The menu compares them with the settings in effect (ui/menu.cpp prompts_note).
static struct { const char *name; int ready; } prompts_folders[2];
static const char *prompts_wanted, *prompts_loaded;
static int prompts_off;
const char *romfs_prompts(void) { return prompts_loaded; }
int romfs_prompts_ready(const char *folder) {
for (int i = 0; i < 2; i++)
if (folder && prompts_folders[i].name && !strcmp(prompts_folders[i].name, folder)) return prompts_folders[i].ready;
return 0;
}
int romfs_prompts_off(const char *folder) {
return folder && prompts_wanted && !strcmp(folder, prompts_wanted) ? prompts_off : ROMFS_PROMPTS_OK;
}
// The first RomFS file that the overlays [a, b) and [c, d) both replace, or NULL.
static const char *overlay_clash(size_t a, size_t b, size_t c, size_t d) {
for (size_t i = a; i < b; i++)
for (size_t j = c; j < d; j++)
if (overlays[i].index != ADDED && overlays[i].index == overlays[j].index &&
strcmp(overlays[i].name, restbl_rel)) // restbl_overlay merges both tables
return overlays[i].name;
return NULL;
}
// Drops the overlays [a, b), the ones after them moving down.
static void overlay_drop(size_t a, size_t b) {
for (size_t k = a; k < b; k++) {
free((void *)overlays[k].path);
free((void *)overlays[k].name);
}
memmove(overlays + a, overlays + b, (noverlay - b) * sizeof *overlays);
noverlay -= b - a;
}
static void overlay_init(void) {
// TOTK_ROMFS_PATCHES unset: romfs-patches next to romfs-index.bin if it has a manifest (tools/make_romfs_patches.py).
// A game resolution that is not 16:9 takes romfs-patches-<w>x<h> instead when it is there: the same overlay with
// the UI laid out for that shape (make_romfs_patches.py --aspect), when the game version has the camera aspect patch
// the layout goes with (res_wants_wide_overlay).
// With pad_layout = xbox_prompts, romfs-patches-xbox in its place: the same patches with the A/B and X/Y prompts
// swapped (make_romfs_patches.py --xbox-prompts). The game reads the archives once at boot, so the prompts stay
// until restart even though the layout itself changes live. Each folder replaces romfs-patches as a whole and the
// setup builds no wide folder with Xbox prompts, so a wide game resolution keeps the Switch prompts.
char def[2100], xbox[2100];
const char *patches = cfg_get("TOTK_ROMFS_PATCHES");
// With prompts = xbox, the Xbox prompts' folder for the pad layout in its place (input_prompts_folder): the same
// patches with Xbox button icons (make_romfs_patches.py --prompts). The game reads the archives once at boot, so
// the prompts stay until restart even though the layout itself changes live. Each folder replaces romfs-patches as
// a whole and the setup builds no folder of another shape with Xbox prompts, so a game resolution that is not 16:9
// keeps the Switch prompts. So does a RomFS mod (the TOTK_ROMFS_MODS manifest or a player mod) that replaces one of
// the prompts' fonts: romfs-patches loads in their place, so the mod's file is not served beside prompts files made
// for the game's own. A mod's resource size table is no clash: restbl_overlay merges it with the prompts' one.
char def[2100], path[2100];
const char *patches = cfg_get("TOTK_ROMFS_PATCHES"), *mods = cfg_get("TOTK_ROMFS_MODS");
int wide = 0;
unsigned out[2];
res_wanted(out);
@@ -403,33 +813,64 @@ static void overlay_init(void) {
"(tools/make_romfs_patches.py --aspect %ux%u)", out[0], out[1], out[0], out[1]);
}
}
xbox_prompts_ready =
snprintf(xbox, sizeof xbox, "%s/romfs-patches-xbox/manifest.tsv", index_dir) < (int)sizeof xbox &&
plat_file_exists(xbox);
int want_xbox = !strcasecmp(cfg_value("TOTK_PAD_LAYOUT"), "xbox_prompts");
if (!patches && want_xbox && xbox_prompts_ready) {
xbox[strlen(xbox) - strlen("/manifest.tsv")] = 0;
xbox_prompts_active = overlay_load(xbox, 1);
if (xbox_prompts_active) rt_log("RomFS overlay: Xbox button prompts (%s)", xbox);
else rt_log("RomFS overlay: %s failed its check (run the setup again); romfs-patches loads instead", xbox);
} else if (want_xbox) {
rt_log("RomFS overlay: pad_layout = xbox_prompts, but %s; Switch prompts stay",
wide ? "the game resolution takes the wide UI layout"
: patches ? "TOTK_ROMFS_PATCHES is set"
: "romfs-patches-xbox has no manifest.tsv (run the setup again)");
static const char *const layouts[2] = {"nintendo", "xbox"}; // one of each folder
for (int i = 0; i < 2; i++) {
prompts_folders[i].name = input_prompts_folder(PROMPTS_XBOX, layouts[i]);
prompts_folders[i].ready =
snprintf(path, sizeof path, "%s/%s/manifest.tsv", index_dir, prompts_folders[i].name) < (int)sizeof path &&
plat_file_exists(path);
}
if (!patches && !xbox_prompts_active && snprintf(def, sizeof def, "%s/romfs-patches/manifest.tsv", index_dir) < (int)sizeof def &&
plat_file_exists(def)) {
def[strlen(def) - strlen("/manifest.tsv")] = 0;
patches = def;
const char *layout = cfg_value("TOTK_PAD_LAYOUT");
prompts_wanted = input_prompts_folder(input_prompts_pick(cfg_get("TOTK_PROMPTS"), layout), layout);
prompts_off = !prompts_wanted ? ROMFS_PROMPTS_OK
: wide ? ROMFS_PROMPTS_SHAPE
: patches ? ROMFS_PROMPTS_PATCHES
: !romfs_prompts_ready(prompts_wanted) ? ROMFS_PROMPTS_MISSING
: ROMFS_PROMPTS_OK;
restbl_find();
size_t first = noverlay;
if (prompts_wanted && prompts_off == ROMFS_PROMPTS_OK) {
snprintf(path, sizeof path, "%s/%s", index_dir, prompts_wanted); // fits: its manifest path did
if (overlay_load(path, 1, 0)) {
prompts_loaded = prompts_wanted;
rt_log("RomFS overlay: Xbox button prompts (%s)", path);
} else {
prompts_off = ROMFS_PROMPTS_FAILED;
rt_log("RomFS overlay: %s failed its check (run the setup again); romfs-patches loads instead", path);
}
} else if (prompts_wanted) {
rt_log("RomFS overlay: prompts = xbox, but %s; Switch prompts stay",
prompts_off == ROMFS_PROMPTS_SHAPE ? "the game resolution takes its own UI layout"
: prompts_off == ROMFS_PROMPTS_PATCHES ? "TOTK_ROMFS_PATCHES is set"
: "their folder has no manifest.tsv (run the setup again)");
}
const char *dirs[2] = {patches, cfg_get("TOTK_ROMFS_MODS")};
for (int i = 0; i < 2; i++)
if (dirs[i] && *dirs[i] && strcmp(dirs[i], "0")) overlay_load(dirs[i], 0);
size_t prompts_end = noverlay;
char plain[2100]; // romfs-patches, when it has a manifest
int plain_ok = snprintf(plain, sizeof plain, "%s/romfs-patches/manifest.tsv", index_dir) < (int)sizeof plain &&
plat_file_exists(plain);
if (plain_ok) plain[strlen(plain) - strlen("/manifest.tsv")] = 0;
if (!patches && !prompts_loaded && plain_ok) patches = plain;
if (patches && *patches && strcmp(patches, "0")) overlay_load(patches, 0, 0);
size_t mods_first = noverlay;
if (mods && *mods && strcmp(mods, "0")) overlay_load(mods, 0, 1);
mods_overlay_init();
const char *clash = prompts_loaded ? overlay_clash(first, prompts_end, mods_first, noverlay) : NULL;
if (clash) {
rt_log("RomFS overlay: a RomFS mod replaces %s, which the Xbox prompts change too; Switch prompts stay", clash);
overlay_drop(first, prompts_end);
prompts_loaded = NULL;
prompts_off = ROMFS_PROMPTS_MODS;
if (plain_ok) overlay_load(plain, 0, 0);
}
restbl_collect();
overlay_contest();
mods_overlay_log();
restbl_overlay();
heapdef_overlay();
camera_overlay();
added_init();
if (noverlay) qsort(overlays, noverlay, sizeof *overlays, overlay_order);
for (size_t k = 1; k < noverlay; k++)
for (size_t k = 1; k < noverlay; k++) // overlay_contest left one per file; the generated ones replace in place
if (overlays[k].index == overlays[k - 1].index)
rt_fatal("RomFS overlay: %s and %s replace the same file %s", overlays[k - 1].path, overlays[k].path,
overlays[k].name);
@@ -551,6 +992,8 @@ const char *romfs_image_path(void) { return image_file; }
size_t romfs_overlay_count(void) { return noverlay; }
int romfs_patches_loaded(void) { return patches_loaded; }
const char *romfs_overlay(size_t k, const char **file, uint64_t *size, int *is_added) {
if (k >= noverlay) return NULL;
*file = overlays[k].path;
+67
View File
@@ -0,0 +1,67 @@
#version 450
// Screen-space contact shadows (runtime/vk_contact.c). Each pixel of the game's lit scene colour marches a short way
// toward the sun through the linear depth target; when the ray passes behind something close in front of it, the pixel
// is in a contact shadow the shadow maps are too coarse to show, and its colour is darkened.
layout(local_size_x = 8, local_size_y = 8) in;
layout(binding = 0) uniform sampler2D lin_depth; // the game's linear depth: view distance / far
layout(binding = 1, r11f_g11f_b10f) uniform image2D scene; // the lit scene colour, darkened in place
layout(push_constant) uniform Params {
vec4 proj; // projection x scale, y scale, far plane, strength (0..1)
vec4 light; // view-space direction toward the sun (xyz), march length in metres at 10 m (w)
vec4 size; // width, height, 1/width, 1/height
vec4 opt; // x: debug (1: write the shadow factor as grey)
} pc;
vec3 view_pos(vec2 uv, float z) { // z: distance in front of the camera
vec2 ndc = uv * 2.0 - 1.0;
return vec3(ndc.x * z / pc.proj.x, -ndc.y * z / pc.proj.y, -z);
}
vec2 to_uv(vec3 p) {
float z = -p.z;
return vec2(0.5 + 0.5 * p.x * pc.proj.x / z, 0.5 - 0.5 * p.y * pc.proj.y / z);
}
float ign(vec2 px) { // interleaved gradient noise: a per-pixel start offset that hides the step pattern
return fract(52.9829189 * fract(dot(px, vec2(0.06711056, 0.00583715))));
}
void main() {
ivec2 px = ivec2(gl_GlobalInvocationID.xy);
if (px.x >= int(pc.size.x) || px.y >= int(pc.size.y)) return;
float d = texelFetch(lin_depth, px, 0).x;
if (d <= 0.0 || d >= 0.999) return; // nothing drawn, or the sky
float z = d * pc.proj.z;
if (z > 80.0) return;
vec2 uv = (vec2(px) + 0.5) * pc.size.zw;
vec3 p = view_pos(uv, z);
// the march grows with distance, as one pixel covers more ground; thickness keeps thin blades from hiding the sky
float len = pc.light.w * clamp(z / 10.0, 0.4, 3.0);
float thick = 0.15 + z * 0.01;
const int STEPS = 16;
float step_len = len / float(STEPS), t = step_len * (0.25 + ign(vec2(px)));
float occ = 0.0;
for (int i = 0; i < STEPS; i++, t += step_len) {
vec3 q = p + pc.light.xyz * t;
if (q.z >= -0.05) break;
vec2 quv = to_uv(q);
if (any(lessThan(quv, vec2(0.0))) || any(greaterThan(quv, vec2(1.0)))) break;
float sz = texelFetch(lin_depth, ivec2(quv * pc.size.xy), 0).x * pc.proj.z;
float delta = -q.z - sz; // how far the scene at that pixel is in front of the ray point
if (delta > 0.02 + z * 0.002 && delta < thick) {
occ = 1.0 - float(i) / float(STEPS); // a hit close to the pixel shadows more than one at the end
break;
}
}
float fade = 1.0 - smoothstep(40.0, 80.0, z);
float k = 1.0 - pc.proj.w * occ * fade;
if (pc.opt.x > 0.5) {
imageStore(scene, px, vec4(k, k, k, 1.0));
return;
}
if (k >= 0.999) return;
vec4 c = imageLoad(scene, px);
imageStore(scene, px, vec4(c.rgb * k, c.a));
}
+63
View File
@@ -0,0 +1,63 @@
#version 450
// Camera motion vectors for DLAA (vk_dlaa.c mv_pass): each pixel's depth is taken back to the world through this
// frame's view-projection and forward through last frame's; the vector is last frame's window position minus this
// frame's, in render pixels, without the jitter (DLSS's default convention). Objects that move on their own get only
// the camera's motion.
// The camera block is TotK's scene uniform block (bound as c4 in the scene's vertex shaders): vec4 rows 3-6 are the
// view-projection, rows of a row-major 4x4 with OpenGL clip depth (-w..w). The replay's viewports have negative
// heights, so window y grows downwards from ndc y = +1, and depth is z_ndc * 0.5 + 0.5.
// With pc.bias > 0 the pass also writes DLSS's bias mask (vk_dlaa.c, "characters"): G-buffer target 0 carries an object
// class in green, above 64/255 for characters, creatures and what they hold (Link 253, others 125, held items 160;
// terrain 0, foliage 32). A pixel gets pc.bias when a character covers it now, or covered the place its surface came
// from last frame (the previous class mask, read through the motion vector, 3x3): there the history holds a moving
// character that the camera-only vector does not follow, which is the trail. chars_out keeps this frame's mask for the
// next; chars_prev is last frame's (pc.prev_ok 0: none).
layout(local_size_x = 8, local_size_y = 8) in;
layout(binding = 0) uniform sampler2D depth_tex;
layout(binding = 1, rg16f) uniform writeonly image2D mv_out;
layout(binding = 2, std140) uniform Cur { vec4 r[16]; } cur;
layout(binding = 3, std140) uniform Prev { vec4 r[16]; } prev;
layout(binding = 4) uniform sampler2D ids_tex;
layout(binding = 5, r8) uniform writeonly image2D mask_out;
layout(binding = 6, r8) uniform readonly image2D chars_prev;
layout(binding = 7, r8) uniform writeonly image2D chars_out;
layout(push_constant) uniform P {
vec2 size; // render size in pixels
vec2 jitter; // this frame's jitter, pixels, as the scene was drawn (window x right, y down)
float bias; // the mask value for character pixels; 0: no mask (bindings 4-7 unused)
float prev_ok; // 1: chars_prev holds last frame's class mask at this size
} pc;
mat4 vp(vec4 a, vec4 b, vec4 c, vec4 d) { return transpose(mat4(a, b, c, d)); }
void main() {
ivec2 p = ivec2(gl_GlobalInvocationID.xy);
if (p.x >= int(pc.size.x) || p.y >= int(pc.size.y)) return;
float d = texelFetch(depth_tex, p, 0).r;
vec2 win = vec2(p) + 0.5 - pc.jitter; // where this pixel's surface sits without the jitter
vec4 ndc = vec4(win.x / pc.size.x * 2.0 - 1.0, 1.0 - win.y / pc.size.y * 2.0, d * 2.0 - 1.0, 1.0);
mat4 c = vp(cur.r[3], cur.r[4], cur.r[5], cur.r[6]);
mat4 q = vp(prev.r[3], prev.r[4], prev.r[5], prev.r[6]);
vec4 world = inverse(c) * ndc;
vec2 mv = vec2(0.0);
if (abs(world.w) > 1e-12) {
vec4 clip = q * (world / world.w);
if (clip.w > 1e-6) {
vec2 pn = clip.xy / clip.w;
vec2 pwin = vec2((pn.x * 0.5 + 0.5) * pc.size.x, (0.5 - pn.y * 0.5) * pc.size.y);
mv = pwin - win;
}
}
imageStore(mv_out, p, vec4(mv, 0.0, 0.0));
if (pc.bias <= 0.0) return;
float ch = texelFetch(ids_tex, p, 0).g > 64.0 / 255.0 ? 1.0 : 0.0;
imageStore(chars_out, p, vec4(ch));
float was = 0.0;
if (pc.prev_ok > 0.5) {
ivec2 q = ivec2(floor(win + mv)), hi = ivec2(pc.size) - 1;
for (int dy = -1; dy <= 1; dy++)
for (int dx = -1; dx <= 1; dx++)
was = max(was, imageLoad(chars_prev, clamp(q + ivec2(dx, dy), ivec2(0), hi)).r);
}
imageStore(mask_out, p, vec4(max(ch, was) * pc.bias));
}
+34
View File
@@ -0,0 +1,34 @@
#version 450
// HDR10 encode on the present (runtime/vk_hdr.c vk_hdr_encode): the game's picture, crop rectangle at offset, linear
// Rec. 709 with the HUD's white at 1.0 (an sRGB view decodes the 8-bit window texture), into an RGBA16F image of PQ
// code values in Rec. 2020 that FSR 1 or the blit then scale into the HDR10 swapchain. p.x: nits of 1.0, p.y: the
// display's peak in nits, p.z: 1 when the source holds sRGB-encoded values in a UNORM format.
// PQ: SMPTE ST 2084; the Rec. 709 to Rec. 2020 matrix: ITU-R BT.2087.
layout(local_size_x = 8, local_size_y = 8) in;
layout(binding = 0) uniform sampler2D src;
layout(binding = 1, rgba16f) uniform writeonly image2D dst;
layout(push_constant) uniform P {
ivec2 offset;
ivec2 size;
vec4 p;
} pc;
vec3 srgb_decode(vec3 c) {
return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), greaterThan(c, vec3(0.04045)));
}
vec3 pq(vec3 nits) {
const float m1 = 0.1593017578125, m2 = 78.84375, c1 = 0.8359375, c2 = 18.8515625, c3 = 18.6875;
vec3 y = pow(clamp(nits / 10000.0, 0.0, 1.0), vec3(m1));
return pow((c1 + c2 * y) / (1.0 + c3 * y), vec3(m2));
}
void main() {
ivec2 at = ivec2(gl_GlobalInvocationID.xy);
if (any(greaterThanEqual(at, pc.size))) return;
vec3 c = max(texelFetch(src, at + pc.offset, 0).rgb, vec3(0.0));
if (pc.p.z > 0.5) c = srgb_decode(clamp(c, 0.0, 1.0));
const mat3 to2020 = mat3(0.6274, 0.0691, 0.0164, 0.3293, 0.9195, 0.0880, 0.0433, 0.0114, 0.8956);
vec3 nits = min(max(to2020 * c, vec3(0.0)) * pc.p.x, vec3(pc.p.y));
imageStore(dst, at, vec4(pq(nits), 1.0));
}
+8
View File
@@ -0,0 +1,8 @@
#version 450
// One triangle over the whole target, for hdr_ui.frag (runtime/vk_hdr.c vk_hdr_ui_compose).
layout(location = 0) out vec2 uv;
void main() {
uv = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2);
gl_Position = vec4(uv * 2.0 - 1.0, 0.0, 1.0);
}
+74
View File
@@ -0,0 +1,74 @@
#version 450
// The game's tonemap pass for HDR output (runtime/vk_hdr.c vk_hdr_shader_swap puts it in place of the translated
// shader when TOTK_HDR=1). Same inputs as the game's: fp_t_tcb_8 (bloom, clamped to 10000 as the game does) plus
// fp_t_tcb_A (the scene), weights in c1[0] and the saturation grade in c3[0]. The game maps luminance and each channel
// with 1 - e^-x, blends the two by the luminance curve squared, clamps to 0..1 and grades saturation. Here the curve is
// the game's up to PIVOT and a straight line with its slope above, so mid-greys look as in SDR and highlights keep
// going; the grade works on the colour divided by its largest channel above 1; a roll-off on the largest channel stops
// at the display's peak. The output is relative to the HUD's white (1.0), which the present maps to TOTK_HDR_UI_NITS.
// Hue correction (hdr.z, TOTK_HDR_HUE): the game's SDR clamp turns bright saturated colours towards white (a torch flame
// clips red, then green, and reads yellow-white, the colour its emitted light was tuned to); the extended curve keeps
// their ratios, so they stay saturated. From the picture's white upwards the colour moves towards the game's own SDR
// result at the HDR luminance, by up to hdr.z (RenoDX's TotK mod has the same control).
// Approach after RenoDX's TotK mod by souperman9 and Musa (github.com/clshortfuse/renodx, src/games/totk, MIT): its
// "extended vanilla" curve.
// Bindings are those of the game's translated shader: vk_hdr.c rewrites them from the original's names.
layout(location = 0) in vec4 uv;
layout(location = 0) out vec4 color;
layout(set = 0, binding = 0, std140) uniform SupportBuffer {
vec4 pad[90];
vec4 hdr; // byte 1440 (vk_exec_draw.c support_fill): game white / HUD white, peak / game white, hue correction
} support_buffer;
layout(set = 0, binding = 1) uniform sampler2D fp_t_tcb_8;
layout(set = 0, binding = 2) uniform sampler2D fp_t_tcb_A;
layout(set = 0, binding = 3, std140) uniform C1 { vec4 v[4096]; } fp_c1;
layout(set = 0, binding = 4, std140) uniform C3 { vec4 v[4096]; } fp_c3;
const float PIVOT = 0.18;
float curve(float x) { // the game's 1 - e^-x below PIVOT, its tangent there above
float y0 = 1.0 - exp(-PIVOT);
return x <= PIVOT ? 1.0 - exp(-x) : y0 + exp(-PIVOT) * (x - PIVOT);
}
vec3 curve3(vec3 x) { return vec3(curve(x.r), curve(x.g), curve(x.b)); }
float maxc(vec3 c) { return max(c.r, max(c.g, c.b)); }
void main() {
vec3 x = min(texture(fp_t_tcb_8, uv.xy).rgb, vec3(10000.0)) + texture(fp_t_tcb_A, uv.xy).rgb;
vec4 w = fp_c1.v[0], g = fp_c3.v[0];
float game = support_buffer.hdr.x > 0.0 ? support_buffer.hdr.x : 1.0;
float peak = support_buffer.hdr.y > 1.0 ? support_buffer.hdr.y : 1.0;
float lum = max(x.r * 0.2989 + x.g * w.x + x.b * w.y, 0.0);
float sdr = 1.0 - exp(-lum);
vec3 by_lum = lum > 0.0 ? x * (curve(lum) / lum) : x;
vec3 c = max(mix(by_lum, curve3(x), sdr * sdr), vec3(0.0));
// the game's saturation grade, on the colour scaled into 0..1 by its largest channel
float s = max(maxc(c), 1.0);
vec3 n = c / s;
float m = maxc(n);
float d = n.r * 0.6666667 + (n.g + n.b) * w.z - 1.0;
float grade = g.y * (1.0 - d * d) + g.x;
c = s * ((n - m) * grade + m);
// the game's own SDR result: the same blend clamped to 0..1, graded
vec3 sdr_c = clamp(mix(lum > 0.0 ? x * (sdr / lum) : x, vec3(1.0) - exp(-x), sdr * sdr), 0.0, 1.0);
float sm = maxc(sdr_c), sd = sdr_c.r * 0.6666667 + (sdr_c.g + sdr_c.b) * w.z - 1.0;
sdr_c = (sdr_c - sm) * (g.y * (1.0 - sd * sd) + g.x) + sm;
float hue = clamp(support_buffer.hdr.z, 0.0, 1.0);
const vec3 Y = vec3(0.2126, 0.7152, 0.0722); // Rec. 709 luminance
float yc = dot(c, Y), ys = dot(sdr_c, Y);
if (hue > 0.0 && ys > 1e-5) c = mix(c, max(sdr_c, vec3(0.0)) * (yc / ys), hue * smoothstep(0.5, 1.5, maxc(c)));
// roll-off of the largest channel from half the peak to the peak
float top = maxc(c), knee = 0.5 * peak;
if (top > knee) {
float r = peak - knee;
c *= (knee + r * (1.0 - exp(-(top - knee) / r))) / top;
}
color = vec4(max(c, vec3(0.0)) * game, 0.0);
}
+27
View File
@@ -0,0 +1,27 @@
#version 450
// The in-game menu on an HDR10 swapchain (runtime/vk_hdr.c vk_hdr_ui_compose): ImGui drew it into an RGBA8 image,
// premultiplied sRGB colour over a clear 0; this turns each pixel back into its colour, puts its white at p.x nits and
// writes the PQ code with its coverage, which the pipeline blends over the picture (in PQ code values, as the menu
// blends in sRGB code values on an SDR swapchain). PQ: SMPTE ST 2084; Rec. 709 to Rec. 2020: ITU-R BT.2087.
layout(location = 0) in vec2 uv;
layout(location = 0) out vec4 color;
layout(binding = 0) uniform sampler2D ui;
layout(push_constant) uniform P { vec4 p; } pc;
vec3 srgb_decode(vec3 c) {
return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), greaterThan(c, vec3(0.04045)));
}
vec3 pq(vec3 nits) {
const float m1 = 0.1593017578125, m2 = 78.84375, c1 = 0.8359375, c2 = 18.8515625, c3 = 18.6875;
vec3 y = pow(clamp(nits / 10000.0, 0.0, 1.0), vec3(m1));
return pow((c1 + c2 * y) / (1.0 + c3 * y), vec3(m2));
}
void main() {
vec4 u = texture(ui, uv);
if (u.a <= 0.0) discard;
vec3 c = srgb_decode(clamp(u.rgb / u.a, 0.0, 1.0));
const mat3 to2020 = mat3(0.6274, 0.0691, 0.0164, 0.3293, 0.9195, 0.0880, 0.0433, 0.0114, 0.8956);
color = vec4(pq(max(to2020 * c, vec3(0.0)) * pc.p.x), u.a);
}
+1 -1
View File
@@ -7,7 +7,7 @@
// tables. Not modelled: FPSR cumulative exception bits and QC, FPCR trap enables, FP16 arithmetic (ARMv8.2).
// FPCR.AHP is honoured by the half-precision conversions. Host assumptions: IEEE binary32/64, MXCSR in
// round-to-nearest outside the slow paths, with FTZ|DAZ equal to FPCR.FZ (cpu.h rt_fpcr_sync keeps it so); fma must be
// correctly rounded (build x86 with -mfma).
// correctly rounded: -march=x86-64-v3 has the FMA instruction, and the v2 build links runtime/fma.c for it.
#pragma once
#include <fenv.h>
#include <immintrin.h>
+58 -11
View File
@@ -59,16 +59,60 @@ SN T FN(nan3)(Cpu *c, T a, T b, T d) {
return FN(fv)(DNAN);
}
// ---- FMA flavours. FMA_S / FMA_V: fast paths, host MXCSR is round-to-nearest there (simd_directed() is checked first).
// FMA_X: scalar FMA for the slow paths, any host rounding mode.
// Without hardware FMA (Ivy Bridge, no -mfma) clang turns __builtin_elementwise_fma into a call to the C runtime's
// fmaf/fma for every lane, which is very slow and keeps the thread outside generated code. For float the product of
// two floats is exact in a double (24 x 24 = 48 bits), so the fused op is done in double. A plain
// (float)(x * y + z) rounds twice and can differ by one ulp; rounding the double sum to odd first (Boldo-Melquiond)
// makes the final float rounding exact: TwoSum gives the error e of s = fl(p + z), and when e != 0 and s has an even
// last bit, s is moved one ulp toward the exact value (the odd neighbour). Inf/NaN lanes are left alone (e is NaN
// there, so the ordered compares below are false). Double has no wider type: it keeps the C runtime's fma.
#if defined(__FMA__) || defined(__aarch64__) || NB == 64
#define FMA_S(x, y, z) __builtin_elementwise_fma(x, y, z)
#define FMA_V(x, y, z) __builtin_elementwise_fma(x, y, z)
#define FMA_X(x, y, z) __builtin_elementwise_fma(x, y, z)
#else
typedef double simd_vf64x4 __attribute__((vector_size(32)));
typedef uint64_t simd_vu64x4 __attribute__((vector_size(32)));
SI float fma_rn_s(float x, float y, float z) {
double p = (double)x * (double)y, zd = (double)z, s = p + zd;
double bb = s - p, e = (p - (s - bb)) + (zd - bb); // TwoSum: s + e == p + zd exactly
uint64_t u;
memcpy(&u, &s, sizeof u);
if (((e < 0.0) | (e > 0.0)) && !(u & 1)) u += (e > 0.0) == (s > 0.0) ? 1 : (uint64_t)-1;
memcpy(&s, &u, sizeof s);
return (float)s;
}
SI vf32 fma_rn_v(vf32 x, vf32 y, vf32 z) {
simd_vf64x4 p = CVT(x, simd_vf64x4) * CVT(y, simd_vf64x4), zd = CVT(z, simd_vf64x4), s = p + zd;
simd_vf64x4 bb = s - p, e = (p - (s - bb)) + (zd - bb);
simd_vu64x4 u = (simd_vu64x4)s;
simd_vu64x4 fix = (simd_vu64x4)((e < 0.0) | (e > 0.0)) & (simd_vu64x4)((u & 1) == 0);
simd_vu64x4 up = (simd_vu64x4)((e > 0.0) == (s > 0.0));
u += fix & ((up & 1) | ~up); // +1 toward the exact value, i.e. +1 if e and s share a sign, else -1
return CVT((simd_vf64x4)u, vf32);
}
// Any rounding mode: directed modes are exact with a plain double (same-direction double rounding is harmless).
SI float fma_any_s(float x, float y, float z) {
if (__builtin_expect(_mm_getcsr() & 0x6000u, 0)) return (float)((double)x * (double)y + (double)z);
return fma_rn_s(x, y, z);
}
#define FMA_S(x, y, z) fma_rn_s(x, y, z)
#define FMA_V(x, y, z) fma_rn_v(x, y, z)
#define FMA_X(x, y, z) fma_any_s(x, y, z)
#endif
// The arithmetic itself, for scalars (KK = K) and vectors (KK = VK). MADD: a + b*d (a = addend).
// RECPS/RSQRTS get their first operand already negated (FPNeg happens before NaN processing).
#define FCALC(op, a, b, d, KK) \
#define FCALC(op, a, b, d, KK, FMA) \
((op) == FOP_ADD ? (a) + (b) : (op) == FOP_SUB ? (a) - (b) \
: (op) == FOP_MUL || (op) == FOP_MULX ? (a) * (b) : (op) == FOP_NMUL ? -((a) * (b)) \
: (op) == FOP_DIV ? (a) / (b) : (op) == FOP_ABD ? __builtin_elementwise_abs((a) - (b)) \
: (op) == FOP_SQRT ? __builtin_elementwise_sqrt(a) \
: (op) == FOP_MADD ? __builtin_elementwise_fma(b, d, a) \
: (op) == FOP_RECPS ? __builtin_elementwise_fma(a, b, KK(2)) \
: (op) == FOP_RSQRTS ? __builtin_elementwise_fma(a, b, KK(3)) * KK(0.5) : (a))
: (op) == FOP_MADD ? FMA(b, d, a) \
: (op) == FOP_RECPS ? FMA(a, b, KK(2)) \
: (op) == FOP_RSQRTS ? FMA(a, b, KK(3)) * KK(0.5) : (a))
// Lanes whose fast result needs fixing: NaN results (NaN operand or invalid op), RSQRTS overflow.
#define FBAD(op, r) ((op) == FOP_RSQRTS ? ((r) != (r)) | (__builtin_elementwise_abs(r) == K(INFINITY)) : (r) != (r))
@@ -76,9 +120,9 @@ SN T FN(nan3)(Cpu *c, T a, T b, T d) {
// (3 + a*b) / 2 with one rounding (a already negated): halve a normal operand first, so a product beyond
// the format's range (which the fast path rounds to inf, or to the largest normal when rounding down) is exact.
SN T FN(rsqrts)(T a, T b) {
if (__builtin_elementwise_abs(a) >= FN(fv)(2 * MINN)) return __builtin_elementwise_fma(a * K(0.5), b, K(1.5));
if (__builtin_elementwise_abs(b) >= FN(fv)(2 * MINN)) return __builtin_elementwise_fma(a, b * K(0.5), K(1.5));
return __builtin_elementwise_fma(a, b, K(3)) * K(0.5);
if (__builtin_elementwise_abs(a) >= FN(fv)(2 * MINN)) return FMA_X(a * K(0.5), b, K(1.5));
if (__builtin_elementwise_abs(b) >= FN(fv)(2 * MINN)) return FMA_X(a, b * K(0.5), K(1.5));
return FMA_X(a, b, K(3)) * K(0.5);
}
// ARM result for a lane flagged by FBAD (operands already flushed).
@@ -136,13 +180,13 @@ SN T FN(slow)(Cpu *c, int op, T a, T b, T d) {
if (FMINMAX(op)) return FN(minmax)(c, op, a, b);
unsigned old = simd_rm_enter(fpcr);
volatile T va = a, vb = b, vd = d;
volatile T vr = op == FOP_RSQRTS ? FN(rsqrts)(va, vb) : FCALC(op, va, vb, vd, K);
volatile T vr = op == FOP_RSQRTS ? FN(rsqrts)(va, vb) : FCALC(op, va, vb, vd, K, FMA_X);
T r = vr;
if (FBAD(op, r)) vr = FN(fix)(c, op, a, b, d), r = vr;
if ((fpcr & FPCR_FZ) && (FN(fb)(r) & ~SGN) <= MINN && !FN(iszero)(FN(fb)(r))) {
if ((FN(fb)(r) & ~SGN) == MINN) {
simd_rm_rz();
volatile T vz = FCALC(op, va, vb, vd, K);
volatile T vz = FCALC(op, va, vb, vd, K, FMA_X);
if ((FN(fb)(vz) & ~SGN) < MINN) r = FN(fv)(FN(fb)(r) & SGN);
} else {
r = FN(fv)(FN(fb)(r) & SGN);
@@ -172,7 +216,7 @@ SI T FN(op)(Cpu *c, int op, T a, T b, T d) {
if (c->fpcr & FPCR_FZ) a = FN(flush)(a), b = FN(flush)(b);
return FN(minmax)(c, op, a, b);
}
T r = FCALC(op, a, b, d, K);
T r = FCALC(op, a, b, d, K, FMA_S);
if (__builtin_expect(op == FOP_RSQRTS ? FREDO(op, r) : !FOK(r), 0)) r = FN(redo)(c, op, a, b, d, r);
return r;
}
@@ -207,7 +251,7 @@ SI VT FN(vop)(Cpu *c, int op, VT a, VT b, VT d) {
r = (VT)FN(vsel)(a < b, x, FN(vsel)(a == b, x | y, y));
return r;
}
r = FCALC(op, a, b, d, VK);
r = FCALC(op, a, b, d, VK, FMA_V);
if (__builtin_expect(op == FOP_RSQRTS ? __builtin_reduce_or(FREDO(op, r)) != 0 : __builtin_reduce_and(FOK(r)) == 0, 0))
return FN(vslow)(c, op, a, b, d);
return r;
@@ -363,3 +407,6 @@ SI T FN(recpx)(Cpu *c, T a) {
#undef MINN
#undef VK
#undef K
#undef FMA_S
#undef FMA_V
#undef FMA_X
+305
View File
@@ -0,0 +1,305 @@
// Amiibo / NFC menu page (Dear ImGui): browser and scan controls.
#include <algorithm>
#include <cctype>
#include <cfloat>
#include <filesystem>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <string_view>
#include <vector>
#include "imgui.h"
#include "ui/amiibo_page.h"
#include "ui/option_rows.h"
extern "C" {
#include "amiibo.h"
#include "cfg.h"
#include "folder_pick.h"
#include "platform/platform.h"
#include "ui_text.h"
}
namespace fs = std::filesystem;
struct FileEntry {
std::string name;
bool is_dir;
};
static const char kDefaultAmiiboDir[] = "./amiibo";
static std::string g_current_dir = kDefaultAmiiboDir;
static std::vector<FileEntry> g_entries;
static int g_selected_entry = -1;
// The last action: a catalog id and the file or folder it names, formatted when drawn (the menu language can change)
static UiTextId g_status_id = UI_MENU_AMIIBO_READY;
static std::string g_status_arg;
static void set_status(UiTextId id, const std::string &arg = std::string()) {
g_status_id = id;
g_status_arg = arg;
}
// Loads a dump and puts it on the reader; the status names the file.
static void tap(const std::string &dir, const std::string &name) {
std::string full_path = (fs::path(dir) / name).string();
set_status(amiibo_scan_and_tap(full_path.c_str()) ? UI_MENU_AMIIBO_TAPPED : UI_MENU_AMIIBO_LOAD_FAILED, name);
}
static bool iequals(std::string_view a, std::string_view b) {
if (a.size() != b.size()) return false;
for (size_t i = 0; i < a.size(); ++i) {
if (std::tolower(static_cast<unsigned char>(a[i])) !=
std::tolower(static_cast<unsigned char>(b[i]))) {
return false;
}
}
return true;
}
static void set_current_dir(const std::string &path) {
g_current_dir = path;
cfg_set("TOTK_AMIIBO_DIR", g_current_dir.c_str());
}
// The host's folder dialog (folder_pick.h) answers on its own thread; the page takes the answer when it draws.
static PlatMutex g_pick_lock = PLAT_MUTEX_INIT;
static bool g_pick_open;
static bool g_pick_ready;
static std::string g_pick_path;
static void on_folder_picked(const char *path, void *ctx) {
(void)ctx;
plat_mutex_lock(&g_pick_lock);
g_pick_ready = path != NULL;
if (path) g_pick_path = path;
g_pick_open = false;
plat_mutex_unlock(&g_pick_lock);
}
static void refresh_dir(void) {
g_entries.clear();
g_selected_entry = -1;
std::error_code ec;
fs::path dir_path(g_current_dir);
// A missing folder lists nothing and says so; it is not replaced by another one, and opening the tab writes no
// setting (the folder is saved only when the player sets one).
if (!fs::exists(dir_path, ec) || !fs::is_directory(dir_path, ec)) {
set_status(UI_MENU_AMIIBO_NO_DIR, g_current_dir);
return;
}
if (g_status_id == UI_MENU_AMIIBO_NO_DIR) set_status(UI_MENU_AMIIBO_READY);
// Add parent navigation if not at root
if (dir_path.has_parent_path() && dir_path != dir_path.parent_path()) {
g_entries.push_back({"..", true});
}
for (const auto &entry : fs::directory_iterator(dir_path, fs::directory_options::skip_permission_denied, ec)) {
if (ec) break;
std::error_code status_ec;
bool is_dir = entry.is_directory(status_ec);
if (status_ec) continue;
std::string filename = entry.path().filename().string();
if (filename.empty() || filename == "." || filename == "..") continue;
if (!is_dir) {
std::string ext = entry.path().extension().string();
if (!iequals(ext, ".bin") && !iequals(ext, ".nfc")) {
continue;
}
}
g_entries.push_back({std::move(filename), is_dir});
}
std::sort(g_entries.begin(), g_entries.end(), [](const FileEntry &a, const FileEntry &b) {
if (a.name == "..") return true;
if (b.name == "..") return false;
if (a.is_dir != b.is_dir) return a.is_dir;
return a.name < b.name;
});
}
void tab_amiibo(float scale) {
(void)scale; // the rows take ImGui's own sizes, already scaled with the font
static bool s_inited = false;
if (!s_inited) {
const char *cfg_dir = cfg_get("TOTK_AMIIBO_DIR");
if (cfg_dir && *cfg_dir) {
g_current_dir = cfg_dir;
} else {
g_current_dir = kDefaultAmiiboDir;
}
refresh_dir();
s_inited = true;
}
plat_mutex_lock(&g_pick_lock);
bool picking = g_pick_open;
std::string picked;
if (g_pick_ready) picked.swap(g_pick_path);
g_pick_ready = false;
plat_mutex_unlock(&g_pick_lock);
if (!picked.empty()) {
set_current_dir(picked);
refresh_dir();
}
// Two panes: Left (Directory Browser & Tag List), Right (Amiibo Tag Details & Controls)
const float content_h = ImGui::GetContentRegionAvail().y - opt_bottom(); // Continue and Quit stay visible
const float left_w = ImGui::GetContentRegionAvail().x * 0.58f;
const float right_w = ImGui::GetContentRegionAvail().x - left_w - ImGui::GetStyle().ItemSpacing.x;
// ---- Left Pane: Explorer & List ----
ImGui::BeginChild("##amiibo_explorer", ImVec2(left_w, content_h), true);
ImGui::TextColored(ImVec4(0.93f, 0.76f, 0.33f, 1.0f), "%s", menu_text(UI_MENU_AMIIBO_DIR));
ImGui::TextWrapped("%s", g_current_dir.c_str());
ImGui::Spacing();
ImGui::BeginDisabled(picking);
if (ImGui::Button(menu_text(UI_MENU_AMIIBO_OPEN))) {
plat_mutex_lock(&g_pick_lock);
g_pick_open = true;
plat_mutex_unlock(&g_pick_lock);
folder_pick(g_current_dir.c_str(), on_folder_picked, NULL);
}
ImGui::EndDisabled();
ImGui::SameLine();
if (ImGui::Button(menu_text(UI_MENU_AMIIBO_DEFAULT_DIR))) {
set_current_dir(kDefaultAmiiboDir);
refresh_dir();
}
ImGui::SameLine();
if (ImGui::Button(menu_text(UI_MENU_AMIIBO_REFRESH))) {
refresh_dir();
}
ImGui::Separator();
ImGui::TextDisabled("%s", menu_text(UI_MENU_AMIIBO_PICK));
ImGui::BeginChild("##file_list", ImVec2(0, 0), true);
if (g_status_id == UI_MENU_AMIIBO_NO_DIR) {
char missing[512];
snprintf(missing, sizeof missing, menu_text(UI_MENU_AMIIBO_NO_DIR), g_current_dir.c_str());
ImGui::TextWrapped("%s", missing);
}
for (size_t i = 0; i < g_entries.size(); i++) {
const auto &e = g_entries[i];
std::string label = e.is_dir ? e.name + "/" : e.name;
bool selected = ((int)i == g_selected_entry);
if (ImGui::Selectable(label.c_str(), selected, ImGuiSelectableFlags_AllowDoubleClick)) {
g_selected_entry = (int)i;
if (e.is_dir) {
if (ImGui::IsMouseDoubleClicked(0) || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceDown)) {
if (e.name == "..") {
fs::path cur(g_current_dir);
if (cur.has_parent_path() && cur != cur.parent_path()) {
set_current_dir(cur.parent_path().string());
} else {
set_current_dir(".");
}
} else {
set_current_dir((fs::path(g_current_dir) / e.name).string());
}
refresh_dir();
break;
}
} else {
if (ImGui::IsMouseDoubleClicked(0)) tap(g_current_dir, e.name);
}
}
}
ImGui::EndChild();
ImGui::EndChild();
ImGui::SameLine();
// ---- Right Pane: Controls & Status ----
ImGui::BeginChild("##amiibo_controls", ImVec2(right_w, content_h), true);
ImGui::TextColored(ImVec4(0.93f, 0.76f, 0.33f, 1.0f), "%s", menu_text(UI_MENU_AMIIBO_READER));
ImGui::Separator();
AmiiboDeviceState state = amiibo_get_reader_state();
UiTextId state_id = UI_MENU_AMIIBO_STATE_IDLE;
ImVec4 state_col = ImVec4(0.8f, 0.8f, 0.8f, 1.0f);
switch (state) {
case AMIIBO_DEV_STATE_INITIALIZED: state_id = UI_MENU_AMIIBO_STATE_IDLE; break;
case AMIIBO_DEV_STATE_SEARCHING: state_id = UI_MENU_AMIIBO_STATE_SEARCHING; state_col = ImVec4(1.0f, 0.8f, 0.2f, 1.0f); break;
case AMIIBO_DEV_STATE_TAG_FOUND: state_id = UI_MENU_AMIIBO_STATE_FOUND; state_col = ImVec4(0.3f, 0.9f, 0.3f, 1.0f); break;
case AMIIBO_DEV_STATE_TAG_MOUNTED: state_id = UI_MENU_AMIIBO_STATE_MOUNTED; state_col = ImVec4(0.2f, 0.9f, 1.0f, 1.0f); break;
case AMIIBO_DEV_STATE_UNAVAILABLE: state_id = UI_MENU_AMIIBO_STATE_OFF; state_col = ImVec4(0.9f, 0.3f, 0.3f, 1.0f); break;
default: break;
}
ImGui::TextUnformatted(menu_text(UI_MENU_AMIIBO_STATE));
ImGui::SameLine();
ImGui::TextColored(state_col, "%s", menu_text(state_id));
ImGui::Spacing();
ImGui::Separator();
ImGui::TextUnformatted(menu_text(UI_MENU_AMIIBO_FILE));
if (g_selected_entry >= 0 && g_selected_entry < (int)g_entries.size() && !g_entries[g_selected_entry].is_dir) {
ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.4f, 1.0f), "%s", g_entries[g_selected_entry].name.c_str());
if (ImGui::Button(menu_text(UI_MENU_AMIIBO_TAP), ImVec2(ImGui::GetContentRegionAvail().x, 0)))
tap(g_current_dir, g_entries[g_selected_entry].name);
} else {
ImGui::TextDisabled("%s", menu_text(UI_MENU_AMIIBO_NO_FILE));
ImGui::BeginDisabled();
ImGui::Button(menu_text(UI_MENU_AMIIBO_TAP), ImVec2(ImGui::GetContentRegionAvail().x, 0));
ImGui::EndDisabled();
}
ImGui::Spacing();
if (ImGui::Button(menu_text(UI_MENU_AMIIBO_REMOVE), ImVec2(ImGui::GetContentRegionAvail().x, 0))) {
amiibo_remove_tag();
set_status(UI_MENU_AMIIBO_REMOVED);
}
ImGui::Spacing();
ImGui::Separator();
bool auto_remove = amiibo_get_auto_remove();
if (ImGui::Checkbox(menu_text(UI_MENU_AMIIBO_AUTO_REMOVE), &auto_remove)) {
amiibo_set_auto_remove(auto_remove);
}
if (auto_remove) {
float delay = amiibo_get_auto_remove_delay_s();
ImGui::TextUnformatted(menu_text(UI_MENU_AMIIBO_HOLD)); // above the slider: beside it the text is cut off
ImGui::SetNextItemWidth(-FLT_MIN);
if (ImGui::SliderFloat("##amiibo_hold", &delay, 1.0f, 6.0f, menu_text(UI_MENU_AMIIBO_SECONDS))) {
amiibo_set_auto_remove_delay_s(delay);
}
}
ImGui::Spacing();
ImGui::Separator();
ImGui::TextUnformatted(menu_text(UI_MENU_AMIIBO_TAG));
if (amiibo_has_tag()) {
const AmiiboInfo *info = amiibo_get_current_info();
char character[8], uid[24];
snprintf(character, sizeof character, "%02x%02x%02x", info->character_id[0], info->character_id[1],
info->character_id[2]);
snprintf(uid, sizeof uid, "%02x:%02x:%02x:%02x:%02x:%02x:%02x", info->uuid[0], info->uuid[1], info->uuid[2],
info->uuid[3], info->uuid[4], info->uuid[5], info->uuid[6]);
ImGui::Text(menu_text(UI_MENU_AMIIBO_TAG_FILE), info->filename);
ImGui::Text(menu_text(UI_MENU_AMIIBO_TAG_ID), character, info->series_id, info->numbering_id, info->nfp_type);
ImGui::Text(menu_text(UI_MENU_AMIIBO_TAG_UID), uid);
} else {
ImGui::TextDisabled("%s", menu_text(UI_MENU_AMIIBO_NO_TAG));
}
ImGui::Spacing();
ImGui::Separator();
char status[512];
snprintf(status, sizeof status, menu_text(g_status_id), g_status_arg.c_str());
ImGui::TextDisabled(menu_text(UI_MENU_AMIIBO_STATUS), status);
ImGui::EndChild();
}
+4
View File
@@ -0,0 +1,4 @@
// Amiibo / NFC menu page (ui/amiibo_page.cpp).
#pragma once
void tab_amiibo(float scale);
+66
View File
@@ -0,0 +1,66 @@
// The Cheats tab of the in-game menu: the cheats of the mods' cheat files (cheats.c), a heading per mod in the Mods
// tab's order, then a row per cheat in file order and a line per group label of the file; a cheat that cannot be
// switched here is greyed out with the reason. While code cheats wait for a rebuild, a row on top restarts the game
// into it.
#include <stdio.h>
#include <string.h>
#include "imgui.h"
#include "ui/option_rows.h"
extern "C" {
#include "cheats.h"
#include "ui_text.h"
}
// Returns true when "Rebuild the game now" was chosen: the menu then asks to restart (ui/menu.cpp restart_confirm).
extern "C" bool tab_cheats(float scale) {
opt_begin("##cheats", scale);
static char line[512], desc[768], buttons[192];
int n = cheats_count();
if (!n) {
snprintf(line, sizeof line, menu_text(UI_MENU_CHEATS_NONE), cheats_file()[0] ? cheats_file() : "<build id>.txt");
opt_text_str(line);
opt_end();
return false;
}
bool rebuild =
cheats_rebuild_pending() && opt_button("##restart", UI_MENU_CHEATS_REBUILD, UI_MENU_CHEATS_REBUILD_DESC);
for (int i = 0; i < n; i++) {
const CheatInfo *c = cheats_info(i);
if (!i || strcmp(c->mod, cheats_info(i - 1)->mod)) {
int listed = 0;
for (int j = i; j < n && !strcmp(cheats_info(j)->mod, c->mod); j++)
listed += cheats_info(j)->kind != CHEAT_HEADING;
snprintf(line, sizeof line, menu_text(UI_MENU_CHEATS_MOD), c->mod, listed);
opt_group_text(line);
}
UiTextId text = UI_MENU_CHEAT_CODE_DESC;
switch (c->kind) {
case CHEAT_HEADING:
if (!strstr(c->name, "TID=")) opt_text_str(c->name); // the file's title line only names the game
continue;
case CHEAT_CODE: break;
case CHEAT_KEY: text = UI_MENU_CHEAT_KEY_DESC; break;
case CHEAT_DATA: text = UI_MENU_CHEAT_DATA_DESC; break;
case CHEAT_MASTER: text = UI_MENU_CHEAT_MASTER_DESC, opt_disable_next(UI_MENU_CHEAT_MASTER); break;
case CHEAT_RESTORE: text = UI_MENU_CHEAT_RESTORE_DESC, opt_disable_next(UI_MENU_CHEAT_RESTORE); break;
case CHEAT_REBUILD: text = UI_MENU_CHEAT_REBUILD_DESC, opt_disable_next(UI_MENU_CHEAT_REBUILD); break;
case CHEAT_UNSUPPORTED:
text = UI_MENU_CHEAT_UNSUPPORTED_DESC, opt_disable_next(UI_MENU_CHEAT_UNSUPPORTED);
break;
}
if (c->kind == CHEAT_KEY)
snprintf(desc, sizeof desc, menu_text(text), cheats_buttons(c->buttons, buttons, sizeof buttons));
else if (c->kind == CHEAT_UNSUPPORTED)
snprintf(desc, sizeof desc, "%s %s", menu_text(text), c->note);
else
snprintf(desc, sizeof desc, "%s", menu_text(text));
if (opt_toggle_text(c->key, c->name, desc, cheats_on(i) != 0)) {
cheats_set(i, !cheats_on(i));
opt_save_soon();
}
}
opt_end();
return rebuild;
}
+362 -55
View File
@@ -30,13 +30,18 @@ static int g_font_bad;
#pragma clang diagnostic ignored "-Wunused-function"
#include "imstb_truetype.h"
#pragma clang diagnostic pop
#include "ui/amiibo_page.h"
#include "ui/binds_page.h"
#include "ui/option_rows.h"
extern "C" {
#include "amiibo.h"
#include "cheats.h"
#include "cfg.h"
#include "fs.h"
#include "input.h"
#include "input_map.h"
#include "mods.h"
#include "perfmon.h"
#include "platform/platform.h"
#include "sysinfo.h"
@@ -49,10 +54,9 @@ void vk_queue_unlock(void);
void res_sizes(unsigned out[2], unsigned scene[2]);
double frame_step_limit_hz(void);
extern const int rt_game_version;
// fs.h (romfs.c): romfs-patches-xbox was next to romfs-index.bin at start, and was loaded.
int romfs_xbox_prompts_ready(void);
int romfs_xbox_prompts_active(void);
extern const char rt_port_version[];
void cheats_frame(uint64_t frame); // cheats.c
bool tab_cheats(float scale); // ui/cheats_tab.cpp; true: restart into the rebuild
}
// Roboto Medium (Apache-2.0, ui/fonts/LICENSE-Roboto.txt) with Latin and Cyrillic glyphs.
@@ -266,7 +270,9 @@ static int vk_up(const MenuTarget *t) {
// Roboto Medium (Latin, Cyrillic, dashes and quotes) at 26 px per 1080 lines, with the glyphs of the Japanese, Korean
// and Chinese language names merged in from a system font when there is one (each language is named in its own script).
// Made again when the window height changes; the old texture goes after the queue is idle (CreateFontsTexture).
// A catalog row also holds menu text (Simplified Chinese), so every string of the row goes into the builder: the merged
// font must cover the whole menu of that language, not only its name. Made again when the window height changes; the old
// texture goes after the queue is idle (CreateFontsTexture).
static const ImWchar kRanges[] = {0x0020, 0x00FF, 0x0400, 0x052F, 0x2010, 0x2027, 0};
static const struct { const char *lang; UiTextId name; } kCjk[] = {
{"ja", UI_MENU_LANGNAME_JA}, {"ko", UI_MENU_LANGNAME_KO}, {"zh-Hans", UI_MENU_LANGNAME_ZH_HANS},
@@ -310,6 +316,11 @@ extern "C" int menu_font_check(void) {
return ok;
}
// The glyphs of every string of a catalog row (ui_text_visit), for the font that draws that language.
static void add_row_glyphs(void *ctx, const char *text) {
static_cast<ImFontGlyphRangesBuilder *>(ctx)->AddText(text);
}
static int fonts_up(float scale) {
enum { N = sizeof kCjk / sizeof *kCjk };
ImFontAtlas *fa = ImGui::GetIO().Fonts;
@@ -334,6 +345,13 @@ static int fonts_up(float scale) {
merged++;
ImFontGlyphRangesBuilder b;
b.AddText(ui_text_in("en", kCjk[i].name));
ui_text_visit(kCjk[i].lang, add_row_glyphs, &b);
// Text the menu shows that no catalog row holds: a mod's cheat names and its folder name,
// both read from disk at runtime. Their glyphs would otherwise fall back to the missing-glyph box.
for (int k = 0; k < cheats_count(); k++)
if (const CheatInfo *ci = cheats_info(k); ci && ci->name) b.AddText(ci->name);
for (int k = 0; k < mods_count(); k++)
if (const ModInfo *mi = mods_at(k); mi) b.AddText(mi->name);
b.BuildRanges(&ranges[i]);
ImFontConfig mc;
mc.MergeMode = true;
@@ -362,7 +380,7 @@ extern "C" void menu_vk_release(void) {
// TOTK_MENU_TEST_SET=<frame>:<key>=<value>[,<key>=<value>...][;<frame>:...]: cfg_set of each key (TOTK_ prefix
// optional) at that presented frame; changes live settings with no input, menu open or not. totk.ini is written only by
// the pseudo-key SAVE=1 (cfg_save, as a row change does; a failed write shows the menu's save note).
enum { TAB_SCREEN, TAB_GAME, TAB_SOUND, TAB_CONTROLS, TAB_MENU, TAB_ADVANCED, TAB_COUNT };
enum { TAB_SCREEN, TAB_GAME, TAB_SOUND, TAB_CONTROLS, TAB_AMIIBO, TAB_MENU, TAB_ADVANCED, TAB_MODS, TAB_CHEATS, TAB_COUNT };
enum { TEST_PAGE_FRAMES = 30, TEST_SETS = 16 };
struct TestSet { uint64_t frame; char key[64], value[64]; };
static struct {
@@ -473,13 +491,15 @@ static void row_window_size(void) {
}
// The game resolution (resolution.c): 16:9 sizes from its smallest, 1280x720 (for weak GPUs), up, the common 21:9 and
// 32:9 monitor sizes and the 16:10 screens of the Steam Deck, handhelds and laptops (the camera and the HUD follow
// 32:9 monitor sizes, the 16:10 screens of the Steam Deck, handhelds and laptops and the 3:2 screens of laptops and
// tablets (Surface, Framework; the camera and the HUD follow
// another shape, resolution.c res_init; the installer lays the HUD out for each, installer/steps.py ASPECT_SIZES), and
// the current value when it is another size.
static void row_output_res(void) {
static const char *const vals[] = {"1280x720", "1600x900", "1920x1080", "2560x1440", "3200x1800", "3840x2160",
"2560x1080", "3440x1440", "3840x1600", "5120x2160", "3840x1080", "5120x1440",
"1280x800", "1680x1050", "1920x1200", "2560x1600"};
"1280x800", "1680x1050", "1920x1200", "2560x1600",
"1920x1280", "2160x1440", "2256x1504", "2880x1920", "3000x2000"};
enum { N = sizeof vals / sizeof *vals };
char shown[N][32];
const char *names[N];
@@ -505,6 +525,27 @@ static void row_render_scale(void) {
opt_choice_list("TOTK_RENDER_SCALE", UI_MENU_RENDER_SCALE, vals, names, N, UI_MENU_RENDER_SCALE_DESC);
}
static void row_shadow_res(void) {
static const char *const vals[] = {"game", "256", "512", "768", "1024", "1536", "2048"};
enum { N = sizeof vals / sizeof *vals };
const char *names[N];
names[0] = menu_text(UI_MENU_SHADOW_RES_GAME);
for (int i = 1; i < N; i++) names[i] = vals[i];
opt_choice_list("TOTK_SHADOW_RES", UI_MENU_SHADOW_RES, vals, names, N, UI_MENU_SHADOW_RES_DESC);
}
static void row_shadow_scale(void) {
static const char *const vals[] = {"1", "2", "3", "4"};
static const char *const names[] = {"960 (1x)", "1920 (2x)", "2880 (3x)", "3840 (4x)"};
opt_choice_list("TOTK_SHADOW_SCALE", UI_MENU_SHADOW_SCALE, vals, names, 4, UI_MENU_SHADOW_SCALE_DESC);
}
static void row_shadow_range(void) {
static const char *const vals[] = {"100", "150", "200", "300"};
static const char *const names[] = {"160 m (1x)", "240 m (1.5x)", "320 m (2x)", "480 m (3x)"};
opt_choice_list("TOTK_SHADOW_RANGE", UI_MENU_SHADOW_RANGE, vals, names, 4, UI_MENU_SHADOW_RANGE_DESC);
}
static void row_gpu(void) {
const char *vals[MAX_GPUS + 1], *names[MAX_GPUS + 1];
char idx[MAX_GPUS][4];
@@ -518,27 +559,25 @@ static void row_gpu(void) {
opt_choice_list("TOTK_GPU_INDEX", UI_MENU_GPU, vals, names, g_gpu_n + 1, UI_MENU_GPU_DESC);
}
// The game language: one entry per language TotK ships (a Switch code that names it), each under its own name. The
// Switch's Portuguese is not among them.
// The game language: one entry per Mals language file the running game build ships (ui_text_game_langs), each under
// its own name. A code that names no entry exactly (older "en", "fr-CA" on a build without it) selects the first entry
// of the same catalog language.
static void row_game_lang(void) {
static const struct { const char *code; UiTextId name; } langs[] = {
{"en-US", UI_MENU_LANGNAME_EN}, {"ja", UI_MENU_LANGNAME_JA}, {"fr", UI_MENU_LANGNAME_FR},
{"de", UI_MENU_LANGNAME_DE}, {"it", UI_MENU_LANGNAME_IT}, {"es", UI_MENU_LANGNAME_ES},
{"nl", UI_MENU_LANGNAME_NL}, {"ru", UI_MENU_LANGNAME_RU},
{"zh-Hans", UI_MENU_LANGNAME_ZH_HANS}, {"zh-Hant", UI_MENU_LANGNAME_ZH_HANT}, {"ko", UI_MENU_LANGNAME_KO},
};
enum { N = sizeof langs / sizeof *langs + 1 };
const char *vals[N], *names[N];
UiGameLang langs[16];
int n = ui_text_game_langs(rt_game_version, langs, 16);
const char *vals[17], *names[17];
vals[0] = "";
names[0] = menu_text(UI_MENU_GAME_LANG_AUTO);
const char *now = cfg_value("TOTK_LANG");
int cur = *now ? -1 : 0;
for (int i = 1; i < N; i++) {
for (int i = 1; i <= n; i++) {
vals[i] = langs[i - 1].code;
names[i] = menu_text(langs[i - 1].name);
if (*now && !strcmp(ui_text_lang(now), ui_text_lang(vals[i]))) cur = i; // en-GB is English too
if (*now && !strcmp(now, vals[i])) cur = i;
}
opt_choice_list("TOTK_LANG", UI_MENU_GAME_LANG, vals, names, N, UI_MENU_GAME_LANG_DESC, cur);
for (int i = 1; i <= n && *now && cur < 0; i++)
if (!strcmp(ui_text_lang(now), ui_text_lang(vals[i]))) cur = i;
opt_choice_list("TOTK_LANG", UI_MENU_GAME_LANG, vals, names, n + 1, UI_MENU_GAME_LANG_DESC, cur);
}
// The frame limit (frame_rate.c): unset, the older fps60 = 0 still means 30. The monitor choice shows the rate it gives.
@@ -623,6 +662,7 @@ static void tab_screen(float scale) {
opt_group(UI_MENU_GRAPHICS);
row_output_res();
row_render_scale();
row_shadow_res();
static const UiTextId up[] = {UI_MENU_UPSCALER_FSR, UI_MENU_UPSCALER_BILINEAR};
opt_choice("TOTK_UPSCALER", UI_MENU_UPSCALER, up, 2, UI_MENU_UPSCALER_DESC);
opt_slider("TOTK_SHARPNESS", UI_MENU_SHARPNESS, 0, 100, UI_MENU_SHARPNESS_DESC, 5, "%.0f %%");
@@ -634,16 +674,33 @@ static void tab_screen(float scale) {
opt_choice_list("TOTK_ANISO", UI_MENU_ANISO, aniso, aniso_names, 5, UI_MENU_ANISO_DESC);
opt_toggle("TOTK_LOD_DETAIL", UI_MENU_LOD_DETAIL, UI_MENU_LOD_DETAIL_DESC);
opt_toggle("TOTK_LOD_STEADY", UI_MENU_LOD_STEADY, UI_MENU_LOD_STEADY_DESC);
row_shadow_scale();
row_shadow_range();
opt_slider("TOTK_PCSS", UI_MENU_PCSS, 0, 200, UI_MENU_PCSS_DESC, 10, "%.0f %%");
opt_slider("TOTK_CONTACT_SHADOWS", UI_MENU_CONTACT_SHADOWS, 0, 100, UI_MENU_CONTACT_SHADOWS_DESC, 10, "%.0f %%");
opt_toggle("TOTK_DLAA", UI_MENU_DLAA, UI_MENU_DLAA_DESC);
static const UiTextId dlss[] = {UI_MENU_DLSS_DLAA, UI_MENU_DLSS_QUALITY, UI_MENU_DLSS_BALANCED,
UI_MENU_DLSS_PERFORMANCE, UI_MENU_DLSS_ULTRA};
opt_choice("TOTK_DLSS", UI_MENU_DLSS, dlss, 5, UI_MENU_DLSS_DESC);
static const UiTextId preset[] = {UI_MENU_DLSS_PRESET_DEFAULT, UI_MENU_DLSS_PRESET_K, UI_MENU_DLSS_PRESET_J};
opt_choice("TOTK_DLSS_PRESET", UI_MENU_DLSS_PRESET, preset, 3, UI_MENU_DLSS_PRESET_DESC);
static const UiTextId chars[] = {UI_MENU_DLSS_CHARS_OFF, UI_MENU_DLSS_CHARS_LIGHT, UI_MENU_DLSS_CHARS_MEDIUM,
UI_MENU_DLSS_CHARS_FULL};
opt_choice("TOTK_DLSS_CHAR_MASK", UI_MENU_DLSS_CHARS, chars, 4, UI_MENU_DLSS_CHARS_DESC);
opt_toggle("TOTK_FXAA", UI_MENU_FXAA, UI_MENU_FXAA_DESC);
rows_color();
opt_group(UI_MENU_HDR_GROUP);
opt_toggle("TOTK_HDR", UI_MENU_HDR, UI_MENU_HDR_DESC);
opt_slider("TOTK_HDR_PEAK_NITS", UI_MENU_HDR_PEAK, 400, 10000, UI_MENU_HDR_PEAK_DESC, 50, "%.0f");
opt_slider("TOTK_HDR_GAME_NITS", UI_MENU_HDR_GAME, 80, 500, UI_MENU_HDR_GAME_DESC, 5, "%.0f");
opt_slider("TOTK_HDR_UI_NITS", UI_MENU_HDR_UI, 80, 500, UI_MENU_HDR_UI_DESC, 5, "%.0f");
opt_slider("TOTK_HDR_HUE", UI_MENU_HDR_HUE, 0, 100, UI_MENU_HDR_HUE_DESC, 5, "%.0f %%");
opt_end();
}
static void tab_game(float scale) {
opt_begin("##game", scale);
row_fps_limit();
opt_toggle("TOTK_REALTIME", UI_MENU_REALTIME, UI_MENU_REALTIME_DESC);
opt_toggle("TOTK_CLOTH_REALTIME", UI_MENU_CLOTH_REALTIME, UI_MENU_CLOTH_REALTIME_DESC);
opt_toggle("TOTK_HIGHFPS_FIX", UI_MENU_HIGHFPS_FIX, UI_MENU_HIGHFPS_FIX_DESC);
row_game_lang();
static const UiTextId mode[] = {UI_MENU_MODE_DOCKED, UI_MENU_MODE_HANDHELD};
opt_choice("TOTK_OPERATION_MODE", UI_MENU_OPERATION_MODE, mode, 2, UI_MENU_OPERATION_MODE_DESC);
@@ -654,17 +711,16 @@ static void tab_game(float scale) {
static void tab_sound(float scale) {
opt_begin("##sound", scale);
opt_slider("TOTK_VOLUME", UI_MENU_VOLUME, 0, 100, UI_MENU_VOLUME_DESC, 5, "%.0f %%");
static const UiTextId channels[] = {UI_MENU_CHANNELS_AUTO, UI_MENU_CHANNELS_STEREO, UI_MENU_CHANNELS_51};
opt_choice("TOTK_AUDIO_CHANNELS", UI_MENU_AUDIO_CHANNELS, channels, 3, UI_MENU_AUDIO_CHANNELS_DESC);
opt_end();
}
// The note under the layout. Xbox prompts (the Nintendo layout with the A/B and X/Y prompts swapped, romfs.c
// overlay_init) change the buttons at once but the prompts only at the next start: "files missing" without
// romfs-patches-xbox, "prompts change after restart" while the prompts in use differ from the choice. Automatic with a
// gamepad connected: "in use: Xbox". NULL otherwise.
// A confirmation is open (Controls: restart, Advanced: reset): B and Esc close it, not the menu; L / R stay on the page.
static bool g_modal;
// The note under the layout: Automatic with a gamepad connected, the layout it picked ("in use: Xbox"). NULL otherwise.
static const char *pad_layout_note(void) {
bool want = !strcasecmp(cfg_value("TOTK_PAD_LAYOUT"), "xbox_prompts");
if (want && !romfs_xbox_prompts_ready()) return menu_text(UI_MENU_PAD_LAYOUT_PROMPTS_MISSING);
if (want != (romfs_xbox_prompts_active() != 0)) return menu_text(UI_MENU_PAD_LAYOUT_PROMPTS_RESTART);
int got = input_pad_layout();
if (got < 0 || strcmp(cfg_value("TOTK_PAD_LAYOUT"), "auto")) return nullptr;
static char note[96];
@@ -673,31 +729,149 @@ static const char *pad_layout_note(void) {
return note;
}
// The action a key presses, or -1: the walk key is a key of its own, but Shift is B in the default bindings, and a
// walk key that also presses something walks and does that something at the same time. The bindings come from a
// snapshot, and every key of an action is looked at: binds_refresh rebuilds the live table on the polling thread while
// the menu draws, and an action may hold more than the two keys its cells show.
static int key_action(const InputMap *m, int key) {
for (int a = 0; a < ACTION_COUNT; a++) {
uint8_t keys[INPUT_BINDING_MAX];
int n = input_map_keys_of(m, a, keys, INPUT_BINDING_MAX);
for (int i = 0; i < n; i++)
if (keys[i] == key) return a;
}
return -1;
}
// The walk key as the handful of keys a player is likely to pick. "none" rather than an empty value closes it: an
// unset key falls back to the default in the settings table, the same as a fresh installation. totk.ini takes any name
// input_map.c knows (walks of the keyboard sticks, not of the gamepad). A key the current bindings also use says which
// action it presses.
static void row_walk_key(void) {
static const char *const keys[] = {"none", "lshift", "lalt", "lctrl", "tab", "capslock"};
const char *names[sizeof keys / sizeof *keys] = {menu_text(UI_MENU_OFF), "Shift", "Alt", "Ctrl", "Tab", "Caps Lock"};
const char *cur = cfg_value("TOTK_WALK_KEY");
static char note[64];
const char *n = nullptr;
InputMap m;
input_map_snapshot(&m);
for (int k = KEY_A; k < KEY_COUNT && !n; k++) {
if (!input_key_name(k) || strcasecmp(input_key_name(k), cur)) continue;
int a = key_action(&m, k);
if (a >= 0 && input_action_name(a)) snprintf(note, sizeof note, menu_text(UI_MENU_WALK_KEY_TAKEN), input_action_name(a)), n = note;
}
opt_choice_list("TOTK_WALK_KEY", UI_MENU_WALK_KEY, keys, names, sizeof keys / sizeof *keys, UI_MENU_WALK_KEY_DESC,
-1, n);
}
// The note under the prompts. The settings name a folder of prompts (input_prompts_folder: the prompts and the pad
// layout, as a layout that puts A on the right button needs the face buttons named the other way round), but the game
// reads its fonts and UI archive once at start (romfs.c overlay_init). While the folder in use differs: "files
// missing" when the setup did not write the one asked for, why it was left out at start (damaged, a game resolution
// that is not 16:9, a RomFS mod with the same files, TOTK_ROMFS_PATCHES), else "prompts change after restart", and only then
// *restart is set: a restart would bring the prompts asked for. NULL when they match.
static const char *prompts_note(bool *restart) {
*restart = false;
const char *layout = cfg_value("TOTK_PAD_LAYOUT"), *used = romfs_prompts();
const char *want = input_prompts_folder(input_prompts_pick(cfg_get("TOTK_PROMPTS"), layout), layout);
if (want == used || (want && used && !strcmp(want, used))) return nullptr;
if (want && !romfs_prompts_ready(want)) return menu_text(UI_MENU_PROMPTS_MISSING);
switch (romfs_prompts_off(want)) {
case ROMFS_PROMPTS_FAILED: return menu_text(UI_MENU_PROMPTS_FAILED);
case ROMFS_PROMPTS_SHAPE: return menu_text(UI_MENU_PROMPTS_OFF_SHAPE);
case ROMFS_PROMPTS_MODS: return menu_text(UI_MENU_PROMPTS_OFF_MODS);
case ROMFS_PROMPTS_PATCHES: return menu_text(UI_MENU_PROMPTS_OFF_PATCHES);
default: *restart = true; return menu_text(UI_MENU_PROMPTS_RESTART);
}
}
// The confirmation of "Restart now", over the menu; Cancel has the cursor first. Restart writes totk.ini, then closes
// the game as Quit does and starts it again (gfx_window_request_restart). It waits while the game writes a save, and
// the game stays when totk.ini cannot be written, as the new prompts would not come back. From the Cheats tab
// (restart_rebuild) Restart also lets the next start rebuild for cheats whose last rebuild failed (cheats_rebuild_allow).
static bool restart_rebuild;
static void restart_confirm(void) {
g_modal = false;
ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
if (!ImGui::BeginPopupModal("##restart_confirm", nullptr,
ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize))
return;
g_modal = true;
ImGui::TextUnformatted(menu_text(UI_MENU_RESTART_CONFIRM));
bool saving = fs_save_busy() != 0;
if (saving || !cfg_last_save_ok())
ImGui::TextColored(ImVec4(0.95f, 0.45f, 0.35f, 1), "%s",
menu_text(saving ? UI_MENU_RESTART_SAVING : UI_MENU_SAVE_FAILED));
ImGui::Spacing();
const char *yes = menu_text(UI_MENU_RESTART_YES), *no = menu_text(UI_MENU_RESET_NO);
const ImGuiStyle &st = ImGui::GetStyle();
float bw = fmaxf(ImGui::CalcTextSize(yes).x, ImGui::CalcTextSize(no).x) + st.FramePadding.x * 4;
bool close = ImGui::Button(no, ImVec2(bw, 0));
if (ImGui::IsWindowAppearing()) ImGui::SetItemDefaultFocus();
ImGui::SameLine();
ImGui::BeginDisabled(saving);
if (ImGui::Button(yes, ImVec2(bw, 0)) && cfg_save()) {
if (restart_rebuild) cheats_rebuild_allow();
gfx_window_request_restart();
}
ImGui::EndDisabled();
if (ImGui::IsKeyPressed(ImGuiKey_Escape, false) || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false))
close = true;
if (close) {
ImGui::CloseCurrentPopup();
restart_rebuild = false;
opt_focus_key("##restart"); // back on the row it came from
}
ImGui::EndPopup();
}
static void tab_controls(float scale) {
opt_begin("##controls", scale);
static const UiTextId layout[] = {UI_MENU_PAD_LAYOUT_AUTO, UI_MENU_PAD_LAYOUT_NINTENDO, UI_MENU_PAD_LAYOUT_XBOX,
UI_MENU_PAD_LAYOUT_XBOX_PROMPTS};
opt_choice("TOTK_PAD_LAYOUT", UI_MENU_PAD_LAYOUT, layout, 4, UI_MENU_PAD_LAYOUT_DESC, pad_layout_note());
static const UiTextId layout[] = {UI_MENU_PAD_LAYOUT_AUTO, UI_MENU_PAD_LAYOUT_NINTENDO, UI_MENU_PAD_LAYOUT_XBOX};
opt_choice("TOTK_PAD_LAYOUT", UI_MENU_PAD_LAYOUT, layout, 3, UI_MENU_PAD_LAYOUT_DESC, pad_layout_note());
static const UiTextId prompts[] = {UI_MENU_PROMPTS_NINTENDO, UI_MENU_PROMPTS_XBOX};
bool restart;
const char *note = prompts_note(&restart);
opt_choice("TOTK_PROMPTS", UI_MENU_PROMPTS, prompts, 2, UI_MENU_PROMPTS_DESC, note);
bool ask = restart && opt_button("##restart", UI_MENU_RESTART, UI_MENU_RESTART_DESC);
opt_toggle("TOTK_MOTION", UI_MENU_MOTION, UI_MENU_MOTION_DESC);
opt_slider("TOTK_RUMBLE_STRENGTH", UI_MENU_RUMBLE_STRENGTH, 0, 300, UI_MENU_RUMBLE_STRENGTH_DESC, 10, "%.0f %%");
opt_slider("TOTK_RUMBLE_CURVE", UI_MENU_RUMBLE_CURVE, 0.2f, 1.5f, UI_MENU_RUMBLE_CURVE_DESC, 0.05f, "%.2f");
opt_toggle("TOTK_RUMBLE_TRIGGERS", UI_MENU_RUMBLE_TRIGGERS, UI_MENU_RUMBLE_TRIGGERS_DESC);
opt_slider("TOTK_STICK_DEADZONE", UI_MENU_STICK_DEADZONE, 0, 50, UI_MENU_STICK_DEADZONE_DESC, 1, "%.0f %%");
opt_slider("TOTK_MOUSE_SENS", UI_MENU_MOUSE_SENS, 0, 10, UI_MENU_MOUSE_SENS_DESC, 0.1f, "%.1f");
row_walk_key();
opt_slider("TOTK_WALK_SCALE", UI_MENU_WALK_SCALE, 0.2f, 0.9f, UI_MENU_WALK_SCALE_DESC, 0.01f, "%.2f");
// Analog sticks: one dead zone row per stick, falling back to TOTK_STICK_DEADZONE (both sticks) while unset. With
// a gamepad connected each row shows its stick's deflection now, before the dead zone: a drifting stick's resting
// value, to set it above.
opt_group(UI_MENU_GROUP_STICKS);
double now[2];
bool pad = input_pad_stick_percent(now) != 0;
char stick_note[2][64];
for (int s = 0; s < 2; s++)
snprintf(stick_note[s], sizeof stick_note[s], menu_text(UI_MENU_STICK_DEADZONE_NOW), now[s]);
opt_slider("TOTK_LSTICK_DEADZONE", UI_MENU_LSTICK_DEADZONE, 0, 50, UI_MENU_STICK_DEADZONE_DESC, 1, "%.0f %%",
pad ? stick_note[0] : nullptr, "TOTK_STICK_DEADZONE");
opt_slider("TOTK_RSTICK_DEADZONE", UI_MENU_RSTICK_DEADZONE, 0, 50, UI_MENU_STICK_DEADZONE_DESC, 1, "%.0f %%",
pad ? stick_note[1] : nullptr, "TOTK_STICK_DEADZONE");
opt_slider("TOTK_STICK_SENS", UI_MENU_STICK_SENS, 0.1f, 3, UI_MENU_STICK_SENS_DESC, 0.05f, "%.2f");
binds_rows(scale);
opt_end();
binds_after_page();
if (ask) ImGui::OpenPopup("##restart_confirm"); // at the level BeginPopupModal looks it up
restart_confirm();
}
static void tab_menu(float scale) {
opt_begin("##menu", scale);
static const UiTextId langs[] = {UI_MENU_MENU_LANG_AUTO, UI_MENU_LANGNAME_EN, UI_MENU_LANGNAME_RU};
opt_choice("TOTK_MENU_LANG", UI_MENU_MENU_LANG, langs, 3, UI_MENU_MENU_LANG_DESC);
static const UiTextId langs[] = {UI_MENU_MENU_LANG_AUTO, UI_MENU_LANGNAME_EN, UI_MENU_LANGNAME_RU,
UI_MENU_LANGNAME_PT_BR, UI_MENU_LANGNAME_ZH_HANS};
opt_choice("TOTK_MENU_LANG", UI_MENU_MENU_LANG, langs, sizeof langs / sizeof *langs, UI_MENU_MENU_LANG_DESC);
opt_toggle("TOTK_DISCORD_RPC", UI_MENU_DISCORD_RPC, UI_MENU_DISCORD_RPC_DESC);
opt_end();
}
// ---- Advanced: the testing and troubleshooting keys, the bug report helpers and the reset of every setting
static bool g_modal; // the reset confirmation is open: B and Esc close it, not the menu; L / R stay on the page
// A thread count with no fixed default: Automatic (unset), then the common counts.
static void row_threads(const char *key, UiTextId label, UiTextId desc) {
@@ -779,7 +953,8 @@ static void tab_advanced(float scale) {
opt_choice("TOTK_MEMORY", UI_MENU_MEMORY, mem, 4, UI_MENU_MEMORY_DESC);
opt_toggle("TOTK_TEX_ALIAS", UI_MENU_TEX_ALIAS, UI_MENU_TEX_ALIAS_DESC);
opt_slider("TOTK_TEX_VRAM_PRESSURE", UI_MENU_TEX_VRAM_PRESSURE, 0, 100, UI_MENU_TEX_VRAM_PRESSURE_DESC, 1, "%.0f%%");
opt_toggle("TOTK_ASTC_BC", UI_MENU_ASTC_BC, UI_MENU_ASTC_BC_DESC);
static const UiTextId astc_bc[] = {UI_MENU_AUTO, UI_MENU_OFF, UI_MENU_ON}; // unset, 0, 1
opt_choice("TOTK_ASTC_BC", UI_MENU_ASTC_BC, astc_bc, 3, UI_MENU_ASTC_BC_DESC);
opt_group(UI_MENU_GROUP_FIXES);
opt_toggle("TOTK_LOD_GUARD", UI_MENU_LOD_GUARD, UI_MENU_LOD_GUARD_DESC);
@@ -805,6 +980,7 @@ static void tab_advanced(float scale) {
row_set_or_not("TOTK_TRACE", UI_MENU_TRACE, UI_MENU_TRACE_DESC, "perf");
opt_toggle("TOTK_FLIGHT", UI_MENU_FLIGHT, UI_MENU_FLIGHT_DESC);
opt_slider("TOTK_FLIGHT_SPIKE_MS", UI_MENU_FLIGHT_SPIKE_MS, 20, 1000, UI_MENU_FLIGHT_SPIKE_MS_DESC, 10, "%.0f");
opt_choice("TOTK_PASS_CRUMBS", UI_MENU_PASS_CRUMBS, dyn, 3, UI_MENU_PASS_CRUMBS_DESC); // vk_crumbs.c pass marks
static char rec_path[600]; // the recording goes beside the log
if (!rec_path[0]) {
char dir[512];
@@ -854,12 +1030,111 @@ static void tab_advanced(float scale) {
}
}
static const UiTextId kTabNames[TAB_COUNT] = {UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_SOUND,
UI_MENU_TAB_CONTROLS, UI_MENU_TAB_MENU, UI_MENU_TAB_ADVANCED};
static const UiTextId kTabNames[TAB_COUNT] = {UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_SOUND,
UI_MENU_TAB_CONTROLS, UI_MENU_TAB_AMIIBO, UI_MENU_TAB_MENU,
UI_MENU_TAB_ADVANCED, UI_MENU_TAB_MODS, UI_MENU_TAB_CHEATS};
static int g_tab; // the tab shown
static int g_tab_request = -1; // select this tab at the next layout; -1 none
static int g_focus_page = -1; // this tab's first row takes the cursor once it is shown; -1 none
// A row of another tab: that tab opens with the row under the cursor.
static void go_to(int tab, const char *key) {
g_tab_request = tab;
opt_focus_key(key);
}
// ---- Mods: the mods folder (mods.c) with switches and the load order, then the port's own patches. The folder was
// read at start; the rows change the order and switches for the next start.
static void mods_builtin_rows(void) {
opt_group(UI_MENU_MODS_BUILTIN);
char fps[64], res[64];
const char *lim = cfg_value("TOTK_FPS_LIMIT");
if (!strcmp(lim, "display")) snprintf(fps, sizeof fps, "%s", menu_text(UI_MENU_FPS_DISPLAY));
else snprintf(fps, sizeof fps, "%s FPS", lim);
if (opt_button("##mods_fps60", UI_MENU_MODS_FPS60, UI_MENU_MODS_FPS60_DESC, fps)) go_to(TAB_GAME, "TOTK_FPS_LIMIT");
int w = 0, h = 0;
sscanf(cfg_value("TOTK_OUTPUT_RES"), "%dx%d", &w, &h);
snprintf(res, sizeof res, "%d × %d", w, h); // U+00D7, as row_output_res shows it
if (opt_button("##mods_res", UI_MENU_MODS_RES, UI_MENU_MODS_RES_DESC, res)) go_to(TAB_SCREEN, "TOTK_OUTPUT_RES");
opt_toggle("TOTK_REALTIME", UI_MENU_REALTIME, UI_MENU_REALTIME_DESC);
opt_toggle("TOTK_CLOTH_REALTIME", UI_MENU_CLOTH_REALTIME, UI_MENU_CLOTH_REALTIME_DESC);
opt_toggle("TOTK_HIGHFPS_FIX", UI_MENU_HIGHFPS_FIX, UI_MENU_HIGHFPS_FIX_DESC);
opt_button("##mods_quickmenu", UI_MENU_MODS_QUICKMENU, UI_MENU_MODS_QUICKMENU_DESC,
menu_text(romfs_patches_loaded() ? UI_MENU_ON : UI_MENU_OFF));
}
static void tab_mods(float scale) {
opt_begin("##mods", scale);
opt_group(UI_MENU_MODS_INSTALLED);
int n = mods_count();
if (!n) opt_text(UI_MENU_MODS_NONE);
const char *after = mods_changed() ? menu_text(UI_MENU_AFTER_RESTART) : nullptr;
for (int i = 0; i < n; i++) {
const ModInfo *m = mods_at(i);
char id[32], desc[1536];
snprintf(id, sizeof id, "##mod%d", i);
char over[512] = "", other[512] = "";
if (m->overridden) snprintf(over, sizeof over, menu_text(UI_MENU_MODS_OVERRIDDEN), m->overridden, m->overridden_by);
if (m->other_version) snprintf(other, sizeof other, menu_text(UI_MENU_MODS_OTHER_VERSION), m->other_version);
char cheat[256] = "";
if (m->kind & MOD_CHEATS) { // its cheats as read at start, or the file they come from
int count = 0;
for (int j = 0; j < cheats_count(); j++)
count += !strcmp(cheats_info(j)->mod, m->name) && cheats_info(j)->kind != CHEAT_HEADING;
if (count) snprintf(cheat, sizeof cheat, menu_text(UI_MENU_MODS_CHEATS), count);
else snprintf(cheat, sizeof cheat, menu_text(UI_MENU_MODS_CHEATS_FILE), cheats_file());
}
char code[512] = "", problem[512] = "";
if (m->nsets && m->overrides[0])
snprintf(code, sizeof code, menu_text(UI_MENU_MODS_REPLACES_BUILTIN), m->nsets, m->overrides);
else if (m->nsets)
snprintf(code, sizeof code, menu_text(UI_MENU_MODS_EXEFS_ON), m->nsets);
switch (m->problem) {
case MOD_EMPTY: snprintf(problem, sizeof problem, "%s", menu_text(UI_MENU_MODS_EMPTY)); break;
case MOD_PLUGIN: snprintf(problem, sizeof problem, "%s", menu_text(UI_MENU_MODS_SUBSDK)); break;
case MOD_EXEFS_LATER: snprintf(problem, sizeof problem, "%s", menu_text(UI_MENU_MODS_EXEFS_LATER)); break;
case MOD_EXEFS_UNSUPPORTED:
snprintf(problem, sizeof problem, menu_text(UI_MENU_MODS_EXEFS_UNSUPPORTED), m->note);
break;
case MOD_EXEFS_OTHER: snprintf(problem, sizeof problem, "%s", menu_text(UI_MENU_MODS_EXEFS_OTHER)); break;
case MOD_BAD_NAME: snprintf(problem, sizeof problem, "%s", menu_text(UI_MENU_MODS_BAD_NAME)); break;
default: break;
}
int k = snprintf(desc, sizeof desc, menu_text(UI_MENU_MODS_ROW_DESC), m->replaced, m->added);
const char *parts[] = {over, other, cheat, code, problem, menu_text(UI_MENU_MODS_MOVE_HINT)};
for (const char *part : parts)
if (*part && k >= 0 && k < (int)sizeof desc) k += snprintf(desc + k, sizeof desc - k, "\n\n%s", part);
const char *note = m->enabled && m->problem != MOD_OK ? menu_text(UI_MENU_MODS_UNUSED) : after;
int s = opt_text_row(id, m->name, menu_text(m->enabled ? UI_MENU_ON : UI_MENU_OFF), note, desc, true);
if (s == 2 || s == -1 || s == 1) {
mods_set_enabled(i, !m->enabled);
opt_save_soon();
} else if ((s == 3 && i > 0) || (s == 4 && i + 1 < n)) {
int to = s == 3 ? i - 1 : i + 1;
mods_move(i, to - i);
snprintf(id, sizeof id, "##mod%d", to);
opt_focus_key(id); // the cursor follows the mod
opt_save_soon();
}
}
bool rebuild =
cheats_rebuild_pending() && opt_button("##restart", UI_MENU_CHEATS_REBUILD, UI_MENU_CHEATS_REBUILD_DESC);
static uint64_t open_failed; // plat_now_ns until which the button says it failed
if (opt_button("##mods_open", UI_MENU_MODS_OPEN, UI_MENU_MODS_OPEN_DESC,
plat_now_ns() < open_failed ? menu_text(UI_MENU_ACTION_FAILED) : "")) {
bool ok = mods_dir()[0] != 0;
if (ok) plat_file_mkdir_p(mods_dir());
if (!ok || !plat_open_folder(mods_dir())) open_failed = plat_now_ns() + 3000000000ull;
}
mods_builtin_rows();
opt_end();
if (rebuild) {
restart_rebuild = true;
ImGui::OpenPopup("##restart_confirm");
}
restart_confirm();
}
// ---- the window: title, tabs (L / R or Q / E switch), the page, and the bottom row with "Continue" and "Quit game".
// B on the gamepad and Esc close it.
static void layout_menu(uint32_t w, uint32_t h, float scale) {
@@ -904,9 +1179,18 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) {
switch (k) {
case TAB_SCREEN: tab_screen(scale); break;
case TAB_GAME: tab_game(scale); break;
case TAB_MODS: tab_mods(scale); break;
case TAB_SOUND: tab_sound(scale); break;
case TAB_CONTROLS: tab_controls(scale); break;
case TAB_AMIIBO: tab_amiibo(scale); break;
case TAB_MENU: tab_menu(scale); break;
case TAB_CHEATS:
if (tab_cheats(scale)) {
restart_rebuild = true;
ImGui::OpenPopup("##restart_confirm");
}
restart_confirm();
break;
case TAB_ADVANCED: tab_advanced(scale); break;
}
ImGui::EndTabItem();
@@ -929,7 +1213,7 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) {
ImGui::SameLine();
if (ImGui::Button(quit, ImVec2(bw, 0))) gfx_window_request_close();
bool was_modal = g_modal || binds_modal();
if (g_tab != TAB_ADVANCED) g_modal = false;
if (g_tab != TAB_ADVANCED && g_tab != TAB_CONTROLS) g_modal = false;
if (!was_modal && (ImGui::IsKeyPressed(ImGuiKey_Escape, false) || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false)))
set_open(0);
ImGui::End();
@@ -1066,7 +1350,11 @@ static void perf_picture(const MenuTarget *t, const ImVec4 &c) {
int s = cfg_int("TOTK_SHARPNESS");
snprintf(v[3], sizeof v[3], menu_text(UI_MENU_OV_FMT_FSR), s < 0 ? 0 : s > 100 ? 100 : s);
} else {
snprintf(v[3], sizeof v[3], "%s", menu_text(t->scaler ? UI_MENU_OV_SCALE_BILINEAR : UI_MENU_OV_SCALE_NONE));
// FSR enlarges only (vk_fsr_record): an image larger than the window is shrunk by the blit even with FSR selected
int down = t->scaler == 1 && !strcmp(cfg_value("TOTK_UPSCALER"), "fsr") &&
(t->image_w > (int)t->width || t->image_h > (int)t->height);
snprintf(v[3], sizeof v[3], "%s",
menu_text(down ? UI_MENU_OV_SCALE_DOWN : t->scaler ? UI_MENU_OV_SCALE_BILINEAR : UI_MENU_OV_SCALE_NONE));
}
double hz = frame_step_limit_hz();
snprintf(v[4], sizeof v[4], "%s", menu_text(UI_MENU_OV_NONE));
@@ -1103,17 +1391,30 @@ static void perf_full_draw(const MenuTarget *t, float scale) {
ImGui::SetWindowFontScale(0.72f);
const ImVec4 gpu_c(0.55f, 0.83f, 0.31f, 1), cpu_c(0.18f, 0.59f, 0.80f, 1), ram_c(0.80f, 0.45f, 0.70f, 1),
fps_c(0.95f, 0.95f, 0.95f, 1), wait_c(0.93f, 0.76f, 0.33f, 1), pic_c(0.62f, 0.70f, 0.95f, 1);
// the port version and the game update first, so a screenshot in a bug report carries both; formatted once per
// menu language
static char ver[96];
static const char *ver_fmt;
if (ver_fmt != menu_text(UI_MENU_VERSION)) {
ver_fmt = menu_text(UI_MENU_VERSION);
char game[16];
snprintf(game, sizeof game, "%d.%d.%d", rt_game_version / 100, rt_game_version / 10 % 10, rt_game_version % 10);
snprintf(ver, sizeof ver, ver_fmt, rt_port_version, game);
}
ImGui::TextDisabled("%s", ver);
if (ImGui::BeginTable("##perft", 4, ImGuiTableFlags_SizingFixedFit)) {
static const UiTextId labels[] = {UI_MENU_OV_GPU, UI_MENU_OV_VRAM, UI_MENU_OV_CPU, UI_MENU_OV_RAM};
static const PerfCol c0[] = {{UI_MENU_OV_FPS, 888}};
static const PerfCol c1[] = {{UI_MENU_OV_FMT_PCT, 100}, {UI_MENU_OV_FMT_GB, 888.8f}, {UI_MENU_OV_FRAME_MS, 888.8f}};
static const PerfCol c2[] = {{UI_MENU_OV_FMT_TEMP, 188}, {UI_MENU_OV_FMT_GB_OF, 888.8f}, {UI_MENU_OV_MAX_MS, 8888.8f}};
static const UiTextId labels[] = {UI_MENU_OV_GPU, UI_MENU_OV_VRAM, UI_MENU_OV_CPU, UI_MENU_OV_RAM,
UI_MENU_OV_FPS_LABEL, UI_MENU_OV_FRAME_LABEL};
static const PerfCol c1[] = {{UI_MENU_OV_FMT_PCT, 100}, {UI_MENU_OV_FMT_GB, 888.8f}, {UI_MENU_OV_FMT_FPS, 888},
{UI_MENU_OV_FRAME_MS, 888.8f}};
static const PerfCol c2[] = {{UI_MENU_OV_FMT_TEMP, 188}, {UI_MENU_OV_FMT_GB_OF, 888.8f}, {UI_MENU_OV_LOW1, 888},
{UI_MENU_OV_MAX_MS, 8888.8f}};
static const PerfCol c3[] = {{UI_MENU_OV_FMT_POWER, 888}, {UI_MENU_OV_FMT_MHZ, 8888}, {UI_MENU_OV_GAME_PCT, 100},
{UI_MENU_OV_GAME_GB, 888.8f}};
perf_column("##c0", c0, 1, labels, 4);
perf_column("##c1", c1, 3);
perf_column("##c2", c2, 3);
perf_column("##c3", c3, 4);
{UI_MENU_OV_GAME_GB, 888.8f}, {UI_MENU_OV_LOW01, 888}};
perf_column("##c0", nullptr, 0, labels, 6);
perf_column("##c1", c1, 4);
perf_column("##c2", c2, 4);
perf_column("##c3", c3, 5);
perf_label(UI_MENU_OV_GPU, gpu_c);
perf_cell(UI_MENU_OV_FMT_PCT, s.gpu_pct);
perf_cell(UI_MENU_OV_FMT_TEMP, s.gpu_temp_c);
@@ -1130,12 +1431,16 @@ static void perf_full_draw(const MenuTarget *t, float scale) {
perf_cell(UI_MENU_OV_FMT_GB, perf_gb(s.ram_used_mb));
perf_cell(UI_MENU_OV_FMT_GB_OF, perf_gb(s.ram_total_mb));
perf_cell(UI_MENU_OV_GAME_GB, perf_gb(s.ram_game_mb));
ImGui::TableNextColumn(); // the frame row: no label, the rate in its place
char b[64];
snprintf(b, sizeof b, menu_text(UI_MENU_OV_FPS), s.fps);
ImGui::TextColored(fps_c, "%s", b);
ImGui::TableNextRow(ImGuiTableRowFlags_None, 6 * scale); // a gap between the machine and the frames
// the frames: the rate over the last second with the lows over the last ten seconds, then the frame times
perf_label(UI_MENU_OV_FPS_LABEL, fps_c);
perf_cell(UI_MENU_OV_FMT_FPS, s.fps);
perf_cell(UI_MENU_OV_LOW1, s.low1_fps);
perf_cell(UI_MENU_OV_LOW01, s.low01_fps);
perf_label(UI_MENU_OV_FRAME_LABEL, fps_c);
perf_cell(UI_MENU_OV_FRAME_MS, s.frame_ms_avg);
perf_cell(UI_MENU_OV_MAX_MS, s.frame_ms_max);
ImGui::TableNextColumn();
ImGui::EndTable();
}
float top = s.frame_ms_max > 50 ? s.frame_ms_max : 50;
@@ -1183,10 +1488,12 @@ static void perf_draw(const MenuTarget *t, float scale) {
extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const char **shot) {
*shot = NULL;
cheats_frame(frame); // the data cheats and the buttons of the cheats that need them held
if (!g_test.parsed) test_parse();
if (g_test.next_set < g_test.n_sets && frame >= g_test.sets[g_test.next_set].frame) test_apply_sets(frame);
if (g_perf_save.exchange(0)) cfg_save();
perf_tick(plat_now_ns(), t);
amiibo_tick();
bool open = g_open.load(std::memory_order_relaxed);
if (!open) {
if (g_save_pending) g_save_pending = opt_save_tick(1); // closed: the last change goes to totk.ini now
+4 -2
View File
@@ -5,8 +5,9 @@
//
// F1 or Esc on the keyboard and Minus and Plus held together (consumed in poll_merged, input_menu_gate in input.h) open it;
// F1, Esc, B or "Continue" close it. While it is open the game gets no input (input_menu, input.h) and keeps running; the
// cursor is released from the mouse camera. Tabs Screen, Game, Sound, Controls and Menu (L / R or Q / E switch them) hold
// option rows (ui/option_rows.h) over the cfg settings; the bottom row has "Continue" and "Quit game".
// cursor is released from the mouse camera. Tabs Screen, Game, Mods, Sound, Controls and Menu (L / R or Q / E switch
// them) hold option rows (ui/option_rows.h) over the cfg settings and the mods folder (mods.h); the bottom row has
// "Continue" and "Quit game".
// Test hooks (ui/menu.cpp): TOTK_MENU_TEST=<frame>[:<frames per page>] opens the menu at that presented frame and saves
// one swapchain shot per tab into TOTK_MENU_TEST_DIR; TOTK_MENU_TEST_SET=<frame>:<key>=<value>[,...][;...] sets settings
// at given frames without input (SAVE=1 writes totk.ini).
@@ -60,6 +61,7 @@ int menu_font_check(void);
// ---- what the menu asks of the platform side (gfx_window_win.c, gfx_window_sdl.c)
void gfx_window_apply_settings(void); // TOTK_FULLSCREEN or TOTK_WINDOW_SIZE changed: the window follows
void gfx_window_request_close(void); // as the window's close button: the process ends
void gfx_window_request_restart(void); // the same, then totk.exe starts again with the same command line
int gfx_window_monitor_size(int *w, int *h); // pixels of the monitor the window is on; 0 when unknown
double gfx_window_refresh_hz(void); // its refresh rate (TOTK_FPS_LIMIT=display); 0 when unknown
unsigned gfx_window_dpi(void); // the window's DPI (96 at 100% display scale); any thread
+80 -19
View File
@@ -33,15 +33,15 @@ static char g_focus_key[64]; // opt_focus_key: the row that takes th
static bool g_held; // the last row's left / right has been held a while (steppers go faster)
static float g_bottom; // opt_reserve_bottom: kept free under the panes
static bool g_disable_next; // opt_disable_next: the next row is greyed out with g_disable_note
static UiTextId g_disable_note;
static const char *g_disable_note;
// The description pane: this frame's hovered and selected rows, the page's first row, and the last one shown.
struct Desc { char text[UI_DESC_BYTES]; };
static Desc g_hover, g_focus, g_first, g_shown;
// disabled: the note of a row opt_disable_next greyed out, else NULL.
static void desc_set(Desc &d, UiTextId desc, const char *key, const CfgMeta *m, const char *disabled) {
int n = snprintf(d.text, sizeof d.text, "%s", menu_text(desc));
static void desc_set(Desc &d, const char *desc, const char *key, const CfgMeta *m, const char *disabled) {
int n = snprintf(d.text, sizeof d.text, "%s", desc);
if (n < 0 || n >= (int)sizeof d.text) return;
if (disabled)
snprintf(d.text + n, sizeof d.text - n, "\n\n%s", disabled);
@@ -56,8 +56,11 @@ void opt_focus_first(void) { g_focus_req = true; }
void opt_focus_key(const char *key) { snprintf(g_focus_key, sizeof g_focus_key, "%s", key); }
void opt_reserve_bottom(float h) { g_bottom = h; }
float opt_bottom(void) { return g_bottom; }
void opt_disable_next(UiTextId note) {
void opt_disable_next(UiTextId note) { opt_disable_next_text(menu_text(note)); }
void opt_disable_next_text(const char *note) {
g_disable_next = true;
g_disable_note = note;
}
@@ -107,11 +110,12 @@ struct RowView {
const char *note; // under the value instead of the "default" mark; NULL for none
};
// One row: draws it, handles A / click and left / right while selected. Returns 2 (A / click), -1 / +1 (left / right) or
// 0; always 0 for a row the environment fixes (greyed out, still selectable so its description shows).
static int row(const char *key, UiTextId label, UiTextId desc, const RowView &v) {
// One row: draws it, handles A / click and left / right while selected. Returns 2 (A / click), -1 / +1 (left / right),
// 3 / 4 (move up / down, movable rows only) or 0; always 0 for a row the environment fixes (greyed out, still selectable
// so its description shows). movable: the top / left face buttons, Ctrl+Up / Ctrl+Down and two drawn arrows move it.
static int row_text(const char *key, const char *label, const char *desc, const RowView &v, bool movable) {
const CfgMeta *m = cfg_meta(key);
const char *disabled = g_disable_next ? menu_text(g_disable_note) : NULL;
const char *disabled = g_disable_next ? g_disable_note : NULL;
g_disable_next = false;
bool off = disabled || cfg_from_env(key) != 0;
ImGui::PushID(key);
@@ -145,6 +149,13 @@ static int row(const char *key, UiTextId label, UiTextId desc, const RowView &v)
// left and right belong to the row (navigation would otherwise move sideways into the description pane)
ImGui::SetKeyOwner(k, ImGui::GetItemID());
}
if (movable) {
bool ctrl = ImGui::GetIO().KeyCtrl;
if (ImGui::IsKeyPressed(ImGuiKey_GamepadFaceUp, false) || (ctrl && ImGui::IsKeyPressed(ImGuiKey_UpArrow)))
step = 3;
if (ImGui::IsKeyPressed(ImGuiKey_GamepadFaceLeft, false) || (ctrl && ImGui::IsKeyPressed(ImGuiKey_DownArrow)))
step = 4;
}
}
if (foc) desc_set(g_focus, desc, key, m, disabled);
if (hov) desc_set(g_hover, desc, key, m, disabled);
@@ -174,11 +185,25 @@ static int row(const char *key, UiTextId label, UiTextId desc, const RowView &v)
right = rx - gap;
value_left = lx;
}
if (movable) { // up and down arrows left of the value; a click on one moves the row
// a fixed value column (On / Off differ in width) keeps the arrows of the rows in one line
float aw = fs * 0.42f, gap = fs * 0.55f;
float cx = right - fmaxf(ImGui::CalcTextSize(v.value).x, fs * 2.8f) - gap * 2 - aw;
float uy = ty + fs * 0.12f, dy = ty + fs * 0.92f;
ImU32 ac = off ? kGrey : hov || foc ? kGold : IM_COL32(170, 170, 160, 255);
dl->AddTriangleFilled(ImVec2(cx, uy + aw * 0.7f), ImVec2(cx + aw, uy + aw * 0.7f), ImVec2(cx + aw * 0.5f, uy), ac);
dl->AddTriangleFilled(ImVec2(cx, dy - aw * 0.7f), ImVec2(cx + aw, dy - aw * 0.7f), ImVec2(cx + aw * 0.5f, dy), ac);
if (clicked && !off) {
ImVec2 mp = ImGui::GetIO().MousePos;
if (mp.x >= cx - gap * 0.5f && mp.x <= cx + aw + gap * 0.5f) step = mp.y < ty + fs * 0.52f ? 3 : 4;
}
value_left = cx - gap;
}
if (v.value[0]) {
float vx = right - ImGui::CalcTextSize(v.value).x;
dl->AddText(ImVec2(vx, ty), off ? kGrey : v.is_default ? IM_COL32(205, 205, 195, 255) : IM_COL32(255, 255, 255, 255),
v.value);
if (!v.arrows) value_left = vx;
if (!v.arrows && !movable) value_left = vx;
}
if (v.note || v.is_default) { // under the value, right-aligned with it
const char *t = v.note ? v.note : menu_text(UI_MENU_DEFAULT_MARK);
@@ -187,8 +212,7 @@ static int row(const char *key, UiTextId label, UiTextId desc, const RowView &v)
}
// the label and its note, clipped before the value
ImVec4 clip(p.x, p.y, value_left - fs * 0.6f, p.y + h);
dl->AddText(font, fs, ImVec2(p.x + pad, ty), off ? kGrey : IM_COL32(240, 236, 224, 255), menu_text(label), NULL, 0,
&clip);
dl->AddText(font, fs, ImVec2(p.x + pad, ty), off ? kGrey : IM_COL32(240, 236, 224, 255), label, NULL, 0, &clip);
const char *note = disabled ? disabled
: off ? menu_text(UI_MENU_SET_BY_ENV)
: m && !m->live ? menu_text(UI_MENU_AFTER_RESTART)
@@ -198,6 +222,16 @@ static int row(const char *key, UiTextId label, UiTextId desc, const RowView &v)
return off ? 0 : step;
}
static int row(const char *key, UiTextId label, UiTextId desc, const RowView &v) {
return row_text(key, menu_text(label), menu_text(desc), v, false);
}
int opt_text_row(const char *id, const char *label, const char *value, const char *note, const char *desc,
bool movable) {
RowView v = {value ? value : "", false, false, note};
return row_text(id, label, desc, v, movable);
}
// ---- writing a setting: at once in memory (live settings follow), to totk.ini a moment later (opt_save_tick)
static uint64_t g_save_at; // plat_now_ns deadline of the pending write; 0 none
static bool g_save_logged;
@@ -241,6 +275,26 @@ bool opt_button(const char *id, UiTextId label, UiTextId desc, const char *value
return row(id, label, desc, v) == 2; // A or a click; left and right do nothing
}
bool opt_toggle_text(const char *id, const char *label, const char *desc, bool on, const char *value) {
// off is the plain state: its value drawn dim, without the "default" mark
RowView v = {value ? value : menu_text(on ? UI_MENU_ON : UI_MENU_OFF), !on, false, on ? NULL : ""};
return row_text(id, label, desc, v, false) != 0; // any step flips it
}
void opt_group_text(const char *title) {
ImGui::Dummy(ImVec2(0, 6 * g_scale));
ImGui::PushTextWrapPos(0);
ImGui::TextColored(ImVec4(0.93f, 0.76f, 0.33f, 1), "%s", title);
ImGui::PopTextWrapPos();
}
void opt_text_str(const char *text, bool warn) {
ImGui::PushTextWrapPos(0);
if (warn) ImGui::TextColored(ImVec4(0.95f, 0.66f, 0.40f, 1), "%s", text);
else ImGui::TextUnformatted(text);
ImGui::PopTextWrapPos();
}
void opt_group(UiTextId title) {
ImGui::Dummy(ImVec2(0, 6 * g_scale));
ImGui::TextColored(ImVec4(0.93f, 0.76f, 0.33f, 1), "%s", menu_text(title));
@@ -294,12 +348,18 @@ bool opt_choice(const char *key, UiTextId label, const UiTextId *names, int n, U
return opt_choice_list(key, label, values, shown, n, desc, -1, note);
}
bool opt_slider(const char *key, UiTextId label, float lo, float hi, UiTextId desc, float step, const char *fmt) {
const CfgMeta *m = cfg_meta(key);
double v = cfg_double(key), def = m ? strtod(m->def, NULL) : lo;
bool opt_slider(const char *key, UiTextId label, float lo, float hi, UiTextId desc, float step, const char *fmt,
const char *note, const char *fallback) {
const char *set = cfg_get(key);
const char *src = fallback && !(set && *set) ? fallback : key; // unset: show the value in effect, the fallback's
const CfgMeta *m = cfg_meta(src);
// A key without a table default of its own (the per-stick dead zones) defaults to its fallback: the "default" mark
// follows the fallback's default, not 0, even once the key is set.
if (fallback && m && !m->def[0]) m = cfg_meta(fallback);
double v = cfg_double(src), def = m && m->def[0] ? strtod(m->def, NULL) : lo;
char shown[48];
snprintf(shown, sizeof shown, fmt, v);
RowView rv = {shown, fabs(v - def) < step * 0.01, true, NULL};
RowView rv = {shown, fabs(v - def) < step * 0.01, true, note};
int s = row(key, label, desc, rv);
if (!s) return false;
int steps = g_held && (hi - lo) > 40 * step ? 10 : 1; // held: ten steps at a time over a long range
@@ -310,7 +370,8 @@ bool opt_slider(const char *key, UiTextId label, float lo, float hi, UiTextId de
char out[32];
if (step >= 1) snprintf(out, sizeof out, "%d", (int)lround(n));
else snprintf(out, sizeof out, "%g", round(n / step) * step);
apply(key, out);
// Landing on the fallback's value unsets the key (its line leaves totk.ini), so the row follows the fallback again.
apply(key, fallback && fabs(n - cfg_double(fallback)) < step * 0.01 ? "" : out);
return true;
}
@@ -400,9 +461,9 @@ int opt_bind_row(const char *key, const char *label, UiTextId desc, const char *
}
char k[64];
snprintf(k, sizeof k, "TOTK_%s", key);
if (row_foc) desc_set(g_focus, desc, k, NULL, NULL);
if (row_hov) desc_set(g_hover, desc, k, NULL, NULL);
if (!g_first.text[0]) desc_set(g_first, desc, k, NULL, NULL);
if (row_foc) desc_set(g_focus, menu_text(desc), k, NULL, NULL);
if (row_hov) desc_set(g_hover, menu_text(desc), k, NULL, NULL);
if (!g_first.text[0]) desc_set(g_first, menu_text(desc), k, NULL, NULL);
if (note && (row_foc || row_hov)) { // e.g. what moved here, after the description
Desc &d = row_hov ? g_hover : g_focus;
size_t n = strlen(d.text);
+18 -1
View File
@@ -19,12 +19,15 @@ void opt_begin(const char *id, float scale);
void opt_end(void);
// The height the next pages leave free under their panes (the menu's bottom row).
void opt_reserve_bottom(float h);
// The height opt_reserve_bottom keeps free, for a tab that lays out its own panes (ui/amiibo_page.cpp).
float opt_bottom(void);
// The next page's first row takes the controller's cursor (opening the menu, switching tabs).
void opt_focus_first(void);
// The row of key (or button id) takes the cursor, scrolled into view, when it is next drawn.
void opt_focus_key(const char *key);
// The next row is greyed out like one the environment fixes, with note under its label and in its description.
void opt_disable_next(UiTextId note);
void opt_disable_next_text(const char *note); // note must outlive the frame
// Page text that is not a row: a group heading in the accent colour, a wrapped paragraph (warn: the warning colour).
void opt_group(UiTextId title);
@@ -45,9 +48,23 @@ bool opt_choice_list(const char *key, UiTextId label, const char *const *values,
// A row that runs an action: true on A or a click. id: unique on the page and not a setting ("##copy_info"); value:
// shown on the right ("" none).
bool opt_button(const char *id, UiTextId label, UiTextId desc, const char *value = "");
// A row whose label, value, note (under the value) and description are text, not catalog ids: a mod's folder name.
// Returns 2 (A / click), -1 / +1 (left / right), 3 / 4 (move up / down: the top / left face buttons, Ctrl+Up /
// Ctrl+Down, the drawn arrows; movable rows only) or 0.
int opt_text_row(const char *id, const char *label, const char *value, const char *note, const char *desc,
bool movable);
// Rows and text that are not settings of the cfg table: a label and description of the caller's own (the cheats of
// the cheat files). opt_toggle_text shows on / off (value: shown instead, NULL for On / Off) and returns true on A, a
// click, left or right; the caller changes its state. id: unique on the page, the environment check uses it.
bool opt_toggle_text(const char *id, const char *label, const char *desc, bool on, const char *value = nullptr);
void opt_group_text(const char *title);
void opt_text_str(const char *text, bool warn = false);
// lo..hi in steps of step (left and right held for a second go ten times as fast); fmt formats the value ("%.0f %%").
// note: a short line under the value in place of the "default" mark (NULL: none). fallback: the setting that applies
// while key is unset; the row shows its value then, and a change sets key. A key with no table default of its own takes
// the "default" mark from the fallback's default, and a step onto the fallback's value unsets key again.
bool opt_slider(const char *key, UiTextId label, float lo, float hi, UiTextId desc, float step = 1,
const char *fmt = "%g");
const char *fmt = "%g", const char *note = nullptr, const char *fallback = nullptr);
// Binding rows (remapping on the Controls tab): a label and three cells, each selectable on its own (left / right move between them).
// opt_bind_header: the column titles above them. opt_bind_row: key is the setting's name without TOTK_ (BIND_A; the
+1509 -37
View File
File diff suppressed because it is too large. Load diff
+86 -11
View File
@@ -11,11 +11,12 @@ typedef enum {
UI_SWKBD_CANCEL,
UI_SWKBD_PAD_HINT, // how a controller answers
// Menu: window, tabs, bottom row. UI_MENU_FIRST..UI_MENU_LAST_ID carry English and Russian texts.
// Menu: window, tabs, bottom row. UI_MENU_FIRST..UI_MENU_LAST_ID carry English, Russian, Brazilian Portuguese and
// Simplified Chinese texts.
UI_MENU_FIRST,
UI_MENU_TITLE = UI_MENU_FIRST,
UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_SOUND, UI_MENU_TAB_CONTROLS, UI_MENU_TAB_MENU,
UI_MENU_TAB_ADVANCED,
UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_MODS, UI_MENU_TAB_SOUND, UI_MENU_TAB_CONTROLS, UI_MENU_TAB_AMIIBO,
UI_MENU_TAB_MENU, UI_MENU_TAB_ADVANCED,
UI_MENU_CONTINUE, UI_MENU_QUIT,
UI_MENU_ON, UI_MENU_OFF, UI_MENU_AUTO, UI_MENU_DEFAULT_MARK, // "default" beside the default value
UI_MENU_AFTER_RESTART, // note on a setting that is read at start
@@ -37,6 +38,7 @@ typedef enum {
UI_MENU_UPSCALER, UI_MENU_UPSCALER_DESC, UI_MENU_UPSCALER_FSR, UI_MENU_UPSCALER_BILINEAR,
UI_MENU_ASPECT, UI_MENU_ASPECT_DESC, UI_MENU_ASPECT_FIT, UI_MENU_ASPECT_STRETCH,
UI_MENU_FOV, UI_MENU_FOV_DESC,
UI_MENU_SHADOW_RES, UI_MENU_SHADOW_RES_DESC, UI_MENU_SHADOW_RES_GAME,
UI_MENU_ANISO, UI_MENU_ANISO_DESC, UI_MENU_ANISO_GAME,
UI_MENU_LOD_DETAIL, UI_MENU_LOD_DETAIL_DESC, UI_MENU_LOD_STEADY, UI_MENU_LOD_STEADY_DESC,
UI_MENU_SHARPNESS, UI_MENU_SHARPNESS_DESC,
@@ -45,6 +47,17 @@ typedef enum {
UI_MENU_COLOR_CUSTOM,
UI_MENU_COLOR_BRIGHTNESS, UI_MENU_COLOR_BRIGHTNESS_DESC, UI_MENU_COLOR_CONTRAST, UI_MENU_COLOR_CONTRAST_DESC,
UI_MENU_COLOR_SATURATION, UI_MENU_COLOR_SATURATION_DESC, UI_MENU_COLOR_GAMMA, UI_MENU_COLOR_GAMMA_DESC,
UI_MENU_HDR_GROUP, // group heading over the HDR rows
UI_MENU_HDR, UI_MENU_HDR_DESC, UI_MENU_HDR_PEAK, UI_MENU_HDR_PEAK_DESC, UI_MENU_HDR_GAME, UI_MENU_HDR_GAME_DESC,
UI_MENU_HDR_UI, UI_MENU_HDR_UI_DESC, UI_MENU_HDR_HUE, UI_MENU_HDR_HUE_DESC,
UI_MENU_SHADOW_SCALE, UI_MENU_SHADOW_SCALE_DESC,
UI_MENU_SHADOW_RANGE, UI_MENU_SHADOW_RANGE_DESC,
UI_MENU_CONTACT_SHADOWS, UI_MENU_CONTACT_SHADOWS_DESC,
UI_MENU_PCSS, UI_MENU_PCSS_DESC,
UI_MENU_DLAA, UI_MENU_DLAA_DESC, UI_MENU_DLSS, UI_MENU_DLSS_DESC, UI_MENU_DLSS_DLAA, UI_MENU_DLSS_QUALITY,
UI_MENU_DLSS_BALANCED, UI_MENU_DLSS_PERFORMANCE, UI_MENU_DLSS_ULTRA, UI_MENU_DLSS_PRESET, UI_MENU_DLSS_PRESET_DESC,
UI_MENU_DLSS_PRESET_DEFAULT, UI_MENU_DLSS_PRESET_K, UI_MENU_DLSS_PRESET_J, UI_MENU_DLSS_CHARS, UI_MENU_DLSS_CHARS_DESC,
UI_MENU_DLSS_CHARS_OFF, UI_MENU_DLSS_CHARS_LIGHT, UI_MENU_DLSS_CHARS_MEDIUM, UI_MENU_DLSS_CHARS_FULL, UI_MENU_FXAA, UI_MENU_FXAA_DESC,
// Game
UI_MENU_FPS_LIMIT, UI_MENU_FPS_LIMIT_DESC, UI_MENU_FPS_30, UI_MENU_FPS_40, UI_MENU_FPS_45, UI_MENU_FPS_60, UI_MENU_FPS_90,
@@ -57,8 +70,28 @@ typedef enum {
UI_MENU_OPERATION_MODE, UI_MENU_OPERATION_MODE_DESC, UI_MENU_MODE_DOCKED, UI_MENU_MODE_HANDHELD,
UI_MENU_ASSUME_FOCUS, UI_MENU_ASSUME_FOCUS_DESC,
// Mods: the port's own patches and the player's mods folder (mods.c)
UI_MENU_MODS_BUILTIN, UI_MENU_MODS_INSTALLED,
UI_MENU_MODS_NONE, // no mod folder yet: where to unpack one
UI_MENU_MODS_OPEN, UI_MENU_MODS_OPEN_DESC,
UI_MENU_MODS_ROW_DESC, // printf: files it replaces, files it adds (as of this start)
UI_MENU_MODS_OVERRIDDEN, // printf: files a higher mod serves instead, that mod's name
UI_MENU_MODS_MOVE_HINT,
UI_MENU_MODS_EMPTY, UI_MENU_MODS_SUBSDK, UI_MENU_MODS_EXEFS_LATER, UI_MENU_MODS_BAD_NAME,
UI_MENU_MODS_EXEFS_UNSUPPORTED, // printf: the file and why
UI_MENU_MODS_EXEFS_OTHER,
UI_MENU_MODS_EXEFS_ON, // printf: its ExeFS patch files in use
UI_MENU_MODS_REPLACES_BUILTIN, // printf: its ExeFS patch files in use, the port's own patch sets they turn off
UI_MENU_MODS_OTHER_VERSION, // printf: files made for another game version, left out
UI_MENU_MODS_UNUSED, // under the switch of a mod the port cannot use
UI_MENU_MODS_CHEATS, // printf: its cheats as read at start
UI_MENU_MODS_CHEATS_FILE, // printf: <build id>.txt, when none were read
UI_MENU_MODS_FPS60, UI_MENU_MODS_FPS60_DESC, UI_MENU_MODS_RES, UI_MENU_MODS_RES_DESC,
UI_MENU_MODS_QUICKMENU, UI_MENU_MODS_QUICKMENU_DESC,
// Sound
UI_MENU_VOLUME, UI_MENU_VOLUME_DESC,
UI_MENU_AUDIO_CHANNELS, UI_MENU_AUDIO_CHANNELS_DESC, UI_MENU_CHANNELS_AUTO, UI_MENU_CHANNELS_STEREO, UI_MENU_CHANNELS_51,
// Controls
UI_MENU_MOTION, UI_MENU_MOTION_DESC,
@@ -66,10 +99,17 @@ typedef enum {
UI_MENU_RUMBLE_CURVE, UI_MENU_RUMBLE_CURVE_DESC,
UI_MENU_RUMBLE_TRIGGERS, UI_MENU_RUMBLE_TRIGGERS_DESC,
UI_MENU_PAD_LAYOUT, UI_MENU_PAD_LAYOUT_DESC, UI_MENU_PAD_LAYOUT_AUTO, UI_MENU_PAD_LAYOUT_NINTENDO,
UI_MENU_PAD_LAYOUT_XBOX, UI_MENU_PAD_LAYOUT_XBOX_PROMPTS, UI_MENU_PAD_LAYOUT_IN_USE,
UI_MENU_PAD_LAYOUT_PROMPTS_MISSING, UI_MENU_PAD_LAYOUT_PROMPTS_RESTART,
UI_MENU_STICK_DEADZONE, UI_MENU_STICK_DEADZONE_DESC,
UI_MENU_PAD_LAYOUT_XBOX, UI_MENU_PAD_LAYOUT_IN_USE,
UI_MENU_PROMPTS, UI_MENU_PROMPTS_DESC, UI_MENU_PROMPTS_NINTENDO, UI_MENU_PROMPTS_XBOX,
// the notes under the prompts: their files are missing or damaged, they change after restart, or why they are off
UI_MENU_PROMPTS_MISSING, UI_MENU_PROMPTS_FAILED, UI_MENU_PROMPTS_RESTART, UI_MENU_PROMPTS_OFF_SHAPE,
UI_MENU_PROMPTS_OFF_MODS, UI_MENU_PROMPTS_OFF_PATCHES,
// "Restart now" under the prompts while they change after restart, and its confirmation (Cancel: UI_MENU_RESET_NO)
UI_MENU_RESTART, UI_MENU_RESTART_DESC, UI_MENU_RESTART_CONFIRM, UI_MENU_RESTART_YES, UI_MENU_RESTART_SAVING,
UI_MENU_GROUP_STICKS, UI_MENU_LSTICK_DEADZONE, UI_MENU_RSTICK_DEADZONE, UI_MENU_STICK_DEADZONE_DESC,
UI_MENU_STICK_DEADZONE_NOW, UI_MENU_STICK_SENS, UI_MENU_STICK_SENS_DESC,
UI_MENU_MOUSE_SENS, UI_MENU_MOUSE_SENS_DESC,
UI_MENU_WALK_KEY, UI_MENU_WALK_KEY_DESC, UI_MENU_WALK_KEY_TAKEN, UI_MENU_WALK_SCALE, UI_MENU_WALK_SCALE_DESC,
// Controls tab: the remapping rows (ui/binds_page.cpp)
UI_BINDS_HELP, UI_BINDS_COL_KEY1, UI_BINDS_COL_KEY2, UI_BINDS_COL_PAD,
@@ -101,13 +141,26 @@ typedef enum {
UI_PAD_ZR, UI_PAD_LPADDLE1, UI_PAD_RPADDLE1, UI_PAD_LPADDLE2, UI_PAD_RPADDLE2,
UI_PAD_CROSS, UI_PAD_CIRCLE, UI_PAD_SQUARE, UI_PAD_TRIANGLE,
// Amiibo tab (ui/amiibo_page.cpp): the dump folder and its files, the emulated NFC reader and its state, the
// amiibo on it and the last action
UI_MENU_AMIIBO_DIR, UI_MENU_AMIIBO_OPEN, UI_MENU_AMIIBO_DEFAULT_DIR, UI_MENU_AMIIBO_REFRESH, UI_MENU_AMIIBO_PICK,
UI_MENU_AMIIBO_NO_DIR, UI_MENU_AMIIBO_READER, UI_MENU_AMIIBO_STATE, UI_MENU_AMIIBO_STATE_IDLE,
UI_MENU_AMIIBO_STATE_SEARCHING, UI_MENU_AMIIBO_STATE_FOUND, UI_MENU_AMIIBO_STATE_MOUNTED,
UI_MENU_AMIIBO_STATE_OFF, UI_MENU_AMIIBO_FILE, UI_MENU_AMIIBO_NO_FILE, UI_MENU_AMIIBO_TAP, UI_MENU_AMIIBO_REMOVE,
UI_MENU_AMIIBO_AUTO_REMOVE, UI_MENU_AMIIBO_HOLD, UI_MENU_AMIIBO_SECONDS, UI_MENU_AMIIBO_TAG,
UI_MENU_AMIIBO_NO_TAG, UI_MENU_AMIIBO_TAG_FILE, UI_MENU_AMIIBO_TAG_ID, UI_MENU_AMIIBO_TAG_UID,
UI_MENU_AMIIBO_READY, UI_MENU_AMIIBO_TAPPED, UI_MENU_AMIIBO_LOAD_FAILED, UI_MENU_AMIIBO_REMOVED,
UI_MENU_AMIIBO_STATUS,
// Menu tab
UI_MENU_MENU_LANG, UI_MENU_MENU_LANG_DESC, UI_MENU_MENU_LANG_AUTO,
UI_MENU_DISCORD_RPC, UI_MENU_DISCORD_RPC_DESC,
// Language names, each in its own language and the same in every row (game language and menu language lists)
UI_MENU_LANGNAME_EN, UI_MENU_LANGNAME_JA, UI_MENU_LANGNAME_FR, UI_MENU_LANGNAME_DE, UI_MENU_LANGNAME_IT,
UI_MENU_LANGNAME_ES, UI_MENU_LANGNAME_NL, UI_MENU_LANGNAME_RU, UI_MENU_LANGNAME_ZH_HANS,
UI_MENU_LANGNAME_ZH_HANT, UI_MENU_LANGNAME_KO,
UI_MENU_LANGNAME_ZH_HANT, UI_MENU_LANGNAME_KO, UI_MENU_LANGNAME_PT_BR, UI_MENU_LANGNAME_EN_GB,
UI_MENU_LANGNAME_FR_CA, UI_MENU_LANGNAME_ES_419,
// Advanced
UI_MENU_ADV_WARNING,
@@ -147,6 +200,7 @@ typedef enum {
UI_MENU_TRACE, UI_MENU_TRACE_DESC,
UI_MENU_FLIGHT, UI_MENU_FLIGHT_DESC,
UI_MENU_FLIGHT_SPIKE_MS, UI_MENU_FLIGHT_SPIKE_MS_DESC,
UI_MENU_PASS_CRUMBS, UI_MENU_PASS_CRUMBS_DESC,
UI_MENU_INPUT_RECORD, UI_MENU_INPUT_RECORD_DESC,
UI_MENU_OPEN_LOG, UI_MENU_OPEN_LOG_DESC,
UI_MENU_COPY_INFO, UI_MENU_COPY_INFO_DESC, UI_MENU_COPY_INFO_DONE,
@@ -155,6 +209,8 @@ typedef enum {
// Performance overlay
UI_MENU_OV_FPS, UI_MENU_OV_FRAME_MS, UI_MENU_OV_GAME_PCT, UI_MENU_OV_MAX_MS,
UI_MENU_OV_FPS_LABEL, UI_MENU_OV_FRAME_LABEL, UI_MENU_OV_FMT_FPS, // the frame rows: their labels, the rate
UI_MENU_OV_LOW1, UI_MENU_OV_LOW01, // printf: the fps of the slowest 1% / 0.1% of the frames, no unit (the overlay column stays narrow)
UI_MENU_OV_GPU, UI_MENU_OV_CPU, UI_MENU_OV_RAM, UI_MENU_OV_VRAM, UI_MENU_OV_TEMP, UI_MENU_OV_POWER,
UI_MENU_OV_CLOCK, UI_MENU_OV_NONE,
UI_MENU_OV_REPLAY, UI_MENU_OV_GPU_TIME, UI_MENU_OV_PIPE_WAIT, UI_MENU_OV_SHADER_WAIT, UI_MENU_OV_TEX_UPLOADS,
@@ -167,7 +223,16 @@ typedef enum {
UI_MENU_OV_FMT_SCENE, // "%ux%u, %.0f%%": the scene and its share of the game image's width
UI_MENU_OV_FMT_FSR, // "AMD FSR 1, sharpness %d%%"
UI_MENU_OV_SCALE_NONE, UI_MENU_OV_SCALE_BILINEAR,
UI_MENU_LAST_ID = UI_MENU_OV_SCALE_BILINEAR,
UI_MENU_OV_SCALE_DOWN, // FSR is selected but the image is larger than the window: FSR only enlarges
// the Cheats tab (cheats.c): the file, the kinds of cheat and why one cannot be switched
UI_MENU_TAB_CHEATS,
UI_MENU_CHEATS_NONE, // "%s": <build id>.txt
UI_MENU_CHEATS_MOD, // "%s": the mod, "%d": its cheats
UI_MENU_CHEATS_REBUILD, UI_MENU_CHEATS_REBUILD_DESC, // restart into the rebuild for unbuilt code cheats
UI_MENU_CHEAT_CODE_DESC, UI_MENU_CHEAT_KEY_DESC /* "%s": the buttons */, UI_MENU_CHEAT_DATA_DESC,
UI_MENU_CHEAT_MASTER, UI_MENU_CHEAT_MASTER_DESC, UI_MENU_CHEAT_RESTORE, UI_MENU_CHEAT_RESTORE_DESC,
UI_MENU_CHEAT_REBUILD, UI_MENU_CHEAT_REBUILD_DESC, UI_MENU_CHEAT_UNSUPPORTED, UI_MENU_CHEAT_UNSUPPORTED_DESC,
UI_MENU_LAST_ID = UI_MENU_CHEAT_UNSUPPORTED_DESC,
UI_TEXT_COUNT
} UiTextId;
@@ -179,13 +244,23 @@ enum { UI_DESC_BYTES = 2048 };
// UTF-8 text for id in the language of ov_language(); English when the catalog has no row for that language.
const char *ui_text(UiTextId id);
// The same for an explicit catalog language ("en", "ja", "fr", "de", "it", "es", "nl", "pt", "ru", "zh-Hans",
// "zh-Hant", "ko"); an empty entry gives the English text.
// "zh-Hant", "ko", "pt-BR"); an empty entry gives the English text.
const char *ui_text_in(const char *lang, UiTextId id);
// Calls visit(ctx, text) for every string the row of lang has its own text for (an id that falls back to English is not
// visited): the font builder covers the glyphs of the text a language shows (ui/menu.cpp).
void ui_text_visit(const char *lang, void (*visit)(void *ctx, const char *text), void *ctx);
// 1 when the row of lang has its own text for id (no fallback to English), for the probe.
int ui_text_defined(const char *lang, UiTextId id);
// The catalog language for a Switch language code ("en-GB" -> "en", "zh-CN" -> "zh-Hans", ...).
const char *ui_text_lang(const char *switch_code);
// Menu text: ui_text_in(menu language, id). The menu language is TOTK_MENU_LANG ("en" / "ru"); unset, Russian when the
// system UI language is Russian, else English. Follows a live change of the setting.
// The game languages the F1 menu offers for a game build (rt_game_version): one entry per Mals language file the build
// ships, each with the Switch code TOTK_LANG takes and the id of its name. 1.4.3 adds Brazilian Portuguese (USpt).
// Fills out (room for max entries) and returns the count.
typedef struct { const char *code; UiTextId name; } UiGameLang;
int ui_text_game_langs(int game_version, UiGameLang *out, int max);
// Menu text: ui_text_in(menu language, id). The menu language is TOTK_MENU_LANG ("en", "ru", "pt-BR", "zh-Hans");
// unset, the system UI language when the catalog has menu text for it (English, Russian, Brazilian Portuguese,
// Simplified Chinese), else English. Follows a live change of the setting.
const char *menu_text(UiTextId id);
+82 -1
View File
@@ -33,7 +33,10 @@ typedef struct VkCtx {
int has_custom_border_color, has_eds, has_eds2, has_eds3, has_vertex_input_dynamic_state,
has_conditional_rendering, has_transform_feedback, has_provoking_vertex, has_device_fault, has_memory_budget,
has_robustness2, has_buffer_device_address, has_fragment_shader_interlock, has_buffer_marker,
has_astc_ldr; // textureCompressionASTC_LDR (enabled when reported)
has_nv_checkpoints, // VK_NV_device_diagnostic_checkpoints (TOTK_PASS_CRUMBS=1, vk_crumbs.c)
has_astc_ldr, // textureCompressionASTC_LDR (enabled when reported)
has_calibrated, // VK_KHR/EXT_calibrated_timestamps (GPU idle split in the perf line)
has_hdr_metadata; // VK_EXT_hdr_metadata (vk_hdr.c vk_hdr_metadata)
// Feedback loops (maxwell.md 1.9, vk_exec_draw.c feedback_prepare): a draw samples a target of its open pass that
// an earlier draw of the pass wrote. TOTK_FEEDBACK=0: VK_FEEDBACK_OFF (sampled in GENERAL without a barrier, the
// old behaviour); VK_FEEDBACK_LAYOUT with VK_EXT_attachment_feedback_loop_layout and dynamicRenderingLocalRead
@@ -85,6 +88,45 @@ void vk_crumbs_release(void);
void vk_crumb(VkCommandBuffer cb, int kind, uint64_t n);
void vk_crumbs_report(void); // logs the two codes and what they name
// ---- pass marks (vk_crumbs.c): the replay (vk_exec.c vk_exec_pass_begin / vk_exec_pass_end, vk_exec_draw.c
// op_dispatch) marks where each render pass and dispatch starts and where it ends, so that a device loss names the
// pass the GPU was in. A mark is a number; a ring of VK_PASS_MARKS records keeps what it was. With
// VK_AMD_buffer_marker the GPU writes the number of the last mark it started (TOP_OF_PIPE, before vkCmdBeginRendering
// or the dispatch) and of the last it finished (BOTTOM_OF_PIPE, after vkCmdEndRendering or the dispatch) into the
// breadcrumb buffer; with VK_NV_device_diagnostic_checkpoints the same two points are checkpoints, read with
// vkGetQueueCheckpointData(2)NV after the loss. TOTK_PASS_CRUMBS: unset, AMD buffer marks only; 1, also NVIDIA
// checkpoints (the extension is enabled at device creation); 0, none.
#define VK_PASS_MARKS 4096 // power of two
enum { VK_MARK_PASS = 1, VK_MARK_DISPATCH };
typedef struct {
uint32_t id; // the mark this record belongs to (0: never written)
uint8_t kind; // VK_MARK_*
uint8_t ncolor; // colour attachments
uint32_t step; // index of the pass, or of the dispatch, within its submission, from 0
uint32_t w, h, d; // render area and layers; a dispatch: group counts (0 0 0: indirect)
uint32_t draws; // draws recorded in the pass; UINT32_MAX until its end is recorded
uint64_t fence; // the submission: the timeline value it signals
VkFormat color[8], depth; // attachment formats (VK_FORMAT_UNDEFINED: none)
const GfxShader *first[2], *last[2];// vertex and fragment shader of the first and last draw; a dispatch: first[0]
} VkPassMark;
// Pass marks wanted and possible (TOTK_PASS_CRUMBS and the extensions): set by vk_crumbs_init.
extern int vk_pass_marks_on;
// vk_device.c create_device, before vkCreateDevice: 1 when TOTK_PASS_CRUMBS asks for NVIDIA checkpoints.
int vk_pass_marks_want_nv(void);
// The next mark: records its start into cb (through the recorder thread when it owns cb) and returns its ring record,
// id, kind and fence set, for the caller to fill. NULL when pass marks are off. Replay thread only.
VkPassMark *vk_pass_mark_begin(VkCommandBuffer cb, int kind, uint64_t fence);
void vk_pass_mark_end(VkCommandBuffer cb, const VkPassMark *m); // records the end of mark m into cb
// The recorder thread's side of both (vk_rec.c): the marker and checkpoint commands themselves.
void vk_pass_mark_cmd(VkCommandBuffer cb, uint32_t id, int end);
// AMD only: the last mark the GPU started and the last it finished (0: none); 0 without buffer marks.
int vk_pass_marks_read(uint32_t *started, uint32_t *finished);
const VkPassMark *vk_pass_mark_record(uint32_t id); // the ring record of mark id; NULL once a later mark took its slot
// The report's text for a started and a finished mark, three lines without a trailing newline: which marks (source:
// the extension they came from), then each with its ring record. vk_pass_marks_report logs it; the probe checks it.
void vk_pass_marks_format(const char *source, uint32_t started, uint32_t finished, char *o, size_t size);
void vk_pass_marks_report(void); // vk_device_fault_report: the AMD words and the NVIDIA checkpoints, formatted
// ---- window and present (gfx_present.c). Host threads only.
// vk_present_image: blits the crop rectangle {x, y, w, h} of src (NULL, or w/h <= 0: the whole w x h image), scaled
// to the swapchain extent, into the acquired swapchain image and presents it. src is in layout, which is
@@ -107,6 +149,26 @@ void vk_fsr_release(void); // before the device goes away
// scales that one instead, crop {0, 0, w, h}); VK_NULL_HANDLE = nothing recorded. src is in GENERAL, fmt its format.
VkImage vk_color_record(VkCommandBuffer cb, unsigned slot, VkImage src, VkFormat fmt, const int crop[4]);
void vk_color_release(void); // before the device goes away
// HDR output (vk_hdr.c). vk_hdr_wanted: TOTK_HDR, read once. vk_hdr_surface_format: the HDR10 surface format when wanted
// and offered (1). vk_hdr_set_active: gfx_present.c says whether the swapchain is HDR10 (vk_hdr_active). vk_hdr_encode:
// like vk_color_record, src's crop as PQ code values (RGBA16F, crop {0, 0, w, h}). vk_hdr_ui_target / vk_hdr_ui_compose:
// the in-game menu's RGBA8 target, then blended onto the swapchain image. vk_hdr_to_srgb8: 10-bit PQ pixels to sRGB bytes.
int vk_hdr_wanted(void);
void vk_hdr_off(void); // probes that read back 8-bit swapchain pixels: SDR whatever the setting
int vk_hdr_surface_format(const VkSurfaceFormatKHR *f, uint32_t n, VkSurfaceFormatKHR *out);
void vk_hdr_metadata(VkSwapchainKHR sc, int new_sc);
void vk_hdr_set_active(int on);
int vk_hdr_active(void);
VkImage vk_hdr_encode(VkCommandBuffer cb, unsigned slot, VkImage src, VkFormat fmt, const int crop[4]);
VkImageView vk_hdr_ui_target(VkCommandBuffer cb, uint32_t w, uint32_t h);
void vk_hdr_ui_compose(VkCommandBuffer cb, VkImageView dst_view, VkFormat fmt, uint32_t w, uint32_t h);
void vk_hdr_to_srgb8(const uint8_t *in, uint8_t *out, size_t px, int a2r);
void vk_hdr_release(void); // before the device goes away
// The support buffer's HDR parameters (vk_exec_draw.c support_fill, read by shaders/hdr_tonemap.frag).
void vk_hdr_support(float out[4]);
// vk_contact.c: screen-space contact shadows on the game's composed scene colour (TOTK_CONTACT_SHADOWS)
int vk_contact_strength(void); // percent, 0 = off
void vk_contact_release(void); // before the device goes away
void vk_present_flip(void);
// Every submission to ctx->gfx_queue (and xfer_queue when shared) takes this lock; vk_present_image and the swapchain
// rebuild do. Recursive.
@@ -193,9 +255,20 @@ void vk_mem_gpu_wrote(const VkMemSpan *sp, uint64_t size);
void vk_usnap_begin(const uint64_t *handles, int n, uint64_t fence);
void vk_usnap_end(uint64_t fence);
int vk_usnap_find(uint64_t addr, uint64_t n, uint64_t align, VkDescriptorBufferInfo *out);
const uint8_t *vk_usnap_map(void); // a host copy of the current arena, at the offsets vk_usnap_find gives
const uint8_t *vk_usnap_bytes(uint64_t addr, uint64_t n); // the copy of [addr, addr+n) as of the submit, NULL: none
void vk_usnap_drop(uint64_t addr, uint64_t n); // the replay makes the GPU write [addr, addr+n) of guest memory
uint64_t vk_usnap_gen(void); // changes whenever a binding may resolve differently
void vk_usnap_shutdown(void); // vk_exec_draw_shutdown: frees the arenas
// vk_mvprev.c: last frame's copy of the scene's object (c7) and bone (c5) blocks, for per-object motion vectors.
// vk_mvprev_step: the distance of the game's other copy of a vertex-stage block the snapshot also copies, 0: none.
// vk_mvprev_find: last frame's block of that object (prev, its address; how, MVPREV_*), 0: none.
enum { MVPREV_NONE, MVPREV_SELF, MVPREV_SIDE, MVPREV_NEARER };
uint64_t vk_mvprev_step(int stage, int index, uint64_t size);
int vk_mvprev_on(void);
void vk_mvprev_want(uint32_t index_mask); // also keep these binding indices' last-frame copies (bit n: index n) // DLAA on and TOTK_DLAA_OBJMV not 0, as of the last present
int vk_mvprev_find(int index, uint64_t addr, uint64_t size, uint64_t *prev, int *how);
void vk_mvprev_frame(void); // each present, beside vk_dlaa_frame
void vk_mem_mirror_begin(void);
int vk_mem_mirror_end(VkCommandBuffer cb, uint64_t fence);
int vk_mem_mirror_pending(void);
@@ -302,7 +375,14 @@ typedef struct {
uint8_t fb_usage; // created with ATTACHMENT_FEEDBACK_LOOP usage (VK_FEEDBACK_LAYOUT, attachable images)
uint8_t fb_learned; // a draw sampled it while it was a written attachment of the open pass: its passes
// attach it in ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT (vk_exec.c vk_exec_pass_begin)
uint8_t scale; // 1, or TOTK_SHADOW_SCALE for a shadow map made larger than the game's (vk_texture.c
// shadow_scale_of): width and height above are the larger ones, the game's regions
// are multiplied by it
} VkTexImage;
// The window texture the backend presents (vk_backend.c): *image and *format become the float picture the game copied
// into it, when the last draw into it was that copy and the swapchain is HDR10.
void vk_hdr_present_source(const VkTexImage *win, VkImage *image, VkFormat *format);
void vk_hdr_image_gone(VkImage image);
const VkTexImage *vk_texture_get(const tex_t *t); // created and made current; NULL for BUFFER or unmapped formats
// A texture slot; a slot whose texture was finalized follows the live texture at the same storage (hle_nvn.c).
const VkTexImage *vk_texture_by_id(int id, view_t *view, int *has_view);
@@ -321,6 +401,7 @@ uint32_t vk_texture_slots_gen(void);
// its storage address is created, dropped, released or taken back into use. Unlocked; read it before the lookup it
// guards (a lookup may create an entry). 0 when the slot was never registered: nothing is kept under 0.
uint64_t vk_texture_slot_token(int id);
void vk_sampler_dlss_bias(float bias); // texture LOD bias added for DLSS upscaling (material samplers)
uint32_t vk_sampler_gen(void); // changes whenever a sampler slot is registered
void vk_texture_gpu_written(const tex_t *t); // rendered or copied into by the GPU: no re-upload from storage
void vk_texture_storage_bound_locked(const VkTexImage *img); // bound as a storage image in the recording submission
+12 -1
View File
@@ -298,9 +298,20 @@ static int create_pipeline(VkCtx *c) {
}
// TOTK_ASTC_BC=1: the BC3 encoder, when the device samples BC3 (every desktop GPU does); 0 leaves ASTC as RGBA8.
// Unset: on when the largest device-local heap is under 5 GiB. There RGBA8 ASTC, four times the size of BC3, fills
// video memory (a GTX 1650 4 GiB went from 10-23 to 3-12 ms of GPU time a frame, issue #87); BC3 loses some precision
// (normal maps), so GPUs with more memory keep RGBA8.
static int create_bc_pipeline(VkCtx *c) {
const char *e = cfg_get("TOTK_ASTC_BC");
if (!e || !*e || *e == '0') return 0;
VkDeviceSize vram = 0;
for (uint32_t h = 0; h < c->mem_props.memoryHeapCount && h < VK_MAX_MEMORY_HEAPS; h++)
if (c->mem_props.memoryHeaps[h].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT && c->mem_props.memoryHeaps[h].size > vram)
vram = c->mem_props.memoryHeaps[h].size;
int on = e && *e ? *e != '0' : vram < (5ull << 30);
if (!(e && *e))
rt_log("vk: TOTK_ASTC_BC unset: BC3 %s (largest device-local heap %llu MiB)", on ? "on" : "off",
(unsigned long long)(vram >> 20));
if (!on) return 0;
VkFormatProperties p;
vkGetPhysicalDeviceFormatProperties(c->phys, VK_FORMAT_BC3_SRGB_BLOCK, &p);
VkFormatFeatureFlags need = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | VK_FORMAT_FEATURE_TRANSFER_DST_BIT;
+10 -1
View File
@@ -29,6 +29,7 @@
#include "vk.h"
#include "vk_exec.h"
#include "platform/platform.h"
#include "vk_dlaa.h"
#define WEAK __attribute__((weak))
@@ -100,6 +101,9 @@ static void present_image(const tex_t *t, const int crop[4], uint64_t at_ns, uin
uint64_t value) {
static volatile int32_t n_skipped;
vk_exec_frame_log(t, frame);
vk_dlaa_frame();
vk_mvsurvey_frame();
vk_mvprev_frame();
vk_mem_census(frame);
if (vk_dump_armed) vk_dump_present(frame);
__atomic_store_n(&gfx_counters.validation_errors, (uint64_t)vk_validation_errors_total(), __ATOMIC_RELAXED);
@@ -116,6 +120,7 @@ static void present_image(const tex_t *t, const int crop[4], uint64_t at_ns, uin
}
PresentJob j = {.image = img->image, .format = img->format, .w = (int)img->width, .h = (int)img->height, .frame = frame,
.at = at_ns, .queued = queued, .value = value};
vk_hdr_present_source(img, &j.image, &j.format); // TOTK_HDR: the float picture the game copied into it, same size
if (crop) {
j.has_crop = 1;
for (int i = 0; i < 4; i++) j.crop[i] = crop[i];
@@ -163,7 +168,10 @@ static uint64_t ck_reads, ck_diff, ck_diff_unexplained, ck_diff_idle;
int vk_replay_async(void) {
static int on = -1;
if (on < 0) {
on = cfg_bool("TOTK_REPLAY_ASYNC"); // off by default: no measured gain yet, one more frame of latency
// On by default: where the game waits for the GPU it overlaps the replay with the game threads (a GTX 1650 in
// the Depths went from 450-686 frames over 50 ms a minute to 10-13, issue #88); where the replay or the game
// threads bound the frame it neither gains nor loses. It adds up to a frame of latency.
on = cfg_bool("TOTK_REPLAY_ASYNC");
rt_log("vk: replay %s (TOTK_REPLAY_ASYNC=%d)",
on ? "on its own thread, at most one frame behind the game" : "on the submitting thread", on);
}
@@ -312,6 +320,7 @@ static void replay_log(uint64_t frame, int total) {
// vk_backend_shutdown.
void gfx_exit_log(void) {
static int32_t done;
rec_check_log();
if (gfx_replay_async() && r_started && !plat_xchg32(&done, 1)) replay_log(game_frames, 1);
}
+10 -10
View File
@@ -6,8 +6,7 @@
// - minStorageBufferOffsetAlignment above 4 (TOTK_VK_SSBO_ALIGN=<power of two> raises it): the translator computes
// storage offsets from the guest address rounded down to that alignment (Ryujinx's unaligned storage path), and
// vk_exec_draw.c ssbo_info binds the rounded-down address, so shader writes reach guest memory instead of a copy.
// - no graphics pipeline library with fast linking (TOTK_GPL=0 forces it; the default on AMD's RDNA 1/2 driver):
// vk_caps.gpl = 0, the extension stays disabled, and pipelines are built whole.
// - no graphics pipeline library with fast linking (TOTK_GPL=0 forces it): vk_caps.gpl = 0, the extension stays disabled, and pipelines are built whole.
// - no 32-lane pin (no subgroupSizeControl, 32 outside min..max, or TOTK_VK_SUBGROUP_PIN=0): stages run at the
// device's subgroupSize (SPIR-V 1.3 without a required size) and the translator is told that size.
// TOTK_VK_SUBGROUP=<n> pins n instead of 32 where the driver allows it.
@@ -46,15 +45,18 @@ void vk_caps_driver(VkPhysicalDevice p) {
vk_caps.amd_sc = drv.driverID == VK_DRIVER_ID_AMD_PROPRIETARY && strstr(drv.driverInfo, "shader compiler");
}
// TOTK_GPL=0/1 forces graphics pipeline libraries off or on. Default off on AMD's RDNA 1/2 driver branch: every boot
// that lost the device there had a cold pipeline cache and draws waiting on fast-linked pipelines, and a run with GPL
// off booted (issue #5); Savage Wind Recomp turns GPL off on RDNA 4 under RADV for a GPU hang at the title screen.
// TOTK_GPL=0 turns graphics pipeline libraries off; they are on wherever the driver has fast linking. AMD's RDNA 1/2
// driver branch had them off for a while: its device losses at boot (issue #5) came with a cold pipeline cache, but
// their cause was GPU writes past 3D BC images (vk_exec.c, "3D BC render targets"). With that fixed, the RDNA 1/2
// driver boots with GPL from a cold cache and fast-links without a failure, while with GPL off every new pipeline is
// built whole on the draw's path (frames of 0.5-1.2 s on an RX 6600, issue #381). Savage Wind Recomp turns GPL off on
// RDNA 4 under RADV for a GPU hang at the title screen.
int vk_caps_gpl(const VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT *f,
const VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT *p) {
gpl_lib = f->graphicsPipelineLibrary;
gpl_fast = p->graphicsPipelineLibraryFastLinking;
const char *e = cfg_get("TOTK_GPL"); // no fixed default: it depends on the driver, see above
vk_caps.gpl = gpl_lib && gpl_fast && (e && *e ? strcmp(e, "0") != 0 : !vk_caps.amd_sc);
const char *e = cfg_get("TOTK_GPL");
vk_caps.gpl = gpl_lib && gpl_fast && !(e && !strcmp(e, "0"));
return vk_caps.gpl;
}
@@ -137,10 +139,8 @@ void vk_caps_init(VkCtx *c) {
has_ext(ep, ne, "VK_EXT_graphics_pipeline_library"), depth_ok(p, VK_FORMAT_D16_UNORM),
depth_ok(p, VK_FORMAT_D24_UNORM_S8_UINT), depth_ok(p, VK_FORMAT_X8_D24_UNORM_PACK32), depth_ok(p, VK_FORMAT_D32_SFLOAT),
depth_ok(p, VK_FORMAT_D32_SFLOAT_S8_UINT));
const char *ge = cfg_get("TOTK_GPL");
rt_log("vk caps: gpl %s fast-link %s (graphicsPipelineLibrary %u%s)", vk_caps.gpl ? "yes" : "no",
gpl_fast ? "yes" : "no", (unsigned)gpl_lib,
!gpl_lib || !gpl_fast || vk_caps.gpl ? "" : ge && *ge ? ", off by TOTK_GPL=0" : ", off on AMD's RDNA 1/2 driver");
gpl_fast ? "yes" : "no", (unsigned)gpl_lib, !gpl_lib || !gpl_fast || vk_caps.gpl ? "" : ", off by TOTK_GPL=0");
rt_log("vk caps: fallbacks: float64 %s, storage buffers %s %u, subgroup pin %u on stages %#x, translator subgroup vs/fs/cs %u/%u/%u",
vk_caps.float64 ? "native" : "softfloat64", vk_caps.sbuf_align ? "rounded down to" : "exact, alignment",
(unsigned)l->minStorageBufferOffsetAlignment, want, (unsigned)vk_caps.sg_pin_stages, told[0], told[1], told[2]);
+188
View File
@@ -0,0 +1,188 @@
// Screen-space contact shadows (TOTK_CONTACT_SHADOWS, percent strength, 0 = off). TotK fills a full-resolution
// G-buffer whose targets include a B10G11R11 scene colour, an R32F linear depth (view distance / far) and a D32F depth
// (is_gbuffer), lights it in half resolution, and then composites the lighting into that scene colour in one pass
// whose only target is the scene colour, with a D16 depth that sorts pixels into material classes (is_composite).
// When the pass after the composite begins, or a dispatch or copy comes first, runtime/shaders/contact_shadow.comp
// marches each pixel a short way toward the sun through the linear depth and darkens the scene colour where the ray
// passes behind nearby geometry: the small shadows at feet, under stones and in grass that the shadow maps are too
// coarse for. Transparent surfaces, the sky and post-processing come after, untouched.
//
// Inputs from the game, read from the fragment stage's uniform block c4 bound in the composite pass (guest memory,
// so it may be one frame newer than the replay): the projection scales c4[7].x and c4[8].y, the far plane c4[14].y,
// and the first sun cascade's depth row c4[44].xyz, whose negated direction points from a view-space position toward
// the sun (the G-buffer shaders compare dot(c4[44].xyz, pos) + c4[44].w with the cascade map). The scene colour images
// get STORAGE usage when the setting is on (vk_texture.c create_tex).
#include "vk.h"
#include <math.h>
#include <string.h>
#include "cfg.h"
#include "contact_shadow_spv.h"
#include "host.h"
#include "vk_exec.h"
static struct {
int tried, ok, strength, debug, logged;
PFN_vkCmdPushDescriptorSetKHR push;
VkDescriptorSetLayout dsl;
VkPipelineLayout layout;
VkPipeline pipe;
VkSampler sampler;
const VkTexImage *scene, *depth; // the last G-buffer's scene colour and linear depth
uint32_t w, h;
int pending; // the composite into scene ran; the march waits for the next pass
uint64_t c4;
} C;
int vk_contact_strength(void) {
if (!C.tried) {
int s = cfg_int("TOTK_CONTACT_SHADOWS");
C.strength = s < 0 ? 0 : s > 100 ? 100 : s;
}
return C.strength;
}
static int init(VkCtx *c) {
C.tried = 1;
vk_contact_strength();
if (!C.strength) return 0;
const char *e = cfg_get("TOTK_CONTACT_DEBUG"); // 1: the frame shows the contact shadow factor in grey
C.debug = e && *e && strcmp(e, "0");
C.push = (PFN_vkCmdPushDescriptorSetKHR)vkGetDeviceProcAddr(c->device, "vkCmdPushDescriptorSetKHR");
VkDescriptorSetLayoutBinding b[2] = {
{.binding = 0, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .descriptorCount = 1,
.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT},
{.binding = 1, .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, .descriptorCount = 1,
.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT}};
VkDescriptorSetLayoutCreateInfo dci = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
.flags = VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR,
.bindingCount = 2, .pBindings = b};
VkPushConstantRange pr = {VK_SHADER_STAGE_COMPUTE_BIT, 0, 64};
VkPipelineLayoutCreateInfo li = {.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 1,
.pSetLayouts = &C.dsl, .pushConstantRangeCount = 1, .pPushConstantRanges = &pr};
VkSamplerCreateInfo si = {.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, .magFilter = VK_FILTER_NEAREST,
.minFilter = VK_FILTER_NEAREST, .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, .maxLod = 0};
VkShaderModuleCreateInfo mi = {.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,
.codeSize = sizeof contact_shadow_spv, .pCode = contact_shadow_spv};
VkShaderModule m = VK_NULL_HANDLE;
if (!C.push || vkCreateDescriptorSetLayout(c->device, &dci, NULL, &C.dsl) != VK_SUCCESS ||
vkCreatePipelineLayout(c->device, &li, NULL, &C.layout) != VK_SUCCESS ||
vkCreateSampler(c->device, &si, NULL, &C.sampler) != VK_SUCCESS ||
vkCreateShaderModule(c->device, &mi, NULL, &m) != VK_SUCCESS) {
rt_log("vk: contact shadows off: their pipeline could not be created");
return 0;
}
VkComputePipelineCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO,
.stage = {.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
.stage = VK_SHADER_STAGE_COMPUTE_BIT, .module = m, .pName = "main"},
.layout = C.layout};
VkResult r = vkCreateComputePipelines(c->device, VK_NULL_HANDLE, 1, &ci, NULL, &C.pipe);
vkDestroyShaderModule(c->device, m, NULL);
if (r != VK_SUCCESS) {
rt_log("vk: contact shadows off: their pipeline could not be created");
return 0;
}
rt_log("vk: contact shadows on, strength %d%%%s", C.strength, C.debug ? " (debug view)" : "");
return C.ok = 1;
}
// A G-buffer pass: a B10G11R11 scene colour, an R32F linear depth and a D32F depth, all one size, at least 640 wide.
static int is_gbuffer(const VkExec *ex, const VkTexImage **scene, const VkTexImage **depth) {
*scene = *depth = NULL;
if (ex->pass_noatt || ex->pass_w < 640 || ex->depth.format != VK_FORMAT_D32_SFLOAT || ex->depth.level) return 0;
for (uint32_t i = 0; i < ex->pass_ncolor && i < 8; i++) {
const VkExecTarget *t = &ex->color[i];
if (!t->image || t->level || t->width != ex->pass_w || t->height != ex->pass_h) continue;
if (t->format == VK_FORMAT_B10G11R11_UFLOAT_PACK32 && !*scene) *scene = t->img;
if (t->format == VK_FORMAT_R32_SFLOAT && !*depth) *depth = t->img;
}
return *scene && *depth && ((*scene)->usage & VK_IMAGE_USAGE_STORAGE_BIT);
}
static void mem_barrier(VkCommandBuffer cb) {
VkMemoryBarrier2 mb = {.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2,
.srcStageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT,
.srcAccessMask = VK_ACCESS_2_MEMORY_WRITE_BIT,
.dstStageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT,
.dstAccessMask = VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT};
VkDependencyInfo d = {.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO, .memoryBarrierCount = 1, .pMemoryBarriers = &mb};
vkCmdPipelineBarrier2(cb, &d);
}
void vk_contact_flush(VkExec *ex) {
if (!C.pending) return;
C.pending = 0;
if (ex->in_pass) return;
const float *u = (const float *)(uintptr_t)C.c4;
float lx = -u[44 * 4 + 0], ly = -u[44 * 4 + 1], lz = -u[44 * 4 + 2], ll = sqrtf(lx * lx + ly * ly + lz * lz);
float px = u[7 * 4 + 0], py = u[8 * 4 + 1], zfar = u[14 * 4 + 1];
if (!(ll > 1e-6f) || !(px > 0) || !(py > 0) || !(zfar > 1)) return;
VkImageView in = vk_exec_target_view(C.depth, VK_FORMAT_R32_SFLOAT, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_ASPECT_COLOR_BIT,
0, 0, 1, 0);
VkImageView out = vk_exec_target_view(C.scene, VK_FORMAT_B10G11R11_UFLOAT_PACK32, VK_IMAGE_VIEW_TYPE_2D,
VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1, 0);
if (!in || !out) return;
VkCommandBuffer cb = ex->cb;
float pcv[16] = {px, py, zfar, (float)C.strength / 100.0f,
lx / ll, ly / ll, lz / ll, 0.6f,
(float)C.w, (float)C.h, 1.0f / (float)C.w, 1.0f / (float)C.h,
(float)C.debug, 0, 0, 0};
if (!C.logged) {
C.logged = 1;
rt_log("vk: contact shadows on a %ux%u scene, sun toward %.3f %.3f %.3f (view space), far %g", C.w, C.h,
pcv[4], pcv[5], pcv[6], zfar);
}
mem_barrier(cb); // the compose passes' writes, before the march reads and writes them
VkDescriptorImageInfo ii = {C.sampler, in, VK_IMAGE_LAYOUT_GENERAL}, oi = {VK_NULL_HANDLE, out, VK_IMAGE_LAYOUT_GENERAL};
VkWriteDescriptorSet w[2] = {
{.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstBinding = 0, .descriptorCount = 1,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImageInfo = &ii},
{.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstBinding = 1, .descriptorCount = 1,
.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, .pImageInfo = &oi}};
vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, C.pipe);
rec_push(C.push, cb, VK_PIPELINE_BIND_POINT_COMPUTE, C.layout, 0, 2, w);
vkCmdPushConstants(cb, C.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof pcv, pcv);
vkCmdDispatch(cb, (C.w + 7) / 8, (C.h + 7) / 8, 1);
mem_barrier(cb); // and what follows sees the darkened colour
ex->recorded += 6;
vk_exec_draw_new_cb(); // the game's bound compute pipeline and descriptors were replaced: bind them again
}
// The lighting composite: the remembered scene colour as the only target, with a D16 depth of its size.
static int is_composite(const VkExec *ex) {
return C.scene && ex->pass_ncolor >= 1 && ex->color[0].img == C.scene && !ex->color[0].level &&
ex->depth.format == VK_FORMAT_D16_UNORM && ex->pass_w == C.w && ex->pass_h == C.h;
}
void vk_contact_pass_begin(VkExec *ex) {
if (!C.tried && !init(vk_ctx())) return;
if (!C.ok) return;
const VkTexImage *scene, *depth;
// The camera block: c4 of the fragment stage, 0x940 bytes. The composite binds it only after its pass begins, so
// the newest one seen at any pass start serves.
const p_bind_buf *b = &ex->ubo[1][1];
if (b->addr && b->size == 0x940) C.c4 = b->addr;
if (is_gbuffer(ex, &scene, &depth)) {
C.pending = 0;
C.scene = scene, C.depth = depth, C.w = ex->pass_w, C.h = ex->pass_h;
return;
}
if (is_composite(ex)) {
C.pending = C.c4 != 0;
return;
}
vk_contact_flush(ex);
}
void vk_contact_release(void) {
VkCtx *c = vk_ctx();
if (!c || !C.tried) return;
if (C.pipe) vkDestroyPipeline(c->device, C.pipe, NULL);
if (C.sampler) vkDestroySampler(c->device, C.sampler, NULL);
if (C.layout) vkDestroyPipelineLayout(c->device, C.layout, NULL);
if (C.dsl) vkDestroyDescriptorSetLayout(c->device, C.dsl, NULL);
memset(&C, 0, sizeof C);
}
+202 -4
View File
@@ -4,19 +4,31 @@
// device loss word 0 names the newest point the GPU reached and word 1 the newest point it had finished: the hang lies
// between them. A code is the crumb kind in the top 4 bits and its number in the low 28. The markers cost two small
// writes per crumb, and crumbs mark submissions, upload batches, ASTC chunks and presents, not draws.
//
// Pass marks (vk.h vk_pass_mark_begin) use words 2 and 3 of the same buffer: the replay marks the start and the end of
// every render pass and dispatch, and a ring of records says what each mark was. The design follows Savage Wind
// Recomp's GPU checkpoints (refs/SavageWindRecomp runtime/nvn/vulkan/exec.c ck_mark and vk_checkpoints_report: a mark
// per pass and dispatch, numbers in a ring of 4096, text only at the device loss); the code is ours.
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "cfg.h"
#include "host.h"
#include "vk.h"
static PFN_vkCmdWriteBufferMarkerAMD write_marker;
static VkBuffer buf;
static VmaAllocation alloc;
static volatile uint32_t *words;
static volatile uint32_t *words; // 0, 1: crumbs; 2, 3: pass marks
void vk_crumbs_init(VkCtx *c) {
if (!c->has_buffer_marker) return;
// Pass marks (below)
int vk_pass_marks_on;
static int pm_amd; // marks into words 2 and 3
static PFN_vkCmdSetCheckpointNV set_checkpoint;
static void pass_marks_init(VkCtx *c);
static void buffer_init(VkCtx *c) {
write_marker = (PFN_vkCmdWriteBufferMarkerAMD)vkGetDeviceProcAddr(c->device, "vkCmdWriteBufferMarkerAMD");
VkBufferCreateInfo bi = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .size = 16,
.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT};
@@ -30,14 +42,20 @@ void vk_crumbs_init(VkCtx *c) {
return;
}
words = info.pMappedData;
words[0] = words[1] = 0;
words[0] = words[1] = words[2] = words[3] = 0;
rt_log("vk: GPU breadcrumbs on (VK_AMD_buffer_marker)");
}
void vk_crumbs_init(VkCtx *c) {
if (c->has_buffer_marker) buffer_init(c);
pass_marks_init(c);
}
void vk_crumbs_release(void) {
VkCtx *c = vk_ctx();
if (buf && c) vmaDestroyBuffer(c->vma, buf, alloc);
buf = VK_NULL_HANDLE, alloc = NULL, words = NULL, write_marker = NULL;
vk_pass_marks_on = pm_amd = 0, set_checkpoint = NULL;
}
void vk_crumb(VkCommandBuffer cb, int kind, uint64_t n) {
@@ -65,3 +83,183 @@ void vk_crumbs_report(void) {
describe(words[1], finished, sizeof finished);
rt_log("vk: GPU breadcrumbs: the GPU last reached %s; everything before %s had finished", reached, finished);
}
// ---- pass marks
// Cost per pass or dispatch: about twenty stores into the ring and two commands, one at the start and one at the end,
// each a marker write or a checkpoint. Per draw nothing, except that the branch of vk_exec_draw.c prepare_draw that
// records changed pipeline state also notes the shaders of a pass's first draw. A full barrier already precedes every
// pass and dispatch (vk_exec.c vk_exec_pass_begin, vk_exec_draw.c op_dispatch), so the end-of-pipe write adds no wait.
static VkPassMark ring[VK_PASS_MARKS];
static uint32_t seq; // marks made; only the replay thread writes it
// TOTK_PASS_CRUMBS: unset, buffer marks where VK_AMD_buffer_marker exists; 1, also NVIDIA checkpoints; 0, neither.
int vk_pass_marks_want_nv(void) {
const char *e = cfg_get("TOTK_PASS_CRUMBS");
return e && *e && strcmp(e, "0") != 0;
}
static void pass_marks_init(VkCtx *c) {
const char *e = cfg_get("TOTK_PASS_CRUMBS");
int off = e && !strcmp(e, "0");
set_checkpoint = c->has_nv_checkpoints
? (PFN_vkCmdSetCheckpointNV)vkGetDeviceProcAddr(c->device, "vkCmdSetCheckpointNV") : NULL;
pm_amd = !off && write_marker && words;
vk_pass_marks_on = pm_amd || set_checkpoint;
if (vk_pass_marks_on)
rt_log("vk: pass marks on (%s%s%s; TOTK_PASS_CRUMBS=0 turns them off%s)", pm_amd ? "VK_AMD_buffer_marker" : "",
pm_amd && set_checkpoint ? " and " : "", set_checkpoint ? "VK_NV_device_diagnostic_checkpoints" : "",
set_checkpoint ? "" : ", =1 adds NVIDIA checkpoints where the driver has them");
else
rt_log("vk: pass marks off (%s)", off ? "TOTK_PASS_CRUMBS=0"
: "no VK_AMD_buffer_marker; TOTK_PASS_CRUMBS=1 asks for NVIDIA checkpoints");
}
void vk_pass_mark_cmd(VkCommandBuffer cb, uint32_t id, int end) {
if (pm_amd)
write_marker(cb, end ? VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, buf,
end ? 12 : 8, id);
if (set_checkpoint) set_checkpoint(cb, (const void *)(uintptr_t)((uint64_t)id << 1 | (end != 0)));
}
VkPassMark *vk_pass_mark_begin(VkCommandBuffer cb, int kind, uint64_t fence) {
if (!vk_pass_marks_on || !cb) return NULL;
uint32_t id = ++seq;
if (!id) id = ++seq; // 0 means no mark
VkPassMark *m = &ring[id & (VK_PASS_MARKS - 1)];
m->id = id, m->kind = (uint8_t)kind, m->fence = fence, m->draws = UINT32_MAX;
rec_pass_mark(cb, id, 0);
return m;
}
void vk_pass_mark_end(VkCommandBuffer cb, const VkPassMark *m) {
if (m && cb) rec_pass_mark(cb, m->id, 1);
}
int vk_pass_marks_read(uint32_t *started, uint32_t *finished) {
if (!pm_amd) return 0;
*started = words[2], *finished = words[3];
return 1;
}
const VkPassMark *vk_pass_mark_record(uint32_t id) {
const VkPassMark *m = &ring[id & (VK_PASS_MARKS - 1)];
return id && m->id == id ? m : NULL;
}
// The first 8 bytes of the shader's input id (gfx_shader.c), the start of its stored input's name <cache>/in/<id>.in.
static unsigned long long shader_id(const GfxShader *s) {
if (!s) return 0;
const uint8_t *iid = gfx_shader_input_id(s);
unsigned long long v = 0;
for (int i = 0; i < 8; i++) v = v << 8 | iid[i];
return v;
}
static void describe_mark(uint32_t id, char *o, size_t size) {
const VkPassMark *m = vk_pass_mark_record(id);
if (!id) {
snprintf(o, size, "nothing yet");
return;
}
if (!m) {
snprintf(o, size, "no record (a later mark took its slot)");
return;
}
if (m->kind == VK_MARK_DISPATCH) {
snprintf(o, size, "dispatch %u of submission %llu: %ux%ux%u groups%s, cs %016llx", m->step,
(unsigned long long)m->fence, m->w, m->h, m->d, m->w ? "" : " (indirect)", shader_id(m->first[0]));
return;
}
size_t n = (size_t)snprintf(o, size, "pass %u of submission %llu: %ux%u, %u layer%s, colour formats", m->step,
(unsigned long long)m->fence, m->w, m->h, m->d, m->d == 1 ? "" : "s");
for (int i = 0; i < m->ncolor && i < 8 && n < size; i++)
n += (size_t)snprintf(o + n, size - n, "%s%d", i ? "," : " ", (int)m->color[i]);
if (!m->ncolor && n < size) n += (size_t)snprintf(o + n, size - n, " none");
if (n < size) n += (size_t)snprintf(o + n, size - n, ", depth format %d", (int)m->depth);
if (n >= size) return;
if (m->draws == UINT32_MAX)
snprintf(o + n, size - n, ", still recording; first draw vs %016llx fs %016llx", shader_id(m->first[0]),
shader_id(m->first[1]));
else if (!m->draws)
snprintf(o + n, size - n, ", no draws");
else
snprintf(o + n, size - n, ", %u draws; first vs %016llx fs %016llx, last vs %016llx fs %016llx", m->draws,
shader_id(m->first[0]), shader_id(m->first[1]), shader_id(m->last[0]), shader_id(m->last[1]));
}
void vk_pass_marks_format(const char *source, uint32_t started, uint32_t finished, char *o, size_t size) {
char a[640], b[640];
describe_mark(started, a, sizeof a);
describe_mark(finished, b, sizeof b);
snprintf(o, size,
"vk: pass marks (%s, %u made): the GPU last started mark %u and last finished mark %u\n"
"vk: last started %u: %s\n"
"vk: last finished %u: %s",
source, (unsigned)seq, (unsigned)started, (unsigned)finished, (unsigned)started, a, (unsigned)finished, b);
}
static void log_lines(char *t) {
for (char *line = t, *nl; line && *line; line = nl ? nl + 1 : NULL) {
nl = strchr(line, '\n');
if (nl) *nl = 0;
rt_log("%s", line);
}
}
// vkGetQueueCheckpointData2NV, else vkGetQueueCheckpointDataNV, on the graphics queue (the replay's): one entry per
// stage with the last checkpoint that stage executed. A checkpoint is the mark's id times 2, plus 1 at its end, so the
// top-of-pipe entry names the last start or end the GPU reached, and the bottom-of-pipe entry the last one before which
// everything had finished: at a start, that is the end of the mark before it.
static void nv_report(void) {
VkCtx *c = vk_ctx();
if (!c || !set_checkpoint) return;
PFN_vkGetQueueCheckpointData2NV get2 =
(PFN_vkGetQueueCheckpointData2NV)vkGetDeviceProcAddr(c->device, "vkGetQueueCheckpointData2NV");
PFN_vkGetQueueCheckpointDataNV get1 =
(PFN_vkGetQueueCheckpointDataNV)vkGetDeviceProcAddr(c->device, "vkGetQueueCheckpointDataNV");
enum { MAXN = 32 };
uint64_t stage[MAXN], marker[MAXN];
uint32_t n = 0;
if (get2) {
VkCheckpointData2NV d[MAXN];
get2(c->gfx_queue, &n, NULL);
if (n > MAXN) n = MAXN;
for (uint32_t i = 0; i < n; i++) d[i] = (VkCheckpointData2NV){.sType = VK_STRUCTURE_TYPE_CHECKPOINT_DATA_2_NV};
get2(c->gfx_queue, &n, d);
for (uint32_t i = 0; i < n; i++) stage[i] = d[i].stage, marker[i] = (uint64_t)(uintptr_t)d[i].pCheckpointMarker;
} else if (get1) {
VkCheckpointDataNV d[MAXN];
get1(c->gfx_queue, &n, NULL);
if (n > MAXN) n = MAXN;
for (uint32_t i = 0; i < n; i++) d[i] = (VkCheckpointDataNV){.sType = VK_STRUCTURE_TYPE_CHECKPOINT_DATA_NV};
get1(c->gfx_queue, &n, d);
for (uint32_t i = 0; i < n; i++) stage[i] = d[i].stage, marker[i] = (uint64_t)(uintptr_t)d[i].pCheckpointMarker;
} else {
rt_log("vk: pass marks: no vkGetQueueCheckpointDataNV entry point");
return;
}
uint32_t started = 0, finished = 0;
for (uint32_t i = 0; i < n; i++) {
uint32_t id = (uint32_t)(marker[i] >> 1);
int end = (int)(marker[i] & 1);
rt_log("vk: checkpoint of stage %#llx: the %s of mark %u", (unsigned long long)stage[i], end ? "end" : "start", id);
if (stage[i] == VK_PIPELINE_STAGE_2_TOP_OF_PIPE_BIT) started = id;
if (stage[i] == VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT) finished = end ? id : id ? id - 1 : 0;
}
if (!n) rt_log("vk: pass marks: the driver reported no checkpoints");
char t[2048];
vk_pass_marks_format("VK_NV_device_diagnostic_checkpoints", started, finished, t, sizeof t);
log_lines(t);
}
void vk_pass_marks_report(void) {
if (!vk_pass_marks_on) return;
uint32_t started, finished;
char t[2048];
if (vk_pass_marks_read(&started, &finished)) {
vk_pass_marks_format("VK_AMD_buffer_marker", started, finished, t, sizeof t);
log_lines(t);
}
nv_report();
}
+35 -5
View File
@@ -10,6 +10,7 @@
#include "host.h"
#include "vk.h"
#include "platform/platform.h"
#include "vk_dlaa.h"
static VkCtx g_vk;
static int g_ready;
@@ -41,6 +42,17 @@ static int layer_present(const char *name) {
return found;
}
static int instance_ext_present(const char *name) {
uint32_t n = 0;
vkEnumerateInstanceExtensionProperties(NULL, &n, NULL);
VkExtensionProperties *e = calloc(n ? n : 1, sizeof *e);
vkEnumerateInstanceExtensionProperties(NULL, &n, e);
int found = 0;
for (uint32_t i = 0; i < n; i++) if (!strcmp(e[i].extensionName, name)) found = 1;
free(e);
return found;
}
// Mesa's drivers (RADV on Linux and the Steam Deck) keep a shader cache of their own beside our pipeline cache, by
// default in ~/.cache and up to 1 GB: about 35 MB in a minute of the title screen. A Deck's /home is small and the game
// usually sits on the SD card, so unless MESA_SHADER_CACHE_DIR names a folder, it goes to mesa-cache beside the exe.
@@ -56,7 +68,7 @@ static void mesa_cache_beside_exe(void) {
static int create_instance(void) {
mesa_cache_beside_exe();
const char *ext[8];
const char *ext[12];
uint32_t n_ext = (uint32_t)gfx_window_vk_extensions(ext, 7);
const char *layers[] = {"VK_LAYER_KHRONOS_validation"};
int validate = cfg_bool("TOTK_VK_VALIDATION");
@@ -65,6 +77,9 @@ static int create_instance(void) {
validate = 0;
}
if (validate) ext[n_ext++] = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
if (vk_hdr_wanted() && instance_ext_present(VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME)) // HDR10 surface formats
ext[n_ext++] = VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME;
vk_dlaa_instance_exts(ext, &n_ext, 12);
VkApplicationInfo app = {.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, .pApplicationName = "TotK Recomp",
.pEngineName = "TotK Recomp", .apiVersion = VK_API_VERSION_1_3};
VkInstanceCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pApplicationInfo = &app,
@@ -209,7 +224,7 @@ static int create_device(void) {
vkEnumerateDeviceExtensionProperties(g_vk.phys, NULL, &ne, NULL);
VkExtensionProperties *ep = calloc(ne ? ne : 1, sizeof *ep);
vkEnumerateDeviceExtensionProperties(g_vk.phys, NULL, &ne, ep);
const char *ext[28];
const char *ext[48];
uint32_t n_ext = 0;
for (size_t i = 0; i < sizeof k_required_ext / sizeof *k_required_ext; i++) ext[n_ext++] = k_required_ext[i];
@@ -246,9 +261,23 @@ static int create_device(void) {
CHAIN(fbl, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ATTACHMENT_FEEDBACK_LOOP_LAYOUT_FEATURES_EXT);
CHAIN(lr, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_LOCAL_READ_FEATURES_KHR);
}
vk_dlaa_device_exts(ep, ne, ext, &n_ext, 40); // NGX's; the eight slots after it stay for the seven below
if (has_ext(ep, ne, VK_EXT_MEMORY_BUDGET_EXTENSION_NAME)) { g_vk.has_memory_budget = 1; ext[n_ext++] = VK_EXT_MEMORY_BUDGET_EXTENSION_NAME; }
// GPU timestamps on the CPU clock (vk_sync.c): the perf line splits GPU idle time into waiting for a submission or not.
if (has_ext(ep, ne, VK_KHR_CALIBRATED_TIMESTAMPS_EXTENSION_NAME)) { g_vk.has_calibrated = 2; ext[n_ext++] = VK_KHR_CALIBRATED_TIMESTAMPS_EXTENSION_NAME; }
else if (has_ext(ep, ne, VK_EXT_CALIBRATED_TIMESTAMPS_EXTENSION_NAME)) { g_vk.has_calibrated = 1; ext[n_ext++] = VK_EXT_CALIBRATED_TIMESTAMPS_EXTENSION_NAME; }
if (vk_hdr_wanted() && has_ext(ep, ne, VK_EXT_HDR_METADATA_EXTENSION_NAME)) { // the display's peak (vk_hdr_metadata)
g_vk.has_hdr_metadata = 1;
ext[n_ext++] = VK_EXT_HDR_METADATA_EXTENSION_NAME;
}
// GPU breadcrumbs for a lost device (vk_crumbs.c): AMD's drivers and RADV report it.
if (has_ext(ep, ne, VK_AMD_BUFFER_MARKER_EXTENSION_NAME)) { g_vk.has_buffer_marker = 1; ext[n_ext++] = VK_AMD_BUFFER_MARKER_EXTENSION_NAME; }
// Pass marks on NVIDIA (vk_crumbs.c): checkpoints only with TOTK_PASS_CRUMBS=1, since NVIDIA documents a cost for
// the extension. NVIDIA's drivers report it, AMD's do not.
if (vk_pass_marks_want_nv() && has_ext(ep, ne, VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME)) {
g_vk.has_nv_checkpoints = 1;
ext[n_ext++] = VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME;
}
// Graphics pipeline library: chained last so it can be dropped again when vk_caps_gpl declines it.
void **gpl_link = NULL;
if (has_ext(ep, ne, VK_KHR_PIPELINE_LIBRARY_EXTENSION_NAME) && has_ext(ep, ne, VK_EXT_GRAPHICS_PIPELINE_LIBRARY_EXTENSION_NAME)) {
@@ -368,7 +397,7 @@ int vk_init(void) {
plat_mutex_lock(&g_lock);
if (!g_ready) {
memset(&g_vk, 0, sizeof g_vk);
if (create_instance() && pick_device() && create_device()) g_ready = 1, vk_headroom_start();
if (create_instance() && pick_device() && create_device()) g_ready = 1, vk_headroom_start(), vk_dlaa_init();
else destroy_all();
}
int ok = g_ready;
@@ -407,6 +436,7 @@ void vk_device_fault_report(VkResult r) {
if (done) { plat_mutex_unlock(&lock); return; }
done = 1;
vk_crumbs_report();
vk_pass_marks_report();
VkCtx *c = vk_ctx();
PFN_vkGetDeviceFaultInfoEXT get =
c && c->has_device_fault ? (PFN_vkGetDeviceFaultInfoEXT)vkGetDeviceProcAddr(c->device, "vkGetDeviceFaultInfoEXT")
@@ -477,11 +507,11 @@ int probe_vkdevice(void) {
c->device_index, c->props.deviceName, VK_API_VERSION_MAJOR(v), VK_API_VERSION_MINOR(v), VK_API_VERSION_PATCH(v),
c->gfx_family, c->xfer_family, c->xfer_shared ? " (shared queue)" : "", c->min_imported_host_alignment);
printf("probe-vkdevice: optional: custom_border=%d eds=%d eds2=%d eds3=%d vertex_input=%d cond_render=%d xfb=%d provoking=%d "
"robustness2=%d fault=%d budget=%d bda=%d interlock=%d validation=%d\n",
"robustness2=%d fault=%d budget=%d bda=%d interlock=%d buffer_marker=%d nv_checkpoints=%d validation=%d\n",
c->has_custom_border_color, c->has_eds, c->has_eds2, c->has_eds3, c->has_vertex_input_dynamic_state,
c->has_conditional_rendering, c->has_transform_feedback, c->has_provoking_vertex, c->has_robustness2,
c->has_device_fault, c->has_memory_budget, c->has_buffer_device_address, c->has_fragment_shader_interlock,
c->validation);
c->has_buffer_marker, c->has_nv_checkpoints, c->validation);
vk_shutdown();
printf("probe-vkdevice: %s (validation errors %ld)\n", g_errors_total ? "FAILED" : "passed", g_errors_total);
return g_errors_total ? 1 : 0;
+1271
View File
File diff suppressed because it is too large. Load diff
+48
View File
@@ -0,0 +1,48 @@
// DLAA (vk_dlaa.c): NVIDIA DLSS at the scene's own size, behind TOTK_DLAA (totk.ini dlaa = 1).
#pragma once
#include "vk.h"
// The narrowest scene the DLSS pass and the motion passes recognise by its D32F depth: Ultra Performance at a 1080p
// output renders 640 wide, smaller windows less.
#define DLAA_SCENE_MIN_W 320u
int vk_dlaa_wanted(void); // the setting is on (the device may still lack DLSS)
// vk_device.c: NGX's instance and device extensions join the lists (room for max names); vk_dlaa_init after the
// device exists brings NGX up and checks that DLSS is available.
void vk_dlaa_instance_exts(const char **ext, uint32_t *n, uint32_t max);
void vk_dlaa_device_exts(const VkExtensionProperties *have, uint32_t nhave, const char **ext, uint32_t *n, uint32_t max);
void vk_dlaa_init(void);
// 1 when dlaa is on and NGX came up with DLSS (after vk_dlaa_init): a DLSS mode's smaller scene is scaled up by DLSS.
int vk_dlaa_available(void);
// vk_exec.c vk_exec_pass_begin, once the pass's targets are resolved and before its barrier: arms the frame on the
// scene's light target or, at the first quarter-width pass after it, runs DLAA on that target. Each present ends the
// frame (vk_dlaa_frame).
typedef struct VkExec VkExec;
void vk_dlaa_pass(VkExec *ex);
void vk_dlaa_frame(void);
// vk_exec_draw.c, each draw before its fixed state is recorded: notes the scene camera block (vk_dlaa_draw), and moves
// the viewport of the scene's draws by the frame's jitter (vk_dlaa_viewport, when the viewport is recorded).
void vk_dlaa_draw(VkExec *ex);
void vk_dlaa_viewport(VkExec *ex, VkViewport *v);
// vk_mvsurvey.c (TOTK_MV_SURVEY): notes the uniform blocks of each scene draw, beside vk_dlaa_draw; each present
// compares them with the previous frames' and logs a summary now and then.
void vk_mvsurvey_draw(VkExec *ex);
void vk_mvsurvey_frame(void);
void vk_mvprev_draw(VkExec *ex); // vk_mvprev.c: notes the scene draw's object and bone blocks
// Per-object motion (vk_exec_draw.c): the moving scene draws are listed again during the replay with
// their vertex shader's last-frame variant; vk_dlaa.c mv_pass records them over the camera motion into ex->cb (and
// leaves every binding of the replay to be set again; draws whose camera block is not cam are left out).
// vk_dlaa_prev_camera: last frame's camera block and this frame's jitter, 0 when there is no history.
int vk_mvobj_execute(VkExec *ex, uint64_t cam, VkImageView mv, VkImageView depth, VkFormat depth_fmt, uint32_t w,
uint32_t h);
int vk_dlaa_prev_camera(VkDescriptorBufferInfo *out, float jitter[2]);
// vk_mvcheck.c (TOTK_MV_CHECK, test): mv_pass hands it the motion image after the camera pass and, after the object
// pass, the motion image again and the scene light target it ran on; it measures how well the vectors fit the picture.
void vk_mvcheck_camera(VkCommandBuffer cb, VkImage mv, uint32_t w, uint32_t h, float jx, float jy);
void vk_mvcheck_final(VkCommandBuffer cb, uint64_t fence, VkImage mv, VkImage cimg, VkFormat cfmt, uint32_t level,
uint32_t layer, uint32_t w, uint32_t h, float jx, float jy);
const char *vk_mvobj_frame_masks(void); // vk_exec_draw.c: the last motion list, per position and changed banks
void vk_mvcheck_output(VkCommandBuffer cb, VkImage out, uint32_t ow, uint32_t oh); // after DLSS on a check frame
// vk_exec_draw.c, once a draw's fragment shader is known: 1 skips the draw (the game's FXAA while TOTK_FXAA is 0, its
// scaling draw when DLSS wrote the scaled picture).
int vk_dlaa_skip_draw(VkExec *ex, const GfxShader *fs);
+8 -5
View File
@@ -18,8 +18,8 @@
// as x/2+1/2, UNORM and sRGB bytes written as stored. Caps: MAX_PASSES passes copied, PNG_CAP bytes of PNGs.
// TOTK_DUMP_TEX=<id>|<w>x<h>[,...]: those texture slots, or 2D textures of that size, are copied where first sampled,
// whatever their format.
// TOTK_DUMP_UBO=1: each listed pipeline also prints the first 16 vec4 of its user uniform blocks (c3 and up), read from
// guest memory when the entry is listed. A block the submission rewrites with UpdateUniformBuffer shows its value from
// TOTK_DUMP_UBO=<n>: each listed pipeline also prints the first n vec4 of its user uniform blocks (c3 and up; 1 means 16,
// the cap is 4096), read from guest memory when the entry is listed. A block the submission rewrites with UpdateUniformBuffer shows its value from
// before the submission (vk_exec_draw.c upd_note).
// TOTK_DUMP_SKIP_RUNS=1: a render pass with the same targets as the render pass before it is logged but not copied
// (the terrain decals draw one pass each into the G-buffer and would use up both caps).
@@ -48,7 +48,7 @@ static uint64_t dump_frame, log_from; // log_from: TOTK_DUMP_LOG, first frame
static char dir[400];
static FILE *passes_f, *images_f;
static int seq, finished, copied; // copied: passes and dispatches of the dump frame whose images were copied
static int skip_runs, dump_ubo; // TOTK_DUMP_SKIP_RUNS, TOTK_DUMP_UBO
static int skip_runs, dump_ubo; // TOTK_DUMP_SKIP_RUNS, TOTK_DUMP_UBO (vec4 per block, 0 for none)
static uint32_t want_tex[16][2]; // TOTK_DUMP_TEX: slot id and 0, or width and height
static int nwant_tex;
static uint64_t last_targets; // targets_sig of the last render pass; 0 after a dispatch
@@ -576,7 +576,7 @@ static void describe_bindings(Str *b, const VkExec *ex, const VkPipeInfo *info)
if (u->addr && vk_mem_resolve(u->addr, 1, &ms)) {
uint64_t n = u->size && u->size < ms.avail ? u->size : ms.avail;
const float *f = (const float *)(uintptr_t)u->addr;
for (uint64_t k = 0; k < 16 && (k + 1) * 16 <= n; k++)
for (uint64_t k = 0; k < (uint64_t)dump_ubo && (k + 1) * 16 <= n; k++)
sp(b, "%s[%llu] %g %g %g %g", k % 4 ? " " : "\n ", (unsigned long long)k, f[4 * k], f[4 * k + 1],
f[4 * k + 2], f[4 * k + 3]);
} else {
@@ -870,7 +870,10 @@ void vk_dump_init(void) {
const char *sr = cfg_get("TOTK_DUMP_SKIP_RUNS");
skip_runs = sr && *sr && *sr != '0';
const char *du = cfg_get("TOTK_DUMP_UBO");
dump_ubo = du && *du && *du != '0';
dump_ubo = du && *du ? atoi(du) : 0;
if (dump_ubo == 1) dump_ubo = 16;
if (dump_ubo > 4096) dump_ubo = 4096;
if (dump_ubo < 0) dump_ubo = 0;
const char *wt = cfg_get("TOTK_DUMP_TEX");
for (char *q = (char *)wt; q && *q && nwant_tex < 16; q += *q == ',') {
uint32_t *w = want_tex[nwant_tex++];
+35 -3
View File
@@ -27,6 +27,7 @@
#include "tex.h"
#include "vk.h"
#include "vk_exec.h"
#include "vk_dlaa.h"
#define WEAK __attribute__((weak))
#define CALL_DEPTH 8
@@ -345,6 +346,7 @@ static void resolve_target(const tex_t *t, const view_t *v, int has_v, int depth
}
o->image = img->image;
o->img = img;
o->scale = img->scale ? img->scale : 1;
o->format = fmt;
o->view_type = layers > 1 ? VK_IMAGE_VIEW_TYPE_2D_ARRAY : VK_IMAGE_VIEW_TYPE_2D;
o->aspect = depth_slot ? img->aspect & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)
@@ -380,7 +382,7 @@ static void resolve_rt(VkExec *ex) {
ex->rt_resolved = 1;
const p_set_rt *r = &ex->rt;
int n = r->n < 0 ? 0 : r->n > 8 ? 8 : r->n;
uint32_t w = UINT32_MAX, h = UINT32_MAX, layers = UINT32_MAX, samples = 0;
uint32_t w = UINT32_MAX, h = UINT32_MAX, layers = UINT32_MAX, samples = 0, scale = 1;
for (int i = 0; i < 8; i++) {
VkExecTarget *t = &ex->color[i];
resolve_target(i < n ? r->color[i] : NULL, &r->cview[i], i < n && r->has_cview[i], 0, t);
@@ -391,6 +393,7 @@ static void resolve_rt(VkExec *ex) {
if (t->height < h) h = t->height;
if (t->layers < layers) layers = t->layers;
if (!samples) samples = t->samples;
if (t->scale > scale) scale = t->scale;
}
VkExecTarget *d = &ex->depth;
resolve_target(r->depth, &r->dview, r->has_dview, 1, d);
@@ -402,6 +405,7 @@ static void resolve_rt(VkExec *ex) {
if (d->height < h) h = d->height;
if (d->layers < layers) layers = d->layers;
if (!samples) samples = d->samples;
if (d->scale > scale) scale = d->scale;
}
ex->pass_noatt = w == UINT32_MAX;
if (ex->pass_noatt) {
@@ -413,6 +417,7 @@ static void resolve_rt(VkExec *ex) {
ex->vp[0][1], ex->vp[0][2], ex->vp[0][3]);
}
ex->pass_w = w, ex->pass_h = h, ex->pass_layers = layers;
ex->pass_scale = ex->pass_noatt ? 1 : scale;
ex->pass_ncolor = (uint32_t)n;
ex->pass_samples = samples ? samples : 1;
ex->pipe.samples = (uint8_t)ex->pass_samples;
@@ -571,6 +576,8 @@ void vk_exec_barrier(VkExec *ex) { barrier_to(ex, NULL, NULL, 0); }
void vk_exec_pass_begin(VkExec *ex) {
if (ex->in_pass) return;
resolve_rt(ex);
vk_contact_pass_begin(ex);
vk_dlaa_pass(ex); // DLAA runs before the bloom chain's first pass (vk_dlaa.c)
// Learned targets (VkTexImage.fb_learned) are attached in the feedback layout
VkImage want[9];
VkImageAspectFlags wasp[9];
@@ -605,6 +612,20 @@ void vk_exec_pass_begin(VkExec *ex) {
if (d->aspect & VK_IMAGE_ASPECT_DEPTH_BIT) da = a;
if (d->aspect & VK_IMAGE_ASPECT_STENCIL_BIT) sa = a;
}
// The start mark goes between the barrier and vkCmdBeginRendering, its end right after vkCmdEndRendering
// (vk_exec_pass_end): outside the pass, and without breaking it.
VkPassMark *m = ex->mark = vk_pass_mark_begin(ex->cb, VK_MARK_PASS, ex->fence);
if (m) {
m->step = ex->mark_passes++;
m->w = ex->pass_w, m->h = ex->pass_h, m->d = ex->pass_layers;
m->ncolor = (uint8_t)(ex->pass_ncolor < 8 ? ex->pass_ncolor : 8);
for (int i = 0; i < m->ncolor; i++) m->color[i] = ex->pass_color[i];
m->depth = ex->pass_depth ? ex->pass_depth : ex->pass_stencil;
// The shaders bound now are the first draw's when it repeats the pipeline state; when it does not,
// vk_exec_draw.c prepare_draw replaces them as it records the new state.
vk_exec_draw_shaders(&m->first[0], &m->first[1]);
ex->mark_draws0 = vk_exec_frame.draws;
}
VkRenderingInfo ri = {.sType = VK_STRUCTURE_TYPE_RENDERING_INFO, .renderArea = {{0, 0}, {ex->pass_w, ex->pass_h}},
.layerCount = ex->pass_layers, .colorAttachmentCount = ex->pass_ncolor,
.pColorAttachments = ca,
@@ -622,6 +643,14 @@ void vk_exec_pass_end(VkExec *ex) {
vkCmdEndRendering(ex->cb);
ex->recorded++;
ex->in_pass = 0;
if (ex->mark) {
// vk_exec_frame_log resets the frame counters at a present (TOTK_TRACE=gfx): then only the draws since it count
uint64_t d = vk_exec_frame.draws, d0 = ex->mark_draws0;
ex->mark->draws = (uint32_t)(d >= d0 ? d - d0 : d);
if (ex->mark->draws) vk_exec_draw_shaders(&ex->mark->last[0], &ex->mark->last[1]);
vk_pass_mark_end(ex->cb, ex->mark);
ex->mark = NULL;
}
for (int i = 0; i < ex->pass_ncolor && i < 8; i++) // stand-ins of 3D BC targets go to their textures
if (ex->color[i].image && ex->color[i].img && ex->color[i].img->image != ex->color[i].image)
bc_copy_back(ex, &ex->color[i]);
@@ -667,8 +696,9 @@ VkBuffer vk_exec_inline_buffer(VkDeviceSize size) {
VkRect2D vk_exec_scissor(const VkExec *ex) {
int64_t w = ex->pass_w, h = ex->pass_h;
if (!ex->has_scissor) return (VkRect2D){{0, 0}, {(uint32_t)w, (uint32_t)h}};
int64_t x0 = ex->scissor.x, y0 = ex->scissor.y;
int64_t x1 = x0 + ex->scissor.w, y1 = y0 + ex->scissor.h;
int64_t k = ex->pass_scale > 1 ? ex->pass_scale : 1;
int64_t x0 = ex->scissor.x * k, y0 = ex->scissor.y * k;
int64_t x1 = x0 + (int64_t)ex->scissor.w * k, y1 = y0 + (int64_t)ex->scissor.h * k;
if (x0 < 0) x0 = 0;
if (y0 < 0) y0 = 0;
if (x1 > w) x1 = w;
@@ -893,6 +923,8 @@ int vk_exec_record(VkCommandBuffer cb, const uint64_t *handles, int n, uint64_t
ex->fence = fence;
ex->recorded = 0;
ex->in_pass = 0;
ex->mark = NULL;
ex->mark_passes = ex->mark_dispatches = 0;
ex->dirty = VK_EXEC_DIRTY_ALL;
ex->rt_resolved = 0; // images may have changed since the last command buffer
ex->nviews = 0;
+20
View File
@@ -35,6 +35,7 @@ typedef struct {
uint32_t width, height, samples; // extent of that level; with blocks, in blocks
int32_t nvn_format; // NVNformat of the view (VkPipeState.color_fmt / depth_fmt)
const VkTexImage *img; // the image (fb_usage, fb_learned)
uint8_t scale; // VkTexImage.scale
} VkExecTarget;
// The replay state. One instance lives for the run: NVN state is queue state and carries over from one submission to
@@ -46,12 +47,19 @@ typedef struct VkExec {
int recorded; // Vulkan commands recorded so far; every handler adds the ones it records
int in_pass; // inside vkCmdBeginRendering
uint32_t dirty; // VK_EXEC_DIRTY_*
// Pass marks (vk.h vk_pass_mark_begin): the open pass's record (NULL: none or marks off), vk_exec_frame.draws when
// it began, and the passes and dispatches this submission marked so far.
VkPassMark *mark;
uint64_t mark_draws0;
uint32_t mark_passes, mark_dispatches;
// ---- render targets (OP_SET_RT) and the current pass
p_set_rt rt; // last OP_SET_RT payload (a change ends the open pass); rt.n 0, no depth: none
int rt_resolved; // color[] and depth hold this command buffer's images for rt
VkExecTarget color[8], depth; // resolved targets
uint32_t pass_w, pass_h, pass_layers; // render area and layer count of the open (or next) pass
uint32_t pass_scale; // its targets' VkTexImage.scale: game viewports and scissors
// are multiplied by it
int pass_noatt; // the pass has no attachment: its size follows the draws (vk_exec_noatt_dims)
VkFormat pass_color[8], pass_depth, pass_stencil; // attachment formats of the pass (VkPipelineRenderingCreateInfo);
// VK_FORMAT_UNDEFINED: none
@@ -123,9 +131,14 @@ void vk_exec_inline_end(int reopen);
// vk_exec_draw.c: forget what the command buffer being recorded has bound (pipeline, sets, dynamic state, vertex
// buffers): the replay continues in a new one (vk_sync_split).
void vk_exec_draw_new_cb(void);
// vk_exec_draw.c: the vertex and fragment shader of the last draw recorded into this command buffer (NULL: none yet).
void vk_exec_draw_shaders(const GfxShader **vs, const GfxShader **fs);
VkBuffer vk_exec_inline_buffer(VkDeviceSize size);
// vk_exec.c: the stand-in a 3D BC render target is drawn through goes with its image (vk_exec_image_gone).
void vk_exec_bc_gone(VkImage image);
// vk_hdr.c: with TOTK_HDR=1, notes a draw into a presented window texture (vk_hdr_track: set by the first present).
extern int vk_hdr_track;
void vk_hdr_draw(VkExec *ex, const VkPipeInfo *info);
// Scissor 0 clipped to the render area of the open pass; extent 0: nothing to draw.
VkRect2D vk_exec_scissor(const VkExec *ex);
void vk_exec_noatt_dims(const VkExec *ex, uint32_t *w, uint32_t *h); // pass size when no attachment is set
@@ -175,6 +188,13 @@ VkImageView vk_exec_target_view(const VkTexImage *img, VkFormat format, VkImageV
// vk_exec_xfer.c: OP_COPY_B2B, OP_COPY_B2T, OP_COPY_T2B, OP_COPY_T2T, OP_CLEAR_TEX, OP_SIGNAL_EVENT, OP_REPORT_COUNTER,
// OP_RESET_COUNTER, OP_RENDER_ENABLE, OP_RENDER_COND, OP_CLEAR_BUF.
void vk_exec_op_xfer(VkExec *ex, uint32_t op, const void *payload);
// vk_dlaa.c: once DLSS has scaled the scene this frame, passes larger than the scene's light target vk_dlaa_swap_img
// sample DLSS's output vk_dlaa_swap_view in its place, so the game's scaling draw scales DLSS's picture.
extern const VkTexImage *vk_dlaa_swap_img;
extern VkImageView vk_dlaa_swap_view;
// vk_contact.c: a pass about to begin (its targets resolved, no pass open), and a dispatch or copy about to be recorded
void vk_contact_pass_begin(VkExec *ex);
void vk_contact_flush(VkExec *ex);
// vk_exec_xfer.c, samples-passed counting: a draw about to be recorded in the open pass (begins an occlusion query
// when counting and none is active), and the open pass about to end (ends the active query).
void vk_exec_oq_draw(VkExec *ex);
+873 -12
View File
File diff suppressed because it is too large. Load diff
+108 -2
View File
@@ -3,7 +3,8 @@
// the completion thread; a guest-memory word a callback writes is visible once fence_wait returns; finish drains every
// submission; a present of a cleared vk_texture.c image (layout GENERAL) reads back exactly through the swapchain
// capture. Clear part: a hand-built op stream (SET_RT to an RGBA8 and a D32 texture, whole-target clears,
// then scissored clears) through submit reads back exactly with read_texels.
// then scissored clears) through submit reads back exactly with read_texels. Pass marks part (test_marks): the GPU's
// buffer marks and the ring records name the last pass of a submission, and the device-lost report text says so.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -175,7 +176,7 @@ static void init_tex(tex_t *t, pool_t *pool, int64_t off, int format) {
t->d.target = NVN_TEXTURE_TARGET_2D, t->d.format = format, t->d.width = TEX_W, t->d.height = TEX_H;
t->d.depth = 1, t->d.levels = 1;
nvn_tex_layout(&t->d, &t->L);
t->pool = pool, t->off = off, t->mem = pool->mem + off, t->serial = 100 + (uint64_t)off;
t->pool = pool, t->pool_flags = (uint16_t)pool->flags, t->off = off, t->mem = pool->mem + off, t->serial = 100 + (uint64_t)off;
}
// Pixel of the RGBA8 target after the stream: the scissored second clear inside the rectangle, the first elsewhere.
@@ -386,6 +387,74 @@ static uint8_t *draw_prefix(uint8_t *q, prog_t *prog, const pool_t *pool, tex_t
return q;
}
// ---- pass marks part (vk_crumbs.c): one submission with a pass of 2 draws into the draw part's target, a dispatch and
// a pass of 3 draws into a second target. Once its fence is done, the buffer marks must name the last pass as both
// started and finished, the ring records must hold what the three were, and vk_pass_marks_format (the text
// vk_device_fault_report logs) must name it. Without VK_AMD_buffer_marker or with TOTK_PASS_CRUMBS=0 it is skipped:
// NVIDIA's checkpoints can only be read once the device is lost.
static char marks_text[2048];
static int marks_skipped;
static int test_marks(const GfxBackend *b, pool_t *pool, tex_t *color, prog_t *gfx, prog_t *cs) {
uint32_t s0, f0;
if (!vk_pass_marks_read(&s0, &f0)) {
marks_skipped = 1;
return 0;
}
static tex_t second;
init_tex(&second, pool, 0x40000, NVN_FORMAT_RGBA8);
CHECK(0x40000 + second.L.size <= 0x80000, "pass-marks target exceeds its pool slot");
static _Alignas(8) uint8_t stream[8192];
uint8_t *q = draw_prefix(stream, gfx, pool, color);
const p_draw d = {NVN_DRAW_PRIMITIVE_TRIANGLES, 0, 3, 0, 0};
for (int i = 0; i < 2; i++) q = put(q, OP_DRAW, &d, sizeof d);
const p_bind_program bc = {cs, 1 << 5};
q = put(q, OP_BIND_PROGRAM, &bc, sizeof bc);
const p_dispatch dp = {2, 1, 1, 0};
q = put(q, OP_DISPATCH, &dp, sizeof dp);
const p_bind_program bg = {gfx, 3};
q = put(q, OP_BIND_PROGRAM, &bg, sizeof bg);
p_set_rt rt;
memset(&rt, 0, sizeof rt);
rt.n = 1, rt.color[0] = &second;
q = put(q, OP_SET_RT, &rt, sizeof rt);
for (int i = 0; i < 3; i++) q = put(q, OP_DRAW, &d, sizeof d);
q = put(q, OP_END, NULL, 0);
CHECK(q <= stream + sizeof stream, "pass-marks op stream overflow");
uint64_t handle = (uint64_t)(uintptr_t)stream;
uint64_t f = b->submit(&handle, 1);
CHECK(b->fence_wait(f, 20000000000ull), "fence_wait of the pass-marks submission timed out");
uint32_t started = 0, finished = 0;
vk_pass_marks_read(&started, &finished);
CHECK(started && started == finished, "after the fence the GPU last started mark %u and finished mark %u (before "
"the submission: %u and %u)", started, finished, s0, f0);
const VkPassMark *p1 = vk_pass_mark_record(finished), *dm = vk_pass_mark_record(finished - 1),
*p0 = vk_pass_mark_record(finished - 2);
CHECK(p1 && p1->kind == VK_MARK_PASS && p1->fence == f && p1->step == 1,
"the last finished mark %u is not pass 1 of submission %llu", finished, (unsigned long long)f);
CHECK(p1->w == TEX_W && p1->h == TEX_H && p1->d == 1 && p1->ncolor == 1 &&
p1->color[0] == VK_FORMAT_R8G8B8A8_UNORM && p1->depth == VK_FORMAT_UNDEFINED,
"pass 1 has %ux%u, %u layers, %u colour targets, format %d, depth %d", p1->w, p1->h, p1->d, p1->ncolor,
(int)p1->color[0], (int)p1->depth);
CHECK(p1->draws == 3 && p1->first[0] && p1->first[1] && p1->first[0] == p1->last[0] && p1->first[1] == p1->last[1],
"pass 1 has %u draws (3 expected) and shaders %p %p ... %p %p", p1->draws, (const void *)p1->first[0],
(const void *)p1->first[1], (const void *)p1->last[0], (const void *)p1->last[1]);
CHECK(dm && dm->kind == VK_MARK_DISPATCH && dm->fence == f && dm->step == 0 && dm->w == 2 && dm->h == 1 &&
dm->d == 1 && dm->first[0],
"the mark before pass 1 is not dispatch 0 of 2x1x1 groups of submission %llu", (unsigned long long)f);
CHECK(p0 && p0->kind == VK_MARK_PASS && p0->fence == f && p0->step == 0 && p0->draws == 2 &&
p0->first[0] == p1->first[0],
"the mark before the dispatch is not pass 0 of submission %llu with 2 draws", (unsigned long long)f);
vk_pass_marks_format("VK_AMD_buffer_marker", started, finished, marks_text, sizeof marks_text);
char want[128];
snprintf(want, sizeof want, "last finished %u: pass 1 of submission %llu: %ux%u, 1 layer, colour formats %d, ",
finished, (unsigned long long)f, TEX_W, TEX_H, (int)VK_FORMAT_R8G8B8A8_UNORM);
CHECK(strstr(marks_text, want) && strstr(marks_text, ", 3 draws; first vs "),
"the report text lacks \"%s\" or the draw count:\n%s", want, marks_text);
b->texture_release(&second);
return 0;
}
static int test_draw(const GfxBackend *b, uint8_t *guest, int *n_drawn, int *n_tries, int *n_cs) {
char root[PLAT_PATH_MAX * 2], path[PLAT_PATH_MAX * 2 + 64];
CHECK(probe_census_dir(root, sizeof root), "no build/v%d/shaders/jobs.json above the exe (run tools/shader_census.py)",
@@ -503,10 +572,12 @@ static int test_draw(const GfxBackend *b, uint8_t *guest, int *n_drawn, int *n_t
// Compute: a few census compute shaders, one dispatch each, resources unbound (zero buffers and stand-in images).
int dispatched = 0;
prog_t *cs_prog = NULL;
for (int t = 0; t < 4 && t < nc; t++) {
const DrawEnt *one[1] = {&e[cs[(long long)t * nc / (nc < 4 ? nc : 4)]]};
prog_t *prog = dr_prog(root, one, 1);
CHECK(prog, "census code file of %.16s is missing", one[0]->key);
cs_prog = prog;
uint8_t *q = stream;
q = put(q, OP_BEGIN, NULL, 0);
const p_bind_program bp = {prog, 1 << 5};
@@ -530,6 +601,7 @@ static int test_draw(const GfxBackend *b, uint8_t *guest, int *n_drawn, int *n_t
dispatched++;
ind_dispatches++;
}
if (test_marks(b, &pool, &color, hit, cs_prog)) return 1;
b->texture_release(&color);
b->pool_fini(&pool);
free(pairs), free(cs), free(e), free(jobs);
@@ -845,7 +917,33 @@ static int test_mirror(const GfxBackend *b, uint8_t *guest, int *bytes) {
return 0;
}
// A pool of zero bytes (TotK makes some now and then; MacNativeGames hit one on 1.2.1) initialises as an empty pool: no
// Vulkan buffer or memory (a buffer or import of 0 bytes is invalid usage) and no pool index entry, so a lookup at its
// address still finds the pool that starts there, before and after the empty pool's Finalize.
static int test_empty_pool(const GfxBackend *b, uint8_t *guest) {
pool_t pool = {.magic = NVN_POOL_MAGIC, .flags = 0x22, .mem = guest + 0xE00000, .size = 0x100000,
.game_mem = guest + 0xE00000};
pool_t empty = {.magic = NVN_POOL_MAGIC, .flags = 0x22, .mem = guest + 0xE00000, .size = 0,
.game_mem = guest + 0xE00000};
CHECK(b->pool_init(&pool), "pool_init of a CPU-visible pool for the empty-pool part");
long errors = vk_validation_errors_total();
CHECK(b->pool_init(&empty), "pool_init of a zero-byte pool");
uint64_t a = (uint64_t)(uintptr_t)pool.mem;
VkMemSpan whole, at, after;
CHECK(vk_mem_resolve(a + 16, 16, &whole) && whole.buffer, "the pool beside an empty pool is not resolved");
CHECK(vk_mem_resolve(a, 0, &at) && at.buffer == whole.buffer && at.offset == whole.offset - 16,
"a lookup at the start of a pool finds the empty pool there");
CHECK(vk_validation_errors_total() == errors, "the zero-byte pool raised %ld validation errors",
vk_validation_errors_total() - errors);
b->pool_fini(&empty);
CHECK(vk_mem_resolve(a + 16, 16, &after) && after.buffer == whole.buffer,
"the empty pool's Finalize took the pool beside it out of the index");
b->pool_fini(&pool);
return 0;
}
int probe_vkexec(void) {
vk_hdr_off(); // the present checks read 8-bit swapchain pixels
layouts_equal = 0;
main_tid = plat_thread_id();
const GfxBackend *b = &gfx_vulkan_backend;
@@ -865,6 +963,7 @@ int probe_vkexec(void) {
int nvnx_bytes = 0, mirror_bytes = 0;
if (!bad) bad = test_nvnx(b, guest, &nvnx_bytes);
if (!bad) bad = test_mirror(b, guest, &mirror_bytes);
if (!bad) bad = test_empty_pool(b, guest);
b->finish();
vk_pipeline_shutdown(); // the pipelines and the draw part's stand-ins go before the device
vk_exec_draw_shutdown();
@@ -909,5 +1008,12 @@ int probe_vkexec(void) {
"between submissions mirrored, CPU bytes beside a fill kept, %d bytes compared)\n", mirror_bytes);
else
printf("probe-vkexec: mirror part skipped (memory mode import)\n");
if (marks_skipped)
printf("probe-vkexec: pass marks part skipped (no VK_AMD_buffer_marker, or TOTK_PASS_CRUMBS=0)\n");
else
printf("probe-vkexec: pass marks part passed (pass, dispatch, pass in one submission: the GPU's last started and "
"finished mark is the last pass, ring records exact); the report reads:\n%s\n", marks_text);
printf("probe-vkexec: empty pool part passed (a zero-byte pool at the start of another: no Vulkan objects, lookups "
"there find the other pool before and after its Finalize)\n");
return 0;
}
Loaded 100 of 186 files, more files were not shown because too many files have changed in this diff. Show more