Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
The Mac front end reads DM_KEYMAP and DM_PAD_MAP, and two silent reverts are repaired
LNPANDY9f7d42162f36
diff --git a/dm/host/front_mac.m b/dm/host/front_mac.mindex a99ce4da..423c581f 100644--- a/dm/host/front_mac.m+++ b/dm/host/front_mac.m@@ -1,7 +1,8 @@// Mac front end: with DM_WINDOW=1 open a window (CAMetalLayer, for the graphics backend to present frames) + keyboard and controllers → dm_input; the guest runs on a large-stack thread instead and the main thread belongs to AppKit.// Without DM_WINDOW: the guest runs directly on the current thread, behaving the same as with no front end (windowless tests use this).// The window is fullscreen-capable (the green button and ⌃⌘F); DM_FULLSCREEN starts it that way. ⌘Q quits; the left mouse button is the touchscreen.-// Key map (Nintendo layout): WASD left stick, arrow keys D-pad, J=A K=B U=X I=Y, Q=L E=R, Z=ZL C=ZR, F=press left stick G=press right stick, Return=+ Tab=−, Space=shake the controller.+// Key map (Nintendo layout): WASD left stick, arrow keys D-pad, J=A K=B U=X I=Y, Q=L E=R, Z=ZL C=ZR, F=press left stick G=press right stick, Return=+ Tab=−, Space=shake the controller;+// DM_KEYMAP moves a function to another key (the right stick too), DM_PAD_MAP changes what a controller's buttons send (input_map.h).// Controllers: buttons by position as on the iPhone (right A, bottom B, top X, left Y), shoulders L R, triggers ZL ZR, Menu + Options −, both sticks and their presses.// Each controller is a player of its own (local co-op): the first one connected is player 1, together with the keyboard, the next player 2, and so on up to 8 (pad_slots.h);// DM_PAD_MERGE=1 merges every controller into player 1 instead, DM_KBD_PLAYER=own makes the keyboard player 1 on its own, with the controllers from player 2 on.@@ -14,13 +15,13 @@#include "front.h"#include "hle.h"#include "pad_slots.h"+#include "input_map.h"#include "haptics_apple.h"#include <signal.h>#include <math.h>static CAMetalLayer *g_layer;static uint64_t g_btn;-static int g_w, g_a, g_s, g_d;static int g_input_on = 1; // main thread: the game window is key, so its keyboard, mouse and controllers reach the game (input_release / input_resume)void *front_metal_layer(void) { return (__bridge void *)g_layer; }@@ -82,27 +83,20 @@ void front_screen_match(int fps) {if (!g_layer || g_match_want == fps) return; // no window (a windowless run's main thread runs the guest), or the rate as beforeg_match_want = fps; dispatch_async(dispatch_get_main_queue(), ^{ screen_match_apply(); });}+// Keyboard: each key holds one function of the key map (input_map.h; DM_KEYMAP changes it), the held functions make the buttons and both sticks+static key_map g_keys;+static uint32_t g_held_fn; // bit f: a key holding function f is downstatic void push(void) {- int32_t lx = (g_d - g_a) * 32767, ly = (g_w - g_s) * 32767;- dm_input_set(g_btn, lx, ly, 0, 0);-}-static int key_bit(unsigned short code) {- switch (code) {- case 38: return 0; case 40: return 1; case 32: return 2; case 34: return 3; // J K U I → A B X Y- case 3: return 4; case 5: return 5; // F G → press stick- case 12: return 6; case 14: return 7; case 6: return 8; case 8: return 9; // Q E Z C → L R ZL ZR- case 36: return 10; case 48: return 11; // Return Tab → + −- case 123: return 12; case 126: return 13; case 124: return 14; case 125: return 15; // ← ↑ → ↓- }- return -1;+ uint32_t h = g_held_fn;+ #define D(f) ((int32_t)(h >> (f) & 1))+ dm_input_set(g_btn, (D(IM_LRIGHT) - D(IM_LLEFT)) * 32767, (D(IM_LUP) - D(IM_LDOWN)) * 32767, (D(IM_RRIGHT) - D(IM_RLEFT)) * 32767, (D(IM_RUP) - D(IM_RDOWN)) * 32767);+ #undef D}static void on_key(NSEvent *e, int down) {if (!g_input_on) return;- unsigned short c = e.keyCode;- switch (c) { case 13: g_w = down; break; case 0: g_a = down; break; case 1: g_s = down; break; case 2: g_d = down; break; }- int b = key_bit(c);- uint64_t m = b >= 0 ? 1ull << b : c == 49 ? DM_BTN_SHAKE : 0; // Space: shaken while held- g_btn = down ? (g_btn | m) : (g_btn & ~m);+ int f = key_map_fn(&g_keys, e.keyCode); if (f < 0) return;+ g_held_fn = down ? (g_held_fn | 1u << f) : (g_held_fn & ~(1u << f));+ g_btn = (g_held_fn & 0xffff) | (g_held_fn >> IM_SHAKE & 1 ? DM_BTN_SHAKE : 0);push();}@@ -114,6 +108,7 @@ static void on_key(NSEvent *e, int down) {static pad_slots g_slots;static GCController *g_held[DM_PLAYERS]; // the controller of each slot, kept alive while it holds it (the slot table keys on its pointer)static int g_merge, g_kbd_own;+static pad_map g_padmap; // DM_PAD_MAP (input_map.h): what each button sends, applied to every controllerstatic int32_t pad_axis(float v) { return (int32_t)(fmaxf(-1.f, fminf(1.f, v)) * DM_STICK_MAX); }static void pad_read(GCExtendedGamepad *g) {if (!g_input_on) return;@@ -126,6 +121,7 @@ static void pad_read(GCExtendedGamepad *g) {K(g.buttonMenu, DM_BTN_PLUS); K(g.buttonOptions, DM_BTN_MINUS); K(g.leftThumbstickButton, DM_BTN_LS); K(g.rightThumbstickButton, DM_BTN_RS); // nil on pads without them: not pressedK(g.dpad.left, DM_BTN_LEFT); K(g.dpad.up, DM_BTN_UP); K(g.dpad.right, DM_BTN_RIGHT); K(g.dpad.down, DM_BTN_DOWN);#undef K+ m = pad_map_apply(&g_padmap, m);dm_pad_set_player(p, m, pad_axis(g.leftThumbstick.xAxis.value), pad_axis(g.leftThumbstick.yAxis.value), pad_axis(g.rightThumbstick.xAxis.value), pad_axis(g.rightThumbstick.yAxis.value));}static const char *pad_name(GCController *c) { return c.vendorName.UTF8String ?: "?"; }@@ -165,7 +161,7 @@ static void pads_changed(GCController *gone) {static int g_mouse_down; // the mouse holds the touch (DmGameView)static void input_release(void) {g_input_on = 0;- g_btn = 0; g_w = g_a = g_s = g_d = 0; push();+ g_btn = 0; g_held_fn = 0; push();if (g_mouse_down) { g_mouse_down = 0; dm_touch_set(NULL, 0); }if (g_merge) { for (GCController *c in GCController.controllers) if (c.extendedGamepad) { dm_pad_set(0, 0, 0, 0, 0); break; } }else for (int p = 0; p < DM_PLAYERS; p++) if (g_held[p]) dm_pad_set_player(p, 0, 0, 0, 0, 0);@@ -176,6 +172,10 @@ static void input_resume(void) {else for (int p = 0; p < DM_PLAYERS; p++) if (g_held[p].extendedGamepad) pad_read(g_held[p].extendedGamepad);}static void pads_start(void) {+ key_map_default(&g_keys); pad_map_default(&g_padmap);+ const char *km = getenv("DM_KEYMAP"), *pm = getenv("DM_PAD_MAP");+ if (km && *km) { int bad = key_map_parse(&g_keys, km); LOG("front end: keyboard map from DM_KEYMAP (%s)%s", km, bad ? ", malformed entries left out" : ""); }+ if (pm && *pm) { int bad = pad_map_parse(&g_padmap, pm); LOG("front end: controller buttons from DM_PAD_MAP (%s)%s", pm, bad ? ", malformed entries left out" : ""); }const char *e = getenv("DM_PAD_MERGE"); g_merge = e && atoi(e);e = getenv("DM_KBD_PLAYER"); g_kbd_own = !g_merge && e && !strcmp(e, "own");static const char kbd = 0;@@ -332,7 +332,7 @@ int front_text_input(const char *title, const char *sub, const char *guide, consdispatch_sync(dispatch_get_main_queue(), ^{// The box takes the keyboard and the mouse, so the game window never sees the key-up of the button or the touch-up of the click that opened it: nothing may stay pressed// while it is up, or the game reads the stuck button / touch the moment the box closes (Stardew Valley's character creation re-opened the keyboard endlessly)- g_btn = 0; g_w = g_a = g_s = g_d = 0; push();+ g_btn = 0; g_held_fn = 0; push();dm_touch_set(NULL, 0);int min_chars = g_swkbd_min_chars > 0 ? g_swkbd_min_chars : 0;NSString *info = [NSString stringWithFormat:@"%s%s%s", sub ? sub : "", sub && *sub && guide && *guide ? "\n" : "", guide ? guide : ""];diff --git a/dm/host/input_map.h b/dm/host/input_map.hnew file mode 100644index 00000000..56fa4993--- /dev/null+++ b/dm/host/input_map.h@@ -0,0 +1,82 @@+// The Mac front end's button assignments (front_mac.m; pure, so tests/t_input_map.c checks it without a keyboard or controller), named as DM_KEYS names them (hle_hid.c).+// DM_KEYMAP=<name>=<key code>,… puts a function on another key: <key code> is the macOS virtual key code (NSEvent.keyCode, decimal), or "none" to leave the function on no key.+// The names are the 16 buttons, the four directions of each stick (LUp … RRight) and Shake; the left stick is on W A S D, the right stick on no key, unless DM_KEYMAP says so.+// One key holds one function: the last assignment of a key wins, and the function that held it before is left on no key, so "A=40,B=38" swaps A and B.+// DM_PAD_MAP=<name>=<name>,… changes what a controller's buttons send: the button that sends <first> by default (by position, as the iPhone maps it) sends <second> instead,+// "none" sends nothing; buttons not named stay as they are, so "A=B,B=A" swaps them. Only the 16 buttons take part (the sticks stay sticks).+// A malformed entry is left out and named in the log; the rest of the list still applies.+#pragma once+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <strings.h>+#include "dm_input.h"++enum { IM_BUTTONS = 16, IM_LUP = 16, IM_LDOWN, IM_LLEFT, IM_LRIGHT, IM_RUP, IM_RDOWN, IM_RLEFT, IM_RRIGHT, IM_SHAKE, IM_N }; // functions 0..15 are the DM_BTN_* bits+#define IM_KEYS 128 // virtual key codes are below 128+typedef struct { int8_t fn[IM_KEYS]; } key_map; // the function each key code holds, -1 none+typedef struct { int8_t to[IM_BUTTONS]; } pad_map; // the button each default button sends, -1 none++static const char *const im_names[IM_N] = {"A", "B", "X", "Y", "LS", "RS", "L", "R", "ZL", "ZR", "Plus", "Minus", "Left", "Up", "Right", "Down",+ "LUp", "LDown", "LLeft", "LRight", "RUp", "RDown", "RLeft", "RRight", "Shake"};+static int im_name(const char *s, size_t n) {+ for (int f = 0; f < IM_N; f++) if (strlen(im_names[f]) == n && !strncasecmp(s, im_names[f], n)) return f;+ return -1;+}+static void key_map_default(key_map *m) {+ memset(m->fn, -1, sizeof m->fn);+ static const struct { uint8_t code; int8_t fn; } d[] = {+ {38, 0}, {40, 1}, {32, 2}, {34, 3}, // J K U I → A B X Y+ {3, 4}, {5, 5}, // F G → press stick+ {12, 6}, {14, 7}, {6, 8}, {8, 9}, // Q E Z C → L R ZL ZR+ {36, 10}, {48, 11}, // Return Tab → + −+ {123, 12}, {126, 13}, {124, 14}, {125, 15}, // ← ↑ → ↓+ {13, IM_LUP}, {1, IM_LDOWN}, {0, IM_LLEFT}, {2, IM_LRIGHT}, // W S A D → left stick+ {49, IM_SHAKE}, // Space: shaken while held+ };+ for (size_t i = 0; i < sizeof d / sizeof *d; i++) m->fn[d[i].code] = d[i].fn;+}+static void pad_map_default(pad_map *m) { for (int b = 0; b < IM_BUTTONS; b++) m->to[b] = (int8_t)b; }++// Walks "<name>=<value>,…", calling one(name's function, value text, its length) for each entry; returns the number of malformed entries, each logged here+static int im_parse(const char *spec, int max_fn, int (*one)(void *, int, const char *, size_t), void *ctx) {+ int bad = 0;+ for (const char *p = spec; p && *p; ) {+ const char *end = strchr(p, ','); size_t n = end ? (size_t)(end - p) : strlen(p);+ const char *eq = memchr(p, '=', n);+ int f = eq ? im_name(p, (size_t)(eq - p)) : -1;+ if (f < 0 || f >= max_fn || !one(ctx, f, eq + 1, n - (size_t)(eq + 1 - p))) {+ fprintf(stderr, "[dm] [RED] input map: '%.*s' is not <name>=<value>, left out\n", (int)n, p); // dm.h LOG's form (this header stays free of dm.h for the test)+ bad++;+ }+ p = end ? end + 1 : NULL;+ }+ return bad;+}+static int im_key_one(void *ctx, int f, const char *v, size_t n) {+ key_map *m = ctx; char buf[8];+ if (n == 4 && !strncasecmp(v, "none", 4)) { for (int c = 0; c < IM_KEYS; c++) if (m->fn[c] == f) m->fn[c] = -1; return 1; }+ if (!n || n >= sizeof buf || strspn(v, "0123456789") < n) return 0;+ memcpy(buf, v, n); buf[n] = 0; int code = atoi(buf);+ if (code >= IM_KEYS) return 0;+ for (int c = 0; c < IM_KEYS; c++) if (m->fn[c] == f) m->fn[c] = -1; // the function leaves its old key+ m->fn[code] = (int8_t)f; // the key's old function is left on no key+ return 1;+}+static int im_pad_one(void *ctx, int f, const char *v, size_t n) {+ pad_map *m = ctx;+ if (n == 4 && !strncasecmp(v, "none", 4)) { m->to[f] = -1; return 1; }+ int t = im_name(v, n); if (t < 0 || t >= IM_BUTTONS) return 0;+ m->to[f] = (int8_t)t; return 1;+}+static int key_map_parse(key_map *m, const char *spec) { return im_parse(spec, IM_N, im_key_one, m); }+static int pad_map_parse(pad_map *m, const char *spec) { return im_parse(spec, IM_BUTTONS, im_pad_one, m); }+static int key_map_fn(const key_map *m, unsigned code) { return code < IM_KEYS ? m->fn[code] : -1; }+// The buttons a controller sends for the buttons the default mapping read (DM_BTN_* bits); bits above the 16 buttons (DM_BTN_SHAKE) pass through+static uint64_t pad_map_apply(const pad_map *m, uint64_t btn) {+ uint64_t out = btn & ~0xffffull;+ for (int b = 0; b < IM_BUTTONS; b++) if (btn >> b & 1 && m->to[b] >= 0) out |= 1ull << m->to[b];+ return out;+}+static int pad_map_is_default(const pad_map *m) { for (int b = 0; b < IM_BUTTONS; b++) if (m->to[b] != b) return 0; return 1; }diff --git a/dm/host/tests/Makefile b/dm/host/tests/Makefileindex b82c76d8..82414b20 100644--- a/dm/host/tests/Makefile+++ b/dm/host/tests/Makefile@@ -7,7 +7,7 @@ PYTHON ?= python3GINC = $(if $(strip $(GAME)),-I../gen/$(GAME) -I../../games/$(GAME),$(error GAME is not set: make GAME=<base game title ID>: $(shell python3 ../../games/game.py list | awk -F'\t' '{printf "%s (%s) ", $$1, $$3}')))$(B)/t_fs $(B)/t_fs_case $(B)/t_fs_commit_list $(B)/t_fs_commit_list_tsan: ../romfs_image.hGAME_H = ../gen/$(GAME)/game_profile.h-run: $(B)/t_heap_size $(B)/t_touch $(B)/t_gesture $(B)/t_oe $(B)/t_fs $(B)/t_fs_commit_list $(B)/t_thread_leak $(B)/t_fs_case $(B)/t_audio $(B)/t_audio_spsc $(B)/t_swkbd $(B)/t_altstack $(B)/t_condvar $(B)/t_condvar_old $(B)/t_pctl $(B)/t_time $(B)/t_shared_font $(B)/t_vorbis $(B)/t_vorbis_divides $(B)/t_hid $(B)/t_haptics $(B)/t_haptics_apple $(B)/t_touchpad_geometry+run: $(B)/t_heap_size $(B)/t_touch $(B)/t_gesture $(B)/t_oe $(B)/t_fs $(B)/t_fs_commit_list $(B)/t_thread_leak $(B)/t_fs_case $(B)/t_audio $(B)/t_audio_spsc $(B)/t_swkbd $(B)/t_altstack $(B)/t_condvar $(B)/t_condvar_old $(B)/t_pctl $(B)/t_time $(B)/t_shared_font $(B)/t_vorbis $(B)/t_vorbis_divides $(B)/t_hid $(B)/t_input_map $(B)/t_haptics $(B)/t_haptics_apple $(B)/t_touchpad_geometry$(B)/t_heap_size$(B)/t_touch$(B)/t_gesture@@ -35,6 +35,7 @@ run: $(B)/t_heap_size $(B)/t_touch $(B)/t_gesture $(B)/t_oe $(B)/t_fs $(B)/t_fs_$(B)/t_vorbis_divides$(B)/t_movie_vpx$(B)/t_hid+ $(B)/t_input_map$(B)/t_haptics$(B)/t_haptics_apple$(B)/t_touchpad_geometry@@ -117,6 +118,8 @@ $(B)/t_pctl: t_pctl.c ../hle_misc.c ../hle.h ../dm.h $(GAME_H) | $(B)clang -O1 -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_pctl.c$(B)/t_shared_font: t_shared_font.c ../hle_sdk16.c ../hle.h ../dm.h $(GAME_H) | $(B)clang -O1 -Wall -Werror -Wno-unused-function -Wno-frame-address -I.. $(GINC) -o $@ t_shared_font.c ../hle_profile.c+$(B)/t_input_map: t_input_map.c ../input_map.h ../dm_input.h | $(B)+ clang -O1 -Wall -Werror -Wno-unused-function -I.. -o $@ t_input_map.c$(B)/t_hid: t_hid.c ../hle_hid.c ../hle_haptics.c ../hle_haptics.h ../pad_slots.h ../dm_input.h ../hle.h ../dm.h $(GAME_H) | $(B)clang -O1 -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_hid.c ../hle_haptics.c$(B)/t_hid_tsan: t_hid.c ../hle_hid.c ../hle_haptics.c ../hle_haptics.h ../pad_slots.h ../dm_input.h ../hle.h ../dm.h $(GAME_H) | $(B)diff --git a/dm/host/tests/t_input_map.c b/dm/host/tests/t_input_map.cnew file mode 100644index 00000000..96736ad6--- /dev/null+++ b/dm/host/tests/t_input_map.c@@ -0,0 +1,43 @@+// The Mac front end's button assignments (input_map.h): the default key map, DM_KEYMAP moving and swapping functions, DM_PAD_MAP's swaps, and malformed entries left out+#include "../input_map.h"++static int checks, fails;+#define CHECK(c, msg) do { checks++; if (!(c)) { fails++; fprintf(stderr, "FAIL: %s (line %d)\n", msg, __LINE__); } } while (0)++int main(void) {+ key_map k; key_map_default(&k);+ CHECK(key_map_fn(&k, 38) == 0 && key_map_fn(&k, 40) == 1 && key_map_fn(&k, 32) == 2 && key_map_fn(&k, 34) == 3, "default: J K U I are A B X Y");+ CHECK(key_map_fn(&k, 13) == IM_LUP && key_map_fn(&k, 0) == IM_LLEFT && key_map_fn(&k, 1) == IM_LDOWN && key_map_fn(&k, 2) == IM_LRIGHT, "default: W A S D are the left stick");+ CHECK(key_map_fn(&k, 49) == IM_SHAKE && key_map_fn(&k, 36) == 10 && key_map_fn(&k, 125) == 15, "default: Space shakes, Return is +, down arrow is Down");+ int right = 0; for (int c = 0; c < IM_KEYS; c++) if (k.fn[c] >= IM_RUP && k.fn[c] <= IM_RRIGHT) right++;+ CHECK(right == 0, "default: the right stick is on no key");+ CHECK(key_map_fn(&k, 200) == -1 && key_map_fn(&k, 50) == -1, "a key code past the table or without a function holds none");++ CHECK(key_map_parse(&k, "A=40,B=38") == 0, "a swap parses");+ CHECK(key_map_fn(&k, 40) == 0 && key_map_fn(&k, 38) == 1, "A=40,B=38 swaps A and B");+ key_map_default(&k);+ CHECK(key_map_parse(&k, "a=49") == 0 && key_map_fn(&k, 49) == 0 && key_map_fn(&k, 38) == -1, "names are case-insensitive; A leaves J, and Space leaves Shake");+ int shake = 0; for (int c = 0; c < IM_KEYS; c++) if (k.fn[c] == IM_SHAKE) shake++;+ CHECK(shake == 0, "the function a key held before is on no key");+ CHECK(key_map_parse(&k, "RUp=126,RLeft=123,Up=none") == 0, "right stick on the arrows, Up on none");+ CHECK(key_map_fn(&k, 126) == IM_RUP && key_map_fn(&k, 123) == IM_RLEFT, "the arrows hold the right stick");+ int up = 0; for (int c = 0; c < IM_KEYS; c++) if (k.fn[c] == 13) up++;+ CHECK(up == 0, "Up=none leaves Up on no key");+ key_map_default(&k);+ CHECK(key_map_parse(&k, "Q=1,ZL=abc,A=128,B=,=5,X=7") == 5, "five malformed entries are counted");+ CHECK(key_map_fn(&k, 7) == 2 && key_map_fn(&k, 6) == 8 && key_map_fn(&k, 38) == 0, "the good entry applies, the malformed ones change nothing");+ CHECK(key_map_parse(&k, "") == 0 && key_map_parse(&k, NULL) == 0 && key_map_parse(&k, "L=12,") == 0, "empty lists and a trailing comma are fine");++ pad_map m; pad_map_default(&m);+ CHECK(pad_map_is_default(&m) && pad_map_apply(&m, DM_BTN_A | DM_BTN_ZR | DM_BTN_SHAKE) == (DM_BTN_A | DM_BTN_ZR | DM_BTN_SHAKE), "default: every button sends itself, Shake passes");+ CHECK(pad_map_parse(&m, "A=B,B=A") == 0 && !pad_map_is_default(&m), "a swap parses");+ CHECK(pad_map_apply(&m, DM_BTN_A) == DM_BTN_B && pad_map_apply(&m, DM_BTN_B) == DM_BTN_A && pad_map_apply(&m, DM_BTN_A | DM_BTN_B) == (DM_BTN_A | DM_BTN_B), "A=B,B=A swaps them");+ CHECK(pad_map_apply(&m, DM_BTN_X | DM_BTN_DOWN) == (DM_BTN_X | DM_BTN_DOWN), "buttons not named stay");+ CHECK(pad_map_parse(&m, "ZL=L,minus=none") == 0, "two buttons on one, and none");+ CHECK(pad_map_apply(&m, DM_BTN_ZL) == DM_BTN_L && pad_map_apply(&m, DM_BTN_L | DM_BTN_ZL) == DM_BTN_L && pad_map_apply(&m, DM_BTN_MINUS) == 0, "ZL sends L, Minus sends nothing");+ pad_map_default(&m);+ CHECK(pad_map_parse(&m, "A=LUp,LUp=A,Shake=B,Y=X") == 3 && m.to[3] == 2 && m.to[0] == 0, "sticks and Shake are no buttons here: left out; Y=X applies");++ printf("input map: %d checks, %d failed\n", checks, fails);+ return fails != 0;+}diff --git a/dm/tools/impact_map.tsv b/dm/tools/impact_map.tsvindex df05fa53..22e68677 100644--- a/dm/tools/impact_map.tsv+++ b/dm/tools/impact_map.tsv@@ -103,5 +103,6 @@ dm/host/main.c *:* the host's startdm/host/loader.c *:* module loadingdm/host/hle.c hle:* the HLE tablesdm/host/front_mac.m present:* the Mac front end+dm/host/input_map.h present:* the Mac front end's key and controller button mapdm/host/front.h present:* the front enddm/ios/* *:* the iOS appdiff --git a/dm/tools/patch_nso.py b/dm/tools/patch_nso.pyindex 7e02476d..e2072200 100644--- a/dm/tools/patch_nso.py+++ b/dm/tools/patch_nso.py@@ -463,14 +463,21 @@ for _ in range(nfde):a, s = rd(o, tenc); o += s_, s = rd(o, tenc); o += sstarts.add(a)-starts = sorted(x for x in starts if x < TEXT_END)+starts = sorted(x for x in starts if x < TEXT_LO + TEXT_END)# ---- Linear scan to find all rewrite points (not relying on register read/write reports) ----# Data blocks in the text (nso_code.py: Absolum's main starts with 1.7 MB of them) are not code: words there that read as rewrite sites are left alonesys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))import nso_code-DATA_BLOCKS = nso_code.data_blocks(IMG, TEXT_END, md)-CODE_RANGES = list(zip([0] + [e for _, e in DATA_BLOCKS], [s for s, _ in DATA_BLOCKS] + [TEXT_END]))+DATA_BLOCKS = nso_code.data_blocks(IMG, TEXT_LO + TEXT_END, md, lo=TEXT_LO)+# The text segment starts at its memory offset: 0 for an NSO (the image is rebuilt from 0) and+# 0x80 for an NRO (the file is the image preceded by its header, so text sits at 0x80). Scanning+# an NRO from 0 read the header's build ID as instructions and reported+# "44 ldr x18, #0xfffffffffff40370" on Final Fantasy X/X-2 HD Remaster (GitHub issue #14).+# TEXT_LO is where the code really begins in IMG; data_blocks() gets the same lower bound so its+# returned offsets are already IMG-absolute and CODE_RANGES needs no further shift.+TEXT_LO = segs[0][1]+CODE_RANGES = list(zip([TEXT_LO] + [e for _, e in DATA_BLOCKS], [s for s, _ in DATA_BLOCKS] + [TEXT_LO + TEXT_END]))md_lite = Cs(CS_ARCH_ARM64, CS_MODE_ARM) # no details: the x18 scan reads only the operand textR18 = re.compile(r'\b[xw]18\b')def x18_words(lo, hi):@@ -969,7 +976,7 @@ def scratch_dead(off):mov x0, x19 before one) or a ret (none of them carries a result under AAPCS64; Pikmin 4's gate sits on the ldp x29, x30 of an epilogue). Only straight-line code is followed: a branchor a blr before the bl or ret answers no"""written = set()- for a in range(off, min(off + 4 * 16, TEXT_END), 4):+ for a in range(off, min(off + 4 * 16, TEXT_LO + TEXT_END), 4):ins = dis(struct.unpack_from('<I', IMG, a)[0], a)if ins.mnemonic in ('bl', 'ret'): return Trueif ins.mnemonic in ('b', 'br', 'blr', 'cbz', 'cbnz', 'tbz', 'tbnz') or ins.mnemonic.startswith('b.'): return False@@ -986,7 +993,7 @@ for off, oid, ow, why in obs:# and right after a call returns the callee was free to clobber them anyway (x16 / x17 are the veneer registers). Elsewhere, where the code ahead reads none of them before its next blafter_bl = off >= 4 and struct.unpack_from('<I', IMG, off - 4)[0] >> 26 == 0x25assert off in set(starts) or after_bl or scratch_dead(off), f'observation gate neither at a function entry, after a bl nor before a call with x9–x17 unread {off:#x}'- assert off < TEXT_END and off not in kinds and not any(lo <= off < hi for wseg in windows for lo, hi in [(wseg[0].address, wseg[-1].address + 4)]), f'observation gate conflicts with a rewrite site {off:#x}'+ assert off < TEXT_LO + TEXT_END and off not in kinds and not any(lo <= off < hi for wseg in windows for lo, hi in [(wseg[0].address, wseg[-1].address + 4)]), f'observation gate conflicts with a rewrite site {off:#x}'put_branch(off, site_obs(off, oid, w)); stat('obs')# ---- Frame step in whole vsyncs (the mains whose patch file has FRAME_STEP: The Legend of Zelda: Tears of the Kingdom 1.4.3, Breath of the Wild 1.9.0, Hyrule Warriors: Age of Calamity 1.3.0,diff --git a/docs/development.md b/docs/development.mdindex 88703bb1..06b31d10 100644--- a/docs/development.md+++ b/docs/development.md@@ -10,7 +10,7 @@ The README covers packing and playing. This page is for working on nxnative itse| Host (`dm/host`) | Stands in for the Horizon kernel and the system services the games call: threads and synchronization, memory, file system with transactional saves, HID, audio, movies (VP9 through libvpx, Vorbis sound through stb_vorbis), software keyboard, focus and lifecycle || Graphics (`dm/gfx`) | NVN on Metal. Shaders are extracted by `shader_split.py` from Nintendo's containers and from Unity's `Shader` objects, then translated offline. Mario: 16,266 of 16,268 shaders compile. Engage: 9,268 of 9,269. Games that render with Vulkan (Hades) or OpenGL (Digimon Story Cyber Sleuth) go through layers of their own on Metal (`dm/gfx/vk`, `dm/gfx/gl`) || Audio | Games that carry the SDK's audio renderer (Mario) run it in-process; games that use AudioOut directly (Engage: Wwise) feed it straight. Output goes through Core Audio (default on iOS, `DM_AUDIO=1` on the Mac) |-| Input | iOS: the touch gamepad and physical controllers, all as player 1; shaking the phone shakes the controller (its six-axis sensor, `hle_hid.c`; the accelerometer in `DmGamepad.m`, threshold `DM_SHAKE_G`, 1.5 G by default). Mac: scripted input (`DM_KEYS=<seconds>:<button>,…`, `Shake` for a shake, with `DM_KBD=<text>` answering the system keyboard) or `DM_WINDOW=1` for a window with keyboard input (Space shakes) and physical controllers (buttons by position, as on the iPhone). On the Mac each controller is a player of its own, for local co-op: the first one connected is player 1, together with the keyboard, the next player 2, and so on up to 8 (`pad_slots.h`); a controller that is removed frees its player and gets it back when it reconnects, and the log names each one's player and npad (`controller 'Xbox Wireless Controller' connected: player 2 (npad 1)`). Player 1 is the Handheld npad in handheld mode and No1 docked, player n is No n; the game's supported npad ids decide how many play (`hle_hid.c`): a one-player game gets every controller as player 1, and a controller past a game's last player is not used. `DM_PAD_MERGE=1` makes every controller player 1, as before; `DM_KBD_PLAYER=own` makes the keyboard player 1 on its own, with the controllers from player 2 on. The window goes fullscreen from its green button or ⌃⌘F; `DM_FULLSCREEN=1` starts it that way. In fullscreen, a screen whose refresh rate is not a multiple of the game's (144 or 165 Hz) runs at one that is (120 Hz) until the window leaves fullscreen; `DM_SCREEN_MATCH=0` keeps its rate. The drawable follows the window in pixels (fullscreen at the screen's resolution); `DM_METAL_HUD=1` shows Apple's performance HUD (on the iPhone too, from `Documents/env.txt`). The left mouse button is the touchscreen, on the 16:9 picture. In handheld mode the touches also drive `hid::GetGestureStates` (taps, presses, pans, swipes, pinches and rotations recognized by the host, `hle_touch.c`) |+| Input | iOS: the touch gamepad and physical controllers, all as player 1; shaking the phone shakes the controller (its six-axis sensor, `hle_hid.c`; the accelerometer in `DmGamepad.m`, threshold `DM_SHAKE_G`, 1.5 G by default). Mac: scripted input (`DM_KEYS=<seconds>:<button>,…`, `Shake` for a shake, with `DM_KBD=<text>` answering the system keyboard) or `DM_WINDOW=1` for a window with keyboard input (Space shakes) and physical controllers (buttons by position, as on the iPhone). On the Mac each controller is a player of its own, for local co-op: the first one connected is player 1, together with the keyboard, the next player 2, and so on up to 8 (`pad_slots.h`); a controller that is removed frees its player and gets it back when it reconnects, and the log names each one's player and npad (`controller 'Xbox Wireless Controller' connected: player 2 (npad 1)`). Player 1 is the Handheld npad in handheld mode and No1 docked, player n is No n; the game's supported npad ids decide how many play (`hle_hid.c`): a one-player game gets every controller as player 1, and a controller past a game's last player is not used. `DM_PAD_MERGE=1` makes every controller player 1, as before; `DM_KBD_PLAYER=own` makes the keyboard player 1 on its own, with the controllers from player 2 on. `DM_KEYMAP=<name>=<key code>,…` puts a button, a stick direction (the right stick too, on no key by default) or `Shake` on another key, and `DM_PAD_MAP=<name>=<name>,…` changes what a controller's buttons send (`A=B,B=A` swaps them; `input_map.h`). The window goes fullscreen from its green button or ⌃⌘F; `DM_FULLSCREEN=1` starts it that way. In fullscreen, a screen whose refresh rate is not a multiple of the game's (144 or 165 Hz) runs at one that is (120 Hz) until the window leaves fullscreen; `DM_SCREEN_MATCH=0` keeps its rate. The drawable follows the window in pixels (fullscreen at the screen's resolution); `DM_METAL_HUD=1` shows Apple's performance HUD (on the iPhone too, from `Documents/env.txt`). The left mouse button is the touchscreen, on the 16:9 picture. In handheld mode the touches also drive `hid::GetGestureStates` (taps, presses, pans, swipes, pinches and rotations recognized by the host, `hle_touch.c`) || iOS app | One unsigned IPA for iPhone and iPad. The rewritten code is embedded in the executable; the shader libraries, the RomFS and the game icon are inside the app. A settings screen comes before the game (`Launcher.swift`, drawn from `dm/launcher.json`, which `dm/games/settings.py` writes from `dm/games/settings.tsv`); the host's loading starts at app launch meanwhile, and the frame rate and render scale go into the frame step state when the game starts (`loader.c` `dm_fps_state_apply`) || Known gaps | Conditional render is always drawn; `MultiDraw*IndirectCount` waits on the CPU for the GPU-written count; geometry shaders do not translate. TBDR optimizations are off by default (they don't understand bindless textures yet). No amiibo. The bundled prewarm lists are empty. On the Mac, Mario's menu and dialogue text render blank (fine on the iPhone) |diff --git a/docs/env_switches.tsv b/docs/env_switches.tsvindex 814429dc..775f9248 100644--- a/docs/env_switches.tsv+++ b/docs/env_switches.tsv@@ -33,6 +33,7 @@ DM_FS diagnostic When set, logs file opens, paths not found or not mounted, andDM_FSLOG diagnostic `=<file>` writes one TSV line per ReadFile: seconds since boot, guest path, offset, length and guest buffer addressDM_FSLOG_HASH diagnostic With `DM_FSLOG`, adds a column with the FNV-1a 64 hash of the bytes readDM_FULLSCREEN switch When set, the Mac window starts in fullscreen+DM_FULL_ROMFS diagnostic `=1` in `build_ipa.sh` packs the game data into the IPA as it did before the slim package; the default leaves it in `Documents/games/<id>/` (`romfs.img`, `aoc/<index>.img`) and the DLC beside it. Only for small games — a full package of a large one is many GB and iOS refuses it (`PackageExtractionFailed`)DM_GAME switch Selects the game profile (a title ID under `dm/games` or `DM_GAMES_DIR`) for the Python tools and the rewriter; there is no defaultDM_GAMES_DIR path Profile folders outside the repository, separated by `:`, searched after `dm/games`; the NSP script points it at a provisional or derived profileDM_GAMES_FIRST switch `=1` searches `DM_GAMES_DIR` before `dm/games`, so a provisional or derived profile wins over the game's own (the NSP script's `--provisional`)@@ -52,6 +53,7 @@ DM_ICON path `=<image>` gives `build_ipa.sh` another app icon (default the `iconDM_IMPORTS diagnostic When set, logs each import the loader binds to a host function and each forced takeoverDM_KBD switch `=<text>`: the system keyboard returns that text as OK without showing an input box; unset with no window, it returns cancelDM_KBD_PLAYER switch `own` makes the Mac keyboard player 1 on its own, with controllers from player 2 on (by default the first controller shares player 1 with the keyboard)+DM_KEYMAP player Mac keyboard: `<name>=<key code>,…` puts a button (`A` … `Down`), a stick direction (`LUp` … `RRight`) or `Shake` on another key (macOS virtual key code, or `none`); one key holds one function (`input_map.h`)DM_KEYS switch Scripted input: `<seconds or f<frame>>:<key>[+key][~hold][*count/interval],…` presses buttons, sticks and `Shake` at those timesDM_LANG player Game language as a language code (default `en-US`; the iOS app sets the one the IPA was packed with)DM_LAUNCHER switch `0` skips the iOS settings screen and starts the game at once@@ -158,6 +160,7 @@ DM_OODLE_JOB path `=<job file>`: the host runs the game's own Oodle decoder on eDM_OODLE_MODULES path The rewritten modules the Mac host's Oodle tool mode loads when `shader_split.py` decodes Trinity packs; set by the NSP scriptDM_OODLE_SERVE switch `=1`: the host answers decode requests on stdin / stdout with the game's own Oodle (or LZ5) decoder from the guest main thread before the SDK starts, until stdin endsDM_OPMODE player The operation mode the game sees: `0` handheld, `1` console (default: the profile's `op_mode`, console unless set); read once at startup+DM_PAD_MAP player Mac controllers: `<name>=<name>,…` makes the button that sends the first by default send the second (or `none`), e.g. `A=B,B=A` swaps them (`input_map.h`)DM_PAD_MERGE switch `=1` on the Mac merges every controller into player 1, as before, instead of giving each controller a player of its ownDM_PATCH_FRONT switch `=<bytes>`: the size of the patch area right before the module base for a long text (`BIG_TEXT`); set only by the rewriter's own rerun with the size it needsDM_PREEMPT switch `0` / `1` overrides the profile's `core_preempt`: also check already-runnable higher-priority peers on the caller's core after every thread SVC@@ -182,6 +185,7 @@ DM_PROBE_LIMIT diagnostic Maximum printed hits per guest probe; 0 or absent leavDM_PROBE_POLL diagnostic `=<address>[+<length>]` (hex, 4 bytes by default, up to 8): a host thread spins on the bytes and on each change snapshots every thread's pc, lr and frames, for writes the watch missesDM_PROBE_WATCH diagnostic `=<address>[+<length>]` (hex, 8 bytes by default): write-protects that host page and reports who writes these bytes, without a debuggerDM_PROBE_X2 diagnostic `=<bytes>` (hex): probe hits also dump that many bytes of the memory x2 points to+DM_PROFILE path `=<file>`: the runtime game profile (layout, switches, tables) the host reads at start, which is how one host binary serves every game (the launcher architecture); the compiled `game_profile.h` stays the fallback, and `DM_PROF_<key>` overrides sit on top of it (`hle_profile.h`)DM_PROGRAM_ID switch `=<hex>`: the program ID the host reports from `svcGetInfo(ProgramId)` (default: the profile's `program_id`)DM_PSO_ARCHIVE path The folder of the per-game Metal 4 pipeline archive of pipeline bases (default `pso_archive/` beside `pso_user.tsv`); `off` keeps no archiveDM_PSO_BUNDLE path The pipeline archive made offline (`<GPU architecture>.mtl4a`, `prebuilt.tsv`), read only; the iOS app and Mac launcher set it to their `pso/` folder; `off` ignores itdiff --git a/scripts/sync_upstream.py b/scripts/sync_upstream.pyindex 01530952..21620b29 100644--- a/scripts/sync_upstream.py+++ b/scripts/sync_upstream.py@@ -46,6 +46,11 @@ OURS = {'dm/host/romfs_arc.c', 'dm/host/romfs_arc.h', 'dm/tools/romfs_arc.py',# (a verify-only patcher was not enough: the sync replaced it first and then complained).'dm/games/game.py','dm/gfx/tex/tests/t_bcdec.c',+ # The Mac front end's key and controller button map (seedds/nxnative#386, still open):+ # the launcher's Controls page writes DM_KEYMAP / DM_PAD_MAP, and patch_front_mac() makes+ # front_mac.m read them. Fork-only until #386 merges, so a sync must not delete them.+ 'dm/host/input_map.h',+ 'dm/host/tests/t_input_map.c',# The Increased Memory Limit guide the README links to; upstream has no such file, and the# first wholesale sync deleted it.'dm/ios/ENTITLEMENTS.md',@@ -329,19 +334,27 @@ def patch_makefile(t):TESTS_MK = 'dm/host/tests/Makefile'def patch_tests_makefile(t):"""The three fs tests #include ../hle_fs.c, which now calls the archive reader: without- romfs_arc.c on their command lines they stop with undefined _romfsarc_* symbols (PR #12)."""- if 'romfs_arc.c' in t: return skip('tests/Makefile (already patched)')- P = [- ('t_fs', 'clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_fs.c t_fs_stub.c ../hle_bigstack.c\n',- 'clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_fs.c t_fs_stub.c ../hle_bigstack.c ../romfs_arc.c\n'),- ('t_fs_commit_list', 'clang -O1 -Wall -Wno-unused-function -I.. $(GINC) -o $@ t_fs_commit_list.c t_fs_stub.c ../hle_bigstack.c\n',- 'clang -O1 -Wall -Wno-unused-function -I.. $(GINC) -o $@ t_fs_commit_list.c t_fs_stub.c ../hle_bigstack.c ../romfs_arc.c\n'),- ('t_fs_case', 'clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_fs_case.c ../hle_bigstack.c\n',- 'clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_fs_case.c ../hle_bigstack.c ../romfs_arc.c\n'),- ]- for name, old, new in P:- if old not in t: fail(f'{TESTS_MK}: {name} link line missing (upstream changed the test rules)')- t = t.replace(old, new, 1)+ romfs_arc.c on their command lines they stop with undefined _romfsarc_* symbols (PR #12).++ Three independent additions follow (the fs link lines, the touch-pad test, the key map+ test), each with its own "already there" test. This used to start with+ `if 'romfs_arc.c' in t: return skip(...)`, which made every later addition dead code: the+ touch-pad block never ran once the fs lines were in, and the marker check could not notice+ its absence. Only the first block skips now.+ """+ if 'romfs_arc.c' not in t:+ P = [+ ('t_fs', 'clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_fs.c t_fs_stub.c ../hle_bigstack.c\n',+ 'clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_fs.c t_fs_stub.c ../hle_bigstack.c ../romfs_arc.c\n'),+ ('t_fs_commit_list', 'clang -O1 -Wall -Wno-unused-function -I.. $(GINC) -o $@ t_fs_commit_list.c t_fs_stub.c ../hle_bigstack.c\n',+ 'clang -O1 -Wall -Wno-unused-function -I.. $(GINC) -o $@ t_fs_commit_list.c t_fs_stub.c ../hle_bigstack.c ../romfs_arc.c\n'),+ ('t_fs_case', 'clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_fs_case.c ../hle_bigstack.c\n',+ 'clang -O1 -Wno-unused-function -I.. $(GINC) -o $@ t_fs_case.c ../hle_bigstack.c ../romfs_arc.c\n'),+ ]+ for name, old, new in P:+ if old not in t: fail(f'{TESTS_MK}: {name} link line missing (upstream changed the test rules)')+ t = t.replace(old, new, 1)+ done('tests/Makefile romfs_arc.c')# the touch-pad geometry test (dm/host/touchpad_geometry.h): header-only, so it needs its own# rule and a place in the run listif 't_touchpad_geometry' not in t:@@ -357,6 +370,20 @@ def patch_tests_makefile(t):'$(B)/t_touchpad_geometry: t_touchpad_geometry.c ../touchpad_geometry.h ../dm_input.h | $(B)\n''\tclang -O1 -Wall -I.. $(GINC) -o $@ t_touchpad_geometry.c\n' + rule_anchor, 1)done('tests/Makefile touchpad test')+ # the key and controller map test (dm/host/input_map.h, seedds/nxnative#386): header-only too+ if 't_input_map' not in t:+ run_old = '$(B)/t_hid $(B)/t_haptics $(B)/t_haptics_apple'+ if run_old not in t: fail(f'{TESTS_MK}: run list anchor for t_hid missing')+ t = t.replace(run_old, '$(B)/t_hid $(B)/t_input_map $(B)/t_haptics $(B)/t_haptics_apple', 1)+ body_old = '\t$(B)/t_hid\n'+ if body_old not in t: fail(f'{TESTS_MK}: run body anchor for t_hid missing')+ t = t.replace(body_old, body_old + '\t$(B)/t_input_map\n', 1)+ rule_anchor = '$(B)/t_hid: t_hid.c'+ if rule_anchor not in t: fail(f'{TESTS_MK}: t_hid rule missing')+ t = t.replace(rule_anchor,+ '$(B)/t_input_map: t_input_map.c ../input_map.h ../dm_input.h | $(B)\n'+ '\tclang -O1 -Wall -Werror -Wno-unused-function -I.. -o $@ t_input_map.c\n' + rule_anchor, 1)+ done('tests/Makefile input map test')# the prerequisites too, so a change to the reader rebuilds them — and hle_profile.h, so a# change to the runtime profile doesfor name in ('t_fs', 't_fs_commit_list', 't_fs_case'):@@ -886,6 +913,140 @@ def patch_main_m(t):done(f'main.m {name}')return t+def patch_patch_nso(t):+ """The NRO header skip in dm/tools/patch_nso.py (issue #14).++ An NRO file is the image itself preceded by a 0x80-byte header, so its text segment starts at+ 0x80; an NSO's starts at 0 after decompression. The scan and CODE_RANGES assumed 0, so on an+ NRO the header's build ID was decoded as instructions and reported as a site+ ("44 ldr x18, #0xfffffffffff40370" on Final Fantasy X/X-2 HD Remaster), and the last 0x80+ bytes of text were never scanned.++ This was fixed once (4b863234) and then silently reverted: patch_nso.py was not a carrier, so+ the next sync that rewrote it took upstream's version, and the fork's test kept failing from+ then on. It is a carrier now.+ """+ if 'TEXT_LO = segs[0][1]' in t: return skip('patch_nso.py NRO header (already patched)')+ P = [+ ('data blocks and code ranges',+ 'DATA_BLOCKS = nso_code.data_blocks(IMG, TEXT_END, md)\n'+ 'CODE_RANGES = list(zip([0] + [e for _, e in DATA_BLOCKS], [s for s, _ in DATA_BLOCKS] + [TEXT_END]))\n',+ 'DATA_BLOCKS = nso_code.data_blocks(IMG, TEXT_LO + TEXT_END, md, lo=TEXT_LO)\n'+ '# The text segment starts at its memory offset: 0 for an NSO (the image is rebuilt from 0) and\n'+ '# 0x80 for an NRO (the file is the image preceded by its header, so text sits at 0x80). Scanning\n'+ '# an NRO from 0 read the header\'s build ID as instructions and reported\n'+ '# "44 ldr x18, #0xfffffffffff40370" on Final Fantasy X/X-2 HD Remaster (GitHub issue #14).\n'+ '# TEXT_LO is where the code really begins in IMG; data_blocks() gets the same lower bound so its\n'+ '# returned offsets are already IMG-absolute and CODE_RANGES needs no further shift.\n'+ 'TEXT_LO = segs[0][1]\n'+ 'CODE_RANGES = list(zip([TEXT_LO] + [e for _, e in DATA_BLOCKS], [s for s, _ in DATA_BLOCKS] + [TEXT_LO + TEXT_END]))\n'),+ ('site starts bound', 'starts = sorted(x for x in starts if x < TEXT_END)',+ 'starts = sorted(x for x in starts if x < TEXT_LO + TEXT_END)'),+ ('observation gate window', ' for a in range(off, min(off + 4 * 16, TEXT_END), 4):',+ ' for a in range(off, min(off + 4 * 16, TEXT_LO + TEXT_END), 4):'),+ ('observation gate assert', ' assert off < TEXT_END and off not in kinds',+ ' assert off < TEXT_LO + TEXT_END and off not in kinds'),+ ]+ for name, old, new in P:+ if new in t:+ skip(f'patch_nso.py {name} (already patched)')+ continue+ if old not in t:+ fail(f'dm/tools/patch_nso.py: patch "{name}" anchor missing (upstream reworked the text '+ 'scan; merge the NRO header skip by hand)')+ t = t.replace(old, new, 1)+ done(f'patch_nso.py {name}')+ return t++def patch_front_mac(t):+ """DM_KEYMAP and DM_PAD_MAP in the Mac front end, from upstream seedds/nxnative#386.++ The launcher's Controls page (Settings → Controls) writes these two variables, but until this+ landed here nothing on this side read them: the page moved the fields and the game kept its+ default keys. Upstream's #386 is still open, so the change has to live here as a carrier: the+ tables below are its hunks, and the day #386 merges, a sync brings them in whole and this+ patcher finds every anchor already applied (or, if upstream rewords one, fails loudly).++ input_map.h is fork-only for now (upstream's file, but shipped here by this commit) and is in+ OURS so a sync cannot take it away.+ """+ if 'key_map_default(&g_keys)' in t: return skip('front_mac.m DM_KEYMAP (already patched)')+ P = [+ ('key map comment',+ '// Key map (Nintendo layout): WASD left stick, arrow keys D-pad, J=A K=B U=X I=Y, Q=L E=R, Z=ZL C=ZR, F=press left stick G=press right stick, Return=+ Tab=−, Space=shake the controller.\n',+ '// Key map (Nintendo layout): WASD left stick, arrow keys D-pad, J=A K=B U=X I=Y, Q=L E=R, Z=ZL C=ZR, F=press left stick G=press right stick, Return=+ Tab=−, Space=shake the controller;\n'+ "// DM_KEYMAP moves a function to another key (the right stick too), DM_PAD_MAP changes what a controller's buttons send (input_map.h).\n"),+ ('input_map include',+ '#include "pad_slots.h"\n',+ '#include "pad_slots.h"\n#include "input_map.h"\n'),+ ('the four stick flags',+ 'static int g_w, g_a, g_s, g_d;\n',+ ''),+ ('key state',+ 'static void push(void) {\n int32_t lx = (g_d - g_a) * 32767, ly = (g_w - g_s) * 32767;\n dm_input_set(g_btn, lx, ly, 0, 0);\n}\n'+ 'static int key_bit(unsigned short code) {\n'+ ' switch (code) {\n'+ ' case 38: return 0; case 40: return 1; case 32: return 2; case 34: return 3; // J K U I → A B X Y\n'+ ' case 3: return 4; case 5: return 5; // F G → press stick\n'+ ' case 12: return 6; case 14: return 7; case 6: return 8; case 8: return 9; // Q E Z C → L R ZL ZR\n'+ ' case 36: return 10; case 48: return 11; // Return Tab → + −\n'+ ' case 123: return 12; case 126: return 13; case 124: return 14; case 125: return 15; // ← ↑ → ↓\n'+ ' }\n'+ ' return -1;\n'+ '}\n',+ '// Keyboard: each key holds one function of the key map (input_map.h; DM_KEYMAP changes it), the held functions make the buttons and both sticks\n'+ 'static key_map g_keys;\n'+ 'static uint32_t g_held_fn; // bit f: a key holding function f is down\n'+ 'static void push(void) {\n'+ ' uint32_t h = g_held_fn;\n'+ ' #define D(f) ((int32_t)(h >> (f) & 1))\n'+ ' dm_input_set(g_btn, (D(IM_LRIGHT) - D(IM_LLEFT)) * 32767, (D(IM_LUP) - D(IM_LDOWN)) * 32767, (D(IM_RRIGHT) - D(IM_RLEFT)) * 32767, (D(IM_RUP) - D(IM_RDOWN)) * 32767);\n'+ ' #undef D\n'+ '}\n'),+ ('on_key',+ ' unsigned short c = e.keyCode;\n'+ ' switch (c) { case 13: g_w = down; break; case 0: g_a = down; break; case 1: g_s = down; break; case 2: g_d = down; break; }\n'+ ' int b = key_bit(c);\n'+ ' uint64_t m = b >= 0 ? 1ull << b : c == 49 ? DM_BTN_SHAKE : 0; // Space: shaken while held\n'+ ' g_btn = down ? (g_btn | m) : (g_btn & ~m);\n',+ ' int f = key_map_fn(&g_keys, e.keyCode); if (f < 0) return;\n'+ ' g_held_fn = down ? (g_held_fn | 1u << f) : (g_held_fn & ~(1u << f));\n'+ ' g_btn = (g_held_fn & 0xffff) | (g_held_fn >> IM_SHAKE & 1 ? DM_BTN_SHAKE : 0);\n'),+ ('pad map state',+ 'static int g_merge, g_kbd_own;\n',+ 'static int g_merge, g_kbd_own;\nstatic pad_map g_padmap; // DM_PAD_MAP (input_map.h): what each button sends, applied to every controller\n'),+ ('pad map apply',+ ' #undef K\n dm_pad_set_player(p, m, pad_axis(g.leftThumbstick.xAxis.value), pad_axis(g.leftThumbstick.yAxis.value), pad_axis(g.rightThumbstick.xAxis.value), pad_axis(g.rightThumbstick.yAxis.value));\n',+ ' #undef K\n m = pad_map_apply(&g_padmap, m);\n dm_pad_set_player(p, m, pad_axis(g.leftThumbstick.xAxis.value), pad_axis(g.leftThumbstick.yAxis.value), pad_axis(g.rightThumbstick.xAxis.value), pad_axis(g.rightThumbstick.yAxis.value));\n'),+ ('start: read the two variables',+ ' const char *e = getenv("DM_PAD_MERGE"); g_merge = e && atoi(e);\n',+ ' key_map_default(&g_keys); pad_map_default(&g_padmap);\n'+ ' const char *km = getenv("DM_KEYMAP"), *pm = getenv("DM_PAD_MAP");\n'+ ' if (km && *km) { int bad = key_map_parse(&g_keys, km); LOG("front end: keyboard map from DM_KEYMAP (%s)%s", km, bad ? ", malformed entries left out" : ""); }\n'+ ' if (pm && *pm) { int bad = pad_map_parse(&g_padmap, pm); LOG("front end: controller buttons from DM_PAD_MAP (%s)%s", pm, bad ? ", malformed entries left out" : ""); }\n'+ ' const char *e = getenv("DM_PAD_MERGE"); g_merge = e && atoi(e);\n'),+ # two call sites, one per indentation: input_release (4 spaces) and front_text_input (8)+ ('release on focus loss',+ ' g_btn = 0; g_w = g_a = g_s = g_d = 0; push();\n if (g_mouse_down)',+ ' g_btn = 0; g_held_fn = 0; push();\n if (g_mouse_down)'),+ ('release for the text box',+ ' g_btn = 0; g_w = g_a = g_s = g_d = 0; push();\n dm_touch_set(NULL, 0);',+ ' g_btn = 0; g_held_fn = 0; push();\n dm_touch_set(NULL, 0);'),+ ]+ for name, old, new in P:+ # A deletion entry has an empty `new`, which is "in" every string, so it would report+ # "already patched" on the first run and never delete anything. It is applied when its+ # `old` is gone instead.+ if (old not in t) if not new else (new in t):+ skip(f'front_mac.m {name} (already patched)')+ continue+ if old not in t:+ fail(f'dm/host/front_mac.m: patch "{name}" anchor missing (upstream moved the key handling; '+ 'merge seedds/nxnative#386 by hand)')+ t = t.replace(old, new, 1)+ done(f'front_mac.m {name}')+ return t+def patch_dm_h(t):"""dm.h pulls in hle_profile.h, so every host source can call dm_profile().@@ -929,6 +1090,8 @@ MARKERS = {'dm/gfx/nvn/nvn_mtl.m': 'if (on_sub_thread()) rec_publish();','dm/games/0100A00019DE0000/game.tsv': 'build v1 1.0.137848','dm/host/dm.h': 'hle_profile.h',+ 'dm/host/front_mac.m': 'DM_KEYMAP',+ 'dm/tools/patch_nso.py': 'TEXT_LO',}PATCHERS = {'dm/host/hle_fs.c': patch_hle_fs,@@ -941,6 +1104,8 @@ PATCHERS = {'dm/gfx/nvn/nvn_mtl.m': patch_nvn_mtl,'dm/games/0100A00019DE0000/game.tsv': patch_hades2,'dm/host/dm.h': patch_dm_h,+ 'dm/host/front_mac.m': patch_front_mac,+ 'dm/tools/patch_nso.py': patch_patch_nso,}report, problems = [], []