diff --git a/README.md b/README.md index 5287d83..8d5caaa 100644 --- a/README.md +++ b/README.md @@ -191,11 +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 | -| **Chips older than A15, devices with 4 GB of RAM** | No reports yet | Same as the row above | If you have tried, please open an Issue and tell us | +| **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 | +| **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 | — | — | @@ -210,6 +214,8 @@ flowchart LR Both routes start with **the files of the game you bought**: the Switch release of Diablo II: Resurrected plus the Reign of the Warlock expansion, updated to 1.0.34.0 (the version the console shows; it corresponds to PC version 3.3.94012, and the directory names and tools in this repository use the latter number). This project is built for the version with that expansion; using it without the expansion is not supported and has not been verified. How to prepare them is in [docs/GAME_FILES.md](docs/GAME_FILES.md). +> This project provides only tools and an install shell that contains no game content. We do not distribute or endorse, and are not responsible for, any third party distributing game assets, game executables or install packages that contain game content. Please use only game files you legally own. + This project is implemented and verified on the Switch release 1.0.34.0 (which corresponds to PC version 3.3.94012), and by default the tools accept only that version. Community users have reported adapting other versions on their own by following the structure of this repository, and running them successfully. The rule tables are grouped by game version (in `dm/tools/patch_nso.py`, keyed by the build ID of the main program); you are welcome to contribute the version you adapted. **Check your device first**: the "Which devices are supported" table above tells you which build to use and whether you also need a Legacy Device Pack. @@ -264,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 @@ -319,6 +325,20 @@ The cleaner arrangement is to move these defaults into per-game configuration an **You must own the game, including the Reign of the Warlock expansion.** This is an independent, non-commercial project. It is not affiliated with, endorsed by, or sponsored by Blizzard Entertainment or Nintendo. Diablo and Blizzard Entertainment are trademarks of Blizzard Entertainment, Inc.; Nintendo Switch is a trademark of Nintendo. Use it only with a copy of the game that you own. +## Acknowledgements + +This project stands on the open-source work below. Thank you to its authors and maintainers. + +- **Ryujinx** (Ryubing 1.3.2, MIT): `dm/third_party/ryujinx` bundles its shader translator unchanged (the Ryujinx.Graphics.Shader, Spv.Generator and Ryujinx.Common projects), which translates the Switch game's shaders to SPIR-V. During development we also ran the original game in a patched Ryujinx as the reference for comparing pictures and game state (see [dm/verify/README.md](dm/verify/README.md); the scripts that build and drive it are not in this repository). +- **deko3d** (devkitPro, zlib): the texture layout size algorithm in `dm/gfx/nvn/nvn_tex.c` is ported from it. +- **nvn.h** (h1k421, MIT): the graphics API declarations in `dm/gfx/nvn/include/nvn.h`. +- **libdeflate** (Eric Biggers, MIT): decompressing game data. +- **bcdec** (iOrange, MIT or Unlicense): decoding BC textures on devices that do not support the BC formats. +- **FLIP** (NVIDIA, BSD 3-Clause): the image difference metric used in image-quality checks. +- **Offline fix patch** (LFS Mod Offline Fix): the 7 rewrites in `dm/tools/patch_nso.py` that let the game run offline come from this community patch. We have no reliable record of where it was first published or who wrote it; if you know, please open an Issue. +- Tools used to build and verify: SPIRV-Cross (SPIR-V to Metal Shading Language), XcodeGen, .NET, Capstone and Unicorn (disassembly and equivalence checks of the rewrites), Pillow, numpy, lz4, astcenc (the Legacy Device Pack), hactool (extracting files from a game package), libimobiledevice and LLVM. Versions and links are in [docs/DEPENDENCIES.md](docs/DEPENDENCIES.md). +- Community contributions: Joe Hu reported and diagnosed several Greater Rift issues and proposed a verification matrix; seedds found and diagnosed the render-target view format issue on another port (#36). Both are credited as co-authors on the corresponding commits. + ## License MIT, see [LICENSE](LICENSE). Third-party code keeps its own license in its own directory; see [docs/DEPENDENCIES.md](docs/DEPENDENCIES.md). diff --git a/README.zh-CN.md b/README.zh-CN.md index 0cf7e9a..65e6974 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -191,11 +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 帧档 | -| **比 A15 更老的芯片、4 GB 内存的设备** | 尚无报告 | 同上一行 | 欢迎试过的人开 Issue 告诉我们结果 | +| **4 GB 内存的设备**(如 iPad Air 第 4 代) | 暂不支持(在优化内存,有进展更新) | — | 已有玩家实测:iPad Air 4(A14,4 GB)带上老机型补充包后,启动几秒即因整机内存不足被系统结束 | +| **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** | 不支持 | — | — | @@ -210,6 +214,8 @@ flowchart LR 两条路都要先有**你自己购买的游戏的文件**:Switch 版《暗黑破坏神 II:狱火重生》本体加「术士君临」资料片,更新到 1.0.34.0(主机上显示的版本号;它对应 PC 版的 3.3.94012,本仓库的目录名和工具里用的是后一个号)。本项目是按带这部资料片的版本做的,没有资料片的情况不支持、也没有验过。怎么准备见 [docs/GAME_FILES.zh-CN.md](docs/GAME_FILES.zh-CN.md)。 +> 本项目只提供工具与不含任何游戏内容的安装壳。我们不提供、不认可、也不对任何第三方分发游戏资源、游戏主程序或含游戏内容的安装包的行为负责。请只使用你自己合法拥有的游戏文件。 + 本项目基于 Switch 版 1.0.34.0(对应 PC 版的 3.3.94012)实现并验证,工具默认只认这一版。已有社区用户反馈,参照仓库结构自行适配了其他版本并成功运行。规则表按游戏版本分组存放(`dm/tools/patch_nso.py` 里按主程序的构建标识分组),欢迎把你适配的版本提交回来。 **先对一下你的设备**:上面「支持哪些设备」那张表告诉你该用哪种构建、要不要多做一份老机型补充包。 @@ -264,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)。 ## 已知限制 @@ -319,6 +325,20 @@ DM_MAC_M3=1 dm/tools/mac_app.sh # macOS 15 – 25:产出 D2R Mobile M3.ap **你必须拥有正版游戏,包括「术士君临」资料片。** 这是一个独立的非商业项目,与暴雪娱乐、任天堂没有关联,也未获其认可或赞助。Diablo 与 Blizzard Entertainment 是暴雪娱乐的商标,Nintendo Switch 是任天堂的商标。请只配合你自己拥有的游戏使用。 +## 致谢 + +这个项目建立在下面这些开源工作之上,谢谢各位作者和维护者。 + +- **Ryujinx**(Ryubing 1.3.2,MIT):`dm/third_party/ryujinx` 原样内置了它的着色器翻译库(Ryujinx.Graphics.Shader、Spv.Generator、Ryujinx.Common 三个项目,未修改),用来把 Switch 原版着色器翻译成 SPIR-V。开发过程中,我们还用打了补丁的 Ryujinx 跑原版游戏,作为画面和游戏状态的对照参考(做法见 [dm/verify/README.zh-CN.md](dm/verify/README.zh-CN.md);构建和驱动它的脚本不在本仓库里)。 +- **deko3d**(devkitPro,zlib):`dm/gfx/nvn/nvn_tex.c` 里的贴图排布尺寸算法移植自它。 +- **nvn.h**(h1k421,MIT):图形接口声明 `dm/gfx/nvn/include/nvn.h`。 +- **libdeflate**(Eric Biggers,MIT):解压游戏数据。 +- **bcdec**(iOrange,MIT 或 Unlicense):在不支持 BC 贴图格式的设备上解压 BC 贴图。 +- **FLIP**(NVIDIA,BSD 3-Clause):画质验证里的画面差异度量。 +- **离线修复补丁**(LFS Mod Offline Fix):`dm/tools/patch_nso.py` 里让游戏离线运行的 7 处改写取自这个社区补丁。它的首发处和作者我们没有确切记录,知道的请开 Issue 告诉我们。 +- 构建与验证用到的工具:SPIRV-Cross(把 SPIR-V 转成 Metal 着色语言)、XcodeGen、.NET、Capstone 和 Unicorn(改写前后的反汇编与等价核对)、Pillow、numpy、lz4、astcenc(老机型补充包)、hactool(从游戏包取文件)、libimobiledevice、LLVM。版本和地址见 [docs/DEPENDENCIES.zh-CN.md](docs/DEPENDENCIES.zh-CN.md)。 +- 社区贡献:Joe Hu 报告并定位了多处秘境问题,还提出了验证矩阵;seedds 在另一款游戏的移植中发现并定位了渲染目标视图格式的问题(#36)。他们在相应提交里署名为共同作者。 + ## 许可证 MIT,见 [LICENSE](LICENSE)。第三方代码各自的许可证在其目录内,见 [docs/DEPENDENCIES.zh-CN.md](docs/DEPENDENCIES.zh-CN.md)。 diff --git a/dm/PRODUCT b/dm/PRODUCT index e7d16f0..e77f2f3 100644 --- a/dm/PRODUCT +++ b/dm/PRODUCT @@ -1 +1 @@ -3.3.94012-r42 +3.3.94012-r44 diff --git a/dm/gfx/nvn/hle_nvn.c b/dm/gfx/nvn/hle_nvn.c index c30b777..7d5fa08 100644 --- a/dm/gfx/nvn/hle_nvn.c +++ b/dm/gfx/nvn/hle_nvn.c @@ -246,6 +246,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); @@ -258,7 +328,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; } @@ -295,6 +365,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) { @@ -340,11 +411,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; } @@ -355,7 +426,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) { @@ -406,10 +477,10 @@ NVN(nvnQueueGetError, NVNqueueGetErrorResult, NVNqueue *q, NVNqueueErrorInfo *in } NVN(nvnQueueFlush, void, NVNqueue *q) { (void)q; #ifdef __ANDROID__ - mtl_queue_flush(); + x_drain(); mtl_queue_flush(); #endif } -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 ---------- @@ -578,8 +649,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); @@ -595,7 +666,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)); } @@ -668,23 +739,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; } @@ -780,23 +851,123 @@ 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) +#ifdef __ANDROID__ +#define ANDROID_SYNC_FENCE 1 // Vulkan 后端的栅栏还计读回等内部提交,不与提交数对齐 | the Vulkan backend's fence also counts internal commits such as readbacks and is not aligned with the submit count +#else +#define ANDROID_SYNC_FENCE 0 +#endif +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 && !ANDROID_SYNC_FENCE) { 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) { +#ifdef __ANDROID__ + // Vulkan 后端还没按翻译线程改:提交线程上同步翻译(读回贴图等也会提交,栅栏不等于提交数,见 x_fence) + // The Vulkan backend has not been adapted to the translation thread yet: translate synchronously on the submit thread (texture readbacks also commit, so the fence is not the submit count, see x_fence) + g_x_sync = 1; LOG("[nvn] 安卓:翻译在提交线程上同步做"); return; +#endif + 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); } +#ifdef __ANDROID__ +static uint64_t x_fence(void) { return mtl_last_fence(); } // 同步翻译:Vulkan 后端的最近栅栏(含读回等内部提交) | synchronous translation: the Vulkan backend's latest fence (including internal commits such as readbacks) +#else +static uint64_t x_fence(void) { return atomic_load(&g_x_subs); } +#endif +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(); } @@ -872,10 +1043,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 @@ -894,8 +1061,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); uint64_t pace_t0 = now_ns(); 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); @@ -911,8 +1078,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; } @@ -1010,10 +1177,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); @@ -1068,29 +1241,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); @@ -1140,7 +1312,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); @@ -1226,7 +1400,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 78e37d0..0c999e4 100644 --- a/dm/gfx/nvn/nvn_mtl.m +++ b/dm/gfx/nvn/nvn_mtl.m @@ -273,7 +273,7 @@ void bf_want_note(const char *key) { // ---------- 内存池 ---------- // ---------- Memory pools ---------- -typedef struct { uintptr_t lo, hi; uintptr_t base; __unsafe_unretained id buf; uint64_t gpu; const void *key; } pool_ent; +typedef struct { uintptr_t lo, hi; uintptr_t base; __unsafe_unretained id buf; uint64_t gpu; const void *key; int res; } pool_ent; // res:已放进驻留集(按需,见 pool_res) | res: already put in the residency set (on demand, see pool_res) static pool_ent *g_pools; static int g_npool, g_cap; static NSMutableArray *g_keep; // 持有缓冲引用(pool_ent 里是不持有的指针) | Holds the buffer references (pool_ent has non-owning pointers) static uint64_t g_pool_adds; @@ -407,16 +407,34 @@ uint64_t dm_mtl_l3_sample(uint32_t tick) { } static _Atomic uint64_t g_reg_gen = 1; // 内存池 / 贴图 / 采样器登记的变更代号:参数缓冲复用以它为失效条件之一 | Change generation of memory pool / texture / sampler registration: one of the invalidation conditions for argument buffer reuse +// 内存池按需驻留:零拷贝缓冲放进驻留集,iOS 会把整个池读进内存并钉成 wired(不计入 footprint,也不能被换出),游戏从没用过的池也一样—— +// 真机 17 Pro Max 实测 512 MB 的渲染目标池一局取址 0 次,放进驻留集整机 wired 高约 530 MB;A14 4 GB 机因此启动几秒就被系统按整机缺页结束(公开仓库 #37)。 +// 所以池建好时不放进驻留集,GPU 第一次经 mtl_addr / mtl_gpu_addr 取到它的地址时才放进去,并当场提交驻留集 +// (GPU 拿池地址只有这两个口子;当场提交 = 早于用到它的任何命令缓冲提交,不依赖各提交口自己调 res_commit)。调用方持 g_mu +// On-demand residency of memory pools: putting a zero-copy buffer into the residency set makes iOS read the whole pool into memory and pin it as wired (not counted in footprint and never paged out), even a pool the game never uses - +// measured on a 17 Pro Max: the 512 MB render-target pool is addressed 0 times in a run, and putting it into the residency set raises device wired memory by about 530 MB; this is why an A14 4 GB device was ended by the system for running out of memory within seconds of launch (public repository #37). +// So a pool is not put into the residency set when created; it is put in, and the residency set committed on the spot, the first time the GPU gets its address through mtl_addr / mtl_gpu_addr +// (these are the only two ways the GPU gets pool addresses; committing on the spot = earlier than any command buffer commit that uses it, without relying on each commit point calling res_commit). Caller holds g_mu +static uint64_t g_cb_commits, g_pool_res_at; // 已提交的命令缓冲个数(主提交 + 上传);最近一次按需驻留时的这个数(0 = 没有待核的) | number of command buffers committed (main + upload); this number at the last on-demand residency (0 = nothing pending to check) +static void pool_res(int i) { + if (g_pools[i].res) return; + res_add(g_pools[i].buf); res_commit(); g_pools[i].res = 1; g_pool_res_at = g_cb_commits + 1; + MLOG("内存池按需驻留:%llu MB 的池第一次被取址,已放进驻留集并提交(此时已提交命令缓冲 %llu 个)", + (unsigned long long)((g_pools[i].hi - g_pools[i].lo) >> 20), (unsigned long long)g_cb_commits); +} +static void cb_committed(void) { // 主提交 / 上传提交之后调:核「驻留集提交早于用到它的第一个命令缓冲提交」,每次按需驻留后记一行 | called after the main submission / upload submission: checks that "the residency set commit is earlier than the first command buffer commit that uses it", one line after each on-demand residency + pthread_mutex_lock(&g_mu); uint64_t n = ++g_cb_commits, at = g_pool_res_at; if (at) g_pool_res_at = 0; pthread_mutex_unlock(&g_mu); + if (at) MLOG("内存池按需驻留:其后第一个命令缓冲提交是第 %llu 个(驻留集在第 %llu 个之前已提交)", (unsigned long long)n, (unsigned long long)at); +} void mtl_pool_add(const void *mem, uint64_t size) { mtl_init(); g_reg_gen++; uintptr_t pg = (uintptr_t)getpagesize(), lo = (uintptr_t)mem, hi = lo + size; uintptr_t a = lo & ~(pg - 1), b = (hi + pg - 1) & ~(pg - 1); id buf = [g_dev newBufferWithBytesNoCopy:(void *)a length:b - a options:MTLResourceStorageModeShared deallocator:nil]; if (!buf) MDIE("内存池 %p+%#llx 建零拷贝缓冲失败", mem, (unsigned long long)size); - res_add(buf); pthread_mutex_lock(&g_mu); if (g_npool == g_cap) { g_cap = g_cap ? g_cap * 2 : 64; g_pools = realloc(g_pools, g_cap * sizeof *g_pools); } - g_pools[g_npool++] = (pool_ent){lo, hi, a, buf, buf.gpuAddress, mem}; + g_pools[g_npool++] = (pool_ent){lo, hi, a, buf, buf.gpuAddress, mem, 0}; // 先不进驻留集:第一次被取址时才放进去(pool_res) | not in the residency set yet: put in the first time it is addressed (pool_res) g_pool_adds++; [g_keep addObject:buf]; pthread_mutex_unlock(&g_mu); @@ -437,7 +455,7 @@ int mtl_addr(uint64_t addr, uint64_t len, void **buf, uint64_t *off) { pthread_mutex_lock(&g_mu); for (int i = 0; i < g_npool; i++) if (addr >= g_pools[i].lo && addr + len <= g_pools[i].hi) { - *buf = (__bridge void *)g_pools[i].buf; *off = addr - g_pools[i].base; ok = 1; break; + pool_res(i); *buf = (__bridge void *)g_pools[i].buf; *off = addr - g_pools[i].base; ok = 1; break; } pthread_mutex_unlock(&g_mu); return ok; @@ -447,7 +465,7 @@ int mtl_gpu_addr(uint64_t addr, uint64_t len, void **buf, uint64_t *off, uint64_ pthread_mutex_lock(&g_mu); for (int i = 0; i < g_npool; i++) if (addr >= g_pools[i].lo && addr + len <= g_pools[i].hi) { - *buf = (__bridge void *)g_pools[i].buf; *off = addr - g_pools[i].base; *gpu = g_pools[i].gpu + *off; ok = 1; break; + pool_res(i); *buf = (__bridge void *)g_pools[i].buf; *off = addr - g_pools[i].base; *gpu = g_pools[i].gpu + *off; ok = 1; break; } pthread_mutex_unlock(&g_mu); return ok; @@ -845,6 +863,7 @@ uint64_t mtl_sub_commit(void) { [g_q4 commit:buffers count:1 options:o]; [g_q4 signalEvent:g_ev value:fence]; #endif + cb_committed(); g_alloc_fence[g_alloc_cur] = fence; g_cb = nil; g_commit_blocks = nil; @@ -1137,6 +1156,7 @@ static void up_flush(void) { CBUF buffers[] = {cb}; [g_q4 commit:buffers count:1 options:o]; #endif + cb_committed(); g_up_cb = nil; if (g_up_block) { defer_obj_release(g_up_block); g_up_block = nil; } g_up_block_off = g_up_block_size = 0; for (id obj in g_up_keep) defer_obj_release(obj); [g_up_keep removeAllObjects]; @@ -1827,10 +1847,34 @@ static void rp_end(void) { if (g_enc) { } } void pg_sub_begin_ext(uint64_t fence) { pg_sub_begin(fence); } void pg_commit_ext(id cb) { pg_commit(cb); } -static void attach(MTLRenderPassAttachmentDescriptor *a, const tex_t *t, const view_t *v, int has_v) { - a.texture = tex_mtl(t); +// 颜色附件实际挂上的格式:视图换了格式且挂得上就是视图格式,否则底图格式(挂附件与管线预测共用,口径一致)。warn:挂不上时报红 +// The format a colour attachment is actually attached with: the view's format if the view changes the format and it can be attached, otherwise the base texture's format (shared by attaching and pipeline prediction, so both agree). warn: log red when it cannot be attached +static MTLPixelFormat rt_color_fmt(id base, const view_t *v, int has_v, int warn) { + if (!base || !has_v || !v->set_format) return base.pixelFormat; + uint32_t pf = 0; uint8_t swz[4]; + if (!nvn_fmt_to_mtl(v->format, &pf, swz) || !pf) return base.pixelFormat; + if (pf != (uint32_t)base.pixelFormat && tex_need_pfv(base.pixelFormat, (MTLPixelFormat)pf) && !(base.usage & MTLTextureUsagePixelFormatView)) { + if (warn) RED_ONCE(48, "渲染目标视图格式 %#x 挂不上(底图 %lu 没有换格式用途),按底图格式画(首例)", v->format, (unsigned long)base.pixelFormat); + return base.pixelFormat; } + return (MTLPixelFormat)pf; +} +// color:颜色附件的视图换了格式(如 RGBA8 底图经 RGBA8_SRGB 视图写)就挂该格式的 Metal 视图——Switch 上写入与清除按视图格式编码, +// 只挂底图则 sRGB 编码整个丢掉、画面偏暗(公开仓库 #36,seedds 在另一款游戏上实测);管线颜色格式取挂上的贴图格式(g_pass.cfmt),随之一致。 +// 视图只活到本次提交跑完(Metal 4 不持有资源;视图与底图同一份存储,不单独驻留)。深度 / 模板附件不换格式 +// color: when the view of a colour attachment changes the format (e.g. an RGBA8 base texture written through an RGBA8_SRGB view), attach a Metal view of that format - on the Switch writes and clears are encoded by the view's format, +// and attaching only the base texture drops the sRGB encoding entirely, making the picture too dark (public repository #36, measured by seedds on another game); the pipeline colour formats take the attached texture's format (g_pass.cfmt), so they follow. +// The view lives only until this submission completes (Metal 4 does not retain resources; the view shares storage with the base texture and is not made resident separately). Depth / stencil attachments do not change format +static void attach(MTLRenderPassAttachmentDescriptor *a, const tex_t *t, const view_t *v, int has_v, int color) { + id base = tex_mtl(t); a.texture = base; if (has_v && v->set_levels) a.level = v->base_level; if (has_v && v->set_layers) { if (t->d.target == 2) a.depthPlane = v->min_layer; else a.slice = v->min_layer; } + if (!color || !base) return; + MTLPixelFormat pf = rt_color_fmt(base, v, has_v, 1); + if (pf == base.pixelFormat) return; + id vw = [base newTextureViewWithPixelFormat:pf]; + if (!vw) { RED_ONCE(49, "渲染目标视图建不出:格式 %#x(底图 %lu),按底图格式画(首例)", v->format, (unsigned long)base.pixelFormat); return; } + a.texture = vw; defer_obj_unref(vw); + { static int once; if (!once++) MLOG("渲染目标经换格式的视图挂上:视图格式 %#x,底图 %lu → 挂 %lu(首例)", v->format, (unsigned long)base.pixelFormat, (unsigned long)pf); } } // mode 1(clear_only):只为落地挂起的清除而开的通道,只挂有清除的附件;mode 2:前瞻证明本通道不用深度模板,不挂深度。 // clear_only:只为落地挂起的清除而开的通道,只挂有清除的附件——其余附件本通道不碰,挂上去在 TBDR 上平白一读一写 @@ -1855,7 +1899,7 @@ static RENC rp_begin_ex(int clear_only) { int any = 0; for (int i = 0; i < R.rt.n; i++) { if (!R.rt.color[i] || (clear_only == 1 && !R.clear_c[i])) continue; - attach(pd.colorAttachments[i], R.rt.color[i], &R.rt.cview[i], R.rt.has_cview[i]); + attach(pd.colorAttachments[i], R.rt.color[i], &R.rt.cview[i], R.rt.has_cview[i], 1); if (!pd.colorAttachments[i].texture) continue; any = 1; pd.colorAttachments[i].loadAction = R.clear_c[i] ? MTLLoadActionClear : MTLLoadActionLoad; @@ -1880,14 +1924,14 @@ static RENC rp_begin_ex(int clear_only) { // clear_only:0 全挂 1 只为清除 2 深度模板都不挂 3 只挂模板 4 只挂深度(3 / 4 由 pass_ds_need 前瞻证明整通道只用那一项) // clear_only: 0 attach all 1 only for clears 2 neither depth nor stencil attached 3 stencil only 4 depth only (3 / 4: the pass_ds_need lookahead proves the whole pass uses only that one) if (R.rt.depth && clear_only == 3) { // 只挂模板:合一格式的深度平面不进 tile、不读不写(Metal 允许深度附件空、模板附件挂合一贴图) | Stencil only: the depth plane of the combined format does not enter the tile and is neither read nor written (Metal allows an empty depth attachment with the combined texture on the stencil attachment) - attach(pd.stencilAttachment, R.rt.depth, &R.rt.dview, R.rt.has_dview); + attach(pd.stencilAttachment, R.rt.depth, &R.rt.dview, R.rt.has_dview, 0); MTLPixelFormat pf = pd.stencilAttachment.texture.pixelFormat; if (pf == MTLPixelFormatDepth32Float_Stencil8 || pf == MTLPixelFormatStencil8) { any = 1; pd.stencilAttachment.loadAction = R.clear_s ? MTLLoadActionClear : MTLLoadActionLoad; pd.stencilAttachment.clearStencil = R.cs; pd.stencilAttachment.storeAction = MTLStoreActionStore; } else pd.stencilAttachment.texture = nil; // 没有模板平面:模板测试恒过,什么都不挂 | No stencil plane: the stencil test always passes, attach nothing } else if (R.rt.depth && clear_only != 2 && !(clear_only == 1 && !R.clear_d && !R.clear_s)) { - attach(pd.depthAttachment, R.rt.depth, &R.rt.dview, R.rt.has_dview); + attach(pd.depthAttachment, R.rt.depth, &R.rt.dview, R.rt.has_dview, 0); if (pd.depthAttachment.texture) { any = 1; pd.depthAttachment.loadAction = R.clear_d ? MTLLoadActionClear : MTLLoadActionLoad; @@ -2061,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; @@ -2242,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; @@ -3283,7 +3327,7 @@ static void pso_predict_rest(void) { if (!fz_next(&cur, &q, &hq, &aq)) break; if (hq.op == OP_SET_RT) { const p_set_rt *r = aq; memset(cf, 0, sizeof cf); dfull = sfull = 0; samples = 1; - for (int i = 0; i < r->n && i < 8; i++) { id t = r->color[i] ? tex_mtl(r->color[i]) : nil; if (t) { cf[i] = (uint32_t)t.pixelFormat; samples = (uint32_t)t.sampleCount; } } + for (int i = 0; i < r->n && i < 8; i++) { id t = r->color[i] ? tex_mtl(r->color[i]) : nil; if (t) { cf[i] = (uint32_t)rt_color_fmt(t, &r->cview[i], r->has_cview[i], 0); samples = (uint32_t)t.sampleCount; } } id dt = r->depth ? tex_mtl(r->depth) : nil; if (dt) { MTLPixelFormat f = dt.pixelFormat; samples = (uint32_t)dt.sampleCount; dfull = f != MTLPixelFormatStencil8 ? (uint32_t)f : 0; sfull = (f == MTLPixelFormatStencil8 || f == MTLPixelFormatDepth32Float_Stencil8) ? (uint32_t)f : 0; } @@ -4472,7 +4516,7 @@ static void draw(const p_draw *dw, const p_draw_idx *di) { if (!strncmp(f->key, "ebcfcd1fa0a77dbc", 16) && !g_enc && R.rt.n == 1 && R.rt.color[0] && !R.clear_c[0]) { uint64_t h = 0; for (int i = 0; i < f->rf.nb && !h; i++) if (f->rf.b[i].kind == NVN_RB_TEX && f->rf.b[i].reg < 128) h = S.tex[1][f->rf.b[i].reg]; if (h) { fx_from = R.rt.color[0]->serial; fx_to = h; PD("N %llu 跳过 FXAA:ser=%llu 的读者改读 ser=%llu", g_stat_pass, (unsigned long long)fx_from, (unsigned long long)h_ser(h)); return; } } - else if (fx_from && !strncmp(f->key, "52aac1f2306b8fc5", 16)) { for (int r = 0; r < 128; r++) if (S.tex[1][r] && h_ser(S.tex[1][r]) == fx_from) S.tex[1][r] = fx_to; fx_from = 0; } } } + else if (fx_from && !strncmp(f->key, "52aac1f2306b8fc5", 16)) { for (int r = 0; r < 128; r++) if (S.tex[1][r] && h_ser(S.tex[1][r]) == fx_from) { S.tex[1][r] = fx_to; g_args_dirty[1] = 1; } fx_from = 0; } } } { static uint64_t bloomq_frame; if (bloomq_frame != atomic_load(&g_cur_frame)) { bloomq_frame = atomic_load(&g_cur_frame); bloomq_reset(); } if (bloomq_enabled() && tbdr_on() && !g_defer_replaying && pr->sh[1]) { NvShader *f = pr->sh[1]; uint64_t tgt = 0; int lv, sl; @@ -4501,14 +4545,14 @@ static void draw(const p_draw *dw, const p_draw_idx *di) { } else if (g_bloomq.state == 2 && !strncmp(f->key, "cc264583f2000c81", 16)) { if (bloomq_target(&tgt, &lv, &sl) && tgt == g_bloomq.b0_ser) { g_bloomq.state = 3; PD("C %llu 泛光 1/4 跳过 B0 上采样", g_stat_pass); return; } } else if (g_bloomq.state == 3 && !strncmp(f->key, "2e2d6700a2569795", 16)) { - if (g_bloomq.b1_h) { for (int r = 0; r < 128; r++) if (S.tex[1][r] && h_ser(S.tex[1][r]) == g_bloomq.b0_ser) S.tex[1][r] = g_bloomq.b1_h; PD("D %llu 泛光 1/4 叠加改读 B1", g_stat_pass); g_bloomq_last_b0 = g_bloomq.b0_ser; g_bloomq_last_b1h = g_bloomq.b1_h; g_bloomq_last_b1s = g_bloomq.b1_ser; bloomq_reset(); } + if (g_bloomq.b1_h) { for (int r = 0; r < 128; r++) if (S.tex[1][r] && h_ser(S.tex[1][r]) == g_bloomq.b0_ser) { S.tex[1][r] = g_bloomq.b1_h; g_args_dirty[1] = 1; } PD("D %llu 泛光 1/4 叠加改读 B1", g_stat_pass); g_bloomq_last_b0 = g_bloomq.b0_ser; g_bloomq_last_b1h = g_bloomq.b1_h; g_bloomq_last_b1s = g_bloomq.b1_ser; bloomq_reset(); } else { RED_ONCE(63, "泛光 1/4 状态缺少 B1 句柄"); bloomq_reset(); } } else if (!g_bloomq.state && g_bloomq_last_b1h && h_ser(g_bloomq_last_b1h) == g_bloomq_last_b1s && !strncmp(f->key, "2e2d6700a2569795", 16)) { // B1 句柄仍指同一张贴图(换分辨率重建后不认) | The B1 handle still points to the same texture (not recognized after a rebuild on resolution change) // 本帧泛光链没跑(运行时外推的外推帧跳过了它:输入 469 区域外是上一帧 LDR,不能跑)就到了泛光叠加:照最近一次改读 B1,叠上一帧的泛光。 // 不改读就读 B0——开了泛光 1/4 的话 B0 的上采样一直被跳过、从没写过,读到的是未初始化显存(M4 Pro 上区域里的单位整个发绿,别处多半是 0、缺泛光) // The bloom overlay is reached without the bloom chain having run this frame (the extrapolated frame of runtime extrapolation skipped it: outside the region the input 469 is the previous frame's LDR, so it cannot run): redirect the read to B1 as last time, overlaying the previous frame's bloom. // Without the redirect it would read B0 -- with bloom 1/4 on, B0's upsample is always skipped and never written, so what is read is uninitialized video memory (on M4 Pro the units in the region turn entirely green; elsewhere it is mostly 0, i.e. missing bloom) - int hit = 0; for (int r = 0; r < 128; r++) if (S.tex[1][r] && h_ser(S.tex[1][r]) == g_bloomq_last_b0) { S.tex[1][r] = g_bloomq_last_b1h; hit = 1; } + int hit = 0; for (int r = 0; r < 128; r++) if (S.tex[1][r] && h_ser(S.tex[1][r]) == g_bloomq_last_b0) { S.tex[1][r] = g_bloomq_last_b1h; hit = 1; g_args_dirty[1] = 1; } if (hit) { PD("D %llu 泛光链没跑:叠加沿用上一帧 B1", g_stat_pass); static uint64_t n; if (n++ % 600 == 0) MLOG("泛光 1/4:泛光链没跑的帧叠加沿用上一帧 B1(第 %llu 次)", (unsigned long long)n); } } else if (g_bloomq.state) { RED_ONCE(61, "泛光 1/4 起点:链中途出现别的绘制,本帧泛光不完整"); bloomq_reset(); } } @@ -4707,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++; } } @@ -4844,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); @@ -5062,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; @@ -5091,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)。 @@ -5358,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); @@ -5678,9 +5730,31 @@ static void present_pipeline(MTLPixelFormat format) { g_blit_samp = [g_dev newSamplerStateWithDescriptor:sd]; } } +// 呈现采样的源:交换链贴图是 sRGB 格式(游戏把交换链建成 RGBA8_SRGB)时经它的非 sRGB 视图采样,屏上显示存的字节,与 Switch 扫描输出一致; +// 直接采样会先解成线性,呈现层(BGRA8Unorm)不再编码,整幅偏暗(公开仓库 #36)。截图读的是原始字节,看不出这一处。 +// 视图按源贴图缓存 4 张、换掉最久没用的:呈现走自己的队列,不能挂主提交的延迟释放;同时在跑的呈现最多 3 帧,被换掉的那张已经用完 +// Source for presentation sampling: when the swapchain texture has an sRGB format (the game created the swapchain as RGBA8_SRGB), sample through its non-sRGB view so the screen shows the stored bytes, as the Switch's scan-out does; +// sampling it directly decodes to linear first, and the present layer (BGRA8Unorm) does not encode again, so the whole picture is too dark (public repository #36). Screenshots read the raw bytes and cannot see this. +// Views are cached per source texture, 4 of them, replacing the least recently used: presentation runs on its own queue and cannot use the deferred release of the main submission; at most 3 presents are in flight, so the replaced one is already done +static id present_src(id src) { + MTLPixelFormat raw = MTLPixelFormatInvalid; + for (size_t i = 0; i < sizeof g_pfv_srgb / sizeof *g_pfv_srgb; i++) if (src.pixelFormat == g_pfv_srgb[i].b) raw = g_pfv_srgb[i].a; + if (raw == MTLPixelFormatInvalid) return src; + static pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER; static id cs[4], cv[4]; static uint64_t used[4], tick; + pthread_mutex_lock(&mu); + int k = -1, old = 0; + for (int i = 0; i < 4; i++) { if (cs[i] == src) k = i; if (used[i] < used[old]) old = i; } + if (k < 0) { k = old; cs[k] = src; cv[k] = [src newTextureViewWithPixelFormat:raw]; + if (!cv[k]) RED_ONCE(50, "出图:sRGB 交换链贴图(格式 %lu)的非 sRGB 视图建不出,直接采样(画面会偏暗,首例)", (unsigned long)src.pixelFormat); + else MLOG("出图:交换链贴图是 sRGB 格式 %lu,经格式 %lu 的视图采样", (unsigned long)src.pixelFormat, (unsigned long)raw); } + used[k] = ++tick; id v = cv[k] ?: src; + pthread_mutex_unlock(&mu); + return v; +} // 出图仅采NVN声明的有效源矩形;与原始交换链读回截图分开。边缘钳到有效区纹素中心,双线性不读外侧黑纹素。 // Present samples only the valid source rectangle declared by NVN; kept separate from the raw swapchain readback screenshot. Edges are clamped to the texel centers of the valid area, so bilinear does not read the black texels outside. -static int present_encode(id cb, id src, id dst, const int crop[4]) { +static int present_encode(id cb, id src0, id dst, const int crop[4]) { + id src = present_src(src0); NSUInteger cx = 0, cy = 0, cw = src.width, ch = src.height; if (crop && (crop[2] || crop[3])) { if (crop[0] < 0 || crop[1] < 0 || crop[2] <= 0 || crop[3] <= 0 || @@ -5719,7 +5793,8 @@ static int present_encode(id cb, id src, id src, id dst, const int crop[4], int uv_i) { +static int present_encode_m4(CBUF cb, id src0, id dst, const int crop[4], int uv_i) { + id src = present_src(src0); NSUInteger cx = 0, cy = 0, cw = src.width, ch = src.height; if (crop && (crop[2] || crop[3])) { if (crop[0] < 0 || crop[1] < 0 || crop[2] <= 0 || crop[3] <= 0 || diff --git a/dm/gfx/nvn/nvn_obj.h b/dm/gfx/nvn/nvn_obj.h index b001f83..8412520 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_SHADER_SCRATCH, OP_WAIT_SYNC, OP_FENCE_SYNC, OP_WAIT_EVENT, 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; @@ -137,6 +138,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/.gitignore b/dm/gfx/tests/.gitignore index 4502c8f..cc294b5 100644 --- a/dm/gfx/tests/.gitignore +++ b/dm/gfx/tests/.gitignore @@ -43,3 +43,5 @@ t_xv t_xv.dSYM/ t_ub t_ub.dSYM/ +t_rt_srgb_view +t_rt_srgb_view.dSYM/ diff --git a/dm/gfx/tests/Makefile b/dm/gfx/tests/Makefile index 175e135..b066bee 100644 --- a/dm/gfx/tests/Makefile +++ b/dm/gfx/tests/Makefile @@ -28,6 +28,8 @@ t_pace: t_pace.c ../nvn/nvn_pace.h clang -O1 -Wall -o $@ t_pace.c t_fuse_check: t_fuse_check.m ../../host/crash.c $(GFX) $(GFX_H) clang $(CFLAGS) -fobjc-arc -o $@ t_fuse_check.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m ../nvn/nvn_entry.S ../nvn/nvn_thunks.S,$(GFX)) $(FW) +t_rt_srgb_view: t_rt_srgb_view.m ../../host/crash.c $(GFX) $(GFX_H) + clang $(CFLAGS) -fobjc-arc -o $@ t_rt_srgb_view.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m ../nvn/nvn_entry.S ../nvn/nvn_thunks.S,$(GFX)) $(FW) t_present_crop: t_present_crop.m ../nvn/hle_nvn.c ../../host/crash.c $(GFX) $(GFX_H) clang $(CFLAGS) -fobjc-arc -o $@ t_present_crop.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m,$(GFX)) $(FW) t_reorder_chain: t_reorder_chain.m ../../host/crash.c $(GFX) $(GFX_H) @@ -77,6 +79,7 @@ run: \ t_rt_range \ t_rt_range_ro \ t_rt_range_shape \ + t_rt_srgb_view \ t_ub \ t_xv \ t_zskip @@ -108,6 +111,7 @@ run: \ DM_NVN_UNWRITTEN_DC=0 MTL_DEBUG_LAYER=1 ./t_rt_range --sample-attachment --both-flags ./t_pso_skey MTL_DEBUG_LAYER=1 ./t_pfv + MTL_DEBUG_LAYER=1 ./t_rt_srgb_view python3 test_tbdr_budget.py .PHONY: run # 老接口版那一遍(图形后端编译期开关 DM_NVN_M3=1,目标 macOS 15.0):在旁边的 tests_m3 目录里用同一份测试源码另编另跑,不动这里的缺省产物。 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/gfx/tests/t_rt_srgb_view.m b/dm/gfx/tests/t_rt_srgb_view.m new file mode 100644 index 0000000..4e8b815 --- /dev/null +++ b/dm/gfx/tests/t_rt_srgb_view.m @@ -0,0 +1,58 @@ +// 换格式的渲染目标视图(公开仓库 #36):RGBA8 底图经 RGBA8_SRGB 视图当颜色附件,清成 0.5 要按 sRGB 编码落进底图; +// 呈现采样 sRGB 交换链贴图要经非 sRGB 视图(读出存的字节)。走生产 rp_begin_ex / rp_end / present_src,4×4 真 Metal 附件。 +// 期望值由常量算,不借被测实现:sRGB 编码 0.5 = 1.055 × 0.5^(1/2.4) − 0.055 = 0.7354 → ×255 = 187.5,硬件取 188;不经视图 = 0.5 × 255 → 128 +// Render-target views that change the format (public repository #36): an RGBA8 base texture used as a colour attachment through an RGBA8_SRGB view must store the sRGB-encoded value when cleared to 0.5; +// presenting from an sRGB swapchain texture must sample through a non-sRGB view (reading the stored bytes). Goes through the production rp_begin_ex / rp_end / present_src with a real 4x4 Metal attachment. +// Expected values come from constants, not from the code under test: sRGB encoding of 0.5 = 1.055 x 0.5^(1/2.4) - 0.055 = 0.7354 -> x255 = 187.5, the hardware gives 188; without the view = 0.5 x 255 -> 128 +#include "../nvn/nvn_mtl.m" +void *front_metal_layer(void) { return NULL; } +module_t *module_of(const void *p) { (void)p; return NULL; } +module_t g_mod[MAX_MOD]; int g_nmod; +void svc_thread_dump(void) {} +uint64_t now_ns(void) { return bp_now(); } + +static int fail, count; +#define EXPECT(name, want, got) do { long long w_ = (want), g_ = (got); count++; \ + printf("%s 期望 %lld → 真结果 %lld %s\n", name, w_, g_, w_ == g_ ? "✓" : "✗"); fail += w_ != g_; } while (0) + +// 清成 0.5 后读回第一个像素的 R 字节;view = 1:经 RGBA8_SRGB 视图挂附件 +// after clearing to 0.5, read back the R byte of the first pixel; view = 1: the attachment goes through an RGBA8_SRGB view +static int clear_and_read(tex_t *t, int view, uint32_t *cfmt) { + memset(&R, 0, sizeof R); R.has_rt = 1; R.rt.n = 1; R.rt.color[0] = t; + if (view) { R.rt.has_cview[0] = 1; R.rt.cview[0].set_format = 1; R.rt.cview[0].format = NVN_FORMAT_RGBA8_SRGB; } + R.clear_c[0] = 1; R.cc[0] = MTLClearColorMake(0.5, 0.5, 0.5, 1); + mtl_sub_begin(); rp_begin_ex(1); *cfmt = g_pass.cfmt[0]; rp_end(); + id b = [g_dev newBufferWithLength:64 options:MTLResourceStorageModeShared]; res_add(b); + [blit() copyFromTexture:tex_mtl(t) sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0, 0, 0) sourceSize:MTLSizeMake(4, 4, 1) + toBuffer:b destinationOffset:0 destinationBytesPerRow:16 destinationBytesPerImage:64]; + enc_b_end(g_blit); g_blit = nil; + uint64_t f = mtl_sub_commit(); + EXPECT("提交完成", 1, mtl_wait(f, 5000000000ull)); + EXPECT("提交反馈无错误", 0, mtl_last_commit_error()); + return ((uint8_t *)b.contents)[0]; +} + +int main(void) { @autoreleasepool { + mtl_init(); + tex_t t = {.serial = 3601}; + t.d.width = t.d.height = 4; t.d.depth = t.d.levels = t.d.samples = 1; t.d.target = NVN_TEXTURE_TARGET_2D; t.d.format = NVN_FORMAT_RGBA8; + uint32_t cf = 0; + EXPECT("负对照:不带视图清 0.5,底图存线性值", 128, clear_and_read(&t, 0, &cf)); + EXPECT("负对照:管线颜色格式 = 底图 RGBA8Unorm", MTLPixelFormatRGBA8Unorm, cf); + EXPECT("经 RGBA8_SRGB 视图清 0.5,底图存 sRGB 编码值", 188, clear_and_read(&t, 1, &cf)); + EXPECT("管线颜色格式跟着视图 = RGBA8Unorm_sRGB", MTLPixelFormatRGBA8Unorm_sRGB, cf); + + MTLTextureDescriptor *d = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm_sRGB width:4 height:4 mipmapped:NO]; + d.usage = MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget; d.storageMode = MTLStorageModePrivate; + id s = [g_dev newTextureWithDescriptor:d], s2 = [g_dev newTextureWithDescriptor:d]; + id v = present_src(s); + EXPECT("呈现:sRGB 交换链经 RGBA8Unorm 视图采样", MTLPixelFormatRGBA8Unorm, v.pixelFormat); + EXPECT("呈现:视图的底图就是交换链贴图", 1, v.parentTexture == s); + EXPECT("呈现:同一张交换链贴图第二次取到同一个视图(缓存)", 1, present_src(s) == v); + id v2 = present_src(s2); + EXPECT("呈现:另一张交换链贴图各自一个视图", 1, v2 != v && v2.parentTexture == s2); + id plain = tex_mtl(&t); + EXPECT("呈现:非 sRGB 交换链原样采样", 1, present_src(plain) == plain); + EXPECT("全程没有报红", 0, g_red_once[48] + g_red_once[49] + g_red_once[50]); + printf("== %d 项,失败 %d ==\n", count, fail); return fail != 0; +} } diff --git a/dm/gfx/vulkan/nvn_vk.c b/dm/gfx/vulkan/nvn_vk.c index 4c5daf5..c6e76de 100644 --- a/dm/gfx/vulkan/nvn_vk.c +++ b/dm/gfx/vulkan/nvn_vk.c @@ -2948,6 +2948,9 @@ void dm_vk_copy_test_read(const tex_t *source,unsigned level,unsigned layer,uint void mtl_stats(uint64_t *passes,uint64_t *draws) { *passes=G.pass_count;*draws=G.draws; } void mtl_pkg_stats(uint64_t *uploads,uint64_t *reuploads) { *uploads=G.uploads;*reuploads=0; } void mtl_set_frame(uint64_t frame) { G.frame=frame; } +// 宿主画法开关(冻结位 / 强制全画):Vulkan 后端没有这两种画法,锁存值恒 0 | host drawing switches (freeze bit / force full draw): the Vulkan backend has neither, the latched value is always 0 +uint64_t mtl_host_latch(void) { return 0; } +void mtl_host_apply(uint64_t v) { (void)v; } double mtl_gpu_ms(uint64_t frame) { (void)frame;return -1; } int mtl_gpu_span(uint64_t frame,uint64_t *a,uint64_t *b) { (void)frame;(void)a;(void)b;return 0; } int mtl_warm_wait(int timeout) { (void)timeout;return 0; } /* No asynchronous pipeline warm-up job exists. */ diff --git a/dm/host/Makefile b/dm/host/Makefile index 9e566b3..cac49ec 100644 --- a/dm/host/Makefile +++ b/dm/host/Makefile @@ -96,8 +96,8 @@ dm_bright_levels.inc: ../tools/gen_bright_levels.py ../ios/tools/touch_layout.py $(NEED_ROMFS) python3 ../tools/gen_bright_levels.py "$(ROMFS)" > $@.tmp && mv $@.tmp $@ dmhost: $(SRC) $(GFX) $(LIBDEFLATE) dm.h hle.h dm_input.h front.h touch_mac.h dm_cursor.h dm_i18n_tab.h ../touch/dm_touch_controls.[ch] $(GFX_H) $(GENH) - clang $(CFLAGS) -I. -I../gfx/nvn/include -fobjc-arc -o $@ $(SRC) $(GFX) $(LIBDEFLATE) -framework Cocoa -framework QuartzCore -framework Metal -framework AudioToolbox -framework ImageIO -framework UniformTypeIdentifiers -framework GameController + clang $(CFLAGS) -I. -I../gfx/nvn/include -fobjc-arc -o $@ $(SRC) $(GFX) $(LIBDEFLATE) -framework Cocoa -framework QuartzCore -framework Metal -framework AudioToolbox -framework CoreAudio -framework ImageIO -framework UniformTypeIdentifiers -framework GameController -framework Network # 老接口版宿主(图形后端不用 Metal 4,目标 macOS 15.0):同一棵树、同一份源码,只多一个编译开关;不在缺省目标里,要用时 make dmhost_m3 # Older-API host (graphics backend without Metal 4, target macOS 15.0): the same tree and the same source, with just one more compile switch; not in the default targets, run make dmhost_m3 when needed dmhost_m3: $(SRC) $(GFX) $(LIBDEFLATE) dm.h hle.h dm_input.h front.h touch_mac.h dm_cursor.h dm_i18n_tab.h ../touch/dm_touch_controls.[ch] $(GFX_H) $(GENH) - clang $(CFLAGS_M3) -I. -I../gfx/nvn/include -fobjc-arc -o $@ $(SRC) $(GFX) $(LIBDEFLATE) -framework Cocoa -framework QuartzCore -framework Metal -framework AudioToolbox -framework ImageIO -framework UniformTypeIdentifiers -framework GameController + clang $(CFLAGS_M3) -I. -I../gfx/nvn/include -fobjc-arc -o $@ $(SRC) $(GFX) $(LIBDEFLATE) -framework Cocoa -framework QuartzCore -framework Metal -framework AudioToolbox -framework CoreAudio -framework ImageIO -framework UniformTypeIdentifiers -framework GameController -framework Network diff --git a/dm/host/app_mac.m b/dm/host/app_mac.m index 19ca632..6b689c9 100644 --- a/dm/host/app_mac.m +++ b/dm/host/app_mac.m @@ -110,6 +110,7 @@ int dm_app_bootstrap(int *argc, char ***argv) { if (!getenv("DM_TOUCH_DEFAULTS")) setenv("DM_TOUCH_DEFAULTS", "1", 1); // 产品缺省同 iOS 包(hle_fs.c settings_seed:玩家没碰过的设置键补上——小地图放右上角、进局自动打开、显示物品用开关式等;已有的键不动)。命令行宿主缺省不做,那边要对 Switch 真值比图 | product defaults same as the iOS package (hle_fs.c settings_seed: fills in settings keys the player has never touched - minimap in the top-right corner, opened automatically on entering a game, show-items as a toggle, and so on; existing keys are left alone). The command-line host does not do this by default, since it has to be compared against Switch ground-truth images if (!getenv("DM_APP_SUPPORT")) setenv("DM_CLOUD_REAL", "1", 1); // iCloud 同步(ios/Sources/cloud_ios.m,两端共用)只认玩家真实的存档目录;测试用的支持目录一律不同步 | iCloud sync (ios/Sources/cloud_ios.m, shared by both platforms) only recognises the player's real save directory; a support directory used for testing is never synced setenv("DM_WINDOW", "1", 1); setenv("DM_APP", "1", 1); + if (!getenv("DM_AUDIO")) setenv("DM_AUDIO", "1", 1); // 产品要出声(hle_audio.c 在 Mac 上的缺省是给命令行回放 / 闸门的静音接收端);无人值守测试显式 DM_AUDIO=0 | the product must play sound (on the Mac, hle_audio.c defaults to the silent sink used for command-line replays / gates); unattended tests set DM_AUDIO=0 explicitly setenv("DM_SAVE", save.fileSystemRepresentation, 1); setenv("DM_TEMP", temp.fileSystemRepresentation, 1); setenv("DM_ROMFS", rom.fileSystemRepresentation, 1); setenv("DM_ROOT", sup.fileSystemRepresentation, 1); NSString *shmap = [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"shader_map.tsv"]; // 图形后端的着色器映射表:命令行起时按可执行文件旁的源码树找,包里放在 Resources | The graphics backend's shader mapping table: when started from the command line it is found via the source tree next to the executable; in the package it is in Resources diff --git a/dm/host/compat/linux/compat_linux.h b/dm/host/compat/linux/compat_linux.h index 871e345..f1073ea 100644 --- a/dm/host/compat/linux/compat_linux.h +++ b/dm/host/compat/linux/compat_linux.h @@ -91,6 +91,7 @@ typedef enum { QOS_CLASS_UTILITY = 0x11, QOS_CLASS_BACKGROUND = 0x09, QOS_CLASS_UNSPECIFIED = 0x00, } qos_class_t; static inline int pthread_set_qos_class_self_np(qos_class_t q, int rel) { (void)q; (void)rel; return 0; } +static inline int pthread_attr_set_qos_class_np(pthread_attr_t *a, qos_class_t q, int rel) { (void)a; (void)q; (void)rel; return 0; } static inline int pthread_get_qos_class_np(pthread_t t, qos_class_t *q, int *rel) { (void)t; if (q) *q = QOS_CLASS_UNSPECIFIED; if (rel) *rel = 0; return 0; } static inline qos_class_t qos_class_self(void) { return QOS_CLASS_UNSPECIFIED; } diff --git a/dm/host/diag.c b/dm/host/diag.c index 2b4a02e..68d7879 100644 --- a/dm/host/diag.c +++ b/dm/host/diag.c @@ -438,6 +438,7 @@ static void setlang_obs(const uint64_t *regs) { void probe_install(void) { if (gate_obs_present(OBS_SETLANG)) gate_obs_set(OBS_SETLANG, setlang_obs); if (gate_obs_present(OBS_EVENT_MSG)) gate_obs_set(OBS_EVENT_MSG, event_msg_obs); + { void dm_ui_tooltip_obs(const uint64_t *regs); if (gate_obs_present(OBS_TOOLTIP)) gate_obs_set(OBS_TOOLTIP, dm_ui_tooltip_obs); } // 说明框停靠(dm_cursor.c) | tooltip docking (dm_cursor.c) const char *ui = getenv("DM_UIMSG"); if (ui && strcmp(ui, "1") && !(g_uifp = fopen(ui, "w"))) die("DM_UIMSG 打不开 %s", ui); g_ui_print = ui != NULL; @@ -970,8 +971,10 @@ static void hud_tick(uint64_t G) { // 每拍:受控玩家等级 / 本 LOG("DM_TEST_GIVE:拍 %u 在玩家旁生成「%s」品质 %d:%d / %d 件成功(物品类号 %u,第一件单位 id %u)%s", tq, code, q, ok, n, cls, id0, !getenv("DM_TEST_GIVE_INV") ? "" : inv == ok ? ",已全部捡进背包" : ",【注意】有没捡进背包的(留在地上)"); } } } } if (main && player) dm_elysium_stash_step(G, player, (uint8_t *)main->base); // 新建极乐世界角色后补齐共享仓库(dm_elysium.c) | Fill in the shared stash after a new Elysium character is created (dm_elysium.c) { void dm_townwp_tick(uint64_t, uint64_t, uint8_t *); if (main && player) dm_townwp_tick(G, player, (uint8_t *)main->base); } // 进局落在城镇小站旁(dm_townwp.c) | Land next to the town waypoint on joining a run (dm_townwp.c) - { int dm_cloud_conflict_take(void); static int shown; // iCloud 同步拦下了共享仓库的覆盖(dm_cloudsync.c):进局后弹一次原版系统提示(每次启动一次) | iCloud sync blocked an overwrite of the shared stash (dm_cloudsync.c): show the original game's system prompt once after joining a run (once per launch) - if (main && player && !shown && dm_cloud_conflict_take()) { shown = 1; dm_game_notice((uint8_t *)main->base, dm_str((uint8_t *)main->base, "dmCloudConflict")); LOG("iCloud 同步:弹了共享仓库不一致的提示"); } } + { int dm_cloud_conflict_take(void); static int shown; // iCloud 共享仓库分叉、本机那份收进了待合并收件箱(dm_cloudsync.c):进局后弹一次原版系统提示(每次启动一次) | the iCloud shared stash forked and the local copy was put in the to-merge inbox (dm_cloudsync.c): one original system notice after entering a run (once per launch) + if (main && player && !shown && dm_cloud_conflict_take()) { shown = 1; dm_game_notice((uint8_t *)main->base, dm_str((uint8_t *)main->base, "dmCloudConflict")); LOG("iCloud 同步:弹了共享仓库收进收件箱的提示"); } } + { int dm_cloud_char_conflict_take(char *, size_t); char nm[256], msg[400]; // iCloud 首次同步遇到同名角色、用了云端那份(dm_cloudsync.c):进局后提示一次 | iCloud first sync met a character with the same name and used the cloud copy (dm_cloudsync.c): one notice after entering a run + if (main && player && dm_cloud_char_conflict_take(nm, sizeof nm)) { snprintf(msg, sizeof msg, dm_str((uint8_t *)main->base, "dmCloudCharConflict"), nm); dm_game_notice((uint8_t *)main->base, msg); LOG("iCloud 同步:弹了同名角色用云端那份的提示(%s)", nm); } } if (main && player) dm_bossrush_tick(G, player, (uint8_t *)main->base); // 首领连战(dm_bossrush.c) | Boss rush (dm_bossrush.c) if (main && player) { void dm_rift_tick(uint64_t, uint64_t, uint8_t *); dm_rift_tick(G, player, (uint8_t *)main->base); } // 秘境爬塔(dm_rift.c) | Rift tower climb (dm_rift.c) { void dm_pages_tick(uint64_t, uint64_t, uint8_t *); if (main) dm_pages_tick(G, player, (uint8_t *)main->base); } // 个人仓库 2–5 页(dm_pages.c);不在局内 player 为 0,模块自己清状态 | Personal stash pages 2–5 (dm_pages.c); player is 0 when not in a run, and the module clears its own state @@ -1188,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)); } @@ -1632,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.h b/dm/host/dm.h index 8367922..380a29b 100644 --- a/dm/host/dm.h +++ b/dm/host/dm.h @@ -63,7 +63,7 @@ module_t *module_of(const void *p); uint64_t gate_dispatch(uint64_t ret_addr, uint64_t *regs); // 观测门(改写器 OBS 表;编号与 patch_nso.py 一致):只读回调,挂上即在门命中时调用 // Observation gates (rewriter OBS table; numbering matches patch_nso.py): read-only callbacks, called on a gate hit once attached -enum { OBS_UIMSG = 1, OBS_TICK = 2, OBS_C2S = 3, OBS_C2S_SYS = 4, OBS_SETLANG = 5, OBS_TARGET_RANK = 7, OBS_UI_PROJECT = 8, OBS_FREEZE_WORLD = 10, OBS_FREEZE_CLIENT = 11, OBS_FREEZE_ANIM = 12, OBS_FREEZE_RENDER = 13, OBS_TEXTBOX = 14, OBS_EVENT_MSG = 15, OBS_LEVEL_WARP = 16, OBS_QUEST_KILL = 17, OBS_NOTICE_INPUT = 18, OBS_ERR_SMOOTH = 19, OBS_MODEL_YAW = 20, OBS_MAX = 21 }; // 6 = iOS 绑定读取(dm_touch_game_bridge.c) | 6 = iOS binding read (dm_touch_game_bridge.c) +enum { OBS_UIMSG = 1, OBS_TICK = 2, OBS_C2S = 3, OBS_C2S_SYS = 4, OBS_SETLANG = 5, OBS_TARGET_RANK = 7, OBS_UI_PROJECT = 8, OBS_FREEZE_WORLD = 10, OBS_FREEZE_CLIENT = 11, OBS_FREEZE_ANIM = 12, OBS_FREEZE_RENDER = 13, OBS_TEXTBOX = 14, OBS_EVENT_MSG = 15, OBS_LEVEL_WARP = 16, OBS_QUEST_KILL = 17, OBS_NOTICE_INPUT = 18, OBS_ERR_SMOOTH = 19, OBS_MODEL_YAW = 20, OBS_TOOLTIP = 21, OBS_PRESET_SPAWN = 22, OBS_MAX = 23 }; // 6 = iOS 绑定读取(dm_touch_game_bridge.c) | 6 = iOS binding read (dm_touch_game_bridge.c) void gate_obs_set(int id, void (*fn)(const uint64_t *regs)); int gate_obs_present(int id); void dm_quiet_difficulty_msg(int on); // 秘境局里拦原版「游戏难度设为 N」提示(观测门 15,diag.c) | In a rift run, block the original game's 「游戏难度设为 N」(Game difficulty set to N) message (observation gate 15, diag.c) diff --git a/dm/host/dm_cloudsync.c b/dm/host/dm_cloudsync.c index 52ecbf0..e06f94a 100644 --- a/dm/host/dm_cloudsync.c +++ b/dm/host/dm_cloudsync.c @@ -13,7 +13,16 @@ // · 首次同步(这一单位没有状态记录)且两边内容不同:一律以云端为准(本地那份照常整份进备份);运行中(allow_down = 0)不传不改,等下次启动下载。云端没有才上传本地。 // · 共享仓库(_stash)再加一道:要被覆盖的一方「明显更多」就不覆盖——任一共享仓库档(.d2i)的编年史段变短(编年史只增不减;新装的空仓库编年史最短)、 // 或要盖上去的是没东西的新档(0 件且编年史还是新建大小)而另一份有物品,或编年史仓库侧文件(.swvault)有件而另一份根本没有这个文件(新装 / 旧版本)。 -// 物品变少、编年史仓库取空都是正常玩法,不拦(只有从没记过编年史的仓库被取空会被当成新档拦下,宁可不同步也不丢)。拦下时本地与云端都不动、状态不记,日志记红,进局后弹系统提示(dm_cloud_conflict_take)。 +// 物品变少、编年史仓库取空都是正常玩法,不算(只有从没记过编年史的仓库被取空会被当成新档)。 +// 共享仓库分叉(iCloud 离线冲突第 1 条第一笔,不丢、不永久拦):首次同步两边不同、或上面那道保险判出「会丢东西」时,不再永久拦住—— +// 启动时一律以云端为现行版(换下的本机那份照常整份进备份),本机那份有东西(物品 / 金币 / 编年史 / 编年史仓库任一项,预置与新建空档不算)就另存进 +// 待合并收件箱 <存档>/_cloudinbox/<时刻>-<序号>/(在存档目录里:局内并回时与角色档、共享仓库同一次存盘提交原子换入,被杀不会复制也不会丢; +// 下划线开头不算角色、也不是共享仓库文件,iCloud 不同步它——收件箱是这台设备自己的):mine.pack = 本机那份;base.pack = 上次同步成功时的共享仓库(状态文件旁的 .stash_base,摘要对得上才带), +// 以后在局内并回:云端是基准的后代(编年史只增不减,基准的编年史条目云端都有)时按「云端 + 本机新增 − 本机取走」,分不清来历时按同一件取一份的并集 +// (单机游戏里少数情况下多出一件比丢一件好)。收不进收件箱就这次不动。 +// 运行中(allow_down = 0)遇到分叉不动、等下次启动。新收进一份就进局提示一次(dm_cloud_conflict_take)。 +// 每次共享仓库同步成功(上传 / 下载 / 一致)都把那一刻的内容写进 <状态文件>.stash_base,给下次分叉当基准。 +// iCloud 自己的同名文件冲突版本(cloud_ios.m 读出来)也走收件箱:dm_cloud_inbox_add。 // Core of iCloud save sync (synced by character name, the later write overwrites the earlier one, and the shared stash works the same way). // This only does the file comparison and moving for "local save directory ↔ one cloud directory" and does not touch the iCloud API: the iOS side (cloud_ios.m) provides the directory in the ubiquity container, confirms the packs have finished downloading, and then calls dm_cloud_sync. // The host unit test (tests/t_cloudsync.c) uses a local directory as the cloud. @@ -28,7 +37,16 @@ // - First sync (this unit has no state record) and the two sides differ: the cloud is always authoritative (the local copy goes into the backup whole as usual); while running (allow_down = 0) nothing is uploaded or changed, and the download waits for the next launch. Local is uploaded only if the cloud has nothing. // - The shared stash (_stash) gets one more check: do not overwrite if the side to be overwritten "clearly has more" -- the chronicle segment of any shared stash save (.d2i) gets shorter (the chronicle only grows, never shrinks; a freshly installed empty stash has the shortest chronicle), // or what would overwrite is an empty new save (0 items and the chronicle still at the freshly-created size) while the other copy has items, or the chronicle vault side file (.swvault) has items while the other copy does not have this file at all (fresh install / old version). -// Fewer items and an emptied chronicle vault are both normal play and are not blocked (only a stash that never recorded any chronicle being emptied is treated as a new save and blocked; better not to sync than to lose data). When blocked, neither local nor cloud is touched, no state is recorded, a failure line is logged, and a system notification is shown after entering a run (dm_cloud_conflict_take). +// Fewer items and an emptied chronicle vault are both normal play and do not count (only a stash that never recorded any chronicle being emptied is treated as a new save). +// Shared stash fork (iCloud offline conflict item 1, first step: nothing lost, nothing blocked forever): when the two sides differ at first sync, or the check above finds that "something would be lost", it is no longer blocked forever - +// at launch the cloud is always taken as the current version (the local copy it replaces goes into the backup whole as usual), and if the local copy has anything (items / gold / chronicle / chronicle vault, any of them; the preset and freshly created empty saves do not count) it is also stored in +// the to-merge inbox /_cloudinbox/-/ (inside the save directory: when merged back in a run it is swapped in atomically in the same save commit as the character saves and the shared stash, so being killed neither duplicates nor loses anything; +// names starting with an underscore are not characters and not shared stash files, and iCloud does not sync it - the inbox belongs to this device): mine.pack = the local copy; base.pack = the shared stash at the last successful sync (.stash_base next to the state file, included only if its digest matches), +// to be merged back in a run later: when the cloud is a descendant of the base (the chronicle only grows; the cloud has every chronicle entry of the base) as "cloud + added locally - taken out locally"; when the origin cannot be told apart, as a union taking one of each identical item +// (in a single-player game, one extra item in rare cases is better than one lost). If it cannot be stored in the inbox, nothing is touched this time. +// While running (allow_down = 0) a fork is left alone until the next launch. Each newly stored copy gives one notice after entering a run (dm_cloud_conflict_take). +// Every successful shared stash sync (upload / download / identical) writes the content at that moment to .stash_base, as the base for the next fork. +// iCloud's own same-name file conflict versions (read out by cloud_ios.m) also go to the inbox: dm_cloud_inbox_add. #include #include #include @@ -39,6 +57,7 @@ #include #include #include +#include #include "dm.h" #define MAXF 64 @@ -68,7 +87,7 @@ static int read_dir(const char *root, const char *rel, cs_unit *u) { // rel } // ---- 共享仓库的内容量(只认结构,不解物品):.d2i 按 55 AA 55 AA 分段,段内 +64 是 'JM' 的是物品页(+66 物品数),其余段是编年史;.swvault 头 'SWVT'、+6 件数 // ---- Content volume of the shared stash (structure only, items are not decoded): .d2i is split into segments by 55 AA 55 AA; a segment with 'JM' at +64 is an item page (+66 item count), the other segments are the chronicle; .swvault has the header 'SWVT', +6 item count -typedef struct { int kind, items, chron, vault; } cs_rich; +typedef struct { int kind, items, chron, vault; long long gold; } cs_rich; // 游戏新建的空共享仓库:物品 0 件、编年史段 148 字节(三份新建档、rf3 的专家仓库都是这个值)。「0 件且编年史还是新建大小」= 没东西的新档, // 不许盖掉有物品的一份(rf3:云端专家仓库 2 件、编年史 148,本机新建的空档同样 148,只比编年史拦不住);编年史长过新建的仓库被玩家取空照常同步 // An empty shared stash newly created by the game: 0 items, chronicle segment 148 bytes (three freshly created saves and rf3's hardcore stash all have this value). "0 items and the chronicle still at the freshly-created size" = an empty new save, @@ -91,7 +110,7 @@ static cs_rich rich_of(const cs_file *f) { if (f->size == sizeof g_stash_seed && !memcmp(f->data, g_stash_seed, sizeof g_stash_seed)) { r.chron = FRESH_CHRON; return r; } // 预置:0 件、新建大小 | seed: 0 items, freshly-created size #endif for (uint32_t o = 0; o + 68 <= f->size && !memcmp(f->data + o, "\x55\xaa\x55\xaa", 4); ) { uint32_t ln; memcpy(&ln, f->data + o + 16, 4); if (ln < 68 || o + ln > f->size) break; - if (!memcmp(f->data + o + 64, "JM", 2)) { uint16_t c; memcpy(&c, f->data + o + 66, 2); r.items += c; } else r.chron += (int)ln; o += ln; } } + if (!memcmp(f->data + o + 64, "JM", 2)) { uint16_t c; uint32_t g; memcpy(&c, f->data + o + 66, 2); memcpy(&g, f->data + o + 12, 4); r.items += c; r.gold += g; } else r.chron += (int)ln; o += ln; } } else if (L > 8 && !strcmp(f->path + L - 8, ".swvault")) { r.kind = 2; if (f->size >= 8 && !memcmp(f->data, "SWVT", 4)) { uint16_t c; memcpy(&c, f->data + 6, 2); r.vault = c; } } return r; } @@ -106,7 +125,18 @@ static const char *stash_shrinks(const cs_unit *w, const cs_unit *x, char *why, return NULL; } static _Atomic int g_conflict; -int dm_cloud_conflict_take(void) { return __atomic_exchange_n((int *)&g_conflict, 0, __ATOMIC_SEQ_CST); } // 进局后取一次:有拦下的共享仓库覆盖就弹系统提示(diag.c) | taken once after entering a run: if a shared stash overwrite was blocked, show a system notification (diag.c) +int dm_cloud_conflict_take(void) { return __atomic_exchange_n((int *)&g_conflict, 0, __ATOMIC_SEQ_CST); } // 进局后取一次:这次启动有共享仓库收进了待合并收件箱就弹系统提示(diag.c) | taken once after entering a run: if a shared stash was put in the to-merge inbox during this launch, show the system notice (diag.c) +static int stash_has_stuff(const cs_unit *u) { // 共享仓库这份有没有东西值得留:任一 .d2i 有物品 / 金币 / 编年史长过新建,或编年史仓库有件(预置与新建空档不算) | whether this shared stash copy has anything worth keeping: any .d2i with items / gold / a chronicle longer than freshly created, or the chronicle vault has items (the preset and freshly created empty saves do not count) + for (int i = 0; i < u->n; i++) { cs_rich r = rich_of(&u->f[i]); if ((r.kind == 1 && (r.items || r.gold || r.chron > FRESH_CHRON)) || (r.kind == 2 && r.vault)) return 1; } + return 0; +} +// 同名角色(iCloud 离线冲突第 3 条):首次同步两边都有同名角色、内容不同 → 照旧以云端为准、本机那份整份进备份,另外记下名字,进局后提示一次(diag.c)。 +// 两份角色档没法合并(等级、任务、身上装备各是一条独立的历史);改名留两份要改 .d2s 头与校验和,不做。 +// Same-name character (iCloud offline conflict item 3): at first sync both sides have a character with the same name and different content -> as before the cloud is authoritative and the local copy goes into the backup whole; the name is also recorded and one notice is shown after entering a run (diag.c). +// Two character saves cannot be merged (level, quests and equipment are each an independent history); keeping both under different names would need changes to the .d2s header and checksum, not done. +static char g_char_conf[256]; static pthread_mutex_t g_cc_mu = PTHREAD_MUTEX_INITIALIZER; +static void char_conf_add(const char *nm) { pthread_mutex_lock(&g_cc_mu); size_t l = strlen(g_char_conf); if (l + strlen(nm) + 3 < sizeof g_char_conf) snprintf(g_char_conf + l, sizeof g_char_conf - l, "%s%s", l ? "、" : "", nm); pthread_mutex_unlock(&g_cc_mu); } +int dm_cloud_char_conflict_take(char *out, size_t n) { pthread_mutex_lock(&g_cc_mu); int r = g_char_conf[0] != 0; if (r) strlcpy(out, g_char_conf, n); g_char_conf[0] = 0; pthread_mutex_unlock(&g_cc_mu); return r; } static int is_stash(const char *nm) { return !strncmp(nm, "SharedStash", 11) || !strncmp(nm, "ModernSharedStash", 17); } static int is_char_dir(const char *save, const char *nm) { char p[1600]; struct stat st; snprintf(p, sizeof p, "%s/%s/%s.d2s", save, nm, nm); return nm[0] != '.' && nm[0] != '_' && !stat(p, &st) && S_ISREG(st.st_mode); } @@ -215,6 +245,42 @@ static cs_state *state_get(cs_state *s, int *n, int cap, const char *unit, int a } static void add_name(char (*names)[64], int *n, const char *nm) { for (int i = 0; i < *n; i++) if (!strcmp(names[i], nm)) return; if (*n < 256 && strlen(nm) < 64) strlcpy(names[(*n)++], nm, 64); } +// ---- 待合并收件箱与基准(见文件头「共享仓库分叉」) +// ---- To-merge inbox and base (see "Shared stash fork" in the file header) +static void base_path(const char *statef, char *o, size_t n) { snprintf(o, n, "%s.stash_base", statef); } +static int base_missing(const char *statef) { char bp[1300]; struct stat st; base_path(statef, bp, sizeof bp); return stat(bp, &st) != 0; } // 升级上来的设备第一次补写 | first write-out on a device upgraded from an older version +static void base_put(const char *statef, const cs_unit *u) { // 共享仓库同步成功那一刻的内容,下次分叉时当基准 | the content at the moment of a successful shared stash sync, used as the base at the next fork + char bp[1300]; base_path(statef, bp, sizeof bp); cs_unit t = *u; t.tomb = 0; + if (pack_write(bp, &t)) LOG("【红】iCloud 同步:共享仓库基准写不进 %s errno=%d", bp, errno); } +// 收件箱新条目:<存档>/_cloudinbox/<时刻>-<序号>/mine.pack(+ base.pack:摘要等于 base_hash 时才带;base_hash = 0 不带)。返回 0 = 收好了 +// New inbox entry: /_cloudinbox/-/mine.pack (+ base.pack: included only when its digest equals base_hash; not included when base_hash = 0). Returns 0 = stored +static int inbox_put(const char *save, const char *statef, const cs_unit *u, uint64_t base_hash, const char *why, const char *who) { + char ib[1300], d[1400], f[1500]; snprintf(ib, sizeof ib, "%s/_cloudinbox", save); mkdir(ib, 0755); + int k = 0; do snprintf(d, sizeof d, "%s/%llu-%d", ib, (unsigned long long)u->stamp, k++); while (mkdir(d, 0755) && errno == EEXIST && k < 100); + snprintf(f, sizeof f, "%s/mine.pack", d); cs_unit t = *u; t.tomb = 0; + if (pack_write(f, &t)) { LOG("【红】iCloud 同步:共享仓库收件箱写不进 %s errno=%d", f, errno); rm_rf(d); return -1; } + int nb = 0; if (base_hash) { char bp[1300]; base_path(statef, bp, sizeof bp); cs_unit *B = calloc(1, sizeof *B); + if (B && pack_read(bp, B) == 1 && B->hash == base_hash) { snprintf(f, sizeof f, "%s/base.pack", d); if (pack_write(f, B)) { LOG("【红】iCloud 同步:收件箱基准写不进 %s errno=%d", f, errno); unit_free(B); free(B); rm_rf(d); return -1; } nb = 1; } + if (B) { unit_free(B); free(B); } } + LOG("iCloud 同步:_stash %s,%s那份收进待合并收件箱 %s(%d 个文件,%s)", why, who, d, u->n, nb ? "带上次同步的基准" : "没有基准:两份当独立来历"); + __atomic_store_n((int *)&g_conflict, 1, __ATOMIC_SEQ_CST); return 0; +} +// iCloud 冲突版本(cloud_ios.m):把一份共享仓库包收进收件箱,基准用本机上次同步的那份。返回 0 = 收好了(或没东西不用收),-1 = 坏包 / 写不进 +// iCloud conflict version (cloud_ios.m): store one shared stash pack in the inbox, with the copy from this device's last sync as the base. Returns 0 = stored (or nothing worth storing), -1 = bad pack / cannot write +int dm_cloud_inbox_add(const char *save, const char *statef, const char *pack) { + cs_unit *u = calloc(1, sizeof *u); if (!u) return -1; int r = pack_read(pack, u), ret = -1; + if (r == 1 && !u->tomb) { if (!stash_has_stuff(u)) ret = 0; else { char bp[1300]; base_path(statef, bp, sizeof bp); cs_unit *B = calloc(1, sizeof *B); uint64_t bh = B && pack_read(bp, B) == 1 ? B->hash : 0; if (B) { unit_free(B); free(B); } + ret = inbox_put(save, statef, u, bh, "iCloud 冲突版本", "冲突版本"); } } + else if (r == 1) ret = 0; else LOG("【红】iCloud 同步:冲突版本 %s 读不了", pack); + unit_free(u); free(u); return ret; +} +// 角色包的 iCloud 冲突版本(cloud_ios.m):包头时刻(游戏最后写它的时刻)、整份进备份、记名进局提示 +// iCloud conflict version of a character pack (cloud_ios.m): the pack header timestamp (the moment the game last wrote it), the whole copy goes into the backup, the name is recorded for a notice after entering a run +uint64_t dm_cloud_pack_stamp(const char *pack) { cs_unit *u = calloc(1, sizeof *u); uint64_t t = u && pack_read(pack, u) == 1 ? u->stamp : 0; if (u) { unit_free(u); free(u); } return t; } +int dm_cloud_bak_pack(const char *bak, const char *unit, const char *pack, const char *why) { + cs_unit *u = calloc(1, sizeof *u); int r = u && pack_read(pack, u) == 1 ? (u->tomb ? 0 : backup_copy(bak, unit, u, why)) : -1; if (u) { unit_free(u); free(u); } return r; } +void dm_cloud_char_conflict_note(const char *unit) { char_conf_add(unit); } + // 返回本次动作数(上传 + 下载 + 删除),-1 = 参数错。ready(单位) 返回 0 = 云端那份还没下载好(iCloud 占位),这一单位本次跳过。now_ms = 写删除标记用的时刻 // Returns the number of actions this time (uploads + downloads + deletions), -1 = bad arguments. ready(unit) returning 0 = the cloud copy has not finished downloading yet (iCloud placeholder), and this unit is skipped this time. now_ms = the timestamp used when writing a deletion marker int dm_cloud_sync(const char *save, const char *cloud, const char *bak, const char *statef, int allow_down, uint64_t now_ms, int (*ready)(const char *unit)) { @@ -245,19 +311,27 @@ int dm_cloud_sync(const char *save, const char *cloud, const char *bak, const ch else if (lchg && !cchg) act = UP; else act = C->stamp > L->stamp ? (C->tomb ? DEL_LOCAL : DOWN) : UP; // 两边都改了(或从没同步过且内容不同):后写的赢 | both sides changed (or never synced and the contents differ): the later write wins if ((act == DOWN || act == DEL_LOCAL) && !allow_down) { act = NONE; goto next; } // 运行中不改本地:等下次启动,状态不动 | do not change local data while running: wait for the next launch, state untouched - if (!strcmp(un, "_stash") && ((act == DOWN && hl) || (act == UP && hc && !C->tomb))) { char why[400]; // 共享仓库:要被覆盖的一方明显更多就不覆盖(见文件头) | shared stash: do not overwrite if the side to be overwritten clearly has more (see the file header) - if (act == DOWN ? stash_shrinks(C, L, why, sizeof why) : stash_shrinks(L, C, why, sizeof why)) { - LOG("【红】iCloud 同步:_stash %s会丢东西(%s),不覆盖、两边都不动", act == DOWN ? "下载云端那份" : "上传本机那份", why); - __atomic_store_n((int *)&g_conflict, 1, __ATOMIC_SEQ_CST); act = NONE; goto next; } } + if (!strcmp(un, "_stash") && hl && hc && !C->tomb && L->hash != C->hash) { char why[400] = ""; // 共享仓库分叉(见文件头):云端为现行版,本机那份有东西就进收件箱 | shared stash fork (see the file header): the cloud is the current version; the local copy goes into the inbox if it has anything + int fork = 0; + if (!S) { snprintf(why, sizeof why, "首次同步两边不同"); fork = 1; } + else if (act == DOWN) fork = stash_shrinks(C, L, why, sizeof why) != NULL; + else if (act == UP) fork = stash_shrinks(L, C, why, sizeof why) != NULL; + if (fork) { + if (!allow_down) { LOG("iCloud 同步:_stash 分叉(%s),运行中不动,等下次启动收进收件箱", why); goto next; } + if (stash_has_stuff(L) && inbox_put(save, statef, L, S ? S->hash : 0, why, "本机")) goto next; // 收不进收件箱:这次不动 | cannot store it in the inbox: leave everything this time + act = DOWN; } } if (act == UP) { if (hc && !C->tomb && C->hash != L->hash && cchg && backup_copy(bak, un, C, "云端(被本机后写覆盖)")) goto next; L->tomb = 0; if (pack_write(cp, L)) { LOG("【红】iCloud 同步:%s 上传失败 errno=%d", un, errno); goto next; } LOG("iCloud 同步:%s 上传(时刻 %llu,%d 个文件)", un, (unsigned long long)L->stamp, L->n); acts++; W = state_get(st, &ns, 256, un, 1); if (W) { W->hash = L->hash; W->stamp = L->stamp; W->tomb = 0; } + if (!strcmp(un, "_stash")) base_put(statef, L); } else if (act == DOWN) { if (local_apply(save, bak, un, hl ? L : NULL, C)) { LOG("【红】iCloud 同步:%s 下载后换进本地失败 errno=%d(本地不变)", un, errno); goto next; } LOG("iCloud 同步:%s 下载(时刻 %llu,%d 个文件)", un, (unsigned long long)C->stamp, C->n); acts++; + if (!S && hl && strcmp(un, "_stash")) { char_conf_add(un); LOG("iCloud 同步:%s 两台设备各有一份同名角色,用云端那份,本机那份已进备份;进局提示", un); } W = state_get(st, &ns, 256, un, 1); if (W) { W->hash = C->hash; W->stamp = C->stamp; W->tomb = 0; } + if (!strcmp(un, "_stash")) base_put(statef, C); } else if (act == DEL_LOCAL) { { char d[1300]; if (move_to_bak(save, bak, un, L, "本机(另一台删了这个角色)", d, sizeof d)) goto next; } // 删 = 整份挪进备份,挪不动就不删 | delete = move the whole copy into the backup; if it cannot be moved, do not delete LOG("iCloud 同步:%s 另一台删了,本机也删(备份已留)", un); acts++; @@ -266,7 +340,8 @@ int dm_cloud_sync(const char *save, const char *cloud, const char *bak, const ch cs_unit t = { .tomb = 1, .stamp = now_ms }; if (pack_write(cp, &t)) { LOG("【红】iCloud 同步:%s 写删除标记失败 errno=%d", un, errno); goto next; } LOG("iCloud 同步:%s 本机删了,云端记删除标记", un); acts++; W = state_get(st, &ns, 256, un, 1); if (W) { W->hash = 0; W->stamp = now_ms; W->tomb = 1; } - } else if (hc) { W = state_get(st, &ns, 256, un, 1); if (W) { W->hash = C->tomb ? 0 : C->hash; W->stamp = C->stamp; W->tomb = C->tomb; } } // 一致:记成已同步 | identical: record as synced + } else if (hc) { W = state_get(st, &ns, 256, un, 1); if (W) { W->hash = C->tomb ? 0 : C->hash; W->stamp = C->stamp; W->tomb = C->tomb; } // 一致:记成已同步 | identical: record as synced + if (!strcmp(un, "_stash") && !C->tomb && (!S || S->hash != C->hash || base_missing(statef))) base_put(statef, C); } next: unit_free(L); unit_free(C); free(L); free(C); } diff --git a/dm/host/dm_cursor.c b/dm/host/dm_cursor.c index 87ebd31..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; } @@ -1938,6 +1947,73 @@ int dm_ui_minimap_rect(float r[4]) { if (!atomic_load(&g_mm_have)) return 0; uin // and if the flip waited for the per-frame check of the panel tree in the next frame, the UI would still be laid out centered in the frame the loading screen is removed (in that frame the health globe is at the centered position and the area name is not lifted). -1 = no message received yet, go by the panel tree. static _Atomic int g_load_up = -1; static uint64_t g_lift_next; +// 系统提示框(NotificationPanel)的停靠高度分两态。布局里写的是没开面板时的高度(gen_romfs_overlay.py:上提到让开底栏上方的生命 / 法力数值); +// 开着大面板时那行数值被面板盖住,上提后的框反而压在背包格子上,所以面板态改停到 NOTE_PANEL_Y(布局单位,同 json 的 y):大面板底边框那一带,在金币 / 存放那排下面。 +// 大面板 = 下面名单里的界面根直接子可见(NPC 讲话框、对话菜单这类小框不算:那时底栏还在,框要留在上提位)。名单漏了的面板照无面板处理(= 上一版行为) +// 改的是对象 +0x19c「停靠目标 y」:原版重排(main+0x3d7e1c)按布局把矩形 y 抄进去,每帧更新(main+0x3d7fbc)滑入滑出时按 (1-t)·目标 插值写 +0x74、 +// 自己从不写 +0x19c——所以改它不跟动画抢坐标(用位置守卫改 +0x74 就是被动画每帧盖回)。单位换算:矩形高 +0x7c 对应布局高 244。 +// 写回由我们确定性做(把写 +0x19c 登记成例外的条件;原版控件规则见 tests/native_write_scan.py NATIVE_FIELD_OK): +// 我们记下原值,停靠条件一结束——面板关、读取画面开(切场景)、保存并退出、回到前端——当场写回,不靠游戏重排;重排只是第二道保险 +// (现值不是我们上次写的 = 游戏重排过(换模式 / 改分辨率),当新原值)。消息路(dm_ui_on_uimsg)在消息到达那一刻写,每帧路兜着。 +// 保存并退出 / 回到前端之后到下一次进局之前不再停靠(暂停菜单在退出那几帧还挂着,不压住的话下一帧又停回面板态)。 +// 测试开关 DM_TEST_NOTE_PANEL_Y=<单位> 试别的高度 +// The docking height of the system notice box (NotificationPanel) has two states. The layout holds the height with no panel open (gen_romfs_overlay.py: raised out of the way of the life / mana numbers above the bottom bar); +// with a large panel open that row of numbers is covered by the panel, and the raised box would sit on the inventory cells instead, so in panel state it docks at NOTE_PANEL_Y (layout units, like y in the json): the band of the large panel's bottom frame, below the gold / Store row. +// Large panel = a root of the list below being a visible direct child (small boxes such as the NPC speech box and dialogue menu do not count: the bottom bar is still there then, and the box stays in the raised position). A panel missing from the list is treated as no panel (= the previous behaviour) +// What is changed is the object's +0x19c "docking target y": the original relayout (main+0x3d7e1c) copies the rectangle y into it from the layout, and the per-frame update (main+0x3d7fbc) writes +0x74 interpolated as (1-t)*target during slide-in / slide-out, +// never writing +0x19c itself - so changing it does not fight the animation for the position (changing +0x74 with a position guard just gets overwritten by the animation every frame). Unit conversion: rectangle height +0x7c corresponds to layout height 244. +// Writing back is done deterministically by us (the condition for registering writes to +0x19c as an exception; the rule for original widgets is in tests/native_write_scan.py NATIVE_FIELD_OK): +// we record the original value, and as soon as the docking condition ends - panel closed, loading screen open (scene change), save and exit, back to the front end - it is written back on the spot, without relying on the game's relayout; the relayout is only a second safety net +// (current value is not what we last wrote = the game relaid it out (mode change / resolution change), taken as the new original). The message path (dm_ui_on_uimsg) writes the moment the message arrives; the per-frame path covers the rest. +// After save and exit / back to the front end, no docking until the next time a game is entered (the pause menu is still up for those few frames of exiting; without holding it, the next frame would dock to the panel state again). +// Test switch DM_TEST_NOTE_PANEL_Y= tries another height +#define NOTE_PANEL_Y -310 +// 停靠目标切换的那一刻框已停稳(+0x198 显示中、矩形 y +0x74 正等于旧目标):原版停稳时不再写坐标,只改 +0x19c 它会一直留在旧位置—— +// 开面板时压着背包格、关面板时压着底栏数值(两个方向都被退回过)。所以两个方向都顺手把 +0x74 一次写成新目标(登记的第二处例外, +// 只许 note_dock_snap 写)。滑入滑出期间 +0x74 不等于旧目标、不写;滑出刚开始那一帧即使相等,之后的插值用的也是已改的 +0x19c,同向不打架。 +// 写完下一帧核:+0x74 还是新目标 = 没在动画期写;被改了记红(g_nd_ychk) +// At the moment the docking target switches, the box has already settled (+0x198 showing, rectangle y +0x74 exactly equal to the old target): once settled the original no longer writes the position, and changing only +0x19c leaves it at the old place - +// over the inventory cells when a panel opens, over the bottom-bar numbers when it closes (both directions were sent back). So both directions also write +0x74 to the new target in one go (the second registered exception, +// written only by note_dock_snap). During slide-in / slide-out +0x74 is not equal to the old target, so nothing is written; even if equal on the first frame of slide-out, the interpolation after that uses the already changed +0x19c, so they move the same way. +// Check on the next frame after writing: +0x74 still the new target = not written during animation; if it was changed, log red (g_nd_ychk) +static uint64_t g_nd_w; static int32_t g_nd_orig, g_nd_mine; static int g_nd_on = -1, g_nd_hold; // g_nd_hold:1 = 退出中(等出局),2 = 已出局(等进局) | g_nd_hold: 1 = leaving (waiting to be out of the game), 2 = out of the game (waiting to enter) +static int g_nd_ychk; static int32_t g_nd_ywant; static unsigned g_nd_ywr, g_nd_ybad; // 写过 +0x74 待下一帧核(核它还是 g_nd_ywant);累计写入次数 / 动画期写入(被改)次数 | +0x74 was written, check it next frame (that it is still g_nd_ywant); total writes / writes during animation (overwritten) +static int note_dock_snap(uint64_t w, int32_t from, int32_t to) { // 框已停稳在 from:矩形 y 一次写成 to。返回 1 = 写了 | the box has settled at from: write the rectangle y as to in one go. Returns 1 = written + int32_t *ry = (int32_t *)(w + 0x74); if (!*(uint8_t *)(w + 0x198) || *ry != from || from == to) return 0; + *ry = to; g_nd_ychk = 1; g_nd_ywant = to; g_nd_ywr++; return 1; +} +static void note_dock_restore(uint64_t root, const char *why) { // 只许游戏主线程 | game main thread only + uint64_t w = root ? ui_find(root, "NotificationPanel", 0) : 0; if (!w || w != g_nd_w) return; // 不在树里 / 不是记下的那个对象:不碰 | not in the tree / not the object we recorded: do not touch + int32_t *t = (int32_t *)(w + 0x19c); + if (*t == g_nd_mine && g_nd_mine != g_nd_orig) { + *t = g_nd_orig; int still = note_dock_snap(w, g_nd_mine, g_nd_orig); + static int lg; if (lg++ < 60) LOG("提示框停靠:%s → 写回原值 y %d%s", why, g_nd_orig, still ? "(框已停稳,矩形 y 一并写回)" : ""); } + g_nd_mine = *t; g_nd_on = 0; +} +static void ui_note_dock_pump(uint64_t root) { + static const char *const big[] = { "PlayerInventoryExpansionLayout", "SkillsTreePanel", "CharacterStatsPanel", "QuestLogPanelExpansion", "BankExpansionLayout", "HoradricCubeLayout", + "WaypointsPanelExpansion", "VendorPanelLayout", "HirelingInventoryPanel", "ImbueItemsPanel", "ChroniclePanel", "MessageLogPanel", "PauseLayout", "PauseLayoutGarden", + "SettingsPanel", "SoundOptionsPanel", "VideoOptionsPanel", "GameplayOptionsPanel" }; + static int py = 1; + if (py > 0) { const char *e = getenv("DM_TEST_NOTE_PANEL_Y"); py = e ? atoi(e) : NOTE_PANEL_Y; } + uint64_t w = ui_find(root, "NotificationPanel", 0); if (!w) { g_nd_w = 0; return; } + int32_t *t = (int32_t *)(w + 0x19c), h = *(int32_t *)(w + 0x7c); + if (g_nd_ychk) { g_nd_ychk = 0; int32_t y = *(int32_t *)(w + 0x74); static int lg; + if (w != g_nd_w) { if (lg++ < 60) LOG("提示框停靠:写回矩形 y 后提示框对象已换(出局 / 重建),不核"); } + else if (y != g_nd_ywant) { g_nd_ybad++; LOG("【红】提示框停靠:矩形 y 写成 %d 后下一帧被改成 %d(动画期写入,第 %u 次)", g_nd_ywant, y, g_nd_ybad); } + else if (lg++ < 60) LOG("提示框停靠:停稳的框下一帧在 y %d(%s;矩形 y 写入第 %u 次,动画期 %u 次)", y, y == g_nd_orig ? "原位" : "面板态位", g_nd_ywr, g_nd_ybad); } + if (w != g_nd_w || *t != g_nd_mine) { g_nd_w = w; g_nd_orig = *t; g_nd_mine = *t; } + int ing = dm_uiscreen_ingame(); if (g_nd_hold == 1 && !ing) g_nd_hold = 2; else if (g_nd_hold == 2 && ing) g_nd_hold = 0; + int panel = 0; uint64_t ch = *(uint64_t *)(root + 0x58), n = *(uint64_t *)(root + 0x60); // 名单里的面板在屏上(可见且有可见内容)= 面板态;两种模式通用 | a panel on the list is on screen (visible and with visible content) = panel state; same for both modes + for (uint64_t j = 0; ing && !g_nd_hold && j < n && !panel; j++) { uint64_t c = *(uint64_t *)(ch + 8 * j); const char *nm = c ? (const char *)*(uint64_t *)(c + 8) : NULL; + if (!nm || !*(uint8_t *)(c + 0x50)) continue; + for (unsigned i = 0; i < sizeof big / sizeof *big && !panel; i++) panel = !strcmp(nm, big[i]) && has_visible_leaf(c, 1); } + int32_t pv = h > 0 ? (int32_t)lroundf(py * h / 244.0f) : g_nd_orig; + if (!(panel && pv > g_nd_orig)) { if (g_nd_on) note_dock_restore(root, ing ? "面板关了" : "不在局内"); } // 只往下挪:布局本来就不低于面板态高度时不动 | only move it down: if the layout is already no higher than the panel-state height, leave it + else if (*t != pv) { int32_t was = *t; *t = pv; g_nd_mine = pv; + if (note_dock_snap(w, was, pv)) { static int lg; if (lg++ < 60) LOG("提示框停靠:开面板时框已停稳在 y %d,矩形 y 一并写成面板态位 %d", was, pv); } } + if (panel != g_nd_on) { g_nd_on = panel; static int lg; if (lg++ < 40) LOG("提示框停靠:%s,目标 y %d(布局原值 %d,矩形高 %d)", panel ? "面板态" : "无面板", *t, g_nd_orig, h); } +} static void ui_lift_pump(uint64_t root, uint64_t fr) { if (fr < g_lift_next) return; g_lift_next = fr + 6; int x, y, w, h; dm_ui_rect(&x, &y, &w, &h); int lift = h > 0 && dm_uiscreen_ingame() ? (int)((long)y * 2160 / h) : 0; @@ -2274,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; } @@ -2430,14 +2572,51 @@ static void ui_panel_state_pump(uint64_t root) { // 游戏主线程,每帧 | // 触屏专属(带 if (tm)):请求全部来自触摸手势——点世界 / 佣兵头像、长按取物、双击使用、点货买、拖放、点技能绑定、副手组页签、开佣兵页。 // 手柄模式与切换事务进行中不跑;在途的请求由切换清理作废(dm_ui_cache_mode_leave)。 // 两种模式都跑:ui_target_pump(鉴定目标,含手柄按住 A)、ui_item_pump(命中查询,宿主自己也问)、ui_ptr_pump(指针事件,宿主合成的点击也走)、 -// ui_safe_pump / ui_lift_pump / ui_trove_tabs_pump / ui_minimap_pump / ui_map_pump / ui_map_geom_pump / ui_map_center(屏幕几何,与输入方式无关)、ui_boss_pct_pump、ui_npcdlg_pump、 +// 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(屏幕几何,与输入方式无关)、ui_boss_pct_pump、ui_npcdlg_pump、 // ui_widestash_pump、mv_audit_pump、ui_pages_pump(含手柄 L / R 翻页)、ui_watch_pump、ui_panel_heal、ui_panel_state_pump、rs_pump(一键重开,在前端泵里调) -// 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 new pump in neither fails). -// Touch only (with if (tm)): requests all come from touch gestures: tap world / mercenary portrait, long-press pickup, double-tap use, tap-to-buy, drag and drop, tap skill binding, off-hand set tab, open mercenary page. -// Not run in controller mode or while a mode switch is in progress; in-flight requests are voided by the switch cleanup (dm_ui_cache_mode_leave). -// Both modes: ui_target_pump (identify target, including controller hold A), ui_item_pump (hit query, the host asks too), ui_ptr_pump (pointer events, host-synthesized clicks go through it too), -// ui_safe_pump / ui_lift_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 controller L / R paging), ui_watch_pump, ui_panel_heal, ui_panel_state_pump, rs_pump (Quick Restart, called from the front-end pump) +// 物品说明框停靠(观测门 OBS_TOOLTIP,挂在说明框面板的「提交一条说明」函数入口 main+0xb0d560(面板, 文字, 目标矩形左上 x2, 目标矩形宽高 x3, 样式, 文字 2))。 +// 说明框是即时式的:悬停着的控件每帧重新提交、画完就清,宿主在自己的时机读面板里的记录数一直是 0,所以只能在提交那一刻改输入。 +// 原版把框摆在目标矩形(被点的那一格)正下 / 正上方:长说明(暗金、符文之语,十几行)盖住腰带、戒指、背包中间几列和「存放」钮,要点被盖住的格子得先点别处。 +// 触屏、只开着物品栏一个面板、光标下是物品时:把目标矩形换成对侧那块暗格空板(物品栏外框里、中间区域左右各一块)顶上的一个点—— +// 物品在面板右半停左空板、在左半停右空板,框从上往下排;量字、摆放、推回屏内仍是游戏自己做(离屏幕边的距离走布局里的 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 视频)。 +// 其余一律原样放行:手柄 / 键鼠模式;并排两个面板的页(储藏箱 / 商人 / 魔盒 / 单件槽 / 佣兵页——没有空带);技能、属性、按钮的说明(光标下不是物品);世界里的名牌。 +// 只许游戏主线程(门回调就在)。 +// 测试开关 DM_TEST_TIPDOCK=1:不看模式(Mac 宿主是手柄版,用它看效果);=0:整个关掉 +// 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 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; } + if (force == 0 || (force < 0 && !ui_touch_mode())) return; + module_t *m = main_module(); uint64_t root = 0; if (!m) return; memcpy(&root, m->base + 0x2f05458, 8); if (!root) return; + if (atomic_load(&g_pstate) & (DM_PS_BANK | DM_PS_VENDOR | DM_PS_IMBUE | DM_PS_CUBE | DM_PS_VAULT | DM_PS_DEAD)) return; + 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], 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 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 把鼠标事件喂给触屏状态机)。 // 只把物品手势的四个执行泵(长按 / 双击使用 / 买 / 拖放)在真鼠标模式下补跑一遍;绑定框、技能页签对调、佣兵页这些改触屏布局的泵不跑。没有请求时这四个什么都不做,手柄玩家不受影响 @@ -2489,7 +2668,7 @@ void dm_ui_mouse_pump(void) { // 游戏取手柄处调(hle_hid fill,主线 else fix = 0; } if (th) { ui_auto_key(th); tnext = fr + 8; } } } } { module_t *pm = main_module(); uint64_t proot = 0; if (pm) { memcpy(&proot, pm->base + 0x2f05458, 8); int32_t pw = *(int32_t *)(pm->base + 0x211da38), phh = *(int32_t *)(pm->base + 0x211da3c); - static uint64_t pf = UINT64_MAX; if (proot && pw > 0 && phh > 0 && pf != fr) { pf = fr; { static int dd; const char *dn; if (!dd && (dn = getenv("DM_UI_DUMP")) && atomic_load(&g_taps_base) && fr >= atomic_load(&g_taps_base) + (getenv("DM_UI_DUMP_AT") ? atoi(getenv("DM_UI_DUMP_AT")) : 45)) { dd = 1; ui_dump(proot, 0, dn, 0, pm); } } int tm = ui_touch_mode(); if (tm) ui_wtap_pump(pm, proot, pw, phh); if (tm) ui_long_pump(); ui_target_pump(pm, fr); if (tm) ui_use_pump(); if (tm) ui_buy_pump(pw, phh); ui_item_pump(proot, pw, phh); ui_ptr_pump(pm, proot, pw, phh); if (tm) ui_drag_pump(pm, proot, pw, phh); UI_MOUSE_ITEM_PUMPS(pm, proot, pw, phh); { int lu = atomic_load(&g_load_up); dm_uiscreen_set_ingame(ui_panel(proot, "HUDPanel") && !(lu < 0 ? ui_find(proot, "LoadScreenPanel", 0) != 0 : lu)); } ui_safe_pump(pm, proot, fr); ui_lift_pump(proot, fr); ui_trove_tabs_pump(pm, proot, fr); ui_minimap_pump(pm, proot, pw, phh, fr); ui_map_pump(pm); ui_map_geom_pump(pm, proot); ui_boss_pct_pump(pm, proot); ui_npcdlg_pump(proot); ui_map_center(pm, proot, *(volatile int32_t *)(pm->base + 0x2d5c748)); if (tm) ui_bind_pump(proot, fr); if (tm) swaptab_pump(proot); if (tm) ui_mercpg_pump(pm, proot, fr); ui_widestash_pump(proot); mv_audit_pump(proot, fr); ui_pages_pump(pm, proot); } } } + static uint64_t pf = UINT64_MAX; if (proot && pw > 0 && phh > 0 && pf != fr) { pf = fr; { static int dd; const char *dn; if (!dd && (dn = getenv("DM_UI_DUMP")) && atomic_load(&g_taps_base) && fr >= atomic_load(&g_taps_base) + (getenv("DM_UI_DUMP_AT") ? atoi(getenv("DM_UI_DUMP_AT")) : 45)) { dd = 1; ui_dump(proot, 0, dn, 0, pm); } } int tm = ui_touch_mode(); if (tm) ui_wtap_pump(pm, proot, pw, phh); if (tm) ui_long_pump(); ui_target_pump(pm, fr); if (tm) ui_use_pump(); if (tm) ui_buy_pump(pw, phh); ui_item_pump(proot, pw, phh); ui_ptr_pump(pm, proot, pw, phh); if (tm) ui_drag_pump(pm, proot, pw, phh); UI_MOUSE_ITEM_PUMPS(pm, proot, pw, phh); { int lu = atomic_load(&g_load_up); dm_uiscreen_set_ingame(ui_panel(proot, "HUDPanel") && !(lu < 0 ? ui_find(proot, "LoadScreenPanel", 0) != 0 : lu)); } ui_safe_pump(pm, proot, fr); ui_lift_pump(proot, fr); ui_note_dock_pump(proot); ui_trove_tabs_pump(pm, proot, fr); ui_minimap_pump(pm, proot, pw, phh, fr); ui_map_pump(pm); ui_map_geom_pump(pm, proot); ui_boss_pct_pump(pm, proot); ui_npcdlg_pump(proot); ui_map_center(pm, proot, *(volatile int32_t *)(pm->base + 0x2d5c748)); if (tm) ui_bind_pump(proot, fr); if (tm) swaptab_pump(proot); if (tm) ui_mercpg_pump(pm, proot, fr); ui_widestash_pump(proot); mv_audit_pump(proot, fr); ui_pages_pump(pm, proot); } } } if (atomic_load(&g_fe_name_open) && atomic_load(&g_ut_phase) == 2) { // 起名页:点输入框(底板 / 文本框)= 重新弹系统键盘,不发鼠标点击 | naming page: tapping the input box (backplate / text box) = pop up the system keyboard again, no mouse click is sent module_t *nm = main_module(); uint64_t nroot = 0; if (nm) memcpy(&nroot, nm->base + 0x2f05458, 8); uint64_t pn = nroot ? ui_find(nroot, "CharacterCreateNamePanel", 0) : 0; if (pn && nm) { int32_t w = *(int32_t *)(nm->base + 0x211da38), h = *(int32_t *)(nm->base + 0x211da3c); uint64_t v = atomic_load(&g_ut_xy); @@ -2646,6 +2825,10 @@ void dm_ui_on_uimsg(const char *cat, const char *act, const char *arg) { if (!strcmp(cat, "PanelManager") && arg && !strcmp(arg, "LoadScreenPanel") && (!strcmp(act, "OpenPanel") || !strcmp(act, "UnloadPanel"))) { int up = act[0] == 'O'; atomic_store(&g_load_up, up); module_t *pm = main_module(); uint64_t root = 0; if (pm) memcpy(&root, pm->base + 0x2f05458, 8); if (root) { dm_uiscreen_set_ingame(!up && ui_find(root, "HUDPanel", 0)); g_lift_next = 0; ui_lift_pump(root, 0); } } + { int ex = (!strcmp(cat, "PausePanelMessage") && !strcmp(act, "ExitGame")) || (!strcmp(cat, "FrontEndNavigation") && !strcmp(act, "ToFrontEnd")), + ld = !strcmp(cat, "PanelManager") && arg && !strcmp(arg, "LoadScreenPanel") && !strcmp(act, "OpenPanel"); + if (ex || ld) { module_t *pm = main_module(); uint64_t root = 0; if (pm) memcpy(&root, pm->base + 0x2f05458, 8); if (ex) g_nd_hold = 1; // 提示框停靠:停靠条件结束,当场写回原值 | notice docking: the docking condition ended, write the original value back on the spot + note_dock_restore(root, ex ? (act[0] == 'E' ? "保存并退出" : "回到前端") : "读取画面(切场景)"); } } if (!strcmp(cat, "QuestLogPanelMessage") && !strcmp(act, "DialogueFinished")) atomic_store(&g_speech_end, dm_guest_frame()); if (!strcmp(cat, "PanelManager")) ui_panel_note(act, arg ? arg : ""); if (!strcmp(cat, "ChroniclePanelMessage") && !strcmp(act, "ToggleChildPanel") && arg && arg[0]) { int c = 0; while (c < 8 && g_chr_child[c][0] && strcmp(g_chr_child[c], arg)) c++; if (c < 8 && !g_chr_child[c][0]) strlcpy(g_chr_child[c], arg, sizeof g_chr_child[c]); } diff --git a/dm/host/dm_i18n_tab.h b/dm/host/dm_i18n_tab.h index 42cbbac..dfcf746 100644 --- a/dm/host/dm_i18n_tab.h +++ b/dm/host/dm_i18n_tab.h @@ -137,6 +137,11 @@ static const struct { const char *k, *zh, *en; } k_dm_i18n[] = { { "dmDlProgress", "正在下载游戏资源\n%.2f / %.2f GB(%.0f%%) %.1f MB/s", "Downloading game resources\n%.2f / %.2f GB (%.0f%%) %.1f MB/s" }, { "dmDlPaused", "下载已暂停(检查网络),恢复后自动继续", "Download paused (check your network). It resumes automatically." }, { "dmDlPackWait", "系统还在准备资源包,完成后自动继续", "The system is still preparing the resource pack. It continues automatically." }, + { "dmDlInstalling", "下载完成,系统正在安装资源包\n可能要几分钟,请保持本 App 在前台\n资源包 %.2f GB,本机可用 %.2f GB", "Download complete. The system is installing the resource pack.\nThis can take a few minutes. Keep this app open.\nPack %.2f GB, %.2f GB free on this device" }, + { "dmDlInstallSpace", "下载完成,但本机空间不够系统安装资源包\n资源包 %.2f GB,%@ 现在可用 %.2f GB,至少还差 %.2f GB\n请在「设置 → 通用 → %@ 储存空间」清理,清理后自动继续", "Download complete, but there is not enough space to install the resource pack.\nPack %.2f GB; this %@ has %.2f GB free, at least %.2f GB more needed.\nFree up space in Settings → General → %@ Storage. It continues automatically." }, + { "dmDlPackSlow", "系统安装资源包已超过 %d 分钟还没完成\n可以继续等,也可以点「改用直接下载」从下载站下载资源(断点续传)", "The system has been installing the resource pack for over %d minutes.\nYou can keep waiting, or tap \"Download Directly\" to get the resources from our download site (resumable)." }, + { "dmDlPackSlowNoDl", "系统安装资源包已超过 %d 分钟还没完成\n可以继续等;也可以点「分享诊断日志」把日志发给我们", "The system has been installing the resource pack for over %d minutes.\nYou can keep waiting, or tap \"Share Diagnostics\" to send us the log." }, + { "dmDlUseDirect", "改用直接下载", "Download Directly" }, { "dmDlNotReady", "游戏资源还不能用\n%@\n处理后点重试", "Game resources are not ready\n%@\nFix this, then tap Retry" }, { "dmDlWill", "将下载游戏资源:还要下 %@(共 %.1f GB)", "Downloading game resources: %@ remaining (%.1f GB total)" }, { "dmDlNotStarted", "%@游戏资源下载没开始:%@\n%@\n也可以从内测页手动下载资源包,放进「我的 iPhone → D2R Mobile」", "%@The resource download could not start: %@\n%@\nYou can also download the resource pack from the beta page and put it in \"On My iPhone → D2R Mobile\"" }, @@ -160,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%%)%@" }, @@ -206,7 +217,11 @@ static const struct { const char *k, *zh, *en; } k_dm_i18n[] = { { "dmRiftSayStart", "第 %d 层开始,限时 15 分钟", "Level %d: 15 minute time limit" }, { "dmRiftSayGift", "赠彩虹刻面一颗,已掉在脚下", "A Rainbow Facet has dropped" }, { "dmRiftSayTimeout", "时间到:本层未过关,守护者仍会掉落", "Time's up: level not cleared" }, + { "dmRiftSayFoes", "本场有 %d 位强敌", "%d powerful foes this run" }, + { "dmRiftSayInvader", "强敌逼近!", "A powerful foe approaches!" }, + { "dmRiftSayInvaderGone", "闯入者退去了", "The intruder withdraws" }, { "dmRiftSayGuardians", "进度已满:两位守护者现身!", "Two Rift Guardians appear!" }, + { "dmRiftSayWave", "守护者第 %d 波现身(共 %d 波)", "Guardian wave %d of %d" }, { "dmRiftSayGuardian", "进度已满:守护者现身!", "The Rift Guardian appears!" }, { "dmElyToaGround", "背包已满,赦免之证掉在脚边", "Inventory full: Token of Absolution dropped" }, { "dmMercSlotLocked", "通关地狱后打通秘境10层解锁", "Clear Greater Rift Level 10 to unlock" }, @@ -253,7 +268,8 @@ static const struct { const char *k, *zh, *en; } k_dm_i18n[] = { { "dmKbRiftFast", "最快 %d:%02d", "Best Time %d:%02d" }, { "dmKbRiftMsGot", "首通奖励已领取", "First clear reward claimed" }, { "dmKbRiftTotal", "最高 %d 层", "Best Level: %d" }, - { "dmCloudConflict", "iCloud 共享仓库两边不一致,已保留本机,请联系我们", "iCloud shared stash mismatch: kept this device. Please contact us" }, + { "dmCloudConflict", "iCloud:两台设备的共享仓库各有内容,已用云端那份,本机那份已完整保存待并回", "iCloud: both devices had shared stash contents. Using the cloud copy; this device's copy is kept to be merged back" }, + { "dmCloudCharConflict", "iCloud:角色 %s 两台设备各有一份,已用云端那份,本机那份已备份", "iCloud: both devices had character %s. Using the cloud copy; this device's copy is backed up" }, { "dmRiftHudTitle", "秘境", "Rift" }, { "dmRiftHudDone", "第 %d 层完成", "Level %d complete" }, { "dmRiftHudLate", "第 %d 层超时", "Level %d overtime" }, @@ -261,6 +277,10 @@ static const struct { const char *k, *zh, *en; } k_dm_i18n[] = { { "dmRiftHudNext", "下次第 %d 层", "Next: Level %d" }, { "dmRiftHudTop", "已通关最高层", "Highest level cleared" }, { "dmRiftHudOver", "已超时:打完仍有掉落,不计通关", "Overtime: drops, no clear" }, + { "dmRiftHudKillWave", "守护者 第 %d/%d 波(%d/%d)", "Guardians %d/%d (%d/%d)" }, + { "dmRiftHudKillN", "击败守护者(%d/%d)", "Slay the Guardians (%d/%d)" }, + { "dmRiftHudOverKill", "已超时:击败守护者仍有掉落", "Overtime: slay it for drops" }, + { "dmRiftHudOverKillN", "已超时:击败守护者(%d/%d)仍有掉落", "Overtime: slay %d/%d for drops" }, { "dmRiftHudSame", "下次仍是这一层", "Next: same level" }, { "dmRiftHudKill", "击败守护者", "Slay the Rift Guardian" }, { "dmRiftHudGoal", "消灭秘境中的怪物 %d%%", "Slay the monsters %d%%" }, diff --git a/dm/host/dm_rift.c b/dm/host/dm_rift.c index e9e016f..33f7bc4 100644 --- a/dm/host/dm_rift.c +++ b/dm/host/dm_rift.c @@ -99,7 +99,11 @@ static void say(const char *key, ...) { char line[160], full[180]; va_list ap; v enum { ST_IDLE, ST_RUN, ST_DONE }; static struct { _Atomic int st; int tier, maps[3], nmaps, cur; // 本次层数、串起来的图、正在第几张 | This rift's level, the chained maps, which map we are on + _Atomic int gdead, gtotal; // 守护者:当前这一波已倒下几位 / 这一波刷出几位(顶部条用) | Guardians: how many of the current wave are down / how many this wave spawned (for the top bar) + int nwave, wave, wcls[3][2], wn[3], whp[3], wdm[3]; uint32_t wave_t; // 守护者分几波(95 层起 2 波、100 层 3 波)、当前第几波(0 起)、各波的类号 / 人数 / 生命与伤害系数(×1000)、上一波全倒那一拍(0 = 不在两波之间) | how many Guardian waves (2 from level 95, 3 at level 100), the current wave (from 0), each wave's class ids / count / life and damage factors (x1000), the tick the previous wave was all down (0 = not between two waves) _Atomic int score, need; uint64_t t0_ns; _Atomic int timeout, guard_dead; // 分数(客户端加)、开局时刻(客体时钟)、超时、守护者已死 | Score (added by the client), start time (guest clock), timed out, guardian dead + int su_order[43], su_next, su_cnt; uint32_t su_live[3], su_seen[3], su_near[3], su_last; // 特殊精英(75 层起):本场的出场次序(池洗过的牌)、下一位、已放几组;在场各组本体的单位 id、最后一次找到它的拍、最后一次离玩家 60 格以内的拍、上次放组的拍 | special elites (from level 75): this run's order of appearance (the shuffled pool), the next one, how many groups placed; for each group present, the body's unit id, the tick it was last found, the tick it was last within 60 tiles of the player; the tick of the last placement + int inv_n, inv_cls[2], inv_pct[2], inv_st[2]; uint32_t inv_id[2], inv_t[2]; // 闯入首领(80 层起):本场几位、各自类号、在进度百分之几闯入、状态(0 未到 / 1 已预警 / 2 在场 / 3 已死 / 4 作罢)、单位 id、预警那一拍 | Invading bosses (from level 80): how many this run, their class ids, at what percentage of progress they invade, state (0 not yet / 1 warned / 2 present / 3 dead / 4 called off), unit id, the tick of the warning uint32_t guard, guards[3]; int guard_cls, gcls[3], nplan, inc; // 守护者:guards[] 各位的单位 id(guard = 第一位,非 0 即「已刷出」)、gcls[] 开局抽好的类号、nplan 本场几位;inc 成功涨了几层 | Guardians: guards[] unit id of each (guard = the first, non-zero meaning "spawned"), gcls[] class ids drawn at the start, nplan how many in this run; inc how many levels were gained on success int players_old; // 开局前的 /players 档 | The /players setting from before the start of the run char who[64]; // 角色名(层数侧文件) | Character name (level sidecar file) @@ -298,6 +302,10 @@ int dm_rift_hud(dm_rift_hud_t *o) { int el = K.t0_ns ? (int)((now - K.t0_ns) / 1000000000ull) : 0; int need = atomic_load(&K.need); o->tier = K.tier; o->progress = need > 0 ? (float)atomic_load(&K.score) / need : 0; if (o->progress > 1) o->progress = 1; o->secs_left = st == ST_DONE ? g_left_done : RIFT_SECS - el; o->done = st == ST_DONE; o->guardian = K.guard != 0 && !atomic_load(&K.guard_dead); o->inc = K.inc; o->next = next_tier(); o->overtime = rift_overtime(); + // 第二行写哪一句在这里定(一个来源):超时优先说明「已超时」,守护者在场就把「击败守护者」合进同一句;两位以上带(已倒 / 总数) + // Which sentence the second line shows is decided here (one source): overtime takes priority with "Overtime", and when Guardians are present "Slay the Rift Guardian" is merged into the same sentence; with two or more it carries (fallen / total) + o->gdead = atomic_load(&K.gdead); o->gtotal = atomic_load(&K.gtotal); o->wave = K.wave + 1 - (K.wave_t != 0); o->nwave = K.nwave; + o->goal = o->overtime ? (o->guardian ? (o->gtotal >= 2 ? 5 : 4) : 3) : o->guardian ? (o->gtotal >= 2 ? 2 : 1) : 0; return 1; } @@ -311,16 +319,67 @@ static uint32_t g_swept[1024]; int dm_rift_swept(uint32_t id) { return id && g_s static int hi_on(const char *seg, int from) { static int off = -1; if (off < 0) { const char *e = getenv("DM_RIFT_HI"); off = e && !strcmp(e, "0"); } if (off) return 0; const char *f = getenv("DM_RIFT_TEST_HI"); return (f && strstr(f, seg)) || K.tier >= from; } // 双守护者每位的生命系数 s、伤害系数 d(×1000):75 层 0.51 / 0.75,线性到 100 层 0.775 / 1.0;低于 75 层被测试开关强制时取 75 层的值。 -// s 的两端:75 层双守护者期望总量 = 74 层单守护者的 1.16 倍(不跳变;双守护者的池是四位,见 k_duo);100 层最大的单体(巴尔)正好不过属性上限。d 未用读数校过 +// s 的两端:75 层双守护者期望总量 = 74 层单守护者的 1.16 倍(不跳变;双守护者的池是四位,见 k_duo);100 层最大的单体(巴尔)正好不过属性上限。d 用替身读数校过一轮(设计稿第十五节:75 层六对的承伤每秒峰值最高是 74 层最重单体的 1.06 倍,各 1 局) // Life factor s and damage factor d of each of two Guardians (x1000): 0.51 / 0.75 at level 75, linear to 0.775 / 1.0 at level 100; below level 75 (forced by a test switch) the level-75 values are used. -// The two ends of s: the expected total of two Guardians at level 75 = 1.16 times a single Guardian at level 74 (no jump; the dual pool has four bosses, see k_duo); at level 100 the largest single one (Baal) stays just within the stat limit. d has not been calibrated with readouts +// The two ends of s: the expected total of two Guardians at level 75 = 1.16 times a single Guardian at level 74 (no jump; the dual pool has four bosses, see k_duo); at level 100 the largest single one (Baal) stays just within the stat limit. d has been calibrated once with stand-in readouts (for the six pairs at level 75 the highest per-second peak of damage taken is 1.06 times the heaviest single Guardian at level 74, one run each) static int hi_duo_x1000(int which) { int t = K.tier < 75 ? 75 : K.tier > 100 ? 100 : K.tier; return which ? 750 + 250 * (t - 75) / 25 : 510 + 265 * (t - 75) / 25; } // 多位首领同场的池不含安达利尔(156):她死后十几到四十拍,同场的另一位首领会跟着死——与巴尔、迪亚波罗各试过,3 + 1 局必现,那时另一位还剩大半生命、 // 不是被伤害打死的;带不带任务事件门都一样;对照组(都瑞尔 + 迪亚波罗)没有这回事。看起来是她原版的死亡过程带的,没读到那段代码。单守护者(74 层及以下)仍是五位 // The pool for several bosses in one fight does not include Andariel (156): ten-odd to forty ticks after she dies, the other boss in the same fight dies too - tried with Baal and with Diablo, reproduced in 3 + 1 runs, with the other one still at most of its life at that point, // not killed by damage; the same with or without the quest-event gate; the control pair (Duriel + Diablo) shows nothing of the kind. It appears to come with her original death sequence; that code has not been read. A single Guardian (level 74 and below) is still drawn from all five static const int k_duo[] = { 211, 242, 243, 544 }; -static int is_guard(uint32_t id) { return id && (id == K.guards[0] || id == K.guards[1] || id == K.guards[2]); } +static int g_entry_lv, g_entry_x, g_entry_y; // 玩家进当前这张秘境图时的落点(退场找不到远处空地时的兜底去处:一定可达) | where the player entered the current rift map (the fallback destination when no distant open ground is found for leaving: always reachable) +// ---- 特殊精英(75 层起;设计稿第二十四节):层数越高原生怪越少、特殊精英越多,90 层起随机生成的原生怪为 0。 +// 池:超级金怪表(66 行)里去掉带任务掉落 / 固定场地 / 脚本的 23 行(设计稿第二十三节;按原版常识圈的),剩 43 行,女伯爵(行 6)在内。掉落一律照原版。 +// 放法:不在开局定点,跟着玩家推进一组一组放——在场组数低于上限、玩家 40 格内敌对单位少于 SU_NEAR 只时,在玩家前方约 70 格的空地用原版函数 +// main+0x69b310(游戏, 房间, x, y, 行号, 0) 连随从一起刷一组(第六个参数含义没查到,取 0 的依据是探路与验收轮的局)。守护者现身后不再放新的。 +// 它们走现有的「客户端见到 → 认作敌对 → 按层改属性 → 计分(本体 15、随从 2)」流程;本体(怪物数据带超级独特标志的,含地图自带的)生命另乘 SU_HP_X,到软顶为止; +// 我们刷的组里的随从生命另乘 SU_MINION_X1000 ÷ 1000。两个系数按「一场的生命和 ≈ 74 层一场 × 层倍率之比」校(设计稿第二十五节):池里高幕的行多、随从按原生等级起算偏肉。 +// 追击:在场的本体离玩家 80 格以外满 5 秒,挪到玩家前方约 70 格——不会被甩在卸载的房间里占着名额,玩家不动它们也会找上来。 +// 两个距离都按「屏幕外」取(推算:一格横向约 16 像素、纵向约 8 像素,1952×900 的画面半宽约 61 格、半高约 56 格;没用截图核),玩家看不到它消失、也看不到它出现 +// 本场有巴尔(守护者或闯入)时不抽随从 9 只的三行(24、36、38):巴尔自己召的触手已占同屏余量。 +// 总开关 DM_RIFT_HI=0;测试开关 DM_RIFT_TEST_HI=su(低层强开)、DM_RIFT_TEST_SUROWS=<行号>,…(指定出场次序)、DM_RIFT_TEST_NAT=<百分数>(指定原生怪比例) +// ---- Special elites (from level 75; design draft section 24): the higher the level, the fewer native monsters and the more special elites; from level 90 randomly generated native monsters are 0. +// Pool: the super unique table (66 rows) minus the 23 rows with quest drops / fixed locations / scripts (design draft section 23; picked by common knowledge of the original), leaving 43 rows, the Countess (row 6) included. Drops always follow the original. +// Placement: not at fixed points at the start, but one group at a time as the player advances - when the number of groups present is below the limit and there are fewer than SU_NEAR hostile units within 40 tiles of the player, a group is spawned with its minions on open ground about 70 tiles ahead of the player with the original function +// main+0x69b310(game, room, x, y, row, 0) (the meaning of the sixth argument was not found; 0 is used on the basis of the exploratory and acceptance runs). No new ones are placed after the Guardians appear. +// They go through the existing "client sees it -> treated as hostile -> attributes scaled by level -> scored (body 15, minion 2)" flow; the body (monster data with the super unique flag, including ones placed by the map) has its life additionally multiplied by SU_HP_X, up to the soft cap; +// minions in the groups we spawned have their life additionally multiplied by SU_MINION_X1000 / 1000. Both factors are calibrated so that "total life in one run ~= one level-74 run x ratio of level multipliers" (design draft section 25): the pool has many high-act rows, and minions starting from their native level are on the tanky side. +// Pursuit: a body present more than 80 tiles from the player for 5 seconds is moved to about 70 tiles ahead of the player - it is not left behind in an unloaded room holding a slot, and comes to the player even if the player stays put. +// Both distances are chosen to be "off screen" (estimate: one tile is about 16 pixels horizontally and about 8 vertically; a 1952x900 view is about 61 tiles half-wide and about 56 tiles half-high; not checked with screenshots), so the player sees it neither disappear nor appear +// When this run has Baal (as Guardian or invader), the three rows with 9 minions (24, 36, 38) are not drawn: the tentacles Baal summons himself already use up the on-screen headroom. +// Master switch DM_RIFT_HI=0; test switches DM_RIFT_TEST_HI=su (force on at low levels), DM_RIFT_TEST_SUROWS=,... (set the order of appearance), DM_RIFT_TEST_NAT= (set the native monster share) +#define SU_NEAR 12 +#define SU_HP_X 3 +#define SU_MINION_X1000 800 // 特殊精英的随从生命另乘 0.8 | special elite minions' life additionally x0.8 +static uint32_t g_su_min[64]; static unsigned g_su_min_w; // 我们刷的特殊精英组里的随从(单位 id):刷出当拍在本体 15 格内找新单位记下 | minions in the special elite groups we spawned (unit ids): on the tick of spawning, new units within 15 tiles of the body are recorded +static int su_minion(uint32_t id) { for (int i = 0; i < 64; i++) if (id && g_su_min[i] == id) return 1; return 0; } +#define SU_HP_SOFT 225000 // 本体生命乘 SU_HP_X 的软顶:× 本层总倍率,90 层约 100 万点(读数:不设顶时攻城兽那一行 383 万) | soft cap for multiplying body life by SU_HP_X: x this level's total multiplier, about 1 million points at level 90 (reading: without a cap the siege beast row reached 3.83 million) +static int su_nat_pct(int tier) { return tier >= 90 ? 0 : tier >= 85 ? 30 : tier >= 80 ? 55 : tier >= 75 ? 80 : 100; } // 原生怪(密度与精英组数)留几成 | what share of native monsters (density and elite pack count) is kept +static int su_quota(int tier) { return tier >= 90 ? 1 << 30 : tier >= 85 ? 7 : tier >= 80 ? 5 : tier >= 75 ? 2 : 0; } // 一场最多放几组(90 层起放到守护者现身为止) | at most this many groups placed in one run (from level 90, placed until the Guardians appear) +static int su_cap(int tier) { return tier >= 90 ? 3 : 2; } // 同时在场最多几组 | at most this many groups present at the same time +// 刷一位超级金怪(连随从)。原版 main+0x69b310 对「表里 +0x21 字节为 0 的行」查本局已出现位图(游戏 +0x5668,第 行号 位):出现过就返回 0、不刷—— +// 同一局里一位超级金怪只出一次(地图上自带的那位,例如图 111 的 Eldritch = 行 49,也算)。秘境同一局连开多场、池放完一轮从头,都会撞上它。 +// 做法:刷之前把这一位清掉、刷完写回原值——原版地图自带的那位该不该出现照旧,我们刷的不受这条限制 +// Spawn one super unique (with minions). The original main+0x69b310, for "rows whose byte +0x21 in the table is 0", checks this game's has-appeared bitmap (game +0x5668, bit ): if it has appeared, it returns 0 and spawns nothing - +// in one game a super unique appears only once (the one placed by the map itself also counts, e.g. Eldritch on map 111 = row 49). Several rifts in a row in one game, and the pool starting again after a full round, both run into this. +// Approach: clear this one's bit before spawning and write the original value back afterwards - whether the one the original map places should appear stays as before, and the ones we spawn are not limited by this +static uint64_t su_spawn(uint64_t G, uint64_t room, int x, int y, int row) { + uint8_t *bm = (uint8_t *)(uintptr_t)(G + 0x5668 + (row >> 3)), bit = (uint8_t)(1u << (row & 7)), old = *bm & bit; *bm &= (uint8_t)~bit; + uint64_t u = ((uint64_t (*)(uint64_t, uint64_t, int, int, int, int))(B + 0x69b310))(G, room, x, y, row, 0); + uint8_t mid = *bm & bit; *bm = (uint8_t)((*bm & ~bit) | old); static int n; if (n++ < 3) LOG("秘境:刷超级金怪 行 %d:本局已出现位 刷前 %d、刷完原版置成 %d、写回 %d", row, old != 0, mid != 0, (*bm & bit) != 0); return u; } +static int g_near_now; // 玩家 40 格内的敌对单位数(hs_tick 每秒数一次) | number of hostile units within 40 tiles of the player (counted once a second by hs_tick) +static const uint8_t k_su_pool[] = { 0, 1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 19, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 40, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59 }; +static uint32_t g_inv_gone[2]; static int g_inv_gone_xy[2][2]; +static uint32_t g_suseq_id; // 测试开关 DM_RIFT_TEST_SUSEQ 当前在场的那位(任务事件的门见到它死要记一行) // 已退场的闯入首领:单位 id(等它所在的房间被游戏卸载后,把它那条存档记录改成不还原;见 inv_gone_pump)与退场落点 | the one currently present for test switch DM_RIFT_TEST_SUSEQ (the quest-event gate records a line when it sees it die) // an invading boss that has left: its unit id (once the game unloads the room it is in, its saved record is changed to do-not-restore; see inv_gone_pump) and where it was sent +// 首领自己召出来的单位(现在只有巴尔的:触手 562–566、分身 570)。75 层以上它们不按层改属性、保持原版数值——它们是首领技能的一部分,不是秘境的怪; +// 按层放大会让触手变成打不完的墙,并且随战斗时长在场上越积越多(实测巴尔在场 36 秒同屏多 26 只、141 秒多 44 只)。74 层及以下照旧(那条「逐位不变」的线不为此破例)。 +// 按类号认:单位上「召唤者是谁」的字段没读到;以后别的首领有召唤物要加进来 +// Units summoned by a boss itself (currently only Baal's: tentacles 562–566, clone 570). Above level 75 they are not scaled by level and keep the original values - they are part of the boss's skills, not monsters of the rift; +// scaling them by level turns the tentacles into a wall that cannot be cleared, and they pile up on the field as the fight goes on (measured: 26 more on screen after Baal has been present for 36 seconds, 44 more after 141 seconds). Level 74 and below stay as they were (the "nothing changes" line is not broken for this). +// Recognised by class id: the "who summoned it" field on the unit has not been read; summons of other bosses will have to be added later +static int boss_summon(uint32_t cls) { return (cls >= 562 && cls <= 566) || cls == 570; } +static int is_guard(uint32_t id) { return id && (id == K.guards[0] || id == K.guards[1] || id == K.guards[2] || id == K.inv_id[0] || id == K.inv_id[1] || id == g_inv_gone[0] || id == g_inv_gone[1]); } // 守护者与闯入首领:不按普通怪再改一遍属性、不按普通怪计分 | Guardians and invading bosses: not scaled again as ordinary monsters, not scored as ordinary monsters static int pts_of(uint8_t fl) { return fl & 0x02 ? 15 : fl & 0x08 ? 10 : fl & 0x04 ? 5 : fl & 0x10 ? 2 : 1; } // 怪物数据 +0x1a:超级独特 / 金怪 / 冠军 / 随从 / 普通(同 hle_target.c) | Monster data +0x1a: super unique / unique (gold) monster / champion / minion / normal (same as hle_target.c) // ---- 每场读数(75 层以上内容曲线的量具,docs 设计稿第 0 步):只记、不改任何玩法。结算时打一行: // 用时;击杀只数与这些怪的生命上限之和(按层改完之后的值,守护者另加);本场认作敌对并改过属性的怪的只数与生命和; @@ -348,7 +407,7 @@ static void hs_tick(uint64_t G, uint64_t player, uint32_t t, int lv) { int px, py, n = 0; if (!unit_xy(player, &px, &py)) return; for (int b = 0; b < 128; b++) for (uint64_t u = rd(G + 0x2230 + 1 * 0x400 + 8 * b); u; u = rd(u + 0x158)) { uint32_t m = *(uint32_t *)(uintptr_t)(u + 0xc); int x, y; if (m == 0 || m == 12 || unit_level(u) != lv || !unit_xy(u, &x, &y) || abs(x - px) > 40 || abs(y - py) > 40 || unit_align(u)) continue; n++; } - HS.near_sum += n; HS.near_n++; if (n > HS.near_peak) HS.near_peak = n; + HS.near_sum += n; HS.near_n++; if (n > HS.near_peak) HS.near_peak = n; g_near_now = n; } static void hs_report(int secs) { LOG("秘境:读数 第 %d 层 用时 %d 秒:击杀 %d 只、生命和 %lld 点(另守护者 %lld 点);改过属性的敌对怪 %d 只、生命和 %lld 点;承伤和 %lld 点、每秒峰值 %lld 点、死亡 %d 次;40 格内敌对单位 峰值 %d / 均值 %.1f(采样 %d 次)", @@ -452,13 +511,15 @@ static uint32_t monlvl(uint64_t G, int lvl, int grp) { uint64_t T = tables(G), a // for a unit with a percentage life bonus, writing the base up to the limit makes the total overflow to a negative number, which is read as 1 point (this is how minions fell back to 1). So headroom is left according to the current total / base. // base / full = the base entry and the total at this moment (raw fixed-point values); with no bonus (total not greater than base) or when the base entry cannot be read, it is the stat limit itself static long long hp_base_limit(int base, int full) { return base > 0 && full > base ? 0x7fffff00LL * base / full : 0x7fffff00LL; } +static int g_hp_soft; // 额外系数的软顶(点数,按「本层总倍率 = 1」计;0 = 没有):特殊精英本体用,免得天生就肉的怪种(攻城兽)再乘 4 变成半个守护者 | soft cap of the extra factor (points, counted with "this level's total multiplier = 1"; 0 = none): used for special elite bodies, so that naturally tanky monster types (siege beasts) do not become half a Guardian after another x4 static int g_hp_mul = 1000; // scale_monster 的生命额外系数(×1000):双守护者的 s 在截顶之前乘进去——先截顶再乘的话,规则值过上限的那位(巴尔)会被多砍一刀 | extra life factor of scale_monster (x1000): the dual-Guardian s is multiplied in before the clamp - clamping first and multiplying afterwards would cut the one whose rule value exceeds the limit (Baal) a second time static void scale_monster(uint64_t G, uint64_t u, int lt, int l9) { // lt = 本层的等级(守护者 + 3)、l9 = 起算层的等级 | lt = this level's level (Guardian + 3), l9 = the baseline level's level int l0 = gs(u, 12); if (l0 <= 0) return; if (lt > lvl_cap()) lt = lvl_cap(); if (l9 > lt) l9 = lt; int tx = tier_total_x1000(K.tier, 0), lb = l0 > l9 ? l0 : l9, le = l0 > lt ? l0 : lt; // lb:「起算层那只怪」的等级;le:写进单位的等级(不降级) | lb: the level of "that monster at the baseline level"; le: the level written into the unit (never lowered) if (le == l0 && lb == l0 && tx == 1000) return; // 9 层、原生等级已不低于目标:什么都不用改 | level 9 and the native level is already no lower than the target: nothing to change uint32_t h0 = monlvl(G, l0, 2), hb = monlvl(G, lb, 2), d0 = monlvl(G, l0, 3), db = monlvl(G, lb, 3), a0 = monlvl(G, l0, 0), a1 = monlvl(G, le, 0); if (!h0 || !d0 || !a0) return; - long long want = (long long)gs(u, 7) * hb / h0 * tx / 1000 * g_hp_mul / 1000, hp = want, lim = hp_base_limit(gsb(u, 7), gs(u, 7)); if (hp > lim) hp = lim; // 定点 ×256;原版上限 2²³ 点,带百分比生命加成的怪按比例留余量(hp_base_limit) | fixed point x256; the original's limit is 2^23 points, and monsters with a percentage life bonus get proportional headroom (hp_base_limit) + long long want = (long long)gs(u, 7) * hb / h0 * tx / 1000 * g_hp_mul / 1000; if (g_hp_soft > 0 && g_hp_mul > 1000) { long long w1 = want * 1000 / g_hp_mul, sf = (long long)g_hp_soft * 256 * tx / 1000; if (want > sf) want = w1 > sf ? w1 : sf; } /* 软顶:额外系数最多把它乘到软顶,本来就过软顶的不再乘 | soft cap: the extra factor raises it at most to the soft cap; one already above the soft cap is not multiplied further */ + long long hp = want, lim = hp_base_limit(gsb(u, 7), gs(u, 7)); if (hp > lim) hp = lim; // 定点 ×256;原版上限 2²³ 点,带百分比生命加成的怪按比例留余量(hp_base_limit) | fixed point x256; the original's limit is 2^23 points, and monsters with a percentage life bonus get proportional headroom (hp_base_limit) // 顶到上限不静默:这只怪(多半是守护者)的生命没按线涨足,只剩伤害在涨。每开一层记前 3 只 // Hitting the cap is not silent: this monster (most likely the Guardian) did not get its full life according to the line, and only its damage keeps // growing. The first 3 are logged for each level opened @@ -831,10 +892,40 @@ static void merc_test(uint64_t G, uint64_t pl, uint32_t t) { static void rift_quest_obs(const uint64_t *regs) { static uint8_t stand_in[0x200]; uint64_t G = regs[0], mon = regs[1]; int st = atomic_load(&K.st); if ((st != ST_RUN && st != ST_DONE) || !G || G != L.G || !mon || !in_rift_map(any_level(mon))) return; - static int n; if (n++ < 6) LOG("秘境:怪物类号 %u(单位 id %u)死在秘境图里,不走原版任务事件", *(uint32_t *)(uintptr_t)(mon + 4), *(uint32_t *)(uintptr_t)(mon + 8)); + static int n; if (n++ < 6 || (g_suseq_id && *(uint32_t *)(uintptr_t)(mon + 8) == g_suseq_id)) LOG("秘境:怪物类号 %u(单位 id %u)死在秘境图里,不走原版任务事件", *(uint32_t *)(uintptr_t)(mon + 4), *(uint32_t *)(uintptr_t)(mon + 8)); ((uint64_t *)(uintptr_t)regs)[1] = (uint64_t)(uintptr_t)stand_in; } +// 90 层起秘境图里不放普通预设怪(90 层以上没有其它怪、全是特殊精英)。观测门 OBS_PRESET_SPAWN 挂在「放一条预设单位记录」main+0x7ce800(游戏, 房间, 记录) 的入口, +// 它只由房间激活时的放预设单位 0x7ce930 调(8 处);我们自己刷守护者 / 闯入首领直接调 0x7ce630,刷特殊精英调 0x69b310,都不经过这里。 +// 记录 {+0 模式, +4 类号, +8 / +0x24 房内坐标, +0x18 地图 AI, +0x20 单位类型 1 怪 / 2 物件};怪的类号分三段(原版 0x6910d0): +// 小于 monstats 行数(表 +0xf98)= 普通怪,再往上超级独特行数(表 +0x10b8)以内 = 超级独特,再往上 = monplace 放置码。 +// 拦的:会打人 / 刷怪的普通怪(投石车 497–500、观察员 516–519、邪恶小屋 528);放置码里的随机怪群、金怪群、冠军、营地、group25–100 等。 +// 留的:超级独特;门 / 墙 / 攻城塔 / 监狱门 / 陷阱 / 友军野蛮人(场景,拿掉会改通行);放置码 0 空、4 / 14–16 NPC、5 血鸦、29–31 尸体。 +// 拦法:x2 换成一份类号 −1 的副本,原版 0x6910d0 入口自己返回空(tbnz w2, #31),0x7ce630 / 0x7ce800 随之走各自的收尾,不碰任何状态;原记录不动。 +// From level 90, no ordinary preset monsters are placed in rift maps (above level 90 there are no other monsters, only special elites). Observation gate OBS_PRESET_SPAWN is hooked at the entry of "place one preset unit record" main+0x7ce800(game, room, record); +// it is only called by the room-activation preset placement 0x7ce930 (8 call sites); our own Guardian / invading boss spawns call 0x7ce630 directly and special elite spawns call 0x69b310, neither goes through here. +// Record {+0 mode, +4 class id, +8 / +0x24 in-room coordinates, +0x18 map AI, +0x20 unit type 1 monster / 2 object}; monster class ids fall into three ranges (original 0x6910d0): +// below the monstats row count (table +0xf98) = ordinary monster, above that within the super unique row count (table +0x10b8) = super unique, above that = monplace placement code. +// Blocked: ordinary monsters that attack or spawn monsters (catapults 497–500, watchers 516–519, evil hut 528); in the placement codes, random monster packs, unique packs, champions, camps, group25–100 etc. +// Kept: super uniques; doors / walls / siege towers / prison doors / traps / friendly barbarians (scenery; removing them changes passability); placement codes 0 empty, 4 / 14–16 NPCs, 5 Blood Raven, 29–31 corpses. +// How it is blocked: x2 is replaced by a copy with class id -1, the original 0x6910d0 entry returns null by itself (tbnz w2, #31), 0x7ce630 / 0x7ce800 then go through their own exits without touching any state; the original record is untouched. +static void rift_preset_obs(const uint64_t *regs) { + static uint8_t stand_in[0x40]; static int n_blk; uint64_t G = regs[0], room = regs[1], rec = regs[2]; int st = atomic_load(&K.st); + if ((st != ST_RUN && st != ST_DONE) || !G || G != L.G || !room || !rec || *(int32_t *)(uintptr_t)(rec + 0x20) != 1 || !hi_on("pre", 90)) return; + uint64_t ex = rd(room + 0x18), lv = ex ? rd(ex + 0x90) : 0; int lvno = lv ? *(int32_t *)(uintptr_t)(lv + 0x1f8) : 0; if (!in_rift_map(lvno)) return; + uint64_t T = tables(G); if (!T) return; int N = *(int32_t *)(uintptr_t)(T + 0xf98), S = *(int32_t *)(uintptr_t)(T + 0x10b8), c = *(int32_t *)(uintptr_t)(rec + 4), blk; + if (c < 0) return; + if (c < N) blk = (c >= 497 && c <= 500) || (c >= 516 && c <= 519) || c == 528; + else if (c < N + S) blk = 0; + else { int p = c - N - S; blk = !(p == 0 || p == 4 || p == 5 || (p >= 14 && p <= 16) || (p >= 29 && p <= 31)); } + if (!blk) return; + memcpy(stand_in, (const void *)(uintptr_t)rec, 0x30); *(int32_t *)(stand_in + 4) = -1; *(uint64_t *)(stand_in + 0x18) = 0; + ((uint64_t *)(uintptr_t)regs)[2] = (uint64_t)(uintptr_t)stand_in; + static int all = -1; if (all < 0) all = getenv("DM_RIFT_TEST_TOUR") != NULL; + if (n_blk++ < 6 || n_blk % 100 == 0 || all) LOG("秘境:第 %d 层 关卡 %d 不放预设怪 类号 %d(%s %d;monstats %d 行、超级独特 %d 行;本进程累计 %d 条)", K.tier, lvno, c, c < N ? "普通" : "放置码", c < N ? c : c - N - S, N, S, n_blk); +} static void rift_gates(void) { static int once; if (once) return; once = 1; + if (gate_obs_present(OBS_PRESET_SPAWN)) gate_obs_set(OBS_PRESET_SPAWN, rift_preset_obs); else LOG("秘境:这个产物不带放预设单位的门(r44 起的 touch 产物才带),90 层起普通预设怪照原版放"); if (gate_obs_present(OBS_QUEST_KILL)) gate_obs_set(OBS_QUEST_KILL, rift_quest_obs); else LOG("秘境:这个产物不带任务事件的门(r36 起的 touch 产物才带),秘境里的首领死亡会走原版任务"); if (gate_obs_present(OBS_LEVEL_WARP)) gate_obs_set(OBS_LEVEL_WARP, rift_level_obs); else LOG("秘境:这个产物不带出口换目的地的门(只有 r36 起的 touch 产物带),走出口会先落到原版的下一关、再由每拍检测送进下一张图"); } @@ -877,6 +968,20 @@ static void region_set(uint64_t G, int mode) { // mode 0 写回原值、1 置 for (int i = 0; i < K.nmaps; i++) { int lv = K.maps[i]; uint8_t *umin, *umax; int32_t *den = region_of(G, lv, &umin, &umax); if (!den) continue; int d = mode ? 0 : g_reg[lv].den, a = mode ? 0 : g_reg[lv].umin, b = mode ? 0 : g_reg[lv].umax; if (*den == d && *umin == a && *umax == b) continue; LOG("秘境:关卡 %d 本局怪物区域 密度 %d → %d、精英组 %d–%d → %d–%d(%s)", lv, *den, d, *umin, *umax, a, b, mode ? "已结算,不再填怪" : "写回原值"); *den = d; *umin = (uint8_t)a; *umax = (uint8_t)b; } } +// 退场的闯入首领的真移除:它被传到远处后,那间房离玩家远、游戏自己会把房间卸载(实测约 150 拍),单位随之从单位表里拿掉、存成房间存档里的一条怪物记录 +// (记录 +0xc 是单位号)。这时把那条记录照 saved_purge 的做法改成「不还原」(标志 +0x14 置 0x100、单位号写成全 1)——以后玩家走回去,房间重新载入也不会再把它放出来。 +// 全程不走死亡 / 掉落 / 击杀计数。房间还没卸载时什么都不做(它在 150 格外原地站着) +// True removal of an invading boss that has left: after it is teleported far away, its room is far from the player and the game unloads the room by itself (about 150 ticks, measured), taking the unit out of the unit table and storing it as one monster record in the room's saved state +// (record +0xc is the unit id). At that point the record is changed to "do not restore" the way saved_purge does it (flag +0x14 set to 0x100, unit id written as all ones) - if the player walks back later and the room is loaded again, it is not brought out again. +// No death / drop / kill count is involved at any point. Nothing is done while the room is not yet unloaded (it stands in place more than 150 tiles away) +static void inv_gone_pump(uint64_t G, uint32_t t) { + for (int i = 0; i < 2; i++) { uint32_t id = g_inv_gone[i]; if (!id || find_unit(G, 1, id)) continue; + uint64_t T = tables(G), heads = rd(G + 0x1b0); int acts = T ? *(int32_t *)(uintptr_t)(T + 0x108) : 0, hit = 0; if (!heads || acts <= 0 || acts > 8) continue; + for (int a = 0; a < acts && !hit; a++) for (uint64_t nd = rd(heads + 8ull * a), k = 0; nd && k < 4096 && !hit; nd = rd(nd + 0x20), k++) for (uint64_t r = rd(nd + 0x10), j = 0; r && j < 1024; r = rd(r + 0xb0), j++) + if (*(uint32_t *)(uintptr_t)(r + 0xc) == id) { *(uint32_t *)(uintptr_t)(r + 0x14) |= 0x100; *(uint32_t *)(uintptr_t)(r + 0xc) = 0xffffffffu; hit = 1; break; } + if (hit) { LOG("秘境:拍 %u 退场的闯入首领(单位 id %u)所在房间已卸载,它的存档记录改成不还原", t, id); g_inv_gone[i] = 0; } + else { static uint32_t warned; if (warned != id && t % 250 == 0) { warned = id; LOG("秘境:拍 %u 退场的闯入首领(单位 id %u)不在单位表里,房间存档里也没找到它的记录", t, id); } } } +} // 已结算的图里,地图预设点上的怪也不再放:给预设记录置原版自己的「跳过」位(记录 +0x28 位 0,放预设单位的循环 main+0x7ce9bc 读它;+0x20 = 1 是怪)。记录在房间初始化时才有,所以每拍对一遍 // 单位阵营(0 敌对 / 2 玩家一方):原版存房间时自己的读法(main+0x7e0f3c 起)——单位 +0x88 的属性表,+0x1c 位 31 没置 = 0;否则在 +0xd0 / +0xd8 两条链(下一条 +0x68)里找状态 0x69 的节点, // 对它取属性 0xac:main+0x5bc810([单位 +0x1bd] 字节, 节点, 0xac, 0);没有这个节点 = 0 @@ -911,7 +1016,8 @@ static void rift_setup(uint64_t G) { uint64_t T = tables(G), a = T ? rd(T + 0x18f8) : 0, n = T ? rd(T + 0x1900) : 0; for (int i = 0; i < K.nmaps; i++) { int lv = K.maps[i]; uint64_t r = rd(G + 0x1d0 + 8ull * lv); if (!r) { LOG("【红】秘境:关卡 %d 没有怪物区域", lv); continue; } uint8_t *umin, *umax; int32_t *den = region_of(G, lv, &umin, &umax); int d0 = g_reg[lv].den, a0 = g_reg[lv].umin, b0 = g_reg[lv].umax; // 从原值算(上一次秘境结算后置过 0) | Computed from the original values (they were set to 0 after the previous rift completion) - int e2 = tier_elite_x2(K.tier); *den = d0 * 3 > 10000 ? 10000 : d0 * 3; *umin = a0 * e2 / 2 > 255 ? 255 : a0 * e2 / 2; *umax = b0 * e2 / 2 > 255 ? 255 : b0 * e2 / 2; // 精英组倍数按层(tier_elite_x2) | elite pack multiplier by level (tier_elite_x2) + int e2 = tier_elite_x2(K.tier); *den = d0 * 3 > 10000 ? 10000 : d0 * 3; *umin = a0 * e2 / 2 > 255 ? 255 : a0 * e2 / 2; *umax = b0 * e2 / 2 > 255 ? 255 : b0 * e2 / 2; + { const char *e = getenv("DM_RIFT_TEST_NAT"); int pct = e ? atoi(e) : hi_on("su", 75) ? su_nat_pct(K.tier) : 100; *den = (int)((long long)*den * pct / 100); *umin = (uint8_t)(*umin * pct / 100); *umax = (uint8_t)(*umax * pct / 100); } // 75 层起原生怪按层减少,位置让给特殊精英 | from level 75, native monsters are reduced level by level, making room for special elites LOG("秘境:关卡 %d 本局怪物区域 密度 %d → %d、精英组 %d–%d → %d–%d(第 %d 层 ×%d.%d)", lv, d0, *den, a0, b0, *umin, *umax, K.tier, e2 / 2, e2 % 2 * 5); for (uint64_t k = 0; a && k < n; k++) if (*(int32_t *)(uintptr_t)(a + k * 0x1c) == lv) { int32_t *rm = (int32_t *)(uintptr_t)(a + k * 0x1c + 0xc); int had = 0; for (int q = 0; q < g_nmz; q++) had |= g_mz[q].lv == lv; if (g_built[lv]) LOG("秘境:关卡 %d 服务端已建,LvlMaze 地狱房间数不动(%d)", lv, *rm); @@ -1101,13 +1207,47 @@ static int start_rift(uint64_t G, uint64_t player, uint32_t t, int tier) { for (int q = 0; q < K.nmaps && L.nused < 24; q++) L.used[L.nused++] = K.maps[q]; atomic_fetch_add(&g_run_seq, 1); rift_setup(G); K.cur = 0; atomic_store(&K.score, getenv("DM_RIFT_TEST_SCORE") ? atoi(getenv("DM_RIFT_TEST_SCORE")) : 0); // 测试:初始分数(看进度条) | Test: initial score (to see the progress bar) - atomic_store(&K.guard_dead, 0); atomic_store(&K.timeout, 0); K.guard = 0; memset(K.guards, 0, sizeof K.guards); K.inc = 0; + atomic_store(&K.guard_dead, 0); atomic_store(&K.timeout, 0); atomic_store(&K.gdead, 0); atomic_store(&K.gtotal, 0); K.guard = 0; memset(K.guards, 0, sizeof K.guards); K.inc = 0; // 本场的守护者开局就抽好(之后回城再来、继续,都是这几位):75 层起两位不同的。测试开关 DM_RIFT_TEST_GUARDS=<类号>[,<类号>] 指定(逐对验收用) // This run's Guardians are drawn at the start (returning to town and coming back, or continuing, gives the same ones): from level 75 two different ones. Test switch DM_RIFT_TEST_GUARDS=[,] specifies them (for pair-by-pair acceptance) { K.nplan = hi_on("duo", 75) ? 2 : 1; K.gcls[2] = 0; if (K.nplan == 2) { int a = rnd(4), b = (a + 1 + rnd(3)) % 4; K.gcls[0] = k_duo[a]; K.gcls[1] = k_duo[b]; } else { K.gcls[0] = k_guard[rnd(5)]; K.gcls[1] = 0; } const char *e = getenv("DM_RIFT_TEST_GUARDS"); if (e) { int x = 0, y = 0, n = sscanf(e, "%d,%d", &x, &y); if (n >= 1 && x > 0) K.gcls[0] = x; if (n >= 2 && y > 0) K.gcls[1] = y; } - K.guard_cls = K.gcls[0]; if (K.nplan == 2) LOG("秘境:本场守护者两位,类号 %d 与 %d(生命 ×%d.%03d、伤害 ×%d.%03d)", K.gcls[0], K.gcls[1], hi_duo_x1000(0) / 1000, hi_duo_x1000(0) % 1000, hi_duo_x1000(1) / 1000, hi_duo_x1000(1) % 1000); } + // 闯入首领(设计稿第二、十七、十八节):80 层起 1 位、90 层起 2 位,开局抽好——是谁(多首领同场的池里、不与本场守护者同类号的那几位,两位不重样)、 + // 在进度百分之几闯入(1 位:30–70;2 位:25–45 与 55–80)。同一场不重抽。掉落不干预:它被打死就照自己在当前难度的原版表掉。 + // 测试开关:DM_RIFT_TEST_INVADE=<类号>[,<类号>] 指定是谁、DM_RIFT_TEST_INVPCT=<百分数> 指定第一位的闯入点 + // Invading bosses (design draft): 1 from level 80, 2 from level 90, drawn at the start - who (from the pool for several bosses in one fight, not sharing a class id with this run's Guardians, the two being different), + // and at what percentage of progress they invade (1 boss: 30–70; 2 bosses: 25–45 and 55–80). Not redrawn within a run. Drops are not interfered with: when killed it drops from its own original table for the current difficulty. + // Test switches: DM_RIFT_TEST_INVADE=[,] chooses who, DM_RIFT_TEST_INVPCT= the first one's invasion point + { memset(K.inv_cls, 0, sizeof K.inv_cls); memset(K.inv_st, 0, sizeof K.inv_st); memset(K.inv_id, 0, sizeof K.inv_id); K.inv_n = !hi_on("invade", 80) ? 0 : (K.tier >= 90 || (getenv("DM_RIFT_TEST_HI") && strstr(getenv("DM_RIFT_TEST_HI"), "invade2"))) ? 2 : 1; + int pool[4], np = 0; for (int q = 0; q < 4; q++) pool[np++] = k_duo[q]; // 可以与本场守护者同类号:守护者现身时在场的闯入首领退场(见刷守护者处),两者不会同场 | it may share a class id with this run's Guardians: when the Guardians appear an invading boss that is present leaves (see where the Guardians are spawned), so the two are never on the field together + if (K.inv_n > np) K.inv_n = np; + for (int q = 0; q < K.inv_n; q++) { int j = rnd(np); K.inv_cls[q] = pool[j]; pool[j] = pool[--np]; + K.inv_pct[q] = K.inv_n == 1 ? 30 + rnd(41) : q == 0 ? 25 + rnd(21) : 55 + rnd(26); } + const char *e = getenv("DM_RIFT_TEST_INVADE"); if (e && K.inv_n) { int x = 0, y = 0, n = sscanf(e, "%d,%d", &x, &y); if (n >= 1 && x > 0) K.inv_cls[0] = x; if (n >= 2 && y > 0 && K.inv_n > 1) K.inv_cls[1] = y; } + if ((e = getenv("DM_RIFT_TEST_INVPCT")) && K.inv_n) K.inv_pct[0] = atoi(e); + if (K.inv_n) { int nd = atomic_load(&K.need); atomic_store(&K.need, nd * (100 + 12 * K.inv_n) / 100); // 打掉一位 +12% 进度:进度需求同步上调,免得内容更多反而更快出守护者 | +12% progress for each one killed: the progress requirement is raised to match, so that more content does not make the Guardians appear sooner + if (K.inv_n >= 2) say("dmRiftSayFoes", K.inv_n); // 90 层起开局说一声本场有几位强敌(不说是谁、不说何时) | from level 90, say at the start how many strong enemies this run has (not who, not when) + LOG("秘境:本场闯入首领 %d 位:类号 %d(进度 %d%% 时)%s;进度需求 %d → %d", K.inv_n, K.inv_cls[0], K.inv_pct[0], K.inv_n > 1 ? "与另一位(见闯入时的日志)" : "", nd, atomic_load(&K.need)); } } + // 特殊精英:开局把池洗成本场的出场次序(放完一轮再从头) + // Special elites: at the start, shuffle the pool into this run's order of appearance (after a full round, start again from the top) + { K.su_next = K.su_cnt = 0; K.su_last = 0; memset(K.su_live, 0, sizeof K.su_live); int np = (int)sizeof k_su_pool; for (int q = 0; q < np; q++) K.su_order[q] = k_su_pool[q]; + for (int q = np - 1; q > 0; q--) { int j = rnd(q + 1), x = K.su_order[q]; K.su_order[q] = K.su_order[j]; K.su_order[j] = x; } + const char *e = getenv("DM_RIFT_TEST_SUROWS"); if (e) { char bf[200]; strlcpy(bf, e, sizeof bf); int q = 0; for (char *sv, *k = strtok_r(bf, ",", &sv); k && q < np; k = strtok_r(NULL, ",", &sv)) K.su_order[q++] = atoi(k); } + if (hi_on("su", 75)) LOG("秘境:本场特殊精英:原生怪留 %d%%,同时在场最多 %d 组,头几位的行号 %d、%d、%d", su_nat_pct(K.tier), su_cap(K.tier), K.su_order[0], K.su_order[1], K.su_order[2]); } + // 守护者分波(设计稿第二十四节第 3 问):安达利尔死时会连带杀死同场的其它首领,所以她单独一波、先出;她倒下 WAVE_GAP 拍后下一波才刷 + // (实测她死后 0 / 25 / 75 拍刷出的迪亚波罗都活着,各 1 局;取 75 拍留余量,也给玩家喘口气)。 + // 95–99 层:安达利尔(生命 ×0.5 → ×0.9)→ 本场那一对(照双守护者的 s / d);100 层:安达利尔(×1.0)→ 一对 → 另一对(四位各 ×0.5、伤害 ×1.0)。94 层及以下一波不变 + // Guardian waves (design draft section 24, question 3): when Andariel dies she also kills the other bosses on the field, so she is a wave of her own and comes first; the next wave is spawned WAVE_GAP ticks after she falls + // (measured: Diablo spawned 0 / 25 / 75 ticks after her death stayed alive, 1 run each; 75 ticks is taken to leave margin, and it also gives the player a breather). + // Levels 95–99: Andariel (life x0.5 -> x0.9) -> this run's pair (with the s / d of the two-Guardian fight); level 100: Andariel (x1.0) -> a pair -> the other pair (each of the four x0.5, damage x1.0). Level 94 and below: one wave, unchanged + K.wave = 0; K.wave_t = 0; K.nwave = 1; K.wn[0] = K.nplan; K.wcls[0][0] = K.gcls[0]; K.wcls[0][1] = K.gcls[1]; K.whp[0] = K.nplan == 2 ? hi_duo_x1000(0) : 1000; K.wdm[0] = K.nplan == 2 ? hi_duo_x1000(1) : 1000; + if (K.nplan == 2 && hi_on("wave", 95)) { const char *tw = getenv("DM_RIFT_TEST_HI"); int three = K.tier >= 100 || (tw && strstr(tw, "wave3")); + K.wn[0] = 1; K.wcls[0][0] = 156; K.wcls[0][1] = 0; K.wdm[0] = 1000; K.whp[0] = three ? 1000 : 500 + 100 * ((K.tier < 95 ? 95 : K.tier > 99 ? 99 : K.tier) - 95); + K.wn[1] = 2; K.wcls[1][0] = K.gcls[0]; K.wcls[1][1] = K.gcls[1]; K.whp[1] = three ? 500 : hi_duo_x1000(0); K.wdm[1] = three ? 1000 : hi_duo_x1000(1); K.nwave = 2; + if (three) { int q = 0; for (int k = 0; k < 4; k++) if (k_duo[k] != K.gcls[0] && k_duo[k] != K.gcls[1] && q < 2) K.wcls[2][q++] = k_duo[k]; K.wn[2] = q; K.whp[2] = 500; K.wdm[2] = 1000; K.nwave = 3; } + LOG("秘境:本场守护者分 %d 波:安达利尔(生命 ×%d.%03d)→ 类号 %d 与 %d(×%d.%03d)%s", K.nwave, K.whp[0] / 1000, K.whp[0] % 1000, K.wcls[1][0], K.wcls[1][1], K.whp[1] / 1000, K.whp[1] % 1000, K.nwave == 3 ? " → 另外两位(×0.500)" : ""); } + K.guard_cls = K.gcls[0]; if (K.nplan == 2 && K.nwave == 1) LOG("秘境:本场守护者两位,类号 %d 与 %d(生命 ×%d.%03d、伤害 ×%d.%03d)", K.gcls[0], K.gcls[1], hi_duo_x1000(0) / 1000, hi_duo_x1000(0) % 1000, hi_duo_x1000(1) / 1000, hi_duo_x1000(1) % 1000); } K.t0_ns = guest_ns(); if (getenv("DM_RIFT_TEST_LATE")) { K.t0_ns -= (uint64_t)RIFT_SECS * 1000000000ull; LOG("秘境:测试 DM_RIFT_TEST_LATE 开局即超时"); } // 造「超时打倒守护者」现场 | set up the "Guardian defeated after time ran out" test case K.players_old = dm_hud_requested_players(); if (!K.players_old) K.players_old = 1; @@ -1125,6 +1265,23 @@ static int start_rift(uint64_t G, uint64_t player, uint32_t t, int tier) { if (!R.gift) L.gift_due = 1; // 第一次进秘境送一颗彩虹刻面,只送一次:落到秘境图里再掉在脚下 | The first rift entry gives one Rainbow Facet, only once: dropped at the player's feet after landing on a rift map return 1; } +// 刷当前这一波守护者(K.wave)。一位:人右下 6 格;两位:一左一右各 6 格。每位先照常按层改(守护者 = 本层怪物等级 + 3,起算层也 + 3,同吃本层总倍率), +// 再乘这一波的生命系数(截顶之前乘)与伤害系数 +// Spawn the Guardians of the current wave (K.wave). One: 6 tiles to the player's lower right; two: 6 tiles to the left and 6 to the right. Each is first scaled by level as usual (Guardian = this level's monster level + 3, the starting level also + 3, taking this level's total multiplier as well), +// then multiplied by this wave's life factor (before capping) and damage factor +#define WAVE_GAP 75 +static void guard_wave(uint64_t G, uint64_t player, uint32_t t, int lowhp) { + static const int ox[2][2] = { { 6, 0 }, { 6, -6 } }, oy[2][2] = { { 6, 0 }, { 6, 6 } }; int w = K.wave, nw = K.wn[w] < 1 ? 1 : K.wn[w] > 2 ? 2 : K.wn[w], x, y, n = 0; unit_xy(player, &x, &y); hs_sync(); + for (int i = 0; i < nw; i++) { int32_t pos[2] = { x + ox[nw - 1][i], y + oy[nw - 1][i] }; uint64_t rr = free_spot(G, unit_room(player), pos); + uint64_t u = rr ? ((uint64_t (*)(uint64_t, uint64_t, int, int, int, int, int, int, uint64_t))(B + 0x7ce630))(G, rr, 1, K.wcls[w][i], pos[0], pos[1], 1, 0, 0x10) : 0; + if (!u) { LOG("【红】秘境:守护者第 %d 波第 %d 位(类号 %d)没刷出来", w + 1, i + 1, K.wcls[w][i]); continue; } + K.guards[i] = *(uint32_t *)(uintptr_t)(u + 8); K.gcls[i] = K.wcls[w][i]; if (!K.guard) K.guard = K.guards[i]; n++; + if (lowhp) ss(u, 6, 256); else if (K.tier >= 9) { g_hp_mul = K.whp[w]; scale_monster(G, u, target_level(player) + 3, dm_rift_tier_level(9, gs(player, 12)) + 3); g_hp_mul = 1000; } + if (K.wdm[w] != 1000 && !lowhp) ss(u, 25, (int)((100LL + gs(u, 25)) * K.wdm[w] / 1000 - 100)); // 伤害:属性 25 是「伤害 +N%」,整体乘 d 即 (100 + N) × d − 100 | damage: stat 25 is "damage +N%", so multiplying the whole by d gives (100 + N) x d - 100 + HS.guard_hp += gs(u, 7) >> 8; + LOG("秘境:拍 %u 刷守护者%s%s 类号 %d id %u 等级 %d 生命 %d 伤害百分比 %d", t, K.nwave > 1 ? (w == 0 ? "(第 1 波)" : w == 1 ? "(第 2 波)" : "(第 3 波)") : "", nw == 2 ? (i ? "(第二位)" : "(第一位)") : "", K.wcls[w][i], K.guards[i], gs(u, 12), gs(u, 7) >> 8, gs(u, 25)); } + atomic_store(&K.gdead, 0); atomic_store(&K.gtotal, n); + if (n) { if (w == 0) say(nw == 2 && n == 2 ? "dmRiftSayGuardians" : "dmRiftSayGuardian"); else say("dmRiftSayWave", w + 1, K.nwave); } } void dm_rift_tick(uint64_t G, uint64_t player, uint8_t *main_base) { B = main_base; if (!G || !player || !B) return; atomic_store(&g_merc_req, 0); if (getenv("DM_TEST_MERC_EQUIP") || getenv("DM_TEST_MERC_DUMP")) merc_test(G, player, *(uint32_t *)(uintptr_t)(G + 0x170)); @@ -1269,51 +1426,179 @@ void dm_rift_tick(uint64_t G, uint64_t player, uint8_t *main_base) { // Newly spawned hostile monsters get their stats changed by level (from level 9). Test switch DM_RIFT_TEST_LOWHP=1: change to 1 life point (hold the main attack button and kill all the way through; verifies scoring / guardian / level increase) static int lowhp = -1; if (lowhp < 0) lowhp = getenv("DM_RIFT_TEST_LOWHP") != NULL; if (K.tier >= 9 || lowhp) { static uint32_t r_; uint32_t w = atomic_load(&g_newq_w); if (w - r_ > NQ) r_ = w - NQ; int lt = target_level(player); - for (; r_ != w; r_++) { uint32_t id = atomic_load(&g_newq[r_ % NQ]); uint64_t u = find_unit(G, 1, id); if (u && !is_guard(id)) { if (K.tier >= 9) scale_monster(G, u, lt, dm_rift_tier_level(9, gs(player, 12))); if (lowhp) ss(u, 6, 256); dmg_probe_add(id, t); hs_spawn(id, gs(u, 7) >> 8); } } } + for (; r_ != w; r_++) { uint32_t id = atomic_load(&g_newq[r_ % NQ]); uint64_t u = find_unit(G, 1, id); if (u && !is_guard(id) && hi_on("summon", 75) && boss_summon(*(uint32_t *)(uintptr_t)(u + 4))) { static int n, sq = -1; int cur = atomic_load(&g_run_seq); if (cur != sq) { sq = cur; n = 0; } + if (n++ < 4) LOG("秘境:首领召唤物 id %u(类号 %u)不按层改,保持原版:等级 %d 生命 %d", id, *(uint32_t *)(uintptr_t)(u + 4), gs(u, 12), gs(u, 7) >> 8); hs_spawn(id, gs(u, 7) >> 8); continue; } + if (u && !is_guard(id)) { uint64_t md = rd(u + 0x10); int su = md && (*(uint8_t *)(uintptr_t)(md + 0x1a) & 0x02) && hi_on("su", 75), sm = !su && su_minion(id); /* 特殊精英本体:生命另乘 SU_HP_X;组里的随从另乘 SU_MINION_X1000 | special elite body: life additionally multiplied by SU_HP_X; minions in the group additionally by SU_MINION_X1000 */ + if (K.tier >= 9) { if (su) { g_hp_mul = SU_HP_X * 1000; g_hp_soft = SU_HP_SOFT; } else if (sm) g_hp_mul = SU_MINION_X1000; scale_monster(G, u, lt, dm_rift_tier_level(9, gs(player, 12))); g_hp_mul = 1000; g_hp_soft = 0; } if (su) { static int n; if (n++ < 12) LOG("秘境:特殊精英本体 id %u(类号 %u,超级独特号 %d)生命另乘 %d:等级 %d 生命 %d", id, *(uint32_t *)(uintptr_t)(u + 4), *(int16_t *)(uintptr_t)(md + 0x2a), SU_HP_X, gs(u, 12), gs(u, 7) >> 8); } if (lowhp) ss(u, 6, 256); dmg_probe_add(id, t); hs_spawn(id, gs(u, 7) >> 8); } } } dmg_probe_pump(G, t); hs_tick(G, player, t, lv); + // 测试开关 DM_RIFT_TEST_PETGOD=1:每 10 拍把秘境图里友方怪物单位(玩家的随从)的当前生命回满——自动局靠随从代打,随从被围死后就没人补最后一下了 + // Test switch DM_RIFT_TEST_PETGOD=1: every 10 ticks, refill the current life of friendly monster units (the player's minions) in the rift map - unattended runs rely on minions to do the fighting, and once the minions are surrounded and killed nobody lands the last hit + { static int on = -1; if (on < 0) on = getenv("DM_RIFT_TEST_PETGOD") != NULL; if (on && t % 10 == 0 && in_rift_map(lv)) for (int b = 0; b < 128; b++) for (uint64_t u = rd(G + 0x2230 + 1 * 0x400 + 8 * b); u; u = rd(u + 0x158)) { + uint32_t m = *(uint32_t *)(uintptr_t)(u + 0xc); if (m != 0 && m != 12 && unit_align(u)) ss(u, 6, gs(u, 7)); } } // 测试读数 DM_RIFT_TEST_ILVL=1:每 10 秒数一次地上的物品(服务端物品表 G+0x2e30,模式 3),报物品等级(数据块 +0x38)范围——验 B 方案下掉落物品等级跟不跟改过的怪物等级 // Test readout DM_RIFT_TEST_ILVL=1: every 10 seconds count the items on the ground (server item table G+0x2e30, mode 3) and report the item level (data block +0x38) range -- verifies whether drop item levels follow the modified monster level under plan B { static int il = -1; if (il < 0) il = getenv("DM_RIFT_TEST_ILVL") != NULL; if (il && t % 250 == 0) { int n = 0, mn = 999, mx = 0; for (int bb = 0; bb < 128; bb++) for (uint64_t it = rd(G + 0x2e30 + 8 * bb); it; it = rd(it + 0x158)) { uint64_t d = rd(it + 0x10); if (!d || *(uint32_t *)(uintptr_t)(it + 0xc) != 3) continue; int v = *(int32_t *)(uintptr_t)(d + 0x38); n++; if (v < mn) mn = v; if (v > mx) mx = v; } LOG("秘境:测试读数 拍 %u 地上物品 %d 件,物品等级 %d–%d", t, n, n ? mn : 0, mx); } } + // 测试开关 DM_RIFT_TEST_TOUR=1:秘境进行中每秒用原版传送把人放到本图房间链里的下一间(中心附近的空地),整张图的房间都激活一遍——验「90 层起不放普通预设怪」要整图的读数 + // Test switch DM_RIFT_TEST_TOUR=1: during a rift, every second the original teleport puts the player in the next room of this map's room chain (open ground near the centre), so every room of the whole map gets activated - verifying "no ordinary preset monsters from level 90" needs readings from the whole map + { static int tour = -1, k; if (tour < 0) tour = getenv("DM_RIFT_TEST_TOUR") != NULL; + if (tour && t % 25 == 0 && in_rift_map(lv) && atomic_load(&K.st) == ST_RUN) { uint64_t lvp = level_of(player), r = dm_level_rooms(lvp); int i = 0, nr = 0; + for (uint64_t q = r; q && nr < 2000; q = rd(q + 0x48)) nr++; + for (; r && i < k % (nr ? nr : 1); r = rd(r + 0x48)) i++; + if (r) { int32_t pos[2] = { *(int32_t *)(uintptr_t)(r + 0x60) * 5 + *(int32_t *)(uintptr_t)(r + 0x68) * 5 / 2, *(int32_t *)(uintptr_t)(r + 0x64) * 5 + *(int32_t *)(uintptr_t)(r + 0x6c) * 5 / 2 }; + uint64_t rs = room_load(G, lvp, pos[0], pos[1]), rr = rs ? free_spot(G, rs, pos) : 0; int ok = rr && dm_teleport(B, G, player, rr, pos[0], pos[1]); + static int ln; if (ln++ < 3 || k == nr - 1) LOG("秘境:测试逐间跳 第 %d / %d 间 → %d,%d %s", k + 1, nr, pos[0], pos[1], ok ? "成" : "不成"); } + { static uint32_t seen[8192]; static int scls[8192], sfl[8192], ns; /* 逐间跳全程:本图出现过的怪按单位 id 去重累计;走完一轮后 5 秒按类号报 | over the whole room-by-room jump: monsters seen in this map are accumulated, de-duplicated by unit id; 5 seconds after a full round, reported by class id */ + for (int b = 0; b < 128; b++) for (uint64_t v = rd(G + 0x2230 + 1 * 0x400 + 8 * b); v; v = rd(v + 0x158)) { uint32_t id = *(uint32_t *)(uintptr_t)(v + 8); if (any_level(v) != lv) continue; int q = 0; for (; q < ns && seen[q] != id; q++) {} + if (q == ns && ns < 8192) { uint64_t md = rd(v + 0x10); uint32_t mo = *(uint32_t *)(uintptr_t)(v + 0xc); seen[ns] = id; scls[ns] = *(int32_t *)(uintptr_t)(v + 4); sfl[ns] = (md ? *(uint8_t *)(uintptr_t)(md + 0x1a) : 0) | (mo == 0 || mo == 12 ? 0x100 : 0); ns++; } } + if (k == nr + 5) { static int cl[1024], cn[1024], cf[1024]; int nc = 0; + for (int q = 0; q < ns; q++) { int j2 = 0; for (; j2 < nc && cl[j2] != scls[q]; j2++) {} if (j2 == nc && nc < 1024) { cl[nc] = scls[q]; cn[nc] = cf[nc] = 0; nc++; } if (j2 < 1024) { cn[j2]++; cf[j2] |= sfl[q]; } } + LOG("[逐间跳读数] 关卡 %d 出现过的怪 %d 只、%d 种", lv, ns, nc); for (int j2 = 0; j2 < nc; j2++) LOG("[逐间跳读数] 类号 %d ×%d 标志 0x%03x(0x100 = 有一只首次见到时已是死的)", cl[j2], cn[j2], cf[j2]); } } + k++; } } // 测试开关 DM_RIFT_TEST_PULL=1:每 3 秒用原版传送 0x7cc530 把人放到一只还活着的敌对怪(客户端认的)旁边——脚本按主攻击键就能一路打(验计分 / 守护者) // Test switch DM_RIFT_TEST_PULL=1: every 3 seconds use the original game's teleport 0x7cc530 to put the player next to a still-living hostile monster (as recognized by the client) -- a script only has to press the main attack button to fight all the way through (verifies scoring / guardian) { static int pull = -1; if (pull < 0) pull = getenv("DM_RIFT_TEST_PULL") != NULL; - if (pull && t % 38 == 0 && in_rift_map(lv) && K.guard && !atomic_load(&K.guard_dead)) { uint64_t g = 0; for (int i = 0; i < 3 && !g; i++) { uint64_t gu = K.guards[i] ? find_unit(G, 1, K.guards[i]) : 0; uint32_t gm = gu ? *(uint32_t *)(uintptr_t)(gu + 0xc) : 0; if (gu && gm != 0 && gm != 12) g = gu; } int x, y; if (g && unit_xy(g, &x, &y)) dm_teleport(B, G, player, unit_room(g), x + 2, y + 2); } - else if (pull && t % 38 == 0 && in_rift_map(lv)) { uint32_t w = atomic_load(&g_newq_w); int px, py, bd = 1 << 30, bx = 0, by = 0; unit_xy(player, &px, &py); // 最近的那只 | The nearest one - for (uint32_t k = 0; k < NQ && k < w; k++) { uint64_t u = find_unit(G, 1, atomic_load(&g_newq[(w - 1 - k) % NQ])); if (!u || unit_level(u) != lv) continue; uint32_t m = *(uint32_t *)(uintptr_t)(u + 0xc); if (m == 0 || m == 12) continue; - int x, y; if (!unit_xy(u, &x, &y)) continue; int d = abs(x - px) + abs(y - py); if (d < bd) { bd = d; bx = x; by = y; } } + if (pull && t % 38 == 0 && in_rift_map(lv) && ((K.guard && !atomic_load(&K.guard_dead)) || K.inv_st[0] == 2 || K.inv_st[1] == 2)) { uint64_t g = 0; for (int i = 0; i < 2 && !g; i++) { uint64_t gu = K.inv_st[i] == 2 ? find_unit(G, 1, K.inv_id[i]) : 0; uint32_t gm = gu ? *(uint32_t *)(uintptr_t)(gu + 0xc) : 0; if (gu && gm != 0 && gm != 12) g = gu; } /* 在场的闯入首领优先 | an invading boss that is present takes priority */ + for (int i = 0; i < 3 && !g; i++) { uint64_t gu = K.guards[i] ? find_unit(G, 1, K.guards[i]) : 0; uint32_t gm = gu ? *(uint32_t *)(uintptr_t)(gu + 0xc) : 0; if (gu && gm != 0 && gm != 12) g = gu; } int x, y; if (g && unit_xy(g, &x, &y)) dm_teleport(B, G, player, unit_room(g), x + 2, y + 2); } + else if (pull && t % 38 == 0 && in_rift_map(lv)) { uint32_t w = atomic_load(&g_newq_w); int px, py, bd = 1 << 30, bx = 0, by = 0; unit_xy(player, &px, &py); // 最近的那只;同一只连着 4 次(约 6 秒)都是最近的还没死,就当它打不死(投石车一类的预设单位、卡在墙里的),以后不再找它 | the nearest one; if the same one is the nearest 4 times in a row (about 6 seconds) and still not dead, treat it as unkillable (preset units such as catapults, ones stuck in walls) and never look for it again + static uint32_t bl[64], last; static int nbl, rep; uint32_t bid = 0; + for (uint32_t k = 0; k < NQ && k < w; k++) { uint32_t id = atomic_load(&g_newq[(w - 1 - k) % NQ]); uint64_t u = find_unit(G, 1, id); if (!u || unit_level(u) != lv) continue; uint32_t m = *(uint32_t *)(uintptr_t)(u + 0xc); if (m == 0 || m == 12) continue; + int x, y, skip = 0; for (int q = 0; q < nbl && q < 64; q++) skip |= bl[q] == id; if (skip || !unit_xy(u, &x, &y)) continue; int d = abs(x - px) + abs(y - py); if (d < bd) { bd = d; bx = x; by = y; bid = id; } } + if (bid && bid == last) { if (++rep >= 4) { bl[nbl++ % 64] = bid; rep = 0; LOG("秘境:测试拉人 单位 id %u 连着 4 次是最近的还没死,不再找它", bid); } } else { last = bid; rep = 0; } if (bd < (1 << 30) && bd > 3) { uint64_t lvp = level_of(player); int32_t pos[2] = { bx + 1, by + 1 }; uint64_t rs = room_at(lvp, pos[0], pos[1]), rr = rs ? free_spot(G, rs, pos) : 0; - int ok = dm_teleport(B, G, player, rr, pos[0], pos[1]); static int ln; if (ln++ < 5) LOG("秘境:测试拉人 → %d,%d(最近的怪 %d 格)%s", pos[0], pos[1], bd, ok ? "成" : "不成"); } } } + int ok = dm_teleport(B, G, player, rr, pos[0], pos[1]); static int ln; if (ln++ < 5 || ln % 20 == 0) LOG("秘境:测试拉人 → %d,%d(最近的怪 id %u,%d 格)%s", pos[0], pos[1], bid, bd, ok ? "成" : "不成"); } + else { static int ln2; if (ln2++ % 20 == 0) LOG("秘境:测试拉人 这一次没拉(最近的怪 id %u,%d 格;新怪队列写到 %u)", bid, bd == 1 << 30 ? -1 : bd, w); } } } // 计时 // Timer { uint64_t now = guest_ns(); if (!atomic_load(&K.timeout) && now - K.t0_ns > (uint64_t)RIFT_SECS * 1000000000ull) { atomic_store(&K.timeout, 1); say("dmRiftSayTimeout"); } } // 守护者 // Guardian + inv_gone_pump(G, t); + if (in_rift_map(lv) && g_entry_lv != lv) { int ex, ey; if (unit_xy(player, &ex, &ey)) { g_entry_lv = lv; g_entry_x = ex; g_entry_y = ey; } } else if (!in_rift_map(lv)) g_entry_lv = 0; + // 特殊精英:每秒看一次要不要放下一组(规则见池那段注释)。「前方」= 玩家最近 2 秒走的方向;八个方向从它起、左右交替着找空地,离人不足 45 格或离本图入口不足 40 格的不要 + // Special elites: once a second, check whether to place the next group (rules in the comment on the pool). "Ahead" = the direction the player walked in the last 2 seconds; the eight directions are searched for open ground starting from it, alternating left and right; spots less than 45 tiles from the player or less than 40 tiles from this map's entrance are rejected + if (t % 25 == 0 && hi_on("su", 75) && atomic_load(&K.st) == ST_RUN && g_entry_lv == lv) { static int hx[2], hy[2], hk; int px, py, live = 0; unit_xy(player, &px, &py); + int dx = hx[hk] ? px - hx[hk] : 0, dy = hx[hk] ? py - hy[hk] : 0; hx[hk] = px; hy[hk] = py; hk ^= 1; + for (int i = 0; i < 3; i++) { if (!K.su_live[i]) continue; uint64_t u = find_unit(G, 1, K.su_live[i]); uint32_t m = u ? *(uint32_t *)(uintptr_t)(u + 0xc) : 1; + if (u && (m == 0 || m == 12)) K.su_live[i] = 0; else if (!u) { if (t - K.su_seen[i] > 750) K.su_live[i] = 0; } /* 本体死了这一组就算打完;30 秒找不到单位(玩家换了图 / 回了城,房间卸载)也不再占名额 | once the body is dead this group counts as finished; if its unit cannot be found for 30 seconds (the player changed map / went to town, the room was unloaded) it no longer takes up a slot either */ + else { K.su_seen[i] = t; int x, y; unit_xy(u, &x, &y); /* 追击(见池那段注释):本体离玩家 80 格以外满 5 秒,挪到玩家前方约 70 格的空地(随从照原版自己跟着首领) | pursuit (see the comment on the pool): once the body has been more than 80 tiles from the player for 5 seconds, move it to open ground about 70 tiles ahead of the player (the minions follow their boss on their own, as in the original) */ + if (abs(x - px) + abs(y - py) <= 80) K.su_near[i] = t; + else if (t - K.su_near[i] >= 125) { static const int cx[8] = { 70, 50, 0, -50, -70, -50, 0, 50 }, cy[8] = { 0, 50, 70, 50, 0, -50, -70, -50 }; int d0 = rnd(8), best = 0, ok = 0; int32_t pos[2]; + if (dx || dy) for (int d = 0; d < 8; d++) { int v = dx * cx[d] + dy * cy[d]; if (v > best) { best = v; d0 = d; } } + for (int k = 0; k < 8 && !ok; k++) { int d = (d0 + (k & 1 ? (k + 1) / 2 : 8 - k / 2)) % 8; pos[0] = px + cx[d]; pos[1] = py + cy[d]; uint64_t rs = room_load(G, level_of(player), pos[0], pos[1]), rr = rs ? free_spot(G, rs, pos) : 0; + if (rr && abs(pos[0] - px) + abs(pos[1] - py) >= 60) ok = dm_teleport(B, G, u, rr, pos[0], pos[1]); } + K.su_near[i] = t; static int n; if (n++ < 8) LOG("秘境:拍 %u 特殊精英(id %u)离玩家 %d 格满 5 秒,%s", t, K.su_live[i], abs(x - px) + abs(y - py), ok ? "挪到玩家前方" : "周围没有空地,下次再挪"); } } + live += K.su_live[i] != 0; } + if (!K.guard && live < su_cap(K.tier) && K.su_cnt < su_quota(K.tier) && g_near_now < SU_NEAR && t - K.su_last >= 75) { + static const int sx[8] = { 70, 50, 0, -50, -70, -50, 0, 50 }, sy[8] = { 0, 50, 70, 50, 0, -50, -70, -50 }; int d0 = rnd(8), best = 0, np = (int)sizeof k_su_pool, baal = 0, row; + if (dx || dy) for (int d = 0; d < 8; d++) { int v = dx * sx[d] + dy * sy[d]; if (v > best) { best = v; d0 = d; } } + for (int w = 0; w < K.nwave; w++) for (int q = 0; q < K.wn[w]; q++) baal |= K.wcls[w][q] == 544; for (int q = 0; q < K.inv_n; q++) baal |= K.inv_cls[q] == 544; + do row = K.su_order[K.su_next++ % np]; while (baal && (row == 24 || row == 36 || row == 38)); + uint64_t u = 0; int32_t pos[2] = { 0, 0 }; int f_room = 0, f_near = 0, f_fn = 0; + for (int k = 0; k < 8 && !u; k++) { int d = (d0 + (k & 1 ? (k + 1) / 2 : 8 - k / 2)) % 8; pos[0] = px + sx[d]; pos[1] = py + sy[d]; uint64_t rs = room_load(G, level_of(player), pos[0], pos[1]), rr = rs ? free_spot(G, rs, pos) : 0; + if (!rr) { f_room++; continue; } if (abs(pos[0] - px) + abs(pos[1] - py) < 45 || abs(pos[0] - g_entry_x) + abs(pos[1] - g_entry_y) < 40) { f_near++; continue; } f_fn++; + u = su_spawn(G, rr, pos[0], pos[1], row); } + static int fails; if (u) fails = 0; else if (++fails < 10) K.su_next--; else fails = 0; /* 放不成:这一位留着 1 秒后再试;同一位连着 10 次放不成就跳过它,免得一行卡住整场 | could not place it: keep this one and try again in 1 second; after 10 failures in a row for the same one, skip it so that one row does not hold up the whole run */ + if (!u) { K.su_last = t - 50; static int n; if (n++ % 20 == 0) LOG("秘境:拍 %u 特殊精英(行 %d)这一秒没放成(第 %d 次):八个方向里没有房间 / 空地的 %d 个、离人或离入口太近的 %d 个、原版函数没刷出来的 %d 个", t, row, n, f_room, f_near, f_fn); } /* 周围没有合适的空地(或原版函数没刷出来):这一位留着,1 秒后再试 | no suitable open ground around (or the original function spawned nothing): keep this one and try again in 1 second */ + else { uint32_t uid = *(uint32_t *)(uintptr_t)(u + 8); int ux = pos[0], uy = pos[1], nm = 0; + for (int b = 0; b < 128; b++) for (uint64_t v = rd(G + 0x2230 + 1 * 0x400 + 8 * b); v; v = rd(v + 0x158)) { uint32_t vid = *(uint32_t *)(uintptr_t)(v + 8); uint64_t md = rd(v + 0x10); int x, y; + if (vid > uid && md && (*(uint8_t *)(uintptr_t)(md + 0x1a) & 0x10) && unit_xy(v, &x, &y) && abs(x - ux) + abs(y - uy) <= 15) { g_su_min[g_su_min_w++ % 64] = vid; nm++; } } + for (int i = 0; i < 3; i++) if (!K.su_live[i]) { K.su_live[i] = uid; K.su_seen[i] = K.su_near[i] = t; break; } K.su_cnt++; K.su_last = t; + LOG("秘境:拍 %u 特殊精英第 %d 组刷出:行 %d 类号 %u id %u 在 %d,%d(离人 %d 格、离入口 %d 格;此前在场 %d 组、40 格内敌对 %d 只;随从 %d 只)", t, K.su_cnt, row, *(uint32_t *)(uintptr_t)(u + 4), *(uint32_t *)(uintptr_t)(u + 8), pos[0], pos[1], + abs(pos[0] - px) + abs(pos[1] - py), abs(pos[0] - g_entry_x) + abs(pos[1] - g_entry_y), live, g_near_now, nm); } } } + // 测试读数 DM_RIFT_TEST_GONE=<拍>:退场的闯入首领每 25 拍报一次位置 / 模式 / 生命 / 离人多远;到 <拍> 时把人传到它跟前,并让固定输出替身开始打它(验:退场后它动不动、走过去会不会打起来、打死给不给进度 / 掉不掉东西) + // Test readout DM_RIFT_TEST_GONE=: an invading boss that has left reports its position / mode / life / distance from the player every 25 ticks; at the player is teleported next to it and the fixed-output stand-in starts hitting it (to verify: whether it moves after leaving, whether walking up to it starts a fight, whether killing it gives progress / drops) + { static int at = -1, hit, gx, gy, cls; static uint32_t hit_t; if (at < 0) { const char *e = getenv("DM_RIFT_TEST_GONE"); at = e ? atoi(e) : 0; } + // 测试开关 DM_RIFT_TEST_GONEKILL=1:退场后第 10 拍把人传到它跟前、把它当前血置 1(由随从补刀)——验「退场到被真移除之间被打死」给不给进度、掉不掉东西 + // Test switch DM_RIFT_TEST_GONEKILL=1: at the 10th tick after it leaves, teleport the player next to it and set its current life to 1 (a minion delivers the last hit) - to verify whether "killed between leaving and being truly removed" gives progress or drops anything + if (getenv("DM_RIFT_TEST_GONEKILL")) for (int i = 0; i < 2; i++) { static uint32_t t0[2], did[2]; uint64_t u = g_inv_gone[i] ? find_unit(G, 1, g_inv_gone[i]) : 0; if (!u) continue; if (did[i] != g_inv_gone[i]) { did[i] = g_inv_gone[i]; t0[i] = t; } + uint32_t m = *(uint32_t *)(uintptr_t)(u + 0xc); int x, y; unit_xy(u, &x, &y); + if (t - t0[i] == 10) { LOG("[退场读数] 拍 %u 把人传到退场的闯入首领跟前(它在 %d,%d,进度 %d)", t, x, y, atomic_load(&K.score)); dm_teleport(B, G, player, unit_room(u), x + 2, y + 2); } + if (t - t0[i] >= 10 && m != 0 && m != 12) ss(u, 6, 256); + if ((m == 0 || m == 12) && t0[i] != 1) { t0[i] = 1; LOG("[退场读数] 拍 %u 退场的闯入首领被打死了(模式 %u),进度 %d", t, m, atomic_load(&K.score)); } } + if (at > 0) { for (int i = 0; i < 2; i++) { uint64_t u = g_inv_gone[i] ? find_unit(G, 1, g_inv_gone[i]) : 0; if (g_inv_gone_xy[i][0]) { gx = g_inv_gone_xy[i][0]; gy = g_inv_gone_xy[i][1]; cls = K.inv_cls[i]; } if (!u || t % 25) continue; + int x, y, px, py; unit_xy(u, &x, &y); unit_xy(player, &px, &py); LOG("[退场读数] 拍 %u 第 %d 位:位置 %d,%d 模式 %u 生命 %d / %d 离人 %d 格", t, i + 1, x, y, *(uint32_t *)(uintptr_t)(u + 0xc), gs(u, 6) >> 8, gs(u, 7) >> 8, abs(x - px) + abs(y - py)); } + if (gx && t >= (uint32_t)at && !hit) { int32_t pos[2] = { gx, gy }; uint64_t rs = room_load(G, level_of(player), gx, gy), rr = rs ? free_spot(G, rs, pos) : 0; hit = 1; hit_t = t; LOG("[退场读数] 拍 %u 把人传到退场落点 %d,%d(%s)", t, gx, gy, rr && dm_teleport(B, G, player, rr, pos[0], pos[1]) ? "成" : "没成"); } + if (hit == 1 && t - hit_t >= 150) { hit = 2; int n = 0, px, py; unit_xy(player, &px, &py); for (int b = 0; b < 128; b++) for (uint64_t u = rd(G + 0x2230 + 1 * 0x400 + 8 * b); u; u = rd(u + 0x158)) { int x, y; if ((int)*(uint32_t *)(uintptr_t)(u + 4) == cls && unit_xy(u, &x, &y) && abs(x - px) + abs(y - py) < 80) n++; } + LOG("[退场读数] 拍 %u 人已在退场落点 150 拍:80 格内类号 %d 的单位 %d 只(人在 %d,%d)", t, cls, n, px, py); } } } + // 测试开关 DM_RIFT_TEST_SUSEQ=<起始拍>:<行号>,<行号>…(特殊精英的验收轮):秘境进行中从这一拍起,在人旁边用原版函数 main+0x69b310(游戏, 房间, x, y, 行号, 0) 依次刷超级金怪, + // 每秒把人放到它旁边(配 DM_RIFT_TEST_LOWHP=1,新刷的怪只剩 1 点血,随从补一下就死);它死后 40 拍报一行:随从几只、这段时间新掉在地上的物品(类号:品质),再刷下一位。600 拍没死记「没打死」照样往下。 + // 第六个参数含义没查到,取 0 的依据是探路那一局(行 3,本体 + 8 只随从照表刷出)与这一轮 + // Test switch DM_RIFT_TEST_SUSEQ=:,... (acceptance round for special elites): from this tick during a rift, super uniques are spawned one after another next to the player with the original function main+0x69b310(game, room, x, y, row, 0), + // and every second the player is put next to it (with DM_RIFT_TEST_LOWHP=1 a freshly spawned monster has only 1 life left and dies from one hit by a minion); 40 ticks after it dies one line is reported: how many minions, the items newly dropped on the ground in that time (class id:quality), then the next one is spawned. If it is not dead after 600 ticks, "not killed" is recorded and it moves on anyway. + // The meaning of the sixth argument was not found; 0 is used on the basis of the exploratory run (row 3, body + 8 minions spawned as in the table) and this round + { static int at = -1, rows[66], nr, idx, ph, row, minions; static uint32_t t0, hi, cls; + if (at < 0) { const char *e = getenv("DM_RIFT_TEST_SUSEQ"); at = e ? atoi(e) : 0; const char *c = e ? strchr(e, ':') : NULL; char bf[400]; strlcpy(bf, c ? c + 1 : "", sizeof bf); for (char *sv, *k = strtok_r(bf, ",", &sv); k && nr < 66; k = strtok_r(NULL, ",", &sv)) rows[nr++] = atoi(k); } + if (at > 0 && idx < nr && in_rift_map(lv) && atomic_load(&K.st) == ST_RUN) { + if (ph == 0 && t >= (uint32_t)at && t >= t0 + 10) { row = rows[idx]; int x, y; unit_xy(player, &x, &y); int32_t pos[2] = { 0, 0 }; uint64_t rr = 0, u = 0; hi = 0; minions = 0; + for (int b = 0; b < 128; b++) for (uint64_t it = rd(G + 0x2e30 + 8 * b); it; it = rd(it + 0x158)) if (*(uint32_t *)(uintptr_t)(it + 8) > hi) hi = *(uint32_t *)(uintptr_t)(it + 8); + for (int d = 0; d < 8 && !u; d++) { static const int ox[8] = { 12, 9, 0, -9, -12, -9, 0, 9 }, oy[8] = { 0, 9, 12, 9, 0, -9, -12, -9 }; pos[0] = x + ox[d]; pos[1] = y + oy[d]; rr = free_spot(G, unit_room(player), pos); /* 原版函数在同一点试 5 次,那点被残留的随从占着就返回 0:换个方向再试 | the original function tries 5 times at the same point and returns 0 if that point is occupied by leftover minions: try again in another direction */ + u = rr ? su_spawn(G, rr, pos[0], pos[1], row) : 0; } + if (!u) { LOG("[验收轮] 拍 %u 行 %d 刷不出(房间 %s,函数返回 0)", t, row, rr ? "有" : "无"); idx++; t0 = t; } + else { g_suseq_id = *(uint32_t *)(uintptr_t)(u + 8); cls = *(uint32_t *)(uintptr_t)(u + 4); t0 = t; ph = 1; } } + else if (ph == 1) { uint64_t u = find_unit(G, 1, g_suseq_id); uint32_t m = u ? *(uint32_t *)(uintptr_t)(u + 0xc) : 0; int dead = !u || m == 0 || m == 12, x, y; + if (t - t0 == 20) { int px, py; unit_xy(player, &px, &py); for (int b = 0; b < 128; b++) for (uint64_t v = rd(G + 0x2230 + 1 * 0x400 + 8 * b); v; v = rd(v + 0x158)) { uint64_t md = rd(v + 0x10); if (md && (*(uint8_t *)(uintptr_t)(md + 0x1a) & 0x10) && unit_xy(v, &x, &y) && abs(x - px) + abs(y - py) <= 40) minions++; } } + if (!dead && t % 25 == 0 && unit_xy(u, &x, &y)) dm_teleport(B, G, player, unit_room(u), x + 2, y + 2); + if (dead || t - t0 > 600) { LOG("[验收轮] 拍 %u 行 %d 类号 %u id %u %s(刷出后 %u 拍),40 格内带随从标志的 %d 只", t, row, cls, g_suseq_id, dead ? "已死" : "【没打死】", t - t0, minions); ph = 2; t0 = t; } } + else if (ph == 2 && t - t0 >= 40) { char ln[700]; int o = 0, n = 0; ln[0] = 0; + for (int b = 0; b < 128; b++) for (uint64_t it = rd(G + 0x2e30 + 8 * b); it; it = rd(it + 0x158)) { uint64_t d = rd(it + 0x10); if (!d || *(uint32_t *)(uintptr_t)(it + 0xc) != 3 || *(uint32_t *)(uintptr_t)(it + 8) <= hi) continue; n++; if (o < (int)sizeof ln - 16) o += snprintf(ln + o, sizeof ln - o, " %u:%d", *(uint32_t *)(uintptr_t)(it + 4), *(int32_t *)(uintptr_t)d); } + LOG("[验收轮] 拍 %u 行 %d 之后新掉在地上的物品 %d 件(类号:品质):%s", t, row, n, ln); g_suseq_id = 0; ph = 0; t0 = t; if (++idx == nr) LOG("[验收轮] 拍 %u 全部 %d 行走完", t, nr); } } } + // 测试开关 DM_RIFT_TEST_SCOREAT=<拍>:<分数>:到这一拍把进度分数直接设成这个数(造「闯入首领还活着时进度满了」这类现场) + // Test switch DM_RIFT_TEST_SCOREAT=:: at this tick set the progress score directly to this number (to stage scenes such as "progress fills while an invading boss is still alive") + { static int at = -1, sc; if (at < 0) { const char *e = getenv("DM_RIFT_TEST_SCOREAT"); at = e ? atoi(e) : 0; const char *c = e ? strchr(e, ':') : NULL; sc = c ? atoi(c + 1) : 0; } + if (at > 0 && t >= (uint32_t)at && atomic_load(&K.st) == ST_RUN) { at = 0; atomic_store(&K.score, sc); LOG("秘境:测试 DM_RIFT_TEST_SCOREAT 拍 %u 把进度分数设成 %d", t, sc); } } + // 闯入首领:进度走到抽好的那一点 → 提示(约 3 秒预警)→ 在离人 36 格左右的空地刷出;生命 = 规则应得值 × 0.30;死了 +12% 进度。 + // 同一时刻最多一位;守护者出来之后不再预警 / 不再刷(已在场的那位留着,它与守护者不同类号)。它不是结算条件 + // Invading boss: progress reaches the drawn point -> message (about 3 seconds of warning) -> spawned on open ground about 36 tiles from the player; life = the rule value x 0.30; +12% progress on death. + // At most one at a time; after the Guardians appear there are no more warnings / spawns (one already present stays; it has a different class id from the Guardians). It is not a completion condition + if (K.inv_n && atomic_load(&K.st) == ST_RUN && in_rift_map(lv)) { int nd = atomic_load(&K.need), busy = 0; for (int i = 0; i < K.inv_n; i++) busy |= K.inv_st[i] == 1 || K.inv_st[i] == 2; + for (int i = 0; i < K.inv_n; i++) { + if (K.inv_st[i] == 0 && !busy && !K.guard && nd > 0 && atomic_load(&K.score) * 100 >= (long long)nd * K.inv_pct[i]) { K.inv_st[i] = 1; K.inv_t[i] = t; busy = 1; say("dmRiftSayInvader"); LOG("秘境:拍 %u 闯入首领预警(第 %d 位,类号 %d,进度 %d%%)", t, i + 1, K.inv_cls[i], K.inv_pct[i]); } + else if (K.inv_st[i] == 1 && K.guard) { K.inv_st[i] = 4; LOG("秘境:守护者已现身,第 %d 位闯入首领作罢", i + 1); } + else if (K.inv_st[i] == 1 && t - K.inv_t[i] >= 75) { static const int dx[8] = { 36, 26, 0, -26, -36, -26, 0, 26 }, dy[8] = { 0, 26, 36, 26, 0, -26, -36, -26 }; int x, y; unit_xy(player, &x, &y); uint64_t u = 0; int32_t pos[2] = { 0, 0 }; + for (int k = 0, d0 = rnd(8); k < 8 && !u; k++) { int d = (d0 + k) % 8; pos[0] = x + dx[d]; pos[1] = y + dy[d]; uint64_t rs = room_load(G, level_of(player), pos[0], pos[1]), rr = rs ? free_spot(G, rs, pos) : 0; + if (!rr || abs(pos[0] - x) + abs(pos[1] - y) < 24) continue; /* 找到的空地被挪到人跟前就不要 | open ground that got moved right next to the player is not accepted */ + u = ((uint64_t (*)(uint64_t, uint64_t, int, int, int, int, int, int, uint64_t))(B + 0x7ce630))(G, rr, 1, K.inv_cls[i], pos[0], pos[1], 1, 0, 0x10); } + if (!u) { if (t - K.inv_t[i] > 325) { K.inv_st[i] = 4; LOG("秘境:第 %d 位闯入首领 10 秒内没找到落点,作罢", i + 1); } continue; } + K.inv_id[i] = *(uint32_t *)(uintptr_t)(u + 8); K.inv_st[i] = 2; + if (K.tier >= 9) { g_hp_mul = 300; scale_monster(G, u, target_level(player) + 3, dm_rift_tier_level(9, gs(player, 12)) + 3); g_hp_mul = 1000; } + LOG("秘境:拍 %u 闯入首领刷出(第 %d 位)类号 %d id %u 在 %d,%d(离人 %d 格)等级 %d 生命 %d", t, i + 1, K.inv_cls[i], K.inv_id[i], pos[0], pos[1], abs(pos[0] - x) + abs(pos[1] - y), gs(u, 12), gs(u, 7) >> 8); } + else if (K.inv_st[i] == 2) { uint64_t u = find_unit(G, 1, K.inv_id[i]); uint32_t m = u ? *(uint32_t *)(uintptr_t)(u + 0xc) : 1; + if (u && (m == 0 || m == 12)) { K.inv_st[i] = 3; int add = nd * 12 / (100 + 12 * K.inv_n); if (add < 1) add = 1; int sc = atomic_fetch_add(&K.score, add) + add; /* 12% 按上调前的进度需求算 | 12% is computed on the progress requirement before the increase */ + LOG("秘境:拍 %u 闯入首领死亡(第 %d 位,类号 %d)→ 进度 +%d,现 %d / %d", t, i + 1, K.inv_cls[i], add, sc, nd); } } } } if (!K.guard && atomic_load(&K.score) >= atomic_load(&K.need) && in_rift_map(lv)) { - // 一位:人右下 6 格;两位:一左一右各 6 格。每位先照常按层改(守护者 = 本层怪物等级 + 3,起算层也 + 3,同吃本层总倍率),两位时再各乘 s(生命)与 d(伤害) - // One Guardian: 6 tiles to the lower right of the player; two: 6 tiles to the left and to the right. Each is first scaled by level as usual (Guardian = this level's monster level + 3, the starting level + 3 as well, with this level's total multiplier), and with two each is additionally multiplied by s (life) and d (damage) - static const int ox[2][2] = { { 6, 0 }, { 6, -6 } }, oy[2][2] = { { 6, 0 }, { 6, 6 } }; int x, y, n = 0; unit_xy(player, &x, &y); hs_sync(); - for (int i = 0; i < K.nplan && i < 2; i++) { int32_t pos[2] = { x + ox[K.nplan - 1][i], y + oy[K.nplan - 1][i] }; uint64_t rr = free_spot(G, unit_room(player), pos); - uint64_t u = rr ? ((uint64_t (*)(uint64_t, uint64_t, int, int, int, int, int, int, uint64_t))(B + 0x7ce630))(G, rr, 1, K.gcls[i], pos[0], pos[1], 1, 0, 0x10) : 0; - if (!u) { LOG("【红】秘境:守护者第 %d 位(类号 %d)没刷出来", i + 1, K.gcls[i]); continue; } - K.guards[i] = *(uint32_t *)(uintptr_t)(u + 8); if (!K.guard) K.guard = K.guards[i]; n++; - if (lowhp) ss(u, 6, 256); else if (K.tier >= 9) { g_hp_mul = K.nplan == 2 ? hi_duo_x1000(0) : 1000; scale_monster(G, u, target_level(player) + 3, dm_rift_tier_level(9, gs(player, 12)) + 3); g_hp_mul = 1000; } - if (K.nplan == 2 && !lowhp) ss(u, 25, (int)((100LL + gs(u, 25)) * hi_duo_x1000(1) / 1000 - 100)); // 伤害:属性 25 是「伤害 +N%」,整体乘 d 即 (100 + N) × d − 100 | damage: stat 25 is "damage +N%", so multiplying the whole by d gives (100 + N) x d - 100 - HS.guard_hp += gs(u, 7) >> 8; - LOG("秘境:拍 %u 刷守护者%s 类号 %d id %u 等级 %d 生命 %d 伤害百分比 %d", t, K.nplan == 2 ? (i ? "(第二位)" : "(第一位)") : "", K.gcls[i], K.guards[i], gs(u, 12), gs(u, 7) >> 8, gs(u, 25)); } - if (n) say(K.nplan == 2 && n == 2 ? "dmRiftSayGuardians" : "dmRiftSayGuardian"); } + // 守护者现身:还在场的闯入首领退场——守护者战期间场上只有守护者。原版没有读到能安全移除一个单位的入口,用已验证过的定点传送把它送到这张图的远处(不触发死亡 / 掉落 / 击杀计数), + // 状态记作罢:之后它死不死都不给进度。玩家想要它的进度与掉落,就得在进度满之前解决它 + // Guardians appear: an invading boss still present leaves - during the Guardian fight only the Guardians are on the field. No entry was found in the original for safely removing a unit, so the already-verified fixed-point teleport sends it far away on this map (no death / drop / kill count is triggered), + // and its state is recorded as called off: whether or not it dies afterwards, it gives no progress. A player who wants its progress and drops has to deal with it before progress is full + for (int i = 0; i < K.inv_n; i++) { if (K.inv_st[i] == 1) { K.inv_st[i] = 4; continue; } if (K.inv_st[i] != 2) continue; + static const int fx[8] = { 150, 106, 0, -106, -150, -106, 0, 106 }, fy[8] = { 0, 106, 150, 106, 0, -106, -150, -106 }; uint64_t iu = find_unit(G, 1, K.inv_id[i]); int px, py, moved = 0; unit_xy(player, &px, &py); + for (int k = 0; iu && k < 8 && !moved && !getenv("DM_RIFT_TEST_NOFAR"); k++) { int32_t fp[2] = { px + fx[k], py + fy[k] }; /* 测试开关 DM_RIFT_TEST_NOFAR=1:当作远处没有空地,走兜底 | test switch DM_RIFT_TEST_NOFAR=1: act as if there were no open ground far away, taking the fallback */ uint64_t rs = room_load(G, level_of(player), fp[0], fp[1]), rr = rs ? free_spot(G, rs, fp) : 0; + if (rr && abs(fp[0] - px) + abs(fp[1] - py) >= 100 && dm_teleport(B, G, iu, rr, fp[0], fp[1])) { moved = 1; LOG("秘境:拍 %u 守护者现身,闯入首领(第 %d 位,类号 %d)退场到 %d,%d(离人 %d 格),不再给进度", t, i + 1, K.inv_cls[i], fp[0], fp[1], abs(fp[0] - px) + abs(fp[1] - py)); } } + if (!moved && iu && g_entry_lv == lv) { int32_t fp[2] = { g_entry_x, g_entry_y }; uint64_t rs = room_load(G, level_of(player), fp[0], fp[1]), rr = rs ? free_spot(G, rs, fp) : 0; // 兜底:传到玩家进这张图时的落点(一定可达) | fallback: teleport to the point where the player entered this map (always reachable) + if (rr && dm_teleport(B, G, iu, rr, fp[0], fp[1])) { moved = 1; LOG("秘境:拍 %u 守护者现身,闯入首领(第 %d 位,类号 %d)远处没有空地,退场到本图入口 %d,%d(离人 %d 格)", t, i + 1, K.inv_cls[i], fp[0], fp[1], abs(fp[0] - px) + abs(fp[1] - py)); } } + if (!moved) LOG("【红】秘境:拍 %u 守护者现身,闯入首领(第 %d 位)退场落点与本图入口都没传成,留在场上(作罢,不给进度)", t, i + 1); + g_inv_gone[i] = K.inv_id[i]; if (iu) unit_xy(iu, &g_inv_gone_xy[i][0], &g_inv_gone_xy[i][1]); K.inv_st[i] = 4; K.inv_id[i] = 0; say("dmRiftSayInvaderGone"); } + guard_wave(G, player, t, lowhp); } + // 两波之间:上一波全倒 WAVE_GAP 拍后刷下一波 + // Between two waves: WAVE_GAP ticks after the previous wave is all down, the next wave is spawned + if (K.wave_t && t >= K.wave_t + WAVE_GAP && atomic_load(&K.st) == ST_RUN) { guard_wave(G, player, t, lowhp); K.wave_t = 0; } /* 先刷、再清「两波之间」:顶部条在两波之间报刚打完的那一波,刷出来才跳到下一波 | spawn first, then clear "between two waves": between waves the top bar reports the wave just finished, and moves to the next wave only once it has spawned */ // 测试替身 DM_RIFT_TEST_DUMMY=<每秒点数>:对在场的每位守护者按固定输出扣当前生命(留 1 点,由随从补最后一下)——人物不用真打,用来出「承伤每秒峰值」的相对值 // Test stand-in DM_RIFT_TEST_DUMMY=: deduct current life from every Guardian present at a fixed output (leaving 1 point, with a minion delivering the last hit) - the character does not have to fight for real; used to obtain relative values of the "per-second peak of damage taken" { static int dps = -1; if (dps < 0) { const char *e = getenv("DM_RIFT_TEST_DUMMY"); dps = e ? atoi(e) : 0; } + if (dps > 0) for (int i = 0; i < 2; i++) { uint64_t u = K.inv_st[i] == 2 ? find_unit(G, 1, K.inv_id[i]) : 0; uint32_t m = u ? *(uint32_t *)(uintptr_t)(u + 0xc) : 0; if (!u || m == 0 || m == 12) continue; /* 在场的闯入首领同样按固定输出扣 | an invading boss that is present is deducted at the fixed output as well */ + long long h = (long long)gs(u, 6) - (long long)dps * 256 / 25; ss(u, 6, h < 256 ? 256 : (int)h); } if (dps > 0 && K.guard && !atomic_load(&K.guard_dead)) for (int i = 0; i < 3; i++) { uint64_t u = K.guards[i] ? find_unit(G, 1, K.guards[i]) : 0; uint32_t m = u ? *(uint32_t *)(uintptr_t)(u + 0xc) : 0; if (!u || m == 0 || m == 12) continue; long long h = (long long)gs(u, 6) - (long long)dps * 256 / 25; ss(u, 6, h < 256 ? 256 : (int)h); } } // 结算条件:本场刷出的守护者全部死亡。任一位还活着(或还在单位表里没判死)都不结算、不开门 // Completion condition: all the Guardians spawned in this run are dead. While any one is alive (or still in the unit table and not judged dead) there is no completion and no door - if (K.guard && !atomic_load(&K.guard_dead)) { int alive = 0; uint64_t last = 0; + if (K.guard && !atomic_load(&K.guard_dead)) { int alive = 0, deadn = 0; uint64_t last = 0; for (int i = 0; i < 3; i++) { if (!K.guards[i]) continue; uint64_t u = find_unit(G, 1, K.guards[i]); if (!u) { alive++; continue; } /* 不在单位表里(房间卸载):不当它死了 | not in the unit table (room unloaded): do not treat it as dead */ - uint32_t m = *(uint32_t *)(uintptr_t)(u + 0xc); if (m == 0 || m == 12) { last = u; static uint32_t said[3]; if (said[i] != K.guards[i]) { said[i] = K.guards[i]; LOG("秘境:拍 %u 守护者死亡(类号 %d id %u)", t, K.gcls[i], K.guards[i]); } } else alive++; } - if (!alive && last) { atomic_store(&K.guard_dead, 1); LOG("秘境:拍 %u 守护者全部死亡 → 结算", t); finish(G, player, last); } } + uint32_t m = *(uint32_t *)(uintptr_t)(u + 0xc); if (m == 0 || m == 12) { last = u; deadn++; static uint32_t said[3]; if (said[i] != K.guards[i]) { said[i] = K.guards[i]; LOG("秘境:拍 %u 守护者死亡(类号 %d id %u)", t, K.gcls[i], K.guards[i]); } } else alive++; } + if (!K.wave_t) atomic_store(&K.gdead, deadn); /* 两波之间 guards 已清空,计数留着上一波的(全倒)给顶部条 | between two waves guards is already cleared; the count keeps the previous wave's (all down) for the top bar */ + if (!alive && last && K.wave + 1 < K.nwave) { memset(K.guards, 0, sizeof K.guards); K.wave++; K.wave_t = t; LOG("秘境:拍 %u 守护者第 %d 波全部倒下,%d 拍后刷第 %d 波", t, K.wave, WAVE_GAP, K.wave + 1); } + else if (!alive && last) { atomic_store(&K.guard_dead, 1); LOG("秘境:拍 %u 守护者全部死亡 → 结算", t); finish(G, player, last); } } } diff --git a/dm/host/dm_rift.h b/dm/host/dm_rift.h index 7778874..9914763 100644 --- a/dm/host/dm_rift.h +++ b/dm/host/dm_rift.h @@ -2,7 +2,7 @@ // Rift tower climb (dm_rift.c) #pragma once #include -typedef struct { int tier; float progress; int secs_left, done, guardian, inc, next, overtime; } dm_rift_hud_t; // overtime = 进行中且限时已到(还能打完拿掉落,不计通关);与菜单里的同名量同源;next = 本层完成后下一次打第几层(封顶 100;等于 tier = 不涨:超时,或已在最高层)。显示方只读它,不自己用 tier + inc 算 | overtime = in progress and the time limit has passed (can still be finished for loot, does not count as a clear); the same source as the quantity of the same name in the menu; next = which level will be played after this one is completed (capped at 100; equal to tier = no increase: overtime, or already at the highest level). Display code only reads it and does not compute tier + inc itself +typedef struct { int tier; float progress; int secs_left, done, guardian, inc, next, overtime, goal, gdead, gtotal, wave, nwave; } dm_rift_hud_t; /* goal = 没结算时第二行该写哪一句(宿主定,显示方只照着选串):0 进度目标、1 击败守护者、2 击败守护者(已倒 / 总数)、3 已超时、4 已超时 + 击败守护者、5 已超时 + 击败守护者(已倒 / 总数);gdead / gtotal = 已倒下与本场已刷出的守护者数 | goal = which sentence the second line should show before completion (decided by the host; the display only picks the string accordingly): 0 progress goal, 1 slay the Guardian, 2 slay the Guardians (fallen / total), 3 overtime, 4 overtime + slay the Guardian, 5 overtime + slay the Guardians (fallen / total); gdead / gtotal = Guardians fallen and Guardians spawned this run */ // overtime = 进行中且限时已到(还能打完拿掉落,不计通关);与菜单里的同名量同源;next = 本层完成后下一次打第几层(封顶 100;等于 tier = 不涨:超时,或已在最高层)。显示方只读它,不自己用 tier + inc 算 | overtime = in progress and the time limit has passed (can still be finished for loot, does not count as a clear); the same source as the quantity of the same name in the menu; next = which level will be played after this one is completed (capped at 100; equal to tier = no increase: overtime, or already at the highest level). Display code only reads it and does not compute tier + inc itself void dm_rift_tick(uint64_t G, uint64_t player, uint8_t *main_base); // 服务端拍(diag.c) | Server tick (diag.c) void dm_rift_c2s(uint64_t G, const uint8_t *pkt, uint32_t len); // 客户端命令(点门) | Client command (door tap) void dm_rift_client_pump(uint8_t *main_base); // 取手柄处(dm_world.c):认击杀、新刷出的怪 | At the controller sampling point (dm_world.c): recognize kills and newly spawned monsters diff --git a/dm/host/front_mac.m b/dm/host/front_mac.m index 5ab983e..0b96932 100644 --- a/dm/host/front_mac.m +++ b/dm/host/front_mac.m @@ -8,6 +8,7 @@ #include #import #import +#import #include "dm.h" #include "dm_input.h" #include "dm_uiscreen.h" @@ -23,35 +24,50 @@ static int g_live; // App 形态(或 DM_TOUCH_LIVE=1):鼠标进我们的 static CAMetalLayer *g_layer; static NSWindow *g_win; static NSView *g_view; -// 窗口不是 16:9(拉伸窗口、全屏到 16:10 的屏):游戏画面保持 16:9 居中,四周留黑边;鼠标位置按游戏画面这一块算 -// The window is not 16:9 (stretched window, full screen on a 16:10 display): the game picture stays 16:9 and centred with black bars around it; the mouse position is computed against the game picture +// 真全屏(App 形态,屏幕比 16:9 窄——16:10 的 MacBook,「不能全屏」:全屏后上下各 56 点黑边):照 iPad 那套(front_ios.m、dm_uiscreen.c)—— +// 启动时按屏幕比例(全屏时的内容区:屏幕扣掉刘海安全区)定游戏分辨率,局内 3D 铺满、界面按 16:9 贴底(开大面板居中),前端各页与读取画面游戏自己按 16:9 出、上下留边。 +// 窗口锁成同一比例,窗口态与全屏态都铺满。屏幕不比 16:9 窄(外接 16:9 / 更宽的屏):照旧全程 16:9。比例在启动时按主屏定,之后挪到别的屏不重算(游戏分辨率只在启动时定)。 +// 测试开关 DM_TEST_SCREEN_ASPECT=<宽>x<高>:当作主屏是这个比例(16x9 = 外接 16:9 屏的口径) +// True full screen (App form, screen narrower than 16:9 - a 16:10 MacBook, "cannot go full screen": 56 points of black bar above and below in full screen): the iPad approach (front_ios.m, dm_uiscreen.c) - +// at launch the game resolution is set from the screen's aspect ratio (the full-screen content area: the screen minus the notch safe area); in game the 3D fills the screen, the interface is 16:9 along the bottom (centred with a large panel open), and the front-end pages and the loading screen are drawn by the game at 16:9 with bars above and below. +// The window is locked to the same ratio, so both windowed and full screen are filled. Screens not narrower than 16:9 (external 16:9 / wider screens): 16:9 throughout as before. The ratio is set from the main screen at launch and not recomputed when moved to another screen (the game resolution is only set at launch). +// Test switch DM_TEST_SCREEN_ASPECT=x: treat the main screen as this ratio (16x9 = the external 16:9 screen case) +static double g_aspect = 16.0 / 9; // 游戏画面比例(宽 ÷ 高) | aspect ratio of the game picture (width / height) +static int g_full; // 1 = 真全屏已开 | 1 = true full screen is on +static void full_setup(void) { + if (!getenv("DM_APP") || getenv("DM_GAME_RES")) return; + NSScreen *sc = NSScreen.mainScreen; double w = sc.frame.size.width, h = sc.frame.size.height - sc.safeAreaInsets.top; const char *e = getenv("DM_TEST_SCREEN_ASPECT"); unsigned tw, th; + if (e && sscanf(e, "%ux%u", &tw, &th) == 2 && tw && th) { w = tw; h = th; } + if (h <= 0 || w / h >= 16.0 / 9 - 0.01) { LOG("画面:主屏 %.0fx%.0f 不比 16:9 窄 → 全程 16:9", w, h); return; } + g_aspect = w / h; g_full = 1; dm_uiscreen_enable(DM_UISCREEN_BOTTOM); + LOG("画面:主屏全屏内容区 %.0fx%.0f(比例 %.3f)比 16:9 窄 → 真全屏:窗口锁这个比例,局内铺满、界面贴底,前端 16:9 留边", w, h, g_aspect); +} +// 游戏画面在视图里的位置:按游戏画面比例放进视图(比例对得上就是整个视图;对不上的四周留黑边) +// Where the game picture sits in the view: fitted into the view by the picture's aspect ratio (if the ratios match, the whole view; otherwise black bars around) static NSRect game_rect(void) { NSSize b = g_view.bounds.size; CGFloat w = b.width, h = b.height; - if (w * 9 > h * 16) w = floor(h * 16 / 9); else h = floor(w * 9 / 16); + if (fabs(w / h / g_aspect - 1) < 0.003) { } // 比例差 0.3% 以内(窗口高取整的零头、全屏内容区比按刘海安全区算的少 1 点)当对得上,铺满 | within 0.3% (the remainder from rounding the window height, and the full-screen content area being 1 point less than computed from the notch safe area) counts as matching, and it fills + else if (w > h * g_aspect) w = round(h * g_aspect); else h = round(w / g_aspect); return NSMakeRect(floor((b.width - w) / 2), floor((b.height - h) / 2), w, h); } static void layout_game(void) { NSRect r = game_rect(); if (NSEqualRects(r, g_layer.frame)) return; - [CATransaction begin]; [CATransaction setDisableActions:YES]; g_layer.frame = r; g_layer.contentsScale = g_view.window.backingScaleFactor; [CATransaction commit]; + CGFloat sc = g_view.window.backingScaleFactor ?: 2; // 画布跟着改:作为子层的 CAMetalLayer 改 frame 不会自己改 drawableSize,原先进全屏后一直用窗口态的画布放大显示(发糊) | the canvas follows: a CAMetalLayer used as a sublayer does not change its drawableSize when its frame changes, so after going full screen it used to keep the windowed canvas and scale it up (blurry) + [CATransaction begin]; [CATransaction setDisableActions:YES]; g_layer.frame = r; g_layer.contentsScale = sc; g_layer.drawableSize = CGSizeMake(round(r.size.width * sc), round(r.size.height * sc)); [CATransaction commit]; 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; - 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); + { 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_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); } @@ -112,6 +128,7 @@ void *front_metal_layer(void) { return (__bridge void *)g_layer; } uint64_t front_game_res(int docked) { unsigned w, h; const char *e = getenv("DM_GAME_RES"); if (e && sscanf(e, "%ux%u", &w, &h) == 2) return docked ? (uint64_t)h << 32 | w : (uint64_t)(h * 4 / 5) << 32 | (w * 4 / 5 + 3) / 4 * 4; + if (g_full) return docked ? (uint64_t)(llround(1600 / g_aspect / 2) * 2) << 32 | 1600 : 720ull << 32 | (uint64_t)(llround(720 * g_aspect / 8) * 8); // 真全屏:宽 1600、高按屏幕比例(16:10 → 1600x1004) | true full screen: width 1600, height by the screen's aspect ratio (16:10 -> 1600x1004) return docked ? 900ull << 32 | 1600 : 720ull << 32 | 1280; } @@ -155,14 +172,15 @@ void front_run(void (*guest)(void)) { @autoreleasepool { [NSApplication sharedApplication]; [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; - NSRect r = NSMakeRect(0, 0, 1280, 720); + full_setup(); + NSRect r = NSMakeRect(0, 0, 1280, floor(1280 / g_aspect)); NSWindow *win = [[NSWindow alloc] initWithContentRect:r styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO]; win.title = @"D2R Mobile"; win.restorable = NO; g_win = win; NSView *v = win.contentView; g_view = v; v.wantsLayer = YES; v.layer.backgroundColor = CGColorGetConstantColor(kCGColorBlack); - win.collectionBehavior = NSWindowCollectionBehaviorFullScreenPrimary; win.contentMinSize = NSMakeSize(640, 360); + win.collectionBehavior = NSWindowCollectionBehaviorFullScreenPrimary; win.contentMinSize = NSMakeSize(640, floor(640 / g_aspect)); if (g_full) win.contentAspectRatio = NSMakeSize(1280, 1280 / g_aspect); static DmWinCtl *ctl; ctl = [DmWinCtl new]; win.delegate = ctl; g_layer = [CAMetalLayer layer]; g_layer.device = MTLCreateSystemDefaultDevice(); @@ -196,6 +214,18 @@ void front_run(void (*guest)(void)) { if (gr.size.width <= 0 || gr.size.height <= 0) return e; float nx = (float)((p.x - gr.origin.x) / gr.size.width), ny = (float)(1.0 - (p.y - gr.origin.y) / gr.size.height); // AppKit 视图原点在左下,触屏原点在左上 | The AppKit view origin is at bottom left, the touchscreen origin is at top left if (e.type == NSEventTypeLeftMouseDown && (nx < 0 || nx > 1 || ny < 0 || ny > 1)) return nil; // 按在黑边上:不算点 | Pressed on the black bars: not a click + if (g_full && g_live) { // 真全屏:状态机吃界面矩形里的归一化坐标(同 iOS 的游戏视图)。两步: | true full screen: the state machine takes normalised coordinates inside the interface rectangle (like the iOS game view). Two steps: + // ① 先换到「实际显示的那块」:游戏当前分辨率(前端 16:9、局内整屏)按比例居中放进游戏画面,与上屏同一口径(nvn_mtl.m present_encode:比例差 1% 内铺满); + // ② 再换到界面矩形(局内贴底)。局内界面矩形外是 3D 世界,带符号交下去(点世界换回整屏,touch_mac.c);不在局内时显示块外是黑边,不算点 + // (1) First map to "the block actually shown": the game's current resolution (16:9 in the front end, the whole screen in game) placed centred in the game picture by aspect ratio, the same measure as presentation (nvn_mtl.m present_encode: fill when the aspect ratios differ by less than 1%); + // (2) then map to the interface rectangle (along the bottom in game). In game, outside the interface rectangle is the 3D world, passed down with a sign (tapping the world maps back to the whole screen, touch_mac.c); outside the game the area beyond the shown block is the black bars, not counted as a tap + int rw = 0, rh = 0; double cx = 0, cy = 0, cw = 1, ch = 1; + if (dm_screen_real(&rw, &rh) && rw > 0 && rh > 0) { double ca = (double)rw / rh, ga = gr.size.width / gr.size.height; + if (fabs(ga / ca - 1) >= 0.01) { if (ga > ca) { cw = ca / ga; cx = (1 - cw) / 2; } else { ch = ga / ca; cy = (1 - ch) / 2; } } } + float vx = (float)((nx - cx) / cw), vy = (float)((ny - cy) / ch); + double fy = 0, fh = 1; ui_rect_frac(&fy, &fh); float uy = fh > 0 ? (float)((vy - fy) / fh) : vy; + if (e.type == NSEventTypeLeftMouseDown && !dm_uiscreen_ingame() && (vx < 0 || vx > 1 || uy < 0 || uy > 1)) return nil; + dm_touch_host_live(e.type == NSEventTypeLeftMouseDown ? 0 : 1, vx, uy); return nil; } dm_touch t = {0, nx < 0 ? 0 : nx > 1 ? 1 : nx, ny < 0 ? 0 : ny > 1 ? 1 : ny}; if (g_live) { dm_touch_host_live(e.type == NSEventTypeLeftMouseDown ? 0 : 1, t.x, t.y); return nil; } dm_touch_set(&t, 1); return nil; @@ -218,7 +248,22 @@ void front_run(void (*guest)(void)) { if (getenv("DM_APP") && !getenv("DM_APP_ROMFS") && ![NSUserDefaults.standardUserDefaults boolForKey:@"KeysShown"]) { show_keys(); [NSUserDefaults.standardUserDefaults setBool:YES forKey:@"KeysShown"]; } // 第一次启动给一次键位对照(界面上的按键提示是手柄字母);以后在「帮助」菜单里 | Show the key mapping once on first launch (button prompts on screen are gamepad letters); afterwards it is in the Help menu { const char *e; // 测试(没人点窗口时用):DM_TEST_WINSIZE=宽x高 设内容区大小;DM_TEST_FULLSCREEN_AT=<秒> 进全屏;DM_TEST_QUIT_AT=<秒> 走一次退出 | Tests (for when nobody is there to click the window): DM_TEST_WINSIZE=WxH sets the content size; DM_TEST_FULLSCREEN_AT= enters full screen; DM_TEST_QUIT_AT= goes through one quit int w, h; if ((e = getenv("DM_TEST_WINSIZE")) && sscanf(e, "%dx%d", &w, &h) == 2) { [win setContentSize:NSMakeSize(w, h)]; layout_game(); } - if ((e = getenv("DM_TEST_FULLSCREEN_AT"))) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(atof(e) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [win toggleFullScreen:nil]; }); + if ((e = getenv("DM_TEST_FULLSCREEN_AT"))) for (const char *q = e; q && *q; q = strchr(q, ';') ? strchr(q, ';') + 1 : NULL) // 「秒[;秒…]」:每个时刻切一次全屏(来回切) | "seconds[;seconds...]": toggle full screen at each time (back and forth) + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(atof(q) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [win toggleFullScreen:nil]; }); + // DM_TEST_PRESENT_SHOT=<秒>:<路径>[;<秒>:<路径>…]:到点取下一次上屏的画面(图形层与上屏同一套编码,见 nvn_mtl.m mtl_grab_next_present)写成 PNG—— + // 看的是玩家真看到的(含留边位置),不是游戏出图贴图(DM_NVN_SHOT_UI 取的那张,裁切区不居中) + // DM_TEST_PRESENT_SHOT=:[;:...]: at the given time, grab the next presented picture (the graphics layer uses the same encoding as presentation, see nvn_mtl.m mtl_grab_next_present) and write it as PNG - + // this is what the player actually sees (including where the bars are), not the game's output texture (the one DM_NVN_SHOT_UI takes, whose crop is not centred) + if ((e = getenv("DM_TEST_PRESENT_SHOT"))) { void mtl_grab_next_present(void (^cb)(CGImageRef img)); + for (NSString *it in [@(e) componentsSeparatedByString:@";"]) { NSRange c = [it rangeOfString:@":"]; if (c.location == NSNotFound) continue; + double at = [it substringToIndex:c.location].doubleValue; NSString *path = [it substringFromIndex:c.location + 1]; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(at * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + NSSize vb = v.bounds.size; NSRect gr = game_rect(); double fy = 0, fh = 1; ui_rect_frac(&fy, &fh); + mtl_grab_next_present(^(CGImageRef img) { if (!img) { LOG("【红】DM_TEST_PRESENT_SHOT:%s 没取到", path.UTF8String); return; } + CGImageDestinationRef d = CGImageDestinationCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:path], (__bridge CFStringRef)@"public.png", 1, NULL); + if (d) { CGImageDestinationAddImage(d, img, NULL); CGImageDestinationFinalize(d); CFRelease(d); } + LOG("DM_TEST_PRESENT_SHOT:%s %zux%zu(内容区 %.0fx%.0f,游戏画面 %.0fx%.0f 在 (%.0f,%.0f),界面矩形纵向 %.3f 高 %.3f,%s)", path.UTF8String, CGImageGetWidth(img), CGImageGetHeight(img), + vb.width, vb.height, gr.size.width, gr.size.height, gr.origin.x, gr.origin.y, fy, fh, dm_uiscreen_ingame() ? "局内" : "局外"); }); }); } } // DM_TEST_NSMOUSE=<文件>:合成真正的系统鼠标事件(NSEvent)投进 App 的事件队列,走与真人点击同一条分发路(事件监视器 → 换算 → 状态机),不经测试入口。 // 每行「秒 down|move|up x,y」,x,y 是内容区里的点(左上角为原点;窗口缺省 1280×720),时刻自窗口建好起算 // DM_TEST_NSMOUSE=: synthesise real system mouse events (NSEvent) and post them to the App's event queue, going through the same dispatch path as a person clicking (event monitor -> conversion -> state machine), not through the test entry. diff --git a/dm/host/hle_audio.c b/dm/host/hle_audio.c index d7616d5..40a0dec 100644 --- a/dm/host/hle_audio.c +++ b/dm/host/hle_audio.c @@ -1,11 +1,15 @@ // nn::audio AudioOut:游戏(FMOD nx 输出层)按块追加 PCM 缓冲,播完由系统放回「已释放」队列并触发事件。 // 宿主:真出声 = CoreAudio AudioUnit(Mac DefaultOutput / iOS RemoteIO);静音接收端 = 按真实时间消耗缓冲(不出声,节奏与真机一致)。 -// iOS 缺省真出声(产品必须有声音),测试要静音显式 DM_AUDIO=0;Mac 缺省静音接收端(回放 / 闸门不出声),DM_AUDIO=1 真出声。 +// iOS 缺省真出声(产品必须有声音),测试要静音显式 DM_AUDIO=0;Mac 命令行宿主缺省静音接收端(回放 / 闸门不出声),DM_AUDIO=1 真出声; +// Mac App(app_mac.m)是产品,启动时设 DM_AUDIO=1(「没有声音」:之前 App 也走了命令行的缺省,从来不出声)。 +// 声卡打不开(没有输出设备等)不再退出:记红,这一路改由静音接收端按实时消耗,游戏照常跑。 // AudioOut / AudioOutBuffer / AudioOutParameter 的内容只经下列接口读写,宿主自定内部布局,只写结构体前部。 -// nn::audio AudioOut: the game (FMOD nx output layer) appends PCM buffers block by block; once played the system puts them back on the "released" queue and signals the event. -// Host: real audio output = CoreAudio AudioUnit (Mac DefaultOutput / iOS RemoteIO); silent sink = consumes buffers in real time (no sound, pacing matches the real device). -// iOS defaults to real audio output (the product must have sound), tests that want silence set DM_AUDIO=0 explicitly; Mac defaults to the silent sink (replay / gate checks are silent), DM_AUDIO=1 for real audio output. -// The contents of AudioOut / AudioOutBuffer / AudioOutParameter are read and written only through the interfaces below; the host defines its own internal layout and only writes the front part of the structs. +// nn::audio AudioOut: the game (FMOD's nx output layer) appends PCM buffers in blocks; once played the system puts them back on the "released" queue and signals an event. +// Host: real sound = CoreAudio AudioUnit (Mac DefaultOutput / iOS RemoteIO); silent sink = buffers consumed in real time (no sound, same pacing as the device). +// iOS plays real sound by default (the product must have sound), tests set DM_AUDIO=0 explicitly for silence; the Mac command-line host defaults to the silent sink (replays / gates are silent), DM_AUDIO=1 for real sound; +// the Mac App (app_mac.m) is the product and sets DM_AUDIO=1 at launch ("no sound": the App used to take the command-line default and never played sound). +// If the sound card cannot be opened (no output device etc.) it no longer exits: logs red, and this channel is consumed in real time by the silent sink while the game runs on. +// The contents of AudioOut / AudioOutBuffer / AudioOutParameter are read and written only through the interfaces below; the host defines its own internal layout and writes only the front part of each struct. #include "hle.h" #if defined(__APPLE__) #include @@ -50,9 +54,11 @@ typedef struct { AudioUnit au; #if defined(__ANDROID__) int out_ch; // 流的声道数:设备收原声道数就等于 ch,否则 2(回调里自己下混) | the stream's channel count: equal to ch when the device takes the original count, otherwise 2 (downmixed in the callback) - int16_t *mix; // 下混用的暂存(ch 声道) | scratch for downmixing (ch channels) _Atomic int lost; // 设备断开(换耳机 / 蓝牙):等普通线程重开 | device disconnected (headphones / Bluetooth switch): waiting for an ordinary thread to reopen +#else + int mix; // 1 = 游戏给 5.1(6 声道),交给 CoreAudio 前我们自己下混成双声道(au_render) | 1 = the game gives 5.1 (6 channels), downmixed to stereo by us before handing to CoreAudio (au_render) #endif + int16_t *mixbuf; // 下混用的暂存(ch 声道) | staging for the downmix (ch channels) pthread_t null_th; _Atomic int null_run; dispatch_semaphore_t notify_sem; pthread_t notify_th; _Atomic int notify_run, notify_pending, notify_armed; @@ -116,14 +122,39 @@ static void pull(aout *a, uint8_t *dst, uint64_t n) { static _Atomic uint64_t g_render_calls; // 声卡回调累计(生命周期验证:恢复后须继续增长) | Cumulative sound card callbacks (lifecycle verification: must keep growing after resume) uint64_t dm_audio_render_calls(void) { return atomic_load_explicit(&g_render_calls, memory_order_relaxed); } #if defined(__APPLE__) +// 5.1 → 双声道(公开 的:原先把游戏的 6 声道原样交给 AudioUnit、不设声道布局,系统隐式转换只取前两路,中置——NPC 对白——整路丢掉)。 +// 游戏的声道顺序(Mac App 走到阿卡拉跟前、对白开口那半秒按声道量能量实测:只有第 3 路跳起来):左前、右前、中置、低音、左后、右后。 +// 系数照 ITU-R BS.775 的 Lo/Ro:L = 左前 + 0.707·中置 + 0.707·左后,R 对称;低音不并入(标准下混不含 LFE,并进去会让低频发闷); +// 整体再乘 0.707 留 3 dB 余量,仍超出 16 位的饱和截断。Q15 定点:0.707 = 23170,0.707 × 0.707 = 16384 +// 5.1 -> stereo (previously: the game's 6 channels were handed to the AudioUnit as is without a channel layout; the system's implicit conversion took only the first two, and the centre - NPC dialogue - was dropped entirely). +// The game's channel order (measured in the Mac App by per-channel energy during the half second Akara starts speaking: only channel 3 jumps): front left, front right, centre, LFE, rear left, rear right. +// Coefficients from the ITU-R BS.775 Lo/Ro downmix: L = front left + 0.707*centre + 0.707*rear left, R symmetric; LFE is not mixed in (the standard downmix excludes LFE, and mixing it in muddies the low end); +// the whole is multiplied by 0.707 again for 3 dB of headroom, and anything still beyond 16 bits is saturated. Q15 fixed point: 0.707 = 23170, 0.707 x 0.707 = 16384 +#define MIXMAX 4096 +static void downmix51(const int16_t *in, int16_t *out, unsigned frames) { + for (unsigned i = 0; i < frames; i++, in += 6, out += 2) { + int32_t l = (23170 * in[0] + 16384 * in[2] + 16384 * in[4]) >> 15, r = (23170 * in[1] + 16384 * in[2] + 16384 * in[5]) >> 15; + out[0] = (int16_t)(l > 32767 ? 32767 : l < -32768 ? -32768 : l); out[1] = (int16_t)(r > 32767 ? 32767 : r < -32768 ? -32768 : r); } +} static OSStatus au_render(void *ctx, AudioUnitRenderActionFlags *f, const AudioTimeStamp *ts, UInt32 bus, UInt32 frames, AudioBufferList *bl) { (void)f; (void)ts; (void)bus; (void)frames; aout *a = ctx; atomic_fetch_add_explicit(&g_render_calls, 1, memory_order_relaxed); - pull(a, bl->mBuffers[0].mData, bl->mBuffers[0].mDataByteSize); + if (!a->mix) pull(a, bl->mBuffers[0].mData, bl->mBuffers[0].mDataByteSize); + else { int16_t *o = bl->mBuffers[0].mData; unsigned left = bl->mBuffers[0].mDataByteSize / 4; // 双声道 16 位:每帧 4 字节 | stereo 16-bit: 4 bytes per frame + while (left) { unsigned k = left < MIXMAX ? left : MIXMAX; pull(a, (uint8_t *)a->mixbuf, (uint64_t)k * 12); downmix51(a->mixbuf, o, k); o += 2 * k; left -= k; } } + // 诊断开关 DM_AUDIO_OUT_DUMP=<文件>:交给 CoreAudio 的那份数据原样续写(下混后是双声道)。本机没有回环设备录不到系统输出,判「对白有没有交出去」看这份 + // Diagnostic switch DM_AUDIO_OUT_DUMP=: append the data handed to CoreAudio as is (stereo after the downmix). This machine has no loopback device and cannot record the system output; to tell whether the dialogue was handed over, look at this file + { static FILE *df; static int on = -1; if (on < 0) { const char *e = getenv("DM_AUDIO_OUT_DUMP"); on = e != NULL; if (on && !(df = fopen(e, "wb"))) LOG("【红】DM_AUDIO_OUT_DUMP 打不开 %s", e); } + if (df) fwrite(bl->mBuffers[0].mData, 1, bl->mBuffers[0].mDataByteSize, df); } return noErr; } -static void au_open(aout *a) { +#if !TARGET_OS_IPHONE +static void dev_name(AudioObjectID id, char *o, size_t n) { // 输出设备名(日志用) | output device name (for the log) + CFStringRef nm = NULL; UInt32 sz = sizeof nm; AudioObjectPropertyAddress pa = { kAudioObjectPropertyName, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain }; + o[0] = 0; if (!AudioObjectGetPropertyData(id, &pa, 0, NULL, &sz, &nm) && nm) { CFStringGetCString(nm, o, (CFIndex)n, kCFStringEncodingUTF8); CFRelease(nm); } } +#endif +static int au_open(aout *a) { // 0 = 声卡开好了;-1 = 开不了(a->au 置空,调用方走静音接收端) | 0 = the sound card is open; -1 = it cannot be opened (a->au set to null, the caller uses the silent sink) AudioComponentDescription d = {.componentType = kAudioUnitType_Output, #if TARGET_OS_IPHONE .componentSubType = kAudioUnitSubType_RemoteIO, @@ -132,15 +163,28 @@ static void au_open(aout *a) { #endif .componentManufacturer = kAudioUnitManufacturer_Apple}; AudioComponent c = AudioComponentFindNext(NULL, &d); - if (!c || AudioComponentInstanceNew(c, &a->au)) die("AudioUnit 建不出来"); + if (!c || AudioComponentInstanceNew(c, &a->au)) { a->au = NULL; LOG("【红】AudioUnit 建不出来:这一路改用静音接收端(不出声)"); return -1; } + a->mix = a->ch == 6; if (a->mix && !a->mixbuf) a->mixbuf = malloc(MIXMAX * 12); // 5.1:我们自己下混,AudioUnit 只收双声道(单 / 双声道照旧原样交) | 5.1: we downmix ourselves and the AudioUnit only takes stereo (mono / stereo are passed through as before) + if (a->mix && !a->mixbuf) { AudioComponentInstanceDispose(a->au); a->au = NULL; LOG("【红】下混暂存申请不到:这一路改用静音接收端(不出声)"); return -1; } + int och = a->mix ? 2 : a->ch; AudioStreamBasicDescription f = {.mSampleRate = RATE, .mFormatID = kAudioFormatLinearPCM, .mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked, - .mBytesPerPacket = 2u * a->ch, .mFramesPerPacket = 1, .mBytesPerFrame = 2u * a->ch, - .mChannelsPerFrame = (UInt32)a->ch, .mBitsPerChannel = 16}; + .mBytesPerPacket = 2u * och, .mFramesPerPacket = 1, .mBytesPerFrame = 2u * och, + .mChannelsPerFrame = (UInt32)och, .mBitsPerChannel = 16}; + if (a->mix) LOG("audio:游戏给 6 声道(5.1)→ 交给声卡前自己下混成双声道(中置 / 后环绕 ×0.707 并入左右,低音不并入,整体 −3 dB、饱和截断)"); AURenderCallbackStruct cb = {au_render, a}; if (AudioUnitSetProperty(a->au, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &f, sizeof f) || AudioUnitSetProperty(a->au, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &cb, sizeof cb) || - AudioUnitInitialize(a->au)) die("AudioUnit 设置失败"); + AudioUnitInitialize(a->au)) { AudioComponentInstanceDispose(a->au); a->au = NULL; LOG("【红】AudioUnit 设置失败(没有输出设备?):这一路改用静音接收端(不出声)"); return -1; } +#if !TARGET_OS_IPHONE + { // 缺省输出单元跟随系统缺省输出设备:两个都记下来,核「声音从系统选的那个设备出」 | the default output unit follows the system default output device: record both, to check that "the sound comes out of the device the system chose" + AudioObjectID cur = 0, def = 0; UInt32 sz = sizeof cur; char cn[128], dn[128]; + AudioUnitGetProperty(a->au, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &cur, &sz); + AudioObjectPropertyAddress pa = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain }; sz = sizeof def; + AudioObjectGetPropertyData(kAudioObjectSystemObject, &pa, 0, NULL, &sz, &def); dev_name(cur, cn, sizeof cn); dev_name(def, dn, sizeof dn); + LOG("audio:输出设备「%s」(%u),系统缺省输出「%s」(%u)%s", cn, (unsigned)cur, dn, (unsigned)def, cur == def ? ",一致" : "【红】不一致"); } +#endif + return 0; } #elif defined(__ANDROID__) // AAudio:48 kHz PCM16,先按游戏的声道数(常见 6)开;设备不收就开双声道,回调里按 ITU 系数把 5.1 下混成立体声 @@ -161,7 +205,7 @@ static aaudio_data_callback_result_t au_render(AAudioStream *st, void *ctx, void if (a->out_ch == a->ch) { pull(a, data, (uint64_t)frames * 2 * a->ch); return AAUDIO_CALLBACK_RESULT_CONTINUE; } int16_t *out = data; while (frames > 0) { int n = frames < MIX_FRAMES ? frames : MIX_FRAMES; - pull(a, (uint8_t *)a->mix, (uint64_t)n * 2 * a->ch); downmix(a->mix, out, n, a->ch); + pull(a, (uint8_t *)a->mixbuf, (uint64_t)n * 2 * a->ch); downmix(a->mixbuf, out, n, a->ch); out += n * 2; frames -= n; } return AAUDIO_CALLBACK_RESULT_CONTINUE; } @@ -197,7 +241,7 @@ static int au_try_open(aout *a) { if (a->ch != 2 && (a->au = au_stream(a, 2, lat))) { a->out_ch = 2; break; } } if (!a->au) return 0; - if (a->out_ch != a->ch && !a->mix) a->mix = malloc((size_t)MIX_FRAMES * 2 * a->ch); + if (a->out_ch != a->ch && !a->mixbuf) a->mixbuf = malloc((size_t)MIX_FRAMES * 2 * a->ch); int burst = AAudioStream_getFramesPerBurst(a->au); if (burst > 0) AAudioStream_setBufferSizeInFrames(a->au, burst * 4); // 4 个突发 ≈ 几毫秒:游戏自己有 FMOD 缓冲,这里少留防爆音 | 4 bursts ≈ a few ms: the game has its own FMOD buffering, keep a little here against crackles LOG("AAudio 打开:48 kHz PCM16 声道 %d(游戏 %d%s)突发 %d 帧 性能模式 %d", a->out_ch, a->ch, a->out_ch != a->ch ? ",下混" : "", burst, AAudioStream_getPerformanceMode(a->au)); @@ -281,15 +325,15 @@ HLE_FORCE("_ZN2nn5audio12OpenAudioOutEPNS0_8AudioOutEPNS_2os11SystemEventEPKcRKN g_aos[slot] = a; pthread_mutex_unlock(&g_aos_lock); LOG("audio::OpenAudioOut %s 声道 %d %s", name ? name : "(默认)", ch, real_audio() ? "真出声" : "静音接收端"); - if (real_audio()) au_open(a); + if (real_audio()) au_open(a); // 开不了就 a->au 为空,开始播放时走静音接收端 | if it cannot be opened, a->au is null, and playback goes to the silent sink when it starts return RES_OK; } HLE_FORCE("_ZN2nn5audio13StartAudioOutEPNS0_8AudioOutE", "开始播放", Result, h_au_Start, void *g) { aout *a = ao(g); pthread_mutex_lock(&a->m); int was = atomic_load_explicit(&a->state, memory_order_relaxed); atomic_store_explicit(&a->state, STATE_STARTED, memory_order_release); pthread_mutex_unlock(&a->m); if (was == STATE_STARTED) return RES_OK; - if (a->au && !g_suspended) { if (AudioOutputUnitStart(a->au)) die("AudioUnit 启动失败"); } - else { atomic_store_explicit(&a->null_run, 1, memory_order_release); pthread_create(&a->null_th, NULL, null_sink, a); } + if (a->au && !g_suspended && AudioOutputUnitStart(a->au)) { LOG("【红】AudioUnit 启动失败:这一路改用静音接收端(不出声)"); AudioUnitUninitialize(a->au); AudioComponentInstanceDispose(a->au); a->au = NULL; } + if (!a->au || g_suspended) { atomic_store_explicit(&a->null_run, 1, memory_order_release); pthread_create(&a->null_th, NULL, null_sink, a); } return RES_OK; } HLE_FORCE("_ZN2nn5audio12StopAudioOutEPNS0_8AudioOutE", "停止播放", void, h_au_Stop, void *g) { @@ -310,11 +354,8 @@ HLE_FORCE("_ZN2nn5audio13CloseAudioOutEPNS0_8AudioOutE", "关闭音频输出", v for (int i = 0; i < AOMAX; i++) if (g_aos[i] == a) g_aos[i] = NULL; pthread_mutex_unlock(&g_aos_lock); if (a->au) { AudioUnitUninitialize(a->au); AudioComponentInstanceDispose(a->au); } -#if defined(__ANDROID__) - free(a->mix); -#endif dispatch_release(a->notify_sem); - pthread_mutex_destroy(&a->m); free(a); + free(a->mixbuf); pthread_mutex_destroy(&a->m); free(a); } HLE_FORCE("_ZN2nn5audio16GetAudioOutStateEPKNS0_8AudioOutE", "播放状态", int, h_au_State, const void *g) { return atomic_load_explicit(&ao(g)->state, memory_order_acquire); } HLE_FORCE("_ZN2nn5audio21GetAudioOutSampleRateEPKNS0_8AudioOutE", "采样率", int, h_au_Rate, const void *g) { (void)ao(g); return RATE; } diff --git a/dm/host/hle_fs.c b/dm/host/hle_fs.c index 08e1774..379ebd0 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); } @@ -248,6 +268,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 ---------- @@ -424,9 +447,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; } @@ -535,6 +567,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) { @@ -560,6 +593,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; @@ -581,16 +615,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]; } @@ -598,7 +635,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); @@ -607,7 +644,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; } @@ -630,7 +667,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) { @@ -687,6 +727,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))) { @@ -703,5 +744,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/Makefile b/dm/host/tests/Makefile index 62380a0..b698d7f 100644 --- a/dm/host/tests/Makefile +++ b/dm/host/tests/Makefile @@ -104,11 +104,11 @@ $(B)/t_touch: t_touch.c ../hle_touch.c ../front.h ../dm.h | $(B) $(B)/t_fs: t_fs.c t_fs_stub.c ../hle_fs.c ../hle.h ../dm.h ../dm_i18n.c | $(B) clang -O1 -Wno-unused-function -I.. -o $@ t_fs.c t_fs_stub.c ../dm_i18n.c $(B)/t_audio: t_audio.c ../hle_audio.c ../hle.h ../dm.h | $(B) - clang -O1 -Wno-unused-function -I.. -o $@ t_audio.c -framework AudioToolbox + clang -O1 -Wno-unused-function -I.. -o $@ t_audio.c -framework AudioToolbox -framework CoreAudio -framework CoreFoundation $(B)/t_audio_spsc: t_audio_spsc.c ../hle_audio.c ../hle.h ../dm.h | $(B) - clang -O1 -Wno-unused-function -I.. -o $@ t_audio_spsc.c -framework AudioToolbox + clang -O1 -Wno-unused-function -I.. -o $@ t_audio_spsc.c -framework AudioToolbox -framework CoreAudio -framework CoreFoundation $(B)/t_audio_spsc_tsan: t_audio_spsc.c ../hle_audio.c ../hle.h ../dm.h | $(B) - clang -O1 -g -O1 -fsanitize=thread -Wno-unused-function -I.. -o $@ t_audio_spsc.c -framework AudioToolbox + clang -O1 -g -O1 -fsanitize=thread -Wno-unused-function -I.. -o $@ t_audio_spsc.c -framework AudioToolbox -framework CoreAudio -framework CoreFoundation $(B)/t_swkbd: t_swkbd.c ../hle_swkbd.c ../hle.h ../dm.h | $(B) clang -O1 -Wno-unused-function -I.. -o $@ t_swkbd.c ../hle_swkbd.c $(B)/t_movie: t_movie.c ../hle_movie.c ../hle.h ../dm.h | $(B) diff --git a/dm/host/tests/native_write_scan.py b/dm/host/tests/native_write_scan.py index 0f3eb62..a13bc96 100644 --- a/dm/host/tests/native_write_scan.py +++ b/dm/host/tests/native_write_scan.py @@ -41,18 +41,32 @@ def vis_scan(text, where): # 直接写可见位的行;在带守卫的函数 # Third check (position guard): in dm_cursor.c, writing a widget rectangle (+0x70 x, +0x74 y, +0x78 width, +0x7c height) is allowed only in mv_offset (original-game widgets, allow list + record original value + must write back) # and in ui_move_ours (only names starting with Touch). Two forms are recognized: a direct *(int32_t *)(... + 0x7?) = ...; or, within the same function, first taking int32_t *name = (int32_t *)(... + 0x7?) and then writing name[k] = / *name = RECT_OK = ('mv_offset', 'ui_move_ours') -RECT_PTR = re.compile(r'int32_t\s*\*\s*(\w+)\s*=\s*\(int32_t\s*\*\)\s*\([^;]*\+\s*0x7[0-9a-c]\b') -RECT_DIRECT = re.compile(r'\*\s*\(int32_t\s*\*\)\s*\([^)]*\+\s*0x7[0-9a-c]\)\s*=(?!=)') -def rect_scan(text, where): +RECT_OFFS = ['0x7%x' % i for i in range(13)] # 0x70–0x7c +# 原版控件字段写入的登记例外(一项一行:文件、字段、只许在哪些函数里写、理由)。名单外的函数写这些字段一律报红 +# Registered exceptions for writes to original widget fields (one per line: file, field, which functions may write it, reason). Writes to these fields from functions not on the list are always red +NATIVE_FIELD_OK = { + ('dm_cursor.c', '0x19c'): (('ui_note_dock_pump', 'note_dock_restore'), 'NotificationPanel 停靠目标 y:原版只在重排时按布局抄进、滑入滑出按它插值写 +0x74;' + '改 +0x74 会被动画每帧盖回(试过)。原值我们自己记、停靠条件一结束当场写回(面板关 / 读取画面 / 保存并退出 / 回到前端)'), + ('dm_cursor.c', '0x74'): (('note_dock_snap',), 'NotificationPanel 矩形 y:停靠目标切换(开 / 关面板)那一刻框已停稳(原版停稳不写坐标)才写成新目标一次,动画期不写;写后下一帧核'), +} +def field_write_scan(text, where, off, ok, what): + ptr = re.compile(r'(?:int32_t|,)\s*\*\s*(\w+)\s*=\s*\(int32_t\s*\*\)\s*\([^;)]*\+\s*%s' % off) # 基址只看本括号:同一行别的变量读别的字段不算;逗号后的第二个声明也认 | the base only counts within its own parentheses: other variables on the same line reading other fields do not count; a second declaration after a comma is recognised too + direct = re.compile(r'\*\s*\(int32_t\s*\*\)\s*\([^)]*\+\s*%s\)\s*=(?!=)' % off) bad, fn, ptrs = [], None, set() for no, line in enumerate(text.split('\n'), 1): m = re.match(r'(?:static\s+)?\w+\s+\*?(\w+)\(', line) if m and not line.startswith(' '): fn, ptrs = m.group(1), set() code = line.split('//', 1)[0] - for pm in RECT_PTR.finditer(code): ptrs.add(pm.group(1)) - code = RECT_PTR.sub('', code) # 声明那一处(int32_t *名 = …)本身不算写 | the declaration itself (int32_t *name = ...) does not count as a write - hit = RECT_DIRECT.search(code) or any(re.search(r'(?])(?:\*\s*%s|%s\s*\[\s*\d\s*\])\s*=(?!=)' % (q, q), code) for q in ptrs) - if hit and fn not in RECT_OK: bad.append('%s:%d 在 %s 里直接写了控件矩形(原版控件走 mv_offset、我们的走 ui_move_ours):%s' % (where, no, fn, line.strip()[:120])) + for pm in ptr.finditer(code): ptrs.add(pm.group(1)) + code = ptr.sub('', code) # 声明那一处(int32_t *名 = …)本身不算写 | the declaration itself (int32_t *name = ...) does not count as a write + hit = direct.search(code) or any(re.search(r'(?])(?:\*\s*%s|%s\s*\[\s*\d\s*\])\s*=(?!=)' % (q, q), code) for q in ptrs) + if hit and fn not in ok: bad.append('%s:%d 在 %s 里直接写了%s:%s' % (where, no, fn, what, line.strip()[:120])) + return bad +def rect_scan(text, where): + exc = [off for (f, off) in NATIVE_FIELD_OK if where.startswith(f) and off in RECT_OFFS] # 矩形字段的登记例外:从矩形扫描里拿出来,按例外单独扫 | registered exceptions for rectangle fields: taken out of the rectangle scan and scanned separately as exceptions + bad = field_write_scan(text, where, '(?:%s)\\b' % '|'.join(o for o in RECT_OFFS if o not in exc), RECT_OK, '控件矩形(原版控件走 mv_offset、我们的走 ui_move_ours)') + for (f, off), (fns, why) in NATIVE_FIELD_OK.items(): + if where.startswith(f): bad += field_write_scan(text, where, re.escape(off) + r'\b', fns + (RECT_OK if off in RECT_OFFS else ()), '原版控件字段 +%s(登记例外只许在 %s 里写)' % (off, ' / '.join(fns))) return bad def pages_pump(src): @@ -66,6 +80,9 @@ def main(): if not scan(' vu_show(vu_find(bk, "grid", 2), 0);', 'selftest') or scan(' vu_show(vu_find(vt, "TouchV_Back", 0), 1); // "grid" 只在注释里', 'selftest') \ or not vis_scan('static void f(uint64_t w) {\n *(uint8_t *)(w + 0x50) = 0;\n}', 'selftest') or vis_scan('static void ui_show_ours(uint64_t w, int on) {\n *(uint8_t *)(w + 0x50) = 1;\n}\n if (*(uint8_t *)(w + 0x50) == 1) x();', 'selftest') \ or not rect_scan('static void f(uint64_t w) {\n int32_t *r = (int32_t *)(w + 0x70); r[0] = 5;\n}', 'selftest') or not rect_scan('static void g(uint64_t w) {\n *(int32_t *)(w + 0x74) = 3;\n}', 'selftest') \ + or rect_scan('static void ui_note_dock_pump(uint64_t w) {\n int32_t *t = (int32_t *)(w + 0x19c), h = *(int32_t *)(w + 0x7c); *t = h;\n}', 'dm_cursor.c') \ + or not rect_scan('static void n(uint64_t w) {\n int32_t *t = (int32_t *)(w + 0x19c); *t = 1;\n}', 'dm_cursor.c') \ + or not rect_scan('static void n2(uint64_t w) {\n int32_t *t = (int32_t *)(w + 0x19c), *ry = (int32_t *)(w + 0x74); *ry = 1;\n}', 'dm_cursor.c') \ or rect_scan('static void k(uint64_t w) {\n int32_t *rx = (int32_t *)(w + 0x70), ww = *(int32_t *)(w + 0x78); if (*rx) x();\n}\nstatic void mv_offset(uint64_t w) {\n int32_t *v = (int32_t *)(w + 0x70); *v = 1;\n}\nstatic int h(float *r) {\n r[0] = 1.0f; int x = *(int32_t *)(w + 0x70); return x;\n}', 'selftest'): print('✗ native_write_scan 自检失败:该报的没报或不该报的报了'); return 1 print('✓ native_write_scan 自检:违规行会报红、注释里的名字不算') diff --git a/dm/host/tests/t_audio.c b/dm/host/tests/t_audio.c index cfac9a0..f030808 100644 --- a/dm/host/tests/t_audio.c +++ b/dm/host/tests/t_audio.c @@ -13,6 +13,18 @@ static _Atomic int g_sig; void hle_signal_system_event(void *g) { (void)g; atomic_fetch_add_explicit(&g_sig, 1, memory_order_seq_cst); } void hle_bind_system_event(void *g, int autoclear) { (void)g; (void)autoclear; } // 真实现要客体线程 + SDK 内核事件;单测只数触发次数 | the real implementation needs a guest thread + SDK kernel event; the unit test only counts triggers int main(void) { + { // 5.1 下混(期望按 Q15 系数手算:0.707·0.707 = 16384/32768 = 0.5,0.707 = 23170/32768):顺序 左前 右前 中置 低音 左后 右后 | 5.1 downmix (expected values worked out by hand from the Q15 coefficients: 0.707*0.707 = 16384/32768 = 0.5, 0.707 = 23170/32768): order front left, front right, centre, LFE, rear left, rear right + static const struct { int16_t in[6]; int16_t l, r; const char *what; } c[] = { + { { 0, 0, 10000, 0, 0, 0 }, 5000, 5000, "只有中置(对白)→ 左右各 5000" }, + { { 0, 0, 0, 0, 10000, 0 }, 5000, 0, "只有左后 → 左 5000、右 0" }, + { { 10000, 0, 0, 0, 0, 0 }, 7070, 0, "只有左前 → 左 7070(−3 dB)" }, + { { 0, 0, 0, 30000, 0, 0 }, 0, 0, "只有低音 → 不并入,0" }, + { { 32767, 32767, 32767, 0, 32767, 32767 }, 32767, 32767, "满幅叠加 → 饱和到 32767" }, + { { -32768, -32768, -32768, 0, -32768, -32768 }, -32768, -32768, "负满幅叠加 → 饱和到 −32768" } }; + int bad = 0; + for (unsigned i = 0; i < sizeof c / sizeof *c; i++) { int16_t o[2]; downmix51(c[i].in, o, 1); int ok = o[0] == c[i].l && o[1] == c[i].r; bad |= !ok; + printf("下混:%s:期望 (%d,%d) → 真结果 (%d,%d) %s\n", c[i].what, c[i].l, c[i].r, o[0], o[1], ok ? "✓" : "✗"); } + if (bad) return 1; } char out[64], ev[64]; uint8_t prm[16]; gbuf b[3]; static int16_t pcm[3][4800 * 2]; h_au_InitParam(prm); if (h_au_Open(out, ev, NULL, prm)) return 1; diff --git a/dm/host/tests/t_cloudsync.c b/dm/host/tests/t_cloudsync.c index 713bb64..7a8fb08 100644 --- a/dm/host/tests/t_cloudsync.c +++ b/dm/host/tests/t_cloudsync.c @@ -10,6 +10,8 @@ #include int dm_cloud_sync(const char *save, const char *cloud, const char *bak, const char *statef, int allow_down, uint64_t now_ms, int (*ready)(const char *unit)); int dm_cloud_conflict_take(void); +int dm_cloud_char_conflict_take(char *out, size_t n); +int dm_cloud_inbox_add(const char *save, const char *statef, const char *pack); #if __has_include("../stash_seed.h") // 公开仓库不带这份预置(它是游戏生成的一份存档的字节):不在时跳过用到它的 ⑱ ⑲ 两组 | the public repository does not ship this seed (it is the bytes of a save the game generated): when it is absent, the two groups that use it, 18 and 19, are skipped #include "../stash_seed.h" #define T_HAVE_STASH_SEED 1 @@ -41,6 +43,10 @@ static void put_d2i(const char *dev, int items, int chron, long sec) { put_bin(dev, "save/ModernSharedStashSoftCoreV2/ModernSharedStashSoftCoreV2.d2i", b, 68 + l2, sec); } static void put_vault(const char *dev, int n, long sec) { uint8_t b[8] = { 'S', 'W', 'V', 'T', 1, 0, (uint8_t)n, 0 }; put_bin(dev, "save/ModernSharedStashSoftCoreV2.swvault", b, 8, sec); } +static int inbox_n(const char *dev) { char d[1024]; path(d, dev, "save/_cloudinbox"); DIR *dp = opendir(d); struct dirent *e; int n = 0; while (dp && (e = readdir(dp))) n += e->d_name[0] != '.'; if (dp) closedir(dp); return n; } +static int inbox_has(const char *dev, const char *f) { // 收件箱里有没有哪个条目带这个文件 | whether any inbox entry carries this file + char d[1024]; path(d, dev, "save/_cloudinbox"); DIR *dp = opendir(d); struct dirent *e; int k = 0; struct stat st; + while (dp && (e = readdir(dp))) { if (e->d_name[0] == '.') continue; char p[1400]; snprintf(p, sizeof p, "%s/%s/%s", d, e->d_name, f); k |= !stat(p, &st); } if (dp) closedir(dp); return k; } static int d2i_items(const char *dev, const char *rel) { char p[1024]; path(p, dev, rel); FILE *f = fopen(p, "rb"); if (!f) return -1; uint8_t b[70]; size_t n = fread(b, 1, 70, f); fclose(f); return n >= 67 ? b[66] : -1; } int main(void) { @@ -139,20 +145,24 @@ int main(void) { CHECK(S3("H", 0) == 0 && d2i_items("H", D2I) == 0, "⑪ 新设备运行中首次同步:不传不改(不能拿空仓库盖云端)"); CHECK(S3("H", 1) == 1 && d2i_items("H", D2I) == 5 && get("H", "save/ModernSharedStashSoftCoreV2.swvault"), "⑪ 新设备启动首次同步:以云端为准,拿到 5 件与编年史仓库"); CHECK(count_bak("H", "_stash-") == 1, "⑪ 新设备本来那份空仓库进备份"); - CHECK(!dm_cloud_conflict_take(), "⑪ 正常首次同步不算冲突"); + CHECK(!dm_cloud_conflict_take() && inbox_n("H") == 0, "⑪ 本机那份是新建空档:不进收件箱、不提示"); put_d2i("G", 6, 400, 6000); CHECK(S3("G", 0) == 1, "⑭ G 编年史变长(400)照常上传"); CHECK(S3("H", 1) == 1 && d2i_items("H", D2I) == 6, "⑭ H 启动拿到 G 的新版"); put_d2i("H", 0, 148, 7000); // H 上的共享仓库不知为何变空(编年史 148、0 件),时刻更新 | the shared stash on H somehow became empty (chronicle 148, 0 items), with a newer timestamp - CHECK(S3("H", 0) == 0, "⑬ H 运行中要上传变空的那份:拦下"); - CHECK(dm_cloud_conflict_take() == 1, "⑬ 拦下记冲突(进局弹提示)"); + CHECK(S3("H", 0) == 0, "⑬ H 运行中要上传变空的那份:分叉,运行中不动"); + CHECK(!dm_cloud_conflict_take(), "⑬ 运行中不提示(不再永久拦)"); CHECK(S3("G", 1) == 0 && d2i_items("G", D2I) == 6, "⑬ 云端没被盖:G 仍是 6 件"); + CHECK(S3("H", 1) == 1 && d2i_items("H", D2I) == 6, "⑬ H 启动:云端为现行版,拿回 6 件"); + CHECK(inbox_n("H") == 1 && dm_cloud_conflict_take() == 1, "⑬ 本机那份共享仓库空了、但编年史仓库侧文件还有 3 件:进收件箱、提示一次"); put_d2i("H", 7, 500, 7500); CHECK(S3("H", 0) == 1, "⑮ H 正常玩:编年史 500 上传"); put_d2i("G", 6, 450, 7600); // G 没同步到 H 的 500 就自己写了 450(两边都改,G 后写) | G wrote 450 itself without having synced H's 500 (both sides changed, G wrote later) - CHECK(S3("G", 0) == 0, "⑮ G 运行中要拿编年史 450 盖云端的 500:拦下"); - CHECK(S3("G", 1) == 0 && d2i_items("G", D2I) == 6, "⑮ G 启动:云端 500 比本机 450 时刻早但编年史长——按后写赢会上传,被拦;本机不动"); - CHECK(dm_cloud_conflict_take() == 1, "⑮ 记冲突"); + CHECK(S3("G", 0) == 0, "⑮ G 运行中要拿编年史 450 盖云端的 500:分叉,运行中不动"); + CHECK(S3("G", 1) == 1 && d2i_items("G", D2I) == 7, "⑮ G 启动:云端(7 件、500)为现行版"); + CHECK(inbox_n("G") == 1 && inbox_has("G", "mine.pack") && inbox_has("G", "base.pack"), "⑮ G 本机那份(6 件、450)进收件箱,带上次同步的基准(6 件、400)"); + CHECK(dm_cloud_conflict_take() == 1, "⑮ 收进收件箱:进局提示一次"); + CHECK(S3("G", 1) == 0 && inbox_n("G") == 1, "⑮ 再启动:一致、无动作、不再收(不是永久状态)"); { char p3[1024]; path(p3, "H", "save/ModernSharedStashSoftCoreV2.swvault"); unlink(p3); } put_d2i("H", 7, 500, 8000); - CHECK(S3("H", 0) == 0 && dm_cloud_conflict_take() == 1, "⑬ 编年史仓库侧文件没了(云端有 3 件):拦下"); + CHECK(S3("H", 0) == 0 && !dm_cloud_conflict_take(), "⑬ 编年史仓库侧文件没了(云端有 3 件):分叉,运行中不动"); put_vault("H", 0, 8100); put_d2i("H", 0, 500, 8100); CHECK(S3("H", 0) == 1 && !dm_cloud_conflict_take(), "⑯ 正常玩法:共享仓库物品取空、编年史仓库取空(文件还在,0 件),编年史没变短——照常上传"); // ⑰ rf3 那个形状:云端专家仓库 2 件、编年史还是新建的 148;本机这份被换成游戏新建的空档(0 件、148),状态记录还在、云端没变 = 走「只本机改了」的上传 @@ -161,8 +171,8 @@ int main(void) { #define S4(dev, down) (path(s3, dev, "save"), path(b3, dev, "bak"), path(t3, dev, "state"), dm_cloud_sync(s3, cd, b3, t3, down, 0, NULL)) put_d2i("J", 2, 148, 1000); CHECK(S4("J", 1) == 1, "⑰ 准备:J 上传 2 件、编年史 148 的仓库"); put_d2i("J", 0, 148, 2000); dm_cloud_conflict_take(); - CHECK(S4("J", 0) == 0 && dm_cloud_conflict_take() == 1, "⑰ 运行中要拿新建空档(0 件、148)盖 2 件的那份:拦下"); - CHECK(S4("J", 1) == 0, "⑰ 启动时同样拦下(不上传)"); + CHECK(S4("J", 0) == 0 && !dm_cloud_conflict_take(), "⑰ 运行中要拿新建空档(0 件、148)盖 2 件的那份:分叉,运行中不动"); + CHECK(S4("J", 1) == 1 && d2i_items("J", D2I) == 2 && inbox_n("J") == 0, "⑰ 启动:拿回云端 2 件;本机空档不进收件箱"); put_d2i("J", 0, 300, 3000); CHECK(S4("J", 0) == 1, "⑰ 编年史长过新建大小的仓库取空:照常上传"); // ⑱ rf3 真形状:云端专家仓库是另一台的预置(stash_seed.h),本机还没有专家仓库档(启动同步跑在写预置之前)→ 不拦、不弹;本机写了预置后上传也不拦 // (18) The real rf3 shape: the cloud hardcore stash is another device's preset (stash_seed.h), and the local device has no hardcore stash file yet (startup sync runs before the preset is written) -> not blocked, no prompt; uploading after the local device writes the preset is not blocked either @@ -180,7 +190,7 @@ int main(void) { { uint8_t big[700]; memset(big, 0, sizeof big); uint32_t l1 = 68, l2 = 300; memcpy(big, "\x55\xaa\x55\xaa", 4); memcpy(big + 16, &l1, 4); memcpy(big + 64, "JM", 2); big[66] = 9; memcpy(big + 68, "\x55\xaa\x55\xaa", 4); memcpy(big + 84, &l2, 4); big[132] = 0xc0; put_bin("K", HC, big, 68 + 300, 5000); CHECK(S5("K", 0) == 1, "⑲ 准备:专家仓库有 9 件、编年史 300 上传"); } put_bin("K", HC, g_stash_seed, sizeof g_stash_seed, 6000); - CHECK(S5("K", 0) == 0 && dm_cloud_conflict_take() == 1, "⑲ 本机变回预置要盖 9 件的那份:拦下"); + CHECK(S5("K", 0) == 0 && !dm_cloud_conflict_take(), "⑲ 本机变回预置要盖 9 件的那份:分叉,运行中不动"); #undef HC #undef S5 } @@ -192,6 +202,61 @@ int main(void) { #undef D2I #undef S3 } + // ⑳ 同名角色(iCloud 离线冲突第 3 条):云端有 P 的 Foo(1000 秒);新设备 Q 从没同步过、离线建了同名 Foo(5000 秒)和 Bar → 首次同步:Foo 用云端那份、 + // 本机 Foo 整份进备份 Foo-5000000、记下名字待进局提示(取一次后清空);Bar 上传、不进提示 + // (20) Same-name character (iCloud offline conflict item 3): the cloud has P's Foo (1000 s); new device Q has never synced and created a Foo with the same name (5000 s) and a Bar offline -> first sync: Foo uses the cloud copy, + // the local Foo goes into the backup whole as Foo-5000000, the name is recorded for a notice after entering a run (cleared once taken); Bar is uploaded and not part of the notice + { char c6[1024], s6[1024], b6[1024], t6[1024]; snprintf(c6, sizeof c6, "%s/cloud6", R); mkdir(c6, 0755); char nm[256]; + #define S6(dev, down) (path(s6, dev, "save"), path(b6, dev, "bak"), path(t6, dev, "state"), dm_cloud_sync(s6, c6, b6, t6, down, 0, NULL)) + put("P", "save/Foo/Foo.d2s", "fooP", 1000); CHECK(S6("P", 1) == 1, "⑳ 准备:P 上传 Foo"); + dm_cloud_char_conflict_take(nm, sizeof nm); + put("Q", "save/Foo/Foo.d2s", "fooQ", 5000); put("Q", "save/Bar/Bar.d2s", "barQ", 5000); + CHECK(S6("Q", 1) == 2, "⑳ Q 首次同步:Foo 下载、Bar 上传,共 2 个动作"); + CHECK(get("Q", "save/Foo/Foo.d2s") && !strcmp(get("Q", "save/Foo/Foo.d2s"), "fooP"), "⑳ Q 的 Foo 应换成云端那份 fooP"); + CHECK(count_bak("Q", "Foo-5000000") == 1, "⑳ Q 本机那份 Foo 应进备份 Foo-5000000"); + CHECK(dm_cloud_char_conflict_take(nm, sizeof nm) == 1 && !strcmp(nm, "Foo"), "⑳ 记下同名角色 Foo 待提示,实为「%s」", nm); + CHECK(dm_cloud_char_conflict_take(nm, sizeof nm) == 0, "⑳ 取过一次后清空"); + CHECK(S6("Q", 1) == 0 && dm_cloud_char_conflict_take(nm, sizeof nm) == 0, "⑳ 再同步无动作、不再提示"); + #undef S6 + } + // ㉑ iCloud 离线冲突三个场景(第一笔口径:两台设备的全部数据都在——仓库或收件箱,且没有永久拦截)。老设备 A:10 件、编年史 600,已上云 + // (21) Three iCloud offline conflict scenarios (first-step criterion: all data of both devices is kept - in the stash or the inbox - and nothing is blocked forever). Old device A: 10 items, chronicle 600, already in the cloud + { char c7[1024], s7[1024], b7[1024], t7[1024], cq[1024]; snprintf(c7, sizeof c7, "%s/cloud7", R); mkdir(c7, 0755); snprintf(cq, sizeof cq, "%s/cloud7q", R); mkdir(cq, 0755); + #define S7(dev, cl, down) (path(s7, dev, "save"), path(b7, dev, "bak"), path(t7, dev, "state"), dm_cloud_sync(s7, cl, b7, t7, down, 0, NULL)) + #define D2I7 "save/ModernSharedStashSoftCoreV2/ModernSharedStashSoftCoreV2.d2i" + put_d2i("A7", 10, 600, 1000); CHECK(S7("A7", c7, 1) == 1, "㉑ 准备:A 上传 10 件"); + dm_cloud_conflict_take(); + // ① 新设备 N 没登录时离线玩(3 件、编年史 300),之后登录、启动同步 + // (1) new device N plays offline while not signed in (3 items, chronicle 300), then signs in and syncs at launch + put_d2i("N7", 3, 300, 5000); + CHECK(S7("N7", c7, 1) == 1 && d2i_items("N7", D2I7) == 10, "㉑① N 首次同步:仓库是云端的 10 件"); + CHECK(inbox_n("N7") == 1 && inbox_has("N7", "mine.pack") && !inbox_has("N7", "base.pack") && dm_cloud_conflict_take() == 1, "㉑① N 本机 3 件进收件箱(没有基准)、提示一次"); + CHECK(S7("N7", c7, 1) == 0 && inbox_n("N7") == 1 && d2i_items("A7", D2I7) == 10, "㉑① 再启动无动作(没有永久状态);A 的 10 件不动"); + // ② 新设备 M 离线期间编年史比云端长(900 > 600):原先永久拦住,现在同样云端为现行版 + 收件箱 + // (2) new device M's chronicle grew longer than the cloud's while offline (900 > 600): previously blocked forever, now likewise the cloud is the current version + inbox + put_d2i("M7", 3, 900, 5000); + CHECK(S7("M7", c7, 0) == 0 && inbox_n("M7") == 0, "㉑② M 运行中:不动、不收(等启动)"); + CHECK(S7("M7", c7, 1) == 1 && d2i_items("M7", D2I7) == 10 && inbox_n("M7") == 1 && dm_cloud_conflict_take() == 1, "㉑② M 启动:仓库 10 件,本机 3 件进收件箱"); + CHECK(S7("M7", c7, 1) == 0 && S7("M7", c7, 0) == 0 && inbox_n("M7") == 1, "㉑② 再启动、再运行中都无动作:不是永久拦截"); + // ③ 新设备 Q 登录但离线、看到的云端是空的(cloud7q),上传了 3 件;联网后 iCloud 拿 Q 的包当现行版(盖到 cloud7 上) + // (3) new device Q signs in but is offline and sees an empty cloud (cloud7q), uploads 3 items; once online, iCloud takes Q's pack as the current version (overwriting cloud7) + put_d2i("Q7", 3, 300, 5000); CHECK(S7("Q7", cq, 1) == 1, "㉑③ 准备:Q 往看着是空的云端传了 3 件"); + char sp[1300], dp[1300], keep[1300]; snprintf(sp, sizeof sp, "%s/_stash.pack", cq); snprintf(dp, sizeof dp, "%s/_stash.pack", c7); snprintf(keep, sizeof keep, "%s/a_old.pack", R); + rename(dp, keep); { FILE *fi = fopen(sp, "rb"), *fo = fopen(dp, "wb"); char buf[8192]; size_t k; while ((k = fread(buf, 1, sizeof buf, fi)) > 0) fwrite(buf, 1, k, fo); fclose(fi); fclose(fo); } + CHECK(S7("A7", c7, 1) == 1 && d2i_items("A7", D2I7) == 3, "㉑③ A 启动:云端(Q 的 3 件)为现行版"); + CHECK(inbox_n("A7") == 1 && inbox_has("A7", "base.pack") && dm_cloud_conflict_take() == 1, "㉑③ A 本机 10 件进收件箱,带上次同步的基准"); + CHECK(S7("A7", c7, 1) == 0 && inbox_n("A7") == 1, "㉑③ 再启动无动作"); + // iCloud 冲突版本:A 那台读出被换下的旧版本(a_old.pack,10 件)收进收件箱;只有预置 / 空档的版本不收 + // iCloud conflict version: device A reads out the replaced old version (a_old.pack, 10 items) and stores it in the inbox; a version with only the preset / an empty save is not stored + { char ts7[1100]; path(s7, "A7", "save"); path(ts7, "A7", "state"); + CHECK(dm_cloud_inbox_add(s7, ts7, keep) == 0 && inbox_n("A7") == 2 && dm_cloud_conflict_take() == 1, "㉑③ 冲突版本(10 件)收进收件箱"); + put_d2i("E7", 0, 148, 100); { char e7[1100], ee[1100], et[1100], pk[1300]; path(e7, "E7", "save"); path(ee, "E7", "bak"); path(et, "E7", "state"); char ce[1300]; snprintf(ce, sizeof ce, "%s/cloud7e", R); mkdir(ce, 0755); + dm_cloud_sync(e7, ce, ee, et, 1, 0, NULL); snprintf(pk, sizeof pk, "%s/_stash.pack", ce); + CHECK(dm_cloud_inbox_add(s7, ts7, pk) == 0 && inbox_n("A7") == 2, "㉑③ 空档的冲突版本:没东西,不收"); } + CHECK(dm_cloud_inbox_add(s7, ts7, "/nonexistent.pack") == -1, "㉑③ 读不了的冲突版本:返回 -1"); } + #undef S7 + #undef D2I7 + } printf("t_cloudsync: %d 项,%d 失败\n", checks, fails); return fails != 0; } 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/tests/t_rift_next.c b/dm/host/tests/t_rift_next.c index 15d21e1..afab59d 100644 --- a/dm/host/tests/t_rift_next.c +++ b/dm/host/tests/t_rift_next.c @@ -51,6 +51,28 @@ int main(void) { K.tier = 100; if (10819454LL * hi_duo_x1000(0) / 1000 > 8388607LL) { fails++; printf(" ✗ 100 层巴尔 × s 过了属性上限\n"); } K.guards[0] = 7; K.guards[1] = 9; K.guards[2] = 0; if (!is_guard(7) || !is_guard(9) || is_guard(0) || is_guard(8)) { fails++; printf(" ✗ is_guard 认错\n"); } printf("hi_duo %s:4 格系数 + 巴尔不过上限 + 认守护者\n", fails ? "失败" : "OK"); + // 闯入首领也算「特殊单位」(不按普通怪计分、不按普通怪再改属性):在场的(K.inv_id)与已退场、还没被真移除的(g_inv_gone)都算—— + // 后者漏掉的话,退场后那几秒里被打死会按普通金怪计 10 分(实测过:进度 400 → 410) + // Invading bosses also count as "special units" (not scored as ordinary monsters, not scaled again as ordinary monsters): both the one present (K.inv_id) and one that has left but is not yet truly removed (g_inv_gone) - + // if the latter is missed, being killed in the few seconds after leaving would score 10 points as an ordinary unique monster (measured: progress 400 -> 410) + K.guards[0] = K.guards[1] = K.guards[2] = 0; K.inv_id[0] = 21; K.inv_id[1] = 0; g_inv_gone[0] = 0; g_inv_gone[1] = 33; + if (!is_guard(21) || !is_guard(33) || is_guard(22) || is_guard(0)) { fails++; printf(" ✗ is_guard 没认全闯入首领(在场 21、已退场 33)\n"); } + K.inv_id[0] = 0; g_inv_gone[1] = 0; if (is_guard(21) || is_guard(33)) { fails++; printf(" ✗ 清掉之后 is_guard 还认\n"); } + // 首领召唤物按类号认:巴尔触手 562–566、分身 570;巴尔本体 544、它的小怪 571、普通怪不算 + // Boss summons are recognised by class id: Baal's tentacles 562–566 and clone 570; Baal himself 544, his minions 571 and ordinary monsters do not count + { static const struct { uint32_t cls; int want; } bc[] = { { 561, 0 }, { 562, 1 }, { 564, 1 }, { 566, 1 }, { 567, 0 }, { 570, 1 }, { 571, 0 }, { 544, 0 }, { 45, 0 } }; + for (unsigned i = 0; i < sizeof bc / sizeof *bc; i++) if (boss_summon(bc[i].cls) != bc[i].want) { fails++; printf(" ✗ boss_summon(%u) 应为 %d\n", bc[i].cls, bc[i].want); } } + printf("invader_guard %s:在场与已退场的闯入首领都算特殊单位\n", fails ? "失败" : "OK"); + // 特殊精英的梯度(设计稿第二十四节):原生怪留几成 / 一场最多几组 / 同时在场几组。74 层及以下 = 100% / 0 / —(逐位不变) + // Special elite gradient (design draft section 24): share of native monsters kept / max groups per run / groups present at once. Level 74 and below = 100% / 0 / - (unchanged bit for bit) + { static const struct { int tier, nat, quota, cap; } sc[] = { { 1, 100, 0, 2 }, { 74, 100, 0, 2 }, { 75, 80, 2, 2 }, { 79, 80, 2, 2 }, { 80, 55, 5, 2 }, { 84, 55, 5, 2 }, { 85, 30, 7, 2 }, { 89, 30, 7, 2 }, { 90, 0, 1 << 30, 3 }, { 100, 0, 1 << 30, 3 } }; + for (unsigned i = 0; i < sizeof sc / sizeof *sc; i++) if (su_nat_pct(sc[i].tier) != sc[i].nat || su_quota(sc[i].tier) != sc[i].quota || su_cap(sc[i].tier) != sc[i].cap) { fails++; printf(" ✗ 第 %d 层特殊精英梯度应为 %d%% / %d 组 / 同时 %d 组\n", sc[i].tier, sc[i].nat, sc[i].quota, sc[i].cap); } + // 池:43 行、不重样、不含剔掉的 23 行、含女伯爵(6)与随从 9 只的三行(24、36、38,有巴尔的场在抽的时候跳过) + // Pool: 43 rows, no duplicates, none of the 23 removed rows, includes the Countess (6) and the three rows with 9 minions (24, 36, 38; skipped when drawing for a run with Baal) + static const uint8_t out[] = { 5, 10, 15, 18, 20, 26, 27, 28, 29, 30, 31, 39, 41, 42, 43, 44, 45, 60, 61, 62, 63, 64, 65 }; int seen[66] = { 0 }, bad = sizeof k_su_pool != 43; + for (unsigned i = 0; i < sizeof k_su_pool; i++) { if (k_su_pool[i] > 65 || seen[k_su_pool[i]]++) bad = 1; } for (unsigned i = 0; i < sizeof out; i++) bad |= seen[out[i]]; bad |= !seen[6] || !seen[24] || !seen[36] || !seen[38]; + if (bad) { fails++; printf(" ✗ 特殊精英的池不对(应 43 行、不重样、不含剔掉的 23 行)\n"); } + printf("su_tiers %s:10 格梯度 + 池 43 行\n", fails ? "失败" : "OK"); } printf("t_rift_next %s:%d 格(层 × 晋级量)下一层 = 手写期望且 ≤ 100,宿主与顶部条同值\n", fails ? "失败" : "OK", n); return fails != 0; } diff --git a/dm/host/tests/t_rift_oldrun.c b/dm/host/tests/t_rift_oldrun.c index 3f0c502..e0d9256 100644 --- a/dm/host/tests/t_rift_oldrun.c +++ b/dm/host/tests/t_rift_oldrun.c @@ -33,6 +33,12 @@ int main(void) { for (unsigned i = 0; i < sizeof oc / sizeof *oc; i++) { atomic_store(&K.st, oc[i].st); K.t0_ns = guest_ns() - (uint64_t)oc[i].ago * 1000000000ull; dm_rift_hud_t h = {0}; dm_rift_menu_t m = {0}; dm_rift_hud(&h); menu_fill(&m, 2); if (rift_overtime() != oc[i].want || m.overtime != oc[i].want || (oc[i].st != ST_IDLE && h.overtime != oc[i].want)) { fails++; printf(" ✗ 状态 %d 开局 %d 秒前:超时量应为 %d,得 %d(顶部条 %d、菜单 %d)\n", oc[i].st, oc[i].ago, oc[i].want, rift_overtime(), h.overtime, m.overtime); } } printf("rift_overtime %s:6 格\n", fails ? "失败" : "OK"); + // 顶部条第二行写哪一句(dm_rift_hud 的 goal,宿主一处定):按「是否超时 × 守护者是否在场 × 守护者几位」手写期望 + // Which sentence the second line of the top bar shows (goal of dm_rift_hud, decided in one place in the host): expected values written by hand over "overtime or not x Guardians present or not x how many Guardians" + static const struct { int ago, guard, dead, total, want; } gc[] = { { 100, 0, 0, 0, 0 }, { 100, 1, 0, 1, 1 }, { 100, 1, 0, 2, 2 }, { 100, 1, 1, 2, 2 }, { 100, 1, 1, 3, 2 }, { 901, 0, 0, 0, 3 }, { 901, 1, 0, 1, 4 }, { 901, 1, 1, 2, 5 } }; + for (unsigned i = 0; i < sizeof gc / sizeof *gc; i++) { atomic_store(&K.st, ST_RUN); K.t0_ns = guest_ns() - (uint64_t)gc[i].ago * 1000000000ull; K.guard = gc[i].guard ? 7 : 0; atomic_store(&K.guard_dead, 0); atomic_store(&K.gdead, gc[i].dead); atomic_store(&K.gtotal, gc[i].total); + dm_rift_hud_t h = {0}; dm_rift_hud(&h); if (h.goal != gc[i].want || h.gdead != gc[i].dead || h.gtotal != gc[i].total) { fails++; printf(" ✗ 开局 %d 秒前 守护者在场 %d(%d/%d):第二行应为 %d,得 %d\n", gc[i].ago, gc[i].guard, gc[i].dead, gc[i].total, gc[i].want, h.goal); } } + K.guard = 0; printf("hud_goal %s:8 格\n", fails ? "失败" : "OK"); printf("t_rift_oldrun %s:%d 格城里入口给页 + 新局重置清请求\n", fails ? "失败" : "OK", n); return fails != 0; } diff --git a/dm/host/tests/t_touch_mac.c b/dm/host/tests/t_touch_mac.c index 5a0ff63..f3dcf2d 100644 --- a/dm/host/tests/t_touch_mac.c +++ b/dm/host/tests/t_touch_mac.c @@ -33,6 +33,7 @@ void dm_elysium_arm(int on) { (void)on; } // 极乐世界勾选(dm_elysium.c void dm_custom_on_uimsg(const char *cat, const char *act, const char *arg) { (void)cat; (void)act; (void)arg; } // 「自定义」设置(dm_custom.c)的桩 | stub for the "Custom" settings (dm_custom.c) void dm_belt_put(unsigned id) { (void)id; } void dm_ui_rect(int *x, int *y, int *w, int *h) { *x = *y = *w = *h = 0; } +void dm_uiscreen_set_panel(int on) { (void)on; } int dm_screen_real(int *w, int *h) { (void)w; (void)h; return 0; } int dm_uiscreen_ingame(void) { return 0; } void dm_uiscreen_set_ingame(int on) { (void)on; } // 界面矩形(dm_uiscreen.c)的桩:没开真全屏 | stub for the UI rectangle (dm_uiscreen.c): true full screen not enabled diff --git a/dm/host/tests/t_touch_tick_stub.c b/dm/host/tests/t_touch_tick_stub.c index d8d1f4d..b5ec6af 100644 --- a/dm/host/tests/t_touch_tick_stub.c +++ b/dm/host/tests/t_touch_tick_stub.c @@ -79,6 +79,7 @@ float dm_ui_ny(float ny) { return ny; } int dm_screen_real(int *w, int *h) { (void)w; (void)h; return 0; } void dm_uiscreen_enable(int m) { (void)m; } void dm_ui_rect(int *x, int *y, int *w, int *h) { *x = *y = *w = *h = 0; } +void dm_uiscreen_set_panel(int on) { (void)on; } int dm_uiscreen_ingame(void) { return 0; } void dm_uiscreen_set_ingame(int on) { (void)on; } void dm_held_stow(void) {} diff --git a/dm/host/touch_mac.c b/dm/host/touch_mac.c index d484bb1..ad962c1 100644 --- a/dm/host/touch_mac.c +++ b/dm/host/touch_mac.c @@ -4,11 +4,17 @@ #include "dm_actions.h" #include "dm_hud.h" #include "../touch/dm_touch_controls.h" +#include "dm_uiscreen.h" #include #include #include uint64_t now_ns(void); +// 手势层的坐标是「界面矩形里的归一化」(同 iOS 的游戏视图);点世界 / 点地走要的是「整屏归一化」。16:9 时两者一样; +// 真全屏(界面按 16:9 贴底、画面更高)下纵向要换:整屏 y = (界面 y × 界面高 + 界面矩形顶边) ÷ 画面高(iOS 前端在点世界前做的同一步,front_ios.m world_norm) +// Gesture-layer coordinates are "normalised within the interface rectangle" (like the iOS game view); tapping the world / tap-to-walk needs "normalised to the whole screen". At 16:9 the two are the same; +// with true full screen (interface 16:9 along the bottom, picture taller) the vertical needs converting: screen y = (interface y x interface height + interface rectangle top) / picture height (the same step the iOS front end does before tapping the world, front_ios.m world_norm) +static float ui_y_to_screen(float uy) { int x, y, w, h, rw = 0, rh = 0; dm_ui_rect(&x, &y, &w, &h); return dm_screen_real(&rw, &rh) && rh > 0 && h > 0 ? (uy * h + y) / rh : uy; } uint64_t guest_ns(void); uint32_t dm_cur_tick(void); int dm_loadscreen_down(void); @@ -54,6 +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); + // 面板模式与 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) @@ -217,7 +234,7 @@ void dm_touch_host_step(uint64_t now, uint64_t *buttons, int32_t *lx, int32_t *l { void dm_world_walk(float, float); int dm_world_tap_result(unsigned), dm_game_paused(void); uint32_t tk = touch_cur_tick(); dm_tc_set_joy_block(&g_touch.state, 1); // 鼠标不起触屏那个浮动摇杆(左下那片按住拖动原先会变成推摇杆) | the mouse does not start the touch layout's floating stick (holding and dragging in the bottom-left area used to turn into pushing the stick) if (g_lm.tap_seq) { int r = dm_world_tap_result(g_lm.tap_seq); if (r >= 0) { if (r == 0 && in && !dm_game_paused()) dm_world_walk(g_lm.tap_x, g_lm.tap_y); g_lm.tap_seq = 0; } } - if (g_lm.down && in && !g_touch.state.navigation_mode && !dm_game_paused() && (int32_t)(tk - g_lm.t0) >= 9 && (!g_lm.last || (int32_t)(tk - g_lm.last) >= 6) && dm_ui_item_at_now(g_lm.x, g_lm.y) != 0) { g_lm.last = tk; dm_world_walk(g_lm.x, g_lm.y); } + if (g_lm.down && in && !g_touch.state.navigation_mode && !dm_game_paused() && (int32_t)(tk - g_lm.t0) >= 9 && (!g_lm.last || (int32_t)(tk - g_lm.last) >= 6) && dm_ui_item_at_now(g_lm.x, g_lm.y) != 0) { g_lm.last = tk; dm_world_walk(g_lm.x, ui_y_to_screen(g_lm.y)); } if (!in) g_lm.down = 0; } } if (g_live_btn) { if ((int32_t)(g_live_btn_until - touch_cur_tick()) > 0) *buttons |= g_live_btn; else g_live_btn = 0; } @@ -299,7 +316,7 @@ apply_input: // 真鼠标:手势层认为没有面板开着(它按名单认面板,大秘境选层页这类借壳的面板不在名单里),这一下却落在某个面板里 → 发界面点击,不当点世界 // Real mouse: the gesture layer believes no panel is open (it recognises panels by a list, and panels that borrow another shell, such as the Greater Rift level-selection page, are not on it), yet this click lands inside some panel -> send a UI click instead of a world click if (g_live_on && dm_ui_item_at_now(wx, wy) == 0) { dm_ui_touch(0, wx, wy); dm_ui_touch(2, wx, wy); } - else if (g_live_on) { unsigned dm_world_click(float, float); g_lm.tap_seq = dm_world_click(wx, wy); g_lm.tap_x = wx; g_lm.tap_y = wy; } else dm_world_tap(wx, wy); } // 真鼠标:记下这一笔,答案是「没有目标」就改成走到那一点 | real mouse: remember this click, and if the answer is "no target" turn it into walking to that point + else if (g_live_on) { unsigned dm_world_click(float, float); float sy = ui_y_to_screen(wy); g_lm.tap_seq = dm_world_click(wx, sy); g_lm.tap_x = wx; g_lm.tap_y = sy; } else dm_world_tap(wx, ui_y_to_screen(wy)); } // 真鼠标:记下这一笔,答案是「没有目标」就改成走到那一点 | real mouse: remember this click, and if the answer is "no target" turn it into walking to that point if (g_touch.state.mouse_click_seq != mc) { float nx = g_touch.state.mouse_click_x / 2868, ny = g_touch.state.mouse_click_y / 1320; dm_ui_touch(0, nx, ny); dm_ui_touch(2, nx, ny); } } } diff --git a/dm/i18n/literal_whitelist.tsv b/dm/i18n/literal_whitelist.tsv index 3033677..c905225 100644 --- a/dm/i18n/literal_whitelist.tsv +++ b/dm/i18n/literal_whitelist.tsv @@ -113,3 +113,8 @@ host/dm_custom.c @DM_WIDGET_OK 同上 host/dm_rift_ui.c @DM_WIDGET_OK 同上 host/dm_autobuff.c * 技能名、排除理由、测试读数都只进日志;这个功能屏上没有自己的文字(玩家看到的是原版的施法动作) ios/Sources/dm_shader_prep.m * 公开版壳专用的「首次准备着色器」页(整个文件在 #ifdef DM_SHELL 里,内测包不编):这时宿主与中英表还没起,中英两套文字就写在文件里、跟系统语言走 +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 39a5611..3c2cfbf 100644 --- a/dm/i18n/ui_text.tsv +++ b/dm/i18n/ui_text.tsv @@ -135,6 +135,11 @@ dmDlCellGo 用流量下载 Use Cellular Data 蜂窝网络提示框按钮 dmDlProgress 正在下载游戏资源\n%.2f / %.2f GB(%.0f%%) %.1f MB/s Downloading game resources\n%.2f / %.2f GB (%.0f%%) %.1f MB/s 资源下载页进度(托管下载) dmDlPaused 下载已暂停(检查网络),恢复后自动继续 Download paused (check your network). It resumes automatically. 资源下载页 dmDlPackWait 系统还在准备资源包,完成后自动继续 The system is still preparing the resource pack. It continues automatically. 资源下载页(main.m) +dmDlInstalling 下载完成,系统正在安装资源包\n可能要几分钟,请保持本 App 在前台\n资源包 %.2f GB,本机可用 %.2f GB Download complete. The system is installing the resource pack.\nThis can take a few minutes. Keep this app open.\nPack %.2f GB, %.2f GB free on this device 资源下载页:托管下载到 100% 之后(main.m) +dmDlInstallSpace 下载完成,但本机空间不够系统安装资源包\n资源包 %.2f GB,%@ 现在可用 %.2f GB,至少还差 %.2f GB\n请在「设置 → 通用 → %@ 储存空间」清理,清理后自动继续 Download complete, but there is not enough space to install the resource pack.\nPack %.2f GB; this %@ has %.2f GB free, at least %.2f GB more needed.\nFree up space in Settings → General → %@ Storage. It continues automatically. 资源下载页:托管下载 100% 后空间不够(main.m) +dmDlPackSlow 系统安装资源包已超过 %d 分钟还没完成\n可以继续等,也可以点「改用直接下载」从下载站下载资源(断点续传) The system has been installing the resource pack for over %d minutes.\nYou can keep waiting, or tap "Download Directly" to get the resources from our download site (resumable). 资源下载页:托管安装超时(main.m) +dmDlPackSlowNoDl 系统安装资源包已超过 %d 分钟还没完成\n可以继续等;也可以点「分享诊断日志」把日志发给我们 The system has been installing the resource pack for over %d minutes.\nYou can keep waiting, or tap "Share Diagnostics" to send us the log. 资源下载页:托管安装超时、包里没配下载地址(main.m) +dmDlUseDirect 改用直接下载 Download Directly 资源下载页按钮(main.m) dmDlNotReady 游戏资源还不能用\n%@\n处理后点重试 Game resources are not ready\n%@\nFix this, then tap Retry 资源下载页(main.m) dmDlWill 将下载游戏资源:还要下 %@(共 %.1f GB) Downloading game resources: %@ remaining (%.1f GB total) 资源下载页:自动开始的大下载,开始前写明大小(%@ = 「4 MB」「4.1 GB」) dmDlNotStarted %@游戏资源下载没开始:%@\n%@\n也可以从内测页手动下载资源包,放进「我的 iPhone → D2R Mobile」 %@The resource download could not start: %@\n%@\nYou can also download the resource pack from the beta page and put it in "On My iPhone → D2R Mobile" 资源下载页:取不到下载地址 / 清单时停在这一页(前缀、原因、下一步) @@ -158,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%%)%@ 老机型补充包下载页进度 @@ -204,7 +215,11 @@ dmRiftSayErr 秘境出错了,这次没开 The Rift could not be opened 秘境 dmRiftSayStart 第 %d 层开始,限时 15 分钟 Level %d: 15 minute time limit 秘境系统提示(dm_rift.c);英文:Greater Rift level / time limit 取自暗黑 3 官方 2.1.0 补丁说明(news.blizzard.com/en-us/article/14569138)「complete the current Greater Rift level within the designated time limit」 dmRiftSayGift 赠彩虹刻面一颗,已掉在脚下 A Rainbow Facet has dropped 秘境系统提示(dm_rift.c);「彩虹刻面」是旧译名(原版现行「彩虹魔石」);英文物品名 = 原版键 Rainbow Facet 的 enUS;英文:物品名 = 暗黑 2 原版 item-names[Rainbow Facet] dmRiftSayTimeout 时间到:本层未过关,守护者仍会掉落 Time's up: level not cleared 秘境系统提示(dm_rift.c);超时打倒守护者不算过关;英文:not cleared,不用 Failed(没死也没失败,只是不计) +dmRiftSayFoes 本场有 %d 位强敌 %d powerful foes this run 秘境系统提示(dm_rift.c):90 层起开局提示本场闯入首领的位数;英文:拟 +dmRiftSayInvader 强敌逼近! A powerful foe approaches! 秘境系统提示(dm_rift.c):80 层起途中闯入一位首领,刷出前约 3 秒提示;英文:拟 +dmRiftSayInvaderGone 闯入者退去了 The intruder withdraws 秘境系统提示(dm_rift.c):守护者现身时,还在场的闯入首领退场;英文:拟 dmRiftSayGuardians 进度已满:两位守护者现身! Two Rift Guardians appear! 秘境系统提示(dm_rift.c):75 层起守护者是两位;英文:同 dmRiftSayGuardian 的用词 +dmRiftSayWave 守护者第 %d 波现身(共 %d 波) Guardian wave %d of %d 秘境系统提示(dm_rift.c):95 层起守护者分波,第 2 波起每波现身时说一声;英文:拟 dmRiftSayGuardian 进度已满:守护者现身! The Rift Guardian appears! 秘境系统提示(dm_rift.c);英文:Rift Guardian 取自暗黑 3 官方 2.1.0 补丁说明(news.blizzard.com/en-us/article/14569138);出现时的界面原句没查到,拟 dmElyToaGround 背包已满,赦免之证掉在脚边 Inventory full: Token of Absolution dropped 极乐世界新角色补齐(dm_elysium.c):背包放不下时的系统提示;英文物品名 = 暗黑 2 原版 Token of Absolution dmMercSlotLocked 通关地狱后打通秘境10层解锁 Clear Greater Rift Level 10 to unlock 佣兵新装备位没解锁时的系统提示(dm_rift.c;中文是 原句);英文:Greater Rift 取暗黑 3 原文 @@ -251,7 +266,8 @@ dmKbRiftMsAll 已全部领取 All claimed 积分牌秘境项(dm_kills.c) dmKbRiftFast 最快 %d:%02d Best Time %d:%02d 积分牌秘境项(dm_kills.c);英文:拟(同积分牌 dmKbTimes 的 Best);暗黑 3 排行榜列名为 Time Spent(意思是用时,不是最快),未采用,留 Best Time dmKbRiftMsGot 首通奖励已领取 First clear reward claimed 积分牌秘境项(dm_kills.c);英文:拟 dmKbRiftTotal 最高 %d 层 Best Level: %d 积分牌秘境项(dm_kills.c);英文:拟 -dmCloudConflict iCloud 共享仓库两边不一致,已保留本机,请联系我们 iCloud shared stash mismatch: kept this device. Please contact us iCloud 同步冲突提示(diag.c) +dmCloudConflict iCloud:两台设备的共享仓库各有内容,已用云端那份,本机那份已完整保存待并回 iCloud: both devices had shared stash contents. Using the cloud copy; this device's copy is kept to be merged back iCloud 共享仓库分叉提示(diag.c;本机那份在待合并收件箱) +dmCloudCharConflict iCloud:角色 %s 两台设备各有一份,已用云端那份,本机那份已备份 iCloud: both devices had character %s. Using the cloud copy; this device's copy is backed up iCloud 首次同步同名角色提示(diag.c,%s = 角色名) dmRiftHudTitle 秘境 Rift 秘境顶部进度条(dm_rift_hud.m,UIKit) dmRiftHudDone 第 %d 层完成 Level %d complete 秘境顶部进度条(dm_rift_hud.m,UIKit);英文:见 dmRiftSayDoneBoth dmRiftHudLate 第 %d 层超时 Level %d overtime 秘境顶部进度条(dm_rift_hud.m,UIKit);英文:拟 @@ -259,6 +275,10 @@ dmRiftHudGuard 守护者现身 Rift Guardian 秘境顶部进度条(dm_rift_hud dmRiftHudNext 下次第 %d 层 Next: Level %d 秘境顶部进度条(dm_rift_hud.m,UIKit);英文:拟 dmRiftHudTop 已通关最高层 Highest level cleared 秘境顶部进度条(dm_rift_hud.m,UIKit):第 100 层限时内通关,没有下一层了(公开仓库);英文:拟 dmRiftHudOver 已超时:打完仍有掉落,不计通关 Overtime: drops, no clear 秘境顶部进度条(dm_rift_hud.m,UIKit)第二行:限时已到、守护者还没倒(公开仓库);英文:拟 +dmRiftHudKillWave 守护者 第 %d/%d 波(%d/%d) Guardians %d/%d (%d/%d) 秘境顶部进度条第二行:守护者分波时(95 层起)写第几波 / 共几波与这一波已倒 / 总数;英文:拟,栏宽所限不写 wave +dmRiftHudKillN 击败守护者(%d/%d) Slay the Guardians (%d/%d) 秘境顶部进度条第二行:守护者两位以上时带已倒 / 总数;英文:同 dmRiftHudKill 的用词 +dmRiftHudOverKill 已超时:击败守护者仍有掉落 Overtime: slay it for drops 秘境顶部进度条第二行:已超时且守护者在场(一位);英文:拟 +dmRiftHudOverKillN 已超时:击败守护者(%d/%d)仍有掉落 Overtime: slay %d/%d for drops 同上,守护者两位以上;英文:拟 dmRiftHudSame 下次仍是这一层 Next: same level 秘境顶部进度条(dm_rift_hud.m,UIKit);英文:拟 dmRiftHudKill 击败守护者 Slay the Rift Guardian 秘境顶部进度条(dm_rift_hud.m,UIKit);英文:拟;任务目标原句没查到 dmRiftHudGoal 消灭秘境中的怪物 %d%% Slay the monsters %d%% 秘境顶部进度条(dm_rift_hud.m,UIKit);英文:拟;任务目标原句没查到 diff --git a/dm/ios/Sources/cloud_ios.m b/dm/ios/Sources/cloud_ios.m index 0014944..33371a5 100644 --- a/dm/ios/Sources/cloud_ios.m +++ b/dm/ios/Sources/cloud_ios.m @@ -21,6 +21,7 @@ #if TARGET_OS_IPHONE #import #endif +#import #include #include #include @@ -28,6 +29,8 @@ #include "hle.h" int dm_cloud_sync(const char *save, const char *cloud, const char *bak, const char *statef, int allow_down, uint64_t now_ms, int (*ready)(const char *unit)); +int dm_cloud_inbox_add(const char *save, const char *statef, const char *pack); uint64_t dm_cloud_pack_stamp(const char *pack); +int dm_cloud_bak_pack(const char *bak, const char *unit, const char *pack, const char *why); void dm_cloud_char_conflict_note(const char *unit); int dm_custom_get(const char *key); extern void (*g_dm_save_commit_hook)(const char *commit_dir); @@ -54,10 +57,39 @@ static int pending_downloads(int start) { // 还没下载好的包数;start } return n; } +// iCloud 自己的同名文件冲突(两台各写了一份同名包、系统挑了一份当现行版,其余成「未解决的冲突版本」;iCloud 离线冲突第 1 条)。启动同步前在文件协调里做: +// 共享仓库:每个冲突版本收进待合并收件箱(dm_cloud_inbox_add,现行版照常走同步); +// 角色:包头时刻(游戏最后写它的时刻)最新的那份当现行版(不是系统挑的就换上去),其余整份进备份,记名进局提示。 +// 全部收好才把冲突标成已解决并删掉其余版本;有一份收不进就都留着,下次启动再来(宁可多留不丢)。 +// iCloud's own same-name file conflict (two devices each wrote a same-name pack, the system picked one as the current version and the rest became "unresolved conflict versions"; iCloud offline conflict item 1). Done inside file coordination before the launch sync: +// shared stash: each conflict version is stored in the to-merge inbox (dm_cloud_inbox_add; the current version goes through sync as usual); +// character: the copy with the newest pack header timestamp (the moment the game last wrote it) becomes the current version (swapped in if it is not the one the system picked), the rest go into the backup whole, and the name is recorded for a notice after entering a run. +// Only once everything is stored are the conflicts marked resolved and the other versions deleted; if any one cannot be stored, all are kept and tried again at the next launch (better keep extra than lose any). +static void take_conflicts(NSString *save) { + NSFileManager *fm = NSFileManager.defaultManager; + for (NSString *f in [fm contentsOfDirectoryAtPath:g_cloud error:nil] ?: @[]) { + if ([f hasPrefix:@"."] || ![f hasSuffix:@".pack"]) continue; + NSURL *u = [NSURL fileURLWithPath:[g_cloud stringByAppendingPathComponent:f]]; NSArray *vs = [NSFileVersion unresolvedConflictVersionsOfItemAtURL:u]; + if (!vs.count) continue; + NSString *unit = f.stringByDeletingPathExtension; int bad = 0; + if ([unit isEqualToString:@"_stash"]) { for (NSFileVersion *v in vs) bad |= dm_cloud_inbox_add(save.fileSystemRepresentation, g_state.fileSystemRepresentation, v.URL.fileSystemRepresentation) != 0; } + else { uint64_t best = dm_cloud_pack_stamp(u.fileSystemRepresentation); NSFileVersion *win = nil; + for (NSFileVersion *v in vs) { uint64_t t = dm_cloud_pack_stamp(v.URL.fileSystemRepresentation); if (t > best) { best = t; win = v; } } + if (win) { NSError *e = nil; bad |= dm_cloud_bak_pack(g_bak.fileSystemRepresentation, unit.UTF8String, u.fileSystemRepresentation, "iCloud 冲突里较旧的现行版") != 0; + if (!bad && ![win replaceItemAtURL:u options:0 error:&e]) { bad = 1; LOG("【红】iCloud 同步:%s 换上较新的冲突版本失败 %s", unit.UTF8String, e.localizedDescription.UTF8String ?: "?"); } } + for (NSFileVersion *v in vs) if (v != win) bad |= dm_cloud_bak_pack(g_bak.fileSystemRepresentation, unit.UTF8String, v.URL.fileSystemRepresentation, "iCloud 冲突版本") != 0; + if (!bad) dm_cloud_char_conflict_note(unit.UTF8String); } + if (bad) { LOG("【红】iCloud 同步:%s 有 %lu 个冲突版本没收好,留着下次启动再来", unit.UTF8String, (unsigned long)vs.count); continue; } + for (NSFileVersion *v in vs) v.resolved = YES; + NSError *e = nil; if (![NSFileVersion removeOtherVersionsOfItemAtURL:u error:&e]) LOG("iCloud 同步:%s 冲突已标解决,删其余版本没成(%s),不影响", unit.UTF8String, e.localizedDescription.UTF8String ?: "?"); + LOG("iCloud 同步:%s 的 %lu 个 iCloud 冲突版本已收好(%s)", unit.UTF8String, (unsigned long)vs.count, [unit isEqualToString:@"_stash"] ? "进待合并收件箱" : "最新的当现行版、其余进备份"); + } +} static int run_sync(NSString *save, int down) { // 在文件协调里做:iCloud 守护进程同时在写这个目录时不会读到半个文件 | Done inside file coordination: half-written files are not read while the iCloud daemon is writing this directory at the same time __block int r = -1; NSError *err = nil; [[[NSFileCoordinator alloc] initWithFilePresenter:nil] coordinateWritingItemAtURL:[NSURL fileURLWithPath:g_cloud] options:NSFileCoordinatorWritingForMerging error:&err byAccessor:^(NSURL *u) { - (void)u; r = dm_cloud_sync(save.fileSystemRepresentation, g_cloud.fileSystemRepresentation, g_bak.fileSystemRepresentation, g_state.fileSystemRepresentation, down, now_ms(), pack_ready); }]; + (void)u; if (down) take_conflicts(save); // 只在启动那次(运行中 save 是提交快照目录,不放收件箱) | only at launch (while running, save is the commit snapshot directory; nothing goes into the inbox) + r = dm_cloud_sync(save.fileSystemRepresentation, g_cloud.fileSystemRepresentation, g_bak.fileSystemRepresentation, g_state.fileSystemRepresentation, down, now_ms(), pack_ready); }]; if (err) LOG("【红】iCloud 同步:文件协调失败 %s", err.localizedDescription.UTF8String); return r; } @@ -187,6 +219,51 @@ static int migrate_v2(NSString *docs, double deadline) { LOG("【红】iCloud 同步:旧目录 saves 复制到 saves_v2 失败(%s),本次不同步", (err ?: e2).localizedDescription.UTF8String ?: "?"); return 0; } LOG("iCloud 同步:旧目录 saves 已复制到 saves_v2(%d 个文件,清单 %lu 个包),旧目录留给旧包用", copied, (unsigned long)[list componentsSeparatedByString:@"\n"].count - 1); return 1; } +// 从没同步成功过的设备先看清云端再同步(iCloud 离线冲突第 2 条):新设备断网首启时,系统还没把云端条目列到本机,云端目录看着是空的—— +// 照常同步会把本机全部当「云端没有」上传(离线时新建的穷共享仓库联网后与云端同名包冲突、盖掉云端),迁移那步还会新建一个空的 saves_v2。 +// 所以状态文件里一条记录都没有(从没同步成功过)时,先问系统的云端条目列表(NSMetadataQuery,收集完成才算数): +// 列出了包 → 这些包都已出现在本机目录(下好的或 iCloud 占位)才同步;列表是空的 → 网络通才同步(世界上第一台设备就是这种)。都不满足 = 本次整套跳过,下次启动再看。 +// 列表收集完成在断网时怎么表现、联网时空列表会不会滞后,要真机断网跑才知道(排给池);滞后漏过去的那种由冲突版本合并兜住(第 1 条)。 +// 测试开关 DM_TEST_ICLOUD_FIRST=<收集完成>,<列出几个>,<到本机几个>,<网络通>:不问系统,按给的值判(Mac 宿主 / 本地测试云端验分支用) +// A device that has never synced successfully first gets a clear view of the cloud before syncing (iCloud offline conflict item 2): on a new device's first launch without network, the system has not yet listed the cloud entries locally, so the cloud directory looks empty - +// a normal sync would upload everything local as "not in the cloud" (a poor shared stash newly created offline conflicts with the cloud's same-name pack once online and overwrites the cloud), and the migration step would also create an empty saves_v2. +// So when the state file has no record at all (never synced successfully), first ask the system for its list of cloud entries (NSMetadataQuery, counted only once gathering has finished): +// packs are listed -> sync only once all of them have appeared in the local directory (downloaded or as iCloud placeholders); the list is empty -> sync only if the network is reachable (the very first device in the world is like this). Neither = skip the whole thing this time and look again at the next launch. +// How gathering completes with no network, and whether an empty list can lag behind when online, can only be known by running on a device with the network cut (queued for the pool); the lagging case that slips through is covered by merging conflict versions (item 1). +// Test switch DM_TEST_ICLOUD_FIRST=,,,: does not ask the system and decides by the given values (for verifying the branches on the Mac host / a local test cloud) +static int never_synced(NSString *statef) { + NSString *t = [NSString stringWithContentsOfFile:statef encoding:NSUTF8StringEncoding error:nil]; + return !t || [t rangeOfString:@"\t"].location == NSNotFound; +} +static int first_listing_ok(double deadline) { + int got = 0, listed = 0, present = 0, net = 0; const char *e = getenv("DM_TEST_ICLOUD_FIRST"); + if (e) { sscanf(e, "%d,%d,%d,%d", &got, &listed, &present, &net); } + else { + __block int g = 0, n = 0, pr = 0; dispatch_semaphore_t sem = dispatch_semaphore_create(0); __block NSMetadataQuery *q = nil; __block id obs = nil; + dispatch_async(dispatch_get_main_queue(), ^{ // 元数据查询要挂在有运行循环的线程上 | the metadata query has to be attached to a thread with a run loop + q = [NSMetadataQuery new]; q.searchScopes = @[NSMetadataQueryUbiquitousDocumentsScope]; + q.predicate = [NSPredicate predicateWithFormat:@"%K LIKE '*.pack'", NSMetadataItemFSNameKey]; + obs = [NSNotificationCenter.defaultCenter addObserverForName:NSMetadataQueryDidFinishGatheringNotification object:q queue:nil usingBlock:^(NSNotification *note) { (void)note; + [q disableUpdates]; n = (int)q.resultCount; NSFileManager *fm = NSFileManager.defaultManager; + for (NSUInteger i = 0; i < q.resultCount; i++) { NSURL *u = [[q resultAtIndex:i] valueForAttribute:NSMetadataItemURLKey]; if (!u) continue; + NSString *ph = [u.path.stringByDeletingLastPathComponent stringByAppendingPathComponent:[NSString stringWithFormat:@".%@.icloud", u.lastPathComponent]]; + if ([fm fileExistsAtPath:u.path] || [fm fileExistsAtPath:ph]) pr++; } + g = 1; [q stopQuery]; [NSNotificationCenter.defaultCenter removeObserver:obs]; dispatch_semaphore_signal(sem); }]; + if (![q startQuery]) { [NSNotificationCenter.defaultCenter removeObserver:obs]; dispatch_semaphore_signal(sem); } }); + double left = deadline - CFAbsoluteTimeGetCurrent(); if (left < 0.5) left = 0.5; + if (dispatch_semaphore_wait(sem, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(left * NSEC_PER_SEC)))) + dispatch_async(dispatch_get_main_queue(), ^{ if (q) { [q stopQuery]; if (obs) [NSNotificationCenter.defaultCenter removeObserver:obs]; } }); + got = g; listed = n; present = pr; + __block int ns = 0; dispatch_semaphore_t ps = dispatch_semaphore_create(0); nw_path_monitor_t m = nw_path_monitor_create(); + nw_path_monitor_set_queue(m, dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)); + nw_path_monitor_set_update_handler(m, ^(nw_path_t path) { if (!ns) { ns = nw_path_get_status(path) == nw_path_status_satisfied ? 1 : 2; dispatch_semaphore_signal(ps); } }); + nw_path_monitor_start(m); dispatch_semaphore_wait(ps, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(NSEC_PER_SEC))); nw_path_monitor_cancel(m); net = ns == 1; + } + int ok = got && (listed ? present >= listed : net); + LOG("iCloud 同步:本机从没同步成功过,先看云端条目列表:收集%s、列出 %d 个包、已到本机 %d 个、网络%s → %s", got ? "完成" : "未完成", listed, present, net ? "通" : "不通", + ok ? "看清了,同步" : "没看清,本次不同步(不上传、不建 saves_v2),下次启动再看"); + return ok; +} void dm_cloud_boot(void) { const char *sv = getenv("DM_SAVE"), *sub = getenv("DM_TEST_ICLOUD_SUB"), *ldir = getenv("DM_TEST_ICLOUD_DIR"), *lroot = getenv("DM_TEST_ICLOUD_ROOT"); if (!sv) return; NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject; @@ -215,6 +292,7 @@ void dm_cloud_boot(void) { if (ldir) g_cloud = test_path(ldir); // 测试:本地目录当云端(没有 iCloud 权限的开发包也能验整条链) | Test: use a local directory as the cloud (a dev build without iCloud entitlement can also verify the whole chain) else if (sub) { NSURL *ct = container(limit); if (!ct) return; g_cloud = [[ct.path stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@(sub)]; } else { NSString *docs = test_path(lroot); if (!lroot) { NSURL *ct = container(limit); if (!ct) return; docs = [ct.path stringByAppendingPathComponent:@"Documents"]; } + if (never_synced([save stringByAppendingString:@".cloudstate"]) && (!lroot || getenv("DM_TEST_ICLOUD_FIRST")) && !first_listing_ok(t0 + limit)) return; if (!migrate_v2(docs, t0 + limit)) return; NSString *nw = [docs stringByAppendingPathComponent:@"saves_v2"]; if (!v2_ready(nw, [save stringByAppendingString:@".cloudv2ok"])) return; g_cloud = nw; } diff --git a/dm/ios/Sources/dm_rift_hud.m b/dm/ios/Sources/dm_rift_hud.m index 5fb740d..888db03 100644 --- a/dm/ios/Sources/dm_rift_hud.m +++ b/dm/ios/Sources/dm_rift_hud.m @@ -75,7 +75,8 @@ void dm_rift_hud_draw(UIView *host, CGRect wr, BOOL hide) { NSString *st = h.done ? (h.inc ? [NSString stringWithFormat:@(dm_ui("dmRiftHudDone")), h.tier] : [NSString stringWithFormat:@(dm_ui("dmRiftHudLate")), h.tier]) : g ? @(dm_ui("dmRiftHudGuard")) : [NSString stringWithFormat:@(dm_ui("dmRiftTierN")), h.tier]; set_text(sub, st, d2font(14 * u), white, CGRectMake(48 * u, 9 * u, 130 * u, 19 * u), kCAAlignmentLeft); set_text(timer, [NSString stringWithFormat:@"%d:%02d", s / 60, s % 60], d2font(17 * u), (s <= 60 && !h.done) ? red : gold, CGRectMake(W - 90 * u, 6 * u, 80 * u, 22 * u), kCAAlignmentRight); - NSString *gl = h.done ? (!h.inc ? @(dm_ui("dmRiftHudSame")) : h.next > h.tier ? [NSString stringWithFormat:@(dm_ui("dmRiftHudNext")), h.next] : @(dm_ui("dmRiftHudTop"))) : h.overtime ? @(dm_ui("dmRiftHudOver")) : g ? @(dm_ui("dmRiftHudKill")) : [NSString stringWithFormat:@(dm_ui("dmRiftHudGoal")), (int)(h.progress * 100)]; // 已超时:第二行换成这一句,优先于「击败守护者」/ 进度目标(第一行照旧写第几层 / 守护者现身) | overtime: the second line becomes this sentence, taking priority over "Slay the Rift Guardian" / the progress goal (the first line still says which level / that the Guardian has appeared) + NSString *gl = h.done ? (!h.inc ? @(dm_ui("dmRiftHudSame")) : h.next > h.tier ? [NSString stringWithFormat:@(dm_ui("dmRiftHudNext")), h.next] : @(dm_ui("dmRiftHudTop"))) : h.goal == 5 ? [NSString stringWithFormat:@(dm_ui("dmRiftHudOverKillN")), h.gdead, h.gtotal] : h.goal == 4 ? @(dm_ui("dmRiftHudOverKill")) : h.goal == 3 ? @(dm_ui("dmRiftHudOver")) + : (h.goal == 1 || h.goal == 2) && h.nwave > 1 ? [NSString stringWithFormat:@(dm_ui("dmRiftHudKillWave")), h.wave, h.nwave, h.gdead, h.gtotal] : h.goal == 2 ? [NSString stringWithFormat:@(dm_ui("dmRiftHudKillN")), h.gdead, h.gtotal] : h.goal == 1 ? @(dm_ui("dmRiftHudKill")) : [NSString stringWithFormat:@(dm_ui("dmRiftHudGoal")), (int)(h.progress * 100)]; // 已超时:第二行换成这一句,优先于「击败守护者」/ 进度目标(第一行照旧写第几层 / 守护者现身) | overtime: the second line becomes this sentence, taking priority over "Slay the Rift Guardian" / the progress goal (the first line still says which level / that the Guardian has appeared) set_text(goal, gl, d2font(12 * u), grey, CGRectMake(10 * u, 32 * u, W - 20 * u, 17 * u), kCAAlignmentLeft); CGRect tr = CGRectMake(11 * u, 55 * u, W - 22 * u, 10 * u); // 含 1 单位外框(条 8 + 外框各 1) // 进度条:外框暗边 + 深底,填充金褐(守护者转暗红),每 10% 一道刻痕,两端菱形钉 | Includes the 1-unit outer frame (bar 8 + frame 1 on each side) // Progress bar: dark-edged outer frame + deep background, golden-brown fill (turns dark red for the guardian), a notch every 10%, diamond studs at both ends track.frame = tr; track.backgroundColor = rgb(25, 20, 14, 1).CGColor; track.borderColor = rgb(95, 78, 48, 1).CGColor; track.borderWidth = MAX(1, u); diff --git a/dm/ios/Sources/dm_sharelog.m b/dm/ios/Sources/dm_sharelog.m index c48fe0c..215cba8 100644 --- a/dm/ios/Sources/dm_sharelog.m +++ b/dm/ios/Sources/dm_sharelog.m @@ -116,3 +116,4 @@ static void on_click(void) { // 宿主在游戏主线程调:玩家点了「 }); } void dm_sharelog_boot(void) { g_t0 = NSDate.date; dm_sharelog_init(on_click); } // main.m 起宿主前调一次 | main.m calls this once before starting the host +void dm_sharelog_share(void) { on_click(); } // 游戏外的界面直接调(资源下载页的「分享诊断日志」按钮,main.m AssetVC) | called directly from screens outside the game (the "Share diagnostic log" button on the asset download page, main.m AssetVC) 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 75aaafa..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 @@ -739,6 +796,14 @@ static void run_boot(void); @property (strong) UILabel *label; @property (strong) UIProgressView *bar; @property (strong) UIButton *retry; @property (assign) int64_t last; @property (assign) CFAbsoluteTime lastT; @property (assign) double rate; @property (strong) nw_path_monitor_t netmon; @property (assign) int netDown, stopped; // 守着网络:停在「下载没开始」那一页时,网络从不通变成通就自己重试 | network watch: while sitting on the "download did not start" page, retry automatically when the network goes from down to up +// 托管下载(TestFlight):进度到 100% 之后系统还要把资源包装进本地(头文件:完成通知 = 下完且本地可用),这段不给进度;完成回调 / 通知不来就会一直停在进度字上(线上玩家卡 10 分钟)。 +// 所以守着系统的「本地可用」状态自己轮询(5 秒一次、30 秒记一行日志),到了就进游戏,不只等回调;100% 后屏上说明在安装、空间不够写清差多少; +// 安装超时 / 暂停 / 报错时给「改用直接下载」(走下载站那条路,包里配了下载地址才给)。packFull = 进度到 100% 的时刻,gone = 已改走直接下载(之后托管的回调只记日志) +// Hosted download (TestFlight): after progress reaches 100% the system still has to install the asset pack locally (header: completion notification = downloaded and available locally), and gives no progress for that part; if the completion callback / notification does not come, the screen stays on the progress text forever (players in the field were stuck for 10 minutes). +// So we watch the system's "available locally" state and poll it ourselves (every 5 seconds, a log line every 30 seconds) and enter the game when it is reached, instead of only waiting for the callback; after 100% the screen explains that it is installing, and if space is short it says by how much; +// on install timeout / pause / error it offers "Use direct download" (the download-site path, only offered if the package has a download address configured). packFull = the moment progress reached 100%, gone = already switched to direct download (after that, callbacks from the hosted download are only logged) +@property (strong) UIButton *useDirect, *share; @property (strong) dispatch_source_t poll; @property (assign) CFAbsoluteTime packT, packFull, logT, testAvailAt; +@property (assign) int64_t packBytes, packDone; @property (assign) int gone, slowShown, finished, textKind, packStop; // packStop:系统报了暂停 / 失败,屏上留那条说明,不再换回「正在安装」 | packStop: the system reported paused / failed; the screen keeps that explanation and does not switch back to "Installing" @end @implementation AssetVC - (void)netUp { if (self.netDown && self.stopped) { plog("assets: 网络通了,自动重试"); self.netDown = 0; [self start]; } else self.netDown = 0; } @@ -765,24 +830,108 @@ static void run_boot(void); self.retry = [UIButton buttonWithType:UIButtonTypeSystem]; self.retry.frame = CGRectMake(b.size.width / 2 - 60, b.size.height / 2 + 50, 120, 44); [self.retry setTitle:T("dmDlRetry") forState:UIControlStateNormal]; self.retry.hidden = YES; self.retry.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin; [self.retry addTarget:self action:@selector(start) forControlEvents:UIControlEventTouchUpInside]; - [self.view addSubview:self.label]; [self.view addSubview:self.bar]; [self.view addSubview:self.retry]; + self.useDirect = [UIButton buttonWithType:UIButtonTypeSystem]; [self.useDirect setTitle:T("dmDlUseDirect") forState:UIControlStateNormal]; self.useDirect.hidden = YES; + [self.useDirect addTarget:self action:@selector(useDirectTap) forControlEvents:UIControlEventTouchUpInside]; + self.share = [UIButton buttonWithType:UIButtonTypeSystem]; [self.share setTitle:T("dmPauseShareLog") forState:UIControlStateNormal]; self.share.hidden = YES; + [self.share addTarget:self action:@selector(shareTap) forControlEvents:UIControlEventTouchUpInside]; + [self.view addSubview:self.label]; [self.view addSubview:self.bar]; [self.view addSubview:self.retry]; [self.view addSubview:self.useDirect]; [self.view addSubview:self.share]; UIApplication.sharedApplication.idleTimerDisabled = YES; [self watchNet]; [self start]; } +- (void)viewDidLayoutSubviews { // 按钮一行居中排:重试 / 改用直接下载 / 分享诊断日志,只排露出来的 | buttons centred in one row: Retry / Use direct download / Share diagnostic log, only the ones showing + [super viewDidLayoutSubviews]; CGRect b = self.view.bounds; NSMutableArray *row = [NSMutableArray array]; CGFloat w = 0; + for (UIButton *x in @[self.retry, self.useDirect, self.share]) if (!x.hidden) { [x sizeToFit]; [row addObject:x]; w += MAX(120, x.bounds.size.width + 24) + (row.count > 1 ? 16 : 0); } + CGFloat x0 = (b.size.width - w) / 2; + for (UIButton *x in row) { CGFloat bw = MAX(120, x.bounds.size.width + 24); x.frame = CGRectMake(x0, b.size.height / 2 + 50, bw, 44); x0 += bw + 16; } +} +- (void)showBtn:(UIButton *)x { dispatch_async(dispatch_get_main_queue(), ^{ x.hidden = NO; [self.view setNeedsLayout]; }); } +- (void)shareTap { plog("assets: 玩家点了分享诊断日志"); void dm_sharelog_share(void); dm_sharelog_share(); } +- (void)useDirectTap { + plog("assets: 玩家点了改用直接下载(托管已等 %.0f 秒,进度 %.2f / %.2f GB%s)", CFAbsoluteTimeGetCurrent() - self.packT, self.packDone / 1e9, self.packBytes / 1e9, self.packFull ? ",已到 100%" : ""); + self.gone = 1; if (self.poll) { dispatch_source_cancel(self.poll); self.poll = nil; } + self.useDirect.hidden = YES; [self.view setNeedsLayout]; [self direct:nil]; +} +- (void)offerDirect:(int)why { // 托管那条路走不下去时给玩家另一条(why:1 安装超时、2 暂停、3 报错):包里没配下载地址(照公开仓库出的包)就不给,只记日志 | when the hosted path cannot go on, give the player another path (why: 1 install timeout, 2 paused, 3 error): if the package has no download address configured (packages built from the public repository), it is not offered, only logged + if (self.gone) return; + if (!res_dl_configured()) { static int lg; if (!lg++) plog("assets: 托管走不下去(%d:1 安装超时 2 暂停 3 报错),但本包没配资源下载地址,不给「改用直接下载」", why); return; } + plog("assets: 托管走不下去(%d:1 安装超时 2 暂停 3 报错)→ 露出「改用直接下载」", why); [self showBtn:self.useDirect]; [self showBtn:self.share]; +} +static double slow_s(void) { const char *t = getenv("DM_TEST_BA_SLOW"); return t ? atof(t) : 300; } // 100% 后等系统装进本地多久算慢(头文件只说完成通知 = 本地可用,中间要多久没写;给 5 分钟);测试开关缩短 | how long to wait after 100% for the system to install it locally before it counts as slow (the header only says the completion notification = available locally, not how long it takes in between; 5 minutes is given); a test switch shortens it +static int64_t free_bytes(void) { // 给 App 用的可用空间(系统「重要用途」口径,同设置里显示的);测试开关 DM_TEST_BA_FREE= 造空间不够 | free space available to the App (the system's "important usage" measure, the same as shown in Settings); test switch DM_TEST_BA_FREE= stages not enough space + const char *t = getenv("DM_TEST_BA_FREE"); if (t) return (int64_t)(atof(t) * 1e9); + NSURL *u = [NSURL fileURLWithPath:NSHomeDirectory()]; NSNumber *v = nil; [u getResourceValue:&v forKey:NSURLVolumeAvailableCapacityForImportantUsageKey error:nil]; return v.longLongValue; +} +- (BOOL)packAvail { + if (getenv("DM_TEST_BA")) return self.testAvailAt > 0 && CFAbsoluteTimeGetCurrent() >= self.testAvailAt; + if (@available(iOS 26.4, *)) return [BAAssetPackManager.sharedManager assetPackIsAvailableLocallyWithIdentifier:@"romfs"]; + return NO; +} +- (void)logPack:(BOOL)avail free:(int64_t)fr { + CFAbsoluteTime now = CFAbsoluteTimeGetCurrent(); double w = now - self.packT, f = self.packFull ? now - self.packFull : -1, d = self.packDone / 1e9, t = self.packBytes / 1e9, g = fr / 1e9; int a = avail; + if (getenv("DM_TEST_BA")) { plog("assets: 托管状态(测试现场):已等 %.0f 秒,进度 %.2f / %.2f GB(100%% 后 %.0f 秒,-1 = 没到),系统说本地可用 %d,可用空间 %.2f GB", w, d, t, f, a, g); return; } + if (@available(iOS 26.4, *)) { + [BAAssetPackManager.sharedManager getLocalStatusOfAssetPackWithIdentifier:@"romfs" completionHandler:^(BAAssetPackStatus st) { + plog("assets: 托管状态:已等 %.0f 秒,进度 %.2f / %.2f GB(100%% 后 %.0f 秒,-1 = 没到),系统说本地可用 %d,可用空间 %.2f GB;系统状态位 0x%lx(1 可下载 2 有更新 4 最新 8 过期 0x10 已撤 0x20 下载中 0x40 已下完)", + w, d, t, f, a, g, (unsigned long)st); }]; + } else plog("assets: 托管状态:已等 %.0f 秒,进度 %.2f / %.2f GB(100%% 后 %.0f 秒,-1 = 没到),系统说本地可用 %d,可用空间 %.2f GB", w, d, t, f, a, g); +} +- (void)packText:(int64_t)fr { // 100% 之后屏上那段:空间不够 > 超时 > 正在安装 | the passage on screen after 100%: not enough space > timeout > installing + NSString *dev = UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad ? @"iPad" : @"iPhone"; + int k = self.packBytes > 0 && fr < self.packBytes ? 3 : self.slowShown ? 2 : 1; + NSString *t = k == 3 ? [NSString stringWithFormat:T("dmDlInstallSpace"), self.packBytes / 1e9, dev, fr / 1e9, (self.packBytes - fr) / 1e9, dev] + : k == 2 ? [NSString stringWithFormat:T(res_dl_configured() ? "dmDlPackSlow" : "dmDlPackSlowNoDl"), (int)MAX(1, lround(slow_s() / 60))] // 没配下载地址就没有「改用直接下载」按钮,文字不提它 | with no download address configured there is no "Use direct download" button, and the text does not mention it + : [NSString stringWithFormat:T("dmDlInstalling"), self.packBytes / 1e9, fr / 1e9]; + if (k != self.textKind) { self.textKind = k; [self say:t]; } // 换了一种说法才进日志;只是空间数字变了就只改屏上的字 | only goes into the log when the wording changes; if only the space numbers changed, just update the text on screen + else if (![self.label.text isEqualToString:t]) dispatch_async(dispatch_get_main_queue(), ^{ self.label.text = t; }); +} +- (void)pollPack { + if (self.gone) return; + CFAbsoluteTime now = CFAbsoluteTimeGetCurrent(); BOOL avail = [self packAvail]; int64_t fr = free_bytes(); + if (now - self.logT >= 30) { self.logT = now; [self logPack:avail free:fr]; } + if (avail) { plog("assets: 轮询:系统说资源包本地可用(完成回调%s)→ 进游戏", self.finished ? "也到了" : "没到"); [self ready]; return; } + if (!self.packFull || self.packStop) return; + if (!self.slowShown && now - self.packFull >= slow_s()) { self.slowShown = 1; plog("assets: 进度 100%% 后 %.0f 秒系统仍没装好", now - self.packFull); [self offerDirect:1]; } + [self packText:fr]; +} +- (void)watchPack { // 托管下载开始后:守着系统状态(主线程定时器) | after the hosted download starts: watch the system state (main-thread timer) + if (self.poll) return; self.packT = CFAbsoluteTimeGetCurrent(); self.logT = 0; + dispatch_source_t s = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue()); self.poll = s; __weak AssetVC *w = self; + dispatch_source_set_timer(s, dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC), 5 * NSEC_PER_SEC, NSEC_PER_SEC / 2); + dispatch_source_set_event_handler(s, ^{ [w pollPack]; }); dispatch_resume(s); +} +// 测试开关 DM_TEST_BA=finish|late|silent|fail(Mac 上的 iOS 包造托管下载现场,资源其实在本地):3 秒内假进度走到 100%,之后—— +// finish 再 3 秒送完成通知;late 什么都不来(配 DM_TEST_BA_SLOW=<秒> 看超时);silent 不送通知、8 秒后「系统说本地可用」(看轮询自愈);fail 送下载失败。 +// DM_TEST_BA_TAP=<秒>:到点替玩家点「改用直接下载」(按钮没露出来就报红) +// Test switch DM_TEST_BA=finish|late|silent|fail (stages a hosted download scene for the iOS package on the Mac, the resources are actually local): fake progress goes to 100% within 3 seconds, then - +// finish sends the completion notification 3 seconds later; late sends nothing (with DM_TEST_BA_SLOW= to see the timeout); silent sends no notification and "the system says it is available locally" after 8 seconds (to see polling recover); fail sends a download failure. +// DM_TEST_BA_TAP=: at that time, taps "Use direct download" for the player (reports red if the button is not showing) +- (void)fakeBA:(NSString *)sc API_AVAILABLE(ios(26.0)) { + plog("assets: 测试现场 DM_TEST_BA=%s", sc.UTF8String); self.packBytes = 4130000000LL; [self watchPack]; [self say:T("dmDlDownloading")]; + NSProgress *g = [NSProgress progressWithTotalUnitCount:self.packBytes]; BAAssetPack *np = nil; + for (int i = 1; i <= 10; i++) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(i * 0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ g.completedUnitCount = self.packBytes * i / 10; [self downloadOfAssetPack:np hasProgress:g]; }); + if ([sc isEqualToString:@"silent"]) self.testAvailAt = CFAbsoluteTimeGetCurrent() + 11; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 6 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ + if ([sc isEqualToString:@"finish"]) [self downloadOfAssetPackFinished:np]; + if ([sc isEqualToString:@"fail"]) [self downloadOfAssetPack:np failedWithError:[NSError errorWithDomain:@"DmTestBA" code:1 userInfo:@{NSLocalizedDescriptionKey: @"test failure"}]]; }); + const char *tp = getenv("DM_TEST_BA_TAP"); if (tp) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(atof(tp) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + if (self.useDirect.hidden) plog("【红】DM_TEST_BA_TAP:「改用直接下载」没露出来"); else [self useDirectTap]; }); +} - (void)say:(NSString *)t { plog("assets: %s", t.UTF8String); dispatch_async(dispatch_get_main_queue(), ^{ self.label.text = t; }); } - (void)fail:(NSString *)what error:(NSError *)e { // 直装包没有托管资源,这条路必然失败:报错只进日志,界面给玩家能照做的指引 // A direct-install build has no hosted assets, so this path always fails: the error goes only to the log, and the screen gives the player instructions they can follow plog("assets: %s失败:%s(%s %ld)", what.UTF8String, e.localizedDescription.UTF8String, e.domain.UTF8String, (long)e.code); [self say:no_assets_text()]; - dispatch_async(dispatch_get_main_queue(), ^{ self.retry.hidden = NO; }); + [self showBtn:self.retry]; } - (void)start { - self.retry.hidden = YES; self.stopped = 0; self.last = 0; self.lastT = CFAbsoluteTimeGetCurrent(); + self.retry.hidden = YES; self.stopped = 0; self.last = 0; self.lastT = CFAbsoluteTimeGetCurrent(); self.packStop = 0; self.textKind = 0; char why[2048]; + if (getenv("DM_TEST_BA") && !self.gone) { if (@available(iOS 26.0, *)) [self fakeBA:@(getenv("DM_TEST_BA"))]; return; } // 测试:造托管下载现场(fakeBA) | test: stage a hosted download scene (fakeBA) if (!getenv("DM_ASSETS_TEST") && romfs_locate(why, sizeof why)) { [self ready]; return; } // 重试时资源已到(如刚在「文件」里拷完) | Assets have already arrived on retry (e.g. just finished copying in the Files app) if (!getenv("DM_ASSETS_TEST") && g_doc_bad) { [self direct:@(why)]; return; } // 有文件夹但不完整(拷到一半 / 下到一半):不试托管下载,直接从下载站补齐;下载站走不通才报原因 | A folder exists but is incomplete (half copied / half downloaded): do not try the hosted download, fill in the rest straight from the download site; report the reason only if the download site is unreachable + if (self.gone) { [self direct:nil]; return; } // 玩家已选「改用直接下载」:重试仍走这条(托管的回调此后不接,回到托管会停在「正在下载」) | the player chose "Use direct download": retries keep going this way (callbacks from the hosted download are not taken from now on; going back to hosted would stay stuck at "Downloading") NSString *stray = !getenv("DM_ASSETS_TEST") && g_doc_stray ? @(why) : nil; // 「D2R Mobile」里有文件夹但都不是资源:托管下载、下载站都走不通时给玩家看这条 | 「D2R Mobile」 has folders but none of them is assets: show the player this message when neither the hosted download nor the download site works if (getenv("DM_ROMFS_TEST_PACK")) { [self ready]; return; } // 只测试用:托管资源包「下完了」但不合格的现场 | Test only: the scenario where the managed asset pack has "finished downloading" but does not pass validation if (getenv("DM_ASSETS_TEST") && !strcmp(getenv("DM_ASSETS_TEST"), "direct")) { [self direct:nil]; return; } // 测试:资源在本地也走真正的直接下载准备(联网取清单、盘点、查空间),配 DM_ASSET_FREE_TEST 造空间不够 | Test: with assets local, still go through the real direct-download preparation (fetch the manifest over the network, take inventory, check space); pair with DM_ASSET_FREE_TEST to fake insufficient space @@ -798,8 +947,11 @@ static void run_boot(void); [m getAssetPackWithIdentifier:@"romfs" completionHandler:^(BAAssetPack *pack, NSError *e) { if (!pack) { plog("assets: 没有托管资源包(%s),改从下载站直接下", e.localizedDescription.UTF8String); dispatch_async(dispatch_get_main_queue(), ^{ [self direct:stray]; }); return; } // 直装包走到这里必然失败 | A direct-install build always fails when it gets here [self say:T("dmDlDownloading")]; + plog("assets: 托管资源包 版本 %ld、%.2f GB,请系统确保本地可用(可用空间 %.2f GB)", (long)pack.version, pack.downloadSize / 1e9, free_bytes() / 1e9); + dispatch_async(dispatch_get_main_queue(), ^{ self.packBytes = pack.downloadSize; [self watchPack]; }); [m ensureLocalAvailabilityOfAssetPack:pack completionHandler:^(NSError *e2) { - if (e2) { [self fail:@"下载游戏资源" error:e2]; return; } + if (e2) { self.packStop = 1; [self fail:@"下载游戏资源" error:e2]; [self offerDirect:3]; return; } + plog("assets: 系统「确保本地可用」完成回调到了"); dispatch_async(dispatch_get_main_queue(), ^{ [self ready]; }); }]; }]; @@ -809,7 +961,7 @@ static void run_boot(void); // Direct-install build: download the assets straight from our own download site into Documents/D2R Mobile Resources (asset_dl.m). When the download site is unreachable the screen falls back to the original instructions (or the reason given by fallback) - (void)direct:(NSString *)fallback { if (!res_dl_configured()) { // 这个包没配下载地址(照公开仓库自己出的包):不去连、不说「下载没开始」,只讲把资源拷进来 | This build has no download address configured (a build made by yourself from the public repository): do not connect, do not say "the download has not started", only explain how to copy the resources in - plog("assets: 本包没配资源下载地址,不走下载"); [self say:fallback ? [NSString stringWithFormat:@"%@\n%@", fallback, T("dmDlCopyInShort")] : no_assets_text()]; self.bar.hidden = YES; self.retry.hidden = NO; self.stopped = 1; return; } // 这条路没有进度可报:不留一条空的进度条 | nothing to report progress on along this path: do not leave an empty progress bar + plog("assets: 本包没配资源下载地址,不走下载"); [self say:fallback ? [NSString stringWithFormat:@"%@\n%@", fallback, T("dmDlCopyInShort")] : no_assets_text()]; self.bar.hidden = YES; [self showBtn:self.retry]; self.stopped = 1; return; } // 这条路没有进度可报:不留一条空的进度条 | nothing to report progress on along this path: do not leave an empty progress bar [self say:T("dmDlConnecting")]; [DmAssetDL.shared prepare:^(NSString *err, int64_t remain, int64_t total, BOOL cellular) { if (err && DmAssetDL.shared.shortBytes > 0) { // 设备空间不够(原先只进日志、界面显示的是「先从内测页下载资源包」,跟真实原因无关):系统提示写清还差多少 | Not enough space on the device (previously this only went to the log and the screen showed 「先从内测页下载资源包」(First download the asset pack from the beta page), unrelated to the real cause): the system prompt states exactly how much is missing @@ -817,7 +969,7 @@ static void run_boot(void); NSString *dev = UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad ? @"iPad" : @"iPhone"; // 按设备写 | Wording depends on the device NSString *m = [NSString stringWithFormat:T("dmDlSpaceMsg"), DmAssetDL.shared.shortBytes / 1e9, remain / 1e9, dev, DmAssetDL.shared.freeBytes / 1e9, dev]; NSString *title = [NSString stringWithFormat:T("dmDlSpaceTitle"), dev]; - [self say:[[title stringByAppendingString:@"\n"] stringByAppendingString:m]]; self.retry.hidden = NO; + [self say:[[title stringByAppendingString:@"\n"] stringByAppendingString:m]]; [self showBtn:self.retry]; UIAlertController *a = [UIAlertController alertControllerWithTitle:title message:m preferredStyle:UIAlertControllerStyleAlert]; [a addAction:[UIAlertAction actionWithTitle:T("dmOk") style:UIAlertActionStyleDefault handler:nil]]; [self presentViewController:a animated:YES completion:^{ plog("assets: 已弹系统提示「%s」|正文:%s", title.UTF8String, [m stringByReplacingOccurrencesOfString:@"\n" withString:@" ⏎ "].UTF8String); }]; return; } @@ -829,7 +981,7 @@ static void run_boot(void); if (err) { // 下载没开始:屏上写真实原因和下一步,不落回「还没有游戏资源」(没网时玩家看到的是「没有资源」,不知道是网络、也不知道能重试) | download did not start: show the real reason and the next step on screen instead of falling back to "no game assets yet" (with no network the player saw "no assets", not knowing it was the network or that a retry was possible) plog("assets: 直接下载走不了:%s", err.UTF8String); [self say:[NSString stringWithFormat:T("dmDlNotStarted"), fallback ? [fallback stringByAppendingString:@"\n"] : @"", self.netDown ? T("dmDlNetDown") : err, self.netDown ? T("dmDlNextAuto") : T("dmDlNextRetry")]]; - self.retry.hidden = NO; self.stopped = 1; return; } + [self showBtn:self.retry]; self.stopped = 1; return; } void (^go)(void) = ^{ [self say:[NSString stringWithFormat:T("dmDlWill"), remain < 100000000 ? [NSString stringWithFormat:@"%.0f MB", remain / 1e6] : [NSString stringWithFormat:@"%.1f GB", remain / 1e9], total / 1e9]]; // 自动开始的大下载,开始前先把要下多少写在屏上 | A large download that starts automatically: show on screen how much will be downloaded before it starts self.last = total - remain; self.lastT = CFAbsoluteTimeGetCurrent(); self.rate = 0; @@ -839,33 +991,45 @@ static void run_boot(void); self.label.text = [NSString stringWithFormat:@"正在下载游戏资源(共 %.1f GB)\n%.2f / %.2f GB(%.0f%%) %.1f MB/s%@", tot / 1e9, done / 1e9, tot / 1e9, tot ? 100.0 * done / tot : 0, self.rate / 1e6, note ? [@"\n" stringByAppendingString:note] : @""]; self.bar.progress = tot ? (float)done / tot : 0; } done:^(NSString *e2) { - if (e2) { [self say:[NSString stringWithFormat:T("dmDlStopped"), e2, self.last / 1e9, total / 1e9]]; self.retry.hidden = NO; self.stopped = 1; return; } + if (e2) { [self say:[NSString stringWithFormat:T("dmDlStopped"), e2, self.last / 1e9, total / 1e9]]; [self showBtn:self.retry]; self.stopped = 1; return; } [self ready]; }]; }; if (!cellular || remain <= 0) { go(); return; } UIAlertController *a = [UIAlertController alertControllerWithTitle:T("dmDlCellTitle") message:[NSString stringWithFormat:T("dmDlCellMsg"), remain / 1e9] preferredStyle:UIAlertControllerStyleAlert]; - [a addAction:[UIAlertAction actionWithTitle:T("dmDlCellLater") style:UIAlertActionStyleCancel handler:^(UIAlertAction *x) { [self say:T("dmDlCellWait")]; self.retry.hidden = NO; }]]; + [a addAction:[UIAlertAction actionWithTitle:T("dmDlCellLater") style:UIAlertActionStyleCancel handler:^(UIAlertAction *x) { [self say:T("dmDlCellWait")]; [self showBtn:self.retry]; }]]; [a addAction:[UIAlertAction actionWithTitle:T("dmDlCellGo") style:UIAlertActionStyleDefault handler:^(UIAlertAction *x) { plog("assets: 玩家同意用流量下载"); go(); }]]; [self presentViewController:a animated:YES completion:nil]; }]; } - (void)downloadOfAssetPack:(BAAssetPack *)p hasProgress:(NSProgress *)g API_AVAILABLE(ios(26.0)) { CFAbsoluteTime now = CFAbsoluteTimeGetCurrent(); int64_t done = g.completedUnitCount, total = g.totalUnitCount; + if (self.gone) return; // 已改走直接下载:屏上是那条路的进度 | already switched to direct download: the screen shows that path's progress + self.packDone = done; if (total > 0) self.packBytes = total; + if (total > 0 && done >= total) { // 到 100%:之后是系统装包,屏上改说明(进度字不再刷) | reached 100%: from here the system installs the pack, the screen switches to an explanation (the progress text is no longer updated) + if (!self.packFull) { self.packFull = now; plog("assets: 托管下载进度到 100%%(%.2f GB),等系统装进本地;可用空间 %.2f GB", total / 1e9, free_bytes() / 1e9); + dispatch_async(dispatch_get_main_queue(), ^{ self.bar.progress = 1; [self packText:free_bytes()]; [self showBtn:self.share]; }); } + return; } if (now - self.lastT >= 1.0) { self.rate = (done - self.last) / (now - self.lastT); self.last = done; self.lastT = now; } NSString *t = [NSString stringWithFormat:T("dmDlProgress"), done / 1e9, total / 1e9, total ? 100.0 * done / total : 0, self.rate / 1e6]; dispatch_async(dispatch_get_main_queue(), ^{ self.label.text = t; self.bar.progress = total ? (float)done / total : 0; }); } -- (void)downloadOfAssetPackFinished:(BAAssetPack *)p API_AVAILABLE(ios(26.0)) { plog("assets: 系统通知资源包下载完成"); dispatch_async(dispatch_get_main_queue(), ^{ [self ready]; }); } -- (void)downloadOfAssetPackPaused:(BAAssetPack *)p API_AVAILABLE(ios(26.0)) { [self say:T("dmDlPaused")]; } -- (void)downloadOfAssetPack:(BAAssetPack *)p failedWithError:(NSError *)e API_AVAILABLE(ios(26.0)) { [self fail:@"下载游戏资源" error:e]; } +- (void)downloadOfAssetPackBegan:(BAAssetPack *)p API_AVAILABLE(ios(26.0)) { plog("assets: 系统通知托管下载开始 / 继续"); self.packStop = 0; self.textKind = 0; } +- (void)downloadOfAssetPackFinished:(BAAssetPack *)p API_AVAILABLE(ios(26.0)) { + plog("assets: 系统通知资源包下载完成%s", self.gone ? "(已改走直接下载,不接)" : ""); if (self.gone) return; self.finished = 1; dispatch_async(dispatch_get_main_queue(), ^{ [self ready]; }); } +- (void)downloadOfAssetPackPaused:(BAAssetPack *)p API_AVAILABLE(ios(26.0)) { + plog("assets: 系统通知托管下载暂停%s", self.gone ? "(已改走直接下载)" : ""); if (self.gone) return; self.packStop = 1; [self say:T("dmDlPaused")]; [self offerDirect:2]; } +- (void)downloadOfAssetPack:(BAAssetPack *)p failedWithError:(NSError *)e API_AVAILABLE(ios(26.0)) { + if (self.gone) { plog("assets: 托管下载失败(已改走直接下载):%s", e.localizedDescription.UTF8String); return; } + self.packStop = 1; [self fail:@"下载游戏资源" error:e]; [self offerDirect:3]; } - (void)ready { char why[2048]; static int started; if (started) return; // 完成回调与系统的完成通知都会走到这里:只起一次 | Both the completion callback and the system's completion notification end up here: start only once if (!romfs_locate(why, sizeof why)) { - if (g_pack_wait) { [self say:T("dmDlPackWait")]; return; } // 等系统的完成通知(downloadOfAssetPackFinished)再来,不按时间等 | Come back when the system's completion notification (downloadOfAssetPackFinished) arrives; do not wait by time - [self say:[NSString stringWithFormat:T("dmDlNotReady"), @(why)]]; self.retry.hidden = NO; return; } - started = 1; + if (g_pack_wait) { if (!self.packFull) [self say:T("dmDlPackWait")]; return; } // 等系统说本地可用(完成通知或 pollPack 轮询到);100% 后屏上是 packText 那段 | waiting for the system to say it is available locally (the completion notification, or found by pollPack's polling); after 100% the screen shows the packText passage + if (self.poll) { plog("assets: 系统说可用但校验没过:%s", why); } + [self say:[NSString stringWithFormat:T("dmDlNotReady"), @(why)]]; [self showBtn:self.retry]; return; } + started = 1; if (self.poll) { dispatch_source_cancel(self.poll); self.poll = nil; } plog("assets: 资源就绪,就地起宿主"); g_need_assets = 0; self.view = front_ios_view(self.view.window.windowScene.coordinateSpace.bounds); @@ -902,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 @@ -920,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 @@ -1064,14 +1229,24 @@ 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) {} - else if (getenv("DM_ASSETS_TEST")) { g_need_assets = 1; plog("boot: DM_ASSETS_TEST——强制走资源下载界面再就地起宿主(测这条路径)"); } + 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); } } else metal_cache_report_and_clean(); diff --git a/dm/ios/project.yml b/dm/ios/project.yml index 67176f6..016aef5 100644 --- a/dm/ios/project.yml +++ b/dm/ios/project.yml @@ -95,6 +95,7 @@ targets: dependencies: - target: RomfsDownloader # 苹果托管资源包要求的下载扩展(系统缺省实现) | Download extension required by Apple-hosted asset packs (system default implementation) - sdk: BackgroundAssets.framework + - sdk: Network.framework # iCloud 首次同步看网络通不通(cloud_ios.m first_listing_ok) | iCloud first sync checks whether the network is reachable (cloud_ios.m first_listing_ok) settings: PRODUCT_BUNDLE_IDENTIFIER: ${DM_BUNDLE_ID} ENABLE_USER_SCRIPT_SANDBOXING: NO # 构建前脚本「从游戏文件生成资源」要读工程外的 RomFS(沙盒里读不到) | The pre-build script 「从游戏文件生成资源」(Generate assets from game files) needs to read the RomFS outside the project (unreadable inside the sandbox) diff --git a/dm/ios/run.sh b/dm/ios/run.sh index 3e20cfa..867218d 100755 --- a/dm/ios/run.sh +++ b/dm/ios/run.sh @@ -52,7 +52,7 @@ if [ "$1" = build ]; then mkdir -p Gen/msl && cp -cR "$MSL/b-$V" Gen/msl/ # 资源直接下载(直装包,Sources/asset_dl.m):地址文件列表(仓库里的 asset_pointers.txt)+ 出包时的缺省下载根地址(DM_ASSET_BASE,tools/adhoc.sh 传隧道地址;没传就不带) # Direct asset download (direct-install package, Sources/asset_dl.m): URL file list (asset_pointers.txt in the repository) + the default download root URL at packaging time (DM_ASSET_BASE; tools/adhoc.sh passes the tunnel URL; omitted if not passed) - cp asset_pointers.txt Gen/dm/; [ -n "${DM_ASSET_BASE:-}" ] && echo "$DM_ASSET_BASE" > Gen/dm/asset_base.txt + cp asset_pointers.txt Gen/dm/; if [ -n "${DM_ASSET_BASE:-}" ]; then echo "$DM_ASSET_BASE" > Gen/dm/asset_base.txt; else rm -f Gen/dm/asset_base.txt; fi # 没给就删掉上次的:生成物只跟本次输入走(原先只写不删,同一棵树先出带地址的包、再出不带的会沿用旧地址) | if not given, delete the previous one: the generated file follows only this run's input (it used to be written but never deleted, so building a package with an address and then one without in the same tree kept the old address) # 老机型补充包的自动下载根地址(DM_ASTC_PACK_BASE,<根>/manifest.json + <根>/data/…;没传 = 只能玩家用「文件」拷,见 Sources/asset_dl.m) # Root URL for automatic download of the Legacy Device Pack (DM_ASTC_PACK_BASE, /manifest.json + /data/...; not passed = players can only copy it with the Files app, see Sources/asset_dl.m) rm -f Gen/dm/astc_pack_base.txt; [ -n "${DM_ASTC_PACK_BASE:-}" ] && echo "$DM_ASTC_PACK_BASE" > Gen/dm/astc_pack_base.txt diff --git a/dm/ios/tests/t_touch_controls.c b/dm/ios/tests/t_touch_controls.c index 6f11f89..ce51f63 100644 --- a/dm/ios/tests/t_touch_controls.c +++ b/dm/ios/tests/t_touch_controls.c @@ -118,11 +118,11 @@ static void two_fingers_same_key(void) { } static void joystick_deadzone(void) { /* 浮动底盘。667×375(k = 1、安全区 0)手算:静止位 (max(90, 0+60)+30, 375−115) = (120, 260);起摇杆区 x < 667×0.40 = 266.8 且 y > 375×0.45 = 168.75; - 夹回 x ≥ 0+60 = 60、y ≤ 375−25−60 = 290。落在区里起手:圆心 = 落点,位移为零 + 夹回只为底盘整圈在屏内:x ≥ 60+8 = 68、y ≤ 375−60−8 = 307(不让安全区)。落在区里起手:圆心 = 落点,位移为零 Floating base. Worked by hand for 667x375 (k = 1, safe area 0): rest position (max(90, 0+60)+30, 375-115) = (120, 260); stick-start zone x < 667x0.40 = 266.8 and y > 375x0.45 = 168.75; - clamp x >= 0+60 = 60, y <= 375-25-60 = 290. Starting inside the zone: centre = touch point, zero displacement */ + clamping only keeps the whole base on screen: x >= 60+8 = 68, y <= 375-60-8 = 307 (not respecting the safe area). Starting inside the zone: centre = touch point, zero displacement */ dm_tc_state s; dm_tc_init(&s,667,375); NEAR(s.layout.joy_x,120,0.001); NEAR(s.layout.joy_y,260,0.001); - NEAR(s.layout.joy_zone_r,266.8,0.001); NEAR(s.layout.joy_zone_t,168.75,0.001); NEAR(s.layout.joy_min_x,60,0.001); NEAR(s.layout.joy_max_y,290,0.001); + NEAR(s.layout.joy_zone_r,266.8,0.001); NEAR(s.layout.joy_zone_t,168.75,0.001); NEAR(s.layout.joy_min_x,68,0.001); NEAR(s.layout.joy_max_y,307,0.001); dm_tc_begin(&s,0,90,275); CHECK(s.joy_slot==0); NEAR(s.joy_origin_x,90,0); NEAR(s.joy_origin_y,275,0); CHECK(s.lx==0 && s.ly==0); @@ -135,8 +135,15 @@ static void joystick_deadzone(void) { dm_tc_move(&s,0,600,200); CHECK(s.lx==DM_STICK_MAX && s.ly==0); NEAR(s.joy_origin_x,200,0); dm_tc_move(&s,0,200,25); CHECK(s.lx==0 && s.ly==DM_STICK_MAX); NEAR(s.joy_origin_y,200,0); dm_tc_end(&s,0); CHECK(s.joy_slot==-1 && s.lx==0 && s.ly==0); NEAR(s.layout.joy_x,120,0.001); - /* 贴左下角落指 (10,370):圆心夹回 (60,290),手指在圆心左下 (−50,−80),一落下就是左下满偏 | touching down against the bottom-left corner (10,370): the centre is clamped back to (60,290), the finger is at (-50,-80) to the lower left of the centre, so it is at full lower-left deflection the moment it lands */ - dm_tc_begin(&s,0,10,370); CHECK(s.joy_slot==0); NEAR(s.joy_origin_x,60,0); NEAR(s.joy_origin_y,290,0); CHECK(s.lx<0 && s.ly<0); dm_tc_end(&s,0); + /* 贴左下角落指 (10,370):底盘画在夹回后的 (68,307),轴值按手指相对落点算——落指那一下为 0;向右挪 6 点仍在死区;7 点起出值 (7−6)/54 × 32767 = 607; + 向右拖满 60 点 = 向右满偏(不是按底盘圆心算出来的「左下」)。底盘不跟手走 + touching down against the bottom-left corner (10,370): the base is drawn at the clamped (68,307), and the axes are computed from the finger relative to the touch point - 0 on touch-down; moving 6 points right is still inside the dead zone; from 7 points the output is (7-6)/54 x 32767 = 607; + dragging the full 60 points right = full right deflection (not the "down-left" one would get by computing from the base centre). The base does not follow the finger */ + dm_tc_begin(&s,0,10,370); CHECK(s.joy_slot==0); NEAR(s.joy_origin_x,68,0); NEAR(s.joy_origin_y,307,0); CHECK(s.lx==0 && s.ly==0); + dm_tc_move(&s,0,16,370); CHECK(s.lx==0 && s.ly==0); + dm_tc_move(&s,0,17,370); CHECK(abs(s.lx-607)<=1 && s.ly==0); + dm_tc_move(&s,0,70,370); CHECK(s.lx==DM_STICK_MAX && s.ly==0); NEAR(s.joy_origin_x,68,0); NEAR(s.joy_origin_y,307,0); + dm_tc_end(&s,0); dm_tc_begin(&s,0,266,169); CHECK(s.joy_slot==0); NEAR(s.joy_origin_x,266,0); NEAR(s.joy_origin_y,169,0); dm_tc_end(&s,0); /* 区的右上角以内 | just inside the zone's top-right corner */ /* 区外:不起摇杆,拖也不变成摇杆 | outside the zone: no stick starts, and dragging does not turn into a stick either */ dm_tc_begin(&s,0,267,275); CHECK(s.joy_slot==-1 && s.lx==0); dm_tc_end(&s,0); @@ -145,13 +152,31 @@ static void joystick_deadzone(void) { /* 区里很快原地松开的那一下兼作点击(落点记成点世界),按久了 / 拖开了的不算 | a quick release in place inside the zone doubles as a tap (the touch point is recorded as a world tap); held long / dragged away does not count */ { unsigned q = s.world_tap_seq; dm_tc_begin_at(&s,0,150,250,40.0); dm_tc_end_at(&s,0,40.1); CHECK(s.world_tap_seq==q+1); NEAR(s.world_tap_x,150,0); NEAR(s.world_tap_y,250,0); dm_tc_begin_at(&s,0,150,250,41.0); dm_tc_move_at(&s,0,200,250,41.05); dm_tc_end_at(&s,0,41.1); CHECK(s.world_tap_seq==q+1); } - /* 拖远了的摇杆手指被系统取消,0.2 秒后在离取消处 40 点的 (236,128) 重新落下((260,160) 偏 (−24,−32);已在起摇杆区上界 168.75 之外):接着当摇杆,圆心沿用取消前的 (90,275)、方向按旧圆心算;超时:不接 | the stick finger, dragged far away, is cancelled by the system and 0.2 s later touches down again at (236,128), 40 points from where it was cancelled ((260,160) offset by (-24,-32); already above the zone's upper bound 168.75): it continues as the stick, the centre stays at (90,275) from before the cancel and the direction is computed from the old centre; after the timeout: not continued */ + /* 拖远了的摇杆手指被系统取消,0.2 秒后在离取消处 40 点的 (236,128) 重新落下((260,160) 偏 (−24,−32);已在起摇杆区上界 168.75 之外):接着当摇杆,落点与底盘沿用取消前的 (90,275)、方向按旧落点算;超时:不接 | the stick finger, dragged far away, is cancelled by the system and 0.2 s later touches down again at (236,128), 40 points from where it was cancelled ((260,160) offset by (-24,-32); already above the zone's upper bound 168.75): it continues as the stick, the touch point and base stay at (90,275) from before the cancel and the direction is computed from the old touch point; after the timeout: not continued */ dm_tc_begin_at(&s,0,90,275,50.0); dm_tc_move_at(&s,0,260,160,50.2); CHECK(s.lx>0 && s.ly>0); dm_tc_cancel_finger(&s,0); CHECK(s.joy_slot==-1 && s.lx==0); dm_tc_begin_at(&s,1,236,128,50.4); CHECK(s.joy_slot==1 && s.lx>0 && s.ly>0); NEAR(s.joy_origin_x,90,0); NEAR(s.joy_origin_y,275,0); dm_tc_cancel_finger(&s,1); dm_tc_begin_at(&s,2,236,128,50.4+0.36); CHECK(s.joy_slot==-1); dm_tc_end_at(&s,2,51.5); /* 超过 0.35 秒、落点在区外 | beyond 0.35 s, touch point outside the zone */ - /* 取消后在区里别处重落(离取消处 140 点,不算接续):按新落点起一个新的,圆心 (265, min(300,290)) | after a cancel, touching down elsewhere in the zone (140 points from where it was cancelled, not a continuation): a new stick starts at the new touch point, centre (265, min(300,290)) */ + /* 取消后在区里别处重落(离取消处 140 点,不算接续):按新落点起一个新的,圆心 (265, min(300,307)) = (265,300),落指那一下轴为 0 | after a cancel, touching down elsewhere in the zone (140 points from where it was cancelled, not a continuation): a new stick starts at the new touch point, centre (265, min(300,307)) = (265,300), axes 0 on touch-down */ dm_tc_begin_at(&s,0,90,275,52.0); dm_tc_move_at(&s,0,260,160,52.2); dm_tc_cancel_finger(&s,0); - dm_tc_begin_at(&s,1,265,300,52.3); CHECK(s.joy_slot==1); NEAR(s.joy_origin_x,265,0); NEAR(s.joy_origin_y,290,0); dm_tc_end_at(&s,1,53.5); + dm_tc_begin_at(&s,1,265,300,52.3); CHECK(s.joy_slot==1); NEAR(s.joy_origin_x,265,0); NEAR(s.joy_origin_y,300,0); CHECK(s.lx==0 && s.ly==0); dm_tc_end_at(&s,1,53.5); +} +/* 956×440(k = 1)手算:夹回界 x ≥ 60+8 = 68、y ≤ 440−68 = 372,只决定底盘画在哪:(6,434) → (68,372);(60,400) → (68,372);(150,330) → 不夹。 + 三处落指那一下轴都为 0;各自向右、向上、向左上(45°)拖 60 点,轴值只看手指相对落点,三处完全相同: + 向右 (60,0) → (32767, 0);向上 (0,60) → (0, 32767);向左上 (−42.43, 42.43) → 斜向预修正后 (−1, 2)/√5 × 32767 = (−14654, 29308)(走出来的屏幕方向 = 手指方向,同 joystick_axes 那例)。 + 贴左下角时向左 / 向下拖不出 60 点(手指到屏幕边了)是物理限制,不在这里测 + Worked by hand for 956x440 (k = 1): clamp bounds x >= 60+8 = 68, y <= 440-68 = 372, which only decide where the base is drawn: (6,434) -> (68,372); (60,400) -> (68,372); (150,330) -> not clamped. + At all three touch points the axes are 0 on touch-down; dragging 60 points right, up and up-left (45 degrees) from each, the axes depend only on the finger relative to the touch point and are identical for all three: + right (60,0) -> (32767, 0); up (0,60) -> (0, 32767); up-left (-42.43, 42.43) -> after the diagonal pre-correction (-1, 2)/sqrt(5) x 32767 = (-14654, 29308) (the screen direction walked = the finger direction, as in the joystick_axes example). + Near the bottom-left corner a drag of 60 points to the left / downwards is not possible (the finger reaches the screen edge); that is a physical limit and not tested here */ +static void joystick_clamp_956(void) { + static const float at[3][4] = {{6, 434, 68, 372}, {60, 400, 68, 372}, {150, 330, 150, 330}}; + dm_tc_state s; dm_tc_init(&s,956,440); NEAR(s.layout.joy_min_x,68,0.001); NEAR(s.layout.joy_max_y,372,0.001); + for (int i = 0; i < 3; i++) { float x = at[i][0], y = at[i][1]; + dm_tc_begin(&s,0,x,y); NEAR(s.joy_origin_x,at[i][2],0); NEAR(s.joy_origin_y,at[i][3],0); CHECK(s.lx==0 && s.ly==0); + dm_tc_move(&s,0,x+60,y); CHECK(s.lx==DM_STICK_MAX && s.ly==0); + dm_tc_move(&s,0,x,y-60); CHECK(s.lx==0 && s.ly==DM_STICK_MAX); + dm_tc_move(&s,0,x-42.4264f,y-42.4264f); CHECK(abs(s.lx+14654)<=2 && abs(s.ly-29308)<=2); + NEAR(s.joy_origin_x,at[i][2],0); NEAR(s.joy_origin_y,at[i][3],0); dm_tc_end(&s,0); } } static void joystick_axes(void) { dm_tc_state s; dm_tc_init(&s,667,375); dm_tc_begin(&s,0,90,275); /* 圆心 90,275;下面各点 = 原用例整体平移 (−10, +75) | center 90,275; the points below = the original cases shifted as a whole by (−10, +75) */ @@ -437,7 +462,7 @@ static void safe_insets(void) { dm_tc_set_safe_insets(62, 62); dm_tc_layout_make(&b, 956, 440); dm_tc_set_safe_insets(0, 0); NEAR(a.target[DM_TC_MAIN].x, 900, 0.001); NEAR(b.target[DM_TC_MAIN].x, 854, 0.001); NEAR(b.target[DM_TC_MAIN].y, a.target[DM_TC_MAIN].y, 0.001); for (int i = DM_TC_SKILL1; i <= DM_TC_SKILL4; ++i) { NEAR(a.target[i].x - b.target[i].x, 46, 0.001); NEAR(a.target[i].y, b.target[i].y, 0.001); CHECK(b.target[i].x + b.target[i].r <= 894.001f); } - NEAR(a.swap.x - b.swap.x, 46, 0.001); NEAR(a.joy_x, 120, 0.001); NEAR(b.joy_x, 152, 0.001); NEAR(b.joy_min_x, 122, 0.001); NEAR(a.joy_y, 325, 0.001); NEAR(a.joy_max_y, 355, 0.001); /* 静止位 max(90, 安全区 + 60) + 30、440 − 115;夹回界 安全区 + 60、440 − 25 − 60 | rest position max(90, safe area + 60) + 30, 440 - 115; clamp bounds safe area + 60, 440 - 25 - 60 */ + NEAR(a.swap.x - b.swap.x, 46, 0.001); NEAR(a.joy_x, 120, 0.001); NEAR(b.joy_x, 152, 0.001); NEAR(b.joy_min_x, 68, 0.001); NEAR(a.joy_y, 325, 0.001); NEAR(a.joy_max_y, 372, 0.001); /* 静止位 max(90, 安全区 + 60) + 30、440 − 115(让安全区);夹回界 60 + 8、440 − 60 − 8(不让安全区) | rest position max(90, safe area + 60) + 30, 440 - 115 (respecting the safe area); clamp bounds 60 + 8, 440 - 60 - 8 (not respecting the safe area) */ dm_tc_layout c; dm_tc_layout_make(&c, 956, 440); NEAR(c.target[DM_TC_MAIN].x, 900, 0.001); } /* 换组键:956×440 下主键中心 (900,358),换组键在技能一正下方 (900−112, 358+52) = (788,410),半径 22;不与技能一(中心 (788,358) 半径 26)重叠、不出屏 | Set-switch button: at 956×440 the main button center is (900,358), the set-switch button is directly below skill one at (900−112, 358+52) = (788,410), radius 22; it does not overlap skill one (center (788,358), radius 26) and does not go off screen */ @@ -556,7 +581,7 @@ static void belt_single_double(void) { } int main(void) { RUN(layout_667); RUN(layout_812); RUN(layout_956); RUN(layout_1024); RUN(layout_ipad169); RUN(layout_pixels); RUN(small_layout); RUN(difficulty_picker); - RUN(hit_edges); RUN(key_hold_and_ownership); RUN(two_fingers_same_key); RUN(joystick_deadzone); + RUN(hit_edges); RUN(key_hold_and_ownership); RUN(two_fingers_same_key); RUN(joystick_deadzone); RUN(joystick_clamp_956); RUN(joystick_axes); RUN(joystick_plus_skills); RUN(no_auto_handoff); RUN(background_no_key); RUN(circles_before_joystick); RUN(cancel_and_resize); RUN(deferred_skill_vs_belt); RUN(held_skill2_vs_belt); RUN(belt_single_double); RUN(no_ui_drag_outside_modal); RUN(invalid_slots_and_repeated_begin); RUN(all_slots_hold); RUN(enabled_targets); RUN(ui_scene_messages); RUN(pointer_tap); RUN(world_tap); RUN(pointer_outside_close); RUN(scene_dialog_only); RUN(pointer_item_tap); RUN(pointer_stack_tap); RUN(pointer_over_disabled_target); RUN(ui_drag_typing); RUN(pointer_drag_out); RUN(pointer_drag); RUN(pointer_long); RUN(pointer_long_then_drag); RUN(pointer_long_seq); RUN(pointer_shop_drag); RUN(pointer_control_hit); RUN(pointer_game_mode); RUN(pointer_pulse_queue); RUN(safe_insets); RUN(swap_key); diff --git a/dm/ios/tools/gen_romfs_overlay.py b/dm/ios/tools/gen_romfs_overlay.py index a149308..c58839f 100644 --- a/dm/ios/tools/gen_romfs_overlay.py +++ b/dm/ios/tools/gen_romfs_overlay.py @@ -28,10 +28,14 @@ with tempfile.TemporaryDirectory() as t: nw=round((x1-x0)*k); nx=round(((x0+x1)/2-ref_w/2)*k)-1 # 系统提示框:整份自己写、不继承原版那份——原版带一个铺满的 Confirm 按钮(继承来的子控件删不掉),提示在屏上时它接住功能键和点击: # 按功能键 / 点它压着的地方都只是把提示关掉(面板开不了、下面的格子点不到)。触屏上提示到点自己消失,不要这个按钮 - # System notification: written entirely by ourselves, not inheriting the original game's one -- the original carries a full-cover Confirm button (an inherited child widget cannot be deleted), which catches the function key and taps while the notification is on screen: - # pressing the function key / tapping where it covers only dismisses the notification (the panel cannot open, the cells beneath cannot be tapped). On a touchscreen the notification disappears by itself when its time is up, so this button is not wanted + # 停靠高度 y −790(原版 −500;先前为让开经验条提到 −600,仍压着底栏上方那行「生命 / 法力」数值——数值位数多时字伸进框里,触屏版那行更高、直接叠在框中间): + # 框的下沿要高过数值行的上沿,触屏版需再上提约 173 单位、手柄版约 77 单位,取一个两版都让开的值。只改布局里的停靠位置,滑入滑出仍是游戏自己的动画 + # System notice box: written entirely by us, not inheriting the original - the original has a full-size Confirm button (inherited child widgets cannot be removed), which takes the function keys and taps while a notice is on screen: + # pressing a function key / tapping where it covers only dismisses the notice (panels cannot be opened, the cells below cannot be tapped). On touch the notice disappears by itself on time, and this button is not wanted + # Docking height y -790 (original -500; it was raised to -600 earlier to clear the experience bar, but still covered the "life / mana" numbers above the bottom bar - with many digits the text ran into the box, and the touch layout's row is higher and sat right in the middle of the box): + # the lower edge of the box has to be above the upper edge of the number row; the touch layout needs about 173 more units, the gamepad layout about 77, so one value that clears both is taken. Only the docking position in the layout changes; slide-in and slide-out are still the game's own animation note={'type':'NotificationPanel','name':'NotificationPanel', - 'fields':{'priority':9002,'notificationSeconds':5.0,'transitionSeconds':0.8,'rect':{'x':nx,'y':-600,'width':nw,'height':244},'anchor':{'x':0.5,'y':1.0}}, + 'fields':{'priority':9002,'notificationSeconds':5.0,'transitionSeconds':0.8,'rect':{'x':nx,'y':-790,'width':nw,'height':244},'anchor':{'x':0.5,'y':1.0}}, 'children':[{'type':'NineTileImageWidget','name':'NotificationBorder', 'fields':{'rect':{'x':0,'y':0,'width':nw,'height':244},'anchor':{'x':-0.5,'y':0.0},'filename':'PANEL/TooltipBorder/TooltipBorder','backgroundColor':[0.0,0.0,0.0,0.70],'tileScale':1}, 'children':[{'type':'TextBoxWidget','name':'Prompt','fields':{'fitToParent':True,'style':'$StyleNotification'}}]}]} @@ -68,9 +72,11 @@ with tempfile.TemporaryDirectory() as t: for rel,gd in (('controller/pauselayoutgardenhd.json',1),('controller/pauselayouthd.json',0)): # 手柄版暂停菜单:一键重开 / 切换难度 / 存放 / 分享诊断日志 | Controller pause menu: one-tap restart / change difficulty / Deposit / Share Diagnostics lp,lt=touch_layout.read_layout(romfs,rel); o=os.path.join(tpad,'pad_pause%d.json'%gd); open(o,'w',encoding='utf-8').write(touch_layout.pad_pause(lt,gd,share=not os.environ.get('DM_OVERLAY_MAC'))); PR[lp.lower()]=o # 大秘境面板(借「消息记录」面板外壳,touch_layout._rift_panel):手柄版同一份。少了它手柄模式点秘境门开出来的是空的原版消息记录面板、进不了秘境;手柄键在 dm_rift_ui.c - # Greater Rift panel (borrows the shell of the "Message Log" panel, touch_layout._rift_panel): the controller version uses the same one. Without it, - # tapping the Rift portal in controller mode opens an empty original Message Log panel and the Rift cannot be entered; the controller keys are in - # dm_rift_ui.c + # 手柄版的系统提示框:原版那份(停靠 y −500)下沿压着底栏上方那行「生命 / 法力」数值,数值位数多时字伸进框里。只把停靠位置上提 90 单位(下沿高过数值行),其余原样 + # Greater Rift panel (borrowing the shell of the "message log" panel, touch_layout._rift_panel): the same for the gamepad layout. Without it, tapping a rift door in gamepad mode opens the empty original message log panel and the rift cannot be entered; gamepad keys are in dm_rift_ui.c + # The gamepad layout's system notice box: in the original (docked at y -500) its lower edge sits on the "life / mana" numbers above the bottom bar, and with many digits the text runs into the box. Only the docking position is raised by 90 units (lower edge above the number row); everything else as in the original + lp,lt=touch_layout.read_layout(romfs,'controller/notificationpanelhd.json'); assert lt.count('"y": -500')==1, lp # 原版手柄版提示框的停靠位置应是 y -500(原包变了就停在这里) | the original gamepad notice box should dock at y -500 (if the original package changes, stop here) + o=os.path.join(tpad,'pad_notification.json'); open(o,'w',encoding='utf-8').write(lt.replace('"y": -500','"y": -590')); PR[lp.lower()]=o lp,lt=touch_layout.read_layout(romfs,'controller/messagelogpanelhd.json'); o=os.path.join(tpad,'pad_rift.json'); open(o,'w',encoding='utf-8').write(touch_layout._rift_panel(lt)[0]); PR[lp.lower()]=o PR.update(merc_slots.build_pad(romfs,tpad)) # 手柄版佣兵面板:同样加六个装备位 | Controller layout mercenary panel: likewise add six equipment slots # 手柄版职业选择页:八个职业的点击矩形同样改成按实际站位分的竖条(touch_layout.CLASS_STRIPS,原因见那里)。手柄用左右键选、原版没暴露; @@ -161,7 +167,7 @@ with tempfile.TemporaryDirectory() as t: # 手柄专用清单:手柄模式下不是原版字节的布局就这几份,一份不许多、一份不许少(改上面某一行时把相邻一行整行替掉过,商人页的刷新钮就从包里掉了) # Controller-only list: these are the only layouts that are not original bytes in controller mode, not one more and not one fewer (once, when a line above was edited, the adjacent line was replaced whole, and the vendor page's refresh button dropped out of the package) PAD_PAGES=('controller/bankexpansionlayouthd.json','controller/console/charactercreatepanelhd.json','controller/console/characteroptionspanelhd.json','controller/console/mainmenubuttonribbonhd.json','controller/console/mainmenupanelhd.json','controller/console/settingspanelhd.json','controller/console/switch/playerinventoryexpansionlayouthd.json','controller/console/videooptionspanelhd.json', - 'controller/controlleroverlayhd.json','controller/hirelinginventorypanelhd.json','controller/hudmonsterhealthhd.json','controller/messagelogpanelhd.json','controller/pauselayoutgardenhd.json','controller/pauselayouthd.json','controller/vendorpanellayouthd.json') + 'controller/controlleroverlayhd.json','controller/hirelinginventorypanelhd.json','controller/hudmonsterhealthhd.json','controller/messagelogpanelhd.json','controller/notificationpanelhd.json','controller/pauselayoutgardenhd.json','controller/pauselayouthd.json','controller/vendorpanellayouthd.json') if sorted(k[len(LAY):] for k in PADLAY)!=sorted(PAD_PAGES): raise SystemExit('gen_romfs_overlay:手柄专用布局与清单 PAD_PAGES 不一致:多 %s,少 %s' % (sorted(set(k[len(LAY):] for k in PADLAY)-set(PAD_PAGES)), sorted(set(PAD_PAGES)-set(k[len(LAY):] for k in PADLAY)))) def emit(repl, dst, tag, prebuilt=None): # repl → 覆盖层(新 .build.config + 一个新数据档)写到 dst/data | repl → overlay (a new .build.config + one new data archive) written to dst/data repl=to_touch(repl); repl.update(PADLAY) 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/dm/tools/patch_nso.py b/dm/tools/patch_nso.py index 8c32dce..9672ce1 100644 --- a/dm/tools/patch_nso.py +++ b/dm/tools/patch_nso.py @@ -778,6 +778,8 @@ if RULE_RUN and PRIVATE_GATES: obs.append((0x463f40, 19, "f81c0ff7", "client per-frame position-error smoothing entry (s0 = frame length in ticks), called by the main loop right after all units were extrapolated in place and before the per-unit error is added back: the native error is only computed on start / stop (0x4639c0, which runs before the tick loop), so a sharp turn inside a tick snaps the extrapolated position back in one frame; the host adds that frame's jump to the local player's error fields (path +0x2a8 / +0x2ac, same clamp as native) and the native code decays it")) obs.append((0x9da5b0, 20, "d104c3ff", "model yaw component per-frame update entry (x1 = argument block: +8 component, +0x20 -> +8 unit): the body turn speed is instance data on the component (+0x10..+0x2c min / max degrees per second for controller / mouse, +0x34 spring parameter); the host only reads them for the local player when a test switch is set")) obs.append((0x2f7664, 7, "6dbb23e9", "touch target rank: candidate compare entry (closure, unit, kind, s0=score); host raises Boss/elite score, native eligibility unchanged")) + obs.append((0xb0d560, 21, "fc1a0fe8", "TooltipsPanel add-tooltip entry (panel, text, target position x2 / x3, style, text2): tooltips are immediate-mode (re-submitted by the hovered widget every frame and cleared after drawing, so the host cannot reach the record at its own time); on touch, in panel state, for an item the player just tapped, the host swaps the target position so the game lays the tooltip out beside the panel instead of over the item grid; everything else passes through unchanged")) + obs.append((0x7ce800, 22, "d100c3ff", "server place-one-preset-unit entry (game, room, record), only called by the room-activation preset loop 0x7ce930 (8 sites): in a rift game at tier 90+ on a rift map, for a monster record that is not a superunique and not scenery / NPC, the host swaps x2 to a copy whose class is -1 so 0x6910d0 takes its own early return (tbnz w2, #31) and nothing is spawned; the real record is untouched; rift guardian / invader / superunique spawns call 0x7ce630 / 0x69b310 directly and never pass here")) for off, oid, ow, why in obs: w = struct.unpack_from('joy_radius = 60*k; l->joy_x = fmaxf(90*k, g_safe_l + 60*k) + 30*k; l->joy_y = l->height - 115*k; l->joy_zone_r = l->width*0.40f; l->joy_zone_t = l->height*0.45f; - l->joy_min_x = g_safe_l + l->joy_radius; l->joy_max_y = l->height - 25*k - l->joy_radius; + l->joy_min_x = l->joy_radius + 8*k; l->joy_max_y = l->height - l->joy_radius - 8*k; } int dm_tc_hit(const dm_tc_layout *l, float x, float y) { @@ -214,7 +216,7 @@ static void update(dm_tc_state *s) { s->lx = s->ly = 0; if (s->joy_slot < 0) return; dm_tc_finger *f = &s->finger[s->joy_slot]; - float dx = f->x-s->joy_origin_x, dy = s->joy_origin_y-f->y; + float dx = f->x-s->joy_touch_x, dy = s->joy_touch_y-f->y; /* 相对落点,不相对底盘圆心:夹回只影响底盘画在哪,不进算法(贴角落指时圆心在手指右上方,按圆心算会出现手指往右、人往下) | relative to the touch point, not the base centre: clamping only affects where the base is drawn and does not enter the computation (touching down in a corner puts the centre to the upper right of the finger, and computing from the centre would make the character move down while the finger moves right) */ /* 输入行程不跟大屏的视觉放大走:拇指不随屏幕变大。满偏 60 点、死区 6 点,手机与 iPad 一致 (原先乘视觉倍数,12.9 寸 iPad 要推 105 点 ≈ 20 mm 才满偏,是手机的两倍)。底盘和摇杆头的大小仍按视觉倍数画。 Input travel does not follow the visual enlargement on large screens: the thumb does not grow with the screen. Full deflection 60 points, dead zone 6 points, same on phone and iPad @@ -296,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) { @@ -388,7 +393,7 @@ void dm_tc_cancel_finger(dm_tc_state *s, int slot) { if (slot < 0 || slot >= DM_TC_MAX_TOUCH) return; ++s->gesture_epoch; if (s->finger[slot].active && s->finger[slot].target == DM_TC_PORTAL) { dm_tc_cancel_portal(s); } - if (slot == s->joy_slot && s->finger[slot].active) { s->joy_lost_s = s->last_time_s; s->joy_lost_x = s->finger[slot].x; s->joy_lost_y = s->finger[slot].y; s->joy_lost_ox = s->joy_origin_x; s->joy_lost_oy = s->joy_origin_y; } /* 系统取消了摇杆那根手指:记下,紧接着在附近重新落下的接着当摇杆 | the system cancelled the joystick finger: record it, and a finger landing again nearby right afterwards continues as the joystick */ + if (slot == s->joy_slot && s->finger[slot].active) { s->joy_lost_s = s->last_time_s; s->joy_lost_x = s->finger[slot].x; s->joy_lost_y = s->finger[slot].y; s->joy_lost_ox = s->joy_origin_x; s->joy_lost_oy = s->joy_origin_y; s->joy_lost_tx = s->joy_touch_x; s->joy_lost_ty = s->joy_touch_y; } /* 系统取消了摇杆那根手指:记下,紧接着在附近重新落下的接着当摇杆 | the system cancelled the joystick finger: record it, and a finger landing again nearby right afterwards continues as the joystick */ s->finger[slot] = (dm_tc_finger){.target=DM_TC_NONE}; if (slot == s->joy_slot) { s->joy_slot = DM_TC_NONE; s->joy_origin_x = s->joy_origin_y = 0; } if (slot == s->aim_slot) s->aim_slot = DM_TC_NONE; @@ -505,14 +510,14 @@ void dm_tc_begin_at(dm_tc_state *s, int slot, float x, float y, double now_s) { } else if (!s->navigation_mode && !s->joy_block && hit == DM_TC_NONE && s->joy_slot == DM_TC_NONE && x >= 0 && y <= s->layout.height && ((x < s->layout.joy_zone_r && y > s->layout.joy_zone_t) || (x < s->layout.width*0.43f && y > s->layout.height*0.25f && s->joy_lost_s > 0 && now_s - s->joy_lost_s <= DM_TC_JOY_RESUME_S && hypotf(x - s->joy_lost_x, y - s->joy_lost_y) <= DM_TC_JOY_GRAB_K * s->layout.joy_radius))) { - /* 浮动底盘:落在起摇杆区里就起摇杆,底盘圆心 = 落点(贴边时夹回,见布局处),方向与幅度按「手指相对底盘圆心」算,按住后拖到多远都照样识别, + /* 浮动底盘:落在起摇杆区里就起摇杆,底盘圆心 = 落点(贴边时夹回,见布局处),方向与幅度按「手指相对落点」算,按住后拖到多远都照样识别, 底盘不跟手走;落在区外照旧是点地。这一下若很快原地松开,仍兼作一次点击(dm_tc_end_at):区里的怪、掉落物、NPC 要点得到。 摇杆那根手指刚被系统取消(通知横幅、系统手势;dm_tc_cancel_finger 记下时刻与位置),DM_TC_JOY_RESUME_S 内在原处附近重新落下的手指接着当摇杆, - 哪怕落点已拖出起摇杆区。只开着讲话文字框 / 对话菜单时不起摇杆(joy_block):夹回会让落点 ≠ 圆心、一落下就有方向,那一下只该关框 - Floating base: a touch inside the stick-start zone starts the stick with the base centre = the touch point (clamped back near the edges, see the layout), direction and magnitude are computed from "finger relative to base centre", and once held, dragging any distance is still recognised; + 哪怕落点已拖出起摇杆区。只开着讲话文字框 / 对话菜单时不起摇杆(joy_block):那一下只该关框、人不走(落指位移为零本来也不出方向,但手指稍一滑就会走,照旧整根挡掉) + Floating base: a touch inside the stick-start zone starts the stick with the base centre = the touch point (clamped near the edges, see the layout), direction and magnitude are computed from "finger relative to the touch point", and once held, dragging any distance is still recognised; the base does not follow the finger; a touch outside the zone is a ground tap as before. If this touch is released quickly in place it still doubles as a tap (dm_tc_end_at): monsters, dropped items and NPCs inside the zone must remain tappable. When the stick finger has just been cancelled by the system (notification banner, system gesture; dm_tc_cancel_finger records the time and position), a finger touching down again near the same place within DM_TC_JOY_RESUME_S continues as the stick, - even if the touch point has been dragged out of the stick-start zone. The stick does not start while only a speech text box / dialogue menu is open (joy_block): clamping would make touch point != centre and give a direction the moment it lands, when that touch should only close the box */ + even if the touch point has been dragged out of the stick-start zone. The stick does not start while only a speech text box / dialogue menu is open (joy_block): that touch should only close the box without moving the character (zero displacement on touch-down gives no direction anyway, but a slight slide would walk, so the whole finger is still blocked) */ int resume = s->joy_lost_s > 0 && now_s - s->joy_lost_s <= DM_TC_JOY_RESUME_S && hypotf(x - s->joy_lost_x, y - s->joy_lost_y) <= DM_TC_JOY_GRAB_K * s->layout.joy_radius; s->joy_lost_s = 0; f->target = DM_TC_JOYSTICK; @@ -520,6 +525,7 @@ void dm_tc_begin_at(dm_tc_state *s, int slot, float x, float y, double now_s) { /* 接续的沿用取消前的圆心,不按新落点重定:触摸被系统反复打断又重来的机器上,每重来一次底盘就跳到手指当前位置,看着像底盘追着手指跑 | a continuation keeps the centre from before the cancel instead of re-centring on the new touch point: on devices where touches are repeatedly interrupted by the system and restarted, the base would jump to the finger's current position on every restart and look as if it were chasing the finger */ s->joy_origin_x = resume ? s->joy_lost_ox : fmaxf(x, s->layout.joy_min_x); s->joy_origin_y = resume ? s->joy_lost_oy : fminf(y, s->layout.joy_max_y); + s->joy_touch_x = resume ? s->joy_lost_tx : x; s->joy_touch_y = resume ? s->joy_lost_ty : y; /* 接续的沿用取消前的落点,同样不按新落点重定 | a continuation keeps the touch point from before the cancel, likewise not re-centred on the new touch point */ } update(s); } diff --git a/dm/touch/dm_touch_controls.h b/dm/touch/dm_touch_controls.h index e500634..beaf8ac 100644 --- a/dm/touch/dm_touch_controls.h +++ b/dm/touch/dm_touch_controls.h @@ -19,7 +19,7 @@ typedef struct { float width, height; dm_tc_target target[DM_TC_COUNT]; float joy_x, joy_y, joy_radius; /* 没按时底盘的显示位置(静止位)与底盘半径 | where the base is shown while not pressed (rest position), and the base radius */ - float joy_zone_r, joy_zone_t, joy_min_x, joy_max_y; /* 起摇杆区的右界与上界(左与下到屏幕边);按下后底盘圆心的夹回界:x 不小于、y 不大于 | right and upper bounds of the stick-start zone (left and bottom reach the screen edges); clamp bounds for the base centre once pressed: x not less than, y not greater than */ + float joy_zone_r, joy_zone_t, joy_min_x, joy_max_y; /* 起摇杆区的右界与上界(左与下到屏幕边);按下后底盘圆心的夹回界:x 不小于、y 不大于(只为底盘整圈画在屏内:屏幕边 + 半径 + 8) | right and upper bounds of the stick-start zone (left and bottom reach the screen edges); clamp bounds for the base centre once pressed: x not less than, y not greater than (only so that the whole base is drawn on screen: screen edge + radius + 8) */ dm_tc_target swap; /* 技能组切换键:本地开关,不直接发按键 | Skill set switch key: a local toggle; does not send a key directly */ dm_tc_target diff; /* 底部 UI v4 第 0 格难度:点开 / 收起 1–8 选择条,不发按键 | Bottom UI v4 cell 0 difficulty: tap to open / collapse the 1–8 selector bar; sends no key */ dm_tc_target pick[8]; /* 选择条 8 格(第 i 格 = 人数档 i+1),在七格上方 | The selector bar's 8 cells (cell i = player-count level i+1), above the seven cells */ @@ -125,6 +125,7 @@ typedef struct { int belt_gap_cell; double belt_gap_at; /* 按着第二组技能时要喝药:先把 ZL 和技能键松开、空出 DM_TC_ZL_LEAD_S,到 belt_gap_at 才按腰带键(belt_gap_cell = 等着的那一格,0 = 没有) | to drink a potion while a skill of the second skill set is held: first release ZL and the skill key and leave a gap of DM_TC_ZL_LEAD_S, and only at belt_gap_at press the belt key (belt_gap_cell = the cell that is waiting, 0 = none) */ double joy_lost_s; float joy_lost_x, joy_lost_y, joy_lost_ox, joy_lost_oy; /* 摇杆手指被系统取消的时刻与当时的位置(0 = 没有):紧接着在附近重新落下的手指接着当摇杆 | time and position at which the joystick finger was cancelled by the system (0 = none): a finger landing again nearby right afterwards continues as the joystick */ int joy_block; /* 讲话文字框单独开着(前端不进面板态):这时落在底座上的手指不起摇杆,照旧只当一次点击(关讲话框)。前端按面板栈写 | speech text box open on its own (the front end does not enter panel state): a finger on the base starts no stick and is still just one click (closes the speech box). Written by the front end from the panel stack */ + float joy_touch_x, joy_touch_y, joy_lost_tx, joy_lost_ty; /* 摇杆那根手指的落点(方向与幅度一律按「手指相对落点」算;joy_origin 只是底盘画在哪 = 落点夹回屏内之后);被系统取消时记下的落点 | touch point of the stick finger (direction and magnitude are always computed from "finger relative to the touch point"; joy_origin is only where the base is drawn = the touch point clamped onto the screen); the touch point recorded when it was cancelled by the system */ double belt_pulse_s; /* 最近一次「给玩家喝」的腰带脉冲还在发的时刻:其间按着的第二组技能连同 ZL 一起让开,收回后 ZL 重新领先 DM_TC_ZL_LEAD_S 技能键才回来 | Time until which the most recent "player drinks" belt pulse is still being sent: during it the held second-set skill gives way together with ZL, and after the release ZL again leads by DM_TC_ZL_LEAD_S before the skill key comes back */ int belt_q; /* 此刻有别的脉冲在发 / 别的补发在等:排着,空了再落地(不互相盖掉)。值 = 格 | another pulse is being sent / another resend is pending: queue and fire when free (they never overwrite each other). Value = cell */ } dm_tc_state; @@ -134,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/docs/MAC.md b/docs/MAC.md index 1a0b7c7..b42b582 100644 --- a/docs/MAC.md +++ b/docs/MAC.md @@ -61,7 +61,7 @@ With a keyboard, the button prompts on screen (the hint bar at the bottom, skill **Creating a character, start to finish**: on the main menu press `=` (or click "New Character") → choose a class with the arrow keys and press Return (or click that class's figure) → on the mode page press Return or Space → on the naming page press Return to open the input box, type, Return → press Return once more to create. -A gamepad works as soon as it is connected, alongside the keyboard. The menu bar has View → Full Screen (⌃⌘F) and Quit (⌘Q). The window can be resized freely; the game picture stays 16:9 and centred. +A gamepad works as soon as it is connected, alongside the keyboard. The menu bar has View → Full Screen (⌃⌘F) and Quit (⌘Q). The window can be resized freely. In game the picture fills the window or screen at its own aspect ratio (on a 16:10 MacBook both windowed and full screen are filled, with the interface along the bottom, centred while a large panel is open); the front-end pages such as the main menu and character select stay 16:9 with bars above and below. ## Mouse @@ -91,6 +91,7 @@ What it cannot do yet: - Saves: `~/Library/Application Support/D2R Mobile/save` - Log: `~/Library/Logs/D2R Mobile/host.log` (the previous run is `host.prev.log`). When reporting a problem use Help → Share Log… in the menu bar: it packs these two logs and a version-information file into one archive and lets you choose where to save it; nothing is uploaded, no saves are included, and the user name in the logs is replaced with `~`. +- No sound: at launch the log has a line `audio:输出设备「…」…,系统缺省输出「…」…` (the output device in use and the system default output; a mismatch is marked red), and on exit a line `声卡回调累计 N` — N = 0 means no sound was played this time. (These log lines are in Chinese.) - The older-API build (`D2R Mobile M3.app`) uses a separate pair of directories with M3 in the name. **iCloud save sync: not available in an App you build from this repository.** The program has the same sync as on iPhone / iPad wired in, but it needs the App to carry the iCloud signing entitlement; an App you build yourself is signed locally without it, so saves stay on this Mac, the log records one line saying iCloud is unavailable and only local saves are used, and the game runs as usual. To bring your phone's progress over, import it by hand as below. diff --git a/docs/MAC.zh-CN.md b/docs/MAC.zh-CN.md index 37e9985..b2b6f89 100644 --- a/docs/MAC.zh-CN.md +++ b/docs/MAC.zh-CN.md @@ -61,7 +61,7 @@ DM_MAC_M3=1 dm/tools/mac_app.sh # macOS 15 – 25 **建一个角色,从头到尾这样按**:主菜单按 `=`(或鼠标点「新角色」)→ 用方向键选职业再按回车(或直接点那个职业的人物)→ 模式页按回车或空格 → 起名页按回车弹出输入框,直接打字,回车 → 再按一次回车创建。 -接上手柄直接可用,与键盘并存。菜单栏有「显示 → 全屏(⌃⌘F)」和「退出(⌘Q)」。窗口可以随意拉大小,游戏画面保持 16:9 居中。 +接上手柄直接可用,与键盘并存。菜单栏有「显示 → 全屏(⌃⌘F)」和「退出(⌘Q)」。窗口可以随意拉大小。进游戏后画面按窗口 / 屏幕的比例铺满(16:10 的 MacBook 上窗口态和全屏态都铺满,界面贴底,开着大面板时界面居中);主菜单、选角等前端页仍是 16:9、上下留边。 ## 鼠标 @@ -91,6 +91,7 @@ DM_MAC_M3=1 dm/tools/mac_app.sh # macOS 15 – 25 - 存档:`~/Library/Application Support/D2R Mobile/save` - 日志:`~/Library/Logs/D2R Mobile/host.log`(上一次运行的是 `host.prev.log`)。报问题时用菜单栏「帮助 → 分享日志…」:它把这两份日志和一份版本信息打成一个压缩包,让你选保存位置;不上传、不带存档,日志里的用户名会换成 `~`。 +- 没有声音时看日志:启动时有一行「audio:输出设备「…」,系统缺省输出「…」」,两者不一致会标红;退出时有一行「声卡回调累计 N」,N 为 0 表示这次没有出声。 - 老接口版(`D2R Mobile M3.app`)用的是名字里带 M3 的另一对目录。 **iCloud 存档同步:从本仓库自己构建的 App 没有。**程序里接了与 iPhone / iPad 相同的同步,但它需要 App 带着 iCloud 的签名权限;自己构建的 App 用的是本机临时签名,没有这项权限,所以存档只留在这台 Mac 上,日志里会记一行「iCloud 不可用…只用本地存档」,游戏照常。要把手机上的进度带过来,用下面的手工导入。 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 的「老机型」一节)——贴图包只和芯片有关,两份壳用的是同一个贴图包。