From b94670c795e28742abe1a9cadd64a234a77260ab Mon Sep 17 00:00:00 2001 From: jhaizhou <258432107+jhaizhou-ops@users.noreply.github.com> Date: Thu, 15 Oct 2026 04:32:15 +0800 Subject: [PATCH] v1.0.15: shell is now build input (.zip), launch self-check for incomplete packages and devices without Metal 3, graphics translation on its own thread, save with the pause menu open, wide-iPhone item tooltip and Chronicle rewards fixes --- README.md | 7 +- README.zh-CN.md | 7 +- dm/gfx/nvn/hle_nvn.c | 250 ++++++++++++++++++++++++----- dm/gfx/nvn/nvn_mtl.m | 26 +-- dm/gfx/nvn/nvn_obj.h | 9 +- dm/gfx/tests/t_nvn.c | 48 +++++- dm/gfx/tests/t_present_crop.m | 2 +- dm/host/diag.c | 73 +++++++-- dm/host/dm_cursor.c | 121 +++++++++++--- dm/host/dm_i18n_tab.h | 6 + dm/host/front_mac.m | 20 +-- dm/host/hle_fs.c | 68 ++++++-- dm/host/tests/t_fs.c | 39 +++++ dm/host/touch_mac.c | 16 +- dm/i18n/literal_whitelist.tsv | 2 + dm/i18n/ui_text.tsv | 6 + dm/ios/Sources/dm_touch_controls.c | 3 + dm/ios/Sources/dm_touch_controls.h | 5 + dm/ios/Sources/front_ios.m | 88 ++-------- dm/ios/Sources/main.m | 92 +++++++++-- dm/ios/tools/shell_build.sh | 26 +-- dm/tools/d2rm_pack.py | 31 ++-- docs/NO_XCODE.md | 8 +- docs/NO_XCODE.zh-CN.md | 8 +- docs/OLDER_SYSTEMS.md | 4 +- docs/OLDER_SYSTEMS.zh-CN.md | 4 +- 26 files changed, 721 insertions(+), 248 deletions(-) diff --git a/README.md b/README.md index 888ea9b..8d5caaa 100644 --- a/README.md +++ b/README.md @@ -191,12 +191,15 @@ flowchart LR ## Which devices are supported +Minimum: **an A14 / M1 chip or later** — the graphics layer needs Metal 3, which Apple supports from A14 / M1 on (see Apple's [Metal support on Apple devices](https://support.apple.com/102894) and [Metal Feature Set Tables](https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf)). + | Device | Playable? | How | How sure we are | |---|---|---|---| | **iPhone / iPad, A17 Pro and later** (iPhone 15 Pro and later, iPhone 16 and later, iPads with M-series chips) | Yes | iOS 26 or later: the default shell / default build; iOS 18 – 25: the iOS 18 shell / [older-API build](docs/OLDER_SYSTEMS.md) | Main devices, played daily | | **iPhone / iPad, A16 and earlier** (all iPhone 14 models, iPhone 15 / 15 Plus, iPhone 13 series and so on) | Yes, with one extra step | Make a Legacy Device Pack from your own game files as in [docs/LEGACY_DEVICES.md](docs/LEGACY_DEVICES.md) and include it when making the install package; the system split is the same as the row above | Played by players: iPhone 14 Pro Max (A16, 6 GB) at 60 fps; iPhone 13 Pro Max (A15, 6 GB) in the 30 fps mode | | **Devices with 4 GB of RAM** (such as the 4th-generation iPad Air) | Not supported yet (we are reducing memory use and will update this when there is progress) | — | Tested by a player: on an iPad Air 4 (A14, 4 GB) with the Legacy Device Pack, the system ends the app a few seconds after launch because the device runs out of memory | -| **Chips older than A15 with 6 GB of RAM or more** | No reports yet | Same as the A16-and-earlier row | If you have tried, please open an Issue and tell us | +| **A14 chips with 6 GB of RAM or more** (such as iPhone 12 Pro / 12 Pro Max) | No reports yet | Same as the A16-and-earlier row | If you have tried, please open an Issue and tell us | +| **A13 and earlier chips** (such as the iPhone 11 series and the 2020 iPad Pro) | Not supported | — | The graphics chip does not support Metal 3 (tested by a player on an iPad Pro with A12Z; Apple's references are above the table); the app says so at launch instead of crashing | | **Mac, Apple silicon** | Yes (native macOS App) | macOS 26 or later: the default build; macOS 15 – 25: the [older-API build](docs/OLDER_SYSTEMS.md). Keyboard, mouse and gamepad all work; what each can do is in [docs/MAC.md](docs/MAC.md) | A player has played the older-API build on macOS 15.7.7 | | **Intel Macs** | Not supported | — | — | @@ -267,7 +270,7 @@ The interface is the original's gamepad interface. Keyboard: Space confirms, Esc ### Without a Mac: the shell plus the packaging tool -Download our prebuilt "shell" package (`D2RMobile-shell.ipa`; `D2RMobile-shell-ios18.ipa` for iOS 18 – 25), which contains no game content, from this repository's [Releases page](https://github.com/jhaizhou-ops/d2r-mobile/releases), add your own game files, make the install package on Windows or Linux, then sign and install it with a sideloading tool. On this route only, because the computer making the package has no Apple shader compiler, the **first launch** on the phone spends about 7 minutes compiling shaders (once, with a progress bar); a package built with Xcode has no such step. The steps, and how far each one has been verified, are in [docs/NO_XCODE.md](docs/NO_XCODE.md). +Download our prebuilt "shell" package (`D2RMobile-shell-build-input.zip`; `D2RMobile-shell-ios18-build-input.zip` for iOS 18 – 25), which contains no game content, from this repository's [Releases page](https://github.com/jhaizhou-ops/d2r-mobile/releases), add your own game files, make the install package on Windows or Linux, then sign and install it with a sideloading tool. The shell is build input, not an app to install (installed as is, it only shows a dialog and does not start the game); when you move to a new release, make the install package again with the new shell. On this route only, because the computer making the package has no Apple shader compiler, the **first launch** on the phone spends about 7 minutes compiling shaders (once, with a progress bar); a package built with Xcode has no such step. The steps, and how far each one has been verified, are in [docs/NO_XCODE.md](docs/NO_XCODE.md). ## Known limitations diff --git a/README.zh-CN.md b/README.zh-CN.md index 27162e8..65e6974 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -191,12 +191,15 @@ flowchart LR ## 支持哪些设备 +最低要求:**A14 / M1 及以后的芯片**——本项目的图形层要用 Metal 3,苹果从 A14 / M1 起才支持(依据:苹果的[Metal 支持的设备](https://support.apple.com/102894)、[Metal 功能表](https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf))。 + | 设备 | 能不能玩 | 怎么做 | 把握程度 | |---|---|---|---| | **iPhone / iPad,A17 Pro 及以后**(iPhone 15 Pro 起、iPhone 16 起、M 系列芯片的 iPad) | 直接玩 | iOS 26 及以上用缺省的壳 / 缺省构建;iOS 18 – 25 用 iOS 18 的壳 / [老接口版](docs/OLDER_SYSTEMS.zh-CN.md) | 主力机型,日常在玩 | | **iPhone / iPad,A16 及更早**(iPhone 14 全系、iPhone 15 / 15 Plus、iPhone 13 系列等) | 可以玩,多一步 | 按 [docs/LEGACY_DEVICES.zh-CN.md](docs/LEGACY_DEVICES.zh-CN.md) 用自己的游戏文件做一份老机型补充包,做安装包时带上它;系统同上一行分 iOS 26 / iOS 18 – 25 | 已有玩家实测:iPhone 14 Pro Max(A16,6 GB)60 帧;iPhone 13 Pro Max(A15,6 GB)30 帧档 | | **4 GB 内存的设备**(如 iPad Air 第 4 代) | 暂不支持(在优化内存,有进展更新) | — | 已有玩家实测:iPad Air 4(A14,4 GB)带上老机型补充包后,启动几秒即因整机内存不足被系统结束 | -| **比 A15 更老的芯片、6 GB 及以上内存** | 尚无报告 | 同 A16 及更早那一行 | 欢迎试过的人开 Issue 告诉我们结果 | +| **A14 芯片、6 GB 及以上内存**(如 iPhone 12 Pro / 12 Pro Max) | 尚无报告 | 同 A16 及更早那一行 | 欢迎试过的人开 Issue 告诉我们结果 | +| **A13 及更早的芯片**(如 iPhone 11 系列、2020 年的 iPad Pro) | 不支持 | — | 图形芯片不支持 Metal 3(玩家在 iPad Pro A12Z 上实测;苹果依据见表上方);App 启动时会直接提示,不会闪退 | | **Mac,Apple 芯片** | 直接玩(原生 macOS App) | macOS 26 及以上用缺省出法;macOS 15 – 25 用[老接口出法](docs/OLDER_SYSTEMS.zh-CN.md)。键盘、鼠标、手柄都能玩,各自能做什么见 [docs/MAC.zh-CN.md](docs/MAC.zh-CN.md) | 已有玩家在 macOS 15.7.7 上实际玩过老接口版 | | **Intel 芯片的 Mac** | 不支持 | — | — | @@ -267,7 +270,7 @@ DM_MAC_M3=1 dm/tools/mac_app.sh # macOS 15 – 25:产出 D2R Mobile M3.ap ### 没有 Mac:壳 + 做包工具 -从本仓库的[发布页](https://github.com/jhaizhou-ops/d2r-mobile/releases)下载我们预先做好的、不含游戏内容的「壳」安装包(`D2RMobile-shell.ipa`;iOS 18 – 25 用 `D2RMobile-shell-ios18.ipa`),加上你自己的游戏文件,在 Windows 或 Linux 上做出安装包,再用自签工具签名装机。只有走这条路时,因为做包的电脑上没有苹果的着色器编译器,手机**第一次启动**要花约 7 分钟把着色器编完(一次性,带进度条);用 Xcode 构建的包没有这一步。步骤与每一步的验证现状见 [docs/NO_XCODE.zh-CN.md](docs/NO_XCODE.zh-CN.md)。 +从本仓库的[发布页](https://github.com/jhaizhou-ops/d2r-mobile/releases)下载我们预先做好的、不含游戏内容的「壳」安装包(`D2RMobile-shell-build-input.zip`;iOS 18 – 25 用 `D2RMobile-shell-ios18-build-input.zip`),加上你自己的游戏文件,在 Windows 或 Linux 上做出安装包,再用自签工具签名装机。壳是做安装包的原料,不能直接装来玩(直接装上去只会弹框说明、不会进游戏);换新版本时要用新版的壳重新做一次安装包。只有走这条路时,因为做包的电脑上没有苹果的着色器编译器,手机**第一次启动**要花约 7 分钟把着色器编完(一次性,带进度条);用 Xcode 构建的包没有这一步。步骤与每一步的验证现状见 [docs/NO_XCODE.zh-CN.md](docs/NO_XCODE.zh-CN.md)。 ## 已知限制 diff --git a/dm/gfx/nvn/hle_nvn.c b/dm/gfx/nvn/hle_nvn.c index d64e95f..63dd130 100644 --- a/dm/gfx/nvn/hle_nvn.c +++ b/dm/gfx/nvn/hle_nvn.c @@ -241,6 +241,76 @@ NVN(nvnTextureBuilderGetStorageAlignment, size_t, const NVNtextureBuilder *b) { } #define TX(t) ((tex_t *)(t)) #define CTX(t) ((const tex_t *)(t)) +// ---------- 对象副本:录制时按序号留一份贴图 / 程序对象,命令载荷存副本地址 ---------- +// 同一序号的对象内容不变(Initialize / SetShaders 才换序号),游戏提交后可以改写或重建自己的对象(真机上 GPU 只看录进命令内存的值), +// 回放层读副本就不受影响。游戏对象里记着副本地址,按值拷来的对象序号相同、直接共用。副本在对象 Finalize / 换序号后再过 SNAP_KEEP 次提交才回收; +// 槽位内存只增不还给系统,回收时清零(序号 0 不与任何有效序号相等),过期的副本地址只会读到不相等的序号、重新取副本。 +// ---------- Object snapshots: when recording, keep one copy of each texture / program object per serial; command payloads store the snapshot address ---------- +// An object with the same serial has the same content (only Initialize / SetShaders change the serial); after submitting, the game may rewrite or rebuild its own objects (on the real device the GPU only sees the values recorded into command memory), +// and the replay layer reading snapshots is unaffected. The game object records the snapshot address, and objects copied by value have the same serial and share it directly. A snapshot is reclaimed only SNAP_KEEP submits after the object is Finalized / changes serial; +// slot memory only grows and is never returned to the system; reclaimed slots are zeroed (serial 0 never equals a valid serial), so a stale snapshot address only reads a non-matching serial and takes a new snapshot. +typedef union snap_slot { tex_t t; prog_t p; union snap_slot *next; } snap_slot; +#define SNAP_KEEP 8 +static pthread_mutex_t g_snap_mu = PTHREAD_MUTEX_INITIALIZER; +static snap_slot *g_snap_free; +static struct { snap_slot *s; uint64_t at; } *g_snap_ret; static size_t g_snap_nret, g_snap_capret, g_snap_live, g_snap_slots; +static uint64_t g_snap_sub; // 已执行(翻译完)的提交数:回收时刻 | Number of submits executed (translated): the reclaim clock +static _Atomic uint64_t g_x_subs; // 已入队的提交数(翻译队列,见 nvnQueueSubmitCommands 前):退役盖戳用它,回收按已执行数,翻译线程落后时副本不会提前回收 | Number of submits enqueued (translation queue, see before nvnQueueSubmitCommands): used for the retire stamp, while reclaim goes by the number executed, so snapshots are not reclaimed early when the translation thread falls behind +static snap_slot *snap_alloc(void) { // 持 g_snap_mu | Holds g_snap_mu + if (!g_snap_free) { + snap_slot *c = calloc(256, sizeof *c); if (!c) { LOG("【红】对象副本分配失败"); abort(); } + for (int i = 255; i >= 0; i--) { c[i].next = g_snap_free; g_snap_free = &c[i]; } + g_snap_slots += 256; // 读数:槽位只在在用 + 待回收占满时才扩,扩槽停住即有上界 | Reading: slots grow only when in-use + pending-reclaim fill them all; slot growth stops, so there is an upper bound + LOG("[nvn] 对象副本槽位扩到 %zu 个(%zu KB):在用 %zu,其中待回收 %zu,第 %llu 次提交", g_snap_slots, g_snap_slots * sizeof *c >> 10, g_snap_live, g_snap_nret, (unsigned long long)g_snap_sub); + } + snap_slot *n = g_snap_free; g_snap_free = n->next; memset(n, 0, sizeof *n); g_snap_live++; + return n; +} +static void snap_retire(const void *s) { // 持 g_snap_mu | Holds g_snap_mu + if (g_snap_nret == g_snap_capret) { g_snap_capret = g_snap_capret ? g_snap_capret * 2 : 256; g_snap_ret = realloc(g_snap_ret, g_snap_capret * sizeof *g_snap_ret); } + g_snap_ret[g_snap_nret].s = (snap_slot *)s; g_snap_ret[g_snap_nret++].at = atomic_load(&g_x_subs); +} +static void snap_tick(uint64_t done) { // 翻译线程每执行完一次提交:回收退役时已入队的提交都执行完、且又过了 SNAP_KEEP 次提交的副本 | Each time the translation thread finishes a submit: reclaim snapshots whose submits enqueued at retirement have all executed and that have passed SNAP_KEEP more submits + pthread_mutex_lock(&g_snap_mu); + g_snap_sub = done; size_t k = 0; + for (size_t i = 0; i < g_snap_nret; i++) { + if (g_snap_ret[i].at + SNAP_KEEP <= g_snap_sub) { snap_slot *n = g_snap_ret[i].s; memset(n, 0, sizeof *n); n->next = g_snap_free; g_snap_free = n; g_snap_live--; } + else g_snap_ret[k++] = g_snap_ret[i]; + } + g_snap_nret = k; + pthread_mutex_unlock(&g_snap_mu); +} +static const tex_t *snap_tex(const NVNtexture *t) { + tex_t *o = TX(t); if (!o || !o->serial) return o; // 没初始化过的对象没有可留的内容,照旧存原址 | An object that was never initialized has no content to keep; store the original address as before + const tex_t *s = __atomic_load_n((const tex_t **)&o->snap, __ATOMIC_ACQUIRE); + if (s && s->serial == o->serial) return s; + pthread_mutex_lock(&g_snap_mu); + s = o->snap; + if (!s || s->serial != o->serial) { snap_slot *n = snap_alloc(); n->t = *o; n->t.snap = NULL; s = &n->t; __atomic_store_n((const tex_t **)&o->snap, s, __ATOMIC_RELEASE); } + pthread_mutex_unlock(&g_snap_mu); + return s; +} +static const prog_t *snap_prog(const NVNprogram *p) { + prog_t *o = (prog_t *)p; if (!o || !o->serial) return o; + const prog_t *s = __atomic_load_n((const prog_t **)&o->snap, __ATOMIC_ACQUIRE); + if (s && s->serial == o->serial) return s; + pthread_mutex_lock(&g_snap_mu); + s = o->snap; + if (!s || s->serial != o->serial) { snap_slot *n = snap_alloc(); n->p = *o; n->p.snap = NULL; s = &n->p; __atomic_store_n((const prog_t **)&o->snap, s, __ATOMIC_RELEASE); } + pthread_mutex_unlock(&g_snap_mu); + return s; +} +static void x_drain(void); +static uint64_t x_fence(void); +// 对象 Finalize / 换序号前调:本序号的副本退役(按值拷来的同序号对象之后再录会重新取副本) +// Called before an object is Finalized / changes serial: retire this serial's snapshot (an object with the same serial copied by value takes a new snapshot when recorded later) +static void snap_drop(const void **pp, uint64_t ser, uint64_t snap_ser_off) { + pthread_mutex_lock(&g_snap_mu); + const uint8_t *s = *pp; uint64_t ss; if (s) memcpy(&ss, s + snap_ser_off, 8); + if (s && ser && ss == ser) snap_retire(s); + *pp = NULL; + pthread_mutex_unlock(&g_snap_mu); +} NVN(nvnTextureInitialize, NVNboolean, NVNtexture *t, const NVNtextureBuilder *b) { const tex_builder_t *s = (const tex_builder_t *)b; tex_t *o = TX(t); memset(o, 0, sizeof *o); @@ -253,7 +323,7 @@ NVN(nvnTextureInitialize, NVNboolean, NVNtexture *t, const NVNtextureBuilder *b) o->d.levels, o->d.format, o->d.target, o->d.flags, o->L.size); return 1; } -NVN(nvnTextureFinalize, void, NVNtexture *t) { mtl_tex_release(TX(t)); TX(t)->magic = 0; } +NVN(nvnTextureFinalize, void, NVNtexture *t) { snap_drop(&TX(t)->snap, TX(t)->serial, offsetof(tex_t, serial)); mtl_tex_release(TX(t)); TX(t)->magic = 0; } NVN(nvnTextureGetFlags, NVNtextureFlags, const NVNtexture *t) { return (NVNtextureFlags)CTX(t)->d.flags; } NVN(nvnTextureGetWidth, int, const NVNtexture *t) { return (int)CTX(t)->d.width; } NVN(nvnTextureGetHeight, int, const NVNtexture *t) { return (int)CTX(t)->d.height; } @@ -290,6 +360,7 @@ static void read_texels(const tex_t *o, const view_t *v, const NVNcopyRegion *r, if (!row) row = wb; if (!img) img = row * hb; unsigned level = v && v->set_levels ? (unsigned)v->base_level : 0, layer0 = v && v->set_layers ? (unsigned)v->min_layer : 0; + x_drain(); // CPU 读贴图:已入队的提交先翻译完 | CPU texture read: submits already enqueued are translated first mtl_read_texels(o, level, layer0, r, dst, (size_t)row, (size_t)img); } NVN(nvnTextureReadTexels, void, const NVNtexture *t, const NVNtextureView *v, const NVNcopyRegion *r, void *dst) { @@ -335,11 +406,11 @@ NVN(nvnSamplerFinalize, void, NVNsampler *s) { ((samp_t *)s)->magic = 0; } NVN(nvnProgramInitialize, NVNboolean, NVNprogram *p, NVNdevice *d) { (void)d; memset(p, 0, sizeof(prog_t)); ((prog_t *)p)->magic = MAGIC('P', 'R', 'O', 'G'); return 1; } -NVN(nvnProgramFinalize, void, NVNprogram *p) { mtl_prog_release((prog_t *)p); ((prog_t *)p)->magic = 0; } +NVN(nvnProgramFinalize, void, NVNprogram *p) { prog_t *o = (prog_t *)p; snap_drop(&o->snap, o->serial, offsetof(prog_t, serial)); mtl_prog_release(o); o->magic = 0; } NVN(nvnProgramSetShaders, NVNboolean, NVNprogram *p, int n, const NVNshaderData *sd) { prog_t *o = (prog_t *)p; if (n < 0 || n > 6) { LOG("【红】ProgramSetShaders 阶段数 %d", n); return 0; } - mtl_prog_release(o); o->nstage = n; memcpy(o->sd, sd, n * sizeof *sd); o->serial = nvn_new_serial(); + snap_drop(&o->snap, o->serial, offsetof(prog_t, serial)); mtl_prog_release(o); o->nstage = n; memcpy(o->sd, sd, n * sizeof *sd); o->serial = nvn_new_serial(); OLOG("ProgramSetShaders %p n=%d data0=%#llx", (void *)p, n, n ? (unsigned long long)sd[0].data : 0ull); return 1; } @@ -350,7 +421,7 @@ NVN(nvnSyncInitialize, NVNboolean, NVNsync *s, NVNdevice *d) { (void)d; *(sync_t NVN(nvnSyncFinalize, void, NVNsync *s) { ((sync_t *)s)->magic = 0; } // 围栏 = 「此前提交到队列的命令全部完成」:记下最近一次提交的栅栏值 // Fence = "all commands previously submitted to the queue have completed": record the fence value of the most recent submit -NVN(nvnQueueFenceSync, void, NVNqueue *q, NVNsync *s, NVNsyncCondition c, int f) { (void)q; (void)c; (void)f; ((sync_t *)s)->fenced = 1; ((sync_t *)s)->fence = mtl_last_fence(); } +NVN(nvnQueueFenceSync, void, NVNqueue *q, NVNsync *s, NVNsyncCondition c, int f) { (void)q; (void)c; (void)f; ((sync_t *)s)->fenced = 1; ((sync_t *)s)->fence = x_fence(); } // 没围栏过的同步对象按真机行为等到超时;已围栏的只在 GPU 真正完成到该栅栏值后放行 // A sync object that was never fenced waits until timeout, as on a real device; a fenced one is released only after the GPU has actually completed up to that fence value NVN(nvnSyncWait, NVNsyncWaitResult, const NVNsync *s, uint64_t timeout) { @@ -400,7 +471,7 @@ NVN(nvnQueueGetError, NVNqueueGetErrorResult, NVNqueue *q, NVNqueueErrorInfo *in (void)q; if (info) memset(info, 0, sizeof *info); return NVN_QUEUE_GET_ERROR_RESULT_GPU_NO_ERROR; } NVN(nvnQueueFlush, void, NVNqueue *q) { (void)q; } -NVN(nvnQueueFinish, void, NVNqueue *q) { (void)q; mtl_finish(); } +NVN(nvnQueueFinish, void, NVNqueue *q) { (void)q; x_drain(); mtl_finish(); } // ---------- 命令缓冲:录进游戏的命令内存,提交时执行 CPU 可见副作用 ---------- // ---------- Command buffer: record into the game's command memory, perform CPU-visible side effects at submit ---------- @@ -545,8 +616,8 @@ NVN(nvnCommandBufferSetRenderTargets, void, NVNcommandBuffer *c, int n, const NV const NVNtexture *dt, const NVNtextureView *dv) { if (n < 0 || n > 8) { LOG("【红】SetRenderTargets 数量 %d", n); n = n < 0 ? 0 : 8; } p_set_rt *r = REC(c, OP_SET_RT, p_set_rt); r->n = n; - for (int i = 0; i < n; i++) { r->color[i] = ct ? (const tex_t *)ct[i] : NULL; copy_view(&r->cview[i], &r->has_cview[i], cv ? cv[i] : NULL); } - r->depth = (const tex_t *)dt; copy_view(&r->dview, &r->has_dview, dv); + for (int i = 0; i < n; i++) { r->color[i] = ct ? snap_tex(ct[i]) : NULL; copy_view(&r->cview[i], &r->has_cview[i], cv ? cv[i] : NULL); } + r->depth = snap_tex(dt); copy_view(&r->dview, &r->has_dview, dv); } NVN(nvnCommandBufferClearColor, void, NVNcommandBuffer *c, int index, const float *rgba, int mask) { p_clear_color *r = REC(c, OP_CLEAR_COLOR, p_clear_color); r->index = index; r->mask = mask; memcpy(r->rgba, rgba, 16); @@ -562,7 +633,7 @@ NVN(nvnCommandBufferSetViewports, void, NVNcommandBuffer *c, int first, int n, c NVN(nvnCommandBufferSetScissor, void, NVNcommandBuffer *c, int x, int y, int w, int h) { *REC(c, OP_SCISSOR, p_scissor) = (p_scissor){x, y, w, h}; } NVN(nvnCommandBufferSetDepthRange, void, NVNcommandBuffer *c, float n, float f) { *REC(c, OP_DEPTH_RANGE, p_depth_range) = (p_depth_range){n, f}; } NVN(nvnCommandBufferBindProgram, void, NVNcommandBuffer *c, const NVNprogram *p, int stages) { - *REC(c, OP_BIND_PROGRAM, p_bind_program) = (p_bind_program){(const prog_t *)p, stages}; + *REC(c, OP_BIND_PROGRAM, p_bind_program) = (p_bind_program){snap_prog(p), stages}; } static void bind_state(NVNcommandBuffer *c, int kind, const void *st, size_t n) { p_bind_state *r = REC(c, OP_BIND_STATE, p_bind_state); r->kind = kind; memcpy(r->bytes, st, n); } NVN(nvnCommandBufferBindBlendState, void, NVNcommandBuffer *c, const NVNblendState *st) { bind_state(c, 0, st, sizeof(blend_st)); } @@ -635,23 +706,23 @@ NVN(nvnCommandBufferSetSamplerPool, void, NVNcommandBuffer *c, const NVNsamplerP NVN(nvnCommandBufferCopyBufferToTexture, void, NVNcommandBuffer *c, NVNbufferAddress src, const NVNtexture *t, const NVNtextureView *v, const NVNcopyRegion *r, int flags) { - p_copy_b2t *o = REC(c, OP_COPY_B2T, p_copy_b2t); o->src = src; o->tex = (const tex_t *)t; copy_view(&o->view, &o->has_view, v); o->r = *r; o->flags = flags; + p_copy_b2t *o = REC(c, OP_COPY_B2T, p_copy_b2t); o->src = src; o->tex = snap_tex(t); copy_view(&o->view, &o->has_view, v); o->r = *r; o->flags = flags; } NVN(nvnCommandBufferCopyTextureToBuffer, void, NVNcommandBuffer *c, const NVNtexture *t, const NVNtextureView *v, const NVNcopyRegion *r, NVNbufferAddress dst, int flags) { - p_copy_b2t *o = REC(c, OP_COPY_T2B, p_copy_b2t); o->src = dst; o->tex = (const tex_t *)t; copy_view(&o->view, &o->has_view, v); o->r = *r; o->flags = flags; + p_copy_b2t *o = REC(c, OP_COPY_T2B, p_copy_b2t); o->src = dst; o->tex = snap_tex(t); copy_view(&o->view, &o->has_view, v); o->r = *r; o->flags = flags; } // 用给定值清贴图区域(浮点 / 无符号整数两版;mask = 通道写掩码) // Clear a texture region with the given value (float / unsigned integer versions; mask = channel write mask) NVN(nvnCommandBufferClearTexture, void, NVNcommandBuffer *c, const NVNtexture *t, const NVNtextureView *v, const NVNcopyRegion *r, const float *rgba, int mask) { - p_clear_tex *o = REC(c, OP_CLEAR_TEX, p_clear_tex); o->tex = (const tex_t *)t; copy_view(&o->view, &o->has_view, v); o->r = *r; o->mask = mask; o->is_uint = 0; memcpy(o->c.f, rgba, 16); + p_clear_tex *o = REC(c, OP_CLEAR_TEX, p_clear_tex); o->tex = snap_tex(t); copy_view(&o->view, &o->has_view, v); o->r = *r; o->mask = mask; o->is_uint = 0; memcpy(o->c.f, rgba, 16); } NVN(nvnCommandBufferClearTextureui, void, NVNcommandBuffer *c, const NVNtexture *t, const NVNtextureView *v, const NVNcopyRegion *r, const uint32_t *rgba, int mask) { - p_clear_tex *o = REC(c, OP_CLEAR_TEX, p_clear_tex); o->tex = (const tex_t *)t; copy_view(&o->view, &o->has_view, v); o->r = *r; o->mask = mask; o->is_uint = 1; memcpy(o->c.u, rgba, 16); + p_clear_tex *o = REC(c, OP_CLEAR_TEX, p_clear_tex); o->tex = snap_tex(t); copy_view(&o->view, &o->has_view, v); o->r = *r; o->mask = mask; o->is_uint = 1; memcpy(o->c.u, rgba, 16); } NVN(nvnCommandBufferCopyTextureToTexture, void, NVNcommandBuffer *c, const NVNtexture *s, const NVNtextureView *sv, const NVNcopyRegion *sr, const NVNtexture *d, const NVNtextureView *dv, const NVNcopyRegion *dr, int flags) { - p_copy_t2t *o = REC(c, OP_COPY_T2T, p_copy_t2t); o->src = (const tex_t *)s; o->dst = (const tex_t *)d; + p_copy_t2t *o = REC(c, OP_COPY_T2T, p_copy_t2t); o->src = snap_tex(s); o->dst = snap_tex(d); copy_view(&o->sv, &o->has_sv, sv); copy_view(&o->dv, &o->has_dv, dv); o->sr = *sr; o->dr = *dr; o->flags = flags; } NVN(nvnCommandBufferSetCopyRowStride, void, NVNcommandBuffer *c, ptrdiff_t st) { REC(c, OP_COPY_STRIDE, p_copy_stride)->stride = st; } @@ -747,23 +818,109 @@ void dm_gfx_suspend(int on) { if (on) while (g_inflight_api) pthread_cond_wait(&g_susp_cv, &g_susp_mu); else pthread_cond_broadcast(&g_susp_cv); pthread_mutex_unlock(&g_susp_mu); - if (on) { mtl_drain(); LOG("[nvn] 图形挂起:在途 GPU 工作已清空"); } else LOG("[nvn] 图形恢复"); + if (on) { x_drain(); mtl_drain(); LOG("[nvn] 图形挂起:在途 GPU 工作已清空"); } else LOG("[nvn] 图形恢复"); } -NVN(nvnQueueSubmitCommands, void, NVNqueue *q, int n, const NVNcommandHandle *h) { - gfx_enter(); +// 一条实时线程的声明状态:游戏主线程(取图处)与翻译线程(帧边界)各一份,按各自每帧 CPU 自动调整(见 set_time_constraint_comp) +// Declaration state of one real-time thread: one each for the game main thread (at acquire) and the translation thread (at frame boundaries), each adjusted automatically from its own per-frame CPU (see set_time_constraint_comp) +typedef struct { const char *who; double comp_ms, period_ms; uint64_t last; double win[120]; int n; } rt_decl; // comp_ms:当前声明的计算量(0 = 未声明) | comp_ms: currently declared computation (0 = not declared) +static rt_decl g_rt_main = {"出图线程"}, g_rt_xlat = {"翻译线程"}; +static void set_time_constraint(rt_decl *d, uint64_t period_ns); +static void rt_comp_tick(rt_decl *d, uint64_t period_ns); +// ---------- 翻译队列(B 方案第二期):提交 / 出图 / 设帧号按序排给翻译线程,游戏线程只登记、立刻返回 ---------- +// 游戏逻辑与上一帧的翻译(回放 + Metal 编码)重叠。栅栏值 = 已入队的提交数:Metal 层每次提交恰好 ++g_fence、g_done 只在已提交的命令缓冲 +// 完成时推进,所以等栅栏 f 就是等「f 翻译完且 GPU 做完」——游戏按栅栏回收命令内存、改写对象时翻译线程早已读完。 +// 出图票号换成本队列的任务号:取图处先等该任务执行完,再按它换来的出图线程票号等。设帧号也排队:回放按帧号重置泛光取样等状态, +// 不能在翻译途中被游戏线程改掉。DM_NVN_SYNC=1:任务在调用线程上当场执行(同一个执行函数),作对照与量测基准。 +// ---------- Translation queue (plan B, phase 2): submit / present / set-frame-number are queued in order to the translation thread; the game thread only records them and returns at once ---------- +// Game logic overlaps the previous frame's translation (replay + Metal encoding). Fence value = number of submits enqueued: the Metal layer does ++g_fence exactly once per submit and g_done advances only when a committed command buffer +// completes, so waiting for fence f means waiting until "f is translated and the GPU is done"; by the time the game reclaims command memory or rewrites objects by fence, the translation thread has long finished reading them. +// Present tickets become this queue's job numbers: acquire first waits for that job to run, then waits on the present thread ticket it was swapped for. Setting the frame number is queued too: replay resets bloom sampling and other state by frame number, +// which must not be changed by the game thread in the middle of translation. DM_NVN_SYNC=1: jobs run in place on the calling thread (the same execution function), as the control and measurement baseline. +enum { XJ_SUBMIT, XJ_PRESENT, XJ_FRAME }; +typedef struct { int kind, n; uint64_t *h; const tex_t *tex; double period; int crop[4]; uint64_t frame, sub, host; } xjob; // host:入队时锁存的宿主画法开关 | host: host drawing switches latched at enqueue +#define XQ 32 +#define XTK 1024 +static xjob g_xq[XQ]; static uint64_t g_xq_in, g_xq_done; // 入队任务数 / 已执行任务数(任务号从 1 计) | Jobs enqueued / jobs executed (job numbers start at 1) +static struct { uint64_t job, tk; } g_xtk[XTK]; // 出图任务号 → 出图线程票号 | Present job number -> present thread ticket +static pthread_mutex_t g_xmu = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t g_xcv = PTHREAD_COND_INITIALIZER; +static int g_x_sync; static pthread_t g_x_thr; static mach_port_t g_x_port; // 翻译线程(策略读数用) | Translation thread (for policy readings) +static void x_submit(const uint64_t *h, int n, uint64_t sub, uint64_t host) { + mtl_host_apply(host); uint64_t t0 = now_ns(), c0 = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID), i0, y0, s0 = thr_sys_ns(); thr_counts(&i0, &y0); - ((queue_t *)q)->submits++; mtl_sub_begin(); - mtl_sub_index((const uint64_t *)h, n); - for (int i = 0; i < n; i++) { mtl_exec_rest((const uint64_t *)h + i + 1, n - i - 1); mtl_exec((const uint8_t *)h[i]); } + mtl_sub_index(h, n); + for (int i = 0; i < n; i++) { mtl_exec_rest(h + i + 1, n - i - 1); mtl_exec((const uint8_t *)h[i]); } mtl_exec_rest(NULL, 0); - mtl_sub_commit(); + uint64_t f = mtl_sub_commit(); + if (f != sub) { static int red; if (!red++) LOG("【红】翻译队列:第 %llu 次提交的 Metal 栅栏是 %llu,栅栏与提交数对不上,游戏等同步会提前 / 推迟放行", (unsigned long long)sub, (unsigned long long)f); } + snap_tick(sub); uint64_t dw = now_ns() - t0; atomic_fetch_add(&g_nvn_ns, dw); atomic_fetch_add(&g_sub_wall_ns, dw); uint64_t i1, y1; thr_counts(&i1, &y1); uint64_t dc = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID) - c0, di = i1 - i0; atomic_fetch_add(&g_cum_sub_cyc, y1 - y0); atomic_fetch_add(&g_cum_sub_sys_ns, thr_sys_ns() - s0); atomic_fetch_add(&g_cum_sub_wall_ns, dw); atomic_fetch_add(&g_sub_cpu_ns, dc); atomic_fetch_add(&g_cum_sub_cpu_ns, dc); atomic_fetch_add(&g_sub_instr, di); atomic_fetch_add(&g_cum_sub_instr, di); +} +static void x_run(const xjob *j, uint64_t job) { + if (j->kind == XJ_SUBMIT) { x_submit(j->h, j->n, j->sub, j->host); free(j->h); } + else if (j->kind == XJ_PRESENT) { uint64_t tk = mtl_present(j->tex, j->period, j->crop); pthread_mutex_lock(&g_xmu); g_xtk[job % XTK].job = job; g_xtk[job % XTK].tk = tk; pthread_mutex_unlock(&g_xmu); } + else { + mtl_set_frame(j->frame); + // 翻译线程与游戏主线程同级:时间约束(实时)线程,周期 = 出图周期,计算量按本线程每帧 CPU 的 p90 自动声明(同取图处的主线程;确定性时钟下不声明) + // The translation thread has the same standing as the game main thread: a time-constraint (real-time) thread, period = present period, computation declared automatically from the p90 of this thread's per-frame CPU (same as the main thread at acquire; not declared under the deterministic clock) + uint64_t pn = (uint64_t)(j->period * 1e9); static uint64_t rt_p; + if (!g_x_sync && !dm_detclock_enabled()) { if (pn && rt_p != pn) { rt_p = pn; set_time_constraint(&g_rt_xlat, pn); } rt_comp_tick(&g_rt_xlat, pn); } + } +} +static void *x_thread(void *a) { + (void)a; pthread_setname_np("nvn-translate"); g_x_port = pthread_mach_thread_np(pthread_self()); + pthread_mutex_lock(&g_xmu); + for (;;) { + while (g_xq_done == g_xq_in) pthread_cond_wait(&g_xcv, &g_xmu); + uint64_t job = g_xq_done + 1; xjob j = g_xq[job % XQ]; + pthread_mutex_unlock(&g_xmu); + x_run(&j, job); + pthread_mutex_lock(&g_xmu); + g_xq_done = job; pthread_cond_broadcast(&g_xcv); + } + return NULL; +} +static void x_start(void) { + const char *e = getenv("DM_NVN_SYNC"); g_x_sync = e && atoi(e); + if (g_x_sync) { LOG("[nvn] DM_NVN_SYNC=1:翻译在提交线程上同步做(对照档)"); return; } + pthread_attr_t at; pthread_attr_init(&at); pthread_attr_set_qos_class_np(&at, QOS_CLASS_USER_INTERACTIVE, 0); pthread_attr_setstacksize(&at, 8 << 20); + pthread_t t; if (pthread_create(&g_x_thr, &at, x_thread, NULL)) { LOG("【红】翻译线程起不来,改为同步翻译"); g_x_sync = 1; } else LOG("[nvn] 翻译线程已起:提交 / 出图在翻译线程上按序执行(队列 %d 项)", XQ); + pthread_attr_destroy(&at); +} +static uint64_t x_push(xjob *j) { // 返回任务号 | Returns the job number + static pthread_once_t once = PTHREAD_ONCE_INIT; pthread_once(&once, x_start); + pthread_mutex_lock(&g_xmu); + while (g_xq_in - g_xq_done >= XQ) pthread_cond_wait(&g_xcv, &g_xmu); + if (j->kind == XJ_SUBMIT) j->sub = atomic_fetch_add(&g_x_subs, 1) + 1; + uint64_t job = ++g_xq_in; + if (g_x_sync) { // 当场执行:单线程提交时与旧路径同序 | Run in place: with single-thread submission the order is the same as the old path + pthread_mutex_unlock(&g_xmu); x_run(j, job); pthread_mutex_lock(&g_xmu); + g_xq_done = job; pthread_cond_broadcast(&g_xcv); + } else { g_xq[job % XQ] = *j; pthread_cond_broadcast(&g_xcv); } + pthread_mutex_unlock(&g_xmu); + return job; +} +static void x_wait(uint64_t job) { pthread_mutex_lock(&g_xmu); while (g_xq_done < job) pthread_cond_wait(&g_xcv, &g_xmu); pthread_mutex_unlock(&g_xmu); } +static void x_drain(void) { pthread_mutex_lock(&g_xmu); uint64_t job = g_xq_in; pthread_mutex_unlock(&g_xmu); x_wait(job); } +static uint64_t x_fence(void) { return atomic_load(&g_x_subs); } +static uint64_t x_present_ticket(uint64_t job) { // 出图任务执行完后换来的出图线程票号(0 = 那次出图被丢弃,不用等) | Present thread ticket obtained after the present job runs (0 = that present was dropped, nothing to wait for) + x_wait(job); + pthread_mutex_lock(&g_xmu); uint64_t tk = g_xtk[job % XTK].job == job ? g_xtk[job % XTK].tk : 0; int lost = g_xtk[job % XTK].job != job; pthread_mutex_unlock(&g_xmu); + if (lost) { static int red; if (!red++) LOG("【红】翻译队列:出图任务 %llu 的票号已被覆盖(票号表 %d 项不够),这次取图不等出图线程", (unsigned long long)job, XTK); } + return tk; +} +NVN(nvnQueueSubmitCommands, void, NVNqueue *q, int n, const NVNcommandHandle *h) { + gfx_enter(); + ((queue_t *)q)->submits++; + xjob j = {XJ_SUBMIT, n, n > 0 ? malloc((size_t)n * sizeof *h) : NULL}; // 句柄数组是游戏的,入队时拷一份 | The handle array belongs to the game; copy it when enqueuing + if (n > 0) memcpy(j.h, h, (size_t)n * sizeof *h); + j.host = mtl_host_latch(); + x_push(&j); gfx_leave(); } @@ -833,10 +990,6 @@ NVN(nvnWindowSetCrop, void, NVNwindow *w, int x, int y, int ww, int hh) { memcpy(o->crop, v, sizeof v); } static void trow(uint64_t f, const char *name, double v); -static void set_time_constraint(uint64_t period_ns); -static void rt_comp_tick(uint64_t period_ns); -static double g_rt_comp_ms; // 当前声明的实时计算量(ms;0 = 未声明) | Currently declared real-time computation amount (ms; 0 = not declared) -static double g_rt_period_ms; static void sleep_until_ns(uint64_t dl); static uint64_t present_period(const win_t *o); __attribute__((weak)) void dm_main_yield_stats(uint64_t *n, uint64_t *ns) { *n = 0; *ns = 0; } // 宿主 hle_thread.c 提供真值;图形单测里为 0 | The host's hle_thread.c provides the ground truth; 0 in graphics unit tests @@ -854,8 +1007,8 @@ NVN(nvnWindowAcquireTexture, NVNwindowAcquireTextureResult, NVNwindow *w, NVNsyn uint64_t at = *idx < 4 ? o->avail[*idx] : 0, now = dm_detclock_enabled() ? guest_ns() : now_ns(), wait = at > now ? at - now : 0; if (!dm_detclock_enabled()) { // 取图线程登记为时间约束线程(不再只在「来早了」时才登记:热态一直落后时也要声明) | Register the acquire thread as a time-constraint thread (no longer registered only when it "arrived early": it must also declare itself when it is constantly behind in the hot state) static uint64_t rt_period; uint64_t period = present_period(o); - if (period && rt_period != period) { rt_period = period; set_time_constraint(period); } - rt_comp_tick(period); + if (period && rt_period != period) { rt_period = period; set_time_constraint(&g_rt_main, period); } + rt_comp_tick(&g_rt_main, period); if (mtl_link_active()) { if (!mtl_link_wait_tick(period ? 2 * period : 33333333ull) && wait) sleep_until_ns(at); } // DM_PRESENT_LINK:节拍完全跟显示节拍(跑得快就等下一拍,落后立刻走);自己的 60 Hz 时钟只作等不到节拍时的兜底 | DM_PRESENT_LINK: pacing fully follows the display link (wait for the next display-link tick when running fast, go immediately when behind); our own 60 Hz clock is only the fallback when no display-link tick arrives else if (wait) sleep_until_ns(at); } else { // DM_DETCLOCK_PACE=1(画面闸门用):客体时钟按帧走的同时,每帧墙钟不短于一个步长——帧数与游戏内时间确定,后台加载线程每帧至少有一个步长的墙钟可用; | DM_DETCLOCK_PACE=1 (used by the screenshot gate): while the guest clock advances per frame, each frame's wall clock is no shorter than one step -- frame count and in-game time are deterministic, and the background loading thread has at least one step of wall clock available per frame; @@ -869,8 +1022,8 @@ NVN(nvnWindowAcquireTexture, NVNwindowAcquireTextureResult, NVNwindow *w, NVNsyn // 该张上一次出图还没被出图线程处理完(显示跟不上、落后一整轮交换链):等它归还,再交给游戏画 // The previous present of this texture has not yet been processed by the present thread (display cannot keep up, a whole swapchain round behind): wait for it to be returned, then hand it to the game to draw uint64_t tk = *idx < 4 ? o->ticket[*idx] : 0; - if (tk) { uint64_t w0 = now_ns(); mtl_present_wait(tk); g_pq_wait_ns += now_ns() - w0; } - if (s) { ((sync_t *)s)->fenced = 1; ((sync_t *)s)->fence = mtl_last_fence(); } // 交换链贴图在此前的提交完成后可用 | The swapchain texture becomes available once the commits before this point have completed + if (tk) { uint64_t w0 = now_ns(), rt = x_present_ticket(tk); if (rt) mtl_present_wait(rt); g_pq_wait_ns += now_ns() - w0; } // tk 是翻译队列的出图任务号 | tk is the translation queue's present job number + if (s) { ((sync_t *)s)->fenced = 1; ((sync_t *)s)->fence = x_fence(); } // 交换链贴图在此前的提交完成后可用 | The swapchain texture becomes available once the commits before this point have completed return NVN_WINDOW_ACQUIRE_TEXTURE_RESULT_SUCCESS; } @@ -968,10 +1121,16 @@ static void tsummary(uint64_t frame) { uint64_t aw = 0, ag = 0; int an = 0; void mtl_alloc_stats(uint64_t *, uint64_t *, int *); mtl_alloc_stats(&aw, &ag, &an); static uint64_t pyn, pyns; uint64_t yn = 0, yns = 0; dm_main_yield_stats(&yn, &yns); LOG("[nvn] 翻译细项 至帧 %llu:每帧提交 周期 %.2f M(每条指令 %.2f 周期)、CPU %.3f ms 其中内核态 %.3f ms、墙钟 %.3f ms;平均主频 %.2f GHz(周期 / CPU 时间);本线程 QoS %#x;分配器池 %d 个、累计等 GPU %llu 次;实时声明计算 %.2f ms;主线程让出 每帧 %.0f 次 / %.3f ms", frame, - cyc / 1e6 / nf, cyc / (double)(ci - pi), cpu / 1e6 / nf, (double)(ck - pk) / 1e6 / nf, (double)(cw - pw) / 1e6 / nf, cpu > 0 ? cyc / cpu : 0, (unsigned)qc, an, (unsigned long long)aw, g_rt_comp_ms, (double)(yn - pyn) / nf, (double)(yns - pyns) / 1e6 / nf); pyn = yn; pyns = yns; } + cyc / 1e6 / nf, cyc / (double)(ci - pi), cpu / 1e6 / nf, (double)(ck - pk) / 1e6 / nf, (double)(cw - pw) / 1e6 / nf, cpu > 0 ? cyc / cpu : 0, (unsigned)qc, an, (unsigned long long)aw, g_rt_main.comp_ms, (double)(yn - pyn) / nf, (double)(yns - pyns) / 1e6 / nf); pyn = yn; pyns = yns; } if (frame % 300 == 0) { unsigned wn = 0; uint32_t wq = dm_guest_work_qos(&wn); thread_extended_info_data_t xi; mach_msg_type_number_t xc = THREAD_EXTENDED_INFO_COUNT; int okx = thread_info(pthread_mach_thread_np(pthread_self()), THREAD_EXTENDED_INFO, (thread_info_t)&xi, &xc) == KERN_SUCCESS; thread_time_constraint_policy_data_t tp; mach_msg_type_number_t tc = THREAD_TIME_CONSTRAINT_POLICY_COUNT; boolean_t def = 0; int rt_live = thread_policy_get(pthread_mach_thread_np(pthread_self()), THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t)&tp, &tc, &def) == KERN_SUCCESS && !def; // def = 1:实时策略没在生效(没设上 / 被撤) | def = 1: the real-time policy is not in effect (never set / revoked) - LOG("[nvn] 线程策略:主线程 实时 计算 %.2f ms / 周期 %.2f ms,实时策略%s,当前优先级 %d(基础 %d,调度类 %d);工作线程 %u 条 QoS %#x;出图 QoS %#x", g_rt_comp_ms, g_rt_period_ms, rt_live ? "在生效" : "未生效", okx ? xi.pth_curpri : -1, okx ? xi.pth_priority : -1, okx ? xi.pth_policy : -1, wn, wq, mtl_present_qos()); } + LOG("[nvn] 线程策略:主线程 实时 计算 %.2f ms / 周期 %.2f ms,实时策略%s,当前优先级 %d(基础 %d,调度类 %d);工作线程 %u 条 QoS %#x;出图 QoS %#x", g_rt_main.comp_ms, g_rt_main.period_ms, rt_live ? "在生效" : "未生效", okx ? xi.pth_curpri : -1, okx ? xi.pth_priority : -1, okx ? xi.pth_policy : -1, wn, wq, mtl_present_qos()); + if (g_x_port) { // 翻译线程:声明、实时策略在不在生效、当前 / 基础优先级、QoS(降级看这几项;在不在大核看「翻译细项」行的平均主频) | Translation thread: declaration, whether the real-time policy is in effect, current / base priority, QoS (check these for demotion; for whether it is on a performance core, see the average clock on the "translation detail" line) + thread_extended_info_data_t yi; mach_msg_type_number_t yc = THREAD_EXTENDED_INFO_COUNT; int oky = thread_info(g_x_port, THREAD_EXTENDED_INFO, (thread_info_t)&yi, &yc) == KERN_SUCCESS; + thread_time_constraint_policy_data_t yp; mach_msg_type_number_t ytc = THREAD_TIME_CONSTRAINT_POLICY_COUNT; boolean_t ydef = 0; int y_live = thread_policy_get(g_x_port, THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t)&yp, &ytc, &ydef) == KERN_SUCCESS && !ydef; + qos_class_t yq = QOS_CLASS_UNSPECIFIED; int yr = 0; pthread_get_qos_class_np(g_x_thr, &yq, &yr); + LOG("[nvn] 线程策略:翻译线程 实时 计算 %.2f ms / 周期 %.2f ms,实时策略%s,当前优先级 %d(基础 %d,调度类 %d);QoS %#x", g_rt_xlat.comp_ms, g_rt_xlat.period_ms, y_live ? "在生效" : "未生效", + oky ? yi.pth_curpri : -1, oky ? yi.pth_priority : -1, oky ? yi.pth_policy : -1, (unsigned)yq); } } py = cy; pk = ck; pw = cw; } pi = ci; pc = cc; pd = dr_; pf = frame; } uint64_t up, re, fa, pr; mtl_pkg_stats(&up, &re); nvn_dirty_stats(&fa, &pr); @@ -1022,29 +1181,28 @@ static void slow_emit(uint64_t f) { // The computation used to be hard-coded at 2 ms, while the game main thread (game logic + recording + submit replay) takes about 10 ms per frame when hot - a 5× gap between declared and actual: // a real-time thread that exceeds its declared computation gets demoted by the system, and the performance controller also sets frequency from the declaration (this declaration is how the system learns the frame deadline and the workload). // DM_RT_COMP= fixes the declaration; default auto = every 120 frames take the p90 of this thread's per-frame CPU time and re-declare if it differs from the declared value by > 15% (capped at 0.9 × period). -static void set_time_constraint_comp(uint64_t period_ns, uint64_t comp_ns) { +static void set_time_constraint_comp(rt_decl *d, uint64_t period_ns, uint64_t comp_ns) { static mach_timebase_info_data_t tb; if (!tb.denom) mach_timebase_info(&tb); if (comp_ns < 1000000ull) comp_ns = 1000000ull; if (comp_ns > period_ns * 9 / 10) comp_ns = period_ns * 9 / 10; thread_time_constraint_policy_data_t p = { .period = (uint32_t)(period_ns * tb.denom / tb.numer), .computation = (uint32_t)(comp_ns * tb.denom / tb.numer), .constraint = (uint32_t)(period_ns * tb.denom / tb.numer), .preemptible = 1}; kern_return_t kr = thread_policy_set(pthread_mach_thread_np(pthread_self()), THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t)&p, THREAD_TIME_CONSTRAINT_POLICY_COUNT); - if (kr == KERN_SUCCESS) { g_rt_comp_ms = comp_ns / 1e6; g_rt_period_ms = period_ns / 1e6; } - LOG("[nvn] 出图线程时间约束策略(周期 %.3f ms、计算 %.3f ms)%s", period_ns / 1e6, comp_ns / 1e6, kr == KERN_SUCCESS ? "已设" : "设置失败"); + if (kr == KERN_SUCCESS) { d->comp_ms = comp_ns / 1e6; d->period_ms = period_ns / 1e6; } + LOG("[nvn] %s时间约束策略(周期 %.3f ms、计算 %.3f ms)%s", d->who, period_ns / 1e6, comp_ns / 1e6, kr == KERN_SUCCESS ? "已设" : "设置失败"); } static int rt_comp_fixed_ms(void) { static int v = -2; if (v == -2) { const char *e = getenv("DM_RT_COMP"); v = e && *e && strcmp(e, "auto") ? atoi(e) : -1; } return v; } // −1 = auto -static void set_time_constraint(uint64_t period_ns) { int f = rt_comp_fixed_ms(); set_time_constraint_comp(period_ns, f > 0 ? (uint64_t)f * 1000000ull : 2000000ull); } // 首次:固定值,或 auto 的起始值 2 ms | first time: the fixed value, or auto's starting value of 2 ms +static void set_time_constraint(rt_decl *d, uint64_t period_ns) { int f = rt_comp_fixed_ms(); set_time_constraint_comp(d, period_ns, f > 0 ? (uint64_t)f * 1000000ull : 2000000ull); } // 首次:固定值,或 auto 的起始值 2 ms | first time: the fixed value, or auto's starting value of 2 ms // 每帧在取图处调:记本线程自上次以来的 CPU 时间;auto 模式下按 p90 重新声明 // Called every frame at acquire: records this thread's CPU time since the last call; in auto mode re-declares based on p90 -static void rt_comp_tick(uint64_t period_ns) { - if (rt_comp_fixed_ms() > 0 || !period_ns || !g_rt_comp_ms) return; - static uint64_t last; static double win[120]; static int n; - uint64_t c = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID); if (!last) { last = c; return; } - win[n++] = (double)(c - last) / 1e6; last = c; - if (n < 120) return; - double v[120]; memcpy(v, win, sizeof v); qsort(v, 120, sizeof *v, dcmp); n = 0; +static void rt_comp_tick(rt_decl *d, uint64_t period_ns) { // 在被声明的那条线程上调(读本线程 CPU 时钟) | Call on the thread being declared (reads this thread's CPU clock) + if (rt_comp_fixed_ms() > 0 || !period_ns || !d->comp_ms) return; + uint64_t c = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID); if (!d->last) { d->last = c; return; } + d->win[d->n++] = (double)(c - d->last) / 1e6; d->last = c; + if (d->n < 120) return; + double v[120]; memcpy(v, d->win, sizeof v); qsort(v, 120, sizeof *v, dcmp); d->n = 0; double p90 = v[107], comp = p90 * 1.25, cap = period_ns * 0.9 / 1e6; if (comp > cap) comp = cap; if (comp < 1) comp = 1; - if (comp > g_rt_comp_ms * 1.15 || comp < g_rt_comp_ms * 0.85) set_time_constraint_comp(period_ns, (uint64_t)(comp * 1e6)); + if (comp > d->comp_ms * 1.15 || comp < d->comp_ms * 0.85) set_time_constraint_comp(d, period_ns, (uint64_t)(comp * 1e6)); } static void sleep_until_ns(uint64_t dl) { // 单调时钟上的绝对时刻 | absolute time on the monotonic clock static mach_timebase_info_data_t tb; if (!tb.denom) mach_timebase_info(&tb); @@ -1094,7 +1252,9 @@ NVN(nvnQueuePresentTexture, void, NVNqueue *q, NVNwindow *w, int idx) { present_cfg(o); gfx_enter(); uint64_t t0 = now_ns(); - if (idx >= 0 && idx < o->ntex && idx < 4) o->ticket[idx] = mtl_present(CTX(o->tex[idx]), present_period(o) / 1e9, o->crop); // 只入队,立即返回 | enqueue only, return immediately + if (idx >= 0 && idx < o->ntex && idx < 4) { // 只入队,立即返回;ticket 存翻译队列的任务号 | Enqueue only and return at once; ticket holds the translation queue's job number + xjob j = {XJ_PRESENT, 0, NULL, snap_tex(o->tex[idx]), present_period(o) / 1e9}; memcpy(j.crop, o->crop, sizeof j.crop); + o->ticket[idx] = x_push(&j); } gfx_leave(); atomic_fetch_add(&g_nvn_ns, now_ns() - t0); uint64_t f = g_frame, ps, dr; mtl_stats(&ps, &dr); @@ -1180,7 +1340,9 @@ NVN(nvnQueuePresentTexture, void, NVNqueue *q, NVNwindow *w, int idx) { prev_in = t0; prev_pass = ps; prev_draw = dr; dump_frame(); if (g_frame % TWIN == 0) tsummary(g_frame); - mtl_set_frame(g_frame); + { static uint64_t pc, py, pf; uint64_t i_, y_, c_ = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID); thr_counts(&i_, &y_); // 主线程(游戏线程)的每帧 CPU 与平均主频:与「翻译细项」行的翻译线程对照,分「整机降频」还是「翻译线程被放小核」 | Per-frame CPU and average clock of the main (game) thread: compared with the translation thread on the "translation detail" line, to tell "whole-chip downclocking" from "translation thread placed on an efficiency core" + if (g_frame % TWIN == 0) { if (pf && g_frame > pf && c_ > pc) LOG("[nvn] 主线程 至帧 %llu:每帧 CPU %.2f ms,平均主频 %.2f GHz(周期 / CPU 时间)", g_frame, (c_ - pc) / 1e6 / (double)(g_frame - pf), (double)(y_ - py) / (double)(c_ - pc)); pc = c_; py = y_; pf = g_frame; } } + { xjob j = {XJ_FRAME}; j.frame = g_frame; j.period = present_period(o) / 1e9; x_push(&j); } // 帧号随队列生效(见翻译队列说明) | The frame number takes effect in queue order (see the translation queue notes) // 真机语义:出图只入队、立即返回;本帧显示时刻按节拍器排,该贴图到「显示时刻 + 一个周期」才可再获取(阻塞在 AcquireTexture) // Real-device semantics: present only enqueues and returns immediately; this frame's display time is scheduled by the pacer, and the texture can be acquired again only at "display time + one period" (blocking in AcquireTexture) uint64_t period = present_period(o), now = dm_detclock_enabled() ? guest_ns() : now_ns(); diff --git a/dm/gfx/nvn/nvn_mtl.m b/dm/gfx/nvn/nvn_mtl.m index f93defe..0c999e4 100644 --- a/dm/gfx/nvn/nvn_mtl.m +++ b/dm/gfx/nvn/nvn_mtl.m @@ -2105,7 +2105,7 @@ static void shmap_load(void) { // Warm-up entry: built in the background, waiting to be taken by the submit thread. vs / fs are strong references (in pso they are only raw pointers, and the background dictionary is released when the task ends) @interface WarmItem : NSObject { @public int kind; NSString *key, *vs_key, *fs_key; NvShader *shader, *vs, *fs; pso_key pso; id fsfn; id object; } @end @implementation WarmItem @end -static NSMutableDictionary *g_shcache; +static NSMutableDictionary *g_shcache; static _Atomic uint32_t g_shcache_n; // 表只在提交线程上读写;条数另记一份原子数给别的线程读(资源计数) | The tables are read and written only on the submit thread; a separate atomic count is kept for other threads to read (resource counts) static void c1_store(NvShader *o) { size_t len = o->rf.c1_len; @@ -2286,7 +2286,7 @@ static NvShader *shader_get(NSString *pc, int stage) { if (o) return o; uint64_t bt = bp_now(); o = shader_load(pc, stage); if (!o) return nil; - g_shcache[pc] = o; + g_shcache[pc] = o; atomic_fetch_add(&g_shcache_n, 1); pso_record("S\t%s\t%d\n", pc.UTF8String, stage); pso_user_record("S\t%s\t%d\n", pc.UTF8String, stage); g_bp_lib_n++; g_bp_lib_ns += bp_now() - bt; @@ -4751,17 +4751,17 @@ static void warm_claim(void) { for (WarmItem *item in items) { if (item->kind == 0) { if (!g_shcache) g_shcache = [NSMutableDictionary dictionary]; - if (!g_shcache[item->key]) { g_shcache[item->key] = item->shader; g_warm_claim_shaders++; } + if (!g_shcache[item->key]) { g_shcache[item->key] = item->shader; atomic_fetch_add(&g_shcache_n, 1); g_warm_claim_shaders++; } } else if (item->kind == 1) { if (!g_shcache) g_shcache = [NSMutableDictionary dictionary]; NvShader *vs = g_shcache[item->vs_key], *fs = item->fs_key.length ? g_shcache[item->fs_key] : nil; - if (!vs) { vs = item->vs; g_shcache[item->vs_key] = vs; } - if (item->fs_key.length && !fs) { fs = item->fs; g_shcache[item->fs_key] = fs; } + if (!vs) { vs = item->vs; g_shcache[item->vs_key] = vs; atomic_fetch_add(&g_shcache_n, 1); } + if (item->fs_key.length && !fs) { fs = item->fs; g_shcache[item->fs_key] = fs; atomic_fetch_add(&g_shcache_n, 1); } item->pso.vs = (__bridge void *)vs; item->pso.fs = (__bridge void *)fs; if (!hm_get_id(&g_pso, &item->pso)) { hm_put_id(&g_pso, &item->pso, item->object); g_warm_claim_rps++; } } else { NvShader *cs = g_shcache[item->key]; - if (!cs) { cs = item->shader; if (!g_shcache) g_shcache = [NSMutableDictionary dictionary]; g_shcache[item->key] = cs; } + if (!cs) { cs = item->shader; if (!g_shcache) g_shcache = [NSMutableDictionary dictionary]; g_shcache[item->key] = cs; atomic_fetch_add(&g_shcache_n, 1); } const void *key = (__bridge const void *)cs; if (!hm_get_id(&g_cps, &key)) { hm_put_id(&g_cps, &key, item->object); g_warm_claim_cps++; } } @@ -4888,6 +4888,7 @@ static void copy_t2b(const p_copy_b2t *c) { // CPU 读贴图(ReadTexels):预排布贴图以池内存为真值,解排布直读;其余从 MTLTexture blit 读回(调用方已按 NVN 规矩等过 GPU) // CPU texture read (ReadTexels): for packaged textures the pool memory is the ground truth, de-layout and read directly; the rest are read back from the MTLTexture by blit (the caller has already waited for the GPU per NVN rules) void mtl_read_texels(const tex_t *t, unsigned level, unsigned layer0, const NVNcopyRegion *r, uint8_t *dst, size_t row, size_t img) { + if (!on_sub_thread()) while (atomic_load(&g_up_pending)) usleep(200); // 翻译在翻译线程:调用方已排空队列(批已随提交冲刷),这里只等上传在 GPU 上做完(提交线程上由 q_cb 冲刷并等) | Translation runs on the translation thread: the caller has already drained the queue (batches were flushed with the submit), so here we only wait for uploads to finish on the GPU (on the submit thread q_cb flushes and waits) xv_check(t->serial, level, layer0, "CPU读回"); PD("U cpu_read ser=%llu lv%u sl%u xyz=%d,%d,%d size=%d,%d,%d dst=%p row=%lu img=%lu", t->serial, level, layer0, r->xoffset, r->yoffset, r->zoffset, r->width, r->height, r->depth, dst, (unsigned long)row, (unsigned long)img); int bw, bh, bpb = nvn_fmt_bpb(t->d.format, &bw, &bh); @@ -5106,7 +5107,13 @@ static const char *cctx_snap(void) { // State constants / buffer updates / events / counters / texture uploads execute as usual (the UI pass needs them, the game is waiting). int g_frz_on = -1; static int g_frz_phase = 2, g_frz_drop, g_frz_seen_ds; static uint64_t g_frz_full_n, g_frz_skip_n; -void mtl_world_frozen(int on) { g_frz_on = on != 0; } +// 宿主在游戏线程上写的两个画法开关(冻结位、强制全画)先记成请求,提交入队时锁存进任务(mtl_host_latch),翻译线程执行那次提交前生效(mtl_host_apply): +// 生效时机与同步翻译时一样落在两次提交之间,不会在翻译途中翻转(回放每条操作都读冻结位;强制全画计数回放里自减,宿主直接写会丢) +// The two drawing switches the host writes on the game thread (freeze bit, force full draw) are first recorded as requests, latched into the job when the submit is enqueued (mtl_host_latch), and take effect before the translation thread runs that submit (mtl_host_apply): +// they take effect between two submits just as with synchronous translation and never flip in the middle of translation (replay reads the freeze bit for every operation; the force-full-draw counter is decremented in replay, and a direct write by the host would lose one) +static _Atomic int g_frz_req = -1, g_force_req; +void mtl_world_frozen(int on) { atomic_store(&g_frz_req, on != 0); } +uint64_t mtl_host_latch(void) { return (uint64_t)(uint32_t)(atomic_load(&g_frz_req) + 1) | (uint64_t)(uint32_t)atomic_exchange(&g_force_req, 0) << 32; } static int frz_wanted(void) { if (g_frz_on < 0) { const char *e = getenv("DM_NVN_TEST_FRZ"); g_frz_on = e && atoi(e); if (g_frz_on) MLOG("DM_NVN_TEST_FRZ:世界冻结状态位由测试开关顶替(常开)"); } tbdr_on(); return g_frz_on > 0 && tbdr_on() && g_ruler_truth <= 0; } // ---------- 运行时外推(省电画法;不给玩家开关;线上出过卡顿缺陷,现缺省关,A17 上有不卡的证据再开)---------- // 3D 隔帧:全画帧照常画,并在附件被挪作他用之前拷下不透明 HDR(468)、主深度模板、色调映射后的 468、FXAA 后的 469; @@ -5135,7 +5142,8 @@ static struct { int env, frame, filt, first, hdrp, mainp_seen, skipall, oit_seen static int rt_want(void); static void rt_toggle_poll(void) { static int tg = -1; if (tg < 0) { const char *e = getenv("DM_RT_AB_TOGGLE"); tg = e ? atoi(e) : 0; (void)rt_want(); } // 首次顺带读 DM_RT_AB(真机上世界冻结位早早置 0,frz_op 不一定被调到) // 测试:每 tg 秒按墙钟在 A / B 之间来回切 | On first call also read DM_RT_AB (on a real device the world-freeze bit is set to 0 very early, so frz_op is not necessarily called) // test: switch back and forth between A / B every tg seconds by wall clock if (tg > 0) { int v = (int)((time(NULL) / tg) & 1); if (v != g_dm_rt_ab) { g_dm_rt_ab = v; MLOG("DM_RT_AB_TOGGLE:画法切到 %s", v ? "B" : "A"); } } } -void mtl_rt_force_full(int n) { g_rt.force_full = n; } // 宿主调:要换 3D 渲染比例等画面整体变化前,之后 n 帧一律全画 | Called by the host: before an overall picture change such as switching the 3D render scale, the following n frames are all fully drawn +void mtl_rt_force_full(int n) { atomic_store(&g_force_req, n); } // 宿主调:要换 3D 渲染比例等画面整体变化前,之后 n 帧一律全画(随下一次提交生效) | Called by the host: before a change to the whole picture such as switching the 3D render scale, draw everything for the next n frames (takes effect with the next submit) +void mtl_host_apply(uint64_t v) { int frz = (int)(uint32_t)v - 1, force = (int)(v >> 32); if (frz >= 0) g_frz_on = frz; if (force) g_rt.force_full = force; } // ---------- 省电模式(30 帧)---------- // 开:显示节拍对象改 30 Hz(帧率范围 30–30,ProMotion 屏跟着降刷新率;front_ios.m 的帧率提示一起降),游戏每拍出一帧;运行时外推关(每帧真画)。 // 游戏逻辑本来就按 25 拍 / 秒走、单位位置按时间插值,30 帧下没有重复帧(真机实测:每帧镜头位移的变异系数 30 帧 0.292、60 帧 0.296)。 @@ -5402,7 +5410,7 @@ void mtl_res_snapshot(mtl_res_count *out) { out->pso = g_pso.n; out->cps = g_cps.n; out->dss = g_dss.n; - out->shaders = (uint32_t)(g_shcache ? g_shcache.count : 0); + out->shaders = atomic_load(&g_shcache_n); // 资源计数在宿主线程上取,回放在翻译线程上改表 | Resource counts are taken on the host thread while replay changes the tables on the translation thread os_unfair_lock_lock(&g_c1_lock); out->c1_bufs = (uint32_t)(g_c1_banks.count + g_c1_exclusive); out->c1_alloc = g_c1_alloc_bytes; out->c1_data = g_c1_data_bytes; os_unfair_lock_unlock(&g_c1_lock); diff --git a/dm/gfx/nvn/nvn_obj.h b/dm/gfx/nvn/nvn_obj.h index ee45b29..37a78df 100644 --- a/dm/gfx/nvn/nvn_obj.h +++ b/dm/gfx/nvn/nvn_obj.h @@ -33,6 +33,7 @@ typedef struct { typedef struct { uint32_t magic; nvn_texdesc d; nvn_texlayout L; uint8_t *mem; pool_t *pool; int64_t off; uint8_t has_layout, layout[8]; uint64_t serial; // 初始化序号:回放层按它在宿主表里找 MTLTexture(游戏可能按值拷贝对象,不能存对象指针) | Initialization serial: the replay layer uses it to find the MTLTexture in the host table (the game may copy the object by value, so object pointers cannot be stored) + const void *snap; // 本序号的不可变副本(hle_nvn.c snap_tex):命令载荷存它,不存游戏对象地址 | This serial's immutable snapshot (hle_nvn.c snap_tex): command payloads store it, not the game object's address } tex_t; FITS(tex_t, NVNtexture); typedef struct { uint8_t set_levels, set_layers, set_format, set_target; int32_t base_level, nlevels, min_layer, nlayers, format, target; } view_t; FITS(view_t, NVNtextureView); @@ -43,7 +44,7 @@ typedef struct { uint8_t minf, magf, ws, wt, wr, cmp_mode, cmp_func; float lod_m typedef struct { NVNdevice *dev; samp_par p; } samp_builder_t; FITS(samp_builder_t, NVNsamplerBuilder); typedef struct { uint32_t magic; samp_par p; } samp_t; FITS(samp_t, NVNsampler); -typedef struct { uint32_t magic, nstage; NVNshaderData sd[6]; uint64_t serial; } prog_t; FITS(prog_t, NVNprogram); // serial:回放层解析结果的表键 | serial: table key for the replay layer's resolved result +typedef struct { uint32_t magic, nstage; NVNshaderData sd[6]; uint64_t serial; const void *snap; } prog_t; FITS(prog_t, NVNprogram); // serial:回放层解析结果的表键;snap:本序号的不可变副本(同 tex_t) | serial: table key for the replay layer's resolved results; snap: this serial's immutable snapshot (same as tex_t) typedef struct { uint32_t magic, fenced; uint64_t fence; } sync_t; FITS(sync_t, NVNsync); typedef struct { const pool_t *pool; int64_t off; } ev_builder_t; FITS(ev_builder_t, NVNeventBuilder); @@ -94,8 +95,8 @@ enum { OP_STENCIL, OP_POLY_OFFSET, OP_DRAW, OP_DRAW_IDX, OP_DISPATCH, OP_BARRIER, OP_SET_TEX_POOL, OP_SET_SAMP_POOL, OP_COPY_B2T, OP_COPY_STRIDE, OP_BLEND_COLOR, OP_COPY_T2B, OP_BIND_IMG, OP_COPY_T2T, OP_RESET_COUNTER, OP_CLEAR_TEX, OP_COUNT_ }; -// 载荷(紧跟 op_hdr) -// Payload (immediately follows op_hdr) +// 载荷(紧跟 op_hdr)。贴图 / 程序指针都指向录制时按序号留下的不可变副本(snap_tex / snap_prog),游戏之后改写或重建对象不影响已录的命令 +// Payload (right after op_hdr). Texture / program pointers point to the immutable snapshots kept by serial at record time (snap_tex / snap_prog); later rewrites or rebuilds of the object by the game do not affect recorded commands typedef struct { int32_t n; const tex_t *color[8]; view_t cview[8]; uint8_t has_cview[8]; const tex_t *depth; view_t dview; uint8_t has_dview; } p_set_rt; typedef struct { int32_t index, mask; float rgba[4]; } p_clear_color; typedef struct { float depth; int32_t depth_mask, stencil, stencil_mask; } p_clear_ds; @@ -136,6 +137,8 @@ void mtl_set_tex_pool_n(int n); // 贴图描述符池 // 计时埋点(Mac / iOS 共用):提交按帧号打标;GPU 时间 = 该帧全部命令缓冲 GPUEnd−GPUStart 之和,全部完成后才可读(否则 −1) // Timing instrumentation (shared by Mac / iOS): submissions are tagged with the frame number; GPU time = sum of GPUEnd−GPUStart over all of that frame's command buffers, readable only after all complete (otherwise −1) void mtl_set_frame(uint64_t f); +uint64_t mtl_host_latch(void); // 游戏线程提交入队时锁存宿主写的画法开关(冻结位 / 强制全画),随任务带到翻译线程 | When the game thread enqueues a submit it latches the host-written drawing switches (freeze bit / force full draw), carried with the job to the translation thread +void mtl_host_apply(uint64_t v); // 翻译线程执行那次提交前生效 | Takes effect before the translation thread runs that submit void mtl_ub_present(double iv_ms); // 同进程交替测量(DM_NVN_UB):出图线程每帧报实际上屏间隔 | Same-process alternating measurement (DM_NVN_UB): the present thread reports the actual present interval every frame double mtl_gpu_ms(uint64_t f); void mtl_sub_index(const uint64_t *h, int n); // 提交开始:按回放顺序建写回前瞻索引(nvn_mtl.m) | Start of submission: build the store lookahead index in replay order (nvn_mtl.m) diff --git a/dm/gfx/tests/t_nvn.c b/dm/gfx/tests/t_nvn.c index dc3f798..2dd7fe7 100644 --- a/dm/gfx/tests/t_nvn.c +++ b/dm/gfx/tests/t_nvn.c @@ -302,7 +302,7 @@ int main(void) { for (int i = 0; i < 24; i++) P(nvnCommandBufferCopyBufferToBuffer)(&cb, (NVNbufferAddress)heap, (NVNbufferAddress)(heap + big), big, 0); NVNcommandHandle hbusy = P(nvnCommandBufferEndRecording)(&cb); P(nvnQueueSubmitCommands)(&q, 1, &hbusy); - uint64_t f = mtl_last_fence(); + uint64_t f = x_fence(); // 游戏经 FenceSync 拿到的栅栏值(翻译异步:可能还没翻译到) | Fence value the game gets from FenceSync (translation is asynchronous: it may not have been translated yet) int busy_before = !mtl_wait(f, 0); dm_gfx_suspend(1); EXPECT("挂起前 GPU 确实在忙(零超时等待未完成)", 1, busy_before); @@ -359,6 +359,52 @@ int main(void) { mtl_present_test_stall(0); mtl_present_flush(); } + // 8. 对象副本:录完命令后游戏 Finalize 并在同址重建贴图 / 换程序着色器,已录命令里读到的仍是录制时的内容;退役副本过 SNAP_KEEP 次提交才回收 + // 8. Object snapshots: after commands are recorded the game Finalizes and rebuilds a texture at the same address / swaps a program's shaders; recorded commands still read what was there at record time; retired snapshots are reclaimed only after SNAP_KEEP submits + { + NVNtextureBuilder b; NVNtexture tx; P(nvnTextureBuilderSetDevice)(&b, &dev); P(nvnTextureBuilderSetDefaults)(&b); + P(nvnTextureBuilderSetWidth)(&b, 8); P(nvnTextureBuilderSetHeight)(&b, 4); P(nvnTextureBuilderSetFormat)(&b, NVN_FORMAT_RGBA8); P(nvnTextureInitialize)(&tx, &b); + NVNprogram pg; NVNshaderData sd[2]; memset(sd, 0, sizeof sd); P(nvnProgramInitialize)(&pg, &dev); P(nvnProgramSetShaders)(&pg, 1, sd); + const NVNtexture *ct[1] = {&tx}; + P(nvnCommandBufferBeginRecording)(&cb); + P(nvnCommandBufferSetRenderTargets)(&cb, 1, ct, NULL, NULL, NULL); + P(nvnCommandBufferBindProgram)(&cb, &pg, NVN_SHADER_STAGE_VERTEX_BIT); + NVNcommandHandle hs = P(nvnCommandBufferEndRecording)(&cb); + const p_set_rt *rt = NULL; const p_bind_program *bp = NULL; + for (const uint8_t *p = (const uint8_t *)hs; p;) { // 按记录格式走:JUMP 跟到下一段,END 结束 | Walk the record format: follow JUMP to the next segment, stop at END + op_hdr h; memcpy(&h, p, sizeof h); + if (h.op == OP_END) break; + if (h.op == OP_JUMP) { memcpy(&p, p + 8, 8); continue; } + if (h.op == OP_SET_RT) rt = (const p_set_rt *)(p + 8); + if (h.op == OP_BIND_PROGRAM) bp = (const p_bind_program *)(p + 8); + p += h.size; + } + EXPECT("录到 SET_RT 与 BIND_PROGRAM", 2, (rt != NULL) + (bp != NULL)); + if (rt && bp) { + const tex_t *s0 = rt->color[0]; + EXPECT("SET_RT 存的不是游戏对象地址", 1, (const void *)s0 != (const void *)&tx); + EXPECT("副本宽 8", 8, s0->d.width); + NVNtexture cp; memcpy(&cp, &tx, sizeof cp); + EXPECT("按值拷来的同序号对象共用同一副本", 1, snap_tex(&cp) == s0); + uint64_t ser0 = s0->serial; + P(nvnTextureFinalize)(&tx); P(nvnTextureBuilderSetWidth)(&b, 16); P(nvnTextureBuilderSetHeight)(&b, 16); P(nvnTextureInitialize)(&tx, &b); + EXPECT("同址重建后已录命令仍读到宽 8", 8, rt->color[0]->d.width); + EXPECT("同址重建后已录命令仍是旧序号", 1, rt->color[0]->serial == ser0); + const tex_t *s1 = snap_tex(&tx); + EXPECT("重建后再录取到新副本、宽 16", 16, s1 != s0 ? (long long)s1->d.width : -1); + P(nvnProgramSetShaders)(&pg, 2, sd); + EXPECT("换着色器后已录命令的程序仍是 1 段", 1, bp->prog->nstage); + x_drain(); uint64_t s_at = atomic_load(&g_x_subs); // 退役盖戳 = 当时已入队的提交数;回收按已执行数 | Retire stamp = number of submits enqueued at that time; reclaim goes by the number executed + for (int k = 1; k < SNAP_KEEP; k++) snap_tick(s_at + k); + EXPECT("退役后 SNAP_KEEP−1 次提交:副本还在", 8, s0->d.width); + snap_tick(s_at + SNAP_KEEP); + EXPECT("退役后 SNAP_KEEP 次提交:副本已回收(序号清零)", 0, s0->serial); + const tex_t *s2 = snap_tex(&cp); + EXPECT("回收后旧拷贝对象再取副本:宽 8、序号是它自己的", 8, s2->serial == ((const tex_t *)&cp)->serial ? (long long)s2->d.width : -1); + } + P(nvnTextureFinalize)(&tx); P(nvnProgramFinalize)(&pg); + } + // 7. 未实现函数:返回 0、报红、只报一次 // 7. Unimplemented functions: return 0, report a failure, report only once unsigned ui = 0; while (strcmp(nvn_names[ui], "nvnBufferBuilderSetDefaults")) ui++; diff --git a/dm/gfx/tests/t_present_crop.m b/dm/gfx/tests/t_present_crop.m index 3955a7b..3594fa3 100644 --- a/dm/gfx/tests/t_present_crop.m +++ b/dm/gfx/tests/t_present_crop.m @@ -71,7 +71,7 @@ int main(void) { @autoreleasepool { NVNT_nvnQueuePresentTexture present=(NVNT_nvnQueuePresentTexture)get(NULL,"nvnQueuePresentTexture"); tex_t tex={.serial=10001};tex.d.width=tex.d.height=8;tex.d.depth=tex.d.levels=1;tex.d.format=NVN_FORMAT_RGBA8;tex.d.target=NVN_TEXTURE_TARGET_2D;serial_put(tex.serial,src); win_t win={.ntex=1};win.tex[0]=(NVNtexture *)&tex;set((NVNwindow *)&win,4,4,4,4); - mtl_present_test_stall(100000000);present(NULL,(NVNwindow *)&win,0);uint64_t tk=win.ticket[0];set((NVNwindow *)&win,0,0,8,8); + mtl_present_test_stall(100000000);present(NULL,(NVNwindow *)&win,0);set((NVNwindow *)&win,0,0,8,8);uint64_t tk=x_present_ticket(win.ticket[0]); // ticket 存翻译队列任务号,换成出图线程票号 | ticket holds the translation queue's job number; swap it for the present thread's ticket #ifdef CROP_LEGACY_HEADER EXPECT("旧队列结构没有四参数副本空间(结构检查)",1,sizeof(pq_item)>=sizeof(tex_t)+sizeof(double)+sizeof(uint64_t)+sizeof br); #else diff --git a/dm/host/diag.c b/dm/host/diag.c index edfdfd6..8c53f1d 100644 --- a/dm/host/diag.c +++ b/dm/host/diag.c @@ -1191,15 +1191,6 @@ int dm_request_save(void) { *(volatile uint64_t *)(uintptr_t)(g_lastG + 0x5800) = 1; return 1; } -// 退出前存盘用(Mac App):单机暂停着(暂停菜单 / 大秘境面板开着,原版界面状态字节 [main+0x2d5ff51] | [main+0x2d5ff67] 非 0,见 dm_rift_ui.c)时游戏不跑拍, -// 上面拨的那次存盘等不到。把这两个字节清掉让拍接着走;只在进程马上要退出时调(不写回)。返回清之前是否暂停着 -// For saving before exit (Mac App): while single-player is paused (pause menu / rift panel open, original UI state bytes [main+0x2d5ff51] | [main+0x2d5ff67] non-zero, see dm_rift_ui.c) the game does not tick, -// so the save requested above would never happen. Clear these two bytes so the ticks continue; called only when the process is about to exit (not written back). Returns whether it was paused before clearing -int dm_unpause_for_exit(void) { - uint8_t *b = NULL; for (int i = 0; i < g_nmod; i++) if (!strcmp(g_mod[i].name, "main")) b = (uint8_t *)g_mod[i].base; - if (!b || !in_game()) return 0; - volatile uint8_t *f = b + 0x2d5ff51, *g = b + 0x2d5ff67; int was = *f || *g; *f = 0; *g = 0; return was; -} // 游戏是不是停着(暂停菜单 / 大秘境选层页这类开着:同上两个界面状态字节)。不在局内返回 0 // Whether the game is stopped (pause menu / Greater Rift level-selection page and the like open: the same two UI state bytes as above). Returns 0 when not in a game int dm_game_paused(void) { uint8_t *b = NULL; for (int i = 0; i < g_nmod; i++) if (!strcmp(g_mod[i].name, "main")) b = (uint8_t *)g_mod[i].base; return b && in_game() && (*(volatile uint8_t *)(b + 0x2d5ff51) | *(volatile uint8_t *)(b + 0x2d5ff67)); } @@ -1635,18 +1626,70 @@ void dm_freeze_frame(int want) { static int idle; if (!atomic_load(&g_dm_frozen) || !atomic_load(&g_frz_by_panel) || want) { idle = 0; return; } if (++idle < 10) return; idle = 0; atomic_store(&g_dm_frozen, 0); atomic_store(&g_frz_by_panel, 0); if (mtl_world_frozen) mtl_world_frozen(0); LOG("面板冻结:解冻(面板已不在屏上而拍入口没在走:原版暂停 / 退出 / 换角色)"); } +static int g_frz_on; // 四个冻结入口门已挂上(freeze_attach) | The four freeze entry gates are attached (freeze_attach) +static int freeze_attach(void) { // 挂冻结用的四个入口门(产物里有门 10–13 才行),挂过就不再挂。返回 1 = 能冻 | Attach the four entry gates used for freezing (needs gates 10–13 in the product); attached only once. Returns 1 = can freeze + static int tried; if (tried) return g_frz_on; tried = 1; + g_frz_on = gate_obs_present(OBS_FREEZE_WORLD) && gate_obs_present(OBS_FREEZE_CLIENT) && gate_obs_present(OBS_FREEZE_ANIM) && gate_obs_present(OBS_FREEZE_RENDER); + if (g_frz_on) { gate_obs_set(OBS_FREEZE_WORLD, freeze_world_obs); gate_obs_set(OBS_FREEZE_CLIENT, freeze_client_obs); gate_obs_set(OBS_FREEZE_ANIM, freeze_anim_obs); gate_obs_set(OBS_FREEZE_RENDER, freeze_render_obs); } + return g_frz_on; +} +// 暂停菜单开着进后台时存一次盘:原版单机暂停时游戏不走拍,前端请的那次存盘要等下一拍,进后台 2.5 秒等不到(10142104 日志 4 次), +// 上次自动存盘到开暂停之间的进度在后台被系统回收时会丢。做法:先冻住世界(同面板冻结:世界 / 客户端 / 动画 / 渲染四个入口换成空跑,拍号不前进——怪不动、时间不走), +// 再临时放开原版暂停的两个界面状态字节让拍走起来、执行那次存盘;等到提交(前端 background_wait_save)后写回两个字节、解冻。前端在主线程调 +// Save once when going to the background with the pause menu open: in single-player pause the original game does not tick, so the save the front end asks for waits for the next tick and the 2.5 s background wait never sees it (seen 4 times in a player's log); +// progress between the last autosave and opening the pause menu is lost if the system reclaims the app in the background. Method: first freeze the world (same as panel freezing: the world / client / animation / render entry points become no-ops and the tick number does not advance, so monsters do not move and time does not pass), +// then temporarily release the two UI state bytes of the original pause so ticks run and perform the save; after the commit (front end background_wait_save) write the two bytes back and unfreeze. Called by the front end on the main thread +static _Atomic int g_bgsave; static uint8_t g_bg_pause[2]; +static int save_unpause_begin(void) { // 1 = 冻住世界并放开了暂停;0 = 游戏没停着(不用做);-1 = 产物没有冻结门,做不了 | 1 = froze the world and released the pause; 0 = the game is not stopped (nothing to do); -1 = the product has no freeze gates, cannot do it + uint8_t *b = NULL; for (int i = 0; i < g_nmod; i++) if (!strcmp(g_mod[i].name, "main")) b = (uint8_t *)g_mod[i].base; + if (!b || !in_game()) return 0; volatile uint8_t *f = b + 0x2d5ff51, *g = b + 0x2d5ff67; if (!*f && !*g) return 0; + if (!freeze_attach()) { LOG("【红】停着存盘:游戏停着,但产物里没有冻结门 10–13,不放开暂停(这次存不了)"); return -1; } + atomic_store(&g_frz_by_panel, 0); atomic_store(&g_bgsave, 1); atomic_store(&g_dm_frozen, 1); // 先冻、后放开:放开后的第一拍世界就已经是空跑 | Freeze first, then release: the world is already idle on the first tick after release + int nm = 0, hp = 0; uint32_t h = g_lastG ? frz_snapshot(g_lastG, &nm, &hp) : 0; + g_bg_pause[0] = *f; g_bg_pause[1] = *g; *f = 0; *g = 0; + LOG("停着存盘:游戏停着 → 冻住世界、临时放开原版暂停(怪 / 佣兵 %d 个,快照 %08x,玩家生命 %d)", nm, h, hp); + return 1; +} +static void save_unpause_end(void) { + if (!atomic_load(&g_bgsave)) return; + uint8_t *b = NULL; for (int i = 0; i < g_nmod; i++) if (!strcmp(g_mod[i].name, "main")) b = (uint8_t *)g_mod[i].base; + if (b) { *(volatile uint8_t *)(b + 0x2d5ff51) = g_bg_pause[0]; *(volatile uint8_t *)(b + 0x2d5ff67) = g_bg_pause[1]; } // 先恢复暂停、后解冻:解冻后的拍不再走 | Restore the pause first, then unfreeze: ticks after unfreezing no longer advance + int nm = 0, hp = 0; uint32_t h = g_lastG ? frz_snapshot(g_lastG, &nm, &hp) : 0; + atomic_store(&g_bgsave, 0); atomic_store(&g_dm_frozen, 0); + LOG("停着存盘:恢复原版暂停、解冻(怪 / 佣兵 %d 个,快照 %08x,玩家生命 %d)", nm, h, hp); +} +// 前端要进程马上可能没了之前(iOS 进后台、Mac 退出)请游戏存一次盘并等提交:游戏停着(暂停菜单 / 大秘境面板开着)就先冻住世界、 +// 临时放开原版暂停让拍走起来执行这次存盘,等完写回暂停、解冻——玩家回来时世界与暂停都和离开前一样。等到「出现过存档提交、之后 0.2 秒没有新的提交」 +// (角色与共享箱是两个容器,可能分两次),最多 max_s 秒;还没进局(读取画面)就每 20 ms 再试,进了局再请。返回 1 = 请到了存盘。 +// *commits = 期间存档提交次数,*froze = 是否冻结放开过暂停,*ms = 用时。在前端主线程调(游戏拍在客体线程照跑) +// Before the process may go away at any moment (iOS going to the background, quitting on Mac), the front end asks the game to save once and waits for the commit. If the game is stopped (pause menu / Greater Rift panel open), it first freezes the world, +// temporarily releases the original pause so ticks run and perform this save, and after waiting writes the pause back and unfreezes, so when the player returns both the world and the pause are as they left them. It waits until "a save commit has happened and no new commit for 0.2 s" +// (character and shared stash are two containers and may commit separately), at most max_s seconds; before entering a game (loading screen) it retries every 20 ms and asks once in game. Returns 1 = the save was requested. +// *commits = number of save commits in the meantime, *froze = whether it froze and released the pause, *ms = time taken. Called on the front end's main thread (game ticks keep running on the guest thread) +uint64_t dm_fs_commit_count(void); +int dm_save_wait(double max_s, uint64_t *commits, int *froze, double *ms) { + uint64_t c0 = dm_fs_commit_count(), t0 = now_ns(), last = c0, last_t = 0, lim = (uint64_t)(max_s * 1e9); int asked = 0, bg = 0; + for (;;) { + if (!bg && in_game()) bg = save_unpause_begin(); // 先冻、放开暂停,再请存盘 | Freeze first, release the pause, then ask for the save + if (!asked) asked = dm_request_save(); + usleep(20000); uint64_t c = dm_fs_commit_count(), t = now_ns(); + if (c != last) { last = c; last_t = t; } + if ((asked && last_t && t - last_t >= 200000000ull) || t - t0 >= lim) break; + } + if (bg > 0) save_unpause_end(); + *commits = last - c0; *froze = bg > 0; *ms = (now_ns() - t0) / 1e6; + return asked; +} static void freeze_tick(uint64_t G) { // 拍入口:定这一拍冻不冻,冻就把拍号先减 1 | Tick entry: decide whether this tick is frozen; if so, decrement the tick number by 1 first - static struct { uint32_t at, n; int st; } w[8]; static int nw = -1, panel, cur = -1, on; static uint32_t left, calls; + static struct { uint32_t at, n; int st; } w[8]; static int nw = -1, panel, cur = -1; static uint32_t left, calls; if (nw < 0) { nw = 0; const char *e = getenv("DM_TEST_FREEZE"); char buf[160]; if (e) { strlcpy(buf, e, sizeof buf); for (char *sv, *t = strtok_r(buf, ";", &sv); t && nw < 8; t = strtok_r(NULL, ";", &sv)) if (sscanf(t, "%u:%u", &w[nw].at, &w[nw].n) == 2) nw++; } e = getenv("DM_PANEL_FREEZE"); panel = e && e[0] != '0'; - if (nw || panel) { on = gate_obs_present(OBS_FREEZE_WORLD) && gate_obs_present(OBS_FREEZE_CLIENT) && gate_obs_present(OBS_FREEZE_ANIM) && gate_obs_present(OBS_FREEZE_RENDER); - if (on) { gate_obs_set(OBS_FREEZE_WORLD, freeze_world_obs); gate_obs_set(OBS_FREEZE_CLIENT, freeze_client_obs); gate_obs_set(OBS_FREEZE_ANIM, freeze_anim_obs); gate_obs_set(OBS_FREEZE_RENDER, freeze_render_obs); LOG("面板冻结:四个入口门已挂(按面板 %d,时间窗 %d 个)", panel, nw); } - else LOG("【红】面板冻结:产物里没有观测门 10–13,不生效"); } } - if (!on) return; + if (nw || panel) { if (freeze_attach()) LOG("面板冻结:四个入口门已挂(按面板 %d,时间窗 %d 个)", panel, nw); else LOG("【红】面板冻结:产物里没有观测门 10–13,不生效"); } } + if (!g_frz_on) return; uint32_t t = 0; if (!tk_rd(G + 0x170, &t, 4)) return; int frozen = atomic_load(&g_dm_frozen); if (cur < 0 && !frozen) for (int i = 0; i < nw; i++) if (!w[i].st && t >= w[i].at) { cur = i; w[i].st = 1; left = w[i].n; break; } if (cur >= 0 && frozen && left && !--left) { w[cur].st = 2; cur = -1; } - int want = cur >= 0 || (panel && atomic_load(&g_dm_frz_want)); + int want = cur >= 0 || (panel && atomic_load(&g_dm_frz_want)) || atomic_load(&g_bgsave); if (want && !frozen) { if (t % 20 == 0 || t % 12 == 0 || t % 11 == 0 || t % 1500 == 0) return; // 晚一拍 | One tick later int nm = 0, hp = 0; uint32_t h = frz_snapshot(G, &nm, &hp); atomic_store(&g_frz_by_panel, cur < 0); atomic_store(&g_dm_frozen, 1); frozen = 1; calls = 0; if (mtl_world_frozen) mtl_world_frozen(1); LOG("面板冻结:拍 %u 冻结(%s);怪 %d 只 校验 %08x 玩家生命 %d", t, cur >= 0 ? "时间窗" : "面板开着", nm, h, hp); } else if (!want && frozen) { int nm = 0, hp = 0; uint32_t h = frz_snapshot(G, &nm, &hp); atomic_store(&g_dm_frozen, 0); frozen = 0; if (mtl_world_frozen) mtl_world_frozen(0); LOG("面板冻结:拍 %u 解冻(冻了 %u 次拍入口);怪 %d 只 校验 %08x 玩家生命 %d", t, calls, nm, h, hp); } diff --git a/dm/host/dm_cursor.c b/dm/host/dm_cursor.c index 85b63a8..71b807a 100644 --- a/dm/host/dm_cursor.c +++ b/dm/host/dm_cursor.c @@ -680,7 +680,15 @@ static int inside_walk(uint64_t w, uint64_t xy, int dep, uint64_t vt_catch) { { const char *nm = (const char *)*(uint64_t *)(w + 8); // 不画东西、只占位的辅助控件不算(名字来自实测:整屏命中、与面板无关) | Helper widgets that draw nothing and only occupy space do not count (names from measurement: full-screen hit, unrelated to panels) static const char *skip[] = { "PanelBordersPanel", "ControllerCursorBounds", "ShowItemsPanel", "MiniMenuPanel", "TooltipsPanel", "EmoteWheelPanel", "TransparentBG", "SpriteColoringHelper", "LanguageFontRemapper", "ShowItemsParameters", "ControllerCursorParameters", "MoviePlayer", "AutoMap", "TooltipTextBox" }; // TooltipTextBox:说明框伸到面板外时不算面板(点它 = 点面板外 = 关;mini 技能树页 2/5 被它挡住) // AutoMap:小地图面板整屏占位(进局后常开) | TooltipTextBox: when the tooltip box extends outside the panel it does not count as a panel (tapping it = tapping outside the panel = close; on the second Mac it blocked 2/5 on the skill tree page) // AutoMap: the minimap panel is a full-screen placeholder (always open after entering a run) if (nm) for (unsigned i = 0; i < sizeof skip / sizeof *skip; i++) if (!strcmp(nm, skip[i])) return 0; } - { uint64_t rel = vt - (vt_catch - 0x20c1328); // 叶子控件,或带子控件的底板类(九宫格底板 0x20b9580、对话框边框 0x20bc048:设置页的 Background 就是带子控件的底板) | A leaf widget, or a backing-type widget with children (nine-slice backing 0x20b9580, dialog border 0x20bc048: the settings page's Background is a backing with children) + { uint64_t rel = vt - (vt_catch - 0x20c1328); // 叶子控件,或带子控件的底板类(九宫格底板 0x20b9580、对话框边框 0x20bc048:设置页的 Background 就是带子控件的底板; | Leaf widgets, or backing classes with children (nine-slice backing 0x20b9580, dialog frame 0x20bc048: the Background of the settings page is a backing with children; + // 带子控件的图片 0x20b8650:编年史「查看奖励」页的整页底板 RewardsBg 就是它,原先不算,卡片之间的空处判成「奖励页没盖住」, + // 点下去穿到底下的编年史列表 / 分类 / 页签上,列表容器拿到焦点、金框画在奖励页上面(iPhone 15 Pro 截图)。按它自己的矩形算,同叶子图片; + // 先查它的子控件、都没中才算它自己——名字要报到最里层(关闭钮按 TouchClose / close 的名字认) + // Image widget with children 0x20b8650: the full-page backing RewardsBg of the Chronicle "View Rewards" page is one. It used to be ignored, so empty space between cards was judged "not covered by the rewards page", + // and a tap fell through to the Chronicle list / categories / tabs underneath; the list container got focus and its gold frame was drawn over the rewards page (iPhone 15 Pro screenshot). It now counts with its own rect, like a leaf image; + // its children are checked first and only if none is hit does it count itself, so the name is reported down to the innermost widget (the close button is recognized by the names TouchClose / close) + if (rel == 0x20b8650 && n && ch && n <= 256) { for (uint64_t i = 0; i < n; i++) if (inside_walk(*(uint64_t *)(ch + 8 * i), xy, dep + 1, vt_catch)) return 1; + uint64_t fn = *(uint64_t *)(vt + 0x48); if (((int (*)(uint64_t, uint64_t))fn)(w, xy) & 1) { g_inside_name = *(uint64_t *)(w + 8) ? (const char *)*(uint64_t *)(w + 8) : "?"; return 1; } return 0; } if (!n || !ch || rel == 0x20b9580 || rel == 0x20bc048) { uint64_t fn = *(uint64_t *)(vt + 0x48); int h = ((int (*)(uint64_t, uint64_t))fn)(w, xy) & 1; if (h) { g_inside_name = *(uint64_t *)(w + 8) ? (const char *)*(uint64_t *)(w + 8) : "?"; return 1; } if (!n || !ch) return 0; } } if (n > 256) return 0; for (uint64_t i = 0; i < n; i++) if (inside_walk(*(uint64_t *)(ch + 8 * i), xy, dep + 1, vt_catch)) return 1; @@ -710,6 +718,7 @@ static int ui_inside_panel(module_t *m, uint64_t root, uint64_t xy) { // 从 for (int i = (int)n - 1; i >= 0; i--) { uint64_t p = *(uint64_t *)(ch + 8 * i); if (!p || !*(uint8_t *)(p + 0x50)) continue; const char *nm = (const char *)*(uint64_t *)(p + 8); if (nm && !strncmp(nm, "HUD", 3)) continue; // HUD 各层属于游戏画面,不算面板 | HUD layers belong to the game screen and do not count as panels if (nm && !strcmp(nm, "NotificationPanel")) continue; // 系统提示框不接点击(同 panel_skip) | system notifications do not take taps (same as panel_skip) + if (nm && !strcmp(nm, "FocusManager")) continue; // 焦点金框只是画在被选中控件上的框,不是可点的东西(同 panel_skip):原先点到金框画着的地方命中「FocusIndicator@FocusManager」,那一下落空 | The focus gold frame is only a frame drawn on the selected widget, not something you can tap (same as panel_skip): before, tapping where the gold frame was drawn hit "FocusIndicator@FocusManager" and the tap went nowhere if (inside_walk(p, xy, 1, (uint64_t)m->base + 0x20c1328)) { g_inside_owner = nm ? nm : "?"; return 1; } } return 0; } @@ -2341,6 +2350,72 @@ int dm_ui_panel_resident(const char *name) { "CandidateListPanel" }; if (!name) return 0; for (unsigned i = 0; i < sizeof k / sizeof *k; i++) if (!strcmp(name, k[i])) return 1; return 0; } +// 面板开合栈(前端「面板模式」的依据,原在 front_ios.m hud_stack_message;搬来,iOS 前端与 Mac touch_mac.c 在各自的界面消息回调里调同一份)。 +// 底部 UI v4 的 UIKit 底栏只在「局内常态」画:维护面板开合栈,常驻 HUD 层(dm_ui_panel_resident)之外任何面板开着就不画、前端进面板态。 +// 返回栈读数:开着的非常驻面板数;只开着 NPC 对话菜单 / 说话框时 -1。日志字样「[hud] 面板栈 …」保持原样(回归脚本按它认) +// Panel open/close stack (the basis of the front end's "panel mode"; formerly front_ios.m hud_stack_message, moved here so the iOS front end and Mac touch_mac.c call the same one from their UI message callbacks). +// The UIKit bottom bar of bottom UI v4 is only drawn in the normal in-game state: maintain the panel stack; whenever any panel other than the resident HUD layers (dm_ui_panel_resident) is open, it is not drawn and the front end enters panel mode. +// Returns the stack reading: number of open non-resident panels; -1 when only the NPC dialog menu / speech box is open. The log text "[hud] 面板栈 ..." is kept as is (regression scripts match on it) +enum { HUD_STACK_MAX = 64 }; +static struct { char name[64]; int open; } g_hud_stack[HUD_STACK_MAX]; +static void hud_stack_update(const char *act, const char *arg) { + // 读取画面撤下:清掉此刻在游戏面板树里已经看不见的记录(防只开不关的漏配),屏上还在的照记—— + // 通关页是读取画面撤下前 0.5 秒开的(OpenExclusivePanel EndScreenPanelExpansion → UnloadPanel LoadScreenPanel),原先整栈清零把它也清了: + // 底栏和技能钮盖在通关页上、点「好」变成点世界 + // Loading screen removed: clear the records no longer visible in the game's panel tree at this moment (guards against open-without-close mismatches), and keep those still on screen -- + // the game-completion page is opened 0.5 seconds before the loading screen is removed (OpenExclusivePanel EndScreenPanelExpansion → UnloadPanel LoadScreenPanel); previously the whole stack was zeroed, clearing it too: + // the bottom bar and skill buttons covered the game-completion page, and tapping 「好」(OK) became a world tap + if(!strcmp(act,"UnloadPanel") && !strcmp(arg,"LoadScreenPanel")) { + for(int i=0;i0 && strcmp(g_hud_stack[i].name,"LoadScreenPanel") && dm_ui_panel_shown(g_hud_stack[i].name)) fprintf(stderr,"[hud] 面板栈 读取画面撤下:%s 屏上还在,照记\n",g_hud_stack[i].name); + else memset(&g_hud_stack[i],0,sizeof g_hud_stack[i]); + } + } + else if(!strcmp(act,"UnloadAll")) memset(g_hud_stack,0,sizeof g_hud_stack); + else { + // PanelManager 的面板动作全集(读码:它的消息分发 main+0xb1dc60 只认这 8 个,与全部日志里出现过的一致): + // OpenPanel / OpenExclusivePanel = 开;ClosePanel / UnloadPanel = 关(读取画面那条见上);TogglePanel = 按当前记录翻转(高级属性页走它); + // UnloadAll = 全清(见上);LoadPanel = 预载、不上屏,不算开关;HideGameInfo = 隐藏游戏信息层,与面板开关无关 + // Full set of PanelManager panel actions (from reading the code: its message dispatch main+0xb1dc60 only recognizes these 8, matching what has appeared across all logs): + // OpenPanel / OpenExclusivePanel = open; ClosePanel / UnloadPanel = close (for the loading screen one see above); TogglePanel = flip according to the current record (the advanced stats page uses it); + // UnloadAll = clear all (see above); LoadPanel = preload without showing, not counted as open or close; HideGameInfo = hide the game info layer, unrelated to panel open / close + int tog=!strcmp(act,"TogglePanel"); + int open=!strcmp(act,"OpenPanel")||!strcmp(act,"OpenExclusivePanel"), close=!strcmp(act,"ClosePanel")||!strcmp(act,"UnloadPanel"); + if(!open && !close && !tog) return; + if(dm_ui_panel_resident(arg)) return; + int slot=-1; for(int i=0;i0) { fprintf(stderr,"[hud] 面板栈 %s %s:已经开着,不重复计\n",act,arg); return; } + g_hud_stack[slot].open=open?1:0; + fprintf(stderr,"[hud] 面板栈 %s %s → %d\n",act,arg,g_hud_stack[slot].open); + } +} +int dm_hud_stack_msg(const char *act, const char *arg) { + hud_stack_update(act, arg); + // NPC 对话菜单(交谈 / 交易…那一小列)不挡底栏:只开着它时底栏照常显示(否则 UIKit 层让开、露出游戏层那份底栏,难度格和回城书不见、腰带样子也变)。 + // 编码进同一个数:对话菜单开着且没有别的面板 → -1(底栏不让开、且免除导航态的隐藏) + // The NPC dialog menu (the small column of Talk / Trade…) does not block the bottom bar: with only it open the bottom bar shows as usual (otherwise the UIKit layer yields and exposes the game layer's bottom bar; the difficulty cell and Tome of Town Portal disappear and the belt looks different too). + // Encoded into the same number: dialog menu open with no other panel → -1 (the bottom bar does not yield, and navigation-mode hiding is waived) + int n=0, dlg=0; for(int i=0;i0; else n+=g_hud_stack[i].open; } // ScrollSpeechPanel = NPC 说话的滚动文字框(屏幕上方一小块),同样不挡底栏 | ScrollSpeechPanel = the scrolling text box of NPC speech (a small block at the top of the screen); it likewise does not block the bottom bar + if(!n && dlg) n=-1; + return n; +} +void dm_hud_stack_dump(void) { for (int i = 0; i < HUD_STACK_MAX; i++) if (g_hud_stack[i].open) fprintf(stderr, "%s×%d ", g_hud_stack[i].name, g_hud_stack[i].open); } // 开着的记录(巡检日志用) | Records currently open (for the patrol log) static struct { char name[48]; int open; } g_pm[48]; // 界面消息上开着的非常驻面板 | Non-persistent panels that are open per the UI messages static void ui_panel_note(const char *act, const char *arg) { // 界面消息回调里调(游戏主线程) | Called from the UI message callback (game main thread) if (!strcmp(act, "UnloadAll")) { memset(g_pm, 0, sizeof g_pm); return; } @@ -2502,25 +2577,31 @@ static void ui_panel_state_pump(uint64_t root) { // 游戏主线程,每帧 | // 物品说明框停靠(观测门 OBS_TOOLTIP,挂在说明框面板的「提交一条说明」函数入口 main+0xb0d560(面板, 文字, 目标矩形左上 x2, 目标矩形宽高 x3, 样式, 文字 2))。 // 说明框是即时式的:悬停着的控件每帧重新提交、画完就清,宿主在自己的时机读面板里的记录数一直是 0,所以只能在提交那一刻改输入。 // 原版把框摆在目标矩形(被点的那一格)正下 / 正上方:长说明(暗金、符文之语,十几行)盖住腰带、戒指、背包中间几列和「存放」钮,要点被盖住的格子得先点别处。 -// 触屏、只开着物品栏一个面板(它居中,左右各有一条「屏幕边到面板内框」的空带,约 0.6 个屏高宽)、光标下是物品时:把目标矩形换成对侧空带顶上的一个点—— -// 物品在面板右半停左带、在左半停右带,框从上往下排;量字、摆放、推回屏内仍是游戏自己做(离屏幕边的距离走布局里的 screenEdgePadding)。 +// 触屏、只开着物品栏一个面板、光标下是物品时:把目标矩形换成对侧那块暗格空板(物品栏外框里、中间区域左右各一块)顶上的一个点—— +// 物品在面板右半停左空板、在左半停右空板,框从上往下排;量字、摆放、推回屏内仍是游戏自己做(离屏幕边的距离走布局里的 screenEdgePadding)。 +// 空板位置按屏高定(面板按屏高缩放):空板中线离屏幕中线 0.617 × 屏高、顶边 0.117 × 屏高(iPhone 15 Pro 档 2556×1179 截图量: +// 667 点宽视图里空板 108–180 / 487–558、屏高 307;拿 16:9 截图验算中线 102 落在那张图的空板 60–145 里)。 +// 原先按「屏幕边到面板内框的带子正中」算,只在 16:9 碰巧落在空板里,2.17:1 的 iPhone 上落到面板外框外、贴着屏幕边(iPhone 15 Pro 视频)。 // 其余一律原样放行:手柄 / 键鼠模式;并排两个面板的页(储藏箱 / 商人 / 魔盒 / 单件槽 / 佣兵页——没有空带);技能、属性、按钮的说明(光标下不是物品);世界里的名牌。 -// 面板内框的半宽 = 0.484 × 屏高(真机截图量:2868×1320 上内框 x 795–2073);顶上让开关闭 X 那一行(0.10 × 屏高)。只许游戏主线程(门回调就在)。 +// 只许游戏主线程(门回调就在)。 // 测试开关 DM_TEST_TIPDOCK=1:不看模式(Mac 宿主是手柄版,用它看效果);=0:整个关掉 -// The per-frame pumps fall into two kinds by mode (the long line in dm_ui_mouse_pump below; tests/mode_scan.py checks: each pump on that line either carries if (tm) or is on this "runs in both modes" list, and a new pump on neither list is red). -// Touch only (with if (tm)): all requests come from touch gestures - tapping the world / the mercenary portrait, long press to take, double tap to use, tap goods to buy, drag and drop, tap to bind a skill, the off-hand set tab, opening the mercenary page. -// Not run in gamepad mode or while a switching transaction is in progress; requests in flight are voided by the switch cleanup (dm_ui_cache_mode_leave). -// Run in both modes: ui_target_pump (identify target, including holding A on a gamepad), ui_item_pump (hit queries, also asked by the host itself), ui_ptr_pump (pointer events, also used by clicks synthesised by the host), +// The per-frame pumps fall into two classes by mode (the long line in dm_ui_mouse_pump below; tests/mode_scan.py checks that every pump on that line either has if (tm) or is on this "runs in both modes" list; a newly added pump that is in neither is red). +// Touch only (with if (tm)): requests all come from touch gestures: tapping the world / mercenary portrait, long-press to pick up, double-tap to use, tap to buy, drag and drop, tapping to bind a skill, the off-hand set tab, opening the mercenary page. +// Not run in gamepad mode or while a switch transaction is in progress; requests in flight are cancelled by the switch cleanup (dm_ui_cache_mode_leave). +// Run in both modes: ui_target_pump (identify target, including holding A on the gamepad), ui_item_pump (hit queries, the host asks too), ui_ptr_pump (pointer events, host-synthesized clicks go through it as well), // ui_safe_pump / ui_lift_pump / ui_note_dock_pump / ui_trove_tabs_pump / ui_minimap_pump / ui_map_pump / ui_map_geom_pump / ui_map_center (screen geometry, independent of input method), ui_boss_pct_pump, ui_npcdlg_pump, -// ui_widestash_pump, mv_audit_pump, ui_pages_pump (including gamepad L / R paging), ui_watch_pump, ui_panel_heal, ui_panel_state_pump, rs_pump (one-tap restart, called in the front-end pump) -// Item tooltip docking (observation gate OBS_TOOLTIP, hooked at the entry of the tooltip panel's "submit one tooltip" function main+0xb0d560(panel, text, top-left of target rect x2, size of target rect x3, style, text 2)). -// The tooltip is immediate-mode: the hovered widget resubmits it every frame and it is cleared once drawn, so the record count in the panel is always 0 whenever the host reads it; the input can only be changed at the moment of submission. -// The original places the box directly below / above the target rectangle (the tapped cell): a long description (uniques, runewords, a dozen lines) covers the belt, rings, the middle columns of the inventory and the "Store" button, and a covered cell can only be tapped after tapping elsewhere first. -// With touch, only the inventory panel open (it is centred, with a free band on each side "from the screen edge to the panel's inner frame", about 0.6 of the screen height wide), and an item under the cursor: the target rectangle is replaced by a point at the top of the opposite free band - -// an item in the right half of the panel docks to the left band, one in the left half to the right band, the box running downwards; measuring the text, placing it and pushing it back on screen are still done by the game (the distance from the screen edge follows screenEdgePadding in the layout). -// Everything else passes through unchanged: gamepad / keyboard-and-mouse mode; pages with two panels side by side (stash / vendor / cube / single-item slots / mercenary page - no free band); tooltips of skills, stats and buttons (not an item under the cursor); name plates in the world. -// Half width of the panel's inner frame = 0.484 x screen height (measured from device screenshots: inner frame x 795–2073 on 2868x1320); the top leaves room for the row with the close X (0.10 x screen height). Game main thread only (where the gate callback runs). -// Test switch DM_TEST_TIPDOCK=1: ignore the mode (the Mac host uses the gamepad layout; use it to see the effect); =0: turn it off entirely +// ui_widestash_pump, mv_audit_pump, ui_pages_pump (including L / R page turning on the gamepad), ui_watch_pump, ui_panel_heal, ui_panel_state_pump, rs_pump (one-tap restart, called from the front end pump) +// Item description box docking (observation gate OBS_TOOLTIP, on the entry of the description panel's "submit one description" function main+0xb0d560(panel, text, target rect top-left x2, target rect size x3, style, text 2)). +// The description box is immediate-mode: the hovered widget resubmits it every frame and it is cleared after drawing, so when the host reads the panel at its own time the record count is always 0; the input can only be changed at the moment of submission. +// The original places the box directly below / above the target rect (the slot that was tapped): long descriptions (uniques, runewords, a dozen lines) cover the belt, rings, the middle columns of the inventory and the Stash button, and you have to tap elsewhere before you can tap a covered slot. +// On touch, with only the inventory panel open and an item under the cursor: replace the target rect with a point at the top of the dark empty side panel on the opposite side (inside the inventory frame, one on each side of the middle area): +// an item in the right half of the panel docks on the left panel and vice versa, and the box is laid out downward; measuring the text, placing it and pushing it back on screen are still done by the game (the distance from the screen edge uses screenEdgePadding from the layout). +// The side panels are positioned by screen height (the panel scales with screen height): panel center line 0.617 x screen height from the screen center line, top edge 0.117 x screen height (measured on an iPhone 15 Pro 2556x1179 screenshot: +// in a 667-point-wide view the panels span 108–180 / 487–558 with screen height 307; cross-checked on a 16:9 screenshot, center line 102 falls inside that image's panel at 60–145). +// This used to be computed as "the middle of the band between the screen edge and the panel's inner frame", which only happened to land in the side panel on 16:9; on 2.17:1 iPhones it landed outside the panel frame against the screen edge (iPhone 15 Pro video). +// Everything else passes through unchanged: gamepad / keyboard and mouse mode; pages with two panels side by side (stash / vendor / Horadric Cube / single-item slot / mercenary page, which have no empty band); descriptions of skills, attributes and buttons (no item under the cursor); name plates in the world. +// Game main thread only (the gate callback runs there). +// Test switch DM_TEST_TIPDOCK=1: ignore the mode (the Mac host is the gamepad version; use it to see the effect); =0: turn it off entirely static int ui_touch_mode(void); void dm_ui_tooltip_obs(const uint64_t *regs) { static int force = -2; if (force == -2) { const char *e = getenv("DM_TEST_TIPDOCK"); force = e ? atoi(e) : -1; } @@ -2530,11 +2611,11 @@ void dm_ui_tooltip_obs(const uint64_t *regs) { if (!ui_panel(root, "PlayerInventoryExpansionLayout") || ui_panel(root, "HirelingInventoryPanel")) return; dm_cursor_item_info ci; if (!dm_cursor_item(&ci)) return; int W = *(int32_t *)(m->base + 0x211da38), H = *(int32_t *)(m->base + 0x211da3c); if (W <= 0 || H <= 0) return; - int tx = (int32_t)regs[2], tw = (int32_t)regs[3], half = (int)(0.484f * H), strip = W / 2 - half; if (strip < H / 4) return; // 空带太窄(窄屏)就不挪 | free band too narrow (narrow screen): do not move it - int left = tx + tw / 2 >= W / 2, cx = left ? strip / 2 : W - strip / 2, y = (int)(0.10f * H); + int tx = (int32_t)regs[2], tw = (int32_t)regs[3], off = (int)lroundf(0.617f * H); if (W / 2 - off < H / 10) return; // 空板贴到屏幕边(比 16:9 还窄的屏)就不挪 | If the side panel would touch the screen edge (screens narrower than 16:9), do not move the box + int left = tx + tw / 2 >= W / 2, cx = left ? W / 2 - off : W / 2 + off, y = (int)(0.117f * H); uint64_t *r = (uint64_t *)(uintptr_t)regs; // 门只回写 x0–x8:改 x2 / x3 | the gate writes back only x0-x8: change x2 / x3 r[2] = (uint64_t)(uint32_t)cx | (uint64_t)(uint32_t)y << 32; r[3] = 0; - static int lg; static int ll = -1; if (ll != left && lg < 40) { ll = left; lg++; LOG("说明框停靠:物品 %s 在面板%s半 → 说明框停到%s侧空带(中线 x %d,顶 y %d;画面 %dx%d)", ci.code, left ? "右" : "左", left ? "左" : "右", cx, y, W, H); } + static int lg; static int ll = -1; if (ll != left && lg < 40) { ll = left; lg++; LOG("说明框停靠:物品 %s 在面板%s半 → 说明框停到%s侧空板(中线 x %d,顶 y %d;画面 %dx%d)", ci.code, left ? "右" : "左", left ? "左" : "右", cx, y, W, H); } } static int ui_touch_mode(void) { int dm_padmode_current(void), dm_padmode_busy(void); return !dm_padmode_current() && !dm_padmode_busy(); } // Mac App:界面是手柄版(上面答「不是触屏模式」),但真鼠标走的是触屏那套物品手势(touch_mac.c 把鼠标事件喂给触屏状态机)。 diff --git a/dm/host/dm_i18n_tab.h b/dm/host/dm_i18n_tab.h index 8664861..dfcf746 100644 --- a/dm/host/dm_i18n_tab.h +++ b/dm/host/dm_i18n_tab.h @@ -165,6 +165,12 @@ static const struct { const char *k, *zh, *en; } k_dm_i18n[] = { { "dmOldDl", "直接下载", "Download" }, { "dmOldCopied", "已经拷好了", "Already Copied" }, { "dmOldQuit", "退出", "Quit" }, + { "dmPackBadTitle", "这个安装包还不能玩", "This Package Is Not Ready" }, + { "dmPackBadMiss", "安装包里缺游戏内容(缺 %d 项,如 %@)。", "The package is missing game content (%d items, e.g. %@)." }, + { "dmPackBadProd", "安装包是用不同版本拼成的(壳是 %@,做进去的内容是 %@)。", "The package mixes versions (shell %@, built-in content %@)." }, + { "dmPackBadHow", "发布页上的壳是做安装包的原料,不能直接装来玩。\n\n怎么做:在电脑上打开 github.com/jhaizhou-ops/d2r-mobile,照 docs/NO_XCODE 的第一步用 d2rm_pack.py 把你的游戏内容做进同一版本的壳,再装它输出的那个安装包。", "The shell on the releases page is build input, not an app to install.\n\nWhat to do: on a computer, open github.com/jhaizhou-ops/d2r-mobile and follow step 1 of docs/NO_XCODE — run d2rm_pack.py to build your game content into the shell of the same release, then install the package it outputs." }, + { "dmGpuOldTitle", "这台设备玩不了", "This Device Is Not Supported" }, + { "dmGpuOldMsg", "这台设备的图形芯片不支持 Metal 3,本游戏的图形层需要它。\n\n需要 A14 / M1 及以后的芯片(iPhone 12 及以后、2021 年及以后的 iPad Pro 等);A13 及更早的芯片(包括 2020 年的 iPad Pro)玩不了。", "This device's graphics chip does not support Metal 3, which the game's graphics layer needs.\n\nAn A14 / M1 chip or later is required (iPhone 12 and later, iPad Pro from 2021 and later, and so on); A13 and earlier chips, including the 2020 iPad Pro, cannot run it." }, { "dmOldConnecting", "正在连接下载服务器…", "Connecting to the download server…" }, { "dmOldDlFail", "下载失败:%s", "Download failed: %s" }, { "dmOldProgress", "正在下载老机型补充包\n%.2f / %.2f GB(%.0f%%)%@", "Downloading the supplementary pack\n%.2f / %.2f GB (%.0f%%)%@" }, diff --git a/dm/host/front_mac.m b/dm/host/front_mac.m index 06d1810..0b96932 100644 --- a/dm/host/front_mac.m +++ b/dm/host/front_mac.m @@ -57,23 +57,17 @@ static void layout_game(void) { LOG("窗口:内容区 %.0f×%.0f,游戏画面 %.0f×%.0f 放在 (%.0f,%.0f)", g_view.bounds.size.width, g_view.bounds.size.height, r.size.width, r.size.height, r.origin.x, r.origin.y); } // 退出(关窗口 / ⌘Q / 菜单):有局在就先请游戏走一次它自己的存盘并等存档提交(做法同 iOS 壳进后台),最多 3 秒,再有序收尾。 -// 暂停菜单 / 大秘境面板开着时游戏停拍:先放开暂停让拍走起来;读取画面里等它进到局内再请。3 秒到了还没有提交就照实记「未存盘退出」 -// Quit (closing the window / ⌘Q / menu): if a game is in progress, first ask the game to do its own save and wait for the save to be committed (the same way the iOS shell does when going to the background), for at most 3 seconds, then shut down in order. -// With the pause menu / rift panel open the game is not ticking: release the pause first so the ticks run; in a loading screen wait until it is in the game, then ask. If nothing is committed when the 3 seconds are up, truthfully log "quit without saving" +// 暂停菜单 / 大秘境面板开着时游戏停拍:冻住世界、临时放开暂停存这一次(diag.c dm_save_wait,与 iOS 进后台同一个函数);读取画面里等它进到局内再请。3 秒到了还没有提交就照实记「未存盘退出」 +// Quit (close window / Cmd-Q / menu): if a game is running, first ask the game to do one of its own saves and wait for the save commit (same as the iOS shell going to the background), at most 3 s, then shut down in order. +// When the pause menu / Greater Rift panel is open the game does not tick: freeze the world and temporarily release the pause for this one save (diag.c dm_save_wait, the same function as iOS going to the background); on the loading screen wait until in game before asking. If there is still no commit after 3 s, log "quit without saving" as is static void app_quit(const char *why) { static int once; if (once++) return; { uint64_t dm_audio_render_calls(void); LOG("窗口:退出(%s);声卡回调累计 %llu(0 = 这次没出声)", why, (unsigned long long)dm_audio_render_calls()); } - int dm_ingame_now(void); int dm_request_save(void); int dm_unpause_for_exit(void); uint64_t dm_fs_commit_count(void); uint64_t now_ns(void); + int dm_ingame_now(void); int dm_save_wait(double max_s, uint64_t *commits, int *froze, double *ms); if (!dm_ingame_now() && !dm_uiscreen_ingame()) { LOG("窗口:退出(不在局内,没有待存的进度)"); dm_host_shutdown(why); return; } - uint64_t c0 = dm_fs_commit_count(), t0 = now_ns(), last = c0, last_t = 0; int asked = 0, paused = 0; - for (;;) { - paused |= dm_unpause_for_exit(); if (!asked) asked = dm_request_save(); - usleep(20000); uint64_t c = dm_fs_commit_count(), t = now_ns(); - if (c != last) { last = c; last_t = t; } - if ((asked && last_t && t - last_t >= 200000000ull) || t - t0 >= 3000000000ull) break; - } - if (last != c0 && asked) LOG("窗口:退出前等游戏存盘 %.0f ms,期间存档提交 %llu 次%s", (now_ns() - t0) / 1e6, (unsigned long long)(last - c0), paused ? "(原先停在暂停菜单 / 面板,已放开)" : ""); - else LOG("【红】窗口:未存盘退出——3 秒内没等到存档提交(%s%s)", asked ? "已请游戏存盘" : "一直没到能请存盘的状态(读取画面?)", paused ? ",原先暂停着、已放开" : ""); + uint64_t n = 0; int froze = 0; double ms = 0; int asked = dm_save_wait(3, &n, &froze, &ms); + if (n && asked) LOG("窗口:退出前等游戏存盘 %.0f ms,期间存档提交 %llu 次%s", ms, (unsigned long long)n, froze ? "(原先暂停着:冻结世界存盘、已恢复暂停)" : ""); + else LOG("【红】窗口:未存盘退出——3 秒内没等到存档提交(%s%s)", asked ? "已请游戏存盘" : "一直没到能请存盘的状态(读取画面?)", froze ? ",原先暂停着、冻结放开过" : ""); { int dm_cloud_flush_wait(double sec); dm_cloud_flush_wait(10); } // 存盘之后把这一局传上 iCloud 再退(没开同步时立即返回) | after saving, upload this session to iCloud before quitting (returns immediately when sync is off) dm_host_shutdown(why); } diff --git a/dm/host/hle_fs.c b/dm/host/hle_fs.c index ff8e772..af9701d 100644 --- a/dm/host/hle_fs.c +++ b/dm/host/hle_fs.c @@ -76,6 +76,20 @@ static const char *envdir(const char *var, const char *rel, char *buf, size_t n) snprintf(buf, n, "%s%s/%s", getenv("DM_ROOT") ?: getenv("HOME"), getenv("DM_ROOT") ? "" : "/dm-work", rel); return buf; } +// 测试注入 DM_TEST_FS_FAILAT=<点>[:<次数>][,…]:存档事务里写失败收场的几步(mountclone 挂载时克隆工作目录、reclone 提交被拒后重新克隆、 +// guestname 改名后写客体名、renameback 改名回退)前 <次数> 次(缺省 1)按 ENOSPC 失败,验「不退出、已提交版本不变、下次提交照常」(tests/t_fs.c) +// Test injection DM_TEST_FS_FAILAT=[:][,...]: the steps of a save transaction that end in a failed write (mountclone = clone the work directory at mount, reclone = reclone after a refused commit, +// guestname = write the guest name after a rename, renameback = rename rollback) fail with ENOSPC for the first times (default 1), to check "no exit, committed version unchanged, next commit works" (tests/t_fs.c) +static int dm_fs_test_fail(const char *pt) { + static char spec[256]; static int cnt[8]; const char *e = getenv("DM_TEST_FS_FAILAT"); if (!e || !e[0]) return 0; + if (strcmp(spec, e)) { strlcpy(spec, e, sizeof spec); memset(cnt, 0, sizeof cnt); } // 换了一组注入就从头数 | A new set of injections starts counting from zero + size_t L = strlen(pt); int k = 0; + for (const char *q = spec; *q && k < 8; k++) { const char *end = strchr(q, ','); size_t n = end ? (size_t)(end - q) : strlen(q); + if (n >= L && !strncmp(q, pt, L) && (n == L || q[L] == ':')) { int lim = n > L ? atoi(q + L + 1) : 1; if (cnt[k] < lim) { cnt[k]++; errno = ENOSPC; LOG("DM_TEST_FS_FAILAT:%s 第 %d 次按 ENOSPC 失败", pt, cnt[k]); return 1; } return 0; } + q = end ? end + 1 : q + n; } + return 0; +} +static int in_txn_dir(const char *hp) { for (int i = 0; i < g_nmnt; i++) { size_t n = strlen(g_mnt[i].dir); if (g_mnt[i].commit[0] && !strncmp(hp, g_mnt[i].dir, n) && (hp[n] == '/' || !hp[n])) return 1; } return 0; } static int rm_tree(const char *p); static Result mount_ex(const char *name, const char *dir, int ro, int txn) { PATH_LOCK(); pthread_mutex_lock(&g_lock); @@ -86,20 +100,26 @@ static Result mount_ex(const char *name, const char *dir, int ro, int txn) { g_mnt[g_nmnt].ro = ro; g_mnt[g_nmnt].overlay[0] = 0; g_mnt[g_nmnt].commit[0] = 0; if (!strcmp(name, "rom") && getenv("DM_ROMFS_OVERLAY")) strlcpy(g_mnt[g_nmnt].overlay, getenv("DM_ROMFS_OVERLAY"), sizeof g_mnt[0].overlay); + int txn_err = 0; // 事务目录建不起来(清不掉残留 / 克隆失败,盘满时真实可能):不退出,改成只读挂载已提交目录——角色照常读得到,写一律失败、提交为空操作,已提交版本一个字节不动 | The transaction directory cannot be set up (leftovers cannot be cleared / clone failed, which really happens on a full disk): do not exit; mount the committed directory read-only instead. Characters still load, every write fails, commits are no-ops, and not one byte of the committed version changes if (txn) { char work[1100], neu[1100]; snprintf(work, sizeof work, "%s.work", dir); snprintf(neu, sizeof neu, "%s.new", dir); mkdir(dir, 0755); - if (!access(work, F_OK) && rm_tree(work)) die("存档事务:清不掉上次残留的工作目录 %s", work); - if (!access(neu, F_OK) && rm_tree(neu)) die("存档事务:清不掉上次残留的 %s", neu); - if (clonefile(dir, work, 0)) die("存档事务:clonefile %s → %s 失败 errno=%d", dir, work, errno); - strlcpy(g_mnt[g_nmnt].commit, dir, sizeof g_mnt[0].commit); - atomic_store(&g_save_poison, 0); // 工作目录刚从已提交版克隆,完好 | the working directory was just cloned from the committed version, intact - strlcpy(g_mnt[g_nmnt].dir, work, sizeof g_mnt[0].dir); + const char *why = NULL; + if (!access(work, F_OK) && rm_tree(work)) why = "清不掉上次残留的工作目录"; + else if (!access(neu, F_OK) && rm_tree(neu)) why = "清不掉上次残留的 .new"; + else if (dm_fs_test_fail("mountclone") || clonefile(dir, work, 0)) why = "克隆工作目录失败"; + if (why) { txn_err = errno ? errno : EIO; g_mnt[g_nmnt].ro = 1; strlcpy(g_mnt[g_nmnt].dir, dir, sizeof g_mnt[0].dir); + LOG("【红】存档事务:%s(%s,errno=%d)——改为只读挂载已提交目录 %s:本局存档写不进去,已提交版本不变", why, work, txn_err, dir); } + else { + strlcpy(g_mnt[g_nmnt].commit, dir, sizeof g_mnt[0].commit); + atomic_store(&g_save_poison, 0); // 工作目录刚从已提交版克隆,完好 | the working directory was just cloned from the committed version, intact + strlcpy(g_mnt[g_nmnt].dir, work, sizeof g_mnt[0].dir); } } else strlcpy(g_mnt[g_nmnt].dir, dir, sizeof g_mnt[0].dir); g_nmnt++; pthread_mutex_unlock(&g_lock); + if (txn_err) front_save_failed(txn_err); if (!ro && !txn) mkdir(dir, 0755); - LOG("fs 挂载 %s: → %s%s%s", name, txn ? g_mnt[g_nmnt - 1].dir : dir, ro ? "(只读)" : txn ? "(事务式存档:工作目录,Commit 原子换入)" : "", g_mnt[g_nmnt - 1].overlay[0] ? "(overlay 优先)" : ""); + LOG("fs 挂载 %s: → %s%s%s", name, txn ? g_mnt[g_nmnt - 1].dir : dir, ro || txn_err ? "(只读)" : txn ? "(事务式存档:工作目录,Commit 原子换入)" : "", g_mnt[g_nmnt - 1].overlay[0] ? "(overlay 优先)" : ""); return RES_OK; } static Result mount(const char *name, const char *dir, int ro) { return mount_ex(name, dir, ro, 0); } @@ -239,6 +259,9 @@ static Result err_res(const char *op, const char *path) { #define HP_EX(path, create) PATH_LOCK(); char hp[1024]; int ro = 0; if (!host_path_ex(path, hp, sizeof hp, &ro, create)) return err_res("path", path) #define HP(path) HP_EX(path, 0) #define RW() if (ro) { LOG("fs 写只读挂载:%s", hp); return RES_FAIL; } +// 建目录 / 建文件:目标已存在就照可写挂载的语义回「已存在」——游戏只认得这一种失败(原版存档盘不会写失败),回通用失败它会拿空句柄继续走(iOS 只读回退局在 CloseDirectory 崩) +// Create directory / create file: if the target exists, answer "already exists" as a writable mount would. That is the only failure the game understands (the original save storage never fails to write); with a generic failure it carries on with a null handle (the iOS read-only fallback crashed in CloseDirectory) +#define RW_CREATE() if (ro) { if (!access(hp, F_OK)) return RES_PATH_EXISTS; LOG("fs 写只读挂载:%s", hp); return RES_FAIL; } // ---------- 挂载 ---------- // ---------- Mount ---------- @@ -415,9 +438,18 @@ HLE_FORCE("_ZN2nn2fs6CommitEPKc", "fsp-srv;事务式存档:工作目录整 } if (d0) closedir(d0); int nopen = 0; for (int k = 0; k < 65536; k++) nopen += g_fsave[k]; // 仍开着的存档文件:重新克隆后这些句柄指向被删的旧工作目录 | save files still open: after re-cloning, these handles point into the deleted old working directory - if (rm_tree(g_mnt[i].dir) || clonefile(g_mnt[i].commit, g_mnt[i].dir, 0)) die("存档事务:丢弃工作目录 %s 后重新克隆失败 errno=%d", g_mnt[i].dir, errno); + // 先把已提交版克隆到同级临时目录,成了再与被污染的工作目录原子互换、删掉换下来的;任一步失败都不退出:工作目录留着、「已污染」标记放回去 + // (下次提交照样拒绝、再试一次重新克隆),已提交版本不变(原先先删工作目录再克隆,克隆失败就 die,盘满时进程直接退出、工作目录也没了) + // First clone the committed version into a sibling temporary directory; once that succeeds, atomically swap it with the tainted work directory and delete the swapped-out one. If any step fails, do not exit: the work directory stays and the "tainted" mark is put back + // (the next commit is refused again and recloning is retried); the committed version is unchanged (before, the work directory was deleted first and then recloned, and a failed clone called die, so with a full disk the process exited and the work directory was gone) + char re[1100]; snprintf(re, sizeof re, "%s.re", g_mnt[i].dir); int rerr = 0; + if (!access(re, F_OK) && rm_tree(re)) rerr = errno ? errno : EIO; + else if (dm_fs_test_fail("reclone") || clonefile(g_mnt[i].commit, re, 0)) { rerr = errno ? errno : EIO; rm_tree(re); } + else if (renamex_np(re, g_mnt[i].dir, RENAME_SWAP)) { rerr = errno ? errno : EIO; rm_tree(re); } + else rm_tree(re); // 换下来的被污染工作目录 | The swapped-out tainted work directory + if (rerr) { save_poison(perr); LOG("【红】存档事务:重新克隆工作目录失败 errno=%d——工作目录不动、保持已污染(下次提交照样拒绝并重试),已提交版本不变", rerr); } pthread_mutex_unlock(&g_lock); - LOG("【红】存档提交拒绝:本事务有存档写失败 errno=%d(工作目录里 0 字节文件:%s);已提交版本不变,工作目录已从已提交版重新克隆%s", perr, tl ? torn + 1 : "无", nopen ? ";【红】仍有存档文件开着" : ""); + LOG("【红】存档提交拒绝:本事务有存档写失败 errno=%d(工作目录里 0 字节文件:%s);已提交版本不变,工作目录%s%s", perr, tl ? torn + 1 : "无", rerr ? "没能重新克隆(见上一行)" : "已从已提交版重新克隆", nopen ? ";【红】仍有存档文件开着" : ""); front_save_failed(perr); return RES_FAIL; } @@ -526,6 +558,7 @@ HLE_FORCE("_ZN2nn2fs8OpenFileEPNS0_10FileHandleEPKci", "fsp-srv → open(2)", Re return RES_OK; } HLE_FORCE("_ZN2nn2fs8ReadFileEPmNS0_10FileHandleElPvm", "fsp-srv → pread(2)", Result, h_fs_ReadFile, size_t *out, uint64_t h, int64_t off, void *buf, size_t sz) { + if (!h) { *out = 0; return RES_FAIL; } // 文件句柄就是 fd,0 是标准输入、不会是游戏打开的文件:打开失败后照用的空句柄 | A file handle is an fd; 0 is standard input and never a file the game opened: it is the null handle the game keeps using after a failed open size_t got = 0; uint64_t t0 = g_flag.bootprof ? now_ns() : 0; dm_guest_write_prepare(buf, sz); // 目标可能是图形层写保护的贴图池页:内核写只读页返回 EFAULT 而不缺页,先解保护并标脏 | The destination may be a texture pool page write-protected by the graphics layer: a kernel write to a read-only page returns EFAULT instead of page-faulting, so unprotect and mark dirty first while (got < sz) { @@ -551,6 +584,7 @@ HLE_FORCE("_ZN2nn2fs8ReadFileEPmNS0_10FileHandleElPvm", "fsp-srv → pread(2)", return RES_OK; } HLE_FORCE("_ZN2nn2fs9WriteFileENS0_10FileHandleElPKvmRKNS0_11WriteOptionE", "fsp-srv → pwrite(2)", Result, h_fs_WriteFile, uint64_t h, int64_t off, const void *buf, size_t sz, const void *opt) { + if (!h) return RES_FAIL; (void)opt; size_t put = 0; if (g_fsave[(int)h & 0xffff]) { // 存档写注入点(确定性回归用;只数存档挂载上的写) | Save write injection point (for deterministic regression; only writes on the save mount are counted) static int cfg = -1, kill_n, fail_n, fail_e; @@ -572,16 +606,19 @@ HLE_FORCE("_ZN2nn2fs9WriteFileENS0_10FileHandleElPKvmRKNS0_11WriteOptionE", "fsp return RES_OK; } HLE_FORCE("_ZN2nn2fs11GetFileSizeEPlNS0_10FileHandleE", "fsp-srv → fstat(2)", Result, h_fs_GetFileSize, int64_t *out, uint64_t h) { + if (!h) return RES_FAIL; struct stat st; if (fstat((int)h, &st)) return err_res("fstat", "fd"); *out = (int)h < 4096 && g_hm[(int)h] ? g_hm[(int)h]->size : st.st_size; return RES_OK; } HLE_FORCE("_ZN2nn2fs11SetFileSizeENS0_10FileHandleEl", "fsp-srv → ftruncate(2)", Result, h_fs_SetFileSize, uint64_t h, int64_t sz) { + if (!h) return RES_FAIL; if (!ftruncate((int)h, sz)) return RES_OK; if (g_fsave[(int)h & 0xffff]) save_poison(errno); return err_res("ftruncate", "fd"); } HLE_FORCE("_ZN2nn2fs9FlushFileENS0_10FileHandleE", "fsp-srv;宿主 write 已进页缓存,刷新为空操作", Result, h_fs_FlushFile, uint64_t h) { (void)h; return RES_OK; } -HLE_FORCE("_ZN2nn2fs9CloseFileENS0_10FileHandleE", "fsp-srv → close(2)", void, h_fs_CloseFile, uint64_t h) { g_fmode[(int)h & 0xffff] = 0; g_fsave[(int)h & 0xffff] = 0; +HLE_FORCE("_ZN2nn2fs9CloseFileENS0_10FileHandleE", "fsp-srv → close(2)", void, h_fs_CloseFile, uint64_t h) { + if (!h) return; g_fmode[(int)h & 0xffff] = 0; g_fsave[(int)h & 0xffff] = 0; if ((int)h >= 0 && (int)h < 4096 && g_hm[(int)h]) { holemap *m = g_hm[(int)h]; g_hm[(int)h] = NULL; free(m->log); free(m->len); free(m->phys); free(m); } close((int)h); } HLE_FORCE("_ZN2nn2fs15GetFileOpenModeENS0_10FileHandleE", "fsp-srv;打开方式由宿主记录", int, h_fs_GetFileOpenMode, uint64_t h) { return g_fmode[(int)h & 0xffff]; } @@ -589,7 +626,7 @@ HLE_FORCE("_ZN2nn2fs15GetFileOpenModeENS0_10FileHandleE", "fsp-srv;打开方 // ---------- 路径操作 ---------- // ---------- Path operations ---------- HLE_FORCE("_ZN2nn2fs10CreateFileEPKcl", "fsp-srv → open(O_CREAT|O_EXCL)+ftruncate", Result, h_fs_CreateFile, const char *path, int64_t sz) { - HP_EX(path, 1); RW(); + HP_EX(path, 1); RW_CREATE(); int fd = open(hp, O_WRONLY | O_CREAT | O_EXCL, 0644); if (fd < 0) return err_res("create", hp); int rc = ftruncate(fd, sz); int e = errno; close(fd); @@ -598,7 +635,7 @@ HLE_FORCE("_ZN2nn2fs10CreateFileEPKcl", "fsp-srv → open(O_CREAT|O_EXCL)+ftrunc errno = e; return rc ? err_res("create", hp) : RES_OK; } HLE_FORCE("_ZN2nn2fs10DeleteFileEPKc", "fsp-srv → unlink(2)", Result, h_fs_DeleteFile, const char *path) { HP(path); RW(); return unlink(hp) ? err_res("unlink", hp) : RES_OK; } -HLE_FORCE("_ZN2nn2fs15CreateDirectoryEPKc", "fsp-srv → mkdir(2)", Result, h_fs_CreateDirectory, const char *path) { HP_EX(path, 1); RW(); +HLE_FORCE("_ZN2nn2fs15CreateDirectoryEPKc", "fsp-srv → mkdir(2)", Result, h_fs_CreateDirectory, const char *path) { HP_EX(path, 1); RW_CREATE(); if (mkdir(hp, 0755)) return err_res("mkdir", hp); if (set_guest_name(hp, path)) { int e = errno; rmdir(hp); errno = e; return err_res("mkdir name", hp); } return RES_OK; } @@ -621,7 +658,10 @@ HLE_FORCE("_ZN2nn2fs10RenameFileEPKcS2_", "fsp-srv → rename(2)", Result, h_fs_ if (!host_path_ex(to, hp2, sizeof hp2, NULL, 1)) return err_res("rename path", to); if (!access(hp2, F_OK)) return RES_PATH_EXISTS; if (rename(hp, hp2)) return err_res("rename", hp); - if (set_guest_name(hp2, to)) { int e = errno; if (rename(hp2, hp)) die("fs 改名元数据失败且回退失败 errno=%d", errno); errno = e; return err_res("rename name", hp2); } + if (dm_fs_test_fail("guestname") || set_guest_name(hp2, to)) { int e = errno ? errno : EIO; + if (dm_fs_test_fail("renameback") || rename(hp2, hp)) { // 回退也失败:文件留在新路径、客体名元数据不对;不退出——在事务存档里就让本事务提交被拒(已提交版本不变,重新克隆即复原) | Rollback also failed: the file stays at the new path with wrong guest-name metadata; do not exit. In a transactional save, this transaction's commit is refused (the committed version is unchanged and recloning restores it) + LOG("【红】fs 改名元数据失败且回退失败 errno=%d:%s 留在新路径%s", errno, hp2, in_txn_dir(hp2) ? ",本事务存档提交将被拒" : ""); if (in_txn_dir(hp2)) save_poison(e); } + errno = e; return err_res("rename name", hp2); } return RES_OK; } HLE_FORCE("_ZN2nn2fs12GetEntryTypeEPNS0_18DirectoryEntryTypeEPKc", "fsp-srv → stat(2)", Result, h_fs_GetEntryType, int32_t *out, const char *path) { @@ -678,6 +718,7 @@ HLE_FORCE("_ZN2nn2fs13OpenDirectoryEPNS0_15DirectoryHandleEPKci", "fsp-srv → o *out = (uint64_t)h; return RES_OK; } HLE_FORCE("_ZN2nn2fs13ReadDirectoryEPlPNS0_14DirectoryEntryENS0_15DirectoryHandleEl", "fsp-srv → readdir(3)", Result, h_fs_ReadDirectory, int64_t *count, DirectoryEntry *ents, uint64_t hh, int64_t max) { + if (!hh) { *count = 0; return RES_FAIL; } PATH_LOCK(); dirh_t *h = (dirh_t *)hh; int64_t n = 0; struct dirent *e; if (h->snap) { while (n < max && h->psnap < h->nsnap) { DirectoryEntry *src = &h->snap[h->psnap++]; if (!(h->mode & (src->type == ENT_DIR ? DIRMODE_DIR : DIRMODE_FILE))) continue; ents[n++] = *src; } *count = n; return RES_OK; } while (n < max && (e = readdir(h->d))) { @@ -694,5 +735,6 @@ HLE_FORCE("_ZN2nn2fs13ReadDirectoryEPlPNS0_14DirectoryEntryENS0_15DirectoryHandl *count = n; return RES_OK; } HLE_FORCE("_ZN2nn2fs14CloseDirectoryENS0_15DirectoryHandleE", "fsp-srv → closedir(3)", void, h_fs_CloseDirectory, uint64_t hh) { + if (!hh) return; // 游戏在打开失败后也会关(句柄是 0):原版无事可做 | The game also closes after a failed open (handle 0): nothing to do in the original either dirh_t *h = (dirh_t *)hh; closedir(h->d); if (h->od) closedir(h->od); free(h->snap); free(h); } diff --git a/dm/host/tests/t_fs.c b/dm/host/tests/t_fs.c index 6e7f43c..09d2e21 100644 --- a/dm/host/tests/t_fs.c +++ b/dm/host/tests/t_fs.c @@ -26,6 +26,7 @@ ssize_t pwrite(int, const void *, size_t, off_t); struct dm_flags g_flag; uint64_t g_t0_ns; uint64_t now_ns(void) { return 0; } // 日志时间戳与读路径的桩(写路径不用) | stubs for log timestamps and the read path (not used by the write path) void dm_prof_add(int id, uint64_t ns, uint64_t b) { (void)id; (void)ns; (void)b; } void dm_guest_write_prepare(void *a, size_t n) { (void)a; (void)n; } +void dm_fs_save_poison(int e); extern int g_nfail, g_lasterr; // 前端通知计数(t_fs_stub.c 的强实现替掉 hle_fs.c 的弱实现) | front-end notification count (the strong implementation in t_fs_stub.c replaces the weak one in hle_fs.c) static int g_mode, g_calls; // 0 照常写;1 一律返回 0;2 第一次只写 3 字节 | 0 write normally; 1 always return 0; 2 write only 3 bytes the first time static ssize_t fake_pwrite(int fd, const void *buf, size_t n, off_t off) { @@ -143,6 +144,44 @@ int main(void) { snprintf(p, sizeof p, "%s/a", work); CHECK(same(p, "new"), "工作目录 a 回到已提交版 new"); snprintf(p, sizeof p, "%s/b", work); CHECK(same(p, "7"), "工作目录 b = 已提交的 7"); + printf("⑥ 写失败收场不退出(DM_TEST_FS_FAILAT)\n"); + unsetenv("DM_TEST_FS_FAIL"); + // ⑥a 提交被拒后重新克隆失败:不退出、工作目录不动、已提交版不变;下次提交照样拒绝并重新克隆成功;再下一个事务照常提交 + // 6a Recloning after a refused commit fails: do not exit, the work directory is untouched and the committed version unchanged; the next commit is refused again and the reclone succeeds; the transaction after that commits normally + setenv("DM_TEST_FS_FAILAT", "reclone:1", 1); + CHECK(write_save("save:/a", "bad") == RES_OK, "写 a=bad"); + dm_fs_save_poison(ENOSPC); int nf0 = g_nfail; + CHECK(h_fs_Commit("save") == RES_FAIL && g_nfail == nf0 + 1, "本事务被拒(重新克隆注入失败),进程还在,前端通知 1 次"); + snprintf(p, sizeof p, "%s/a", save); CHECK(same(p, "new"), "已提交目录 a 仍是 new"); + snprintf(p, sizeof p, "%s/a", work); CHECK(same(p, "bad"), "工作目录没删(a 还是 bad)"); + CHECK(h_fs_Commit("save") == RES_FAIL && g_nfail == nf0 + 2, "仍是已污染:下一次提交照样拒绝"); + snprintf(p, sizeof p, "%s/a", work); CHECK(same(p, "new"), "这次重新克隆成了:工作目录 a 回到 new"); + snprintf(p, sizeof p, "%s.re", work); CHECK(access(p, F_OK) != 0, "没有 .re 残留"); + CHECK(write_save("save:/a", "good") == RES_OK && h_fs_Commit("save") == RES_OK, "下一个事务写 a=good,提交成功"); + snprintf(p, sizeof p, "%s/a", save); CHECK(same(p, "good"), "已提交 a = good"); + // ⑥b 改名后写客体名失败、回退也失败:不退出;文件在事务存档里 → 本事务提交被拒、已提交版不变;重新克隆后照常 + // 6b Writing the guest name after a rename fails and the rollback fails too: do not exit; the file is in a transactional save, so this transaction's commit is refused and the committed version is unchanged; after recloning everything works + setenv("DM_TEST_FS_FAILAT", "guestname:1,renameback:1", 1); + h_fs_CreateFile("save:/c", 0); CHECK(write_save("save:/c", "c") == RES_OK, "写 c"); + CHECK(h_fs_RenameFile("save:/c", "save:/d") != RES_OK, "改名 c → d 返回失败(两步都注入失败),进程还在"); + nf0 = g_nfail; CHECK(h_fs_Commit("save") == RES_FAIL && g_nfail == nf0 + 1, "本事务提交被拒"); + snprintf(p, sizeof p, "%s/c", save); CHECK(access(p, F_OK) != 0, "已提交目录没有 c"); + snprintf(p, sizeof p, "%s/d", save); CHECK(access(p, F_OK) != 0, "已提交目录没有 d"); + snprintf(p, sizeof p, "%s/a", save); CHECK(same(p, "good"), "已提交 a 仍是 good"); + CHECK(write_save("save:/a", "ok2") == RES_OK && h_fs_Commit("save") == RES_OK, "下一个事务照常提交"); + // ⑥c 挂载时克隆工作目录失败:不退出,改成只读挂载已提交目录——读得到、写不进、提交是空操作、已提交版不变、前端通知 1 次;下次正常挂载照旧 + // 6c Cloning the work directory at mount fails: do not exit; mount the committed directory read-only instead. Reads work, writes fail, commits are no-ops, the committed version is unchanged, and the front end is notified once; the next normal mount works as before + setenv("DM_TEST_FS_FAILAT", "mountclone:1", 1); g_nmnt = 0; nf0 = g_nfail; + snprintf(p, sizeof p, "rm -rf '%s'", work); system(p); + CHECK(h_fs_MountSave("save", NULL) == RES_OK && g_nfail == nf0 + 1, "挂载返回成功、前端通知 1 次(实际 %d 次)", g_nfail - nf0); + CHECK(read_fs("save:/a", got, sizeof got) && !strcmp(got, "ok2"), "只读挂载下读得到已提交的 a=ok2(读到 %s)", got); + CHECK(write_save("save:/a", "zzz") != RES_OK, "写不进去"); + CHECK(h_fs_Commit("save") == RES_OK, "提交是空操作"); + snprintf(p, sizeof p, "%s/a", save); CHECK(same(p, "ok2"), "已提交 a 仍是 ok2"); + unsetenv("DM_TEST_FS_FAILAT"); g_nmnt = 0; + CHECK(h_fs_MountSave("save", NULL) == RES_OK && write_save("save:/a", "ok3") == RES_OK && h_fs_Commit("save") == RES_OK, "去掉注入重新挂载:事务式照常,写 a=ok3 提交成功"); + snprintf(p, sizeof p, "%s/a", save); CHECK(same(p, "ok3"), "已提交 a = ok3"); + // 语言开关改写设置文件(settings_lang_apply):期望值按规则手算——只在「与开关不符」时把 Language / VoiceLanguage 改成 0(英文)或 8(简中),别的键和别的语言不动 // Language switch rewriting the settings file (settings_lang_apply): expected values computed by hand from the rule -- only when it "does not match the switch" are Language / VoiceLanguage changed to 0 (English) or 8 (Simplified Chinese); other keys and other languages are untouched { extern int g_t_lang; char sd[1200], sf[1300], gotj[512]; snprintf(sd, sizeof sd, "%s/langt", root); mkdir(sd, 0755); snprintf(sf, sizeof sf, "%s/Settings", sd); mkdir(sf, 0755); snprintf(sf, sizeof sf, "%s/Settings/Settings.json", sd); diff --git a/dm/host/touch_mac.c b/dm/host/touch_mac.c index 666e241..ee20568 100644 --- a/dm/host/touch_mac.c +++ b/dm/host/touch_mac.c @@ -60,11 +60,17 @@ static void touch_uimsg(const char *cat, const char *act, const char *arg) { scene.game = 1; dm_tc_set_panel_state(dm_ui_panel_state()); int navigation = dm_tc_navigation(&scene, cat, act, arg); - // 真全屏(16:10 的 Mac,front_mac.m):局内开大面板时界面整块移到正中、上下留同样宽的边,关掉回落贴底——iPad 的做法,判据同 front_ios.m 的 nmode == 1: - // 面板模式,且不是只开着 NPC 对话菜单(菜单跟着 NPC 摆,留在贴底)、不是死亡页。没开真全屏时宿主不动 - // True full screen (16:10 Mac, front_mac.m): in game with a large panel open the interface moves as a block to the centre with equal bars above and below, and drops back to the bottom when closed - the iPad approach, same criterion as nmode == 1 in front_ios.m: - // panel mode, and not only the NPC dialogue menu open (the menu follows the NPC and stays at the bottom), and not the death page. Without true full screen the host does nothing - dm_uiscreen_set_panel(navigation && !dm_tc_scene_dead() && !dm_tc_scene_dialog_only(&scene)); + // 面板模式与 iOS 同一个量:面板开合栈(宿主 dm_hud_stack_msg)与算式(dm_tc_panel_mode)两端共用。栈里还开着非常驻面板就算面板态—— + // 大秘境确认页这类借壳面板不在手势层的名单里,原先 Mac 上它开着时界面不居中(iPad 居中)。 + // 用途只有一个:真全屏(16:10 的 Mac,front_mac.m)下面板态界面整块移到正中、关掉回落贴底(iPad 的做法);没开真全屏时宿主不动。 + // 手势层自己的导航态(下面 dm_tc_set_navigation_mode)仍按 navigation,鼠标的点击分流不变 + // Panel mode is the same quantity as on iOS: the panel stack (host dm_hud_stack_msg) and the formula (dm_tc_panel_mode) are shared by both ends. While a non-resident panel is still open in the stack, it is panel mode. + // Borrowed panels such as the Greater Rift confirmation page are not on the gesture layer's list, so before, with one of them open, the UI was not centered on Mac (it was on iPad). + // It has only one use: in true fullscreen (16:10 Macs, front_mac.m), panel-mode UI moves as a whole to the center and drops back to the bottom when closed (the iPad behavior); without true fullscreen the host does nothing. + // The gesture layer's own navigation state (dm_tc_set_navigation_mode below) still follows navigation, and mouse click routing is unchanged + { int dm_hud_stack_msg(const char *, const char *); static int blocked; + if (!strcmp(cat, "PanelManager")) blocked = dm_hud_stack_msg(act, arg ? arg : ""); + dm_uiscreen_set_panel(dm_tc_panel_mode(navigation || (scene.game && blocked > 0), &scene, blocked) == 1); } if (g_touch.enabled) { dm_tc_set_navigation_mode(&g_touch.state, navigation); static int pad = -1; if (pad < 0) { const char *e = getenv("DM_TOUCH_NAV_PAD"); pad = e && e[0] == '1'; } // 缺省不给圆钮(同 front_ios.m) | no round button by default (same as front_ios.m) diff --git a/dm/i18n/literal_whitelist.tsv b/dm/i18n/literal_whitelist.tsv index 5ca538c..c905225 100644 --- a/dm/i18n/literal_whitelist.tsv +++ b/dm/i18n/literal_whitelist.tsv @@ -116,3 +116,5 @@ ios/Sources/dm_shader_prep.m * 公开版壳专用的「首次准备着色器」 host/dm_rift.c (第 1 波) 只进日志:刷守护者那行标第几波(分波时) host/dm_rift.c (第 2 波) 同上 host/dm_rift.c (第 3 波) 同上 +ios/Sources/main.m 安装包自检没过 拦下原因只进日志(弹框文字走中英表) +ios/Sources/main.m 图形芯片不支持 Metal 3 拦下原因只进日志(弹框文字走中英表) diff --git a/dm/i18n/ui_text.tsv b/dm/i18n/ui_text.tsv index 7d6ddae..3c2cfbf 100644 --- a/dm/i18n/ui_text.tsv +++ b/dm/i18n/ui_text.tsv @@ -163,6 +163,12 @@ dmOldWhySuffix \n(%s) \n(%s) 老机型弹框正文末尾的原因 dmOldDl 直接下载 Download 老机型弹框按钮 dmOldCopied 已经拷好了 Already Copied 老机型弹框按钮 dmOldQuit 退出 Quit 老机型弹框按钮 +dmPackBadTitle 这个安装包还不能玩 This Package Is Not Ready 安装包自检弹框标题(main.m pack_check:装了没做过第一步的壳 / 拼装的包) +dmPackBadMiss 安装包里缺游戏内容(缺 %d 项,如 %@)。 The package is missing game content (%d items, e.g. %@). 安装包自检弹框正文第一句:缺壳清单里的项 +dmPackBadProd 安装包是用不同版本拼成的(壳是 %@,做进去的内容是 %@)。 The package mixes versions (shell %@, built-in content %@). 安装包自检弹框正文第一句:打包记录的产物代号与壳不一致 +dmPackBadHow 发布页上的壳是做安装包的原料,不能直接装来玩。\n\n怎么做:在电脑上打开 github.com/jhaizhou-ops/d2r-mobile,照 docs/NO_XCODE 的第一步用 d2rm_pack.py 把你的游戏内容做进同一版本的壳,再装它输出的那个安装包。 The shell on the releases page is build input, not an app to install.\n\nWhat to do: on a computer, open github.com/jhaizhou-ops/d2r-mobile and follow step 1 of docs/NO_XCODE — run d2rm_pack.py to build your game content into the shell of the same release, then install the package it outputs. 安装包自检弹框正文后段(缺项与版本不一致共用) +dmGpuOldTitle 这台设备玩不了 This Device Is Not Supported 图形芯片不支持 Metal 3 时的弹框标题(main.m) +dmGpuOldMsg 这台设备的图形芯片不支持 Metal 3,本游戏的图形层需要它。\n\n需要 A14 / M1 及以后的芯片(iPhone 12 及以后、2021 年及以后的 iPad Pro 等);A13 及更早的芯片(包括 2020 年的 iPad Pro)玩不了。 This device's graphics chip does not support Metal 3, which the game's graphics layer needs.\n\nAn A14 / M1 chip or later is required (iPhone 12 and later, iPad Pro from 2021 and later, and so on); A13 and earlier chips, including the 2020 iPad Pro, cannot run it. 图形芯片不支持 Metal 3 时的弹框正文(main.m) dmOldConnecting 正在连接下载服务器… Connecting to the download server… 老机型补充包下载页 dmOldDlFail 下载失败:%s Download failed: %s 老机型补充包:没用上的原因 dmOldProgress 正在下载老机型补充包\n%.2f / %.2f GB(%.0f%%)%@ Downloading the supplementary pack\n%.2f / %.2f GB (%.0f%%)%@ 老机型补充包下载页进度 diff --git a/dm/ios/Sources/dm_touch_controls.c b/dm/ios/Sources/dm_touch_controls.c index f244dc7..ccba3a5 100644 --- a/dm/ios/Sources/dm_touch_controls.c +++ b/dm/ios/Sources/dm_touch_controls.c @@ -298,6 +298,9 @@ static _Atomic int g_imbue_open; /* 单件任务槽面板开着(灌魔 / 打 static _Atomic int g_cube_open; /* 赫拉迪克方块页开着:双击 = 按住 Y(原版「移到另一侧」:背包 → 方块 / 方块 → 背包),不是「使用 / 装备」 | Horadric Cube page open: double tap = hold Y (the original game's "move to the other side": inventory → cube / cube → inventory), not "use / equip" */ static _Atomic int g_vault_open; /* 储藏箱开在第六页「编年史」:双击背包物品 = 存进编年史仓库(走 use_seq,宿主 ui_use_pump 判页),不发原版「按住 Y」——那一页游戏当魔盒页 | Stash open on page six 「编年史」(Chronicle): double-tapping an inventory item = store it in the Chronicle vault (goes through use_seq; the host's ui_use_pump determines the page); do not send the original game's "hold Y" -- the game treats that page as the cube page */ static _Atomic int g_bank_open; /* 储藏箱开着(前端从宿主读游戏面板树的结果设进来,不靠开关消息):双击 = 按住 Y(移到另一侧) | Stash open (set by the front end from the host's reading of the game panel tree, not from open/close messages): double tap = hold Y (move to the other side) */ +int dm_tc_panel_mode(int nav, const dm_tc_scene *scene, int blocked) { /* 原在 front_ios.m(nmode);菜单上又开了雇佣列表这类页时读数 > 0,不算「只开着对话菜单」 | formerly in front_ios.m (nmode); when a page such as the hire list is also open over the menu the reading is > 0, which does not count as "only the dialog menu open" */ + return nav ? (dm_tc_scene_dead() ? 2 : dm_tc_scene_dialog_only(scene) && blocked <= 0 ? 3 : 1) : 0; +} void dm_tc_set_panel_state(int bits) { atomic_store(&g_bank_open, (bits & 1) != 0); atomic_store(&g_vendor_open, (bits & 2) != 0); atomic_store(&g_dead_modal, (bits & 4) != 0); atomic_store(&g_imbue_open, (bits & 16) != 0); atomic_store(&g_cube_open, (bits & 32) != 0); atomic_store(&g_vault_open, (bits & 64) != 0); } /* 位同 dm_cursor.h 的 DM_PS_*;宿主读游戏状态得来 | Bits are the same as DM_PS_* in dm_cursor.h; obtained by the host reading the game state */ static void pointer_drag_begin(dm_tc_state *s, dm_tc_finger *f) { diff --git a/dm/ios/Sources/dm_touch_controls.h b/dm/ios/Sources/dm_touch_controls.h index 6912cdd..beaf8ac 100644 --- a/dm/ios/Sources/dm_touch_controls.h +++ b/dm/ios/Sources/dm_touch_controls.h @@ -135,6 +135,11 @@ typedef struct { int game; uint64_t panels; } dm_tc_scene; int dm_tc_navigation(dm_tc_scene *scene, const char *cat, const char *act, const char *arg); int dm_tc_scene_dialog_only(const dm_tc_scene *scene); /* 只开着 NPC 对话菜单 | Only the NPC dialog menu is open */ int dm_tc_scene_dead(void); /* 死亡弹窗开着(导航态,但不给手柄圆钮) | Death popup open (navigation state, but no controller round buttons) */ +/* 面板模式(前端两端共用一个算式,iOS front_ios.m 与 Mac touch_mac.c):0 = 游戏态;1 = 面板态;2 = 死亡页;3 = 只开着 NPC 对话菜单。 + nav = 手势层的导航判断(dm_tc_navigation,再并上「面板栈里还开着非常驻面板」);blocked = 面板栈读数(dm_hud_stack_msg:只开着对话菜单时 -1) + Panel mode (one formula shared by both front ends, iOS front_ios.m and Mac touch_mac.c): 0 = game; 1 = panel; 2 = death screen; 3 = only the NPC dialog menu open. + nav = the gesture layer's navigation judgment (dm_tc_navigation, combined with "a non-resident panel is still open in the panel stack"); blocked = the panel stack reading (dm_hud_stack_msg: -1 when only the dialog menu is open) */ +int dm_tc_panel_mode(int nav, const dm_tc_scene *scene, int blocked); /* 坐标使用 UIKit 点;布局本身不画球、不声称游戏已绑定回城/腰带。 | Coordinates use UIKit points; the layout itself does not draw the orbs and does not claim the game has bound town portal/belt. */ /* 安全区左右内缩(点);在 init / resize 之前设,之后的布局按它把右侧技能键组与左摇杆移进安全区。缺省 0。 | Left/right safe-area insets (points); set before init / resize, and the layout afterwards uses them to move the right-side skill key group and the left stick into the safe area. Default 0. */ diff --git a/dm/ios/Sources/front_ios.m b/dm/ios/Sources/front_ios.m index cb3aaae..784c735 100644 --- a/dm/ios/Sources/front_ios.m +++ b/dm/ios/Sources/front_ios.m @@ -750,65 +750,16 @@ static BOOL touch_done(UITouch *t) { UITouchPhase ph=t.phase; return ph==UITouch // 底部 UI v4 的 UIKit 底栏只在「局内常态」画:维护面板开合栈,常驻 HUD 层之外任何面板开着就不画(未知面板默认让开,免挡游戏自己的画面)。 // 常驻层 = 营地无操作时 OpenPanel 后一直不关的 13 个(实测 UI 消息流)+ 存档提示 / 通知 / 组队消息 / 帮助按钮 / 手柄提示层 / 自动地图(战斗叠加) // 名单在宿主 dm_cursor.c 的 dm_ui_panel_resident(面板状态安全阀同用一份) -// The UIKit bottom bar of bottom UI v4 is drawn only in the "normal in-run state": maintain a panel open / close stack, and do not draw when any panel other than the always-on HUD layers is open (unknown panels yield by default, to avoid covering the game's own picture). -// Always-on layers = the 13 that stay open after OpenPanel when idle in camp (measured UI message stream) + save hint / notification / party message / help button / controller hint layer / automap (combat overlay) -// The list is in the host's dm_cursor.c dm_ui_panel_resident (shared with the panel state safety valve) -enum { HUD_STACK_MAX=64 }; -static struct { char name[64]; int open; } g_hud_stack[HUD_STACK_MAX]; -static _Atomic int g_hud_blocked; // 栈里还开着的非常驻面板数 | Number of panels other than the always-on layers still open in the stack +// 面板开合栈搬到宿主 dm_cursor.c(dm_hud_stack_msg,Mac touch_mac.c 共用同一份);这里只记「连续多久非零」并通知 UIKit 底栏让开 +// The UIKit bottom bar of bottom UI v4 is only drawn in the normal in-game state: maintain the panel stack; whenever any panel other than the resident HUD layers is open, it is not drawn (unknown panels make way by default so they do not cover the game's own picture). +// Resident layers = the 13 panels that are opened and never closed in camp when idle (measured from the UI message stream) + save notice / notifications / party messages / help button / gamepad hint layer / automap (combat overlay). +// The list is dm_ui_panel_resident in the host's dm_cursor.c (shared with the panel state safety valve). +// The panel stack moved to the host's dm_cursor.c (dm_hud_stack_msg, shared with Mac touch_mac.c); here we only track how long it has been non-zero and tell the UIKit bottom bar to make way +int dm_hud_stack_msg(const char *act, const char *arg); void dm_hud_stack_dump(void); +static _Atomic int g_hud_blocked; // 栈读数:开着的非常驻面板数(只开着 NPC 对话菜单时 -1) | Stack reading: number of open non-resident panels (-1 when only the NPC dialog menu is open) static uint64_t g_hud_blocked_since; static void hud_stack_message(const char *act,const char *arg) { - // 读取画面撤下:清掉此刻在游戏面板树里已经看不见的记录(防只开不关的漏配),屏上还在的照记—— - // 通关页是读取画面撤下前 0.5 秒开的(OpenExclusivePanel EndScreenPanelExpansion → UnloadPanel LoadScreenPanel),原先整栈清零把它也清了: - // 底栏和技能钮盖在通关页上、点「好」变成点世界 - // Loading screen removed: clear the records no longer visible in the game's panel tree at this moment (guards against open-without-close mismatches), and keep those still on screen -- - // the game-completion page is opened 0.5 seconds before the loading screen is removed (OpenExclusivePanel EndScreenPanelExpansion → UnloadPanel LoadScreenPanel); previously the whole stack was zeroed, clearing it too: - // the bottom bar and skill buttons covered the game-completion page, and tapping 「好」(OK) became a world tap - if(!strcmp(act,"UnloadPanel") && !strcmp(arg,"LoadScreenPanel")) { - for(int i=0;i0 && strcmp(g_hud_stack[i].name,"LoadScreenPanel") && dm_ui_panel_shown(g_hud_stack[i].name)) fprintf(stderr,"[hud] 面板栈 读取画面撤下:%s 屏上还在,照记\n",g_hud_stack[i].name); - else memset(&g_hud_stack[i],0,sizeof g_hud_stack[i]); - } - } - else if(!strcmp(act,"UnloadAll")) memset(g_hud_stack,0,sizeof g_hud_stack); - else { - // PanelManager 的面板动作全集(读码:它的消息分发 main+0xb1dc60 只认这 8 个,与全部日志里出现过的一致): - // OpenPanel / OpenExclusivePanel = 开;ClosePanel / UnloadPanel = 关(读取画面那条见上);TogglePanel = 按当前记录翻转(高级属性页走它); - // UnloadAll = 全清(见上);LoadPanel = 预载、不上屏,不算开关;HideGameInfo = 隐藏游戏信息层,与面板开关无关 - // Full set of PanelManager panel actions (from reading the code: its message dispatch main+0xb1dc60 only recognizes these 8, matching what has appeared across all logs): - // OpenPanel / OpenExclusivePanel = open; ClosePanel / UnloadPanel = close (for the loading screen one see above); TogglePanel = flip according to the current record (the advanced stats page uses it); - // UnloadAll = clear all (see above); LoadPanel = preload without showing, not counted as open or close; HideGameInfo = hide the game info layer, unrelated to panel open / close - int tog=!strcmp(act,"TogglePanel"); - int open=!strcmp(act,"OpenPanel")||!strcmp(act,"OpenExclusivePanel"), close=!strcmp(act,"ClosePanel")||!strcmp(act,"UnloadPanel"); - if(!open && !close && !tog) return; - if(dm_ui_panel_resident(arg)) return; - int slot=-1; for(int i=0;i0) { fprintf(stderr,"[hud] 面板栈 %s %s:已经开着,不重复计\n",act,arg); return; } - g_hud_stack[slot].open=open?1:0; - fprintf(stderr,"[hud] 面板栈 %s %s → %d\n",act,arg,g_hud_stack[slot].open); - } - // NPC 对话菜单(交谈 / 交易…那一小列)不挡底栏:只开着它时底栏照常显示(否则 UIKit 层让开、露出游戏层那份底栏,难度格和回城书不见、腰带样子也变)。 - // 编码进同一个数:对话菜单开着且没有别的面板 → -1(底栏不让开、且免除导航态的隐藏) - // The NPC dialog menu (the small column of Talk / Trade…) does not block the bottom bar: with only it open the bottom bar shows as usual (otherwise the UIKit layer yields and exposes the game layer's bottom bar; the difficulty cell and Tome of Town Portal disappear and the belt looks different too). - // Encoded into the same number: dialog menu open with no other panel → -1 (the bottom bar does not yield, and navigation-mode hiding is waived) - int n=0, dlg=0; for(int i=0;i0; else n+=g_hud_stack[i].open; } // ScrollSpeechPanel = NPC 说话的滚动文字框(屏幕上方一小块),同样不挡底栏 | ScrollSpeechPanel = the scrolling text box of NPC speech (a small block at the top of the screen); it likewise does not block the bottom bar - if(!n && dlg) n=-1; + int n=dm_hud_stack_msg(act,arg); uint64_t t=now_ns(); if(n>0 && !g_hud_blocked_since) g_hud_blocked_since=t; if(n<=0) g_hud_blocked_since=0; @@ -823,7 +774,7 @@ static void hud_stack_message(const char *act,const char *arg) { static void hud_stack_watch(void) { if(g_hud_blocked_since && now_ns()-g_hud_blocked_since>60000000000ull) { fprintf(stderr,"[hud] 面板栈已连续 60 秒非零(线索,非缺陷):"); - for(int i=0;i= 200000000ull) break; - if (t - t0 >= 2500000000ull) break; - } + dm_save_wait(2.5, &n, &froze, &ms); // 游戏停着(暂停菜单开着)时冻住世界、临时放开暂停存这一次,存完写回(diag.c) | If the game is stopped (pause menu open), freeze the world and temporarily release the pause for this one save, then write it back (diag.c) mtl_present_discard(0); - LOG("前端:进后台等游戏存盘 %.0f ms,期间存档提交 %llu 次%s", (now_ns() - t0) / 1e6, (unsigned long long)(last - c0), last == c0 ? "【红】(2.5 秒内没等到)" : ""); + LOG("前端:进后台等游戏存盘 %.0f ms,期间存档提交 %llu 次%s%s", ms, (unsigned long long)n, froze ? "(原先暂停着:冻结世界存盘、已恢复暂停)" : "", n ? "" : "【红】(2.5 秒内没等到)"); } // 失活时也请游戏存一次盘(查 #22 发现的缺口):上划进多任务界面时 App 多半只「失活」、不进后台,在那里直接划掉进程 // 走不到进后台的存盘,丢掉距上次定时存盘(游戏 5 分钟一次)以来的进度。只置游戏「下一拍就自动存盘」的计时(同 dm_request_save),不等提交、不挡主线程; @@ -1479,7 +1423,7 @@ void front_ios_lifecycle_install(void) { LOG("前端:测试回前台(DM_TEST_BG)"); mtl_link_pause(0); front_ios_focus_event(2); front_ios_focus_event(3); uint64_t c0 = dm_audio_render_calls(); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2000000000), dispatch_get_main_queue(), ^{ - LOG("前端:测试回前台后 2 s 声卡回调 +%llu(客体时钟 %.3f s)", (unsigned long long)(dm_audio_render_calls() - c0), guest_ns() / 1e9); }); }); + int dm_game_paused(void); LOG("前端:测试回前台后 2 s 声卡回调 +%llu(客体时钟 %.3f s;原版暂停 %d)", (unsigned long long)(dm_audio_render_calls() - c0), guest_ns() / 1e9, dm_game_paused()); }); }); } // 测试开关 DM_TEST_RESIGN=秒:到点只发「失活」(sceneWillResignActive),不进后台——模仿上划停在多任务界面;配合测试脚本随后 kill -9 = 在多任务界面里划掉 // Test switch DM_TEST_RESIGN=seconds: at that time send only "resign active" (sceneWillResignActive) without going to background -- mimics swiping up and stopping in the app switcher; combined with the test script's subsequent kill -9 = swiping it away in the app switcher diff --git a/dm/ios/Sources/main.m b/dm/ios/Sources/main.m index c575249..401b43a 100644 --- a/dm/ios/Sources/main.m +++ b/dm/ios/Sources/main.m @@ -365,11 +365,20 @@ static int g_pack_wait; // 托管资源包的目录已经在、系统还没说 static int g_doc_stray; // 另一条附带结论:「D2R Mobile」里有文件夹但没有一个是资源(why = 现有哪些文件夹),托管资源包也没到——照常去试托管下载,下载站也走不通时把 why 给玩家看 | The other side conclusion: 「D2R Mobile」 has folders but none of them is assets (why = which folders exist now), and the hosted asset pack has not arrived either -- try the hosted download as usual, and show why to the player when the download site is unreachable too // 本包有没有配置苹果的托管资源包(Info.plist 的 BAHasManagedAssetPacks)。没配置的包(免费账号档、不带游戏内容的壳:tools/project_free.py、 // tools/shell_build.sh 把那几项去掉了)一碰 BAAssetPackManager,系统接口内部断言直接让进程退出——真机实测:没有资源的第一次启动必崩。 -// 所以凡是要问那个接口的地方先问这里。 -// Whether this bundle is configured with Apple managed asset packs (BAHasManagedAssetPacks in Info.plist). In a bundle without it (the free-account build and the shell with no game content: tools/project_free.py and -// tools/shell_build.sh remove those keys), merely touching BAAssetPackManager trips an assertion inside the system framework and the process exits -- measured on a device: the first launch with no resources always crashed. -// So every place that is about to ask that framework asks here first. -static BOOL ba_configured(void) { return [[NSBundle.mainBundle objectForInfoDictionaryKey:@"BAHasManagedAssetPacks"] boolValue]; } +// 所以凡是要问那个接口的地方先问这里。另一种同样会崩的包:Info.plist 还声明着,但签名里没有它要的 app group(用自己的 Apple ID / 自签工具重签的 +// 包——描述文件里没有我们的 app group):系统 Swift 层报「app group … is inaccessible」致命错误。所以还要核声明的 app group 拿得到容器目录(拿不到 = 签名没带这项权限) +// Whether this package configures Apple's managed asset packs (BAHasManagedAssetPacks in Info.plist). In packages without it (the free-account build, and the shell without game content: tools/project_free.py and +// tools/shell_build.sh remove those entries), touching BAAssetPackManager makes an assertion inside the system interface terminate the process; measured on a device, the first launch without resources always crashed. +// So every place that would ask that interface asks here first. Another kind of package crashes the same way: Info.plist still declares it, but the signature lacks the app group it needs (packages re-signed with your own Apple ID / a sideloading tool, +// whose provisioning profile does not include our app group): the system Swift layer raises a fatal "app group ... is inaccessible" error. So we also check that the declared app group returns a container directory (none = the signature does not carry that entitlement) +static BOOL ba_configured(void) { + static int v = -1; if (v >= 0) return v; + NSString *g = [NSBundle.mainBundle objectForInfoDictionaryKey:@"BAAppGroupID"]; + if (![[NSBundle.mainBundle objectForInfoDictionaryKey:@"BAHasManagedAssetPacks"] boolValue]) v = 0; + else if (!g.length || ![NSFileManager.defaultManager containerURLForSecurityApplicationGroupIdentifier:g]) { v = 0; plog("boot: 本包声明了托管资源包,但签名里没有它要的 app group「%s」(自签 / 重签的包),不走托管资源包", g.UTF8String ?: "未声明"); } + else v = 1; + return v; +} static NSString *romfs_locate(char *why, size_t n) { g_doc_bad = 0; g_doc_stray = 0; @@ -507,6 +516,51 @@ static BOOL astc_dl_configured(void) { // 自动下载地址配了没有:测 for (NSString *l in [t componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]) { NSString *v = [l stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet]; if (v.length && ![v hasPrefix:@"#"]) return YES; } return NO; } +// 安装包自检(只查从发布页的壳做出来的包:壳带着 dm/shell_manifest.txt;Xcode 出的包没有它,不查)。壳清单里每一项都要由 d2rm_pack.py 做进来, +// 缺 = 装的是没做过第一步的壳(或拼装的包)——起宿主会在装载器读 dm/main.fixups.tsv 处退出(线上闪退)。另比产物代号:打包记录 dm/pack_info.txt 与壳的 +// dm/shell_info.txt(两份都在才比,旧版打包工具不写打包记录)。不过就不起宿主,弹框说明缺什么、该做哪一步 +// Install package self-check (only for packages made from the shell on the releases page: the shell carries dm/shell_manifest.txt; packages built with Xcode do not have it and are not checked). Every item in the shell manifest must have been built in by d2rm_pack.py; +// missing = the shell was installed without doing step 1 (or the package was assembled), and starting the host would exit where the loader reads dm/main.fixups.tsv (a crash for players). The product generation is also compared: the pack record dm/pack_info.txt against the shell's +// dm/shell_info.txt (only when both exist; older pack tools did not write a pack record). If the check fails, do not start the host; show a message saying what is missing and which step to do +static NSString *g_block_title, *g_block_msg, *g_block_why; // 非空 = 这台设备 / 这个安装包起不了游戏:不起宿主,场景里弹框(BlockVC)说明;why 进日志 | Non-empty = this device / this install package cannot start the game: do not start the host, show a message in the scene (BlockVC); why goes to the log +static NSString *g_romfs; static char g_romfs_why[2048]; // 起宿主前那次资源校验的结果(host_start 写,boot_prepare 用) | Result of the resource check before starting the host (written by host_start, used by boot_prepare) +static UIWindow *g_window; +static NSString *kv_file(NSString *path, NSString *key) { + NSString *t = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; + for (NSString *l in [t componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]) if ([l hasPrefix:[key stringByAppendingString:@"="]]) return [l substringFromIndex:key.length + 1]; + return nil; +} +static NSString *pack_check(void) { + NSString *app = NSBundle.mainBundle.resourcePath; NSFileManager *fm = NSFileManager.defaultManager; + // 只测试用:DM_TEST_PACK_MANIFEST=<文件,相对 Documents> 换一份壳清单、DM_TEST_PACK_INFO=<文件> 换一份打包记录(Xcode 包里没有壳信息时,同一文件的 SHELL_PRODUCT= 充当壳的代号;造「缺项」「代号不一致」现场,不动包内文件、不破签名) + // Test only: DM_TEST_PACK_MANIFEST= substitutes the shell manifest and DM_TEST_PACK_INFO= substitutes the pack record (in an Xcode package, which has no shell info, SHELL_PRODUCT= in the same file stands in for the shell's generation), to create "missing item" and "generation mismatch" cases without touching files in the package or breaking the signature + NSString *(^tpath)(const char *) = ^NSString *(const char *e) { if (!e) return nil; NSString *p = @(e); return [p hasPrefix:@"/"] ? p : // 相对路径按 Documents 解析(沙盒读不到容器外;真机容器路径每次变) | Relative paths are resolved against Documents (the sandbox cannot read outside the container, and the device container path changes every time) + [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:p]; }; + NSString *tm = tpath(getenv("DM_TEST_PACK_MANIFEST")), *ti = tpath(getenv("DM_TEST_PACK_INFO")); + NSString *man = [NSString stringWithContentsOfFile:tm ?: [app stringByAppendingPathComponent:@"dm/shell_manifest.txt"] encoding:NSUTF8StringEncoding error:nil]; + if (!man) { plog("boot: 安装包自检:没有壳清单(Xcode 出的包),不查"); return nil; } + NSMutableArray *miss = [NSMutableArray array]; int total = 0; + for (NSString *l in [man componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]) { + NSString *m = [l stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet]; if (!m.length) continue; total++; + BOOL dir = NO; if (![fm fileExistsAtPath:[app stringByAppendingPathComponent:m] isDirectory:&dir] || dir != [m hasSuffix:@"/"]) [miss addObject:m]; } + if (miss.count) { + plog("boot: 🔴 安装包自检:壳清单 %d 项缺 %lu 项:%s", total, (unsigned long)miss.count, [miss componentsJoinedByString:@", "].UTF8String); + return [NSString stringWithFormat:T("dmPackBadMiss"), (int)miss.count, [[miss subarrayWithRange:NSMakeRange(0, MIN(miss.count, (NSUInteger)3))] componentsJoinedByString:@", "]]; } + NSString *sp = kv_file([app stringByAppendingPathComponent:@"dm/shell_info.txt"], @"PRODUCT") ?: (ti ? kv_file(ti, @"SHELL_PRODUCT") : nil), *pp = kv_file(ti ?: [app stringByAppendingPathComponent:@"dm/pack_info.txt"], @"PRODUCT"); + if (sp && pp && ![sp isEqualToString:pp]) { plog("boot: 🔴 安装包自检:壳的产物代号 %s,打包记录 %s,不一致", sp.UTF8String, pp.UTF8String); return [NSString stringWithFormat:T("dmPackBadProd"), sp, pp]; } + plog("boot: 安装包自检通过:壳清单 %d 项齐全;产物代号 壳 %s / 打包记录 %s", total, sp.UTF8String ?: "无", pp.UTF8String ?: "无(旧版打包工具)"); + return nil; +} +@interface BlockVC : UIViewController @end +@implementation BlockVC +- (void)viewDidAppear:(BOOL)animated { + [super viewDidAppear:animated]; static int shown; if (shown++) return; + UIAlertController *a = [UIAlertController alertControllerWithTitle:g_block_title message:g_block_msg preferredStyle:UIAlertControllerStyleAlert]; + [a addAction:[UIAlertAction actionWithTitle:T("dmOldQuit") style:UIAlertActionStyleCancel handler:^(UIAlertAction *x) { plog("boot: 玩家点了「退出」(%s)", g_block_why.UTF8String); exit(0); }]]; + [self presentViewController:a animated:YES completion:nil]; + plog("boot: 已弹框(%s)|屏上标题:%s|正文:%s", g_block_why.UTF8String, a.title.UTF8String, [a.message stringByReplacingOccurrencesOfString:@"\n" withString:@" ⏎ "].UTF8String); +} +@end @interface NoBcVC : UIViewController @property (strong) UILabel *label; @property (strong) UIProgressView *bar; @property (assign) BOOL shown; @end @implementation NoBcVC - (void)viewDidLoad { @@ -561,10 +615,10 @@ static void boot_prepare(void) { NSFileManager *fm = NSFileManager.defaultManager; [fm createDirectoryAtPath:romfs withIntermediateDirectories:YES attributes:nil error:nil]; NSURL *romURL = [NSURL fileURLWithPath:romfs]; NSNumber *excluded = @YES; [romURL setResourceValue:excluded forKey:NSURLIsExcludedFromBackupKey error:nil]; - char romwhy[2048]; - NSString *found = romfs_locate(romwhy, sizeof romwhy); + const char *romwhy = g_romfs_why; + NSString *found = g_romfs; // host_start 起宿主前刚校验过(唯一一次);没过的不会走到这里 | host_start checked right before starting the host (the only time); failures never reach here if (!found) { - plog("boot: 🔴 RomFS 校验失败:%s", romwhy); + plog("boot: 🔴 RomFS 没经过起宿主前的校验(不应发生):%s", romwhy); plog("boot: 请推送原版 RomFS:xcrun devicectl device copy to --device <设备> --domain-type appDataContainer --domain-identifier <包名> --source $DM_ROOT/data/switch/3.3.94012/Update/RomFS --destination 'Library/Application Support/romfs'"); abort(); } @@ -685,6 +739,9 @@ static void log_promote(void) { // 场景第一次到前台:这一轮是玩 static void host_start(void) { if (g_host_up) return; if (getenv("DM_TEST_BG_RELAUNCH")) return; // 这次启动只为造后台拉起(见 bg_relaunch_test),马上自己退出 | this launch exists only to stage a background relaunch (see bg_relaunch_test) and exits by itself right away + { NSString *r = romfs_locate(g_romfs_why, sizeof g_romfs_why); // 资源校验:起宿主前只在这里做一次(boot_prepare 用这次结果)。没过(启动判定之后资源被挪 / 删)就回资源界面,不闪退 | Resource check: done only once, here, before starting the host (boot_prepare uses this result). If it fails (resources moved / deleted after the launch decision), go back to the resources screen instead of crashing + if (!r) { plog("boot: 起宿主前资源校验没过(%s),回到资源界面", g_romfs_why); if (g_window) astc_handoff(g_window); return; } + g_romfs = r; } #ifdef DM_SHELL // 壳:着色器是以源码进包的话,进游戏之前先一次编完(dm_shader_prep.m,带进度页);做完它回头再调这里 // Shell: if the shaders are shipped as source in the package, compile them all in one go before entering the game (dm_shader_prep.m, with a progress page); when done it calls back here @@ -1009,10 +1066,11 @@ static void astc_handoff(UIWindow *w) { // 补充包到位(玩家刚拷好 / @implementation SceneDelegate - (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)s options:(UISceneConnectionOptions *)o { UIWindowScene *ws = (UIWindowScene *)scene; - self.window = [[UIWindow alloc] initWithWindowScene:ws]; + self.window = [[UIWindow alloc] initWithWindowScene:ws]; g_window = self.window; UIViewController *vc = [DmGameVC new]; vc.view.backgroundColor = UIColor.blackColor; - if ([g_mode isEqualToString:@"boot"] && g_no_bc) { vc = [NoBcVC new]; vc.view.backgroundColor = UIColor.blackColor; } // 本机型不支持:只弹框 | This device model is not supported: only show an alert + if ([g_mode isEqualToString:@"boot"] && g_block_title) { vc = [BlockVC new]; vc.view.backgroundColor = UIColor.blackColor; } // 图形芯片不支持 / 安装包不完整:只弹框 | Graphics chip not supported / install package incomplete: only show the message + else if ([g_mode isEqualToString:@"boot"] && g_no_bc) { vc = [NoBcVC new]; vc.view.backgroundColor = UIColor.blackColor; } // 本机型不支持:只弹框 | This device model is not supported: only show an alert else if ([g_mode isEqualToString:@"boot"] && g_need_assets) vc = [AssetVC new]; // 资源包没到:下载界面 | Asset pack not here yet: download screen else if ([g_mode isEqualToString:@"boot"]) vc.view = front_ios_view(ws.coordinateSpace.bounds); // 图形后端出图的层(不叠任何控件) | The layer the graphics backend presents into (no widgets stacked on it) else if ([g_mode isEqualToString:@"blank"]) { UIView *front_ios_blank_view(CGRect); vc.view = front_ios_blank_view(ws.coordinateSpace.bounds); } // 发热负对照 | Heat negative control @@ -1027,7 +1085,7 @@ static void astc_handoff(UIWindow *w) { // 补充包到位(玩家刚拷好 / } - (void)sceneWillResignActive:(UIScene *)s { if (g_host_up) front_ios_focus_event(0); } - (void)sceneDidEnterBackground:(UIScene *)s { if (g_host_up) front_ios_focus_event(1); } -- (void)sceneWillEnterForeground:(UIScene *)s { log_promote(); if ([g_mode isEqualToString:@"boot"] && !g_need_assets && !g_no_bc) { host_start(); if (g_host_up) front_ios_focus_event(2); } } +- (void)sceneWillEnterForeground:(UIScene *)s { log_promote(); if ([g_mode isEqualToString:@"boot"] && !g_need_assets && !g_no_bc && !g_block_title) { host_start(); if (g_host_up) front_ios_focus_event(2); } } - (void)sceneDidBecomeActive:(UIScene *)s { if (g_host_up) front_ios_focus_event(3); } // 场景断开 / App 终止:宿主有序收尾后 _exit(hle_lifecycle.c)。注意:用户在多任务界面划掉一个已在后台挂起的 App 时,系统直接 SIGKILL,不走这两个回调 // Scene disconnect / App termination: the host shuts down in order, then _exit (hle_lifecycle.c). Note: when the user swipes away an App already suspended in the background from the multitasking screen, the system sends SIGKILL directly and neither of these two callbacks runs @@ -1171,13 +1229,23 @@ int main(int argc, char *argv[]) { metal_cache_report_and_clean(); char why[2048]; { id dev = MTLCreateSystemDefaultDevice(); g_no_bc = !dev.supportsBCTextureCompression || getenv("DM_TEST_NO_BC"); + // 图形层要 Metal 3(参数缓冲里直接写 gpuAddress 的无绑定用法):A14 / M1(Apple7 家族)起才有,A13 及更早不支持。不支持就不起游戏、弹框说明(不再走到解包 / 建管线时闪退)。 + // 测试开关 DM_TEST_NO_METAL3=1 当成不支持 + // The graphics layer needs Metal 3 (bindless use that writes gpuAddress directly into argument buffers): available from A14 / M1 (the Apple7 family); A13 and earlier do not support it. If unsupported, do not start the game and show a message (instead of crashing later while unpacking / building pipelines). + // Test switch DM_TEST_NO_METAL3=1 treats the device as unsupported + if (![dev supportsFamily:MTLGPUFamilyMetal3] || getenv("DM_TEST_NO_METAL3")) { + g_block_title = T("dmGpuOldTitle"); g_block_msg = T("dmGpuOldMsg"); g_block_why = @"图形芯片不支持 Metal 3"; + plog("boot: 🔴 显卡 %s 不支持 Metal 3%s——不起游戏,弹框说明", dev.name.UTF8String, getenv("DM_TEST_NO_METAL3") ? "(测试开关 DM_TEST_NO_METAL3)" : ""); } plog("boot: 显卡 %s,BC 压缩格式%s", dev.name.UTF8String, g_no_bc ? (getenv("DM_TEST_NO_BC") ? "按测试开关 DM_TEST_NO_BC 当成不支持" : "不支持——不起游戏,弹框说明后退出") : "支持"); } if (g_no_bc) { // 不支持 BC:有配套的老机型补充包就照常起(覆盖层换 ASTC 版,见 boot_prepare),没有就弹框 | BC not supported: if the matching Legacy Device Pack is present, start as usual (the overlay switches to the ASTC version, see boot_prepare); otherwise show an alert NSString *d = astc_pack_locate(g_astc_why, sizeof g_astc_why); if (d) { g_astc_dir = d; g_no_bc = 0; plog("boot: 用老机型补充包 %s", d.UTF8String); } else plog("boot: 老机型补充包未就绪:%s", g_astc_why); } - if (g_no_bc) {} + NSString *pb = g_block_title ? nil : pack_check(); + if (pb) { g_block_title = T("dmPackBadTitle"); g_block_msg = [NSString stringWithFormat:@"%@\n\n%@", pb, T("dmPackBadHow")]; g_block_why = @"安装包自检没过"; } + if (g_block_title) {} // 起不了游戏:不起宿主,场景里弹框(BlockVC) | The game cannot start: do not start the host; show a message in the scene (BlockVC) + else if (g_no_bc) {} else if (getenv("DM_ASSETS_TEST") || getenv("DM_TEST_BA")) { g_need_assets = 1; plog("boot: DM_ASSETS_TEST——强制走资源下载界面再就地起宿主(测这条路径)"); } else if (romfs_locate(why, sizeof why)) plog("boot: 游戏资源就绪,宿主等场景到前台再装载"); else { g_need_assets = 1; plog("boot: 游戏资源还没到(%s),先显示资源下载界面", why); } diff --git a/dm/ios/tools/shell_build.sh b/dm/ios/tools/shell_build.sh index b41ed9e..ba53d7c 100755 --- a/dm/ios/tools/shell_build.sh +++ b/dm/ios/tools/shell_build.sh @@ -3,26 +3,26 @@ # 做进去,再用自签工具整包签名装机——全程不需要 Xcode,也不需要 Mac。 # shell_build.sh [ios|mac] ios(缺省)= 真机用的壳;mac = 「Mac 上跑的 iOS 包」变体,只给我们自己在 Mac 上验这条路用 # 产物($DM_ROOT/build/shell//): -# D2RMobile-shell.ipa 壳。里面没有:游戏程序、着色器库、覆盖层、界面素材、任何从游戏文件生成的表 +# D2RMobile-shell-build-input.zip 壳(构建原料,不能直接安装:不用 .ipa 扩展名,自签工具认不出来;装上去缺游戏内容也只会弹框说明)。里面没有:游戏程序、着色器库、覆盖层、界面素材、任何从游戏文件生成的表 # shell_manifest.txt 壳里缺的东西的清单(安装包内路径,一行一个;以 / 结尾 = 整个目录)。d2rm_pack.py 照它核对做全了没有 # ref/ 对照:用本机游戏文件生成的那些内容(不发布,只用来核对工具的产出) # 做法:把源码树拷到临时副本里构建,不动当前工作树(三份「从游戏文件生成、编进代码」的文件要换成替身,换在副本里)。 # 出壳的这台机器要有游戏文件与全套构建环境(和平时出包一样):要用真实的生成结果定表的大小、定清单。 -# Build the "shell": an unsigned install package with no game content at all. Users use their own game files (dm/tools/d2rm_pack.py) to put the game program and derived content -# into it, then sign the whole package with a sideloading tool and install it -- no Xcode and no Mac needed at any point. -# shell_build.sh [ios|mac] ios (default) = the shell for real devices; mac = the "iOS app running on Mac" variant, only for ourselves to verify this path on a Mac -# Build outputs ($DM_ROOT/build/shell//): -# D2RMobile-shell.ipa The shell. Not inside: game program, shader libraries, overlay, UI assets, any table generated from the game files -# shell_manifest.txt Manifest of what the shell lacks (paths inside the install package, one per line; ending with / = a whole directory). d2rm_pack.py checks against it whether everything has been made -# ref/ Reference: the content generated from this machine's game files (not published, only used to check the tool's output) -# Approach: copy the source tree to a temporary copy and build there, leaving the current worktree untouched (the three files "generated from the game files and compiled into the code" have to be replaced with stubs, and the replacing is done in the copy). -# The machine that builds the shell must have the game files and the full build environment (same as for a normal package build): the real generation results are needed to fix the table sizes and the manifest. +# Build the "shell": an unsigned install package with no game content. Users build the game program and derived content into it from their own game files (dm/tools/d2rm_pack.py), +# then sign the whole package with a sideloading tool and install it, with no Xcode and no Mac needed. +# shell_build.sh [ios|mac] ios (default) = the shell for devices; mac = the "iOS package running on Mac" variant, only for us to check this path on a Mac +# Output ($DM_ROOT/build/shell//): +# D2RMobile-shell-build-input.zip the shell (build input, not installable: it does not use the .ipa extension so sideloading tools do not recognize it; installed as is, it lacks the game content and only shows a message). It does not contain: the game program, shader library, overlay, UI art, or any table generated from the game files +# shell_manifest.txt list of what the shell lacks (paths inside the package, one per line; a trailing / = a whole directory). d2rm_pack.py checks against it that everything was built in +# ref/ reference: that content generated from the local game files (not published, only used to check the tool's output) +# Method: copy the source tree to a temporary copy and build there, leaving the current work tree alone (three files that are generated from the game files and compiled into the code are replaced with stand-ins, in the copy). +# The machine that builds the shell needs the game files and the full build environment (same as a normal build): the real generated results determine the table sizes and the manifest. set -u KIND=${1:-ios}; case $KIND in ios|mac) ;; *) echo "用法:shell_build.sh [ios|mac]"; exit 2;; esac HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd); SRC=$(cd "$HERE/../.." && pwd) # SRC = dm/ ROOT=${DM_ROOT:-$HOME/dm-work}; O=$ROOT/build/shell/$KIND; W=$O/tree; DD=$O/dd t() { echo "[$(date +%T)] $*"; }; die() { t "🔴 $*"; exit 1; } -mkdir -p "$O" && rm -rf "$W" "$O/ref" "$O/app" "$O/D2RMobile-shell.ipa" "$O/shell_manifest.txt" && mkdir -p "$W" "$O/ref" || die "建不了 $O" +mkdir -p "$O" && rm -rf "$W" "$O/ref" "$O/app" "$O/D2RMobile-shell-build-input.zip" "$O/shell_manifest.txt" && mkdir -p "$W" "$O/ref" || die "建不了 $O" rsync -a --exclude '/ios/Gen' --exclude '/ios/DmIOS.xcodeproj' --exclude '.iosdd*' --exclude '/ios/local.env' "$SRC/" "$W/dm/" || die "拷源码树失败" # 壳的包名只是占位:自签工具装机时会换成使用者自己的。团队号同理(不签名,用不到) # The shell's package name is only a placeholder: the sideloading tool replaces it with the user's own at install time. Same for the team ID (not signed, so it is not used) @@ -104,5 +104,5 @@ for d, _, fs in os.walk(app): print('内容核对:%d 个特征串(另有 %d 个是源码里本来就有的,不算)× %d 个文件,命中 %d 个文件' % (len(needles), len(own), sum(len(fs) for _, _, fs in os.walk(app)), bad)); sys.exit(1 if bad else 0) PYEOF ( cd "$A" && find . -type f | sort | while read -r f; do printf '%s\t%s\n' "$(stat -f %z "$f")" "$f"; done ) > "$O/shell_files.tsv" -( cd "$O" && rm -rf Payload && mkdir Payload && cp -R app Payload/DmIOS.app && zip -qry D2RMobile-shell.ipa Payload && rm -rf Payload ) || die "打包失败" -t "壳:$O/D2RMobile-shell.ipa($(du -h "$O/D2RMobile-shell.ipa" | cut -f1),$(wc -l < "$O/shell_files.tsv" | tr -d ' ') 个文件);缺的内容 $(wc -l < "$O/shell_manifest.txt" | tr -d ' ') 项,清单 $O/shell_manifest.txt" +( cd "$O" && rm -rf Payload && mkdir Payload && cp -R app Payload/DmIOS.app && zip -qry D2RMobile-shell-build-input.zip Payload && rm -rf Payload ) || die "打包失败" +t "壳:$O/D2RMobile-shell-build-input.zip($(du -h "$O/D2RMobile-shell-build-input.zip" | cut -f1),$(wc -l < "$O/shell_files.tsv" | tr -d ' ') 个文件);缺的内容 $(wc -l < "$O/shell_manifest.txt" | tr -d ' ') 项,清单 $O/shell_manifest.txt" diff --git a/dm/tools/d2rm_pack.py b/dm/tools/d2rm_pack.py index 76c1121..6dfe7a3 100755 --- a/dm/tools/d2rm_pack.py +++ b/dm/tools/d2rm_pack.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 # 不用 Xcode 出可玩的安装包:把你自己的游戏文件做进「壳」。 -# 壳(D2RMobile-shell.ipa)是一个不含任何游戏内容、没有签名的安装包;本工具用你的游戏文件在你的电脑上生成它缺的全部内容 +# 壳(D2RMobile-shell-build-input.zip,构建原料、不能直接安装)是一个不含任何游戏内容、没有签名的安装包;本工具用你的游戏文件在你的电脑上生成它缺的全部内容 # (改写后的游戏程序、着色器库、覆盖层、界面素材、几张数据表),放进去,写出一个新的安装包。之后用自签工具整包签名装机。 # 游戏文件只在本机读,不上传;做出来的安装包里有游戏内容,请只自己用,不要分发。 # 用法:d2rm_pack.py <壳.ipa> <游戏文件目录> <输出.ipa> @@ -10,17 +10,17 @@ # 需要:Python 3.9+ 与 pillow numpy lz4 capstone unicorn;C 编译器(clang 或 gcc,解贴图的小段 C 用);.NET SDK(编着色器翻译工具); # spirv-cross;苹果的 Metal 着色器编译器(Mac 上随 Xcode)。缺什么本工具开头会逐项报。 # 它做的事与「./setup.sh + dm/ios/run.sh build 的生成部分」相同,只是最后不调 Xcode 构建,而是把产物放进壳里。 -# Build a playable install package without Xcode: put your own game files into the "shell". -# The shell (D2RMobile-shell.ipa) is an unsigned install package with no game content at all; this tool uses your game files to generate, on your computer, everything it lacks -# (the rewritten game program, shader libraries, overlay, UI assets, a few data tables), puts it in, and writes out a new install package. Afterwards sign the whole package with a sideloading tool and install it. -# The game files are only read locally and never uploaded; the resulting install package contains game content, so please use it only yourself and do not distribute it. -# Usage: d2rm_pack.py -# game files directory = the Update directory of Switch version 3.3.94012, containing ExeFS/{main,sdk} and RomFS/data/... (how to export it from your own game) -# working directory (cache and intermediate outputs, about 12 GB): environment variable DM_ROOT, default ~/dm-work; every step already done is skipped -# Older devices (A16 and earlier chips): make the texture pack first, then run this tool with the environment variable D2RM_ASTC_PACK= -# Requires: Python 3.9+ with pillow numpy lz4 capstone unicorn; a C compiler (clang or gcc, for the small piece of C that decodes textures); the .NET SDK (to build the shader translation tool); -# spirv-cross; Apple's Metal shader compiler (on a Mac it comes with Xcode). This tool reports whatever is missing item by item at the start. -# What it does is the same as "./setup.sh + the generation part of dm/ios/run.sh build", except that at the end it does not invoke an Xcode build but puts the build outputs into the shell. +# Make a playable install package without Xcode: build your own game files into the "shell". +# The shell (D2RMobile-shell-build-input.zip, build input, not installable) is an unsigned install package with no game content; this tool generates everything it lacks from your game files on your computer +# (the rewritten game program, shader library, overlay, UI art and a few data tables), puts it in, and writes a new install package. Then sign the whole package with a sideloading tool and install it. +# Your game files are only read locally and never uploaded; the package you make contains game content, so keep it for yourself and do not distribute it. +# Usage: d2rm_pack.py +# game files dir = the Update directory of the Switch version 3.3.94012, containing ExeFS/{main,sdk} and RomFS/data/... (how to export it from your own game) +# Work directory (cache and intermediates, about 12 GB): environment variable DM_ROOT, default ~/dm-work; every step that is already done is skipped +# Older devices (A16 and earlier chips): build the texture pack first, then run this tool with D2RM_ASTC_PACK= +# Requires: Python 3.9+ with pillow numpy lz4 capstone unicorn; a C compiler (clang or gcc, for a small C texture decoder); the .NET SDK (to build the shader translator); +# spirv-cross; Apple's Metal shader compiler (comes with Xcode on a Mac). The tool lists anything missing at the start. +# It does the same as the generation part of ./setup.sh + dm/ios/run.sh build, except that instead of building with Xcode it puts the results into the shell. import hashlib, json, os, re, runpy, shutil, subprocess, sys, time, zipfile HERE = os.path.dirname(os.path.abspath(__file__)); DM = os.path.dirname(HERE); IOS = os.path.join(DM, 'ios'); GT = os.path.join(DM, 'gfx', 'tools') @@ -237,10 +237,15 @@ def main(): if ('b-' + chain) not in open(c1, encoding='utf-8').readline(): die('着色器下标清单首行的链版本不是壳要的 %s' % chain) say('自检:%d 个着色器说明、下标清单、目录名的链版本都是壳要的 %s;翻译出的源码摘要 %s%s' % (len(js), chain, got, '与壳一致' if info.get('SHADER_SRC') else '(这个壳没带摘要,没比)')) + # 打包记录:做进去的内容是哪个产物代号。壳启动时与 dm/shell_info.txt 的代号比,不一致(拼装出来的包)就弹框说明、不起游戏(main.m pack_check) + # Pack record: which product generation was built in. At launch the shell compares it with the generation in dm/shell_info.txt; if they differ (a package assembled from different releases) it shows a message and does not start the game (main.m pack_check) + with open(os.path.join(stage, 'dm', 'pack_info.txt'), 'w', encoding='utf-8') as f: f.write('PRODUCT=%s\n' % P) + extra = extra + ['dm/pack_info.txt'] + # 六、照壳的清单核对一项不缺,再放进去 # 6. Check against the shell's manifest that nothing is missing, then put it in miss = [m for m in manifest if not (os.path.isdir(os.path.join(stage, m)) if m.endswith('/') else os.path.isfile(os.path.join(stage, m)))] - if miss: die('有 %d 项没做出来:%s。壳的清单里要、而这份工具没有生成——壳与工具不是同一版。请用与这份仓库同一版本的壳(发布页最新的 D2RMobile-shell.ipa),或把仓库更新到与壳对应的版本' % (len(miss), '、'.join(miss))) + if miss: die('有 %d 项没做出来:%s。壳的清单里要、而这份工具没有生成——壳与工具不是同一版。请用与这份仓库同一版本的壳(发布页最新的 D2RMobile-shell-build-input.zip),或把仓库更新到与壳对应的版本' % (len(miss), '、'.join(miss))) tmp = out_ipa + '.part'; added = 0 with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED, compresslevel=6) as o: for i in z.infolist(): o.writestr(i, z.read(i.filename)) diff --git a/docs/NO_XCODE.md b/docs/NO_XCODE.md index f68bb5b..840c2f6 100644 --- a/docs/NO_XCODE.md +++ b/docs/NO_XCODE.md @@ -15,9 +15,11 @@ The normal route is to build the whole app with Xcode on a Mac (see "Building" o ## What the shell contains and does not contain -Download the shell from this repository's [Releases page](https://github.com/jhaizhou-ops/d2r-mobile/releases). There are two on the Releases page: `D2RMobile-shell.ipa` for iOS 26 and later, `D2RMobile-shell-ios18.ipa` for iOS 18 – 25 ([OLDER_SYSTEMS.md](OLDER_SYSTEMS.md)); pick the one for your phone's system, the steps after that are the same. The shell (about 4 MB) contains only our own host program, the icon and two tables that are public in this repository. It does **not** contain: the game program, shaders, the overlay, UI art, or any data table generated from game files. The script that builds the shell (`dm/ios/tools/shell_build.sh`) finishes by searching every file in the shell for real game content, and refuses to produce a shell if it finds any. +Download the shell from this repository's [Releases page](https://github.com/jhaizhou-ops/d2r-mobile/releases). There are two on the Releases page: `D2RMobile-shell-build-input.zip` for iOS 26 and later, `D2RMobile-shell-ios18-build-input.zip` for iOS 18 – 25 ([OLDER_SYSTEMS.md](OLDER_SYSTEMS.md)); pick the one for your phone's system, the steps after that are the same. The shell (about 4 MB) contains only our own host program, the icon and two tables that are public in this repository. It does **not** contain: the game program, shaders, the overlay, UI art, or any data table generated from game files. The script that builds the shell (`dm/ios/tools/shell_build.sh`) finishes by searching every file in the shell for real game content, and refuses to produce a shell if it finds any. -The shell cannot start by itself: on launch it tells you that this package has no game program in it yet. +**The shell is build input, not an app to install** (which is why it is a `.zip`, not an `.ipa`). If you rename it and install it as is, the app shows a "This Package Is Not Ready" dialog on launch, lists what is missing and points you back to step 1 below; it does not start the game. + +**Every time you move to a new release, redo step 1 with the new shell and the source of the same release**, then install the package you just made. The resource archives you put on the phone in step 3 do not depend on the version and do not need to be copied again. ## What you need @@ -41,7 +43,7 @@ The tool lists whatever is missing, item by item, when it starts. ## Step 1: put the game content into the shell ``` -python3 dm/tools/d2rm_pack.py +python3 dm/tools/d2rm_pack.py ``` `` is the level that contains `ExeFS/` and `RomFS/`. In order, the tool: rewrites the game program and writes it out as a dynamic library → generates UI art and a few data tables from the game files → generates the overlay → translates the game's shaders to Metal → checks against the list inside the shell that nothing is missing → writes the new package (about 130 MB). The first run takes a bit over ten minutes, mostly translating shaders; every step is skipped once done. diff --git a/docs/NO_XCODE.zh-CN.md b/docs/NO_XCODE.zh-CN.md index e3e1a75..41405b3 100644 --- a/docs/NO_XCODE.zh-CN.md +++ b/docs/NO_XCODE.zh-CN.md @@ -15,9 +15,11 @@ English: [NO_XCODE.md](NO_XCODE.md) ## 壳里有什么、没有什么 -壳从本仓库的[发布页](https://github.com/jhaizhou-ops/d2r-mobile/releases)下载。发布页上有两份:`D2RMobile-shell.ipa` 给 iOS 26 及以上,`D2RMobile-shell-ios18.ipa` 给 iOS 18 – 25([OLDER_SYSTEMS.zh-CN.md](OLDER_SYSTEMS.zh-CN.md)),按手机的系统挑一份,后面的步骤相同。壳(约 4 MB)里只有我们自己的宿主程序、图标和两张随仓库公开的表。它**没有**:游戏程序、着色器、覆盖层、界面素材、任何从游戏文件生成的数据表。构建壳的脚本(`dm/ios/tools/shell_build.sh`)在最后会拿真实的游戏内容去壳里逐个文件搜一遍,搜到就不出壳。 +壳从本仓库的[发布页](https://github.com/jhaizhou-ops/d2r-mobile/releases)下载。发布页上有两份:`D2RMobile-shell-build-input.zip` 给 iOS 26 及以上,`D2RMobile-shell-ios18-build-input.zip` 给 iOS 18 – 25([OLDER_SYSTEMS.zh-CN.md](OLDER_SYSTEMS.zh-CN.md)),按手机的系统挑一份,后面的步骤相同。壳(约 4 MB)里只有我们自己的宿主程序、图标和两张随仓库公开的表。它**没有**:游戏程序、着色器、覆盖层、界面素材、任何从游戏文件生成的数据表。构建壳的脚本(`dm/ios/tools/shell_build.sh`)在最后会拿真实的游戏内容去壳里逐个文件搜一遍,搜到就不出壳。 -壳自己起不来——它启动时会告诉你「这个安装包里还没有游戏程序」。 +**壳是做安装包的原料,不能直接装来玩**(所以它是 `.zip`,不是 `.ipa`)。把它改名直接装上去,App 启动时会弹框「这个安装包还不能玩」,列出缺的内容,告诉你回到下面第一步;不会进游戏。 + +**每次换新版本,都要用新版的壳和同一版本的源码重新做一遍第一步**,再装新做出来的安装包。手机上第三步放的资源档案和版本无关,不用重拷。 ## 你需要准备的 @@ -41,7 +43,7 @@ English: [NO_XCODE.md](NO_XCODE.md) ## 第一步:把游戏内容做进壳 ``` -python3 dm/tools/d2rm_pack.py <你的游戏文件目录> <输出.ipa> +python3 dm/tools/d2rm_pack.py <你的游戏文件目录> <输出.ipa> ``` `<你的游戏文件目录>` 是含 `ExeFS/` 与 `RomFS/` 的那一层。它依次:改写游戏程序并写成一个动态库 → 从游戏文件生成界面素材与几张数据表 → 生成覆盖层 → 把游戏的着色器翻译成 Metal → 照壳里的清单核对一项不缺 → 写出新的安装包(约 130 MB)。第一次约十几分钟,主要花在翻译着色器上;每一步做过就跳过。 diff --git a/docs/OLDER_SYSTEMS.md b/docs/OLDER_SYSTEMS.md index 3652ac0..3e4ca43 100644 --- a/docs/OLDER_SYSTEMS.md +++ b/docs/OLDER_SYSTEMS.md @@ -36,8 +36,8 @@ The Releases page has two shells. Pick the one for your system; every other step | Shell | For | |---|---| -| `D2RMobile-shell.ipa` | iOS 26 and later | -| `D2RMobile-shell-ios18.ipa` | iOS 18 – 25 | +| `D2RMobile-shell-build-input.zip` | iOS 26 and later | +| `D2RMobile-shell-ios18-build-input.zip` | iOS 18 – 25 | The packaging tool accepts both shells with the same command. For A16 and earlier devices add `D2RM_ASTC_PACK` as well (see the "Older devices" section of NO_XCODE) — the texture pack depends only on the chip, and both shells use the same pack. diff --git a/docs/OLDER_SYSTEMS.zh-CN.md b/docs/OLDER_SYSTEMS.zh-CN.md index 085a2d3..17232e9 100644 --- a/docs/OLDER_SYSTEMS.zh-CN.md +++ b/docs/OLDER_SYSTEMS.zh-CN.md @@ -36,8 +36,8 @@ DM_IOS_M3=1 ./run.sh build | 壳 | 给谁 | |---|---| -| `D2RMobile-shell.ipa` | iOS 26 及以上 | -| `D2RMobile-shell-ios18.ipa` | iOS 18 – 25 | +| `D2RMobile-shell-build-input.zip` | iOS 26 及以上 | +| `D2RMobile-shell-ios18-build-input.zip` | iOS 18 – 25 | 做包工具两份壳都认,命令不变。A16 及更早的机型同样加 `D2RM_ASTC_PACK`(见 NO_XCODE 的「老机型」一节)——贴图包只和芯片有关,两份壳用的是同一个贴图包。