diff --git a/README.md b/README.md index 4310382..2e582e7 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ This is not a tech demo that "sort of runs". It is a mobile version polished for daily play, from your first character all the way through the endgame. -Platforms: iPhone / iPad (iOS 26 and later) · Mac (Apple silicon, macOS 26 or later, first version) · Game version: Switch release with Reign of the Warlock, 1.0.34.0 (corresponds to PC version 3.3.94012) · English / 中文 · License: MIT · **Bring your own game files** +Platforms: iPhone / iPad (iOS 26 and later; iOS 18 – 25 with the older-API build) · Mac (Apple silicon, macOS 26 or later; macOS 15 – 25 with the older-API build) · Game version: Switch release with Reign of the Warlock, 1.0.34.0 (corresponds to PC version 3.3.94012) · English / 中文 · License: MIT · **Bring your own game files** 中文: [README.zh-CN.md](README.zh-CN.md) @@ -195,6 +195,15 @@ Both routes start with **the files of the game you bought**: the Switch release 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 system decides which build to use, the chip decides whether you also need a texture pack, and the two combine: + +| Your device | iOS 26 or later | iOS 18 – 25 | +|---|---|---| +| **A17 Pro and newer** (iPhone 15 Pro and later, iPhone 16 and later) | Default build, follow the steps below | [Older-API build](docs/OLDER_SYSTEMS.md) | +| **A16 and earlier** (iPhone 14 series, iPhone 15 / 15 Plus and before) | Default build + [Legacy Device Pack](docs/LEGACY_DEVICES.md) | [Older-API build](docs/OLDER_SYSTEMS.md) + [Legacy Device Pack](docs/LEGACY_DEVICES.md) | + +On a Mac only the system matters: macOS 26 or later uses the default build, macOS 15 – 25 the [older-API build](docs/OLDER_SYSTEMS.md). + | | With a Mac | Without a Mac | |---|---|---| | Computer | An Apple silicon Mac with Xcode installed | Windows / Linux / a Mac without Xcode | @@ -233,18 +242,19 @@ The first time you open the app on your phone, it asks for the "game resource fo ### Playing directly on a Mac -After the same `./setup.sh`, one more command produces a native macOS App that starts on double-click and works with keyboard, mouse and gamepad, with no developer account needed: +After the same `./setup.sh`, one more command builds a native macOS App that starts on double-click and works with keyboard, mouse and gamepad, with no developer account: ```bash source ~/dm-work/build/cache/dm/venv/bin/activate -dm/tools/mac_app.sh # produces ~/dm-work/out/macapp/D2R Mobile.app +dm/tools/mac_app.sh # macOS 26 or later: produces ~/dm-work/out/macapp/D2R Mobile.app +DM_MAC_M3=1 dm/tools/mac_app.sh # macOS 15 – 25: produces D2R Mobile M3.app ``` -This is a first version: it uses the original gamepad UI, with the keyboard mapped to the full set of gamepad buttons. Nobody has actually sat down and played it yet — the key mapping, the known gaps and what to do on first launch are in [docs/MAC.md](docs/MAC.md). +The interface is the original's gamepad interface. Keyboard: Space confirms, Esc goes back, Return, the `=` key opens the menu / a new character, W A S D moves, and every other gamepad button has a key. Mouse: clicking a monster, NPC or object walks over and interacts, and the skill slots, potion cells and key hints at the bottom, buttons and tabs in panels, the class figures when creating a character and the minimap can all be clicked; walking by clicking empty ground and dragging items are not there yet. Saves stay on this Mac (an App you build yourself has no iCloud sync) and can be imported by hand from an iPhone / iPad. The key table, how to create a character, what the mouse can do, the import steps and the known shortcomings are in [docs/MAC.md](docs/MAC.md). Keyboard and a physical gamepad have not been operated by a person yet — if you try it, please tell us how it went. ### Without a Mac: the shell plus the packaging tool -Download our prebuilt "shell" package (`D2RMobile-shell.ipa`), 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.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). ## Known limitations @@ -254,7 +264,8 @@ Download our prebuilt "shell" package (`D2RMobile-shell.ipa`), which contains no | `.nsp` / `.xci` game packages | The tools only check the version of the main program and do not distinguish package formats; we ran the whole path with an `.xci` ourselves, and users have reported that `.nsp` packages work perfectly as well | | Signing and installing with a sideloading tool (Sideloadly, AltStore and the like) | Not verified; open an issue and tell us how it went | | Making the package on Linux | Not verified (verified on Windows and Mac) | -| A16 and earlier devices (iPhone 14 family, iPhone 15 / 15 Plus and so on) | Playable; they need a Legacy Device Pack and an App built with it: [docs/LEGACY_DEVICES.md](docs/LEGACY_DEVICES.md). "Device Not Supported" in the App means this step is missing | +| Devices that have not moved to iOS 26 / macOS 26 | Playable with the older-API build (minimum iOS 18.0 / macOS 15.0): [docs/OLDER_SYSTEMS.md](docs/OLDER_SYSTEMS.md) | +| A16 and earlier devices (iPhone 14 family, iPhone 15 / 15 Plus and so on) | Playable; they need a Legacy Device Pack and an App built with it: [docs/LEGACY_DEVICES.md](docs/LEGACY_DEVICES.md). "One More Step for This Device" (older versions say "Device Not Supported") in the App means this step is missing | | The "one-line verdict" and "legacy Chinese name" entries in item notes | These two content tables are not shipped with the repository; you can supply your own, see `dm/ios/tools/annot/README.md` | ## Contributing and feedback @@ -265,6 +276,18 @@ Download our prebuilt "shell" package (`D2RMobile-shell.ipa`), which contains no **Taking it to other platforms:** this approach is not limited to iPhone and iPad. Apple silicon Macs already have a native version (see "Playing directly on a Mac" above), built from the same game program and the same host. Android phones use the same class of processor, so the game program executes natively there as well, and the route is fully open: the only parts to replace are the sides of the host and the graphics layer that face the platform. The author has no Android phone at hand, and would love to see someone bring it to Android. +**Taking it to other games:** someone has already tried other Switch games on the same host. The host has some behaviour that is on by default on iOS and was written for this one game; another game runs into these first, so turn them off or move them out before you start: + +- `dm/host/hle_oe.c`: the 3D render scale defaults to 0.75 on iOS, and `scale3d_tick` rewrites it at offsets inside this game's renderer — with another game that is a wild pointer. +- `dm/host/hle_fs.c`: seeding the shared stash on first launch (`DM_STASH_SEED`) and the touch-layout default settings (`DM_TOUCH_DEFAULTS`) are on by default on iOS. +- `dm/host/main.c`: the save-flush throttle patches a constant at a fixed address in the game program; `argv[0]` is hard-coded to `"D2R"`. +- `dm/host/hle_time.c`: the fixed-time test switch recognises a fixed address in the game program. +- `front_game_res` in `dm/host/front_mac.m`: the docked / handheld resolutions are hard-coded to 1600×900 / 1280×720. +- `dm/host/dm_cloudsync.c`: character directories are recognised by `.d2s`. +- `dm/host/dm_cursor.c` and `dm/host/dm_world.c`: the whole files are specific to this game. + +The cleaner arrangement is to move these defaults into per-game configuration and keep the host free of game-specific defaults; pull requests in that direction are welcome. + ## Documentation by part | Document | Covers | @@ -278,6 +301,7 @@ Download our prebuilt "shell" package (`D2RMobile-shell.ipa`), which contains no | [docs/NO_XCODE.md](docs/NO_XCODE.md) | Building without Xcode and without a Mac | | [docs/MAC.md](docs/MAC.md) | Playing on a Mac: building the macOS App, key mapping, known gaps | | [docs/LEGACY_DEVICES.md](docs/LEGACY_DEVICES.md) | Older devices (A16 and earlier): making the texture pack and putting it on the phone | +| [docs/OLDER_SYSTEMS.md](docs/OLDER_SYSTEMS.md) | Older systems (iOS 18 – 25, macOS 15 – 25): building the older-API version and combining it with the Legacy Device Pack | | [docs/DERIVED.md](docs/DERIVED.md) | Game-related material in this repository: what is here, what is not, and why | ## Legal diff --git a/README.zh-CN.md b/README.zh-CN.md index 0a06f17..b9e77c8 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -4,7 +4,7 @@ 这不是一个「勉强能跑」的技术演示,而是一个打磨到可以天天玩、从开荒一路玩到终局的移动版。 -平台:iPhone / iPad(iOS 26 起)· Mac(Apple 芯片,macOS 26 及以上,第一版)· 游戏版本:Switch 版「术士君临」1.0.34.0(对应 PC 版 3.3.94012)· 中文 / English · 许可证:MIT · **需要自备游戏文件** +平台:iPhone / iPad(iOS 26 起;iOS 18 – 25 用老接口版)· Mac(Apple 芯片,macOS 26 及以上;macOS 15 – 25 用老接口版)· 游戏版本:Switch 版「术士君临」1.0.34.0(对应 PC 版 3.3.94012)· 中文 / English · 许可证:MIT · **需要自备游戏文件** English: [README.md](README.md) @@ -195,6 +195,15 @@ flowchart LR 本项目基于 Switch 版 1.0.34.0(对应 PC 版的 3.3.94012)实现并验证,工具默认只认这一版。已有社区用户反馈,参照仓库结构自行适配了其他版本并成功运行。规则表按游戏版本分组存放(`dm/tools/patch_nso.py` 里按主程序的构建标识分组),欢迎把你适配的版本提交回来。 +**先对一下你的设备**——系统决定用哪种构建,芯片决定要不要多做一份贴图包,两件事可以叠: + +| 你的设备 | iOS 26 及以上 | iOS 18 – 25 | +|---|---|---| +| **A17 Pro 及更新**(iPhone 15 Pro 起、iPhone 16 起) | 缺省构建,照下面走 | [老接口版](docs/OLDER_SYSTEMS.zh-CN.md) | +| **A16 及更早**(iPhone 14 系列、iPhone 15 / 15 Plus 及更早) | 缺省构建 + [老机型贴图包](docs/LEGACY_DEVICES.zh-CN.md) | [老接口版](docs/OLDER_SYSTEMS.zh-CN.md) + [老机型贴图包](docs/LEGACY_DEVICES.zh-CN.md) | + +Mac 只看系统:macOS 26 及以上用缺省构建,macOS 15 – 25 用[老接口版](docs/OLDER_SYSTEMS.zh-CN.md)。 + | | 有 Mac | 没有 Mac | |---|---|---| | 电脑 | Apple 芯片的 Mac,装好 Xcode | Windows / Linux / 没装 Xcode 的 Mac | @@ -237,14 +246,15 @@ flowchart LR ```bash source ~/dm-work/build/cache/dm/venv/bin/activate -dm/tools/mac_app.sh # 产出 ~/dm-work/out/macapp/D2R Mobile.app +dm/tools/mac_app.sh # macOS 26 及以上:产出 ~/dm-work/out/macapp/D2R Mobile.app +DM_MAC_M3=1 dm/tools/mac_app.sh # macOS 15 – 25:产出 D2R Mobile M3.app ``` -这是第一版:界面用原版的手柄版界面,键盘对应整套手柄键位。它还没有人真的坐下来玩过——键位、已知的不足和第一次打开时要做的事,见 [docs/MAC.zh-CN.md](docs/MAC.zh-CN.md)。 +界面用原版的手柄版界面。键盘:空格确认、Esc 返回、回车、`=` 键开菜单 / 新角色,W A S D 移动,其余手柄键各有对应。鼠标:点怪、NPC、物件会走过去交互,底部的技能格、药水格、按键提示、面板里的按钮和页签、建角时的职业、小地图都能点;点空地走路和物品的拖放还没有。存档在这台 Mac 上(自己构建的 App 没有 iCloud 同步),可以从 iPhone / iPad 手工导入。键位表、建角怎么按、鼠标能做什么、导入步骤和已知不足,见 [docs/MAC.zh-CN.md](docs/MAC.zh-CN.md)。键盘、实体手柄这几项还未经真人操作,你试过的话,请告诉我们结果。 ### 没有 Mac:壳 + 做包工具 -从本仓库的[发布页](https://github.com/jhaizhou-ops/d2r-mobile/releases)下载我们预先做好的、不含游戏内容的「壳」安装包(`D2RMobile-shell.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.ipa`;iOS 18 – 25 用 `D2RMobile-shell-ios18.ipa`),加上你自己的游戏文件,在 Windows 或 Linux 上做出安装包,再用自签工具签名装机。只有走这条路时,因为做包的电脑上没有苹果的着色器编译器,手机**第一次启动**要花约 7 分钟把着色器编完(一次性,带进度条);用 Xcode 构建的包没有这一步。步骤与每一步的验证现状见 [docs/NO_XCODE.zh-CN.md](docs/NO_XCODE.zh-CN.md)。 ## 已知限制 @@ -254,7 +264,8 @@ dm/tools/mac_app.sh # 产出 ~/dm-work/out/macapp/D2R Mobile.app | `.nsp` / `.xci` 两种游戏包 | 工具只核对主程序的版本,不区分包的格式;我们自己用 `.xci` 走过全程,有网友反馈 `.nsp` 格式的游戏包也完美兼容 | | 用自签工具(Sideloadly、AltStore 等)签名装机 | 没验过,欢迎开 Issue 告诉我们结果 | | Linux 上做包 | 没验过(Windows 与 Mac 上验过) | -| A16 及更早的机型(iPhone 14 系列、iPhone 15 / 15 Plus 等) | 可以玩,要多做一份老机型贴图包并带着它构建 App:[docs/LEGACY_DEVICES.zh-CN.md](docs/LEGACY_DEVICES.zh-CN.md)。App 提示「暂不支持本机型」就是缺这一步 | +| 没升到 iOS 26 / macOS 26 的设备 | 可以玩,用老接口版(最低 iOS 18.0 / macOS 15.0):[docs/OLDER_SYSTEMS.zh-CN.md](docs/OLDER_SYSTEMS.zh-CN.md) | +| A16 及更早的机型(iPhone 14 系列、iPhone 15 / 15 Plus 等) | 可以玩,要多做一份老机型贴图包并带着它构建 App:[docs/LEGACY_DEVICES.zh-CN.md](docs/LEGACY_DEVICES.zh-CN.md)。App 提示「这台设备要多做一步」(旧版本显示的是「暂不支持本机型」)就是缺这一步 | | 物品注释里的「一句点评」与「旧译名对照」 | 两张内容表不随仓库提供,可自备,见 `dm/ios/tools/annot/README.zh-CN.md` | ## 参与与反馈 @@ -265,6 +276,18 @@ dm/tools/mac_app.sh # 产出 ~/dm-work/out/macapp/D2R Mobile.app **往别的平台走:** 这套做法不限于 iPhone 和 iPad。Apple 芯片的 Mac 已经有了原生版本(见上面「在 Mac 上直接玩」),用的是同一份游戏程序和同一个宿主。安卓手机用的是同一类处理器,游戏程序同样可以原生执行,这条路完全走得通:要换的只是宿主和图形层对接的那一侧。作者手边没有安卓手机,非常期待看到有人把它带到安卓上。 +**往别的游戏走:** 已经有人拿同一份宿主去试别的 Switch 游戏。宿主里有一些「iOS 上缺省就开」的行为是为这一个游戏写的,换游戏会先撞到它们,动手前先关掉或挪走: + +- `dm/host/hle_oe.c`:三维渲染比例在 iOS 上缺省 0.75,`scale3d_tick` 按这个游戏渲染器里的偏移去改写——换一个游戏,那就是个野指针。 +- `dm/host/hle_fs.c`:首次启动预置共享仓库(`DM_STASH_SEED`)与触屏版缺省设置(`DM_TOUCH_DEFAULTS`),iOS 上缺省开。 +- `dm/host/main.c`:存档落盘节流改的是游戏程序里一个固定地址上的常数;`argv[0]` 写死成 `"D2R"`。 +- `dm/host/hle_time.c`:固定时刻的测试开关认的是游戏程序里的一个固定地址。 +- `dm/host/front_mac.m` 的 `front_game_res`:底座 / 掌机两档分辨率写死成 1600×900 / 1280×720。 +- `dm/host/dm_cloudsync.c`:按 `.d2s` 认角色目录。 +- `dm/host/dm_cursor.c`、`dm/host/dm_world.c`:整个文件都是这个游戏专属的。 + +更干净的做法是把这些缺省值挪进各游戏自己的配置,宿主里不带游戏专属的缺省;欢迎朝这个方向提合并请求。 + ## 各部分的说明 | 说明 | 讲什么 | @@ -278,6 +301,7 @@ dm/tools/mac_app.sh # 产出 ~/dm-work/out/macapp/D2R Mobile.app | [docs/NO_XCODE.zh-CN.md](docs/NO_XCODE.zh-CN.md) | 不用 Xcode、不用 Mac 的做法 | | [docs/MAC.zh-CN.md](docs/MAC.zh-CN.md) | 在 Mac 上玩:构建 macOS App、键位、已知不足 | | [docs/LEGACY_DEVICES.zh-CN.md](docs/LEGACY_DEVICES.zh-CN.md) | 老机型(A16 及更早):怎么做贴图包、怎么放进手机 | +| [docs/OLDER_SYSTEMS.zh-CN.md](docs/OLDER_SYSTEMS.zh-CN.md) | 老系统(iOS 18 – 25、macOS 15 – 25):老接口版怎么出、和老机型贴图包怎么组合 | | [docs/DERIVED.zh-CN.md](docs/DERIVED.zh-CN.md) | 仓库里与游戏有关的东西:有什么、没有什么、为什么 | ## 声明 diff --git a/dm/gfx/.gitignore b/dm/gfx/.gitignore new file mode 100644 index 0000000..86cbf7a --- /dev/null +++ b/dm/gfx/.gitignore @@ -0,0 +1 @@ +tests_m3/ diff --git a/dm/gfx/nvn/nvn_mtl.m b/dm/gfx/nvn/nvn_mtl.m index 0a0fa2c..857e4b7 100644 --- a/dm/gfx/nvn/nvn_mtl.m +++ b/dm/gfx/nvn/nvn_mtl.m @@ -14,6 +14,36 @@ #include #include #include "nvn_mtl.h" +// 编译期开关 DM_NVN_M3=1:图形后端走老接口(普通命令队列 / 命令缓冲 / 渲染与计算与拷贝编码器,逐槽绑定缓冲,对参数块引用的资源逐个声明), +// 目标 macOS 15 / iOS 18。缺省 0 = Metal 4(macOS 26 / iOS 26)。两支共用同一份回放逻辑,分叉处都在 #if DM_NVN_M3 里 +// Compile-time switch DM_NVN_M3=1: the graphics backend uses the older API (ordinary command queue / command buffers / render, compute and copy encoders, buffers bound per slot, each resource referenced by an argument block declared individually), +// target macOS 15 / iOS 18. Default 0 = Metal 4 (macOS 26 / iOS 26). Both branches share the same replay logic, and every divergence is inside #if DM_NVN_M3 +#ifndef DM_NVN_M3 +#define DM_NVN_M3 0 +#endif +#if DM_NVN_M3 +#define RENC id +#define CENC id +#define BENC id +#define CBUF id +#define RPD MTLRenderPassDescriptor +#define FB_ON(o, cb) cb +#define M4_ONLY(...) +#define M3_PRESENT(cb, dr) [cb presentDrawable:dr] +#define FB_SEL addCompletedHandler +#define FB_ARG id +#else +#define RENC id +#define CENC id +#define BENC id +#define CBUF id +#define RPD MTL4RenderPassDescriptor +#define FB_ON(o, cb) o +#define M4_ONLY(...) __VA_ARGS__ +#define M3_PRESENT(cb, dr) [dr present] +#define FB_SEL addFeedbackHandler +#define FB_ARG id +#endif #include "nvn_obj.h" #include "../tex/nvn_fmt_mtl.h" #include "../tex/nvn_deswizzle.h" @@ -54,19 +84,26 @@ static id g_dev; static NSMutableArray *g_l3_gpu_leaks; static int g_nvn_deswz_gpu; static id g_q; +#if !DM_NVN_M3 static id g_q4; static dispatch_queue_t g_feedback_q; +#endif static _Atomic uint32_t g_present_qos; #define ALLOC_MAX 8 -static id g_alloc4[ALLOC_MAX]; static int g_alloc_n, g_alloc_cur; // 主提交的命令分配器池:开工时挑一个 GPU 已用完的,没有就新建(到上限才等) | Command allocator pool of the main submission: at start pick one the GPU has finished with, create a new one if there is none (wait only at the cap) +static int g_alloc_n, g_alloc_cur; // 主提交的在途槽(Metal 4:每槽一个命令分配器;老接口:只用来限制在途提交数) | in-flight slots of the main submission (Metal 4: one command allocator per slot; older API: used only to limit the number of in-flight submissions) +#if !DM_NVN_M3 +static id g_alloc4[ALLOC_MAX]; // 主提交的命令分配器池:开工时挑一个 GPU 已用完的,没有就新建(到上限才等) | Command allocator pool of the main submission: at start pick one the GPU has finished with, create a new one if there is none (wait only at the cap) static id g_up_alloc4[3]; static id g_present_alloc4[3]; -static id g_present_cb[3]; +static CBUF g_present_cb[3]; static id g_vt, g_ft, g_ct, g_up_ct; static id g_present_args; +#endif static id g_present_uv[3]; int g_bloom_q = -1; // 泛光 1/4 起点(非 static:真机同进程交替直接改 0 / 1) | Bloom 1/4 starting point (non-static: real-device same-process alternation sets it to 0 / 1 directly) +#if !DM_NVN_M3 static id g_bloomq_args; +#endif static id g_bloomq_const[3]; static id g_bloomq_samp; static id g_bloomq_pso; @@ -99,6 +136,25 @@ static _Atomic int g_up_pending; static pthread_mutex_t g_res_mu = PTHREAD_MUTEX_INITIALIZER; // 驻留集专用锁:res_add 会在持 g_mu 的路径里调用(arena_new),不能共用 g_mu | Dedicated lock for the residency set: res_add is called on paths that hold g_mu (arena_new), so it cannot share g_mu static NSHashTable *g_res_objects; +#if DM_NVN_M3 +// 老接口按「缓冲对象 + 偏移」绑定,而回放层手里是显卡地址:登记过的缓冲(内存池的零拷贝缓冲、参数区块、暂存块等,几十个)按地址区间反查。 +// 弱引用登记(__unsafe_unretained + 撤驻留时摘掉);最近命中的那一项先试——同一通道里的绑定几乎都落在同一两个缓冲上 +// The older API binds by "buffer object + offset", while the replay layer holds GPU addresses: registered buffers (zero-copy buffers of memory pools, argument blocks, staging blocks and so on, a few dozen) are looked up by address range. +// Registered by weak reference (__unsafe_unretained, removed when residency is withdrawn); the most recently hit entry is tried first - bindings within one pass almost always land on the same one or two buffers +enum { M3_BUFS = 512 }; +static struct { uint64_t gpu, len; __unsafe_unretained id buf; } g_m3_bufs[M3_BUFS]; static int g_m3_nbufs; static os_unfair_lock g_m3_lk = OS_UNFAIR_LOCK_INIT; +static void m3_buf_add(id b) { os_unfair_lock_lock(&g_m3_lk); if (g_m3_nbufs < M3_BUFS) { g_m3_bufs[g_m3_nbufs].gpu = b.gpuAddress; g_m3_bufs[g_m3_nbufs].len = b.length; g_m3_bufs[g_m3_nbufs++].buf = b; } os_unfair_lock_unlock(&g_m3_lk); } +static void m3_buf_del(id b) { os_unfair_lock_lock(&g_m3_lk); for (int i = 0; i < g_m3_nbufs; i++) if (g_m3_bufs[i].buf == b) { g_m3_bufs[i] = g_m3_bufs[--g_m3_nbufs]; break; } os_unfair_lock_unlock(&g_m3_lk); } +static id m3_buf(uint64_t gpu, NSUInteger *off) { + static _Thread_local int last; id r = nil; *off = 0; if (!gpu) return nil; + os_unfair_lock_lock(&g_m3_lk); + int i = last < g_m3_nbufs && gpu >= g_m3_bufs[last].gpu && gpu - g_m3_bufs[last].gpu < g_m3_bufs[last].len ? last : -1; + for (int k = 0; i < 0 && k < g_m3_nbufs; k++) if (gpu >= g_m3_bufs[k].gpu && gpu - g_m3_bufs[k].gpu < g_m3_bufs[k].len) i = k; + if (i >= 0) { last = i; r = g_m3_bufs[i].buf; *off = (NSUInteger)(gpu - g_m3_bufs[i].gpu); } + os_unfair_lock_unlock(&g_m3_lk); + return r; +} +#endif // 测试开关 DM_RES_CENSUS=1(不常开):记下进过驻留集的全部对象(弱引用),内存读数行那一拍按「还在驻留集里 / 已移出驻留集却还没销毁」各报个数与占用。 // 后一类 = 我们已经不用、但还有人攥着引用(例如客体线程上从不排空的自动释放池)的显卡内存 // Test switch DM_RES_CENSUS=1 (not normally on): records every object that has entered the residency set (weak references); on the tick of the memory readout line it reports the count and size of those "still in the residency set" and those "removed from the residency set but not yet destroyed". @@ -110,6 +166,9 @@ static void res_add(id r) { [g_res addAllocation:(id)r]; if (!g_res_objects) g_res_objects = [NSHashTable weakObjectsHashTable]; [g_res_objects addObject:r]; +#if DM_NVN_M3 + if ([r conformsToProtocol:@protocol(MTLBuffer)]) m3_buf_add((id)r); +#endif if (g_res_census < 0) g_res_census = getenv("DM_RES_CENSUS") != NULL; if (g_res_census > 0) { if (!g_res_ever) g_res_ever = [NSHashTable weakObjectsHashTable]; [g_res_ever addObject:r]; } g_res_dirty = 1; @@ -120,6 +179,9 @@ static void res_remove(id r) { pthread_mutex_lock(&g_res_mu); [g_res removeAllocation:(id)r]; [g_res_objects removeObject:r]; +#if DM_NVN_M3 + m3_buf_del(r); +#endif g_res_dirty = 1; pthread_mutex_unlock(&g_res_mu); } @@ -273,13 +335,16 @@ void mtl_init(void) { if (!g_res) MDIE("建立 MTLResidencySet 失败"); [g_q addResidencySet:g_res]; { void crash_set_wait_dump(void (*fn)(void)); void mtl_wait_state_dump(void); crash_set_wait_dump(mtl_wait_state_dump); } +#if !DM_NVN_M3 dispatch_queue_attr_t feedback_attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INTERACTIVE, 0); g_feedback_q = dispatch_queue_create("dm.nvn.mtl4-feedback", feedback_attr); MTL4CommandQueueDescriptor *q4d = [MTL4CommandQueueDescriptor new]; q4d.feedbackQueue = g_feedback_q; g_q4 = [g_dev newMTL4CommandQueueWithDescriptor:q4d error:&re]; if (!g_q4) MDIE("建立 MTL4CommandQueue 失败"); [g_q4 addResidencySet:g_res]; +#endif g_alloc_n = 3; +#if !DM_NVN_M3 for (int i = 0; i < 3; i++) { MTL4CommandAllocatorDescriptor *ad = [MTL4CommandAllocatorDescriptor new]; ad.label = [NSString stringWithFormat:@"nvn-mtl allocator %d", i]; @@ -308,6 +373,7 @@ void mtl_init(void) { if (!g_present_args) MDIE("建立出图 argument table 失败:%s", ate.localizedDescription.UTF8String); g_bloomq_args = [g_dev newArgumentTableWithDescriptor:pad error:&ate]; if (!g_bloomq_args) MDIE("建立泛光 1/4 argument table 失败:%s", ate.localizedDescription.UTF8String); +#endif for (int i = 0; i < 3; i++) { g_present_uv[i] = [g_dev newBufferWithLength:sizeof(float) * 8 options:MTLResourceStorageModeShared]; if (!g_present_uv[i]) MDIE("建立出图 UV 缓冲[%d] 失败", i); @@ -428,7 +494,7 @@ static zskip_zero g_zskip_cand[8]; static uint8_t g_zskip_cand_ok[8]; static void zskip_clear(void); static int tbdr_on(void); static id g_cb; -static id g_blit; +static BENC g_blit; static NSMutableArray *g_commit_blocks; static uint64_t g_alloc_fence[ALLOC_MAX]; static uint64_t g_alloc_waits, g_alloc_grown; int mtl_wait(uint64_t fence, uint64_t timeout_ns); @@ -476,20 +542,30 @@ void mtl_sub_begin(void) { g_sub_thread = pthread_self(); atomic_store(&g_sub_thread_set, 1); atomic_store(&g_last_commit_error, 0); g_sub_pool = objc_autoreleasePoolPush(); +#if DM_NVN_M3 + g_cb = [g_q commandBuffer]; +#else g_cb = [g_dev newCommandBuffer]; +#endif // 不在帧中间等 GPU(真机热态:固定 3 个轮转时 GPU 跟不上就每帧在这里阻塞,提交线程睡醒后按低频跑,指令数 −18% 而 CPU 时间 +49%): // 挑一个 GPU 已用完的分配器;都在用就新建;到上限才等最老的那个。超前量由游戏取交换链贴图处的等待约束,与旧接口相同。 // Do not wait for the GPU mid-frame (hot real device: with a fixed rotation of 3, when the GPU cannot keep up every frame blocks here, and the submit thread runs at low frequency after waking, instruction count −18% but CPU time +49%): // pick an allocator the GPU has finished with; if all are in use create a new one; only at the cap wait for the oldest one. How far ahead it runs is bounded by the wait where the game acquires the swapchain texture, same as the old interface. int alloc_i = -1; uint64_t done = g_done; for (int i = 0; i < g_alloc_n; i++) if (g_alloc_fence[i] <= done) { alloc_i = i; break; } +#if DM_NVN_M3 + if (alloc_i < 0 && g_alloc_n < ALLOC_MAX) { alloc_i = g_alloc_n++; g_alloc_grown++; } +#else if (alloc_i < 0 && g_alloc_n < ALLOC_MAX) { NSError *ae = nil; MTL4CommandAllocatorDescriptor *ad = [MTL4CommandAllocatorDescriptor new]; g_alloc4[g_alloc_n] = [g_dev newCommandAllocatorWithDescriptor:ad error:&ae]; if (!g_alloc4[g_alloc_n]) MDIE("新建 MTL4CommandAllocator 失败:%s", ae.localizedDescription.UTF8String); alloc_i = g_alloc_n++; g_alloc_grown++; } +#endif if (alloc_i < 0) { alloc_i = 0; for (int i = 1; i < g_alloc_n; i++) if (g_alloc_fence[i] < g_alloc_fence[alloc_i]) alloc_i = i; g_alloc_waits++; mtl_wait(g_alloc_fence[alloc_i], UINT64_MAX); } g_alloc_cur = alloc_i; +#if !DM_NVN_M3 [g_alloc4[alloc_i] reset]; [g_cb beginCommandBufferWithAllocator:g_alloc4[alloc_i]]; +#endif g_commit_blocks = [NSMutableArray array]; g_npost = 0; g_vis = nil; g_vis_n = 0; g_vis_cur = -1; g_npend = 0; g_pend_over = 0; zskip_clear(); g_zskip_count = 0; @@ -521,43 +597,80 @@ static void ser_gate(void) { // 只放开头不够:t_rt_range「通道 1 → 通道 2 → 拷贝」读回黑色,补上结束处屏障后 19/19。旧队列的编码器(上传 / 诊断 / 上屏)不走这里的屏障。 // Metal 4 conservative barriers (first version): a consumer barrier at the start of an encoder (all prior work → this encoder) and a producer barrier at the end (this encoder and earlier → later encoders). // Only the one at the start is not enough: t_rt_range 'pass 1 → pass 2 → copy' read back black, and after adding the end barrier it is 19/19. Old-queue encoders (upload / diagnostics / present) do not go through these barriers. +#if DM_NVN_M3 +static inline void m4_end(id e) { [e endEncoding]; } // 老接口没有显式屏障:依赖关系由 useResource 声明 + 系统自动跟踪 | the older API has no explicit barriers: dependencies come from useResource declarations plus the system's automatic tracking +static inline void m3_rbuf(id e, int vertex, NSUInteger i, uint64_t gpu) { + NSUInteger off; id b = m3_buf(gpu, &off); if (gpu && !b) { { static int n_; if (!n_++) MLOG("【红】" "老接口绑定:显卡地址 %#llx 不在任何登记过的缓冲里(槽 %lu)", (unsigned long long)gpu, (unsigned long)i); } return; } + if (vertex) [e setVertexBuffer:b offset:off atIndex:i]; else [e setFragmentBuffer:b offset:off atIndex:i]; +} +#else static inline void m4_end(id e) { if ([e conformsToProtocol:@protocol(MTL4CommandEncoder)]) [(id)e barrierAfterStages:MTLStageAll beforeQueueStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice]; [e endEncoding]; } -static inline id enc_r_begin(MTL4RenderPassDescriptor *d) { id e = [g_cb renderCommandEncoderWithDescriptor:d]; [e barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice]; [e setArgumentTable:g_vt atStages:MTLRenderStageVertex]; [e setArgumentTable:g_ft atStages:MTLRenderStageFragment]; return e; } +#endif +#if DM_NVN_M3 +static inline RENC enc_r_begin(RPD *d) { return [g_cb renderCommandEncoderWithDescriptor:d]; } +#else +static inline RENC enc_r_begin(RPD *d) { RENC e = [g_cb renderCommandEncoderWithDescriptor:d]; [e barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice]; [e setArgumentTable:g_vt atStages:MTLRenderStageVertex]; [e setArgumentTable:g_ft atStages:MTLRenderStageFragment]; return e; } +#endif static inline void enc_r_end(id e) { m4_end(e); } -static inline void enc_r_pso(id e, id p) { [e setRenderPipelineState:p]; } -static inline void enc_r_dss(id e, id s) { [e setDepthStencilState:s]; } -static inline void enc_r_viewport(id e, MTLViewport v) { [e setViewport:v]; } -static inline void enc_r_scissor(id e, MTLScissorRect r) { [e setScissorRect:r]; } -static inline void enc_r_cull(id e, MTLCullMode m) { [e setCullMode:m]; } -static inline void enc_r_winding(id e, MTLWinding w) { [e setFrontFacingWinding:w]; } -static inline void enc_r_fill(id e, MTLTriangleFillMode m) { [e setTriangleFillMode:m]; } -static inline void enc_r_depth_bias(id e, float u, float s, float c) { [e setDepthBias:u slopeScale:s clamp:c]; } -static inline void enc_r_depth_clip(id e, BOOL v) { [e setDepthClipMode:v ? MTLDepthClipModeClip : MTLDepthClipModeClamp]; } -static inline void enc_r_stencil_ref(id e, uint32_t f, uint32_t b) { (void)b; [e setStencilReferenceValue:f]; } -static inline void enc_r_blend_color(id e, float r, float g, float b, float a) { [e setBlendColorRed:r green:g blue:b alpha:a]; } -static inline void enc_r_visibility(id e, MTLVisibilityResultMode m, NSUInteger o) { [e setVisibilityResultMode:m offset:o]; } -static inline void enc_r_vbuf(id e, NSUInteger i, uint64_t gpu) { (void)e; [g_vt setAddress:gpu atIndex:i]; } -static inline void enc_r_args(id e, MTLRenderStages s, uint64_t gpu, NSUInteger i) { (void)e; [(s == MTLRenderStageVertex ? g_vt : g_ft) setAddress:gpu atIndex:i]; } -static inline void enc_r_draw(id e, MTLPrimitiveType p, NSUInteger v, NSUInteger n) { [e drawPrimitives:p vertexStart:v vertexCount:n]; } -static inline void enc_r_draw_instanced(id e, MTLPrimitiveType p, NSUInteger v, NSUInteger n, NSUInteger i, NSUInteger b) { [e drawPrimitives:p vertexStart:v vertexCount:n instanceCount:i baseInstance:b]; } -static inline void enc_r_draw_indexed(id e, MTLPrimitiveType p, NSUInteger n, MTLIndexType t, uint64_t gpu, NSUInteger len, NSUInteger i, NSInteger bv, NSUInteger bi) { [e drawIndexedPrimitives:p indexCount:n indexType:t indexBuffer:gpu indexBufferLength:len instanceCount:i baseVertex:bv baseInstance:bi]; } -static inline id enc_c_begin(MTLComputePassDescriptor *d) { (void)d; id e = [g_cb computeCommandEncoder]; [e barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice]; [e setArgumentTable:g_ct]; return e; } +static inline void enc_r_pso(RENC e, id p) { [e setRenderPipelineState:p]; } +static inline void enc_r_dss(RENC e, id s) { [e setDepthStencilState:s]; } +static inline void enc_r_viewport(RENC e, MTLViewport v) { [e setViewport:v]; } +static inline void enc_r_scissor(RENC e, MTLScissorRect r) { [e setScissorRect:r]; } +static inline void enc_r_cull(RENC e, MTLCullMode m) { [e setCullMode:m]; } +static inline void enc_r_winding(RENC e, MTLWinding w) { [e setFrontFacingWinding:w]; } +static inline void enc_r_fill(RENC e, MTLTriangleFillMode m) { [e setTriangleFillMode:m]; } +static inline void enc_r_depth_bias(RENC e, float u, float s, float c) { [e setDepthBias:u slopeScale:s clamp:c]; } +static inline void enc_r_depth_clip(RENC e, BOOL v) { [e setDepthClipMode:v ? MTLDepthClipModeClip : MTLDepthClipModeClamp]; } +static inline void enc_r_stencil_ref(RENC e, uint32_t f, uint32_t b) { (void)b; [e setStencilReferenceValue:f]; } +static inline void enc_r_blend_color(RENC e, float r, float g, float b, float a) { [e setBlendColorRed:r green:g blue:b alpha:a]; } +static inline void enc_r_visibility(RENC e, MTLVisibilityResultMode m, NSUInteger o) { [e setVisibilityResultMode:m offset:o]; } +#if DM_NVN_M3 +static inline void enc_r_vbuf(RENC e, NSUInteger i, uint64_t gpu) { m3_rbuf(e, 1, i, gpu); } +static inline void enc_r_args(RENC e, MTLRenderStages s, uint64_t gpu, NSUInteger i) { m3_rbuf(e, s == MTLRenderStageVertex, i, gpu); } +#else +static inline void enc_r_vbuf(RENC e, NSUInteger i, uint64_t gpu) { (void)e; [g_vt setAddress:gpu atIndex:i]; } +static inline void enc_r_args(RENC e, MTLRenderStages s, uint64_t gpu, NSUInteger i) { (void)e; [(s == MTLRenderStageVertex ? g_vt : g_ft) setAddress:gpu atIndex:i]; } +#endif +static inline void enc_r_draw(RENC e, MTLPrimitiveType p, NSUInteger v, NSUInteger n) { [e drawPrimitives:p vertexStart:v vertexCount:n]; } +static inline void enc_r_draw_instanced(RENC e, MTLPrimitiveType p, NSUInteger v, NSUInteger n, NSUInteger i, NSUInteger b) { [e drawPrimitives:p vertexStart:v vertexCount:n instanceCount:i baseInstance:b]; } +#if DM_NVN_M3 +static inline void enc_r_draw_indexed(RENC e, MTLPrimitiveType p, NSUInteger n, MTLIndexType t, uint64_t gpu, NSUInteger len, NSUInteger i, NSInteger bv, NSUInteger bi) { (void)len; if (!n) return; NSUInteger off; id b = m3_buf(gpu, &off); if (!b) { { static int n_; if (!n_++) MLOG("【红】" "老接口绘制:索引缓冲地址 %#llx 不在任何登记过的缓冲里", (unsigned long long)gpu); } return; } [e drawIndexedPrimitives:p indexCount:n indexType:t indexBuffer:b indexBufferOffset:off instanceCount:i baseVertex:bv baseInstance:bi]; } +#else +static inline void enc_r_draw_indexed(RENC e, MTLPrimitiveType p, NSUInteger n, MTLIndexType t, uint64_t gpu, NSUInteger len, NSUInteger i, NSInteger bv, NSUInteger bi) { [e drawIndexedPrimitives:p indexCount:n indexType:t indexBuffer:gpu indexBufferLength:len instanceCount:i baseVertex:bv baseInstance:bi]; } +#endif +#if DM_NVN_M3 +static inline CENC enc_c_begin(MTLComputePassDescriptor *d) { return d ? [g_cb computeCommandEncoderWithDescriptor:d] : [g_cb computeCommandEncoder]; } +#else +static inline CENC enc_c_begin(MTLComputePassDescriptor *d) { (void)d; CENC e = [g_cb computeCommandEncoder]; [e barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice]; [e setArgumentTable:g_ct]; return e; } +#endif static inline id enc_c_begin_concurrent(id cb) { return [cb computeCommandEncoderWithDispatchType:MTLDispatchTypeConcurrent]; } static inline void enc_c_end(id e) { m4_end(e); } static inline void enc_c_pso(id e, id p) { [e setComputePipelineState:p]; } +#if DM_NVN_M3 +static inline void enc_c_args(id e, uint64_t gpu, NSUInteger i) { NSUInteger off; id b = m3_buf(gpu, &off); if (gpu && !b) { { static int n_; if (!n_++) MLOG("【红】" "老接口计算绑定:显卡地址 %#llx 不在任何登记过的缓冲里(槽 %lu)", (unsigned long long)gpu, (unsigned long)i); } return; } [(id)e setBuffer:b offset:off atIndex:i]; } +#else static inline void enc_c_args(id e, uint64_t gpu, NSUInteger i) { (void)e; [g_ct setAddress:gpu atIndex:i]; } +#endif static inline void enc_c_dispatch(id e, MTLSize n, MTLSize t) { [e dispatchThreadgroups:n threadsPerThreadgroup:t]; } +#if DM_NVN_M3 +static inline id enc_b_begin(id cb) { return [cb blitCommandEncoder]; } +#else static inline id enc_b_begin(id cb) { return [cb respondsToSelector:@selector(beginCommandBufferWithAllocator:)] ? [cb computeCommandEncoder] : [cb blitCommandEncoder]; } +#endif static inline void enc_b_end(id e) { m4_end(e); } static inline void enc_b_copy_buffer(id e, id s, NSUInteger so, id d, NSUInteger doff, NSUInteger n) { [e copyFromBuffer:s sourceOffset:so toBuffer:d destinationOffset:doff size:n]; } static inline void enc_b_copy_buffer_texture(id e, id s, NSUInteger so, NSUInteger row, NSUInteger img, MTLSize z, id d, NSUInteger sl, NSUInteger lv, MTLOrigin o) { [e copyFromBuffer:s sourceOffset:so sourceBytesPerRow:row sourceBytesPerImage:img sourceSize:z toTexture:d destinationSlice:sl destinationLevel:lv destinationOrigin:o]; } static inline void enc_b_copy_texture_buffer(id e, id s, NSUInteger sl, NSUInteger lv, MTLOrigin o, MTLSize z, id d, NSUInteger doff, NSUInteger row, NSUInteger img) { [e copyFromTexture:s sourceSlice:sl sourceLevel:lv sourceOrigin:o sourceSize:z toBuffer:d destinationOffset:doff destinationBytesPerRow:row destinationBytesPerImage:img]; } static inline void enc_b_copy_texture(id e, id s, NSUInteger sl, NSUInteger lv, MTLOrigin so, MTLSize z, id d, NSUInteger dl, NSUInteger dv, MTLOrigin doo) { [e copyFromTexture:s sourceSlice:sl sourceLevel:lv sourceOrigin:so sourceSize:z toTexture:d destinationSlice:dl destinationLevel:dv destinationOrigin:doo]; } static void blit_note(void); // 逐通道转储:拷贝 / 缓冲更新结束了渲染通道(定义在 PD 之后) | Per-pass dump: a copy / buffer update ended the render pass (defined after PD) -static id blit(void) { blit_note(); rp_end(); if (!g_blit) { ser_gate(); g_blit = enc_b_begin(g_cb); [g_blit barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice]; } return g_blit; } +#if DM_NVN_M3 +static BENC blit(void) { blit_note(); rp_end(); if (!g_blit) { ser_gate(); g_blit = enc_b_begin(g_cb); } return g_blit; } +#else +static BENC blit(void) { blit_note(); rp_end(); if (!g_blit) { ser_gate(); g_blit = enc_b_begin(g_cb); [g_blit barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice]; } return g_blit; } +#endif void mtl_sub_copy(uint64_t src, uint64_t dst, uint64_t n) { if (g_npend < PEND_MAX) { g_pend_lo[g_npend] = dst; g_pend_hi[g_npend++] = dst + n; } else g_pend_over = 1; @@ -699,11 +812,13 @@ uint64_t mtl_sub_commit(void) { int n = g_npost; post_op *ops = n ? malloc(n * sizeof *ops) : NULL; if (n) memcpy(ops, g_post, n * sizeof *ops); NSArray *commit_blocks = [g_commit_blocks copy]; +#if !DM_NVN_M3 MTL4CommitOptions *o = [MTL4CommitOptions new]; - [o addFeedbackHandler:^(id f) { (void)f; for (dispatch_block_t block in commit_blocks) block(); }]; +#endif + [FB_ON(o, g_cb) FB_SEL:^(FB_ARG f) { (void)f; for (dispatch_block_t block in commit_blocks) block(); }]; uint64_t gpu_f = atomic_load(&g_cur_frame); gpu_tag_begin(gpu_f); NSString *cctx = @(cctx_snap()); - [o addFeedbackHandler:^(id cb) { + [FB_ON(o, g_cb) FB_SEL:^(FB_ARG cb) { gpu_tag_done(gpu_f, cb.GPUStartTime, cb.GPUEndTime); if (cb.error) { atomic_store(&g_last_commit_error, 1); static int n, nv; int victim = [cb.error.description containsString:@"InnocentVictim"]; if (victim ? nv++ < 1 : n++ < 8) MLOG("【红】命令缓冲错误详情 fence=%llu:%s | GPU %.3f→%.3f", (unsigned long long)fence, cb.error.description.UTF8String, cb.GPUStartTime, cb.GPUEndTime); if (!victim) MLOG("【红】出错那次提交的现场 fence=%llu:%s", (unsigned long long)fence, cctx.UTF8String); MLOG("【红】命令缓冲执行出错:%s", cb.error.localizedDescription.UTF8String); } for (int i = 0; i < n; i++) { @@ -721,10 +836,15 @@ uint64_t mtl_sub_commit(void) { }]; void arena_commit(uint64_t fence); arena_commit(fence); res_commit(); +#if DM_NVN_M3 + [g_cb encodeSignalEvent:g_ev value:fence]; + [g_cb commit]; +#else [g_cb endCommandBuffer]; - id buffers[] = {g_cb}; + CBUF buffers[] = {g_cb}; [g_q4 commit:buffers count:1 options:o]; [g_q4 signalEvent:g_ev value:fence]; +#endif g_alloc_fence[g_alloc_cur] = fence; g_cb = nil; g_commit_blocks = nil; @@ -857,7 +977,7 @@ static id tex_upgrade_pfv(const tex_t *t, id base, MTLPi id upgraded = [g_dev newTextureWithDescriptor:d]; if (!upgraded) { RED_ONCE(45, "贴图升级失败 ser=%llu 格式 %lu → %lu", t->serial, (unsigned long)base.pixelFormat, (unsigned long)view_pf); return base; } res_add(upgraded); - id b = blit(); + BENC b = blit(); NSUInteger slices = base.textureType == MTLTextureType3D ? 1 : base.arrayLength * (base.textureType == MTLTextureTypeCube || base.textureType == MTLTextureTypeCubeArray ? 6 : 1); for (NSUInteger l = 0; l < base.mipmapLevelCount; l++) { NSUInteger w = MAX(base.width >> l, 1u), h = MAX(base.height >> l, 1u), z = base.textureType == MTLTextureType3D ? MAX(base.depth >> l, 1u) : 1; @@ -880,8 +1000,8 @@ static id tex_upgrade_pfv(const tex_t *t, id base, MTLPi // the same queue executes in commit order ⇒ uploads are always finished before the first sample. Uploads outside a submission are flushed on the spot. The staging area is cut from 32 MB private blocks, held by the command buffer until completion. static _Atomic uint64_t g_upload_ns; // 提交线程上解排布 + 上传编码的累计耗时(计时埋点) | Cumulative time of deswizzle + upload encoding on the submit thread (timing instrumentation) static _Atomic uint64_t g_upload_gpu_ns; -static id g_up_cb; -static id g_up_ce; +static CBUF g_up_cb; +static CENC g_up_ce; static _Atomic int g_up_alloc_busy[3]; static unsigned g_up_seq; #define UP_BLOCK_SIZE (32u * 1024u * 1024u) @@ -957,7 +1077,25 @@ static void up_flush(void) { if (g_up_ce) { m4_end(g_up_ce); g_up_ce = nil; } - id b = g_nup_blits || g_nup_decs ? g_up_ce = [g_up_cb computeCommandEncoder] : nil; +#if DM_NVN_M3 + // 老接口:拷贝与计算是两种编码器——先一个拷贝编码器做「暂存块 → 贴图」,再一个计算编码器做无 BC 的 GPU 解压 + // Older API: copy and compute are two kinds of encoder - first a copy encoder does "staging block -> texture", then a compute encoder does the GPU decompression for devices without BC + BENC b = g_nup_blits ? [g_up_cb blitCommandEncoder] : nil; + for (int i = 0; b && i < g_nup_blits; i++) { + up_blit *x = &g_up_blits[i]; + enc_b_copy_buffer_texture(b, x->src, x->off, x->row, x->image, x->size, x->dst, x->slice, x->level, MTLOriginMake(0, 0, 0)); + } + [b endEncoding]; + CENC dc = g_nup_decs ? [g_up_cb computeCommandEncoder] : nil; + if (dc) { + [dc setComputePipelineState:bcd_pso()]; + for (int i = 0; i < g_nup_decs; i++) { up_dec *x = &g_up_decs[i]; + [dc setBuffer:x->src offset:0 atIndex:0]; [dc setBuffer:x->params offset:x->poff atIndex:1]; [dc setTexture:x->view atIndex:0]; + [dc dispatchThreadgroups:MTLSizeMake((x->bw + 7) / 8, (x->bh + 7) / 8, 1) threadsPerThreadgroup:MTLSizeMake(8, 8, 1)]; } + } + [dc endEncoding]; g_up_ce = nil; +#else + CENC b = g_nup_blits || g_nup_decs ? g_up_ce = [g_up_cb computeCommandEncoder] : nil; if (b) [b barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice]; for (int i = 0; b && i < g_nup_blits; i++) { up_blit *x = &g_up_blits[i]; @@ -970,13 +1108,16 @@ static void up_flush(void) { [b dispatchThreadgroups:MTLSizeMake((x->bw + 7) / 8, (x->bh + 7) / 8, 1) threadsPerThreadgroup:MTLSizeMake(8, 8, 1)]; } } if (b) { m4_end(b); g_up_ce = nil; } - id cb = g_up_cb; +#endif + CBUF cb = g_up_cb; unsigned slot = (g_up_seq - 1) % 3; NSMutableArray *dsts = [NSMutableArray arrayWithCapacity:(NSUInteger)g_nup_blits]; for (int i = 0; i < g_nup_blits; i++) if (g_up_blits[i].dst) [dsts addObject:g_up_blits[i].dst]; static int lost_at = -2; static uint64_t batch_n; if (lost_at == -2) { const char *e = getenv("DM_TEST_UP_LOST"); lost_at = e ? atoi(e) : -1; } int fake_lost = dsts.count && lost_at > 0 && (int)++batch_n == lost_at; +#if !DM_NVN_M3 MTL4CommitOptions *o = [MTL4CommitOptions new]; +#endif atomic_fetch_add(&g_up_pending, 1); - [o addFeedbackHandler:^(id f) { + [FB_ON(o, cb) FB_SEL:^(FB_ARG f) { if (f.error) MLOG("【红】上传命令缓冲执行出错:%s", f.error.description.UTF8String); if (f.error || fake_lost) { os_unfair_lock_lock(&g_up_lost_lk); if (!g_up_lost) g_up_lost = [NSHashTable weakObjectsHashTable]; for (id d in dsts) [g_up_lost addObject:d]; int n = (int)g_up_lost.allObjects.count; atomic_store(&g_up_lost_n, n); os_unfair_lock_unlock(&g_up_lost_lk); @@ -989,9 +1130,13 @@ static void up_flush(void) { atomic_fetch_sub(&g_up_pending, 1); }]; res_commit(); +#if DM_NVN_M3 + [cb commit]; +#else [cb endCommandBuffer]; - id buffers[] = {cb}; + CBUF buffers[] = {cb}; [g_q4 commit:buffers count:1 options:o]; +#endif 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]; @@ -1006,12 +1151,17 @@ static void up_begin(void) { unsigned slot = g_up_seq++ % 3; while (atomic_load(&g_up_alloc_busy[slot])) usleep(1000); atomic_store(&g_up_alloc_busy[slot], 1); +#if DM_NVN_M3 + g_up_cb = [g_q commandBuffer]; + g_up_ce = [g_up_cb computeCommandEncoder]; +#else [g_up_alloc4[slot] reset]; g_up_cb = [g_dev newCommandBuffer]; [g_up_cb beginCommandBufferWithAllocator:g_up_alloc4[slot]]; g_up_ce = [g_up_cb computeCommandEncoder]; [g_up_ce barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice]; [g_up_ce setArgumentTable:g_up_ct]; +#endif if (!g_up_texs) g_up_texs = [NSMutableArray array]; if (!g_up_keep) g_up_keep = [NSMutableArray array]; } @@ -1125,8 +1275,12 @@ static id pkg_upload_(const tex_t *t, uint64_t *stamp) { uint32_t w = MAX(t->d.width >> l, 1u), h = MAX(t->d.height >> l, 1u), z = t->d.target == 2 ? MAX(t->d.depth >> l, 1u) : 1; size_t pitch = (size_t)((w + bw - 1) / bw) * bpb, rows = (h + bh - 1) / bh; for (unsigned y = 0; y < layers; y++) { +#if DM_NVN_M3 + if (nvn_deswz_gpu_encode(g_up_ce, (__bridge id)mb, mo, &t->d, l, y, stg, stg_off + off, pitch)) { enc_ok = 0; break; } +#else size_t poff; id params = up_param_alloc(&poff); // Metal 4 无 setBytes:每次解排布的参数块从共享块里切(不逐次新建 GPU 缓冲) | Metal 4 has no setBytes: the parameter block of each deswizzle is cut from a shared block (no new GPU buffer each time) if (nvn_deswz_gpu_encode_m4(g_up_ce, g_up_ct, params, poff, (__bridge id)mb, mo, &t->d, l, y, stg, stg_off + off, pitch)) { enc_ok = 0; break; } +#endif if (gdec) { // 解压任务:冲刷时过了屏障再派发(见 up_flush) | Decompression job: dispatched at flush time after the barrier (see up_flush) MTLPixelFormat vf = mt.pixelFormat == MTLPixelFormatRGBA8Unorm_sRGB ? MTLPixelFormatRGBA8Unorm : mt.pixelFormat; id v = [mt newTextureViewWithPixelFormat:vf textureType:MTLTextureType2D levels:NSMakeRange(l, 1) slices:NSMakeRange(y, 1)]; @@ -1310,7 +1464,7 @@ static void rr_begin(void), rr_finish(int ranged); static void rr_snap(const p_draw *, const p_draw_idx *); static void rr_reset(void); #endif -static id g_enc; +static RENC g_enc; // 当前渲染通道的目标信息:rp_begin 时由附件定一次,通道内各绘制共用(管线键、深度模板、视口 / 剪裁都只依赖它) // Target info of the current render pass: determined once from the attachments at rp_begin and shared by all draws in the pass (pipeline key, depth-stencil, viewport / scissor all depend only on it) static struct { uint32_t cfmt[8], dfmt, sfmt, samples; int hd, hs; NSUInteger tw, th; uint64_t serial, reg_gen, ser_gen, range_dirty; int range_external, range_depth_nonro; __unsafe_unretained id range_color, range_depth; } g_pass; @@ -1388,7 +1542,7 @@ static uint64_t att_bytes(id t, NSUInteger level) { static NSUInteger mip_extent(NSUInteger size, NSUInteger level) { return level < sizeof(size) * 8 ? MAX(size >> level, 1) : 1; } -static void pass_dims(MTL4RenderPassDescriptor *pd, NSUInteger nc, NSUInteger *w, NSUInteger *h) { +static void pass_dims(RPD *pd, NSUInteger nc, NSUInteger *w, NSUInteger *h) { *w = *h = 0; for (NSUInteger i = 0; i < nc + 2; i++) { MTLRenderPassAttachmentDescriptor *a = i < nc ? pd.colorAttachments[i] : i == nc ? pd.depthAttachment : pd.stencilAttachment; @@ -1449,7 +1603,7 @@ static pg_pass *pg_new(int kind, int nslot) { g_pg_used += nslot; return p; } -static void pg_render(MTL4RenderPassDescriptor *pd, NSUInteger nc) { +static void pg_render(RPD *pd, NSUInteger nc) { (void)pd; (void)nc; return; #if 0 @@ -1684,9 +1838,9 @@ static void attach(MTLRenderPassAttachmentDescriptor *a, const tex_t *t, const v // mode 1 (clear_only): a pass opened only to land pending clears, attaching only the attachments that have clears; mode 2: the lookahead proves this pass does not use depth-stencil, so depth is not attached. // clear_only: a pass opened only to land pending clears, attaching only the attachments that have clears - the other attachments are not touched by this pass, and attaching them costs a pointless load and store on TBDR // (Mac character select screen: the color-clear pass drags along a 400x225 depth load and store) -static id rp_begin_ex(int clear_only); -static id rp_begin(void) { return rp_begin_ex(0); } -static id rp_begin_ex(int clear_only) { +static RENC rp_begin_ex(int clear_only); +static RENC rp_begin(void) { return rp_begin_ex(0); } +static RENC rp_begin_ex(int clear_only) { if (g_enc) return g_enc; memset(g_zskip_cand_ok, 0, sizeof g_zskip_cand_ok); g_enc_mode = clear_only; @@ -1697,7 +1851,7 @@ static id rp_begin_ex(int clear_only) { if (rt_range_on()) { reg0 = g_reg_gen; ser0 = g_ser_gen; } if (rt_range_on()) dirty0=nvn_dirty_now(); if (g_blit) { enc_b_end(g_blit); g_blit = nil; } - MTL4RenderPassDescriptor *pd = [MTL4RenderPassDescriptor new]; + RPD *pd = [RPD new]; 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; @@ -2711,7 +2865,18 @@ static int encode_args(id en, NvShader *sh, int nvn_stage, in g_stat_args_reuse++; return 1; } +#if DM_NVN_M3 + // 老接口:着色器经参数块间接访问的每个资源都要在本编码器上声明用途,系统才知道它和别的编码器(上传拷贝、别的通道)之间的先后依赖; + // 不声明的话只读贴图会和写它的拷贝乱序(迁 Metal 4 前实测过)。同一编码器内重复声明是幂等的 + // Older API: every resource a shader accesses indirectly through an argument block must have its usage declared on this encoder, so that the system knows its ordering dependency against other encoders (upload copies, other passes); + // without the declaration a read-only texture gets out of order with the copy that writes it (measured before the move to Metal 4). Repeated declarations within one encoder are idempotent + #define USE(r, u) do { id r_ = (id)(r); if (r_) { if (nvn_stage == 5) [(id)en useResource:r_ usage:(u)]; else [(id)en useResource:r_ usage:(u) stages:MTLRenderStageVertex | MTLRenderStageFragment]; } \ + if (__builtin_expect(g_res_check_on, 0)) res_check((r), sh->key, reg); } while (0) + #define USE_SAMP(r, u) do { (void)(u); if (__builtin_expect(g_res_check_on, 0)) res_check((r), sh->key, reg); } while (0) // 采样器不是资源,不用声明 | samplers are not resources and need no declaration +#else #define USE(r, u) do { (void)(u); if (__builtin_expect(g_res_check_on, 0)) res_check((r), sh->key, reg); } while (0) + #define USE_SAMP(r, u) USE(r, u) +#endif // DM_NVN_PASSDUMP:每通道每阶段第一次新编时记着色器键(K)与各绑定的实际来源(B:UBO 地址 / 长度 / 前 4 个浮点,贴图号与序号或「哑」) // DM_NVN_PASSDUMP: on the first new encode per pass per stage, records the shader key (K) and the actual source of each binding (B: UBO address / length / first 4 floats, texture ID and serial, or 「哑」(dummy)) static uint64_t bl_pass[6]; static int bl_all = -1; if (bl_all < 0) bl_all = getenv("DM_NVN_PASSDUMP_ALL") != NULL; // 每次新编都记(否则只记每通道每阶段第一次) | Record on every new encode (otherwise only the first time per pass per stage) @@ -2744,7 +2909,7 @@ static int encode_args(id en, NvShader *sh, int nvn_stage, in int sid = reg < 128 ? (int)((b->kind == NVN_RB_SAMPT ? S.tex[nvn_stage][reg] : S.samp[nvn_stage][reg]) >> 20) : 0; __unsafe_unretained id ss = sid ? (__bridge id)samp_fast(sid) : nil; slots[aid] = sid && sid < g_nsreg && g_srid[sid] ? g_srid[sid] : dummy_samp_rid(); - USE(ss ? ss : dummy_samp(), MTLResourceUsageRead); + USE_SAMP(ss ? ss : dummy_samp(), MTLResourceUsageRead); if (bl && sid > 0) { int ok = sid < g_nsreg && g_sreg_ok[sid]; samp_par sp = ok ? g_sreg[sid] : (samp_par){0}; // 本段已持 g_rmu | g_rmu is already held in this section if (ok) PD("B %llu st%d samp reg%d sid=%d mag=%d min=%d(0 最近点 / 1 双线性;2–5 带 mip)", g_stat_pass, nvn_stage, reg, sid, (int)sp.magf, (int)sp.minf); } } else if (b->kind == NVN_RB_TEX) { @@ -2810,6 +2975,7 @@ static int encode_args(id en, NvShader *sh, int nvn_stage, in } else RED_ONCE(46, "绑定种类 %d 未实现", b->kind); } #undef USE + #undef USE_SAMP pthread_mutex_unlock(&g_rmu); NSUInteger arg_len = sh->arg_len ? sh->arg_len : sh->ae.encodedLength; id ab; size_t off = arena_alloc(arg_len, &ab); @@ -2820,7 +2986,7 @@ static int encode_args(id en, NvShader *sh, int nvn_stage, in return 1; } static id g_quad_ib; static uint64_t g_quad_gpu; -static id rp_begin(void); +static RENC rp_begin(void); // ---------- 通道前瞻:本通道是否用到深度 / 模板 ---------- // 开通道时从当前绘制的下一条起往后扫,模拟深度模板状态的变化,直到本通道必然结束处(重设目标、拷贝、计算派发—— // 与回放里结束通道的操作一一对应)。期间没有任何绘制开深度测试 / 深度写 / 模板测试,则本通道可不挂深度附件: @@ -3553,7 +3719,7 @@ static void fz_check_run(const fuse_t *fz) { for (int a = 0; a < na; a++) { id t = att[a], c = scr[a]; NSUInteger W = t.width, H = t.height, bpp = (NSUInteger)(att_bytes(t, 0) / (W * H)); id b1 = [g_dev newBufferWithLength:W * H * bpp options:MTLResourceStorageModeShared], b2 = [g_dev newBufferWithLength:W * H * bpp options:MTLResourceStorageModeShared]; - id b = blit(); + BENC b = blit(); enc_b_copy_texture_buffer(b, c, 0, 0, MTLOriginMake(0, 0, 0), MTLSizeMake(W, H, 1), b1, 0, W * bpp, W * H * bpp); enc_b_copy_texture_buffer(b, t, 0, 0, MTLOriginMake(0, 0, 0), MTLSizeMake(W, H, 1), b2, 0, W * bpp, W * H * bpp); unsigned long long ser = sers[a], pass = g_stat_pass, frame = atomic_load(&g_cur_frame); NSUInteger nb = W * H * bpp; @@ -4154,11 +4320,16 @@ static int bloomq_capture(void) { id dst = base; if (lv || sl) { static id vb; static int vl, vs; if (vb != base || vl != lv || vs != sl) { defer_obj_release(g_bloomq_view); /* 旧视图退役(原先直接被覆盖:留在驻留集里,连带钉住旧底图) | retire the old view (it used to be overwritten directly: it stayed in the residency set and pinned the old base texture with it) */ g_bloomq_view = [base newTextureViewWithPixelFormat:base.pixelFormat textureType:base.textureType levels:NSMakeRange(lv, 1) slices:NSMakeRange(sl, 1)]; if (g_bloomq_view) res_add(g_bloomq_view); vb = base; vl = lv; vs = sl; } dst = g_bloomq_view; } if (!dst || !bloomq_make_pipeline(dst.pixelFormat)) return 0; rp_end(); - MTL4RenderPassDescriptor *rp = [MTL4RenderPassDescriptor new]; rp.colorAttachments[0].texture = dst; rp.colorAttachments[0].loadAction = MTLLoadActionDontCare; rp.colorAttachments[0].storeAction = MTLStoreActionStore; - id en = [g_cb renderCommandEncoderWithDescriptor:rp]; if (!en) return 0; + RPD *rp = [RPD new]; rp.colorAttachments[0].texture = dst; rp.colorAttachments[0].loadAction = MTLLoadActionDontCare; rp.colorAttachments[0].storeAction = MTLStoreActionStore; + RENC en = [g_cb renderCommandEncoderWithDescriptor:rp]; if (!en) return 0; +#if DM_NVN_M3 + [en setFragmentTexture:src atIndex:0]; [en setFragmentSamplerState:g_bloomq_samp atIndex:0]; + float *p = g_bloomq_const[g_bloomq_i].contents; p[0] = g_bloomq.threshold; p[1] = g_bloomq.coeff_g; p[2] = g_bloomq.coeff_b; p[3] = src.width; p[4] = src.height; [en setFragmentBuffer:g_bloomq_const[g_bloomq_i] offset:0 atIndex:0]; +#else [en barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice]; [en setArgumentTable:g_bloomq_args atStages:MTLRenderStageFragment]; [g_bloomq_args setTexture:src.gpuResourceID atIndex:0]; [g_bloomq_args setSamplerState:g_bloomq_samp.gpuResourceID atIndex:0]; float *p = g_bloomq_const[g_bloomq_i].contents; p[0] = g_bloomq.threshold; p[1] = g_bloomq.coeff_g; p[2] = g_bloomq.coeff_b; p[3] = src.width; p[4] = src.height; [g_bloomq_args setAddress:g_bloomq_const[g_bloomq_i].gpuAddress atIndex:0]; +#endif [en setViewport:(MTLViewport){0,0,dst.width,dst.height,0,1}]; [en setRenderPipelineState:g_bloomq_pso]; [en drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3]; m4_end(en); g_bloomq_i = (g_bloomq_i + 1) % 3; args_dirty_all(); g_pso_dirty = g_dss_dirty = 1; return 1; } @@ -4557,7 +4728,10 @@ static const char k_lut_msl[] = " float s = smoothstep(0.65, 1.0, dot(b.rgb, float3(0.2126, 0.7152, 0.0722)));\n" // 高光保护:提亮后越接近白,越收回原值(雪、天光不糊成一片白);暗处 s = 0 照常提亮 | Highlight protection: after brightening, the closer to white, the more it is pulled back to the original value (snow and skylight do not blur into a sheet of white); in dark areas s = 0 and brightening proceeds as usual " dst.write(float4(max(mix(b.rgb, o.rgb, s), o.rgb), b.a), g); }\n"; static void bright_lut(NvShader *cs) { - static int failed; static id ps; static id at; static id tmp; static id kb[3]; static int ki; + static int failed; static id ps; static id tmp; static id kb[3]; static int ki; +#if !DM_NVN_M3 + static id at; +#endif if (failed || strncmp(cs->key, "552f45c348a61b86", 16)) return; float k = dm_bright_k(); if (!(k > 1.005f)) return; // k ≈ 1(局外 / 正午):表保持原版 | k ~= 1 (out of game / noon): the table stays as in the original game if (k > 4.0f) k = 4.0f; @@ -4566,16 +4740,23 @@ static void bright_lut(NvShader *cs) { if (!lut || lut.textureType != MTLTextureType3D || !(lut.usage & MTLTextureUsageShaderWrite)) { static int n; if (!n++) MLOG("【红】3D 画面加亮:调色表认不出(贴图号 %d),不加亮", tid); return; } if (!ps) { NSError *e = nil; id lib = [g_dev newLibraryWithSource:@(k_lut_msl) options:nil error:&e]; id f = lib ? [lib newFunctionWithName:@"lutk"] : nil; ps = f ? [g_dev newComputePipelineStateWithFunction:f error:&e] : nil; +#if !DM_NVN_M3 MTL4ArgumentTableDescriptor *ad = [MTL4ArgumentTableDescriptor new]; ad.maxTextureBindCount = 2; ad.maxBufferBindCount = 1; at = [g_dev newArgumentTableWithDescriptor:ad error:&e]; +#endif for (int i = 0; i < 3; i++) { kb[i] = [g_dev newBufferWithLength:16 options:MTLResourceStorageModeShared]; if (kb[i]) res_add(kb[i]); } - if (!ps || !at || !kb[0] || !kb[1] || !kb[2]) { failed = 1; MLOG("【红】3D 画面加亮:计算管线建不出 %s(退回原版亮度)", e.localizedDescription.UTF8String); return; } + if (!ps || M4_ONLY(!at ||) !kb[0] || !kb[1] || !kb[2]) { failed = 1; MLOG("【红】3D 画面加亮:计算管线建不出 %s(退回原版亮度)", e.localizedDescription.UTF8String); return; } MLOG("3D 画面加亮:建好(调色表 %lux%lux%lu,曝光每帧由 dm_bright_k 给)", (unsigned long)lut.width, (unsigned long)lut.height, (unsigned long)lut.depth); } if (!tmp || tmp.width != lut.width || tmp.height != lut.height || tmp.depth != lut.depth || tmp.pixelFormat != lut.pixelFormat) { MTLTextureDescriptor *d = [MTLTextureDescriptor new]; d.textureType = MTLTextureType3D; d.pixelFormat = lut.pixelFormat; d.width = lut.width; d.height = lut.height; d.depth = lut.depth; d.usage = MTLTextureUsageShaderRead; d.storageMode = MTLStorageModePrivate; if (tmp) defer_obj_release(tmp); tmp = [g_dev newTextureWithDescriptor:d]; if (!tmp) { failed = 1; return; } res_add(tmp); } id b0 = kb[ki]; ki = (ki + 1) % 3; *(float *)b0.contents = k; // 三份轮换:在途的帧还在读上一份 | Three copies in rotation: in-flight frames are still reading the previous copy - id b = blit(); enc_b_copy_texture(b, lut, 0, 0, MTLOriginMake(0, 0, 0), MTLSizeMake(lut.width, lut.height, lut.depth), tmp, 0, 0, MTLOriginMake(0, 0, 0)); enc_b_end(g_blit); g_blit = nil; - id ce = (id)enc_c_begin(NULL); [ce setArgumentTable:at]; [at setTexture:tmp.gpuResourceID atIndex:0]; [at setTexture:lut.gpuResourceID atIndex:1]; [at setAddress:b0.gpuAddress atIndex:0]; + BENC b = blit(); enc_b_copy_texture(b, lut, 0, 0, MTLOriginMake(0, 0, 0), MTLSizeMake(lut.width, lut.height, lut.depth), tmp, 0, 0, MTLOriginMake(0, 0, 0)); enc_b_end(g_blit); g_blit = nil; + CENC ce = (CENC)enc_c_begin(NULL); +#if DM_NVN_M3 + [ce setTexture:tmp atIndex:0]; [ce setTexture:lut atIndex:1]; [ce setBuffer:b0 offset:0 atIndex:0]; +#else + [ce setArgumentTable:at]; [at setTexture:tmp.gpuResourceID atIndex:0]; [at setTexture:lut.gpuResourceID atIndex:1]; [at setAddress:b0.gpuAddress atIndex:0]; +#endif enc_c_pso(ce, ps); enc_c_dispatch(ce, MTLSizeMake((lut.width + 3) / 4, (lut.height + 3) / 4, (lut.depth + 3) / 4), MTLSizeMake(4, 4, 4)); enc_c_end(ce); args_dirty_all(); } @@ -4634,7 +4815,7 @@ static void copy_t2b(const p_copy_b2t *c) { int is3d = c->tex->d.target == 2, nz = c->r.depth ? c->r.depth : 1; void *mb; uint64_t mo; if (!mtl_addr(c->src, img * nz, &mb, &mo)) { RED_ONCE(31, "贴图→缓冲拷贝的目标不在内存池里"); return; } - id b = blit(); + BENC b = blit(); if (is3d) enc_b_copy_texture_buffer(b, t, 0, level, MTLOriginMake(c->r.xoffset, c->r.yoffset, c->r.zoffset), MTLSizeMake(c->r.width, c->r.height, nz), (__bridge id)mb, mo, row, img); else @@ -4693,13 +4874,13 @@ static void copy_b2t(const p_copy_b2t *c) { id tb = [g_dev newBufferWithLength:uimg * nz ?: 16 options:MTLResourceStorageModeShared]; for (int z = 0; z < nz; z++) nvn_bc_decode(c->tex->d.format, src + mo + z * img, row, c->r.width, c->r.height, (uint8_t *)tb.contents + z * uimg, up); res_add(tb); - id b = blit(); + BENC b = blit(); if (is3d) enc_b_copy_buffer_texture(b, tb, 0, up, uimg, MTLSizeMake(c->r.width, c->r.height, nz), t, 0, level, MTLOriginMake(c->r.xoffset, c->r.yoffset, c->r.zoffset)); else for (int z = 0; z < nz; z++) enc_b_copy_buffer_texture(b, tb, z * uimg, up, uimg, MTLSizeMake(c->r.width, c->r.height, 1), t, layer0 + c->r.zoffset + z, level, MTLOriginMake(c->r.xoffset, c->r.yoffset, 0)); defer_obj_release(tb); // 本次提交跑完再放(并撤驻留) | Release after this submit has finished running (and remove from residency) return; } - id b = blit(); + BENC b = blit(); if (is3d) enc_b_copy_buffer_texture(b, (__bridge id)mb, mo, row, img, MTLSizeMake(c->r.width, c->r.height, nz), t, 0, level, MTLOriginMake(c->r.xoffset, c->r.yoffset, c->r.zoffset)); else @@ -4717,12 +4898,17 @@ static const char k_a2u_msl[] = "kernel void a2u(texture2d src [[texture(0)]], texture2d dst [[texture(1)]], constant uint4 *p [[buffer(0)]], uint2 g [[thread_position_in_grid]]) {\n" " if (g.x >= p[1].x || g.y >= p[1].y) return; float4 v = src.read(g + p[0].xy); if (p[1].z) v.rgb = enc(v.rgb); dst.write(v, g + p[0].zw); }\n"; static int copy_t2t_astc(id s, id d, unsigned sl, unsigned ss, unsigned dl, unsigned ds, int sx, int sy, int dx, int dy, int w, int h) { - static int failed; static id ps; static id at; + static int failed; static id ps; +#if !DM_NVN_M3 + static id at; +#endif if (failed) return 0; if (!ps) { NSError *e = nil; id lib = [g_dev newLibraryWithSource:@(k_a2u_msl) options:nil error:&e]; id f = lib ? [lib newFunctionWithName:@"a2u"] : nil; ps = f ? [g_dev newComputePipelineStateWithFunction:f error:&e] : nil; +#if !DM_NVN_M3 MTL4ArgumentTableDescriptor *ad = [MTL4ArgumentTableDescriptor new]; ad.maxTextureBindCount = 2; ad.maxBufferBindCount = 1; at = [g_dev newArgumentTableWithDescriptor:ad error:&e]; - if (!ps || !at) { failed = 1; MLOG("【红】无 BC:ASTC → 解压格式拷贝的计算管线建不出 %s", e.localizedDescription.UTF8String); return 0; } } +#endif + if (!ps M4_ONLY(|| !at)) { failed = 1; MLOG("【红】无 BC:ASTC → 解压格式拷贝的计算管线建不出 %s", e.localizedDescription.UTF8String); return 0; } } MTLTextureType tt = MTLTextureType2D; id sv = [s newTextureViewWithPixelFormat:s.pixelFormat textureType:tt levels:NSMakeRange(sl, 1) slices:NSMakeRange(ss, 1)]; id dv = [d newTextureViewWithPixelFormat:MTLPixelFormatRGBA8Unorm textureType:tt levels:NSMakeRange(dl, 1) slices:NSMakeRange(ds, 1)]; @@ -4731,8 +4917,13 @@ static int copy_t2t_astc(id s, id d, unsigned sl, unsign uint32_t *p = pb.contents; p[0] = sx; p[1] = sy; p[2] = dx; p[3] = dy; p[4] = w; p[5] = h; p[6] = s.pixelFormat == MTLPixelFormatASTC_4x4_sRGB; p[7] = 0; res_add(pb); rp_end(); if (g_blit) { enc_b_end(g_blit); g_blit = nil; } - id ce = (id)enc_c_begin(NULL); [ce setArgumentTable:at]; + CENC ce = (CENC)enc_c_begin(NULL); +#if DM_NVN_M3 + [ce setTexture:sv atIndex:0]; [ce setTexture:dv atIndex:1]; [ce setBuffer:pb offset:0 atIndex:0]; +#else + [ce setArgumentTable:at]; [at setTexture:sv.gpuResourceID atIndex:0]; [at setTexture:dv.gpuResourceID atIndex:1]; [at setAddress:pb.gpuAddress atIndex:0]; +#endif enc_c_pso(ce, ps); enc_c_dispatch(ce, MTLSizeMake((w + 7) / 8, (h + 7) / 8, 1), MTLSizeMake(8, 8, 1)); enc_c_end(ce); args_dirty_all(); defer_obj_unref(sv); defer_obj_unref(dv); defer_obj_release(pb); // 本次提交跑完再放(视图不单独驻留,参数块撤驻留) | Release after this submit has finished running (views are not made resident separately; the parameter block is removed from residency) @@ -4770,7 +4961,7 @@ static void copy_t2t(const p_copy_t2t *c) { c->flags, (unsigned long)s.pixelFormat, (unsigned long)d.pixelFormat, s3, d3); return; } - id b = blit(); + BENC b = blit(); if (s3) enc_b_copy_texture(b, s, 0, sl, MTLOriginMake(c->sr.xoffset, c->sr.yoffset, c->sr.zoffset), MTLSizeMake(c->sr.width, c->sr.height, nz), d, 0, dl, MTLOriginMake(c->dr.xoffset, c->dr.yoffset, c->dr.zoffset)); else @@ -4813,7 +5004,7 @@ static void clear_tex(const p_clear_tex *c) { } rp_end(); if (g_blit) { enc_b_end(g_blit); g_blit = nil; } for (int z = 0; z < nz; z++) { - MTL4RenderPassDescriptor *rp = [MTL4RenderPassDescriptor new]; + RPD *rp = [RPD new]; MTLRenderPassAttachmentDescriptor *a = depth ? rp.depthAttachment : stencil ? rp.stencilAttachment : rp.colorAttachments[0]; a.texture = t; a.level = lv; a.loadAction = MTLLoadActionClear; a.storeAction = MTLStoreActionStore; if (is3d) a.depthPlane = c->r.zoffset + z; else a.slice = l0 + c->r.zoffset + z; @@ -4920,11 +5111,11 @@ static id rt_cp(id src, id dst0) { d.usage = MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget | MTLTextureUsagePixelFormatView; d.storageMode = MTLStorageModePrivate; if (dst0) defer_obj_release(dst0); // 换尺寸:旧副本可能还被在途的命令缓冲读着(MTL4 命令缓冲不保留资源),延迟放 | Size change: the old copy may still be read by an in-flight command buffer (MTL4 command buffers do not retain resources), so release it deferred dst = [g_dev newTextureWithDescriptor:d]; if (!dst) return nil; res_add(dst); } - id b = blit(); enc_b_copy_texture(b, src, 0, 0, MTLOriginMake(0, 0, 0), MTLSizeMake(src.width, src.height, 1), dst, 0, 0, MTLOriginMake(0, 0, 0)); return dst; } + BENC b = blit(); enc_b_copy_texture(b, src, 0, 0, MTLOriginMake(0, 0, 0), MTLSizeMake(src.width, src.height, 1), dst, 0, 0, MTLOriginMake(0, 0, 0)); return dst; } static void rt_blit_shift(id src, id dst, int dx, int dy) { // 整数偏移拷贝:dst(x + dx, y + dy) = src(x, y);搬不到的屏边一条留给区域重算(外推趟已标 0x80) | Integer-offset copy: dst(x + dx, y + dy) = src(x, y); the strip at the screen edge that cannot be moved is left for the region recompute (the extrapolation pass has already marked it 0x80) if (!src || !dst || src.width != dst.width || src.height != dst.height) return; int W = (int)src.width, H = (int)src.height, w = W - abs(dx), h = H - abs(dy); if (w <= 0 || h <= 0) return; - id b = blit(); enc_b_copy_texture(b, src, 0, 0, MTLOriginMake(MAX(0, -dx), MAX(0, -dy), 0), MTLSizeMake(w, h, 1), dst, 0, 0, MTLOriginMake(MAX(0, dx), MAX(0, dy), 0)); } + BENC b = blit(); enc_b_copy_texture(b, src, 0, 0, MTLOriginMake(MAX(0, -dx), MAX(0, -dy), 0), MTLSizeMake(w, h, 1), dst, 0, 0, MTLOriginMake(MAX(0, dx), MAX(0, dy), 0)); } static void rt_copy_prev(void) { // 全画帧:不透明 HDR 与主深度模板各拷一份(GPU 内按序,在本命令缓冲里) | Fully drawn frame: copy the opaque HDR and the main depth-stencil once each (in order within the GPU, in this command buffer) if (g_rt.copied || !g_rt.main_seen || !g_rt.hdr || !g_rt.ds) return; g_rt.copied = 1; // 本帧没认出主通道(前台 / 读取画面)不拷:上次认的贴图可能已被游戏放掉、不在驻留集里 | Do not copy when the main pass was not recognized this frame (foreground / loading screen): the textures recognized last time may already have been released by the game and not be in the residency set if (!rx_setup(g_rt.hdr.pixelFormat, g_rt.ds.pixelFormat)) { if (!g_rt.disabled) { g_rt.disabled = 1; MLOG("【红】运行时外推:外推管线在这台设备上建不出,整局退回原画法"); } return; } // 建不出(老 GPU 不支持模板导出等):整局退回 | Cannot be built (old GPU does not support stencil export etc.): fall back for the whole run @@ -5183,7 +5374,7 @@ void mtl_res_counts(uint32_t tick, const char *why) { static struct { uint64_t frame; char path[1024]; } g_shotq[SHOTQ_MAX]; static int g_nshotq; static pthread_mutex_t g_shotq_mu = PTHREAD_MUTEX_INITIALIZER; static int present_encode(id cb, id src, id dst, const int crop[4]); -static int present_encode_m4(id cb, id src, id dst, const int crop[4], int uv_i); +static int present_encode_m4(CBUF cb, id src, id dst, const int crop[4], int uv_i); // 整窗截图要的游戏画面(前端 window_shot,不再对挂着显示节拍的 Metal 图层做 drawViewHierarchy):下一次上屏时,出图线程把同一帧 // 按上屏同一套编码(present_encode)画进一张与交换链同尺寸的离屏贴图,GPU 做完后在完成回调里交出 CGImage(回调不阻塞上屏)。g_shotq_mu 护 // Game picture needed by the whole-window screenshot (front end window_shot; no longer does drawViewHierarchy on a Metal layer with the display link attached): at the next present, the present thread draws the same frame @@ -5306,7 +5497,7 @@ static void shot(id src, const char *path, int screen, const int cro // Diagnostic: before the first render pass of the next frame is opened, wait for the GPU to finish, then draw each one (the mip level used by that frame) by full-screen sampling into RGBA8 and save as PNG (float formats are clamped to [0,1]) static long g_td_frame = -2; static const char *g_td_path; static NSMutableArray *g_td_list; static int g_td_done; static void td_dump(void); -void td_note(MTL4RenderPassDescriptor *pd, NSUInteger nc) { +void td_note(RPD *pd, NSUInteger nc) { if (g_td_frame == -2) { const char *e = getenv("DM_NVN_TEXDUMP"), *c = e ? strchr(e, ':') : NULL; g_td_frame = c ? atol(e) : -1; g_td_path = c ? c + 1 : NULL; g_td_list = [NSMutableArray array]; } if (g_td_frame < 0 || g_td_done) return; long f = (long)atomic_load(&g_cur_frame); @@ -5393,7 +5584,7 @@ static void td_dump(void) { // (the same target is often cleared and reused within a frame, so the end-of-frame state cannot reflect the output of intermediate passes); file name index = in-frame index*100000 + texture index*100 + mip level static int g_ts_idx[64], g_ts_n = -1, g_ts_on; static uint64_t g_ts_first, g_ts_curf = ~0ull; static __strong id g_ts_att[8]; static uint64_t g_ts_ser[8]; static NSUInteger g_ts_lv[8]; static int g_ts_na; -void ts_note(MTL4RenderPassDescriptor *pd, NSUInteger nc) { +void ts_note(RPD *pd, NSUInteger nc) { if (g_ts_n < 0) { g_ts_n = 0; const char *e = getenv("DM_NVN_TEXSNAP"); for (const char *q = e; q && *q && g_ts_n < 64; q = strchr(q, ',') ? strchr(q, ',') + 1 : q + strlen(q)) g_ts_idx[g_ts_n++] = atoi(q); } g_ts_on = 0; if (!g_ts_n || g_td_frame < 0 || g_td_done) return; @@ -5443,7 +5634,9 @@ int mtl_display_hz(void) { #endif } static _Atomic uint64_t g_present_stall_ns; // 单测用:出图线程每次出图前额外停顿(模拟 drawable 迟迟不可用) | For unit tests: an extra pause before each present on the present thread (simulating a drawable that stays unavailable) +#if !DM_NVN_M3 static CAMetalLayer *g_present_layer_resident; +#endif void mtl_present_test_stall(uint64_t ns) { g_present_stall_ns = ns; } static void present_pipeline(MTLPixelFormat format) { if (!g_blit_pso || g_blit_fmt != format) { @@ -5507,7 +5700,7 @@ static int present_encode(id cb, id src, id cb, id src, id dst, const int crop[4], int uv_i) { +static int present_encode_m4(CBUF cb, id src, id dst, const int crop[4], int uv_i) { 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 || @@ -5521,21 +5714,30 @@ static int present_encode_m4(id cb, id src, id en = [cb renderCommandEncoderWithDescriptor:rp]; + RENC en = [cb renderCommandEncoderWithDescriptor:rp]; if (!en) { MLOG("【红】M4 出图渲染编码器创建失败"); return 0; } +#if DM_NVN_M3 + [en setFragmentTexture:src atIndex:0]; + [en setFragmentSamplerState:g_blit_samp atIndex:0]; +#else [en barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice]; [en setArgumentTable:g_present_args atStages:MTLRenderStageFragment]; [g_present_args setTexture:src.gpuResourceID atIndex:0]; [g_present_args setSamplerState:g_blit_samp.gpuResourceID atIndex:0]; +#endif float *uv = g_present_uv[uv_i].contents; uv[0] = (float)cx / src.width; uv[1] = (float)cy / src.height; uv[2] = (float)cw / src.width; uv[3] = (float)ch / src.height; uv[4] = (cx + 0.5f) / src.width; uv[5] = (cy + 0.5f) / src.height; uv[6] = (cx + cw - 0.5f) / src.width; uv[7] = (cy + ch - 0.5f) / src.height; +#if DM_NVN_M3 + [en setFragmentBuffer:g_present_uv[uv_i] offset:0 atIndex:0]; +#else [g_present_args setAddress:g_present_uv[uv_i].gpuAddress atIndex:0]; +#endif [en setViewport:vp]; [en setRenderPipelineState:g_blit_pso]; [en drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3]; m4_end(en); @@ -5596,7 +5798,9 @@ static int present_now(const tex_t *t, double period, uint64_t frame, uint64_t t if (g_burst_left > 0) burst_grab(src); // 测试:连拍 | test: burst capture CAMetalLayer *layer = (__bridge CAMetalLayer *)front_metal_layer(); if (!layer) return 0; +#if !DM_NVN_M3 if (g_present_layer_resident != layer) { [g_q4 addResidencySet:layer.residencySet]; g_present_layer_resident = layer; } +#endif #if TARGET_OS_OSX if (!layer.displaySyncEnabled) layer.displaySyncEnabled = YES; // 窗口模式按显示器垂直同步,防撕裂 | Windowed mode follows the display's vsync to prevent tearing #endif @@ -5612,20 +5816,31 @@ static int present_now(const tex_t *t, double period, uint64_t frame, uint64_t t while (g_pq_done < g_present_alloc_fence[alloc_i]) pthread_cond_wait(&g_pq_cv, &g_pq_mu); pthread_mutex_unlock(&g_pq_mu); } +#if DM_NVN_M3 + CBUF cb = [g_q commandBuffer]; // 老接口:交画面记在命令缓冲上(presentDrawable),这一帧的绘制做完才上屏 | older API: presentation is recorded on the command buffer (presentDrawable), so the frame reaches the screen only after its drawing is done + if (!present_encode_m4(cb, src, dr.texture, crop, alloc_i)) return 0; +#else [g_present_alloc4[alloc_i] reset]; [g_q4 waitForDrawable:dr]; - id cb = g_present_cb[alloc_i]; + CBUF cb = g_present_cb[alloc_i]; [cb beginCommandBufferWithAllocator:g_present_alloc4[alloc_i]]; if (!present_encode_m4(cb, src, dr.texture, crop, alloc_i)) { [cb endCommandBuffer]; [g_q4 signalDrawable:dr]; return 0; } [cb endCommandBuffer]; +#endif +#if !DM_NVN_M3 MTL4CommitOptions *o = [MTL4CommitOptions new]; - [o addFeedbackHandler:^(id f) { +#endif + [FB_ON(o, cb) FB_SEL:^(FB_ARG f) { if (f.error) MLOG("【红】上屏命令缓冲错误:%s", f.error.description.UTF8String); pthread_mutex_lock(&g_pq_mu); if (ticket > g_pq_done) g_pq_done = ticket; g_pq_inflight--; pthread_cond_broadcast(&g_pq_cv); pthread_mutex_unlock(&g_pq_mu); }]; - id buffers[] = {cb}; +#if !DM_NVN_M3 + CBUF buffers[] = {cb}; +#endif pthread_mutex_lock(&g_pq_mu); g_pq_inflight++; pthread_mutex_unlock(&g_pq_mu); +#if !DM_NVN_M3 [g_q4 commit:buffers count:1 options:o]; +#endif if (target_ts > 0) { static double leads[300], e2e[300]; // e2e:游戏入队 → 系统预定上屏(含在队列里等节拍回调的时间),输入延迟里我们这一侧能读到的全程 | e2e: game enqueue -> system-scheduled present (including the time waiting in the queue for the display-link callback), the full span of input latency that our side can read static uint64_t lead_n; @@ -5641,10 +5856,12 @@ static int present_now(const tex_t *t, double period, uint64_t frame, uint64_t t (unsigned long long)g_link_dropped, a[149], a[0], b[149], b[0], b[299]); } } +#if !DM_NVN_M3 [g_q4 signalDrawable:dr]; +#endif g_present_alloc_fence[alloc_i] = ticket; #if TARGET_OS_SIMULATOR // iOS 模拟器 SDK 没有呈现时刻回调与最短显示时长(只作画面验收用,不计节拍) | The iOS simulator SDK has no presentation-time callback and no minimum display duration (used only for picture acceptance, display-link ticks are not counted) - (void)period; [dr present]; + (void)period; M3_PRESENT(cb, dr); #else uint64_t pn = ticket; // 按游戏出图序号(票号)记上屏时刻:hle 的上屏统计按「游戏第 n 次出图」取;显示节拍路径里实际出图次数 ≠ 游戏出图次数(旧帧会被合并丢弃) | Record the present time by the game's present sequence number (ticket number): hle's present statistics are taken by "the game's nth present"; in the display link path the actual present count != the game's present count (old frames get merged and dropped) [dr addPresentedHandler:^(id d) { // 真实呈现时刻(屏幕上真正换上这一帧的时间,CACurrentMediaTime 基准) | Actual presentation time (the time this frame is really put on screen, CACurrentMediaTime base) @@ -5653,8 +5870,15 @@ static int present_now(const tex_t *t, double period, uint64_t frame, uint64_t t }]; // 每张至少显示一个出图周期:GPU 完成时刻在 120 Hz 刷新边界附近抖动时,不再出现「25 ms + 8.33 ms」成对的顿挫 // Each frame is displayed for at least one present period: when the GPU completion time jitters around a 120 Hz refresh boundary, the paired "25 ms + 8.33 ms" stutter no longer appears +#if DM_NVN_M3 + if (target_ts <= 0 && period > 0) [cb presentDrawable:dr afterMinimumDuration:period]; else [cb presentDrawable:dr]; +#else if (target_ts > 0) [dr present]; else if (period > 0) [dr presentAfterMinimumDuration:period]; else [dr present]; +#endif +#endif +#if DM_NVN_M3 + [cb commit]; #endif (void)frame; return 1; diff --git a/dm/gfx/nvn/nvn_rtex.inc b/dm/gfx/nvn/nvn_rtex.inc index f7da6f3..b855fb8 100644 --- a/dm/gfx/nvn/nvn_rtex.inc +++ b/dm/gfx/nvn/nvn_rtex.inc @@ -22,7 +22,12 @@ // Before and after the call: this function first calls rp_end() to close the current render pass and copy encoder; after encoding it sets args_dirty_all() / g_pso_dirty / g_dss_dirty, and the game's next draw reopens its pass with 'load'. // Resources: src_hdr / src_ds are created and res_add'ed by the caller; src_ds must be able to open an X32_Stencil8 view (created with MTLTextureUsagePixelFormatView). static id g_rx_pso1; static MTLPixelFormat g_rx_fmt_c, g_rx_fmt_ds; -static id g_rx_dss; static id g_rx_args; +static id g_rx_dss; +#if DM_NVN_M3 +static int g_rx_args; // 老接口没有参数表:只当「常量缓冲建过没有」的标记 | the older API has no argument table: used only as the marker for "has the constant buffer been created" +#else +static id g_rx_args; +#endif static id g_rx_const[3]; static int g_rx_ci; static id g_rx_stv; static __unsafe_unretained id g_rx_stv_src; static const char *k_rx_msl = @@ -84,8 +89,12 @@ static int rx_setup(MTLPixelFormat fc, MTLPixelFormat fds) { if (fds == MTLPixelFormatDepth32Float_Stencil8) { MTLStencilDescriptor *sd = [MTLStencilDescriptor new]; sd.stencilCompareFunction = MTLCompareFunctionEqual; sd.readMask = 0x2; sd.writeMask = 0x80; sd.depthStencilPassOperation = MTLStencilOperationReplace; // 洞 / 屏外新进来的像素由片元导出 0x80,后面 LDR 区域据此重算 // 本帧被界面挡住的像素(界面模板趟已写 0x2)不算 | Hole pixels / pixels newly entering from off-screen get 0x80 exported by the fragment, and the later LDR region is recomputed accordingly // Pixels covered by this frame's UI (the UI stencil pass already wrote 0x2) do not count dd.frontFaceStencil = sd; dd.backFaceStencil = sd; } g_rx_dss = [g_dev newDepthStencilStateWithDescriptor:dd]; +#if DM_NVN_M3 + if (!g_rx_args) { g_rx_args = 1; +#else if (!g_rx_args) { MTL4ArgumentTableDescriptor *ad = [MTL4ArgumentTableDescriptor new]; ad.maxTextureBindCount = 3; ad.maxBufferBindCount = 1; g_rx_args = [g_dev newArgumentTableWithDescriptor:ad error:&e]; +#endif for (int i = 0; i < 3; i++) { g_rx_const[i] = [g_dev newBufferWithLength:256 options:MTLResourceStorageModeShared]; res_add(g_rx_const[i]); } } if (!g_rx_args || !g_rx_dss) { MLOG("【红】运行时外推:参数表 / 深度状态建不出"); g_rx_pso1 = nil; failed = 1; return 0; } g_rx_fmt_c = fc; g_rx_fmt_ds = fds; MLOG("运行时外推:着色器建好(颜色格式 %lu,深度格式 %lu)", (unsigned long)fc, (unsigned long)fds); @@ -143,15 +152,20 @@ int rt_ex_encode(id dst_hdr, id dst_ds, id s rp_end(); if (g_blit) { enc_b_end(g_blit); g_blit = nil; } // 单趟:外推 + 补洞 + 按小数相位补锐化 → dst_hdr;深度写进 dst_ds;本帧界面挡住的像素按模板跳过(模板不写) // Single pass: extrapolation + hole filling + sharpening compensation by fractional phase → dst_hdr; depth is written into dst_ds; pixels covered by this frame's UI are skipped by stencil (stencil not written) - MTL4RenderPassDescriptor *rp = [MTL4RenderPassDescriptor new]; + RPD *rp = [RPD new]; rp.colorAttachments[0].texture = dst_hdr; rp.colorAttachments[0].loadAction = MTLLoadActionLoad; rp.colorAttachments[0].storeAction = MTLStoreActionStore; rp.depthAttachment.texture = dst_ds; rp.depthAttachment.loadAction = MTLLoadActionLoad; rp.depthAttachment.storeAction = MTLStoreActionStore; if (dst_ds.pixelFormat == MTLPixelFormatDepth32Float_Stencil8) { rp.stencilAttachment.texture = dst_ds; rp.stencilAttachment.loadAction = MTLLoadActionLoad; rp.stencilAttachment.storeAction = MTLStoreActionStore; } - id en = [g_cb renderCommandEncoderWithDescriptor:rp]; if (!en) return 0; + RENC en = [g_cb renderCommandEncoderWithDescriptor:rp]; if (!en) return 0; +#if DM_NVN_M3 + [en setFragmentTexture:src_hdr atIndex:0]; [en setFragmentTexture:src_ds atIndex:1]; [en setFragmentTexture:g_rx_stv atIndex:2]; + [en setFragmentBuffer:cbuf offset:0 atIndex:0]; +#else [en barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice]; [en setArgumentTable:g_rx_args atStages:MTLRenderStageFragment]; [g_rx_args setTexture:src_hdr.gpuResourceID atIndex:0]; [g_rx_args setTexture:src_ds.gpuResourceID atIndex:1]; [g_rx_args setTexture:g_rx_stv.gpuResourceID atIndex:2]; [g_rx_args setAddress:cbuf.gpuAddress atIndex:0]; +#endif [en setViewport:(MTLViewport){0, 0, W, H, 0, 1}]; [en setRenderPipelineState:g_rx_pso1]; [en setDepthStencilState:g_rx_dss]; [en setStencilReferenceValue:0]; [en drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3]; m4_end(en); args_dirty_all(); g_pso_dirty = g_dss_dirty = 1; diff --git a/dm/gfx/tests/Makefile b/dm/gfx/tests/Makefile index bc2995a..4c3639a 100644 --- a/dm/gfx/tests/Makefile +++ b/dm/gfx/tests/Makefile @@ -85,3 +85,10 @@ run: t_nvn t_dirty_slots t_dirty_race t_builtin t_deswz_gpu t_pace t_refl t_hmap MTL_DEBUG_LAYER=1 ./t_pfv python3 test_tbdr_budget.py .PHONY: run +# 老接口版那一遍(图形后端编译期开关 DM_NVN_M3=1,目标 macOS 15.0):在旁边的 tests_m3 目录里用同一份测试源码另编另跑,不动这里的缺省产物。 +# 闸门(verify/accept.sh)两遍都跑,免得以后只测一边 +# The older-API pass (compile-time switch DM_NVN_M3=1 of the graphics backend, target macOS 15.0): built and run separately from the same test sources in the sibling tests_m3 directory, leaving the default outputs here untouched. +# The gate (verify/accept.sh) runs both passes, so that only one side being tested cannot happen later +run-m3: + rm -rf ../tests_m3 && mkdir ../tests_m3 && cp Makefile *.c *.m *.py ../tests_m3/ + $(MAKE) -C ../tests_m3 run CFLAGS="$(CFLAGS) -DDM_NVN_M3=1 -mmacosx-version-min=15.0" diff --git a/dm/gfx/tests/t_rt_range.m b/dm/gfx/tests/t_rt_range.m index 44e6be3..41e34c0 100644 --- a/dm/gfx/tests/t_rt_range.m +++ b/dm/gfx/tests/t_rt_range.m @@ -15,9 +15,9 @@ static tex_t color={.serial=52000},depth={.serial=52001};static prog_t pg[2]={{. static p_set_rt rt(int levels){p_set_rt r={.n=1,.depth=&depth,.has_dview=1};r.color[0]=&color;r.has_cview[0]=1; r.cview[0]=(view_t){.set_levels=1,.set_layers=1,.set_format=1,.set_target=1,.nlevels=levels,.nlayers=1,.format=NVN_FORMAT_RGBA8,.target=NVN_TEXTURE_TARGET_2D}; r.dview=r.cview[0];r.dview.nlevels=1;r.dview.base_level=small_depth?1:0;r.dview.format=NVN_FORMAT_DEPTH32F_STENCIL8;return r;} -static void seed(void){MTL4RenderPassDescriptor *p=[MTL4RenderPassDescriptor new];p.colorAttachments[0].texture=tex_mtl(&color);p.colorAttachments[0].loadAction=MTLLoadActionClear;p.colorAttachments[0].storeAction=MTLStoreActionStore;p.colorAttachments[0].clearColor=MTLClearColorMake(0,0,0,1); +static void seed(void){RPD *p=[RPD new];p.colorAttachments[0].texture=tex_mtl(&color);p.colorAttachments[0].loadAction=MTLLoadActionClear;p.colorAttachments[0].storeAction=MTLStoreActionStore;p.colorAttachments[0].clearColor=MTLClearColorMake(0,0,0,1); p.depthAttachment.texture=p.stencilAttachment.texture=tex_mtl(&depth);p.depthAttachment.loadAction=p.stencilAttachment.loadAction=MTLLoadActionClear;p.depthAttachment.storeAction=p.stencilAttachment.storeAction=MTLStoreActionStore;p.depthAttachment.clearDepth=.75;p.stencilAttachment.clearStencil=0x2d;enc_r_end(enc_r_begin(p)); - if(sample_attachment){MTL4RenderPassDescriptor *q=[MTL4RenderPassDescriptor new];q.colorAttachments[0].texture=tex_mtl(&color);q.colorAttachments[0].level=1;q.colorAttachments[0].loadAction=MTLLoadActionClear;q.colorAttachments[0].storeAction=MTLStoreActionStore;q.colorAttachments[0].clearColor=MTLClearColorMake(0,1,0,0);enc_r_end(enc_r_begin(q));} + if(sample_attachment){RPD *q=[RPD new];q.colorAttachments[0].texture=tex_mtl(&color);q.colorAttachments[0].level=1;q.colorAttachments[0].loadAction=MTLLoadActionClear;q.colorAttachments[0].storeAction=MTLStoreActionStore;q.colorAttachments[0].clearColor=MTLClearColorMake(0,1,0,0);enc_r_end(enc_r_begin(q));} if(small_depth){p.colorAttachments[0].texture=nil;p.depthAttachment.level=p.stencilAttachment.level=1;enc_r_end(enc_r_begin(p));}} static void rr_read_planes(id __strong *b){id t=tex_mtl(&color),d=tex_mtl(&depth);[blit()copyFromTexture:t sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0,0,0)sourceSize:MTLSizeMake(8,8,1)toBuffer:b[0]destinationOffset:0 destinationBytesPerRow:32 destinationBytesPerImage:256]; [blit()copyFromTexture:d sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0,0,0)sourceSize:MTLSizeMake(8,8,1)toBuffer:b[1]destinationOffset:0 destinationBytesPerRow:32 destinationBytesPerImage:256 options:MTLBlitOptionDepthFromDepthStencil]; diff --git a/dm/gfx/tex/nvn_deswizzle_gpu.h b/dm/gfx/tex/nvn_deswizzle_gpu.h index e312bb9..c097bc1 100644 --- a/dm/gfx/tex/nvn_deswizzle_gpu.h +++ b/dm/gfx/tex/nvn_deswizzle_gpu.h @@ -3,12 +3,17 @@ #include #import #include "nvn_deswizzle.h" +#ifndef DM_NVN_M3 +#define DM_NVN_M3 0 // 见 nvn_mtl.m:1 = 图形后端走老接口 | see nvn_mtl.m: 1 = the graphics backend uses the older API +#endif int nvn_deswz_gpu_init(id dev); int nvn_deswz_gpu_encode(id enc, id src, uint64_t src_off, const nvn_texdesc *d, unsigned level, unsigned layer, id dst, uint64_t dst_off, size_t dst_pitch); +#if !DM_NVN_M3 int nvn_deswz_gpu_encode_m4(id enc, id table, id params, size_t params_off, id src, uint64_t src_off, const nvn_texdesc *d, unsigned level, unsigned layer, id dst, uint64_t dst_off, size_t dst_pitch); +#endif diff --git a/dm/gfx/tex/nvn_deswizzle_gpu.m b/dm/gfx/tex/nvn_deswizzle_gpu.m index 5fc4190..137ed78 100644 --- a/dm/gfx/tex/nvn_deswizzle_gpu.m +++ b/dm/gfx/tex/nvn_deswizzle_gpu.m @@ -48,6 +48,7 @@ int nvn_deswz_gpu_encode(id enc, id src, ui return 0; } +#if !DM_NVN_M3 int nvn_deswz_gpu_encode_m4(id enc, id table, id params, size_t params_off, id src, uint64_t src_off, const nvn_texdesc *d, unsigned level, unsigned layer, @@ -71,3 +72,4 @@ int nvn_deswz_gpu_encode_m4(id enc, id <输出根目录> 产出 <输出根目录>/b-<翻译链版本>/ +# 为什么要有:dmsh_build.py 编库时不带最低版本参数,库里记的目标是编译这台机器的 SDK(macOS 26);老系统上加载这种库会直接失败 +# (同程序本体的最低系统版本是一回事,换了个地方)。老接口版的包(tools/mac_app.sh DM_MAC_M3=1)带的是这里重编出来的库。 +# 源码来源(共用缓存只读):_b 库旁边的 .metal;_bf 库(可读 tile 版本)的源码在内容寻址缓存里,按库文件内容对上。 +# 编译命令与 dmsh_build.py 相同,只多一个 -mmacosx-version-min。约 7000 个库 3 分钟。 +# Recompile the Mac shader libraries for a given minimum system version: msl_retarget.sh produces /b-/ +# Why it exists: dmsh_build.py compiles the libraries without a minimum-version flag, so the target recorded in them is the SDK of the build machine (macOS 26); loading such a library on an older system simply fails +# (the same matter as the minimum system version of the executable, in a different place). The older-API package (tools/mac_app.sh DM_MAC_M3=1) carries the libraries recompiled here. +# Where the sources come from (the shared cache is read-only): the .metal next to each _b library; the sources of _bf libraries (the readable-tile variants) are in the content-addressed cache and are matched by the content of the library file. +# The compile command is the same as in dmsh_build.py with only -mmacosx-version-min added. About 7000 libraries in 3 minutes. +set -u; MIN=$1; OUTROOT=$2 +HERE=$(cd "$(dirname "$0")" && pwd); ROOT=${DM_ROOT:-$HOME/dm-work} +V=$(sed -n 's/.*DMSH_CHAIN "\(.*\)".*/\1/p' "$HERE/../nvn/dmsh_chain.h"); S=$ROOT/build/cache/metal_shader_cache/b-$V; CAS=$ROOT/build/cache/metal_shader_cache/cas/variant +[ -d "$S" ] || { echo "🔴 没有着色器库 ${S}(先跑 dmsh_build.py)"; exit 2; } +D=$OUTROOT/b-$V; rm -rf "$D"; mkdir -p "$D"; cp -c "$S"/*.json "$D"/ +one() { src=$1; dst=$2; t=$(mktemp -d); if xcrun -sdk macosx metal -c -mmacosx-version-min="$MIN" "$src" -o "$t/a.air" 2>"$t/err" && xcrun -sdk macosx metallib "$t/a.air" -o "$t/a.metallib" 2>>"$t/err"; then mv "$t/a.metallib" "$dst"; else echo "失败 $(basename "$dst"):$(head -1 "$t/err" | cut -c1-120)"; fi; rm -rf "$t"; } +export -f one; export MIN D S +BAD=$(ls "$S" | grep '_b\.metal$' | sed 's/\.metal$//' | xargs -P 10 -I{} bash -c 'one "$S/{}.metal" "$D/{}.metallib"') +T=$(mktemp); for r in "$CAS"/*/; do [ -f "$r/mac.metallib" ] && [ -f "$r/metal" ] && echo "$(shasum -a 256 "$r/mac.metallib" | cut -c1-64) $r"; done > "$T" +miss=0 +for f in "$S"/*_bf.metallib; do [ -f "$f" ] || continue; h=$(shasum -a 256 "$f" | cut -c1-64); r=$(grep -m1 "^$h " "$T" | cut -d' ' -f2-) + if [ -n "$r" ]; then m=$D/$(basename "${f%.metallib}").metal; cp "$r/metal" "$m"; BAD="$BAD$(one "$m" "$D/$(basename "$f")")"; rm -f "$m"; else miss=$((miss+1)); fi; done +rm -f "$T" +have=$(ls "$D" | grep -c '\.metallib$'); want=$(ls "$S" | grep -c '\.metallib$') +[ -z "$BAD" ] && [ "$miss" = 0 ] && [ "$have" = "$want" ] || { echo "🔴 着色器库重编不全:产出 ${have} / ${want},_bf 源码没对上 ${miss} 个;${BAD:0:300}"; exit 3; } +echo "MSL_RETARGET ${D}(${have} 个库,目标 macOS ${MIN})" diff --git a/dm/host/Makefile b/dm/host/Makefile index 62e9eb9..3a181fd 100644 --- a/dm/host/Makefile +++ b/dm/host/Makefile @@ -7,7 +7,7 @@ MACOS_MIN ?= 26.0 CFLAGS=-O1 -g -Wall -Wno-unused-function -mmacosx-version-min=$(MACOS_MIN) # 服务层接管 hle_*.c 按通配纳入:新增文件不改这一行(免合并冲突) # Service-layer takeover hle_*.c files are included by wildcard: adding a file does not touch this line (avoids merge conflicts) -SRC=main.c loader.c hle.c crash.c diag.c thread.c memstat.m dm_cursor.c dm_cursor_item.c dm_world.c dm_textinput.c dm_update.c dm_actions.c dm_namegen.c dm_cloudsync.c dm_custom.c dm_elysium.c dm_bossrush.c dm_pages.c dm_vault.c dm_vault_ui.c dm_kills.c dm_textbox.c dm_turnsmooth.c dm_textbox_core.c dm_potpick.c dm_lootfilter.c dm_autobuff.c dm_beltauto.c dm_padmode.c dm_pouch.c dm_drophaptic.c dm_freetp.c dm_townwp.c dm_shoprefresh.c dm_runeword.c dm_uiscreen.c dm_dropfilter.c dm_hud.c dm_rift.c dm_rift_ui.c dm_bright.c touch_mac.c romfs_validate.c ../ios/Sources/dm_touch_controls.c $(sort $(wildcard hle_*.c)) front_mac.m app_mac.m ../ios/Sources/dm_gamepad.m entry.S dm_i18n.c +SRC=main.c loader.c hle.c crash.c diag.c thread.c memstat.m dm_cursor.c dm_cursor_item.c dm_world.c dm_textinput.c dm_update.c dm_actions.c dm_namegen.c dm_cloudsync.c dm_custom.c dm_elysium.c dm_bossrush.c dm_pages.c dm_vault.c dm_vault_ui.c dm_kills.c dm_textbox.c dm_turnsmooth.c dm_textbox_core.c dm_potpick.c dm_lootfilter.c dm_autobuff.c dm_beltauto.c dm_padmode.c dm_pouch.c dm_drophaptic.c dm_freetp.c dm_townwp.c dm_shoprefresh.c dm_runeword.c dm_rwlv_core.c dm_uiscreen.c dm_dropfilter.c dm_hud.c dm_rift.c dm_rift_ui.c dm_bright.c touch_mac.c romfs_validate.c ../ios/Sources/dm_touch_controls.c $(sort $(wildcard hle_*.c)) front_mac.m app_mac.m ../ios/Sources/dm_gamepad.m ../ios/Sources/cloud_ios.m entry.S dm_i18n.c # NVN 空设备 + nn::vi(dm/gfx/) # 按通配纳入 dm/gfx 与 dm/gfx/nvn 下的源(tests/ metal/ 不进宿主):新增文件不改这一行 # NVN null device + nn::vi (dm/gfx/) @@ -20,6 +20,12 @@ LIBDEFLATE=../third_party/libdeflate/lib/deflate_decompress.c ../third_party/lib .DEFAULT_GOAL := dmhost # 下面先写了表头生成规则,缺省目标要明说(否则 make 只生成表头、不编宿主) | The header generation rules are written first below, so the default goal must be stated explicitly (otherwise make only generates the headers and does not build the host) print-macos-min: @echo $(MACOS_MIN) +# 老接口版(图形后端不用 Metal 4,见 gfx/nvn/nvn_mtl.m 的 DM_NVN_M3):最低系统单独一个数;包名另起,存档与日志目录跟着包名走、不与正式包共用 +# Older-API build (graphics backend without Metal 4, see DM_NVN_M3 in gfx/nvn/nvn_mtl.m): its minimum system is a separate number; the package gets its own name, and the save and log directory follows the package name instead of being shared with the regular package +MACOS_MIN_M3 ?= 15.0 +CFLAGS_M3=$(subst -mmacosx-version-min=$(MACOS_MIN),-mmacosx-version-min=$(MACOS_MIN_M3),$(CFLAGS)) -DDM_NVN_M3=1 -DAPP_NAME='"D2R Mobile M3"' +print-macos-min-m3: + @echo $(MACOS_MIN_M3) # 由原版表生成的头文件:不进仓库,构建时从玩家自己的游戏文件(Switch 版 3.3.94012 的 Update/RomFS)生成;路径用环境变量 DM_ROMFS_SRC 指定 # Headers generated from the original game's tables: not checked into the repository, generated at build time from the player's own game files (Update/RomFS of Switch version 3.3.94012); the path is given by the environment variable DM_ROMFS_SRC ROMFS?=$(or $(DM_ROMFS_SRC),$(DM_ROOT)/data/switch/3.3.94012/Update/RomFS) @@ -36,3 +42,7 @@ dm_bright_levels.inc: ../tools/gen_bright_levels.py ../ios/tools/touch_layout.py 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 ../ios/Sources/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 +# 老接口版宿主(图形后端不用 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 ../ios/Sources/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 diff --git a/dm/host/app_mac.m b/dm/host/app_mac.m index 8a6c7ae..07ea2f0 100644 --- a/dm/host/app_mac.m +++ b/dm/host/app_mac.m @@ -14,7 +14,9 @@ #include "dm_i18n.h" #define T(k) (@(dm_ui(k))) -#define APP_NAME "D2R Mobile" +#ifndef APP_NAME +#define APP_NAME "D2R Mobile" // 存档与日志目录名;老接口版构建时另给(host/Makefile CFLAGS_M3),两个包不共用存档 | name of the save and log directory; given separately when building the older-API version (host/Makefile CFLAGS_M3), so the two packages do not share saves +#endif static NSString *const kRomfsKey = @"RomfsDir"; // 这个文件夹是不是游戏资源:认 data/build_manifest.psv。选到上一两层(解包目录的根、Update)也认,往里找一层 @@ -79,12 +81,21 @@ int dm_app_bootstrap(int *argc, char ***argv) { [fm removeItemAtPath:[logd stringByAppendingPathComponent:@"host.prev.log"] error:nil]; [fm moveItemAtPath:lf toPath:[logd stringByAppendingPathComponent:@"host.prev.log"] error:nil]; if (!isatty(2)) { freopen(lf.fileSystemRepresentation, "w", stderr); setvbuf(stderr, NULL, _IOLBF, 0); } + // 不要系统的「窗口状态恢复」:上次被强退 / 崩过之后,系统会在启动时弹「上次意外退出,要重新打开窗口吗」的模态框——游戏没有可恢复的窗口, + // 框却挡着主窗口收不到鼠标键盘(游戏在后面照跑)。等同于带启动参数 -ApplePersistenceIgnoreState YES;要在建 NSApplication 之前设 + // No system "window state restoration": after a forced quit / crash the system shows a modal "the app quit unexpectedly, reopen windows?" at launch - the game has no window to restore, + // yet the dialog covers the main window, which then receives no mouse or keyboard (the game keeps running behind it). Equivalent to the launch argument -ApplePersistenceIgnoreState YES; must be set before NSApplication is created + [NSUserDefaults.standardUserDefaults setVolatileDomain:@{ @"ApplePersistenceIgnoreState": @YES } forName:NSArgumentDomain]; [NSApplication sharedApplication]; [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; [NSApp activateIgnoringOtherApps:YES]; NSString *prod = res_item(@"product"); if (!prod || ![fm fileExistsAtPath:[prod stringByAppendingPathComponent:@"main.patched.bin"]]) { alert(T("dmAppBrokenTitle"), T("dmAppBroken")); exit(1); } NSUserDefaults *ud = NSUserDefaults.standardUserDefaults; + // 包标识换过(内测正式包为了 iCloud 改用与 iOS 包同一个标识):偏好按包标识分域,选过的资源文件夹、看过键位对照这两项从旧域(公开口径的标识)接过来一次,免得再选一遍 + // The bundle identifier has changed (the internal build switched to the same identifier as the iOS package for iCloud): preferences are scoped by bundle identifier, so the two items - the chosen resource folder and having seen the key reference - are carried over once from the old domain (the identifier of public builds), to avoid choosing again + if (![ud stringForKey:kRomfsKey] && ![NSBundle.mainBundle.bundleIdentifier isEqualToString:@"org.d2rmobile.mac"]) { NSUserDefaults *old = [[NSUserDefaults alloc] initWithSuiteName:@"org.d2rmobile.mac"]; NSString *r = [old stringForKey:kRomfsKey]; + if (r) { [ud setObject:r forKey:kRomfsKey]; if ([old boolForKey:@"KeysShown"]) [ud setBool:YES forKey:@"KeysShown"]; LOG("App:从旧包标识的偏好里接过资源文件夹 %s", r.UTF8String); } } NSString *saved = [ud stringForKey:kRomfsKey], *why = nil, *rom = saved ? romfs_root(saved, &why) : nil; if (getenv("DM_APP_ROMFS")) { // 测试(没人点对话框时用):直接给资源文件夹;不对就把同一句报错写进日志并退出,不弹框、不记进偏好 | Test (for when nobody is there to click the dialog): give the resource folder directly; if it is wrong, write the same error sentence to the log and exit, with no dialog and nothing saved to preferences rom = romfs_root(@(getenv("DM_APP_ROMFS")), &why); @@ -95,6 +106,8 @@ int dm_app_bootstrap(int *argc, char ***argv) { [ud setObject:rom forKey:kRomfsKey]; } { void dm_custom_init(const char *dir); dm_custom_init(sup.fileSystemRepresentation); } // 自定义设置文件的目录现在就给(同 iOS 壳):不给的话要等存档挂上才知道在哪,而语言开关正是在挂存档那一刻读它改游戏语言的——晚了开关就不生效 | the directory of the custom settings file is given right now (same as the iOS shell): otherwise it is only known once the save is mounted, and the language switch is read to change the game language at exactly that moment - too late and the switch has no effect + 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); setenv("DM_SAVE", save.fileSystemRepresentation, 1); setenv("DM_TEMP", temp.fileSystemRepresentation, 1); setenv("DM_ROMFS", rom.fileSystemRepresentation, 1); setenv("DM_ROOT", sup.fileSystemRepresentation, 1); diff --git a/dm/host/diag.c b/dm/host/diag.c index 2010434..b1a0e7d 100644 --- a/dm/host/diag.c +++ b/dm/host/diag.c @@ -1197,6 +1197,9 @@ int dm_unpause_for_exit(void) { 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)); } // 测试用:按 id 取服务端物品单位(物品表 G+0x2e30,128 桶、next=+0x158);不在局内 / 没找到返回 0 // For tests: get a server item unit by id (item table G+0x2e30, 128 buckets, next=+0x158); returns 0 when not in a run / not found uint64_t dm_diag_srv_item(uint32_t id) { if (!in_game()) return 0; uint64_t u = 0; tk_rd(g_lastG + 0x2e30 + 8 * (id & 0x7f), &u, 8); for (int k = 0; u && k < 4096; k++) { uint32_t ty = 0, uid = 0; if (!tk_rd(u, &ty, 4) || !tk_rd(u + 8, &uid, 4)) return 0; if (ty == 4 && uid == id) return u; if (!tk_rd(u + 0x158, &u, 8)) return 0; } return 0; } diff --git a/dm/host/dm_cursor.c b/dm/host/dm_cursor.c index f48eebc..4f052f8 100644 --- a/dm/host/dm_cursor.c +++ b/dm/host/dm_cursor.c @@ -446,6 +446,7 @@ static _Atomic uint64_t g_ut_xy; // 归一化坐标各 16 位 // the global flag is cleared along with it, and this click can then select the new one. Confirming does not rely on tapping again; it uses the 「继续」(Continue) button in the layout (sends ToConsoleCharacterOptions, valid at any time). static _Atomic int g_cc_open; static _Atomic int g_fe_name_open, g_fe_name_tap; // 起名页开着;点了输入框(重新弹键盘) | Naming page open; the input box was tapped (bring the keyboard up again) +static _Atomic int g_fe_name_has; // 起名页开着期间已经填过名字(输入框确认过非空的字,含留空取的随机名) | a name has been filled in while the naming page was open (the input field confirmed non-empty text, including the random name taken when left empty) static const char *const k_cc_class[8] = { "Amazon", "Assassin", "Necromancer", "Barbarian", "Paladin", "Sorceress", "Warlock", "Druid" }; static _Atomic int g_fe_opt_open, g_fe_confirm_open, g_fe_back; static _Atomic int g_fe_opt_side; // 模式页最近一次点的是哪张牌:0 标准(左半屏)1 专家(右半屏) | Which card was tapped most recently on the mode page: 0 Standard (left half of the screen), 1 Hardcore (right half of the screen) @@ -1074,6 +1075,16 @@ static int ui_classify0(module_t *m, uint64_t root, int x, int y, char *hit, siz int yy = y + off[i] * vh / 2160; if (yy < 0 || yy >= vh) continue; int tl = ui_top_cover(m, root, x, yy); if (tl < 0) tl = 0; for (int k = (int)rn - 1; k >= tl && !th; k--) th = tab_walk(*(uint64_t *)(rch + 8 * k), (uint64_t)(uint32_t)x | ((uint64_t)(uint32_t)yy << 32), 1, (uint64_t)m->base + 0x20ba3a8, &d, &top); } } if (th) { atomic_store(&g_tab_delta, d); atomic_store(&g_tab_top, top); snprintf(hit, hn, "页签 %+d%s", d, top ? "(顶部)" : ""); return 2; } + // 手柄版技能树的页内分页(防御光环 / 攻击光环…)不是页签条控件,是四个文字框 TextTabK,只认 ZL / ZR:点在第 K 个文字框上 = 按差值走。 + // 当前页 = TabK 里 Background 可见的那个(「综合技能」那页 Tab3 没有 Background:前三个都不可见就是它)。只在手柄版布局认(触屏版布局的技能树页签是可点的) + // The in-page pagination of the gamepad-layout skill tree (Defensive Auras / Offensive Auras ...) is not a tab-bar widget but four text boxes TextTabK that only respond to ZL / ZR: a click on the K-th text box = step by the difference. + // The current page = the TabK whose Background is visible (on the "general skills" page Tab3 has no Background: if none of the first three is visible, it is that one). Recognised only in the gamepad layout (in the touch layout the skill tree tabs are clickable) + { int dm_padmode_current(void); uint64_t sp = dm_padmode_current() ? ui_find(root, "SkillsTreePanel", 0) : 0; + if (sp && *(uint8_t *)(sp + 0x50) && *(uint8_t *)(sp + 0x51)) { int tgt = -1, cur = 3; char nm[16]; + for (int k = 0; k < 4; k++) { snprintf(nm, sizeof nm, "TextTab%d", k); uint64_t tw = ui_find(sp, nm, 0); + if (tw && *(uint8_t *)(tw + 0x50) && (((int (*)(uint64_t, uint64_t))*(uint64_t *)(*(uint64_t *)tw + 0x48))(tw, xy) & 1)) tgt = k; + snprintf(nm, sizeof nm, "Tab%d", k); uint64_t tb = k < 3 ? ui_find(sp, nm, 0) : 0, bg = tb ? ui_find(tb, "Background", 0) : 0; if (bg && *(uint8_t *)(bg + 0x50)) cur = k; } + if (tgt >= 0) { atomic_store(&g_tab_w, 0); atomic_store(&g_tab_delta, tgt - cur); atomic_store(&g_tab_top, 0); snprintf(hit, hn, "技能树分页 %+d", tgt - cur); return 2; } } } { int sx = x, sy = y, sn = ui_snap(m, root, &sx, &sy); if (sn == 6) { snprintf(hit, hn, "盖:%s 不点", g_inside_name); return 6; } if (sn == 1) { if (snap_guarded(root, g_click_name)) snap_guard_near(g_click_w, g_click_name, x, y, sx, sy, *(int32_t *)(m->base + 0x211da38), *(int32_t *)(m->base + 0x211da3c)); // 只为留一行本体点数读数 | only to leave one line of readout of the widget body's size in points snprintf(hit, hn, " 可点控件 %s", g_click_name); bd_note_skill(m, root, sx, sy); return 0; } @@ -2634,7 +2645,7 @@ void dm_ui_on_uimsg(const char *cat, const char *act, const char *arg) { if (strcmp(cat, "InputMessage") && strcmp(cat, "MonsterHealth") && strcmp(cat, "PartyPanelMessage")) DM_LAT("ui %s %s %s", cat, act, arg ? arg : ""); { static const char *at; static int got; if (!got) { got = 1; at = getenv("DM_UI_TAPS_AT"); } if (at && !atomic_load(&g_taps_base)) { char k[160]; snprintf(k, sizeof k, "%s:%s", act, arg); if (strstr(k, at)) atomic_store(&g_taps_base, dm_guest_frame() | 1); } } - if (!strcmp(cat, "PanelManager") && !strcmp(arg, "CharacterCreateNamePanel")) { int op = !strcmp(act, "OpenPanel"); if (op || !strcmp(act, "ClosePanel") || !strcmp(act, "UnloadPanel")) { atomic_store(&g_fe_name_open, op); if (op) atomic_store(&g_fe_name, 1); } } + if (!strcmp(cat, "PanelManager") && !strcmp(arg, "CharacterCreateNamePanel")) { int op = !strcmp(act, "OpenPanel"); if (op || !strcmp(act, "ClosePanel") || !strcmp(act, "UnloadPanel")) { atomic_store(&g_fe_name_open, op); if (op) atomic_store(&g_fe_name_has, 0); if (op) atomic_store(&g_fe_name, 1); } } if (!strcmp(cat, "PanelManager") && (!strcmp(arg, "CharacterOptionsPanel") || !strcmp(arg, "ConfirmationModal"))) { int op = !strcmp(act, "OpenPanel"); if (op || !strcmp(act, "ClosePanel") || !strcmp(act, "UnloadPanel")) atomic_store(arg[1] == 'h' ? &g_fe_opt_open : &g_fe_confirm_open, op); } if (!strcmp(cat, "PanelManager") && !strcmp(arg, "DeleteCharacterModal")) { if (!strcmp(act, "OpenPanel")) atomic_store(&g_fe_del_open, 1); else if (!strcmp(act, "ClosePanel") || !strcmp(act, "UnloadPanel")) { atomic_store(&g_fe_del_open, 0); atomic_store(&g_del_hold, 0); } } if (!strcmp(cat, "PanelManager") && !strcmp(arg, "CharacterCreatePanel")) { if (!strcmp(act, "OpenExclusivePanel") || !strcmp(act, "OpenPanel")) atomic_store(&g_cc_open, 1); else if (!strcmp(act, "ClosePanel") || !strcmp(act, "UnloadPanel")) atomic_store(&g_cc_open, 0); } @@ -2665,7 +2676,8 @@ static uint64_t ui_find(uint64_t w, const char *name, int dep) { // 按名字 static uint64_t fe_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return (uint64_t)t.tv_sec * 1000 + t.tv_nsec / 1000000; } static char g_fe_name_text[64]; static _Atomic uint64_t g_fe_name_ms; // 键盘交回的名字(写完后才置 g_fe_name_done);主线程第一次看到交回的时刻 | the name handed back by the keyboard (g_fe_name_done is set only after it is written); the moment the main thread first sees the hand-back _Atomic int g_fe_name_no_accept; // 前端置 1:这次返回的是替玩家抽的随机名(front_ios.m),只填进名字框、不自动「接受」——同原版「随机名字」键,玩家看到名字再自己点创建 | set to 1 by the front end: what is returned this time is a random name drawn for the player (front_ios.m), which is only filled into the name box without an automatic 「接受」(Accept) -- same as the original game's 「随机名字」(Random Name) button, the player sees the name and then taps create themselves -void dm_ui_text_entered(const char *text) { if (atomic_exchange(&g_fe_name_no_accept, 0)) return; if (text && *text && atomic_load(&g_fe_name_open)) { strlcpy(g_fe_name_text, text, sizeof g_fe_name_text); atomic_store(&g_fe_name_done, 1); } } // 系统键盘返回(hle_swkbd.c):起名页输完名字 → 自动「接受」 | system keyboard returns (hle_swkbd.c): name entered on the naming page → automatic 「接受」(Accept) +int dm_ui_fe_name_wants_input(void) { return atomic_load(&g_fe_name_open) && !atomic_load(&g_fe_name_has); } // 起名页开着、名字还没填:Mac 键盘的回车这时当「输入名称」(A)而不是「接受」(+),见 touch_mac.c | naming page open and the name not yet filled in: Return on a Mac keyboard then acts as "Enter Name" (A) instead of "Accept" (+), see touch_mac.c +void dm_ui_text_entered(const char *text) { if (text && *text && atomic_load(&g_fe_name_open)) atomic_store(&g_fe_name_has, 1); if (atomic_exchange(&g_fe_name_no_accept, 0)) return; if (text && *text && atomic_load(&g_fe_name_open)) { strlcpy(g_fe_name_text, text, sizeof g_fe_name_text); atomic_store(&g_fe_name_done, 1); } } // 系统键盘返回(hle_swkbd.c):起名页输完名字 → 自动「接受」 | system keyboard returns (hle_swkbd.c): name entered on the naming page → automatic 「接受」(Accept) // 前端要宿主替玩家点一下某个手柄键(任意线程调):按住 frames 个客体帧后自动松开。目前只有一处用:进局后点一次「显示物品」键(front_ios.m item_labels_on) // The front end asks the host to press a controller button once for the player (callable from any thread): held for frames guest frames and then released automatically. Currently used in only one place: pressing the 「显示物品」(Show Items) button once after entering a run (front_ios.m item_labels_on) static _Atomic uint64_t g_pulse_mask, g_pulse_until; diff --git a/dm/host/dm_i18n_tab.h b/dm/host/dm_i18n_tab.h index a180f4b..66b6bc7 100644 --- a/dm/host/dm_i18n_tab.h +++ b/dm/host/dm_i18n_tab.h @@ -152,8 +152,8 @@ static const struct { const char *k, *zh, *en; } k_dm_i18n[] = { { "dmOldPackSize", "「%s」里的补充包大小不对(%.2f / %.2f GB),像是没拷完", "The pack in \"%s\" has the wrong size (%.2f / %.2f GB); the copy looks incomplete" }, { "dmOldPackBad", "「%s」里的补充包内容不对(和这个版本不配套,或拷坏了),请重新下载", "The pack in \"%s\" does not match this version or is corrupted; please download it again" }, { "dmOldPackNone", "没找到老机型补充包", "Supplementary pack for older devices not found" }, - { "dmOldUnsupTitle", "暂不支持本机型", "Device Not Supported" }, - { "dmOldUnsupMsg", "本机型(iPhone 14 及更早,A16 及以前芯片)暂不支持:显卡不支持游戏素材格式。iPhone 15 Pro 及以后可以玩。", "This device (iPhone 14 or earlier, A16 chip or older) is not supported yet: its GPU cannot read the game's texture format. iPhone 15 Pro and later can run the game." }, + { "dmOldUnsupTitle", "这台设备要多做一步", "One More Step for This Device" }, + { "dmOldUnsupMsg", "本机型(A16 及更早的芯片,如 iPhone 14 系列、iPhone 15 / 15 Plus)可以玩,但要多做一份「Legacy Device Pack」,并在做安装包时带上它——这个安装包没有带。\n\n怎么做:打开 github.com/jhaizhou-ops/d2r-mobile,照 docs/LEGACY_DEVICES 说明做好补充包,带着它重新做一次安装包,再装到手机上。", "This device (A16 chip or older, such as the iPhone 14 family and iPhone 15 / 15 Plus) can run the game, but it needs a supplementary pack for older devices, and the install package has to be made with it - this one was not.\n\nWhat to do: open github.com/jhaizhou-ops/d2r-mobile, follow docs/LEGACY_DEVICES to make the pack, make the install package again with it, then install it on the phone." }, { "dmOldNeedTitle", "需要老机型补充包", "Supplementary Pack Required" }, { "dmOldNeedMsg", "本机型需要老机型补充包(约 %.1f GB)。\n在「文件」里把「Legacy Device Pack」文件夹整个拷到「我的 iPhone → D2R Mobile」,再打开D2R Mobile。%@", "This device needs the supplementary pack for older devices (about %.1f GB).\nIn the Files app, copy the whole \"Legacy Device Pack\" folder into \"On My iPhone → D2R Mobile\", then open D2R Mobile again.%@" }, { "dmOldWhySuffix", "\n(%s)", "\n(%s)" }, @@ -317,5 +317,5 @@ static const struct { const char *k, *zh, *en; } k_dm_i18n[] = { { "dmAppFullscreen", "全屏", "Toggle Full Screen" }, { "dmAppMenuHelp", "帮助", "Help" }, { "dmAppKeysTitle", "键盘与手柄按键对照", "Keyboard and Controller Buttons" }, - { "dmAppKeysText", "界面上的按键提示是手柄字母,键盘这样对应:\n\n移动:W A S D(左摇杆)\n十字键:方向键\nA 确认:J  B 返回:K  X:U  Y:I\nL:Q  R:E  ZL:Z  ZR:C\n按左摇杆:F  按右摇杆:G\n+(菜单):回车  −(地图):Tab\n\n鼠标:左键点目标或界面,右键 = B,滚轮滚列表。\n接上手柄可以直接用。这一页以后在「帮助」菜单里。", "On-screen button hints use controller letters. Keyboard mapping:\n\nMove: W A S D (left stick)\nD-pad: arrow keys\nA confirm: J B back: K X: U Y: I\nL: Q R: E ZL: Z ZR: C\nPress left stick: F Press right stick: G\n+ (menu): Return − (map): Tab\n\nMouse: left click a target or the interface, right click = B, wheel scrolls lists.\nA connected controller works right away. This page stays in the Help menu." }, + { "dmAppKeysText", "界面上的按键提示是手柄字母,键盘这样对应:\n\n确认(A):空格 或 J  返回(B):Esc 或 K\n回车:确认;页面底部有「+」提示时是 +(如起名后的「接受」)\n+(菜单 / 新角色):= 键  −(地图):Tab\n移动:W A S D(左摇杆)  十字键:方向键\nX:U  Y:I  L:Q  R:E  ZL:Z  ZR:C\n按左摇杆:F  按右摇杆:G\n\n鼠标:左键点目标、界面、底部的按键提示和技能 / 药水格;右键 = 返回;滚轮滚列表。\n接上手柄可以直接用。这一页以后在「帮助」菜单里。", "On-screen button hints use controller letters. Keyboard mapping:\n\nConfirm (A): Space or J Back (B): Esc or K\nReturn: confirm; acts as + when the page shows a + hint (e.g. Accept after naming)\n+ (menu / new character): = key − (map): Tab\nMove: W A S D (left stick) D-pad: arrow keys\nX: U Y: I L: Q R: E ZL: Z ZR: C\nPress left stick: F Press right stick: G\n\nMouse: left click targets, the interface, the button hints at the bottom and skill / potion slots; right click = back; wheel scrolls lists.\nA connected controller works right away. This page stays in the Help menu." }, }; diff --git a/dm/host/dm_padmode.c b/dm/host/dm_padmode.c index 794dcb6..1e03273 100644 --- a/dm/host/dm_padmode.c +++ b/dm/host/dm_padmode.c @@ -309,6 +309,21 @@ static uint64_t legend_at(uint8_t *b, uint64_t w, uint64_t xy, int dep) { uint64_t ch = rd8(w + 0x58), n = rd8(w + 0x60); for (uint64_t i = n < 256 ? n : 0; ch && i-- > 0; ) { uint64_t r = legend_at(b, rd8(ch + 8 * i), xy, dep + 1); if (r) return r; } return 0; } +// 屏上最上面那条看得见的按键提示条里有没有某个键帽(如 + = 0xe005)。Mac 键盘的回车据此决定当 + 还是当确认(touch_mac.c)。只许游戏主线程调 +// Whether the topmost visible key-hint bar on screen contains a given key cap (e.g. + = 0xe005). Return on a Mac keyboard uses this to decide between + and confirm (touch_mac.c). Call only from the game main thread +static uint64_t legend_top(uint8_t *b, uint64_t w, int dep) { + if (!w || dep > 8 || !*(uint8_t *)(uintptr_t)(w + 0x50) || !*(uint8_t *)(uintptr_t)(w + 0x51)) return 0; + uint64_t vt = rd8(w) - (uint64_t)(uintptr_t)b; if (vt == 0x20b7960 || vt == 0x20b7a30) return rd8(w + 0x88) && rd8(w + 0x90) && rd8(w + 0x90) <= 12 ? w : 0; + uint64_t ch = rd8(w + 0x58), n = rd8(w + 0x60); for (uint64_t i = n < 256 ? n : 0; ch && i-- > 0; ) { uint64_t r = legend_top(b, rd8(ch + 8 * i), dep + 1); if (r) return r; } + return 0; +} +int dm_padmode_legend_has(uint32_t glyph) { + extern module_t g_mod[]; extern int g_nmod; 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; + uint64_t root = b ? rd8((uint64_t)(uintptr_t)(b + 0x2f05458)) : 0, lg = root ? legend_top(b, root, 0) : 0; if (!lg) return 0; + { const char *nm = (const char *)(uintptr_t)rd8(lg + 8); if (glyph == 0xe005 && nm && !strcmp(nm, "MainMenuLegend")) return 0; } // 主菜单例外:它的提示条有「+ 新角色」,但回车在主菜单要当确认(进入游戏);新角色用 = 键或鼠标点那一条 | main menu exception: its hint bar has "+ New Character", but Return on the main menu must act as confirm (enter the game); a new character uses the = key or a mouse click on that entry + uint64_t arr = rd8(lg + 0x88), n = rd8(lg + 0x90); for (uint64_t i = 0; i < n; i++) if (*(int32_t *)(uintptr_t)(arr + 0x40 * i + 8) == 1 && *(uint32_t *)(uintptr_t)(arr + 0x40 * i) == glyph) return 1; + return 0; +} uint64_t dm_padmode_legend_click(float nx, float ny) { extern module_t g_mod[]; extern int g_nmod; 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 || !g_cur) return 0; int W = *(int32_t *)(b + 0x211da38), H = *(int32_t *)(b + 0x211da3c); uint64_t root = rd8((uint64_t)(uintptr_t)(b + 0x2f05458)); if (!root || W <= 0 || H <= 0) return 0; @@ -325,10 +340,39 @@ uint64_t dm_padmode_legend_click(float nx, float ny) { if (*(int32_t *)(uintptr_t)(e + 8) == 1) for (unsigned k = 0; k < sizeof km / sizeof *km && !btn; k++) { // 键帽 → 键:照 legend_find 的比法,拿动作号建一个空字条目取它的键帽来比 | key cap -> key: the same comparison as legend_find, build an entry with empty text from the action number and take its key cap to compare uint64_t ent[8] = { 0 }; struct { const char *p; uint64_t n; } sv = { "", 0 }; ((void (*)(void *, int, int, void *))(b + 0xaa9358))(ent, km[k].act, 0, &sv); legend_free(b, ent); if ((int32_t)ent[1] == 1 && (uint32_t)ent[0] == gl) btn = km[k].btn; } + if (!btn && gl == 0xe008) btn = DM_BTN_LS; // 按左摇杆(物品栏「打开魔盒」)同样没有动作号可比(实测 e008) | pressing the left stick (inventory "Open Cube") likewise has no action number to compare with (measured e008) if (!btn && gl == 0xe005) btn = DM_BTN_PLUS; // + 键没有对应的动作号可比(主菜单「+ 新角色」):直接认它的键帽码(实测 e005) | the + key has no action number to compare with (main menu "+ New Character"): recognise its key-cap code directly (measured e005) LOG("手柄提示条:鼠标点在第 %d 条(共 %llu 条,键帽 %x)→ %s", hit + 1, (unsigned long long)n, gl, btn ? "按它那个键" : "认不出是哪个键,不按"); return btn; } +// 鼠标点局内底部 HUD(Mac App):手柄版 HUD 上的东西不是可点控件(手柄各有专键),鼠标点上去原先被当成「点世界」。按在哪个控件上就按它对应的键: +// 技能格 1–6 = A B Y X R ZR(屏上键帽的次序);腰带四格 = 十字键 左 上 下 右(原版对应,同 dm_touch_controls.c);中间的钮 = +(开功能页);跑 / 走钮 = 按左摇杆。 +// 血球、魔球、经验条、耐力条:没有对应的键,吃掉这一下(不许落到世界上去发令)。返回 0 = 没点在 HUD 上,1 = 按 *btn,2 = 吃掉不处理。只许游戏主线程调 +// Mouse clicks on the in-game bottom HUD (Mac App): the things on the gamepad-layout HUD are not clickable widgets (the gamepad has a dedicated key for each), and a mouse click on them used to be treated as "click the world". Pressing on a widget presses its corresponding key: +// skill slots 1–6 = A B Y X R ZR (the order of the key caps on screen); the four belt cells = D-pad left up down right (as in the original, same as dm_touch_controls.c); the middle button = + (open the function page); the run / walk button = press the left stick. +// Life orb, mana orb, experience bar, stamina bar: no corresponding key, so the click is swallowed (it must not fall through to the world and issue an order). Returns 0 = not on the HUD, 1 = press *btn, 2 = swallowed without action. Call only from the game main thread +int dm_padmode_hud_click(float nx, float ny, uint64_t *btn) { + extern module_t g_mod[]; extern int g_nmod; 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 || !g_cur) return 0; int W = *(int32_t *)(b + 0x211da38), H = *(int32_t *)(b + 0x211da3c); uint64_t root = rd8((uint64_t)(uintptr_t)(b + 0x2f05458)); if (!root || W <= 0 || H <= 0) return 0; + if (*(volatile uint8_t *)(b + 0x2d5ff51) | *(volatile uint8_t *)(b + 0x2d5ff67)) return 0; // 游戏停着(暂停菜单、大秘境选层页这类借壳的面板开着——手势层的面板名单认不到后者):HUD 不认,免得点技能格变成在那一页上按 A | the game is stopped (pause menu, or a panel borrowing another shell such as the Greater Rift level-selection page is open - the gesture layer's panel list does not recognise the latter): the HUD is not recognised, so a click on a skill slot does not turn into pressing A on that page + uint64_t hud = pm_find(root, "HUDPanel", 5); if (!hud || !*(uint8_t *)(uintptr_t)(hud + 0x50) || !*(uint8_t *)(uintptr_t)(hud + 0x51)) return 0; // pm_find 的第三个参数是起始深度:只看根的直接子面板 | the third argument of pm_find is the starting depth: look only at the direct child panels of the root + uint64_t xy = (uint64_t)(uint32_t)(nx * W) | ((uint64_t)(uint32_t)(ny * H) << 32), ch = rd8(hud + 0x58), n = rd8(hud + 0x60); + static const struct { const char *nm; uint64_t btn; } km[] = { { "SkillButton1", DM_BTN_A }, { "SkillButton2", DM_BTN_B }, { "SkillButton3", DM_BTN_Y }, { "SkillButton4", DM_BTN_X }, { "SkillButton5", DM_BTN_R }, { "SkillButton6", DM_BTN_ZR }, + { "LevelUpButton", DM_BTN_PLUS }, { "RunButton", DM_BTN_LS }, { "RunButtonPrompt", DM_BTN_LS }, { "HealthBall", 0 }, { "ManaBall", 0 }, { "ExpBar", 0 }, { "StaminaBar", 0 }, { "SkillSwapIndicator", 0 }, { "LTButtonPrompt", 0 } }; + static const uint64_t belt[4] = { DM_BTN_LEFT, DM_BTN_UP, DM_BTN_DOWN, DM_BTN_RIGHT }; + #define HUD_HIT(w, q) (((int (*)(uint64_t, uint64_t))rd8(rd8(w) + 0x48))((w), (q)) & 1) + int px = (int)(nx * W), py = (int)(ny * H); + for (int pass = 0; pass < 2; pass++) // 先认有键的(跑 / 走钮被耐力条压着一部分),再认只吃掉的 | first recognise the ones with a key (the run / walk button is partly covered by the stamina bar), then the ones that are only swallowed + for (uint64_t i = n < 64 ? n : 0; ch && i-- > 0; ) { uint64_t w = rd8(ch + 8 * i); if (!w || !*(uint8_t *)(uintptr_t)(w + 0x50)) continue; const char *nm = (const char *)(uintptr_t)rd8(w + 8); if (!nm) continue; + if (!pass && !strcmp(nm, "Belt") && HUD_HIT(w, xy)) { // 腰带是一个控件、四格等宽(子控件只是四个键帽字):沿这一行量出它的左右边,按四等分取格 | the belt is one widget with four equal-width cells (the child widgets are only the four key-cap glyphs): measure its left and right edges along this row and pick the cell by quarters + int l = px, r = px; while (l > 0 && HUD_HIT(w, (uint64_t)(uint32_t)(l - 2) | ((uint64_t)(uint32_t)py << 32))) l -= 2; while (r < W - 1 && HUD_HIT(w, (uint64_t)(uint32_t)(r + 2) | ((uint64_t)(uint32_t)py << 32))) r += 2; + int k = r > l ? (px - l) * 4 / (r - l + 1) : 0; if (k < 0) k = 0; if (k > 3) k = 3; *btn = belt[k]; LOG("手柄 HUD:鼠标点在腰带第 %d 格(腰带 x %d–%d)→ 按十字键 %s", k + 1, l, r, k == 0 ? "LEFT" : k == 1 ? "UP" : k == 2 ? "DOWN" : "RIGHT"); return 1; } + for (unsigned k = 0; k < sizeof km / sizeof *km; k++) if ((km[k].btn != 0) == !pass && !strcmp(nm, km[k].nm) && HUD_HIT(w, xy)) { + *btn = km[k].btn; uint64_t kb = km[k].btn; const char *kn = kb == DM_BTN_A ? "A" : kb == DM_BTN_B ? "B" : kb == DM_BTN_Y ? "Y" : kb == DM_BTN_X ? "X" : kb == DM_BTN_R ? "R" : kb == DM_BTN_ZR ? "ZR" : kb == DM_BTN_PLUS ? "PLUS" : kb == DM_BTN_LS ? "LS" : ""; + if (kb) LOG("手柄 HUD:鼠标点在 %s → 按 %s", nm, kn); else LOG("手柄 HUD:鼠标点在 %s → 没有对应的键,这一下不处理", nm); return kb ? 1 : 2; } } + #undef HUD_HIT + return 0; +} static void legend_pump(uint8_t *b, uint64_t frame) { // 游戏主线程每帧 | Game main thread, every frame static int miss, tot; static uint64_t logged; int test = getenv("DM_TEST_LEGEND") != NULL; // 测试开关 DM_TEST_LEGEND=<动作号>:<字>[,…]:手柄模式下一直声明这些条目;DM_TEST_LEGEND_OFF=<帧>:到这一帧起不再声明。DM_TEST_LEGEND_LOG=1:每 120 帧记一行提示条现状(不声明条目) diff --git a/dm/host/dm_runeword.c b/dm/host/dm_runeword.c index 701051f..a1582eb 100644 --- a/dm/host/dm_runeword.c +++ b/dm/host/dm_runeword.c @@ -24,6 +24,7 @@ // Get localized string main+0x7f5630(&{key, length}) (the game picks between the normal / legacy translation sets by setting). Client send packet main+0x2ceab0(packet, length). // Socket packets follow the client packets of a real socketing run (fm_ipadfull_k): 0x19 [item id][u32 x][u32 y][u32 page] (17 bytes, pick up to the cursor) → 0x28 [rune id][base id][u32 equipment slot 0][u32 page][u16 x][u16 y] (21 bytes, socket it). #include "hle.h" +#include "dm_rwlv_core.h" #include "dm_i18n.h" #include "dm_actions.h" #include "dm_input.h" @@ -146,7 +147,7 @@ static uint64_t first_item(uint64_t u) { uint64_t c = u ? *(uint64_t *)(u + 0x90 static struct { uint32_t base; int n; cand_t c[NROW]; int open; } g_list; // 打开着的清单 | The currently open list static int rune_lv(uint8_t *b, uint64_t t, int cls, int lvoff) { uint64_t ir = *(uint64_t *)(t + 0x15c0); uint32_t in = *(uint32_t *)(t + 0x15c8); return ir && cls >= 0 && (uint32_t)cls < in && lvoff >= 0 ? *(uint8_t *)(ir + (uint64_t)cls * 0x1c0 + lvoff) : 0; } static void rune_code(uint64_t t, int cls, char out[4]) { uint64_t ir = *(uint64_t *)(t + 0x15c0); uint32_t in = *(uint32_t *)(t + 0x15c8); memset(out, 0, 4); if (ir && cls >= 0 && (uint32_t)cls < in) memcpy(out, (const void *)(ir + (uint64_t)cls * 0x1c0 + 0x80), 3); } -static int g_lvoff = -1; // 物品表行里「需要等级」的偏移:首次用到时按已知三颗符文的值(塔尔 17 / 艾斯 15 / 沙伊 29,misc.txt levelreq)在行里找,找不到就不显示等级 | Offset of "required level" in the item table row: on first use, searched for in the row using the known values of three runes (Tal 17 / Eth 15 / Shael 29, misc.txt levelreq); if not found, the level is not shown +static int g_lvoff = -1; // 物品表行里「需求等级」(levelreq)的偏移:首次用到时按已知物品的原版值在行里找(dm_rwlv_core.c),找不到就不显示等级 | offset of "required level" (levelreq) in an item-table row: found on first use by the original values of known items (dm_rwlv_core.c); when not found no level is shown // 这件物品能当符文之语底材吗(品质、孔、物品表标志;位置另判) // Can this item serve as a runeword base item (quality, sockets, item table flag; location is checked separately) @@ -163,10 +164,13 @@ static void count_have(uint8_t *b, uint64_t pl, int cls, have_t *h) { if (st) h->stack += st; else if (o) h->shared++; else if (pg == PG_INV) h->inv++; else if (pg == PG_CUBE) h->cube++; else h->stash++; } it = *(uint64_t *)(d + 0xb0); } } -static int find_lvoff(uint64_t t) { - uint64_t ir = *(uint64_t *)(t + 0x15c0); if (!ir || *(uint32_t *)(t + 0x15c8) < 640) return -1; - for (int o = 0; o < 0x1c0; o++) if (*(uint8_t *)(ir + 631 * 0x1c0 + o) == 17 && *(uint8_t *)(ir + 629 * 0x1c0 + o) == 15 && *(uint8_t *)(ir + 637 * 0x1c0 + o) == 29) return o; - return -1; +static int find_lvoff(uint64_t t) { // 锚点与找法见 dm_rwlv_core.c;找不到(或不唯一)返回 -1,清单不显示等级 | anchors and the search are in dm_rwlv_core.c; returns -1 when not found (or not unique), and the list then shows no level + uint64_t ir = *(uint64_t *)(t + 0x15c0); uint32_t in = *(uint32_t *)(t + 0x15c8); int o = ir ? dm_rw_find_lvoff((const uint8_t *)ir, in, 0x1c0) : -1; + // 测试开关 DM_TEST_RW_LVDUMP=<文件>:把整张物品表逐行写成「物品码读到的需求等级」,给 dm/ios/tools/rw_lvcheck.py 与原版 weapons / armor / misc 三张表全量核 + // Test switch DM_TEST_RW_LVDUMP=: write the whole item table line by line as "item coderequired level read", for dm/ios/tools/rw_lvcheck.py to check in full against the original weapons / armor / misc tables + const char *e = getenv("DM_TEST_RW_LVDUMP"); FILE *f = e && o >= 0 ? fopen(e, "w") : NULL; + if (f) { for (uint32_t i = 0; i < in; i++) { const uint8_t *r = (const uint8_t *)(ir + (uint64_t)i * 0x1c0); char c[5] = {0}; memcpy(c, r + 0x80, 4); for (int k = 0; k < 4; k++) if (c[k] == ' ') c[k] = 0; fprintf(f, "%s\t%u\n", c, r[o]); } fclose(f); LOG("符文之语:DM_TEST_RW_LVDUMP 写了 %u 行 → %s", in, e); } + return o; } static int cand_cmp(const void *a, const void *b2) { const cand_t *x = a, *y = b2; if (x->ok != y->ok) return y->ok - x->ok; if (x->miss != y->miss) return x->miss - y->miss; return x->lv - y->lv; } // 列出这件底材能做的全部符文之语,并按此刻能取用的符文定 ok(能出按钮) @@ -174,7 +178,7 @@ static int cand_cmp(const void *a, const void *b2) { const cand_t *x = a, *y = b static int base_where(uint8_t *b, uint64_t pl, uint64_t it, int *page, int *x, int *y, int *slot); static int build_list(uint8_t *b, uint64_t it) { uint64_t t = tables(b, it), pl = player(b); if (!t || !pl || !base_ok(b, it, t)) return 0; - if (g_lvoff < 0) { g_lvoff = find_lvoff(t); LOG("符文之语:物品表「需要等级」偏移 %#x", g_lvoff); } + if (g_lvoff == -1) { g_lvoff = find_lvoff(t); if (g_lvoff < 0) LOG("【红】符文之语:物品表里没找到「需求等级」那一列(锚点物品对不上),清单不显示等级"); else LOG("符文之语:物品表「需求等级」偏移 %#x", g_lvoff); if (g_lvoff < 0) g_lvoff = -2; } int ns = sockets(b, it), stash_open = *(uint8_t *)(b + 0x2d5ff60) != 0, bp = 0, bx = 0, by = 0, bsl = 0, bw = base_where(b, pl, it, &bp, &bx, &by, &bsl); int can_put = bw && !(bw == 1 && bp == PG_STASH && !stash_open); // 底材在能镶的位置(储藏箱里的要箱子开着);共享仓库里的照列、不出按钮 | Base item is in a socketable location (one in the stash needs the stash open); one in the shared stash is still listed, without a button uint64_t rr = *(uint64_t *)(t + 0x1880), rn = *(uint64_t *)(t + 0x1888); g_list.n = 0; @@ -186,9 +190,11 @@ static int build_list(uint8_t *b, uint64_t it) { int good = 0; for (int k = 0; k < 6 && !good && !bad; k++) { int ty = *(const int16_t *)(e + 0x4a + 2 * k); if (ty && is_type(b, it, ty)) good = 1; } if (bad || !good) continue; cand_t *c = &g_list.c[g_list.n++]; memset(c, 0, sizeof *c); c->rec = (int)r; c->nr = nr; memcpy(c->cls, cls, sizeof cls); c->ok = can_put; int runes_ok = 1; - c->lv = rune_lv(b, t, *(int32_t *)(it + 4), g_lvoff); // 需要等级 = 底材与各符文的最大值(原版做成以后的说明同此;物品单位 +4 = 物品类号) | Required level = max of the base item and each rune (same as the original game's description once formed; item unit +4 = item class id) + int base_req = rune_lv(b, t, *(int32_t *)(it + 4), g_lvoff), rreq[6]; // 需要等级 = 底材与各符文需求等级的最大值(原版做成以后的说明同此;物品单位 +4 = 物品类号) | required level = the maximum of the required levels of the base item and each rune (the same as the original's description once made; item unit +4 = item class number) char key[64]; memcpy(key, e, 63); key[63] = 0; loc_tb(b, key, c->name, sizeof c->name); - for (int k = 0; k < nr; k++) { int lv = rune_lv(b, t, cls[k], g_lvoff); if (lv > c->lv) c->lv = lv; + for (int k = 0; k < nr; k++) rreq[k] = rune_lv(b, t, cls[k], g_lvoff); + c->lv = dm_rw_need_level(base_req, rreq, nr); + for (int k = 0; k < nr; k++) { int need = 0; for (int j = 0; j < nr; j++) need += cls[j] == cls[k]; have_t h; count_have(b, pl, cls[k], &h); int usable = h.inv + (stash_open ? h.stash + h.shared + h.stack : 0), total = h.inv + h.stash + h.shared + h.stack + h.cube; if (usable < need) { c->ok = 0; runes_ok = 0; } @@ -552,7 +558,7 @@ int dm_runeword_long_press(const dm_cursor_item_info *ci) { // 长按物品分 uint64_t it = unit_item(b, ci->id); if (!it || *(uint32_t *)(it + 0xc) > 1) return 0; if (!build_list(b, it)) return 0; g_list.base = ci->id; g_list.open = 1; ui_show(b, 1); ui_fill(b, it); ui_layout(); g_check_at = 6; - LOG("符文之语:长按 %s(id %u)→ 清单 %d 行(首行「%s」%s)", ci->code, ci->id, g_list.n, g_list.c[0].name, g_list.c[0].ok ? "可做" : "不可做"); + LOG("符文之语:长按 %s(id %u)→ 清单 %d 行(首行「%s」需要等级 %d %s)", ci->code, ci->id, g_list.n, g_list.c[0].name, g_list.c[0].lv, g_list.c[0].ok ? "可做" : "不可做"); if (getenv("DM_TEST_RW_DESC") && !strcmp(getenv("DM_TEST_RW_DESC"), "all")) { // 测试开关 =all:表里每个 complete 的符文之语都生成一遍原版说明,记行数(定详情字号用) | Test switch =all: generate the original game's description once for every complete runeword in the table and log the line counts (used to pick the detail font size) uint8_t ver = *(uint8_t *)(b + 0x2127c48); uint64_t t = ver >= 1 && ver <= 3 ? *(uint64_t *)(b + 0x2d64a18 + ver * 16) : 0, rr = t ? *(uint64_t *)(t + 0x1880) : 0; uint32_t rn = t ? *(uint32_t *)(t + 0x1888) : 0; int mx = 0, mxr = -1, cnt = 0, fail = 0; static char d[4096]; diff --git a/dm/host/dm_rwlv_core.c b/dm/host/dm_rwlv_core.c new file mode 100644 index 0000000..01a2a80 --- /dev/null +++ b/dm/host/dm_rwlv_core.c @@ -0,0 +1,37 @@ +// 见 dm_rwlv_core.h。 +// 「需求等级」的偏移没有写死,按已知物品的原版值在行里找——锚点必须含「物品等级 ≠ 需求等级」的行: +// 原先只用三颗符文(塔尔 17 / 艾斯 15 / 沙伊 29)当锚点,而符文的物品等级(misc.txt level)与需求等级(levelreq)33 颗里 32 颗是同一个数, +// 先撞上的是排在前面的物品等级那一列;读符文没差,读底材就成了物品等级(塔盔 uhm:需求 59 被读成 79),清单里整页的需要等级偏高。 +// See dm_rwlv_core.h. +// The offset of "required level" is not hard-coded; it is found in the row by the original values of known items - the anchors must include rows where "item level != required level": +// previously only three runes (Tal 17 / Eth 15 / Shael 29) served as anchors, and for runes the item level (misc.txt level) and the required level (levelreq) are the same number for 32 of the 33, +// so the first hit was the item-level column that comes earlier; reading runes made no difference, but reading a base item gave its item level (Spired Helm uhm: required 59 read as 79), and the whole page of required levels in the list was too high. +#include "dm_rwlv_core.h" +#include + +// 原版 armor.txt / misc.txt 的 levelreq(括号里是同一行的 level,两者不同的才分得开两列) +// levelreq from the original armor.txt / misc.txt (in parentheses the level of the same row; only rows where the two differ can tell the two columns apart) +static const struct { const char *code; uint8_t req; } k_anchor[] = { + { "uhm", 59 }, // 塔盔(79) | Spired Helm (79) + { "xhm", 25 }, // 翼盔(51) | Winged Helm (51) + { "ci3", 64 }, // 权冠(85) | Diadem (85) + { "urn", 66 }, // 宝冠(85) | Corona (85) + { "ulm", 51 }, // 武装盔(68) | Armet (68) + { "r07", 17 }, // 塔尔(17) | Tal (17) + { "r13", 29 }, // 沙伊(29) | Shael (29) +}; +#define NANCHOR (int)(sizeof k_anchor / sizeof k_anchor[0]) + +int dm_rw_find_lvoff(const uint8_t *rows, uint32_t n, uint32_t rowsize) { + const uint8_t *at[NANCHOR]; memset(at, 0, sizeof at); + if (!rows || rowsize < 0x84) return -1; + for (uint32_t i = 0; i < n; i++) { const uint8_t *r = rows + (uint64_t)i * rowsize; + for (int k = 0; k < NANCHOR; k++) if (!at[k] && !memcmp(r + 0x80, k_anchor[k].code, 3) && (r[0x83] == 0 || r[0x83] == ' ')) at[k] = r; } + for (int k = 0; k < NANCHOR; k++) if (!at[k]) return -1; + int found = -1; + for (uint32_t o = 0; o < rowsize; o++) { int ok = 1; for (int k = 0; k < NANCHOR && ok; k++) ok = at[k][o] == k_anchor[k].req; + if (ok) { if (found >= 0) return -1; found = (int)o; } } + return found; +} + +int dm_rw_need_level(int base_req, const int *rune_req, int n) { int lv = base_req; for (int i = 0; i < n; i++) if (rune_req[i] > lv) lv = rune_req[i]; return lv; } diff --git a/dm/host/dm_rwlv_core.h b/dm/host/dm_rwlv_core.h new file mode 100644 index 0000000..6c1efee --- /dev/null +++ b/dm/host/dm_rwlv_core.h @@ -0,0 +1,12 @@ +// 符文之语清单的「需要等级」:纯算法部分(不碰游戏内存布局以外的东西,宿主单测 tests/t_rwlv.c 直接链) +// "Required level" in the runeword list: the pure-algorithm part (touches nothing beyond the game's memory layout; the host unit test tests/t_rwlv.c links it directly) +#pragma once +#include +// 在物品表(weapons + armor + misc 合成的一张,每行 rowsize 字节,行内 +0x80 起 3 字节是物品码)里找「需求等级」那一个字节的行内偏移。 +// 找不到或不唯一返回 -1。 +// Find the in-row offset of the one byte holding "required level" in the item table (weapons + armor + misc combined, rowsize bytes per row, with the 3-byte item code at +0x80 in the row). +// Returns -1 when not found or not unique. +int dm_rw_find_lvoff(const uint8_t *rows, uint32_t n, uint32_t rowsize); +// 做成以后的需要等级 = 底材需求等级与各符文需求等级的最大值 +// Required level once made = the maximum of the base item's required level and each rune's required level +int dm_rw_need_level(int base_req, const int *rune_req, int n); diff --git a/dm/host/front_mac.m b/dm/host/front_mac.m index b462d9a..9638605 100644 --- a/dm/host/front_mac.m +++ b/dm/host/front_mac.m @@ -20,6 +20,7 @@ __attribute__((constructor)) static void ui_shift_reg(void) { mtl_set_ui_rect_fn void dm_touch_host_live_enable(void); void dm_touch_host_live(int op, float nx, float ny); // touch_mac.c static int g_live; // App 形态(或 DM_TOUCH_LIVE=1):鼠标进我们的触屏状态机;否则照旧当原版触摸屏的一个触点 | App form (or DM_TOUCH_LIVE=1): the mouse goes into our touch state machine; otherwise it stays a single touch point of the original touch screen as before 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 @@ -50,6 +51,7 @@ static void app_quit(const char *why) { } 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 ? ",原先暂停着、已放开" : ""); + { 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); } static const char *ui(const char *k) { const char *dm_ui(const char *key); return dm_ui(k); } @@ -84,7 +86,10 @@ static int key_bit(unsigned short code) { case 38: return 0; case 40: return 1; case 32: return 2; case 34: return 3; // J K U I → A B X Y case 3: return 4; case 5: return 5; // F G → 按摇杆 | F G → press stick case 12: return 6; case 14: return 7; case 6: return 8; case 8: return 9; // Q E Z C → L R ZL ZR - case 36: return 10; case 48: return 11; // 回车 Tab → + − | Return Tab → + − + case 36: return g_live ? 40 : 10; case 48: return 11; // 回车 Tab → + −(App 形态:回车交给 touch_mac.c 按当前页决定是 + 还是确认,见那里) | Return Tab -> + - (App form: Return is handed to touch_mac.c, which decides by the current page whether it is + or confirm, see there) + case 24: case 69: return 10; // = 键(+ 那个键)、小键盘 + → + | the = key (the one with +) and keypad + -> + + case 49: return 0; // 空格 → A(确认) | Space -> A (confirm) + case 53: return g_live ? 41 : -1; // Esc → 返回(App 形态;局内没有面板时是开功能页,touch_mac.c) | Esc -> back (App form; with no panel open in game it opens the function page, touch_mac.c) case 123: return 12; case 126: return 13; case 124: return 14; case 125: return 15; // ← ↑ → ↓ } return -1; @@ -113,7 +118,7 @@ void front_run(void (*guest)(void)) { NSWindow *win = [[NSWindow alloc] initWithContentRect:r styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO]; - win.title = @"D2R Mobile"; + 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); @@ -173,6 +178,36 @@ void front_run(void (*guest)(void)) { { 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]; }); + // 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. + // Each line is " down|move|up x,y", where x,y is a point in the content area (origin at top-left; the window defaults to 1280x720), and time counts from when the window is created + if ((e = getenv("DM_TEST_NSMOUSE"))) { NSString *txt = [NSString stringWithContentsOfFile:@(e) encoding:NSUTF8StringEncoding error:nil]; NSTimeInterval t0 = NSProcessInfo.processInfo.systemUptime; int n = 0; + dispatch_queue_t tq = dispatch_queue_create("dm.test.nsevent", DISPATCH_QUEUE_SERIAL); // 不排在主队列上:我们自己的弹框是在主队列的一个块里跑模态循环的,那期间主队列上别的块不执行,事件就投不进弹框 | not queued on the main queue: our own dialog runs its modal loop inside a block on the main queue, during which other blocks on the main queue do not execute, so events could not be delivered into the dialog + for (NSString *ln in [txt componentsSeparatedByString:@"\n"]) { double sec, x = 0, y = 0; char op[8]; + if (sscanf(ln.UTF8String, "%lf %7s %lf,%lf", &sec, op, &x, &y) < 2 || ln.UTF8String[0] == '#') continue; n++; + if (!strcmp(op, "key") || !strcmp(op, "type")) { // 「秒 key <键码>」:合成一次真正的键盘按下 / 0.08 秒后松开(键码 = 苹果的虚拟键码,如回车 36、Tab 48、J 38);「秒 type <字>」:逐字打字。 | " key ": synthesise a real key press / release 0.08 s later (key code = Apple virtual key code, e.g. Return 36, Tab 48, J 38); " type ": type character by character. + // 都投给当时的键窗口(真键盘就是这样:弹着输入框时进输入框),并记一行键窗口是不是游戏窗口 + // All are posted to the key window at that moment (which is what a real keyboard does: into the input field while it is shown), and one line records whether the key window is the game window + int ty = !strcmp(op, "type"); char word[64] = ""; if (ty) sscanf(ln.UTF8String, "%*lf %*7s %63s", word); NSString *chars = ty ? @(word) : (x == 36 ? @"\r" : @""); + if (ty) { // 打字:在主线程的运行循环里执行(模态框开着时也走——主队列那时不走),记下第一响应者是谁,再把字经响应链送进去(等于输入法提交了这些字) | typing: executed in the main thread's run loop (which also runs while a modal dialog is open - the main queue does not), noting who the first responder is, then sending the text through the responder chain (as if an input method committed it) + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(sec * NSEC_PER_SEC)), tq, ^{ CFRunLoopPerformBlock(CFRunLoopGetMain(), kCFRunLoopCommonModes, ^{ + NSWindow *kw = NSApp.keyWindow; id fr = kw.firstResponder; BOOL ok = [NSApp sendAction:@selector(insertText:) to:nil from:chars]; + LOG("DM_TEST_NSMOUSE:%.2f 秒打字「%s」(键窗口%s,第一响应者 %s,%s)", NSProcessInfo.processInfo.systemUptime - t0, chars.UTF8String, kw == win ? "是游戏窗口" : kw ? "是弹框" : "没有", fr ? NSStringFromClass([fr class]).UTF8String : "无", ok ? "有人收" : "没人收"); }); + CFRunLoopWakeUp(CFRunLoopGetMain()); }); + continue; } + for (NSUInteger ci = 0; ci < (ty ? chars.length : 1); ci++) { NSString *one = ty ? [chars substringWithRange:NSMakeRange(ci, 1)] : chars; double at = sec + ci * 0.15; + for (int dn = 1; dn >= 0; dn--) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((at + (dn ? 0 : 0.08)) * NSEC_PER_SEC)), tq, ^{ NSWindow *kw = NSApp.keyWindow; + if (dn) LOG("DM_TEST_NSMOUSE:%.2f 秒投 键盘 %s%s(键窗口%s)", NSProcessInfo.processInfo.systemUptime - t0, ty ? "字 " : "键码 ", ty ? one.UTF8String : [NSString stringWithFormat:@"%d", (int)x].UTF8String, kw == win ? "是游戏窗口" : kw ? "是别的窗口(弹框)" : "没有:App 里没有键窗口"); + [NSApp postEvent:[NSEvent keyEventWithType:dn ? NSEventTypeKeyDown : NSEventTypeKeyUp location:NSZeroPoint modifierFlags:0 timestamp:NSProcessInfo.processInfo.systemUptime windowNumber:(kw ?: win).windowNumber context:nil characters:one charactersIgnoringModifiers:one isARepeat:NO keyCode:ty ? 0 : (unsigned short)x] atStart:NO]; }); } + continue; } + NSEventType ty = !strcmp(op, "down") ? NSEventTypeLeftMouseDown : !strcmp(op, "up") ? NSEventTypeLeftMouseUp : NSEventTypeLeftMouseDragged; int has = !strcmp(op, "up") ? 0 : 1; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(sec * NSEC_PER_SEC)), tq, ^{ static NSPoint last; + if (has) last = NSMakePoint(x, v.bounds.size.height - y); // 内容区的点 → 窗口坐标(原点左下) | point in the content area -> window coordinates (origin at bottom-left) + NSEvent *ev = [NSEvent mouseEventWithType:ty location:[v convertPoint:last toView:nil] modifierFlags:0 timestamp:NSProcessInfo.processInfo.systemUptime windowNumber:win.windowNumber context:nil eventNumber:0 clickCount:1 pressure:ty == NSEventTypeLeftMouseUp ? 0 : 1]; + LOG("DM_TEST_NSMOUSE:%.2f 秒投 %s 内容区 (%.0f,%.0f)(窗口%s是主窗口,App %s在前台,背板缩放 %.1f)", NSProcessInfo.processInfo.systemUptime - t0, ty == NSEventTypeLeftMouseDown ? "按下" : ty == NSEventTypeLeftMouseUp ? "抬起" : "拖动", last.x, v.bounds.size.height - last.y, win.isKeyWindow ? "" : "不", NSApp.isActive ? "" : "不", win.backingScaleFactor); + [NSApp postEvent:ev atStart:NO]; }); } + LOG("DM_TEST_NSMOUSE:%d 条排好", n); } if ((e = getenv("DM_TEST_QUIT_AT"))) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(atof(e) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ app_quit("DM_TEST_QUIT_AT"); }); } // 生命周期(hle.h / dm.h):失焦 → 2、拿回焦点 → 1;最小化 → 3 + 音频暂停 + GPU 挂起,还原 → 恢复(随后拿回焦点 → 1) // Lifecycle (hle.h / dm.h): focus lost → 2, focus regained → 1; minimized → 3 + audio paused + GPU suspended, restored → resume (followed by focus regained → 1) @@ -205,8 +240,13 @@ int front_text_input(const char *title, const char *sub, const char *guide, cons NSTextField *f = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 300, 24)]; f.stringValue = initial ? @(initial) : @""; if (guide && *guide) f.placeholderString = @(guide); - a.accessoryView = f; a.window.initialFirstResponder = f; + a.accessoryView = f; [a layout]; a.window.initialFirstResponder = f; + f.target = a.buttons.firstObject; f.action = @selector(performClick:); // 在输入框里按回车 = 点「确定」(明确接上,不靠系统把回车转给缺省按钮) | pressing Return in the input field = clicking "OK" (wired explicitly, not relying on the system forwarding Return to the default button) + // 弹框出来后光标要在输入框里:只指定「初始第一响应者」不生效(实测弹出后第一响应者是弹框自己,要先点一下输入框才能打字),等模态循环转起来再显式指定一次 + // The cursor must be in the input field once the dialog appears: specifying only the "initial first responder" does not work (measured: after it appears the first responder is the dialog itself, and the field has to be clicked before typing), so it is specified explicitly once more after the modal loop starts running + CFRunLoopPerformBlock(CFRunLoopGetMain(), kCFRunLoopCommonModes, ^{ [a.window makeFirstResponder:f]; }); r = [a runModal] == NSAlertFirstButtonReturn; + [g_win makeKeyAndOrderFront:nil]; // 弹框关掉后把游戏窗口显式设回键窗口(系统通常自己会还,保险) | after the dialog closes, explicitly make the game window key again (the system usually returns it by itself; this is for safety) text = f.stringValue; }); if (!r) return 0; diff --git a/dm/host/main.c b/dm/host/main.c index 5291f97..1980793 100644 --- a/dm/host/main.c +++ b/dm/host/main.c @@ -171,7 +171,7 @@ void dm_host_preload_start(int argc, char **argv) { int dm_app_bootstrap(int *argc, char ***argv); // app_mac.m:包成 .app 双击起时备好环境与参数;命令行起原样 | app_mac.m: when packaged as an .app and started by double-click, prepare the environment and arguments; command-line starts are unchanged int main(int argc, char **argv) { #if TARGET_OS_OSX // iOS 包也编这个文件(入口由外壳调),那边没有 app_mac.m | The iOS package compiles this file too (the entry is called by the shell); there is no app_mac.m on that side - dm_app_bootstrap(&argc, &argv); + if (dm_app_bootstrap(&argc, &argv)) { void dm_cloud_boot(void); dm_cloud_boot(); } // App 形态:挂存档之前先做一次 iCloud 同步(同 iOS 壳的启动次序);取不到容器 / 测试存档时它自己记一行就返回 | App form: do one iCloud sync before mounting the save (same startup order as the iOS shell); when the container cannot be obtained / with a test save it logs one line and returns #endif if (getenv("DM_PRELOAD")) dm_host_preload_start(argc, argv); // Mac 上验证提前起跑的路径(iOS 由 App 的 main() 调) | Exercise the early-start path on Mac (on iOS it is called from the App's main()) if (atomic_load(&g_pre.started)) { diff --git a/dm/host/tests/Makefile b/dm/host/tests/Makefile index 974b50a..da375cd 100644 --- a/dm/host/tests/Makefile +++ b/dm/host/tests/Makefile @@ -4,7 +4,7 @@ DM_ROOT ?= $(HOME)/dm-work PY ?= $(DM_ROOT)/build/cache/dm/venv/bin/python EXEFS ?= $(DM_ROOT)/data/switch/3.3.94012/Update/ExeFS B = build -run: $(B)/t_thread_leak $(B)/t_rift_clock $(B)/t_textbox $(B)/t_padmap $(B)/t_touch $(B)/t_hid_receipt $(B)/t_hid_script $(B)/t_touch_mac $(B)/t_oe $(B)/t_fs $(B)/t_fs_case $(B)/t_romfs_validate $(B)/t_audio $(B)/t_audio_spsc $(B)/t_swkbd $(B)/t_altstack $(B)/t_movie $(B)/t_condvar $(B)/t_condvar_old $(B)/t_target_rank $(B)/t_hud_dead $(B)/t_namegen $(B)/t_modetx $(B)/t_unit_level $(B)/t_widget $(B)/t_doorspot $(B)/t_cloudsync $(B)/t_i18n $(B)/main.orig.bin $(B)/subsdk0.orig.bin +run: $(B)/t_thread_leak $(B)/t_rift_clock $(B)/t_textbox $(B)/t_rwlv $(B)/t_padmap $(B)/t_touch $(B)/t_hid_receipt $(B)/t_hid_script $(B)/t_touch_mac $(B)/t_oe $(B)/t_fs $(B)/t_fs_case $(B)/t_romfs_validate $(B)/t_audio $(B)/t_audio_spsc $(B)/t_swkbd $(B)/t_altstack $(B)/t_movie $(B)/t_condvar $(B)/t_condvar_old $(B)/t_target_rank $(B)/t_hud_dead $(B)/t_namegen $(B)/t_modetx $(B)/t_unit_level $(B)/t_widget $(B)/t_doorspot $(B)/t_cloudsync $(B)/t_i18n $(B)/main.orig.bin $(B)/subsdk0.orig.bin python3 native_write_scan.py --selftest .. python3 mode_scan.py ../.. python3 ../../ios/tools/dm_i18n.py --check @@ -12,6 +12,7 @@ run: $(B)/t_thread_leak $(B)/t_rift_clock $(B)/t_textbox $(B)/t_padmap $(B)/t_to $(B)/t_thread_leak $(B)/t_rift_clock $(B)/t_textbox + $(B)/t_rwlv $(B)/t_touch $(B)/t_hid_script 2>/dev/null $(B)/t_hid_receipt 2>/dev/null @@ -45,6 +46,8 @@ $(B)/t_hud_dead: t_hud_dead.c ../dm_hud.h | $(B) clang -O1 -Wall -Werror -I.. -o $@ t_hud_dead.c $(B)/t_textbox: t_textbox.c ../dm_textbox_core.c ../dm_textbox_core.h | $(B) clang -O1 -Wall -Werror -o $@ t_textbox.c ../dm_textbox_core.c +$(B)/t_rwlv: t_rwlv.c ../dm_rwlv_core.c ../dm_rwlv_core.h | $(B) + clang -O1 -Wall -Werror -o $@ t_rwlv.c ../dm_rwlv_core.c $(B)/t_doorspot: t_doorspot.c ../dm_doorspot.h | $(B) clang -O1 -Wall -Werror -I.. -o $@ t_doorspot.c $(B)/t_widget: t_widget.c ../dm_widget.h | $(B) diff --git a/dm/host/tests/mode_scan.py b/dm/host/tests/mode_scan.py index bc2ef45..267054e 100644 --- a/dm/host/tests/mode_scan.py +++ b/dm/host/tests/mode_scan.py @@ -40,7 +40,7 @@ else: if name not in on_line and name not in both: red.append('dm_cursor.c 定义了 %s,但每帧那一行和「两种模式都跑」单子上都没有它' % name) # ---- 2 ---- -PADMODE = {'host/dm_cursor.c': 8, 'host/dm_custom.c': 2, 'host/dm_kills.c': 2, 'host/dm_rift_ui.c': 4, 'host/dm_runeword.c': 3, 'host/dm_vault_ui.c': 1, 'host/dm_update.c': 2, 'host/hle_tact.c': 1} +PADMODE = {'host/dm_cursor.c': 9, 'host/dm_custom.c': 2, 'host/dm_kills.c': 2, 'host/dm_rift_ui.c': 4, 'host/dm_runeword.c': 3, 'host/dm_vault_ui.c': 1, 'host/dm_update.c': 2, 'host/hle_tact.c': 1} AUTOKEY = {'host/dm_cursor.c': 38, 'host/dm_rift_ui.c': 6, 'host/hle_hid.c': 2, 'ios/Sources/front_ios.m': 4} def count(pat, skip_defs): out = {} diff --git a/dm/host/tests/t_rwlv.c b/dm/host/tests/t_rwlv.c new file mode 100644 index 0000000..bbfc936 --- /dev/null +++ b/dm/host/tests/t_rwlv.c @@ -0,0 +1,51 @@ +// 符文之语清单「需要等级」:找列与取最大值。期望值全部取自原版数据表手算(armor.txt / misc.txt 的 levelreq、runes.txt 的配方),不跑被测实现算。 +// 底材:塔盔 uhm 需求 59(物品等级 79)、翼盔 xhm 25(51)、权冠 ci3 64(85)、宝冠 urn 66(85)、武装盔 ulm 51(68)、头盔 hlm 0(11) +// 符文:塔尔 r07 17、书尔 r10 23、索尔 r12 27、沙伊 r13 29、艾欧 r16 35、蓝姆 r20 43、伊斯特 r24 51 +// "Required level" in the runeword list: finding the column and taking the maximum. All expected values are worked out by hand from the original data tables (levelreq in armor.txt / misc.txt, recipes in runes.txt), not by running the implementation under test. +// Bases: Spired Helm uhm requires 59 (item level 79), Winged Helm xhm 25 (51), Diadem ci3 64 (85), Corona urn 66 (85), Armet ulm 51 (68), Helm hlm 0 (11) +// Runes: Tal r07 17, Thul r10 23, Sol r12 27, Shael r13 29, Io r16 35, Lem r20 43, Ist r24 51 +#include "../dm_rwlv_core.h" +#include +#include +static int fails; +#define CHECK(c) do { if (!(c)) { printf("FAIL %s:%d %s\n", __FILE__, __LINE__, #c); fails++; } } while (0) +#define ROW 0x1c0 +static uint8_t tab[16][ROW]; static int nrow; +// 造一行:物品码在 +0x80,「物品等级」放在 lv_off,「需求等级」放在 req_off;其余字节填与等级无关的值 +// Build one row: item code at +0x80, "item level" at lv_off, "required level" at req_off; the remaining bytes are filled with values unrelated to levels +static void row(const char *code, uint8_t level, uint8_t req, int lv_off, int req_off) { uint8_t *r = tab[nrow++]; memset(r, 0xee, ROW); memset(r + 0x80, 0, 4); memcpy(r + 0x80, code, 3); r[lv_off] = level; r[req_off] = req; } +static void build(int lv_off, int req_off) { nrow = 0; memset(tab, 0, sizeof tab); + row("hlm", 11, 0, lv_off, req_off); row("xhm", 51, 25, lv_off, req_off); row("uhm", 79, 59, lv_off, req_off); row("ci3", 85, 64, lv_off, req_off); row("urn", 85, 66, lv_off, req_off); row("ulm", 68, 51, lv_off, req_off); + row("r05", 15, 15, lv_off, req_off); row("r07", 17, 17, lv_off, req_off); row("r13", 29, 29, lv_off, req_off); } +int main(void) { + // 一、找列:物品等级那一列排在需求等级前面(线上缺陷的现场:旧找法只看符文,先撞上物品等级)——必须返回需求等级那一列 + // Part one, finding the column: the item-level column comes before the required-level column (the scene of the reported defect: the old search looked only at runes and hit item level first) - the required-level column must be returned + build(0x57, 0x5b); CHECK(dm_rw_find_lvoff(&tab[0][0], (uint32_t)nrow, ROW) == 0x5b); + // 两列次序反过来也一样 + // The same with the two columns in the opposite order + build(0x5b, 0x57); CHECK(dm_rw_find_lvoff(&tab[0][0], (uint32_t)nrow, ROW) == 0x57); + // 找到的那一列读塔盔必须是 59,不是 79 + // The column found must read 59 for the Spired Helm, not 79 + build(0x57, 0x5b); { int o = dm_rw_find_lvoff(&tab[0][0], (uint32_t)nrow, ROW); CHECK(o >= 0 && tab[2][o] == 59); } + // 负对照:表里缺锚点物品(只剩符文)→ 找不到;需求等级那一列被改坏一行 → 找不到;空表 → 找不到 + // Negative controls: anchor items missing from the table (only runes left) -> not found; one row of the required-level column corrupted -> not found; empty table -> not found + build(0x57, 0x5b); CHECK(dm_rw_find_lvoff(&tab[6][0], 3, ROW) == -1); + build(0x57, 0x5b); tab[2][0x5b] = 60; CHECK(dm_rw_find_lvoff(&tab[0][0], (uint32_t)nrow, ROW) == -1); + CHECK(dm_rw_find_lvoff(NULL, 0, ROW) == -1); + // 二、需要等级 = max(底材需求, 各符文需求)。线上图里的四条(塔盔 3 孔): + // Part two: required level = max(base requirement, each rune's requirement). The four entries in the reported screenshot (3-socket Spired Helm): + { int hearth[] = {29, 35, 23}, cure[] = {29, 35, 17}, bulwark[] = {29, 35, 27}, delirium[] = {43, 51, 35}; + CHECK(dm_rw_need_level(59, hearth, 3) == 59); // 壁炉:夏 + 艾欧 + 书尔 | Hearth: Shael + Io + Thul + CHECK(dm_rw_need_level(59, cure, 3) == 59); // 解药:夏 + 艾欧 + 塔尔 | Cure: Shael + Io + Tal + CHECK(dm_rw_need_level(59, bulwark, 3) == 59); // 壁垒:夏 + 艾欧 + 索尔 | Bulwark: Shael + Io + Sol + CHECK(dm_rw_need_level(59, delirium, 3) == 59); // 迷狂:蓝姆 + 伊斯特 + 艾欧 | Delirium: Lem + Ist + Io + // 别的底材:符文盖过底材 / 底材盖过符文各两条 + // Other bases: two cases each of runes outweighing the base / the base outweighing the runes + CHECK(dm_rw_need_level(25, hearth, 3) == 35); // 壁炉做在翼盔(25)上:艾欧 35 | Hearth made in a Winged Helm (25): Io 35 + CHECK(dm_rw_need_level(25, delirium, 3) == 51); // 迷狂做在翼盔上:伊斯特 51 | Delirium made in a Winged Helm: Ist 51 + CHECK(dm_rw_need_level(66, delirium, 3) == 66); // 迷狂做在宝冠(66)上:底材 66 | Delirium made in a Corona (66): base 66 + CHECK(dm_rw_need_level(64, cure, 3) == 64); } // 解药做在权冠(64)上:底材 64 | Cure made in a Diadem (64): base 64 + CHECK(dm_rw_need_level(0, NULL, 0) == 0); + if (fails) { printf("t_rwlv: %d 处失败\n", fails); return 1; } + printf("t_rwlv OK\n"); return 0; +} diff --git a/dm/host/tests/t_touch_mac.c b/dm/host/tests/t_touch_mac.c index b3e410b..737fd29 100644 --- a/dm/host/tests/t_touch_mac.c +++ b/dm/host/tests/t_touch_mac.c @@ -10,7 +10,7 @@ uint64_t guest_ns(void) { return 0; } uint64_t dm_guest_frame(void) { return 0; } // 界面鼠标 / 前端路径按出图帧节拍走;本单测不测它们 | the UI mouse / front-end paths run on the presented-frame cadence; this unit test does not test them int dm_world_has_target(void) { return 1; } // 点世界(dm_world.c)的桩:有目标 = 主按钮照常发键 | stub for world tapping (dm_world.c): has a target = the primary button sends its key as usual unsigned dm_world_tap(float nx, float ny) { (void)nx; (void)ny; return 0; } -uint64_t dm_padmode_legend_click(float nx, float ny) { (void)nx; (void)ny; return 0; } +uint64_t dm_padmode_legend_click(float nx, float ny) { (void)nx; (void)ny; return 0; } int dm_padmode_hud_click(float nx, float ny, uint64_t *b) { (void)nx; (void)ny; (void)b; return 0; } int dm_padmode_legend_has(uint32_t g) { (void)g; return 0; } int dm_game_paused(void) { return 0; } int dm_shop_open(void) { return 0; } // 商人页(dm_actions.c)的桩:没开 | stub for the vendor page (dm_actions.c): not open int dm_padmode_current(void) { return 0; } // 手柄 / 触屏模式(dm_padmode.c)的桩:触屏 | Stub for controller / touch mode (dm_padmode.c): touch uint64_t dm_padmode_page_keys(uint64_t m) { (void)m; return 0; } void dm_padmode_legend_hide(const char *l, int a) { (void)l; (void)a; } int dm_padmode_busy(void) { return 0; } uint64_t dm_padmode_page_held(void) { return 0; } void dm_padmode_page_pulse(uint64_t m) { (void)m; } void dm_padmode_ident_hint(int on) { (void)on; } void dm_padmode_legend(int a, const char *t) { (void)a; (void)t; } const char *dm_str(uint8_t *b, const char *k) { (void)b; return k; } // 手柄页键 / 提示条 / 取串的桩(个人仓库手柄翻页用,触屏下不走) | Stubs for controller page keys / button legend / string fetch (used by controller paging of the personal stash, not reached under touch) diff --git a/dm/host/tests/t_touch_tick_stub.c b/dm/host/tests/t_touch_tick_stub.c index 3e9fd5d..07fe582 100644 --- a/dm/host/tests/t_touch_tick_stub.c +++ b/dm/host/tests/t_touch_tick_stub.c @@ -90,4 +90,4 @@ int dm_runeword_long_press(const void *ci) { (void)ci; return 0; } // 符文 int dm_runeword_list_open(void) { return 0; } void dm_runeword_button(const char *name) { (void)name; } void dm_runeword_list_close(void) {} -uint64_t dm_padmode_legend_click(float nx, float ny) { (void)nx; (void)ny; return 0; } // 鼠标点按键提示条(dm_padmode.c):这些单测不带游戏映像,给空桩 | mouse click on the key-hint bar (dm_padmode.c): these unit tests carry no game image, so an empty stub is given +uint64_t dm_padmode_legend_click(float nx, float ny) { (void)nx; (void)ny; return 0; } int dm_padmode_hud_click(float nx, float ny, uint64_t *b) { (void)nx; (void)ny; (void)b; return 0; } int dm_padmode_legend_has(uint32_t g) { (void)g; return 0; } int dm_game_paused(void) { return 0; } // 鼠标点按键提示条(dm_padmode.c):这些单测不带游戏映像,给空桩 | mouse click on the key-hint bar (dm_padmode.c): these unit tests carry no game image, so an empty stub is given diff --git a/dm/host/touch_mac.c b/dm/host/touch_mac.c index de0643e..5427225 100644 --- a/dm/host/touch_mac.c +++ b/dm/host/touch_mac.c @@ -161,17 +161,38 @@ void dm_touch_host_game_start(uint64_t now) { void dm_touch_host_step(uint64_t now, uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry) { if (!g_touch.ready) touch_init(now); + if (g_live_on) { // Mac 键盘的回车与 Esc(front_mac.m 用两个游戏不认的高位送来):按下那一刻按当前页定成哪个手柄键,按住期间不变 | Return and Esc on a Mac keyboard (sent by front_mac.m as two high bits the game does not recognise): decided as a gamepad key by the current page at the moment of pressing, unchanged while held + static uint64_t ent, esc; int dm_padmode_legend_has(uint32_t glyph), dm_game_paused(void), dm_uiscreen_ingame(void); uint64_t kb = *buttons; *buttons &= ~((1ull << 40) | (1ull << 41)); + // 回车:缺省 = 确认(A)——提示条写的是手柄字母,拿键盘的人按回车是想确认;当前页的提示条里有「+」这一条时 = +(起名页的「创建」等;主菜单除外,见 dm_padmode_legend_has) + // 起名页另有一条:名字还没填时回车 = 输入名称(A),填过之后才是接受(+)——「回车弹框 → 打字 → 回车 → 回车创建」 + // Return: default = confirm (A) - the hint bar shows gamepad letters, and someone with a keyboard presses Return to confirm; when the current page's hint bar has a "+" entry = + ("Create" on the naming page and so on; except the main menu, see dm_padmode_legend_has) + // The naming page has one more rule: before a name is filled in Return = Enter Name (A), and only afterwards is it Accept (+) - "Return opens the dialog -> type -> Return -> Return creates" + if (!(kb & (1ull << 40))) ent = 0; else if (!ent) { int dm_ui_fe_name_wants_input(void); ent = !dm_ui_fe_name_wants_input() && dm_padmode_legend_has(0xe005) ? DM_BTN_PLUS : DM_BTN_A; } + // Esc:返回(B);局内没有面板开着、游戏也没停着时 = 开功能页(+)——那时 B 是一格技能 + // Esc: back (B); with no panel open in game and the game not stopped = open the function page (+) - B is a skill slot then + if (!(kb & (1ull << 41))) esc = 0; else if (!esc) esc = dm_uiscreen_ingame() && !g_touch.state.navigation_mode && !dm_game_paused() ? DM_BTN_PLUS : DM_BTN_B; + *buttons |= ent | esc; } if (g_live_on) { // 真鼠标:前端页直通界面点击;局内并进事件表(拍 = 此刻),与脚本事件同一段处理 | Real mouse: on front-end pages it goes straight to a UI click; in game it joins the event table (tick = now) and is handled in the same pass as script events int dm_uiscreen_ingame(void); int in = dm_uiscreen_ingame(); static float px, py; unsigned h; if (in && !g_live_based) { g_live_based = 1; g_live_tick0 = touch_cur_tick(); if (!g_touch.based) { g_touch.started = 1; g_touch.based = 1; g_touch.loaded = 1; g_touch.tick_set = 1; g_touch.start_tick = g_live_tick0; g_touch.to_game_tick = g_live_tick0; } } if (!in) g_live_based = 0; while ((h = atomic_load(&g_live.head)) != atomic_load(&g_live.tail)) { int op = g_live.q[h % 64].op; float nx = g_live.q[h % 64].nx, ny = g_live.q[h % 64].ny; if (op != 2) { px = nx; py = ny; } - // 按在按键提示条的某一条上:这一下不当点击,改成按那个键 4 拍(dm_padmode.c);吞到抬起为止 - // Pressed on an entry of the key-hint bar: this is not treated as a click but as pressing that key for 4 ticks (dm_padmode.c); swallowed until release - { uint64_t dm_padmode_legend_click(float, float); static int eat; uint64_t lb = op == 0 ? dm_padmode_legend_click(px, py) : 0; - if (lb) { eat = 1; g_live_btn = lb; g_live_btn_until = touch_cur_tick() + 4; } - if (eat) { if (op == 2) eat = 0; atomic_store(&g_live.head, h + 1); continue; } } + // 按在按键提示条的某一条上:这一下不当点击,改成按那个键 4 拍(dm_padmode.c);按在局内底部 HUD 的技能格 / 腰带格 / 钮上:按住期间按着对应的键,抬起再放(至少 3 拍); + // HUD 上没有对应键的东西(血球、魔球、经验条):吃掉。都吞到抬起为止 + // Pressed on an entry of the key-hint bar: this is not treated as a click but as pressing that key for 4 ticks (dm_padmode.c); pressed on a skill slot / belt cell / button of the in-game bottom HUD: the corresponding key is held while the mouse is down and released on mouse up (at least 3 ticks); + // things on the HUD with no corresponding key (life orb, mana orb, experience bar): swallowed. All are swallowed until release + { uint64_t dm_padmode_legend_click(float, float); int dm_padmode_hud_click(float, float, uint64_t *); static int eat, hold; uint64_t lb = op == 0 ? dm_padmode_legend_click(px, py) : 0, hb = 0; int hk = op == 0 && !lb && in && !g_touch.state.navigation_mode ? dm_padmode_hud_click(px, py, &hb) : 0; /* 有面板开着:不认 HUD(面板底下那排 HUD 还画着) | a panel is open: the HUD is not recognised (the HUD row under the panel is still drawn) */ + if (lb) { eat = 1; hold = 0; g_live_btn = lb; g_live_btn_until = touch_cur_tick() + 4; } + else if (hk == 1) { eat = 1; hold = 1; g_live_btn = hb; g_live_btn_until = touch_cur_tick() + 30 * 600; } + else if (hk == 2) { eat = 1; hold = 0; } + // 右上角小地图(同 iOS 壳):点它顶上区域名那一条(矩形高的 1/4)= 切到全屏地图;全屏地图开着时点 HUD 以外的任何地方 = 回到小地图。只在没有面板开着时认 + // Top-right minimap (same as the iOS shell): clicking the area-name strip at its top (1/4 of the rectangle's height) = switch to the full-screen map; with the full-screen map open, clicking anywhere outside the HUD = back to the minimap. Recognised only when no panel is open + else if (op == 0 && in && !g_touch.state.navigation_mode) { int dm_ui_minimap_rect(float r[4]), dm_ui_map_is_full(void); void dm_ui_map_full(int on); float mr[4]; + if (dm_ui_map_is_full()) { dm_ui_map_full(0); eat = 1; hold = 0; fprintf(stderr, "[dm] 鼠标:全屏地图开着,点一下 → 回到小地图\n"); } + else if (dm_ui_minimap_rect(mr)) { float band = (mr[3] - mr[1]) / 4; if (band < 0.042f) band = 0.042f; if (band > (mr[3] - mr[1]) * 0.4f) band = (mr[3] - mr[1]) * 0.4f; + if (px >= mr[0] && px <= mr[2] && py >= mr[1] && py <= mr[1] + band) { dm_ui_map_full(1); eat = 1; hold = 0; fprintf(stderr, "[dm] 鼠标:点在小地图顶上那一条 → 切到全屏地图\n"); } } } + if (eat) { if (op == 2) { eat = 0; if (hold) { hold = 0; g_live_btn_until = touch_cur_tick() + 3; } } atomic_store(&g_live.head, h + 1); continue; } } if (!in) { // 前端页:抬起时先问一次命中——落在页签上就走「点页签 = 按对应的手柄键」(页签不认鼠标点击;局内由手势层做同一件事),其余照旧发鼠标点击 | front-end pages: on release, hit-test once first - landing on a tab goes through "clicking a tab = pressing the corresponding gamepad key" (tabs do not take mouse clicks; in game the gesture layer does the same), everything else sends a mouse click as before if (op == 2 && dm_ui_item_at_now(px, py) == 2) { dm_ui_touch(3, px, py); dm_ui_tab_go(); } else dm_ui_touch(op, px, py); atomic_store(&g_live.head, h + 1); continue; } diff --git a/dm/i18n/ui_text.tsv b/dm/i18n/ui_text.tsv index 37ba95e..e5c2aa7 100644 --- a/dm/i18n/ui_text.tsv +++ b/dm/i18n/ui_text.tsv @@ -150,8 +150,8 @@ dmOldNoSupportPkg 本包不带老机型支持(缺 romfs_overlay_astc/pack.json dmOldPackSize 「%s」里的补充包大小不对(%.2f / %.2f GB),像是没拷完 The pack in "%s" has the wrong size (%.2f / %.2f GB); the copy looks incomplete 老机型补充包:没用上的原因 dmOldPackBad 「%s」里的补充包内容不对(和这个版本不配套,或拷坏了),请重新下载 The pack in "%s" does not match this version or is corrupted; please download it again 老机型补充包:没用上的原因 dmOldPackNone 没找到老机型补充包 Supplementary pack for older devices not found 老机型补充包:没用上的原因 -dmOldUnsupTitle 暂不支持本机型 Device Not Supported 老机型弹框标题(本包不带老机型支持时) -dmOldUnsupMsg 本机型(iPhone 14 及更早,A16 及以前芯片)暂不支持:显卡不支持游戏素材格式。iPhone 15 Pro 及以后可以玩。 This device (iPhone 14 or earlier, A16 chip or older) is not supported yet: its GPU cannot read the game's texture format. iPhone 15 Pro and later can run the game. 老机型弹框正文 +dmOldUnsupTitle 这台设备要多做一步 One More Step for This Device 老机型弹框标题(本包不带老机型支持时) +dmOldUnsupMsg 本机型(A16 及更早的芯片,如 iPhone 14 系列、iPhone 15 / 15 Plus)可以玩,但要多做一份「Legacy Device Pack」,并在做安装包时带上它——这个安装包没有带。\n\n怎么做:打开 github.com/jhaizhou-ops/d2r-mobile,照 docs/LEGACY_DEVICES 说明做好补充包,带着它重新做一次安装包,再装到手机上。 This device (A16 chip or older, such as the iPhone 14 family and iPhone 15 / 15 Plus) can run the game, but it needs a supplementary pack for older devices, and the install package has to be made with it - this one was not.\n\nWhat to do: open github.com/jhaizhou-ops/d2r-mobile, follow docs/LEGACY_DEVICES to make the pack, make the install package again with it, then install it on the phone. 老机型弹框正文 dmOldNeedTitle 需要老机型补充包 Supplementary Pack Required 老机型弹框标题 dmOldNeedMsg 本机型需要老机型补充包(约 %.1f GB)。\n在「文件」里把「Legacy Device Pack」文件夹整个拷到「我的 iPhone → D2R Mobile」,再打开D2R Mobile。%@ This device needs the supplementary pack for older devices (about %.1f GB).\nIn the Files app, copy the whole "Legacy Device Pack" folder into "On My iPhone → D2R Mobile", then open D2R Mobile again.%@ 老机型弹框正文(%@ = 没用上的原因,可空) dmOldWhySuffix \n(%s) \n(%s) 老机型弹框正文末尾的原因 @@ -315,4 +315,4 @@ dmAppMenuView 显示 View Mac App 菜单栏(host/front_mac.m,下同) dmAppFullscreen 全屏 Toggle Full Screen 显示菜单的全屏项 dmAppMenuHelp 帮助 Help 帮助菜单 dmAppKeysTitle 键盘与手柄按键对照 Keyboard and Controller Buttons 帮助菜单的键位对照项,也是那一页的标题 -dmAppKeysText 界面上的按键提示是手柄字母,键盘这样对应:\n\n移动:W A S D(左摇杆)\n十字键:方向键\nA 确认:J  B 返回:K  X:U  Y:I\nL:Q  R:E  ZL:Z  ZR:C\n按左摇杆:F  按右摇杆:G\n+(菜单):回车  −(地图):Tab\n\n鼠标:左键点目标或界面,右键 = B,滚轮滚列表。\n接上手柄可以直接用。这一页以后在「帮助」菜单里。 On-screen button hints use controller letters. Keyboard mapping:\n\nMove: W A S D (left stick)\nD-pad: arrow keys\nA confirm: J B back: K X: U Y: I\nL: Q R: E ZL: Z ZR: C\nPress left stick: F Press right stick: G\n+ (menu): Return − (map): Tab\n\nMouse: left click a target or the interface, right click = B, wheel scrolls lists.\nA connected controller works right away. This page stays in the Help menu. 键位对照正文(首次启动弹一次) +dmAppKeysText 界面上的按键提示是手柄字母,键盘这样对应:\n\n确认(A):空格 或 J  返回(B):Esc 或 K\n回车:确认;页面底部有「+」提示时是 +(如起名后的「接受」)\n+(菜单 / 新角色):= 键  −(地图):Tab\n移动:W A S D(左摇杆)  十字键:方向键\nX:U  Y:I  L:Q  R:E  ZL:Z  ZR:C\n按左摇杆:F  按右摇杆:G\n\n鼠标:左键点目标、界面、底部的按键提示和技能 / 药水格;右键 = 返回;滚轮滚列表。\n接上手柄可以直接用。这一页以后在「帮助」菜单里。 On-screen button hints use controller letters. Keyboard mapping:\n\nConfirm (A): Space or J Back (B): Esc or K\nReturn: confirm; acts as + when the page shows a + hint (e.g. Accept after naming)\n+ (menu / new character): = key − (map): Tab\nMove: W A S D (left stick) D-pad: arrow keys\nX: U Y: I L: Q R: E ZL: Z ZR: C\nPress left stick: F Press right stick: G\n\nMouse: left click targets, the interface, the button hints at the bottom and skill / potion slots; right click = back; wheel scrolls lists.\nA connected controller works right away. This page stays in the Help menu. 键位对照正文(首次启动弹一次) diff --git a/dm/ios/Sources/cloud_ios.m b/dm/ios/Sources/cloud_ios.m index 7f4417a..0014944 100644 --- a/dm/ios/Sources/cloud_ios.m +++ b/dm/ios/Sources/cloud_ios.m @@ -4,16 +4,23 @@ // 只同步玩家真实存档 Documents/save;测试存档(save.test 等)缺省不同步。测试开关 DM_TEST_ICLOUD_SUB=<子目录名>:测试存档也同步,云端用容器里的这个子目录(与真实存档的 saves 隔开,不会把测试角色传到玩家设备上)。 // 测试开关 DM_TEST_ICLOUD_DIR=<本地目录>:用本地目录当云端(不碰 iCloud),测试存档也同步。不以 / 开头的路径拼到 App 的 Documents 下(下同)。 // 测试开关 DM_TEST_ICLOUD_ROOT=<本地目录>:用本地目录当 iCloud 容器的 Documents(下有 saves / saves_v2),验目录换代与一次性迁移;测试存档也同步。 +// Mac 原生 App(宿主 app_mac.m 包成的那个)也编这个文件,同一个容器、同一套规则:真实存档 = 应用支持目录下的 save(启动代码设 DM_CLOUD_REAL=1; +// 带 DM_APP_SUPPORT 起的测试局不设,一律当测试存档、不同步);没有「切后台」,改成退出 App 前传一次并等它传完(dm_cloud_flush_wait)。 // 开关:「自定义」页 icloud(缺省开)。没登录 iCloud / 本 App 的 iCloud 被关:取不到容器,整套跳过,日志记一行。 -// iOS side of iCloud save sync: get the iCloud container directory, let the cloud packages download first, then call the shared core dm_cloud_sync (dm/host/dm_cloudsync.c). -// Startup: dm_cloud_boot is called in boot_thread before dm_main mounts the save; waits at most 5 seconds, pulls each cloud package and swaps it into the local save under "later write overwrites earlier write"; after that the game reads the save list as usual. -// While running: each time a save commit succeeds (Commit in hle_fs.c), the commit hook first clonefiles the committed directory into a snapshot (copy-on-write, nearly free); in a run it is only marked pending, and on leaving the run / going to background the snapshot is compared with the cloud on a serial queue, upload only (allow_down = 0); commits outside a run are uploaded on the spot. -// Only the player's real save Documents/save is synced; test saves (save.test etc.) are not synced by default. Test switch DM_TEST_ICLOUD_SUB=: test saves are synced too, and the cloud uses this subdirectory of the container (kept apart from the real save's saves, so test characters are not uploaded to the player's devices). -// Test switch DM_TEST_ICLOUD_DIR=: use a local directory as the cloud (iCloud untouched); test saves are synced too. Paths not starting with / are joined under the App's Documents (same below). -// Test switch DM_TEST_ICLOUD_ROOT=: use a local directory as the iCloud container's Documents (containing saves / saves_v2), to verify the directory generation change and the one-time migration; test saves are synced too. -// Switch: icloud on the 「自定义」(Custom) page (on by default). Not signed in to iCloud / iCloud turned off for this App: the container cannot be obtained, the whole thing is skipped and one log line is written. +// The iOS side of iCloud save sync: obtain the iCloud container directory, let the cloud packages download first, then call the shared core dm_cloud_sync (dm/host/dm_cloudsync.c). +// Startup: dm_cloud_boot is called in boot_thread, before dm_main mounts the save; it waits at most 5 seconds, pulls each cloud package and swaps it into the local save by "last write wins", after which the game reads the save list as usual. +// While running: every time a save commit succeeds (Commit in hle_fs.c), the commit hook first clonefiles the committed directory into a snapshot (copy-on-write, nearly free); in game it is only marked as pending, and on leaving the game / going to the background the snapshot is compared with the cloud on a serial queue and only uploaded (allow_down = 0); commits outside a game are uploaded on the spot. +// Only the player's real save Documents/save is synced; test saves (save.test and so on) are not synced by default. Test switch DM_TEST_ICLOUD_SUB=: test saves are synced as well, using this subdirectory of the container in the cloud (separate from the saves of the real save, so test characters are not sent to the player's devices). +// Test switch DM_TEST_ICLOUD_DIR=: use a local directory as the cloud (iCloud is not touched); test saves are synced as well. A path not starting with / is joined under the App's Documents (same below). +// Test switch DM_TEST_ICLOUD_ROOT=: use a local directory as the Documents of the iCloud container (with saves / saves_v2 under it), to verify the directory generation change and the one-time migration; test saves are synced as well. +// The native Mac App (the one the host's app_mac.m is wrapped into) compiles this file too, with the same container and the same rules: the real save = save under the application support directory (the startup code sets DM_CLOUD_REAL=1; +// test runs launched with DM_APP_SUPPORT do not set it and are always treated as test saves, not synced); there is no "going to the background", so it uploads once before quitting the App and waits for it to finish (dm_cloud_flush_wait). +// Switch: icloud on the Custom page (on by default). Not signed in to iCloud / iCloud turned off for this App: the container cannot be obtained, the whole thing is skipped, and one line is logged. #import +#include +#if TARGET_OS_IPHONE #import +#endif #include #include #include @@ -87,15 +94,28 @@ static void on_commit(const char *commit_dir) { void dm_cloud_flush(int background) { if (!g_q) return; // 没开同步(测试存档 / 没登录 iCloud / 自定义页关了) | Sync not enabled (test save / not signed in to iCloud / turned off on the Custom page) if (background) atomic_store(&g_bg, 1); +#if TARGET_OS_IPHONE __block UIBackgroundTaskIdentifier tk = UIBackgroundTaskInvalid; if (background) tk = [UIApplication.sharedApplication beginBackgroundTaskWithName:@"dm.cloud" expirationHandler:^{ LOG("【红】iCloud 同步:后台收尾时间到,系统叫停(没传完的下次启动补传)"); [UIApplication.sharedApplication endBackgroundTask:tk]; tk = UIBackgroundTaskInvalid; }]; +#endif dispatch_async(g_q, ^{ NSString *p = g_pend; g_pend = nil; if (p) upload_snap(p, background ? "切到后台," : "退出这一局回到前端,"); else LOG("iCloud 同步:%s,局内没有待传的存档", background ? "切到后台" : "退出这一局回到前端"); +#if TARGET_OS_IPHONE if (tk != UIBackgroundTaskInvalid) dispatch_async(dispatch_get_main_queue(), ^{ if (tk != UIBackgroundTaskInvalid) { [UIApplication.sharedApplication endBackgroundTask:tk]; tk = UIBackgroundTaskInvalid; } }); +#endif }); } +// 退出 App 前(Mac):把局内攒下的最新一份传掉,并等队列里的活做完,最多 sec 秒。返回 1 = 做完了(或本来就没开同步),0 = 到点还没完 +// Before quitting the App (Mac): upload the latest copy accumulated during the game and wait for the queued work to finish, at most sec seconds. Returns 1 = done (or sync was not on in the first place), 0 = not finished in time +int dm_cloud_flush_wait(double sec) { + if (!g_q) return 1; + dispatch_semaphore_t done = dispatch_semaphore_create(0); + dispatch_async(g_q, ^{ NSString *p = g_pend; g_pend = nil; if (p) upload_snap(p, "退出 App 前,"); else LOG("iCloud 同步:退出 App 前,没有待传的存档"); dispatch_semaphore_signal(done); }); + if (dispatch_semaphore_wait(done, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(sec * NSEC_PER_SEC)))) { LOG("【红】iCloud 同步:退出 App 前 %.0f 秒没传完(没传完的下次启动补传)", sec); return 0; } + return 1; +} void dm_cloud_foreground(void) { atomic_store(&g_bg, 0); } static void cloud_ingame(int on) { if (on) atomic_store(&g_session, 1); } static void cloud_charsel(void) { if (atomic_exchange(&g_session, 0)) dm_cloud_flush(0); } // 退出这一局回到前端(主菜单 / 选角页):这一局结束 | Left this run back to the front end (main menu / character select page): this run has ended @@ -126,7 +146,11 @@ static NSURL *container(double limit) { // 取 iCloud 容器:要在主线程 // (later, deleting a character removes packages, so we cannot keep blocking on the manifest forever). Returns 0 = skip sync this time static NSString *test_path(const char *e) { // 测试开关里的路径:不以 / 开头的拼到 App 的 Documents 下(真机容器路径每次装包都变) | Paths in test switches: those not starting with / are joined under the App's Documents (the real-device container path changes on every install) if (!e) return nil; if (e[0] == '/') return @(e); +#if TARGET_OS_OSX + return [@(getenv("DM_SAVE") ?: ".").stringByDeletingLastPathComponent stringByAppendingPathComponent:@(e)]; // Mac:拼到存档目录的上一级(应用支持目录) | Mac: joined to the parent of the save directory (the application support directory) +#else return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@(e)]; +#endif } static int v2_ready(NSString *nw, NSString *okf) { // 迁移过来的整套是否都到了本机 | Whether the whole migrated set has arrived on this device NSFileManager *fm = NSFileManager.defaultManager; if ([fm fileExistsAtPath:okf]) return 1; @@ -167,8 +191,15 @@ 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; NSString *save = @(sv); int real = [save.stringByStandardizingPath isEqualToString:[doc stringByAppendingPathComponent:@"save"].stringByStandardizingPath]; +#if TARGET_OS_OSX + real = getenv("DM_CLOUD_REAL") != NULL; (void)doc; // Mac:真实存档由启动代码认(app_mac.m:没带 DM_APP_SUPPORT 的那种起法) | Mac: the real save is recognised by the startup code (app_mac.m: the way of launching without DM_APP_SUPPORT) +#endif int off = getenv("DM_TEST_ICLOUD_OFF") != NULL; // 测试总闸:脚本起的局一律带它(tools/cloud_guard.sh),整局不同步 | Test master gate: runs launched by scripts always carry it (tools/cloud_guard.sh), and the whole run does not sync - if (!real && !sub && !ldir && !lroot) { if (off) LOG("iCloud 同步:测试开关 DM_TEST_ICLOUD_OFF,本局不同步"); return; } // 测试存档:不同步 | Test save: not synced + if (!real && !sub && !ldir && !lroot) { if (off) LOG("iCloud 同步:测试开关 DM_TEST_ICLOUD_OFF,本局不同步"); // 测试存档:不同步 | Test save: not synced +#if TARGET_OS_OSX + else LOG("iCloud 同步:测试用的存档目录(DM_APP_SUPPORT),本局不同步"); +#endif + return; } // Mac 上跑的 iOS 包:缺省整个不连真实 iCloud。这个包只发 iPhone / iPad,Mac 上跑的全是开发与测试;开发机登着真实账号时, // 它就是那个账号的又一台设备,任何脚本、手点图标都会和真实云端双向同步(出过把测试存档传进真实云端)。本地测试云端(DIR / ROOT)不受影响; // 真要在 Mac 上连真实云端:同时给 DM_REAL_ICLOUD=1 与 DM_REAL_ICLOUD_CONFIRM=写入真实云端。真机不走这一支。 @@ -193,9 +224,10 @@ void dm_cloud_boot(void) { g_q = dispatch_queue_create("dm.cloud", DISPATCH_QUEUE_SERIAL); for (NSString *f in [NSFileManager.defaultManager contentsOfDirectoryAtPath:save.stringByDeletingLastPathComponent error:nil] ?: @[]) // 上次被杀时没删掉的提交快照 | Commit snapshots not deleted when we were last killed if ([f hasPrefix:[save.lastPathComponent stringByAppendingString:@".cloudsnap"]]) [NSFileManager.defaultManager removeItemAtPath:[save.stringByDeletingLastPathComponent stringByAppendingPathComponent:f] error:nil]; - int pend = pending_downloads(1); + double t1 = CFAbsoluteTimeGetCurrent(); int pend = pending_downloads(1); while (pend && CFAbsoluteTimeGetCurrent() - t0 < limit) { usleep(100000); pend = pending_downloads(0); } - int n = run_sync(save, 1); + double t2 = CFAbsoluteTimeGetCurrent(); int n = run_sync(save, 1); + LOG("iCloud 同步:启动分段 取容器与查齐 %.0f ms、等下载 %.0f ms、文件协调与同步 %.0f ms", (t1 - t0) * 1000, (t2 - t1) * 1000, (CFAbsoluteTimeGetCurrent() - t2) * 1000); LOG("iCloud 同步:启动 %.0f ms,动作 %d 个%s(云端目录 %s)", (CFAbsoluteTimeGetCurrent() - t0) * 1000, n, pend ? [NSString stringWithFormat:@",%d 个包没等到下载完、本次跳过", pend].UTF8String : "", ldir ? "本地测试目录" : sub ? sub : "saves_v2"); g_dm_save_commit_hook = on_commit; { extern void (*g_dm_ingame_hook)(int); extern void (*g_dm_charsel_hook)(void); g_dm_ingame_hook = cloud_ingame; g_dm_charsel_hook = cloud_charsel; } // 进局记一局开始;回到前端 = 这一局结束,传一次 | Entering a run marks the start of a run; returning to the front end = this run has ended, upload once diff --git a/dm/ios/Sources/dm_touch_controls.c b/dm/ios/Sources/dm_touch_controls.c index a488f2a..acf7171 100644 --- a/dm/ios/Sources/dm_touch_controls.c +++ b/dm/ios/Sources/dm_touch_controls.c @@ -76,9 +76,19 @@ void dm_tc_layout_make(dm_tc_layout *l, float width, float height) { { float sx = main_x-112*k, bar_r = l->width/2+(2015-1434)*u+8*k+22*k; /* 右雕像翼尖:七格时 2075,六格石条右端收进 60 | Right statue wing tip: 2075 with seven cells; with six cells the right end of the stone bar is pulled in by 60 */ if (sx < bar_r) sx = bar_r; l->swap = (dm_tc_target){sx, main_y+52*k, 22*k, 0}; } /* 底栏外侧是血 / 蓝球;球不是输入目标。 | Outside the bottom bar are the life / mana orbs; the orbs are not input targets. */ - l->joy_x = fmaxf(90*k, g_safe_l + 60*k); /* 摇杆底盘(半径 60)左沿不越过安全区左界 | The left edge of the stick base (radius 60) does not cross the left boundary of the safe area */ - l->joy_y = l->height - 100*k; + /* 左摇杆是浮动底盘:左下「起摇杆区」里手指落在哪,底盘圆心就落在哪,松手回静止位。 + 静止位:圆心离安全区左界 90(底盘半径 60 + 30)、不小于 120,离屏幕底 115——只是没按时画在哪。 + 起摇杆区:屏宽的左 40% × 屏高的下 55%(左与下到屏幕边:拇指压在刘海那一条上也算);区里我们的圆钮 / 腰带格、原版界面上可点的东西各自优先。 + 夹回:落点贴边时圆心挪回来,整个底盘留在安全区左界以右、底盘下沿离屏幕底不少于 25(不撞系统横条) + The left stick is a floating base: wherever the finger lands inside the bottom-left "stick-start zone", the base centre goes there, and it returns to the rest position on release. + Rest position: centre 90 from the left edge of the safe area (base radius 60 + 30), not less than 120, and 115 from the bottom of the screen - only where it is drawn while not pressed. + Stick-start zone: the left 40% of the screen width x the lower 55% of the screen height (reaching the screen edges on the left and bottom: a thumb on the notch strip counts too); inside the zone our round buttons / belt cells and the clickable things of the original UI each take priority. + Clamping: when the touch point is near an edge the centre is moved back so that the whole base stays to the right of the safe area's left edge and its lower rim is at least 25 from the bottom of the screen (clear of the system bar) */ l->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; } int dm_tc_hit(const dm_tc_layout *l, float x, float y) { @@ -378,7 +388,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; } /* 系统取消了摇杆那根手指:记下,紧接着在附近重新落下的接着当摇杆 | 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; } /* 系统取消了摇杆那根手指:记下,紧接着在附近重新落下的接着当摇杆 | 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; @@ -492,23 +502,24 @@ void dm_tc_begin_at(dm_tc_state *s, int slot, float x, float y, double now_s) { if (!s->mouse_click_mode) { s->pointer_valid = 1; s->pointer_x = x; s->pointer_y = y; } } else if (!s->navigation_mode && hit == DM_TC_NONE && g_edge_b > 0 && x >= 0 && x < s->layout.width*0.43f && y > s->layout.height - g_edge_b) { f->target = DM_TC_EDGE; - } 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.width*0.43f && y > s->layout.height*0.25f && - (hypotf(x - s->layout.joy_x, y - s->layout.joy_y) <= DM_TC_JOY_GRAB_K * s->layout.joy_radius || - (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_JOY_GRAB_K 倍半径内)才起摇杆,方向与幅度按「手指相对底座中心」算, - 按住后拖到多远都照样识别;落在左侧别处不起摇杆(照旧是点地)。原先是浮动摇杆:落在左侧区域哪里,底座就出在哪里、松手回原位。 - 例外:摇杆那根手指刚被系统取消(通知横幅、系统手势;dm_tc_cancel_finger 记下时刻与位置),DM_TC_JOY_RESUME_S 内在原处附近重新落下的手指接着当摇杆—— - 拖远了的摇杆被系统打断一下不该就此断掉;浮动摇杆时这种情形表现为底座追着手指重起 - The joystick base is fixed at its home position in the lower left: the joystick starts only when a finger lands near the base (within DM_TC_JOY_GRAB_K × radius), and direction and magnitude are computed as "finger relative to the base center"; - once held it is still recognized however far it is dragged; landing elsewhere on the left does not start the joystick (it is a ground tap as before). Previously it was a floating joystick: wherever in the left area the finger landed, the base appeared there, returning to its home position on release. - Exception: when the joystick finger has just been cancelled by the system (notification banner, system gesture; dm_tc_cancel_finger records the time and position), a finger landing again near the same spot within DM_TC_JOY_RESUME_S continues as the joystick -- - a joystick dragged far away should not be cut off for good by a brief system interruption; with the floating joystick this case showed up as the base restarting under the finger */ + } 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; + 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 */ + 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; s->joy_slot = slot; - s->joy_origin_x = s->layout.joy_x; - s->joy_origin_y = s->layout.joy_y; + /* 接续的沿用取消前的圆心,不按新落点重定:触摸被系统反复打断又重来的机器上,每重来一次底盘就跳到手指当前位置,看着像底盘追着手指跑 | 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); } update(s); } @@ -625,7 +636,7 @@ void dm_tc_end_at(dm_tc_state *s, int slot, double now_s) { else if (s->belt_rows > 1 && up < -th) s->belt_request = 2; else if (fabsf(dx) <= th && fabsf(up) <= th) belt_fire(s, 0x10 | (done.target - DM_TC_BELT1)); } - if (done.active && !s->navigation_mode && done.target == DM_TC_NONE && now_s - done.start_time_s < DM_TC_POINTER_TAP_S && /* 落在摇杆底座上的那一下是摇杆(一按就有方向),不再兼作点地 | the tap that lands on the joystick base is the joystick (direction as soon as pressed) and no longer doubles as a ground tap */ + if (done.active && !s->navigation_mode && (done.target == DM_TC_NONE || done.target == DM_TC_JOYSTICK) && now_s - done.start_time_s < DM_TC_POINTER_TAP_S && /* 起摇杆区里很快原地松开的那一下兼作点击 | a quick release in place inside the stick-start zone doubles as a tap */ hypotf(done.x - done.aim_origin_x, done.y - done.aim_origin_y) <= DM_TC_POINTER_MOVE_PT * scale_for(&s->layout)) { s->world_tap_x = done.aim_origin_x; s->world_tap_y = done.aim_origin_y; ++s->world_tap_seq; /* 点游戏世界 | Tap the game world */ } diff --git a/dm/ios/Sources/dm_touch_controls.h b/dm/ios/Sources/dm_touch_controls.h index 3196477..e500634 100644 --- a/dm/ios/Sources/dm_touch_controls.h +++ b/dm/ios/Sources/dm_touch_controls.h @@ -18,7 +18,8 @@ typedef struct { float x, y, r; uint64_t button; } dm_tc_target; typedef struct { float width, height; dm_tc_target target[DM_TC_COUNT]; - float joy_x, joy_y, joy_radius; + 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 */ 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 */ @@ -122,7 +123,7 @@ typedef struct { int belt_rows, belt_open, belt_request; /* 腰带点一下 = 自己喝,松手那一刻就喝,点几下喝几瓶;不判双击、腰带上不做喂雇佣兵的手势 | one tap on the belt = the player drinks, at the moment of release, several taps drink several; no double-tap detection, no mercenary feeding gesture on the belt */ 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; /* 摇杆手指被系统取消的时刻与当时的位置(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 */ + 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 */ 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 */ @@ -193,7 +194,7 @@ int dm_tc_belt_outside(const dm_tc_state *state, float x, float y); #define DM_TC_BELT_SWIPE_PT 24 /* 腰带格上松手时纵向位移过这么多点 = 展开 / 收起;不到 = 点按(喝) | On release over a belt cell, vertical displacement beyond this many points = expand / collapse; less = tap (drink) */ #define DM_TC_KEY_MIN_S 0.035 /* 技能键至少按住这么久(约 2 帧);不够的松手时补成脉冲,保证游戏读到 | A skill button is held at least this long (about 2 frames); a shorter one is made up as a pulse on release to guarantee the game reads it */ #define DM_TC_JOY_RESUME_S 0.35 /* 摇杆那根手指被系统取消后,这么久之内在原处附近重新落下的手指接着当摇杆(不要求落在底座附近) | after the joystick finger is cancelled by the system, a finger landing again near the same spot within this long continues as the joystick (landing near the base is not required) */ -#define DM_TC_JOY_GRAB_K 1.5f /* 手指落在离摇杆底座中心这么多倍半径之内才起摇杆(底座固定,不跟落指点) | the joystick starts only when a finger lands within this many radii of the joystick base center (the base is fixed and does not follow the touch-down point) */ +#define DM_TC_JOY_GRAB_K 1.5f /* 摇杆那根手指被系统取消后重新落下:离原处这么多倍底盘半径之内才接着当摇杆 | after the stick finger is cancelled by the system and touches down again: it continues as the stick only within this many base radii of the original place */ #define DM_TC_ZL_LEAD_S 0.17 /* 修饰键领先主键的时间(约 10 帧;同一帧按下游戏只认主键) | Time the modifier key leads the main key (about 10 frames; pressed in the same frame, the game only recognizes the main key) */ #define DM_TC_DOUBLE_TAP_S 0.40 /* 两次单击间隔上限 | Upper limit of the interval between two single taps */ #define DM_TC_HOLD_USE_S 0.60 /* 「按住」动作的按住时长:Mac 宿主实测 0.25 s 只捡起、0.45 s 打开魔盒 | Hold duration of the "hold" action: measured on the Mac host, 0.25 s only picks up, 0.45 s opens the cube */ diff --git a/dm/ios/Sources/main.m b/dm/ios/Sources/main.m index b2c5571..75aaafa 100644 --- a/dm/ios/Sources/main.m +++ b/dm/ios/Sources/main.m @@ -850,15 +850,15 @@ static void run_boot(void); [self presentViewController:a animated:YES completion:nil]; }]; } -- (void)downloadOfAssetPack:(BAAssetPack *)p hasProgress:(NSProgress *)g { +- (void)downloadOfAssetPack:(BAAssetPack *)p hasProgress:(NSProgress *)g API_AVAILABLE(ios(26.0)) { CFAbsoluteTime now = CFAbsoluteTimeGetCurrent(); int64_t done = g.completedUnitCount, total = g.totalUnitCount; 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 { plog("assets: 系统通知资源包下载完成"); dispatch_async(dispatch_get_main_queue(), ^{ [self ready]; }); } -- (void)downloadOfAssetPackPaused:(BAAssetPack *)p { [self say:T("dmDlPaused")]; } -- (void)downloadOfAssetPack:(BAAssetPack *)p failedWithError:(NSError *)e { [self fail:@"下载游戏资源" error:e]; } +- (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)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 @@ -978,9 +978,21 @@ static void bg_relaunch_test(void) { } const char *us = getenv("DM_TEST_UISHOT"); // 只测试用:DM_TEST_UISHOT=<秒>:<名字>,到点把当前窗口存成 Documents/<名字>.png——资源界面、着色器准备页这类系统界面层,游戏内截图截不到 | Test only: DM_TEST_UISHOT=: saves the current window to Documents/.png at that time -- UIKit-level screens such as the resource screen and the shader preparation page cannot be captured by the in-game screenshot if (us && atof(us) > 0 && strchr(us, ':')) { NSString *fn = @(strchr(us, ':') + 1); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(atof(us) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ - UIWindow *w = nil; for (UIScene *sc in UIApplication.sharedApplication.connectedScenes) if ([sc isKindOfClass:UIWindowScene.class]) for (UIWindow *x in ((UIWindowScene *)sc).windows) if (x.isKeyWindow || !w) w = x; - if (!w) { plog("【红】DM_TEST_UISHOT:没有窗口"); return; } - UIImage *im = [[[UIGraphicsImageRenderer alloc] initWithBounds:w.bounds] imageWithActions:^(UIGraphicsImageRendererContext *c) { [w drawViewHierarchyInRect:w.bounds afterScreenUpdates:NO]; }]; + // 所有场景的所有窗口按层级从低到高画进同一张图(系统弹框不一定在主窗口里,只取主窗口会得到一张黑图); + // 另把最上层呈现的界面里每个文字标签的「实际高度 / 排完整段要的高度」记进日志——截图万一仍截不到,截没截断也有数可读 + // All windows of all scenes are drawn into one image from the lowest level to the highest (a system alert is not necessarily in the main window, and taking only the main window gives a black image); + // in addition, for every text label in the topmost presented interface, "actual height / height needed to lay out the whole text" is written to the log - should the screenshot still fail to capture it, whether it is truncated can be read from numbers + NSMutableArray *ws = [NSMutableArray array]; for (UIScene *sc in UIApplication.sharedApplication.connectedScenes) if ([sc isKindOfClass:UIWindowScene.class]) [ws addObjectsFromArray:((UIWindowScene *)sc).windows]; + [ws sortUsingComparator:^NSComparisonResult(UIWindow *x, UIWindow *y) { return x.windowLevel < y.windowLevel ? NSOrderedAscending : x.windowLevel > y.windowLevel ? NSOrderedDescending : NSOrderedSame; }]; + if (!ws.count) { plog("【红】DM_TEST_UISHOT:没有窗口"); return; } + CGRect all = CGRectZero; for (UIWindow *x in ws) all = CGRectUnion(all, x.frame); + UIImage *im = [[[UIGraphicsImageRenderer alloc] initWithBounds:all] imageWithActions:^(UIGraphicsImageRendererContext *c) { for (UIWindow *x in ws) if (!x.hidden) [x drawViewHierarchyInRect:x.frame afterScreenUpdates:YES]; }]; + for (UIWindow *x in ws) { UIViewController *top = x.rootViewController; while (top.presentedViewController) top = top.presentedViewController; + plog("DM_TEST_UISHOT:窗口 %s 层级 %.0f %.0fx%.0f%s|最上层 %s", NSStringFromClass(x.class).UTF8String, x.windowLevel, x.frame.size.width, x.frame.size.height, x.hidden ? "(隐藏)" : "", top ? NSStringFromClass(top.class).UTF8String : "无"); + if (top && top != x.rootViewController) { NSMutableArray *q = [NSMutableArray arrayWithObject:top.view]; + while (q.count) { UIView *v = q.firstObject; [q removeObjectAtIndex:0]; [q addObjectsFromArray:v.subviews]; + if ([v isKindOfClass:UILabel.class] && ((UILabel *)v).text.length) { UILabel *l = (UILabel *)v; CGFloat need = [l sizeThatFits:CGSizeMake(l.bounds.size.width, CGFLOAT_MAX)].height; BOOL sc = NO; for (UIView *u = l.superview; u; u = u.superview) if ([u isKindOfClass:UIScrollView.class]) sc = YES; + plog("DM_TEST_UISHOT:标签 %.0fx%.0f 排完要高 %.0f 行数上限 %ld%s %s|%.24s", l.bounds.size.width, l.bounds.size.height, need, (long)l.numberOfLines, sc ? " 在滚动区里" : "", need <= l.bounds.size.height + 0.5 ? "不截断" : "【红】高度不够", l.text.UTF8String); } } } } NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:[fn.lastPathComponent stringByAppendingString:@".png"]]; plog("DM_TEST_UISHOT:%s %s", path.fileSystemRepresentation, [UIImagePNGRepresentation(im) writeToFile:path atomically:YES] ? "已存" : "【红】没存下"); }); } diff --git a/dm/ios/run.sh b/dm/ios/run.sh index d86f60e..3e20cfa 100755 --- a/dm/ios/run.sh +++ b/dm/ios/run.sh @@ -72,15 +72,25 @@ if [ "$1" = build ]; then [ -f Gen/romfs_overlay/data/.build.config ] || { t "🔴 没生成覆盖层 Gen/romfs_overlay"; exit 1; } # 免费的开发者账号(个人团队)签不了这几项权限:DM_FREE_ACCOUNT=1 时从工程描述里去掉再生成。去掉后少的是 iCloud 存档同步、 # 持续执行模式与更高的内存上限;游戏照常运行(地址预留已按不带扩展虚拟寻址也放得下来定,见 host/hle_svc.c) - # A free developer account (personal team) cannot sign these entitlements: with DM_FREE_ACCOUNT=1 they are removed from the project - # description before generating. What is lost is iCloud save sync, - # sustained execution mode and the higher memory limit; the game runs as usual (the address reservation is already sized to fit without - # extended virtual addressing, see host/hle_svc.c) + # 两个开关各自独立、可以叠:先按免费档去掉签不了的,再按老接口版改部署目标(公开用户多是免费账号,「免费账号 + iOS 18」要两样都生效)。都没设 = 原样生成 + # A free developer account (personal team) cannot sign these entitlements: with DM_FREE_ACCOUNT=1 they are removed from the project description before generating. What is lost is iCloud save sync, + # sustained execution mode and the higher memory limit; the game runs as usual (the address reservation is sized to fit without extended virtual addressing as well, see host/hle_svc.c) + # The two switches are independent and can be combined: first remove what the free tier cannot sign, then change the deployment target for the older-API build (most public users have free accounts, and "free account + iOS 18" needs both to take effect). Neither set = generate as is + SPEC=project.yml; FREE= if [ "${DM_FREE_ACCOUNT:-0}" = 1 ]; then python3 tools/project_free.py project.yml project_free.yml || { t "🔴 DM_FREE_ACCOUNT:免费档的工程描述没生成(见上)"; exit 1; } # 去掉签不了的六行权限与用不上的资源下载扩展 | remove the six entitlement lines it cannot sign and the asset download extension it has no use for - xcodegen generate -q --spec project_free.yml >/dev/null || { t "🔴 xcodegen 失败"; exit 1; }; rm -f project_free.yml; t "按免费账号生成:不带 iCloud / 持续执行 / 增加内存上限 / 扩展虚拟寻址,也不带资源下载扩展(只占一个应用标识)" - else + SPEC=project_free.yml; FREE=free + fi + if [ "${DM_IOS_M3:-0}" = 1 ]; then # 老接口版:图形后端不用 Metal 4,部署目标 iOS 18.0(tools/project_m3.py);缺省不走这里 | older-API build: the graphics backend does not use Metal 4, deployment target iOS 18.0 (tools/project_m3.py); not taken by default + python3 tools/project_m3.py $SPEC project_m3.yml $FREE || { rm -f project_free.yml; t "🔴 DM_IOS_M3:老接口版的工程描述没生成(见上)"; exit 1; } + SPEC=project_m3.yml + fi + if [ $SPEC = project.yml ]; then xcodegen generate -q >/dev/null || { t "🔴 xcodegen 失败"; exit 1; } + else + xcodegen generate -q --spec $SPEC >/dev/null; XG=$?; rm -f project_free.yml project_m3.yml; [ $XG = 0 ] || { t "🔴 xcodegen 失败"; exit 1; } + [ -z "$FREE" ] || t "按免费账号生成:不带 iCloud / 持续执行 / 增加内存上限 / 扩展虚拟寻址,也不带资源下载扩展(只占一个应用标识)" + [ "${DM_IOS_M3:-0}" != 1 ] || t "按老接口版生成:部署目标 iOS 18.0、图形后端不用 Metal 4" fi [ "${DM_GEN_ONLY:-}" = 1 ] && { t "生成完成(DM_GEN_ONLY)"; exit 0; } # tools/testflight.sh 只要生成,自己 archive | tools/testflight.sh only needs the generation step and does the archive itself asc_auth # App Store Connect API 密钥(有就带上,供签名自动注册 App Group 等能力;见 tools/asc_env.sh) | App Store Connect API key (included if present, so signing can auto-register capabilities such as the App Group; see tools/asc_env.sh) diff --git a/dm/ios/tests/t_joy_travel.c b/dm/ios/tests/t_joy_travel.c index 4fcefae..5156792 100644 --- a/dm/ios/tests/t_joy_travel.c +++ b/dm/ios/tests/t_joy_travel.c @@ -5,7 +5,7 @@ #include static int checks; #define CHECK(x) do { ++checks; if (!(x)) { fprintf(stderr,"FAIL line=%d %s\n",__LINE__,#x); exit(1); } } while (0) -static int push(dm_tc_state *s, float w, float h, float d) { /* 在底座圆心起手(底座固定),向右推 d 点,返回横轴输出 | start on the base center (the base is fixed), push d points to the right, return the horizontal axis output */ +static int push(dm_tc_state *s, float w, float h, float d) { /* 在静止位起手(在起摇杆区里,圆心 = 落点),向右推 d 点,返回横轴输出 | start at the rest position (inside the stick-start zone, centre = touch point), push d points to the right, return the horizontal output */ dm_tc_init(s, w, h); float cx = s->layout.joy_x, cy = s->layout.joy_y; dm_tc_begin(s, 0, cx, cy); CHECK(s->joy_slot == 0); dm_tc_move(s, 0, cx + d, cy); return s->lx; } @@ -24,7 +24,7 @@ int main(void) { dm_tc_init(&s, 1366, 768); CHECK(s.layout.joy_radius > 104 && s.layout.joy_radius < 105); /* 画出来的底盘仍按视觉倍数:60 × 1.745 | The drawn base still follows the visual multiplier: 60 × 1.745 */ /* 底边那一条:手机(没设)照旧能在最底起摇杆 | Bottom-edge strip: a phone (not set) can still start the stick at the very bottom as before */ - dm_tc_init(&s, 956, 440); dm_tc_begin(&s, 0, 90, 425); CHECK(s.joy_slot == 0); dm_tc_cancel_all(&s); /* 圆心 90,340、可起手半径 90:(90,425) 在内 | center 90,340, grab radius 90: (90,425) is inside */ + dm_tc_init(&s, 956, 440); dm_tc_begin(&s, 0, 90, 425); CHECK(s.joy_slot == 0); dm_tc_cancel_all(&s); /* 起摇杆区一直到屏幕底:(90,425) 在内 | the stick-start zone reaches the bottom of the screen: (90,425) is inside */ /* iPad:底部 20 点里起手不当摇杆、松手不当点地 | iPad: a touch starting in the bottom 20 points is not treated as the stick, and its release is not treated as a ground tap */ dm_tc_set_edge_bottom(20); dm_tc_init(&s, 1366, 768); dm_tc_begin(&s, 0, 100, 760); CHECK(s.joy_slot == DM_TC_NONE && s.finger[0].target == DM_TC_EDGE); diff --git a/dm/ios/tests/t_touch_controls.c b/dm/ios/tests/t_touch_controls.c index 002aad3..6f11f89 100644 --- a/dm/ios/tests/t_touch_controls.c +++ b/dm/ios/tests/t_touch_controls.c @@ -117,28 +117,41 @@ static void two_fingers_same_key(void) { dm_tc_end(&s,1); CHECK(s.buttons==0); } static void joystick_deadzone(void) { - /* 底座固定在静止位(667×375:圆心 90,275、半径 60):落在圆心上起手,原点 = 圆心 | the base is fixed at its rest position (667×375: center 90,275, radius 60): starting on the center, origin = center */ - dm_tc_state s; dm_tc_init(&s,667,375); dm_tc_begin(&s,0,90,275); + /* 浮动底盘。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。落在区里起手:圆心 = 落点,位移为零 + 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 */ + 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); + 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); dm_tc_move(&s,0,96,275); CHECK(s.lx==0 && s.ly==0); dm_tc_move(&s,0,96.1f,275); CHECK(s.lx>0 && s.lx<100 && s.ly==0); dm_tc_move(&s,0,123,275); CHECK(abs(s.lx-16384)<=1 && s.ly==0); dm_tc_end(&s,0); - /* 落在底座附近(离圆心不超过 1.5 倍半径 = 90 点):起摇杆,原点仍是圆心,一按下就按「手指相对圆心」出方向((150,275) 在圆心右 60 = 满偏) | landing near the base (no more than 1.5 × radius = 90 points from the center): the joystick starts, the origin is still the center, and from the moment of pressing the direction is "finger relative to the center" ((150,275) is 60 to the right of the center = full deflection) */ - dm_tc_begin(&s,0,150,275); CHECK(s.joy_slot==0); NEAR(s.joy_origin_x,90,0); NEAR(s.joy_origin_y,275,0); CHECK(s.lx==DM_STICK_MAX && s.ly==0); - dm_tc_move(&s,0,600,275); CHECK(s.lx==DM_STICK_MAX && s.ly==0); NEAR(s.joy_origin_x,90,0); /* 拖到很远:照样识别,底座不动 | dragged very far: still recognized, the base does not move */ - dm_tc_move(&s,0,90,100); CHECK(s.lx==0 && s.ly==DM_STICK_MAX); NEAR(s.joy_origin_y,275,0); - dm_tc_end(&s,0); CHECK(s.joy_slot==-1 && s.lx==0 && s.ly==0); - dm_tc_begin(&s,0,90,365); CHECK(s.joy_slot==0); dm_tc_end(&s,0); /* 正下方 90 点:刚好在内 | 90 points straight down: just inside */ - dm_tc_begin(&s,0,181,275); CHECK(s.joy_slot==-1 && s.lx==0); dm_tc_end(&s,0); /* 右边 91 点:不起摇杆 | 91 points to the right: no joystick started */ - dm_tc_begin(&s,0,250,150); CHECK(s.joy_slot==-1 && s.lx==0 && s.ly==0); dm_tc_move(&s,0,300,150); CHECK(s.joy_slot==-1 && s.lx==0); dm_tc_end(&s,0); /* 左侧别处:不起摇杆,拖也不变成摇杆 | elsewhere on the left: no joystick started, and dragging does not turn into a joystick either */ - /* 拖远了的摇杆手指被系统取消,0.35 秒内在原处附近重新落下:接着当摇杆(原点仍是圆心);超时或离得远:不接 | a joystick finger dragged far away is cancelled by the system and lands again near the same spot within 0.35 seconds: it continues as the joystick (the origin is still the center); timed out or too far away: not picked up */ + /* 区里别处:圆心跟落点;按住后拖到多远都照样识别,底盘不跟手走;松手后静止位不变 | elsewhere in the zone: the centre follows the touch point; once held, dragging any distance is still recognised and the base does not follow the finger; after release the rest position is unchanged */ + dm_tc_begin(&s,0,200,200); CHECK(s.joy_slot==0); NEAR(s.joy_origin_x,200,0); NEAR(s.joy_origin_y,200,0); CHECK(s.lx==0 && s.ly==0); + 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); + 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); + dm_tc_begin(&s,0,100,168); CHECK(s.joy_slot==-1 && s.lx==0); dm_tc_end(&s,0); + dm_tc_begin(&s,0,300,150); CHECK(s.joy_slot==-1 && s.lx==0 && s.ly==0); dm_tc_move(&s,0,200,250); CHECK(s.joy_slot==-1 && s.lx==0); dm_tc_end(&s,0); + /* 区里很快原地松开的那一下兼作点击(落点记成点世界),按久了 / 拖开了的不算 | 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 */ 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,265,165,50.4); CHECK(s.joy_slot==1 && s.lx>0 && s.ly>0); NEAR(s.joy_origin_x,90,0); dm_tc_cancel_finger(&s,1); - dm_tc_begin_at(&s,2,265,165,50.4+0.36); CHECK(s.joy_slot==-1); dm_tc_end_at(&s,2,51.5); /* 超过 0.35 秒 | more than 0.35 seconds */ + 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)) */ 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); dm_tc_end_at(&s,1,53.5); /* 离取消时的位置 140 点:不接 | 140 points from the position at cancellation: not picked up */ + 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); } 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) */ @@ -308,15 +321,15 @@ static void pointer_over_disabled_target(void) { static void world_tap(void) { dm_tc_state s; dm_tc_init(&s,667,375); dm_tc_enable_targets(&s,(1u<x,m->y,14.0); CHECK(s.buttons==m->button); dm_tc_end_at(&s,0,14.1); CHECK(s.world_tap_seq==2); /* 点主按钮:发键,不算点世界 | Tapping the main button: sends the key, does not count as a world tap */ - dm_tc_set_joy_block(&s,1); dm_tc_begin_at(&s,0,120,250,20.5); CHECK(s.joy_slot==-1 && s.lx==0 && s.ly==0); dm_tc_end_at(&s,0,20.6); CHECK(s.world_tap_seq==3); NEAR(s.world_tap_x,120,0.001); /* 讲话文字框单独开着:同一处点一下不起摇杆、没有方向,只当一次点击 | speech text box open on its own: a tap in the same place starts no stick and gives no direction, it is just one click */ - dm_tc_set_joy_block(&s,0); dm_tc_begin_at(&s,0,120,250,21.5); CHECK(s.joy_slot==0); dm_tc_end_at(&s,0,21.6); CHECK(s.world_tap_seq==3); /* 文字框关了:照旧是摇杆 | text box closed: stick as usual */ - dm_tc_set_navigation_mode(&s,1); dm_tc_begin_at(&s,0,400,120,16.0); dm_tc_end_at(&s,0,16.1); CHECK(s.world_tap_seq==3); /* 面板态不记 | Not recorded in panel state */ + dm_tc_begin_at(&s,0,m->x,m->y,14.0); CHECK(s.buttons==m->button); dm_tc_end_at(&s,0,14.1); CHECK(s.world_tap_seq==3); /* 点主按钮:发键,不算点世界 | Tapping the main button: sends the key, does not count as a world tap */ + dm_tc_set_joy_block(&s,1); dm_tc_begin_at(&s,0,120,250,20.5); CHECK(s.joy_slot==-1 && s.lx==0 && s.ly==0); dm_tc_end_at(&s,0,20.6); CHECK(s.world_tap_seq==4); NEAR(s.world_tap_x,120,0.001); /* 讲话文字框单独开着:同一处点一下不起摇杆、没有方向,只当一次点击 | speech text box open on its own: a tap in the same place starts no stick and gives no direction, it is just one click */ + dm_tc_set_joy_block(&s,0); dm_tc_begin_at(&s,0,120,250,21.5); CHECK(s.joy_slot==0); dm_tc_end_at(&s,0,21.6); CHECK(s.world_tap_seq==5); /* 文字框关了:起摇杆,短按照样兼作点世界 | text box closed: the stick starts, and a short press still doubles as a world tap */ + dm_tc_set_navigation_mode(&s,1); dm_tc_begin_at(&s,0,400,120,16.0); dm_tc_end_at(&s,0,16.1); CHECK(s.world_tap_seq==5); /* 面板态不记 | Not recorded in panel state */ } /* 面板外点按 = 按 B 到面板关掉为止:第一下在 tick 里发;面板还开着,0.3 秒后再发;面板关了就不再发;至多 3 下 | Tap outside the panel = press B until the panel closes: the first press is sent in tick; if the panel is still open, send again 0.3 seconds later; once the panel is closed no more are sent; at most 3 presses */ static void pointer_outside_close(void) { @@ -424,7 +437,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, 90, 0.001); NEAR(b.joy_x, 122, 0.001); CHECK(b.joy_x - b.joy_radius >= 61.999f); + 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 */ 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 */ diff --git a/dm/ios/tools/gen_romfs_overlay.py b/dm/ios/tools/gen_romfs_overlay.py index 87bd8ee..e94d489 100644 --- a/dm/ios/tools/gen_romfs_overlay.py +++ b/dm/ios/tools/gen_romfs_overlay.py @@ -71,6 +71,13 @@ with tempfile.TemporaryDirectory() as t: # dm_rift_ui.c 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,原因见那里)。手柄用左右键选、原版没暴露; + # Mac App 是手柄版布局 + 鼠标,点德鲁伊出术士、右半边四个职业都错一格 + # Gamepad-layout class selection page: the click rectangles of the eight classes are likewise changed to vertical strips split by where the characters actually stand (touch_layout.CLASS_STRIPS, see there for the reason). A gamepad selects with left / right and the original never exposed this; + # the Mac App is the gamepad layout plus a mouse, where clicking the Druid selected the Warlock and all four classes on the right half were off by one + lp,lt=touch_layout.read_layout(romfs,'controller/console/charactercreatepanelhd.json') + for nm,x0,x1 in touch_layout.CLASS_STRIPS: lt=touch_layout.set_rect(lt,nm,x0,450,x1-x0,1300) + o=os.path.join(tpad,'pad_charcreate.json'); open(o,'w',encoding='utf-8').write(lt); PR[lp.lower()]=o PR.update(touch_layout.build_ingame(romfs,tpad,touch_layout.PAD_VENDOR,present=False)[0]) # 手柄版商人页:刷新货架钮 | Controller layout vendor page: the refresh shop stock button lp,lt=touch_layout.read_layout(romfs,'controller/console/mainmenupanelhd.json'); o=os.path.join(tpad,'pad_mainmenu.json'); open(o,'w',encoding='utf-8').write(touch_layout.pad_mainmenu(lt)); PR[lp.lower()]=o # 手柄版主菜单:构建号与新版本提示 | Controller layout main menu: build number and new version notice lp,lt=touch_layout.read_layout(romfs,'controller/console/mainmenubuttonribbonhd.json'); o=os.path.join(tpad,'pad_ribbon.json'); open(o,'w',encoding='utf-8').write(touch_layout.pad_ribbon(lt)); PR[lp.lower()]=o # 手柄版主菜单按钮栏:拿掉「电影动画」 | Controller layout main menu button ribbon: remove 「电影动画」(Cinematics) @@ -151,7 +158,7 @@ with tempfile.TemporaryDirectory() as t: PADLAY={k:v for k,v in PR.items() if touch_path(k)} # 手柄版只取布局(数据表、图与触屏版同一份) | The controller version takes only layouts (data tables and images are the same copy as the touch version) # 手柄专用清单:手柄模式下不是原版字节的布局就这几份,一份不许多、一份不许少(改上面某一行时把相邻一行整行替掉过,商人页的刷新钮就从包里掉了) # 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/characteroptionspanelhd.json','controller/console/mainmenubuttonribbonhd.json','controller/console/mainmenupanelhd.json','controller/console/settingspanelhd.json','controller/console/switch/playerinventoryexpansionlayouthd.json','controller/console/videooptionspanelhd.json', + 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') 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 diff --git a/dm/ios/tools/project_m3.py b/dm/ios/tools/project_m3.py new file mode 100644 index 0000000..e788b8f --- /dev/null +++ b/dm/ios/tools/project_m3.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +# 老接口版的工程描述:project_m3.py <输出.yml> [free] (run.sh 在 DM_IOS_M3=1 时调) +# 第三个参数 free = 输入已经过了免费档(tools/project_free.py,DM_FREE_ACCOUNT=1 同时设着):资源下载扩展那五处免费档已去掉,这里要求一处都不剩 +# 只改主程序三处:部署目标 26.0 → 18.0;编译参数加 -DDM_NVN_M3=1(图形后端不用 Metal 4,见 gfx/nvn/nvn_mtl.m); +# 处理器基线 a18 → a14(iOS 18 能装的机器里,内存够跑这个游戏的最老是 A14;宿主汇编要的 LSE 原子指令 A11 起就有)。 +# 资源下载扩展(RomfsDownloader,只服务苹果托管资源包,部署目标 iOS 26.4)不带:扩展的最低系统高于主程序的包在老系统上装不装得上没人验过, +# 老接口版的资源本来也不走托管资源包(内测直装走自己的下载地址 / 手动拷,公开版用户自备)。去掉的三样与免费账号档相同(tools/project_free.py): +# 扩展目标、主程序对它的依赖、Info.plist 里托管资源包的三个键;主程序里见不到这三个键就不碰托管资源包。 +# 每处都要求恰好命中一次,工程描述改了格式就在这里失败,不悄悄出一个没改到的工程。 +# Project description for the older-API build: project_m3.py [free] (called by run.sh when DM_IOS_M3=1) +# The third argument free = the input has already been through the free tier (tools/project_free.py, with DM_FREE_ACCOUNT=1 set at the same time): the five places of the resource-download extension are already removed by the free tier, and here none may remain +# Only three things of the main program change: deployment target 26.0 -> 18.0; compile flags gain -DDM_NVN_M3=1 (the graphics backend does not use Metal 4, see gfx/nvn/nvn_mtl.m); +# processor baseline a18 -> a14 (among the devices that can install iOS 18, the oldest with enough memory for this game is the A14; the LSE atomic instructions the host assembly needs exist from the A11). +# The resource-download extension (RomfsDownloader, serving only Apple-hosted asset packs, deployment target iOS 26.4) is left out: whether a package whose extension has a higher minimum system than the main program installs on an older system has not been verified by anyone, +# and the older-API build does not use hosted asset packs for resources anyway (public users bring their own). The three things removed are the same as for the free-account tier (tools/project_free.py): +# the extension target, the main program's dependency on it, and the three hosted-asset-pack keys in Info.plist; without these three keys the main program does not touch hosted asset packs. +# Each place must match exactly once, so that a change in the format of the project description fails here instead of quietly producing a project that was not changed. +import sys +src, dst = sys.argv[1:3]; free = sys.argv[3:4] == ['free']; s = open(src).read() +def one(old, new): + global s + if s.count(old) != 1: sys.exit(f"🔴 project_m3:工程描述里「{old[:40]}」应恰好出现 1 次,实际 {s.count(old)} 次") + s = s.replace(old, new) +one(' iOS: "26.0"', ' iOS: "18.0"') +one('OTHER_CFLAGS: $(inherited) -mcpu=apple-a18', 'OTHER_CFLAGS: $(inherited) -mcpu=apple-a14 -DDM_NVN_M3=1') +import re +L = s.split('\n'); out, n_ba, n_dep, n_tgt, i = [], 0, 0, 0, 0 +while i < len(L): + l = L[i] + if re.match(r'^ *(BAAppGroupID|BAHasManagedAssetPacks|BAUsesAppleHosting):', l): n_ba += 1; i += 1; continue + if re.match(r'^ *- target: RomfsDownloader\b', l): n_dep += 1; i += 1; continue + if re.match(r'^ RomfsDownloader:\s*$', l): # 整个目标块:到下一个同级键为止 | the whole target block: up to the next key at the same level + n_tgt += 1; i += 1 + while i < len(L) and not re.match(r'^ \S', L[i]) and not re.match(r'^\S', L[i]): i += 1 + continue + out.append(l); i += 1 +want = (0, 0, 0) if free else (3, 1, 1) +if (n_ba, n_dep, n_tgt) != want: sys.exit(f"🔴 project_m3:资源下载扩展没去干净(托管资源包键 {n_ba} / {want[0]}、依赖 {n_dep} / {want[1]}、扩展目标 {n_tgt} / {want[2]}{';输入应已过免费档' if free else ''})") +if any('RomfsDownloader' in l and not l.lstrip().startswith('#') for l in out): sys.exit("🔴 project_m3:去掉之后工程描述里还有 RomfsDownloader") +open(dst, 'w').write('\n'.join(out)) diff --git a/dm/ios/tools/rw_lvcheck.py b/dm/ios/tools/rw_lvcheck.py new file mode 100644 index 0000000..07461dd --- /dev/null +++ b/dm/ios/tools/rw_lvcheck.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +# 符文之语清单「需要等级」全量核对:rw_lvcheck.py <原版表目录(含 weapons.txt armor.txt misc.txt runes.txt)> +# 一、整张物品表逐行:宿主读到的需求等级(导出文件,物品码值)对原版三张表的 levelreq; +# 二、每个可做成的符文之语:按宿主读数取各符文需求等级的最大值,对按原版表算的同一个量。任何一处不等退出码 1。 +# Full check of "required level" in the runeword list: rw_lvcheck.py +# One, the whole item table row by row: the required level the host read (the exported file, item codevalue) against levelreq in the three original tables; +# Two, every runeword that can be made: the maximum of the runes' required levels by the host's readings against the same quantity computed from the original tables. Any mismatch exits with code 1. +import sys,csv,os +dump,d=sys.argv[1],sys.argv[2] +got={} +for l in open(dump,encoding='latin-1'): + c,v=l.rstrip('\n').split('\t') + if c: got.setdefault(c,int(v)) +def rows(n): return list(csv.DictReader(open(os.path.join(d,n),encoding='latin-1'),delimiter='\t')) +want={}; diff_cols=0 +for n in ('weapons.txt','armor.txt','misc.txt'): + for r in rows(n): + c=r.get('code','').strip() + if not c or c in want: continue + want[c]=int(r['levelreq'] or 0); diff_cols+=(r.get('level') or '0')!=(r['levelreq'] or '0') +bad=[(c,got.get(c),w) for c,w in want.items() if c in got and got[c]!=w]; miss=[c for c in want if c not in got] +print(f'物品表:原版三张表 {len(want)} 个物品码,导出 {len(got)} 个;逐行对上 {sum(1 for c in want if got.get(c)==want[c])},不等 {len(bad)},导出里没有的 {len(miss)};其中物品等级 ≠ 需求等级的物品 {diff_cols} 个(这些行分得出两列)') +for c,g,w in bad[:20]: print(f' 不等:{c} 读到 {g} 原版 {w}') +rb=0; n=0 +for r in rows('runes.txt'): + if r.get('complete')!='1': continue + rs=[r[f'Rune{i}'] for i in range(1,7) if r.get(f'Rune{i}')] + if not rs: continue + n+=1; a=max(got.get(c,-1) for c in rs); b=max(want.get(c,-1) for c in rs) + if a!=b: rb+=1; print(f' 符文之语 {r["Name"]}({r.get("*Rune Name","")})符文 {rs}:读到 {a} 原版 {b}') +print(f'符文之语:可做成的 {n} 个,符文部分的需要等级不等 {rb} 个') +sys.exit(1 if bad or rb else 0) diff --git a/dm/ios/tools/uireg/affected.tsv b/dm/ios/tools/uireg/affected.tsv index be7a586..c1b5de1 100644 --- a/dm/ios/tools/uireg/affected.tsv +++ b/dm/ios/tools/uireg/affected.tsv @@ -14,7 +14,8 @@ dm/ios/tools/dm_i18n.py * dm/host/dm_i18n* * dm/ios/tools/annot_strings.py k j rw1 rw2 kbb vt1 dm/host/dm_textbox* k j rw1 rw2 kbb vt1 -dm/host/dm_runeword* k j rw1 rw2 rwp rwd d +dm/host/dm_rwlv* k j rw1 rw2 rwp rwd d rwlv +dm/host/dm_runeword* k j rw1 rw2 rwp rwd d rwlv dm/host/dm_vault* vf1 vf2 vt1 pg1 pg2 c s sb t u d cb dm/host/dm_pages* pg1 pg2 vt1 c s sb dm/ios/tools/wide_stash.py vf1 vf2 vt1 pg1 pg2 c s sb t u d cb diff --git a/dm/ios/tools/uireg/uireg.py b/dm/ios/tools/uireg/uireg.py index e7f1069..9cdf41c 100644 --- a/dm/ios/tools/uireg/uireg.py +++ b/dm/ios/tools/uireg/uireg.py @@ -1084,7 +1084,15 @@ def groups(): LISTOK=r"符文之语:长按[^\n]*→ 清单 [1-9]\d* 行" def anyl(p): return lambda s,b: ("通:" if re.search(p,b+s) else "不通:")+"整局日志" # rw1:背包里符文齐——长按 1 孔软帽不开清单;长按 2 孔软帽开清单;点清单外关;再长按、点「一键合成」成型,两枚符文离开背包 - # rw1: all runes are in the inventory - long-pressing the 1-socket cap does not open the list; long-pressing the 2-socket cap opens the list; tapping outside the list closes it; long-press again and tap 「一键合成」(Craft) to form it, and the two runes leave the inventory + # rwlv 局:清单里的「需要等级」取底材的需求等级,不是物品等级(线上缺陷:塔盔需求 59、物品等级 79,清单整页显示 79)。 + # 现场:背包里 7 顶塔盔(uhm,白装孔数随机但逐局相同),长按其中带孔的一顶;2 孔塔盔的首行是「知识」(欧特 21 + 索尔 27)→ max(59, 27) = 59 + # rw1: all runes in the inventory - a long press on a 1-socket Cap does not open the list; a long press on a 2-socket Cap opens it; a tap outside the list closes it; long press again and tap "Craft" to make it, and the two runes leave the inventory + # rwlv run: "required level" in the list takes the base item's required level, not its item level (reported defect: the Spired Helm requires 59 with item level 79, and the whole page of the list showed 79). + # Scene: 7 Spired Helms in the inventory (uhm; socket counts of white items are random but the same every run), long press one with sockets; the first row for a 2-socket Spired Helm is Lore (Ort 21 + Sol 27) -> max(59, 27) = 59 + g=G("rwlv","DM_TEST_GIVE=uhm:2:7@60 DM_TEST_GIVE_INV=1"); g.sect("rwlv",0); g.enter(); g.wait(2.0); g.tap("@menu",1.4) + g.item("长按背包里带孔的塔盔","弹清单,需要等级 59(看截图:每行都是 59)",r"长按 uhm[^\n]*需要等级 59",r"长按 uhm[^\n]*需要等级 79|【红】符文之语"); g.hold(395,267); g.wait(1.0); g.shot() + g.item("点清单外","清单关掉",r"清单外 → 关清单|清单关闭"); g.tap(P(120,200),1.5); g.shot() + gs.append(g) g=G("rw1",RWE+" DM_TEST_RW_LIST=75"); g.sect("rw1",0); g.enter(); g.wait(2.0); g.tap("@menu",1.4) g.item("背包布局","软帽、符文在 k 局同样的位置(看截图)",None); g.shot() g.item("长按 1 孔软帽","不开清单(1 孔帽子没有能做的符文之语)",None,LISTOK); g.hold(376,228); g.wait(1.0); g.shot() diff --git a/dm/tools/mac_app.sh b/dm/tools/mac_app.sh index ec739a3..daac778 100755 --- a/dm/tools/mac_app.sh +++ b/dm/tools/mac_app.sh @@ -15,10 +15,13 @@ set -eu HERE=$(cd "$(dirname "$0")" && pwd); DM=$HERE/..; ROOT=${DM_ROOT:-$HOME/dm-work} OUT=${1:-$ROOT/out/macapp}; KIND=${DM_MAC_PRODUCT:-touch}; BID=${DM_MAC_BUNDLE_ID:-org.d2rmobile.mac} P=$(bash "$HERE/product.sh" path "$KIND"); [ -f "$P/main.patched.bin" ] || { echo "🔴 没有产物 ${P}(先跑 product.sh build)"; exit 2; } -make -C "$DM/host" > /dev/null -MIN=$(make -s -C "$DM/host" print-macos-min) # 最低系统版本:与编译宿主用的是同一个数(host/Makefile 的 MACOS_MIN) | minimum system version: the same number the host is compiled with (MACOS_MIN in host/Makefile) -APP="$OUT/D2R Mobile.app"; rm -rf "$APP"; mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" -cp "$DM/host/dmhost" "$APP/Contents/MacOS/D2RMobile" +# DM_MAC_M3=1:老接口版(图形后端不用 Metal 4,最低系统 host/Makefile 的 MACOS_MIN_M3)。包名、显示名、包标识都带 M3,能和正式包并存;存档与日志目录也是另一个 +# DM_MAC_M3=1: older-API build (the graphics backend does not use Metal 4; minimum system is MACOS_MIN_M3 in host/Makefile). Package name, display name and bundle identifier all carry M3 so it can coexist with the regular package; the save and log directory is a separate one as well +M3=${DM_MAC_M3:-}; NAME="D2R Mobile${M3:+ M3}"; [ -z "$M3" ] || BID=${DM_MAC_BUNDLE_ID:-org.d2rmobile.mac.m3} +make -C "$DM/host" ${M3:+dmhost_m3} > /dev/null +MIN=$(make -s -C "$DM/host" print-macos-min${M3:+-m3}) # 最低系统版本:与编译宿主用的是同一个数(host/Makefile 的 MACOS_MIN / MACOS_MIN_M3) | minimum system version: the same number the host is compiled with (MACOS_MIN / MACOS_MIN_M3 in host/Makefile) +APP="$OUT/$NAME.app"; rm -rf "$APP"; mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" +cp "$DM/host/dmhost${M3:+_m3}" "$APP/Contents/MacOS/D2RMobile" LINK=${DM_MAC_LINK-1}; [ "$LINK" != 0 ] || LINK=; RES="$APP/Contents/Resources"; : > "$RES/paths.txt" if [ -n "$LINK" ]; then echo "product=$P" >> "$RES/paths.txt"; else cp -R "$P" "$RES/product"; fi cp "$DM/gfx/nvn/shader_map.tsv" "$APP/Contents/Resources/shader_map.tsv" @@ -26,7 +29,11 @@ cp "$DM/gfx/nvn/pso_manifest.tsv" "$APP/Contents/Resources/pso_manifest.tsv" # [ ! -f "$DM/gfx/nvn/c1_full.tsv" ] || cp "$DM/gfx/nvn/c1_full.tsv" "$APP/Contents/Resources/c1_full.tsv" # 图形后端按「与映射表同目录」找它 | The graphics backend looks for it "in the same directory as the mapping table" # 编好的着色器库(Mac 版,dmsh_build.py 出的):只带运行要用的 .metallib 与反射 .json,源码 .metal 不带 # The compiled shader library (Mac variant, produced by dmsh_build.py): only the .metallib and reflection .json needed at run time are included, not the .metal sources -V=$(sed -n 's/.*DMSH_CHAIN "\(.*\)".*/\1/p' "$DM/gfx/nvn/dmsh_chain.h"); MSL=${DM_MSL_DIR:-$ROOT/build/cache/metal_shader_cache}/b-$V +V=$(sed -n 's/.*DMSH_CHAIN "\(.*\)".*/\1/p' "$DM/gfx/nvn/dmsh_chain.h") +# 老接口版:着色器库也要按它的最低系统重编一份(缓存里那份记的目标是编译机的系统版本,老系统上加载不了);DM_MSL_DIR 给了就用给的 +# Older-API build: the shader libraries must also be recompiled for its minimum system (the ones in the cache record the system version of the build machine as target and cannot be loaded on an older system); DM_MSL_DIR is used when given +[ -z "$M3" ] || [ -n "${DM_MSL_DIR:-}" ] || { bash "$DM/gfx/tools/msl_retarget.sh" "$MIN" "$OUT/msl_min$MIN" > /dev/null || { echo "🔴 着色器库按 macOS ${MIN} 重编失败"; exit 2; }; DM_MSL_DIR=$OUT/msl_min$MIN; } +MSL=${DM_MSL_DIR:-$ROOT/build/cache/metal_shader_cache}/b-$V [ -d "$MSL" ] || { echo "🔴 没有着色器库 ${MSL}(先跑 dm/gfx/tools/dmsh_build.py)"; exit 2; } if [ -n "$LINK" ]; then echo "msl=$(dirname "$MSL")" >> "$RES/paths.txt" else mkdir -p "$RES/msl/b-$V"; rsync -a --include='*.metallib' --include='*.json' --exclude='*' "$MSL/" "$RES/msl/b-$V/"; fi @@ -44,8 +51,8 @@ cat > "$APP/Contents/Info.plist" < -CFBundleNameD2R Mobile -CFBundleDisplayNameD2R Mobile +CFBundleName$NAME +CFBundleDisplayName$NAME CFBundleIdentifier$BID CFBundleExecutableD2RMobile CFBundlePackageTypeAPPL @@ -60,10 +67,19 @@ PL # 自检:管线预热的种子清单在包里、与映射表同目录、不是空的 # Self-check: the seed list for pipeline warm-up is in the package, in the same directory as the mapping table, and not empty [ -s "$RES/pso_manifest.tsv" ] && [ -s "$RES/shader_map.tsv" ] || { echo "🔴 包里缺管线预热种子清单或着色器映射表(Resources/pso_manifest.tsv、shader_map.tsv)"; exit 3; } +# 老接口版另核:程序本体里不许引用任何 Metal 4 符号 +# Extra check for the older-API build: the executable must not reference any Metal 4 symbol +[ -z "$M3" ] || { N4=$(nm "$APP/Contents/MacOS/D2RMobile" | grep -c MTL4 || true); [ "$N4" = 0 ] || { echo "🔴 老接口版的程序本体里还有 ${N4} 个 Metal 4 符号"; exit 3; }; } +# 自检:带进包的着色器库记的目标系统不许高于包声明的最低系统(抽查头、中、尾各一个与一个 _bf;链接式的包不带库,不查) +# Self-check: the target system recorded in the shader libraries carried in the package must not be higher than the minimum system the package declares (spot-check one each from the head, middle and tail plus one _bf; a link-style package carries no libraries and is not checked) +if [ -z "$LINK" ]; then ( cd "$RES/msl/b-$V" && for f in $(ls | grep '_b\.metallib$' | sed -n '1p;1000p;$p') $(ls | grep '_bf\.metallib$' | head -1); do + LV=$(xcrun -sdk macosx metal-objdump -d "$f" 2>/dev/null | sed -n 's/.*target triple = ".*-apple-macosx\([0-9]*\.[0-9]*\).*/\1/p' | head -1) + [ -n "$LV" ] && [ "$(printf '%s\n%s\n' "$LV" "$MIN" | sort -V | tail -1)" = "$MIN" ] || { echo "🔴 着色器库 ${f} 的目标系统是 macOS ${LV:-读不到},高于包声明的最低系统 ${MIN}"; exit 3; } +done ) || exit 3; fi # 自检:程序本体里记的最低系统版本要与 Info.plist 写的相等(不等时老系统上双击只会得到一句「不能与此版本的 macOS 配合使用」);只许有 arm64 一个架构 # Self-check: the minimum system version recorded in the executable must equal the one written in Info.plist (if they differ, double-clicking on an older system only yields "cannot be used with this version of macOS"); only the single arm64 architecture is allowed BIN_MIN=$(otool -l "$APP/Contents/MacOS/D2RMobile" | awk '$1=="minos"{print $2; exit}'); PL_MIN=$(/usr/libexec/PlistBuddy -c "Print :LSMinimumSystemVersion" "$APP/Contents/Info.plist") [ -n "$BIN_MIN" ] && [ "$BIN_MIN" = "$PL_MIN" ] || { echo "🔴 最低系统版本对不上:程序本体 ${BIN_MIN:-读不到},Info.plist ${PL_MIN}"; exit 3; } ARCHS=$(lipo -archs "$APP/Contents/MacOS/D2RMobile"); [ "$ARCHS" = arm64 ] || { echo "🔴 程序本体的架构不是只有 arm64:${ARCHS}"; exit 3; } codesign --force -s - "$APP" > /dev/null 2>&1 || { echo "🔴 本地签名失败"; exit 3; } -echo "MACAPP ${APP}(版本 ${VER} 构建 ${BUILD},最低系统 macOS ${MIN},产物 $(basename "$P"),$(du -sh "$APP" | cut -f1)${LINK:+,不带派生物:只能在本机跑})" +echo "MACAPP ${APP}(${M3:+老接口版,}版本 ${VER} 构建 ${BUILD},最低系统 macOS ${MIN},产物 $(basename "$P"),$(du -sh "$APP" | cut -f1)${LINK:+,不带派生物:只能在本机跑})" diff --git a/dm/verify/accept.sh b/dm/verify/accept.sh index bc8102a..1a7ca89 100755 --- a/dm/verify/accept.sh +++ b/dm/verify/accept.sh @@ -46,7 +46,7 @@ echo $$ > "$LOCK/pid"; echo "$ME" > "$LOCK/owner"; trap 'rm -rf "$LOCK"' EXIT mkdir -p "${DM_ROOT:-$HOME/dm-work}/run/verify/dm/accept" L=$(mktemp -d "${DM_ROOT:-$HOME/dm-work}/run/verify/dm/accept/$(date +%m%d_%H%M%S)_${TREE}_$$.XXXXXX") || { echo "ACCEPT RED 无法创建结果目录"; exit 1; } T0=$SECONDS -SKIP=""; SCOPE="全量" +SKIP=""; SCOPE="全量"; M3GATE=1 # M3GATE:老接口版(图形后端 DM_NVN_M3=1)的画面闸门跑不跑,见 ⑪ | M3GATE: whether the picture gate of the older-API build (graphics backend DM_NVN_M3=1) runs, see step 11 if [ "${ACCEPT_ALL:-0}" != 1 ]; then ROOT=$(git -C "$HERE" rev-parse --show-toplevel 2>/dev/null); MB=$(git -C "$HERE" merge-base HEAD main 2>/dev/null) CH=""; [ -n "$ROOT" ] && [ -n "$MB" ] && CH=$( { git -C "$ROOT" diff --name-only --no-renames "$MB" HEAD; git -C "$ROOT" status --porcelain --no-renames | cut -c4-; } 2>/dev/null | sort -u | grep -v '^$') # --no-renames:改名按「删旧 + 加新」两条路径列,旧路径在别的目录时不会被漏掉 | --no-renames: a rename is listed as two paths, "delete old + add new", so the old path is not missed when it is in another directory @@ -62,7 +62,10 @@ if [ "${ACCEPT_ALL:-0}" != 1 ]; then elif ! printf '%s\n' "$CH" | grep -qvE '^(dm/gfx/|dm/ios/|docs/)|\.md$'; then SKIP="1 2 5 6 7 9"; SCOPE="改动只在 dm/gfx(及 dm/ios、文档)"; fi fi fi -echo "SCOPE ${SCOPE}$([ -n "$SKIP" ] && echo ";跳过项序号 ${SKIP}(ACCEPT_ALL=1 强制全量)")" +# ⑪ 老接口版画面闸门只在改动碰到图形层或宿主的图形 / 前端 / 构建文件时跑(动图形的人两条路都得验,别的线不多付这一分钟);读不出改动清单时照跑 +# The older-API picture gate (step 11) runs only when the change touches the graphics layer or the host's graphics / front-end / build files (whoever changes graphics must verify both paths, and other work does not pay this extra minute); when the list of changes cannot be read it runs anyway +if [ "${ACCEPT_ALL:-0}" != 1 ] && [ -n "${CH:-}" ] && ! printf '%s\n' "$CH" | grep -qE '^dm/gfx/|^dm/host/(front|app_mac|touch_mac|memstat)[^/]*$|^dm/host/Makefile$|^dm/verify/(shotgate|hostshot|accept)'; then M3GATE=0; fi +echo "SCOPE ${SCOPE}$([ -n "$SKIP" ] && echo ";跳过项序号 ${SKIP}(ACCEPT_ALL=1 强制全量)");老接口版画面闸门 $([ $M3GATE = 1 ] && echo 跑 || echo 本次改动不涉及,跳过)" [ "${ACCEPT_SCOPE_ONLY:-0}" = 1 ] && exit 0 # 并行子项都调用增量make;先在锁内只构建一次,避免冷树多个链接器争写同一个dmhost/dSYM。 # The parallel sub-items all invoke an incremental make; build once first inside the lock, so that on a cold tree several linkers do not compete to write the same dmhost/dSYM. @@ -192,13 +195,24 @@ item 9 "⑨ 功能用例 touchchain" "自动收集 script.txt + assert.py 用例 PAGES=() [ "$MODE" = fast ] && PAGES=(camp_e stash wild charselect skilltree) PAGE_NAMES=${PAGES[*]:-$(cd "$HERE/shotgate_pages" && ls *.json | sed 's/\.json$//' | tr '\n' ' ')} -item 3 "③ 画面闸门 shotgate ${MODE}(${PAGE_NAMES})" "每页对真值绿(结构 / 非黑 / 网格 / 命名区域 / 应有元素 / 宿主日志无【红】)" shotgate.log 'SHOTGATE_ALL' 1 "$HERE/shotgate.sh" "$OUT" ${PAGES[@]+"${PAGES[@]}"} & +# ⑪ 老接口版画面闸门:同一批页面用老接口版宿主(make dmhost_m3)再过一遍。排在 ③ 后面串着跑,不和 ③ 抢宿主 +# Step 11, older-API picture gate: the same set of pages is run once more with the older-API host (make dmhost_m3). It runs serially after step 3 and does not compete with it for hosts +m3_shotgate() { + local name="⑪ 老接口版画面闸门 shotgate ${MODE}(DM_NVN_M3=1,${PAGE_NAMES})" want="老接口版宿主每页对真值绿" + if [ $M3GATE != 1 ]; then printf '0\n| %s | %s | ⏭ 老接口版画面闸门:本次改动不涉及,跳过 | 0 秒 |\n' "$name" "$want" > "$L/11.row"; echo "⏭ ${name}(老接口版画面闸门:本次改动不涉及,跳过)"; return 0; fi + case " $SKIP " in *" 3 "*) printf '0\n| %s | %s | ⏭ 跳过:%s | 0 秒 |\n' "$name" "$want" "$SCOPE" > "$L/11.row"; echo "⏭ ${name}(跳过:${SCOPE})"; return 0;; esac + local s=$SECONDS rc=0 + { make -s -C "$HERE/../host" dmhost_m3 && DM_HOST="$HERE/../host/dmhost_m3" "$HERE/shotgate.sh" "$OUT" ${PAGES[@]+"${PAGES[@]}"}; } > "$L/shotgate_m3.log" 2>&1 || rc=1 + local got=$(grep -E 'SHOTGATE_ALL' "$L/shotgate_m3.log" | tail -1) mark; [ $rc = 0 ] && mark="✅" || mark="🔴" + printf '%s\n| %s | %s | %s %s | %s 秒 |\n' "$rc" "$name" "$want" "$mark" "${got:-(无读数行,见 shotgate_m3.log)}" "$((SECONDS - s))" > "$L/11.row"; echo "$mark ${name}($((SECONDS - s)) 秒)" +} +{ item 3 "③ 画面闸门 shotgate ${MODE}(${PAGE_NAMES})" "每页对真值绿(结构 / 非黑 / 网格 / 命名区域 / 应有元素 / 宿主日志无【红】)" shotgate.log 'SHOTGATE_ALL' 1 "$HERE/shotgate.sh" "$OUT" ${PAGES[@]+"${PAGES[@]}"}; m3_shotgate; } & unit_tests() { # ④ 宿主与图形单测(E:SHOT 合入后 gfx 单测链接失败,accept 却绿):任何失败或构建 / 链接错误即红 | (4) host and graphics unit tests (after E:SHOT was merged the gfx unit test failed to link, yet accept was green): any failure or build / link error is a failure local rc=0 "${DM_ROOT:-$HOME/dm-work}/build/cache/dm/venv/bin/python" "$HERE/ryu/test_selfcmp.py" > "$L/unit_selfcmp.log" 2>&1 && echo "UNIT selfcmp 通过" || { echo "UNIT selfcmp 失败(见 unit_selfcmp.log)"; rc=1; } "${DM_ROOT:-$HOME/dm-work}/build/cache/dm/venv/bin/python" "$HERE/ryu/test_plan.py" > "$L/unit_plan.log" 2>&1 && echo "UNIT plan 通过" || { echo "UNIT plan 失败(见 unit_plan.log)"; rc=1; } make -j8 -C "$HERE/../host/tests" run > "$L/unit_host.log" 2>&1 && echo "UNIT host 通过" || { echo "UNIT host 失败:$(grep -m1 -iE 'error|fail|失败|红' "$L/unit_host.log" | cut -c1-140)"; rc=1; } - make -j8 -C "$HERE/../gfx/tests" run > "$L/unit_gfx.log" 2>&1 && echo "UNIT gfx 通过" || { echo "UNIT gfx 失败:$(grep -m1 -iE 'error|fail|失败|红|undefined' "$L/unit_gfx.log" | cut -c1-140)"; rc=1; } + make -j8 -C "$HERE/../gfx/tests" run > "$L/unit_gfx.log" 2>&1 && make -j8 -C "$HERE/../gfx/tests" run-m3 >> "$L/unit_gfx.log" 2>&1 && echo "UNIT gfx 通过" || { echo "UNIT gfx 失败:$(grep -m1 -iE 'error|fail|失败|红|undefined' "$L/unit_gfx.log" | cut -c1-140)"; rc=1; } # iOS 触摸层单测(这一套从没接进闸门,回城钮改版后红了一天没人看见) # iOS touch layer unit tests (this set was never wired into the gate check, and after the town portal button redesign it was red for a day without anyone seeing it) make -C "$HERE/../ios/tests" test > "$L/unit_ios.log" 2>&1 && echo "UNIT ios 通过" || { echo "UNIT ios 失败:$(grep -m1 -E 'FAIL|Error|error' "$L/unit_ios.log" | cut -c1-140)"; rc=1; } @@ -229,7 +243,7 @@ item 10 "⑩ 局内切运行模式 opmode" "切换前已进局;取走通知 30 [ "$MODE" = full ] && item 6 "⑥ 存档事务 save_txn_regress" "4/4 注入命中;已提交文件同期望版;校验和自洽;残缺工作目录 / 拒绝日志负对照成立" save_txn.log '^✓|^✗|^结论|^SAVE_TXN' 6 bash "$HERE/../tools/save_txn_regress.sh" "$OUT" & wait allrc=0; rows=() -ITEMS=(0 1 2 3 4 5 7 8 9 10); [ "$MODE" = full ] && ITEMS+=(6) +ITEMS=(0 1 2 3 11 4 5 7 8 9 10); [ "$MODE" = full ] && ITEMS+=(6) for k in "${ITEMS[@]}"; do { read -r rc; read -r row; } < "$L/$k.row"; [ "$rc" = 0 ] || allrc=1; rows+=("$row"); done [ "$allrc" = 0 ] || echo "ACCEPT $MODE 红;本目录保留,不删不覆盖" > "$L/KEEP" echo; echo "| 项 | 期望 | 真结果 | 用时 |"; echo "|---|---|---|---|"; printf '%s\n' "${rows[@]}" diff --git a/dm/verify/test_accept.py b/dm/verify/test_accept.py index 9762b7f..55e8c49 100644 --- a/dm/verify/test_accept.py +++ b/dm/verify/test_accept.py @@ -45,13 +45,14 @@ class AcceptTests(unittest.TestCase): 'echo txn >> "$TRACE"; echo "结论:存档事务回归 4/4 绿"; exit "${TXN_RC:-0}"\n') for tree in ['host', 'gfx']: p = self.root / f'dm/{tree}/tests'; p.mkdir(parents=True) - (p / 'Makefile').write_text('run:\n\t@echo OK\n') + (p / 'Makefile').write_text('run:\n\t@echo OK\nrun-m3:\n\t@echo OK\n') # run-m3:图形层单测的老接口版那一遍(accept ④ 两遍都跑) | run-m3: the older-API pass of the graphics-layer unit tests (accept step 4 runs both passes) p = self.root / 'dm/ios/tests'; p.mkdir(parents=True) # iOS 触摸层单测(accept ④ 第六套)的替身 | Stand-in for the iOS touch layer unit tests (accept ④, sixth suite) (p / 'Makefile').write_text('test:\n\t@echo OK\n') (self.root / 'dm/host/Makefile').write_text( 'all:\n\t@test "$${HOST_BUILD_RC:-0}" = 0\n' '\t@echo built >> "$$HOME/build-count"\n' - '\t@touch "$$HOME/host-built"\n') + '\t@touch "$$HOME/host-built"\n' + 'dmhost_m3:\n\t@true\n') # 老接口版宿主(accept ⑪ 用) | older-API host (used by accept step 11) for p in ['camp_e', 'stash', 'wild', 'charselect', 'skilltree', 'npc']: (self.verify / f'shotgate_pages/{p}.json').write_text('{}') @@ -64,10 +65,27 @@ class AcceptTests(unittest.TestCase): return subprocess.run(['bash', str(self.verify / 'accept.sh'), *args], env=self.env, capture_output=True, text=True, errors='replace', timeout=10) + def test_m3_shotgate_runs_only_when_graphics_touched(self): + # ⑪ 老接口版画面闸门按改动范围触发:碰图形层 / 宿主图形前端文件就跑,碰不到就跳过并写明(期望值按规则手写) + # The older-API picture gate (step 11) is triggered by the scope of the change: it runs when graphics-layer / host graphics and front-end files are touched, and is skipped with a note otherwise (expected values written by hand from the rule) + for ch, want in (('dm/gfx/nvn/nvn_mtl.m', '老接口版画面闸门 跑'), ('dm/host/front_mac.m dm/host/dm_rift.c', '老接口版画面闸门 跑'), + ('dm/host/Makefile', '老接口版画面闸门 跑'), ('dm/host/dm_rift.c dm/host/hle_fs.c', '老接口版画面闸门 本次改动不涉及,跳过'), + ('dm/ios/Sources/main.m docs/x.md', '老接口版画面闸门 本次改动不涉及,跳过')): + r = self.run_accept('/fixture/out', ACCEPT_SCOPE_CH=ch, ACCEPT_SCOPE_ONLY='1') + self.assertIn(want, r.stdout, ch) + + def test_m3_shotgate_row_present(self): + # 夹具不是 git 仓库、读不出改动清单 ⇒ 照跑:表里有 ⑪ 这一行,画面闸门脚本被调了两次(缺省宿主一次、老接口版宿主一次) + # The fixture is not a git repository and no list of changes can be read => it runs anyway: the table has the step 11 row, and the picture-gate script is called twice (once with the default host, once with the older-API host) + r = self.run_accept('/fixture/out') + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn('⑪ 老接口版画面闸门', r.stdout) + self.assertEqual(self.trace.read_text().count('shot:'), 2, self.trace.read_text()) + def test_fast_has_only_five_pages_and_no_transaction(self): r = self.run_accept('--fast', '/fixture/out') self.assertEqual(r.returncode, 0, r.stdout + r.stderr) - self.assertEqual(self.trace.read_text().strip(), 'shot:/fixture/out camp_e stash wild charselect skilltree') + self.assertEqual(self.trace.read_text().strip(), '\n'.join(['shot:/fixture/out camp_e stash wild charselect skilltree'] * 2)) # 两次:③ 缺省宿主、⑪ 老接口版宿主(夹具读不出改动清单 ⇒ 照跑),页面相同 | twice: step 3 with the default host, step 11 with the older-API host (the fixture cannot read a list of changes => it runs anyway), same pages def test_full_runs_transaction_and_propagates_its_failure(self): r = self.run_accept('--full', '/fixture/out', TXN_RC='1') diff --git a/docs/LEGACY_DEVICES.md b/docs/LEGACY_DEVICES.md index 78f4006..bac5ff6 100644 --- a/docs/LEGACY_DEVICES.md +++ b/docs/LEGACY_DEVICES.md @@ -8,7 +8,7 @@ The iPhone 14 family, iPhone 15 / 15 Plus and earlier models can play; they just Almost all of the game's textures use BC compression. Apple GPUs support that format only from the A17 Pro (iPhone 15 Pro) on; earlier chips cannot read it. The answer is to convert those textures offline, on a computer, into ASTC, which these devices do support — the picture is the same picture. Textures are game content, so we cannot provide this pack; it can only be generated on your own computer from your own game files. -**Which devices need it**: the App decides this itself at launch, so there is no table to consult. A device that needs it shows "Supplementary Pack Required"; if it shows "Device Not Supported" instead, the App was built without the part that goes with the pack — rebuild it as in step 4 below. +**Which devices need it**: the App decides this itself at launch, so there is no table to consult. A device that needs it shows "Supplementary Pack Required"; if it shows "One More Step for This Device" (older versions say "Device Not Supported") instead, the App was built without the part that goes with the pack — rebuild it as in step 4 below. ## What you need @@ -51,7 +51,7 @@ Afterwards `$D/pack` contains: cd dm/ios && DM_ASTC_PACK="$D/pack" ./run.sh build ``` - An App built without this variable only says "Device Not Supported" on older devices. + An App built without this variable only says "One More Step for This Device" (older versions say "Device Not Supported") on older devices. 5. **Install** as usual (`./run.sh install` or Xcode). @@ -72,4 +72,4 @@ Afterwards `$D/pack` contains: ## In practice -The lowest device we measured is the iPhone 14 Pro Max (A16, 6 GB of RAM), running at 60 fps. During internal testing this route was completed by users on A16 devices. +The lowest device we measured is the iPhone 14 Pro Max (A16, 6 GB of RAM), running at 60 fps. During internal testing this route was completed by users on A16 devices; the oldest device our test players actually play on is the iPhone 13 Pro Max (A15, 6 GB of RAM), in the 30 fps mode. diff --git a/docs/LEGACY_DEVICES.zh-CN.md b/docs/LEGACY_DEVICES.zh-CN.md index 6567e43..61ac340 100644 --- a/docs/LEGACY_DEVICES.zh-CN.md +++ b/docs/LEGACY_DEVICES.zh-CN.md @@ -8,7 +8,7 @@ iPhone 14 系列、iPhone 15 / 15 Plus 以及更早的机型可以玩,只是 游戏的贴图绝大多数用的是 BC 压缩格式。苹果的显卡从 A17 Pro(iPhone 15 Pro)起才支持这种格式,更早的芯片不认。做法是在电脑上把这些贴图离线转成这些机型支持的 ASTC 格式,画面是同一份画面。贴图是游戏内容,所以这个包不能由我们提供,只能用你自己的游戏文件在你自己的电脑上生成。 -**哪些机型需要**:App 启动时自己会判断,不用查表。需要的机型会弹「需要老机型补充包」(补充包就是这里说的贴图包);如果弹的是「暂不支持本机型」,说明这个 App 构建时没有带上贴图包的配套部分——照下面第 4 步重新构建即可。 +**哪些机型需要**:App 启动时自己会判断,不用查表。需要的机型会弹「需要老机型补充包」(补充包就是这里说的贴图包);如果弹的是「这台设备要多做一步」(旧版本显示的是「暂不支持本机型」),说明这个 App 构建时没有带上贴图包的配套部分——照下面第 4 步重新构建即可。 ## 需要什么 @@ -51,7 +51,7 @@ python3 dm/tools/astc_pack.py finalize "$D/pack" # 3 收尾: cd dm/ios && DM_ASTC_PACK="$D/pack" ./run.sh build ``` - 不带这个变量构建出来的 App,在老机型上只会提示「暂不支持本机型」。 + 不带这个变量构建出来的 App,在老机型上只会提示「这台设备要多做一步」(旧版本显示的是「暂不支持本机型」)。 5. **装机**,和平常一样(`./run.sh install` 或用 Xcode)。 @@ -72,4 +72,4 @@ python3 dm/tools/astc_pack.py finalize "$D/pack" # 3 收尾: ## 实际情况 -最低实测机型是 iPhone 14 Pro Max(A16,6 GB 内存),60 帧运行。这条路在内测阶段由 A16 机型的用户走通过。 +最低实测机型是 iPhone 14 Pro Max(A16,6 GB 内存),60 帧运行。这条路在内测阶段由 A16 机型的用户走通过;内测玩家实际在玩的最老机型是 iPhone 13 Pro Max(A15,6 GB 内存),30 帧档。 diff --git a/docs/MAC.md b/docs/MAC.md index 1a3e268..2da8d7b 100644 --- a/docs/MAC.md +++ b/docs/MAC.md @@ -1,70 +1,137 @@ -# Playing on a Mac (macOS App, first version) +# Playing on a Mac (macOS App) -中文:[MAC.zh-CN.md](MAC.zh-CN.md) +简体中文: [MAC.zh-CN.md](MAC.zh-CN.md) -On an Apple silicon Mac running **macOS 26 or later**, this project can be built into a native macOS App, `D2R Mobile.app`: double-click to start, with keyboard, mouse and gamepad all working. It runs the same game and the same features we added (rifts, the trove, the chronicle, the Custom page and so on), using the original game's gamepad UI. +On an Apple silicon Mac this project can be built into a native macOS App, `D2R Mobile.app`: double-click to start, with keyboard, mouse and gamepad all working. It runs the same game and the same features we added (rifts, the trove, the chronicle, the Custom page and so on), using the original's gamepad interface. -**Up front: nobody has actually sat down and played this version yet.** Keyboard keys, a physical gamepad, the resource-folder dialog, ⌘Q and menu clicks, and how it feels in the hand — none of these five has been operated by a person. Everything described as "verified" below was run unattended: keys injected by a test script, the mouse through a test entry point, quit / full screen / window resizing through test switches. If you are among the first to try it, please open an issue and tell us how it went. +**Up front: these five things have not been operated by a person yet** — keyboard keys, a physical gamepad, the resource-folder dialog, ⌘Q and menu clicks, and how it feels in the hand. Where this page says "verified", it was run unattended: keys injected by a test script, the mouse through a test entry, quitting, full screen and resizing through test switches. If you try it, please open an Issue and tell us how it went. ## Requirements -Apple silicon and macOS 26 or later. The graphics side is built entirely on a graphics interface that only exists from macOS 26 on (Metal 4); on earlier systems it neither compiles nor opens (the system says the App cannot be used with this version of macOS). The iPhone / iPad version requires iOS 26 for the same reason. +Apple silicon. Two tiers by system: + +| Your system | How to build | Output | +|---|---|---| +| macOS 26 or later | Default: `dm/tools/mac_app.sh` | `D2R Mobile.app` | +| macOS 15 – 25 | Older-API build: `DM_MAC_M3=1 dm/tools/mac_app.sh` | `D2R Mobile M3.app` | + +The default build puts the graphics side on a graphics interface that only exists from macOS 26 on (Metal 4); on earlier systems it does not open (the system says the App cannot be used with this version of macOS). The older-API build is the same source and the same game with the graphics side using interfaces that older systems also have; its minimum is macOS 15.0. Details: [OLDER_SYSTEMS.md](OLDER_SYSTEMS.md). ## Build -The prerequisites are the same as for the iOS route: your game files in place and `./setup.sh` finished (see "Getting started" on the front page). Then: +The prerequisites are the same as for iOS: game files in place and `./setup.sh` finished (see "Getting started" in the README). Then: ```bash source ~/dm-work/build/cache/dm/venv/bin/activate -dm/tools/mac_app.sh +dm/tools/mac_app.sh # macOS 26 or later +DM_MAC_M3=1 dm/tools/mac_app.sh # macOS 15 – 25 ``` -It takes a dozen seconds or so and produces `~/dm-work/out/macapp/D2R Mobile.app` (about 3 MB). To put it elsewhere: `dm/tools/mac_app.sh `. +The default build takes ten-odd seconds and produces `~/dm-work/out/macapp/D2R Mobile.app` (about 3 MB). The older-API build recompiles the shader libraries for macOS 15 the first time, which adds about 3–4 minutes, and produces `D2R Mobile M3.app`; it has its own save and log directories (with M3 in the name), so it can sit next to the default App. To put the output elsewhere, add an output directory after the command. -The App contains only our own program. The rewritten game program, the shader library and the UI overlay are made from your game files; they stay in your workspace (`~/dm-work`) and the App only records where they are — so **this App runs only on the Mac that built it**. Please do not copy it to anyone else, and do not delete the workspace. It is signed with a local ad-hoc signature: no developer account and no device registration are needed. +The App contains only our own program. The rewritten game program, the shader libraries and the UI overlay are all made from your game files; they stay in your working directory (`~/dm-work`) and the App only records where they are — so **the App runs only on the Mac that built it**. Please do not copy it to anyone, and do not delete or move the working directory (the shader libraries recompiled for the older-API build are in the output directory). Signing is local ad-hoc signing: no developer account and no device registration. + +Version and build number can be set: `DM_MAC_VERSION` (default 1.0) and `DM_MAC_BUILD` (default: the current month-day-hour-minute). ## First launch -Double-click `D2R Mobile.app`. The first launch asks you to choose the **game resource folder**: pick `~/dm-work/data/switch/3.3.94012/Update` (or the `RomFS` inside it); it must contain a `data` folder. A wrong choice is explained and you can pick again; a right one is remembered and not asked for again. +Double-click the App. The first launch asks you to choose the **game resource folder**: pick `~/dm-work/data/switch/3.3.94012/Update` (or the `RomFS` inside it); it must contain a `data` folder. A wrong choice is explained and you are asked again; a correct one is remembered. -The key mapping is then shown once; afterwards it is always available under Help in the menu bar. +A key reference is then shown once; afterwards it is under Help in the menu bar. -## Where things are - -- Saves: `~/Library/Application Support/D2R Mobile/save` -- Log: `~/Library/Logs/D2R Mobile/host.log` (the previous run is `host.prev.log`). Please attach it when reporting a problem. +Language: the first launch follows the system language (Chinese systems start in Chinese, everything else in English). To change it: Options → Custom, the language switch in the first row → Accept All → close and reopen the App. ## Keyboard ↔ gamepad -Button prompts on screen show gamepad letters; the keyboard keys are: +Button prompts on screen show gamepad letters. Where the screen says "A", "B", "X" or "Y", the key to press is **not** the letter of the same name on the keyboard (the keyboard's A walks left) but the one in the right-hand column: -| Gamepad | Keyboard | +| What you want / gamepad button | Keyboard | |---|---| +| Confirm (A) | Space or J | +| Back (B) | Esc or K (in game with no panel open, Esc opens the inventory group of pages) | +| Return | confirm; acts as + when the bottom of the page shows a "+" hint (such as "Accept" after naming); on the main menu Return = enter the game | +| + (menu / new character) | the = key | +| − (map) | Tab | | Left stick (move) | W A S D | | D-pad | Arrow keys | -| A confirm / B back / X / Y | J / K / U / I | +| X / Y | U / I | | L / R | Q / E | | ZL / ZR | Z / C | | Left stick press / right stick press | F / G | -| + (menu) / − (map) | Return / Tab | -Mouse: left click on a target or on the UI, right click = B (back / close panel), wheel scrolls lists. A gamepad works as soon as it is connected, alongside the keyboard. +**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. -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; the game picture stays 16:9 and centred. + +## Mouse + +What it can do now: + +- **Click a target in the world** (monster, NPC, chest, waypoint, item on the ground): the character walks over and interacts. +- **Click the bottom row**: a skill icon = use that skill (the same as pressing the key shown under it), a potion cell = drink it, the middle button = open the inventory group of pages, the run / walk button = toggle. +- **Click the interface**: buttons, checkboxes and tabs in panels (including the in-page tabs of the skill tree), the pause menu, the settings pages, "Start" on the rift level-selection page. +- **Click a key hint at the bottom**: clicking an entry presses that key. +- **Click a figure when creating a character**: the class you click is selected. +- **Top-right minimap**: opens automatically on entering a game; Tab toggles it; clicking the area name at its top switches to the full-screen map, and another click returns. +- Right click = back (B); the wheel scrolls lists. + +What it cannot do yet: + +- **Clicking empty ground does not walk.** Move with W A S D or a gamepad stick. +- **Key caps on screen are still gamepad letters**; translate them with the table above. +- **Long press / double click / drag / buying on items do not take the mouse.** Use the keyboard or gamepad cursor: move the cursor onto the item with W A S D and press the key shown in the bottom bar. For example, buying from a vendor: cursor onto the goods (the bottom bar shows "A Buy") → press Space (or J) → press it again in the confirmation. +- "Hold …" key hints need longer than a click, so hold the key on the keyboard; a hint with two key caps is not recognised. +- The life orb, mana orb and experience bar do nothing when clicked. + +## Saves, logs and iCloud + +- Saves: `~/Library/Application Support/D2R Mobile/save` +- Log: `~/Library/Logs/D2R Mobile/host.log` (the previous run is `host.prev.log`). Please attach it when reporting a problem. +- 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. + +### Importing saves from an iPhone / iPad + +Importing is a one-time manual copy: afterwards each side goes its own way and progress diverges; to bring them together later you copy the whole thing again and let one side overwrite the other. + +**1. Find the save on the iPhone / iPad** + +- Quit the game completely on the phone / tablet first (swipe it away in the app switcher). +- Open the built-in Files app → "On My iPhone" (or "On My iPad") → "D2R Mobile" → the `save` folder inside is the save. + +**2. Copy the whole `save` folder, do not pick files** + +It holds one folder per character (folder name = character name), a few shared-stash files and a `Settings` folder (game settings including the interface language — after copying, the Mac's game settings become the phone's). The data of the features we added (the extra personal stash pages, the pouch, rift records, the chronicle vault and so on) is in this folder too. The switches on the Custom page are not in it; each device keeps its own. + +AirDrop, a cable (the Files tab in Finder) or iCloud Drive all work for getting it to the Mac. + +**3. Put it on the Mac** + +1. Quit the game on the Mac completely (⌘Q). +2. In Finder press ⇧⌘G, enter `~/Library/Application Support/D2R Mobile` and press Return. (This folder exists only after the game has been started once.) +3. **Back up first**: rename the existing `save` folder there (for example `save backup`); do not delete it. +4. Put the `save` folder from the phone here. Correct looks like this: directly under `D2R Mobile/save/` are the character folders, `Settings` and a few `.d2i` files — no extra level (not `save/save/…`). +5. If `save.work` or `save.new` sit next to it, leave them; the game discards and rebuilds them at launch. +6. Open the game; the phone's characters should appear on the main menu. + +Got it wrong or want to go back: quit the game, take the `save` you just put in away, and rename the one from step 3 back to `save`. + +The other direction (Mac → iPhone / iPad) uses the same files and mirrors the steps: quit the game on the Mac, copy the Mac's `save` into the game's folder in Files on the phone, replacing the one there (rename the phone's original first as a backup). Keep the App on both sides as current as you can. + +Verified: on a Mac, a save placed in the save directory laid out as in step 4 shows its characters on the main menu after launch and can enter a game (one unattended run). The whole route from a real iPhone / iPad through the Files app onto the Mac, the other direction, and hardcore characters have not been operated by a person. ## Quitting and saving -Closing the window, ⌘Q and Quit in the menu all save first and then quit, in any state: in game, with the pause menu open, with a panel open, in a loading screen and with the rift panel open were each verified once. It waits at most 3 seconds; if the save has not completed by then, the log records "quit without saving". +Closing the window, ⌘Q and Quit in the menu all save before quitting, in any state: in game, with the pause menu open, with a panel open, on the loading screen and with the rift panel open were each verified with one run. It waits at most 3 seconds; if saving has not finished by then, the log records a line saying it quit without saving. -## How this version is operated +After a forced quit or a crash, the system's "reopen windows?" dialog no longer comes up to block the game window on the next launch. -- **Move** with W A S D or the gamepad stick. A mouse click on a monster, NPC or object walks over and interacts; a click on empty ground does not move. -- **Items** — sorting, equipping, buying and selling — are handled with the keyboard or gamepad cursor: move the cursor onto the item with W A S D and press the key shown in the bottom bar. For example, buying from a vendor: cursor onto the goods (the bottom bar shows "A Buy") → press J → press J again in the confirmation. -- **The UI** is the original gamepad UI, and the pages we added (the Custom page, the trove, the chronicle, rift floor selection and so on) are all in it. +## Known shortcomings -## Not in this version yet - -- Mouse click-to-move on the ground, and long-press / double-click / drag-and-drop on items with the mouse. -- The free town portal on the empty ZR slot of the gamepad. -- The rift task list on the left. -- iCloud save sync, update checks, sharing the diagnostic log. +- The five things from the top have not been operated by a person: keyboard keys, a physical gamepad, the resource-folder dialog, ⌘Q and menu clicks, how it feels in the hand. The key mapping was written from the key-code table. +- Clicking empty ground does not walk; key caps on screen are still gamepad letters; long press / double click / drag / buying on items do not take the mouse (see "Mouse" above). +- The free town portal on ZR + Space of a gamepad is not there. +- The quest bar on the left in rifts is not there. +- An App you build yourself has no iCloud save sync; there are no update checks and no sharing of the diagnostic log. +- The older-API build was played on macOS 15 by one player in our test group (Mac mini M4, macOS 15.7, using a package built elsewhere); building it from this repository on a Mac running macOS 15 has not been operated by a person. diff --git a/docs/MAC.zh-CN.md b/docs/MAC.zh-CN.md index a1a4aee..b33308e 100644 --- a/docs/MAC.zh-CN.md +++ b/docs/MAC.zh-CN.md @@ -1,14 +1,21 @@ -# 在 Mac 上玩(macOS App,第一版) +# 在 Mac 上玩(macOS App) English: [MAC.md](MAC.md) -Apple 芯片的 Mac(**macOS 26 及以上**)可以把本项目构建成一个原生的 macOS App:`D2R Mobile.app`,双击启动,键盘、鼠标、手柄都能用。它跑的是同一份游戏、同一套我们加的功能(秘境、珍宝匣、编年史、自定义页等),界面用的是原版的手柄版界面。 +Apple 芯片的 Mac 可以把本项目构建成一个原生的 macOS App:`D2R Mobile.app`,双击启动,键盘、鼠标、手柄都能用。它跑的是同一份游戏、同一套我们加的功能(秘境、珍宝匣、编年史、自定义页等),界面用的是原版的手柄版界面。 -**先说在前面:这一版还没有人真的坐下来玩过。**键盘按键、实体手柄、选资源文件夹的对话框、⌘Q 与菜单点击、真人手感——这五项都没有人实际操作过。下面写「验过」的,都是无人值守跑出来的:按键用测试脚本注入,鼠标用测试入口注入,退出、全屏、改窗口大小用测试开关。欢迎第一批试用的人把结果开 Issue 告诉我们。 +**先说在前面:下面这五项还未经真人操作**——键盘按键、实体手柄、选资源文件夹的对话框、⌘Q 与菜单点击、真人手感。下面写「验过」的,都是无人值守跑出来的:按键用测试脚本注入,鼠标用测试入口注入,退出、全屏、改窗口大小用测试开关。你试过的话,请开 Issue 把结果告诉我们。 ## 系统要求 -Apple 芯片,macOS 26 及以上。图形部分整个建在 macOS 26 才有的图形接口(Metal 4)上,更早的系统上编不过、也打不开(系统会提示这个 App 不能与当前版本的 macOS 配合使用)。iPhone / iPad 版要求 iOS 26 是同一个原因。 +Apple 芯片。按系统分两档: + +| 你的系统 | 用哪种出法 | 产出 | +|---|---|---| +| macOS 26 及以上 | 缺省:`dm/tools/mac_app.sh` | `D2R Mobile.app` | +| macOS 15 – 25 | 老接口版:`DM_MAC_M3=1 dm/tools/mac_app.sh` | `D2R Mobile M3.app` | + +缺省的构建把图形部分建在 macOS 26 才有的图形接口(Metal 4)上,更早的系统上打不开(系统会提示这个 App 不能与当前版本的 macOS 配合使用)。老接口版是同一份源码、同一个游戏,图形部分改用老系统也有的接口,最低 macOS 15.0;细节见 [OLDER_SYSTEMS.zh-CN.md](OLDER_SYSTEMS.zh-CN.md)。 ## 构建 @@ -16,55 +23,115 @@ Apple 芯片,macOS 26 及以上。图形部分整个建在 macOS 26 才有的 ```bash source ~/dm-work/build/cache/dm/venv/bin/activate -dm/tools/mac_app.sh +dm/tools/mac_app.sh # macOS 26 及以上 +DM_MAC_M3=1 dm/tools/mac_app.sh # macOS 15 – 25 ``` -约十几秒,产出 `~/dm-work/out/macapp/D2R Mobile.app`(约 3 MB)。想放到别处:`dm/tools/mac_app.sh <输出目录>`。 +缺省出法约十几秒,产出 `~/dm-work/out/macapp/D2R Mobile.app`(约 3 MB)。老接口版第一次要把着色器库按 macOS 15 重编一份,多花约 3–4 分钟,产出 `D2R Mobile M3.app`;它有自己的存档与日志目录(名字里带 M3),可以和缺省的 App 并存。想放到别处:命令后面跟输出目录。 -这个 App 里只有我们自己的程序。改写后的游戏程序、着色器库、界面覆盖层都是从你的游戏文件做出来的,它们留在你的工作区(`~/dm-work`)里,App 只记着它们的位置——所以**这个 App 只能在构建它的这台 Mac 上跑**,请不要拷给别人,也不要删掉工作区。签名用的是本机临时签名,不需要开发者账号,也不需要登记设备。 +这个 App 里只有我们自己的程序。改写后的游戏程序、着色器库、界面覆盖层都是从你的游戏文件做出来的,它们留在你的工作区(`~/dm-work`)里,App 只记着它们的位置——所以**这个 App 只能在构建它的这台 Mac 上跑**,请不要拷给别人,也不要删掉或挪动工作区(老接口版重编的着色器库就在输出目录里)。签名用的是本机临时签名,不需要开发者账号,也不需要登记设备。 + +版本号与构建号可以指定:`DM_MAC_VERSION`(缺省 1.0)、`DM_MAC_BUILD`(缺省取当前的月日时分)。 ## 第一次打开 -双击 `D2R Mobile.app`。第一次启动会请你选**游戏资源文件夹**:选 `~/dm-work/data/switch/3.3.94012/Update`(或它里面的 `RomFS`)即可,里面要有 `data` 文件夹。选错了会说明原因并让你重选;选对之后会记住,下次不再问。 +双击 App。第一次启动会请你选**游戏资源文件夹**:选 `~/dm-work/data/switch/3.3.94012/Update`(或它里面的 `RomFS`)即可,里面要有 `data` 文件夹。选错了会说明原因并让你重选;选对之后会记住,下次不再问。 接着会弹一次键位对照表,之后在菜单栏「帮助」里随时能看。 -## 东西放在哪 - -- 存档:`~/Library/Application Support/D2R Mobile/save` -- 日志:`~/Library/Logs/D2R Mobile/host.log`(上一次运行的是 `host.prev.log`)。报问题时请附上它。 +语言:首次启动跟系统语言(中文系统进中文,其余进英文)。想换:设置 →「自定义」页第一行的语言开关 → 全部接受 → 把 App 关掉重开。 ## 键盘 ↔ 手柄 -界面上的按键提示显示的是手柄字母,对应的键盘按键如下: +界面上的按键提示显示的是手柄字母。屏上写着「A」「B」「X」「Y」的地方,按的**不是**键盘上的同名字母(键盘的 A 是向左走),而是下表右边那一列: -| 手柄 | 键盘 | +| 要做的事 / 手柄键 | 键盘 | |---|---| +| 确认(A) | 空格 或 J | +| 返回(B) | Esc 或 K(局内没有面板开着时,Esc = 打开物品栏那组页面) | +| 回车 | 确认;页面底部有「+」提示时是 +(如起名之后的「接受」);主菜单上回车 = 进入游戏 | +| +(菜单 / 新角色) | = 键 | +| −(地图) | Tab | | 左摇杆(移动) | W A S D | | 十字键 | 方向键 | -| A 确认 / B 返回 / X / Y | J / K / U / I | +| X / Y | U / I | | L / R | Q / E | | ZL / ZR | Z / C | | 按左摇杆 / 按右摇杆 | F / G | -| +(菜单)/ −(地图) | 回车 / Tab | -鼠标:左键点目标或界面,右键 = B(返回 / 关面板),滚轮滚列表。接上手柄直接可用,与键盘并存。 +**建一个角色,从头到尾这样按**:主菜单按 `=`(或鼠标点「新角色」)→ 用方向键选职业再按回车(或直接点那个职业的人物)→ 模式页按回车或空格 → 起名页按回车弹出输入框,直接打字,回车 → 再按一次回车创建。 -菜单栏有「显示 → 全屏(⌃⌘F)」和「退出(⌘Q)」。窗口可以随意拉大小,游戏画面保持 16:9 居中。 +接上手柄直接可用,与键盘并存。菜单栏有「显示 → 全屏(⌃⌘F)」和「退出(⌘Q)」。窗口可以随意拉大小,游戏画面保持 16:9 居中。 + +## 鼠标 + +现在能做的: + +- **点世界里的目标**(怪、NPC、箱子、传送点、地上的物品):走过去交互。 +- **点底部那一排**:技能图标 = 放那个技能(等于按它下面标的键),药水格 = 喝那格药,中间的钮 = 打开物品栏那组页面,跑 / 走钮 = 切换。 +- **点界面**:面板里的按钮、勾选框、页签(含技能树页里的分页)、暂停菜单、设置页、秘境选层页的「开始」。 +- **点底部的按键提示**:点哪一条,等于按那个键。 +- **建角时点人物**:点哪个职业的人物就选哪个。 +- **右上角小地图**:进局自动打开,按 Tab 开 / 关;点它顶上的地名那一条 = 切到全屏地图,再点一下回来。 +- 右键 = 返回(B),滚轮 = 滚列表。 + +还不能的: + +- **点空地不会走**。移动用 W A S D 或手柄摇杆。 +- **屏上的键帽仍是手柄字母**,照上面的表换成键盘键。 +- **物品的长按 / 双击 / 拖放 / 购买不认鼠标**,用键盘或手柄的光标操作:W A S D 把光标移到物品上,按底栏提示的键。例如在商人处买东西:光标移到货物上(底栏出现「A 购买」)→ 按空格(或 J)→ 确认框里再按一次。 +- 「按住…」类的按键提示点一下不够长,用键盘按住;一条提示带两个键帽的不认。 +- 血球、魔球、经验条点了没有反应。 + +## 存档、日志与 iCloud + +- 存档:`~/Library/Application Support/D2R Mobile/save` +- 日志:`~/Library/Logs/D2R Mobile/host.log`(上一次运行的是 `host.prev.log`)。报问题时请附上它。 +- 老接口版(`D2R Mobile M3.app`)用的是名字里带 M3 的另一对目录。 + +**iCloud 存档同步:从本仓库自己构建的 App 没有。**程序里接了与 iPhone / iPad 相同的同步,但它需要 App 带着 iCloud 的签名权限;自己构建的 App 用的是本机临时签名,没有这项权限,所以存档只留在这台 Mac 上,日志里会记一行「iCloud 不可用…只用本地存档」,游戏照常。要把手机上的进度带过来,用下面的手工导入。 + +### 从 iPhone / iPad 导入存档 + +导入是手工拷一次:拷完之后两边各玩各的,进度会分叉;以后想合到一起,只能再整份拷一次、以其中一边为准覆盖另一边。 + +**1. 在 iPhone / iPad 上找到存档** + +- 先把手机 / 平板上的游戏完全退出(从多任务界面划掉)。 +- 打开系统自带的「文件」App →「我的 iPhone」(或「我的 iPad」)→「D2R Mobile」→ 里面的 `save` 文件夹就是存档。 + +**2. 拷整个 `save` 文件夹,不要挑文件** + +里面每个角色一个文件夹(文件夹名 = 角色名),另有共享仓库的几个文件和一个 `Settings` 文件夹(游戏设置,含界面语言——拷过来后 Mac 上的游戏设置会变成手机上那份)。我们加的功能(个人仓库的另外几页、百宝囊、秘境纪录、编年史仓库等)的数据也都在这个文件夹里。「自定义」页的开关不在里面,两台设备各管各的。 + +用隔空投送、数据线(访达里的「文件」页)或 iCloud 云盘把它传到 Mac 上都行。 + +**3. 放到 Mac 上** + +1. 把 Mac 上的游戏完全退出(⌘Q)。 +2. 在访达里按 ⇧⌘G,输入 `~/Library/Application Support/D2R Mobile` 回车。(这个文件夹在游戏第一次启动后才有。) +3. **先备份**:把里面现有的 `save` 文件夹改个名字(比如 `save 备份`),别删。 +4. 把从手机拷来的 `save` 文件夹放进来。放对的样子是:`D2R Mobile/save/` 下面直接就是各个角色文件夹、`Settings`、几个 `.d2i` 文件——不要多套一层(不是 `save/save/…`)。 +5. 旁边若有 `save.work`、`save.new` 不用管,游戏启动时会丢掉重建。 +6. 打开游戏,主菜单上应当出现手机上的角色。 + +放错了或想恢复:退出游戏,把刚放进去的 `save` 拿走,把第 3 步改了名的那份改回 `save`。 + +反方向(Mac → iPhone / iPad)文件是同一套,做法对称:Mac 上退出游戏,把 Mac 的 `save` 拷到手机「文件」里游戏文件夹下替换原来的(先把手机上原来的改名备份)。两边的 App 尽量都用最新的。 + +验过的:在 Mac 上把一份存档按上面第 4 步的摆法放进存档目录,启动后主菜单显示出那份存档里的角色,能进局(无人值守一局)。从真的 iPhone / iPad 经「文件」App 拷出来再放进 Mac 的整个过程、反方向、专家模式角色,未经真人操作。 ## 退出与存盘 关窗口、⌘Q、菜单里点退出,在任何状态下都会先存盘再退:局内、暂停菜单开着、面板开着、读取画面、秘境面板开着各验过一局。最多等 3 秒;到点还没存成,会在日志里记一行「未存盘退出」。 -## 这一版的操作方式 +被强制退出或崩溃之后再打开,不会再有系统那个「要重新打开窗口吗」的框挡住游戏窗口。 -- **移动**用 W A S D 或手柄摇杆。鼠标点到怪物、NPC、物件会走过去交互;点空地不会走。 -- **物品**的整理、穿脱、买卖用键盘或手柄的光标操作:W A S D 把光标移到物品上,按底栏提示的键。例如在商人处买东西:光标移到货物上(底栏出现「A 购买」)→ 按 J → 确认框里再按 J。 -- **界面**是原版的手柄版界面,我们加的页面(自定义页、珍宝匣、编年史、秘境选层等)都在里面。 +## 已知不足 -## 这一版还没有的 - -- 鼠标点地面走路、鼠标对物品的长按 / 双击 / 拖放。 -- 手柄上 ZR 空格的免费回城。 -- 秘境左侧的任务栏。 -- iCloud 存档同步、更新检查、分享诊断日志。 +- 开头说的五项未经真人操作:键盘按键、实体手柄、选资源文件夹的对话框、⌘Q 与菜单点击、真人手感。键位是照键码表写的。 +- 鼠标点空地不会走;屏上的键帽仍是手柄字母;物品的长按 / 双击 / 拖放 / 购买不认鼠标(见上面「鼠标」一节)。 +- 手柄上 ZR 空格的免费回城没有。 +- 秘境左侧的任务栏没有。 +- 自己构建的 App 没有 iCloud 存档同步;没有更新检查和分享诊断日志。 +- 老接口版在 macOS 15 上由一位内测玩家实际玩过(Mac mini M4,macOS 15.7,用的是出好的包);在 macOS 15 的 Mac 上从本仓库自己构建,未经真人操作。 diff --git a/docs/NO_XCODE.md b/docs/NO_XCODE.md index 25277d0..f68bb5b 100644 --- a/docs/NO_XCODE.md +++ b/docs/NO_XCODE.md @@ -15,7 +15,7 @@ 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). The shell (`D2RMobile-shell.ipa`, about 3 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.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. The shell cannot start by itself: on launch it tells you that this package has no game program in it yet. diff --git a/docs/NO_XCODE.zh-CN.md b/docs/NO_XCODE.zh-CN.md index 4fd93e8..e3e1a75 100644 --- a/docs/NO_XCODE.zh-CN.md +++ b/docs/NO_XCODE.zh-CN.md @@ -15,7 +15,7 @@ English: [NO_XCODE.md](NO_XCODE.md) ## 壳里有什么、没有什么 -壳从本仓库的[发布页](https://github.com/jhaizhou-ops/d2r-mobile/releases)下载。壳(`D2RMobile-shell.ipa`,约 3 MB)里只有我们自己的宿主程序、图标和两张随仓库公开的表。它**没有**:游戏程序、着色器、覆盖层、界面素材、任何从游戏文件生成的数据表。构建壳的脚本(`dm/ios/tools/shell_build.sh`)在最后会拿真实的游戏内容去壳里逐个文件搜一遍,搜到就不出壳。 +壳从本仓库的[发布页](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`)在最后会拿真实的游戏内容去壳里逐个文件搜一遍,搜到就不出壳。 壳自己起不来——它启动时会告诉你「这个安装包里还没有游戏程序」。 diff --git a/docs/OLDER_SYSTEMS.md b/docs/OLDER_SYSTEMS.md new file mode 100644 index 0000000..30880a2 --- /dev/null +++ b/docs/OLDER_SYSTEMS.md @@ -0,0 +1,61 @@ +# Older systems: iOS 18 – 25 and macOS 15 + +**English** | [简体中文](OLDER_SYSTEMS.zh-CN.md) + +The default build requires iOS 26 / macOS 26: the graphics side is built on a graphics interface that only exists from those systems on (Metal 4). Devices that have not moved to 26 use the "older-API build" — the same source, the same game, the same features, with the graphics side using interfaces that older systems also have. Its minimum is **iOS 18.0 / macOS 15.0**. + +## Which one do I need + +Look at the system first, then at the chip. The two are independent and can be combined: + +| Your device | System is iOS 26 or later | System is iOS 18 – 25 | +|---|---|---| +| **A17 Pro and newer** (iPhone 15 Pro and later, iPhone 16 and later) | Default build, nothing to add | Older-API build | +| **A16 and earlier** (iPhone 14 series, iPhone 15 / 15 Plus and before) | Default build + Legacy Device Pack | Older-API build + Legacy Device Pack | + +- The **system** decides which build to use (default / older-API). +- The **chip** decides whether you also need a Legacy Device Pack: the GPU of the A16 and earlier does not accept the format of the game textures. See [LEGACY_DEVICES.md](LEGACY_DEVICES.md). +- On a Mac only the system matters: macOS 26 or later uses the default build, macOS 15 – 25 the older-API build; no Apple silicon Mac needs the texture pack. + +## Building the older-API version + +### iPhone / iPad, with a Mac and Xcode + +Preparation is unchanged (`./setup.sh`); add one switch when building: + +```bash +cd dm/ios +DM_IOS_M3=1 ./run.sh build +``` + +It changes the deployment target to iOS 18.0 and switches the graphics side to the older interfaces. A free Apple ID still works: `DM_FREE_ACCOUNT=1` can be set together with it. For A16 and earlier devices, also bring the texture pack (`DM_ASTC_PACK`) as described in [LEGACY_DEVICES.md](LEGACY_DEVICES.md). + +### iPhone / iPad, without Xcode + +The Releases page has two shells. Pick the one for your system; every other step is exactly as in [NO_XCODE.md](NO_XCODE.md): + +| Shell | For | +|---|---| +| `D2RMobile-shell.ipa` | iOS 26 and later | +| `D2RMobile-shell-ios18.ipa` | 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. + +### Mac + +```bash +source ~/dm-work/build/cache/dm/venv/bin/activate +DM_MAC_M3=1 dm/tools/mac_app.sh # produces ~/dm-work/out/macapp/D2R Mobile M3.app +``` + +It recompiles the shader libraries for macOS 15 (about 3 minutes, the first time only) into the output directory. The older-API App is called "D2R Mobile M3" and has its own save and log directory, so it can sit next to the default App. Like the default App it runs only on the Mac that built it; **do not delete or move the output directory**, the recompiled shader libraries are in it. + +## How it differs from the default build + +- Picture, gameplay and save format are the same. +- The graphics side submits about 20 – 30% more commands per draw, so the same picture costs some more CPU time; the frame-time difference we measured is within measurement noise. +- The resource-download extension is not included (it only serves Apple-hosted asset packs, which public builds do not use anyway). + +## In practice + +macOS 15: a player in our test group has played the older-API build on a Mac mini M4 running macOS 15.7. iOS 18: a community developer has run the game on iOS 18 on their own branch with the same kind of change; the iOS 18 package of this repository's version has just gone out to our test group. If you run into a problem, open an Issue with the device model, the system version and the diagnostic log (pause menu → "Share diagnostic log"). diff --git a/docs/OLDER_SYSTEMS.zh-CN.md b/docs/OLDER_SYSTEMS.zh-CN.md new file mode 100644 index 0000000..0cacaa3 --- /dev/null +++ b/docs/OLDER_SYSTEMS.zh-CN.md @@ -0,0 +1,61 @@ +# 老系统:iOS 18 – 25 与 macOS 15 + +[English](OLDER_SYSTEMS.md) | **简体中文** + +缺省的构建要求 iOS 26 / macOS 26:图形部分建在这两个系统才有的图形接口(Metal 4)上。没升到 26 的设备用「老接口版」——同一份源码、同一个游戏、同样的功能,只是图形部分改用老系统也有的接口,最低 **iOS 18.0 / macOS 15.0**。 + +## 我该用哪一种 + +先看系统,再看芯片。两件事互不相干,可以叠在一起: + +| 你的设备 | 系统是 iOS 26 及以上 | 系统是 iOS 18 – 25 | +|---|---|---| +| **A17 Pro 及更新**(iPhone 15 Pro 起、iPhone 16 起) | 缺省构建,什么都不用加 | 老接口版 | +| **A16 及更早**(iPhone 14 系列、iPhone 15 / 15 Plus 及更早) | 缺省构建 + 老机型贴图包 | 老接口版 + 老机型贴图包 | + +- **系统**决定用哪种构建(缺省 / 老接口版)。 +- **芯片**决定要不要多做一份「老机型贴图包」:A16 及更早的显卡不认游戏贴图的格式,做法见 [LEGACY_DEVICES.zh-CN.md](LEGACY_DEVICES.zh-CN.md)。 +- Mac 只看系统:macOS 26 及以上用缺省构建,macOS 15 – 25 用老接口版;Apple 芯片的 Mac 都不需要贴图包。 + +## 怎么出老接口版 + +### iPhone / iPad,有 Mac 和 Xcode + +准备步骤不变(`./setup.sh`),构建时多带一个开关: + +```bash +cd dm/ios +DM_IOS_M3=1 ./run.sh build +``` + +它把部署目标改成 iOS 18.0、图形部分换成老接口。免费的 Apple ID 照旧可用:`DM_FREE_ACCOUNT=1` 与它可以同时设。A16 及更早的机型,再照 [LEGACY_DEVICES.zh-CN.md](LEGACY_DEVICES.zh-CN.md) 带上贴图包(`DM_ASTC_PACK`)。 + +### iPhone / iPad,不用 Xcode + +发布页上有两份壳,挑对应系统的那一份,其余步骤与 [NO_XCODE.zh-CN.md](NO_XCODE.zh-CN.md) 完全相同: + +| 壳 | 给谁 | +|---|---| +| `D2RMobile-shell.ipa` | iOS 26 及以上 | +| `D2RMobile-shell-ios18.ipa` | iOS 18 – 25 | + +做包工具两份壳都认,命令不变。A16 及更早的机型同样加 `D2RM_ASTC_PACK`(见 NO_XCODE 的「老机型」一节)——贴图包只和芯片有关,两份壳用的是同一个贴图包。 + +### Mac + +```bash +source ~/dm-work/build/cache/dm/venv/bin/activate +DM_MAC_M3=1 dm/tools/mac_app.sh # 产出 ~/dm-work/out/macapp/D2R Mobile M3.app +``` + +它会把着色器库按 macOS 15 重编一份(约 3 分钟,只在第一次),放在输出目录里。老接口版的 App 叫「D2R Mobile M3」,存档和日志目录也是单独的,可以和缺省的 App 并存。和缺省的 App 一样,它只能在构建它的这台 Mac 上跑;**输出目录不要删也不要挪**,重编的着色器库在里面。 + +## 和缺省构建有什么不同 + +- 画面、玩法、存档格式都一样。 +- 图形部分每次绘制要多提交约两到三成的指令,所以同样的画面多花一些处理器时间;我们量到的帧时间差别在测量噪声之内。 +- 不带「资源下载扩展」(它只服务苹果托管的资源包,公开构建本来也用不上)。 + +## 实际情况 + +macOS 15:已有内测玩家在 Mac mini M4(macOS 15.7)上实际玩过老接口版。iOS 18:已有社区开发者在自己的分支上用同样的改法把游戏跑在了 iOS 18 上;本仓库这一版的 iOS 18 包刚发给内测玩家。遇到问题请开 Issue,带上机型、系统版本和诊断日志(暂停菜单 →「分享诊断日志」)。 diff --git a/setup.sh b/setup.sh index c1885e5..e5a3581 100755 --- a/setup.sh +++ b/setup.sh @@ -40,7 +40,7 @@ if [ "$(uname -s)" = Darwin ] && [ "$(uname -m)" = arm64 ]; then ok "$(m "Apple else bad "$(m "需要 Apple 芯片的 Mac(这台是 $(uname -s) $(uname -m))" "An Apple silicon Mac is required (this is $(uname -s) $(uname -m))")" "$(m "换一台 Apple 芯片的 Mac 再来" "Use an Apple silicon Mac")"; fi # 图形层整个建在 macOS 26 / iOS 26 才有的图形接口(Metal 4)上:macOS 低于 26 时,在这台 Mac 上运行的那几样(Mac App、宿主、图形层单测、Mac 冒烟)编不过也跑不了 # The graphics layer is built entirely on a graphics interface that exists only from macOS 26 / iOS 26 on (Metal 4): below macOS 26, the things that run on this Mac (the Mac App, the host, the graphics unit tests, the Mac smoke run) neither build nor run -case "${OSV%%.*}" in ''|*[!0-9]*) ;; *) [ "${OSV%%.*}" -ge 26 ] || note "$(m "这台 Mac 是 macOS ${OSV}:低于 26。Mac App(dm/tools/mac_app.sh)、宿主与图形层单测、Mac 冒烟需要 macOS 26 及以上(用到了 macOS 26 才有的图形接口)" "This Mac runs macOS ${OSV}, below 26. The Mac App (dm/tools/mac_app.sh), the host and graphics unit tests and the Mac smoke run need macOS 26 or later (they use a graphics interface that exists only from macOS 26 on)")";; esac +case "${OSV%%.*}" in ''|*[!0-9]*) ;; *) [ "${OSV%%.*}" -ge 26 ] || note "$(m "这台 Mac 是 macOS ${OSV}:低于 26。Mac App(dm/tools/mac_app.sh)、宿主与图形层单测、Mac 冒烟需要 macOS 26 及以上(用到了 macOS 26 才有的图形接口)。要在这台 Mac 上玩,出老接口版:DM_MAC_M3=1 dm/tools/mac_app.sh(最低 macOS 15.0,见 docs/OLDER_SYSTEMS.zh-CN.md)" "This Mac runs macOS ${OSV}, below 26. The Mac App (dm/tools/mac_app.sh), the host and graphics unit tests and the Mac smoke run need macOS 26 or later (they use a graphics interface that exists only from macOS 26 on). To play on this Mac, build the older-API version: DM_MAC_M3=1 dm/tools/mac_app.sh (minimum macOS 15.0, see docs/OLDER_SYSTEMS.md)")";; esac DK=$DM_ROOT; while [ ! -d "$DK" ] && [ "$DK" != / ]; do DK=$(dirname "$DK"); done; FREE=$(df -g "$DK" 2> /dev/null | awk 'NR==2 {print $4}'); WANT=30; [ -d "$GAME" ] && WANT=15 if [ -n "$FREE" ] && [ "$FREE" -ge "$WANT" ]; then ok "$(m "磁盘剩余 $FREE GB(至少要 $WANT GB)" "$FREE GB free disk space (at least $WANT GB needed)")" else bad "$(m "磁盘剩余 ${FREE:-?} GB,不够:工作区要约 12 GB,解游戏包另要约 20 GB" "Only ${FREE:-?} GB free: the workspace needs about 12 GB, extracting the game package about 20 GB more")" "$(m "腾出空间,或用 DM_ROOT=<别的盘上的目录> 换位置" "Free up space, or point DM_ROOT= elsewhere")"; fi