Compare commits
15
Commits
main
..
android-port
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a6c3655e21 | ||
|
|
8eb294e7e0 | ||
|
|
b94670c795 | ||
|
|
7ff4e36710 | ||
|
|
e2a0c9a9b5 | ||
|
|
1ceeeaba77 | ||
|
|
685d3ddef8 | ||
|
|
615a429a29 | ||
|
|
f43480dc48 | ||
|
|
3c25cd89fc | ||
|
|
3429c6c0a4 | ||
|
|
3076dc4a69 | ||
|
|
944e199c8a | ||
|
|
4d91f80bae | ||
|
|
cfa70b3d02 |
@@ -3,3 +3,6 @@
|
||||
.iosdd_mac/
|
||||
.iosdd_*/
|
||||
.DS_Store
|
||||
|
||||
# 本地原版游戏资源与安装包(不进仓库) | local original game resources and builds (never committed)
|
||||
/resources/
|
||||
|
||||
+1
-1
@@ -53,7 +53,7 @@ The following are generated at build time and are already listed in the `.gitign
|
||||
|---|---|
|
||||
| `dm/host/dm_vault_tab.h`, `dm/host/dm_hud_exp.h`, `dm/host/dm_bright_levels.inc` | Headers generated from the game's data tables (by `dm/host/Makefile` at build time) |
|
||||
| `dm/ios/Gen/` | Generated parts of the iOS package: UI images made from the game files, the embedded game program, the overlay |
|
||||
| `dm/ios/Sources/TouchArt/dm_native_*.png`, `dm/ios/Sources/dm_touch_native_art.c` | The skill atlas and skill index |
|
||||
| `dm/ios/Sources/TouchArt/dm_native_*.png`, `dm/touch/dm_touch_native_art.c` | The skill atlas and skill index |
|
||||
| `dm/ios/DmIOS.xcodeproj/`, `dm/ios/Sources/Info.plist`, `dm/ios/Sources/DmIOS.entitlements`, and `Info.plist` and `RomfsDownloader.entitlements` under `dm/ios/RomfsDownloader/` | The project and configuration generated from `dm/ios/project.yml` |
|
||||
| `dm/ios/local.env` | Your own signing configuration |
|
||||
| `dm/host/dmhost`, `*.dSYM/`, `*.bin`, `*.pkl`, `__pycache__/`, the test programs built under each `tests/` | Build output and intermediate files |
|
||||
|
||||
@@ -53,7 +53,7 @@ English: [CONTRIBUTING.md](CONTRIBUTING.md)
|
||||
|---|---|
|
||||
| `dm/host/dm_vault_tab.h`、`dm/host/dm_hud_exp.h`、`dm/host/dm_bright_levels.inc` | 由游戏的数据表生成的表头(`dm/host/Makefile` 构建时生成) |
|
||||
| `dm/ios/Gen/` | iOS 包的生成物:由游戏文件做出的界面图、内嵌的游戏程序、覆盖层 |
|
||||
| `dm/ios/Sources/TouchArt/dm_native_*.png`、`dm/ios/Sources/dm_touch_native_art.c` | 技能图集与技能索引 |
|
||||
| `dm/ios/Sources/TouchArt/dm_native_*.png`、`dm/touch/dm_touch_native_art.c` | 技能图集与技能索引 |
|
||||
| `dm/ios/DmIOS.xcodeproj/`、`dm/ios/Sources/Info.plist`、`dm/ios/Sources/DmIOS.entitlements`、`dm/ios/RomfsDownloader/` 下的 `Info.plist` 与 `RomfsDownloader.entitlements` | 由 `dm/ios/project.yml` 生成的工程与配置 |
|
||||
| `dm/ios/local.env` | 你自己的签名配置 |
|
||||
| `dm/host/dmhost`、`*.dSYM/`、`*.bin`、`*.pkl`、`__pycache__/`、各 `tests/` 下编出的测试程序 | 编译产物与中间文件 |
|
||||
|
||||
@@ -191,11 +191,15 @@ flowchart LR
|
||||
|
||||
## Which devices are supported
|
||||
|
||||
Minimum: **an A14 / M1 chip or later** — the graphics layer needs Metal 3, which Apple supports from A14 / M1 on (see Apple's [Metal support on Apple devices](https://support.apple.com/102894) and [Metal Feature Set Tables](https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf)).
|
||||
|
||||
| Device | Playable? | How | How sure we are |
|
||||
|---|---|---|---|
|
||||
| **iPhone / iPad, A17 Pro and later** (iPhone 15 Pro and later, iPhone 16 and later, iPads with M-series chips) | Yes | iOS 26 or later: the default shell / default build; iOS 18 – 25: the iOS 18 shell / [older-API build](docs/OLDER_SYSTEMS.md) | Main devices, played daily |
|
||||
| **iPhone / iPad, A16 and earlier** (all iPhone 14 models, iPhone 15 / 15 Plus, iPhone 13 series and so on) | Yes, with one extra step | Make a Legacy Device Pack from your own game files as in [docs/LEGACY_DEVICES.md](docs/LEGACY_DEVICES.md) and include it when making the install package; the system split is the same as the row above | Played by players: iPhone 14 Pro Max (A16, 6 GB) at 60 fps; iPhone 13 Pro Max (A15, 6 GB) in the 30 fps mode |
|
||||
| **Chips older than A15, devices with 4 GB of RAM** | No reports yet | Same as the row above | If you have tried, please open an Issue and tell us |
|
||||
| **Devices with 4 GB of RAM** (such as the 4th-generation iPad Air) | Not supported yet (we are reducing memory use and will update this when there is progress) | — | Tested by a player: on an iPad Air 4 (A14, 4 GB) with the Legacy Device Pack, the system ends the app a few seconds after launch because the device runs out of memory |
|
||||
| **A14 chips with 6 GB of RAM or more** (such as iPhone 12 Pro / 12 Pro Max) | No reports yet | Same as the A16-and-earlier row | If you have tried, please open an Issue and tell us |
|
||||
| **A13 and earlier chips** (such as the iPhone 11 series and the 2020 iPad Pro) | Not supported | — | The graphics chip does not support Metal 3 (tested by a player on an iPad Pro with A12Z; Apple's references are above the table); the app says so at launch instead of crashing |
|
||||
| **Mac, Apple silicon** | Yes (native macOS App) | macOS 26 or later: the default build; macOS 15 – 25: the [older-API build](docs/OLDER_SYSTEMS.md). Keyboard, mouse and gamepad all work; what each can do is in [docs/MAC.md](docs/MAC.md) | A player has played the older-API build on macOS 15.7.7 |
|
||||
| **Intel Macs** | Not supported | — | — |
|
||||
|
||||
@@ -210,6 +214,8 @@ flowchart LR
|
||||
|
||||
Both routes start with **the files of the game you bought**: the Switch release of Diablo II: Resurrected plus the Reign of the Warlock expansion, updated to 1.0.34.0 (the version the console shows; it corresponds to PC version 3.3.94012, and the directory names and tools in this repository use the latter number). This project is built for the version with that expansion; using it without the expansion is not supported and has not been verified. How to prepare them is in [docs/GAME_FILES.md](docs/GAME_FILES.md).
|
||||
|
||||
> This project provides only tools and an install shell that contains no game content. We do not distribute or endorse, and are not responsible for, any third party distributing game assets, game executables or install packages that contain game content. Please use only game files you legally own.
|
||||
|
||||
This project is implemented and verified on the Switch release 1.0.34.0 (which corresponds to PC version 3.3.94012), and by default the tools accept only that version. Community users have reported adapting other versions on their own by following the structure of this repository, and running them successfully. The rule tables are grouped by game version (in `dm/tools/patch_nso.py`, keyed by the build ID of the main program); you are welcome to contribute the version you adapted.
|
||||
|
||||
**Check your device first**: the "Which devices are supported" table above tells you which build to use and whether you also need a Legacy Device Pack.
|
||||
@@ -264,7 +270,7 @@ The interface is the original's gamepad interface. Keyboard: Space confirms, Esc
|
||||
|
||||
### Without a Mac: the shell plus the packaging tool
|
||||
|
||||
Download our prebuilt "shell" package (`D2RMobile-shell.ipa`; `D2RMobile-shell-ios18.ipa` for iOS 18 – 25), which contains no game content, from this repository's [Releases page](https://github.com/jhaizhou-ops/d2r-mobile/releases), add your own game files, make the install package on Windows or Linux, then sign and install it with a sideloading tool. On this route only, because the computer making the package has no Apple shader compiler, the **first launch** on the phone spends about 7 minutes compiling shaders (once, with a progress bar); a package built with Xcode has no such step. The steps, and how far each one has been verified, are in [docs/NO_XCODE.md](docs/NO_XCODE.md).
|
||||
Download our prebuilt "shell" package (`D2RMobile-shell-build-input.zip`; `D2RMobile-shell-ios18-build-input.zip` for iOS 18 – 25), which contains no game content, from this repository's [Releases page](https://github.com/jhaizhou-ops/d2r-mobile/releases), add your own game files, make the install package on Windows or Linux, then sign and install it with a sideloading tool. The shell is build input, not an app to install (installed as is, it only shows a dialog and does not start the game); when you move to a new release, make the install package again with the new shell. On this route only, because the computer making the package has no Apple shader compiler, the **first launch** on the phone spends about 7 minutes compiling shaders (once, with a progress bar); a package built with Xcode has no such step. The steps, and how far each one has been verified, are in [docs/NO_XCODE.md](docs/NO_XCODE.md).
|
||||
|
||||
## Known limitations
|
||||
|
||||
@@ -319,6 +325,20 @@ The cleaner arrangement is to move these defaults into per-game configuration an
|
||||
|
||||
**You must own the game, including the Reign of the Warlock expansion.** This is an independent, non-commercial project. It is not affiliated with, endorsed by, or sponsored by Blizzard Entertainment or Nintendo. Diablo and Blizzard Entertainment are trademarks of Blizzard Entertainment, Inc.; Nintendo Switch is a trademark of Nintendo. Use it only with a copy of the game that you own.
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
This project stands on the open-source work below. Thank you to its authors and maintainers.
|
||||
|
||||
- **Ryujinx** (Ryubing 1.3.2, MIT): `dm/third_party/ryujinx` bundles its shader translator unchanged (the Ryujinx.Graphics.Shader, Spv.Generator and Ryujinx.Common projects), which translates the Switch game's shaders to SPIR-V. During development we also ran the original game in a patched Ryujinx as the reference for comparing pictures and game state (see [dm/verify/README.md](dm/verify/README.md); the scripts that build and drive it are not in this repository).
|
||||
- **deko3d** (devkitPro, zlib): the texture layout size algorithm in `dm/gfx/nvn/nvn_tex.c` is ported from it.
|
||||
- **nvn.h** (h1k421, MIT): the graphics API declarations in `dm/gfx/nvn/include/nvn.h`.
|
||||
- **libdeflate** (Eric Biggers, MIT): decompressing game data.
|
||||
- **bcdec** (iOrange, MIT or Unlicense): decoding BC textures on devices that do not support the BC formats.
|
||||
- **FLIP** (NVIDIA, BSD 3-Clause): the image difference metric used in image-quality checks.
|
||||
- **Offline fix patch** (LFS Mod Offline Fix): the 7 rewrites in `dm/tools/patch_nso.py` that let the game run offline come from this community patch. We have no reliable record of where it was first published or who wrote it; if you know, please open an Issue.
|
||||
- Tools used to build and verify: SPIRV-Cross (SPIR-V to Metal Shading Language), XcodeGen, .NET, Capstone and Unicorn (disassembly and equivalence checks of the rewrites), Pillow, numpy, lz4, astcenc (the Legacy Device Pack), hactool (extracting files from a game package), libimobiledevice and LLVM. Versions and links are in [docs/DEPENDENCIES.md](docs/DEPENDENCIES.md).
|
||||
- Community contributions: Joe Hu reported and diagnosed several Greater Rift issues and proposed a verification matrix; seedds found and diagnosed the render-target view format issue on another port (#36). Both are credited as co-authors on the corresponding commits.
|
||||
|
||||
## License
|
||||
|
||||
MIT, see [LICENSE](LICENSE). Third-party code keeps its own license in its own directory; see [docs/DEPENDENCIES.md](docs/DEPENDENCIES.md).
|
||||
|
||||
+22
-2
@@ -191,11 +191,15 @@ flowchart LR
|
||||
|
||||
## 支持哪些设备
|
||||
|
||||
最低要求:**A14 / M1 及以后的芯片**——本项目的图形层要用 Metal 3,苹果从 A14 / M1 起才支持(依据:苹果的[Metal 支持的设备](https://support.apple.com/102894)、[Metal 功能表](https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf))。
|
||||
|
||||
| 设备 | 能不能玩 | 怎么做 | 把握程度 |
|
||||
|---|---|---|---|
|
||||
| **iPhone / iPad,A17 Pro 及以后**(iPhone 15 Pro 起、iPhone 16 起、M 系列芯片的 iPad) | 直接玩 | iOS 26 及以上用缺省的壳 / 缺省构建;iOS 18 – 25 用 iOS 18 的壳 / [老接口版](docs/OLDER_SYSTEMS.zh-CN.md) | 主力机型,日常在玩 |
|
||||
| **iPhone / iPad,A16 及更早**(iPhone 14 全系、iPhone 15 / 15 Plus、iPhone 13 系列等) | 可以玩,多一步 | 按 [docs/LEGACY_DEVICES.zh-CN.md](docs/LEGACY_DEVICES.zh-CN.md) 用自己的游戏文件做一份老机型补充包,做安装包时带上它;系统同上一行分 iOS 26 / iOS 18 – 25 | 已有玩家实测:iPhone 14 Pro Max(A16,6 GB)60 帧;iPhone 13 Pro Max(A15,6 GB)30 帧档 |
|
||||
| **比 A15 更老的芯片、4 GB 内存的设备** | 尚无报告 | 同上一行 | 欢迎试过的人开 Issue 告诉我们结果 |
|
||||
| **4 GB 内存的设备**(如 iPad Air 第 4 代) | 暂不支持(在优化内存,有进展更新) | — | 已有玩家实测:iPad Air 4(A14,4 GB)带上老机型补充包后,启动几秒即因整机内存不足被系统结束 |
|
||||
| **A14 芯片、6 GB 及以上内存**(如 iPhone 12 Pro / 12 Pro Max) | 尚无报告 | 同 A16 及更早那一行 | 欢迎试过的人开 Issue 告诉我们结果 |
|
||||
| **A13 及更早的芯片**(如 iPhone 11 系列、2020 年的 iPad Pro) | 不支持 | — | 图形芯片不支持 Metal 3(玩家在 iPad Pro A12Z 上实测;苹果依据见表上方);App 启动时会直接提示,不会闪退 |
|
||||
| **Mac,Apple 芯片** | 直接玩(原生 macOS App) | macOS 26 及以上用缺省出法;macOS 15 – 25 用[老接口出法](docs/OLDER_SYSTEMS.zh-CN.md)。键盘、鼠标、手柄都能玩,各自能做什么见 [docs/MAC.zh-CN.md](docs/MAC.zh-CN.md) | 已有玩家在 macOS 15.7.7 上实际玩过老接口版 |
|
||||
| **Intel 芯片的 Mac** | 不支持 | — | — |
|
||||
|
||||
@@ -210,6 +214,8 @@ flowchart LR
|
||||
|
||||
两条路都要先有**你自己购买的游戏的文件**:Switch 版《暗黑破坏神 II:狱火重生》本体加「术士君临」资料片,更新到 1.0.34.0(主机上显示的版本号;它对应 PC 版的 3.3.94012,本仓库的目录名和工具里用的是后一个号)。本项目是按带这部资料片的版本做的,没有资料片的情况不支持、也没有验过。怎么准备见 [docs/GAME_FILES.zh-CN.md](docs/GAME_FILES.zh-CN.md)。
|
||||
|
||||
> 本项目只提供工具与不含任何游戏内容的安装壳。我们不提供、不认可、也不对任何第三方分发游戏资源、游戏主程序或含游戏内容的安装包的行为负责。请只使用你自己合法拥有的游戏文件。
|
||||
|
||||
本项目基于 Switch 版 1.0.34.0(对应 PC 版的 3.3.94012)实现并验证,工具默认只认这一版。已有社区用户反馈,参照仓库结构自行适配了其他版本并成功运行。规则表按游戏版本分组存放(`dm/tools/patch_nso.py` 里按主程序的构建标识分组),欢迎把你适配的版本提交回来。
|
||||
|
||||
**先对一下你的设备**:上面「支持哪些设备」那张表告诉你该用哪种构建、要不要多做一份老机型补充包。
|
||||
@@ -264,7 +270,7 @@ DM_MAC_M3=1 dm/tools/mac_app.sh # macOS 15 – 25:产出 D2R Mobile M3.ap
|
||||
|
||||
### 没有 Mac:壳 + 做包工具
|
||||
|
||||
从本仓库的[发布页](https://github.com/jhaizhou-ops/d2r-mobile/releases)下载我们预先做好的、不含游戏内容的「壳」安装包(`D2RMobile-shell.ipa`;iOS 18 – 25 用 `D2RMobile-shell-ios18.ipa`),加上你自己的游戏文件,在 Windows 或 Linux 上做出安装包,再用自签工具签名装机。只有走这条路时,因为做包的电脑上没有苹果的着色器编译器,手机**第一次启动**要花约 7 分钟把着色器编完(一次性,带进度条);用 Xcode 构建的包没有这一步。步骤与每一步的验证现状见 [docs/NO_XCODE.zh-CN.md](docs/NO_XCODE.zh-CN.md)。
|
||||
从本仓库的[发布页](https://github.com/jhaizhou-ops/d2r-mobile/releases)下载我们预先做好的、不含游戏内容的「壳」安装包(`D2RMobile-shell-build-input.zip`;iOS 18 – 25 用 `D2RMobile-shell-ios18-build-input.zip`),加上你自己的游戏文件,在 Windows 或 Linux 上做出安装包,再用自签工具签名装机。壳是做安装包的原料,不能直接装来玩(直接装上去只会弹框说明、不会进游戏);换新版本时要用新版的壳重新做一次安装包。只有走这条路时,因为做包的电脑上没有苹果的着色器编译器,手机**第一次启动**要花约 7 分钟把着色器编完(一次性,带进度条);用 Xcode 构建的包没有这一步。步骤与每一步的验证现状见 [docs/NO_XCODE.zh-CN.md](docs/NO_XCODE.zh-CN.md)。
|
||||
|
||||
## 已知限制
|
||||
|
||||
@@ -319,6 +325,20 @@ DM_MAC_M3=1 dm/tools/mac_app.sh # macOS 15 – 25:产出 D2R Mobile M3.ap
|
||||
|
||||
**你必须拥有正版游戏,包括「术士君临」资料片。** 这是一个独立的非商业项目,与暴雪娱乐、任天堂没有关联,也未获其认可或赞助。Diablo 与 Blizzard Entertainment 是暴雪娱乐的商标,Nintendo Switch 是任天堂的商标。请只配合你自己拥有的游戏使用。
|
||||
|
||||
## 致谢
|
||||
|
||||
这个项目建立在下面这些开源工作之上,谢谢各位作者和维护者。
|
||||
|
||||
- **Ryujinx**(Ryubing 1.3.2,MIT):`dm/third_party/ryujinx` 原样内置了它的着色器翻译库(Ryujinx.Graphics.Shader、Spv.Generator、Ryujinx.Common 三个项目,未修改),用来把 Switch 原版着色器翻译成 SPIR-V。开发过程中,我们还用打了补丁的 Ryujinx 跑原版游戏,作为画面和游戏状态的对照参考(做法见 [dm/verify/README.zh-CN.md](dm/verify/README.zh-CN.md);构建和驱动它的脚本不在本仓库里)。
|
||||
- **deko3d**(devkitPro,zlib):`dm/gfx/nvn/nvn_tex.c` 里的贴图排布尺寸算法移植自它。
|
||||
- **nvn.h**(h1k421,MIT):图形接口声明 `dm/gfx/nvn/include/nvn.h`。
|
||||
- **libdeflate**(Eric Biggers,MIT):解压游戏数据。
|
||||
- **bcdec**(iOrange,MIT 或 Unlicense):在不支持 BC 贴图格式的设备上解压 BC 贴图。
|
||||
- **FLIP**(NVIDIA,BSD 3-Clause):画质验证里的画面差异度量。
|
||||
- **离线修复补丁**(LFS Mod Offline Fix):`dm/tools/patch_nso.py` 里让游戏离线运行的 7 处改写取自这个社区补丁。它的首发处和作者我们没有确切记录,知道的请开 Issue 告诉我们。
|
||||
- 构建与验证用到的工具:SPIRV-Cross(把 SPIR-V 转成 Metal 着色语言)、XcodeGen、.NET、Capstone 和 Unicorn(改写前后的反汇编与等价核对)、Pillow、numpy、lz4、astcenc(老机型补充包)、hactool(从游戏包取文件)、libimobiledevice、LLVM。版本和地址见 [docs/DEPENDENCIES.zh-CN.md](docs/DEPENDENCIES.zh-CN.md)。
|
||||
- 社区贡献:Joe Hu 报告并定位了多处秘境问题,还提出了验证矩阵;seedds 在另一款游戏的移植中发现并定位了渲染目标视图格式的问题(#36)。他们在相应提交里署名为共同作者。
|
||||
|
||||
## 许可证
|
||||
|
||||
MIT,见 [LICENSE](LICENSE)。第三方代码各自的许可证在其目录内,见 [docs/DEPENDENCIES.zh-CN.md](docs/DEPENDENCIES.zh-CN.md)。
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
3.3.94012-r42
|
||||
3.3.94012-r44
|
||||
|
||||
+9
-2
@@ -75,6 +75,10 @@ The game draws with NVN (the Switch graphics interface). `main` imports only one
|
||||
|
||||
The App compiles the sources of `host/` and `gfx/` in directly. The front-end interface `host/front.h` is implemented on the Mac by `host/front_mac.m` and on iOS by `ios/Sources/front_ios.m`. The rewritten module images are turned into embedded assembly by `ios/tools/gen_embed.py` and compiled into the executable; the iOS branch of `loader.c` does not copy code, it only maps these blocks back at their original relative positions. Touch controls and the user interface are also in `ios/`. See [ios/README.md](ios/README.md) for details.
|
||||
|
||||
### 6. Android shell (`android/`, Adreno devices only)
|
||||
|
||||
The same `host/` and `gfx/` sources are built with the NDK into `libd2r.so`, loaded by a GameActivity; the front-end interface is implemented by `android/Sources/front_app.c`, and the touch HUD is in `android/Sources/touch_app.c`. Graphics replay switches to Vulkan: `gfx/vulkan/nvn_vk.c` consumes the same commands recorded by `hle_nvn.c`. Differences in system interfaces are filled in by `host/compat/linux/`. See [android/README.md](android/README.md) for details.
|
||||
|
||||
## Directories
|
||||
|
||||
| Location | Contents |
|
||||
@@ -82,8 +86,9 @@ The App compiles the sources of `host/` and `gfx/` in directly. The front-end in
|
||||
| `PRODUCT` | The codename of the current rewrite build output, one line |
|
||||
| `tools/` | The rewriter `patch_nso.py`, the build output script `product.sh`, `dmx.py` for reading the game's resource storage, `casc_overlay.py` for rewriting the resource storage at build time, and a batch of code-reading and analysis scripts |
|
||||
| `host/` | The host: loading, system call and system library takeover, the Mac front end, in-game features; `host/tests/` holds the unit tests |
|
||||
| `gfx/` | The graphics layer: `nvn/` (interface layer and Metal replay), `tex/` (texture formats and deswizzling), `tools/` (shader translation chain), `tests/` |
|
||||
| `gfx/` | The graphics layer: `nvn/` (interface layer and Metal replay), `vulkan/` (Vulkan replay for Android), `tex/` (texture formats and deswizzling), `tools/` (shader translation chain), `tests/` |
|
||||
| `ios/` | The iOS App: `Sources/`, the project description `project.yml`, the build-and-install script `run.sh`, `tools/` (asset generation, smoke tests, UI regression), `tests/` |
|
||||
| `android/` | The Android App: `app/` (GameActivity, `res/`, packaging script), `Sources/` (front end and touch HUD), the build entry point `Makefile`, `tests/` |
|
||||
| `verify/` | Verification: the rewrite-equivalence regression `regress.sh`, the full acceptance run `accept.sh`, and the scripts and format descriptions its items use |
|
||||
| `data/` | Small data shipped with the repository: the registry of borrowed paths for the resource overlay. The startup prefetch list is not in the public repository: without it there is no prefetch, and startup skips one step of decoding ahead of time |
|
||||
| `i18n/` | The Chinese-English string table `ui_text.tsv`; `scan_literals.py` checks that all Chinese text the player can see goes through this table, with exceptions registered in `literal_whitelist.tsv` |
|
||||
@@ -128,6 +133,8 @@ Usage is `dmhost <build output directory> [module…] [-- game arguments…]`. `
|
||||
|
||||
**Unit tests**: `make -C dm/host/tests run`, `make -C dm/gfx/tests run`, `make -C dm/ios/tests test`.
|
||||
|
||||
**Build the Android package**: `make -C dm/android -j8` (output `dm/android/build/app/d2r.apk`); `make -C dm/android install` installs it onto the phone connected over adb.
|
||||
|
||||
**Build the iOS package**: `cd dm/ios && ./run.sh build`; to install on a device use `./run.sh install`. For signing configuration see the top-level README.
|
||||
|
||||
**Full acceptance run**: `dm/verify/accept.sh [--fast|--full]` runs rewrite equivalence, save-file comparison, the screenshot gate, unit tests, the iOS build, functional cases and more together. Besides the game files it also needs reference run data and standard save files, which are not provided with the repository; the emulator driver scripts used to obtain the reference run data are not shipped either, so the full acceptance run cannot be run with this repository alone.
|
||||
@@ -217,7 +224,7 @@ When game files are missing, a one-sentence message says directly which director
|
||||
| Right-hand panel of character select | `dm/ios/Gen/assets/NativeHUD/touch/` | `gen_fe_rightpanel.py` |
|
||||
| Minimap goal marker | `dm/ios/Gen/assets/NativeHUD/mapgoal/` | `gen_map_goal_art.py` |
|
||||
| Bottom UI (background and layout) | `dm/ios/Gen/assets/NativeHUD/v4/` | `gen_hud_v4.py` (geometry in `hud_v4_design.py`; layout = original layout + `touchrectv1_patch.json`) |
|
||||
| Skill atlas, skill index | `dm/ios/Sources/TouchArt/dm_native_*.png`, `dm/ios/Sources/dm_touch_native_art.c` | `native_art/generate.py` (checks the originals against `dm/ios/Sources/TouchArt/native_art_manifest.json`) |
|
||||
| Skill atlas, skill index | `dm/ios/Sources/TouchArt/dm_native_*.png`, `dm/touch/dm_touch_native_art.c` | `native_art/generate.py` (checks the originals against `dm/ios/Sources/TouchArt/native_art_manifest.json`) |
|
||||
| Chronicle vault table, experience table | `dm/host/dm_vault_tab.h`, `dm/host/dm_hud_exp.h` | `gen_vault_table.py`, `gen_hud_exp.py` (called by `dm/host/Makefile`) |
|
||||
| Level day/night table (used by 3D picture brightening) | `dm/host/dm_bright_levels.inc` | `dm/tools/gen_bright_levels.py` (also called by `dm/host/Makefile`) |
|
||||
|
||||
|
||||
+9
-2
@@ -75,6 +75,10 @@ English: [README.md](README.md)
|
||||
|
||||
App 把 `host/` 与 `gfx/` 的源码直接编进去,前端接口 `host/front.h` 在 Mac 上由 `host/front_mac.m` 实现、在 iOS 上由 `ios/Sources/front_ios.m` 实现。改写后的模块映像由 `ios/tools/gen_embed.py` 生成内嵌汇编,编进可执行文件;`loader.c` 的 iOS 分支不拷贝代码,只把这几块按原来的相对位置映射回去。触摸操作与界面也在 `ios/` 里。细节见 [ios/README.zh-CN.md](ios/README.zh-CN.md)。
|
||||
|
||||
### 6. Android 外壳(`android/`,仅 Adreno 机型)
|
||||
|
||||
同一套 `host/` 与 `gfx/` 源码用 NDK 编成 `libd2r.so`,由 GameActivity 加载;前端接口由 `android/Sources/front_app.c` 实现,触屏 HUD 在 `android/Sources/touch_app.c`。图形回放换成 Vulkan:`gfx/vulkan/nvn_vk.c` 接 `hle_nvn.c` 录下的同一份命令。系统接口的差异由 `host/compat/linux/` 补齐。细节见 [android/README.zh-CN.md](android/README.zh-CN.md)。
|
||||
|
||||
## 目录
|
||||
|
||||
| 位置 | 内容 |
|
||||
@@ -82,8 +86,9 @@ App 把 `host/` 与 `gfx/` 的源码直接编进去,前端接口 `host/front.h
|
||||
| `PRODUCT` | 当前改写产物的代号,一行 |
|
||||
| `tools/` | 改写器 `patch_nso.py`、产物脚本 `product.sh`、读游戏资源存储的 `dmx.py`、构建期改写资源存储的 `casc_overlay.py`,以及一批读码与分析脚本 |
|
||||
| `host/` | 宿主:装载、系统调用与系统库接管、Mac 前端、游戏内功能;`host/tests/` 是单元测试 |
|
||||
| `gfx/` | 图形层:`nvn/`(接口层与 Metal 回放)、`tex/`(贴图格式与解排布)、`tools/`(着色器翻译链)、`tests/` |
|
||||
| `gfx/` | 图形层:`nvn/`(接口层与 Metal 回放)、`vulkan/`(Android 的 Vulkan 回放)、`tex/`(贴图格式与解排布)、`tools/`(着色器翻译链)、`tests/` |
|
||||
| `ios/` | iOS App:`Sources/`、工程描述 `project.yml`、出包与装机脚本 `run.sh`、`tools/`(资源生成、冒烟、界面回归)、`tests/` |
|
||||
| `android/` | Android App:`app/`(GameActivity、`res/`、出包脚本)、`Sources/`(前端与触屏 HUD)、构建入口 `Makefile`、`tests/` |
|
||||
| `verify/` | 验证:改写等价回归 `regress.sh`、整套验收 `accept.sh` 及其各项用到的脚本与格式说明 |
|
||||
| `data/` | 随仓库的小数据:资源覆盖层的借用路径登记表。启动预取清单公开仓库不带:缺了就不预取,启动时少一步提前解码 |
|
||||
| `i18n/` | 中英文案表 `ui_text.tsv`;`scan_literals.py` 检查玩家看得到的中文都进了这张表,例外登记在 `literal_whitelist.tsv` |
|
||||
@@ -128,6 +133,8 @@ DM_ROMFS=<Update/RomFS 目录> DM_SAVE=<存档目录> DM_TEMP=<临时目录> DM_
|
||||
|
||||
**单元测试**:`make -C dm/host/tests run`、`make -C dm/gfx/tests run`、`make -C dm/ios/tests test`。
|
||||
|
||||
**出 Android 包**:`make -C dm/android -j8`(产物 `dm/android/build/app/d2r.apk`),`make -C dm/android install` 装到 adb 连着的手机。
|
||||
|
||||
**出 iOS 包**:`cd dm/ios && ./run.sh build`,装到设备用 `./run.sh install`。签名配置见顶层 README。
|
||||
|
||||
**整套验收**:`dm/verify/accept.sh [--fast|--full]` 把改写等价、存档对拍、画面闸门、单测、iOS 构建、功能用例等并在一起跑。它除游戏文件外还要用到参照运行数据和标准存档,这些没有随仓库提供;取参照运行数据用的模拟器驱动脚本也不随仓库提供,所以整套验收在仓库外跑不了。
|
||||
@@ -217,7 +224,7 @@ DM_ROMFS=<Update/RomFS 目录> DM_SAVE=<存档目录> DM_TEMP=<临时目录> DM_
|
||||
| 选角右侧面板 | `dm/ios/Gen/assets/NativeHUD/touch/` | `gen_fe_rightpanel.py` |
|
||||
| 小地图终点标记 | `dm/ios/Gen/assets/NativeHUD/mapgoal/` | `gen_map_goal_art.py` |
|
||||
| 底部 UI(底图与布局) | `dm/ios/Gen/assets/NativeHUD/v4/` | `gen_hud_v4.py`(几何在 `hud_v4_design.py`,布局 = 原版布局 + `touchrectv1_patch.json`) |
|
||||
| 技能图集、技能索引 | `dm/ios/Sources/TouchArt/dm_native_*.png`、`dm/ios/Sources/dm_touch_native_art.c` | `native_art/generate.py`(按 `dm/ios/Sources/TouchArt/native_art_manifest.json` 核原件) |
|
||||
| 技能图集、技能索引 | `dm/ios/Sources/TouchArt/dm_native_*.png`、`dm/touch/dm_touch_native_art.c` | `native_art/generate.py`(按 `dm/ios/Sources/TouchArt/native_art_manifest.json` 核原件) |
|
||||
| 编年史仓库表、经验表 | `dm/host/dm_vault_tab.h`、`dm/host/dm_hud_exp.h` | `gen_vault_table.py`、`gen_hud_exp.py`(由 `dm/host/Makefile` 调用) |
|
||||
| 关卡昼夜表(3D 画面加亮用) | `dm/host/dm_bright_levels.inc` | `dm/tools/gen_bright_levels.py`(同样由 `dm/host/Makefile` 调用) |
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# 构建产物、缓存、日志、游戏截图 | build outputs, caches, logs, game frame captures
|
||||
build/
|
||||
@@ -0,0 +1,29 @@
|
||||
# Android 入口(仅 Adreno 机型)。规则在 build.mk,以 dm/host 为当前目录跑(宿主共用源码);产物在 build/(不进 git)
|
||||
# make = make apk:libd2r.so + d2r.apk(不用 Gradle)
|
||||
# make install 装到 adb 连着的手机(会结束正在运行的游戏)
|
||||
# make headless 无头宿主 build/dmhost(adb shell 直接跑)
|
||||
# make tests Vulkan 后端设备测试 build/tests/t_vk_perf
|
||||
# 没有游戏文件生成的表头时:DM_GENH_DIR=<表头目录>;并行:-j8
|
||||
# Android entry point (Adreno devices only). The rules are in build.mk, run with dm/host as the current directory (shared host sources); outputs in build/ (not in git)
|
||||
# make = make apk: libd2r.so + d2r.apk (no Gradle)
|
||||
# make install install onto the phone connected over adb (ends a running game)
|
||||
# make headless headless host build/dmhost (run directly from adb shell)
|
||||
# make tests Vulkan backend device test build/tests/t_vk_perf
|
||||
# Without the headers generated from game files: DM_GENH_DIR=<header dir>; parallel: -j8
|
||||
HOST := $(abspath ../host)
|
||||
B := $(CURDIR)/build
|
||||
apk: lib
|
||||
sh app/build_apk.sh
|
||||
lib:
|
||||
$(MAKE) -C $(HOST) -f $(CURDIR)/build.mk APP=1 $(B)/app/libd2r.so
|
||||
install: apk
|
||||
adb install -r $(B)/app/d2r.apk
|
||||
headless:
|
||||
$(MAKE) -C $(HOST) -f $(CURDIR)/build.mk $(B)/dmhost
|
||||
tests:
|
||||
$(MAKE) -C tests
|
||||
host-tests:
|
||||
python3 tests/run_checks.py --host-only $(if $(NDK),--ndk "$(NDK)") --output $(B)/checks-$(shell date +%Y%m%d-%H%M%S)
|
||||
clean:
|
||||
rm -rf $(B)
|
||||
.PHONY: apk lib install headless tests host-tests clean
|
||||
@@ -0,0 +1,67 @@
|
||||
# Vulkan performance verification — 2026-10-13
|
||||
|
||||
Device: OnePlus 13, Adreno 830. Build: Android NDK 28.2.13676358, API 33, repository Android `-O1` build. Headless, audio disabled, existing game resources and `save.work`. Game content, shaders, caches and captures are excluded from Git.
|
||||
|
||||
## Observed results / 实测结果
|
||||
|
||||
The final binary ran under `timeout 90`. It produced a complete hero selection capture at frame 601, reached the frame 602 profile interval, received SIGTERM, drained GPU work, and exited through the timeout path (`rc=124`). Graceful shutdown took 0.043 seconds. No `STOP`, abort or crash occurred in this run. The final capture shows the camp, characters, fire, Chinese title/description and Create button without visible corruption.
|
||||
|
||||
| 60-frame interval | Existing baseline log, frame 602 | Final build, frame 602 |
|
||||
|---|---:|---:|
|
||||
| Elapsed | 38,066.393 ms | 9,557.800 ms |
|
||||
| Pipeline creation | 11,268.754 ms | 0.000 ms |
|
||||
| Draws | 68,566 | 81,902 |
|
||||
| Actual Vulkan submissions | 240 (180 logged + 60 Present) | 240 |
|
||||
| Render pass begins | One per draw in the old implementation | 4,380 |
|
||||
| Graphics + compute pipeline hits / misses | Recreated each time | 82,382 / 0 |
|
||||
| Framebuffer cache hits | Uncached | 83,702 |
|
||||
|
||||
Final steady hero selection intervals (frames 302 through 602) took 9.147–12.410 seconds per 60 frames, median 11.373 seconds, with about 81,800–82,000 draws per interval and zero pipeline creation time. The historical baseline and final run have different loading/animation timing and draw counts; this is a practical scene comparison, not a controlled benchmark with identical command traces. Sustained rendering remains roughly 5–6.5 FPS in this scene and still needs further CPU/upload/descriptor optimization.
|
||||
|
||||
最终版 90 秒无崩溃,角色选择第 601 帧正常,第 602 帧区间约 9.56 秒 / 60 帧。稳定区间约 9.15–12.41 秒 / 60 帧,pipeline 创建时间持续为零。旧日志约 38.07 秒 / 60 帧;两次运行的加载 / 动画时间及 draw 数不同,不作为严格同指令流 benchmark。
|
||||
|
||||
The disk cache successfully loaded 1,628,103 bytes at startup. An invalid 32-byte all-zero cache was rejected (`pipeline_cache_load bytes=0`) and the real-Vulkan regression still passed.
|
||||
|
||||
## Update: Redmi 25098RA98C (Adreno 710) — 2026-10-13
|
||||
|
||||
Changes: `BATCH_SLOTS` raised to 8; GPU timestamp queries report `gpu_ms` per interval; shader pack built with `SB_ALIGN=64` so storage buffers bind directly from `addr & -64` instead of being copied to aligned transient buffers; draw-time SSBO write detection now tests vkmeta flag bit 0 only. `DM_VK_PASSPROF=N` gives a per-pass GPU breakdown.
|
||||
|
||||
| Hero selection, 60-frame interval | Before (`redmi1`, old pack) | After (`redmi8`–`redmi10`, `rt64` pack) |
|
||||
|---|---:|---:|
|
||||
| Elapsed | 18,230–34,909 ms | 7,080–7,164 ms |
|
||||
| Storage-buffer bind time | ~9,800 ms (up to 32,000 ms in later intervals) | ~400 ms |
|
||||
| Transient buffers created | 8,309 | 0 |
|
||||
| Render passes / pass breaks | 5,336 / 4,927 | 4,380 / 2,880 |
|
||||
| GPU time (`gpu_ms`) | not measured | ~5,060 ms (≈85 ms/frame) |
|
||||
| Draws | — | ~81,900 |
|
||||
|
||||
The scene now runs at about 8.4 FPS on this device (60 frames in ~7.1 s) and is GPU-bound: GPU time alone caps it near 12 FPS. `PASSPROF` shows one 1600×900 forward+ lighting pass (pixel shader `5c1ca4e7c3e4657c`, 385 draws) takes ~44 ms of ~87 ms per frame; `spirv-opt -O` made no difference. The 60 FPS target applies to Adreno 830-class devices, which still need re-measuring with this build.
|
||||
|
||||
更新(Redmi,Adreno 710):批次槽位改为 8,新增 GPU 时间戳 `gpu_ms`,着色器包使用 `SB_ALIGN=64` 后存储缓冲区按 64 字节对齐直接绑定,不再拷贝。角色选择每 60 帧从 18–35 秒降到约 7.1 秒,临时缓冲区创建从 8,309 降为 0;当前为 GPU 瓶颈(约 85 ms/帧,其中一个前向+光照 pass 约 44 ms)。60 FPS 目标需在 Adreno 830 上复测。Logs: `dm/android/build/perf/redmi1.log`, `redmi8.log`–`redmi10.log`.
|
||||
|
||||
Update (WaitEvent, Redmi): `WAIT_PROFILE` showed every CPU wait came from `OP_WAIT_EVENT` (~5.1 s per 60 frames, two per frame); the host committed and CPU-waited for all prior GPU work although NVN's WaitEvent is a GPU-side wait, so CPU and GPU ran serially. Events already satisfied by queued signals now record only a barrier (`event_queued=120 event_blocked=0`). 60 frames: 7.7 s → 5.03–5.05 s (≈11.9 FPS), submits 4 → 2 per frame; elapsed now equals `gpu_ms`, so the scene is purely GPU-bound. The remaining `sync` wait (~2.6 s / 60, `sync_lag_max=5`) is the game's own one-frame-ahead throttle. Frame 841 matches the baseline. `DM_VK_EVENT_SYNC=1` restores the old path. Logs: `redmi18.log` (before), `redmi19.log` (after).
|
||||
|
||||
更新(WaitEvent):`WAIT_PROFILE` 显示所有 CPU 等待都来自 `OP_WAIT_EVENT`(每 60 帧约 5.1 秒、每帧 2 次)——宿主把 GPU 侧等待实现成了“提交 + CPU 等待之前全部 GPU 工作”,导致 CPU 与 GPU 串行。现在事件若可由排队的 signal 满足,只录屏障。每 60 帧 7.7 秒 → 约 5.04 秒(≈11.9 FPS),提交从 4 次/帧降到 2 次/帧,耗时等于 `gpu_ms`,完全 GPU 瓶颈。
|
||||
|
||||
Combined with `DM_VK_VRS=2x2` (opt-in): 60 frames 4.37 s (≈13.7 FPS), `gpu_ms` ≈4,356, sync wait ~1.85 s / 60; edges stay sharp, textures slightly softer (frame 841 mean abs diff 3.8 vs no VRS). Log: `redmi20.log`.
|
||||
|
||||
叠加 `DM_VK_VRS=2x2`(需手动开启):每 60 帧 4.37 秒(≈13.7 FPS),仍为 GPU 瓶颈;边缘清晰,纹理略软。
|
||||
|
||||
## Submission boundary / 提交边界
|
||||
|
||||
Deferred commits, reusable fence slots (eight since the update above) and completion publication are implemented. This game path still requires about four actual submissions per frame because explicit QueueFlush / CPU waits and Present end batches; after the WaitEvent change above it is two per frame. No draw creates a new fence or performs its own queue idle. Ordinary consecutive draws retain their render pass; feedback, storage writes and explicit barriers keep required boundaries. Thus the strict “one submit per frame” target has not been reached for this guest command stream.
|
||||
|
||||
已实现延迟提交与多槽 fence 轮转(上方更新后为八槽),但游戏的显式 Flush / 等待边界仍导致约 4 次真实提交 / 帧(WaitEvent 改动后为 2 次)。下一步若要继续减少次数,需要根据客体的实际同步消费点优化,不能直接删除这些边界。真实窗口的 WSI 同步优化仍待第四步验证。
|
||||
|
||||
## Validation / 验证
|
||||
|
||||
- Android host builds and links with no compiler warnings.
|
||||
- Real Vulkan device regression: `VK_PERF_TEST_PASS` for full key equality after hash collision, immutable CPU input address reuse, GPU-authored input reuse, isolated writeback snapshots across submissions, timeout / fence checks, slot rotations past the ring size, events published while the guest only polls memory, descriptor pool growth past 8,192 sets, and capacity splitting without advancing the logical fence early.
|
||||
- Invalid disk cache fallback passes the same GPU regression. Final game startup confirms a non-empty compatible disk cache load.
|
||||
- Final game capture visually checked at frame 601. Headless shutdown drained in-flight work.
|
||||
- `python3 dm/ios/tools/dm_i18n.py --check`: passes, 301 entries.
|
||||
- `python3 dm/i18n/scan_literals.py`: fails on two existing unrelated strings in `dm/ios/tools/gen_romfs_overlay.py:200` and `dm/ios/tools/drop_light.py:65`; those files were not changed by this work.
|
||||
- Khronos validation could not be enabled on this retail device: the Android loader returned `VK_ERROR_LAYER_NOT_PRESENT`, and `/data/local/debug/vulkan` is not writable by shell. No validation-layer-clean claim is made. Android's loader discovery restrictions are described in [the Android Vulkan implementation documentation](https://source.android.com/docs/core/graphics/implement-vulkan).
|
||||
- Mac / iOS runtime, real-window WSI and AAudio were not exercised. The new QueueFlush declaration/call are guarded by `__ANDROID__`.
|
||||
|
||||
Reproduction commands and environment variables are in [README.md](README.md) / [README.zh-CN.md](README.zh-CN.md). Local evidence lives in ignored `dm/android/build/perf/`: `baseline.log`, `final.log`, `gpu-tests.log`, `cache-test.log`, and `final-0601.ppm` / `.png`. The device retains the original `dmhost`; the tested binary is `dmhost-perf-final` under `/data/local/tmp/d2r`.
|
||||
@@ -0,0 +1,102 @@
|
||||
# Android shell (Adreno devices only)
|
||||
|
||||
中文: [README.zh-CN.md](README.zh-CN.md)
|
||||
|
||||
Layout (a sibling of `dm/ios/`):
|
||||
|
||||
| Path | Contents |
|
||||
|---|---|
|
||||
| `app/` | The GameActivity app: `AndroidManifest.xml`, `java/`, `res/`, the packaging script `build_apk.sh`, `art_from_ipa.py` |
|
||||
| `Sources/` | Front ends: `front_app.c` (app), `touch_app.c` (touch HUD), `front_headless.c` (adb headless host) |
|
||||
| `Makefile`, `build.mk` | Build entry point and rules; the shared host sources come from `dm/host/`, outputs go to `build/` (not in git) |
|
||||
| `tests/` | Vulkan backend device test `t_vk_perf` |
|
||||
| `../gfx/vulkan/` | The Vulkan graphics backend `nvn_vk.c` (counterpart of the Metal backend `gfx/nvn/nvn_mtl.m`) |
|
||||
|
||||
The backend (`gfx/vulkan/nvn_vk.c`) retains the NVN recorder's `mtl_*` interface. Headless rendering is verified on OnePlus 13 / Adreno 830. The app includes window management, a touch HUD, gamepad and text input, AAudio and lifecycle suspend/resume. Integration does not establish validation on every device.
|
||||
|
||||
## Build and test
|
||||
|
||||
Run from the repository root with generated host headers and your own rewritten game files:
|
||||
|
||||
```sh
|
||||
make -C dm/android headless -j8 # headless host dm/android/build/dmhost
|
||||
make -C dm/android tests
|
||||
adb push dm/android/build/tests/t_vk_perf /data/local/tmp/d2r/t_vk_perf
|
||||
adb shell /data/local/tmp/d2r/t_vk_perf
|
||||
```
|
||||
|
||||
Use `NDK=...` or `ANDROID_NDK_HOME` to override the newest local SDK NDK. The device test uses real Vulkan and checks hash collisions, reused CPU input addresses, GPU writebacks, fence rotation, event publication during memory polling, descriptor pool growth and capacity splits. Success prints `VK_PERF_TEST_PASS`.
|
||||
|
||||
| Environment variable | Purpose |
|
||||
|---|---|
|
||||
| `DM_VK_SHADERS` | Vulkan shader pack generated by `dmsh_vk.py` |
|
||||
| `DM_VK_PIPELINE_CACHE` | Driver cache file; defaults to the shader directory with vendor / device / driver version in its name |
|
||||
| `DM_DISABLE_PIPELINE_CACHE=1` | Disable the driver cache; the state-to-pipeline memory cache remains active |
|
||||
| `DM_VK_SUBRES=0` | Disable disjoint-mip layouts and use the original whole-image path for device A/B; enabled by default |
|
||||
| `DM_VK_SYNC=1` | Submit and wait at every logical commit for comparison |
|
||||
| `DM_FRAME_DIR` | Existing PPM frame capture and requested diagnostics |
|
||||
| `DM_VULKAN_VALIDATION=1` | Request the Khronos layer, which must be discoverable by Android's loader |
|
||||
| `DM_VK_PASSPROF=N` | Timestamp every render pass / dispatch of frame N and print per-pass GPU time (`PASSPROF` lines) at frame N+3 |
|
||||
| `DM_VK_VRS=WxH[:hash,...]` | Pipeline fragment shading rate for the listed pixel shaders (default: forward+ lighting `5c1ca4e7c3e4657c`); needs `VK_KHR_fragment_shading_rate`, otherwise ignored |
|
||||
| `DM_VK_AHB_POOL=1` | Try AHardwareBuffer BLOBs for memory-pool remapping before OPAQUE_FD. Off by default: on OnePlus 13 a large BLOB crashes the vendor allocator service (and the display stack with it), and it never succeeded on tested devices |
|
||||
| `DM_3D_SCALE=0.5–1.0` | 3D internal render scale (the game's own upscale shader brings it back to the output size; the UI stays at output resolution). Android default 0.8: 3D at 720 lines under a 900-line output. Dynamic levels 0.72 / 0.70 kick in only on sustained dropped frames |
|
||||
| `DM_FPS=30\|60` | Pin the frame rate. Otherwise it follows the Custom page's power-saving mode (`eco_fps`): 30 fps uses a software 30 Hz tick and hints the panel down with `ANativeWindow_setFrameRate` |
|
||||
| `DM_VK_EVENT_SYNC=1` | Restore the old WaitEvent behavior (commit and CPU-wait for all prior GPU work) for comparison |
|
||||
|
||||
Following the [Vulkan cache header contract](https://docs.vulkan.org/spec/latest/chapters/pipelines.html), loading checks size, header version, vendor / device and UUID, and falls back to an empty cache. New compilation data is saved every 60 frames and on Finish / Drain using a temporary file and rename. Cache I/O failure does not stop rendering.
|
||||
|
||||
## App (GameActivity)
|
||||
|
||||
```sh
|
||||
make -C dm/android -j8 # libd2r.so + dm/android/build/app/d2r.apk, no Gradle
|
||||
make -C dm/android install # adb install -r (ends a running game)
|
||||
```
|
||||
|
||||
`APP=1` builds the host as `libd2r.so` with `Sources/front_app.c` in place of `Sources/front_headless.c`. `build_apk.sh` uses javac (Android Studio's JBR by default), d8, aapt2, zipalign and apksigner with the debug keystore. The app is debuggable so game data can be copied in with `run-as`:
|
||||
|
||||
```sh
|
||||
adb shell run-as org.d2rmobile.app sh -c 'mkdir -p files/d2r && cp -r /data/local/tmp/d2r/dm /data/local/tmp/d2r/romfs /data/local/tmp/d2r/romfs_overlay /data/local/tmp/d2r/rt64 /data/local/tmp/d2r/save files/d2r/'
|
||||
adb shell am start -n org.d2rmobile.app/.GameActivity
|
||||
adb shell run-as org.d2rmobile.app cat files/d2r/run.log
|
||||
```
|
||||
|
||||
The data root is `files/d2r` (`dm/main.patched.bin`, `romfs`, `rt64` required). stderr goes to `run.log`; optional `env.txt` lines `KEY=VALUE` are exported before start (e.g. `DM_VK_VRS=2x2`). AAudio is on by default (`DM_AUDIO=0` mutes). UI output follows screen aspect and native height (900–1080 lines); the default 3D target is approximately 720 lines (`DM_GAME_RES` / `DM_3D_SCALE` override). Without a window (app in background) the render thread holds at Present and resumes when a new surface arrives. On front-end pages (main menu, character select / creation) the first finger becomes UI mouse clicks via `dm_ui_touch` (tap = click at the lift point, vertical drag = scroll), as on iOS; in a run the touch HUD and game-state bridge handle gestures, with unclaimed touches available to the raw touchscreen. Gamepad buttons and sticks go to the pad.
|
||||
|
||||
## Implementation and boundaries
|
||||
|
||||
- Graphics and compute pipelines use effective Vulkan state keys with full equality after hash lookup. Dynamic viewport / scissor / blend constants and resource addresses are excluded; shaders, vertex input, topology, blend, depth / stencil, feedback flags and attachment compatibility are included. Pipelines and layouts live with the device.
|
||||
- Render passes cache attachment descriptions; framebuffers cache images, mip / layer, extent and pass. Ordinary consecutive draws retain a pass. Layout transitions, copies, barriers, storage writes and feedback sampling preserve required boundaries. Texture release drains work and clears framebuffers. Adreno's GENERAL feedback path retains pass boundaries.
|
||||
- Logical NVN commits can continue recording until Present, QueueFlush, a CPU wait or capacity boundary. Eight slots (`BATCH_SLOTS`) reuse command buffers, descriptor / query pools and fences; transient resources retire only after GPU completion. A completion worker publishes events / counters for guests that only poll memory and flushes report-bearing work after 2 ms of idle time.
|
||||
- NVN `CommandBufferWaitEvent` is a GPU-side wait. If the event condition is already met by memory plus the signals queued in pending / recording batches (in submit order), the host records only a barrier and does not wait on the CPU. Only an event that no queued work can satisfy falls back to commit + CPU wait (`event_blocked` in `WAIT_PROFILE`).
|
||||
- Build the shader pack with `SB_ALIGN=64` (the `dmsh_vk.py` default). Shaders then derive SSBO offsets from `base & -64`, and vkmeta flag bit 1 lets the host bind storage buffers directly from `addr & -64` with no copy. vkmeta storage flag bit 0 means writable. Packs built with `SB_ALIGN=16` still work through the copy path.
|
||||
- CPU inputs use immutable snapshots. GPU-authored inputs stay in shared GPU buffers; ordered staging copies supply uncovered CPU bytes. Each batch snapshots its GPU writebacks to prevent subsequent batches contaminating earlier results.
|
||||
- Capacity splits retain the logical fence until the final piece completes. Explicit Flush / wait boundaries prevent a strict one-submit-per-frame guarantee.
|
||||
- Windowed present does not drain: each batch slot reuses its acquire semaphore and each swapchain image has its own present semaphore. `VK_ERROR_OUT_OF_DATE_KHR` on acquire recreates the swapchain and retries; on present it marks the swapchain for recreation at the next frame. Surface changes wait for the queue to idle before the swapchain is dropped.
|
||||
|
||||
`RENDER_PROFILE` counts actual Vulkan submissions including Present; the old counter excluded Present. `RENDER_CACHE_PROFILE` records cache reuse, pass count, pass breaks, transient buffer use and `gpu_ms` (GPU time of the interval from timestamp queries). `RENDER_INPUT_PROFILE` records uploads and shared GPU reads. `WAIT_PROFILE` splits CPU-side GPU wait time by origin (sync / event / present / slot / readtex / texrel / sampler / pooldel / finish / capture, as `ms/count`), plus `sync_lag_max` and `event_queued` / `event_blocked`.
|
||||
|
||||
See [PERFORMANCE.md](PERFORMANCE.md) for measurements and validation limits. Keep binaries, caches, logs and game screenshots under ignored `dm/android/build/` or device test directories.
|
||||
|
||||
|
||||
## Subresource layouts and cross-GPU verification
|
||||
|
||||
See [VALIDATION.md](VALIDATION.md) for this change's completed checks and outstanding device/package validation.
|
||||
|
||||
Inspired by [dodola/d2r-mobile at 642480b](https://github.com/dodola/d2r-mobile/blob/642480b7606cf4adda30bcf009eb56f87745c908/dm/gfx/nvn/nvn_vk.c), this backend tracks per-mip layouts for disjoint sampling/rendering on drivers without feedback-layout support. The bounded path covers single-layer 2D color images with 2–16 mips. Every sampled view in both graphics stages must avoid every attachment mip. Overlap, storage images, comparison sampling, depth/stencil, arrays and volumes retain the original path. Whole-image operations consolidate each run using its actual old layout, preserving pixels during upload, copies and readback.
|
||||
|
||||
No build91738 addresses, resource paths or input services were imported. The build94012 HUD/save/build integration remains in place. **Existing Adreno validation remains the supported scope. Mali requires device validation; a successful capability probe does not prove game compatibility.**
|
||||
|
||||
Game-free checks (each output directory must be new):
|
||||
|
||||
```sh
|
||||
# Host layout regression + ASan/UBSan + NDK test binary build; no device access
|
||||
python3 dm/android/tests/run_checks.py --output dm/android/build/checks-local
|
||||
# Host checks only; NDK Vulkan headers are still required
|
||||
make -C dm/android host-tests
|
||||
# Explicit device opt-in: runs test binaries, does not install/start the game
|
||||
python3 dm/android/tests/run_checks.py --output dm/android/build/checks-device --run-device --serial DEVICE_SERIAL
|
||||
```
|
||||
|
||||
Use `--ndk /path/to/ndk` and `HOST_CC` to select toolchains. `result.json` records commands, exit codes, source/binary SHA-256 and whether device/GPU checks actually ran. `t_vk_caps` emits system-driver GPU/features/extensions/formats/memory JSON; it does not inspect the app's private driver. `t_vk_perf` includes cross-stage overlap checks and real GPU multi-mip readback. Run `t_vk_perf mips` for only the added cases.
|
||||
|
||||
Compare `DM_VK_SUBRES=0` / `1` on the same build94012 game, character, location, output extent and fixed 3D scale. Record driver, actual refresh rate, SurfaceFlinger display intervals and temperature. Check pixels and save/resume before evaluating speed. Different builds/drivers and submission-only FPS are not controlled comparisons.
|
||||
@@ -0,0 +1,104 @@
|
||||
# Android 外壳(仅 Adreno 机型)
|
||||
|
||||
English: [README.md](README.md)
|
||||
|
||||
目录(与 `dm/ios/` 平级):
|
||||
|
||||
| 位置 | 内容 |
|
||||
|---|---|
|
||||
| `app/` | GameActivity 应用:`AndroidManifest.xml`、`java/`、`res/`、出包脚本 `build_apk.sh`、`art_from_ipa.py` |
|
||||
| `Sources/` | 前端:`front_app.c`(App)、`touch_app.c`(触屏 HUD)、`front_headless.c`(adb 无头宿主) |
|
||||
| `Makefile`、`build.mk` | 构建入口与规则;宿主共用源码来自 `dm/host/`,产物在 `build/`(不入库) |
|
||||
| `tests/` | Vulkan 后端设备测试 `t_vk_perf` |
|
||||
| `../gfx/vulkan/` | Vulkan 图形后端 `nvn_vk.c`(与 Metal 后端 `gfx/nvn/nvn_mtl.m` 对应) |
|
||||
|
||||
`gfx/vulkan/nvn_vk.c` 保留 NVN 记录器的 `mtl_*` 接口。目前在 OnePlus 13 / Adreno 830 上验证无头渲染。`app/` 已接入窗口、触屏 HUD、手柄、文字输入、AAudio 及前后台挂起 / 恢复。功能接入不代表所有机型已完成验证。
|
||||
|
||||
## 构建与回归
|
||||
|
||||
从仓库根目录运行,使用已生成的宿主表头与玩家自己的改写产物:
|
||||
|
||||
```sh
|
||||
make -C dm/android headless -j8 # 无头宿主 dm/android/build/dmhost
|
||||
make -C dm/android tests
|
||||
adb push dm/android/build/tests/t_vk_perf /data/local/tmp/d2r/t_vk_perf
|
||||
adb shell /data/local/tmp/d2r/t_vk_perf
|
||||
```
|
||||
|
||||
NDK 默认取 `ANDROID_NDK_HOME`,否则使用本机 Android SDK 中最新的 NDK;可传 `NDK=...`。`t_vk_perf` 使用设备上的真实 Vulkan,检查哈希碰撞、CPU 输入地址复用、GPU 写回、fence 轮转、独立内存轮询的事件发布、描述符池扩容和容量分批。通过时输出 `VK_PERF_TEST_PASS`。
|
||||
|
||||
游戏仍按现有无头宿主方式启动,额外环境变量:
|
||||
|
||||
| 变量 | 用途 |
|
||||
|---|---|
|
||||
| `DM_VK_SHADERS` | `dmsh_vk.py` 生成的 Vulkan 着色器包目录 |
|
||||
| `DM_VK_PIPELINE_CACHE` | 驱动缓存文件路径;默认放在着色器包目录,文件名包含 vendor / device / driver 版本 |
|
||||
| `DM_DISABLE_PIPELINE_CACHE=1` | 关闭驱动缓存,状态到 pipeline 的内存缓存仍启用 |
|
||||
| `DM_VK_SUBRES=0` | 关闭不重叠 mip 的独立布局,恢复整图布局路径,用于真机 A/B;默认开启 |
|
||||
| `DM_VK_SYNC=1` | 每次逻辑提交立即提交并等待,用于异步行为对照 |
|
||||
| `DM_FRAME_DIR` | 按现有规则抓取 PPM 帧与按需诊断数据 |
|
||||
| `DM_VULKAN_VALIDATION=1` | 请求 Khronos validation layer;需要 Android loader 能发现该 layer |
|
||||
| `DM_VK_PASSPROF=N` | 第 N 帧逐个 render pass / dispatch 打 GPU 时间戳,第 N+3 帧打印每个 pass 的 GPU 耗时(`PASSPROF` 行) |
|
||||
| `DM_VK_VRS=WxH[:hash,...]` | 对列出的像素着色器使用管线级可变着色率(默认只作用于前向+光照 `5c1ca4e7c3e4657c`);需要 `VK_KHR_fragment_shading_rate`,不支持时忽略 |
|
||||
| `DM_VK_AHB_POOL=1` | 内存池重映射先尝试 AHardwareBuffer BLOB,再退回 OPAQUE_FD。默认关闭:OnePlus 13 上大 BLOB 会让厂商 allocator 服务崩溃并连带显示栈重启,已测设备上也从未成功 |
|
||||
| `DM_3D_SCALE=0.5–1.0` | 3D 内部渲染比例(游戏自带的放大着色器拉回输出尺寸,界面仍按输出分辨率画)。安卓缺省 0.8:输出 900 行时 3D 为 720 行。持续掉帧时才动态降到 0.72 / 0.70 |
|
||||
| `DM_FPS=30\|60` | 钉住帧数。不设则跟自定义页的省电模式(`eco_fps`):30 帧时用软件 30 Hz 节拍,并用 `ANativeWindow_setFrameRate` 提示屏幕降刷新率 |
|
||||
| `DM_VK_EVENT_SYNC=1` | 恢复旧的 WaitEvent 行为(提交并在 CPU 上等待之前所有 GPU 工作),用于对照 |
|
||||
|
||||
按照 [Vulkan cache header 约定](https://docs.vulkan.org/spec/latest/chapters/pipelines.html),缓存加载前检查尺寸、header 版本、vendor / device 和 UUID,加载失败时创建空缓存。新编译结果每 60 帧及 Finish / Drain 时保存,使用临时文件加 rename;缓存读写失败不影响渲染。
|
||||
|
||||
## App(GameActivity)
|
||||
|
||||
```sh
|
||||
make -C dm/android -j8 # libd2r.so + dm/android/build/app/d2r.apk,不用 Gradle
|
||||
make -C dm/android install # adb install -r(会结束正在运行的游戏)
|
||||
```
|
||||
|
||||
`APP=1` 把宿主编成 `libd2r.so`,用 `Sources/front_app.c` 取代 `Sources/front_headless.c`。`build_apk.sh` 使用 javac(默认 Android Studio 自带 JBR)、d8、aapt2、zipalign 和 apksigner(debug keystore)。应用是 debuggable 的,游戏数据可以用 `run-as` 拷进去:
|
||||
|
||||
```sh
|
||||
adb shell run-as org.d2rmobile.app sh -c 'mkdir -p files/d2r && cp -r /data/local/tmp/d2r/dm /data/local/tmp/d2r/romfs /data/local/tmp/d2r/romfs_overlay /data/local/tmp/d2r/rt64 /data/local/tmp/d2r/save files/d2r/'
|
||||
adb shell am start -n org.d2rmobile.app/.GameActivity
|
||||
adb shell run-as org.d2rmobile.app cat files/d2r/run.log
|
||||
```
|
||||
|
||||
数据根目录是 `files/d2r`(必须有 `dm/main.patched.bin`、`romfs`、`rt64`)。stderr 写入 `run.log`;可选的 `env.txt` 每行 `KEY=VALUE`,启动前导出(例如 `DM_VK_VRS=2x2`)。AAudio 默认启用,`DM_AUDIO=0` 可静音。界面输出按屏幕比例和原生高度(900–1080 行),默认 3D 目标约 720 行,`DM_GAME_RES` / `DM_3D_SCALE` 可覆盖。没有窗口(应用在后台)时渲染线程停在 Present,新 surface 到来后继续。前端页(主菜单、选角 / 建角)上第一根手指经 `dm_ui_touch` 变成界面鼠标点击(点按 = 抬起处点击,纵向拖 = 滚动),与 iOS 相同;局内由触屏 HUD 和游戏状态桥接处理,未消费触点仍可交给原始触摸屏。手柄按键与摇杆送到 pad。
|
||||
|
||||
## 性能实现与边界
|
||||
|
||||
- 图形与计算 pipeline 按实际 Vulkan 状态构造 key,哈希定位后比较完整 key。动态 viewport / scissor / blend constants、资源地址不进入 key;shader、顶点布局、拓扑、混合、深度 / 模板、反馈标志、附件兼容性进入 key。pipeline 和 layout 随 device 保留。
|
||||
- render pass 按附件描述缓存,framebuffer 按 image、mip / layer、尺寸和 pass 缓存。同一 framebuffer 上普通连续 draw 保持在一个 pass 内;布局转换、复制、屏障、存储写入及反馈采样保留所需边界。释放纹理前 Drain,并清理 framebuffer 缓存。Adreno 的 GENERAL 反馈路径保留 pass 边界。
|
||||
- NVN 逻辑提交可继续向当前 Vulkan command buffer 编码;Present、QueueFlush、CPU 等待、容量上限才提交。八个槽位(`BATCH_SLOTS`)复用 command buffer、descriptor / query pool 和 fence;临时资源在 GPU 完成后释放。事件 / counter 的后台完成线程可在游戏只轮询内存时发布结果;含报告的未提交工作空闲 2 ms 后会提交。
|
||||
- NVN `CommandBufferWaitEvent` 是 GPU 侧等待。若事件条件由当前内存值加上待完成 / 录制中批次里按提交顺序排队的 signal 即可满足,宿主只录一个屏障,不在 CPU 上等待;只有排队工作无法满足的事件才退回提交 + CPU 等待(`WAIT_PROFILE` 中的 `event_blocked`)。
|
||||
- 着色器包用 `SB_ALIGN=64` 构建(`dmsh_vk.py` 默认值):着色器按 `base & -64` 计算 SSBO 偏移,vkmeta 标志 bit 1 让宿主直接从 `addr & -64` 绑定存储缓冲区,无需拷贝;bit 0 表示可写。`SB_ALIGN=16` 的旧包仍走拷贝路径。
|
||||
- CPU 输入使用不可变上传快照。GPU 生成的输入直接读共享 GPU 缓冲区,未覆盖的 CPU 数据通过有序 staging copy 上传。每批 GPU 写回先拷到独立读回副本,防止后批写入污染前批结果。
|
||||
- 容量不足可在一个逻辑提交内分批,逻辑 fence 在最后一批完成后才可见。显式 Flush / 等待仍会打断合帧,因此不能保证所有游戏路径严格每帧一次提交。
|
||||
- 有窗口时 Present 不再 Drain:每个批次槽位复用自己的 acquire 信号量,每张 swapchain 图像有独立的 present 信号量。acquire 遇到 `VK_ERROR_OUT_OF_DATE_KHR` 时重建 swapchain 并重试一次;present 遇到时标记,在下一帧重建。surface 变化时先等队列空闲再销毁 swapchain。
|
||||
|
||||
`RENDER_PROFILE` 计时并统计实际 Vulkan 提交(包括 Present);`RENDER_CACHE_PROFILE` 记录 pipeline 命中、pass / framebuffer 复用、pass 次数与打断次数、临时缓冲区用量,以及 `gpu_ms`(时间戳查询得到的区间 GPU 时间);`RENDER_INPUT_PROFILE` 记录上传和共享 GPU 输入;`WAIT_PROFILE` 按来源拆分 CPU 等待 GPU 的时间(sync / event / present / slot / readtex / texrel / sampler / pooldel / finish / capture,格式 `毫秒/次数`),并给出 `sync_lag_max` 与 `event_queued` / `event_blocked`。旧后端的提交统计不包含 Present,比较时需注意口径。
|
||||
|
||||
2026-10-13 的实测和限制见 [PERFORMANCE.md](PERFORMANCE.md)。构建文件、缓存、日志、游戏截图均留在 `dm/android/build/` 或设备测试目录,不入库。
|
||||
|
||||
|
||||
## 子资源布局与跨 GPU 验证
|
||||
|
||||
本次实现、已通过检查及尚未执行的真机项目见 [VALIDATION.md](VALIDATION.md)。
|
||||
|
||||
参考 [dodola/d2r-mobile 的 Vulkan 实现(642480b)](https://github.com/dodola/d2r-mobile/blob/642480b7606cf4adda30bcf009eb56f87745c908/dm/gfx/nvn/nvn_vk.c),本分支增加按 mip 跟踪布局。在不提供反馈布局扩展的驱动上,单层 2D 颜色纹理的 2–16 级 mip 链可以在不重叠的级别上同时采样与渲染,避免把这类操作误当作整张图像的反馈。两个图形着色阶段的所有采样范围都参与判断;存在任一重叠、存储图像或比较采样时继续采用原来的整图路径。深度 / 模板、数组和体纹理也沿用原路径。复制、上传、清屏和读回前会按每段实际旧布局合并整图状态。
|
||||
|
||||
没有移植 build91738 的游戏地址、资源路径或输入服务。现有 build94012 的 HUD、存档和构建入口保留。**目前支持范围仍以原有 Adreno 验证为准,Mali 需要真机验证;能力探针成功不等于游戏兼容。**
|
||||
|
||||
不依赖游戏资源的检查(输出目录必须不存在):
|
||||
|
||||
```sh
|
||||
# 本机布局回归 + ASan/UBSan + NDK 编译设备测试程序;不连接设备
|
||||
python3 dm/android/tests/run_checks.py --output dm/android/build/checks-local
|
||||
# 仅本机回归,仍需 NDK 提供 Vulkan 头文件
|
||||
make -C dm/android host-tests
|
||||
# 指定设备后才推送测试程序并执行;不安装 APK,不访问游戏与存档
|
||||
python3 dm/android/tests/run_checks.py --output dm/android/build/checks-device --run-device --serial DEVICE_SERIAL
|
||||
```
|
||||
|
||||
`--ndk /path/to/ndk` 可指定 NDK,`HOST_CC` 可指定本机编译器。`result.json` 记录每条命令的退出状态、日志、源文件 / 设备产物 SHA-256,以及是否连接设备、是否执行 GPU。`t_vk_caps` 输出系统 Vulkan 驱动的 GPU、特性、扩展、格式及内存类型 JSON,不代表 App 选择的私有驱动。`t_vk_perf` 新增跨着色阶段重叠判断和真实 GPU 多 mip 像素读回检查;单独执行 `t_vk_perf mips` 可只跑新增用例。
|
||||
|
||||
后续 Mali / Adreno 验收应使用相同 build94012 游戏文件、角色、位置、输出尺寸和固定 3D 比例,分别测试 `DM_VK_SUBRES=0` / `1`。同时记录驱动、实际屏幕刷新率、SurfaceFlinger 显示间隔和温度。先过像素及存档 / 恢复检查,再判断性能;旧版游戏、不同驱动或只统计提交帧的 FPS 不作直接比较。
|
||||
@@ -0,0 +1,240 @@
|
||||
// Android App 前端(libd2r.so,由 GameActivity 加载):替换无头的 front_headless.c。
|
||||
// 宿主照常从 main() 起跑(在 JNI 起的线程里),这里给它窗口、输入、软键盘和前后台切换。
|
||||
// 游戏数据放在 App 私有目录 files/d2r/(dm/ 模块、romfs/、romfs_overlay/、rt64/ 着色器包、save/、temp/);
|
||||
// files/d2r/env.txt 每行 KEY=VALUE 在起跑前 setenv(调试开关,如 DM_VK_VRS=2x2)。日志写 files/d2r/run.log。
|
||||
// Android app front end (libd2r.so, loaded by GameActivity): replaces the headless front_headless.c.
|
||||
// The host starts from main() as usual (on a thread started over JNI); this file gives it the window, input, software keyboard and foreground / background switching.
|
||||
// Game data lives in the app's private directory files/d2r/ (dm/ modules, romfs/, romfs_overlay/, rt64/ shader pack, save/, temp/);
|
||||
// each KEY=VALUE line of files/d2r/env.txt is setenv'd before start (debug switches such as DM_VK_VRS=2x2). The log is written to files/d2r/run.log.
|
||||
#include "../../host/dm.h"
|
||||
#include "../../host/hle.h"
|
||||
#include "../../host/front.h"
|
||||
#include "../../host/dm_input.h"
|
||||
#include "../../host/dm_padmap.h"
|
||||
#include "../../host/dm_cursor.h"
|
||||
#include "../../gfx/vulkan/vk_platform.h"
|
||||
#include <jni.h>
|
||||
#include <android/native_window_jni.h>
|
||||
#include <android/log.h>
|
||||
#include <fcntl.h>
|
||||
#include <math.h>
|
||||
#include <signal.h>
|
||||
#include <stdatomic.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv);
|
||||
|
||||
static char g_root[512];
|
||||
static unsigned g_screen_w, g_screen_h;
|
||||
static _Atomic int g_started, g_window;
|
||||
|
||||
static void path_of(char *out, size_t n, const char *leaf) { snprintf(out, n, "%s/%s", g_root, leaf); }
|
||||
static int exists(const char *p) { struct stat st; return !stat(p, &st); }
|
||||
|
||||
// env.txt:KEY=VALUE 每行一条,# 开头为注释 | env.txt: one KEY=VALUE per line, lines starting with # are comments
|
||||
static void env_file(void) {
|
||||
char p[600]; path_of(p, sizeof p, "env.txt"); FILE *f = fopen(p, "r"); if (!f) return;
|
||||
char line[1024];
|
||||
while (fgets(line, sizeof line, f)) {
|
||||
line[strcspn(line, "\r\n")] = 0; char *eq = strchr(line, '=');
|
||||
if (line[0] == '#' || !eq) continue;
|
||||
*eq = 0; setenv(line, eq + 1, 1); LOG("app: env %s=%s", line, eq + 1);
|
||||
}
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
static void *host_thread(void *unused) {
|
||||
(void)unused;
|
||||
char dm[600]; path_of(dm, sizeof dm, "dm");
|
||||
char *argv[] = {"dmhost", dm, "main", "sdk", NULL};
|
||||
int rc = main(4, argv);
|
||||
LOG("app: 宿主 main 返回 %d | host main returned %d", rc, rc);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// ---- front.h ----
|
||||
// 客体在 64 MB 栈的线程里跑(与无头前端、iOS 壳一致)| The guest runs on a thread with a 64 MB stack (same as the headless front end and the iOS shell)
|
||||
static void *guest_thread(void *p) {
|
||||
static char alt[65536]; // 信号备用栈每线程一份:客体栈溢出时崩溃打印也要能跑 | per-thread alternate signal stack, so the crash printout runs even on guest stack overflow
|
||||
stack_t ss = {.ss_sp = alt, .ss_size = sizeof alt}; sigaltstack(&ss, NULL);
|
||||
sigset_t all; sigfillset(&all); pthread_sigmask(SIG_UNBLOCK, &all, NULL); // JNI 线程继承了 ART 的信号屏蔽字 | the JNI thread inherited ART's signal mask
|
||||
void touch_app_guest_start(void); touch_app_guest_start(); // 触屏 HUD(touch_app.c)| touch HUD (touch_app.c)
|
||||
((void (*)(void))p)(); return NULL;
|
||||
}
|
||||
void front_run(void (*guest)(void)) {
|
||||
pthread_attr_t a; pthread_t t;
|
||||
pthread_attr_init(&a); pthread_attr_setstacksize(&a, 64 << 20);
|
||||
if (pthread_create(&t, &a, guest_thread, (void *)guest)) die("建客体线程失败");
|
||||
pthread_join(t, NULL);
|
||||
}
|
||||
// 只当「有窗口」标志用(hle_swkbd 据此决定弹不弹输入框)| Used only as a "has a window" flag (hle_swkbd decides from it whether to show the input box)
|
||||
void *front_metal_layer(void) { return (void *)(uintptr_t)1; }
|
||||
// 主机档:屏幕原生高(夹在 900–1080)× 屏幕比例(宽取 8 的倍数,≤ 4096);掌机档 720 同比。比 16:9 窄的屏按 16:9。DM_GAME_RES=宽x高 覆盖
|
||||
// Docked profile: the screen's native height (clamped to 900–1080) × the screen aspect ratio (width rounded to a multiple of 8, ≤ 4096); handheld uses 720 the same way. Screens narrower than 16:9 use 16:9. DM_GAME_RES=WxH overrides
|
||||
uint64_t front_game_res(int docked) {
|
||||
unsigned w, h; const char *e = getenv("DM_GAME_RES");
|
||||
if (e && sscanf(e, "%ux%u", &w, &h) == 2) return docked ? (uint64_t)h << 32 | w : (uint64_t)(h * 4 / 5) << 32 | (w * 4 / 5 + 3) / 4 * 4;
|
||||
double aspect = g_screen_w && g_screen_h ? (double)g_screen_w / g_screen_h : 16.0 / 9;
|
||||
if (aspect < 16.0 / 9) aspect = 16.0 / 9;
|
||||
// 主机档按屏幕原生高(900–1080 之间):界面与文字 1:1 上屏,不再经 1.2 倍线性放大发糊;3D 目标仍按 720 高(hle_oe.c),GPU 不变(OnePlus 13 实测 12.1 → 12.0 ms/帧)。
|
||||
// 上限 1080:2K 屏(1440 高)界面多画 78% 像素,换来的清晰度看不出
|
||||
// Docked uses the screen's native height (between 900 and 1080): UI and text go to the screen 1:1 instead of a blurry 1.2x linear upscale; the 3D target stays 720 high (hle_oe.c), GPU unchanged (OnePlus 13 measured 12.1 -> 12.0 ms/frame).
|
||||
// Capped at 1080: on 2K screens (1440 high) the UI would draw 78% more pixels for sharpness nobody can see
|
||||
uint64_t sh = g_screen_h < 900 ? 900 : g_screen_h > 1080 ? 1080 : g_screen_h, hh = docked ? sh : 720, ww = (uint64_t)llround(hh * aspect / 8) * 8;
|
||||
if (ww > 4096) ww = 4096;
|
||||
return hh << 32 | ww;
|
||||
}
|
||||
|
||||
// 软键盘:客体线程挂一条请求并阻塞;Java 界面线程轮询 nativeTextRequest 弹框,结果经 nativeTextResult 交回
|
||||
// Software keyboard: the guest thread posts a request and blocks; the Java UI thread polls nativeTextRequest to show the dialog and returns the result via nativeTextResult
|
||||
static pthread_mutex_t text_mu = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t text_cv = PTHREAD_COND_INITIALIZER;
|
||||
static struct { int pending, done, ok, max_chars; const char *title, *sub, *guide, *initial; char result[1024]; } g_text;
|
||||
int front_text_input(const char *title, const char *sub, const char *guide, const char *initial, int max_chars, char *out, int out_cap) {
|
||||
pthread_mutex_lock(&text_mu);
|
||||
g_text.title = title ? title : ""; g_text.sub = sub ? sub : ""; g_text.guide = guide ? guide : ""; g_text.initial = initial ? initial : "";
|
||||
g_text.max_chars = max_chars; g_text.done = 0; g_text.pending = 1;
|
||||
while (!g_text.done) pthread_cond_wait(&text_cv, &text_mu);
|
||||
int ok = g_text.ok; if (ok) snprintf(out, (size_t)out_cap, "%s", g_text.result);
|
||||
pthread_mutex_unlock(&text_mu);
|
||||
return ok;
|
||||
}
|
||||
|
||||
// ---- JNI ----
|
||||
#define JNI(name) JNICALL Java_org_d2rmobile_app_GameActivity_##name
|
||||
|
||||
// root = files/d2r;返回 0 = 已起跑,否则错误码(缺文件等)| root = files/d2r; returns 0 = started, otherwise an error code (missing files etc.)
|
||||
JNIEXPORT jint JNI(nativeStart)(JNIEnv *env, jclass cls, jstring root, jint screen_w, jint screen_h) {
|
||||
(void)cls;
|
||||
if (atomic_exchange(&g_started, 1)) return 0;
|
||||
const char *r = (*env)->GetStringUTFChars(env, root, NULL); snprintf(g_root, sizeof g_root, "%s", r); (*env)->ReleaseStringUTFChars(env, root, r);
|
||||
g_screen_w = (unsigned)(screen_w > screen_h ? screen_w : screen_h); g_screen_h = (unsigned)(screen_w > screen_h ? screen_h : screen_w);
|
||||
char p[600];
|
||||
path_of(p, sizeof p, "run.log"); int fd = open(p, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
|
||||
if (fd >= 0) { dup2(fd, 2); close(fd); setvbuf(stderr, NULL, _IONBF, 0); }
|
||||
if (chdir(g_root)) { __android_log_print(ANDROID_LOG_ERROR, "d2r", "chdir %s failed", g_root); return 2; }
|
||||
path_of(p, sizeof p, "dm/main.patched.bin"); if (!exists(p)) return 3;
|
||||
path_of(p, sizeof p, "romfs"); if (!exists(p)) return 4;
|
||||
path_of(p, sizeof p, "rt64"); if (!exists(p)) return 5;
|
||||
// 缺省值:命令行版 run.sh 的那几项;env.txt 可覆盖 | Defaults: the items of the command-line run.sh; env.txt may override
|
||||
setenv("DM_ROOT", g_root, 1);
|
||||
path_of(p, sizeof p, "romfs"); setenv("DM_ROMFS", p, 1);
|
||||
path_of(p, sizeof p, "romfs_overlay"); if (exists(p)) setenv("DM_ROMFS_OVERLAY", p, 1);
|
||||
path_of(p, sizeof p, "save"); mkdir(p, 0755); setenv("DM_SAVE", p, 1);
|
||||
path_of(p, sizeof p, "temp"); mkdir(p, 0755); setenv("DM_TEMP", p, 1);
|
||||
path_of(p, sizeof p, "rt64"); setenv("DM_VK_SHADERS", p, 1);
|
||||
// App 总有窗口,只是熄屏启动时第一次出图前还没拿到:出图间隔模式不能靠那一刻「有没有窗口」定(否则锁成 game 模式的间隔 2 = 30 帧)
|
||||
// The app always has a window, it just may not have one yet before the first present when started with the screen off: the present interval mode must not be decided by "is there a window" at that moment (that locks game mode, interval 2 = 30 fps)
|
||||
setenv("DM_PRESENT_INTERVAL", "display", 1);
|
||||
env_file();
|
||||
LOG("app: 起跑 root=%s screen=%ux%u game=%llux%llu", g_root, g_screen_w, g_screen_h,
|
||||
(unsigned long long)(uint32_t)front_game_res(1), (unsigned long long)(front_game_res(1) >> 32));
|
||||
dm_vk_hold_without_window(1);
|
||||
pthread_attr_t a; pthread_t t;
|
||||
pthread_attr_init(&a); pthread_attr_setstacksize(&a, 8 << 20);
|
||||
if (pthread_create(&t, &a, host_thread, NULL)) return 6;
|
||||
pthread_detach(t);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// surface = NULL:窗口没了(切后台 / 销毁),出图阻塞到窗口回来 | surface = NULL: the window is gone (background / destroyed), present blocks until it returns
|
||||
JNIEXPORT void JNI(nativeSurface)(JNIEnv *env, jclass cls, jobject surface, jfloat hz) {
|
||||
(void)cls;
|
||||
ANativeWindow *w = surface ? ANativeWindow_fromSurface(env, surface) : NULL;
|
||||
if (hz > 0) dm_vk_set_display_hz((int)(hz + 0.5f));
|
||||
dm_vk_set_window(w); // 后端自己 acquire 一份 | the backend acquires its own reference
|
||||
if (w) ANativeWindow_release(w);
|
||||
atomic_store(&g_window, w != NULL);
|
||||
LOG("app: surface %s", w ? "attached" : "detached");
|
||||
}
|
||||
|
||||
// ---- 前后台(同 iOS front_ios_focus_event)| foreground / background (same as iOS front_ios_focus_event) ----
|
||||
// 进后台(onStop):局内先请游戏存一次盘、等提交完成再挂起。等的时候游戏主循环照常跑,窗口可能已经没了,所以临时不让出图因「没窗口」阻塞
|
||||
// (没窗口就照常回放、不上屏,同 adb 无头);等到「出现过存档提交、之后 0.2 秒没有新提交」(角色与共享箱分两次),最多 2.5 秒。
|
||||
// 之后 dm_gfx_suspend(1) 挡住后续提交 / 出图——必须在恢复「没窗口阻塞」之前:出图若已停在等窗口,挂起会等它退出而卡死
|
||||
// Entering background (onStop): in a run, first ask the game to save once and wait for the commit before suspending. While waiting the game main loop runs as usual and the window may already be gone, so presents temporarily do not block on "no window"
|
||||
// (with no window they replay as usual without presenting, like adb headless); wait until "a save commit has appeared and no new commit for 0.2 s after it" (character and shared stash commit separately), at most 2.5 s.
|
||||
// Then dm_gfx_suspend(1) blocks later submits / presents -- this must come before "block without window" is restored: if a present were already parked waiting for a window, the suspend would wait for it to exit and deadlock
|
||||
static void background_wait_save(void) {
|
||||
int dm_ingame_now(void); uint64_t dm_fs_commit_count(void); int dm_request_save(void);
|
||||
if (!dm_ingame_now() || !dm_request_save()) return; // 让游戏下一拍走它自己的定时存盘(diag.c) | let the game run its own timed save on the next tick (diag.c)
|
||||
uint64_t c0 = dm_fs_commit_count(), t0 = now_ns(), last = c0, last_t = 0;
|
||||
for (;;) {
|
||||
usleep(20000);
|
||||
uint64_t c = dm_fs_commit_count(), t = now_ns();
|
||||
if (c != last) { last = c; last_t = t; }
|
||||
if (last_t && t - last_t >= 200000000ull) break;
|
||||
if (t - t0 >= 2500000000ull) break;
|
||||
}
|
||||
LOG("app: 进后台等游戏存盘 %.0f ms,期间存档提交 %llu 次%s", (now_ns() - t0) / 1e6, (unsigned long long)(last - c0), last == c0 ? "【红】(2.5 秒内没等到)" : "");
|
||||
}
|
||||
// 失活(onPause)也请游戏存一次盘、不等:多任务界面里直接划掉进程时未必走得到 onStop 的存盘;30 秒内只请一次
|
||||
// Pausing (onPause) also asks the game to save once without waiting: swiping the process away in the recents screen may not reach the onStop save; at most once per 30 s
|
||||
static void resign_save(void) {
|
||||
int dm_ingame_now(void); int dm_request_save(void);
|
||||
static uint64_t last; uint64_t now = now_ns();
|
||||
if (!dm_ingame_now() || (last && now - last < 30000000000ull)) return;
|
||||
if (dm_request_save()) { last = now; LOG("app: 失活,请游戏下一拍存一次盘(不等)"); }
|
||||
}
|
||||
// ev:0 onPause(失活)、1 onStop(进后台)、2 onStart(回前台)、3 onResume(激活)。在 UI 线程调;1 最多挡 2.5 秒
|
||||
// ev: 0 onPause (resign active), 1 onStop (background), 2 onStart (foreground), 3 onResume (active). Called on the UI thread; 1 blocks for at most 2.5 s
|
||||
JNIEXPORT void JNI(nativeLifecycle)(JNIEnv *env, jclass cls, jint ev) {
|
||||
(void)env; (void)cls;
|
||||
static const char *k[] = {"onPause", "onStop", "onStart", "onResume"};
|
||||
static int bg; // 进过后台、还没回前台(第一次 onStart 没有对应的 onStop) | went to background and not back yet (the first onStart has no matching onStop)
|
||||
if (ev < 0 || ev > 3 || !atomic_load(&g_started)) return;
|
||||
{ uint64_t guest_ns(void); LOG("app: %s(客体时钟 %.3f s)", k[ev], guest_ns() / 1e9); }
|
||||
void guest_clock_freeze_for(int reason, int on); void dm_ui_lifecycle(int background); void dm_3d_scale_resumed(void);
|
||||
switch (ev) {
|
||||
case 0: dm_focus_set(2); resign_save(); break; // 触点、手柄键由 Java 端先清 | touches and controller keys are cleared on the Java side first
|
||||
// 客体时钟一并冻结(等效 Switch 挂起):否则回来时游戏内时间一下跳过整段后台时长 | the guest clock is frozen as well (like Switch suspend): otherwise in-game time jumps over the whole background period on return
|
||||
case 1: dm_focus_set(3); dm_ui_lifecycle(1); dm_audio_suspend(1);
|
||||
dm_vk_hold_without_window(0); background_wait_save(); dm_gfx_suspend(1); dm_vk_hold_without_window(1);
|
||||
guest_clock_freeze_for(1, 1); bg = 1; break;
|
||||
case 2: if (!bg) break; bg = 0;
|
||||
dm_ui_lifecycle(0); dm_3d_scale_resumed(); dm_gfx_suspend(0); guest_clock_freeze_for(1, 0); dm_audio_suspend(0); dm_focus_set(2); break; // 窗口未回来前出图仍停在等窗口 | until the window returns, presents still park waiting for it
|
||||
case 3: dm_focus_set(1); break;
|
||||
}
|
||||
}
|
||||
|
||||
// 游戏已出的帧数,Java 端据此算 FPS 标签 | frames the game has presented, for the Java FPS label
|
||||
JNIEXPORT jlong JNI(nativeFrames)(JNIEnv *env, jclass cls) {
|
||||
(void)env; (void)cls;
|
||||
extern uint64_t mtl_present_count(void);
|
||||
return (jlong)mtl_present_count();
|
||||
}
|
||||
|
||||
// 触点由 touch_app.c 的 nativeTouchEvent 接 | touches are taken by nativeTouchEvent in touch_app.c
|
||||
|
||||
// 实体手柄:face 位 0–3 = 下 / 右 / 左 / 上面键(按位置),其余按钮已是 DM_BTN_* 位;摇杆 ±1 浮点
|
||||
// Physical controller: face bits 0–3 = bottom / right / left / top face buttons (by position), other buttons already as DM_BTN_* bits; sticks as ±1 floats
|
||||
JNIEXPORT void JNI(nativePad)(JNIEnv *env, jclass cls, jint face, jint other, jboolean nintendo, jfloat lx, jfloat ly, jfloat rx, jfloat ry) {
|
||||
(void)env; (void)cls;
|
||||
uint64_t b = dm_padmap_face(nintendo ? DM_PADKIND_NINTENDO : DM_PADKIND_XBOX, face & 1, face >> 1 & 1, face >> 2 & 1, face >> 3 & 1) | (uint32_t)other;
|
||||
// Android 的 Y 轴向下为正,nn::hid 向上为正 | Android's Y axis is positive downwards, nn::hid's is positive upwards
|
||||
void touch_app_pad(uint64_t, int32_t, int32_t, int32_t, int32_t);
|
||||
touch_app_pad(b, (int32_t)(lx * DM_STICK_MAX), (int32_t)(-ly * DM_STICK_MAX), (int32_t)(rx * DM_STICK_MAX), (int32_t)(-ry * DM_STICK_MAX));
|
||||
}
|
||||
|
||||
// 软键盘请求:没有就返回 null;有则 [标题, 说明, 提示, 初值, 最大字数] | Software keyboard request: null if none, otherwise [title, subtitle, hint, initial, max chars]
|
||||
JNIEXPORT jobjectArray JNI(nativeTextRequest)(JNIEnv *env, jclass cls) {
|
||||
(void)cls; jobjectArray a = NULL;
|
||||
pthread_mutex_lock(&text_mu);
|
||||
if (g_text.pending) {
|
||||
g_text.pending = 0; char max[16]; snprintf(max, sizeof max, "%d", g_text.max_chars);
|
||||
const char *v[5] = {g_text.title, g_text.sub, g_text.guide, g_text.initial, max};
|
||||
a = (*env)->NewObjectArray(env, 5, (*env)->FindClass(env, "java/lang/String"), NULL);
|
||||
for (int i = 0; i < 5; i++) (*env)->SetObjectArrayElement(env, a, i, (*env)->NewStringUTF(env, v[i]));
|
||||
}
|
||||
pthread_mutex_unlock(&text_mu);
|
||||
return a;
|
||||
}
|
||||
JNIEXPORT void JNI(nativeTextResult)(JNIEnv *env, jclass cls, jboolean ok, jstring text) {
|
||||
(void)cls;
|
||||
pthread_mutex_lock(&text_mu);
|
||||
g_text.ok = ok && text; g_text.result[0] = 0;
|
||||
if (g_text.ok) { const char *s = (*env)->GetStringUTFChars(env, text, NULL); snprintf(g_text.result, sizeof g_text.result, "%s", s); (*env)->ReleaseStringUTFChars(env, text, s); }
|
||||
g_text.done = 1; pthread_cond_broadcast(&text_cv);
|
||||
pthread_mutex_unlock(&text_mu);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// Android 无头前端(adb shell 直接跑 dmhost,先跑通引导链):无窗口、无输入框,客体在当前线程跑;GameActivity 前端接上后由它替换
|
||||
// Android headless front end (run dmhost straight from adb shell to get the boot chain working first): no window, no input box, the guest runs on the current thread; replaced by the GameActivity front end once that is wired up
|
||||
#include "../../host/dm.h"
|
||||
#include "../../host/front.h"
|
||||
// 客体在 64 MB 栈的线程里跑(与 iOS 壳的 boot_thread 一致;adb shell 主线程栈只有 8 MB)
|
||||
// The guest runs on a thread with a 64 MB stack (same as the iOS shell's boot_thread; the adb shell main thread has only 8 MB)
|
||||
static void *guest_thread(void *p) { ((void (*)(void))p)(); return NULL; }
|
||||
void front_run(void (*guest)(void)) {
|
||||
pthread_attr_t a; pthread_t t;
|
||||
pthread_attr_init(&a); pthread_attr_setstacksize(&a, 64 << 20);
|
||||
if (pthread_create(&t, &a, guest_thread, (void *)guest)) die("建客体线程失败");
|
||||
pthread_join(t, NULL);
|
||||
}
|
||||
void *front_metal_layer(void) { return NULL; }
|
||||
// 与 front_mac.m 同一规则:DM_GAME_RES=宽x高 指定主机模式分辨率,掌机模式取 4/5
|
||||
// Same rule as front_mac.m: DM_GAME_RES=WxH sets the docked resolution, handheld takes 4/5 of it
|
||||
uint64_t front_game_res(int docked) {
|
||||
unsigned w, h; const char *e = getenv("DM_GAME_RES");
|
||||
if (e && sscanf(e, "%ux%u", &w, &h) == 2) return docked ? (uint64_t)h << 32 | w : (uint64_t)(h * 4 / 5) << 32 | (w * 4 / 5 + 3) / 4 * 4;
|
||||
return docked ? 900ull << 32 | 1600 : 720ull << 32 | 1280;
|
||||
}
|
||||
int front_text_input(const char *title, const char *sub, const char *guide, const char *initial, int max_chars, char *out, int out_cap) {
|
||||
(void)title; (void)sub; (void)guide; (void)initial; (void)max_chars; (void)out; (void)out_cap;
|
||||
return -1;
|
||||
}
|
||||
@@ -0,0 +1,702 @@
|
||||
// Android 局内触屏操作层:front_ios.m 里 DmMetalView(手势 → 手势层 dm_touch_controls → 宿主)与 DmTouchOverlay(画操作层)的移植。
|
||||
// 坐标一律用 dp(≈ UIKit 点):Java 传视图尺寸、安全边距与触点时已除以 density。
|
||||
// 线程:触点、每帧 tick、绘制都在 Java 界面线程;界面消息(touch_ui_message)在客体线程,只写原子量,界面线程 tick 时取用
|
||||
// (iOS 这里用 dispatch_async 切主线程)。绘制不直接碰 Canvas:C 产出一张绘制指令表(浮点数组 + 字符串表),Java 照表画。
|
||||
// 没移植:秘境任务条、货架拖货跟手图、测试脚本触点、操作层截图。
|
||||
// Android in-run touch layer: port of DmMetalView (gestures → gesture layer dm_touch_controls → host) and DmTouchOverlay (draws the layer) from front_ios.m.
|
||||
// All coordinates are dp (≈ UIKit points): Java divides the view size, safe insets and touch points by density before passing them.
|
||||
// Threads: touches, the per-frame tick and drawing all run on the Java UI thread; UI messages (touch_ui_message) arrive on the guest thread and only write
|
||||
// atomics that the UI-thread tick picks up (iOS uses dispatch_async to the main thread here). Drawing does not touch a Canvas: C emits a draw list
|
||||
// (float array + string table) that Java executes.
|
||||
// Not ported: Rift objective bar, the shelf-drag ghost image, scripted test touches, overlay capture.
|
||||
#include "../../host/dm.h"
|
||||
#include "../../host/front.h"
|
||||
#include "../../host/hle.h"
|
||||
#include "../../host/dm_input.h"
|
||||
#include "../../host/dm_cursor.h"
|
||||
#include "../../host/dm_hud.h"
|
||||
#include "../../host/dm_world.h"
|
||||
#include "../../host/dm_uiscreen.h"
|
||||
#include "../../host/dm_actions.h"
|
||||
#include "../../host/dm_i18n.h"
|
||||
#include "../../host/dm_custom.h"
|
||||
#include "../../touch/dm_touch_controls.h"
|
||||
#include "../../touch/dm_touch_game_state.h"
|
||||
#include "../../touch/dm_touch_native_art.h"
|
||||
#include <jni.h>
|
||||
#include <math.h>
|
||||
#include <stdatomic.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
|
||||
void dm_tp_request(void);
|
||||
int dm_drop_haptic_take(void);
|
||||
int dm_padmode_busy(void);
|
||||
void dm_padmode_request(int pad);
|
||||
uint32_t dm_padmode_rebuilds(void);
|
||||
int dm_swapskill_slot(int, int *);
|
||||
int dm_freetp_zr_free(int zl);
|
||||
void dm_ui_key_pulse_alone(uint64_t, int);
|
||||
void uimsg_subscribe(void (*)(const char *, const char *, const char *));
|
||||
|
||||
static double now_s(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec + t.tv_nsec * 1e-9; }
|
||||
#define MIN(a, b) ((a) < (b) ? (a) : (b))
|
||||
#define MAX(a, b) ((a) > (b) ? (a) : (b))
|
||||
|
||||
// ---- 客体线程 → 界面线程 | guest thread → UI thread ----
|
||||
static _Atomic int g_touch_frontend = 1, g_touch_navigation = 1, g_hud_blocked, g_cover;
|
||||
static _Atomic int g_nav_pub;
|
||||
int dm_front_navigation(void) { return atomic_load(&g_nav_pub); } // 面板 / 读取画面 / 过场开着:手柄 ZR 只在游戏态接管 | a panel / loading screen / cutscene is open: the pad's ZR is taken over only in game state
|
||||
int dm_touch_frontend(void) { return atomic_load(&g_touch_frontend); }
|
||||
static void restart_cover_hook(int on) { atomic_store(&g_cover, on); } // 0 撤 / 1 黑屏 / 2 透明但吞触点 | 0 remove / 1 black / 2 transparent but swallows touches
|
||||
|
||||
// ---- 触摸记录:Android 指针 id 会复用,iOS 的 UITouch 身份换成记录下标 | touch records: Android pointer ids get reused, records stand in for UITouch identity ----
|
||||
enum { NREC = 32 };
|
||||
static struct { int used, pid, done; float x, y; } R[NREC];
|
||||
static int pid_rec(int pid) { for (int i = 0; i < NREC; i++) if (R[i].used && !R[i].done && R[i].pid == pid) return i; return -1; }
|
||||
|
||||
// ---- DmMetalView 状态 | DmMetalView state ----
|
||||
static dm_tc_state C;
|
||||
static float W, H; // 视图尺寸(dp) | view size (dp)
|
||||
static int g_slot[16]; // 手指槽 → 记录;-1 = 空 | finger slot → record; -1 = empty
|
||||
static uint32_t g_swallow; // 手柄模式 / 切换中 / 遮罩下落下的手指(记录位图) | fingers that landed in pad mode / mid-switch / under the cover (record bitmap)
|
||||
static int g_pad, g_fe = 1, g_nav = -1, g_blocked_applied, g_dialog_only, g_hud_blocked_v;
|
||||
static int ui_finger = -1, map_t = -1, mapback_t = -1, bind_t = -1, pend_end = -1;
|
||||
static float fe_ox, fe_oy, map_x0, map_y0, bind_x0, bind_y0; static int fe_drag, ui_drag_on;
|
||||
static double map_t0, pend_time, pend_wall; static int pend_fire, final_asked;
|
||||
static uint64_t bind_key; static uint32_t sel_id; static double stat_next, tip_until, add_at;
|
||||
static unsigned map_world_seq; static int map_world_asked; static float map_wx, map_wy;
|
||||
static int pulse_ticking; static uint64_t pulse_epoch, pulse_s0; static double pulse_t0, pulse_seen, pulse_free;
|
||||
static unsigned item_seq, rel_seq; static int rel_asked, item_asked, item_kind;
|
||||
static double labels_at; static int labels_done;
|
||||
static dm_hud_info g_hud; static dm_tg_snapshot g_native;
|
||||
static int g_dirty = 1, g_haptic;
|
||||
|
||||
static int slot_of_rec(int t) { for (int i = 0; i < 16; i++) if (g_slot[i] == t) return i; return -1; }
|
||||
static int rec_referenced(int t) { return slot_of_rec(t) >= 0 || t == ui_finger || t == map_t || t == mapback_t || t == bind_t || t == pend_end || (g_swallow >> t & 1); }
|
||||
static void gc_recs(void) { for (int i = 0; i < NREC; i++) if (R[i].used && R[i].done && !rec_referenced(i)) R[i].used = 0; }
|
||||
|
||||
static void push(void) {
|
||||
dm_touch ts[16]; int n = 0;
|
||||
if (W > 0 && H > 0) for (int i = 0; i < 16; i++) if (g_slot[i] >= 0) {
|
||||
int t = g_slot[i]; ts[n++] = (dm_touch){(uint32_t)i, fminf(fmaxf(R[t].x / W, 0), .99999f), fminf(fmaxf(R[t].y / H, 0), .99999f)};
|
||||
}
|
||||
dm_touch_set(ts, n);
|
||||
if (C.pointer_valid) dm_cursor_set_screen(C.pointer_x, C.pointer_y, W, H); else dm_cursor_clear();
|
||||
dm_input_set(C.buttons, C.lx, C.ly, C.rx, C.ry);
|
||||
if (C.belt_request) { int br = C.belt_request; C.belt_request = 0; if (br == 1 || br == 2) dm_belt_expand(br == 1); else dm_belt_use(br & 0xf, br >> 4 & 0xf); }
|
||||
if (C.diff_request) { dm_hud_request_players(C.diff_request); C.diff_request = 0; }
|
||||
g_dirty = 1;
|
||||
}
|
||||
static void cancel_controls(void) {
|
||||
pend_end = -1; final_asked = 0;
|
||||
for (int i = 0; i < 16; i++) g_slot[i] = -1;
|
||||
dm_tc_cancel_all(&C); push();
|
||||
if (ui_drag_on) { ui_drag_on = 0; dm_ui_drag_end(); }
|
||||
map_t = mapback_t = bind_t = -1;
|
||||
}
|
||||
static void set_pad_mode(int pad) {
|
||||
g_pad = pad;
|
||||
if (pad) { tip_until = -2; dm_tc_cancel_all(&C); push(); }
|
||||
g_dirty = 1;
|
||||
}
|
||||
static void set_frontend(int fe) {
|
||||
g_fe = fe;
|
||||
if (fe) { pend_end = -1; final_asked = 0; for (int i = 0; i < 16; i++) g_slot[i] = -1; dm_tc_cancel_all(&C); push(); }
|
||||
g_dirty = 1;
|
||||
}
|
||||
static void hud_blocked(int n) { g_hud_blocked_v = n > 0; g_dialog_only = n < 0; dm_tc_set_joy_block(&C, n < 0); g_dirty = 1; }
|
||||
static void navigation_mode(int n) {
|
||||
if (g_nav == n) return;
|
||||
dm_tc_set_navigation_mode(&C, n); g_nav = n; atomic_store(&g_nav_pub, n);
|
||||
static int pad = -1; if (pad < 0) { const char *e = getenv("DM_TOUCH_NAV_PAD"); pad = e && e[0] == '1'; }
|
||||
uint32_t mask = n ? (dm_tc_nav_mask(pad && n != 2) | (n == 3 ? 1u << DM_TC_MENU : 0)) : (((1u << DM_TC_COUNT) - 1) & ~(1u << DM_TC_MAP));
|
||||
dm_tc_enable_targets(&C, mask); push();
|
||||
// 进局后第一次回游戏态:替玩家按一次 L 打开物品名标签(同 iOS itemLabelsOn,1.5 秒后) | first return to game state: press L once for the player to turn item labels on (as iOS itemLabelsOn, after 1.5 s)
|
||||
if (!n && !labels_done && !labels_at) { const char *e = getenv("DM_TOUCH_DEFAULTS"); if (!(e && !strcmp(e, "0"))) labels_at = now_s() + 1.5; }
|
||||
if (n && dm_ui_map_is_full()) { dm_ui_map_full(0); LOG("前端:开了面板,全屏地图先收回小地图"); }
|
||||
}
|
||||
// 客体线程发布的状态落到界面线程 | apply the state published by the guest thread on the UI thread
|
||||
static void apply_pending(void) {
|
||||
int fe = atomic_load(&g_touch_frontend); if (fe != g_fe) set_frontend(fe);
|
||||
int hb = atomic_load(&g_hud_blocked); if (hb != g_blocked_applied) { g_blocked_applied = hb; hud_blocked(hb); }
|
||||
navigation_mode(atomic_load(&g_touch_navigation));
|
||||
}
|
||||
|
||||
// ---- 界面消息(客体线程):同 iOS hud_stack_message / touch_ui_message | UI messages (guest thread): as iOS hud_stack_message / touch_ui_message ----
|
||||
enum { HUD_STACK_MAX = 64 };
|
||||
static struct { char name[64]; int open; } g_hud_stack[HUD_STACK_MAX];
|
||||
static void hud_stack_message(const char *act, const char *arg) {
|
||||
if (!strcmp(act, "UnloadPanel") && !strcmp(arg, "LoadScreenPanel")) {
|
||||
for (int i = 0; i < HUD_STACK_MAX; i++)
|
||||
if (!(g_hud_stack[i].open > 0 && strcmp(g_hud_stack[i].name, "LoadScreenPanel") && dm_ui_panel_shown(g_hud_stack[i].name))) memset(&g_hud_stack[i], 0, sizeof g_hud_stack[i]);
|
||||
} else if (!strcmp(act, "UnloadAll")) memset(g_hud_stack, 0, sizeof g_hud_stack);
|
||||
else {
|
||||
int tog = !strcmp(act, "TogglePanel");
|
||||
int open = !strcmp(act, "OpenPanel") || !strcmp(act, "OpenExclusivePanel"), close = !strcmp(act, "ClosePanel") || !strcmp(act, "UnloadPanel");
|
||||
if (!open && !close && !tog) return;
|
||||
if (dm_ui_panel_resident(arg)) return;
|
||||
int slot = -1; for (int i = 0; i < HUD_STACK_MAX; i++) if (!strcmp(g_hud_stack[i].name, arg)) { slot = i; break; }
|
||||
if (slot < 0) for (int i = 0; i < HUD_STACK_MAX; i++) if (!g_hud_stack[i].name[0]) { slot = i; snprintf(g_hud_stack[i].name, sizeof g_hud_stack[i].name, "%s", arg); break; }
|
||||
if (slot < 0) return;
|
||||
if (tog) { open = g_hud_stack[slot].open <= 0; close = !open; }
|
||||
if (close && g_hud_stack[slot].open <= 0) return;
|
||||
if (open && g_hud_stack[slot].open > 0) return;
|
||||
g_hud_stack[slot].open = open ? 1 : 0;
|
||||
fprintf(stderr, "[hud] 面板栈 %s %s → %d\n", act, arg, g_hud_stack[slot].open);
|
||||
}
|
||||
int n = 0, dlg = 0;
|
||||
for (int i = 0; i < HUD_STACK_MAX; i++) {
|
||||
if (!strcmp(g_hud_stack[i].name, "NpcDialogPanel") || !strcmp(g_hud_stack[i].name, "ScrollSpeechPanel")) dlg |= g_hud_stack[i].open > 0;
|
||||
else n += g_hud_stack[i].open;
|
||||
}
|
||||
if (!n && dlg) n = -1;
|
||||
atomic_store(&g_hud_blocked, n);
|
||||
}
|
||||
static void touch_ui_message(const char *cat, const char *act, const char *arg) {
|
||||
if (!strcmp(cat, "PanelManager")) hud_stack_message(act, arg);
|
||||
static dm_tc_scene scene; static uint64_t scene_epoch = 1, world_epoch = 1; static int prev_mode = 1;
|
||||
dm_tc_scene before = scene;
|
||||
dm_tc_set_panel_state(dm_ui_panel_state());
|
||||
int mode = dm_tc_navigation(&scene, cat, act, arg);
|
||||
if (scene.game && atomic_load(&g_hud_blocked) > 0) mode = 1;
|
||||
if (before.game != scene.game) ++world_epoch;
|
||||
{ static uint32_t rb0; uint32_t rb = dm_padmode_rebuilds(); if (rb != rb0) { rb0 = rb; ++world_epoch; } }
|
||||
if (mode != prev_mode) ++scene_epoch;
|
||||
prev_mode = mode;
|
||||
dm_touch_game_set_scene(!mode, scene_epoch, world_epoch);
|
||||
atomic_store(&g_touch_frontend, !scene.game);
|
||||
int nmode = mode ? (dm_tc_scene_dead() ? 2 : dm_tc_scene_dialog_only(&scene) && atomic_load(&g_hud_blocked) <= 0 ? 3 : 1) : 0;
|
||||
atomic_store(&g_touch_navigation, nmode);
|
||||
dm_uiscreen_set_panel(nmode == 1);
|
||||
}
|
||||
// front_run 在客体线程开头调 | called by front_run at the start of the guest thread
|
||||
void touch_app_guest_start(void) {
|
||||
extern void (*g_dm_restart_cover_hook)(int); g_dm_restart_cover_hook = restart_cover_hook;
|
||||
uimsg_subscribe(touch_ui_message);
|
||||
dm_touch_game_live_check(1);
|
||||
if (!dm_touch_game_attach()) LOG("【红】技能绑定读取没挂上(产物没有观测门 OBS_BINDING_GETTER,或 main 模块不符):技能键图标 / 回城键绑定不工作");
|
||||
}
|
||||
|
||||
// ---- 手柄模式(iOS dm_gamepad.m 的 apply / set_mode,Android 只有一路合并后的手柄) | pad mode (iOS dm_gamepad.m apply / set_mode; Android has one merged pad) ----
|
||||
static int g_need_center;
|
||||
static void pad_set_mode(int pad) {
|
||||
if (g_pad == pad) return;
|
||||
dm_padmode_request(pad); LOG("手柄:%s", pad ? "手柄有输入 → 手柄模式" : "碰了屏幕 → 触屏模式");
|
||||
set_pad_mode(pad);
|
||||
}
|
||||
static int stick_on(int was, int32_t x, int32_t y) { double m = hypot(x, y) / DM_STICK_MAX; return was ? m >= 0.15 : m >= 0.25; }
|
||||
static uint64_t pad_b; static int32_t pad_ax[4];
|
||||
static void pad_apply(void) {
|
||||
uint64_t b = pad_b; int32_t ax[4] = {pad_ax[0], pad_ax[1], pad_ax[2], pad_ax[3]};
|
||||
static int on[2]; static uint64_t prev_b;
|
||||
on[0] = stick_on(on[0], ax[0], ax[1]); on[1] = stick_on(on[1], ax[2], ax[3]);
|
||||
if (!on[0] && !on[1]) g_need_center = 0;
|
||||
if ((b & ~prev_b) || ((on[0] || on[1]) && !g_need_center)) pad_set_mode(1);
|
||||
prev_b = b;
|
||||
if (!g_pad || !on[0]) ax[0] = ax[1] = 0;
|
||||
if (!g_pad || !on[1]) ax[2] = ax[3] = 0;
|
||||
{ static uint64_t prev; static int mine;
|
||||
if ((b & DM_BTN_ZR) && !(prev & DM_BTN_ZR)) { mine = !dm_front_navigation() && dm_freetp_zr_free((b & DM_BTN_ZL) != 0); if (mine) { dm_tp_request(); LOG("手柄:ZR(这一格空着)→ 免费回城"); } }
|
||||
prev = b; if (mine) b &= ~(uint64_t)DM_BTN_ZR; if (!(b & DM_BTN_ZR) && !(prev & DM_BTN_ZR)) mine = 0; }
|
||||
dm_pad_set(b, ax[0], ax[1], ax[2], ax[3]);
|
||||
}
|
||||
void touch_app_pad(uint64_t b, int32_t lx, int32_t ly, int32_t rx, int32_t ry) { pad_b = b; pad_ax[0] = lx; pad_ax[1] = ly; pad_ax[2] = rx; pad_ax[3] = ry; pad_apply(); }
|
||||
static void gamepad_touched(void) { if (g_pad) { g_need_center = 1; pad_set_mode(0); pad_apply(); } }
|
||||
|
||||
// ---- 手势 | gestures ----
|
||||
static uint64_t skill_key_at(float x, float y, int *empty) {
|
||||
int i = dm_tc_hit(&C.layout, x, y);
|
||||
if (i >= DM_TC_SKILL1 && i <= DM_TC_SKILL4 && (C.enabled_targets & (1u << i))) {
|
||||
const dm_tc_target *t = &C.layout.target[i];
|
||||
dm_ta_glyph g = dm_ta_current_set(&g_native, t->button, now_ns(), C.skill_set); *empty = g.status == DM_TA_EMPTY;
|
||||
return t->button | (C.skill_set ? DM_BTN_ZL : 0);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
static int in_minimap(float x, float y) {
|
||||
float r[4]; if (g_nav || W <= 0 || !dm_ui_minimap_rect(r)) return 0;
|
||||
if (dm_tc_hit(&C.layout, x, y) >= 0) return 0;
|
||||
float x0 = r[0] * W, y0 = r[1] * H, w = (r[2] - r[0]) * W, h = (r[3] - r[1]) * H, band = h / 4; if (band < 30) band = MIN(30, h * 0.4f);
|
||||
return x >= x0 && x < x0 + w && y >= y0 && y < y0 + band;
|
||||
}
|
||||
static void refresh_portal_binding(void) {
|
||||
{ dm_hud_info h; dm_hud_get(&h); h.x = h.y = 0; if (memcmp(&h, &g_hud, sizeof h)) { g_hud = h; g_dirty = 1; } }
|
||||
dm_tg_snapshot s = {0}; dm_touch_game_snapshot(&s);
|
||||
if (memcmp(&s.raw_skill_id, &g_native.raw_skill_id, sizeof s.raw_skill_id) || memcmp(&s.mapping, &g_native.mapping, sizeof s.mapping) || s.valid != g_native.valid) g_dirty = 1;
|
||||
g_native = s;
|
||||
if (g_nav || !s.supported) return;
|
||||
uint64_t mask = 0; // 回城键不跟原生绑定(同 iOS) | the portal key does not follow the native binding (as iOS)
|
||||
if (C.layout.target[DM_TC_PORTAL].button != mask || C.portal_binding_identity != s.binding_identity || C.portal_scene_epoch != s.scene_epoch) {
|
||||
dm_tc_set_portal_binding(&C, mask, s.binding_identity, s.scene_epoch); push();
|
||||
}
|
||||
}
|
||||
static void bind_tap_sync(void) {
|
||||
float nx = 0, ny = 0;
|
||||
{ static int was; int st = dm_ui_bind_active(); if (st == 2 && was != 2 && W > 0) { C.pointer_valid = 1; C.pointer_x = 0.155f * W; C.pointer_y = 0.5f * H; } was = st; }
|
||||
int hk = dm_ui_bind_skill_hit(&nx, &ny); C.tap_button = 0; C.tap_move = 0;
|
||||
if (!hk) sel_id = 0;
|
||||
if (hk) { C.tap_x = nx * W; C.tap_y = ny * H;
|
||||
if (hk == 1 && dm_ui_bind_active() == 2) C.tap_button = DM_BTN_Y;
|
||||
else if (!dm_ui_bind_active()) C.tap_move = 1; }
|
||||
}
|
||||
static void ui_touch(const int *ts, int n, int ph) {
|
||||
if (W <= 0 || H <= 0) return;
|
||||
for (int k = 0; k < n; k++) {
|
||||
int t = ts[k];
|
||||
if (ph == 0 && ui_finger < 0) { ui_finger = t; fe_ox = R[t].x; fe_oy = R[t].y; fe_drag = 0; }
|
||||
if (t != ui_finger) continue;
|
||||
float px = R[t].x, py = R[t].y, dy = fabsf(py - fe_oy);
|
||||
if (ph == 1 && !fe_drag && !ui_drag_on && dy > 10 && dy > fabsf(px - fe_ox) && dm_ui_fe_drag_ok()) {
|
||||
fe_drag = 1; ui_drag_on = 1; dm_ui_touch(3, 0, 0); dm_ui_drag_begin(1, fe_ox / W, fe_oy / H, 0);
|
||||
}
|
||||
if (fe_drag) { if (ph == 1) dm_ui_drag_move(px / W, py / H); else if (ph == 2) { fe_drag = 0; ui_drag_on = 0; dm_ui_drag_end(); ui_finger = -1; } continue; }
|
||||
dm_ui_touch(ph, px / W, py / H);
|
||||
if (ph == 2) ui_finger = -1;
|
||||
}
|
||||
}
|
||||
static void pulse_tick(void);
|
||||
static void arm_pulse_end(void) {
|
||||
if (pulse_ticking || (!C.pulse_button && !dm_tc_pulse_pending(&C))) return;
|
||||
pulse_ticking = 1; pulse_epoch = 0; pulse_tick();
|
||||
}
|
||||
static void touches_began(const int *ts, int n) {
|
||||
{ int was = g_pad; gamepad_touched();
|
||||
if (was || dm_padmode_busy() || atomic_load(&g_cover)) { for (int k = 0; k < n; k++) g_swallow |= 1u << ts[k]; if (was) LOG("前端:手柄模式下碰屏 → 只切回触屏模式,这一下不执行"); return; } }
|
||||
if (g_fe) { ui_touch(ts, n, 0); return; }
|
||||
refresh_portal_binding();
|
||||
void finish_touches(const int *, int, int);
|
||||
if (pend_end >= 0) { int pt = pend_end; pend_fire = 1; finish_touches(&pt, 1, 0); pend_fire = 0; pend_end = -1; final_asked = 0; }
|
||||
double now = now_s();
|
||||
for (int k = 0; k < n; k++) {
|
||||
int t = ts[k]; float px = R[t].x, py = R[t].y;
|
||||
{ int ex = 0; C.belt_rows = dm_belt_rows(&ex); C.belt_open = ex;
|
||||
if (dm_tc_belt_outside(&C, px, py)) { dm_belt_expand(0); LOG("前端:腰带展开着点别处 (%.0f,%.0f) → 只收腰带", px, py); continue; } }
|
||||
if (!g_nav && bind_t < 0 && !dm_ui_bind_active()) { int em = 0; uint64_t bk = skill_key_at(px, py, &em); if (bk && em) { bind_t = t; bind_key = bk; bind_x0 = px; bind_y0 = py; map_t0 = now; continue; } }
|
||||
if (map_t < 0 && in_minimap(px, py)) { map_t = t; map_x0 = px; map_y0 = py; map_t0 = now; continue; }
|
||||
for (int i = 0; i < 16; i++) if (g_slot[i] < 0) {
|
||||
g_slot[i] = t; { int ex = 0; C.belt_rows = dm_belt_rows(&ex); C.belt_open = ex; } dm_tc_begin_at(&C, i, px, py, now);
|
||||
if (!g_nav && C.finger[i].target == DM_TC_PORTAL) { dm_tp_request(); LOG("前端:点回城钮 → 免费回城"); }
|
||||
if (!g_nav && mapback_t < 0 && C.finger[i].target == DM_TC_NONE && dm_ui_map_is_full()) { mapback_t = t; map_x0 = px; map_y0 = py; map_t0 = now; }
|
||||
if (C.navigation_mode && C.pointer_slot == i && W > 0) item_seq = dm_ui_item_query(px / W, py / H);
|
||||
item_asked = 1; item_kind = -1; // iOS 原样:这两句不在 if 里 | as on iOS: these two are outside the if
|
||||
break;
|
||||
}
|
||||
}
|
||||
push();
|
||||
}
|
||||
static void touches_moved(const int *ts0, int n0) {
|
||||
int ts[NREC], n = 0; for (int k = 0; k < n0; k++) if (!(g_swallow >> ts0[k] & 1)) ts[n++] = ts0[k];
|
||||
if (!n) return;
|
||||
if (g_fe) { ui_touch(ts, n, 1); return; }
|
||||
if (ui_finger >= 0) { int m = 0, hit = 0; for (int k = 0; k < n; k++) { if (ts[k] == ui_finger) hit = 1; else ts[m++] = ts[k]; }
|
||||
if (hit) { int u = ui_finger; ui_touch(&u, 1, 1); n = m; if (!n) return; } }
|
||||
double now = now_s(); float sc = dm_tc_scale_for_size(W, H);
|
||||
for (int k = 0; k < n; k++) {
|
||||
int t = ts[k], i = slot_of_rec(t); if (i < 0) continue;
|
||||
float px = R[t].x, py = R[t].y;
|
||||
dm_tc_move_at(&C, i, px, py, now);
|
||||
if (C.navigation_mode && C.pointer_slot == i && C.finger[i].ui_drag && W > 0) { dm_tc_finger *f = &C.finger[i];
|
||||
if (!ui_drag_on) { ui_drag_on = 1; dm_ui_drag_lift(DM_TC_POINTER_LIFT_PT * sc / H); dm_ui_drag_begin(f->ui_drag, f->aim_origin_x / W, f->aim_origin_y / H, 44.0f / H); }
|
||||
dm_ui_drag_move(px / W, py / H); }
|
||||
if (C.navigation_mode && C.pointer_slot == i && C.finger[i].pointer_dragged && W > 0) { rel_seq = dm_ui_drop_query(px / W, (py - DM_TC_POINTER_LIFT_PT * sc) / H, py / H); rel_asked = 1; }
|
||||
}
|
||||
push();
|
||||
arm_pulse_end();
|
||||
}
|
||||
// cancelled:0 = 抬起,1 = 系统取消 | cancelled: 0 = lifted, 1 = cancelled by the system
|
||||
void finish_touches(const int *ts0, int n0, int cancelled) {
|
||||
int ts[NREC], n = 0;
|
||||
for (int k = 0; k < n0; k++) { if (g_swallow >> ts0[k] & 1) g_swallow &= ~(1u << ts0[k]); else ts[n++] = ts0[k]; }
|
||||
if (ui_finger >= 0) { int m = 0, hit = 0; for (int k = 0; k < n; k++) { if (ts[k] == ui_finger) hit = 1; else ts[m++] = ts[k]; }
|
||||
if (hit) { int u = ui_finger; ui_touch(&u, 1, 2); n = m; } }
|
||||
if (!n) return;
|
||||
double now = now_s(); float sc = dm_tc_scale_for_size(W, H);
|
||||
for (int k = 0; k < n; k++) {
|
||||
int t = ts[k]; float px = R[t].x, py = R[t].y;
|
||||
if (t == map_t) { map_t = -1;
|
||||
if (!cancelled && !g_nav && hypotf(px - map_x0, py - map_y0) <= 14 && now - map_t0 < 0.6) {
|
||||
if (dm_ui_map_is_full()) { dm_ui_map_full(0); LOG("前端:点小地图那一块 (%.0f,%.0f) → 回小地图", px, py); }
|
||||
else if (W > 0) { map_world_seq = dm_world_tap(px / W, py / H); map_world_asked = 1; map_wx = px; map_wy = py; } }
|
||||
continue; }
|
||||
if (t == bind_t) { bind_t = -1;
|
||||
if (!cancelled && !g_nav && hypotf(px - bind_x0, py - bind_y0) <= 14) { dm_ui_bind_begin(bind_key); LOG("前端:点空技能位 (%.0f,%.0f) → 给键 %#llx 选技能", px, py, (unsigned long long)bind_key); }
|
||||
continue; }
|
||||
if (t == mapback_t) { mapback_t = -1;
|
||||
if (!cancelled && !g_nav && dm_ui_map_is_full() && hypotf(px - map_x0, py - map_y0) <= 14 && now - map_t0 < 0.6) { dm_ui_map_full(0); LOG("前端:全屏地图开着,点空处 (%.0f,%.0f) → 回小地图", px, py); } }
|
||||
if (!pend_fire && pend_end < 0 && !cancelled && C.navigation_mode && C.pointer_slot >= 0 && g_slot[C.pointer_slot] == t && W > 0) {
|
||||
dm_tc_finger *pf = &C.finger[C.pointer_slot]; int wait = 0;
|
||||
if (item_asked && dm_ui_item_result(item_seq) < 0) wait = 1;
|
||||
else if (pf->pointer_dragged) {
|
||||
dm_tc_move_at(&C, C.pointer_slot, px, py, now);
|
||||
rel_seq = dm_ui_drop_query(px / W, (py - DM_TC_POINTER_LIFT_PT * sc) / H, py / H); rel_asked = 1; final_asked = 1; wait = 1; }
|
||||
if (wait) { pend_end = t; pend_time = now; pend_wall = now; continue; }
|
||||
}
|
||||
int i = slot_of_rec(t); if (i < 0) continue;
|
||||
if (cancelled) { dm_tc_finger *cf = &C.finger[i]; int drag = C.navigation_mode && C.pointer_slot == i && (cf->pointer_dragged || cf->shop_drag);
|
||||
if (ui_drag_on && C.pointer_slot == i) { ui_drag_on = 0; dm_ui_drag_end(); }
|
||||
if (drag) { int shop = cf->shop_drag; if (!shop) dm_tc_pointer_release(&C, 0); dm_tc_end_at(&C, i, now); LOG("前端:拖动中被系统取消触摸 → %s", shop ? "不买不取" : "放回原处"); }
|
||||
else dm_tc_cancel_finger(&C, i);
|
||||
if (C.pointer_slot < 0) { rel_asked = 0; item_asked = 0; }
|
||||
g_slot[i] = -1; continue; }
|
||||
if (C.navigation_mode && C.pointer_slot == i && C.finger[i].shop_drag) {
|
||||
int rk = rel_asked ? dm_ui_item_result(rel_seq) : 0; if (rk < 0) rk = dm_ui_drop_last();
|
||||
if (rk == 5 && !dm_ui_drop_bag()) LOG("前端:%s拖出后松在背包格以外的物品区 → 不%s", item_kind == 8 ? "一叠" : "货架上的货", item_kind == 8 ? "取" : "买");
|
||||
else if ((rk == 5 || rk == 11) && W > 0) { dm_tc_finger *sf = &C.finger[i]; float ax = sf->aim_origin_x / W, ay = sf->aim_origin_y / H;
|
||||
if (rk == 11) { dm_ui_stack_cube_at(ax, ay); LOG("前端:高级仓库里的一叠拖到魔盒格上松手 → 1 件进魔盒"); }
|
||||
else if (item_kind == 8) { dm_ui_stack_take_at(ax, ay); LOG("前端:高级仓库里的一叠拖到背包松手 → 取 1 件"); }
|
||||
else { LOG("前端:货架上的货拖到背包松手 → 买"); dm_ui_shop_buy_at(ax, ay); }
|
||||
C.pointer_x = sf->aim_origin_x; C.pointer_y = sf->aim_origin_y; }
|
||||
} else if (C.navigation_mode && C.pointer_slot == i && C.finger[i].pointer_dragged && rel_asked) {
|
||||
int rr = dm_ui_item_result(rel_seq); if (rr < 0) rr = dm_ui_drop_last(); if (rr < 0) rr = 0; float dx, dy;
|
||||
if ((rr == 5 && dm_ui_drop_point(&dx, &dy)) || (rr == 0 && dm_ui_origin_point(&dx, &dy))) dm_tc_pointer_release_at(&C, dx * W, dy * H);
|
||||
else { if (rr == 7) { dm_shop_sell_cursor(); rr = 0; } dm_tc_pointer_release(&C, rr < 0 ? 1 : rr); }
|
||||
}
|
||||
rel_asked = 0;
|
||||
if (C.navigation_mode && C.pointer_slot == i && item_asked) { item_asked = 0; dm_tc_pointer_item(&C, dm_ui_item_result(item_seq)); bind_tap_sync(); }
|
||||
unsigned wt = C.world_tap_seq, mc = C.mouse_click_seq, tt = C.tab_tap_seq, us = C.use_seq, ids = C.ident_seq, sts = C.stack_take_seq, lps = C.long_press_seq, its = C.item_tap_seq;
|
||||
if (ui_drag_on && C.pointer_slot == i) { ui_drag_on = 0; dm_ui_drag_end(); }
|
||||
int was_ptr = C.pointer_slot == i; unsigned tm = C.tap_move_seq;
|
||||
dm_tc_end_at(&C, i, pend_fire ? pend_time : now); g_slot[i] = -1;
|
||||
if (C.tap_move_seq != tm) { uint32_t hid = dm_ui_hit_id();
|
||||
if (hid && hid == sel_id) { if (hid <= 4) { dm_stat_add((int)hid - 1, 1); LOG("前端:再点同一个「+」(属性 %u)→ 加 1 点", hid - 1); } else add_at = C.last_time_s + 0.3; }
|
||||
else { sel_id = hid; LOG("前端:点加点类按钮 → 选中(标识 %#x)", hid); } }
|
||||
if (C.tab_tap_seq != tt) dm_ui_tab_go();
|
||||
if (C.long_press_seq != lps) dm_ui_long_press();
|
||||
if (C.item_tap_seq != its) dm_ui_item_tap();
|
||||
if (C.stack_take_seq != sts) { dm_stash_take(1); LOG("前端:双击高级仓库里的一叠 → 取 1 件"); }
|
||||
if (C.ident_seq != ids) dm_ui_identify_hovered();
|
||||
if (C.use_seq != us) dm_ui_use_item();
|
||||
if (C.world_tap_seq != wt && W > 0) { float wx = C.world_tap_x / W, wy = C.world_tap_y / H; dm_ui_world_tap(wx, wy, wx, wy); }
|
||||
if (was_ptr && C.navigation_mode) tip_until = C.tap_move_seq != tm ? -1 : C.last_time_s + (C.mouse_click_seq != mc ? 0.05 : 2.8);
|
||||
if (C.mouse_click_seq != mc && W > 0) { float nx = C.mouse_click_x / W, ny = C.mouse_click_y / H; dm_ui_touch(0, nx, ny); dm_ui_touch(2, nx, ny); }
|
||||
}
|
||||
push();
|
||||
arm_pulse_end();
|
||||
}
|
||||
// 松手施放的脉冲:游戏真取走了(输入采样数前进、光标不扣着)才收回;iOS 用 120 Hz 定时器,这里每帧 tick 一次
|
||||
// Release-to-cast pulse: released only once the game has really taken it (input samples advanced, cursor not holding it); iOS uses a 120 Hz timer, here once per frame tick
|
||||
static void pulse_tick(void) {
|
||||
uint64_t n = dm_input_samples(); double now = now_s();
|
||||
if (C.pulse_button) {
|
||||
if (pulse_epoch != C.pulse_epoch) { pulse_epoch = C.pulse_epoch; pulse_s0 = n; pulse_t0 = now; pulse_seen = 0; pulse_free = 0; }
|
||||
if (!pulse_seen && n > pulse_s0) pulse_seen = now;
|
||||
if (pulse_seen && !pulse_free && !dm_cursor_pending()) pulse_free = now;
|
||||
double hold = C.pulse_hold_s;
|
||||
int taken = pulse_seen && now - pulse_seen >= 0.12 && n - pulse_s0 >= 3 && !dm_cursor_pending() && (hold <= 0 || (pulse_free && now - pulse_free >= hold));
|
||||
if (taken || now - pulse_t0 > 2.0 + hold) {
|
||||
if (!taken) LOG("[touch] 【红】脉冲 2 秒内游戏没取走(取了 %llu 次,扣着 %d 下),强制收回", (unsigned long long)(n - pulse_s0), dm_cursor_pending());
|
||||
if (dm_tc_pulse_end(&C, pulse_epoch)) push();
|
||||
pulse_s0 = n; pulse_t0 = now;
|
||||
}
|
||||
} else if (dm_tc_pulse_pending(&C)) {
|
||||
if (n - pulse_s0 >= 2 || now - pulse_t0 > 0.5) { if (dm_tc_pulse_resume(&C)) push(); }
|
||||
} else pulse_ticking = 0;
|
||||
}
|
||||
static void tick(double now) {
|
||||
apply_pending();
|
||||
int hide = g_fe || g_pad || dm_padmode_busy();
|
||||
{ static int lh = -1; if (hide != lh) { lh = hide; g_dirty = 1; } }
|
||||
{ int t = dm_drop_haptic_take(); if (t >= 1 && t <= 3) { g_haptic = t; LOG("掉落震动:前端震第 %d 档", t); } }
|
||||
if (labels_at && now >= labels_at) { labels_at = 0; if (!g_nav && !labels_done) { labels_done = 1; dm_ui_key_pulse_alone(DM_BTN_L, 9); } }
|
||||
dm_tc_set_tap_box(dm_ui_tap_box()); dm_tc_set_cur_stack(dm_ui_cur_stack_id()); dm_tc_set_hover_unid(dm_ui_hover_unid());
|
||||
{ dm_hud_info hi; dm_hud_get(&hi); dm_tc_set_holding(&C, hi.valid && hi.holding && !dm_ui_targeting()); }
|
||||
if (item_asked && C.navigation_mode && C.pointer_slot >= 0) { int ir = dm_ui_item_result(item_seq); if (ir >= 0) { item_asked = 0; item_kind = ir; dm_tc_pointer_item(&C, ir); } }
|
||||
if (pend_end >= 0) {
|
||||
int ready = !(item_asked && dm_ui_item_result(item_seq) < 0) && !(final_asked && dm_ui_item_result(rel_seq) < 0);
|
||||
if (ready || now - pend_wall > 0.25) { int pt = pend_end;
|
||||
pend_fire = 1; finish_touches(&pt, 1, 0); pend_fire = 0; pend_end = -1; final_asked = 0; }
|
||||
}
|
||||
bind_tap_sync();
|
||||
float sc = dm_tc_scale_for_size(W, H);
|
||||
if (C.navigation_mode && !dm_ui_bind_active() && !item_asked && C.pointer_slot >= 0 && C.pointer_slot < DM_TC_MAX_TOUCH) {
|
||||
dm_tc_finger *f = &C.finger[C.pointer_slot]; float nx = 0, ny = 0; uint32_t hid = dm_ui_hit_id();
|
||||
if (f->active && !f->pointer_dragged && !f->ui_drag && now - f->start_time_s >= 0.5 && hypotf(f->x - f->aim_origin_x, f->y - f->aim_origin_y) <= 10 * sc && dm_ui_bind_skill_hit(&nx, &ny) == 2 && hid >= 1 && hid <= 4) {
|
||||
if (!f->pointer_long) { f->pointer_long = 1; stat_next = now; sel_id = hid; C.pointer_valid = 1; C.pointer_x = nx * W; C.pointer_y = ny * H; LOG("前端:按住「+」(属性 %u)→ 连续加点", hid - 1); }
|
||||
if (now >= stat_next) { stat_next = now + 0.15; dm_stat_add((int)hid - 1, 1); } }
|
||||
}
|
||||
if (C.navigation_mode && !dm_ui_bind_active() && !item_asked && C.pointer_slot >= 0 && C.pointer_slot < DM_TC_MAX_TOUCH) {
|
||||
dm_tc_finger *f = &C.finger[C.pointer_slot]; float nx = 0, ny = 0;
|
||||
if (pend_end < 0 && f->active && !f->pointer_dragged && !f->pointer_long && now - f->start_time_s >= 0.5 && hypotf(f->x - f->aim_origin_x, f->y - f->aim_origin_y) <= 10 * sc && dm_ui_bind_skill_hit(&nx, &ny) == 1) {
|
||||
dm_tc_pointer_press(&C, nx * W, ny * H, DM_BTN_Y); LOG("前端:技能树里长按技能 (%.0f,%.0f) → 开绑定框", nx * W, ny * H); }
|
||||
}
|
||||
if (map_world_asked) { int wr = dm_world_tap_result(map_world_seq);
|
||||
if (wr >= 0) { map_world_asked = 0; if (wr == 0 && !g_nav) { dm_ui_map_full(1); LOG("前端:点小地图那一块 (%.0f,%.0f) → 全屏地图", map_wx, map_wy); }
|
||||
else LOG("前端:点小地图那一块 (%.0f,%.0f) → 底下有世界目标(类 %d),交互、不切地图", map_wx, map_wy, wr); } }
|
||||
if (add_at > 0 && now >= add_at) { dm_points_info pi; dm_points_get(&pi);
|
||||
if (pi.tree_open && pi.sel_skill >= 0 && !dm_cursor_pending()) { add_at = 0; if (pi.sel_block == 0 || pi.sel_block == 5) dm_skill_add_selected(); else LOG("前端:再点同一个技能 → 不能加(原因 %d),不发", pi.sel_block); }
|
||||
else if (now > add_at + 1.0 || !pi.tree_open) add_at = 0; }
|
||||
if (!C.navigation_mode || g_pad) tip_until = -2;
|
||||
else if (C.pointer_slot >= 0) tip_until = -1;
|
||||
else if (tip_until == -2) { if (dm_ui_free_cursor()) tip_until = now + 0.3; }
|
||||
else if (tip_until > 0 && now >= tip_until && !C.holding && !dm_ui_bind_active() && !dm_ui_touch_active() && !C.pulse_button && !dm_tc_pulse_pending(&C) && !dm_cursor_pending()) {
|
||||
C.pointer_valid = 1; C.pointer_x = 0.02f * W; C.pointer_y = 0.5f * H; tip_until = 0; }
|
||||
uint64_t tb = C.buttons;
|
||||
dm_tc_tick(&C, now);
|
||||
{ int fg = 0; for (int i = 0; i < DM_TC_MAX_TOUCH; i++) fg |= C.finger[i].active; dm_ui_hand_idle(!fg && !C.pulse_button && !dm_tc_pulse_pending(&C) && !dm_cursor_pending() && !dm_ui_touch_active()); }
|
||||
if (C.buttons != tb && !C.pulse_button) push();
|
||||
else if (C.belt_request && !C.pulse_button) push();
|
||||
if (C.pulse_button && !pulse_ticking) { push(); arm_pulse_end(); }
|
||||
if (C.pointer_valid) dm_cursor_set_screen(C.pointer_x, C.pointer_y, W, H);
|
||||
else if (C.navigation_mode) dm_cursor_clear();
|
||||
if (pulse_ticking) pulse_tick();
|
||||
refresh_portal_binding();
|
||||
{ static uint64_t lb; static int32_t llx, lly; if (C.buttons != lb || C.lx != llx || C.ly != lly) { lb = C.buttons; llx = C.lx; lly = C.ly; g_dirty = 1; } }
|
||||
}
|
||||
|
||||
// ---- 绘制指令表(Java TouchOverlay 照表画;与 DmTouchOverlay.m drawRect 一一对应) | draw list (executed by Java TouchOverlay; mirrors DmTouchOverlay.m drawRect) ----
|
||||
enum { OP_FILL_ELLIPSE = 1, OP_STROKE_ELLIPSE, OP_LINE, OP_ARC, OP_IMAGE, OP_TEXT, OP_FILL_RECT, OP_V4, OP_V4TEXT, OP_LABEL, OP_COVER };
|
||||
// 三层:0 = HUD 主体,1 = 摇杆,2 = 小地图任务终点(draw_goals)。手指在摇杆上动时只有摇杆层变,主体层(GPU 缓存成一张纹理)不重画——
|
||||
// 整层 HUD 每帧在 HWUI 里重画要占 GPU 6–11 ms,和游戏抢同一块 GPU,跑动中转向(手指一直在动)就掉帧
|
||||
// Three layers: 0 = HUD body, 1 = joystick, 2 = minimap quest goals (draw_goals). While a finger moves on the stick only the joystick layer changes, and the body layer (cached on the GPU as one texture) is not redrawn --
|
||||
// redrawing the whole HUD in HWUI every frame cost 6-11 ms of GPU, competing with the game for the same GPU, so turning while running (finger always moving) dropped frames
|
||||
typedef struct { float ops[8192]; int n; char str[96][64]; int nstr; } op_list;
|
||||
static op_list g_drawn[3], g_probe; static op_list *g_ol = &g_drawn[0];
|
||||
static void op(int code, int n, const float *v) {
|
||||
if (g_ol->n + n + 2 > (int)(sizeof g_ol->ops / sizeof *g_ol->ops)) return;
|
||||
g_ol->ops[g_ol->n++] = (float)code; g_ol->ops[g_ol->n++] = (float)n; memcpy(&g_ol->ops[g_ol->n], v, n * sizeof *v); g_ol->n += n;
|
||||
}
|
||||
static float str(const char *s) {
|
||||
for (int i = 0; i < g_ol->nstr; i++) if (!strcmp(g_ol->str[i], s)) return (float)i;
|
||||
if (g_ol->nstr >= 96) return -1;
|
||||
snprintf(g_ol->str[g_ol->nstr], sizeof g_ol->str[0], "%s", s); return (float)g_ol->nstr++;
|
||||
}
|
||||
static int same_list(const op_list *a, const op_list *b) {
|
||||
if (a->n != b->n || a->nstr != b->nstr || memcmp(a->ops, b->ops, a->n * sizeof *a->ops)) return 0;
|
||||
for (int i = 0; i < a->nstr; i++) if (strcmp(a->str[i], b->str[i])) return 0;
|
||||
return 1;
|
||||
}
|
||||
#define OPV(code, ...) do { const float v_[] = {__VA_ARGS__}; op(code, (int)(sizeof v_ / sizeof *v_), v_); } while (0)
|
||||
static void fill_ellipse(float x, float y, float w, float h, float r, float g, float b, float a) { OPV(OP_FILL_ELLIPSE, x, y, w, h, r, g, b, a); }
|
||||
static void stroke_ellipse(float x, float y, float w, float h, float lw, float r, float g, float b, float a) { OPV(OP_STROKE_ELLIPSE, x, y, w, h, lw, r, g, b, a); }
|
||||
static void caption(const char *s, float x, float y, float w, float h, float size, float alpha) { OPV(OP_TEXT, str(s), x, y, w, h, size, alpha); }
|
||||
// 图:素材路径(备用路径,-1 无),裁切框(sw ≤ 0 = 整张),目标框,不透明度,混合(0 正常 / 1 灰度) | image: asset path (fallback path, -1 none), crop (sw ≤ 0 = whole), destination, alpha, blend (0 normal / 1 luminosity)
|
||||
static void image(const char *a, const char *fb, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh, float alpha, int blend) {
|
||||
OPV(OP_IMAGE, str(a), fb ? str(fb) : -1, sx, sy, sw, sh, dx, dy, dw, dh, alpha, (float)blend);
|
||||
}
|
||||
static dm_ta_glyph shown_glyph(uint64_t button, uint64_t now, int set) {
|
||||
dm_ta_glyph g = dm_ta_current_set(&g_native, button, now, set);
|
||||
if (g.status == DM_TA_UNKNOWN && g_native.captured_ns && now > g_native.captured_ns && now - g_native.captured_ns > DM_TG_MAX_AGE_NS) g = dm_ta_current_set(&g_native, button, g_native.captured_ns, set);
|
||||
return g;
|
||||
}
|
||||
// 技能图标的裁切框;0 = 没有 | skill icon crop rect; 0 = none
|
||||
static int skill_frame(dm_ta_glyph g, int held, dm_ta_frame *f, char *path, char *sil, size_t n) {
|
||||
if (g.status != DM_TA_GLYPH) return 0;
|
||||
if (!dm_ta_frame_at(g.atlas, held ? g.pressed_frame : g.normal_frame, f)) return 0;
|
||||
snprintf(path, n, "TouchArt/%s.png", dm_ta_atlases[g.atlas].asset); snprintf(sil, n, "hud_v4_ui/sil_%s.png", dm_ta_atlases[g.atlas].asset);
|
||||
return 1;
|
||||
}
|
||||
#define DM_SKILL_IDLE_ALPHA .6f
|
||||
static void draw_shell(float x, float y, float rr, int held) {
|
||||
float lw = MAX(1.5f, rr * 0.075f), fr = held ? 1 : DM_SKILL_IDLE_ALPHA, d = rr * 2;
|
||||
fill_ellipse(x - rr, y - rr, d, d, .086f, .067f, .047f, held ? .92f : .80f * fr);
|
||||
stroke_ellipse(x - rr + lw / 2, y - rr + lw / 2, d - lw, d - lw, lw, .60f, .47f, .28f, held ? 1 : .9f * fr);
|
||||
stroke_ellipse(x - rr + lw * 1.3f, y - rr + lw * 1.3f, d - lw * 2.6f, d - lw * 2.6f, lw * .5f, .12f, .09f, .05f, .9f * fr);
|
||||
}
|
||||
// 小地图任务终点(同 front_ios.m mapGoalSync;宿主 dm_world.c 找终点、dm_cursor.c 给地图几何):七个墓的真墓口 = 塔拉夏符号,其余 = 原版名牌 + 灰十字;
|
||||
// 在地图可见范围外 = 只写名字,沿 玩家点 → 终点 的方向贴边(全屏地图让开右下技能区)。世界格 (x, y) 在 玩家点 + ((Δx−Δy)×1.6, (Δx+Δy)×0.8) × 每格像素。
|
||||
// 画面 = 整个视图(Android 不留边)。面板开着不画;手柄模式照画(同 iOS)。素材 assets/mapgoal/(art_from_ipa.py 从 iOS 包取)
|
||||
// Minimap quest goals (same as front_ios.m mapGoalSync; the host's dm_world.c finds the goals, dm_cursor.c gives the map geometry): the real tomb of the seven = the Tal Rasha symbol, others = the original nameplate + grey cross;
|
||||
// outside the visible map range = name only, clamped to the edge along player point → goal (the fullscreen map avoids the bottom-right skill area). World cell (x, y) is at player point + ((Δx−Δy)×1.6, (Δx+Δy)×0.8) × pixels per cell.
|
||||
// The picture = the whole view (no letterbox on Android). Not drawn while a panel is open; drawn in pad mode too (as on iOS). Art in assets/mapgoal/ (taken from the iOS bundle by art_from_ipa.py)
|
||||
static void draw_goals(void) {
|
||||
static int old = -1; if (old < 0) old = dm_custom_get("item_notes") != 0; // 旧译名开关重启生效 | the old-names switch takes effect on restart
|
||||
dm_map_goal_view v; float cell = 0; int mode = dm_ui_map_geom(&cell), n = dm_map_goals(&v), rw = 0, rh = 0; dm_screen_real(&rw, &rh);
|
||||
float mm[4]; int mini = dm_ui_minimap_rect(mm);
|
||||
int show = mode && n > 0 && !g_nav && !g_fe && rw > 0 && cell > 0 && (mode == 2 || mini);
|
||||
static int lm = -1, ln = -1, lc; int m2 = show ? mode : 0;
|
||||
if ((m2 != lm || n != ln) && lc < 40) { lm = m2; ln = n; lc++; LOG("小地图终点:%s %d 个(地图 %d,每格 %.2f 像素 = %.2f dp)", show ? "画" : "不画", n, mode, cell, cell * W / (rw > 0 ? rw : 1)); }
|
||||
if (!show) return;
|
||||
if (n > 12) n = 12;
|
||||
float c = cell * W / rw, lh = H * .0236f, sh = H * .085f * (mode == 1 ? .6f : 1), cw = lh * 1.4f, ch = cw * 18 / 34;
|
||||
float ox, oy, ax0, ay0, ax1, ay1; // 玩家点,可见范围 | player point, visible area
|
||||
if (mode == 2) { ox = v.sx * W; oy = v.sy * H; ax0 = W * .04f; ay0 = H * .06f; ax1 = ax0 + W * .92f; ay1 = ay0 + H * .72f; }
|
||||
else { ax0 = mm[0] * W; ay0 = mm[1] * H; ax1 = mm[2] * W; ay1 = mm[3] * H; ox = (ax0 + ax1) / 2; oy = (ay0 + ay1) / 2;
|
||||
float iw = (ax1 - ax0) * .06f, ih = (ay1 - ay0) * .08f; ax0 += iw; ax1 -= iw; ay0 += ih; ay1 -= ih; }
|
||||
for (int i = 0; i < n; i++) {
|
||||
int dx = v.x[i] - v.px, dy = v.y[i] - v.py; float px = ox + (dx - dy) * 1.6f * c, py = oy + (dx + dy) * .8f * c;
|
||||
int skill = mode == 2 && px > W * .72f && py > H * .45f; // 全屏地图右下是技能区 | the bottom right of the fullscreen map is the skill area
|
||||
int inside = px >= ax0 && px < ax1 && py >= ay0 && py < ay1 && !skill, art = v.art[i], sym = art >= 64;
|
||||
char lab[48] = "", fb[48] = "", mark[48] = "";
|
||||
if (inside && sym) snprintf(mark, sizeof mark, "mapgoal/sym_%d.png", art - 64);
|
||||
else { int id = sym ? 0 : art; snprintf(fb, sizeof fb, "mapgoal/label_%d.png", id);
|
||||
if (!dm_lang_zh()) snprintf(lab, sizeof lab, "mapgoal/label_%d_en.png", id); // 简中 / 繁体用中文名牌,其余 enUS;旧译名只跟简中 | zh uses the Chinese label, others enUS; old names only for zhCN
|
||||
else if (old && dm_lang_index() == 8) snprintf(lab, sizeof lab, "mapgoal/label_%d_old.png", id);
|
||||
else snprintf(lab, sizeof lab, "%s", fb);
|
||||
if (inside) snprintf(mark, sizeof mark, "mapgoal/cross.png"); }
|
||||
if (!inside) { // 画面外:收到可见范围边上,只写名字 | off-screen: clamp to the edge of the visible range, name only
|
||||
float tx = px > ox ? (ax1 - ox) / (px - ox) : px < ox ? (ax0 - ox) / (px - ox) : 1e9f, ty = py > oy ? (ay1 - oy) / (py - oy) : py < oy ? (ay0 - oy) / (py - oy) : 1e9f, t = MIN(tx, ty);
|
||||
px = ox + (px - ox) * t; py = oy + (py - oy) * t;
|
||||
if (mode == 2 && px > W * .72f && py > H * .45f) py = H * .45f; }
|
||||
if (lab[0]) OPV(OP_LABEL, str(lab), px, mark[0] ? py - ch / 2 - 2 - lh / 2 : py, lh, strcmp(lab, fb) ? str(fb) : -1);
|
||||
if (mark[0]) { if (sym) OPV(OP_LABEL, str(mark), px, py, sh); else image(mark, NULL, 0, 0, 0, 0, px - cw / 2, py - ch / 2, cw, ch, 1, 0); }
|
||||
}
|
||||
}
|
||||
static void draw_overlay(int part) {
|
||||
g_ol->n = 0; g_ol->nstr = 0;
|
||||
int cover = atomic_load(&g_cover);
|
||||
if (cover == 1) { if (!part) OPV(OP_COVER, W, H); return; }
|
||||
if (part == 2) { draw_goals(); return; }
|
||||
if (g_fe || g_pad || dm_padmode_busy()) return;
|
||||
const dm_tc_state *s = &C; const dm_tc_layout *l = &s->layout;
|
||||
float k = l->joy_radius / 60; if (k <= 0) return;
|
||||
if (part) {
|
||||
if ((g_hud.valid && g_hud.dead) || s->navigation_mode) return;
|
||||
int moving = s->joy_slot >= 0;
|
||||
float ox = moving ? s->joy_origin_x : l->joy_x, oy = moving ? s->joy_origin_y : l->joy_y, radius = l->joy_radius;
|
||||
stroke_ellipse(ox - radius, oy - radius, radius * 2, radius * 2, k, .66f, .53f, .32f, moving ? .32f : .12f);
|
||||
float dx = s->lx / 32767.0f * radius, dy = -s->ly / 32767.0f * radius;
|
||||
image("TouchArt/dm_touch_joy.png", NULL, 0, 0, 0, 0, ox + dx - 23 * k, oy + dy - 23 * k, 46 * k, 46 * k, moving ? .8f : .18f, 0);
|
||||
if (moving && (s->lx || s->ly)) { float ang = atan2f(dy, dx); OPV(OP_ARC, ox, oy, radius + 3 * k, ang - (float)M_PI / 6, ang + (float)M_PI / 6, 2 * k, .66f, .53f, .32f, .7f); }
|
||||
return;
|
||||
}
|
||||
int nav = g_nav != 0; uint64_t host_now = now_ns();
|
||||
const char *labels[DM_TC_COUNT] = {"主技能", "技能一", "技能二", "技能三", "技能四", "回城", "药剂", "药剂", "药剂", "药剂", "功能", "地图"};
|
||||
if (nav) { labels[0] = "确认/交换"; labels[1] = "返回"; labels[2] = "操作"; labels[3] = "绑定"; labels[4] = "下一页"; }
|
||||
for (int i = 0; i < DM_TC_COUNT; i++) {
|
||||
if (!(s->enabled_targets & (1u << i))) continue;
|
||||
if (!nav && i > DM_TC_PORTAL && i <= DM_TC_MENU) continue;
|
||||
const dm_tc_target *t = &l->target[i]; float bx = t->x - t->r, by = t->y - t->r, bw = t->r * 2;
|
||||
int held = t->button != 0 && (s->buttons & t->button) == t->button;
|
||||
if (i == DM_TC_PORTAL) for (int f = 0; f < DM_TC_MAX_TOUCH; f++) held |= s->finger[f].active && s->finger[f].target == DM_TC_PORTAL;
|
||||
float opacity = held ? .6f : .28f;
|
||||
if (!nav && i == DM_TC_MAP && s->map_cancel_active) { OPV(OP_FILL_RECT, bx, by, bw, bw, .55f, .05f, .04f, .36f); labels[i] = "取消"; }
|
||||
int skill_key = !nav && (i <= DM_TC_SKILL4 || i == DM_TC_PORTAL);
|
||||
if (skill_key) draw_shell(t->x, t->y, t->r, held);
|
||||
else image("TouchArt/dm_native_circle.png", NULL, 0, 0, 0, 0, bx, by, bw, bw, opacity, 0);
|
||||
int have_icon = 0, show_caption = 1, ss_kind = 0, ss_charges = 0; dm_ta_frame fr; char ip[96], sp[96]; float iw = 0, ih = 0;
|
||||
if (!nav && i <= DM_TC_SKILL4) {
|
||||
dm_ta_glyph g = shown_glyph(t->button, host_now, s->skill_set);
|
||||
if (g.status != DM_TA_EMPTY && g.status != DM_TA_UNKNOWN) ss_kind = dm_swapskill_slot(g.slot, &ss_charges);
|
||||
have_icon = skill_frame(g, held, &fr, ip, sp, sizeof ip);
|
||||
show_caption = g.status != DM_TA_EMPTY && !have_icon;
|
||||
} else if (!nav && i == DM_TC_PORTAL) have_icon = skill_frame(dm_ta_skill(359), held, &fr, ip, sp, sizeof ip);
|
||||
else if (!nav && (i == DM_TC_MENU || i == DM_TC_MAP)) {
|
||||
have_icon = 1; fr = (dm_ta_frame){held ? 36 : 0, 0, 36, 36};
|
||||
snprintf(ip, sizeof ip, "TouchArt/%s", i == DM_TC_MAP ? "dm_native_map.png" : "dm_native_menu.png"); sp[0] = 0;
|
||||
}
|
||||
if (!nav && i == DM_TC_MAP && s->map_cancel_active) { have_icon = 0; show_caption = 1; }
|
||||
if (have_icon) { iw = (float)fr.width; ih = (float)fr.height; }
|
||||
if (skill_key && !have_icon && (!show_caption || i == DM_TC_MAIN)) { // 空格:十字 | empty slot: a cross
|
||||
float a_ = t->r * .30f, w_ = MAX(1.5f, t->r * .085f), al = held ? 1 : .9f;
|
||||
OPV(OP_LINE, t->x - a_, t->y, t->x + a_, t->y, w_, .60f, .47f, .28f, al);
|
||||
OPV(OP_LINE, t->x, t->y - a_, t->x, t->y + a_, w_, .60f, .47f, .28f, al);
|
||||
continue;
|
||||
}
|
||||
if (skill_key) {
|
||||
int bare = have_icon, spent = (ss_kind & 2) && ss_charges <= 0;
|
||||
if (have_icon) { float size = bw * (bare ? .64f : .56f), fit = size / MAX(iw, ih);
|
||||
float rx_ = t->x - iw * fit / 2, ry_ = t->y - (bare ? 0 : t->r * .12f) - ih * fit / 2;
|
||||
if (spent) { fill_ellipse(bx + t->r * .14f, by + t->r * .14f, bw - t->r * .28f, bw - t->r * .28f, .30f, .30f, .30f, 1);
|
||||
image(sp, ip, fr.x, fr.y, fr.width, fr.height, rx_, ry_, iw * fit, ih * fit, .55f, 1);
|
||||
fill_ellipse(bx, by, bw, bw, 0, 0, 0, .35f); }
|
||||
else image(sp[0] ? sp : ip, sp[0] ? ip : NULL, fr.x, fr.y, fr.width, fr.height, rx_, ry_, iw * fit, ih * fit, held ? 1 : .92f, 0); }
|
||||
if (ss_kind & 1) { float br = t->r * .30f, bx2 = t->x + t->r * .74f, by2 = t->y - t->r * .74f, in = MAX(1, br * .08f);
|
||||
fill_ellipse(bx2 - br, by2 - br, br * 2, br * 2, .11f, .094f, .078f, .95f);
|
||||
stroke_ellipse(bx2 - br + in, by2 - br + in, br * 2 - in * 2, br * 2 - in * 2, MAX(1, br * .14f), .63f, .50f, .27f, 1);
|
||||
float ts = br * 1.15f; caption("Ⅱ", bx2 - br, by2 - ts * .62f, br * 2, ts * 1.4f, ts, 1); }
|
||||
if (ss_kind & 2) { char cs[16]; snprintf(cs, sizeof cs, "%d", ss_charges < 0 ? 0 : ss_charges); float u = H / 1320.0f;
|
||||
if (u > 0) OPV(OP_V4TEXT, str(cs), (t->x + t->r * .66f - W / 2) / u + 1434, (t->y + t->r * .42f) / u, 1); }
|
||||
if (bare) continue;
|
||||
char ln[48]; if (i == DM_TC_MAIN) snprintf(ln, sizeof ln, "hud_v4_ui/lbl_main.png"); else snprintf(ln, sizeof ln, "hud_v4_ui/lbl_f%d.png", i - DM_TC_SKILL1 + 1 + (s->skill_set ? 4 : 0));
|
||||
OPV(OP_LABEL, str(ln), t->x, t->y + t->r * .50f, t->r * (i == DM_TC_MAIN ? .30f : .36f));
|
||||
continue;
|
||||
}
|
||||
if (have_icon) { float size = bw * (i == DM_TC_MAIN ? .55f : .62f), fit = size / MAX(iw, ih);
|
||||
image(ip, NULL, fr.x, fr.y, fr.width, fr.height, t->x - iw * fit / 2, t->y - ih * fit / 2, iw * fit, ih * fit, held ? 1 : .82f, 0); show_caption = 0; }
|
||||
float ts = (i == DM_TC_MAIN ? 13 : 10) * k;
|
||||
if (show_caption) caption(labels[i], bx, t->y - ts * .6f, bw, ts * 1.6f, ts, held ? 1 : .84f);
|
||||
if (i >= DM_TC_BELT1 && i <= DM_TC_BELT4) { char d[4]; snprintf(d, sizeof d, "%d", i - DM_TC_BELT1 + 1); caption(d, t->x - 10 * k, t->y + 8 * k, 20 * k, 12 * k, 8 * k, .65f); }
|
||||
}
|
||||
if (!nav && l->swap.r > 0) {
|
||||
int sheld = 0; for (int f = 0; f < DM_TC_MAX_TOUCH; f++) sheld |= s->finger[f].active && hypotf(s->finger[f].x - l->swap.x, s->finger[f].y - l->swap.y) <= l->swap.r;
|
||||
draw_shell(l->swap.x, l->swap.y, l->swap.r, sheld);
|
||||
float ts = 14 * k; caption(s->skill_set ? "Ⅱ" : "Ⅰ", l->swap.x - l->swap.r, l->swap.y - ts * .8f, l->swap.r * 2, ts * 1.6f, ts, 1);
|
||||
}
|
||||
if (g_hud.valid && g_hud.dead) return;
|
||||
if (s->navigation_mode) return;
|
||||
// 底部 UI v4:可见性在这里判,几何与字形 Java 按 hud_v4_ui/ui.json 画 | bottom UI v4: visibility decided here, geometry and glyphs drawn by Java from hud_v4_ui/ui.json
|
||||
const dm_hud_info *h = &g_hud;
|
||||
if (dm_hud_bar_visible(h, nav && !g_dialog_only, g_hud_blocked_v)) {
|
||||
char life[64], mana[64], lv[48];
|
||||
snprintf(life, sizeof life, dm_ui("dmHudLife"), h->hp, h->hp_max); snprintf(mana, sizeof mana, dm_ui("dmHudMana"), h->mp, h->mp_max);
|
||||
snprintf(lv, sizeof lv, "Lv %d · %d%%", h->level, h->exp_permille / 10);
|
||||
OPV(OP_V4, str(life), str(mana), str(lv), (s->buttons & DM_BTN_PLUS) ? 1 : 0, h->points > 0 ? 1 : 0, h->quest_unread ? 1 : 0, (float)h->exp_permille,
|
||||
(float)h->belt[0], (float)h->belt[1], (float)h->belt[2], (float)h->belt[3], (float)h->players, s->diff_open ? 1 : 0);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- JNI(GameActivity 界面线程) | JNI (GameActivity UI thread) ----
|
||||
#define JNI(name) JNICALL Java_org_d2rmobile_app_GameActivity_##name
|
||||
JNIEXPORT void JNI(nativeLayout)(JNIEnv *env, jclass cls, jfloat w, jfloat h, jfloat safe_l, jfloat safe_r) {
|
||||
(void)env; (void)cls;
|
||||
static int inited; static float sl = -1, sr = -1;
|
||||
if (!inited) {
|
||||
inited = 1; for (int i = 0; i < 16; i++) g_slot[i] = -1;
|
||||
dm_tc_set_tall_scale(1); dm_tc_init(&C, w, h); C.mouse_click_mode = 1; W = w; H = h;
|
||||
g_nav = -1; navigation_mode(atomic_load(&g_touch_navigation));
|
||||
}
|
||||
int safe_changed = safe_l != sl || safe_r != sr;
|
||||
if (safe_changed) { sl = safe_l; sr = safe_r; dm_tc_set_safe_insets(safe_l, safe_r); }
|
||||
dm_tc_set_edge_bottom(0);
|
||||
if (h > 0) { dm_ui_safe_left((int)lroundf(safe_l / h * 2160)); dm_ui_safe_right((int)lroundf(safe_r / h * 2160)); }
|
||||
if (safe_changed || C.layout.width != w || C.layout.height != h) { W = w; H = h; cancel_controls(); dm_tc_resize(&C, w, h); }
|
||||
LOG("触屏:视图 %.0fx%.0f dp,安全边距 左 %.0f 右 %.0f", w, h, safe_l, safe_r);
|
||||
g_dirty = 1;
|
||||
}
|
||||
// action:0 按下(pid 为新手指)/ 1 移动 / 2 抬起(pid)/ 3 取消(全部);pids / xs / ys 为这一刻全部手指(dp)
|
||||
// action: 0 down (pid is the new finger) / 1 move / 2 up (pid) / 3 cancel (all); pids / xs / ys are all fingers at this moment (dp)
|
||||
JNIEXPORT void JNI(nativeTouchEvent)(JNIEnv *env, jclass cls, jint action, jint pid, jintArray pids, jfloatArray xs, jfloatArray ys, jint n) {
|
||||
(void)cls;
|
||||
if (W <= 0) return;
|
||||
jint id[NREC]; jfloat x[NREC], y[NREC]; if (n > NREC) n = NREC;
|
||||
if (n > 0) { (*env)->GetIntArrayRegion(env, pids, 0, n, id); (*env)->GetFloatArrayRegion(env, xs, 0, n, x); (*env)->GetFloatArrayRegion(env, ys, 0, n, y); }
|
||||
apply_pending();
|
||||
int ts[NREC], m = 0;
|
||||
for (int i = 0; i < n; i++) { int t = pid_rec(id[i]); if (t >= 0) { R[t].x = x[i]; R[t].y = y[i]; } }
|
||||
if (action == 0) {
|
||||
if (pid_rec(pid) >= 0) return;
|
||||
int t = -1; for (int i = 0; i < NREC; i++) if (!R[i].used) { t = i; break; }
|
||||
if (t < 0) { gc_recs(); return; }
|
||||
R[t].used = 1; R[t].done = 0; R[t].pid = pid; R[t].x = R[t].y = 0;
|
||||
for (int i = 0; i < n; i++) if (id[i] == pid) { R[t].x = x[i]; R[t].y = y[i]; }
|
||||
ts[m++] = t; touches_began(ts, m);
|
||||
} else if (action == 1) {
|
||||
for (int i = 0; i < NREC; i++) if (R[i].used && !R[i].done) ts[m++] = i;
|
||||
if (m) touches_moved(ts, m);
|
||||
} else if (action == 2) {
|
||||
int t = pid_rec(pid); if (t < 0) return;
|
||||
R[t].done = 1; ts[m++] = t; finish_touches(ts, m, 0);
|
||||
} else {
|
||||
for (int i = 0; i < NREC; i++) if (R[i].used && !R[i].done) { R[i].done = 1; ts[m++] = i; }
|
||||
if (m) finish_touches(ts, m, 1);
|
||||
}
|
||||
gc_recs();
|
||||
}
|
||||
// 每帧(Choreographer):返回位 0 / 1 / 2 = 主体层 / 摇杆层 / 终点层要重画,位 4–5 = 掉落震动档(1 重 / 2 中 / 3 轻),位 8–9 = 重开遮罩(1 黑屏 / 2 透明)
|
||||
// Per frame (Choreographer): bits 0 / 1 / 2 = body / joystick / goals layer needs a redraw, bits 4–5 = drop haptic level (1 heavy / 2 medium / 3 light), bits 8–9 = restart cover (1 black / 2 transparent)
|
||||
JNIEXPORT jint JNI(nativeTick)(JNIEnv *env, jclass cls) {
|
||||
(void)env; (void)cls;
|
||||
if (W <= 0) return 0;
|
||||
tick(now_s());
|
||||
static int lc; int cover = atomic_load(&g_cover); if (cover != lc) { lc = cover; g_dirty = 1; if (cover) cancel_controls(); }
|
||||
// 位 0 / 1 = 主体层 / 摇杆层要重画:重算一遍指令表,和上次画出来的不同才算 | bits 0 / 1 = body / joystick layer needs a redraw: rebuild the draw list, and only count it if it differs from what was last drawn
|
||||
int r = (g_haptic & 3) << 4 | (cover & 3) << 8;
|
||||
if (g_dirty) for (int part = 0; part < 2; part++) { g_ol = &g_probe; draw_overlay(part); if (!same_list(&g_probe, &g_drawn[part])) r |= 1 << part; }
|
||||
{ g_ol = &g_probe; draw_overlay(2); if (!same_list(&g_probe, &g_drawn[2])) r |= 4; } // 终点层跟着玩家走,每帧都比 | the goals layer follows the player, compared every frame
|
||||
g_dirty = 0; g_haptic = 0;
|
||||
return r;
|
||||
}
|
||||
// 返回 [float[] 指令, String[] 字符串表] | returns [float[] ops, String[] strings]
|
||||
JNIEXPORT jobjectArray JNI(nativeDraw)(JNIEnv *env, jclass cls, jint part) {
|
||||
(void)cls;
|
||||
if (part < 0 || part > 2) part = 0;
|
||||
g_ol = &g_drawn[part]; draw_overlay(part);
|
||||
jfloatArray f = (*env)->NewFloatArray(env, g_ol->n); if (g_ol->n) (*env)->SetFloatArrayRegion(env, f, 0, g_ol->n, g_ol->ops);
|
||||
jclass sc = (*env)->FindClass(env, "java/lang/String");
|
||||
jobjectArray sa = (*env)->NewObjectArray(env, g_ol->nstr, sc, NULL);
|
||||
for (int i = 0; i < g_ol->nstr; i++) { jstring js = (*env)->NewStringUTF(env, g_ol->str[i]); (*env)->SetObjectArrayElement(env, sa, i, js); (*env)->DeleteLocalRef(env, js); }
|
||||
jobjectArray out = (*env)->NewObjectArray(env, 2, (*env)->FindClass(env, "java/lang/Object"), NULL);
|
||||
(*env)->SetObjectArrayElement(env, out, 0, f); (*env)->SetObjectArrayElement(env, out, 1, sa);
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
# Android subresource-layout validation
|
||||
|
||||
Local validation date: 2026-10-15 (America/Los_Angeles).
|
||||
|
||||
This change retains `android-port` and its build94012 game integration. The
|
||||
per-mip approach is adapted from [dodola/d2r-mobile at 642480b](https://github.com/dodola/d2r-mobile/blob/642480b7606cf4adda30bcf009eb56f87745c908/dm/gfx/nvn/nvn_vk.c).
|
||||
No build91738 game addresses or platform/input services were imported.
|
||||
|
||||
## Implemented scope
|
||||
|
||||
- Track independent layouts for single-layer 2D color mip chains (2–16 levels)
|
||||
when sampled mips do not intersect any attachment mip in either graphics stage.
|
||||
- Retain the existing path for storage/comparison images, overlapping views,
|
||||
depth/stencil, arrays, volumes and devices using feedback-layout support.
|
||||
- Consolidate mixed layouts using the actual old layout of each mip run before
|
||||
whole-image operations; restore individual layouts after diagnostic captures.
|
||||
- Allow device A/B with `DM_VK_SUBRES=0` / `1`, without replacing the current
|
||||
pipeline cache, input, audio, save or APK packaging implementations.
|
||||
- Add a game-free system Vulkan capability probe, GPU readback fixture and a
|
||||
host/NDK/device test runner with explicit device opt-in and JSON receipts.
|
||||
|
||||
## Completed checks
|
||||
|
||||
| Check | Result |
|
||||
| --- | --- |
|
||||
| Production layout tracker vs independent per-level oracle | 320,000 deterministic random transitions; 407,319 emitted barriers checked |
|
||||
| Same regression with AddressSanitizer + UndefinedBehaviorSanitizer | Passed |
|
||||
| Invalid ranges, no-op transitions, mixed-to-uniform transitions, >16-level whole-image fallback | Passed in both host builds |
|
||||
| NDK 28.2.13676358 / API 33 / arm64 device test binaries | `t_vk_perf` and `t_vk_caps` built and linked |
|
||||
| Production Vulkan App object, `-fPIC -ffixed-x18 -O2` | Built successfully |
|
||||
| Diff whitespace and Python syntax | Passed |
|
||||
|
||||
Reproduction:
|
||||
|
||||
```sh
|
||||
python3 dm/android/tests/run_checks.py --output dm/android/build/checks-new
|
||||
```
|
||||
|
||||
Local receipts and compiler logs are under ignored
|
||||
`dm/android/build/checks-mip-final/`. The JSON explicitly records
|
||||
`device_contacted: false`, `gpu_executed: false` and `game_tested: false`.
|
||||
|
||||
## Outstanding device and package checks
|
||||
|
||||
No Android device was attached. The new cross-stage binding-policy and real
|
||||
Vulkan mip pixel-readback fixtures were compiled, **not executed**. No Mali game
|
||||
compatibility, validation-layer cleanliness, improved FPS, display cadence,
|
||||
thermal behavior or power result is claimed.
|
||||
|
||||
The full App native-library build was attempted but stopped at the missing
|
||||
generated `dm_hud_exp.h` included by `dm/host/diag.c`. Generate the host headers
|
||||
from the player's own resources before validating the complete library/APK.
|
||||
The modified production Vulkan object builds independently of that header.
|
||||
|
||||
Use the explicit `--run-device --serial DEVICE_SERIAL` runner option for GPU
|
||||
checks, then perform the controlled game A/B described in the Android README.
|
||||
The capability probe reports the system driver; an app using a private Turnip
|
||||
driver requires separate testing with that driver.
|
||||
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.d2rmobile.app"
|
||||
android:versionCode="1" android:versionName="0.1">
|
||||
<uses-sdk android:minSdkVersion="29" android:targetSdkVersion="33" />
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
<uses-feature android:name="android.hardware.vulkan.version" android:version="0x401000" android:required="true" />
|
||||
<!-- debuggable:run-as 往私有目录放游戏数据、读 run.log | debuggable: run-as to put game data into the private directory and read run.log -->
|
||||
<application android:label="D2R Mobile" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher" android:debuggable="true" android:allowBackup="false" android:hasCode="true"
|
||||
android:extractNativeLibs="true" android:isGame="true" android:appCategory="game"
|
||||
android:theme="@android:style/Theme.Material.NoActionBar.Fullscreen">
|
||||
<activity android:name=".GameActivity" android:exported="true" android:screenOrientation="sensorLandscape"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density"
|
||||
android:launchMode="singleTask" android:resizeableActivity="false">
|
||||
<intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter>
|
||||
</activity>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env python3
|
||||
# 没有完整原版 RomFS(缺 build_manifest.psv)时,从现成 iOS 安装包解出的 DmIOS.app 取触屏素材:TouchArt PNG、hud_v4_ui、mapgoal、dm_touch_native_art.c。
|
||||
# 每张 PNG 与技能索引都按仓库里冻结的 native_art_manifest.json 核过哈希(同 ios/tools/native_art/generate.py 的产物)。
|
||||
# 用法:art_from_ipa.py <解开的 Payload/DmIOS.app> <dm 目录>
|
||||
# Without a full original RomFS (no build_manifest.psv), take the touch art from an unpacked iOS build (DmIOS.app): TouchArt PNGs, hud_v4_ui, mapgoal, dm_touch_native_art.c.
|
||||
# Every PNG and the skill index are hash-checked against the frozen native_art_manifest.json (same output as ios/tools/native_art/generate.py).
|
||||
# Usage: art_from_ipa.py <unpacked Payload/DmIOS.app> <dm directory>
|
||||
import hashlib, json, shutil, sys
|
||||
from pathlib import Path
|
||||
app = Path(sys.argv[1]); dm = Path(sys.argv[2]); ios = dm / 'ios'; nat = ios / 'tools/native_art'
|
||||
sha = lambda b: hashlib.sha256(b).hexdigest()
|
||||
mpath = ios / 'Sources/TouchArt/native_art_manifest.json'; man = json.loads(mpath.read_text())
|
||||
art = ios / 'Sources/TouchArt'; atl = {}
|
||||
for a in man['assets']:
|
||||
b = (app / a['asset']).read_bytes()
|
||||
assert sha(b) == a['decoded_png_sha256'], a['asset']
|
||||
(art / a['asset']).write_bytes(b); atl[a['asset']] = a
|
||||
rows = [[int(x) for x in l.split('\t')[1:4]] for l in open(app / 'dm/derived.tsv') if l.startswith('TAROW')]
|
||||
assert sha(json.dumps(rows, sort_keys=True, separators=(',', ':')).encode()) == man['descriptor_index_sha256']
|
||||
out = ['/* Generated from frozen official Skills/Skilldesc; do not hand-edit rows. */', '#include "dm_touch_native_art.h"', '#include "../host/dm_input.h"', '#include <stddef.h>',
|
||||
'const dm_ta_atlas dm_ta_atlases[DM_TA_ATLASES]={']
|
||||
for i in range(9):
|
||||
a = atl['dm_native_skill_%d.png' % i]; out.append(' {"%s",%d,%d,%d,%d,%d},' % (a['asset'][:-4], *a['atlas_px'], a['frame_width'], a['frame_pitch'], a['frame_count']))
|
||||
out += ['};', f'const char dm_ta_manifest_sha[]="{sha(mpath.read_bytes())}";', f'const char dm_ta_geometry_sha[]="{sha((ios / "docs/native_art_v1_geometry.json").read_bytes())}";',
|
||||
f'const char dm_ta_binding_sha[]="{sha((ios / "docs/touch_layout_spec_native_binding_v5.json").read_bytes())}";', 'static const struct { uint32_t id; int atlas,frame; } rows[]={']
|
||||
out += [' {%d,%d,%d},' % tuple(r) for r in rows] + ['};', (nat / 'implementation.c.inc').read_text()]
|
||||
(dm / 'touch/dm_touch_native_art.c').write_text('\n'.join(out) + '\n')
|
||||
hud = ios / 'Gen/assets/NativeHUD/v4/hud_v4_ui'
|
||||
shutil.rmtree(hud, ignore_errors=True); shutil.copytree(app / 'hud_v4_ui', hud)
|
||||
goal = ios / 'Gen/assets/NativeHUD/mapgoal' # 小地图任务终点(gen_map_goal_art.py 的产物,按它的 mapgoal.json 核齐) | minimap quest goals (gen_map_goal_art.py output, checked complete against its mapgoal.json)
|
||||
shutil.rmtree(goal, ignore_errors=True); shutil.copytree(app / 'mapgoal', goal)
|
||||
gm = json.loads((goal / 'mapgoal.json').read_text())
|
||||
need = ['cross.png'] + ['sym_%d.png' % i for i in range(gm['symbol_frames'])]
|
||||
assert all((goal / f).is_file() for f in need), 'mapgoal incomplete'
|
||||
print(len(rows), 'rows,', len(atl), 'atlases,', len(list(hud.iterdir())), 'hud files,', len(list(goal.iterdir())), 'mapgoal files')
|
||||
@@ -0,0 +1,50 @@
|
||||
#!/bin/sh
|
||||
# Package build/app/libd2r.so + GameActivity into a debug-signed APK, without Gradle.
|
||||
# make -C dm/android (= build libd2r.so, then this script)
|
||||
# Env: ANDROID_SDK (default ~/Library/Android/sdk), BUILD_TOOLS (35.0.0), PLATFORM (android-33),
|
||||
# JAVA_HOME (default: Android Studio's bundled JBR), KEYSTORE (default ~/.android/debug.keystore).
|
||||
set -eu
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
out=$(cd "$here/.." && pwd)/build/app
|
||||
sdk=${ANDROID_SDK:-$HOME/Library/Android/sdk}
|
||||
bt=$sdk/build-tools/${BUILD_TOOLS:-35.0.0}
|
||||
jar=$sdk/platforms/${PLATFORM:-android-33}/android.jar
|
||||
jh=${JAVA_HOME:-"/Applications/Android Studio.app/Contents/jbr/Contents/Home"}
|
||||
ks=${KEYSTORE:-$HOME/.android/debug.keystore}
|
||||
so=$out/libd2r.so
|
||||
|
||||
[ -f "$so" ] || { echo "missing $so (build with APP=1 first)" >&2; exit 1; }
|
||||
[ -f "$jar" ] || { echo "missing $jar" >&2; exit 1; }
|
||||
[ -x "$jh/bin/javac" ] || { echo "no javac at $jh (set JAVA_HOME to JDK 11+)" >&2; exit 1; }
|
||||
|
||||
w=$out/apk
|
||||
rm -rf "$w"; mkdir -p "$w/classes" "$w/dex" "$w/lib/arm64-v8a"
|
||||
|
||||
"$jh/bin/javac" -nowarn --release 11 -classpath "$jar" -d "$w/classes" \
|
||||
$(find "$here/java" -name '*.java')
|
||||
PATH="$jh/bin:$PATH" "$bt/d8" --release --min-api 29 --lib "$jar" --output "$w/dex" \
|
||||
$(find "$w/classes" -name '*.class')
|
||||
|
||||
# 触屏 HUD 素材(从玩家自己的游戏文件生成,不进仓库):TouchArt/ = ios/tools/native_art/generate.py,hud_v4_ui/ = ios/tools/gen_hud_v4.py,mapgoal/ = ios/tools/gen_map_goal_art.py
|
||||
# Touch HUD assets (generated from the player's own game files, not in the repo): TouchArt/ = ios/tools/native_art/generate.py, hud_v4_ui/ = ios/tools/gen_hud_v4.py, mapgoal/ = ios/tools/gen_map_goal_art.py
|
||||
ios=$(cd "$here/../../ios" && pwd)
|
||||
mkdir -p "$w/assets/TouchArt"
|
||||
cp "$ios"/Sources/TouchArt/*.png "$w/assets/TouchArt/" 2>/dev/null || echo "warning: no TouchArt pngs (run ios/tools/gen_assets.py)" >&2
|
||||
if [ -d "$ios/Gen/assets/NativeHUD/v4/hud_v4_ui" ]; then cp -R "$ios/Gen/assets/NativeHUD/v4/hud_v4_ui" "$w/assets/"
|
||||
else echo "warning: no hud_v4_ui (run ios/tools/gen_assets.py)" >&2; fi
|
||||
if [ -d "$ios/Gen/assets/NativeHUD/mapgoal" ]; then rm -rf "$w/assets/mapgoal"; cp -R "$ios/Gen/assets/NativeHUD/mapgoal" "$w/assets/mapgoal" # 小地图任务终点 = ios/tools/gen_map_goal_art.py | minimap quest goals = ios/tools/gen_map_goal_art.py
|
||||
else echo "warning: no mapgoal (run ios/tools/gen_assets.py)" >&2; fi
|
||||
# 资源只有启动图标(res/:自适应图标,图同 iOS AppIcon1024.png)| The only resource is the launcher icon (res/: adaptive icon, same art as iOS AppIcon1024.png)
|
||||
"$bt/aapt2" compile --dir "$here/res" -o "$w/res.zip"
|
||||
"$bt/aapt2" link -o "$w/base.apk" --manifest "$here/AndroidManifest.xml" -I "$jar" \
|
||||
--min-sdk-version 29 --target-sdk-version 33 -A "$w/assets" -R "$w/res.zip" --auto-add-overlay
|
||||
cp "$so" "$w/lib/arm64-v8a/libd2r.so"
|
||||
(cd "$w/dex" && zip -q -X "$w/base.apk" classes.dex)
|
||||
# Native libs stored uncompressed so they stay page-aligned for zipalign -P.
|
||||
(cd "$w" && zip -q -X -0 base.apk lib/arm64-v8a/libd2r.so)
|
||||
|
||||
"$bt/zipalign" -f -P 16 4 "$w/base.apk" "$w/aligned.apk"
|
||||
PATH="$jh/bin:$PATH" "$bt/apksigner" sign --ks "$ks" --ks-pass pass:android \
|
||||
--ks-key-alias androiddebugkey --key-pass pass:android \
|
||||
--out "$out/d2r.apk" "$w/aligned.apk"
|
||||
echo "$out/d2r.apk"
|
||||
@@ -0,0 +1,287 @@
|
||||
// 全屏横屏 Activity:SurfaceView 交给 Vulkan 后端出图,上面盖一层触屏 HUD(TouchOverlay);触点 / 手柄 / 软键盘转给 libd2r.so(front_app.c、touch_app.c)。
|
||||
// Fullscreen landscape Activity: the SurfaceView goes to the Vulkan backend for presenting, with the touch HUD (TouchOverlay) on top; touches / controller / software keyboard go to libd2r.so (front_app.c, touch_app.c).
|
||||
package org.d2rmobile.app;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.AlertDialog;
|
||||
import android.os.Bundle;
|
||||
import android.os.VibrationEffect;
|
||||
import android.os.Vibrator;
|
||||
import android.view.Choreographer;
|
||||
import android.view.DisplayCutout;
|
||||
import android.view.WindowInsets;
|
||||
import android.widget.FrameLayout;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.text.InputFilter;
|
||||
import android.util.DisplayMetrics;
|
||||
import android.view.InputDevice;
|
||||
import android.view.KeyEvent;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.SurfaceHolder;
|
||||
import android.view.SurfaceView;
|
||||
import android.view.View;
|
||||
import android.view.WindowManager;
|
||||
import android.widget.EditText;
|
||||
import android.widget.TextView;
|
||||
import java.io.File;
|
||||
|
||||
public final class GameActivity extends Activity implements SurfaceHolder.Callback {
|
||||
private static native int nativeStart(String root, int screenW, int screenH);
|
||||
private static native void nativeSurface(Object surface, float hz);
|
||||
// 触屏 HUD(touch_app.c),坐标单位 dp | touch HUD (touch_app.c), coordinates in dp
|
||||
private static native void nativeLayout(float w, float h, float safeL, float safeR);
|
||||
private static native void nativeTouchEvent(int action, int pid, int[] pids, float[] xs, float[] ys, int n);
|
||||
private static native int nativeTick();
|
||||
static native Object[] nativeDraw(int part);
|
||||
private static native void nativePad(int face, int other, boolean nintendo, float lx, float ly, float rx, float ry);
|
||||
private static native long nativeFrames();
|
||||
private static native String[] nativeTextRequest();
|
||||
private static native void nativeTextResult(boolean ok, String text);
|
||||
// 前后台:0 onPause、1 onStop(局内等存盘,最多 2.5 s)、2 onStart、3 onResume(front_app.c)| foreground / background: 0 onPause, 1 onStop (waits for the save in a run, at most 2.5 s), 2 onStart, 3 onResume (front_app.c)
|
||||
private static native void nativeLifecycle(int ev);
|
||||
|
||||
// nn::hid 按钮位(dm_input.h)| nn::hid button bits (dm_input.h)
|
||||
private static final int LS = 1 << 4, RS = 1 << 5, L = 1 << 6, R = 1 << 7, ZL = 1 << 8, ZR = 1 << 9,
|
||||
PLUS = 1 << 10, MINUS = 1 << 11, LEFT = 1 << 12, UP = 1 << 13, RIGHT = 1 << 14, DOWN = 1 << 15;
|
||||
|
||||
private final Handler ui = new Handler(Looper.getMainLooper());
|
||||
private SurfaceView view;
|
||||
private boolean started;
|
||||
private TouchOverlay overlay, joy, goals;
|
||||
private float safeL, safeR;
|
||||
private Vibrator vibrator;
|
||||
private final int[] tPids = new int[32]; private final float[] tXs = new float[32], tYs = new float[32];
|
||||
private int padFace, padKeys, padHat;
|
||||
private float lx, ly, rx, ry, lt, rt;
|
||||
private boolean nintendo;
|
||||
private AlertDialog textDialog;
|
||||
// 左上角 FPS 标签:每 1 s 按游戏出帧数更新 | top-left FPS label: refreshed every 1 s from the game's presented frame count
|
||||
private TextView fps;
|
||||
private long fpsFrames, fpsTime;
|
||||
|
||||
/* 游戏自己按 60 Hz(省电 30 Hz)出帧;120 Hz 面板上软件时钟和垂直同步拍频,帧落在 1/2/3 个 vsync 上抖动,所以把屏幕钉在同分辨率的 60 Hz 模式
|
||||
* The game paces itself at 60 Hz (30 Hz in eco); on a 120 Hz panel the software clock beats against vsync and frames land on 1/2/3 vsyncs, so pin the panel to the same-resolution 60 Hz mode */
|
||||
private void pin60Hz() {
|
||||
if (android.os.Build.VERSION.SDK_INT < 23) return;
|
||||
android.view.Display d = getWindowManager().getDefaultDisplay();
|
||||
android.view.Display.Mode cur = d.getMode(), best = null;
|
||||
for (android.view.Display.Mode m : d.getSupportedModes()) {
|
||||
if (m.getPhysicalWidth() != cur.getPhysicalWidth() || m.getPhysicalHeight() != cur.getPhysicalHeight()) continue;
|
||||
if (Math.abs(m.getRefreshRate() - 60f) < 1f) { best = m; break; }
|
||||
}
|
||||
if (best == null) return;
|
||||
WindowManager.LayoutParams lp = getWindow().getAttributes();
|
||||
lp.preferredDisplayModeId = best.getModeId();
|
||||
getWindow().setAttributes(lp);
|
||||
}
|
||||
|
||||
@Override protected void onCreate(Bundle state) {
|
||||
super.onCreate(state);
|
||||
// 库的构造函数要按 DM_ROOT 找 dm/derived.tsv(经验表等),所以先设环境变量再加载 | the library's constructors locate dm/derived.tsv (EXP table etc.) via DM_ROOT, so set it before loading
|
||||
try { android.system.Os.setenv("DM_ROOT", new File(getFilesDir(), "d2r").getAbsolutePath(), true); } catch (Exception e) {}
|
||||
System.loadLibrary("d2r");
|
||||
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
if (android.os.Build.VERSION.SDK_INT >= 28)
|
||||
getWindow().getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
|
||||
pin60Hz();
|
||||
view = new SurfaceView(this);
|
||||
view.getHolder().addCallback(this);
|
||||
view.setFocusable(true); view.setFocusableInTouchMode(true);
|
||||
// 主体层与摇杆层分开:手指在摇杆上动时只重画摇杆层(见 touch_app.c op_list)。主体层不设 LAYER_TYPE_HARDWARE:在 Adreno 上那块离屏层刚进游戏的十几秒里会把屏幕顶部合成成台阶状黑块
|
||||
// the body and joystick layers are separate: while a finger moves on the stick only the joystick layer is redrawn (see touch_app.c op_list). No LAYER_TYPE_HARDWARE on the body layer: on Adreno that offscreen layer composited stepped black blocks at the top of the screen for the first dozen seconds in game
|
||||
overlay = new TouchOverlay(this, 0);
|
||||
joy = new TouchOverlay(this, 1);
|
||||
goals = new TouchOverlay(this, 2); // 小地图任务终点:跟着玩家走每帧变,单独一层不牵动主体层 | minimap quest goals: change every frame as the player walks, own layer so the body layer is untouched
|
||||
FrameLayout root = new FrameLayout(this);
|
||||
root.addView(view, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
|
||||
root.addView(goals, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
|
||||
root.addView(overlay, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
|
||||
root.addView(joy, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
|
||||
fps = new TextView(this);
|
||||
fps.setTextSize(12); fps.setTextColor(0xffe9d9ba); fps.setBackgroundColor(0x80000000);
|
||||
fps.setTypeface(android.graphics.Typeface.MONOSPACE); fps.setPadding(12, 4, 12, 4);
|
||||
root.addView(fps, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT));
|
||||
setContentView(root);
|
||||
// 刘海 / 挖孔:横屏左右的安全边距交给布局(同 iOS safeAreaInsets)| cutout / punch hole: the landscape left / right safe insets go to the layout (like iOS safeAreaInsets)
|
||||
root.setOnApplyWindowInsetsListener((v, in) -> {
|
||||
DisplayCutout cut = in.getDisplayCutout();
|
||||
safeL = cut != null ? cut.getSafeInsetLeft() : 0; safeR = cut != null ? cut.getSafeInsetRight() : 0;
|
||||
fps.setTranslationX(safeL);
|
||||
layoutHud(); return in;
|
||||
});
|
||||
overlay.addOnLayoutChangeListener((v, l, t, r, b, ol, ot, or, ob) -> layoutHud());
|
||||
vibrator = getSystemService(Vibrator.class);
|
||||
immersive();
|
||||
ui.post(textPoll);
|
||||
}
|
||||
private void immersive() {
|
||||
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
|
||||
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
|
||||
View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
|
||||
}
|
||||
@Override public void onWindowFocusChanged(boolean focus) { super.onWindowFocusChanged(focus); if (focus) immersive(); }
|
||||
|
||||
private void fail(String text) {
|
||||
TextView t = new TextView(this); t.setText(text); t.setTextSize(18); t.setPadding(48, 48, 48, 48);
|
||||
t.setTextColor(0xffe9d9ba); t.setBackgroundColor(0xff0d0d0f); setContentView(t);
|
||||
}
|
||||
|
||||
// ---- Surface ----
|
||||
@Override public void surfaceCreated(SurfaceHolder h) {}
|
||||
@Override public void surfaceChanged(SurfaceHolder h, int format, int w, int hh) {
|
||||
if (!started) {
|
||||
DisplayMetrics m = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getRealMetrics(m);
|
||||
File root = new File(getFilesDir(), "d2r");
|
||||
int rc = nativeStart(root.getAbsolutePath(), m.widthPixels, m.heightPixels);
|
||||
if (rc != 0) { fail("游戏文件不全(错误 " + rc + ")\n请把 dm/、romfs/、rt64/ 放到\n" + root.getAbsolutePath()); return; }
|
||||
started = true;
|
||||
layoutHud();
|
||||
Choreographer.getInstance().postFrameCallback(frame);
|
||||
}
|
||||
// 同步交出窗口:surfaceDestroyed 返回前后端必须已放手,这里对称处理 | Hand the window over synchronously: the backend must let go before surfaceDestroyed returns, handled symmetrically here
|
||||
nativeSurface(h.getSurface(), getWindowManager().getDefaultDisplay().getRefreshRate());
|
||||
}
|
||||
@Override public void surfaceDestroyed(SurfaceHolder h) {
|
||||
if (started) nativeSurface(null, 0);
|
||||
cancelTouches();
|
||||
}
|
||||
|
||||
// ---- 触屏 HUD | touch HUD ----
|
||||
private void layoutHud() {
|
||||
if (!started || overlay.getWidth() <= 0) return;
|
||||
float d = getResources().getDisplayMetrics().density;
|
||||
nativeLayout(overlay.getWidth() / d, overlay.getHeight() / d, safeL / d, safeR / d);
|
||||
overlay.invalidate(); joy.invalidate(); goals.invalidate();
|
||||
}
|
||||
// 每帧:推进 HUD 状态机(长按、松手脉冲、腰带 …),要重画才 invalidate;掉落震动按档位 | per frame: advance the HUD state machine (long press, release pulse, belt …), invalidate only when a redraw is needed; drop haptics by level
|
||||
private final Choreographer.FrameCallback frame = new Choreographer.FrameCallback() { public void doFrame(long t) {
|
||||
if (!started) return;
|
||||
int r = nativeTick();
|
||||
if ((r & 1) != 0) overlay.invalidate();
|
||||
if ((r & 2) != 0) joy.invalidate();
|
||||
if ((r & 4) != 0) goals.invalidate();
|
||||
if (t - fpsTime >= 1_000_000_000L) {
|
||||
long n = nativeFrames();
|
||||
if (fpsTime != 0) fps.setText(String.format(java.util.Locale.ROOT, "%.1f FPS", (n - fpsFrames) * 1e9 / (t - fpsTime)));
|
||||
fpsFrames = n; fpsTime = t;
|
||||
}
|
||||
int hap = r >> 4 & 3;
|
||||
if (hap != 0 && vibrator != null && vibrator.hasVibrator())
|
||||
vibrator.vibrate(VibrationEffect.createPredefined(hap == 1 ? VibrationEffect.EFFECT_HEAVY_CLICK : hap == 2 ? VibrationEffect.EFFECT_CLICK : VibrationEffect.EFFECT_TICK));
|
||||
Choreographer.getInstance().postFrameCallback(this);
|
||||
}};
|
||||
private void cancelTouches() { if (started) nativeTouchEvent(3, -1, null, null, null, 0); }
|
||||
@Override public boolean onTouchEvent(MotionEvent e) {
|
||||
if (!started) return true;
|
||||
int act = e.getActionMasked(), action;
|
||||
switch (act) {
|
||||
case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: action = 0; break;
|
||||
case MotionEvent.ACTION_MOVE: action = 1; break;
|
||||
case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: action = 2; break;
|
||||
case MotionEvent.ACTION_CANCEL: action = 3; break;
|
||||
default: return true;
|
||||
}
|
||||
float d = getResources().getDisplayMetrics().density;
|
||||
int n = Math.min(e.getPointerCount(), tPids.length);
|
||||
for (int i = 0; i < n; i++) { tPids[i] = e.getPointerId(i); tXs[i] = e.getX(i) / d; tYs[i] = e.getY(i) / d; }
|
||||
int pid = action == 0 || action == 2 ? e.getPointerId(e.getActionIndex()) : -1;
|
||||
nativeTouchEvent(action, pid, tPids, tXs, tYs, n); // 重画交给同一帧随后的 doFrame(nativeTick 比对指令表) | the redraw is left to the doFrame later in the same frame (nativeTick compares the draw lists)
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- 实体手柄 | physical controller ----
|
||||
private static boolean isPad(int source) {
|
||||
return (source & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD || (source & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK;
|
||||
}
|
||||
private void padPublish() {
|
||||
int other = padKeys | padHat | (lt > 0.5f ? ZL : 0) | (rt > 0.5f ? ZR : 0);
|
||||
nativePad(padFace, other, nintendo, lx, ly, rx, ry);
|
||||
}
|
||||
private static float dead(float v) { return Math.abs(v) < 0.12f ? 0 : v; }
|
||||
@Override public boolean dispatchKeyEvent(KeyEvent e) {
|
||||
int code = e.getKeyCode();
|
||||
if (code == KeyEvent.KEYCODE_BACK && !isPad(e.getSource())) return true; // 系统返回键不退出游戏 | the system back key does not quit the game
|
||||
if (!started || !isPad(e.getSource())) return super.dispatchKeyEvent(e);
|
||||
int face = 0, key = 0;
|
||||
switch (code) {
|
||||
case KeyEvent.KEYCODE_BUTTON_A: face = 1; break; // 下 | bottom
|
||||
case KeyEvent.KEYCODE_BUTTON_B: face = 2; break; // 右 | right
|
||||
case KeyEvent.KEYCODE_BUTTON_X: face = 4; break; // 左 | left
|
||||
case KeyEvent.KEYCODE_BUTTON_Y: face = 8; break; // 上 | top
|
||||
case KeyEvent.KEYCODE_BUTTON_L1: key = L; break;
|
||||
case KeyEvent.KEYCODE_BUTTON_R1: key = R; break;
|
||||
case KeyEvent.KEYCODE_BUTTON_L2: key = ZL; break;
|
||||
case KeyEvent.KEYCODE_BUTTON_R2: key = ZR; break;
|
||||
case KeyEvent.KEYCODE_BUTTON_THUMBL: key = LS; break;
|
||||
case KeyEvent.KEYCODE_BUTTON_THUMBR: key = RS; break;
|
||||
case KeyEvent.KEYCODE_BUTTON_START: key = PLUS; break;
|
||||
case KeyEvent.KEYCODE_BUTTON_SELECT: case KeyEvent.KEYCODE_BACK: key = MINUS; break;
|
||||
case KeyEvent.KEYCODE_DPAD_UP: key = UP; break;
|
||||
case KeyEvent.KEYCODE_DPAD_DOWN: key = DOWN; break;
|
||||
case KeyEvent.KEYCODE_DPAD_LEFT: key = LEFT; break;
|
||||
case KeyEvent.KEYCODE_DPAD_RIGHT: key = RIGHT; break;
|
||||
default: return super.dispatchKeyEvent(e);
|
||||
}
|
||||
InputDevice d = e.getDevice(); nintendo = d != null && d.getName() != null && d.getName().toLowerCase().matches(".*(nintendo|switch|joy-con).*");
|
||||
boolean down = e.getAction() == KeyEvent.ACTION_DOWN;
|
||||
if (face != 0) padFace = down ? padFace | face : padFace & ~face;
|
||||
else padKeys = down ? padKeys | key : padKeys & ~key;
|
||||
padPublish();
|
||||
return true;
|
||||
}
|
||||
@Override public boolean dispatchGenericMotionEvent(MotionEvent e) {
|
||||
if (!started || !isPad(e.getSource()) || e.getAction() != MotionEvent.ACTION_MOVE) return super.dispatchGenericMotionEvent(e);
|
||||
lx = dead(e.getAxisValue(MotionEvent.AXIS_X)); ly = dead(e.getAxisValue(MotionEvent.AXIS_Y));
|
||||
rx = dead(e.getAxisValue(MotionEvent.AXIS_Z)); ry = dead(e.getAxisValue(MotionEvent.AXIS_RZ));
|
||||
lt = Math.max(e.getAxisValue(MotionEvent.AXIS_LTRIGGER), e.getAxisValue(MotionEvent.AXIS_BRAKE));
|
||||
rt = Math.max(e.getAxisValue(MotionEvent.AXIS_RTRIGGER), e.getAxisValue(MotionEvent.AXIS_GAS));
|
||||
float hx = e.getAxisValue(MotionEvent.AXIS_HAT_X), hy = e.getAxisValue(MotionEvent.AXIS_HAT_Y);
|
||||
padHat = (hx < -0.5f ? LEFT : 0) | (hx > 0.5f ? RIGHT : 0) | (hy < -0.5f ? UP : 0) | (hy > 0.5f ? DOWN : 0);
|
||||
padPublish();
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- 软键盘 | software keyboard ----
|
||||
private final Runnable textPoll = new Runnable() { public void run() {
|
||||
if (started && textDialog == null) {
|
||||
String[] r = nativeTextRequest();
|
||||
if (r != null) showText(r);
|
||||
}
|
||||
ui.postDelayed(this, 250);
|
||||
}};
|
||||
private void showText(String[] r) {
|
||||
final EditText edit = new EditText(this);
|
||||
edit.setSingleLine(true); edit.setText(r[3]); edit.setSelection(edit.getText().length());
|
||||
if (!r[2].isEmpty()) edit.setHint(r[2]);
|
||||
int max = Integer.parseInt(r[4]); if (max > 0) edit.setFilters(new InputFilter[]{new InputFilter.LengthFilter(max)});
|
||||
String msg = r[1] + (!r[1].isEmpty() && !r[2].isEmpty() ? "\n" : "") + r[2];
|
||||
textDialog = new AlertDialog.Builder(this).setTitle(r[0].isEmpty() ? "输入" : r[0]).setMessage(msg.isEmpty() ? null : msg).setView(edit)
|
||||
.setPositiveButton(android.R.string.ok, (d, w) -> { nativeTextResult(true, edit.getText().toString()); textDialog = null; })
|
||||
.setNegativeButton(android.R.string.cancel, (d, w) -> { nativeTextResult(false, null); textDialog = null; })
|
||||
.setOnCancelListener(d -> { nativeTextResult(false, null); textDialog = null; })
|
||||
.create();
|
||||
textDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
|
||||
textDialog.show();
|
||||
}
|
||||
|
||||
// ---- 前后台 | foreground / background ----
|
||||
// 切走时按着的触点和手柄键一并清零:在后台松开收不到「松开」| touches and controller keys held while switching away are cleared: a release in the background never arrives
|
||||
@Override protected void onPause() {
|
||||
super.onPause();
|
||||
if (!started) return;
|
||||
cancelTouches();
|
||||
padFace = padKeys = padHat = 0; lx = ly = rx = ry = lt = rt = 0; padPublish();
|
||||
nativeLifecycle(0);
|
||||
}
|
||||
@Override protected void onStop() { super.onStop(); if (started) nativeLifecycle(1); }
|
||||
@Override protected void onStart() { super.onStart(); if (started) nativeLifecycle(2); }
|
||||
@Override protected void onResume() { super.onResume(); if (started) nativeLifecycle(3); }
|
||||
|
||||
@Override protected void onDestroy() {
|
||||
ui.removeCallbacks(textPoll);
|
||||
super.onDestroy();
|
||||
// 宿主不支持在同一进程里重新起跑:Activity 销毁就结束进程 | The host cannot restart in the same process: end the process when the Activity is destroyed
|
||||
if (isFinishing()) android.os.Process.killProcess(android.os.Process.myPid());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
// 局内触屏 HUD 叠加层:照 touch_app.c 每帧给的绘制指令表画(与 iOS DmTouchOverlay.m drawRect 一一对应);坐标单位 dp。
|
||||
// 素材取自 APK assets:TouchArt/(原版技能图集等)与 hud_v4_ui/(底部 UI v4,gen_hud_v4.py 生成)。本视图不接触摸,触摸由 Activity 交给 nativeTouchEvent。
|
||||
// In-run touch HUD overlay: draws from the per-frame draw list given by touch_app.c (one-to-one with iOS DmTouchOverlay.m drawRect); units are dp.
|
||||
// Assets come from the APK assets: TouchArt/ (original game skill atlases etc.) and hud_v4_ui/ (bottom UI v4, generated by gen_hud_v4.py). This view takes no touches; the Activity hands them to nativeTouchEvent.
|
||||
package org.d2rmobile.app;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.graphics.BlendMode;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.RectF;
|
||||
import android.graphics.Typeface;
|
||||
import android.util.Log;
|
||||
import android.view.View;
|
||||
import java.io.InputStream;
|
||||
import java.util.HashMap;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
final class TouchOverlay extends View {
|
||||
// 指令码:与 touch_app.c 的 OP_* 一致 | op codes: same as OP_* in touch_app.c
|
||||
private static final int FILL_ELLIPSE = 1, STROKE_ELLIPSE = 2, LINE = 3, ARC = 4, IMAGE = 5, TEXT = 6, FILL_RECT = 7, V4 = 8, V4TEXT = 9, LABEL = 10, COVER = 11;
|
||||
|
||||
private final float density;
|
||||
private final int part; // 0 = HUD 主体,1 = 摇杆,2 = 小地图任务终点(touch_app.c draw_overlay) | 0 = HUD body, 1 = joystick, 2 = minimap quest goals (touch_app.c draw_overlay)
|
||||
private final Paint fill = new Paint(Paint.ANTI_ALIAS_FLAG), stroke = new Paint(Paint.ANTI_ALIAS_FLAG),
|
||||
img = new Paint(Paint.FILTER_BITMAP_FLAG), text = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
private final HashMap<String, Bitmap> bitmaps = new HashMap<>();
|
||||
private final RectF rf = new RectF(); private final Rect src = new Rect();
|
||||
private JSONObject ui; private boolean uiLoaded;
|
||||
|
||||
TouchOverlay(Context c, int part) {
|
||||
super(c);
|
||||
this.part = part;
|
||||
density = getResources().getDisplayMetrics().density;
|
||||
fill.setStyle(Paint.Style.FILL); stroke.setStyle(Paint.Style.STROKE);
|
||||
text.setTypeface(Typeface.create(Typeface.SERIF, Typeface.NORMAL)); text.setTextAlign(Paint.Align.CENTER);
|
||||
setWillNotDraw(false); setClickable(false); setFocusable(false);
|
||||
}
|
||||
|
||||
private Bitmap bitmap(String path) {
|
||||
if (bitmaps.containsKey(path)) return bitmaps.get(path);
|
||||
Bitmap b = null;
|
||||
try (InputStream in = getContext().getAssets().open(path)) {
|
||||
BitmapFactory.Options o = new BitmapFactory.Options(); o.inScaled = false; o.inPremultiplied = true;
|
||||
b = BitmapFactory.decodeStream(in, null, o);
|
||||
} catch (Exception e) { Log.w("d2r", "触屏 HUD:缺素材 " + path); }
|
||||
bitmaps.put(path, b); return b; // 缺的也记下,不每帧重试 | misses are remembered too, no per-frame retry
|
||||
}
|
||||
private JSONObject ui() {
|
||||
if (!uiLoaded) { uiLoaded = true;
|
||||
try (InputStream in = getContext().getAssets().open("hud_v4_ui/ui.json")) {
|
||||
ui = new JSONObject(new String(in.readAllBytes(), "UTF-8"));
|
||||
} catch (Exception e) { Log.e("d2r", "【红】底部 UI v4:APK 内缺 hud_v4_ui/ui.json"); } }
|
||||
return ui;
|
||||
}
|
||||
private static int rgba(float r, float g, float b, float a) {
|
||||
return Color.argb(Math.round(Math.max(0, Math.min(1, a)) * 255), Math.round(r * 255), Math.round(g * 255), Math.round(b * 255));
|
||||
}
|
||||
|
||||
@Override protected void onDraw(Canvas c) {
|
||||
Object[] d = GameActivity.nativeDraw(part); if (d == null) return;
|
||||
float[] o = (float[]) d[0]; String[] s = (String[]) d[1];
|
||||
c.save(); c.scale(density, density);
|
||||
for (int p = 0; p + 2 <= o.length; ) {
|
||||
int code = (int) o[p], n = (int) o[p + 1], a = p + 2; p = a + n;
|
||||
switch (code) {
|
||||
case FILL_ELLIPSE: fill.setColor(rgba(o[a + 4], o[a + 5], o[a + 6], o[a + 7])); rf.set(o[a], o[a + 1], o[a] + o[a + 2], o[a + 1] + o[a + 3]); c.drawOval(rf, fill); break;
|
||||
case STROKE_ELLIPSE: stroke.setStrokeWidth(o[a + 4]); stroke.setColor(rgba(o[a + 5], o[a + 6], o[a + 7], o[a + 8])); rf.set(o[a], o[a + 1], o[a] + o[a + 2], o[a + 1] + o[a + 3]); c.drawOval(rf, stroke); break;
|
||||
case LINE: stroke.setStrokeWidth(o[a + 4]); stroke.setStrokeCap(Paint.Cap.BUTT); stroke.setColor(rgba(o[a + 5], o[a + 6], o[a + 7], o[a + 8])); c.drawLine(o[a], o[a + 1], o[a + 2], o[a + 3], stroke); break;
|
||||
case ARC: { float r = o[a + 2]; stroke.setStrokeWidth(o[a + 5]); stroke.setColor(rgba(o[a + 6], o[a + 7], o[a + 8], o[a + 9]));
|
||||
rf.set(o[a] - r, o[a + 1] - r, o[a] + r, o[a + 1] + r);
|
||||
c.drawArc(rf, (float) Math.toDegrees(o[a + 3]), (float) Math.toDegrees(o[a + 4] - o[a + 3]), false, stroke); break; }
|
||||
case FILL_RECT: fill.setColor(rgba(o[a + 4], o[a + 5], o[a + 6], o[a + 7])); c.drawRect(o[a], o[a + 1], o[a] + o[a + 2], o[a + 1] + o[a + 3], fill); break;
|
||||
case IMAGE: {
|
||||
Bitmap b = o[a] >= 0 ? bitmap(s[(int) o[a]]) : null;
|
||||
if (b == null && o[a + 1] >= 0) b = bitmap(s[(int) o[a + 1]]);
|
||||
if (b == null) break;
|
||||
if (o[a + 4] > 0) src.set((int) o[a + 2], (int) o[a + 3], (int) (o[a + 2] + o[a + 4]), (int) (o[a + 3] + o[a + 5]));
|
||||
else src.set(0, 0, b.getWidth(), b.getHeight());
|
||||
rf.set(o[a + 6], o[a + 7], o[a + 6] + o[a + 8], o[a + 7] + o[a + 9]);
|
||||
img.setAlpha(Math.round(Math.max(0, Math.min(1, o[a + 10])) * 255));
|
||||
img.setBlendMode(o[a + 11] == 1 ? BlendMode.LUMINOSITY : null);
|
||||
c.drawBitmap(b, src, rf, img); img.setBlendMode(null); break; }
|
||||
case TEXT: { // 矩形内水平居中、顶对齐(同 NSString drawInRect)| centered horizontally, top-aligned in the rect (like NSString drawInRect)
|
||||
text.setTextSize(o[a + 5]); text.setColor(rgba(.85f, .79f, .65f, o[a + 6]));
|
||||
c.drawText(s[(int) o[a]], o[a + 1] + o[a + 3] / 2, o[a + 2] - text.getFontMetrics().ascent, text); break; }
|
||||
case LABEL: {
|
||||
Bitmap b = bitmap(s[(int) o[a]]);
|
||||
if (b == null && n > 4 && o[a + 4] >= 0) b = bitmap(s[(int) o[a + 4]]); // 可选第 5 项 = 备用图 | optional 5th value = fallback image
|
||||
if (b == null) break;
|
||||
float h = o[a + 3], w = b.getWidth() * h / b.getHeight();
|
||||
rf.set(o[a + 1] - w / 2, o[a + 2] - h / 2, o[a + 1] + w / 2, o[a + 2] + h / 2); img.setAlpha(255); c.drawBitmap(b, null, rf, img); break; }
|
||||
case V4TEXT: { JSONObject u = ui(); if (u == null) break;
|
||||
float hh = getHeight() / density, ww = getWidth() / density;
|
||||
v4text(c, s[(int) o[a]], u.optJSONObject("badge").optJSONObject("glyphs"), o[a + 1], o[a + 2], (int) o[a + 3], ww, hh / 1320f); break; }
|
||||
case V4: drawV4(c, o, a, s); break;
|
||||
case COVER: fill.setColor(Color.BLACK); c.drawRect(0, 0, o[a], o[a + 1], fill); break;
|
||||
}
|
||||
}
|
||||
c.restore();
|
||||
}
|
||||
|
||||
// ---- 底部 UI v4(同 DmTouchOverlay.m drawV4):几何单位 = 2868×1320 效果图像素,x = (像素 − 1434) × u + 宽/2,y = 像素 × u,u = 高/1320 ----
|
||||
// ---- Bottom UI v4 (same as DmTouchOverlay.m drawV4): geometry unit = pixels of the 2868×1320 mockup, x = (px − 1434) × u + width/2, y = px × u, u = height/1320 ----
|
||||
private void v4text(Canvas c, String str, JSONObject glyphs, float x, float baseline, int align, float W, float u) {
|
||||
if (glyphs == null) return;
|
||||
float adv = 0; for (int i = 0; i < str.length(); i++) { JSONObject g = glyphs.optJSONObject(str.substring(i, i + 1)); if (g != null) adv += (float) g.optDouble("adv"); }
|
||||
float pen = align == 1 ? x - adv : x - adv / 2;
|
||||
img.setAlpha(255);
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
JSONObject g = glyphs.optJSONObject(str.substring(i, i + 1)); if (g == null) continue;
|
||||
String f = g.optString("file", null); Bitmap b = f != null && !g.isNull("file") ? bitmap("hud_v4_ui/" + f) : null;
|
||||
if (b != null) { float l = (pen + (float) g.optDouble("dx") - 1434) * u + W / 2, t = (baseline + (float) g.optDouble("dy")) * u;
|
||||
rf.set(l, t, l + b.getWidth() * u, t + b.getHeight() * u); c.drawBitmap(b, null, rf, img); }
|
||||
pen += (float) g.optDouble("adv");
|
||||
}
|
||||
}
|
||||
private float X(float px, float u, float W) { return (px - 1434) * u + W / 2; }
|
||||
private void blit(Canvas c, Bitmap b, float l, float t, float w, float h, float alpha) {
|
||||
if (b == null) return; rf.set(l, t, l + w, t + h); img.setAlpha(Math.round(alpha * 255)); c.drawBitmap(b, null, rf, img); img.setAlpha(255);
|
||||
}
|
||||
private void digit(Canvas c, int n, float cx, float cy, float alpha, float u, float W) {
|
||||
Bitmap d = bitmap("hud_v4_ui/diff_" + n + ".png"); if (d == null) return;
|
||||
blit(c, d, X(cx, u, W) - d.getWidth() * u / 2, cy * u - d.getHeight() * u / 2, d.getWidth() * u, d.getHeight() * u, alpha);
|
||||
}
|
||||
private static int rgb(JSONArray a) { return Color.rgb(a.optInt(0), a.optInt(1), a.optInt(2)); }
|
||||
// v:life, mana, lv(字符串表下标), 十字按住, 有点数, 任务未读, 经验‰, 腰带 ×4, 难度档, 选择条展开
|
||||
// v: life, mana, lv (string table indices), cross held, has points, quest unread, exp ‰, belt ×4, difficulty level, selector expanded
|
||||
private void drawV4(Canvas c, float[] o, int a, String[] s) {
|
||||
JSONObject ui = ui(); if (ui == null) return;
|
||||
try {
|
||||
float W = getWidth() / density, u = getHeight() / density / 1320f;
|
||||
boolean held = o[a + 3] != 0, points = o[a + 4] != 0, alert = points || o[a + 5] != 0;
|
||||
float exp = o[a + 6]; int players = (int) o[a + 11]; boolean diffOpen = o[a + 12] != 0;
|
||||
Bitmap full = bitmap("hud_v4_ui/base_full.png"); JSONObject bo = ui.getJSONObject("base");
|
||||
if (full != null) blit(c, full, X((float) bo.getDouble("x"), u, W), (float) bo.getDouble("y") * u, full.getWidth() * u, full.getHeight() * u, 1);
|
||||
JSONArray slots = ui.getJSONArray("slots"), s6 = slots.getJSONArray(5);
|
||||
Bitmap btn = bitmap(alert ? (held ? "hud_v4_ui/lvl_1.png" : "hud_v4_ui/lvl_0.png") : (held ? "hud_v4_ui/lvl_d1.png" : "hud_v4_ui/lvl_d0.png"));
|
||||
float bl = X((float) s6.getDouble(0), u, W), bt = (float) s6.getDouble(1) * u, bw = (float) (s6.getDouble(2) - s6.getDouble(0)) * u, bh = (float) (s6.getDouble(3) - s6.getDouble(1)) * u;
|
||||
if (btn != null) {
|
||||
if (points) { img.setShadowLayer(10 * u, 0, 0, Color.argb(242, 255, 209, 89)); blit(c, btn, bl, bt, bw, bh, 1); img.clearShadowLayer(); }
|
||||
blit(c, btn, bl, bt, bw, bh, 1);
|
||||
}
|
||||
JSONObject e = ui.getJSONObject("exp");
|
||||
float x0 = (float) e.getDouble("x0"), x1 = (float) e.getDouble("x1"), y = (float) e.getDouble("y"), eh = (float) e.getDouble("h");
|
||||
fill.setColor(rgb(e.getJSONArray("track"))); c.drawRect(X(x0, u, W), y * u, X(x0, u, W) + (x1 - x0) * u, (y + eh) * u, fill);
|
||||
stroke.setColor(rgb(e.getJSONArray("edge"))); stroke.setStrokeWidth(u);
|
||||
c.drawRect(X(x0, u, W) + u / 2, y * u + u / 2, X(x0, u, W) + u / 2 + (x1 - x0 - 1) * u, y * u + u / 2 + (eh - 1) * u, stroke);
|
||||
fill.setColor(rgb(e.getJSONArray("fill"))); c.drawRect(X(x0 + 1, u, W), (y + 1) * u, X(x0 + 1, u, W) + (x1 - x0 - 2) * u * exp / 1000f, (y + eh - 1) * u, fill);
|
||||
int ticks = e.getInt("ticks"); fill.setColor(rgb(e.getJSONArray("track")));
|
||||
for (int t = 1; t < ticks; t++) { float tx = X(x0 + Math.round((x1 - x0) * t / (double) ticks), u, W); c.drawRect(tx, (y + 1) * u, tx + u, (y + eh - 1) * u, fill); }
|
||||
JSONObject vt = ui.getJSONObject("vital");
|
||||
v4text(c, s[(int) o[a]], vt.getJSONObject("glyphs"), (float) vt.getDouble("left_x"), (float) vt.getDouble("baseline"), 0, W, u);
|
||||
v4text(c, s[(int) o[a + 1]], vt.getJSONObject("glyphs"), (float) vt.getDouble("right_x"), (float) vt.getDouble("baseline"), 0, W, u);
|
||||
JSONObject lv = ui.getJSONObject("lv");
|
||||
v4text(c, s[(int) o[a + 2]], lv.getJSONObject("glyphs"), (float) lv.getDouble("x"), (float) lv.getDouble("baseline"), 0, W, u);
|
||||
JSONArray in = ui.getJSONArray("inner"); JSONObject bd = ui.getJSONObject("badge");
|
||||
for (int i = 1; i <= 4; i++) { int cnt = (int) o[a + 6 + i]; if (cnt == 0) continue;
|
||||
JSONArray si = slots.getJSONArray(i);
|
||||
v4text(c, Integer.toString(cnt), bd.getJSONObject("glyphs"), (float) (si.getDouble(0) + in.getDouble(2) + bd.getDouble("dx")), (float) (si.getDouble(1) + in.getDouble(3) + bd.getDouble("dy")), 1, W, u); }
|
||||
float icx = (float) (in.getDouble(0) + in.getDouble(2) + 1) / 2, icy = (float) (in.getDouble(1) + in.getDouble(3) + 1) / 2;
|
||||
JSONArray s0 = slots.getJSONArray(0);
|
||||
if (players >= 1 && players <= 8) digit(c, players, (float) s0.getDouble(0) + icx, (float) s0.getDouble(1) + icy, 1, u, W);
|
||||
if (diffOpen) {
|
||||
JSONObject pk = ui.getJSONObject("pick"); Bitmap tile = bitmap("hud_v4_ui/slot.png");
|
||||
for (int i = 0; i < 8; i++) {
|
||||
float cx = (float) (pk.getDouble("center_x") + (i - 3.5) * pk.getDouble("pitch")), cy = (float) pk.getDouble("y"), al = i + 1 == players ? 1 : .82f;
|
||||
if (tile != null) blit(c, tile, X(cx - tile.getWidth() / 2f, u, W), (cy - tile.getHeight() / 2f) * u, tile.getWidth() * u, tile.getHeight() * u, al);
|
||||
digit(c, i + 1, cx, cy, al, u, W);
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) { Log.e("d2r", "底部 UI v4 绘制失败:" + ex); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- 自适应图标:图在 108dp 画布中缩到 72dp,各家圆形 / 圆角遮罩都不裁到图(iOS 同一张 AppIcon1024.png)| Adaptive icon: the art is scaled to 72dp inside the 108dp canvas so no launcher mask crops it (same AppIcon1024.png as iOS) -->
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@android:color/black" />
|
||||
<foreground android:drawable="@mipmap/ic_launcher_fg" />
|
||||
</adaptive-icon>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 69 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 120 KiB |
@@ -0,0 +1,70 @@
|
||||
# Android(arm64,仅 Adreno 机型)构建规则。由 dm/android/Makefile 以 dm/host 为当前目录调用(宿主共用源码按 host 的相对路径列),产物放 dm/android/build/
|
||||
# 缺省:无头宿主 dmhost(adb shell 直接跑);APP=1:libd2r.so 给 GameActivity 加载
|
||||
# Android (arm64, Adreno devices only) build rules. Invoked by dm/android/Makefile with dm/host as the current directory (the shared host sources are listed relative to host); outputs go to dm/android/build/
|
||||
# Default: the headless host dmhost (run directly from adb shell); APP=1: libd2r.so for GameActivity to load
|
||||
ANDROID_DIR := $(abspath ../android)
|
||||
NDK ?= $(or $(ANDROID_NDK_HOME),$(lastword $(sort $(wildcard $(HOME)/Library/Android/sdk/ndk/*))))
|
||||
API ?= 33
|
||||
CC := $(wildcard $(NDK)/toolchains/llvm/prebuilt/*/bin)/aarch64-linux-android$(API)-clang
|
||||
OUT ?= $(ANDROID_DIR)/build
|
||||
# 表头:没有游戏文件时可用 DM_GENH_DIR 指向现成的表头目录 | generated headers: without game files, DM_GENH_DIR can point at a directory of ready-made headers
|
||||
GENH_DIR ?= $(or $(DM_GENH_DIR),.)
|
||||
# -ffixed-x18:x18 是客体的平台寄存器,宿主代码不许碰;16K 页对齐(Android 15+ 16K 页设备);保留 __start_/__stop_ 段登记表
|
||||
# -ffixed-x18: x18 is the guest's platform register, host code must not touch it; 16K page alignment (Android 15+ 16K-page devices); keep the __start_/__stop_ section registration tables
|
||||
CFLAGS = -O1 -g -Wall -Wno-unused-function -Wno-format -ffixed-x18 -fPIE \
|
||||
-include compat/linux/compat_linux.h -Icompat/linux/include -I. -I$(GENH_DIR) -I../gfx/nvn/include -I../gfx/nvn
|
||||
LDFLAGS = -pie -Wl,-z,max-page-size=16384 -Wl,-z,nostart-stop-gc -Wl,--export-dynamic
|
||||
# APP=1:同一份源编成 libd2r.so 给 GameActivity 加载(dm/android/app/),前端换成 Sources/front_app.c;APK 由 app/build_apk.sh 打
|
||||
# APP=1: build the same sources into libd2r.so for GameActivity to load (dm/android/app/), with Sources/front_app.c as the front end; the APK is packed by app/build_apk.sh
|
||||
ifeq ($(APP),1)
|
||||
OUT := $(ANDROID_DIR)/build/app
|
||||
CFLAGS := $(subst -fPIE,-fPIC,$(CFLAGS))
|
||||
LDFLAGS := -shared -Wl,-soname,libd2r.so -Wl,-Bsymbolic -Wl,--no-undefined -Wl,-z,max-page-size=16384 -Wl,-z,nostart-stop-gc
|
||||
endif
|
||||
LIBS = -llog -lm -ldl -lz -landroid -laaudio
|
||||
# 与 Makefile 同一份源单,去掉 macOS 专属(.m、touch_mac.c、front_mac.m、memstat.m)
|
||||
# Same source list as Makefile, minus the macOS-only ones (.m, touch_mac.c, front_mac.m, memstat.m)
|
||||
# Makefile 的 SRC 是续行写的(一行一个),读到第一条不带续行符的行为止 | Makefile's SRC uses continuation lines (one per line); read up to the first line without a continuation
|
||||
SRC_MAC := $(filter %.c,$(shell awk '/^SRC=/{f=1} f{l=$$0; sub(/^SRC=/,"",l); c=(l ~ /[\\\\]$$/); sub(/[\\\\]$$/,"",l); print l; if(!c) exit}' Makefile))
|
||||
SRC := $(filter-out touch_mac.c,$(SRC_MAC)) $(sort $(wildcard hle_*.c)) $(wildcard compat/linux/*.c)
|
||||
ifneq ($(APP),1)
|
||||
SRC += ../android/Sources/front_headless.c
|
||||
else
|
||||
SRC += ../android/Sources/front_app.c ../android/Sources/touch_app.c \
|
||||
../touch/dm_touch_game_bridge.c ../touch/dm_touch_game_state.c ../touch/dm_touch_game_identity.c ../touch/dm_touch_native_art.c
|
||||
endif
|
||||
GFX := $(sort $(wildcard ../gfx/*.c ../gfx/nvn/*.c ../gfx/tex/*.c ../gfx/vulkan/*.c))
|
||||
LIBDEFLATE := $(shell sed -n 's/^LIBDEFLATE=//p' Makefile)
|
||||
ASM := entry.S ../gfx/nvn/nvn_entry.S ../gfx/nvn/nvn_thunks.S
|
||||
OBJ := $(patsubst %.c,$(OUT)/obj/%.o,$(subst ../,up/,$(SRC) $(GFX) $(LIBDEFLATE))) \
|
||||
$(patsubst %.S,$(OUT)/obj/%.o,$(subst ../,up/,$(ASM)))
|
||||
|
||||
$(OUT)/dmhost: $(OBJ)
|
||||
$(CC) $(LDFLAGS) -Wl,--error-limit=0 -o $@ $^ $(LIBS)
|
||||
$(OUT)/libd2r.so: $(OBJ)
|
||||
$(CC) $(LDFLAGS) -Wl,--error-limit=0 -o $@ $^ $(LIBS)
|
||||
|
||||
# 图形回放(gfx/,含 Vulkan 后端 gfx/vulkan/)是逐绘制热路径,用 -O2;其余宿主代码保持 -O1,与 Mac 构建一致
|
||||
# Graphics replay (gfx/, including the Vulkan backend gfx/vulkan/) is the per-draw hot path, built at -O2; the rest of the host stays at -O1 like the Mac build
|
||||
$(OUT)/obj/up/gfx/%.o: CFLAGS += -O2
|
||||
$(OUT)/obj/up/gfx/vulkan/nvn_vk.o: ../gfx/vulkan/nvn_vk_mip_layout.h ../gfx/vulkan/nvn_vk_dispatch.h
|
||||
|
||||
$(OUT)/obj/up/%.o: ../%.c
|
||||
@mkdir -p $(dir $@)
|
||||
$(CC) $(CFLAGS) -c $< -o $@
|
||||
$(OUT)/obj/%.o: %.c dm.h hle.h compat/linux/compat_linux.h
|
||||
@mkdir -p $(dir $@)
|
||||
$(CC) $(CFLAGS) -c $< -o $@
|
||||
# Mach-O 汇编转 ELF:去符号前导 _、@PAGE/@PAGEOFF 换 ELF 写法、.cstring 换 .rodata
|
||||
# Mach-O assembly to ELF: strip the leading _ of symbols, @PAGE/@PAGEOFF to the ELF forms, .cstring to .rodata
|
||||
ASM2ELF = perl -pe 's/(?<![\w.])_([A-Za-z])/$$1/g; s/(\w+)\@PAGEOFF/:lo12:$$1/g; s/(\w+)\@PAGE\b/$$1/g; s/^\s*\.cstring\b/\t.section .rodata/'
|
||||
$(OUT)/obj/up/%.o: ../%.S
|
||||
@mkdir -p $(dir $@)
|
||||
$(ASM2ELF) $< > $(@:.o=.elf.S) && $(CC) -c $(@:.o=.elf.S) -o $@
|
||||
$(OUT)/obj/%.o: %.S
|
||||
@mkdir -p $(dir $@)
|
||||
$(ASM2ELF) $< > $(@:.o=.elf.S) && $(CC) -c $(@:.o=.elf.S) -o $@
|
||||
|
||||
clean:
|
||||
rm -rf $(OUT)
|
||||
.PHONY: clean
|
||||
@@ -0,0 +1,13 @@
|
||||
NDK ?= $(or $(ANDROID_NDK_HOME),$(lastword $(sort $(wildcard $(HOME)/Library/Android/sdk/ndk/*))))
|
||||
.DEFAULT_GOAL := all
|
||||
CC := $(wildcard $(NDK)/toolchains/llvm/prebuilt/*/bin)/aarch64-linux-android33-clang
|
||||
OUT ?= ../build/tests
|
||||
CFLAGS = -O1 -g -Wall -Wno-unused-function -ffunction-sections -fdata-sections -I../../gfx/nvn -I../../gfx/nvn/include -include ../../host/compat/linux/compat_linux.h -I../../host/compat/linux/include -I../../host
|
||||
$(OUT)/t_vk_perf: t_vk_perf.c ../../gfx/vulkan/nvn_vk.c ../../gfx/vulkan/nvn_vk_dispatch.h ../../gfx/vulkan/nvn_vk_mip_layout.h
|
||||
@mkdir -p $(OUT)
|
||||
$(CC) $(CFLAGS) -Wl,--gc-sections -Wl,-z,max-page-size=16384 $< -o $@ -landroid -ldl -lm -lz
|
||||
$(OUT)/t_vk_caps: t_vk_caps.c
|
||||
@mkdir -p $(OUT)
|
||||
$(CC) -O2 -g -Wall -Wextra -Werror -Wl,-z,max-page-size=16384 $< -o $@ -lvulkan
|
||||
.PHONY: all
|
||||
all: $(OUT)/t_vk_perf $(OUT)/t_vk_caps
|
||||
@@ -0,0 +1,107 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Game-free host checks, NDK build, and optional real-device Vulkan regression.
|
||||
|
||||
Default: host + ASan/UBSan + Android test binaries, without contacting a device.
|
||||
--run-device requires an explicit serial; it only pushes these test binaries to
|
||||
a unique /data/local/tmp directory. It does not install/start the game app.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
parser.add_argument('--ndk', type=Path)
|
||||
parser.add_argument('--host-only', action='store_true')
|
||||
parser.add_argument('--run-device', action='store_true')
|
||||
parser.add_argument('--serial')
|
||||
args = parser.parse_args()
|
||||
if args.run_device and (args.host_only or not args.serial):
|
||||
parser.error('--run-device requires --serial and an Android build')
|
||||
repo = Path(__file__).resolve().parents[3]
|
||||
out = args.output.resolve()
|
||||
out.mkdir(parents=True, exist_ok=False)
|
||||
report = {'schema': 1, 'passed': False, 'device_contacted': False,
|
||||
'gpu_executed': False, 'game_tested': False, 'steps': []}
|
||||
|
||||
def save():
|
||||
(out / 'result.json').write_text(json.dumps(report, indent=2) + '\n')
|
||||
|
||||
def run(name, command, timeout=120):
|
||||
print(name, flush=True)
|
||||
start = time.monotonic()
|
||||
process = subprocess.run(command, cwd=repo, capture_output=True, text=True, timeout=timeout)
|
||||
(out / (name + '.log')).write_text(process.stdout + process.stderr)
|
||||
report['steps'].append({'name': name, 'command': command, 'exit_code': process.returncode,
|
||||
'elapsed_seconds': round(time.monotonic() - start, 3)})
|
||||
save()
|
||||
process.check_returncode()
|
||||
return process.stdout
|
||||
|
||||
save()
|
||||
try:
|
||||
candidates = sorted((Path.home() / 'Library/Android/sdk/ndk').glob('*'),
|
||||
key=lambda p: tuple(int(v) for v in p.name.split('.') if v.isdigit()))
|
||||
ndk = args.ndk or (Path(os.environ['ANDROID_NDK_HOME']) if os.environ.get('ANDROID_NDK_HOME') else None)
|
||||
if ndk is None and candidates:
|
||||
ndk = candidates[-1]
|
||||
if ndk is None:
|
||||
raise RuntimeError('Specify --ndk (Vulkan headers are needed even for host-only checks)')
|
||||
ndk = ndk.resolve()
|
||||
headers = list(ndk.glob('toolchains/llvm/prebuilt/*/sysroot/usr/include'))
|
||||
if len(headers) != 1:
|
||||
raise RuntimeError('Expected one NDK host toolchain under ' + str(ndk))
|
||||
cc = shlex.split(os.environ.get('HOST_CC', 'clang'))
|
||||
common = cc + ['-std=c11', '-O1', '-g', '-Wall', '-Wextra', '-Werror', '-idirafter', str(headers[0]),
|
||||
'dm/android/tests/t_vk_mip_layout.c']
|
||||
for mode, flags in [('normal', []), ('sanitized', ['-fsanitize=address,undefined', '-fno-omit-frame-pointer'])]:
|
||||
binary = out / ('mip-' + mode)
|
||||
run('build-' + mode, common + flags + ['-o', str(binary)])
|
||||
run('run-' + mode, [str(binary)])
|
||||
if not args.host_only:
|
||||
binaries = out / 'android'
|
||||
run('ndk-build', ['make', '-C', 'dm/android/tests', 'all', 'NDK=' + str(ndk), 'OUT=' + str(binaries)], 180)
|
||||
report['artifacts_sha256'] = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(binaries.iterdir())}
|
||||
sources = ['dm/gfx/vulkan/nvn_vk.c', 'dm/gfx/vulkan/nvn_vk_mip_layout.h',
|
||||
'dm/android/tests/t_vk_perf.c', 'dm/android/tests/t_vk_caps.c',
|
||||
'dm/android/tests/t_vk_mip_layout.c', 'dm/android/tests/Makefile', 'dm/android/tests/run_checks.py']
|
||||
report['source_sha256'] = {p: hashlib.sha256((repo / p).read_bytes()).hexdigest() for p in sources}
|
||||
if args.run_device:
|
||||
adb = shutil.which('adb')
|
||||
if not adb:
|
||||
raise RuntimeError('adb is not available')
|
||||
device = [adb, '-s', args.serial]
|
||||
report['device_contacted'] = True
|
||||
run('device-state', device + ['get-state'])
|
||||
remote = '/data/local/tmp/d2r-checks-' + uuid.uuid4().hex
|
||||
run('device-mkdir', device + ['shell', 'mkdir', remote])
|
||||
try:
|
||||
for name in ('t_vk_caps', 't_vk_perf'):
|
||||
run('push-' + name, device + ['push', str(binaries / name), remote + '/' + name])
|
||||
run('chmod-' + name, device + ['shell', 'chmod', '700', remote + '/' + name])
|
||||
caps = run('device-caps', device + ['shell', remote + '/t_vk_caps'])
|
||||
report['capabilities'] = json.loads(caps)
|
||||
report['gpu_executed'] = True
|
||||
run('device-regression', device + ['shell', remote + '/t_vk_perf'], 180)
|
||||
finally:
|
||||
run('device-cleanup', device + ['shell', 'rm', '-rf', remote])
|
||||
report['passed'] = True
|
||||
except Exception as exc:
|
||||
report['error'] = str(exc)
|
||||
raise
|
||||
finally:
|
||||
save()
|
||||
print('ANDROID_CHECKS_PASS ' + str(out / 'result.json'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,44 @@
|
||||
/* Standalone, game-free Vulkan capability receipt. No private driver, layer,
|
||||
* window, pipeline, game file or application setting is changed by this probe. */
|
||||
#include <vulkan/vulkan.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
static void json_string(const char *s) {
|
||||
putchar('"');
|
||||
for(const unsigned char *p=(const unsigned char *)s;*p;p++) {
|
||||
if(*p=='"'||*p=='\\')printf("\\%c",*p);
|
||||
else if(*p<32)printf("\\u%04x",*p);
|
||||
else putchar(*p);
|
||||
}
|
||||
putchar('"');
|
||||
}
|
||||
int main(void) {
|
||||
VkApplicationInfo app={.sType=VK_STRUCTURE_TYPE_APPLICATION_INFO,.pApplicationName="D2R capability probe",.apiVersion=VK_API_VERSION_1_1};
|
||||
VkInstanceCreateInfo ci={.sType=VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,.pApplicationInfo=&app};VkInstance instance;
|
||||
VkResult rc=vkCreateInstance(&ci,NULL,&instance);
|
||||
if(rc!=VK_SUCCESS){fprintf(stderr,"vkCreateInstance: %d\n",rc);return 1;}
|
||||
uint32_t n=0;rc=vkEnumeratePhysicalDevices(instance,&n,NULL);
|
||||
if(rc!=VK_SUCCESS||!n){fprintf(stderr,"no physical devices: %d\n",rc);vkDestroyInstance(instance,NULL);return 1;}
|
||||
VkPhysicalDevice *devices=calloc(n,sizeof *devices);if(!devices)return 1;
|
||||
rc=vkEnumeratePhysicalDevices(instance,&n,devices);if(rc!=VK_SUCCESS){free(devices);vkDestroyInstance(instance,NULL);return 1;}
|
||||
printf("{\"schema\":1,\"game_compatibility_verified\":false,\"devices\":[");
|
||||
for(uint32_t i=0;i<n;i++) {
|
||||
VkPhysicalDeviceProperties p;VkPhysicalDeviceFeatures f;VkPhysicalDeviceMemoryProperties m;
|
||||
vkGetPhysicalDeviceProperties(devices[i],&p);vkGetPhysicalDeviceFeatures(devices[i],&f);vkGetPhysicalDeviceMemoryProperties(devices[i],&m);
|
||||
if(i)putchar(',');printf("{\"name\":");json_string(p.deviceName);
|
||||
printf(",\"vendor_id\":%u,\"device_id\":%u,\"api_version\":%u,\"driver_version\":%u",p.vendorID,p.deviceID,p.apiVersion,p.driverVersion);
|
||||
printf(",\"independent_blend\":%u,\"draw_storage\":%u,\"storage_read_without_format\":%u,\"storage_write_without_format\":%u,\"gather_extended\":%u",f.independentBlend,f.fragmentStoresAndAtomics,f.shaderStorageImageReadWithoutFormat,f.shaderStorageImageWriteWithoutFormat,f.shaderImageGatherExtended);
|
||||
printf(",\"memory_types\":[");
|
||||
for(uint32_t j=0;j<m.memoryTypeCount;j++){if(j)putchar(',');printf("{\"flags\":%u,\"heap\":%u}",m.memoryTypes[j].propertyFlags,m.memoryTypes[j].heapIndex);}printf("]");
|
||||
uint32_t ne=0;rc=vkEnumerateDeviceExtensionProperties(devices[i],NULL,&ne,NULL);if(rc!=VK_SUCCESS)return 1;
|
||||
VkExtensionProperties *e=calloc(ne?ne:1,sizeof *e);if(!e)return 1;
|
||||
rc=vkEnumerateDeviceExtensionProperties(devices[i],NULL,&ne,e);if(rc!=VK_SUCCESS){free(e);return 1;}
|
||||
printf(",\"extensions\":[");for(uint32_t j=0;j<ne;j++){if(j)putchar(',');json_string(e[j].extensionName);}printf("]");free(e);
|
||||
const VkFormat formats[]={VK_FORMAT_R8G8B8A8_UNORM,VK_FORMAT_R16G16B16A16_SFLOAT,VK_FORMAT_D16_UNORM,VK_FORMAT_D24_UNORM_S8_UINT,VK_FORMAT_D32_SFLOAT,VK_FORMAT_D32_SFLOAT_S8_UINT};
|
||||
printf(",\"formats\":[");
|
||||
for(unsigned j=0;j<sizeof formats/sizeof *formats;j++){VkFormatProperties fp;vkGetPhysicalDeviceFormatProperties(devices[i],formats[j],&fp);if(j)putchar(',');printf("{\"format\":%u,\"optimal_features\":%u}",formats[j],fp.optimalTilingFeatures);}printf("]}");
|
||||
}
|
||||
printf("]}\n");free(devices);vkDestroyInstance(instance,NULL);return 0;
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/* Host regression: compare production barriers with an independent per-level
|
||||
* oracle. A barrier whose oldLayout is stale fails before the oracle updates. */
|
||||
#include "../../gfx/vulkan/nvn_vk_mip_layout.h"
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
typedef struct {
|
||||
VkImageLayout actual[64], next;
|
||||
unsigned base, count, barriers;
|
||||
} Oracle;
|
||||
static void barrier(void *ctx,VkImageLayout old,VkImageLayout next,unsigned base,unsigned count) {
|
||||
Oracle *o=ctx;
|
||||
assert(count && base>=o->base && base+count<=o->base+o->count && next==o->next);
|
||||
for(unsigned i=base;i<base+count;i++) {
|
||||
assert(o->actual[i]==old && old!=next);
|
||||
o->actual[i]=next;
|
||||
}
|
||||
o->barriers++;
|
||||
}
|
||||
static void transition(NvnVkMipLayouts *s,Oracle *o,unsigned total,unsigned base,unsigned count,VkImageLayout next) {
|
||||
VkImageLayout expected[64];memcpy(expected,o->actual,sizeof expected);
|
||||
for(unsigned i=base;i<base+count;i++)expected[i]=next;
|
||||
o->base=base;o->count=count;o->next=next;
|
||||
assert(nvn_vk_mip_transition(s,total,base,count,next,barrier,o));
|
||||
assert(!memcmp(expected,o->actual,sizeof expected));
|
||||
for(unsigned i=0;i<total;i++)assert((s->mixed?s->levels[i]:s->uniform)==expected[i]);
|
||||
}
|
||||
static unsigned rng=0x91738940;
|
||||
static unsigned random_u32(void) { rng^=rng<<13;rng^=rng>>17;rng^=rng<<5;return rng; }
|
||||
int main(void) {
|
||||
unsigned mask=0;
|
||||
assert(nvn_vk_mip_mask(16,0,16,&mask)&&mask==65535);
|
||||
assert(nvn_vk_mip_mask(16,15,1,&mask)&&mask==32768);
|
||||
assert(!nvn_vk_mip_mask(17,0,1,&mask));
|
||||
assert(!nvn_vk_mip_mask(16,16,1,&mask));
|
||||
assert(!nvn_vk_mip_mask(16,1,~0u,&mask));
|
||||
assert(!nvn_vk_mip_mask(0,0,0,&mask));
|
||||
const VkImageLayout layouts[]={VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,VK_IMAGE_LAYOUT_GENERAL};
|
||||
unsigned runs=0,emitted=0;
|
||||
for(unsigned total=1;total<=16;total++) {
|
||||
NvnVkMipLayouts s={0};Oracle o={0};
|
||||
transition(&s,&o,total,0,total,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
|
||||
if(total>1) {
|
||||
transition(&s,&o,total,0,1,VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
|
||||
transition(&s,&o,total,1,1,VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
|
||||
assert(s.mixed);
|
||||
}
|
||||
transition(&s,&o,total,0,total,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
|
||||
assert(!s.mixed);
|
||||
unsigned before=o.barriers;
|
||||
transition(&s,&o,total,0,total,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
|
||||
assert(o.barriers==before);
|
||||
for(unsigned i=0;i<20000;i++) {
|
||||
unsigned base=random_u32()%total,count=1+random_u32()%(total-base);
|
||||
transition(&s,&o,total,base,count,layouts[random_u32()%5]);runs++;
|
||||
}
|
||||
NvnVkMipLayouts saved=s;
|
||||
before=o.barriers;
|
||||
assert(!nvn_vk_mip_transition(&s,total,total,1,VK_IMAGE_LAYOUT_GENERAL,barrier,&o));
|
||||
assert(!nvn_vk_mip_transition(&s,total,0,~0u,VK_IMAGE_LAYOUT_GENERAL,barrier,&o));
|
||||
assert(!nvn_vk_mip_transition(&s,total,0,0,VK_IMAGE_LAYOUT_GENERAL,barrier,&o));
|
||||
assert(!memcmp(&saved,&s,sizeof s)&&o.barriers==before);
|
||||
emitted+=o.barriers;
|
||||
}
|
||||
NvnVkMipLayouts large={0};Oracle o={0};
|
||||
transition(&large,&o,32,0,32,VK_IMAGE_LAYOUT_GENERAL);
|
||||
assert(!nvn_vk_mip_transition(&large,32,0,1,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,barrier,&o));
|
||||
transition(&large,&o,32,0,32,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
|
||||
printf("VK_MIP_LAYOUT_PASS random_transitions=%u barriers=%u invalid_ranges large_image_fallback\n",runs,emitted);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
/* Runs real Vulkan buffer/fence regressions on an Android device. The include
|
||||
* exposes the backend's private cache/batch state without a production API. */
|
||||
#include "../../gfx/vulkan/nvn_vk.c"
|
||||
#include <assert.h>
|
||||
|
||||
static void wait_current(void) { uint64_t ticket=mtl_sub_commit();assert(mtl_wait(ticket,UINT64_MAX)); }
|
||||
static void mip_policy_checks(void) {
|
||||
int feedback=G.feedback_layout;G.feedback_layout=0;
|
||||
int subresources=G.subresources;G.subresources=1;
|
||||
VTexture t={.serial=9001,.format=VK_FORMAT_R8G8B8A8_UNORM};
|
||||
t.source.serial=t.serial;t.source.d.target=NVN_TEXTURE_TARGET_2D;t.source.d.levels=4;t.source.L.layers=1;
|
||||
G.state.rt.n=1;G.state.rt.color[0]=&t.source;G.state.rt.has_cview[0]=1;
|
||||
G.state.rt.cview[0]=(view_t){.set_levels=1,.base_level=1,.nlevels=1};
|
||||
TSlot *slots=G.tslot;size_t capacity=G.texture_slots;int pool_n=G.texture_pool_n;
|
||||
G.tslot=calloc(2,sizeof *G.tslot);assert(G.tslot);G.texture_slots=2;G.texture_pool_n=2;
|
||||
G.tslot[1]=(TSlot){.live=1,.texture=t.source,.has_view=1,.view={.set_levels=1,.base_level=0,.nlevels=1}};
|
||||
VShader vs={0},ps={0};vs.h.nb=ps.h.nb=1;ps.h.stage=1;vs.b[0].kind=ps.b[0].kind=4;
|
||||
G.state.tex[0][0]=G.state.tex[1][0]=1;G.nimage_uses=0;
|
||||
collect_image_uses(&vs);assert(disjoint_mip_sampling(&t));
|
||||
/* Another stage's overlapping view must disable the optimization for both. */
|
||||
G.tslot[1].view.base_level=1;collect_image_uses(&ps);assert(!disjoint_mip_sampling(&t));
|
||||
G.nimage_uses=0;G.tslot[1].view.base_level=0;collect_image_uses(&vs);
|
||||
G.image_uses[0].roles|=2;assert(!disjoint_mip_sampling(&t));G.image_uses[0].roles=1;
|
||||
G.image_uses[0].roles|=4;assert(!disjoint_mip_sampling(&t));G.image_uses[0].roles=1;
|
||||
G.feedback_layout=1;assert(!disjoint_mip_sampling(&t));G.feedback_layout=0;
|
||||
G.tslot[1].has_view=0;G.nimage_uses=0;collect_image_uses(&vs);assert(!disjoint_mip_sampling(&t));
|
||||
G.tslot[1].has_view=1;G.nimage_uses=0;collect_image_uses(&vs);assert(disjoint_mip_sampling(&t));
|
||||
G.state.rt.n=2;G.state.rt.color[1]=&t.source;G.state.rt.has_cview[1]=0;assert(!disjoint_mip_sampling(&t));G.state.rt.n=1;
|
||||
t.source.L.layers=2;assert(!disjoint_mip_sampling(&t));t.source.L.layers=1;
|
||||
G.subresources=0;assert(!disjoint_mip_sampling(&t));G.subresources=subresources;
|
||||
free(G.tslot);G.tslot=slots;G.texture_slots=capacity;G.texture_pool_n=pool_n;
|
||||
memset(&G.state.rt,0,sizeof G.state.rt);G.state.tex[0][0]=G.state.tex[1][0]=0;G.nimage_uses=0;G.feedback_layout=feedback;
|
||||
}
|
||||
/* Real GPU readback verifies both mips survive split layouts and a later
|
||||
* whole-image copy transition; this fixture needs no game/shader assets. */
|
||||
static void mip_gpu_checks(void) {
|
||||
mip_policy_checks();
|
||||
VTexture t={.serial=9002,.format=VK_FORMAT_R8G8B8A8_UNORM,.width=8,.height=8,.depth=1};
|
||||
t.source.d.levels=4;t.source.L.layers=1;
|
||||
VkImageCreateInfo ci={.sType=VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,.imageType=VK_IMAGE_TYPE_2D,.format=t.format,
|
||||
.extent={8,8,1},.mipLevels=4,.arrayLayers=1,.samples=VK_SAMPLE_COUNT_1_BIT,.tiling=VK_IMAGE_TILING_OPTIMAL,
|
||||
.usage=VK_IMAGE_USAGE_TRANSFER_SRC_BIT|VK_IMAGE_USAGE_TRANSFER_DST_BIT|VK_IMAGE_USAGE_SAMPLED_BIT|VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT};
|
||||
CHECK(vkCreateImage(G.device,&ci,NULL,&t.image));VkMemoryRequirements req;vkGetImageMemoryRequirements(G.device,t.image,&req);
|
||||
VkMemoryAllocateInfo ai={.sType=VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,.allocationSize=req.size,.memoryTypeIndex=memory_type(req.memoryTypeBits,VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)};
|
||||
CHECK(vkAllocateMemory(G.device,&ai,NULL,&t.memory));CHECK(vkBindImageMemory(G.device,t.image,t.memory,0));
|
||||
VBuffer readback=buffer_make(320,VK_BUFFER_USAGE_TRANSFER_DST_BIT);
|
||||
mtl_sub_begin();texture_transition(&t,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
|
||||
for(unsigned i=0;i<4;i++) {
|
||||
VkClearColorValue value={.float32={i==0?1:0,i==1?1:0,0,1}};
|
||||
VkImageSubresourceRange range={VK_IMAGE_ASPECT_COLOR_BIT,i,1,0,1};
|
||||
vkCmdClearColorImage(G.batch->command,t.image,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,&value,1,&range);
|
||||
}
|
||||
texture_transition_levels(&t,0,1,VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
|
||||
texture_transition_levels(&t,1,1,VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);assert(t.layouts.mixed);
|
||||
texture_transition_levels(&t,0,1,VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
|
||||
texture_transition_levels(&t,1,1,VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
|
||||
texture_transition(&t,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);assert(!t.layouts.mixed);
|
||||
for(unsigned i=0;i<2;i++) {
|
||||
VkBufferImageCopy copy={.bufferOffset=i?256:0,.imageSubresource={VK_IMAGE_ASPECT_COLOR_BIT,i,0,1},.imageExtent={8>>i,8>>i,1}};
|
||||
vkCmdCopyImageToBuffer(G.batch->command,t.image,t.layouts.uniform,readback.b,1,©);
|
||||
}
|
||||
wait_current();
|
||||
for(unsigned i=0;i<80;i++){const uint8_t *p=readback.map+4*i;assert(p[0]==(i<64?255:0)&&p[1]==(i<64?0:255)&&p[2]==0&&p[3]==255);}
|
||||
buffer_free(&readback);vkDestroyImage(G.device,t.image,NULL);vkFreeMemory(G.device,t.memory,NULL);
|
||||
fprintf(stderr,"VK_MIP_GPU_PASS disjoint_views cross_stage_overlap storage_fallback split_layouts preserved_pixels\n");
|
||||
}
|
||||
static void copy_input(uint32_t *guest,VBuffer *readback) {
|
||||
uint64_t offset=0;VPool *input=input_read((uint64_t)(uintptr_t)guest,16,&offset);
|
||||
all_barrier();VkBufferCopy copy={offset,0,16};vkCmdCopyBuffer(G.batch->command,input->v.b,readback->b,1,©);
|
||||
}
|
||||
/* Zero-copy pools (host import or mremap of Vulkan memory): GPU reads the guest bytes
|
||||
* current at execution and writes land in guest memory without writeback. */
|
||||
static int direct_main(void) {
|
||||
mtl_init();
|
||||
if(!G.host_import && !G.get_memory_fd && !G.get_ahb_properties){fprintf(stderr,"VK_PERF_TEST_SKIP direct: no zero-copy path\n");return 0;}
|
||||
uint32_t *guest=aligned_alloc(4096,4096);assert(guest);memset(guest,0,4096);mtl_pool_add(guest,4096);
|
||||
uint64_t offset=0;VPool *pool=pool_find((uint64_t)(uintptr_t)guest,16,&offset);assert(pool && pool->direct && offset==0);
|
||||
VBuffer first=buffer_make(16,VK_BUFFER_USAGE_TRANSFER_DST_BIT);
|
||||
for(unsigned i=0;i<4;i++)guest[i]=i+10;
|
||||
mtl_sub_begin();copy_input(guest,&first);wait_current();
|
||||
for(unsigned i=0;i<4;i++)assert(((uint32_t *)first.map)[i]==i+10);
|
||||
uint32_t update[4]={31,32,33,34};
|
||||
mtl_sub_begin();all_barrier();vkCmdUpdateBuffer(G.batch->command,pool->v.b,offset,16,update);mark_write((uint64_t)(uintptr_t)guest,16);
|
||||
assert(!G.batch->nwrites);wait_current();assert(!memcmp(guest,update,16));
|
||||
/* Identical driver tables reuse one slot within a batch; changes get a new one. */
|
||||
uint8_t table[TABLE_BYTES]={0};mtl_sub_begin();
|
||||
VkDescriptorBufferInfo t0=table_bind(0,0,table),t1=table_bind(0,0,table);table[0x168]=7;VkDescriptorBufferInfo t2=table_bind(0,0,table);
|
||||
assert(t0.buffer==t1.buffer && t0.offset==t1.offset && t2.offset!=t0.offset && t2.range==65536);wait_current();
|
||||
/* Coherence over a cached mapping: lines the CPU holds must observe GPU
|
||||
* fills, and CPU stores must reach a GPU copy without explicit flushes. */
|
||||
size_t big=8<<20;uint32_t *wide=aligned_alloc(4096,big);assert(wide);
|
||||
for(size_t i=0;i<big/4;i++)wide[i]=(uint32_t)i;mtl_pool_add(wide,big);
|
||||
VPool *wp=pool_find((uint64_t)(uintptr_t)wide,big,&offset);assert(wp && wp->direct);
|
||||
uint64_t sum=0;for(size_t i=0;i<big/4;i++)sum+=wide[i];assert(sum==(uint64_t)(big/4)*(big/4-1)/2);
|
||||
static uint32_t fill[16384];for(size_t i=0;i<16384;i++)fill[i]=0x5a5a5a5au;
|
||||
mtl_sub_begin();all_barrier();for(size_t at=0;at<big;at+=sizeof(fill))vkCmdUpdateBuffer(G.batch->command,wp->v.b,at,sizeof(fill),fill);wait_current();
|
||||
for(size_t i=0;i<big/4;i++)assert(wide[i]==0x5a5a5a5au);
|
||||
for(size_t i=0;i<big/4;i++)wide[i]=(uint32_t)i*3;
|
||||
VBuffer check=buffer_make(big,VK_BUFFER_USAGE_TRANSFER_DST_BIT);
|
||||
mtl_sub_begin();all_barrier();VkBufferCopy whole={0,0,big};vkCmdCopyBuffer(G.batch->command,wp->v.b,check.b,1,&whole);wait_current();
|
||||
for(size_t i=0;i<big/4;i++)assert(((uint32_t *)check.map)[i]==(uint32_t)i*3);
|
||||
mtl_pool_del(wide);buffer_free(&check);free(wide);
|
||||
volatile uint32_t event=0;mtl_sub_begin();mtl_sub_event(&event,0,73);mtl_sub_commit();
|
||||
uint64_t deadline=dm_android_nvn_clock_ns()+1000000000;
|
||||
while(!atomic_load((_Atomic uint32_t *)&event) && dm_android_nvn_clock_ns()<deadline){struct timespec pause={0,1000000};nanosleep(&pause,NULL);}
|
||||
assert(event==73);
|
||||
guest[5]=99;mtl_pool_del(guest);assert(guest[0]==31 && guest[5]==99);guest[6]=1; /* bytes survive unremap, pages stay writable */
|
||||
mtl_finish();buffer_free(&first);free(guest);
|
||||
fprintf(stderr,"VK_PERF_TEST_PASS direct_pool gpu_write_in_place cached_coherence driver_table_reuse events\n");return 0;
|
||||
}
|
||||
/* Memory-type microbenchmark for upload arenas: CPU write, CPU read-back
|
||||
* (snapshot dedupe memcmp) and GPU copy throughput per host-visible type. */
|
||||
static double ms_since(uint64_t t){return (dm_android_nvn_clock_ns()-t)/1e6;}
|
||||
static int bench_main(void) {
|
||||
mtl_init();size_t n=16<<20;uint8_t *src=malloc(n);assert(src);for(size_t i=0;i<n;i++)src[i]=(uint8_t)(i*7);
|
||||
VBuffer dst=buffer_make(n,VK_BUFFER_USAGE_TRANSFER_DST_BIT);
|
||||
for(uint32_t type=0;type<G.memory.memoryTypeCount;type++){VkMemoryPropertyFlags f=G.memory.memoryTypes[type].propertyFlags;
|
||||
|
||||
if(!(f&VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)&&type)continue;VBuffer b={.size=n};VkBufferCreateInfo info={.sType=VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,.size=n,.usage=VK_BUFFER_USAGE_TRANSFER_SRC_BIT|VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT|VK_BUFFER_USAGE_STORAGE_BUFFER_BIT|VK_BUFFER_USAGE_VERTEX_BUFFER_BIT|VK_BUFFER_USAGE_INDEX_BUFFER_BIT|VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT|VK_BUFFER_USAGE_TRANSFER_DST_BIT};
|
||||
CHECK(vkCreateBuffer(G.device,&info,NULL,&b.b));VkMemoryRequirements r;vkGetBufferMemoryRequirements(G.device,b.b,&r);
|
||||
if(type==0)fprintf(stderr,"VK_BENCH memoryTypeBits=%#x\n",r.memoryTypeBits);
|
||||
if(!(r.memoryTypeBits&(1u<<type))){vkDestroyBuffer(G.device,b.b,NULL);continue;}
|
||||
if(!(f&VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)){vkDestroyBuffer(G.device,b.b,NULL);continue;}
|
||||
VkMemoryAllocateInfo a={.sType=VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,.allocationSize=r.size,.memoryTypeIndex=type};
|
||||
uint64_t t=dm_android_nvn_clock_ns();CHECK(vkAllocateMemory(G.device,&a,NULL,&b.m));CHECK(vkBindBufferMemory(G.device,b.b,b.m,0));
|
||||
void *m;CHECK(vkMapMemory(G.device,b.m,0,n,0,&m));b.map=m;double alloc=ms_since(t);
|
||||
t=dm_android_nvn_clock_ns();memset(b.map,0,n);double zero=ms_since(t);
|
||||
t=dm_android_nvn_clock_ns();for(int k=0;k<4;k++)memcpy(b.map,src,n);double write=ms_since(t)/4;
|
||||
t=dm_android_nvn_clock_ns();int diff=0;for(int k=0;k<4;k++)diff|=memcmp(b.map,src,n);double read=ms_since(t)/4;assert(!diff);
|
||||
double gpu=0;for(int k=0;k<4;k++){mtl_sub_begin();VkBufferCopy c={0,0,n};vkCmdCopyBuffer(G.batch->command,b.b,dst.b,1,&c);
|
||||
t=dm_android_nvn_clock_ns();wait_current();gpu+=ms_since(t);}gpu/=4;assert(!memcmp(dst.map,src,n));
|
||||
fprintf(stderr,"VK_BENCH type=%u flags=%#x MiB=16 alloc_map_ms=%.3f memset_ms=%.3f write_ms=%.3f read_cmp_ms=%.3f gpu_copy_ms=%.3f\n",type,f,alloc,zero,write,read,gpu);
|
||||
buffer_free(&b);}
|
||||
mtl_finish();buffer_free(&dst);free(src);return 0;
|
||||
}
|
||||
/* Game-shaped input load: ~11k distinct ~3 KiB snapshots over 4 batches per frame. */
|
||||
static double input_frames(int frames) {
|
||||
size_t n=64<<20;uint8_t *guest=aligned_alloc(4096,n);assert(guest);memset(guest,1,n);mtl_pool_add(guest,n);
|
||||
uint64_t t=dm_android_nvn_clock_ns();
|
||||
for(int f=0;f<frames;f++)for(int b=0;b<4;b++){mtl_sub_begin();
|
||||
for(int i=0;i<2750;i++){uint64_t at=((uint64_t)(f*11000+b*2750+i)*3072)%(n-4096),off;input_read((uint64_t)(uintptr_t)guest+at,3072,&off);}
|
||||
mtl_sub_commit();pthread_mutex_lock(&G.lock);flush_locked();pthread_mutex_unlock(&G.lock);}
|
||||
mtl_finish();double ms=ms_since(t);mtl_pool_del(guest);free(guest);return ms;
|
||||
}
|
||||
int main(int argc,char **argv) {
|
||||
if(argc>1 && !strcmp(argv[1],"mips")){mtl_init();mip_gpu_checks();return 0;}
|
||||
if(argc>1 && !strcmp(argv[1],"bench"))return bench_main();
|
||||
if(argc>1 && !strcmp(argv[1],"input")){setenv("DM_VK_POOL_COPY","1",1);mtl_init();
|
||||
double recycled=input_frames(60);temporary_keep_bytes=0;double fresh=input_frames(60);
|
||||
fprintf(stderr,"VK_BENCH input 60 frames recycled_ms=%.1f fresh_ms=%.1f\n",recycled,fresh);return 0;}
|
||||
if(argc>1 && !strcmp(argv[1],"direct"))return direct_main();
|
||||
setenv("DM_VK_POOL_COPY","1",1); /* staged copy path: snapshot semantics */
|
||||
mtl_init();
|
||||
/* Deliberate hash collision must never conflate distinct effective states. */
|
||||
PipelineKey a={0},b={0};key_word(&a,71);key_word(&b,72);
|
||||
Pso *pa=pso_insert(&a,12345),*pb=pso_insert(&b,12345);
|
||||
assert(pso_find(&a,12345)==pa && pso_find(&b,12345)==pb);
|
||||
uint32_t *guest=aligned_alloc(4096,4096);assert(guest);memset(guest,0,4096);mtl_pool_add(guest,4096);
|
||||
VBuffer first=buffer_make(16,VK_BUFFER_USAGE_TRANSFER_DST_BIT),second=buffer_make(16,VK_BUFFER_USAGE_TRANSFER_DST_BIT);
|
||||
for(unsigned i=0;i<4;i++)guest[i]=i+10;
|
||||
mtl_sub_begin();copy_input(guest,&first);uint64_t ticket=mtl_sub_commit();
|
||||
assert(G.batch->recording && !G.batch->pending); /* Logical commit stays batched. */
|
||||
for(unsigned i=0;i<4;i++)guest[i]=i+20;
|
||||
mtl_sub_begin();copy_input(guest,&second);wait_current();
|
||||
assert(mtl_wait(ticket,0));
|
||||
for(unsigned i=0;i<4;i++)assert(((uint32_t *)first.map)[i]==i+10 && ((uint32_t *)second.map)[i]==i+20);
|
||||
/* GPU updates override stale guest bytes in a subsequent input snapshot. */
|
||||
mtl_sub_begin();uint64_t offset=0;VPool *pool=pool_find((uint64_t)(uintptr_t)guest,16,&offset);pool_materialize(pool);
|
||||
uint32_t update[4]={31,32,33,34};all_barrier();vkCmdUpdateBuffer(G.batch->command,pool->v.b,offset,16,update);mark_write((uint64_t)(uintptr_t)guest,16);
|
||||
copy_input(guest,&first);wait_current();assert(!memcmp(first.map,update,16));assert(!memcmp(guest,update,16));
|
||||
/* Across separately submitted batches the newer write must not contaminate
|
||||
* the older batch's CPU-visible writeback snapshot. */
|
||||
mtl_sub_begin();all_barrier();update[0]=41;vkCmdUpdateBuffer(G.batch->command,pool->v.b,offset,16,update);mark_write((uint64_t)(uintptr_t)guest,16);
|
||||
ticket=mtl_sub_commit();pthread_mutex_lock(&G.lock);flush_locked();Batch *old=G.batch;pthread_mutex_unlock(&G.lock);
|
||||
mtl_sub_begin();copy_input(guest,&second);all_barrier();update[0]=51;vkCmdUpdateBuffer(G.batch->command,pool->v.b,offset,16,update);mark_write((uint64_t)(uintptr_t)guest,16);
|
||||
uint64_t newer=mtl_sub_commit();pthread_mutex_lock(&G.lock);flush_locked();
|
||||
if(old->pending){assert(retire_locked(old,UINT64_MAX));assert(guest[0]==41);}
|
||||
pthread_mutex_unlock(&G.lock);assert(mtl_wait(newer,UINT64_MAX));assert(guest[0]==51 && ((uint32_t *)second.map)[0]==41);
|
||||
assert(!mtl_wait(newer+100,0));
|
||||
/* An event must reach a guest that polls memory without another API call. */
|
||||
volatile uint32_t event=0;mtl_sub_begin();mtl_sub_event(&event,0,73);mtl_sub_commit();
|
||||
uint64_t deadline=dm_android_nvn_clock_ns()+1000000000;
|
||||
while(!atomic_load((_Atomic uint32_t *)&event) && dm_android_nvn_clock_ns()<deadline){struct timespec pause={0,1000000};nanosleep(&pause,NULL);}
|
||||
assert(event==73);
|
||||
/* Descriptor chunks grow within a batch without invalidating old sets. */
|
||||
VkDescriptorSetLayoutBinding binding={.binding=0,.descriptorType=VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,.descriptorCount=1,.stageFlags=VK_SHADER_STAGE_VERTEX_BIT};
|
||||
VkDescriptorSetLayoutCreateInfo layout_info={.sType=VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,.bindingCount=1,.pBindings=&binding};
|
||||
VShader shader={0};shader.h.nb=1;shader.b[0].type=VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
|
||||
CHECK(vkCreateDescriptorSetLayout(G.device,&layout_info,NULL,&shader.layout));
|
||||
mtl_sub_begin();for(unsigned i=0;i<8200;i++)assert(shader_set_allocate(&shader,0));assert(G.batch->nextra_descriptors==1);
|
||||
/* Capacity splits keep the logical fence reserved for the final piece. */
|
||||
uint64_t before=G.fence;G.batch->ncounter=3000;
|
||||
for(int i=0;i<3000;i++)G.batch->counter_ops[i]=(CounterOp){0,0,0};
|
||||
batch_checkpoint();assert(G.fence==before && G.batch->recording);wait_current();
|
||||
PFN_vkDestroyDescriptorSetLayout destroy_layout=(PFN_vkDestroyDescriptorSetLayout)dm_vk_get(G.instance,"vkDestroyDescriptorSetLayout");assert(destroy_layout);destroy_layout(G.device,shader.layout,NULL);
|
||||
/* Slot rotation and destruction drain work before recycling resources. */
|
||||
G.profile_gpu_ns=0;unsigned pending_max=0;
|
||||
for(unsigned i=0;i<2*BATCH_SLOTS+4;i++){mtl_sub_begin();copy_input(guest,&first);mtl_sub_commit();pthread_mutex_lock(&G.lock);flush_locked();
|
||||
unsigned pending=0;for(unsigned j=0;j<BATCH_SLOTS;j++)pending+=G.batches[j].pending;if(pending>pending_max)pending_max=pending;pthread_mutex_unlock(&G.lock);}
|
||||
/* Every retired batch contributes its begin/end GPU span. */
|
||||
mtl_finish();assert(!G.timestamp_bits || G.profile_gpu_ns>0);
|
||||
fprintf(stderr,"ring slots=%u pending_max=%u gpu_ms=%.3f\n",BATCH_SLOTS,pending_max,G.profile_gpu_ns/1e6);
|
||||
/* Retired transient buffers are recycled by size class, not reallocated. */
|
||||
mtl_finish();mtl_sub_begin();VBuffer *recycled=temporary(5000,VK_BUFFER_USAGE_TRANSFER_SRC_BIT);VkBuffer handle=recycled->b;assert(recycled->size==8192);wait_current();
|
||||
mtl_finish();mtl_sub_begin();assert(temporary(8192,VK_BUFFER_USAGE_TRANSFER_DST_BIT)->b==handle);wait_current();mtl_finish();
|
||||
mtl_pool_del(guest);mtl_finish();buffer_free(&first);buffer_free(&second);free(guest);
|
||||
mip_gpu_checks();
|
||||
fprintf(stderr,"VK_PERF_TEST_PASS snapshots collisions GPU_writebacks fences ring_rotation gpu_timestamps events descriptor_chunks capacity_split temporary_recycle mip_layouts\n");return 0;
|
||||
}
|
||||
@@ -1,3 +1,3 @@
|
||||
// 生成文件(dm/gfx/tools/dmsh_chain.py --header):本源码树期望的 B 着色器库翻译链版本(缺省选项);宿主只加载 <库目录>/b-<V>/
|
||||
// Generated file (dm/gfx/tools/dmsh_chain.py --header): the translation chain version of the B shader library expected by this source tree (default options); the host only loads <library dir>/b-<V>/
|
||||
#define DMSH_CHAIN "15cf7ca29eaf"
|
||||
#define DMSH_CHAIN "f0d74f7f12a9"
|
||||
|
||||
+270
-48
@@ -66,13 +66,13 @@ typedef struct { const char *name; void *fn; } nvn_impl;
|
||||
#define NVN(name, ret, ...) \
|
||||
static ret h_##name(__VA_ARGS__); \
|
||||
static const NVNT_##name chk_##name __attribute__((unused)) = h_##name; \
|
||||
__attribute__((used, section("__DATA,swnvn"))) static const nvn_impl e_##name = {#name, (void *)h_##name}; \
|
||||
__attribute__((used, DM_SECT("swnvn"))) static const nvn_impl e_##name = {#name, (void *)h_##name}; \
|
||||
static ret h_##name(__VA_ARGS__)
|
||||
// 无原型的新版接口:不做签名检查
|
||||
// Newer interfaces without prototypes: no signature check
|
||||
#define NVN_NOPROTO(name, ret, ...) \
|
||||
static ret h_##name(__VA_ARGS__); \
|
||||
__attribute__((used, section("__DATA,swnvn"))) static const nvn_impl e_##name = {#name, (void *)h_##name}; \
|
||||
__attribute__((used, DM_SECT("swnvn"))) static const nvn_impl e_##name = {#name, (void *)h_##name}; \
|
||||
static ret h_##name(__VA_ARGS__)
|
||||
|
||||
static int g_log;
|
||||
@@ -164,7 +164,12 @@ NVN(nvnDeviceGetSeparateSamplerHandle, NVNseparateSamplerHandle, const NVNdevice
|
||||
NVN(nvnDeviceInstallDebugCallback, void, NVNdevice *d, const PFNNVNDEBUGCALLBACKPROC cb, void *data, uint32_t enable) {
|
||||
dev_t_ *o = (dev_t_ *)d; o->dbg_cb = B(enable) ? (void *)cb : NULL; o->dbg_data = data;
|
||||
}
|
||||
NVN(nvnDeviceSetWindowOriginMode, void, NVNdevice *d, NVNwindowOriginMode m) { ((dev_t_ *)d)->origin = m; LOG("[nvn] 窗口原点 %s", m ? "左上(同 D3D / Metal)" : "左下(GL)"); }
|
||||
NVN(nvnDeviceSetWindowOriginMode, void, NVNdevice *d, NVNwindowOriginMode m) {
|
||||
((dev_t_ *)d)->origin = m;
|
||||
#ifdef __ANDROID__
|
||||
mtl_set_window_origin_mode(m); // Vulkan 后端按原点选负高视口 | the Vulkan backend picks a negative-height viewport by origin
|
||||
#endif
|
||||
LOG("[nvn] 窗口原点 %s", m ? "左上(同 D3D / Metal)" : "左下(GL)"); }
|
||||
NVN(nvnDeviceSetDepthMode, void, NVNdevice *d, NVNdepthMode m) { ((dev_t_ *)d)->depth_mode = m; LOG("[nvn] 深度模式 %s", m ? "近=0(同 D3D / Metal)" : "近=-w(GL)"); }
|
||||
NVN(nvnDeviceFinalizeCommandHandle, void, NVNdevice *d, NVNcommandHandle h) { (void)d; (void)h; }
|
||||
|
||||
@@ -241,6 +246,76 @@ NVN(nvnTextureBuilderGetStorageAlignment, size_t, const NVNtextureBuilder *b) {
|
||||
}
|
||||
#define TX(t) ((tex_t *)(t))
|
||||
#define CTX(t) ((const tex_t *)(t))
|
||||
// ---------- 对象副本:录制时按序号留一份贴图 / 程序对象,命令载荷存副本地址 ----------
|
||||
// 同一序号的对象内容不变(Initialize / SetShaders 才换序号),游戏提交后可以改写或重建自己的对象(真机上 GPU 只看录进命令内存的值),
|
||||
// 回放层读副本就不受影响。游戏对象里记着副本地址,按值拷来的对象序号相同、直接共用。副本在对象 Finalize / 换序号后再过 SNAP_KEEP 次提交才回收;
|
||||
// 槽位内存只增不还给系统,回收时清零(序号 0 不与任何有效序号相等),过期的副本地址只会读到不相等的序号、重新取副本。
|
||||
// ---------- Object snapshots: when recording, keep one copy of each texture / program object per serial; command payloads store the snapshot address ----------
|
||||
// An object with the same serial has the same content (only Initialize / SetShaders change the serial); after submitting, the game may rewrite or rebuild its own objects (on the real device the GPU only sees the values recorded into command memory),
|
||||
// and the replay layer reading snapshots is unaffected. The game object records the snapshot address, and objects copied by value have the same serial and share it directly. A snapshot is reclaimed only SNAP_KEEP submits after the object is Finalized / changes serial;
|
||||
// slot memory only grows and is never returned to the system; reclaimed slots are zeroed (serial 0 never equals a valid serial), so a stale snapshot address only reads a non-matching serial and takes a new snapshot.
|
||||
typedef union snap_slot { tex_t t; prog_t p; union snap_slot *next; } snap_slot;
|
||||
#define SNAP_KEEP 8
|
||||
static pthread_mutex_t g_snap_mu = PTHREAD_MUTEX_INITIALIZER;
|
||||
static snap_slot *g_snap_free;
|
||||
static struct { snap_slot *s; uint64_t at; } *g_snap_ret; static size_t g_snap_nret, g_snap_capret, g_snap_live, g_snap_slots;
|
||||
static uint64_t g_snap_sub; // 已执行(翻译完)的提交数:回收时刻 | Number of submits executed (translated): the reclaim clock
|
||||
static _Atomic uint64_t g_x_subs; // 已入队的提交数(翻译队列,见 nvnQueueSubmitCommands 前):退役盖戳用它,回收按已执行数,翻译线程落后时副本不会提前回收 | Number of submits enqueued (translation queue, see before nvnQueueSubmitCommands): used for the retire stamp, while reclaim goes by the number executed, so snapshots are not reclaimed early when the translation thread falls behind
|
||||
static snap_slot *snap_alloc(void) { // 持 g_snap_mu | Holds g_snap_mu
|
||||
if (!g_snap_free) {
|
||||
snap_slot *c = calloc(256, sizeof *c); if (!c) { LOG("【红】对象副本分配失败"); abort(); }
|
||||
for (int i = 255; i >= 0; i--) { c[i].next = g_snap_free; g_snap_free = &c[i]; }
|
||||
g_snap_slots += 256; // 读数:槽位只在在用 + 待回收占满时才扩,扩槽停住即有上界 | Reading: slots grow only when in-use + pending-reclaim fill them all; slot growth stops, so there is an upper bound
|
||||
LOG("[nvn] 对象副本槽位扩到 %zu 个(%zu KB):在用 %zu,其中待回收 %zu,第 %llu 次提交", g_snap_slots, g_snap_slots * sizeof *c >> 10, g_snap_live, g_snap_nret, (unsigned long long)g_snap_sub);
|
||||
}
|
||||
snap_slot *n = g_snap_free; g_snap_free = n->next; memset(n, 0, sizeof *n); g_snap_live++;
|
||||
return n;
|
||||
}
|
||||
static void snap_retire(const void *s) { // 持 g_snap_mu | Holds g_snap_mu
|
||||
if (g_snap_nret == g_snap_capret) { g_snap_capret = g_snap_capret ? g_snap_capret * 2 : 256; g_snap_ret = realloc(g_snap_ret, g_snap_capret * sizeof *g_snap_ret); }
|
||||
g_snap_ret[g_snap_nret].s = (snap_slot *)s; g_snap_ret[g_snap_nret++].at = atomic_load(&g_x_subs);
|
||||
}
|
||||
static void snap_tick(uint64_t done) { // 翻译线程每执行完一次提交:回收退役时已入队的提交都执行完、且又过了 SNAP_KEEP 次提交的副本 | Each time the translation thread finishes a submit: reclaim snapshots whose submits enqueued at retirement have all executed and that have passed SNAP_KEEP more submits
|
||||
pthread_mutex_lock(&g_snap_mu);
|
||||
g_snap_sub = done; size_t k = 0;
|
||||
for (size_t i = 0; i < g_snap_nret; i++) {
|
||||
if (g_snap_ret[i].at + SNAP_KEEP <= g_snap_sub) { snap_slot *n = g_snap_ret[i].s; memset(n, 0, sizeof *n); n->next = g_snap_free; g_snap_free = n; g_snap_live--; }
|
||||
else g_snap_ret[k++] = g_snap_ret[i];
|
||||
}
|
||||
g_snap_nret = k;
|
||||
pthread_mutex_unlock(&g_snap_mu);
|
||||
}
|
||||
static const tex_t *snap_tex(const NVNtexture *t) {
|
||||
tex_t *o = TX(t); if (!o || !o->serial) return o; // 没初始化过的对象没有可留的内容,照旧存原址 | An object that was never initialized has no content to keep; store the original address as before
|
||||
const tex_t *s = __atomic_load_n((const tex_t **)&o->snap, __ATOMIC_ACQUIRE);
|
||||
if (s && s->serial == o->serial) return s;
|
||||
pthread_mutex_lock(&g_snap_mu);
|
||||
s = o->snap;
|
||||
if (!s || s->serial != o->serial) { snap_slot *n = snap_alloc(); n->t = *o; n->t.snap = NULL; s = &n->t; __atomic_store_n((const tex_t **)&o->snap, s, __ATOMIC_RELEASE); }
|
||||
pthread_mutex_unlock(&g_snap_mu);
|
||||
return s;
|
||||
}
|
||||
static const prog_t *snap_prog(const NVNprogram *p) {
|
||||
prog_t *o = (prog_t *)p; if (!o || !o->serial) return o;
|
||||
const prog_t *s = __atomic_load_n((const prog_t **)&o->snap, __ATOMIC_ACQUIRE);
|
||||
if (s && s->serial == o->serial) return s;
|
||||
pthread_mutex_lock(&g_snap_mu);
|
||||
s = o->snap;
|
||||
if (!s || s->serial != o->serial) { snap_slot *n = snap_alloc(); n->p = *o; n->p.snap = NULL; s = &n->p; __atomic_store_n((const prog_t **)&o->snap, s, __ATOMIC_RELEASE); }
|
||||
pthread_mutex_unlock(&g_snap_mu);
|
||||
return s;
|
||||
}
|
||||
static void x_drain(void);
|
||||
static uint64_t x_fence(void);
|
||||
// 对象 Finalize / 换序号前调:本序号的副本退役(按值拷来的同序号对象之后再录会重新取副本)
|
||||
// Called before an object is Finalized / changes serial: retire this serial's snapshot (an object with the same serial copied by value takes a new snapshot when recorded later)
|
||||
static void snap_drop(const void **pp, uint64_t ser, uint64_t snap_ser_off) {
|
||||
pthread_mutex_lock(&g_snap_mu);
|
||||
const uint8_t *s = *pp; uint64_t ss; if (s) memcpy(&ss, s + snap_ser_off, 8);
|
||||
if (s && ser && ss == ser) snap_retire(s);
|
||||
*pp = NULL;
|
||||
pthread_mutex_unlock(&g_snap_mu);
|
||||
}
|
||||
NVN(nvnTextureInitialize, NVNboolean, NVNtexture *t, const NVNtextureBuilder *b) {
|
||||
const tex_builder_t *s = (const tex_builder_t *)b; tex_t *o = TX(t);
|
||||
memset(o, 0, sizeof *o);
|
||||
@@ -253,7 +328,7 @@ NVN(nvnTextureInitialize, NVNboolean, NVNtexture *t, const NVNtextureBuilder *b)
|
||||
o->d.levels, o->d.format, o->d.target, o->d.flags, o->L.size);
|
||||
return 1;
|
||||
}
|
||||
NVN(nvnTextureFinalize, void, NVNtexture *t) { mtl_tex_release(TX(t)); TX(t)->magic = 0; }
|
||||
NVN(nvnTextureFinalize, void, NVNtexture *t) { snap_drop(&TX(t)->snap, TX(t)->serial, offsetof(tex_t, serial)); mtl_tex_release(TX(t)); TX(t)->magic = 0; }
|
||||
NVN(nvnTextureGetFlags, NVNtextureFlags, const NVNtexture *t) { return (NVNtextureFlags)CTX(t)->d.flags; }
|
||||
NVN(nvnTextureGetWidth, int, const NVNtexture *t) { return (int)CTX(t)->d.width; }
|
||||
NVN(nvnTextureGetHeight, int, const NVNtexture *t) { return (int)CTX(t)->d.height; }
|
||||
@@ -290,6 +365,7 @@ static void read_texels(const tex_t *o, const view_t *v, const NVNcopyRegion *r,
|
||||
if (!row) row = wb;
|
||||
if (!img) img = row * hb;
|
||||
unsigned level = v && v->set_levels ? (unsigned)v->base_level : 0, layer0 = v && v->set_layers ? (unsigned)v->min_layer : 0;
|
||||
x_drain(); // CPU 读贴图:已入队的提交先翻译完 | CPU texture read: submits already enqueued are translated first
|
||||
mtl_read_texels(o, level, layer0, r, dst, (size_t)row, (size_t)img);
|
||||
}
|
||||
NVN(nvnTextureReadTexels, void, const NVNtexture *t, const NVNtextureView *v, const NVNcopyRegion *r, void *dst) {
|
||||
@@ -335,11 +411,11 @@ NVN(nvnSamplerFinalize, void, NVNsampler *s) { ((samp_t *)s)->magic = 0; }
|
||||
NVN(nvnProgramInitialize, NVNboolean, NVNprogram *p, NVNdevice *d) {
|
||||
(void)d; memset(p, 0, sizeof(prog_t)); ((prog_t *)p)->magic = MAGIC('P', 'R', 'O', 'G'); return 1;
|
||||
}
|
||||
NVN(nvnProgramFinalize, void, NVNprogram *p) { mtl_prog_release((prog_t *)p); ((prog_t *)p)->magic = 0; }
|
||||
NVN(nvnProgramFinalize, void, NVNprogram *p) { prog_t *o = (prog_t *)p; snap_drop(&o->snap, o->serial, offsetof(prog_t, serial)); mtl_prog_release(o); o->magic = 0; }
|
||||
NVN(nvnProgramSetShaders, NVNboolean, NVNprogram *p, int n, const NVNshaderData *sd) {
|
||||
prog_t *o = (prog_t *)p;
|
||||
if (n < 0 || n > 6) { LOG("【红】ProgramSetShaders 阶段数 %d", n); return 0; }
|
||||
mtl_prog_release(o); o->nstage = n; memcpy(o->sd, sd, n * sizeof *sd); o->serial = nvn_new_serial();
|
||||
snap_drop(&o->snap, o->serial, offsetof(prog_t, serial)); mtl_prog_release(o); o->nstage = n; memcpy(o->sd, sd, n * sizeof *sd); o->serial = nvn_new_serial();
|
||||
OLOG("ProgramSetShaders %p n=%d data0=%#llx", (void *)p, n, n ? (unsigned long long)sd[0].data : 0ull);
|
||||
return 1;
|
||||
}
|
||||
@@ -350,7 +426,7 @@ NVN(nvnSyncInitialize, NVNboolean, NVNsync *s, NVNdevice *d) { (void)d; *(sync_t
|
||||
NVN(nvnSyncFinalize, void, NVNsync *s) { ((sync_t *)s)->magic = 0; }
|
||||
// 围栏 = 「此前提交到队列的命令全部完成」:记下最近一次提交的栅栏值
|
||||
// Fence = "all commands previously submitted to the queue have completed": record the fence value of the most recent submit
|
||||
NVN(nvnQueueFenceSync, void, NVNqueue *q, NVNsync *s, NVNsyncCondition c, int f) { (void)q; (void)c; (void)f; ((sync_t *)s)->fenced = 1; ((sync_t *)s)->fence = mtl_last_fence(); }
|
||||
NVN(nvnQueueFenceSync, void, NVNqueue *q, NVNsync *s, NVNsyncCondition c, int f) { (void)q; (void)c; (void)f; ((sync_t *)s)->fenced = 1; ((sync_t *)s)->fence = x_fence(); }
|
||||
// 没围栏过的同步对象按真机行为等到超时;已围栏的只在 GPU 真正完成到该栅栏值后放行
|
||||
// A sync object that was never fenced waits until timeout, as on a real device; a fenced one is released only after the GPU has actually completed up to that fence value
|
||||
NVN(nvnSyncWait, NVNsyncWaitResult, const NVNsync *s, uint64_t timeout) {
|
||||
@@ -399,8 +475,12 @@ NVN(nvnQueueFinalize, void, NVNqueue *q) { ((queue_t *)q)->magic = 0; }
|
||||
NVN(nvnQueueGetError, NVNqueueGetErrorResult, NVNqueue *q, NVNqueueErrorInfo *info) {
|
||||
(void)q; if (info) memset(info, 0, sizeof *info); return NVN_QUEUE_GET_ERROR_RESULT_GPU_NO_ERROR;
|
||||
}
|
||||
NVN(nvnQueueFlush, void, NVNqueue *q) { (void)q; }
|
||||
NVN(nvnQueueFinish, void, NVNqueue *q) { (void)q; mtl_finish(); }
|
||||
NVN(nvnQueueFlush, void, NVNqueue *q) { (void)q;
|
||||
#ifdef __ANDROID__
|
||||
x_drain(); mtl_queue_flush();
|
||||
#endif
|
||||
}
|
||||
NVN(nvnQueueFinish, void, NVNqueue *q) { (void)q; x_drain(); mtl_finish(); }
|
||||
|
||||
// ---------- 命令缓冲:录进游戏的命令内存,提交时执行 CPU 可见副作用 ----------
|
||||
// ---------- Command buffer: record into the game's command memory, perform CPU-visible side effects at submit ----------
|
||||
@@ -535,6 +615,30 @@ static void *rec(NVNcommandBuffer *c, uint32_t op, size_t payload) {
|
||||
return p + 8;
|
||||
}
|
||||
#define REC(c, OP, T) ((T *)rec((c), (OP), sizeof(T)))
|
||||
#ifdef __ANDROID__
|
||||
// Vulkan 后端要按命令序处理的同步命令(Metal 端仍当空操作,见 g_nops);格式与 dodola/d2r-mobile 的 nvn_vk.c 一致
|
||||
// Sync commands the Vulkan backend handles in command order (still no-ops on Metal, see g_nops); format matches nvn_vk.c of dodola/d2r-mobile
|
||||
NVN(nvnCommandBufferSetShaderScratchMemory, void, NVNcommandBuffer *c, const NVNmemoryPool *p, ptrdiff_t off, size_t size) {
|
||||
const pool_t *pool = (const pool_t *)p;
|
||||
if (!pool || pool->magic != MAGIC('P', 'O', 'O', 'L') || !pool->mem || off < 0 || (uint64_t)off > pool->size || size > pool->size - (uint64_t)off)
|
||||
die("ShaderScratchMemory 范围非法 off=%lld size=%llu", (long long)off, (unsigned long long)size);
|
||||
*REC(c, OP_SHADER_SCRATCH, p_bind_buf) = (p_bind_buf){.addr = (uint64_t)(uintptr_t)(pool->mem + off), .size = size};
|
||||
}
|
||||
NVN(nvnCommandBufferWaitSync, void, NVNcommandBuffer *c, const NVNsync *s) {
|
||||
if (!s || ((const sync_t *)s)->magic != MAGIC('S', 'Y', 'N', 'C')) die("CommandBufferWaitSync 同步对象非法");
|
||||
*REC(c, OP_WAIT_SYNC, p_sync) = (p_sync){(sync_t *)s, 0, 0};
|
||||
}
|
||||
NVN(nvnCommandBufferFenceSync, void, NVNcommandBuffer *c, NVNsync *s, NVNsyncCondition cond, int flags) {
|
||||
if (!s || ((sync_t *)s)->magic != MAGIC('S', 'Y', 'N', 'C') || cond < 0 || cond > 1 || (flags & ~1)) die("CommandBufferFenceSync 参数非法");
|
||||
*REC(c, OP_FENCE_SYNC, p_sync) = (p_sync){(sync_t *)s, cond, flags};
|
||||
}
|
||||
NVN(nvnCommandBufferWaitEvent, void, NVNcommandBuffer *c, const NVNevent *e, NVNeventWaitMode mode, uint32_t v) {
|
||||
const ev_t *ev = (const ev_t *)e;
|
||||
if (!ev || ev->magic != MAGIC('E', 'V', 'N', 'T') || !ev->val || mode < 0 || mode > 1) die("CommandBufferWaitEvent 参数非法");
|
||||
uint8_t *p = rec(c, OP_WAIT_EVENT, 16); uint64_t a = (uint64_t)(uintptr_t)ev->val; uint32_t mm = mode;
|
||||
memcpy(p, &a, 8); memcpy(p + 8, &mm, 4); memcpy(p + 12, &v, 4);
|
||||
}
|
||||
#endif
|
||||
// 带数组的绑定记录按实际个数分配:前缀字段 + n 个元素(回放端只读前 n 个)。原先按最大个数定长记(绑顶点缓冲 272 字节、绑贴图 / 采样器 280 字节,
|
||||
// 实际常只有 1–2 个),空尾占每帧命令字节的四到五成;88 级法师的高级属性页每帧录 12.5 MB,把游戏自己的命令内存池(约每帧 105 段 × 128 KB)用空
|
||||
// Binding records with arrays are allocated by the actual count: prefix fields + n elements (the replay side reads only the first n). Previously they were recorded at fixed length for the maximum count (bind vertex buffers 272 bytes, bind textures / samplers 280 bytes,
|
||||
@@ -545,8 +649,8 @@ NVN(nvnCommandBufferSetRenderTargets, void, NVNcommandBuffer *c, int n, const NV
|
||||
const NVNtexture *dt, const NVNtextureView *dv) {
|
||||
if (n < 0 || n > 8) { LOG("【红】SetRenderTargets 数量 %d", n); n = n < 0 ? 0 : 8; }
|
||||
p_set_rt *r = REC(c, OP_SET_RT, p_set_rt); r->n = n;
|
||||
for (int i = 0; i < n; i++) { r->color[i] = ct ? (const tex_t *)ct[i] : NULL; copy_view(&r->cview[i], &r->has_cview[i], cv ? cv[i] : NULL); }
|
||||
r->depth = (const tex_t *)dt; copy_view(&r->dview, &r->has_dview, dv);
|
||||
for (int i = 0; i < n; i++) { r->color[i] = ct ? snap_tex(ct[i]) : NULL; copy_view(&r->cview[i], &r->has_cview[i], cv ? cv[i] : NULL); }
|
||||
r->depth = snap_tex(dt); copy_view(&r->dview, &r->has_dview, dv);
|
||||
}
|
||||
NVN(nvnCommandBufferClearColor, void, NVNcommandBuffer *c, int index, const float *rgba, int mask) {
|
||||
p_clear_color *r = REC(c, OP_CLEAR_COLOR, p_clear_color); r->index = index; r->mask = mask; memcpy(r->rgba, rgba, 16);
|
||||
@@ -562,7 +666,7 @@ NVN(nvnCommandBufferSetViewports, void, NVNcommandBuffer *c, int first, int n, c
|
||||
NVN(nvnCommandBufferSetScissor, void, NVNcommandBuffer *c, int x, int y, int w, int h) { *REC(c, OP_SCISSOR, p_scissor) = (p_scissor){x, y, w, h}; }
|
||||
NVN(nvnCommandBufferSetDepthRange, void, NVNcommandBuffer *c, float n, float f) { *REC(c, OP_DEPTH_RANGE, p_depth_range) = (p_depth_range){n, f}; }
|
||||
NVN(nvnCommandBufferBindProgram, void, NVNcommandBuffer *c, const NVNprogram *p, int stages) {
|
||||
*REC(c, OP_BIND_PROGRAM, p_bind_program) = (p_bind_program){(const prog_t *)p, stages};
|
||||
*REC(c, OP_BIND_PROGRAM, p_bind_program) = (p_bind_program){snap_prog(p), stages};
|
||||
}
|
||||
static void bind_state(NVNcommandBuffer *c, int kind, const void *st, size_t n) { p_bind_state *r = REC(c, OP_BIND_STATE, p_bind_state); r->kind = kind; memcpy(r->bytes, st, n); }
|
||||
NVN(nvnCommandBufferBindBlendState, void, NVNcommandBuffer *c, const NVNblendState *st) { bind_state(c, 0, st, sizeof(blend_st)); }
|
||||
@@ -635,23 +739,23 @@ NVN(nvnCommandBufferSetSamplerPool, void, NVNcommandBuffer *c, const NVNsamplerP
|
||||
|
||||
NVN(nvnCommandBufferCopyBufferToTexture, void, NVNcommandBuffer *c, NVNbufferAddress src, const NVNtexture *t, const NVNtextureView *v,
|
||||
const NVNcopyRegion *r, int flags) {
|
||||
p_copy_b2t *o = REC(c, OP_COPY_B2T, p_copy_b2t); o->src = src; o->tex = (const tex_t *)t; copy_view(&o->view, &o->has_view, v); o->r = *r; o->flags = flags;
|
||||
p_copy_b2t *o = REC(c, OP_COPY_B2T, p_copy_b2t); o->src = src; o->tex = snap_tex(t); copy_view(&o->view, &o->has_view, v); o->r = *r; o->flags = flags;
|
||||
}
|
||||
NVN(nvnCommandBufferCopyTextureToBuffer, void, NVNcommandBuffer *c, const NVNtexture *t, const NVNtextureView *v, const NVNcopyRegion *r,
|
||||
NVNbufferAddress dst, int flags) {
|
||||
p_copy_b2t *o = REC(c, OP_COPY_T2B, p_copy_b2t); o->src = dst; o->tex = (const tex_t *)t; copy_view(&o->view, &o->has_view, v); o->r = *r; o->flags = flags;
|
||||
p_copy_b2t *o = REC(c, OP_COPY_T2B, p_copy_b2t); o->src = dst; o->tex = snap_tex(t); copy_view(&o->view, &o->has_view, v); o->r = *r; o->flags = flags;
|
||||
}
|
||||
// 用给定值清贴图区域(浮点 / 无符号整数两版;mask = 通道写掩码)
|
||||
// Clear a texture region with the given value (float / unsigned integer versions; mask = channel write mask)
|
||||
NVN(nvnCommandBufferClearTexture, void, NVNcommandBuffer *c, const NVNtexture *t, const NVNtextureView *v, const NVNcopyRegion *r, const float *rgba, int mask) {
|
||||
p_clear_tex *o = REC(c, OP_CLEAR_TEX, p_clear_tex); o->tex = (const tex_t *)t; copy_view(&o->view, &o->has_view, v); o->r = *r; o->mask = mask; o->is_uint = 0; memcpy(o->c.f, rgba, 16);
|
||||
p_clear_tex *o = REC(c, OP_CLEAR_TEX, p_clear_tex); o->tex = snap_tex(t); copy_view(&o->view, &o->has_view, v); o->r = *r; o->mask = mask; o->is_uint = 0; memcpy(o->c.f, rgba, 16);
|
||||
}
|
||||
NVN(nvnCommandBufferClearTextureui, void, NVNcommandBuffer *c, const NVNtexture *t, const NVNtextureView *v, const NVNcopyRegion *r, const uint32_t *rgba, int mask) {
|
||||
p_clear_tex *o = REC(c, OP_CLEAR_TEX, p_clear_tex); o->tex = (const tex_t *)t; copy_view(&o->view, &o->has_view, v); o->r = *r; o->mask = mask; o->is_uint = 1; memcpy(o->c.u, rgba, 16);
|
||||
p_clear_tex *o = REC(c, OP_CLEAR_TEX, p_clear_tex); o->tex = snap_tex(t); copy_view(&o->view, &o->has_view, v); o->r = *r; o->mask = mask; o->is_uint = 1; memcpy(o->c.u, rgba, 16);
|
||||
}
|
||||
NVN(nvnCommandBufferCopyTextureToTexture, void, NVNcommandBuffer *c, const NVNtexture *s, const NVNtextureView *sv, const NVNcopyRegion *sr,
|
||||
const NVNtexture *d, const NVNtextureView *dv, const NVNcopyRegion *dr, int flags) {
|
||||
p_copy_t2t *o = REC(c, OP_COPY_T2T, p_copy_t2t); o->src = (const tex_t *)s; o->dst = (const tex_t *)d;
|
||||
p_copy_t2t *o = REC(c, OP_COPY_T2T, p_copy_t2t); o->src = snap_tex(s); o->dst = snap_tex(d);
|
||||
copy_view(&o->sv, &o->has_sv, sv); copy_view(&o->dv, &o->has_dv, dv); o->sr = *sr; o->dr = *dr; o->flags = flags;
|
||||
}
|
||||
NVN(nvnCommandBufferSetCopyRowStride, void, NVNcommandBuffer *c, ptrdiff_t st) { REC(c, OP_COPY_STRIDE, p_copy_stride)->stride = st; }
|
||||
@@ -747,23 +851,123 @@ void dm_gfx_suspend(int on) {
|
||||
if (on) while (g_inflight_api) pthread_cond_wait(&g_susp_cv, &g_susp_mu);
|
||||
else pthread_cond_broadcast(&g_susp_cv);
|
||||
pthread_mutex_unlock(&g_susp_mu);
|
||||
if (on) { mtl_drain(); LOG("[nvn] 图形挂起:在途 GPU 工作已清空"); } else LOG("[nvn] 图形恢复");
|
||||
if (on) { x_drain(); mtl_drain(); LOG("[nvn] 图形挂起:在途 GPU 工作已清空"); } else LOG("[nvn] 图形恢复");
|
||||
}
|
||||
NVN(nvnQueueSubmitCommands, void, NVNqueue *q, int n, const NVNcommandHandle *h) {
|
||||
gfx_enter();
|
||||
// 一条实时线程的声明状态:游戏主线程(取图处)与翻译线程(帧边界)各一份,按各自每帧 CPU 自动调整(见 set_time_constraint_comp)
|
||||
// Declaration state of one real-time thread: one each for the game main thread (at acquire) and the translation thread (at frame boundaries), each adjusted automatically from its own per-frame CPU (see set_time_constraint_comp)
|
||||
typedef struct { const char *who; double comp_ms, period_ms; uint64_t last; double win[120]; int n; } rt_decl; // comp_ms:当前声明的计算量(0 = 未声明) | comp_ms: currently declared computation (0 = not declared)
|
||||
static rt_decl g_rt_main = {"出图线程"}, g_rt_xlat = {"翻译线程"};
|
||||
static void set_time_constraint(rt_decl *d, uint64_t period_ns);
|
||||
static void rt_comp_tick(rt_decl *d, uint64_t period_ns);
|
||||
// ---------- 翻译队列(B 方案第二期):提交 / 出图 / 设帧号按序排给翻译线程,游戏线程只登记、立刻返回 ----------
|
||||
// 游戏逻辑与上一帧的翻译(回放 + Metal 编码)重叠。栅栏值 = 已入队的提交数:Metal 层每次提交恰好 ++g_fence、g_done 只在已提交的命令缓冲
|
||||
// 完成时推进,所以等栅栏 f 就是等「f 翻译完且 GPU 做完」——游戏按栅栏回收命令内存、改写对象时翻译线程早已读完。
|
||||
// 出图票号换成本队列的任务号:取图处先等该任务执行完,再按它换来的出图线程票号等。设帧号也排队:回放按帧号重置泛光取样等状态,
|
||||
// 不能在翻译途中被游戏线程改掉。DM_NVN_SYNC=1:任务在调用线程上当场执行(同一个执行函数),作对照与量测基准。
|
||||
// ---------- Translation queue (plan B, phase 2): submit / present / set-frame-number are queued in order to the translation thread; the game thread only records them and returns at once ----------
|
||||
// Game logic overlaps the previous frame's translation (replay + Metal encoding). Fence value = number of submits enqueued: the Metal layer does ++g_fence exactly once per submit and g_done advances only when a committed command buffer
|
||||
// completes, so waiting for fence f means waiting until "f is translated and the GPU is done"; by the time the game reclaims command memory or rewrites objects by fence, the translation thread has long finished reading them.
|
||||
// Present tickets become this queue's job numbers: acquire first waits for that job to run, then waits on the present thread ticket it was swapped for. Setting the frame number is queued too: replay resets bloom sampling and other state by frame number,
|
||||
// which must not be changed by the game thread in the middle of translation. DM_NVN_SYNC=1: jobs run in place on the calling thread (the same execution function), as the control and measurement baseline.
|
||||
enum { XJ_SUBMIT, XJ_PRESENT, XJ_FRAME };
|
||||
typedef struct { int kind, n; uint64_t *h; const tex_t *tex; double period; int crop[4]; uint64_t frame, sub, host; } xjob; // host:入队时锁存的宿主画法开关 | host: host drawing switches latched at enqueue
|
||||
#define XQ 32
|
||||
#define XTK 1024
|
||||
static xjob g_xq[XQ]; static uint64_t g_xq_in, g_xq_done; // 入队任务数 / 已执行任务数(任务号从 1 计) | Jobs enqueued / jobs executed (job numbers start at 1)
|
||||
static struct { uint64_t job, tk; } g_xtk[XTK]; // 出图任务号 → 出图线程票号 | Present job number -> present thread ticket
|
||||
static pthread_mutex_t g_xmu = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t g_xcv = PTHREAD_COND_INITIALIZER;
|
||||
static int g_x_sync; static pthread_t g_x_thr; static mach_port_t g_x_port; // 翻译线程(策略读数用) | Translation thread (for policy readings)
|
||||
#ifdef __ANDROID__
|
||||
#define ANDROID_SYNC_FENCE 1 // Vulkan 后端的栅栏还计读回等内部提交,不与提交数对齐 | the Vulkan backend's fence also counts internal commits such as readbacks and is not aligned with the submit count
|
||||
#else
|
||||
#define ANDROID_SYNC_FENCE 0
|
||||
#endif
|
||||
static void x_submit(const uint64_t *h, int n, uint64_t sub, uint64_t host) {
|
||||
mtl_host_apply(host);
|
||||
uint64_t t0 = now_ns(), c0 = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID), i0, y0, s0 = thr_sys_ns(); thr_counts(&i0, &y0);
|
||||
((queue_t *)q)->submits++;
|
||||
mtl_sub_begin();
|
||||
mtl_sub_index((const uint64_t *)h, n);
|
||||
for (int i = 0; i < n; i++) { mtl_exec_rest((const uint64_t *)h + i + 1, n - i - 1); mtl_exec((const uint8_t *)h[i]); }
|
||||
mtl_sub_index(h, n);
|
||||
for (int i = 0; i < n; i++) { mtl_exec_rest(h + i + 1, n - i - 1); mtl_exec((const uint8_t *)h[i]); }
|
||||
mtl_exec_rest(NULL, 0);
|
||||
mtl_sub_commit();
|
||||
uint64_t f = mtl_sub_commit();
|
||||
if (f != sub && !ANDROID_SYNC_FENCE) { static int red; if (!red++) LOG("【红】翻译队列:第 %llu 次提交的 Metal 栅栏是 %llu,栅栏与提交数对不上,游戏等同步会提前 / 推迟放行", (unsigned long long)sub, (unsigned long long)f); }
|
||||
snap_tick(sub);
|
||||
uint64_t dw = now_ns() - t0;
|
||||
atomic_fetch_add(&g_nvn_ns, dw); atomic_fetch_add(&g_sub_wall_ns, dw);
|
||||
uint64_t i1, y1; thr_counts(&i1, &y1); uint64_t dc = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID) - c0, di = i1 - i0;
|
||||
atomic_fetch_add(&g_cum_sub_cyc, y1 - y0); atomic_fetch_add(&g_cum_sub_sys_ns, thr_sys_ns() - s0); atomic_fetch_add(&g_cum_sub_wall_ns, dw);
|
||||
atomic_fetch_add(&g_sub_cpu_ns, dc); atomic_fetch_add(&g_cum_sub_cpu_ns, dc);
|
||||
atomic_fetch_add(&g_sub_instr, di); atomic_fetch_add(&g_cum_sub_instr, di);
|
||||
}
|
||||
static void x_run(const xjob *j, uint64_t job) {
|
||||
if (j->kind == XJ_SUBMIT) { x_submit(j->h, j->n, j->sub, j->host); free(j->h); }
|
||||
else if (j->kind == XJ_PRESENT) { uint64_t tk = mtl_present(j->tex, j->period, j->crop); pthread_mutex_lock(&g_xmu); g_xtk[job % XTK].job = job; g_xtk[job % XTK].tk = tk; pthread_mutex_unlock(&g_xmu); }
|
||||
else {
|
||||
mtl_set_frame(j->frame);
|
||||
// 翻译线程与游戏主线程同级:时间约束(实时)线程,周期 = 出图周期,计算量按本线程每帧 CPU 的 p90 自动声明(同取图处的主线程;确定性时钟下不声明)
|
||||
// The translation thread has the same standing as the game main thread: a time-constraint (real-time) thread, period = present period, computation declared automatically from the p90 of this thread's per-frame CPU (same as the main thread at acquire; not declared under the deterministic clock)
|
||||
uint64_t pn = (uint64_t)(j->period * 1e9); static uint64_t rt_p;
|
||||
if (!g_x_sync && !dm_detclock_enabled()) { if (pn && rt_p != pn) { rt_p = pn; set_time_constraint(&g_rt_xlat, pn); } rt_comp_tick(&g_rt_xlat, pn); }
|
||||
}
|
||||
}
|
||||
static void *x_thread(void *a) {
|
||||
(void)a; pthread_setname_np("nvn-translate"); g_x_port = pthread_mach_thread_np(pthread_self());
|
||||
pthread_mutex_lock(&g_xmu);
|
||||
for (;;) {
|
||||
while (g_xq_done == g_xq_in) pthread_cond_wait(&g_xcv, &g_xmu);
|
||||
uint64_t job = g_xq_done + 1; xjob j = g_xq[job % XQ];
|
||||
pthread_mutex_unlock(&g_xmu);
|
||||
x_run(&j, job);
|
||||
pthread_mutex_lock(&g_xmu);
|
||||
g_xq_done = job; pthread_cond_broadcast(&g_xcv);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
static void x_start(void) {
|
||||
#ifdef __ANDROID__
|
||||
// Vulkan 后端还没按翻译线程改:提交线程上同步翻译(读回贴图等也会提交,栅栏不等于提交数,见 x_fence)
|
||||
// The Vulkan backend has not been adapted to the translation thread yet: translate synchronously on the submit thread (texture readbacks also commit, so the fence is not the submit count, see x_fence)
|
||||
g_x_sync = 1; LOG("[nvn] 安卓:翻译在提交线程上同步做"); return;
|
||||
#endif
|
||||
const char *e = getenv("DM_NVN_SYNC"); g_x_sync = e && atoi(e);
|
||||
if (g_x_sync) { LOG("[nvn] DM_NVN_SYNC=1:翻译在提交线程上同步做(对照档)"); return; }
|
||||
pthread_attr_t at; pthread_attr_init(&at); pthread_attr_set_qos_class_np(&at, QOS_CLASS_USER_INTERACTIVE, 0); pthread_attr_setstacksize(&at, 8 << 20);
|
||||
pthread_t t; if (pthread_create(&g_x_thr, &at, x_thread, NULL)) { LOG("【红】翻译线程起不来,改为同步翻译"); g_x_sync = 1; } else LOG("[nvn] 翻译线程已起:提交 / 出图在翻译线程上按序执行(队列 %d 项)", XQ);
|
||||
pthread_attr_destroy(&at);
|
||||
}
|
||||
static uint64_t x_push(xjob *j) { // 返回任务号 | Returns the job number
|
||||
static pthread_once_t once = PTHREAD_ONCE_INIT; pthread_once(&once, x_start);
|
||||
pthread_mutex_lock(&g_xmu);
|
||||
while (g_xq_in - g_xq_done >= XQ) pthread_cond_wait(&g_xcv, &g_xmu);
|
||||
if (j->kind == XJ_SUBMIT) j->sub = atomic_fetch_add(&g_x_subs, 1) + 1;
|
||||
uint64_t job = ++g_xq_in;
|
||||
if (g_x_sync) { // 当场执行:单线程提交时与旧路径同序 | Run in place: with single-thread submission the order is the same as the old path
|
||||
pthread_mutex_unlock(&g_xmu); x_run(j, job); pthread_mutex_lock(&g_xmu);
|
||||
g_xq_done = job; pthread_cond_broadcast(&g_xcv);
|
||||
} else { g_xq[job % XQ] = *j; pthread_cond_broadcast(&g_xcv); }
|
||||
pthread_mutex_unlock(&g_xmu);
|
||||
return job;
|
||||
}
|
||||
static void x_wait(uint64_t job) { pthread_mutex_lock(&g_xmu); while (g_xq_done < job) pthread_cond_wait(&g_xcv, &g_xmu); pthread_mutex_unlock(&g_xmu); }
|
||||
static void x_drain(void) { pthread_mutex_lock(&g_xmu); uint64_t job = g_xq_in; pthread_mutex_unlock(&g_xmu); x_wait(job); }
|
||||
#ifdef __ANDROID__
|
||||
static uint64_t x_fence(void) { return mtl_last_fence(); } // 同步翻译:Vulkan 后端的最近栅栏(含读回等内部提交) | synchronous translation: the Vulkan backend's latest fence (including internal commits such as readbacks)
|
||||
#else
|
||||
static uint64_t x_fence(void) { return atomic_load(&g_x_subs); }
|
||||
#endif
|
||||
static uint64_t x_present_ticket(uint64_t job) { // 出图任务执行完后换来的出图线程票号(0 = 那次出图被丢弃,不用等) | Present thread ticket obtained after the present job runs (0 = that present was dropped, nothing to wait for)
|
||||
x_wait(job);
|
||||
pthread_mutex_lock(&g_xmu); uint64_t tk = g_xtk[job % XTK].job == job ? g_xtk[job % XTK].tk : 0; int lost = g_xtk[job % XTK].job != job; pthread_mutex_unlock(&g_xmu);
|
||||
if (lost) { static int red; if (!red++) LOG("【红】翻译队列:出图任务 %llu 的票号已被覆盖(票号表 %d 项不够),这次取图不等出图线程", (unsigned long long)job, XTK); }
|
||||
return tk;
|
||||
}
|
||||
NVN(nvnQueueSubmitCommands, void, NVNqueue *q, int n, const NVNcommandHandle *h) {
|
||||
gfx_enter();
|
||||
((queue_t *)q)->submits++;
|
||||
xjob j = {XJ_SUBMIT, n, n > 0 ? malloc((size_t)n * sizeof *h) : NULL}; // 句柄数组是游戏的,入队时拷一份 | The handle array belongs to the game; copy it when enqueuing
|
||||
if (n > 0) memcpy(j.h, h, (size_t)n * sizeof *h);
|
||||
j.host = mtl_host_latch();
|
||||
x_push(&j);
|
||||
gfx_leave();
|
||||
}
|
||||
|
||||
@@ -777,12 +981,18 @@ static const char *const g_nops[] = {
|
||||
"nvnCommandBufferDispatchComputeIndirect",
|
||||
"nvnCommandBufferSetDepthBounds",
|
||||
"nvnCommandBufferDownsampleTextureView",
|
||||
#ifndef __ANDROID__
|
||||
"nvnCommandBufferWaitSync",
|
||||
#endif
|
||||
#ifndef __ANDROID__
|
||||
"nvnCommandBufferSetShaderScratchMemory",
|
||||
#endif
|
||||
"nvnCommandBufferPushDebugGroupDynamic",
|
||||
"nvnCommandBufferPopDebugGroup",
|
||||
"nvnCommandBufferInsertDebugMarkerDynamic",
|
||||
#ifndef __ANDROID__
|
||||
"nvnCommandBufferWaitEvent",
|
||||
#endif
|
||||
"nvnWindowFinalize",
|
||||
};
|
||||
__attribute__((constructor)) static void nvn_nops_register(void) {
|
||||
@@ -833,13 +1043,10 @@ NVN(nvnWindowSetCrop, void, NVNwindow *w, int x, int y, int ww, int hh) {
|
||||
memcpy(o->crop, v, sizeof v);
|
||||
}
|
||||
static void trow(uint64_t f, const char *name, double v);
|
||||
static void set_time_constraint(uint64_t period_ns);
|
||||
static void rt_comp_tick(uint64_t period_ns);
|
||||
static double g_rt_comp_ms; // 当前声明的实时计算量(ms;0 = 未声明) | Currently declared real-time computation amount (ms; 0 = not declared)
|
||||
static double g_rt_period_ms;
|
||||
static void sleep_until_ns(uint64_t dl);
|
||||
static uint64_t present_period(const win_t *o);
|
||||
__attribute__((weak)) void dm_main_yield_stats(uint64_t *n, uint64_t *ns) { *n = 0; *ns = 0; } // 宿主 hle_thread.c 提供真值;图形单测里为 0 | The host's hle_thread.c provides the ground truth; 0 in graphics unit tests
|
||||
__attribute__((weak)) void mtl_pace_slept(uint64_t ns) { (void)ns; } // 取图里节拍等待的墙钟;安卓后端(nvn_vk.c)据此算每帧真实工作时长报给 ADPF | Wall time spent in the acquire pacing wait; the Android backend (nvn_vk.c) uses it to derive each frame's real work time for ADPF
|
||||
__attribute__((weak)) uint32_t dm_guest_work_qos(unsigned *count) { if (count) *count = 0; return QOS_CLASS_UNSPECIFIED; }
|
||||
extern uint32_t mtl_present_qos(void);
|
||||
static uint64_t g_frame;
|
||||
@@ -854,10 +1061,12 @@ NVN(nvnWindowAcquireTexture, NVNwindowAcquireTextureResult, NVNwindow *w, NVNsyn
|
||||
uint64_t at = *idx < 4 ? o->avail[*idx] : 0, now = dm_detclock_enabled() ? guest_ns() : now_ns(), wait = at > now ? at - now : 0;
|
||||
if (!dm_detclock_enabled()) { // 取图线程登记为时间约束线程(不再只在「来早了」时才登记:热态一直落后时也要声明) | Register the acquire thread as a time-constraint thread (no longer registered only when it "arrived early": it must also declare itself when it is constantly behind in the hot state)
|
||||
static uint64_t rt_period; uint64_t period = present_period(o);
|
||||
if (period && rt_period != period) { rt_period = period; set_time_constraint(period); }
|
||||
rt_comp_tick(period);
|
||||
if (period && rt_period != period) { rt_period = period; set_time_constraint(&g_rt_main, period); }
|
||||
rt_comp_tick(&g_rt_main, period);
|
||||
uint64_t pace_t0 = now_ns();
|
||||
if (mtl_link_active()) { if (!mtl_link_wait_tick(period ? 2 * period : 33333333ull) && wait) sleep_until_ns(at); } // DM_PRESENT_LINK:节拍完全跟显示节拍(跑得快就等下一拍,落后立刻走);自己的 60 Hz 时钟只作等不到节拍时的兜底 | DM_PRESENT_LINK: pacing fully follows the display link (wait for the next display-link tick when running fast, go immediately when behind); our own 60 Hz clock is only the fallback when no display-link tick arrives
|
||||
else if (wait) sleep_until_ns(at);
|
||||
mtl_pace_slept(now_ns() - pace_t0);
|
||||
} else { // DM_DETCLOCK_PACE=1(画面闸门用):客体时钟按帧走的同时,每帧墙钟不短于一个步长——帧数与游戏内时间确定,后台加载线程每帧至少有一个步长的墙钟可用; | DM_DETCLOCK_PACE=1 (used by the screenshot gate): while the guest clock advances per frame, each frame's wall clock is no shorter than one step -- frame count and in-game time are deterministic, and the background loading thread has at least one step of wall clock available per frame;
|
||||
// 机器满载时帧只会更慢、后台得到的墙钟只会更多,所以「消息后第 N 帧」截到的画面与负载无关
|
||||
// When the machine is fully loaded frames only get slower and the background only gets more wall clock, so the picture captured at "the Nth frame after the message" is independent of load
|
||||
@@ -869,8 +1078,8 @@ NVN(nvnWindowAcquireTexture, NVNwindowAcquireTextureResult, NVNwindow *w, NVNsyn
|
||||
// 该张上一次出图还没被出图线程处理完(显示跟不上、落后一整轮交换链):等它归还,再交给游戏画
|
||||
// The previous present of this texture has not yet been processed by the present thread (display cannot keep up, a whole swapchain round behind): wait for it to be returned, then hand it to the game to draw
|
||||
uint64_t tk = *idx < 4 ? o->ticket[*idx] : 0;
|
||||
if (tk) { uint64_t w0 = now_ns(); mtl_present_wait(tk); g_pq_wait_ns += now_ns() - w0; }
|
||||
if (s) { ((sync_t *)s)->fenced = 1; ((sync_t *)s)->fence = mtl_last_fence(); } // 交换链贴图在此前的提交完成后可用 | The swapchain texture becomes available once the commits before this point have completed
|
||||
if (tk) { uint64_t w0 = now_ns(), rt = x_present_ticket(tk); if (rt) mtl_present_wait(rt); g_pq_wait_ns += now_ns() - w0; } // tk 是翻译队列的出图任务号 | tk is the translation queue's present job number
|
||||
if (s) { ((sync_t *)s)->fenced = 1; ((sync_t *)s)->fence = x_fence(); } // 交换链贴图在此前的提交完成后可用 | The swapchain texture becomes available once the commits before this point have completed
|
||||
return NVN_WINDOW_ACQUIRE_TEXTURE_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
@@ -968,14 +1177,24 @@ static void tsummary(uint64_t frame) {
|
||||
uint64_t aw = 0, ag = 0; int an = 0; void mtl_alloc_stats(uint64_t *, uint64_t *, int *); mtl_alloc_stats(&aw, &ag, &an);
|
||||
static uint64_t pyn, pyns; uint64_t yn = 0, yns = 0; dm_main_yield_stats(&yn, &yns);
|
||||
LOG("[nvn] 翻译细项 至帧 %llu:每帧提交 周期 %.2f M(每条指令 %.2f 周期)、CPU %.3f ms 其中内核态 %.3f ms、墙钟 %.3f ms;平均主频 %.2f GHz(周期 / CPU 时间);本线程 QoS %#x;分配器池 %d 个、累计等 GPU %llu 次;实时声明计算 %.2f ms;主线程让出 每帧 %.0f 次 / %.3f ms", frame,
|
||||
cyc / 1e6 / nf, cyc / (double)(ci - pi), cpu / 1e6 / nf, (double)(ck - pk) / 1e6 / nf, (double)(cw - pw) / 1e6 / nf, cpu > 0 ? cyc / cpu : 0, (unsigned)qc, an, (unsigned long long)aw, g_rt_comp_ms, (double)(yn - pyn) / nf, (double)(yns - pyns) / 1e6 / nf); pyn = yn; pyns = yns; }
|
||||
cyc / 1e6 / nf, cyc / (double)(ci - pi), cpu / 1e6 / nf, (double)(ck - pk) / 1e6 / nf, (double)(cw - pw) / 1e6 / nf, cpu > 0 ? cyc / cpu : 0, (unsigned)qc, an, (unsigned long long)aw, g_rt_main.comp_ms, (double)(yn - pyn) / nf, (double)(yns - pyns) / 1e6 / nf); pyn = yn; pyns = yns; }
|
||||
if (frame % 300 == 0) { unsigned wn = 0; uint32_t wq = dm_guest_work_qos(&wn); thread_extended_info_data_t xi; mach_msg_type_number_t xc = THREAD_EXTENDED_INFO_COUNT; int okx = thread_info(pthread_mach_thread_np(pthread_self()), THREAD_EXTENDED_INFO, (thread_info_t)&xi, &xc) == KERN_SUCCESS;
|
||||
thread_time_constraint_policy_data_t tp; mach_msg_type_number_t tc = THREAD_TIME_CONSTRAINT_POLICY_COUNT; boolean_t def = 0; int rt_live = thread_policy_get(pthread_mach_thread_np(pthread_self()), THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t)&tp, &tc, &def) == KERN_SUCCESS && !def; // def = 1:实时策略没在生效(没设上 / 被撤) | def = 1: the real-time policy is not in effect (never set / revoked)
|
||||
LOG("[nvn] 线程策略:主线程 实时 计算 %.2f ms / 周期 %.2f ms,实时策略%s,当前优先级 %d(基础 %d,调度类 %d);工作线程 %u 条 QoS %#x;出图 QoS %#x", g_rt_comp_ms, g_rt_period_ms, rt_live ? "在生效" : "未生效", okx ? xi.pth_curpri : -1, okx ? xi.pth_priority : -1, okx ? xi.pth_policy : -1, wn, wq, mtl_present_qos()); }
|
||||
LOG("[nvn] 线程策略:主线程 实时 计算 %.2f ms / 周期 %.2f ms,实时策略%s,当前优先级 %d(基础 %d,调度类 %d);工作线程 %u 条 QoS %#x;出图 QoS %#x", g_rt_main.comp_ms, g_rt_main.period_ms, rt_live ? "在生效" : "未生效", okx ? xi.pth_curpri : -1, okx ? xi.pth_priority : -1, okx ? xi.pth_policy : -1, wn, wq, mtl_present_qos());
|
||||
if (g_x_port) { // 翻译线程:声明、实时策略在不在生效、当前 / 基础优先级、QoS(降级看这几项;在不在大核看「翻译细项」行的平均主频) | Translation thread: declaration, whether the real-time policy is in effect, current / base priority, QoS (check these for demotion; for whether it is on a performance core, see the average clock on the "translation detail" line)
|
||||
thread_extended_info_data_t yi; mach_msg_type_number_t yc = THREAD_EXTENDED_INFO_COUNT; int oky = thread_info(g_x_port, THREAD_EXTENDED_INFO, (thread_info_t)&yi, &yc) == KERN_SUCCESS;
|
||||
thread_time_constraint_policy_data_t yp; mach_msg_type_number_t ytc = THREAD_TIME_CONSTRAINT_POLICY_COUNT; boolean_t ydef = 0; int y_live = thread_policy_get(g_x_port, THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t)&yp, &ytc, &ydef) == KERN_SUCCESS && !ydef;
|
||||
qos_class_t yq = QOS_CLASS_UNSPECIFIED; int yr = 0; pthread_get_qos_class_np(g_x_thr, &yq, &yr);
|
||||
LOG("[nvn] 线程策略:翻译线程 实时 计算 %.2f ms / 周期 %.2f ms,实时策略%s,当前优先级 %d(基础 %d,调度类 %d);QoS %#x", g_rt_xlat.comp_ms, g_rt_xlat.period_ms, y_live ? "在生效" : "未生效",
|
||||
oky ? yi.pth_curpri : -1, oky ? yi.pth_priority : -1, oky ? yi.pth_policy : -1, (unsigned)yq); } }
|
||||
py = cy; pk = ck; pw = cw; }
|
||||
pi = ci; pc = cc; pd = dr_; pf = frame; }
|
||||
uint64_t up, re, fa, pr; mtl_pkg_stats(&up, &re); nvn_dirty_stats(&fa, &pr);
|
||||
#ifdef __ANDROID__
|
||||
{ int nvn_dirty_vma_count(void); LOG("[nvn] 预排布贴图 首传 %llu 张、池内容变化重传 %llu 次;写保护缺页 %llu 次、宿主写前解保护 %llu 页;漏检 %llu(累计);进程映射 %d 段", up, re, fa, pr, mtl_pkg_miss(), nvn_dirty_vma_count()); }
|
||||
#else
|
||||
LOG("[nvn] 预排布贴图 首传 %llu 张、池内容变化重传 %llu 次;写保护缺页 %llu 次、宿主写前解保护 %llu 页;漏检 %llu(累计)", up, re, fa, pr, mtl_pkg_miss());
|
||||
#endif
|
||||
memset(g_tn, 0, sizeof g_tn);
|
||||
}
|
||||
// DM_SLOWFRAME=1(测试开关,真机经日志端口读):逐帧计时先存近 16 帧环;滞后 8 帧(GPU / 上屏时刻已回)判掉帧,
|
||||
@@ -1022,29 +1241,28 @@ static void slow_emit(uint64_t f) {
|
||||
// The computation used to be hard-coded at 2 ms, while the game main thread (game logic + recording + submit replay) takes about 10 ms per frame when hot - a 5× gap between declared and actual:
|
||||
// a real-time thread that exceeds its declared computation gets demoted by the system, and the performance controller also sets frequency from the declaration (this declaration is how the system learns the frame deadline and the workload).
|
||||
// DM_RT_COMP=<ms> fixes the declaration; default auto = every 120 frames take the p90 of this thread's per-frame CPU time and re-declare if it differs from the declared value by > 15% (capped at 0.9 × period).
|
||||
static void set_time_constraint_comp(uint64_t period_ns, uint64_t comp_ns) {
|
||||
static void set_time_constraint_comp(rt_decl *d, uint64_t period_ns, uint64_t comp_ns) {
|
||||
static mach_timebase_info_data_t tb; if (!tb.denom) mach_timebase_info(&tb);
|
||||
if (comp_ns < 1000000ull) comp_ns = 1000000ull; if (comp_ns > period_ns * 9 / 10) comp_ns = period_ns * 9 / 10;
|
||||
thread_time_constraint_policy_data_t p = {
|
||||
.period = (uint32_t)(period_ns * tb.denom / tb.numer), .computation = (uint32_t)(comp_ns * tb.denom / tb.numer),
|
||||
.constraint = (uint32_t)(period_ns * tb.denom / tb.numer), .preemptible = 1};
|
||||
kern_return_t kr = thread_policy_set(pthread_mach_thread_np(pthread_self()), THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t)&p, THREAD_TIME_CONSTRAINT_POLICY_COUNT);
|
||||
if (kr == KERN_SUCCESS) { g_rt_comp_ms = comp_ns / 1e6; g_rt_period_ms = period_ns / 1e6; }
|
||||
LOG("[nvn] 出图线程时间约束策略(周期 %.3f ms、计算 %.3f ms)%s", period_ns / 1e6, comp_ns / 1e6, kr == KERN_SUCCESS ? "已设" : "设置失败");
|
||||
if (kr == KERN_SUCCESS) { d->comp_ms = comp_ns / 1e6; d->period_ms = period_ns / 1e6; }
|
||||
LOG("[nvn] %s时间约束策略(周期 %.3f ms、计算 %.3f ms)%s", d->who, period_ns / 1e6, comp_ns / 1e6, kr == KERN_SUCCESS ? "已设" : "设置失败");
|
||||
}
|
||||
static int rt_comp_fixed_ms(void) { static int v = -2; if (v == -2) { const char *e = getenv("DM_RT_COMP"); v = e && *e && strcmp(e, "auto") ? atoi(e) : -1; } return v; } // −1 = auto
|
||||
static void set_time_constraint(uint64_t period_ns) { int f = rt_comp_fixed_ms(); set_time_constraint_comp(period_ns, f > 0 ? (uint64_t)f * 1000000ull : 2000000ull); } // 首次:固定值,或 auto 的起始值 2 ms | first time: the fixed value, or auto's starting value of 2 ms
|
||||
static void set_time_constraint(rt_decl *d, uint64_t period_ns) { int f = rt_comp_fixed_ms(); set_time_constraint_comp(d, period_ns, f > 0 ? (uint64_t)f * 1000000ull : 2000000ull); } // 首次:固定值,或 auto 的起始值 2 ms | first time: the fixed value, or auto's starting value of 2 ms
|
||||
// 每帧在取图处调:记本线程自上次以来的 CPU 时间;auto 模式下按 p90 重新声明
|
||||
// Called every frame at acquire: records this thread's CPU time since the last call; in auto mode re-declares based on p90
|
||||
static void rt_comp_tick(uint64_t period_ns) {
|
||||
if (rt_comp_fixed_ms() > 0 || !period_ns || !g_rt_comp_ms) return;
|
||||
static uint64_t last; static double win[120]; static int n;
|
||||
uint64_t c = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID); if (!last) { last = c; return; }
|
||||
win[n++] = (double)(c - last) / 1e6; last = c;
|
||||
if (n < 120) return;
|
||||
double v[120]; memcpy(v, win, sizeof v); qsort(v, 120, sizeof *v, dcmp); n = 0;
|
||||
static void rt_comp_tick(rt_decl *d, uint64_t period_ns) { // 在被声明的那条线程上调(读本线程 CPU 时钟) | Call on the thread being declared (reads this thread's CPU clock)
|
||||
if (rt_comp_fixed_ms() > 0 || !period_ns || !d->comp_ms) return;
|
||||
uint64_t c = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID); if (!d->last) { d->last = c; return; }
|
||||
d->win[d->n++] = (double)(c - d->last) / 1e6; d->last = c;
|
||||
if (d->n < 120) return;
|
||||
double v[120]; memcpy(v, d->win, sizeof v); qsort(v, 120, sizeof *v, dcmp); d->n = 0;
|
||||
double p90 = v[107], comp = p90 * 1.25, cap = period_ns * 0.9 / 1e6; if (comp > cap) comp = cap; if (comp < 1) comp = 1;
|
||||
if (comp > g_rt_comp_ms * 1.15 || comp < g_rt_comp_ms * 0.85) set_time_constraint_comp(period_ns, (uint64_t)(comp * 1e6));
|
||||
if (comp > d->comp_ms * 1.15 || comp < d->comp_ms * 0.85) set_time_constraint_comp(d, period_ns, (uint64_t)(comp * 1e6));
|
||||
}
|
||||
static void sleep_until_ns(uint64_t dl) { // 单调时钟上的绝对时刻 | absolute time on the monotonic clock
|
||||
static mach_timebase_info_data_t tb; if (!tb.denom) mach_timebase_info(&tb);
|
||||
@@ -1094,7 +1312,9 @@ NVN(nvnQueuePresentTexture, void, NVNqueue *q, NVNwindow *w, int idx) {
|
||||
present_cfg(o);
|
||||
gfx_enter();
|
||||
uint64_t t0 = now_ns();
|
||||
if (idx >= 0 && idx < o->ntex && idx < 4) o->ticket[idx] = mtl_present(CTX(o->tex[idx]), present_period(o) / 1e9, o->crop); // 只入队,立即返回 | enqueue only, return immediately
|
||||
if (idx >= 0 && idx < o->ntex && idx < 4) { // 只入队,立即返回;ticket 存翻译队列的任务号 | Enqueue only and return at once; ticket holds the translation queue's job number
|
||||
xjob j = {XJ_PRESENT, 0, NULL, snap_tex(o->tex[idx]), present_period(o) / 1e9}; memcpy(j.crop, o->crop, sizeof j.crop);
|
||||
o->ticket[idx] = x_push(&j); }
|
||||
gfx_leave();
|
||||
atomic_fetch_add(&g_nvn_ns, now_ns() - t0);
|
||||
uint64_t f = g_frame, ps, dr; mtl_stats(&ps, &dr);
|
||||
@@ -1180,7 +1400,9 @@ NVN(nvnQueuePresentTexture, void, NVNqueue *q, NVNwindow *w, int idx) {
|
||||
prev_in = t0; prev_pass = ps; prev_draw = dr;
|
||||
dump_frame();
|
||||
if (g_frame % TWIN == 0) tsummary(g_frame);
|
||||
mtl_set_frame(g_frame);
|
||||
{ static uint64_t pc, py, pf; uint64_t i_, y_, c_ = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID); thr_counts(&i_, &y_); // 主线程(游戏线程)的每帧 CPU 与平均主频:与「翻译细项」行的翻译线程对照,分「整机降频」还是「翻译线程被放小核」 | Per-frame CPU and average clock of the main (game) thread: compared with the translation thread on the "translation detail" line, to tell "whole-chip downclocking" from "translation thread placed on an efficiency core"
|
||||
if (g_frame % TWIN == 0) { if (pf && g_frame > pf && c_ > pc) LOG("[nvn] 主线程 至帧 %llu:每帧 CPU %.2f ms,平均主频 %.2f GHz(周期 / CPU 时间)", g_frame, (c_ - pc) / 1e6 / (double)(g_frame - pf), (double)(y_ - py) / (double)(c_ - pc)); pc = c_; py = y_; pf = g_frame; } }
|
||||
{ xjob j = {XJ_FRAME}; j.frame = g_frame; j.period = present_period(o) / 1e9; x_push(&j); } // 帧号随队列生效(见翻译队列说明) | The frame number takes effect in queue order (see the translation queue notes)
|
||||
// 真机语义:出图只入队、立即返回;本帧显示时刻按节拍器排,该贴图到「显示时刻 + 一个周期」才可再获取(阻塞在 AcquireTexture)
|
||||
// Real-device semantics: present only enqueues and returns immediately; this frame's display time is scheduled by the pacer, and the texture can be acquired again only at "display time + one period" (blocking in AcquireTexture)
|
||||
uint64_t period = present_period(o), now = dm_detclock_enabled() ? guest_ns() : now_ns();
|
||||
|
||||
+18
-1
@@ -14,6 +14,7 @@
|
||||
#include <unistd.h>
|
||||
#include <mach/mach_time.h>
|
||||
#include <sched.h>
|
||||
#include <stdio.h>
|
||||
|
||||
// 页状态与 mprotect 的次序(改保护的一方先把状态改成 BUSY,mprotect 落地后才改成终态;别的线程见 BUSY 就等):
|
||||
// 设只读:NONE → BUSY → mprotect(只读) → PROT;解保护:PROT → BUSY → mprotect(可写) → NONE。
|
||||
@@ -102,9 +103,25 @@ static void prep_write(void *addr, size_t len) {
|
||||
}
|
||||
}
|
||||
|
||||
// 跟踪粒度 = 系统页、但至少 16K。安卓页 4K:逐页解保护把池的映射切成只读 / 可写交错的碎段,每段一个 VMA,
|
||||
// 一局十几分钟累计十几万次缺页后进程撞上 vm.max_map_count(约 65530),之后任何 mprotect / mmap 都回 ENOMEM(MapMemory 建线程栈时中止)。
|
||||
// 16K 与苹果一致:碎段数降到四分之一,代价是同一 16K 内相邻贴图互相连坐(多一次重传,内容不会错)
|
||||
// Tracking granularity = the system page, but at least 16K. Android pages are 4K: unprotecting page by page cuts a pool's mapping into interleaved read-only / writable pieces, one VMA each;
|
||||
// after a dozen minutes of play and over a hundred thousand faults the process hits vm.max_map_count (about 65530), and from then on every mprotect / mmap returns ENOMEM (MapMemory aborts while creating a thread stack).
|
||||
// 16K matches Apple: the number of pieces drops to a quarter, at the cost of neighbouring textures within one 16K implicating each other (one more re-upload, never wrong content)
|
||||
static uintptr_t unit_size(void) { uintptr_t pg = (uintptr_t)getpagesize(); return pg < 0x4000 ? 0x4000 : pg; }
|
||||
#ifdef __ANDROID__
|
||||
int nvn_dirty_vma_count(void) { // /proc/self/maps 行数 = 进程 VMA 数(统计行用,几十毫秒级,别放热路径) | line count of /proc/self/maps = process VMA count (for the stats line; tens of ms, keep it off hot paths)
|
||||
FILE *f = fopen("/proc/self/maps", "r"); if (!f) return -1;
|
||||
char buf[65536]; size_t n; int lines = 0;
|
||||
while ((n = fread(buf, 1, sizeof buf, f)) > 0) for (size_t i = 0; i < n; i++) lines += buf[i] == '\n';
|
||||
fclose(f); return lines;
|
||||
}
|
||||
#endif
|
||||
|
||||
void nvn_dirty_add_range(const void *mem, size_t size) {
|
||||
static int inited;
|
||||
if (!inited) { inited = 1; g_pg = (uintptr_t)getpagesize(); g_shift = __builtin_ctzl(g_pg); mach_timebase_info(&g_tb); dm_fault_hook_register(on_fault); dm_guest_write_prep_register(prep_write); }
|
||||
if (!inited) { inited = 1; g_pg = unit_size(); g_shift = __builtin_ctzl(g_pg); mach_timebase_info(&g_tb); dm_fault_hook_register(on_fault); dm_guest_write_prep_register(prep_write); }
|
||||
atomic_fetch_add(&g_adds_total, 1);
|
||||
pthread_mutex_lock(&g_slot_mu);
|
||||
int n = atomic_load(&g_nr);
|
||||
|
||||
@@ -37,6 +37,9 @@ uint64_t mtl_sub_commit(void);
|
||||
|
||||
uint64_t mtl_last_fence(void); // 最近一次提交的栅栏值(0 = 从未提交) | Fence value of the most recent submit (0 = never submitted)
|
||||
int mtl_wait(uint64_t fence, uint64_t timeout_ns); // GPU 完成到 fence 返回 1,超时 0 | Returns 1 when the GPU has completed up to fence, 0 on timeout
|
||||
#ifdef __ANDROID__
|
||||
void mtl_queue_flush(void); // Submit deferred Vulkan work without waiting.
|
||||
#endif
|
||||
void mtl_finish(void); // 等所有已提交的命令完成 | Wait for all submitted commands to complete
|
||||
void mtl_drain(void); // 等队列上全部命令(含出图)完成:提交空命令缓冲并等它 | Wait for all commands on the queue (including presents) to complete: submit an empty command buffer and wait for it
|
||||
void mtl_xv_window_tex(uint64_t serial); // 登记窗口(交换链)贴图:跨提交有效性账本永不收它 | Register a window (swapchain) texture: the cross-submit validity ledger never collects it
|
||||
|
||||
+100
-25
@@ -273,7 +273,7 @@ void bf_want_note(const char *key) {
|
||||
|
||||
// ---------- 内存池 ----------
|
||||
// ---------- Memory pools ----------
|
||||
typedef struct { uintptr_t lo, hi; uintptr_t base; __unsafe_unretained id<MTLBuffer> buf; uint64_t gpu; const void *key; } pool_ent;
|
||||
typedef struct { uintptr_t lo, hi; uintptr_t base; __unsafe_unretained id<MTLBuffer> buf; uint64_t gpu; const void *key; int res; } pool_ent; // res:已放进驻留集(按需,见 pool_res) | res: already put in the residency set (on demand, see pool_res)
|
||||
static pool_ent *g_pools; static int g_npool, g_cap;
|
||||
static NSMutableArray *g_keep; // 持有缓冲引用(pool_ent 里是不持有的指针) | Holds the buffer references (pool_ent has non-owning pointers)
|
||||
static uint64_t g_pool_adds;
|
||||
@@ -407,16 +407,34 @@ uint64_t dm_mtl_l3_sample(uint32_t tick) {
|
||||
}
|
||||
|
||||
static _Atomic uint64_t g_reg_gen = 1; // 内存池 / 贴图 / 采样器登记的变更代号:参数缓冲复用以它为失效条件之一 | Change generation of memory pool / texture / sampler registration: one of the invalidation conditions for argument buffer reuse
|
||||
// 内存池按需驻留:零拷贝缓冲放进驻留集,iOS 会把整个池读进内存并钉成 wired(不计入 footprint,也不能被换出),游戏从没用过的池也一样——
|
||||
// 真机 17 Pro Max 实测 512 MB 的渲染目标池一局取址 0 次,放进驻留集整机 wired 高约 530 MB;A14 4 GB 机因此启动几秒就被系统按整机缺页结束(公开仓库 #37)。
|
||||
// 所以池建好时不放进驻留集,GPU 第一次经 mtl_addr / mtl_gpu_addr 取到它的地址时才放进去,并当场提交驻留集
|
||||
// (GPU 拿池地址只有这两个口子;当场提交 = 早于用到它的任何命令缓冲提交,不依赖各提交口自己调 res_commit)。调用方持 g_mu
|
||||
// On-demand residency of memory pools: putting a zero-copy buffer into the residency set makes iOS read the whole pool into memory and pin it as wired (not counted in footprint and never paged out), even a pool the game never uses -
|
||||
// measured on a 17 Pro Max: the 512 MB render-target pool is addressed 0 times in a run, and putting it into the residency set raises device wired memory by about 530 MB; this is why an A14 4 GB device was ended by the system for running out of memory within seconds of launch (public repository #37).
|
||||
// So a pool is not put into the residency set when created; it is put in, and the residency set committed on the spot, the first time the GPU gets its address through mtl_addr / mtl_gpu_addr
|
||||
// (these are the only two ways the GPU gets pool addresses; committing on the spot = earlier than any command buffer commit that uses it, without relying on each commit point calling res_commit). Caller holds g_mu
|
||||
static uint64_t g_cb_commits, g_pool_res_at; // 已提交的命令缓冲个数(主提交 + 上传);最近一次按需驻留时的这个数(0 = 没有待核的) | number of command buffers committed (main + upload); this number at the last on-demand residency (0 = nothing pending to check)
|
||||
static void pool_res(int i) {
|
||||
if (g_pools[i].res) return;
|
||||
res_add(g_pools[i].buf); res_commit(); g_pools[i].res = 1; g_pool_res_at = g_cb_commits + 1;
|
||||
MLOG("内存池按需驻留:%llu MB 的池第一次被取址,已放进驻留集并提交(此时已提交命令缓冲 %llu 个)",
|
||||
(unsigned long long)((g_pools[i].hi - g_pools[i].lo) >> 20), (unsigned long long)g_cb_commits);
|
||||
}
|
||||
static void cb_committed(void) { // 主提交 / 上传提交之后调:核「驻留集提交早于用到它的第一个命令缓冲提交」,每次按需驻留后记一行 | called after the main submission / upload submission: checks that "the residency set commit is earlier than the first command buffer commit that uses it", one line after each on-demand residency
|
||||
pthread_mutex_lock(&g_mu); uint64_t n = ++g_cb_commits, at = g_pool_res_at; if (at) g_pool_res_at = 0; pthread_mutex_unlock(&g_mu);
|
||||
if (at) MLOG("内存池按需驻留:其后第一个命令缓冲提交是第 %llu 个(驻留集在第 %llu 个之前已提交)", (unsigned long long)n, (unsigned long long)at);
|
||||
}
|
||||
void mtl_pool_add(const void *mem, uint64_t size) {
|
||||
mtl_init(); g_reg_gen++;
|
||||
uintptr_t pg = (uintptr_t)getpagesize(), lo = (uintptr_t)mem, hi = lo + size;
|
||||
uintptr_t a = lo & ~(pg - 1), b = (hi + pg - 1) & ~(pg - 1);
|
||||
id<MTLBuffer> buf = [g_dev newBufferWithBytesNoCopy:(void *)a length:b - a options:MTLResourceStorageModeShared deallocator:nil];
|
||||
if (!buf) MDIE("内存池 %p+%#llx 建零拷贝缓冲失败", mem, (unsigned long long)size);
|
||||
res_add(buf);
|
||||
pthread_mutex_lock(&g_mu);
|
||||
if (g_npool == g_cap) { g_cap = g_cap ? g_cap * 2 : 64; g_pools = realloc(g_pools, g_cap * sizeof *g_pools); }
|
||||
g_pools[g_npool++] = (pool_ent){lo, hi, a, buf, buf.gpuAddress, mem};
|
||||
g_pools[g_npool++] = (pool_ent){lo, hi, a, buf, buf.gpuAddress, mem, 0}; // 先不进驻留集:第一次被取址时才放进去(pool_res) | not in the residency set yet: put in the first time it is addressed (pool_res)
|
||||
g_pool_adds++;
|
||||
[g_keep addObject:buf];
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
@@ -437,7 +455,7 @@ int mtl_addr(uint64_t addr, uint64_t len, void **buf, uint64_t *off) {
|
||||
pthread_mutex_lock(&g_mu);
|
||||
for (int i = 0; i < g_npool; i++)
|
||||
if (addr >= g_pools[i].lo && addr + len <= g_pools[i].hi) {
|
||||
*buf = (__bridge void *)g_pools[i].buf; *off = addr - g_pools[i].base; ok = 1; break;
|
||||
pool_res(i); *buf = (__bridge void *)g_pools[i].buf; *off = addr - g_pools[i].base; ok = 1; break;
|
||||
}
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
return ok;
|
||||
@@ -447,7 +465,7 @@ int mtl_gpu_addr(uint64_t addr, uint64_t len, void **buf, uint64_t *off, uint64_
|
||||
pthread_mutex_lock(&g_mu);
|
||||
for (int i = 0; i < g_npool; i++)
|
||||
if (addr >= g_pools[i].lo && addr + len <= g_pools[i].hi) {
|
||||
*buf = (__bridge void *)g_pools[i].buf; *off = addr - g_pools[i].base; *gpu = g_pools[i].gpu + *off; ok = 1; break;
|
||||
pool_res(i); *buf = (__bridge void *)g_pools[i].buf; *off = addr - g_pools[i].base; *gpu = g_pools[i].gpu + *off; ok = 1; break;
|
||||
}
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
return ok;
|
||||
@@ -845,6 +863,7 @@ uint64_t mtl_sub_commit(void) {
|
||||
[g_q4 commit:buffers count:1 options:o];
|
||||
[g_q4 signalEvent:g_ev value:fence];
|
||||
#endif
|
||||
cb_committed();
|
||||
g_alloc_fence[g_alloc_cur] = fence;
|
||||
g_cb = nil;
|
||||
g_commit_blocks = nil;
|
||||
@@ -1137,6 +1156,7 @@ static void up_flush(void) {
|
||||
CBUF buffers[] = {cb};
|
||||
[g_q4 commit:buffers count:1 options:o];
|
||||
#endif
|
||||
cb_committed();
|
||||
g_up_cb = nil; if (g_up_block) { defer_obj_release(g_up_block); g_up_block = nil; } g_up_block_off = g_up_block_size = 0;
|
||||
for (id obj in g_up_keep) defer_obj_release(obj);
|
||||
[g_up_keep removeAllObjects];
|
||||
@@ -1827,10 +1847,34 @@ static void rp_end(void) { if (g_enc) {
|
||||
} }
|
||||
void pg_sub_begin_ext(uint64_t fence) { pg_sub_begin(fence); }
|
||||
void pg_commit_ext(id<MTLCommandBuffer> cb) { pg_commit(cb); }
|
||||
static void attach(MTLRenderPassAttachmentDescriptor *a, const tex_t *t, const view_t *v, int has_v) {
|
||||
a.texture = tex_mtl(t);
|
||||
// 颜色附件实际挂上的格式:视图换了格式且挂得上就是视图格式,否则底图格式(挂附件与管线预测共用,口径一致)。warn:挂不上时报红
|
||||
// The format a colour attachment is actually attached with: the view's format if the view changes the format and it can be attached, otherwise the base texture's format (shared by attaching and pipeline prediction, so both agree). warn: log red when it cannot be attached
|
||||
static MTLPixelFormat rt_color_fmt(id<MTLTexture> base, const view_t *v, int has_v, int warn) {
|
||||
if (!base || !has_v || !v->set_format) return base.pixelFormat;
|
||||
uint32_t pf = 0; uint8_t swz[4];
|
||||
if (!nvn_fmt_to_mtl(v->format, &pf, swz) || !pf) return base.pixelFormat;
|
||||
if (pf != (uint32_t)base.pixelFormat && tex_need_pfv(base.pixelFormat, (MTLPixelFormat)pf) && !(base.usage & MTLTextureUsagePixelFormatView)) {
|
||||
if (warn) RED_ONCE(48, "渲染目标视图格式 %#x 挂不上(底图 %lu 没有换格式用途),按底图格式画(首例)", v->format, (unsigned long)base.pixelFormat);
|
||||
return base.pixelFormat; }
|
||||
return (MTLPixelFormat)pf;
|
||||
}
|
||||
// color:颜色附件的视图换了格式(如 RGBA8 底图经 RGBA8_SRGB 视图写)就挂该格式的 Metal 视图——Switch 上写入与清除按视图格式编码,
|
||||
// 只挂底图则 sRGB 编码整个丢掉、画面偏暗(公开仓库 #36,seedds 在另一款游戏上实测);管线颜色格式取挂上的贴图格式(g_pass.cfmt),随之一致。
|
||||
// 视图只活到本次提交跑完(Metal 4 不持有资源;视图与底图同一份存储,不单独驻留)。深度 / 模板附件不换格式
|
||||
// color: when the view of a colour attachment changes the format (e.g. an RGBA8 base texture written through an RGBA8_SRGB view), attach a Metal view of that format - on the Switch writes and clears are encoded by the view's format,
|
||||
// and attaching only the base texture drops the sRGB encoding entirely, making the picture too dark (public repository #36, measured by seedds on another game); the pipeline colour formats take the attached texture's format (g_pass.cfmt), so they follow.
|
||||
// The view lives only until this submission completes (Metal 4 does not retain resources; the view shares storage with the base texture and is not made resident separately). Depth / stencil attachments do not change format
|
||||
static void attach(MTLRenderPassAttachmentDescriptor *a, const tex_t *t, const view_t *v, int has_v, int color) {
|
||||
id<MTLTexture> base = tex_mtl(t); a.texture = base;
|
||||
if (has_v && v->set_levels) a.level = v->base_level;
|
||||
if (has_v && v->set_layers) { if (t->d.target == 2) a.depthPlane = v->min_layer; else a.slice = v->min_layer; }
|
||||
if (!color || !base) return;
|
||||
MTLPixelFormat pf = rt_color_fmt(base, v, has_v, 1);
|
||||
if (pf == base.pixelFormat) return;
|
||||
id<MTLTexture> vw = [base newTextureViewWithPixelFormat:pf];
|
||||
if (!vw) { RED_ONCE(49, "渲染目标视图建不出:格式 %#x(底图 %lu),按底图格式画(首例)", v->format, (unsigned long)base.pixelFormat); return; }
|
||||
a.texture = vw; defer_obj_unref(vw);
|
||||
{ static int once; if (!once++) MLOG("渲染目标经换格式的视图挂上:视图格式 %#x,底图 %lu → 挂 %lu(首例)", v->format, (unsigned long)base.pixelFormat, (unsigned long)pf); }
|
||||
}
|
||||
// mode 1(clear_only):只为落地挂起的清除而开的通道,只挂有清除的附件;mode 2:前瞻证明本通道不用深度模板,不挂深度。
|
||||
// clear_only:只为落地挂起的清除而开的通道,只挂有清除的附件——其余附件本通道不碰,挂上去在 TBDR 上平白一读一写
|
||||
@@ -1855,7 +1899,7 @@ static RENC rp_begin_ex(int clear_only) {
|
||||
int any = 0;
|
||||
for (int i = 0; i < R.rt.n; i++) {
|
||||
if (!R.rt.color[i] || (clear_only == 1 && !R.clear_c[i])) continue;
|
||||
attach(pd.colorAttachments[i], R.rt.color[i], &R.rt.cview[i], R.rt.has_cview[i]);
|
||||
attach(pd.colorAttachments[i], R.rt.color[i], &R.rt.cview[i], R.rt.has_cview[i], 1);
|
||||
if (!pd.colorAttachments[i].texture) continue;
|
||||
any = 1;
|
||||
pd.colorAttachments[i].loadAction = R.clear_c[i] ? MTLLoadActionClear : MTLLoadActionLoad;
|
||||
@@ -1880,14 +1924,14 @@ static RENC rp_begin_ex(int clear_only) {
|
||||
// clear_only:0 全挂 1 只为清除 2 深度模板都不挂 3 只挂模板 4 只挂深度(3 / 4 由 pass_ds_need 前瞻证明整通道只用那一项)
|
||||
// clear_only: 0 attach all 1 only for clears 2 neither depth nor stencil attached 3 stencil only 4 depth only (3 / 4: the pass_ds_need lookahead proves the whole pass uses only that one)
|
||||
if (R.rt.depth && clear_only == 3) { // 只挂模板:合一格式的深度平面不进 tile、不读不写(Metal 允许深度附件空、模板附件挂合一贴图) | Stencil only: the depth plane of the combined format does not enter the tile and is neither read nor written (Metal allows an empty depth attachment with the combined texture on the stencil attachment)
|
||||
attach(pd.stencilAttachment, R.rt.depth, &R.rt.dview, R.rt.has_dview);
|
||||
attach(pd.stencilAttachment, R.rt.depth, &R.rt.dview, R.rt.has_dview, 0);
|
||||
MTLPixelFormat pf = pd.stencilAttachment.texture.pixelFormat;
|
||||
if (pf == MTLPixelFormatDepth32Float_Stencil8 || pf == MTLPixelFormatStencil8) {
|
||||
any = 1; pd.stencilAttachment.loadAction = R.clear_s ? MTLLoadActionClear : MTLLoadActionLoad;
|
||||
pd.stencilAttachment.clearStencil = R.cs; pd.stencilAttachment.storeAction = MTLStoreActionStore;
|
||||
} else pd.stencilAttachment.texture = nil; // 没有模板平面:模板测试恒过,什么都不挂 | No stencil plane: the stencil test always passes, attach nothing
|
||||
} else if (R.rt.depth && clear_only != 2 && !(clear_only == 1 && !R.clear_d && !R.clear_s)) {
|
||||
attach(pd.depthAttachment, R.rt.depth, &R.rt.dview, R.rt.has_dview);
|
||||
attach(pd.depthAttachment, R.rt.depth, &R.rt.dview, R.rt.has_dview, 0);
|
||||
if (pd.depthAttachment.texture) {
|
||||
any = 1;
|
||||
pd.depthAttachment.loadAction = R.clear_d ? MTLLoadActionClear : MTLLoadActionLoad;
|
||||
@@ -2061,7 +2105,7 @@ static void shmap_load(void) {
|
||||
// Warm-up entry: built in the background, waiting to be taken by the submit thread. vs / fs are strong references (in pso they are only raw pointers, and the background dictionary is released when the task ends)
|
||||
@interface WarmItem : NSObject { @public int kind; NSString *key, *vs_key, *fs_key; NvShader *shader, *vs, *fs; pso_key pso; id<MTLFunction> fsfn; id object; } @end
|
||||
@implementation WarmItem @end
|
||||
static NSMutableDictionary<NSString *, NvShader *> *g_shcache;
|
||||
static NSMutableDictionary<NSString *, NvShader *> *g_shcache; static _Atomic uint32_t g_shcache_n; // 表只在提交线程上读写;条数另记一份原子数给别的线程读(资源计数) | The tables are read and written only on the submit thread; a separate atomic count is kept for other threads to read (resource counts)
|
||||
|
||||
static void c1_store(NvShader *o) {
|
||||
size_t len = o->rf.c1_len;
|
||||
@@ -2242,7 +2286,7 @@ static NvShader *shader_get(NSString *pc, int stage) {
|
||||
if (o) return o;
|
||||
uint64_t bt = bp_now(); o = shader_load(pc, stage);
|
||||
if (!o) return nil;
|
||||
g_shcache[pc] = o;
|
||||
g_shcache[pc] = o; atomic_fetch_add(&g_shcache_n, 1);
|
||||
pso_record("S\t%s\t%d\n", pc.UTF8String, stage);
|
||||
pso_user_record("S\t%s\t%d\n", pc.UTF8String, stage);
|
||||
g_bp_lib_n++; g_bp_lib_ns += bp_now() - bt;
|
||||
@@ -3283,7 +3327,7 @@ static void pso_predict_rest(void) {
|
||||
if (!fz_next(&cur, &q, &hq, &aq)) break;
|
||||
if (hq.op == OP_SET_RT) {
|
||||
const p_set_rt *r = aq; memset(cf, 0, sizeof cf); dfull = sfull = 0; samples = 1;
|
||||
for (int i = 0; i < r->n && i < 8; i++) { id<MTLTexture> t = r->color[i] ? tex_mtl(r->color[i]) : nil; if (t) { cf[i] = (uint32_t)t.pixelFormat; samples = (uint32_t)t.sampleCount; } }
|
||||
for (int i = 0; i < r->n && i < 8; i++) { id<MTLTexture> t = r->color[i] ? tex_mtl(r->color[i]) : nil; if (t) { cf[i] = (uint32_t)rt_color_fmt(t, &r->cview[i], r->has_cview[i], 0); samples = (uint32_t)t.sampleCount; } }
|
||||
id<MTLTexture> dt = r->depth ? tex_mtl(r->depth) : nil;
|
||||
if (dt) { MTLPixelFormat f = dt.pixelFormat; samples = (uint32_t)dt.sampleCount;
|
||||
dfull = f != MTLPixelFormatStencil8 ? (uint32_t)f : 0; sfull = (f == MTLPixelFormatStencil8 || f == MTLPixelFormatDepth32Float_Stencil8) ? (uint32_t)f : 0; }
|
||||
@@ -4472,7 +4516,7 @@ static void draw(const p_draw *dw, const p_draw_idx *di) {
|
||||
if (!strncmp(f->key, "ebcfcd1fa0a77dbc", 16) && !g_enc && R.rt.n == 1 && R.rt.color[0] && !R.clear_c[0]) {
|
||||
uint64_t h = 0; for (int i = 0; i < f->rf.nb && !h; i++) if (f->rf.b[i].kind == NVN_RB_TEX && f->rf.b[i].reg < 128) h = S.tex[1][f->rf.b[i].reg];
|
||||
if (h) { fx_from = R.rt.color[0]->serial; fx_to = h; PD("N %llu 跳过 FXAA:ser=%llu 的读者改读 ser=%llu", g_stat_pass, (unsigned long long)fx_from, (unsigned long long)h_ser(h)); return; } }
|
||||
else if (fx_from && !strncmp(f->key, "52aac1f2306b8fc5", 16)) { for (int r = 0; r < 128; r++) if (S.tex[1][r] && h_ser(S.tex[1][r]) == fx_from) S.tex[1][r] = fx_to; fx_from = 0; } } }
|
||||
else if (fx_from && !strncmp(f->key, "52aac1f2306b8fc5", 16)) { for (int r = 0; r < 128; r++) if (S.tex[1][r] && h_ser(S.tex[1][r]) == fx_from) { S.tex[1][r] = fx_to; g_args_dirty[1] = 1; } fx_from = 0; } } }
|
||||
{ static uint64_t bloomq_frame; if (bloomq_frame != atomic_load(&g_cur_frame)) { bloomq_frame = atomic_load(&g_cur_frame); bloomq_reset(); }
|
||||
if (bloomq_enabled() && tbdr_on() && !g_defer_replaying && pr->sh[1]) {
|
||||
NvShader *f = pr->sh[1]; uint64_t tgt = 0; int lv, sl;
|
||||
@@ -4501,14 +4545,14 @@ static void draw(const p_draw *dw, const p_draw_idx *di) {
|
||||
} else if (g_bloomq.state == 2 && !strncmp(f->key, "cc264583f2000c81", 16)) {
|
||||
if (bloomq_target(&tgt, &lv, &sl) && tgt == g_bloomq.b0_ser) { g_bloomq.state = 3; PD("C %llu 泛光 1/4 跳过 B0 上采样", g_stat_pass); return; }
|
||||
} else if (g_bloomq.state == 3 && !strncmp(f->key, "2e2d6700a2569795", 16)) {
|
||||
if (g_bloomq.b1_h) { for (int r = 0; r < 128; r++) if (S.tex[1][r] && h_ser(S.tex[1][r]) == g_bloomq.b0_ser) S.tex[1][r] = g_bloomq.b1_h; PD("D %llu 泛光 1/4 叠加改读 B1", g_stat_pass); g_bloomq_last_b0 = g_bloomq.b0_ser; g_bloomq_last_b1h = g_bloomq.b1_h; g_bloomq_last_b1s = g_bloomq.b1_ser; bloomq_reset(); }
|
||||
if (g_bloomq.b1_h) { for (int r = 0; r < 128; r++) if (S.tex[1][r] && h_ser(S.tex[1][r]) == g_bloomq.b0_ser) { S.tex[1][r] = g_bloomq.b1_h; g_args_dirty[1] = 1; } PD("D %llu 泛光 1/4 叠加改读 B1", g_stat_pass); g_bloomq_last_b0 = g_bloomq.b0_ser; g_bloomq_last_b1h = g_bloomq.b1_h; g_bloomq_last_b1s = g_bloomq.b1_ser; bloomq_reset(); }
|
||||
else { RED_ONCE(63, "泛光 1/4 状态缺少 B1 句柄"); bloomq_reset(); }
|
||||
} else if (!g_bloomq.state && g_bloomq_last_b1h && h_ser(g_bloomq_last_b1h) == g_bloomq_last_b1s && !strncmp(f->key, "2e2d6700a2569795", 16)) { // B1 句柄仍指同一张贴图(换分辨率重建后不认) | The B1 handle still points to the same texture (not recognized after a rebuild on resolution change)
|
||||
// 本帧泛光链没跑(运行时外推的外推帧跳过了它:输入 469 区域外是上一帧 LDR,不能跑)就到了泛光叠加:照最近一次改读 B1,叠上一帧的泛光。
|
||||
// 不改读就读 B0——开了泛光 1/4 的话 B0 的上采样一直被跳过、从没写过,读到的是未初始化显存(M4 Pro 上区域里的单位整个发绿,别处多半是 0、缺泛光)
|
||||
// The bloom overlay is reached without the bloom chain having run this frame (the extrapolated frame of runtime extrapolation skipped it: outside the region the input 469 is the previous frame's LDR, so it cannot run): redirect the read to B1 as last time, overlaying the previous frame's bloom.
|
||||
// Without the redirect it would read B0 -- with bloom 1/4 on, B0's upsample is always skipped and never written, so what is read is uninitialized video memory (on M4 Pro the units in the region turn entirely green; elsewhere it is mostly 0, i.e. missing bloom)
|
||||
int hit = 0; for (int r = 0; r < 128; r++) if (S.tex[1][r] && h_ser(S.tex[1][r]) == g_bloomq_last_b0) { S.tex[1][r] = g_bloomq_last_b1h; hit = 1; }
|
||||
int hit = 0; for (int r = 0; r < 128; r++) if (S.tex[1][r] && h_ser(S.tex[1][r]) == g_bloomq_last_b0) { S.tex[1][r] = g_bloomq_last_b1h; hit = 1; g_args_dirty[1] = 1; }
|
||||
if (hit) { PD("D %llu 泛光链没跑:叠加沿用上一帧 B1", g_stat_pass); static uint64_t n; if (n++ % 600 == 0) MLOG("泛光 1/4:泛光链没跑的帧叠加沿用上一帧 B1(第 %llu 次)", (unsigned long long)n); }
|
||||
} else if (g_bloomq.state) { RED_ONCE(61, "泛光 1/4 起点:链中途出现别的绘制,本帧泛光不完整"); bloomq_reset(); }
|
||||
}
|
||||
@@ -4707,17 +4751,17 @@ static void warm_claim(void) {
|
||||
for (WarmItem *item in items) {
|
||||
if (item->kind == 0) {
|
||||
if (!g_shcache) g_shcache = [NSMutableDictionary dictionary];
|
||||
if (!g_shcache[item->key]) { g_shcache[item->key] = item->shader; g_warm_claim_shaders++; }
|
||||
if (!g_shcache[item->key]) { g_shcache[item->key] = item->shader; atomic_fetch_add(&g_shcache_n, 1); g_warm_claim_shaders++; }
|
||||
} else if (item->kind == 1) {
|
||||
if (!g_shcache) g_shcache = [NSMutableDictionary dictionary];
|
||||
NvShader *vs = g_shcache[item->vs_key], *fs = item->fs_key.length ? g_shcache[item->fs_key] : nil;
|
||||
if (!vs) { vs = item->vs; g_shcache[item->vs_key] = vs; }
|
||||
if (item->fs_key.length && !fs) { fs = item->fs; g_shcache[item->fs_key] = fs; }
|
||||
if (!vs) { vs = item->vs; g_shcache[item->vs_key] = vs; atomic_fetch_add(&g_shcache_n, 1); }
|
||||
if (item->fs_key.length && !fs) { fs = item->fs; g_shcache[item->fs_key] = fs; atomic_fetch_add(&g_shcache_n, 1); }
|
||||
item->pso.vs = (__bridge void *)vs; item->pso.fs = (__bridge void *)fs;
|
||||
if (!hm_get_id(&g_pso, &item->pso)) { hm_put_id(&g_pso, &item->pso, item->object); g_warm_claim_rps++; }
|
||||
} else {
|
||||
NvShader *cs = g_shcache[item->key];
|
||||
if (!cs) { cs = item->shader; if (!g_shcache) g_shcache = [NSMutableDictionary dictionary]; g_shcache[item->key] = cs; }
|
||||
if (!cs) { cs = item->shader; if (!g_shcache) g_shcache = [NSMutableDictionary dictionary]; g_shcache[item->key] = cs; atomic_fetch_add(&g_shcache_n, 1); }
|
||||
const void *key = (__bridge const void *)cs;
|
||||
if (!hm_get_id(&g_cps, &key)) { hm_put_id(&g_cps, &key, item->object); g_warm_claim_cps++; }
|
||||
}
|
||||
@@ -4844,6 +4888,7 @@ static void copy_t2b(const p_copy_b2t *c) {
|
||||
// CPU 读贴图(ReadTexels):预排布贴图以池内存为真值,解排布直读;其余从 MTLTexture blit 读回(调用方已按 NVN 规矩等过 GPU)
|
||||
// CPU texture read (ReadTexels): for packaged textures the pool memory is the ground truth, de-layout and read directly; the rest are read back from the MTLTexture by blit (the caller has already waited for the GPU per NVN rules)
|
||||
void mtl_read_texels(const tex_t *t, unsigned level, unsigned layer0, const NVNcopyRegion *r, uint8_t *dst, size_t row, size_t img) {
|
||||
if (!on_sub_thread()) while (atomic_load(&g_up_pending)) usleep(200); // 翻译在翻译线程:调用方已排空队列(批已随提交冲刷),这里只等上传在 GPU 上做完(提交线程上由 q_cb 冲刷并等) | Translation runs on the translation thread: the caller has already drained the queue (batches were flushed with the submit), so here we only wait for uploads to finish on the GPU (on the submit thread q_cb flushes and waits)
|
||||
xv_check(t->serial, level, layer0, "CPU读回");
|
||||
PD("U cpu_read ser=%llu lv%u sl%u xyz=%d,%d,%d size=%d,%d,%d dst=%p row=%lu img=%lu", t->serial, level, layer0, r->xoffset, r->yoffset, r->zoffset, r->width, r->height, r->depth, dst, (unsigned long)row, (unsigned long)img);
|
||||
int bw, bh, bpb = nvn_fmt_bpb(t->d.format, &bw, &bh);
|
||||
@@ -5062,7 +5107,13 @@ static const char *cctx_snap(void) {
|
||||
// State constants / buffer updates / events / counters / texture uploads execute as usual (the UI pass needs them, the game is waiting).
|
||||
int g_frz_on = -1;
|
||||
static int g_frz_phase = 2, g_frz_drop, g_frz_seen_ds; static uint64_t g_frz_full_n, g_frz_skip_n;
|
||||
void mtl_world_frozen(int on) { g_frz_on = on != 0; }
|
||||
// 宿主在游戏线程上写的两个画法开关(冻结位、强制全画)先记成请求,提交入队时锁存进任务(mtl_host_latch),翻译线程执行那次提交前生效(mtl_host_apply):
|
||||
// 生效时机与同步翻译时一样落在两次提交之间,不会在翻译途中翻转(回放每条操作都读冻结位;强制全画计数回放里自减,宿主直接写会丢)
|
||||
// The two drawing switches the host writes on the game thread (freeze bit, force full draw) are first recorded as requests, latched into the job when the submit is enqueued (mtl_host_latch), and take effect before the translation thread runs that submit (mtl_host_apply):
|
||||
// they take effect between two submits just as with synchronous translation and never flip in the middle of translation (replay reads the freeze bit for every operation; the force-full-draw counter is decremented in replay, and a direct write by the host would lose one)
|
||||
static _Atomic int g_frz_req = -1, g_force_req;
|
||||
void mtl_world_frozen(int on) { atomic_store(&g_frz_req, on != 0); }
|
||||
uint64_t mtl_host_latch(void) { return (uint64_t)(uint32_t)(atomic_load(&g_frz_req) + 1) | (uint64_t)(uint32_t)atomic_exchange(&g_force_req, 0) << 32; }
|
||||
static int frz_wanted(void) { if (g_frz_on < 0) { const char *e = getenv("DM_NVN_TEST_FRZ"); g_frz_on = e && atoi(e); if (g_frz_on) MLOG("DM_NVN_TEST_FRZ:世界冻结状态位由测试开关顶替(常开)"); } tbdr_on(); return g_frz_on > 0 && tbdr_on() && g_ruler_truth <= 0; }
|
||||
// ---------- 运行时外推(省电画法;不给玩家开关;线上出过卡顿缺陷,现缺省关,A17 上有不卡的证据再开)----------
|
||||
// 3D 隔帧:全画帧照常画,并在附件被挪作他用之前拷下不透明 HDR(468)、主深度模板、色调映射后的 468、FXAA 后的 469;
|
||||
@@ -5091,7 +5142,8 @@ static struct { int env, frame, filt, first, hdrp, mainp_seen, skipall, oit_seen
|
||||
static int rt_want(void);
|
||||
static void rt_toggle_poll(void) { static int tg = -1; if (tg < 0) { const char *e = getenv("DM_RT_AB_TOGGLE"); tg = e ? atoi(e) : 0; (void)rt_want(); } // 首次顺带读 DM_RT_AB(真机上世界冻结位早早置 0,frz_op 不一定被调到) // 测试:每 tg 秒按墙钟在 A / B 之间来回切 | On first call also read DM_RT_AB (on a real device the world-freeze bit is set to 0 very early, so frz_op is not necessarily called) // test: switch back and forth between A / B every tg seconds by wall clock
|
||||
if (tg > 0) { int v = (int)((time(NULL) / tg) & 1); if (v != g_dm_rt_ab) { g_dm_rt_ab = v; MLOG("DM_RT_AB_TOGGLE:画法切到 %s", v ? "B" : "A"); } } }
|
||||
void mtl_rt_force_full(int n) { g_rt.force_full = n; } // 宿主调:要换 3D 渲染比例等画面整体变化前,之后 n 帧一律全画 | Called by the host: before an overall picture change such as switching the 3D render scale, the following n frames are all fully drawn
|
||||
void mtl_rt_force_full(int n) { atomic_store(&g_force_req, n); } // 宿主调:要换 3D 渲染比例等画面整体变化前,之后 n 帧一律全画(随下一次提交生效) | Called by the host: before a change to the whole picture such as switching the 3D render scale, draw everything for the next n frames (takes effect with the next submit)
|
||||
void mtl_host_apply(uint64_t v) { int frz = (int)(uint32_t)v - 1, force = (int)(v >> 32); if (frz >= 0) g_frz_on = frz; if (force) g_rt.force_full = force; }
|
||||
// ---------- 省电模式(30 帧)----------
|
||||
// 开:显示节拍对象改 30 Hz(帧率范围 30–30,ProMotion 屏跟着降刷新率;front_ios.m 的帧率提示一起降),游戏每拍出一帧;运行时外推关(每帧真画)。
|
||||
// 游戏逻辑本来就按 25 拍 / 秒走、单位位置按时间插值,30 帧下没有重复帧(真机实测:每帧镜头位移的变异系数 30 帧 0.292、60 帧 0.296)。
|
||||
@@ -5358,7 +5410,7 @@ void mtl_res_snapshot(mtl_res_count *out) {
|
||||
out->pso = g_pso.n;
|
||||
out->cps = g_cps.n;
|
||||
out->dss = g_dss.n;
|
||||
out->shaders = (uint32_t)(g_shcache ? g_shcache.count : 0);
|
||||
out->shaders = atomic_load(&g_shcache_n); // 资源计数在宿主线程上取,回放在翻译线程上改表 | Resource counts are taken on the host thread while replay changes the tables on the translation thread
|
||||
os_unfair_lock_lock(&g_c1_lock);
|
||||
out->c1_bufs = (uint32_t)(g_c1_banks.count + g_c1_exclusive); out->c1_alloc = g_c1_alloc_bytes; out->c1_data = g_c1_data_bytes;
|
||||
os_unfair_lock_unlock(&g_c1_lock);
|
||||
@@ -5678,9 +5730,31 @@ static void present_pipeline(MTLPixelFormat format) {
|
||||
g_blit_samp = [g_dev newSamplerStateWithDescriptor:sd];
|
||||
}
|
||||
}
|
||||
// 呈现采样的源:交换链贴图是 sRGB 格式(游戏把交换链建成 RGBA8_SRGB)时经它的非 sRGB 视图采样,屏上显示存的字节,与 Switch 扫描输出一致;
|
||||
// 直接采样会先解成线性,呈现层(BGRA8Unorm)不再编码,整幅偏暗(公开仓库 #36)。截图读的是原始字节,看不出这一处。
|
||||
// 视图按源贴图缓存 4 张、换掉最久没用的:呈现走自己的队列,不能挂主提交的延迟释放;同时在跑的呈现最多 3 帧,被换掉的那张已经用完
|
||||
// Source for presentation sampling: when the swapchain texture has an sRGB format (the game created the swapchain as RGBA8_SRGB), sample through its non-sRGB view so the screen shows the stored bytes, as the Switch's scan-out does;
|
||||
// sampling it directly decodes to linear first, and the present layer (BGRA8Unorm) does not encode again, so the whole picture is too dark (public repository #36). Screenshots read the raw bytes and cannot see this.
|
||||
// Views are cached per source texture, 4 of them, replacing the least recently used: presentation runs on its own queue and cannot use the deferred release of the main submission; at most 3 presents are in flight, so the replaced one is already done
|
||||
static id<MTLTexture> present_src(id<MTLTexture> src) {
|
||||
MTLPixelFormat raw = MTLPixelFormatInvalid;
|
||||
for (size_t i = 0; i < sizeof g_pfv_srgb / sizeof *g_pfv_srgb; i++) if (src.pixelFormat == g_pfv_srgb[i].b) raw = g_pfv_srgb[i].a;
|
||||
if (raw == MTLPixelFormatInvalid) return src;
|
||||
static pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER; static id<MTLTexture> cs[4], cv[4]; static uint64_t used[4], tick;
|
||||
pthread_mutex_lock(&mu);
|
||||
int k = -1, old = 0;
|
||||
for (int i = 0; i < 4; i++) { if (cs[i] == src) k = i; if (used[i] < used[old]) old = i; }
|
||||
if (k < 0) { k = old; cs[k] = src; cv[k] = [src newTextureViewWithPixelFormat:raw];
|
||||
if (!cv[k]) RED_ONCE(50, "出图:sRGB 交换链贴图(格式 %lu)的非 sRGB 视图建不出,直接采样(画面会偏暗,首例)", (unsigned long)src.pixelFormat);
|
||||
else MLOG("出图:交换链贴图是 sRGB 格式 %lu,经格式 %lu 的视图采样", (unsigned long)src.pixelFormat, (unsigned long)raw); }
|
||||
used[k] = ++tick; id<MTLTexture> v = cv[k] ?: src;
|
||||
pthread_mutex_unlock(&mu);
|
||||
return v;
|
||||
}
|
||||
// 出图仅采NVN声明的有效源矩形;与原始交换链读回截图分开。边缘钳到有效区纹素中心,双线性不读外侧黑纹素。
|
||||
// Present samples only the valid source rectangle declared by NVN; kept separate from the raw swapchain readback screenshot. Edges are clamped to the texel centers of the valid area, so bilinear does not read the black texels outside.
|
||||
static int present_encode(id<MTLCommandBuffer> cb, id<MTLTexture> src, id<MTLTexture> dst, const int crop[4]) {
|
||||
static int present_encode(id<MTLCommandBuffer> cb, id<MTLTexture> src0, id<MTLTexture> dst, const int crop[4]) {
|
||||
id<MTLTexture> src = present_src(src0);
|
||||
NSUInteger cx = 0, cy = 0, cw = src.width, ch = src.height;
|
||||
if (crop && (crop[2] || crop[3])) {
|
||||
if (crop[0] < 0 || crop[1] < 0 || crop[2] <= 0 || crop[3] <= 0 ||
|
||||
@@ -5719,7 +5793,8 @@ static int present_encode(id<MTLCommandBuffer> cb, id<MTLTexture> src, id<MTLTex
|
||||
[en endEncoding];
|
||||
return 1;
|
||||
}
|
||||
static int present_encode_m4(CBUF cb, id<MTLTexture> src, id<MTLTexture> dst, const int crop[4], int uv_i) {
|
||||
static int present_encode_m4(CBUF cb, id<MTLTexture> src0, id<MTLTexture> dst, const int crop[4], int uv_i) {
|
||||
id<MTLTexture> src = present_src(src0);
|
||||
NSUInteger cx = 0, cy = 0, cw = src.width, ch = src.height;
|
||||
if (crop && (crop[2] || crop[3])) {
|
||||
if (crop[0] < 0 || crop[1] < 0 || crop[2] <= 0 || crop[3] <= 0 ||
|
||||
|
||||
+11
-4
@@ -33,6 +33,7 @@ typedef struct {
|
||||
typedef struct {
|
||||
uint32_t magic; nvn_texdesc d; nvn_texlayout L; uint8_t *mem; pool_t *pool; int64_t off; uint8_t has_layout, layout[8];
|
||||
uint64_t serial; // 初始化序号:回放层按它在宿主表里找 MTLTexture(游戏可能按值拷贝对象,不能存对象指针) | Initialization serial: the replay layer uses it to find the MTLTexture in the host table (the game may copy the object by value, so object pointers cannot be stored)
|
||||
const void *snap; // 本序号的不可变副本(hle_nvn.c snap_tex):命令载荷存它,不存游戏对象地址 | This serial's immutable snapshot (hle_nvn.c snap_tex): command payloads store it, not the game object's address
|
||||
} tex_t; FITS(tex_t, NVNtexture);
|
||||
typedef struct { uint8_t set_levels, set_layers, set_format, set_target; int32_t base_level, nlevels, min_layer, nlayers, format, target; } view_t;
|
||||
FITS(view_t, NVNtextureView);
|
||||
@@ -43,7 +44,7 @@ typedef struct { uint8_t minf, magf, ws, wt, wr, cmp_mode, cmp_func; float lod_m
|
||||
typedef struct { NVNdevice *dev; samp_par p; } samp_builder_t; FITS(samp_builder_t, NVNsamplerBuilder);
|
||||
typedef struct { uint32_t magic; samp_par p; } samp_t; FITS(samp_t, NVNsampler);
|
||||
|
||||
typedef struct { uint32_t magic, nstage; NVNshaderData sd[6]; uint64_t serial; } prog_t; FITS(prog_t, NVNprogram); // serial:回放层解析结果的表键 | serial: table key for the replay layer's resolved result
|
||||
typedef struct { uint32_t magic, nstage; NVNshaderData sd[6]; uint64_t serial; const void *snap; } prog_t; FITS(prog_t, NVNprogram); // serial:回放层解析结果的表键;snap:本序号的不可变副本(同 tex_t) | serial: table key for the replay layer's resolved results; snap: this serial's immutable snapshot (same as tex_t)
|
||||
|
||||
typedef struct { uint32_t magic, fenced; uint64_t fence; } sync_t; FITS(sync_t, NVNsync);
|
||||
typedef struct { const pool_t *pool; int64_t off; } ev_builder_t; FITS(ev_builder_t, NVNeventBuilder);
|
||||
@@ -92,10 +93,10 @@ enum {
|
||||
OP_BIND_PROGRAM, OP_BIND_STATE, OP_BIND_VATTR, OP_BIND_VSTREAM, OP_BIND_VBUF,
|
||||
OP_BIND_UBO, OP_BIND_SSBO, OP_BIND_TEX, OP_BIND_SAMP,
|
||||
OP_STENCIL, OP_POLY_OFFSET, OP_DRAW, OP_DRAW_IDX, OP_DISPATCH, OP_BARRIER,
|
||||
OP_SET_TEX_POOL, OP_SET_SAMP_POOL, OP_COPY_B2T, OP_COPY_STRIDE, OP_BLEND_COLOR, OP_COPY_T2B, OP_BIND_IMG, OP_COPY_T2T, OP_RESET_COUNTER, OP_CLEAR_TEX, OP_COUNT_
|
||||
OP_SET_TEX_POOL, OP_SET_SAMP_POOL, OP_COPY_B2T, OP_COPY_STRIDE, OP_BLEND_COLOR, OP_COPY_T2B, OP_BIND_IMG, OP_COPY_T2T, OP_RESET_COUNTER, OP_CLEAR_TEX, OP_SHADER_SCRATCH, OP_WAIT_SYNC, OP_FENCE_SYNC, OP_WAIT_EVENT, OP_COUNT_
|
||||
};
|
||||
// 载荷(紧跟 op_hdr)
|
||||
// Payload (immediately follows op_hdr)
|
||||
// 载荷(紧跟 op_hdr)。贴图 / 程序指针都指向录制时按序号留下的不可变副本(snap_tex / snap_prog),游戏之后改写或重建对象不影响已录的命令
|
||||
// Payload (right after op_hdr). Texture / program pointers point to the immutable snapshots kept by serial at record time (snap_tex / snap_prog); later rewrites or rebuilds of the object by the game do not affect recorded commands
|
||||
typedef struct { int32_t n; const tex_t *color[8]; view_t cview[8]; uint8_t has_cview[8]; const tex_t *depth; view_t dview; uint8_t has_dview; } p_set_rt;
|
||||
typedef struct { int32_t index, mask; float rgba[4]; } p_clear_color;
|
||||
typedef struct { float depth; int32_t depth_mask, stencil, stencil_mask; } p_clear_ds;
|
||||
@@ -120,6 +121,7 @@ typedef struct { const tex_t *src, *dst; view_t sv, dv; uint8_t has_sv, has_dv;
|
||||
typedef struct { const tex_t *tex; view_t view; uint8_t has_view, is_uint; NVNcopyRegion r; int32_t mask; union { float f[4]; uint32_t u[4]; } c; } p_clear_tex;
|
||||
typedef struct { int64_t stride; } p_copy_stride;
|
||||
typedef struct { float rgba[4]; } p_blend_color;
|
||||
typedef struct { sync_t *sync; int32_t condition, flags; } p_sync; // OP_WAIT_SYNC / OP_FENCE_SYNC(仅 Android 录制) | OP_WAIT_SYNC / OP_FENCE_SYNC (recorded on Android only)
|
||||
|
||||
// Metal 回放层入口(nvn_mtl.m):把一组命令句柄回放进当前提交
|
||||
// Entry point of the Metal replay layer (nvn_mtl.m): replays a set of command handles into the current submission
|
||||
@@ -136,6 +138,8 @@ void mtl_set_tex_pool_n(int n); // 贴图描述符池
|
||||
// 计时埋点(Mac / iOS 共用):提交按帧号打标;GPU 时间 = 该帧全部命令缓冲 GPUEnd−GPUStart 之和,全部完成后才可读(否则 −1)
|
||||
// Timing instrumentation (shared by Mac / iOS): submissions are tagged with the frame number; GPU time = sum of GPUEnd−GPUStart over all of that frame's command buffers, readable only after all complete (otherwise −1)
|
||||
void mtl_set_frame(uint64_t f);
|
||||
uint64_t mtl_host_latch(void); // 游戏线程提交入队时锁存宿主写的画法开关(冻结位 / 强制全画),随任务带到翻译线程 | When the game thread enqueues a submit it latches the host-written drawing switches (freeze bit / force full draw), carried with the job to the translation thread
|
||||
void mtl_host_apply(uint64_t v); // 翻译线程执行那次提交前生效 | Takes effect before the translation thread runs that submit
|
||||
void mtl_ub_present(double iv_ms); // 同进程交替测量(DM_NVN_UB):出图线程每帧报实际上屏间隔 | Same-process alternating measurement (DM_NVN_UB): the present thread reports the actual present interval every frame
|
||||
double mtl_gpu_ms(uint64_t f);
|
||||
void mtl_sub_index(const uint64_t *h, int n); // 提交开始:按回放顺序建写回前瞻索引(nvn_mtl.m) | Start of submission: build the store lookahead index in replay order (nvn_mtl.m)
|
||||
@@ -171,6 +175,9 @@ void mtl_read_texels(const tex_t *t, unsigned level, unsigned layer0, const NVNc
|
||||
void mtl_reg_tex(int id, const tex_t *t, const view_t *v);
|
||||
void mtl_reg_samp(int id, const samp_par *p);
|
||||
void mtl_prog_release(prog_t *p);
|
||||
#ifdef __ANDROID__
|
||||
void mtl_set_window_origin_mode(int mode);
|
||||
#endif
|
||||
// 新序号(> 0,全局递增)
|
||||
// New serial (> 0, globally increasing)
|
||||
uint64_t nvn_new_serial(void);
|
||||
|
||||
@@ -43,3 +43,5 @@ t_xv
|
||||
t_xv.dSYM/
|
||||
t_ub
|
||||
t_ub.dSYM/
|
||||
t_rt_srgb_view
|
||||
t_rt_srgb_view.dSYM/
|
||||
|
||||
@@ -28,6 +28,8 @@ t_pace: t_pace.c ../nvn/nvn_pace.h
|
||||
clang -O1 -Wall -o $@ t_pace.c
|
||||
t_fuse_check: t_fuse_check.m ../../host/crash.c $(GFX) $(GFX_H)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_fuse_check.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m ../nvn/nvn_entry.S ../nvn/nvn_thunks.S,$(GFX)) $(FW)
|
||||
t_rt_srgb_view: t_rt_srgb_view.m ../../host/crash.c $(GFX) $(GFX_H)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_rt_srgb_view.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m ../nvn/nvn_entry.S ../nvn/nvn_thunks.S,$(GFX)) $(FW)
|
||||
t_present_crop: t_present_crop.m ../nvn/hle_nvn.c ../../host/crash.c $(GFX) $(GFX_H)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_present_crop.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m,$(GFX)) $(FW)
|
||||
t_reorder_chain: t_reorder_chain.m ../../host/crash.c $(GFX) $(GFX_H)
|
||||
@@ -77,6 +79,7 @@ run: \
|
||||
t_rt_range \
|
||||
t_rt_range_ro \
|
||||
t_rt_range_shape \
|
||||
t_rt_srgb_view \
|
||||
t_ub \
|
||||
t_xv \
|
||||
t_zskip
|
||||
@@ -108,6 +111,7 @@ run: \
|
||||
DM_NVN_UNWRITTEN_DC=0 MTL_DEBUG_LAYER=1 ./t_rt_range --sample-attachment --both-flags
|
||||
./t_pso_skey
|
||||
MTL_DEBUG_LAYER=1 ./t_pfv
|
||||
MTL_DEBUG_LAYER=1 ./t_rt_srgb_view
|
||||
python3 test_tbdr_budget.py
|
||||
.PHONY: run
|
||||
# 老接口版那一遍(图形后端编译期开关 DM_NVN_M3=1,目标 macOS 15.0):在旁边的 tests_m3 目录里用同一份测试源码另编另跑,不动这里的缺省产物。
|
||||
|
||||
+47
-1
@@ -302,7 +302,7 @@ int main(void) {
|
||||
for (int i = 0; i < 24; i++) P(nvnCommandBufferCopyBufferToBuffer)(&cb, (NVNbufferAddress)heap, (NVNbufferAddress)(heap + big), big, 0);
|
||||
NVNcommandHandle hbusy = P(nvnCommandBufferEndRecording)(&cb);
|
||||
P(nvnQueueSubmitCommands)(&q, 1, &hbusy);
|
||||
uint64_t f = mtl_last_fence();
|
||||
uint64_t f = x_fence(); // 游戏经 FenceSync 拿到的栅栏值(翻译异步:可能还没翻译到) | Fence value the game gets from FenceSync (translation is asynchronous: it may not have been translated yet)
|
||||
int busy_before = !mtl_wait(f, 0);
|
||||
dm_gfx_suspend(1);
|
||||
EXPECT("挂起前 GPU 确实在忙(零超时等待未完成)", 1, busy_before);
|
||||
@@ -359,6 +359,52 @@ int main(void) {
|
||||
mtl_present_test_stall(0); mtl_present_flush();
|
||||
}
|
||||
|
||||
// 8. 对象副本:录完命令后游戏 Finalize 并在同址重建贴图 / 换程序着色器,已录命令里读到的仍是录制时的内容;退役副本过 SNAP_KEEP 次提交才回收
|
||||
// 8. Object snapshots: after commands are recorded the game Finalizes and rebuilds a texture at the same address / swaps a program's shaders; recorded commands still read what was there at record time; retired snapshots are reclaimed only after SNAP_KEEP submits
|
||||
{
|
||||
NVNtextureBuilder b; NVNtexture tx; P(nvnTextureBuilderSetDevice)(&b, &dev); P(nvnTextureBuilderSetDefaults)(&b);
|
||||
P(nvnTextureBuilderSetWidth)(&b, 8); P(nvnTextureBuilderSetHeight)(&b, 4); P(nvnTextureBuilderSetFormat)(&b, NVN_FORMAT_RGBA8); P(nvnTextureInitialize)(&tx, &b);
|
||||
NVNprogram pg; NVNshaderData sd[2]; memset(sd, 0, sizeof sd); P(nvnProgramInitialize)(&pg, &dev); P(nvnProgramSetShaders)(&pg, 1, sd);
|
||||
const NVNtexture *ct[1] = {&tx};
|
||||
P(nvnCommandBufferBeginRecording)(&cb);
|
||||
P(nvnCommandBufferSetRenderTargets)(&cb, 1, ct, NULL, NULL, NULL);
|
||||
P(nvnCommandBufferBindProgram)(&cb, &pg, NVN_SHADER_STAGE_VERTEX_BIT);
|
||||
NVNcommandHandle hs = P(nvnCommandBufferEndRecording)(&cb);
|
||||
const p_set_rt *rt = NULL; const p_bind_program *bp = NULL;
|
||||
for (const uint8_t *p = (const uint8_t *)hs; p;) { // 按记录格式走:JUMP 跟到下一段,END 结束 | Walk the record format: follow JUMP to the next segment, stop at END
|
||||
op_hdr h; memcpy(&h, p, sizeof h);
|
||||
if (h.op == OP_END) break;
|
||||
if (h.op == OP_JUMP) { memcpy(&p, p + 8, 8); continue; }
|
||||
if (h.op == OP_SET_RT) rt = (const p_set_rt *)(p + 8);
|
||||
if (h.op == OP_BIND_PROGRAM) bp = (const p_bind_program *)(p + 8);
|
||||
p += h.size;
|
||||
}
|
||||
EXPECT("录到 SET_RT 与 BIND_PROGRAM", 2, (rt != NULL) + (bp != NULL));
|
||||
if (rt && bp) {
|
||||
const tex_t *s0 = rt->color[0];
|
||||
EXPECT("SET_RT 存的不是游戏对象地址", 1, (const void *)s0 != (const void *)&tx);
|
||||
EXPECT("副本宽 8", 8, s0->d.width);
|
||||
NVNtexture cp; memcpy(&cp, &tx, sizeof cp);
|
||||
EXPECT("按值拷来的同序号对象共用同一副本", 1, snap_tex(&cp) == s0);
|
||||
uint64_t ser0 = s0->serial;
|
||||
P(nvnTextureFinalize)(&tx); P(nvnTextureBuilderSetWidth)(&b, 16); P(nvnTextureBuilderSetHeight)(&b, 16); P(nvnTextureInitialize)(&tx, &b);
|
||||
EXPECT("同址重建后已录命令仍读到宽 8", 8, rt->color[0]->d.width);
|
||||
EXPECT("同址重建后已录命令仍是旧序号", 1, rt->color[0]->serial == ser0);
|
||||
const tex_t *s1 = snap_tex(&tx);
|
||||
EXPECT("重建后再录取到新副本、宽 16", 16, s1 != s0 ? (long long)s1->d.width : -1);
|
||||
P(nvnProgramSetShaders)(&pg, 2, sd);
|
||||
EXPECT("换着色器后已录命令的程序仍是 1 段", 1, bp->prog->nstage);
|
||||
x_drain(); uint64_t s_at = atomic_load(&g_x_subs); // 退役盖戳 = 当时已入队的提交数;回收按已执行数 | Retire stamp = number of submits enqueued at that time; reclaim goes by the number executed
|
||||
for (int k = 1; k < SNAP_KEEP; k++) snap_tick(s_at + k);
|
||||
EXPECT("退役后 SNAP_KEEP−1 次提交:副本还在", 8, s0->d.width);
|
||||
snap_tick(s_at + SNAP_KEEP);
|
||||
EXPECT("退役后 SNAP_KEEP 次提交:副本已回收(序号清零)", 0, s0->serial);
|
||||
const tex_t *s2 = snap_tex(&cp);
|
||||
EXPECT("回收后旧拷贝对象再取副本:宽 8、序号是它自己的", 8, s2->serial == ((const tex_t *)&cp)->serial ? (long long)s2->d.width : -1);
|
||||
}
|
||||
P(nvnTextureFinalize)(&tx); P(nvnProgramFinalize)(&pg);
|
||||
}
|
||||
|
||||
// 7. 未实现函数:返回 0、报红、只报一次
|
||||
// 7. Unimplemented functions: return 0, report a failure, report only once
|
||||
unsigned ui = 0; while (strcmp(nvn_names[ui], "nvnBufferBuilderSetDefaults")) ui++;
|
||||
|
||||
@@ -71,7 +71,7 @@ int main(void) { @autoreleasepool {
|
||||
NVNT_nvnQueuePresentTexture present=(NVNT_nvnQueuePresentTexture)get(NULL,"nvnQueuePresentTexture");
|
||||
tex_t tex={.serial=10001};tex.d.width=tex.d.height=8;tex.d.depth=tex.d.levels=1;tex.d.format=NVN_FORMAT_RGBA8;tex.d.target=NVN_TEXTURE_TARGET_2D;serial_put(tex.serial,src);
|
||||
win_t win={.ntex=1};win.tex[0]=(NVNtexture *)&tex;set((NVNwindow *)&win,4,4,4,4);
|
||||
mtl_present_test_stall(100000000);present(NULL,(NVNwindow *)&win,0);uint64_t tk=win.ticket[0];set((NVNwindow *)&win,0,0,8,8);
|
||||
mtl_present_test_stall(100000000);present(NULL,(NVNwindow *)&win,0);set((NVNwindow *)&win,0,0,8,8);uint64_t tk=x_present_ticket(win.ticket[0]); // ticket 存翻译队列任务号,换成出图线程票号 | ticket holds the translation queue's job number; swap it for the present thread's ticket
|
||||
#ifdef CROP_LEGACY_HEADER
|
||||
EXPECT("旧队列结构没有四参数副本空间(结构检查)",1,sizeof(pq_item)>=sizeof(tex_t)+sizeof(double)+sizeof(uint64_t)+sizeof br);
|
||||
#else
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
// 换格式的渲染目标视图(公开仓库 #36):RGBA8 底图经 RGBA8_SRGB 视图当颜色附件,清成 0.5 要按 sRGB 编码落进底图;
|
||||
// 呈现采样 sRGB 交换链贴图要经非 sRGB 视图(读出存的字节)。走生产 rp_begin_ex / rp_end / present_src,4×4 真 Metal 附件。
|
||||
// 期望值由常量算,不借被测实现:sRGB 编码 0.5 = 1.055 × 0.5^(1/2.4) − 0.055 = 0.7354 → ×255 = 187.5,硬件取 188;不经视图 = 0.5 × 255 → 128
|
||||
// Render-target views that change the format (public repository #36): an RGBA8 base texture used as a colour attachment through an RGBA8_SRGB view must store the sRGB-encoded value when cleared to 0.5;
|
||||
// presenting from an sRGB swapchain texture must sample through a non-sRGB view (reading the stored bytes). Goes through the production rp_begin_ex / rp_end / present_src with a real 4x4 Metal attachment.
|
||||
// Expected values come from constants, not from the code under test: sRGB encoding of 0.5 = 1.055 x 0.5^(1/2.4) - 0.055 = 0.7354 -> x255 = 187.5, the hardware gives 188; without the view = 0.5 x 255 -> 128
|
||||
#include "../nvn/nvn_mtl.m"
|
||||
void *front_metal_layer(void) { return NULL; }
|
||||
module_t *module_of(const void *p) { (void)p; return NULL; }
|
||||
module_t g_mod[MAX_MOD]; int g_nmod;
|
||||
void svc_thread_dump(void) {}
|
||||
uint64_t now_ns(void) { return bp_now(); }
|
||||
|
||||
static int fail, count;
|
||||
#define EXPECT(name, want, got) do { long long w_ = (want), g_ = (got); count++; \
|
||||
printf("%s 期望 %lld → 真结果 %lld %s\n", name, w_, g_, w_ == g_ ? "✓" : "✗"); fail += w_ != g_; } while (0)
|
||||
|
||||
// 清成 0.5 后读回第一个像素的 R 字节;view = 1:经 RGBA8_SRGB 视图挂附件
|
||||
// after clearing to 0.5, read back the R byte of the first pixel; view = 1: the attachment goes through an RGBA8_SRGB view
|
||||
static int clear_and_read(tex_t *t, int view, uint32_t *cfmt) {
|
||||
memset(&R, 0, sizeof R); R.has_rt = 1; R.rt.n = 1; R.rt.color[0] = t;
|
||||
if (view) { R.rt.has_cview[0] = 1; R.rt.cview[0].set_format = 1; R.rt.cview[0].format = NVN_FORMAT_RGBA8_SRGB; }
|
||||
R.clear_c[0] = 1; R.cc[0] = MTLClearColorMake(0.5, 0.5, 0.5, 1);
|
||||
mtl_sub_begin(); rp_begin_ex(1); *cfmt = g_pass.cfmt[0]; rp_end();
|
||||
id<MTLBuffer> b = [g_dev newBufferWithLength:64 options:MTLResourceStorageModeShared]; res_add(b);
|
||||
[blit() copyFromTexture:tex_mtl(t) sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0, 0, 0) sourceSize:MTLSizeMake(4, 4, 1)
|
||||
toBuffer:b destinationOffset:0 destinationBytesPerRow:16 destinationBytesPerImage:64];
|
||||
enc_b_end(g_blit); g_blit = nil;
|
||||
uint64_t f = mtl_sub_commit();
|
||||
EXPECT("提交完成", 1, mtl_wait(f, 5000000000ull));
|
||||
EXPECT("提交反馈无错误", 0, mtl_last_commit_error());
|
||||
return ((uint8_t *)b.contents)[0];
|
||||
}
|
||||
|
||||
int main(void) { @autoreleasepool {
|
||||
mtl_init();
|
||||
tex_t t = {.serial = 3601};
|
||||
t.d.width = t.d.height = 4; t.d.depth = t.d.levels = t.d.samples = 1; t.d.target = NVN_TEXTURE_TARGET_2D; t.d.format = NVN_FORMAT_RGBA8;
|
||||
uint32_t cf = 0;
|
||||
EXPECT("负对照:不带视图清 0.5,底图存线性值", 128, clear_and_read(&t, 0, &cf));
|
||||
EXPECT("负对照:管线颜色格式 = 底图 RGBA8Unorm", MTLPixelFormatRGBA8Unorm, cf);
|
||||
EXPECT("经 RGBA8_SRGB 视图清 0.5,底图存 sRGB 编码值", 188, clear_and_read(&t, 1, &cf));
|
||||
EXPECT("管线颜色格式跟着视图 = RGBA8Unorm_sRGB", MTLPixelFormatRGBA8Unorm_sRGB, cf);
|
||||
|
||||
MTLTextureDescriptor *d = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm_sRGB width:4 height:4 mipmapped:NO];
|
||||
d.usage = MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget; d.storageMode = MTLStorageModePrivate;
|
||||
id<MTLTexture> s = [g_dev newTextureWithDescriptor:d], s2 = [g_dev newTextureWithDescriptor:d];
|
||||
id<MTLTexture> v = present_src(s);
|
||||
EXPECT("呈现:sRGB 交换链经 RGBA8Unorm 视图采样", MTLPixelFormatRGBA8Unorm, v.pixelFormat);
|
||||
EXPECT("呈现:视图的底图就是交换链贴图", 1, v.parentTexture == s);
|
||||
EXPECT("呈现:同一张交换链贴图第二次取到同一个视图(缓存)", 1, present_src(s) == v);
|
||||
id<MTLTexture> v2 = present_src(s2);
|
||||
EXPECT("呈现:另一张交换链贴图各自一个视图", 1, v2 != v && v2.parentTexture == s2);
|
||||
id<MTLTexture> plain = tex_mtl(&t);
|
||||
EXPECT("呈现:非 sRGB 交换链原样采样", 1, present_src(plain) == plain);
|
||||
EXPECT("全程没有报红", 0, g_red_once[48] + g_red_once[49] + g_red_once[50]);
|
||||
printf("== %d 项,失败 %d ==\n", count, fail); return fail != 0;
|
||||
} }
|
||||
@@ -2,7 +2,7 @@
|
||||
dmsh_xlate.dll aff3b70cff6bf29e
|
||||
Ryujinx.Graphics.Shader.dll 72886c0b30bc0016
|
||||
Ryujinx.Common.dll 614dced78b44547d
|
||||
xlate_source 1cc46907ca1ee8d0
|
||||
xlate_source d379d76ef969729f
|
||||
spirv-cross c95d3fc88f6ae5f5
|
||||
metal_macosx Apple metal version 32023.883 (metalfe-32023.883)
|
||||
metal_iphoneos Apple metal version 32023.883 (metalfe-32023.883)
|
||||
|
||||
@@ -0,0 +1,380 @@
|
||||
#!/usr/bin/env python3
|
||||
# Vulkan 路线离线出包(Android):Switch 原版着色器 → SPIR-V(dmsh_xlate,Ryujinx 翻译器)→ 直接给 Vulkan 用,不经 spirv-cross / Metal。
|
||||
# 与 dmsh_build.py 共用作业构造(作答表 nvn/shader_facts.tsv、映射表 nvn/shader_map.tsv、c1、内嵌着色器);反射直接从 SPIR-V 的名字与修饰里读,
|
||||
# 资源分类与 dmsh_build.reflect 同口径(Ryujinx 的资源名 spirv-cross 原样保留进 MSL,所以同一套名字规则在 SPIR-V 上同样成立)。
|
||||
# 改写:描述符组号按阶段分开——顶点 / 计算 = 0,像素 = 1(Ryujinx 一律放进第 0 组,绑定号各阶段都从 1 起,同一管线里会撞)。
|
||||
# 用法:dmsh_vk.py <Switch 着色器包目录> <输出目录> [键…](不给键 = 全部) 环境:XLATE=翻译工具,MAIN=Switch main NSO(内嵌着色器),J=并发,SPIRV_VAL=校验工具
|
||||
# 产物:<输出目录>/<键>.spv(已改组号)、<输出目录>/<键>.vk.json(反射)、<输出目录>/_vk_build.json(逐键结果);
|
||||
# <输出目录>/rt/:设备端运行时缓存(nvn_vk.c 读)= shader_index.bin(控制段 → 键)+ <键>.vkmeta(绑定表)+ <键>.spv.gz
|
||||
# PACK_ONLY=1 只按已有 .spv / .vk.json 重出 rt/;GLSLC=glslc 时一并编译 main 内嵌的 4 个计数报告内核(nvn_builtin.h)
|
||||
# SB_ALIGN=宿主存储缓冲偏移对齐(缺省 64 = Adreno):翻译器按 base & -SB_ALIGN 求 SSBO 偏移,vkmeta 绑定标志位 1 告诉宿主可下对齐绑定、免拷贝;16 = 与 iOS 同样的翻译
|
||||
# Vulkan-route offline build (Android): original Switch shaders → SPIR-V (dmsh_xlate, the Ryujinx translator) → used by Vulkan directly, no spirv-cross / Metal.
|
||||
# Shares job construction with dmsh_build.py (answer table nvn/shader_facts.tsv, mapping table nvn/shader_map.tsv, c1, embedded shaders); reflection is read straight from SPIR-V names and decorations,
|
||||
# resource classification follows dmsh_build.reflect (spirv-cross keeps Ryujinx's resource names in the MSL unchanged, so the same naming rules hold on SPIR-V).
|
||||
# Rewrite: descriptor set numbers are split by stage - vertex / compute = 0, pixel = 1 (Ryujinx puts everything in set 0 with binding numbers starting at 1 in every stage, which collide within one pipeline).
|
||||
# Usage: dmsh_vk.py <Switch shader package dir> <output dir> [key...] (no keys = all) Environment: XLATE=translator, MAIN=Switch main NSO (embedded shaders), J=concurrency, SPIRV_VAL=validator
|
||||
# Output: <output dir>/<key>.spv (set numbers rewritten), <output dir>/<key>.vk.json (reflection), <output dir>/_vk_build.json (per-key results);
|
||||
# <output dir>/rt/: the on-device runtime cache (read by nvn_vk.c) = shader_index.bin (control segment → key) + <key>.vkmeta (binding table) + <key>.spv.gz
|
||||
# PACK_ONLY=1 only re-emits rt/ from the existing .spv / .vk.json; with GLSLC=glslc the 4 counter-report kernels embedded in main (nvn_builtin.h) are compiled too
|
||||
# SB_ALIGN=host storage buffer offset alignment (default 64 = Adreno): the translator takes SSBO offsets from base & -SB_ALIGN, and vkmeta binding flag bit 1 tells the host it may bind aligned down without copying; 16 = the same translation as iOS
|
||||
import os, sys, re, json, struct, gzip, hashlib, shutil, subprocess, tempfile, collections, concurrent.futures as cf
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE); import dmsh_facts
|
||||
DM_ROOT = os.environ.get('DM_ROOT') or os.path.expanduser('~/dm-work')
|
||||
dm_dir, out = sys.argv[1:3]; want = set(sys.argv[3:])
|
||||
XLATE = os.environ.get('XLATE', f'{DM_ROOT}/build/gfx/dmsh_xlate/dmsh_xlate')
|
||||
MAIN = os.environ.get('MAIN', f'{DM_ROOT}/data/switch/3.3.94012/Update/ExeFS/main')
|
||||
SPIRV_VAL = os.environ.get('SPIRV_VAL', shutil.which('spirv-val') or '')
|
||||
MAP = os.path.join(HERE, '../nvn/shader_map.tsv')
|
||||
FACTS = dmsh_facts.load()
|
||||
if not FACTS: sys.exit('【红】没有作答表 nvn/shader_facts.tsv')
|
||||
TEX_BASE, SAMP_BASE, IMG_BASE = 0x168, 0x568, 0x120
|
||||
SET_OF = {'vs': 0, 'cs': 0, 'ps': 1}
|
||||
|
||||
def records(d):
|
||||
r = [m.start() for m in re.finditer(b'BTCDBTCD', d)]
|
||||
return [d[x:(r[k + 1] if k + 1 < len(r) else len(d))] for k, x in enumerate(r)]
|
||||
|
||||
loc, stage_of = {}, {}
|
||||
for ln in open(MAP):
|
||||
c = ln.rstrip('\n').split('\t')
|
||||
if len(c) > 4 and c[0].endswith('.bin'): loc.setdefault(c[3], (c[0], int(c[1])))
|
||||
if len(c) > 4 and c[0].startswith('main.rodata@'):
|
||||
loc.setdefault(c[3], (c[0], int(c[0].split('@')[1], 16))); stage_of[c[3]] = {'顶点': 'vs', '像素': 'ps'}[c[2]]
|
||||
|
||||
def main_rec(mi, o):
|
||||
# 同 dmsh_build.main_rec:内嵌代码区紧贴控制段之前 | same as dmsh_build.main_rec: the embedded code area sits right before the control segment
|
||||
g = mi.rfind(bytes.fromhex('78563412'), o - 0x1000, o)
|
||||
if g < 0 or mi[o:o + 4] != bytes.fromhex('34127698'): sys.exit(f'【红】main 映像 @{o:#x} 不是内嵌着色器控制段(MAIN={MAIN})')
|
||||
return bytes(0x38) + mi[g:o + 0x880]
|
||||
|
||||
def job_for(key, name, rec, w):
|
||||
# 同 dmsh_build.job_for | same as dmsh_build.job_for
|
||||
ci = rec.find(bytes.fromhex('34127698')); code = rec[0x38:ci]; stage = stage_of.get(key, name[:2])
|
||||
c1o, c1t = struct.unpack_from('<2I', rec, ci + 0x700)
|
||||
c1 = rec[0x38 + c1o:0x38 + c1t]
|
||||
if stage != 'cs': code = code[0x30:]
|
||||
cp = os.path.join(w, key + '.bin'); open(cp, 'wb').write(code)
|
||||
j = {'key': key, 'stage': stage, 'code': cp, 'tex': {}, 'img': {}, 'attr': {}, 'fout': {}, 'c1': c1.hex(),
|
||||
'debug': os.environ.get('XLATE_DEBUG', '1') != '0', 'reduced': os.environ.get('XLATE_REDUCED', '1') == '1',
|
||||
'sb_align': int(os.environ.get('SB_ALIGN', '64')), # Adreno minStorageBufferOffsetAlignment;翻译器按 base & -64 求偏移 | translator takes offsets from base & -64
|
||||
'nan_minmax': os.environ.get('XLATE_NAN_MINMAX', '1') != '0',
|
||||
'nan_out': os.environ.get('XLATE_NAN_OUT', '1') != '0'} # 浮点颜色输出 NaN 换 0;XLATE_NAN_OUT=0 关 | NaN in float color outputs becomes 0; XLATE_NAN_OUT=0 turns it off # 浮点 min/max/clamp 用 NaN 安全版(同 Maxwell);XLATE_NAN_MINMAX=0 关 | NaN-safe float min/max/clamp (as on Maxwell); XLATE_NAN_MINMAX=0 turns it off
|
||||
if key not in FACTS: j['pc_missing'] = True; return j, c1
|
||||
j.update(FACTS[key])
|
||||
return j, c1
|
||||
|
||||
def decode_tex(name):
|
||||
# 同 dmsh_build.decode_tex | same as dmsh_build.decode_tex
|
||||
m = re.match(r'[a-z]+_[ti]\w*?_(?:cb(\d+)|tcb)_([0-9A-F]+)', name)
|
||||
if not m: return None
|
||||
slots = int(m.group(1)) if m.group(1) else -1; h = int(m.group(2), 16)
|
||||
tb = (slots & 0xffff) if slots >= 0 else 2; sb = ((slots >> 16) - 1) if slots >= 0 and (slots >> 16) else tb
|
||||
o0, o1, ty = h & 0x3fff, (h >> 14) & 0x3fff, h >> 28
|
||||
def slot(word, base, cb): return (word * 4 - base) // 8 if cb == 2 and word * 4 >= base and (word * 4 - base) % 8 == 0 else None
|
||||
words = [o0] + ([o1] if ty else [])
|
||||
if re.match(r'[a-z]+_i', name):
|
||||
return next((slot(x, IMG_BASE, tb) for x in words if IMG_BASE <= x * 4 < TEX_BASE and slot(x, IMG_BASE, tb) is not None), None), None, ty
|
||||
t = next((slot(x, TEX_BASE, tb) for x in words if slot(x, TEX_BASE, tb) is not None and x * 4 < SAMP_BASE), None)
|
||||
s = next((slot(x, SAMP_BASE, sb) for x in words if x * 4 >= SAMP_BASE and slot(x, SAMP_BASE, sb) is not None), None)
|
||||
return t, s, ty
|
||||
|
||||
# ---- SPIR-V 解析 | SPIR-V parsing ----
|
||||
OP_NAME, OP_DECORATE, OP_VARIABLE, OP_TYPE_POINTER, OP_ENTRY, OP_EXEC_MODE = 5, 71, 59, 32, 15, 16
|
||||
OP_TYPE_IMAGE, OP_TYPE_SAMPLER, OP_TYPE_SAMPLED_IMAGE, OP_TYPE_ARRAY, OP_TYPE_RUNTIME_ARRAY, OP_TYPE_STRUCT = 25, 26, 27, 28, 29, 30
|
||||
DEC_BINDING, DEC_SET, DEC_LOCATION, DEC_BUILTIN = 33, 34, 30, 11
|
||||
SC_UNIFORM_CONSTANT, SC_INPUT, SC_UNIFORM, SC_OUTPUT, SC_STORAGE_BUFFER = 0, 1, 2, 3, 12
|
||||
|
||||
def spv_insts(words):
|
||||
o = 5
|
||||
while o < len(words):
|
||||
n, op = words[o] >> 16, words[o] & 0xffff
|
||||
if not n or o + n > len(words): raise ValueError(f'SPIR-V 指令越界 @{o}')
|
||||
yield o, op, words[o + 1:o + n]; o += n
|
||||
|
||||
def spv_str(ops):
|
||||
b = struct.pack(f'<{len(ops)}I', *ops); return b[:b.index(0)].decode()
|
||||
|
||||
def reflect_spv(key, stage, words, res):
|
||||
names, deco, types, var = {}, collections.defaultdict(dict), {}, {}
|
||||
for o, op, a in spv_insts(words):
|
||||
if op == OP_NAME: names[a[0]] = spv_str(a[1:])
|
||||
elif op == OP_DECORATE and len(a) >= 2: deco[a[0]][a[1]] = a[2] if len(a) > 2 else 1
|
||||
elif 19 <= op <= 39: types[a[0]] = (op, a[1:])
|
||||
elif op == OP_VARIABLE: var[a[1]] = (a[0], a[2])
|
||||
def pointee(tid):
|
||||
t = types.get(tid); return t[1][1] if t and t[0] == OP_TYPE_POINTER else None
|
||||
def base(tid):
|
||||
while tid in types and types[tid][0] in (OP_TYPE_ARRAY, OP_TYPE_RUNTIME_ARRAY): tid = types[tid][1][0]
|
||||
return tid
|
||||
def desc_type(sc, tid):
|
||||
"""VkDescriptorType:0 采样器、1 组合、2 采样图像、3 存储图像、4 uniform 纹素缓冲、5 存储纹素缓冲、6 uniform 缓冲、7 存储缓冲 | VkDescriptorType numbering"""
|
||||
t = types.get(base(tid))
|
||||
if sc == SC_UNIFORM: return 7 if deco[base(tid)].get(3) else 6 # BufferBlock(3) 旧式存储缓冲 | BufferBlock (3) is the legacy storage buffer form
|
||||
if sc == SC_STORAGE_BUFFER: return 7
|
||||
if not t: return None
|
||||
if t[0] == OP_TYPE_SAMPLER: return 0
|
||||
if t[0] == OP_TYPE_SAMPLED_IMAGE:
|
||||
im = types[t[1][0]]; return 4 if im[1][1] == 5 else 1 # Dim Buffer = 5
|
||||
if t[0] == OP_TYPE_IMAGE:
|
||||
dim, sampled = t[1][1], t[1][5]
|
||||
if dim == 5: return 4 if sampled == 1 else 5
|
||||
return 2 if sampled == 1 else 3
|
||||
return None
|
||||
binds = []
|
||||
sb_sorted = sorted(res['sbufs'], key=lambda b: b['binding'])
|
||||
sb_by_binding = {b['binding']: (i, b) for i, b in enumerate(sb_sorted)}
|
||||
sbase = {'vs': 0x110, 'cs': 0x310, 'ps': 0x510}[stage]
|
||||
for vid, (ptype, sc) in var.items():
|
||||
if sc not in (SC_UNIFORM_CONSTANT, SC_UNIFORM, SC_STORAGE_BUFFER) or DEC_BINDING not in deco[vid]: continue
|
||||
nm = names.get(vid, ''); ty = desc_type(sc, pointee(ptype))
|
||||
tdef = types.get(pointee(ptype)); count = 1
|
||||
if tdef and tdef[0] == OP_TYPE_ARRAY: count = -1 # 描述符数组:Ryujinx 只在无绑定贴图时出,这里不支持 | descriptor array: Ryujinx only emits it for bindless textures; unsupported here
|
||||
e = {'name': nm, 'binding': deco[vid][DEC_BINDING], 'set': deco[vid].get(DEC_SET, 0), 'vk_type': ty, 'count': count, 'var': vid}
|
||||
if nm == 'support_buffer': e['kind'] = 'support'
|
||||
elif re.fullmatch(r'[a-z]+_c(\d+)', nm):
|
||||
n = int(re.fullmatch(r'[a-z]+_c(\d+)', nm).group(1))
|
||||
e.update(kind='cbuf', reg=n - 3) if 3 <= n <= 16 else e.update(kind='c1' if n == 1 else 'drvcb', bank=n)
|
||||
elif re.fullmatch(r'[a-z]+_s(\d+)', nm):
|
||||
idx, b = sb_by_binding.get(e['binding'], (None, None))
|
||||
e.update(kind='sbuf', index=idx)
|
||||
off = b['cb_offset'] * 4 if b and b['cb_slot'] == 0 else None
|
||||
if stage == 'cs' and off is not None and 0x210 <= off < 0x310 and (off - 0x210) % 16 == 0:
|
||||
e.update(kind='ubo_ptr', reg=(off - 0x210) // 16)
|
||||
else: e['reg'] = (off - sbase) // 16 if off is not None and 0 <= off - sbase < 0x100 and (off - sbase) % 16 == 0 else None
|
||||
e['rw'] = bool(b and b['flags'] & 2)
|
||||
elif ty == 0:
|
||||
t, s, hty = decode_tex(nm[:-5] if nm.endswith('Smplr') else nm) or (None, None, 0)
|
||||
e.update(kind='samp', reg=s) if hty else e.update(kind='samp_tex', reg=t)
|
||||
else:
|
||||
d = decode_tex(nm)
|
||||
if not d: e['kind'] = '?'
|
||||
else:
|
||||
img = bool(re.match(r'[a-z]+_i', nm))
|
||||
e.update(kind='img' if img else ('tbuf' if ty in (4, 5) else 'tex'), reg=d[0])
|
||||
if not img and ty == 1: # 组合采样:采样器号取同一句柄(类型 0 = 贴图槽句柄高位) | combined: sampler from the same handle (type 0 = high bits of the texture slot's handle)
|
||||
e['samp'] = d[1] if d[2] else None; e['samp_from_tex'] = not d[2]
|
||||
binds.append(e)
|
||||
binds.sort(key=lambda b: b['binding'])
|
||||
inputs = sorted(deco[v][DEC_LOCATION] for v, (_, sc) in var.items() if sc == SC_INPUT and DEC_LOCATION in deco[v] and DEC_BUILTIN not in deco[v])
|
||||
outputs = sorted(deco[v][DEC_LOCATION] for v, (_, sc) in var.items() if sc == SC_OUTPUT and DEC_LOCATION in deco[v] and DEC_BUILTIN not in deco[v])
|
||||
return binds, inputs, outputs
|
||||
|
||||
def drv_reads(words, binds):
|
||||
"""对驱动段 c0 / c2 的访问:OpAccessChain(var, 0, 常量 vec4 下标, 常量分量) → 字节偏移;非常量 → 动态 | accesses to driver segments c0 / c2"""
|
||||
consts, out = {}, {}
|
||||
for o, op, a in spv_insts(words):
|
||||
if op == 43 and len(a) == 3: consts[a[1]] = a[2]
|
||||
drv = {b['var']: b['bank'] for b in binds if b['kind'] == 'drvcb'}
|
||||
for o, op, a in spv_insts(words):
|
||||
if op in (65, 66) and len(a) >= 3 and a[2] in drv:
|
||||
d = out.setdefault(str(drv[a[2]]), {'offsets': set(), 'dynamic': False})
|
||||
idx = a[3:]
|
||||
if len(idx) >= 2 and all(i in consts for i in idx[:3]): d['offsets'].add(consts[idx[1]] * 16 + (consts[idx[2]] * 4 if len(idx) > 2 else 0))
|
||||
else: d['dynamic'] = True
|
||||
return {k: {'offsets': sorted(v['offsets']), 'dynamic': v['dynamic']} for k, v in out.items()}
|
||||
|
||||
def set_rewrite(words, stage):
|
||||
"""组号按阶段改写;去掉 Ryujinx 无条件声明、实际没用到的能力(Float64 / Int64 / 像素互锁 / 绘制参数),免得驱动按缺特性拒收
|
||||
Rewrite set numbers per stage; drop capabilities Ryujinx declares unconditionally but never uses (Float64 / Int64 / pixel interlock / draw parameters), so drivers lacking the feature do not reject the module"""
|
||||
s = SET_OF[stage]; used = set(); keep = []
|
||||
for o, op, a in spv_insts(words):
|
||||
if op == 22 and a[1] == 64: used.add(10) # OpTypeFloat 64 → Float64
|
||||
if op == 21 and a[1] == 64: used.add(11) # OpTypeInt 64 → Int64
|
||||
if op in (5364, 5365): used.add(5378) # Begin / EndInvocationInterlockEXT
|
||||
if op == OP_DECORATE and len(a) == 3 and a[1] == DEC_BUILTIN and a[2] in (4424, 4425, 4426): used.add(4427) # BaseVertex / BaseInstance / DrawIndex
|
||||
drop = {10, 11, 5378, 4427} - used
|
||||
have = {a[0] for o, op, a in spv_insts(words) if op == 17}
|
||||
unk = any(op == OP_TYPE_IMAGE and a[6] == 2 and a[7] == 0 for o, op, a in spv_insts(words)) # 无格式存储图像 | storage image with Unknown format
|
||||
add = [c for c in (55, 56) if unk and c not in have] # Storage Image Read / WriteWithoutFormat(Adreno 两个特性都有 | Adreno has both features)
|
||||
for o, op, a in spv_insts(words):
|
||||
if op == 17 and add:
|
||||
for c in add: keep.extend([2 << 16 | 17, c])
|
||||
add = []
|
||||
ins = list(words[o:o + 1 + len(a)])
|
||||
if op == 17 and a[0] in drop: continue
|
||||
if op == 10 and spv_str(a) == 'SPV_EXT_fragment_shader_interlock' and 5378 in drop: continue
|
||||
if op == 16 and a[1] in (5366, 5367, 5368, 5369, 5370, 5371) and 5378 in drop: continue # 互锁执行模式 | interlock execution modes
|
||||
if op == OP_DECORATE and len(a) == 3 and a[1] == DEC_SET: ins[3] = s
|
||||
keep.extend(ins)
|
||||
return list(words[:5]) + keep
|
||||
|
||||
# 翻译器对每个着色器都声明 GroupNonUniform{Vote,Ballot,Shuffle}(cap 62/64/65),实际只有少数 ps / cs 用到;
|
||||
# Adreno 的 subgroup 只支持 fragment / compute,顶点着色器带着这些声明会被拒,所以没用到 subgroup 指令 / 内建量的就把声明去掉
|
||||
# The translator declares GroupNonUniform{Vote,Ballot,Shuffle} (cap 62/64/65) on every shader but only a few ps / cs use them;
|
||||
# Adreno supports subgroups only in fragment / compute and a vertex shader carrying them is rejected, so drop the declarations when no subgroup instruction / builtin is used
|
||||
SUBGROUP_CAPS = set(range(61, 69))
|
||||
SUBGROUP_BUILTINS = {36, 37, 38, 39, 40, 41, 4416, 4417, 4418, 4419, 4420}
|
||||
def strip_subgroup(words):
|
||||
used = False
|
||||
for o, op, a in spv_insts(words):
|
||||
if 333 <= op <= 366 or op in (4421, 4422, 4428, 4429, 4430, 4431, 4432) or \
|
||||
(op == 71 and len(a) >= 3 and a[1] == DEC_BUILTIN and a[2] in SUBGROUP_BUILTINS): used = True; break
|
||||
if used: return words
|
||||
keep = [x for o, op, a in spv_insts(words) for x in words[o:o + (words[o] >> 16)] if not (op == 17 and a[0] in SUBGROUP_CAPS)]
|
||||
return list(words[:5]) + keep
|
||||
|
||||
def finish(key, w, j, c1, name, k):
|
||||
if j['stage'] not in SET_OF: return 'skip stage ' + j['stage'], None # 外壳 / 域各 1 个,Metal 回放层同样不用 | one hull / one domain shader; the Metal replay does not use them either
|
||||
spv = os.path.join(w, key + '.spv')
|
||||
if not os.path.exists(spv): return 'no spv', None
|
||||
res = json.load(open(os.path.join(w, key + '.res.json')))
|
||||
data = open(spv, 'rb').read(); words = list(struct.unpack(f'<{len(data) // 4}I', data))
|
||||
if words[0] != 0x07230203: return 'bad magic', None
|
||||
binds, inputs, outputs = reflect_spv(key, j['stage'], words, res)
|
||||
words = set_rewrite(words, j['stage'])
|
||||
words = strip_subgroup(words)
|
||||
open(os.path.join(out, key + '.spv'), 'wb').write(struct.pack(f'<{len(words)}I', *words))
|
||||
caps = sorted({a[0] for o, op, a in spv_insts(words) if op == 17})
|
||||
exts = sorted({spv_str(a) for o, op, a in spv_insts(words) if op == 10})
|
||||
refl = {'key': key, 'stage': j['stage'], 'set': SET_OF[j['stage']], 'source': f'{name}#{k}', 'c1': c1.hex(),
|
||||
'local': j.get('local'), 'shared': j.get('shared', 0), 'notes': res['notes'] + (['pc_missing'] if j.get('pc_missing') else []),
|
||||
'bindings': [{x: v for x, v in b.items() if x not in ('var', 'set')} for b in binds], 'inputs': inputs, 'outputs': outputs,
|
||||
'sb_align': res.get('sb_align', 16), 'frag_out_map': res.get('frag_out_map'), 'uses_frag_coord': res.get('uses_frag_coord'),
|
||||
'drv_reads': drv_reads(words, binds), 'caps': caps, 'exts': exts}
|
||||
bad = [b for b in binds if b['kind'] == '?' or b['vk_type'] is None or b['count'] != 1 or
|
||||
(b['kind'] in ('cbuf', 'samp', 'samp_tex', 'tex', 'img', 'tbuf', 'sbuf', 'ubo_ptr') and b.get('reg') is None)]
|
||||
if bad: refl['unresolved'] = [b['name'] for b in bad]
|
||||
json.dump(refl, open(os.path.join(out, key + '.vk.json'), 'w'), ensure_ascii=False, indent=1)
|
||||
if SPIRV_VAL:
|
||||
r = subprocess.run([SPIRV_VAL, '--target-env', 'vulkan1.1', os.path.join(out, key + '.spv')], capture_output=True, text=True)
|
||||
if r.returncode: return 'spirv-val: ' + (r.stdout + r.stderr).strip().splitlines()[0][:140], refl
|
||||
return ('unresolved' if bad else 'ok'), refl
|
||||
|
||||
# ---- 设备端运行时缓存(nvn_vk.c 的 RHeader / RBinding 布局) | on-device runtime cache (RHeader / RBinding layout of nvn_vk.c) ----
|
||||
STAGE_NO = {'vs': 0, 'ps': 1, 'cs': 5}
|
||||
# 资源种类码 | resource kind codes: 1 support 2 uniform 3 storage 4 texture 6 image 7 c1 8 driver table 9 uniform via storage 10 texel buffer
|
||||
KIND_NO = {'support': 1, 'cbuf': 2, 'sbuf': 3, 'tex': 4, 'img': 6, 'c1': 7, 'drvcb': 8, 'ubo_ptr': 9, 'tbuf': 10}
|
||||
# 计数报告内核(nvn_builtin.h 的 Vulkan 版):u64 用 uvec2 进位算,免 Int64 | counter-report kernels (Vulkan form of nvn_builtin.h): u64 as uvec2 with carry, no Int64
|
||||
BUILTIN = {'d0f769bb916bbba9': (0x1df10e8, 'ST(LD(id * 4u));'),
|
||||
'16479cc6d75c2b28': (0x1df1a94, 'ST(LD(id * 4u + 2u));'),
|
||||
'0687e2ef95133577': (0x1df2440, 'ST(SUB(LD(id * 8u + 4u), LD(id * 8u)));'),
|
||||
'4df5909e6dabee05': (0x1df2dec, 'ST(SUB(LD(id * 8u + 6u), LD(id * 8u + 2u)));')}
|
||||
BUILTIN_GLSL = """#version 450
|
||||
layout(local_size_x = 32) in;
|
||||
layout(set = 0, binding = 0) uniform U { uint n; } u;
|
||||
layout(set = 0, binding = 1) readonly buffer S { uint s[]; };
|
||||
layout(set = 0, binding = 2) writeonly buffer D { uint d[]; };
|
||||
#define LD(w) uvec2(s[w], s[(w) + 1u])
|
||||
#define ST(v) { uvec2 v_ = v; d[id * 2u] = v_.x; d[id * 2u + 1u] = v_.y; }
|
||||
uvec2 SUB(uvec2 a, uvec2 b) { uint borrow; uint lo = usubBorrow(a.x, b.x, borrow); return uvec2(lo, a.y - b.y - borrow); }
|
||||
void main() { uint id = (gl_WorkGroupID.x << 5) + gl_LocalInvocationID.x; if (id >= u.n) return; BODY }
|
||||
"""
|
||||
|
||||
def vkmeta(refl, spv_size):
|
||||
st = STAGE_NO[refl['stage']]; bs = refl['bindings']
|
||||
attrs = [(l, 0) for l in refl['inputs']] if refl['stage'] == 'vs' else []
|
||||
c1 = bytes.fromhex(refl['c1']).rstrip(b'\0')
|
||||
c1 += bytes(-len(c1) % 4)
|
||||
caps = refl['caps']; local = refl.get('local') or [0, 0, 0]
|
||||
fout = refl.get('frag_out_map'); fout = 0 if fout is None else fout
|
||||
if len(bs) > 64 or len(attrs) > 32 or len(caps) > 32 or len(c1) > 4096: raise ValueError(f"{refl['key']} 超出 vkmeta 上限")
|
||||
h = struct.pack('<11I', 0x4d4b5644, 1, st, len(bs), len(attrs), len(c1), len(caps), *local[:3], fout) + struct.pack('<I', spv_size)
|
||||
for b in bs:
|
||||
k = KIND_NO[b['kind']]
|
||||
slot = 0 if k in (1, 7) else b['bank'] if k == 8 else b['reg']
|
||||
samp = b['samp'] if k == 4 and b.get('samp') is not None else -1
|
||||
# 位 0 可写;位 1 着色器偏移相对 base & -64(翻译器实际答的对齐),宿主可下对齐绑定 | bit 0 writable; bit 1 shader offsets are relative to base & -64 (the alignment the translator actually used), so the host may bind aligned down
|
||||
flags = (int(bool(b.get('rw'))) | (2 if refl.get('sb_align', 16) == 64 else 0)) if k == 3 else 0
|
||||
h += struct.pack('<4I2i2I', SET_OF[refl['stage']], b['binding'], b['vk_type'], k, slot, samp, 1, flags)
|
||||
for a in attrs: h += struct.pack('<2I', *a)
|
||||
h += struct.pack(f'<{len(caps)}I', *caps) + c1
|
||||
return h
|
||||
|
||||
def emit_runtime(entries):
|
||||
"""entries: [(键, 控制段 0x880 字节, 反射, SPIR-V 字节)] → <out>/rt | entries: [(key, 0x880-byte control segment, reflection, SPIR-V bytes)] → <out>/rt"""
|
||||
rt = os.path.join(out, 'rt'); os.makedirs(rt, exist_ok=True)
|
||||
idx = [struct.pack('<3I', 0x494b5644, 1, len(entries))]
|
||||
for key, ctl, refl, spv in entries:
|
||||
assert len(ctl) == 0x880 and len(key) == 16
|
||||
words = strip_subgroup(list(struct.unpack(f'<{len(spv) // 4}I', spv))) # PACK_ONLY 读的旧产物也要剔 | old outputs read by PACK_ONLY need it too
|
||||
spv = struct.pack(f'<{len(words)}I', *words); refl = dict(refl, caps=sorted({a[0] for o, op, a in spv_insts(words) if op == 17}))
|
||||
idx.append(key.encode() + struct.pack('<I', STAGE_NO[refl['stage']]) + ctl)
|
||||
open(os.path.join(rt, key + '.vkmeta'), 'wb').write(vkmeta(refl, len(spv)))
|
||||
open(os.path.join(rt, key + '.spv.gz'), 'wb').write(gzip.compress(spv, 9, mtime=0))
|
||||
open(os.path.join(rt, 'shader_index.bin'), 'wb').write(b''.join(idx))
|
||||
print(f'运行时缓存:{len(entries)} 条 → {rt}')
|
||||
|
||||
def builtin_entries(mi):
|
||||
glslc = os.environ.get('GLSLC')
|
||||
if not glslc: print('【黄】没给 GLSLC,跳过 4 个内嵌计数报告内核'); return []
|
||||
res = []
|
||||
for key, (o, body) in BUILTIN.items():
|
||||
ctl = mi[o:o + 0x880]
|
||||
if hashlib.sha256(ctl).hexdigest()[:16] != key: sys.exit(f'【红】main @{o:#x} 控制段哈希与内嵌内核键 {key} 不符')
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
src = os.path.join(t, 'k.comp'); open(src, 'w').write(BUILTIN_GLSL.replace('BODY', body))
|
||||
r = subprocess.run([glslc, '--target-env=vulkan1.1', '-O', src, '-o', os.path.join(t, 'k.spv')], capture_output=True, text=True)
|
||||
if r.returncode: sys.exit('【红】内嵌内核编译失败:' + r.stderr)
|
||||
spv = open(os.path.join(t, 'k.spv'), 'rb').read()
|
||||
refl = {'key': key, 'stage': 'cs', 'c1': '', 'local': [32, 1, 1], 'inputs': [], 'caps': [1], 'frag_out_map': 0,
|
||||
'bindings': [{'binding': 0, 'vk_type': 6, 'kind': 'cbuf', 'reg': 0},
|
||||
{'binding': 1, 'vk_type': 7, 'kind': 'sbuf', 'reg': 0, 'rw': False},
|
||||
{'binding': 2, 'vk_type': 7, 'kind': 'sbuf', 'reg': 1, 'rw': True}]}
|
||||
res.append((key, ctl, refl, spv))
|
||||
return res
|
||||
|
||||
def main():
|
||||
keys = sorted(want) if want else sorted(loc)
|
||||
NJ = int(os.environ.get('J', '8'))
|
||||
os.makedirs(out, exist_ok=True)
|
||||
w = tempfile.mkdtemp(prefix='dmsh_vk_', dir=os.environ.get('WORK'))
|
||||
packs, jobs, c1s, ctls = {}, {}, {}, {}
|
||||
pack_only = os.environ.get('PACK_ONLY') == '1'
|
||||
for key in keys:
|
||||
name, k = loc[key]
|
||||
if name.startswith('main.rodata@'):
|
||||
if 'main' not in packs:
|
||||
sys.path.insert(0, os.path.join(HERE, '../../verify')); import nsoimg
|
||||
packs['main'] = nsoimg.load(MAIN)
|
||||
rec = main_rec(packs['main'], k)
|
||||
else:
|
||||
if name not in packs: packs[name] = records(open(os.path.join(dm_dir, name), 'rb').read())
|
||||
rec = packs[name][k]
|
||||
ci = rec.find(bytes.fromhex('34127698'))
|
||||
if hashlib.sha256(rec[ci:ci + 0x880]).hexdigest()[:16] != key: sys.exit(f'【红】{name}#{k} 控制段哈希与键 {key} 不符')
|
||||
ctls[key] = rec[ci:ci + 0x880]
|
||||
if not pack_only: jobs[key], c1s[key] = job_for(key, name, rec, w)
|
||||
if 'main' not in packs and os.environ.get('GLSLC'):
|
||||
sys.path.insert(0, os.path.join(HERE, '../../verify')); import nsoimg
|
||||
packs['main'] = nsoimg.load(MAIN)
|
||||
if pack_only:
|
||||
shutil.rmtree(w, ignore_errors=True)
|
||||
st = {r['key']: r['st'] for r in json.load(open(os.path.join(out, '_vk_build.json')))}
|
||||
ents = [(k, ctls[k], json.load(open(os.path.join(out, k + '.vk.json'))), open(os.path.join(out, k + '.spv'), 'rb').read())
|
||||
for k in keys if st.get(k) == 'ok']
|
||||
emit_runtime(ents + builtin_entries(packs.get('main', b''))); return
|
||||
chunks = [c for c in (keys[i::NJ] for i in range(NJ)) if c]
|
||||
def xl(ch):
|
||||
jp = os.path.join(w, f'job_{ch[0]}.json'); json.dump([jobs[k] for k in ch], open(jp, 'w'))
|
||||
return subprocess.run([XLATE, jp, w], capture_output=True, text=True)
|
||||
with cf.ThreadPoolExecutor(NJ) as ex: xr = list(ex.map(xl, chunks))
|
||||
xerr = {}
|
||||
for r in xr:
|
||||
for ln in r.stderr.splitlines():
|
||||
m = re.match(r'【红】(\w+):(.*)', ln)
|
||||
if m: xerr[m.group(1)] = m.group(2)[:160]
|
||||
def fin(key):
|
||||
if key in xerr: return key, 'xlate: ' + xerr[key], None
|
||||
st, refl = finish(key, w, jobs[key], c1s[key], *loc[key])
|
||||
return key, st, refl
|
||||
with cf.ThreadPoolExecutor(NJ) as ex: res = list(ex.map(fin, keys))
|
||||
shutil.rmtree(w, ignore_errors=True)
|
||||
st = collections.Counter(r[1].split(':')[0] for r in res)
|
||||
print(f'着色器 {len(res)}:' + ','.join(f'{k} {v}' for k, v in st.most_common()))
|
||||
for e, n in collections.Counter(r[1] for r in res if r[1] != 'ok').most_common(12): print(f' {n:5d} {e}')
|
||||
ok = [r[2] for r in res if r[2]]
|
||||
for e, n in collections.Counter(u for x in ok for u in x.get('unresolved', [])).most_common(8): print(f' 未解绑定 {n:5d} {e}')
|
||||
for e, n in collections.Counter(c for x in ok for c in x['caps']).most_common(): print(f' cap {e}: {n}')
|
||||
for e, n in collections.Counter(c for x in ok for c in x['exts']).most_common(): print(f' ext {e}: {n}')
|
||||
dr = collections.Counter()
|
||||
for x in ok:
|
||||
for bank, d in x['drv_reads'].items():
|
||||
dr[f'c{bank} dyn'] += d['dynamic']
|
||||
for o in d['offsets']: dr[f'c{bank}+{o:#x}'] += 1
|
||||
print('驱动段读取(前 20):', ', '.join(f'{k}×{v}' for k, v in dr.most_common(20)))
|
||||
json.dump([{'key': r[0], 'st': r[1]} for r in res], open(os.path.join(out, '_vk_build.json'), 'w'), ensure_ascii=False)
|
||||
emit_runtime([(r[0], ctls[r[0]], r[2], open(os.path.join(out, r[0] + '.spv'), 'rb').read()) for r in res if r[1] == 'ok']
|
||||
+ builtin_entries(packs.get('main', b'')))
|
||||
|
||||
if __name__ == '__main__': main()
|
||||
@@ -93,9 +93,19 @@ static class SwshXlate
|
||||
false /* 不做 Y 取反 | no Y flip */, true /* 原点左上 | origin upper-left */, false);
|
||||
}
|
||||
public bool QueryHostSupportsTextureShadowLod() => true;
|
||||
// 作业 sb_align:宿主存储缓冲偏移对齐(Adreno 64)。大于 NVN 的 16 时,着色器按 base & -sb_align 求偏移,宿主下对齐绑定、不再拷贝
|
||||
// Job sb_align: host storage buffer offset alignment (Adreno 64). Above NVN's 16, shaders take offsets from base & -sb_align, so the host binds aligned down without copying
|
||||
public int QueryHostStorageBufferOffsetAlignment() => _job["sb_align"] is JsonNode n ? (int)n : 16;
|
||||
public bool QueryHasUnalignedStorageBuffer() => QueryHostStorageBufferOffsetAlignment() > 16;
|
||||
// 作业 reduced = true:放宽精度——翻译器只给强制精确的运算打 NoContraction(缺省全部打:保持 Maxwell 分开舍入的逐位结果,代价是 MSL 里大量禁优化的 spvFMul 等)
|
||||
// Job reduced = true: relaxed precision - the translator marks NoContraction only on operations that must be exact (the default marks all: keeps the bit-exact results of Maxwell's separate rounding, at the cost of many optimization-disabled spvFMul etc. in the MSL)
|
||||
public bool QueryHostReducedPrecision() => _job["reduced"] is JsonNode n && (bool)n;
|
||||
// 作业 nan_minmax = true:浮点 min / max / clamp 出 NMin / NMax / NClamp(Maxwell FMNMX 与 .SAT 遇 NaN 取另一操作数;Adreno 上 FMax / FClamp 会把 NaN 传下去,bloom 链把它扩成黑块)
|
||||
// Job nan_minmax = true: float min / max / clamp emit NMin / NMax / NClamp (Maxwell FMNMX and .SAT take the other operand on NaN; on Adreno FMax / FClamp pass the NaN on, and the bloom chain spreads it into a black block)
|
||||
public bool QueryHostNanSafeMinMax() => _job["nan_minmax"] is JsonNode n && (bool)n;
|
||||
// 作业 nan_out = true:像素着色器写浮点颜色输出时 NaN 换成 0(Adreno 上 foliage 等偶尔算出 NaN 像素,降采样 / bloom 链把它扩成闪块)
|
||||
// Job nan_out = true: pixel shaders store 0 instead of NaN in float color outputs (on Adreno foliage etc. occasionally produce NaN pixels, which downsample / bloom chains spread into flickering blocks)
|
||||
public bool QueryHostNanFreeColorOutput() => _job["nan_out"] is JsonNode n && (bool)n;
|
||||
}
|
||||
|
||||
static int Main(string[] args)
|
||||
@@ -126,7 +136,7 @@ static class SwshXlate
|
||||
{
|
||||
["key"] = key, ["stage"] = (string)job["stage"], ["notes"] = new JsonArray(acc.Notes.ConvertAll(n => (JsonNode)n).ToArray()),
|
||||
["cbufs"] = new JsonArray(), ["sbufs"] = new JsonArray(), ["textures"] = new JsonArray(), ["images"] = new JsonArray(),
|
||||
["uses_frag_coord"] = p.Info.UsesFragCoord, ["frag_out_map"] = p.Info.FragmentOutputMap,
|
||||
["sb_align"] = acc.QueryHostStorageBufferOffsetAlignment(), ["uses_frag_coord"] = p.Info.UsesFragCoord, ["frag_out_map"] = p.Info.FragmentOutputMap,
|
||||
};
|
||||
foreach (var b in p.Info.CBuffers) res["cbufs"].AsArray().Add(new JsonObject { ["binding"] = b.Binding, ["slot"] = b.Slot });
|
||||
foreach (var b in p.Info.SBuffers) res["sbufs"].AsArray().Add(new JsonObject { ["binding"] = b.Binding, ["slot"] = b.Slot, ["cb_slot"] = b.SbCbSlot, ["cb_offset"] = b.SbCbOffset, ["flags"] = (int)b.Flags });
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,309 @@
|
||||
static PFN_vkGetPipelineCacheData dm_vkGetPipelineCacheData;
|
||||
#define vkGetPipelineCacheData dm_vkGetPipelineCacheData
|
||||
static PFN_vkGetFenceStatus dm_vkGetFenceStatus;
|
||||
#define vkGetFenceStatus dm_vkGetFenceStatus
|
||||
static PFN_vkResetFences dm_vkResetFences;
|
||||
#define vkResetFences dm_vkResetFences
|
||||
static PFN_vkResetCommandBuffer dm_vkResetCommandBuffer;
|
||||
#define vkResetCommandBuffer dm_vkResetCommandBuffer
|
||||
static PFN_vkResetCommandPool dm_vkResetCommandPool;
|
||||
#define vkResetCommandPool dm_vkResetCommandPool
|
||||
static PFN_vkResetDescriptorPool dm_vkResetDescriptorPool;
|
||||
#define vkResetDescriptorPool dm_vkResetDescriptorPool
|
||||
/* Vulkan dispatch belongs to the explicitly selected loader instance. */
|
||||
static PFN_vkGetInstanceProcAddr dm_vk_get;
|
||||
static PFN_vkAcquireNextImageKHR dm_vkAcquireNextImageKHR;
|
||||
#define vkAcquireNextImageKHR dm_vkAcquireNextImageKHR
|
||||
static PFN_vkAllocateCommandBuffers dm_vkAllocateCommandBuffers;
|
||||
#define vkAllocateCommandBuffers dm_vkAllocateCommandBuffers
|
||||
static PFN_vkAllocateDescriptorSets dm_vkAllocateDescriptorSets;
|
||||
#define vkAllocateDescriptorSets dm_vkAllocateDescriptorSets
|
||||
static PFN_vkAllocateMemory dm_vkAllocateMemory;
|
||||
#define vkAllocateMemory dm_vkAllocateMemory
|
||||
static PFN_vkBeginCommandBuffer dm_vkBeginCommandBuffer;
|
||||
#define vkBeginCommandBuffer dm_vkBeginCommandBuffer
|
||||
static PFN_vkBindBufferMemory dm_vkBindBufferMemory;
|
||||
#define vkBindBufferMemory dm_vkBindBufferMemory
|
||||
static PFN_vkBindImageMemory dm_vkBindImageMemory;
|
||||
#define vkBindImageMemory dm_vkBindImageMemory
|
||||
static PFN_vkCmdBeginQuery dm_vkCmdBeginQuery;
|
||||
#define vkCmdBeginQuery dm_vkCmdBeginQuery
|
||||
static PFN_vkCmdBeginRenderPass dm_vkCmdBeginRenderPass;
|
||||
#define vkCmdBeginRenderPass dm_vkCmdBeginRenderPass
|
||||
static PFN_vkCmdBindDescriptorSets dm_vkCmdBindDescriptorSets;
|
||||
#define vkCmdBindDescriptorSets dm_vkCmdBindDescriptorSets
|
||||
static PFN_vkCmdBindIndexBuffer dm_vkCmdBindIndexBuffer;
|
||||
#define vkCmdBindIndexBuffer dm_vkCmdBindIndexBuffer
|
||||
static PFN_vkCmdBindPipeline dm_vkCmdBindPipeline;
|
||||
#define vkCmdBindPipeline dm_vkCmdBindPipeline
|
||||
static PFN_vkCmdBindVertexBuffers dm_vkCmdBindVertexBuffers;
|
||||
#define vkCmdBindVertexBuffers dm_vkCmdBindVertexBuffers
|
||||
static PFN_vkCmdBlitImage dm_vkCmdBlitImage;
|
||||
#define vkCmdBlitImage dm_vkCmdBlitImage
|
||||
static PFN_vkCmdClearAttachments dm_vkCmdClearAttachments;
|
||||
#define vkCmdClearAttachments dm_vkCmdClearAttachments
|
||||
static PFN_vkCmdClearColorImage dm_vkCmdClearColorImage;
|
||||
#define vkCmdClearColorImage dm_vkCmdClearColorImage
|
||||
static PFN_vkCmdClearDepthStencilImage dm_vkCmdClearDepthStencilImage;
|
||||
#define vkCmdClearDepthStencilImage dm_vkCmdClearDepthStencilImage
|
||||
static PFN_vkCmdCopyBuffer dm_vkCmdCopyBuffer;
|
||||
#define vkCmdCopyBuffer dm_vkCmdCopyBuffer
|
||||
static PFN_vkCmdCopyBufferToImage dm_vkCmdCopyBufferToImage;
|
||||
#define vkCmdCopyBufferToImage dm_vkCmdCopyBufferToImage
|
||||
static PFN_vkCmdCopyImageToBuffer dm_vkCmdCopyImageToBuffer;
|
||||
#define vkCmdCopyImageToBuffer dm_vkCmdCopyImageToBuffer
|
||||
static PFN_vkCmdDispatch dm_vkCmdDispatch;
|
||||
#define vkCmdDispatch dm_vkCmdDispatch
|
||||
static PFN_vkCmdDraw dm_vkCmdDraw;
|
||||
#define vkCmdDraw dm_vkCmdDraw
|
||||
static PFN_vkCmdDrawIndexed dm_vkCmdDrawIndexed;
|
||||
#define vkCmdDrawIndexed dm_vkCmdDrawIndexed
|
||||
static PFN_vkCmdEndQuery dm_vkCmdEndQuery;
|
||||
#define vkCmdEndQuery dm_vkCmdEndQuery
|
||||
static PFN_vkCmdEndRenderPass dm_vkCmdEndRenderPass;
|
||||
#define vkCmdEndRenderPass dm_vkCmdEndRenderPass
|
||||
static PFN_vkCmdPipelineBarrier dm_vkCmdPipelineBarrier;
|
||||
#define vkCmdPipelineBarrier dm_vkCmdPipelineBarrier
|
||||
static PFN_vkCmdResetQueryPool dm_vkCmdResetQueryPool;
|
||||
#define vkCmdResetQueryPool dm_vkCmdResetQueryPool
|
||||
static PFN_vkCmdSetBlendConstants dm_vkCmdSetBlendConstants;
|
||||
#define vkCmdSetBlendConstants dm_vkCmdSetBlendConstants
|
||||
static PFN_vkCmdSetScissor dm_vkCmdSetScissor;
|
||||
#define vkCmdSetScissor dm_vkCmdSetScissor
|
||||
static PFN_vkCmdSetViewport dm_vkCmdSetViewport;
|
||||
#define vkCmdSetViewport dm_vkCmdSetViewport
|
||||
static PFN_vkCmdUpdateBuffer dm_vkCmdUpdateBuffer;
|
||||
#define vkCmdUpdateBuffer dm_vkCmdUpdateBuffer
|
||||
static PFN_vkCmdWriteTimestamp dm_vkCmdWriteTimestamp;
|
||||
#define vkCmdWriteTimestamp dm_vkCmdWriteTimestamp
|
||||
static PFN_vkCreateAndroidSurfaceKHR dm_vkCreateAndroidSurfaceKHR;
|
||||
#define vkCreateAndroidSurfaceKHR dm_vkCreateAndroidSurfaceKHR
|
||||
static PFN_vkCreateBuffer dm_vkCreateBuffer;
|
||||
#define vkCreateBuffer dm_vkCreateBuffer
|
||||
static PFN_vkCreateCommandPool dm_vkCreateCommandPool;
|
||||
#define vkCreateCommandPool dm_vkCreateCommandPool
|
||||
static PFN_vkCreateComputePipelines dm_vkCreateComputePipelines;
|
||||
#define vkCreateComputePipelines dm_vkCreateComputePipelines
|
||||
static PFN_vkCreateDescriptorPool dm_vkCreateDescriptorPool;
|
||||
#define vkCreateDescriptorPool dm_vkCreateDescriptorPool
|
||||
static PFN_vkCreateDescriptorSetLayout dm_vkCreateDescriptorSetLayout;
|
||||
#define vkCreateDescriptorSetLayout dm_vkCreateDescriptorSetLayout
|
||||
static PFN_vkCreateDevice dm_vkCreateDevice;
|
||||
#define vkCreateDevice dm_vkCreateDevice
|
||||
static PFN_vkCreateFence dm_vkCreateFence;
|
||||
#define vkCreateFence dm_vkCreateFence
|
||||
static PFN_vkCreateFramebuffer dm_vkCreateFramebuffer;
|
||||
#define vkCreateFramebuffer dm_vkCreateFramebuffer
|
||||
static PFN_vkCreateGraphicsPipelines dm_vkCreateGraphicsPipelines;
|
||||
#define vkCreateGraphicsPipelines dm_vkCreateGraphicsPipelines
|
||||
static PFN_vkCreateImage dm_vkCreateImage;
|
||||
#define vkCreateImage dm_vkCreateImage
|
||||
static PFN_vkCreateImageView dm_vkCreateImageView;
|
||||
#define vkCreateImageView dm_vkCreateImageView
|
||||
static PFN_vkCreateInstance dm_vkCreateInstance;
|
||||
#define vkCreateInstance dm_vkCreateInstance
|
||||
static PFN_vkCreatePipelineCache dm_vkCreatePipelineCache;
|
||||
#define vkCreatePipelineCache dm_vkCreatePipelineCache
|
||||
static PFN_vkCreatePipelineLayout dm_vkCreatePipelineLayout;
|
||||
#define vkCreatePipelineLayout dm_vkCreatePipelineLayout
|
||||
static PFN_vkCreateQueryPool dm_vkCreateQueryPool;
|
||||
#define vkCreateQueryPool dm_vkCreateQueryPool
|
||||
static PFN_vkCreateRenderPass dm_vkCreateRenderPass;
|
||||
#define vkCreateRenderPass dm_vkCreateRenderPass
|
||||
static PFN_vkCreateSampler dm_vkCreateSampler;
|
||||
#define vkCreateSampler dm_vkCreateSampler
|
||||
static PFN_vkCreateSemaphore dm_vkCreateSemaphore;
|
||||
#define vkCreateSemaphore dm_vkCreateSemaphore
|
||||
static PFN_vkCreateShaderModule dm_vkCreateShaderModule;
|
||||
#define vkCreateShaderModule dm_vkCreateShaderModule
|
||||
static PFN_vkCreateSwapchainKHR dm_vkCreateSwapchainKHR;
|
||||
#define vkCreateSwapchainKHR dm_vkCreateSwapchainKHR
|
||||
static PFN_vkDestroyBuffer dm_vkDestroyBuffer;
|
||||
#define vkDestroyBuffer dm_vkDestroyBuffer
|
||||
static PFN_vkDestroyDescriptorPool dm_vkDestroyDescriptorPool;
|
||||
#define vkDestroyDescriptorPool dm_vkDestroyDescriptorPool
|
||||
static PFN_vkDestroyFence dm_vkDestroyFence;
|
||||
#define vkDestroyFence dm_vkDestroyFence
|
||||
static PFN_vkDestroyFramebuffer dm_vkDestroyFramebuffer;
|
||||
#define vkDestroyFramebuffer dm_vkDestroyFramebuffer
|
||||
static PFN_vkDestroyImage dm_vkDestroyImage;
|
||||
#define vkDestroyImage dm_vkDestroyImage
|
||||
static PFN_vkDestroyImageView dm_vkDestroyImageView;
|
||||
#define vkDestroyImageView dm_vkDestroyImageView
|
||||
static PFN_vkDestroyPipeline dm_vkDestroyPipeline;
|
||||
#define vkDestroyPipeline dm_vkDestroyPipeline
|
||||
static PFN_vkDestroyPipelineLayout dm_vkDestroyPipelineLayout;
|
||||
#define vkDestroyPipelineLayout dm_vkDestroyPipelineLayout
|
||||
static PFN_vkDestroyQueryPool dm_vkDestroyQueryPool;
|
||||
#define vkDestroyQueryPool dm_vkDestroyQueryPool
|
||||
static PFN_vkDestroyRenderPass dm_vkDestroyRenderPass;
|
||||
#define vkDestroyRenderPass dm_vkDestroyRenderPass
|
||||
static PFN_vkDestroySampler dm_vkDestroySampler;
|
||||
#define vkDestroySampler dm_vkDestroySampler
|
||||
static PFN_vkDestroySemaphore dm_vkDestroySemaphore;
|
||||
#define vkDestroySemaphore dm_vkDestroySemaphore
|
||||
static PFN_vkDestroySurfaceKHR dm_vkDestroySurfaceKHR;
|
||||
#define vkDestroySurfaceKHR dm_vkDestroySurfaceKHR
|
||||
static PFN_vkDestroySwapchainKHR dm_vkDestroySwapchainKHR;
|
||||
#define vkDestroySwapchainKHR dm_vkDestroySwapchainKHR
|
||||
static PFN_vkDeviceWaitIdle dm_vkDeviceWaitIdle;
|
||||
#define vkDeviceWaitIdle dm_vkDeviceWaitIdle
|
||||
static PFN_vkEndCommandBuffer dm_vkEndCommandBuffer;
|
||||
#define vkEndCommandBuffer dm_vkEndCommandBuffer
|
||||
static PFN_vkEnumeratePhysicalDevices dm_vkEnumeratePhysicalDevices;
|
||||
#define vkEnumeratePhysicalDevices dm_vkEnumeratePhysicalDevices
|
||||
static PFN_vkFreeCommandBuffers dm_vkFreeCommandBuffers;
|
||||
#define vkFreeCommandBuffers dm_vkFreeCommandBuffers
|
||||
static PFN_vkFreeMemory dm_vkFreeMemory;
|
||||
#define vkFreeMemory dm_vkFreeMemory
|
||||
static PFN_vkGetBufferMemoryRequirements dm_vkGetBufferMemoryRequirements;
|
||||
#define vkGetBufferMemoryRequirements dm_vkGetBufferMemoryRequirements
|
||||
static PFN_vkGetDeviceQueue dm_vkGetDeviceQueue;
|
||||
#define vkGetDeviceQueue dm_vkGetDeviceQueue
|
||||
static PFN_vkGetImageMemoryRequirements dm_vkGetImageMemoryRequirements;
|
||||
#define vkGetImageMemoryRequirements dm_vkGetImageMemoryRequirements
|
||||
static PFN_vkGetPhysicalDeviceFeatures dm_vkGetPhysicalDeviceFeatures;
|
||||
#define vkGetPhysicalDeviceFeatures dm_vkGetPhysicalDeviceFeatures
|
||||
static PFN_vkGetPhysicalDeviceFormatProperties dm_vkGetPhysicalDeviceFormatProperties;
|
||||
#define vkGetPhysicalDeviceFormatProperties dm_vkGetPhysicalDeviceFormatProperties
|
||||
static PFN_vkGetPhysicalDeviceMemoryProperties dm_vkGetPhysicalDeviceMemoryProperties;
|
||||
#define vkGetPhysicalDeviceMemoryProperties dm_vkGetPhysicalDeviceMemoryProperties
|
||||
static PFN_vkGetPhysicalDeviceProperties dm_vkGetPhysicalDeviceProperties;
|
||||
#define vkGetPhysicalDeviceProperties dm_vkGetPhysicalDeviceProperties
|
||||
static PFN_vkGetPhysicalDeviceProperties2 dm_vkGetPhysicalDeviceProperties2;
|
||||
#define vkGetPhysicalDeviceProperties2 dm_vkGetPhysicalDeviceProperties2
|
||||
static PFN_vkGetPhysicalDeviceQueueFamilyProperties dm_vkGetPhysicalDeviceQueueFamilyProperties;
|
||||
#define vkGetPhysicalDeviceQueueFamilyProperties dm_vkGetPhysicalDeviceQueueFamilyProperties
|
||||
static PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR dm_vkGetPhysicalDeviceSurfaceCapabilitiesKHR;
|
||||
#define vkGetPhysicalDeviceSurfaceCapabilitiesKHR dm_vkGetPhysicalDeviceSurfaceCapabilitiesKHR
|
||||
static PFN_vkGetPhysicalDeviceSurfaceFormatsKHR dm_vkGetPhysicalDeviceSurfaceFormatsKHR;
|
||||
#define vkGetPhysicalDeviceSurfaceFormatsKHR dm_vkGetPhysicalDeviceSurfaceFormatsKHR
|
||||
static PFN_vkGetPhysicalDeviceSurfaceSupportKHR dm_vkGetPhysicalDeviceSurfaceSupportKHR;
|
||||
#define vkGetPhysicalDeviceSurfaceSupportKHR dm_vkGetPhysicalDeviceSurfaceSupportKHR
|
||||
static PFN_vkGetQueryPoolResults dm_vkGetQueryPoolResults;
|
||||
#define vkGetQueryPoolResults dm_vkGetQueryPoolResults
|
||||
static PFN_vkGetSwapchainImagesKHR dm_vkGetSwapchainImagesKHR;
|
||||
#define vkGetSwapchainImagesKHR dm_vkGetSwapchainImagesKHR
|
||||
static PFN_vkMapMemory dm_vkMapMemory;
|
||||
#define vkMapMemory dm_vkMapMemory
|
||||
static PFN_vkQueuePresentKHR dm_vkQueuePresentKHR;
|
||||
#define vkQueuePresentKHR dm_vkQueuePresentKHR
|
||||
static PFN_vkQueueSubmit dm_vkQueueSubmit;
|
||||
#define vkQueueSubmit dm_vkQueueSubmit
|
||||
static PFN_vkQueueWaitIdle dm_vkQueueWaitIdle;
|
||||
#define vkQueueWaitIdle dm_vkQueueWaitIdle
|
||||
static PFN_vkUnmapMemory dm_vkUnmapMemory;
|
||||
#define vkUnmapMemory dm_vkUnmapMemory
|
||||
static PFN_vkUpdateDescriptorSets dm_vkUpdateDescriptorSets;
|
||||
#define vkUpdateDescriptorSets dm_vkUpdateDescriptorSets
|
||||
static PFN_vkWaitForFences dm_vkWaitForFences;
|
||||
#define vkWaitForFences dm_vkWaitForFences
|
||||
static PFN_vkCreateBufferView dm_vkCreateBufferView;
|
||||
#define vkCreateBufferView dm_vkCreateBufferView
|
||||
static PFN_vkDestroyBufferView dm_vkDestroyBufferView;
|
||||
#define vkDestroyBufferView dm_vkDestroyBufferView
|
||||
static PFN_vkCmdCopyImage dm_vkCmdCopyImage;
|
||||
#define vkCmdCopyImage dm_vkCmdCopyImage
|
||||
static void dm_vk_resolve(VkInstance instance) {
|
||||
dm_vkCmdCopyImage=(PFN_vkCmdCopyImage)dm_vk_get(instance,"vkCmdCopyImage");if(!dm_vkCmdCopyImage)die("Vulkan dispatch vkCmdCopyImage",0);
|
||||
dm_vkDestroyBufferView=(PFN_vkDestroyBufferView)dm_vk_get(instance,"vkDestroyBufferView");if(!dm_vkDestroyBufferView)die("Vulkan dispatch vkDestroyBufferView",0);
|
||||
dm_vkCreateBufferView=(PFN_vkCreateBufferView)dm_vk_get(instance,"vkCreateBufferView");if(!dm_vkCreateBufferView)die("Vulkan dispatch vkCreateBufferView",0);
|
||||
dm_vkAcquireNextImageKHR=(PFN_vkAcquireNextImageKHR)dm_vk_get(instance,"vkAcquireNextImageKHR");if(!dm_vkAcquireNextImageKHR)die("Vulkan dispatch vkAcquireNextImageKHR",0);
|
||||
dm_vkAllocateCommandBuffers=(PFN_vkAllocateCommandBuffers)dm_vk_get(instance,"vkAllocateCommandBuffers");if(!dm_vkAllocateCommandBuffers)die("Vulkan dispatch vkAllocateCommandBuffers",0);
|
||||
dm_vkAllocateDescriptorSets=(PFN_vkAllocateDescriptorSets)dm_vk_get(instance,"vkAllocateDescriptorSets");if(!dm_vkAllocateDescriptorSets)die("Vulkan dispatch vkAllocateDescriptorSets",0);
|
||||
dm_vkAllocateMemory=(PFN_vkAllocateMemory)dm_vk_get(instance,"vkAllocateMemory");if(!dm_vkAllocateMemory)die("Vulkan dispatch vkAllocateMemory",0);
|
||||
dm_vkBeginCommandBuffer=(PFN_vkBeginCommandBuffer)dm_vk_get(instance,"vkBeginCommandBuffer");if(!dm_vkBeginCommandBuffer)die("Vulkan dispatch vkBeginCommandBuffer",0);
|
||||
dm_vkBindBufferMemory=(PFN_vkBindBufferMemory)dm_vk_get(instance,"vkBindBufferMemory");if(!dm_vkBindBufferMemory)die("Vulkan dispatch vkBindBufferMemory",0);
|
||||
dm_vkBindImageMemory=(PFN_vkBindImageMemory)dm_vk_get(instance,"vkBindImageMemory");if(!dm_vkBindImageMemory)die("Vulkan dispatch vkBindImageMemory",0);
|
||||
dm_vkCmdBeginQuery=(PFN_vkCmdBeginQuery)dm_vk_get(instance,"vkCmdBeginQuery");if(!dm_vkCmdBeginQuery)die("Vulkan dispatch vkCmdBeginQuery",0);
|
||||
dm_vkCmdBeginRenderPass=(PFN_vkCmdBeginRenderPass)dm_vk_get(instance,"vkCmdBeginRenderPass");if(!dm_vkCmdBeginRenderPass)die("Vulkan dispatch vkCmdBeginRenderPass",0);
|
||||
dm_vkCmdBindDescriptorSets=(PFN_vkCmdBindDescriptorSets)dm_vk_get(instance,"vkCmdBindDescriptorSets");if(!dm_vkCmdBindDescriptorSets)die("Vulkan dispatch vkCmdBindDescriptorSets",0);
|
||||
dm_vkCmdBindIndexBuffer=(PFN_vkCmdBindIndexBuffer)dm_vk_get(instance,"vkCmdBindIndexBuffer");if(!dm_vkCmdBindIndexBuffer)die("Vulkan dispatch vkCmdBindIndexBuffer",0);
|
||||
dm_vkCmdBindPipeline=(PFN_vkCmdBindPipeline)dm_vk_get(instance,"vkCmdBindPipeline");if(!dm_vkCmdBindPipeline)die("Vulkan dispatch vkCmdBindPipeline",0);
|
||||
dm_vkCmdBindVertexBuffers=(PFN_vkCmdBindVertexBuffers)dm_vk_get(instance,"vkCmdBindVertexBuffers");if(!dm_vkCmdBindVertexBuffers)die("Vulkan dispatch vkCmdBindVertexBuffers",0);
|
||||
dm_vkCmdBlitImage=(PFN_vkCmdBlitImage)dm_vk_get(instance,"vkCmdBlitImage");if(!dm_vkCmdBlitImage)die("Vulkan dispatch vkCmdBlitImage",0);
|
||||
dm_vkCmdClearAttachments=(PFN_vkCmdClearAttachments)dm_vk_get(instance,"vkCmdClearAttachments");if(!dm_vkCmdClearAttachments)die("Vulkan dispatch vkCmdClearAttachments",0);
|
||||
dm_vkCmdClearColorImage=(PFN_vkCmdClearColorImage)dm_vk_get(instance,"vkCmdClearColorImage");if(!dm_vkCmdClearColorImage)die("Vulkan dispatch vkCmdClearColorImage",0);
|
||||
dm_vkCmdClearDepthStencilImage=(PFN_vkCmdClearDepthStencilImage)dm_vk_get(instance,"vkCmdClearDepthStencilImage");if(!dm_vkCmdClearDepthStencilImage)die("Vulkan dispatch vkCmdClearDepthStencilImage",0);
|
||||
dm_vkCmdCopyBuffer=(PFN_vkCmdCopyBuffer)dm_vk_get(instance,"vkCmdCopyBuffer");if(!dm_vkCmdCopyBuffer)die("Vulkan dispatch vkCmdCopyBuffer",0);
|
||||
dm_vkCmdCopyBufferToImage=(PFN_vkCmdCopyBufferToImage)dm_vk_get(instance,"vkCmdCopyBufferToImage");if(!dm_vkCmdCopyBufferToImage)die("Vulkan dispatch vkCmdCopyBufferToImage",0);
|
||||
dm_vkCmdCopyImageToBuffer=(PFN_vkCmdCopyImageToBuffer)dm_vk_get(instance,"vkCmdCopyImageToBuffer");if(!dm_vkCmdCopyImageToBuffer)die("Vulkan dispatch vkCmdCopyImageToBuffer",0);
|
||||
dm_vkCmdDispatch=(PFN_vkCmdDispatch)dm_vk_get(instance,"vkCmdDispatch");if(!dm_vkCmdDispatch)die("Vulkan dispatch vkCmdDispatch",0);
|
||||
dm_vkCmdDraw=(PFN_vkCmdDraw)dm_vk_get(instance,"vkCmdDraw");if(!dm_vkCmdDraw)die("Vulkan dispatch vkCmdDraw",0);
|
||||
dm_vkCmdDrawIndexed=(PFN_vkCmdDrawIndexed)dm_vk_get(instance,"vkCmdDrawIndexed");if(!dm_vkCmdDrawIndexed)die("Vulkan dispatch vkCmdDrawIndexed",0);
|
||||
dm_vkCmdEndQuery=(PFN_vkCmdEndQuery)dm_vk_get(instance,"vkCmdEndQuery");if(!dm_vkCmdEndQuery)die("Vulkan dispatch vkCmdEndQuery",0);
|
||||
dm_vkCmdEndRenderPass=(PFN_vkCmdEndRenderPass)dm_vk_get(instance,"vkCmdEndRenderPass");if(!dm_vkCmdEndRenderPass)die("Vulkan dispatch vkCmdEndRenderPass",0);
|
||||
dm_vkCmdPipelineBarrier=(PFN_vkCmdPipelineBarrier)dm_vk_get(instance,"vkCmdPipelineBarrier");if(!dm_vkCmdPipelineBarrier)die("Vulkan dispatch vkCmdPipelineBarrier",0);
|
||||
dm_vkCmdResetQueryPool=(PFN_vkCmdResetQueryPool)dm_vk_get(instance,"vkCmdResetQueryPool");if(!dm_vkCmdResetQueryPool)die("Vulkan dispatch vkCmdResetQueryPool",0);
|
||||
dm_vkCmdSetBlendConstants=(PFN_vkCmdSetBlendConstants)dm_vk_get(instance,"vkCmdSetBlendConstants");if(!dm_vkCmdSetBlendConstants)die("Vulkan dispatch vkCmdSetBlendConstants",0);
|
||||
dm_vkCmdSetScissor=(PFN_vkCmdSetScissor)dm_vk_get(instance,"vkCmdSetScissor");if(!dm_vkCmdSetScissor)die("Vulkan dispatch vkCmdSetScissor",0);
|
||||
dm_vkCmdSetViewport=(PFN_vkCmdSetViewport)dm_vk_get(instance,"vkCmdSetViewport");if(!dm_vkCmdSetViewport)die("Vulkan dispatch vkCmdSetViewport",0);
|
||||
dm_vkCmdUpdateBuffer=(PFN_vkCmdUpdateBuffer)dm_vk_get(instance,"vkCmdUpdateBuffer");if(!dm_vkCmdUpdateBuffer)die("Vulkan dispatch vkCmdUpdateBuffer",0);
|
||||
dm_vkCmdWriteTimestamp=(PFN_vkCmdWriteTimestamp)dm_vk_get(instance,"vkCmdWriteTimestamp");if(!dm_vkCmdWriteTimestamp)die("Vulkan dispatch vkCmdWriteTimestamp",0);
|
||||
dm_vkCreateAndroidSurfaceKHR=(PFN_vkCreateAndroidSurfaceKHR)dm_vk_get(instance,"vkCreateAndroidSurfaceKHR");if(!dm_vkCreateAndroidSurfaceKHR)die("Vulkan dispatch vkCreateAndroidSurfaceKHR",0);
|
||||
dm_vkCreateBuffer=(PFN_vkCreateBuffer)dm_vk_get(instance,"vkCreateBuffer");if(!dm_vkCreateBuffer)die("Vulkan dispatch vkCreateBuffer",0);
|
||||
dm_vkCreateCommandPool=(PFN_vkCreateCommandPool)dm_vk_get(instance,"vkCreateCommandPool");if(!dm_vkCreateCommandPool)die("Vulkan dispatch vkCreateCommandPool",0);
|
||||
dm_vkCreateComputePipelines=(PFN_vkCreateComputePipelines)dm_vk_get(instance,"vkCreateComputePipelines");if(!dm_vkCreateComputePipelines)die("Vulkan dispatch vkCreateComputePipelines",0);
|
||||
dm_vkCreateDescriptorPool=(PFN_vkCreateDescriptorPool)dm_vk_get(instance,"vkCreateDescriptorPool");if(!dm_vkCreateDescriptorPool)die("Vulkan dispatch vkCreateDescriptorPool",0);
|
||||
dm_vkCreateDescriptorSetLayout=(PFN_vkCreateDescriptorSetLayout)dm_vk_get(instance,"vkCreateDescriptorSetLayout");if(!dm_vkCreateDescriptorSetLayout)die("Vulkan dispatch vkCreateDescriptorSetLayout",0);
|
||||
dm_vkCreateDevice=(PFN_vkCreateDevice)dm_vk_get(instance,"vkCreateDevice");if(!dm_vkCreateDevice)die("Vulkan dispatch vkCreateDevice",0);
|
||||
dm_vkCreateFence=(PFN_vkCreateFence)dm_vk_get(instance,"vkCreateFence");if(!dm_vkCreateFence)die("Vulkan dispatch vkCreateFence",0);
|
||||
dm_vkCreateFramebuffer=(PFN_vkCreateFramebuffer)dm_vk_get(instance,"vkCreateFramebuffer");if(!dm_vkCreateFramebuffer)die("Vulkan dispatch vkCreateFramebuffer",0);
|
||||
dm_vkCreateGraphicsPipelines=(PFN_vkCreateGraphicsPipelines)dm_vk_get(instance,"vkCreateGraphicsPipelines");if(!dm_vkCreateGraphicsPipelines)die("Vulkan dispatch vkCreateGraphicsPipelines",0);
|
||||
dm_vkCreateImage=(PFN_vkCreateImage)dm_vk_get(instance,"vkCreateImage");if(!dm_vkCreateImage)die("Vulkan dispatch vkCreateImage",0);
|
||||
dm_vkCreateImageView=(PFN_vkCreateImageView)dm_vk_get(instance,"vkCreateImageView");if(!dm_vkCreateImageView)die("Vulkan dispatch vkCreateImageView",0);
|
||||
dm_vkCreatePipelineCache=(PFN_vkCreatePipelineCache)dm_vk_get(instance,"vkCreatePipelineCache");if(!dm_vkCreatePipelineCache)die("Vulkan dispatch vkCreatePipelineCache",0);
|
||||
dm_vkCreatePipelineLayout=(PFN_vkCreatePipelineLayout)dm_vk_get(instance,"vkCreatePipelineLayout");if(!dm_vkCreatePipelineLayout)die("Vulkan dispatch vkCreatePipelineLayout",0);
|
||||
dm_vkCreateQueryPool=(PFN_vkCreateQueryPool)dm_vk_get(instance,"vkCreateQueryPool");if(!dm_vkCreateQueryPool)die("Vulkan dispatch vkCreateQueryPool",0);
|
||||
dm_vkCreateRenderPass=(PFN_vkCreateRenderPass)dm_vk_get(instance,"vkCreateRenderPass");if(!dm_vkCreateRenderPass)die("Vulkan dispatch vkCreateRenderPass",0);
|
||||
dm_vkCreateSampler=(PFN_vkCreateSampler)dm_vk_get(instance,"vkCreateSampler");if(!dm_vkCreateSampler)die("Vulkan dispatch vkCreateSampler",0);
|
||||
dm_vkCreateSemaphore=(PFN_vkCreateSemaphore)dm_vk_get(instance,"vkCreateSemaphore");if(!dm_vkCreateSemaphore)die("Vulkan dispatch vkCreateSemaphore",0);
|
||||
dm_vkCreateShaderModule=(PFN_vkCreateShaderModule)dm_vk_get(instance,"vkCreateShaderModule");if(!dm_vkCreateShaderModule)die("Vulkan dispatch vkCreateShaderModule",0);
|
||||
dm_vkCreateSwapchainKHR=(PFN_vkCreateSwapchainKHR)dm_vk_get(instance,"vkCreateSwapchainKHR");if(!dm_vkCreateSwapchainKHR)die("Vulkan dispatch vkCreateSwapchainKHR",0);
|
||||
dm_vkDestroyBuffer=(PFN_vkDestroyBuffer)dm_vk_get(instance,"vkDestroyBuffer");if(!dm_vkDestroyBuffer)die("Vulkan dispatch vkDestroyBuffer",0);
|
||||
dm_vkDestroyDescriptorPool=(PFN_vkDestroyDescriptorPool)dm_vk_get(instance,"vkDestroyDescriptorPool");if(!dm_vkDestroyDescriptorPool)die("Vulkan dispatch vkDestroyDescriptorPool",0);
|
||||
dm_vkDestroyFence=(PFN_vkDestroyFence)dm_vk_get(instance,"vkDestroyFence");if(!dm_vkDestroyFence)die("Vulkan dispatch vkDestroyFence",0);
|
||||
dm_vkDestroyFramebuffer=(PFN_vkDestroyFramebuffer)dm_vk_get(instance,"vkDestroyFramebuffer");if(!dm_vkDestroyFramebuffer)die("Vulkan dispatch vkDestroyFramebuffer",0);
|
||||
dm_vkDestroyImage=(PFN_vkDestroyImage)dm_vk_get(instance,"vkDestroyImage");if(!dm_vkDestroyImage)die("Vulkan dispatch vkDestroyImage",0);
|
||||
dm_vkDestroyImageView=(PFN_vkDestroyImageView)dm_vk_get(instance,"vkDestroyImageView");if(!dm_vkDestroyImageView)die("Vulkan dispatch vkDestroyImageView",0);
|
||||
dm_vkDestroyPipeline=(PFN_vkDestroyPipeline)dm_vk_get(instance,"vkDestroyPipeline");if(!dm_vkDestroyPipeline)die("Vulkan dispatch vkDestroyPipeline",0);
|
||||
dm_vkDestroyPipelineLayout=(PFN_vkDestroyPipelineLayout)dm_vk_get(instance,"vkDestroyPipelineLayout");if(!dm_vkDestroyPipelineLayout)die("Vulkan dispatch vkDestroyPipelineLayout",0);
|
||||
dm_vkDestroyQueryPool=(PFN_vkDestroyQueryPool)dm_vk_get(instance,"vkDestroyQueryPool");if(!dm_vkDestroyQueryPool)die("Vulkan dispatch vkDestroyQueryPool",0);
|
||||
dm_vkDestroyRenderPass=(PFN_vkDestroyRenderPass)dm_vk_get(instance,"vkDestroyRenderPass");if(!dm_vkDestroyRenderPass)die("Vulkan dispatch vkDestroyRenderPass",0);
|
||||
dm_vkDestroySampler=(PFN_vkDestroySampler)dm_vk_get(instance,"vkDestroySampler");if(!dm_vkDestroySampler)die("Vulkan dispatch vkDestroySampler",0);
|
||||
dm_vkDestroySemaphore=(PFN_vkDestroySemaphore)dm_vk_get(instance,"vkDestroySemaphore");if(!dm_vkDestroySemaphore)die("Vulkan dispatch vkDestroySemaphore",0);
|
||||
dm_vkDestroySurfaceKHR=(PFN_vkDestroySurfaceKHR)dm_vk_get(instance,"vkDestroySurfaceKHR");if(!dm_vkDestroySurfaceKHR)die("Vulkan dispatch vkDestroySurfaceKHR",0);
|
||||
dm_vkDestroySwapchainKHR=(PFN_vkDestroySwapchainKHR)dm_vk_get(instance,"vkDestroySwapchainKHR");if(!dm_vkDestroySwapchainKHR)die("Vulkan dispatch vkDestroySwapchainKHR",0);
|
||||
dm_vkDeviceWaitIdle=(PFN_vkDeviceWaitIdle)dm_vk_get(instance,"vkDeviceWaitIdle");if(!dm_vkDeviceWaitIdle)die("Vulkan dispatch vkDeviceWaitIdle",0);
|
||||
dm_vkEndCommandBuffer=(PFN_vkEndCommandBuffer)dm_vk_get(instance,"vkEndCommandBuffer");if(!dm_vkEndCommandBuffer)die("Vulkan dispatch vkEndCommandBuffer",0);
|
||||
dm_vkEnumeratePhysicalDevices=(PFN_vkEnumeratePhysicalDevices)dm_vk_get(instance,"vkEnumeratePhysicalDevices");if(!dm_vkEnumeratePhysicalDevices)die("Vulkan dispatch vkEnumeratePhysicalDevices",0);
|
||||
dm_vkFreeCommandBuffers=(PFN_vkFreeCommandBuffers)dm_vk_get(instance,"vkFreeCommandBuffers");if(!dm_vkFreeCommandBuffers)die("Vulkan dispatch vkFreeCommandBuffers",0);
|
||||
dm_vkFreeMemory=(PFN_vkFreeMemory)dm_vk_get(instance,"vkFreeMemory");if(!dm_vkFreeMemory)die("Vulkan dispatch vkFreeMemory",0);
|
||||
dm_vkGetBufferMemoryRequirements=(PFN_vkGetBufferMemoryRequirements)dm_vk_get(instance,"vkGetBufferMemoryRequirements");if(!dm_vkGetBufferMemoryRequirements)die("Vulkan dispatch vkGetBufferMemoryRequirements",0);
|
||||
dm_vkGetDeviceQueue=(PFN_vkGetDeviceQueue)dm_vk_get(instance,"vkGetDeviceQueue");if(!dm_vkGetDeviceQueue)die("Vulkan dispatch vkGetDeviceQueue",0);
|
||||
dm_vkGetImageMemoryRequirements=(PFN_vkGetImageMemoryRequirements)dm_vk_get(instance,"vkGetImageMemoryRequirements");if(!dm_vkGetImageMemoryRequirements)die("Vulkan dispatch vkGetImageMemoryRequirements",0);
|
||||
dm_vkGetPhysicalDeviceFeatures=(PFN_vkGetPhysicalDeviceFeatures)dm_vk_get(instance,"vkGetPhysicalDeviceFeatures");if(!dm_vkGetPhysicalDeviceFeatures)die("Vulkan dispatch vkGetPhysicalDeviceFeatures",0);
|
||||
dm_vkGetPhysicalDeviceFormatProperties=(PFN_vkGetPhysicalDeviceFormatProperties)dm_vk_get(instance,"vkGetPhysicalDeviceFormatProperties");if(!dm_vkGetPhysicalDeviceFormatProperties)die("Vulkan dispatch vkGetPhysicalDeviceFormatProperties",0);
|
||||
dm_vkGetPhysicalDeviceMemoryProperties=(PFN_vkGetPhysicalDeviceMemoryProperties)dm_vk_get(instance,"vkGetPhysicalDeviceMemoryProperties");if(!dm_vkGetPhysicalDeviceMemoryProperties)die("Vulkan dispatch vkGetPhysicalDeviceMemoryProperties",0);
|
||||
dm_vkGetPhysicalDeviceProperties=(PFN_vkGetPhysicalDeviceProperties)dm_vk_get(instance,"vkGetPhysicalDeviceProperties");if(!dm_vkGetPhysicalDeviceProperties)die("Vulkan dispatch vkGetPhysicalDeviceProperties",0);
|
||||
dm_vkGetPhysicalDeviceProperties2=(PFN_vkGetPhysicalDeviceProperties2)dm_vk_get(instance,"vkGetPhysicalDeviceProperties2");if(!dm_vkGetPhysicalDeviceProperties2)die("Vulkan dispatch vkGetPhysicalDeviceProperties2",0);
|
||||
dm_vkGetPhysicalDeviceQueueFamilyProperties=(PFN_vkGetPhysicalDeviceQueueFamilyProperties)dm_vk_get(instance,"vkGetPhysicalDeviceQueueFamilyProperties");if(!dm_vkGetPhysicalDeviceQueueFamilyProperties)die("Vulkan dispatch vkGetPhysicalDeviceQueueFamilyProperties",0);
|
||||
dm_vkGetPhysicalDeviceSurfaceCapabilitiesKHR=(PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR)dm_vk_get(instance,"vkGetPhysicalDeviceSurfaceCapabilitiesKHR");if(!dm_vkGetPhysicalDeviceSurfaceCapabilitiesKHR)die("Vulkan dispatch vkGetPhysicalDeviceSurfaceCapabilitiesKHR",0);
|
||||
dm_vkGetPhysicalDeviceSurfaceFormatsKHR=(PFN_vkGetPhysicalDeviceSurfaceFormatsKHR)dm_vk_get(instance,"vkGetPhysicalDeviceSurfaceFormatsKHR");if(!dm_vkGetPhysicalDeviceSurfaceFormatsKHR)die("Vulkan dispatch vkGetPhysicalDeviceSurfaceFormatsKHR",0);
|
||||
dm_vkGetPhysicalDeviceSurfaceSupportKHR=(PFN_vkGetPhysicalDeviceSurfaceSupportKHR)dm_vk_get(instance,"vkGetPhysicalDeviceSurfaceSupportKHR");if(!dm_vkGetPhysicalDeviceSurfaceSupportKHR)die("Vulkan dispatch vkGetPhysicalDeviceSurfaceSupportKHR",0);
|
||||
dm_vkGetQueryPoolResults=(PFN_vkGetQueryPoolResults)dm_vk_get(instance,"vkGetQueryPoolResults");if(!dm_vkGetQueryPoolResults)die("Vulkan dispatch vkGetQueryPoolResults",0);
|
||||
dm_vkGetSwapchainImagesKHR=(PFN_vkGetSwapchainImagesKHR)dm_vk_get(instance,"vkGetSwapchainImagesKHR");if(!dm_vkGetSwapchainImagesKHR)die("Vulkan dispatch vkGetSwapchainImagesKHR",0);
|
||||
dm_vkMapMemory=(PFN_vkMapMemory)dm_vk_get(instance,"vkMapMemory");if(!dm_vkMapMemory)die("Vulkan dispatch vkMapMemory",0);
|
||||
dm_vkQueuePresentKHR=(PFN_vkQueuePresentKHR)dm_vk_get(instance,"vkQueuePresentKHR");if(!dm_vkQueuePresentKHR)die("Vulkan dispatch vkQueuePresentKHR",0);
|
||||
dm_vkQueueSubmit=(PFN_vkQueueSubmit)dm_vk_get(instance,"vkQueueSubmit");if(!dm_vkQueueSubmit)die("Vulkan dispatch vkQueueSubmit",0);
|
||||
dm_vkQueueWaitIdle=(PFN_vkQueueWaitIdle)dm_vk_get(instance,"vkQueueWaitIdle");if(!dm_vkQueueWaitIdle)die("Vulkan dispatch vkQueueWaitIdle",0);
|
||||
dm_vkUnmapMemory=(PFN_vkUnmapMemory)dm_vk_get(instance,"vkUnmapMemory");if(!dm_vkUnmapMemory)die("Vulkan dispatch vkUnmapMemory",0);
|
||||
dm_vkUpdateDescriptorSets=(PFN_vkUpdateDescriptorSets)dm_vk_get(instance,"vkUpdateDescriptorSets");if(!dm_vkUpdateDescriptorSets)die("Vulkan dispatch vkUpdateDescriptorSets",0);
|
||||
dm_vkWaitForFences=(PFN_vkWaitForFences)dm_vk_get(instance,"vkWaitForFences");if(!dm_vkWaitForFences)die("Vulkan dispatch vkWaitForFences",0);
|
||||
dm_vkGetPipelineCacheData=(PFN_vkGetPipelineCacheData)dm_vk_get(instance,"vkGetPipelineCacheData");if(!dm_vkGetPipelineCacheData)die("Vulkan dispatch vkGetPipelineCacheData",0);
|
||||
dm_vkGetFenceStatus=(PFN_vkGetFenceStatus)dm_vk_get(instance,"vkGetFenceStatus");if(!dm_vkGetFenceStatus)die("Vulkan dispatch vkGetFenceStatus",0);
|
||||
dm_vkResetFences=(PFN_vkResetFences)dm_vk_get(instance,"vkResetFences");if(!dm_vkResetFences)die("Vulkan dispatch vkResetFences",0);
|
||||
dm_vkResetCommandBuffer=(PFN_vkResetCommandBuffer)dm_vk_get(instance,"vkResetCommandBuffer");if(!dm_vkResetCommandBuffer)die("Vulkan dispatch vkResetCommandBuffer",0);
|
||||
dm_vkResetCommandPool=(PFN_vkResetCommandPool)dm_vk_get(instance,"vkResetCommandPool");if(!dm_vkResetCommandPool)die("Vulkan dispatch vkResetCommandPool",0);
|
||||
dm_vkResetDescriptorPool=(PFN_vkResetDescriptorPool)dm_vk_get(instance,"vkResetDescriptorPool");if(!dm_vkResetDescriptorPool)die("Vulkan dispatch vkResetDescriptorPool",0);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/* Per-mip layout tracking, inspired by dodola/d2r-mobile's Vulkan backend
|
||||
* (642480b). Keep the current backend's conservative synchronization masks.
|
||||
* No game addresses, platform services or shader metadata are shared. */
|
||||
#ifndef NVN_VK_MIP_LAYOUT_H
|
||||
#define NVN_VK_MIP_LAYOUT_H
|
||||
#include <vulkan/vulkan_core.h>
|
||||
|
||||
#define NVN_VK_TRACKED_MIPS 16
|
||||
typedef struct {
|
||||
/* uniform is only usable as an image-wide layout when mixed == 0. */
|
||||
VkImageLayout uniform, levels[NVN_VK_TRACKED_MIPS];
|
||||
unsigned mixed;
|
||||
} NvnVkMipLayouts;
|
||||
typedef void (*NvnVkMipBarrier)(void *, VkImageLayout, VkImageLayout, unsigned, unsigned);
|
||||
|
||||
static inline int nvn_vk_mip_mask(unsigned total, unsigned base, unsigned count, unsigned *mask) {
|
||||
if (!total || total > NVN_VK_TRACKED_MIPS || base >= total || !count || count > total - base) return 0;
|
||||
*mask = ((1u << count) - 1u) << base;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Validate before changing state or emitting barriers. Whole-image transitions
|
||||
* remain supported for images outside the bounded per-mip tracking path. */
|
||||
static inline int nvn_vk_mip_transition(NvnVkMipLayouts *s, unsigned total,
|
||||
unsigned base, unsigned count, VkImageLayout next, NvnVkMipBarrier emit, void *ctx) {
|
||||
if (!total || base >= total || !count || count > total - base ||
|
||||
(total > NVN_VK_TRACKED_MIPS && (base || count != total || s->mixed))) return 0;
|
||||
if (!s->mixed) {
|
||||
if (s->uniform == next) return 1;
|
||||
if (!base && count == total) {
|
||||
emit(ctx, s->uniform, next, 0, total); s->uniform = next; return 1;
|
||||
}
|
||||
for (unsigned i = 0; i < total; i++) s->levels[i] = s->uniform;
|
||||
s->mixed = 1;
|
||||
}
|
||||
for (unsigned i = base; i < base + count;) {
|
||||
VkImageLayout old = s->levels[i];
|
||||
if (old == next) { i++; continue; }
|
||||
unsigned end = i + 1;
|
||||
while (end < base + count && s->levels[end] == old) end++;
|
||||
emit(ctx, old, next, i, end - i);
|
||||
for (unsigned k = i; k < end; k++) s->levels[k] = next;
|
||||
i = end;
|
||||
}
|
||||
unsigned i = 1;
|
||||
while (i < total && s->levels[i] == s->levels[0]) i++;
|
||||
if (i == total) { s->uniform = s->levels[0]; s->mixed = 0; }
|
||||
return 1;
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,27 @@
|
||||
// Vulkan 后端暂不提供的 Metal 统计 / 调度接口:一律「无数据」,宿主诊断按缺数据处理
|
||||
// Metal statistics / scheduling interfaces the Vulkan backend does not provide yet: all "no data", host diagnostics treat them as missing
|
||||
#include "../../host/dm.h"
|
||||
#include "nvn_obj.h"
|
||||
#include "nvn_mtl.h"
|
||||
|
||||
uint32_t mtl_present_qos(void) { return 0; }
|
||||
__attribute__((weak)) int dm_fps_setting(void) { return 60; } // 宿主 dm_custom.c 提供强定义(省电模式 eco_fps) | The host's dm_custom.c provides the strong definition (power-saving mode eco_fps)
|
||||
int mtl_fps_target(void) { // 与 nvn_mtl.m 同义:DM_FPS=30/60 钉住,否则跟自定义页的省电模式 | Same as nvn_mtl.m: DM_FPS=30/60 pins it, otherwise follows the Custom page's power-saving mode
|
||||
static int env = -2;
|
||||
if (env == -2) { const char *e = getenv("DM_FPS"); env = e ? atoi(e) : -1; if (env != 30 && env != 60) env = -1; }
|
||||
return env > 0 ? env : dm_fps_setting() == 30 ? 30 : 60;
|
||||
}
|
||||
void mtl_args_stats(uint64_t *enc, uint64_t *reuse) { *enc = *reuse = 0; }
|
||||
void mtl_use_stats(uint64_t *call, uint64_t *skip) { *call = *skip = 0; }
|
||||
uint64_t mtl_ds_omit(void) { return 0; }
|
||||
uint64_t mtl_drawable_ns_take(void) { return 0; }
|
||||
void mtl_bw(uint64_t *load, uint64_t *store, uint64_t *full_rw_passes) { *load = *store = *full_rw_passes = 0; }
|
||||
uint64_t mtl_udc_saved_bytes(void) { return 0; }
|
||||
uint64_t mtl_pkg_miss(void) { return 0; }
|
||||
uint64_t mtl_upload_ns_take(void) { return 0; }
|
||||
uint64_t mtl_upload_gpu_ns_take(void) { return 0; }
|
||||
void mtl_alloc_stats(uint64_t *waits, uint64_t *grown, int *n) { *waits = *grown = 0; *n = 0; }
|
||||
void mtl_mem_stat(unsigned long long frame, unsigned long long rss_mb, int heap_ok, unsigned long long heap_mb, unsigned long long heap_free_mb, unsigned long long heap_maxblk_kb) {
|
||||
(void)frame; (void)rss_mb; (void)heap_ok; (void)heap_mb; (void)heap_free_mb; (void)heap_maxblk_kb;
|
||||
}
|
||||
int dm_nvn_ruler_truth(void) { return 0; }
|
||||
@@ -0,0 +1,16 @@
|
||||
// Vulkan 后端的平台钩子(移植自 dodola/d2r-mobile 的 android/nvn_platform_*):单调时钟 + 前端交给后端的窗口 / 着色器目录
|
||||
// Platform hooks of the Vulkan backend (ported from android/nvn_platform_* of dodola/d2r-mobile): monotonic clock + window / shader directory handed over by the front end
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <time.h>
|
||||
static inline uint64_t dm_android_nvn_clock_ns(void) {
|
||||
struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t);
|
||||
return (uint64_t)t.tv_sec * 1000000000ull + (uint64_t)t.tv_nsec;
|
||||
}
|
||||
void dm_vk_set_shader_root(const char *path); // 着色器运行包目录(shader_index.bin / *.vkmeta / *.spv.gz) | shader runtime pack directory
|
||||
void dm_vk_set_window(void *native); // ANativeWindow*;NULL = 无头(不上屏,只按需读回) | ANativeWindow*; NULL = headless (no swapchain, readback on demand)
|
||||
void dm_vk_set_display_hz(int hz);
|
||||
// on = 1:没有窗口时出图阻塞到 dm_vk_set_window 给回窗口(App 切后台);0 = 无头照常跑 | on = 1: with no window, present blocks until dm_vk_set_window returns one (app in background); 0 = headless runs as usual
|
||||
void dm_vk_hold_without_window(int on);
|
||||
void *dm_vk_native_window(void);
|
||||
@@ -4,3 +4,4 @@ dm_hud_exp.h
|
||||
dm_bright_levels.inc
|
||||
*.h.tmp
|
||||
*.inc.tmp
|
||||
|
||||
|
||||
+5
-5
@@ -61,7 +61,7 @@ SRC=\
|
||||
touch_mac.c \
|
||||
../ios/Sources/cloud_ios.m \
|
||||
../ios/Sources/dm_gamepad.m \
|
||||
../ios/Sources/dm_touch_controls.c \
|
||||
../touch/dm_touch_controls.c \
|
||||
$(sort $(wildcard hle_*.c))
|
||||
# NVN 空设备 + nn::vi(dm/gfx/)
|
||||
# 按通配纳入 dm/gfx 与 dm/gfx/nvn 下的源(tests/ metal/ 不进宿主):新增文件不改这一行
|
||||
@@ -95,9 +95,9 @@ dm_hud_exp.h: ../ios/tools/gen_hud_exp.py ../ios/tools/romfs_art.py
|
||||
dm_bright_levels.inc: ../tools/gen_bright_levels.py ../ios/tools/touch_layout.py
|
||||
$(NEED_ROMFS)
|
||||
python3 ../tools/gen_bright_levels.py "$(ROMFS)" > $@.tmp && mv $@.tmp $@
|
||||
dmhost: $(SRC) $(GFX) $(LIBDEFLATE) dm.h hle.h dm_input.h front.h touch_mac.h dm_cursor.h dm_i18n_tab.h ../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
|
||||
dmhost: $(SRC) $(GFX) $(LIBDEFLATE) dm.h hle.h dm_input.h front.h touch_mac.h dm_cursor.h dm_i18n_tab.h ../touch/dm_touch_controls.[ch] $(GFX_H) $(GENH)
|
||||
clang $(CFLAGS) -I. -I../gfx/nvn/include -fobjc-arc -o $@ $(SRC) $(GFX) $(LIBDEFLATE) -framework Cocoa -framework QuartzCore -framework Metal -framework AudioToolbox -framework CoreAudio -framework ImageIO -framework UniformTypeIdentifiers -framework GameController -framework Network
|
||||
# 老接口版宿主(图形后端不用 Metal 4,目标 macOS 15.0):同一棵树、同一份源码,只多一个编译开关;不在缺省目标里,要用时 make dmhost_m3
|
||||
# Older-API host (graphics backend without Metal 4, target macOS 15.0): the same tree and the same source, with just one more compile switch; not in the default targets, run make dmhost_m3 when needed
|
||||
dmhost_m3: $(SRC) $(GFX) $(LIBDEFLATE) dm.h hle.h dm_input.h front.h touch_mac.h dm_cursor.h dm_i18n_tab.h ../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
|
||||
dmhost_m3: $(SRC) $(GFX) $(LIBDEFLATE) dm.h hle.h dm_input.h front.h touch_mac.h dm_cursor.h dm_i18n_tab.h ../touch/dm_touch_controls.[ch] $(GFX_H) $(GENH)
|
||||
clang $(CFLAGS_M3) -I. -I../gfx/nvn/include -fobjc-arc -o $@ $(SRC) $(GFX) $(LIBDEFLATE) -framework Cocoa -framework QuartzCore -framework Metal -framework AudioToolbox -framework CoreAudio -framework ImageIO -framework UniformTypeIdentifiers -framework GameController -framework Network
|
||||
|
||||
@@ -110,6 +110,7 @@ int dm_app_bootstrap(int *argc, char ***argv) {
|
||||
if (!getenv("DM_TOUCH_DEFAULTS")) setenv("DM_TOUCH_DEFAULTS", "1", 1); // 产品缺省同 iOS 包(hle_fs.c settings_seed:玩家没碰过的设置键补上——小地图放右上角、进局自动打开、显示物品用开关式等;已有的键不动)。命令行宿主缺省不做,那边要对 Switch 真值比图 | product defaults same as the iOS package (hle_fs.c settings_seed: fills in settings keys the player has never touched - minimap in the top-right corner, opened automatically on entering a game, show-items as a toggle, and so on; existing keys are left alone). The command-line host does not do this by default, since it has to be compared against Switch ground-truth images
|
||||
if (!getenv("DM_APP_SUPPORT")) setenv("DM_CLOUD_REAL", "1", 1); // iCloud 同步(ios/Sources/cloud_ios.m,两端共用)只认玩家真实的存档目录;测试用的支持目录一律不同步 | iCloud sync (ios/Sources/cloud_ios.m, shared by both platforms) only recognises the player's real save directory; a support directory used for testing is never synced
|
||||
setenv("DM_WINDOW", "1", 1); setenv("DM_APP", "1", 1);
|
||||
if (!getenv("DM_AUDIO")) setenv("DM_AUDIO", "1", 1); // 产品要出声(hle_audio.c 在 Mac 上的缺省是给命令行回放 / 闸门的静音接收端);无人值守测试显式 DM_AUDIO=0 | the product must play sound (on the Mac, hle_audio.c defaults to the silent sink used for command-line replays / gates); unattended tests set DM_AUDIO=0 explicitly
|
||||
setenv("DM_SAVE", save.fileSystemRepresentation, 1); setenv("DM_TEMP", temp.fileSystemRepresentation, 1);
|
||||
setenv("DM_ROMFS", rom.fileSystemRepresentation, 1); setenv("DM_ROOT", sup.fileSystemRepresentation, 1);
|
||||
NSString *shmap = [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"shader_map.tsv"]; // 图形后端的着色器映射表:命令行起时按可执行文件旁的源码树找,包里放在 Resources | The graphics backend's shader mapping table: when started from the command line it is found via the source tree next to the executable; in the package it is in Resources
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
// Linux / Android 兼容层实现:compat_linux.h 与 include/ 替身头里声明的函数。
|
||||
// Linux / Android compatibility layer implementation: the functions declared in compat_linux.h and the stand-in headers under include/.
|
||||
#include "compat_linux.h"
|
||||
#include <CommonCrypto/CommonDigest.h>
|
||||
#include <dirent.h>
|
||||
#include <dispatch/dispatch.h>
|
||||
#include <limits.h>
|
||||
#include <semaphore.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/uio.h>
|
||||
#include <sys/xattr.h>
|
||||
|
||||
// ---- 读自己进程的内存:process_vm_readv 读自己,不可读返回 EFAULT 而不是崩 ----
|
||||
// ---- Reading our own memory: process_vm_readv on ourselves returns EFAULT for unreadable ranges instead of faulting ----
|
||||
kern_return_t vm_read_overwrite(mach_port_t task, vm_address_t addr, vm_size_t size, vm_address_t data, vm_size_t *outsize) {
|
||||
(void)task;
|
||||
struct iovec l = {(void *)data, size}, r = {(void *)addr, size};
|
||||
ssize_t n = process_vm_readv(getpid(), &l, 1, &r, 1, 0);
|
||||
if (n < 0 && errno == ENOSYS) {
|
||||
// 退路:写进管道再读出;write 遇不可读源地址返回 EFAULT | Fallback: write into a pipe and read back; write returns EFAULT on an unreadable source
|
||||
int p[2]; if (pipe(p)) return KERN_FAILURE;
|
||||
n = size <= 65536 ? write(p[1], (void *)addr, size) : -1;
|
||||
if (n > 0 && read(p[0], (void *)data, (size_t)n) != n) n = -1;
|
||||
close(p[0]); close(p[1]);
|
||||
}
|
||||
if (n != (ssize_t)size) return KERN_INVALID_ADDRESS;
|
||||
if (outsize) *outsize = size;
|
||||
return KERN_SUCCESS;
|
||||
}
|
||||
|
||||
kern_return_t task_info(mach_port_t task, task_flavor_t flavor, task_info_t out, mach_msg_type_number_t *count) {
|
||||
(void)task;
|
||||
if (flavor != TASK_VM_INFO || *count < TASK_VM_INFO_COUNT) return KERN_FAILURE;
|
||||
unsigned long long vsz = 0, rss = 0; FILE *f = fopen("/proc/self/statm", "r");
|
||||
if (!f) return KERN_FAILURE;
|
||||
int ok = fscanf(f, "%llu %llu", &vsz, &rss) == 2; fclose(f);
|
||||
if (!ok) return KERN_FAILURE;
|
||||
uint64_t pg = (uint64_t)sysconf(_SC_PAGESIZE);
|
||||
task_vm_info_data_t *vi = (task_vm_info_data_t *)out;
|
||||
vi->virtual_size = vsz * pg; vi->resident_size = vi->phys_footprint = rss * pg;
|
||||
return KERN_SUCCESS;
|
||||
}
|
||||
|
||||
// ---- pthread 栈:Darwin 的 stackaddr 是栈顶 ----
|
||||
// ---- pthread stack: Darwin's stackaddr is the stack top ----
|
||||
static int stack_of(pthread_t t, void **lo, size_t *sz) {
|
||||
pthread_attr_t a;
|
||||
if (pthread_getattr_np(t, &a)) return -1;
|
||||
int r = pthread_attr_getstack(&a, lo, sz);
|
||||
pthread_attr_destroy(&a);
|
||||
return r;
|
||||
}
|
||||
void *pthread_get_stackaddr_np(pthread_t t) { void *lo; size_t sz; return stack_of(t, &lo, &sz) ? NULL : (char *)lo + sz; }
|
||||
size_t pthread_get_stacksize_np(pthread_t t) { void *lo; size_t sz; return stack_of(t, &lo, &sz) ? 0 : sz; }
|
||||
|
||||
// ---- 文件 ----
|
||||
// ---- Files ----
|
||||
int dm_fcntl_getpath(int fd, char *out) {
|
||||
char p[64]; snprintf(p, sizeof p, "/proc/self/fd/%d", fd);
|
||||
ssize_t n = readlink(p, out, PATH_MAX - 1);
|
||||
if (n < 0) return -1;
|
||||
out[n] = 0; return 0;
|
||||
}
|
||||
|
||||
// 缓冲一律放堆上:clonefile 由存档挂载(svc 门)调用,跑在客体线程的小栈上
|
||||
// All buffers live on the heap: clonefile is called by save mounting (an svc gate) and runs on a guest thread's small stack
|
||||
static int copy_xattrs(int sfd, int dfd) {
|
||||
char *names = malloc(4096), *v = malloc(4096); int r = 0;
|
||||
ssize_t n = names && v ? flistxattr(sfd, names, 4096) : -1;
|
||||
for (char *k = names; n > 0 && k < names + n; k += strlen(k) + 1) {
|
||||
if (strncmp(k, "user.", 5)) continue;
|
||||
ssize_t vn = fgetxattr(sfd, k, v, 4096);
|
||||
if (vn >= 0 && fsetxattr(dfd, k, v, (size_t)vn, 0)) { r = -1; break; }
|
||||
}
|
||||
free(names); free(v);
|
||||
return r;
|
||||
}
|
||||
static int copy_file(const char *src, const char *dst, mode_t mode) {
|
||||
int sfd = open(src, O_RDONLY), dfd = sfd < 0 ? -1 : open(dst, O_WRONLY | O_CREAT | O_EXCL, mode);
|
||||
char *buf = malloc(65536);
|
||||
int r = sfd < 0 || dfd < 0 || !buf ? -1 : 0; ssize_t n;
|
||||
while (!r && (n = read(sfd, buf, 65536)) != 0) {
|
||||
if (n < 0) { r = -1; break; }
|
||||
for (ssize_t o = 0; o < n;) { ssize_t w = write(dfd, buf + o, (size_t)(n - o)); if (w < 0) { r = -1; break; } o += w; }
|
||||
}
|
||||
if (!r) r = copy_xattrs(sfd, dfd);
|
||||
free(buf);
|
||||
if (sfd >= 0) close(sfd);
|
||||
if (dfd >= 0) close(dfd);
|
||||
return r;
|
||||
}
|
||||
static int copy_tree(const char *src, const char *dst) {
|
||||
struct stat st; if (lstat(src, &st)) return -1;
|
||||
if (S_ISREG(st.st_mode)) return copy_file(src, dst, st.st_mode & 07777);
|
||||
if (!S_ISDIR(st.st_mode)) { errno = ENOTSUP; return -1; }
|
||||
if (mkdir(dst, st.st_mode & 07777)) return -1;
|
||||
DIR *d = opendir(src); if (!d) return -1;
|
||||
char *s2 = NULL, *d2 = NULL; struct dirent *e; int r = 0;
|
||||
while (!r && (e = readdir(d))) {
|
||||
if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
|
||||
if (asprintf(&s2, "%s/%s", src, e->d_name) < 0 || asprintf(&d2, "%s/%s", dst, e->d_name) < 0) r = -1;
|
||||
else r = copy_tree(s2, d2);
|
||||
free(s2); free(d2); s2 = d2 = NULL;
|
||||
}
|
||||
closedir(d);
|
||||
if (!r) { int sfd = open(src, O_RDONLY | O_DIRECTORY), dfd = open(dst, O_RDONLY | O_DIRECTORY);
|
||||
if (sfd >= 0 && dfd >= 0) r = copy_xattrs(sfd, dfd);
|
||||
if (sfd >= 0) close(sfd); if (dfd >= 0) close(dfd); }
|
||||
return r;
|
||||
}
|
||||
int clonefile(const char *src, const char *dst, uint32_t flags) {
|
||||
(void)flags;
|
||||
struct stat st; if (!lstat(dst, &st)) { errno = EEXIST; return -1; }
|
||||
return copy_tree(src, dst);
|
||||
}
|
||||
|
||||
int renamex_np(const char *from, const char *to, unsigned flags) {
|
||||
if (flags & RENAME_SWAP) return (int)syscall(SYS_renameat2, AT_FDCWD, from, AT_FDCWD, to, 2 /* RENAME_EXCHANGE */);
|
||||
return rename(from, to);
|
||||
}
|
||||
|
||||
// ---- 进程映像 ----
|
||||
// ---- Process image ----
|
||||
// 安卓 App 里 /proc/self/exe 是 app_process:GameActivity 在加载 libd2r.so 前设好 DM_ROOT(数据根),这里把「可执行文件」报成 <DM_ROOT>/dmhost,
|
||||
// 与 adb 无头时 dmhost 和 dm/ 同目录的布局一致——库构造函数(dm/derived.tsv 的经验表等)在 chdir 之前就要用它
|
||||
// In the Android app /proc/self/exe is app_process: GameActivity sets DM_ROOT (the data root) before loading libd2r.so, and the "executable" is reported as <DM_ROOT>/dmhost,
|
||||
// matching the adb headless layout where dmhost sits next to dm/ -- library constructors (the EXP table from dm/derived.tsv, etc.) need it before the chdir
|
||||
int _NSGetExecutablePath(char *buf, uint32_t *size) {
|
||||
char p[PATH_MAX]; ssize_t n;
|
||||
#ifdef __ANDROID__
|
||||
const char *root = getenv("DM_ROOT");
|
||||
if (root && *root) n = snprintf(p, sizeof p, "%s/dmhost", root); else
|
||||
#endif
|
||||
n = readlink("/proc/self/exe", p, sizeof p - 1);
|
||||
if (n < 0 || n >= (ssize_t)sizeof p) return -1;
|
||||
p[n] = 0;
|
||||
if ((uint32_t)n + 1 > *size) { *size = (uint32_t)n + 1; return -1; }
|
||||
memcpy(buf, p, (size_t)n + 1); return 0;
|
||||
}
|
||||
const struct mach_header_64 _mh_execute_header = {0xfeedfacf};
|
||||
|
||||
// Mach-O "__DATA,<名>" 登记段 → ELF 段 <名>(DM_SECT),链接器给 __start_<名> / __stop_<名>;未用到的段弱引用为空
|
||||
// Mach-O "__DATA,<name>" registration section -> ELF section <name> (DM_SECT); the linker provides __start_<name> / __stop_<name>; unused sections are weak and empty
|
||||
#define SECT(n) extern uint8_t __start_##n[] __attribute__((weak)), __stop_##n[] __attribute__((weak));
|
||||
SECT(swhle) SECT(swforce) SECT(swnvn)
|
||||
#undef SECT
|
||||
uint8_t *getsectiondata(const struct mach_header_64 *mh, const char *seg, const char *sect, unsigned long *size) {
|
||||
(void)mh; (void)seg;
|
||||
uint8_t *a = NULL, *b = NULL;
|
||||
if (!strcmp(sect, "swhle")) a = __start_swhle, b = __stop_swhle;
|
||||
else if (!strcmp(sect, "swforce")) a = __start_swforce, b = __stop_swforce;
|
||||
else if (!strcmp(sect, "swnvn")) a = __start_swnvn, b = __stop_swnvn;
|
||||
*size = a && b ? (unsigned long)(b - a) : 0;
|
||||
return *size ? a : NULL;
|
||||
}
|
||||
|
||||
// ---- 摘要:MD5 / SHA-1 / SHA-256(只做校验与诊断用,不涉安全) ----
|
||||
// ---- Digests: MD5 / SHA-1 / SHA-256 (only for checksums and diagnostics, not security) ----
|
||||
#define ROL(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
|
||||
#define ROR(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
|
||||
|
||||
static void md5_block(uint32_t h[4], const uint8_t *p) {
|
||||
static const uint32_t K[64] = {
|
||||
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
|
||||
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
|
||||
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
|
||||
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
|
||||
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
|
||||
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
|
||||
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
|
||||
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391};
|
||||
static const uint8_t S[16] = {7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21};
|
||||
uint32_t m[16]; for (int i = 0; i < 16; i++) m[i] = p[4 * i] | p[4 * i + 1] << 8 | p[4 * i + 2] << 16 | (uint32_t)p[4 * i + 3] << 24;
|
||||
uint32_t a = h[0], b = h[1], c = h[2], d = h[3];
|
||||
for (int i = 0; i < 64; i++) {
|
||||
uint32_t f; int g;
|
||||
if (i < 16) f = (b & c) | (~b & d), g = i;
|
||||
else if (i < 32) f = (d & b) | (~d & c), g = (5 * i + 1) & 15;
|
||||
else if (i < 48) f = b ^ c ^ d, g = (3 * i + 5) & 15;
|
||||
else f = c ^ (b | ~d), g = (7 * i) & 15;
|
||||
uint32_t t = d; d = c; c = b;
|
||||
b = b + ROL(a + f + K[i] + m[g], S[(i >> 4) * 4 + (i & 3)]);
|
||||
a = t;
|
||||
}
|
||||
h[0] += a; h[1] += b; h[2] += c; h[3] += d;
|
||||
}
|
||||
|
||||
// 通用 Merkle–Damgård 外壳:64 字节块,长度尾按 big 端或 little 端
|
||||
// Generic Merkle-Damgard wrapper: 64-byte blocks, length trailer big- or little-endian
|
||||
static void md_run(const uint8_t *p, uint64_t len, int big, void (*blk)(uint32_t *, const uint8_t *), uint32_t *h) {
|
||||
uint64_t full = len & ~63ull;
|
||||
for (uint64_t o = 0; o < full; o += 64) blk(h, p + o);
|
||||
uint8_t t[128] = {0}; size_t r = (size_t)(len - full);
|
||||
memcpy(t, p + full, r); t[r] = 0x80;
|
||||
size_t tl = r + 9 <= 64 ? 64 : 128; uint64_t bits = len * 8;
|
||||
for (int i = 0; i < 8; i++) t[tl - 8 + i] = big ? (uint8_t)(bits >> (56 - 8 * i)) : (uint8_t)(bits >> (8 * i));
|
||||
for (size_t o = 0; o < tl; o += 64) blk(h, t + o);
|
||||
}
|
||||
static void md5_blk(uint32_t *h, const uint8_t *p) { md5_block(h, p); }
|
||||
unsigned char *CC_MD5(const void *data, CC_LONG len, unsigned char *md) {
|
||||
uint32_t h[4] = {0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476};
|
||||
md_run(data, len, 0, md5_blk, h);
|
||||
for (int i = 0; i < 16; i++) md[i] = (uint8_t)(h[i / 4] >> (8 * (i & 3)));
|
||||
return md;
|
||||
}
|
||||
|
||||
static void sha1_blk(uint32_t *h, const uint8_t *p) {
|
||||
uint32_t w[80];
|
||||
for (int i = 0; i < 16; i++) w[i] = (uint32_t)p[4 * i] << 24 | p[4 * i + 1] << 16 | p[4 * i + 2] << 8 | p[4 * i + 3];
|
||||
for (int i = 16; i < 80; i++) w[i] = ROL(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
|
||||
uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4];
|
||||
for (int i = 0; i < 80; i++) {
|
||||
uint32_t f, k;
|
||||
if (i < 20) f = (b & c) | (~b & d), k = 0x5a827999;
|
||||
else if (i < 40) f = b ^ c ^ d, k = 0x6ed9eba1;
|
||||
else if (i < 60) f = (b & c) | (b & d) | (c & d), k = 0x8f1bbcdc;
|
||||
else f = b ^ c ^ d, k = 0xca62c1d6;
|
||||
uint32_t t = ROL(a, 5) + f + e + k + w[i]; e = d; d = c; c = ROL(b, 30); b = a; a = t;
|
||||
}
|
||||
h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e;
|
||||
}
|
||||
unsigned char *CC_SHA1(const void *data, CC_LONG len, unsigned char *md) {
|
||||
uint32_t h[5] = {0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0};
|
||||
md_run(data, len, 1, sha1_blk, h);
|
||||
for (int i = 0; i < 20; i++) md[i] = (uint8_t)(h[i / 4] >> (24 - 8 * (i & 3)));
|
||||
return md;
|
||||
}
|
||||
|
||||
static void sha256_blk(uint32_t *h, const uint8_t *p) {
|
||||
static const uint32_t K[64] = {
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
|
||||
uint32_t w[64];
|
||||
for (int i = 0; i < 16; i++) w[i] = (uint32_t)p[4 * i] << 24 | p[4 * i + 1] << 16 | p[4 * i + 2] << 8 | p[4 * i + 3];
|
||||
for (int i = 16; i < 64; i++) {
|
||||
uint32_t s0 = ROR(w[i - 15], 7) ^ ROR(w[i - 15], 18) ^ (w[i - 15] >> 3), s1 = ROR(w[i - 2], 17) ^ ROR(w[i - 2], 19) ^ (w[i - 2] >> 10);
|
||||
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
|
||||
}
|
||||
uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7];
|
||||
for (int i = 0; i < 64; i++) {
|
||||
uint32_t t1 = hh + (ROR(e, 6) ^ ROR(e, 11) ^ ROR(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + w[i];
|
||||
uint32_t t2 = (ROR(a, 2) ^ ROR(a, 13) ^ ROR(a, 22)) + ((a & b) ^ (a & c) ^ (b & c));
|
||||
hh = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2;
|
||||
}
|
||||
h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
|
||||
}
|
||||
int CC_SHA256_Init(CC_SHA256_CTX *c) {
|
||||
static const uint32_t H0[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
|
||||
memcpy(c->h, H0, sizeof H0); c->len = 0; c->n = 0; return 1;
|
||||
}
|
||||
int CC_SHA256_Update(CC_SHA256_CTX *c, const void *data, CC_LONG len) {
|
||||
const uint8_t *p = data; c->len += len;
|
||||
while (len) {
|
||||
if (!c->n && len >= 64) { sha256_blk(c->h, p); p += 64; len -= 64; continue; }
|
||||
uint32_t k = 64 - c->n < len ? 64 - c->n : len;
|
||||
memcpy(c->buf + c->n, p, k); c->n += k; p += k; len -= k;
|
||||
if (c->n == 64) { sha256_blk(c->h, c->buf); c->n = 0; }
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
int CC_SHA256_Final(unsigned char *md, CC_SHA256_CTX *c) {
|
||||
uint8_t t[128] = {0}; memcpy(t, c->buf, c->n); t[c->n] = 0x80;
|
||||
size_t tl = c->n + 9 <= 64 ? 64 : 128; uint64_t bits = c->len * 8;
|
||||
for (int i = 0; i < 8; i++) t[tl - 8 + i] = (uint8_t)(bits >> (56 - 8 * i));
|
||||
for (size_t o = 0; o < tl; o += 64) sha256_blk(c->h, t + o);
|
||||
for (int i = 0; i < 32; i++) md[i] = (uint8_t)(c->h[i / 4] >> (24 - 8 * (i & 3)));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// ---- dispatch 计数信号量 ----
|
||||
// ---- dispatch counting semaphore ----
|
||||
struct dm_dsema { sem_t s; };
|
||||
dispatch_semaphore_t dispatch_semaphore_create(long value) {
|
||||
dispatch_semaphore_t d = malloc(sizeof *d);
|
||||
if (d && sem_init(&d->s, 0, (unsigned)value)) { free(d); d = NULL; }
|
||||
return d;
|
||||
}
|
||||
long dispatch_semaphore_signal(dispatch_semaphore_t d) { sem_post(&d->s); return 0; }
|
||||
long dispatch_semaphore_wait(dispatch_semaphore_t d, dispatch_time_t timeout) {
|
||||
if (timeout == DISPATCH_TIME_FOREVER) { while (sem_wait(&d->s) && errno == EINTR) {} return 0; }
|
||||
if (timeout == DISPATCH_TIME_NOW) return sem_trywait(&d->s) ? 1 : 0;
|
||||
struct timespec ts = {(time_t)(timeout / 1000000000ull), (long)(timeout % 1000000000ull)}; // 绝对 CLOCK_REALTIME 纳秒 | absolute CLOCK_REALTIME ns
|
||||
while (sem_timedwait(&d->s, &ts)) if (errno != EINTR) return 1;
|
||||
return 0;
|
||||
}
|
||||
void dispatch_release(void *obj) { struct dm_dsema *d = obj; if (d) { sem_destroy(&d->s); free(d); } }
|
||||
|
||||
uint64_t mach_absolute_time(void) { return clock_gettime_nsec_np(CLOCK_MONOTONIC); }
|
||||
@@ -0,0 +1,151 @@
|
||||
// Linux / Android 兼容层:宿主源码按 Darwin 写,在 Linux 上用 -include 强制先包含本头,
|
||||
// 再由 compat/linux/include 下的同名替身头(mach/mach.h、CommonCrypto/CommonDigest.h…)吃掉 Apple 头的 #include。
|
||||
// 这里只补「同一语义、换个名字」的接口;语义不同的(线程暂停取寄存器、AudioUnit、GCD 信号源、xattr 参数)在源码里按 __APPLE__ 分支。
|
||||
// Linux / Android compatibility layer: the host sources are written against Darwin; on Linux this header is force-included first with -include,
|
||||
// and the same-named stand-in headers under compat/linux/include (mach/mach.h, CommonCrypto/CommonDigest.h, ...) absorb the #include of Apple headers.
|
||||
// Only "same semantics, different name" interfaces are provided here; the ones with different semantics (suspending a thread to read its registers,
|
||||
// AudioUnit, GCD signal sources, xattr arguments) branch on __APPLE__ in the sources.
|
||||
#pragma once
|
||||
#if !defined(__linux__)
|
||||
#error "compat_linux.h 只给 Linux / Android 用 | compat_linux.h is for Linux / Android only"
|
||||
#endif
|
||||
#ifndef _GNU_SOURCE
|
||||
#define _GNU_SOURCE 1
|
||||
#endif
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
// ---- TargetConditionals:Linux 既不是 iPhone 也不是 OSX;运行时可写代码(探针 / 计数桩)这类「非 iPhone」路径照常可用 ----
|
||||
// ---- TargetConditionals: Linux is neither iPhone nor OSX; "non-iPhone" paths such as runtime-written code (probes / counting stubs) work as usual ----
|
||||
#define TARGET_OS_IPHONE 0
|
||||
#define TARGET_OS_IOS 0
|
||||
#define TARGET_OS_OSX 0
|
||||
#define TARGET_OS_MAC 0
|
||||
#define TARGET_OS_SIMULATOR 0
|
||||
#define TARGET_OS_MACCATALYST 0
|
||||
#define DM_LINUX 1
|
||||
|
||||
// ---- 时钟:CLOCK_UPTIME_RAW(不含睡眠)= Linux CLOCK_MONOTONIC(同样不含挂起);mach 时基取 1/1 = 纳秒 ----
|
||||
// ---- Clocks: CLOCK_UPTIME_RAW (excludes sleep) = Linux CLOCK_MONOTONIC (also excludes suspend); the mach time base is 1/1 = nanoseconds ----
|
||||
#define CLOCK_UPTIME_RAW CLOCK_MONOTONIC
|
||||
#define CLOCK_UPTIME_RAW_APPROX CLOCK_MONOTONIC_COARSE
|
||||
#define CLOCK_MONOTONIC_RAW_APPROX CLOCK_MONOTONIC_COARSE
|
||||
static inline uint64_t clock_gettime_nsec_np(clockid_t c) {
|
||||
struct timespec ts; if (clock_gettime(c, &ts)) return 0;
|
||||
return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec;
|
||||
}
|
||||
typedef int kern_return_t;
|
||||
#define KERN_SUCCESS 0
|
||||
#define KERN_FAILURE 5
|
||||
#define KERN_INVALID_ADDRESS 1
|
||||
typedef struct { uint32_t numer, denom; } mach_timebase_info_data_t;
|
||||
typedef mach_timebase_info_data_t *mach_timebase_info_t;
|
||||
static inline kern_return_t mach_timebase_info(mach_timebase_info_t t) { t->numer = t->denom = 1; return KERN_SUCCESS; }
|
||||
// 真符号:nvn_entry.S 直接 bl mach_absolute_time | a real symbol: nvn_entry.S calls mach_absolute_time directly
|
||||
uint64_t mach_absolute_time(void);
|
||||
static inline uint64_t mach_continuous_time(void) { return clock_gettime_nsec_np(CLOCK_BOOTTIME); }
|
||||
static inline kern_return_t mach_wait_until(uint64_t deadline) {
|
||||
struct timespec ts = {(time_t)(deadline / 1000000000ull), (long)(deadline % 1000000000ull)};
|
||||
while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL) == EINTR) {}
|
||||
return KERN_SUCCESS;
|
||||
}
|
||||
|
||||
// ---- 任务 / 内存:只有「读自己进程一段可能不可读的内存」这一种用法(诊断),用 process_vm_readv 读自己,缺页返回错误而不是崩 ----
|
||||
// ---- Task / memory: the only use is "read a possibly unreadable range of our own process" (diagnostics); process_vm_readv on ourselves returns an error instead of faulting ----
|
||||
typedef int mach_port_t;
|
||||
typedef mach_port_t task_t, thread_t, thread_act_t;
|
||||
typedef unsigned mach_msg_type_number_t;
|
||||
typedef uintptr_t vm_address_t;
|
||||
typedef size_t vm_size_t;
|
||||
typedef int vm_prot_t;
|
||||
static inline mach_port_t mach_task_self(void) { return 0; }
|
||||
static inline mach_port_t mach_thread_self(void) { return (mach_port_t)gettid(); }
|
||||
static inline mach_port_t pthread_mach_thread_np(pthread_t t) { return (mach_port_t)pthread_gettid_np(t); }
|
||||
static inline kern_return_t mach_port_deallocate(mach_port_t task, mach_port_t p) { (void)task; (void)p; return KERN_SUCCESS; }
|
||||
// task_info(TASK_VM_INFO):只给 phys_footprint(取 /proc/self/statm 的常驻页) | task_info(TASK_VM_INFO): only phys_footprint (resident pages from /proc/self/statm)
|
||||
typedef int task_flavor_t;
|
||||
typedef int *task_info_t;
|
||||
#define TASK_VM_INFO 22
|
||||
typedef struct { uint64_t virtual_size, resident_size, phys_footprint; } task_vm_info_data_t;
|
||||
#define TASK_VM_INFO_COUNT ((mach_msg_type_number_t)(sizeof(task_vm_info_data_t) / sizeof(int)))
|
||||
kern_return_t task_info(mach_port_t task, task_flavor_t flavor, task_info_t out, mach_msg_type_number_t *count);
|
||||
kern_return_t vm_read_overwrite(mach_port_t task, vm_address_t addr, vm_size_t size, vm_address_t data, vm_size_t *outsize);
|
||||
|
||||
// ---- 指令缓存 ----
|
||||
// ---- Instruction cache ----
|
||||
static inline void sys_icache_invalidate(void *p, size_t n) { __builtin___clear_cache((char *)p, (char *)p + n); }
|
||||
static inline void sys_dcache_flush(void *p, size_t n) { (void)p; (void)n; }
|
||||
|
||||
// ---- QoS:Linux 没有,按「不设」处理;查询返回 UNSPECIFIED ----
|
||||
// ---- QoS: Linux has none; treated as "not set", queries return UNSPECIFIED ----
|
||||
typedef enum {
|
||||
QOS_CLASS_USER_INTERACTIVE = 0x21, QOS_CLASS_USER_INITIATED = 0x19, QOS_CLASS_DEFAULT = 0x15,
|
||||
QOS_CLASS_UTILITY = 0x11, QOS_CLASS_BACKGROUND = 0x09, QOS_CLASS_UNSPECIFIED = 0x00,
|
||||
} qos_class_t;
|
||||
static inline int pthread_set_qos_class_self_np(qos_class_t q, int rel) { (void)q; (void)rel; return 0; }
|
||||
static inline int pthread_attr_set_qos_class_np(pthread_attr_t *a, qos_class_t q, int rel) { (void)a; (void)q; (void)rel; return 0; }
|
||||
static inline int pthread_get_qos_class_np(pthread_t t, qos_class_t *q, int *rel) { (void)t; if (q) *q = QOS_CLASS_UNSPECIFIED; if (rel) *rel = 0; return 0; }
|
||||
static inline qos_class_t qos_class_self(void) { return QOS_CLASS_UNSPECIFIED; }
|
||||
|
||||
// ---- pthread 的 Darwin 扩展 ----
|
||||
// ---- Darwin extensions of pthread ----
|
||||
// Darwin pthread_setname_np 只给当前线程起名
|
||||
// Darwin pthread_setname_np only names the current thread
|
||||
#define pthread_setname_np(n) pthread_setname_np(pthread_self(), (n))
|
||||
// Darwin 的 stackaddr 是栈顶(高地址)
|
||||
// Darwin's stackaddr is the stack top (high address)
|
||||
void *pthread_get_stackaddr_np(pthread_t t);
|
||||
size_t pthread_get_stacksize_np(pthread_t t);
|
||||
static inline int pthread_threadid_np(pthread_t t, uint64_t *id) { *id = (uint64_t)pthread_gettid_np(t ? t : pthread_self()); return 0; }
|
||||
static inline int pthread_main_np(void) { return getpid() == gettid(); }
|
||||
|
||||
// ---- 文件 ----
|
||||
// ---- Files ----
|
||||
#define st_mtimespec st_mtim
|
||||
#define st_atimespec st_atim
|
||||
#define st_ctimespec st_ctim
|
||||
static inline int getdtablesize(void) { return (int)sysconf(_SC_OPEN_MAX); }
|
||||
#define F_GETPATH 0x7fff0032 // 由 dm_fcntl_getpath 处理(fcntl 不认识这个号) | handled by dm_fcntl_getpath (fcntl does not know this number)
|
||||
#ifndef ENOATTR
|
||||
#define ENOATTR ENODATA
|
||||
#endif
|
||||
int dm_fcntl_getpath(int fd, char *out);
|
||||
// 整树复制(含 user.* 扩展属性);Linux 没有写时复制克隆,存档目录小,复制可接受
|
||||
// Whole-tree copy (including user.* extended attributes); Linux has no copy-on-write clone, save directories are small so copying is acceptable
|
||||
int clonefile(const char *src, const char *dst, uint32_t flags);
|
||||
#define RENAME_SWAP 2u
|
||||
int renamex_np(const char *from, const char *to, unsigned flags);
|
||||
|
||||
// ---- 进程映像:可执行文件路径;Mach-O 段登记表的 ELF 对应(__start_<段> / __stop_<段>) ----
|
||||
// ---- Process image: executable path; the ELF counterpart of the Mach-O registration sections (__start_<sect> / __stop_<sect>) ----
|
||||
int _NSGetExecutablePath(char *buf, uint32_t *size);
|
||||
struct mach_header_64 { uint32_t magic; };
|
||||
extern const struct mach_header_64 _mh_execute_header;
|
||||
uint8_t *getsectiondata(const struct mach_header_64 *mh, const char *seg, const char *sect, unsigned long *size);
|
||||
|
||||
// ---- 随机数:bionic 自带 arc4random;glibc 2.36 起也有 ----
|
||||
// ---- Random numbers: bionic ships arc4random; glibc has it since 2.36 ----
|
||||
#include <stdlib.h>
|
||||
|
||||
#include <stdio.h>
|
||||
#include <sys/ucontext.h>
|
||||
// ---- 信号上下文:ESR 在 __reserved 的 esr_context 里(magic 0x45535201) ----
|
||||
// ---- Signal context: ESR lives in the esr_context inside __reserved (magic 0x45535201) ----
|
||||
static inline uint64_t dm_uc_esr(const ucontext_t *uc) {
|
||||
const uint8_t *p = (const uint8_t *)uc->uc_mcontext.__reserved, *end = p + sizeof uc->uc_mcontext.__reserved;
|
||||
while (p + 8 <= end) {
|
||||
uint32_t magic, size; memcpy(&magic, p, 4); memcpy(&size, p + 4, 4);
|
||||
if (!magic || size < 8) break;
|
||||
if (magic == 0x45535201u) { uint64_t esr; memcpy(&esr, p + 8, 8); return esr; }
|
||||
p += size;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// Linux 替身:CommonCrypto/CommonDigest.h —— 实际定义见 compat_linux.h(-include 强制先含)
|
||||
// Linux stand-in: CommonCrypto/CommonDigest.h -- the actual definitions are in compat_linux.h (force-included with -include)
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
|
||||
typedef uint32_t CC_LONG;
|
||||
#define CC_MD5_DIGEST_LENGTH 16
|
||||
#define CC_SHA1_DIGEST_LENGTH 20
|
||||
#define CC_SHA256_DIGEST_LENGTH 32
|
||||
typedef struct { uint32_t h[8]; uint64_t len; uint8_t buf[64]; uint32_t n; } CC_SHA256_CTX;
|
||||
unsigned char *CC_MD5(const void *data, CC_LONG len, unsigned char *md);
|
||||
unsigned char *CC_SHA1(const void *data, CC_LONG len, unsigned char *md);
|
||||
int CC_SHA256_Init(CC_SHA256_CTX *c);
|
||||
int CC_SHA256_Update(CC_SHA256_CTX *c, const void *data, CC_LONG len);
|
||||
int CC_SHA256_Final(unsigned char *md, CC_SHA256_CTX *c);
|
||||
@@ -0,0 +1,3 @@
|
||||
// Linux 替身:TargetConditionals.h —— 实际定义见 compat_linux.h(-include 强制先含)
|
||||
// Linux stand-in: TargetConditionals.h -- the actual definitions are in compat_linux.h (force-included with -include)
|
||||
#pragma once
|
||||
@@ -0,0 +1,15 @@
|
||||
// Linux 替身:dispatch/dispatch.h —— 实际定义见 compat_linux.h(-include 强制先含)
|
||||
// Linux stand-in: dispatch/dispatch.h -- the actual definitions are in compat_linux.h (force-included with -include)
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
|
||||
// 只实现计数信号量(hle_audio 用);队列 / 定时 / 信号源在源码里按 __APPLE__ 分支
|
||||
// Only the counting semaphore is implemented (used by hle_audio); queues / timers / signal sources branch on __APPLE__ in the sources
|
||||
typedef struct dm_dsema *dispatch_semaphore_t;
|
||||
typedef uint64_t dispatch_time_t;
|
||||
#define DISPATCH_TIME_NOW 0ull
|
||||
#define DISPATCH_TIME_FOREVER (~0ull)
|
||||
dispatch_semaphore_t dispatch_semaphore_create(long value);
|
||||
long dispatch_semaphore_signal(dispatch_semaphore_t s);
|
||||
long dispatch_semaphore_wait(dispatch_semaphore_t s, dispatch_time_t timeout);
|
||||
void dispatch_release(void *obj);
|
||||
@@ -0,0 +1,3 @@
|
||||
// Linux 替身:libkern/OSCacheControl.h —— 实际定义见 compat_linux.h(-include 强制先含)
|
||||
// Linux stand-in: libkern/OSCacheControl.h -- the actual definitions are in compat_linux.h (force-included with -include)
|
||||
#pragma once
|
||||
@@ -0,0 +1,4 @@
|
||||
// Linux 替身:mach-o/dyld.h —— 实际定义见 compat_linux.h(-include 强制先含)
|
||||
// Linux stand-in: mach-o/dyld.h -- the actual definitions are in compat_linux.h (force-included with -include)
|
||||
#pragma once
|
||||
#include <dlfcn.h>
|
||||
@@ -0,0 +1,3 @@
|
||||
// Linux 替身:mach-o/getsect.h —— 实际定义见 compat_linux.h(-include 强制先含)
|
||||
// Linux stand-in: mach-o/getsect.h -- the actual definitions are in compat_linux.h (force-included with -include)
|
||||
#pragma once
|
||||
@@ -0,0 +1,3 @@
|
||||
// Linux 替身:mach-o/ldsyms.h —— 实际定义见 compat_linux.h(-include 强制先含)
|
||||
// Linux stand-in: mach-o/ldsyms.h -- the actual definitions are in compat_linux.h (force-included with -include)
|
||||
#pragma once
|
||||
@@ -0,0 +1,33 @@
|
||||
// Linux 替身:mach/mach.h —— 实际定义见 compat_linux.h(-include 强制先含)
|
||||
// Linux stand-in: mach/mach.h -- the actual definitions are in compat_linux.h (force-included with -include)
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
|
||||
// ---- 线程诊断接口:Linux 上一律返回失败,调用方走「拿不到」分支(暂停取寄存器、线程信息、实时策略都只用于诊断 / 调优) ----
|
||||
// ---- Thread diagnostic interfaces: always fail on Linux, callers take their "unavailable" branch (suspend-and-read-registers, thread info and real-time policy are only for diagnostics / tuning) ----
|
||||
typedef int boolean_t;
|
||||
typedef int *thread_info_t, *thread_state_t, *thread_policy_t;
|
||||
typedef int thread_flavor_t, thread_state_flavor_t, thread_policy_flavor_t;
|
||||
typedef mach_port_t *thread_act_array_t;
|
||||
typedef struct { int seconds, microseconds; } time_value_t;
|
||||
typedef struct { time_value_t user_time, system_time; int cpu_usage, policy, run_state, flags, suspend_count, sleep_time; } thread_basic_info_data_t;
|
||||
typedef struct { uint64_t pth_user_time, pth_system_time; int32_t pth_cpu_usage, pth_policy, pth_run_state, pth_flags, pth_sleep_time, pth_curpri, pth_priority, pth_maxpriority; char pth_name[64]; } thread_extended_info_data_t;
|
||||
typedef struct { uint64_t __x[29], __fp, __lr, __sp, __pc; uint32_t __cpsr, __pad; } arm_thread_state64_t;
|
||||
#define THREAD_BASIC_INFO 3
|
||||
#define THREAD_BASIC_INFO_COUNT ((mach_msg_type_number_t)(sizeof(thread_basic_info_data_t) / sizeof(int)))
|
||||
#define THREAD_EXTENDED_INFO 5
|
||||
#define THREAD_EXTENDED_INFO_COUNT ((mach_msg_type_number_t)(sizeof(thread_extended_info_data_t) / sizeof(int)))
|
||||
#define ARM_THREAD_STATE64 6
|
||||
#define ARM_THREAD_STATE64_COUNT ((mach_msg_type_number_t)(sizeof(arm_thread_state64_t) / sizeof(int)))
|
||||
#define __darwin_arm_thread_state64_get_pc(s) ((s).__pc)
|
||||
#define __darwin_arm_thread_state64_get_lr(s) ((s).__lr)
|
||||
#define __darwin_arm_thread_state64_get_fp(s) ((s).__fp)
|
||||
#define __darwin_arm_thread_state64_get_sp(s) ((s).__sp)
|
||||
static inline kern_return_t thread_info(mach_port_t t, thread_flavor_t f, thread_info_t o, mach_msg_type_number_t *n) { (void)t; (void)f; (void)o; (void)n; return KERN_FAILURE; }
|
||||
static inline kern_return_t thread_suspend(mach_port_t t) { (void)t; return KERN_FAILURE; }
|
||||
static inline kern_return_t thread_resume(mach_port_t t) { (void)t; return KERN_FAILURE; }
|
||||
static inline kern_return_t thread_get_state(mach_port_t t, thread_state_flavor_t f, thread_state_t s, mach_msg_type_number_t *n) { (void)t; (void)f; (void)s; (void)n; return KERN_FAILURE; }
|
||||
static inline kern_return_t task_threads(mach_port_t task, thread_act_array_t *a, mach_msg_type_number_t *n) { (void)task; *a = 0; *n = 0; return KERN_FAILURE; }
|
||||
static inline kern_return_t vm_deallocate(mach_port_t task, vm_address_t a, vm_size_t n) { (void)task; (void)a; (void)n; return KERN_SUCCESS; }
|
||||
// libSystem 私有:本线程 {指令, 周期};Linux 版给 0(可改用 perf_event_open) | libSystem private: this thread's {instructions, cycles}; Linux gives 0 (perf_event_open could be used instead)
|
||||
static inline int thread_selfcounts(int type, void *buf, size_t nbytes) { (void)type; memset(buf, 0, nbytes); return -1; }
|
||||
@@ -0,0 +1,3 @@
|
||||
// Linux 替身:mach/mach_time.h —— 实际定义见 compat_linux.h(-include 强制先含)
|
||||
// Linux stand-in: mach/mach_time.h -- the actual definitions are in compat_linux.h (force-included with -include)
|
||||
#pragma once
|
||||
@@ -0,0 +1,3 @@
|
||||
// Linux 替身:mach/thread_info.h —— 实际定义见 compat_linux.h(-include 强制先含)
|
||||
// Linux stand-in: mach/thread_info.h -- the actual definitions are in compat_linux.h (force-included with -include)
|
||||
#pragma once
|
||||
@@ -0,0 +1,15 @@
|
||||
// Linux 替身:mach/thread_policy.h —— 实时线程策略在 Linux 上一律失败(调用方只记日志)
|
||||
// Linux stand-in: mach/thread_policy.h -- real-time thread policy always fails on Linux (callers only log)
|
||||
#pragma once
|
||||
#include <mach/mach.h>
|
||||
typedef struct { uint32_t period, computation, constraint; boolean_t preemptible; } thread_time_constraint_policy_data_t;
|
||||
#define THREAD_TIME_CONSTRAINT_POLICY 2
|
||||
#define THREAD_TIME_CONSTRAINT_POLICY_COUNT ((mach_msg_type_number_t)(sizeof(thread_time_constraint_policy_data_t) / sizeof(int)))
|
||||
typedef struct { int importance; } thread_precedence_policy_data_t;
|
||||
#define THREAD_PRECEDENCE_POLICY 3
|
||||
#define THREAD_PRECEDENCE_POLICY_COUNT 1
|
||||
typedef struct { boolean_t timeshare; } thread_extended_policy_data_t;
|
||||
#define THREAD_EXTENDED_POLICY 1
|
||||
#define THREAD_EXTENDED_POLICY_COUNT 1
|
||||
static inline kern_return_t thread_policy_set(mach_port_t t, thread_policy_flavor_t f, thread_policy_t p, mach_msg_type_number_t n) { (void)t; (void)f; (void)p; (void)n; return KERN_FAILURE; }
|
||||
static inline kern_return_t thread_policy_get(mach_port_t t, thread_policy_flavor_t f, thread_policy_t p, mach_msg_type_number_t *n, boolean_t *def) { (void)t; (void)f; (void)p; (void)n; if (def) *def = 1; return KERN_FAILURE; }
|
||||
@@ -0,0 +1,3 @@
|
||||
// Linux 替身:mach/vm_statistics.h —— 实际定义见 compat_linux.h(-include 强制先含)
|
||||
// Linux stand-in: mach/vm_statistics.h -- the actual definitions are in compat_linux.h (force-included with -include)
|
||||
#pragma once
|
||||
@@ -0,0 +1,10 @@
|
||||
// Linux 替身:malloc/malloc.h —— 实际定义见 compat_linux.h(-include 强制先含)
|
||||
// Linux stand-in: malloc/malloc.h -- the actual definitions are in compat_linux.h (force-included with -include)
|
||||
#pragma once
|
||||
#include <malloc.h>
|
||||
typedef struct { unsigned blocks_in_use; size_t size_in_use, max_size_in_use, size_allocated; } malloc_statistics_t;
|
||||
// 只填 size_in_use(mallinfo 的 uordblks);zone 参数忽略 | Only size_in_use is filled (mallinfo uordblks); the zone argument is ignored
|
||||
static inline void malloc_zone_statistics(void *zone, malloc_statistics_t *s) {
|
||||
(void)zone; struct mallinfo mi = mallinfo();
|
||||
memset(s, 0, sizeof *s); s->size_in_use = s->size_allocated = (size_t)mi.uordblks;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
// Linux 替身:pthread/qos.h —— 实际定义见 compat_linux.h(-include 强制先含)
|
||||
// Linux stand-in: pthread/qos.h -- the actual definitions are in compat_linux.h (force-included with -include)
|
||||
#pragma once
|
||||
@@ -0,0 +1,3 @@
|
||||
// Linux 替身:sys/clonefile.h —— 实际定义见 compat_linux.h(-include 强制先含)
|
||||
// Linux stand-in: sys/clonefile.h -- the actual definitions are in compat_linux.h (force-included with -include)
|
||||
#pragma once
|
||||
+5
-5
@@ -133,15 +133,15 @@ static void on_crash(int sig, siginfo_t *si, void *uc_) {
|
||||
ucontext_t *uc = uc_;
|
||||
if (sig == SIGTRAP && g_trap_hook && g_trap_hook(uc)) return;
|
||||
if (sig == SIGSEGV || sig == SIGBUS) {
|
||||
int is_write = (int)((uc->uc_mcontext->__es.__esr >> 6) & 1); // ESR 的 WnR 位 | The WnR bit of ESR
|
||||
int is_write = (int)((UC_ESR(uc) >> 6) & 1); // ESR 的 WnR 位 | The WnR bit of ESR
|
||||
for (int i = 0; i < g_nfault_hook; i++) if (g_fault_hook[i](si->si_addr, is_write, uc)) return;
|
||||
}
|
||||
fprintf(stderr, "[dm] CRASH sig=%d", sig);
|
||||
off("addr", (uint64_t)si->si_addr); off("pc", uc->uc_mcontext->__ss.__pc); off("lr", uc->uc_mcontext->__ss.__lr);
|
||||
fprintf(stderr, " sp=%#llx\n", uc->uc_mcontext->__ss.__sp);
|
||||
for (int i = 0; i < 29; i++) fprintf(stderr, "x%d=%#llx%s", i, uc->uc_mcontext->__ss.__x[i], i % 6 == 5 ? "\n" : " ");
|
||||
off("addr", (uint64_t)si->si_addr); off("pc", UC_PC(uc)); off("lr", UC_LR(uc));
|
||||
fprintf(stderr, " sp=%#llx\n", UC_SP(uc));
|
||||
for (int i = 0; i < 29; i++) fprintf(stderr, "x%d=%#llx%s", i, UC_X(uc, i), i % 6 == 5 ? "\n" : " ");
|
||||
fprintf(stderr, "\n");
|
||||
dm_backtrace(uc->uc_mcontext->__ss.__fp);
|
||||
dm_backtrace(UC_FP(uc));
|
||||
if (g_dump_hook) g_dump_hook();
|
||||
_exit(128 + sig);
|
||||
}
|
||||
|
||||
+73
-27
@@ -166,25 +166,25 @@ static void probe_dump_once(void) {
|
||||
LOG("探针转储 %s+%s 长 %s → %s", mod, o, n, f ? f : def);
|
||||
}
|
||||
static int probe_hit(ucontext_t *uc) { // 由 probe_install 注册给 crash.c 的 SIGTRAP 分支 | Registered by probe_install with the SIGTRAP branch of crash.c
|
||||
uint64_t pc = uc->uc_mcontext->__ss.__pc;
|
||||
uint64_t pc = UC_PC(uc);
|
||||
for (int i = 0; i < g_nprobe; i++) if (g_probe[i].at == pc) {
|
||||
probe_dump_once();
|
||||
if (g_probe[i].fn) { g_probe[i].hits++; g_probe[i].fn(uc); uc->uc_mcontext->__ss.__pc = (uint64_t)g_probe[i].slot; return 1; }
|
||||
if (g_probe[i].fn) { g_probe[i].hits++; g_probe[i].fn(uc); UC_PC(uc) = (uint64_t)g_probe[i].slot; return 1; }
|
||||
{ extern uint64_t g_t0_ns; uint64_t now_ns(void); fprintf(stderr, "[dm] PROBE %s #%u [%.4fs]", g_probe[i].name, ++g_probe[i].hits, (now_ns() - g_t0_ns) / 1e9); }
|
||||
for (int r = 0; r < 4; r++) { uint64_t v = uc->uc_mcontext->__ss.__x[r]; fprintf(stderr, " x%d=%#llx", r, v); probe_str(v); }
|
||||
for (int r = 19; r < 24; r++) fprintf(stderr, " x%d=%#llx", r, uc->uc_mcontext->__ss.__x[r]);
|
||||
{ uint64_t x8 = uc->uc_mcontext->__ss.__x[8]; Dl_info di; fprintf(stderr, " x8=%#llx", x8); // x8:间接调用目标常在这里(blr x8 前下探针) | x8: indirect call targets are often here (probe placed before blr x8)
|
||||
for (int r = 0; r < 4; r++) { uint64_t v = UC_X(uc, r); fprintf(stderr, " x%d=%#llx", r, v); probe_str(v); }
|
||||
for (int r = 19; r < 24; r++) fprintf(stderr, " x%d=%#llx", r, UC_X(uc, r));
|
||||
{ uint64_t x8 = UC_X(uc, 8); Dl_info di; fprintf(stderr, " x8=%#llx", x8); // x8:间接调用目标常在这里(blr x8 前下探针) | x8: indirect call targets are often here (probe placed before blr x8)
|
||||
if (dladdr((void *)x8, &di) && di.dli_sname) fprintf(stderr, "(%s+%#lx)", di.dli_sname, (unsigned long)(x8 - (uint64_t)di.dli_saddr)); }
|
||||
if (g_probe[i].dump >= 0) {
|
||||
uint8_t b[16]; vm_size_t got = 0;
|
||||
uint64_t at = uc->uc_mcontext->__ss.__x[0] + (g_probe[i].dump & 0xffffff);
|
||||
uint64_t at = UC_X(uc, 0) + (g_probe[i].dump & 0xffffff);
|
||||
if (g_probe[i].dump & 0x1000000) { uint64_t p = 0; vm_size_t g = 0; if (!vm_read_overwrite(mach_task_self(), at, 8, (vm_address_t)&p, &g)) at = p; else at = 0; } // @*偏移:先解引用再转储 | @*offset: dereference first, then dump
|
||||
if (at && !vm_read_overwrite(mach_task_self(), at, 16, (vm_address_t)b, &got) && got == 16) {
|
||||
fprintf(stderr, " [%s%#lx]=", (g_probe[i].dump & 0x1000000) ? "*x0+" : "x0+", g_probe[i].dump & 0xffffff); for (int k = 0; k < 16; k++) fprintf(stderr, "%02x", b[k]); }
|
||||
}
|
||||
fputc('\n', stderr);
|
||||
dm_backtrace(uc->uc_mcontext->__ss.__fp);
|
||||
uc->uc_mcontext->__ss.__pc = (uint64_t)g_probe[i].slot;
|
||||
dm_backtrace(UC_FP(uc));
|
||||
UC_PC(uc) = (uint64_t)g_probe[i].slot;
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
@@ -438,6 +438,7 @@ static void setlang_obs(const uint64_t *regs) {
|
||||
void probe_install(void) {
|
||||
if (gate_obs_present(OBS_SETLANG)) gate_obs_set(OBS_SETLANG, setlang_obs);
|
||||
if (gate_obs_present(OBS_EVENT_MSG)) gate_obs_set(OBS_EVENT_MSG, event_msg_obs);
|
||||
{ void dm_ui_tooltip_obs(const uint64_t *regs); if (gate_obs_present(OBS_TOOLTIP)) gate_obs_set(OBS_TOOLTIP, dm_ui_tooltip_obs); } // 说明框停靠(dm_cursor.c) | tooltip docking (dm_cursor.c)
|
||||
const char *ui = getenv("DM_UIMSG");
|
||||
if (ui && strcmp(ui, "1") && !(g_uifp = fopen(ui, "w"))) die("DM_UIMSG 打不开 %s", ui);
|
||||
g_ui_print = ui != NULL;
|
||||
@@ -480,8 +481,8 @@ static void on_sample(int sig, siginfo_t *si, void *uc_) {
|
||||
unsigned i = atomic_load(&g_shead) % SRING;
|
||||
extern uint64_t now_ns(void);
|
||||
uint32_t thr_cur_handle(void);
|
||||
g_sring[i].h = thr_cur_handle(); g_sring[i].t = now_ns(); g_sring[i].pc = uc->uc_mcontext->__ss.__pc; g_sring[i].lr = uc->uc_mcontext->__ss.__lr;
|
||||
uint64_t fp = uc->uc_mcontext->__ss.__fp; int n = 0;
|
||||
g_sring[i].h = thr_cur_handle(); g_sring[i].t = now_ns(); g_sring[i].pc = UC_PC(uc); g_sring[i].lr = UC_LR(uc);
|
||||
uint64_t fp = UC_FP(uc); int n = 0;
|
||||
// 帧链用安全读:被打断的函数可能把 x29 当普通寄存器用(直接解引用曾段错误)
|
||||
// The frame chain uses safe reads: the interrupted function may be using x29 as an ordinary register (a direct dereference once segfaulted)
|
||||
for (; n < 16 && fp && !(fp & 7); n++) {
|
||||
@@ -970,8 +971,10 @@ static void hud_tick(uint64_t G) { // 每拍:受控玩家等级 / 本
|
||||
LOG("DM_TEST_GIVE:拍 %u 在玩家旁生成「%s」品质 %d:%d / %d 件成功(物品类号 %u,第一件单位 id %u)%s", tq, code, q, ok, n, cls, id0, !getenv("DM_TEST_GIVE_INV") ? "" : inv == ok ? ",已全部捡进背包" : ",【注意】有没捡进背包的(留在地上)"); } } } }
|
||||
if (main && player) dm_elysium_stash_step(G, player, (uint8_t *)main->base); // 新建极乐世界角色后补齐共享仓库(dm_elysium.c) | Fill in the shared stash after a new Elysium character is created (dm_elysium.c)
|
||||
{ void dm_townwp_tick(uint64_t, uint64_t, uint8_t *); if (main && player) dm_townwp_tick(G, player, (uint8_t *)main->base); } // 进局落在城镇小站旁(dm_townwp.c) | Land next to the town waypoint on joining a run (dm_townwp.c)
|
||||
{ int dm_cloud_conflict_take(void); static int shown; // iCloud 同步拦下了共享仓库的覆盖(dm_cloudsync.c):进局后弹一次原版系统提示(每次启动一次) | iCloud sync blocked an overwrite of the shared stash (dm_cloudsync.c): show the original game's system prompt once after joining a run (once per launch)
|
||||
if (main && player && !shown && dm_cloud_conflict_take()) { shown = 1; dm_game_notice((uint8_t *)main->base, dm_str((uint8_t *)main->base, "dmCloudConflict")); LOG("iCloud 同步:弹了共享仓库不一致的提示"); } }
|
||||
{ int dm_cloud_conflict_take(void); static int shown; // iCloud 共享仓库分叉、本机那份收进了待合并收件箱(dm_cloudsync.c):进局后弹一次原版系统提示(每次启动一次) | the iCloud shared stash forked and the local copy was put in the to-merge inbox (dm_cloudsync.c): one original system notice after entering a run (once per launch)
|
||||
if (main && player && !shown && dm_cloud_conflict_take()) { shown = 1; dm_game_notice((uint8_t *)main->base, dm_str((uint8_t *)main->base, "dmCloudConflict")); LOG("iCloud 同步:弹了共享仓库收进收件箱的提示"); } }
|
||||
{ int dm_cloud_char_conflict_take(char *, size_t); char nm[256], msg[400]; // iCloud 首次同步遇到同名角色、用了云端那份(dm_cloudsync.c):进局后提示一次 | iCloud first sync met a character with the same name and used the cloud copy (dm_cloudsync.c): one notice after entering a run
|
||||
if (main && player && dm_cloud_char_conflict_take(nm, sizeof nm)) { snprintf(msg, sizeof msg, dm_str((uint8_t *)main->base, "dmCloudCharConflict"), nm); dm_game_notice((uint8_t *)main->base, msg); LOG("iCloud 同步:弹了同名角色用云端那份的提示(%s)", nm); } }
|
||||
if (main && player) dm_bossrush_tick(G, player, (uint8_t *)main->base); // 首领连战(dm_bossrush.c) | Boss rush (dm_bossrush.c)
|
||||
if (main && player) { void dm_rift_tick(uint64_t, uint64_t, uint8_t *); dm_rift_tick(G, player, (uint8_t *)main->base); } // 秘境爬塔(dm_rift.c) | Rift tower climb (dm_rift.c)
|
||||
{ void dm_pages_tick(uint64_t, uint64_t, uint8_t *); if (main) dm_pages_tick(G, player, (uint8_t *)main->base); } // 个人仓库 2–5 页(dm_pages.c);不在局内 player 为 0,模块自己清状态 | Personal stash pages 2–5 (dm_pages.c); player is 0 when not in a run, and the module clears its own state
|
||||
@@ -1188,15 +1191,6 @@ int dm_request_save(void) {
|
||||
*(volatile uint64_t *)(uintptr_t)(g_lastG + 0x5800) = 1;
|
||||
return 1;
|
||||
}
|
||||
// 退出前存盘用(Mac App):单机暂停着(暂停菜单 / 大秘境面板开着,原版界面状态字节 [main+0x2d5ff51] | [main+0x2d5ff67] 非 0,见 dm_rift_ui.c)时游戏不跑拍,
|
||||
// 上面拨的那次存盘等不到。把这两个字节清掉让拍接着走;只在进程马上要退出时调(不写回)。返回清之前是否暂停着
|
||||
// For saving before exit (Mac App): while single-player is paused (pause menu / rift panel open, original UI state bytes [main+0x2d5ff51] | [main+0x2d5ff67] non-zero, see dm_rift_ui.c) the game does not tick,
|
||||
// so the save requested above would never happen. Clear these two bytes so the ticks continue; called only when the process is about to exit (not written back). Returns whether it was paused before clearing
|
||||
int dm_unpause_for_exit(void) {
|
||||
uint8_t *b = NULL; for (int i = 0; i < g_nmod; i++) if (!strcmp(g_mod[i].name, "main")) b = (uint8_t *)g_mod[i].base;
|
||||
if (!b || !in_game()) return 0;
|
||||
volatile uint8_t *f = b + 0x2d5ff51, *g = b + 0x2d5ff67; int was = *f || *g; *f = 0; *g = 0; return was;
|
||||
}
|
||||
// 游戏是不是停着(暂停菜单 / 大秘境选层页这类开着:同上两个界面状态字节)。不在局内返回 0
|
||||
// Whether the game is stopped (pause menu / Greater Rift level-selection page and the like open: the same two UI state bytes as above). Returns 0 when not in a game
|
||||
int dm_game_paused(void) { uint8_t *b = NULL; for (int i = 0; i < g_nmod; i++) if (!strcmp(g_mod[i].name, "main")) b = (uint8_t *)g_mod[i].base; return b && in_game() && (*(volatile uint8_t *)(b + 0x2d5ff51) | *(volatile uint8_t *)(b + 0x2d5ff67)); }
|
||||
@@ -1632,18 +1626,70 @@ void dm_freeze_frame(int want) { static int idle;
|
||||
if (!atomic_load(&g_dm_frozen) || !atomic_load(&g_frz_by_panel) || want) { idle = 0; return; }
|
||||
if (++idle < 10) return; idle = 0; atomic_store(&g_dm_frozen, 0); atomic_store(&g_frz_by_panel, 0); if (mtl_world_frozen) mtl_world_frozen(0);
|
||||
LOG("面板冻结:解冻(面板已不在屏上而拍入口没在走:原版暂停 / 退出 / 换角色)"); }
|
||||
static int g_frz_on; // 四个冻结入口门已挂上(freeze_attach) | The four freeze entry gates are attached (freeze_attach)
|
||||
static int freeze_attach(void) { // 挂冻结用的四个入口门(产物里有门 10–13 才行),挂过就不再挂。返回 1 = 能冻 | Attach the four entry gates used for freezing (needs gates 10–13 in the product); attached only once. Returns 1 = can freeze
|
||||
static int tried; if (tried) return g_frz_on; tried = 1;
|
||||
g_frz_on = gate_obs_present(OBS_FREEZE_WORLD) && gate_obs_present(OBS_FREEZE_CLIENT) && gate_obs_present(OBS_FREEZE_ANIM) && gate_obs_present(OBS_FREEZE_RENDER);
|
||||
if (g_frz_on) { gate_obs_set(OBS_FREEZE_WORLD, freeze_world_obs); gate_obs_set(OBS_FREEZE_CLIENT, freeze_client_obs); gate_obs_set(OBS_FREEZE_ANIM, freeze_anim_obs); gate_obs_set(OBS_FREEZE_RENDER, freeze_render_obs); }
|
||||
return g_frz_on;
|
||||
}
|
||||
// 暂停菜单开着进后台时存一次盘:原版单机暂停时游戏不走拍,前端请的那次存盘要等下一拍,进后台 2.5 秒等不到(10142104 日志 4 次),
|
||||
// 上次自动存盘到开暂停之间的进度在后台被系统回收时会丢。做法:先冻住世界(同面板冻结:世界 / 客户端 / 动画 / 渲染四个入口换成空跑,拍号不前进——怪不动、时间不走),
|
||||
// 再临时放开原版暂停的两个界面状态字节让拍走起来、执行那次存盘;等到提交(前端 background_wait_save)后写回两个字节、解冻。前端在主线程调
|
||||
// Save once when going to the background with the pause menu open: in single-player pause the original game does not tick, so the save the front end asks for waits for the next tick and the 2.5 s background wait never sees it (seen 4 times in a player's log);
|
||||
// progress between the last autosave and opening the pause menu is lost if the system reclaims the app in the background. Method: first freeze the world (same as panel freezing: the world / client / animation / render entry points become no-ops and the tick number does not advance, so monsters do not move and time does not pass),
|
||||
// then temporarily release the two UI state bytes of the original pause so ticks run and perform the save; after the commit (front end background_wait_save) write the two bytes back and unfreeze. Called by the front end on the main thread
|
||||
static _Atomic int g_bgsave; static uint8_t g_bg_pause[2];
|
||||
static int save_unpause_begin(void) { // 1 = 冻住世界并放开了暂停;0 = 游戏没停着(不用做);-1 = 产物没有冻结门,做不了 | 1 = froze the world and released the pause; 0 = the game is not stopped (nothing to do); -1 = the product has no freeze gates, cannot do it
|
||||
uint8_t *b = NULL; for (int i = 0; i < g_nmod; i++) if (!strcmp(g_mod[i].name, "main")) b = (uint8_t *)g_mod[i].base;
|
||||
if (!b || !in_game()) return 0; volatile uint8_t *f = b + 0x2d5ff51, *g = b + 0x2d5ff67; if (!*f && !*g) return 0;
|
||||
if (!freeze_attach()) { LOG("【红】停着存盘:游戏停着,但产物里没有冻结门 10–13,不放开暂停(这次存不了)"); return -1; }
|
||||
atomic_store(&g_frz_by_panel, 0); atomic_store(&g_bgsave, 1); atomic_store(&g_dm_frozen, 1); // 先冻、后放开:放开后的第一拍世界就已经是空跑 | Freeze first, then release: the world is already idle on the first tick after release
|
||||
int nm = 0, hp = 0; uint32_t h = g_lastG ? frz_snapshot(g_lastG, &nm, &hp) : 0;
|
||||
g_bg_pause[0] = *f; g_bg_pause[1] = *g; *f = 0; *g = 0;
|
||||
LOG("停着存盘:游戏停着 → 冻住世界、临时放开原版暂停(怪 / 佣兵 %d 个,快照 %08x,玩家生命 %d)", nm, h, hp);
|
||||
return 1;
|
||||
}
|
||||
static void save_unpause_end(void) {
|
||||
if (!atomic_load(&g_bgsave)) return;
|
||||
uint8_t *b = NULL; for (int i = 0; i < g_nmod; i++) if (!strcmp(g_mod[i].name, "main")) b = (uint8_t *)g_mod[i].base;
|
||||
if (b) { *(volatile uint8_t *)(b + 0x2d5ff51) = g_bg_pause[0]; *(volatile uint8_t *)(b + 0x2d5ff67) = g_bg_pause[1]; } // 先恢复暂停、后解冻:解冻后的拍不再走 | Restore the pause first, then unfreeze: ticks after unfreezing no longer advance
|
||||
int nm = 0, hp = 0; uint32_t h = g_lastG ? frz_snapshot(g_lastG, &nm, &hp) : 0;
|
||||
atomic_store(&g_bgsave, 0); atomic_store(&g_dm_frozen, 0);
|
||||
LOG("停着存盘:恢复原版暂停、解冻(怪 / 佣兵 %d 个,快照 %08x,玩家生命 %d)", nm, h, hp);
|
||||
}
|
||||
// 前端要进程马上可能没了之前(iOS 进后台、Mac 退出)请游戏存一次盘并等提交:游戏停着(暂停菜单 / 大秘境面板开着)就先冻住世界、
|
||||
// 临时放开原版暂停让拍走起来执行这次存盘,等完写回暂停、解冻——玩家回来时世界与暂停都和离开前一样。等到「出现过存档提交、之后 0.2 秒没有新的提交」
|
||||
// (角色与共享箱是两个容器,可能分两次),最多 max_s 秒;还没进局(读取画面)就每 20 ms 再试,进了局再请。返回 1 = 请到了存盘。
|
||||
// *commits = 期间存档提交次数,*froze = 是否冻结放开过暂停,*ms = 用时。在前端主线程调(游戏拍在客体线程照跑)
|
||||
// Before the process may go away at any moment (iOS going to the background, quitting on Mac), the front end asks the game to save once and waits for the commit. If the game is stopped (pause menu / Greater Rift panel open), it first freezes the world,
|
||||
// temporarily releases the original pause so ticks run and perform this save, and after waiting writes the pause back and unfreezes, so when the player returns both the world and the pause are as they left them. It waits until "a save commit has happened and no new commit for 0.2 s"
|
||||
// (character and shared stash are two containers and may commit separately), at most max_s seconds; before entering a game (loading screen) it retries every 20 ms and asks once in game. Returns 1 = the save was requested.
|
||||
// *commits = number of save commits in the meantime, *froze = whether it froze and released the pause, *ms = time taken. Called on the front end's main thread (game ticks keep running on the guest thread)
|
||||
uint64_t dm_fs_commit_count(void);
|
||||
int dm_save_wait(double max_s, uint64_t *commits, int *froze, double *ms) {
|
||||
uint64_t c0 = dm_fs_commit_count(), t0 = now_ns(), last = c0, last_t = 0, lim = (uint64_t)(max_s * 1e9); int asked = 0, bg = 0;
|
||||
for (;;) {
|
||||
if (!bg && in_game()) bg = save_unpause_begin(); // 先冻、放开暂停,再请存盘 | Freeze first, release the pause, then ask for the save
|
||||
if (!asked) asked = dm_request_save();
|
||||
usleep(20000); uint64_t c = dm_fs_commit_count(), t = now_ns();
|
||||
if (c != last) { last = c; last_t = t; }
|
||||
if ((asked && last_t && t - last_t >= 200000000ull) || t - t0 >= lim) break;
|
||||
}
|
||||
if (bg > 0) save_unpause_end();
|
||||
*commits = last - c0; *froze = bg > 0; *ms = (now_ns() - t0) / 1e6;
|
||||
return asked;
|
||||
}
|
||||
static void freeze_tick(uint64_t G) { // 拍入口:定这一拍冻不冻,冻就把拍号先减 1 | Tick entry: decide whether this tick is frozen; if so, decrement the tick number by 1 first
|
||||
static struct { uint32_t at, n; int st; } w[8]; static int nw = -1, panel, cur = -1, on; static uint32_t left, calls;
|
||||
static struct { uint32_t at, n; int st; } w[8]; static int nw = -1, panel, cur = -1; static uint32_t left, calls;
|
||||
if (nw < 0) { nw = 0; const char *e = getenv("DM_TEST_FREEZE"); char buf[160]; if (e) { strlcpy(buf, e, sizeof buf); for (char *sv, *t = strtok_r(buf, ";", &sv); t && nw < 8; t = strtok_r(NULL, ";", &sv)) if (sscanf(t, "%u:%u", &w[nw].at, &w[nw].n) == 2) nw++; }
|
||||
e = getenv("DM_PANEL_FREEZE"); panel = e && e[0] != '0';
|
||||
if (nw || panel) { on = gate_obs_present(OBS_FREEZE_WORLD) && gate_obs_present(OBS_FREEZE_CLIENT) && gate_obs_present(OBS_FREEZE_ANIM) && gate_obs_present(OBS_FREEZE_RENDER);
|
||||
if (on) { gate_obs_set(OBS_FREEZE_WORLD, freeze_world_obs); gate_obs_set(OBS_FREEZE_CLIENT, freeze_client_obs); gate_obs_set(OBS_FREEZE_ANIM, freeze_anim_obs); gate_obs_set(OBS_FREEZE_RENDER, freeze_render_obs); LOG("面板冻结:四个入口门已挂(按面板 %d,时间窗 %d 个)", panel, nw); }
|
||||
else LOG("【红】面板冻结:产物里没有观测门 10–13,不生效"); } }
|
||||
if (!on) return;
|
||||
if (nw || panel) { if (freeze_attach()) LOG("面板冻结:四个入口门已挂(按面板 %d,时间窗 %d 个)", panel, nw); else LOG("【红】面板冻结:产物里没有观测门 10–13,不生效"); } }
|
||||
if (!g_frz_on) return;
|
||||
uint32_t t = 0; if (!tk_rd(G + 0x170, &t, 4)) return; int frozen = atomic_load(&g_dm_frozen);
|
||||
if (cur < 0 && !frozen) for (int i = 0; i < nw; i++) if (!w[i].st && t >= w[i].at) { cur = i; w[i].st = 1; left = w[i].n; break; }
|
||||
if (cur >= 0 && frozen && left && !--left) { w[cur].st = 2; cur = -1; }
|
||||
int want = cur >= 0 || (panel && atomic_load(&g_dm_frz_want));
|
||||
int want = cur >= 0 || (panel && atomic_load(&g_dm_frz_want)) || atomic_load(&g_bgsave);
|
||||
if (want && !frozen) { if (t % 20 == 0 || t % 12 == 0 || t % 11 == 0 || t % 1500 == 0) return; // 晚一拍 | One tick later
|
||||
int nm = 0, hp = 0; uint32_t h = frz_snapshot(G, &nm, &hp); atomic_store(&g_frz_by_panel, cur < 0); atomic_store(&g_dm_frozen, 1); frozen = 1; calls = 0; if (mtl_world_frozen) mtl_world_frozen(1); LOG("面板冻结:拍 %u 冻结(%s);怪 %d 只 校验 %08x 玩家生命 %d", t, cur >= 0 ? "时间窗" : "面板开着", nm, h, hp); }
|
||||
else if (!want && frozen) { int nm = 0, hp = 0; uint32_t h = frz_snapshot(G, &nm, &hp); atomic_store(&g_dm_frozen, 0); frozen = 0; if (mtl_world_frozen) mtl_world_frozen(0); LOG("面板冻结:拍 %u 解冻(冻了 %u 次拍入口);怪 %d 只 校验 %08x 玩家生命 %d", t, calls, nm, h, hp); }
|
||||
|
||||
+10
-1
@@ -6,6 +6,7 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "dm_plat.h"
|
||||
|
||||
#define MAX_MOD 8
|
||||
#define LOG(...) do { fprintf(stderr, "[dm] " __VA_ARGS__); fputc('\n', stderr); } while (0)
|
||||
@@ -43,6 +44,14 @@ extern int g_nmod;
|
||||
// Four thread-local slots: K18 = the Switch's x18, KTLS = tpidr_el0, KTLR = tpidrro_el0 (ThreadLocalRegion), KGATE = host gate entry; the actual key numbers are written into the key page by the loader
|
||||
extern pthread_key_t g_key18, g_keytls, g_keytlr, g_keygate;
|
||||
extern pthread_key_t g_keyres[2], g_keyaspect, g_keyaspectui;
|
||||
// 槽写入:Apple 槽 = pthread TSD(tpidrro_el0 + 8*键);Linux / Android 槽 = tp[2](bionic TLS_SLOT_APP)指向的每线程槽块 + 8*键,键是 1..8 的小整数
|
||||
// Slot write: on Apple a slot = pthread TSD (tpidrro_el0 + 8*key); on Linux / Android a slot = the per-thread slot block pointed to by tp[2] (bionic TLS_SLOT_APP) + 8*key, keys being small integers 1..8
|
||||
#ifdef __APPLE__
|
||||
#define dm_slot_set(k, v) pthread_setspecific((k), (v))
|
||||
#else
|
||||
void dm_slot_set(pthread_key_t k, void *v);
|
||||
uint64_t *dm_slot_block(void);
|
||||
#endif
|
||||
|
||||
void load_modules(const char *dir, const char **names, int n);
|
||||
void run_module_inits(void);
|
||||
@@ -54,7 +63,7 @@ module_t *module_of(const void *p);
|
||||
uint64_t gate_dispatch(uint64_t ret_addr, uint64_t *regs);
|
||||
// 观测门(改写器 OBS 表;编号与 patch_nso.py 一致):只读回调,挂上即在门命中时调用
|
||||
// Observation gates (rewriter OBS table; numbering matches patch_nso.py): read-only callbacks, called on a gate hit once attached
|
||||
enum { OBS_UIMSG = 1, OBS_TICK = 2, OBS_C2S = 3, OBS_C2S_SYS = 4, OBS_SETLANG = 5, OBS_TARGET_RANK = 7, OBS_UI_PROJECT = 8, OBS_FREEZE_WORLD = 10, OBS_FREEZE_CLIENT = 11, OBS_FREEZE_ANIM = 12, OBS_FREEZE_RENDER = 13, OBS_TEXTBOX = 14, OBS_EVENT_MSG = 15, OBS_LEVEL_WARP = 16, OBS_QUEST_KILL = 17, OBS_NOTICE_INPUT = 18, OBS_ERR_SMOOTH = 19, OBS_MODEL_YAW = 20, OBS_MAX = 21 }; // 6 = iOS 绑定读取(dm_touch_game_bridge.c) | 6 = iOS binding read (dm_touch_game_bridge.c)
|
||||
enum { OBS_UIMSG = 1, OBS_TICK = 2, OBS_C2S = 3, OBS_C2S_SYS = 4, OBS_SETLANG = 5, OBS_TARGET_RANK = 7, OBS_UI_PROJECT = 8, OBS_FREEZE_WORLD = 10, OBS_FREEZE_CLIENT = 11, OBS_FREEZE_ANIM = 12, OBS_FREEZE_RENDER = 13, OBS_TEXTBOX = 14, OBS_EVENT_MSG = 15, OBS_LEVEL_WARP = 16, OBS_QUEST_KILL = 17, OBS_NOTICE_INPUT = 18, OBS_ERR_SMOOTH = 19, OBS_MODEL_YAW = 20, OBS_TOOLTIP = 21, OBS_PRESET_SPAWN = 22, OBS_MAX = 23 }; // 6 = iOS 绑定读取(dm_touch_game_bridge.c) | 6 = iOS binding read (dm_touch_game_bridge.c)
|
||||
void gate_obs_set(int id, void (*fn)(const uint64_t *regs));
|
||||
int gate_obs_present(int id);
|
||||
void dm_quiet_difficulty_msg(int on); // 秘境局里拦原版「游戏难度设为 N」提示(观测门 15,diag.c) | In a rift run, block the original game's 「游戏难度设为 N」(Game difficulty set to N) message (observation gate 15, diag.c)
|
||||
|
||||
@@ -99,7 +99,7 @@ static int skipped(int skill) { if (getenv("DM_TEST_BUFF_NOSKIP")) return 0; /
|
||||
uint32_t dm_cur_tick(void);
|
||||
|
||||
static int enabled(void) { static int env = -2; if (env == -2) { const char *e = getenv("DM_AUTOBUFF"); env = e ? e[0] != '0' : -1; }
|
||||
return env >= 0 ? env : (TARGET_OS_IPHONE && dm_custom_get("auto_buff")); }
|
||||
return env >= 0 ? env : (DM_TOUCH_PRODUCT && dm_custom_get("auto_buff")); }
|
||||
static int cfg(const char *nm, int def) { const char *e = getenv(nm); return e && atoi(e) > 0 ? atoi(e) : def; }
|
||||
static int has_state(uint64_t u, int st) {
|
||||
uint64_t sl = *(uint64_t *)(u + 0x88); if (!sl || !(*(uint32_t *)(sl + 0x1c) >> 31)) return 0;
|
||||
|
||||
+85
-10
@@ -13,7 +13,16 @@
|
||||
// · 首次同步(这一单位没有状态记录)且两边内容不同:一律以云端为准(本地那份照常整份进备份);运行中(allow_down = 0)不传不改,等下次启动下载。云端没有才上传本地。
|
||||
// · 共享仓库(_stash)再加一道:要被覆盖的一方「明显更多」就不覆盖——任一共享仓库档(.d2i)的编年史段变短(编年史只增不减;新装的空仓库编年史最短)、
|
||||
// 或要盖上去的是没东西的新档(0 件且编年史还是新建大小)而另一份有物品,或编年史仓库侧文件(.swvault)有件而另一份根本没有这个文件(新装 / 旧版本)。
|
||||
// 物品变少、编年史仓库取空都是正常玩法,不拦(只有从没记过编年史的仓库被取空会被当成新档拦下,宁可不同步也不丢)。拦下时本地与云端都不动、状态不记,日志记红,进局后弹系统提示(dm_cloud_conflict_take)。
|
||||
// 物品变少、编年史仓库取空都是正常玩法,不算(只有从没记过编年史的仓库被取空会被当成新档)。
|
||||
// 共享仓库分叉(iCloud 离线冲突第 1 条第一笔,不丢、不永久拦):首次同步两边不同、或上面那道保险判出「会丢东西」时,不再永久拦住——
|
||||
// 启动时一律以云端为现行版(换下的本机那份照常整份进备份),本机那份有东西(物品 / 金币 / 编年史 / 编年史仓库任一项,预置与新建空档不算)就另存进
|
||||
// 待合并收件箱 <存档>/_cloudinbox/<时刻>-<序号>/(在存档目录里:局内并回时与角色档、共享仓库同一次存盘提交原子换入,被杀不会复制也不会丢;
|
||||
// 下划线开头不算角色、也不是共享仓库文件,iCloud 不同步它——收件箱是这台设备自己的):mine.pack = 本机那份;base.pack = 上次同步成功时的共享仓库(状态文件旁的 .stash_base,摘要对得上才带),
|
||||
// 以后在局内并回:云端是基准的后代(编年史只增不减,基准的编年史条目云端都有)时按「云端 + 本机新增 − 本机取走」,分不清来历时按同一件取一份的并集
|
||||
// (单机游戏里少数情况下多出一件比丢一件好)。收不进收件箱就这次不动。
|
||||
// 运行中(allow_down = 0)遇到分叉不动、等下次启动。新收进一份就进局提示一次(dm_cloud_conflict_take)。
|
||||
// 每次共享仓库同步成功(上传 / 下载 / 一致)都把那一刻的内容写进 <状态文件>.stash_base,给下次分叉当基准。
|
||||
// iCloud 自己的同名文件冲突版本(cloud_ios.m 读出来)也走收件箱:dm_cloud_inbox_add。
|
||||
// Core of iCloud save sync (synced by character name, the later write overwrites the earlier one, and the shared stash works the same way).
|
||||
// This only does the file comparison and moving for "local save directory ↔ one cloud directory" and does not touch the iCloud API: the iOS side (cloud_ios.m) provides the directory in the ubiquity container, confirms the packs have finished downloading, and then calls dm_cloud_sync.
|
||||
// The host unit test (tests/t_cloudsync.c) uses a local directory as the cloud.
|
||||
@@ -28,7 +37,16 @@
|
||||
// - First sync (this unit has no state record) and the two sides differ: the cloud is always authoritative (the local copy goes into the backup whole as usual); while running (allow_down = 0) nothing is uploaded or changed, and the download waits for the next launch. Local is uploaded only if the cloud has nothing.
|
||||
// - The shared stash (_stash) gets one more check: do not overwrite if the side to be overwritten "clearly has more" -- the chronicle segment of any shared stash save (.d2i) gets shorter (the chronicle only grows, never shrinks; a freshly installed empty stash has the shortest chronicle),
|
||||
// or what would overwrite is an empty new save (0 items and the chronicle still at the freshly-created size) while the other copy has items, or the chronicle vault side file (.swvault) has items while the other copy does not have this file at all (fresh install / old version).
|
||||
// Fewer items and an emptied chronicle vault are both normal play and are not blocked (only a stash that never recorded any chronicle being emptied is treated as a new save and blocked; better not to sync than to lose data). When blocked, neither local nor cloud is touched, no state is recorded, a failure line is logged, and a system notification is shown after entering a run (dm_cloud_conflict_take).
|
||||
// Fewer items and an emptied chronicle vault are both normal play and do not count (only a stash that never recorded any chronicle being emptied is treated as a new save).
|
||||
// Shared stash fork (iCloud offline conflict item 1, first step: nothing lost, nothing blocked forever): when the two sides differ at first sync, or the check above finds that "something would be lost", it is no longer blocked forever -
|
||||
// at launch the cloud is always taken as the current version (the local copy it replaces goes into the backup whole as usual), and if the local copy has anything (items / gold / chronicle / chronicle vault, any of them; the preset and freshly created empty saves do not count) it is also stored in
|
||||
// the to-merge inbox <save>/_cloudinbox/<timestamp>-<seq>/ (inside the save directory: when merged back in a run it is swapped in atomically in the same save commit as the character saves and the shared stash, so being killed neither duplicates nor loses anything;
|
||||
// names starting with an underscore are not characters and not shared stash files, and iCloud does not sync it - the inbox belongs to this device): mine.pack = the local copy; base.pack = the shared stash at the last successful sync (.stash_base next to the state file, included only if its digest matches),
|
||||
// to be merged back in a run later: when the cloud is a descendant of the base (the chronicle only grows; the cloud has every chronicle entry of the base) as "cloud + added locally - taken out locally"; when the origin cannot be told apart, as a union taking one of each identical item
|
||||
// (in a single-player game, one extra item in rare cases is better than one lost). If it cannot be stored in the inbox, nothing is touched this time.
|
||||
// While running (allow_down = 0) a fork is left alone until the next launch. Each newly stored copy gives one notice after entering a run (dm_cloud_conflict_take).
|
||||
// Every successful shared stash sync (upload / download / identical) writes the content at that moment to <state file>.stash_base, as the base for the next fork.
|
||||
// iCloud's own same-name file conflict versions (read out by cloud_ios.m) also go to the inbox: dm_cloud_inbox_add.
|
||||
#include <dirent.h>
|
||||
#include <errno.h>
|
||||
#include <stdint.h>
|
||||
@@ -39,6 +57,7 @@
|
||||
#include <sys/time.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
#include <pthread.h>
|
||||
#include "dm.h"
|
||||
|
||||
#define MAXF 64
|
||||
@@ -68,7 +87,7 @@ static int read_dir(const char *root, const char *rel, cs_unit *u) { // rel
|
||||
}
|
||||
// ---- 共享仓库的内容量(只认结构,不解物品):.d2i 按 55 AA 55 AA 分段,段内 +64 是 'JM' 的是物品页(+66 物品数),其余段是编年史;.swvault 头 'SWVT'、+6 件数
|
||||
// ---- Content volume of the shared stash (structure only, items are not decoded): .d2i is split into segments by 55 AA 55 AA; a segment with 'JM' at +64 is an item page (+66 item count), the other segments are the chronicle; .swvault has the header 'SWVT', +6 item count
|
||||
typedef struct { int kind, items, chron, vault; } cs_rich;
|
||||
typedef struct { int kind, items, chron, vault; long long gold; } cs_rich;
|
||||
// 游戏新建的空共享仓库:物品 0 件、编年史段 148 字节(三份新建档、rf3 的专家仓库都是这个值)。「0 件且编年史还是新建大小」= 没东西的新档,
|
||||
// 不许盖掉有物品的一份(rf3:云端专家仓库 2 件、编年史 148,本机新建的空档同样 148,只比编年史拦不住);编年史长过新建的仓库被玩家取空照常同步
|
||||
// An empty shared stash newly created by the game: 0 items, chronicle segment 148 bytes (three freshly created saves and rf3's hardcore stash all have this value). "0 items and the chronicle still at the freshly-created size" = an empty new save,
|
||||
@@ -91,7 +110,7 @@ static cs_rich rich_of(const cs_file *f) {
|
||||
if (f->size == sizeof g_stash_seed && !memcmp(f->data, g_stash_seed, sizeof g_stash_seed)) { r.chron = FRESH_CHRON; return r; } // 预置:0 件、新建大小 | seed: 0 items, freshly-created size
|
||||
#endif
|
||||
for (uint32_t o = 0; o + 68 <= f->size && !memcmp(f->data + o, "\x55\xaa\x55\xaa", 4); ) { uint32_t ln; memcpy(&ln, f->data + o + 16, 4); if (ln < 68 || o + ln > f->size) break;
|
||||
if (!memcmp(f->data + o + 64, "JM", 2)) { uint16_t c; memcpy(&c, f->data + o + 66, 2); r.items += c; } else r.chron += (int)ln; o += ln; } }
|
||||
if (!memcmp(f->data + o + 64, "JM", 2)) { uint16_t c; uint32_t g; memcpy(&c, f->data + o + 66, 2); memcpy(&g, f->data + o + 12, 4); r.items += c; r.gold += g; } else r.chron += (int)ln; o += ln; } }
|
||||
else if (L > 8 && !strcmp(f->path + L - 8, ".swvault")) { r.kind = 2; if (f->size >= 8 && !memcmp(f->data, "SWVT", 4)) { uint16_t c; memcpy(&c, f->data + 6, 2); r.vault = c; } }
|
||||
return r;
|
||||
}
|
||||
@@ -106,7 +125,18 @@ static const char *stash_shrinks(const cs_unit *w, const cs_unit *x, char *why,
|
||||
return NULL;
|
||||
}
|
||||
static _Atomic int g_conflict;
|
||||
int dm_cloud_conflict_take(void) { return __atomic_exchange_n((int *)&g_conflict, 0, __ATOMIC_SEQ_CST); } // 进局后取一次:有拦下的共享仓库覆盖就弹系统提示(diag.c) | taken once after entering a run: if a shared stash overwrite was blocked, show a system notification (diag.c)
|
||||
int dm_cloud_conflict_take(void) { return __atomic_exchange_n((int *)&g_conflict, 0, __ATOMIC_SEQ_CST); } // 进局后取一次:这次启动有共享仓库收进了待合并收件箱就弹系统提示(diag.c) | taken once after entering a run: if a shared stash was put in the to-merge inbox during this launch, show the system notice (diag.c)
|
||||
static int stash_has_stuff(const cs_unit *u) { // 共享仓库这份有没有东西值得留:任一 .d2i 有物品 / 金币 / 编年史长过新建,或编年史仓库有件(预置与新建空档不算) | whether this shared stash copy has anything worth keeping: any .d2i with items / gold / a chronicle longer than freshly created, or the chronicle vault has items (the preset and freshly created empty saves do not count)
|
||||
for (int i = 0; i < u->n; i++) { cs_rich r = rich_of(&u->f[i]); if ((r.kind == 1 && (r.items || r.gold || r.chron > FRESH_CHRON)) || (r.kind == 2 && r.vault)) return 1; }
|
||||
return 0;
|
||||
}
|
||||
// 同名角色(iCloud 离线冲突第 3 条):首次同步两边都有同名角色、内容不同 → 照旧以云端为准、本机那份整份进备份,另外记下名字,进局后提示一次(diag.c)。
|
||||
// 两份角色档没法合并(等级、任务、身上装备各是一条独立的历史);改名留两份要改 .d2s 头与校验和,不做。
|
||||
// Same-name character (iCloud offline conflict item 3): at first sync both sides have a character with the same name and different content -> as before the cloud is authoritative and the local copy goes into the backup whole; the name is also recorded and one notice is shown after entering a run (diag.c).
|
||||
// Two character saves cannot be merged (level, quests and equipment are each an independent history); keeping both under different names would need changes to the .d2s header and checksum, not done.
|
||||
static char g_char_conf[256]; static pthread_mutex_t g_cc_mu = PTHREAD_MUTEX_INITIALIZER;
|
||||
static void char_conf_add(const char *nm) { pthread_mutex_lock(&g_cc_mu); size_t l = strlen(g_char_conf); if (l + strlen(nm) + 3 < sizeof g_char_conf) snprintf(g_char_conf + l, sizeof g_char_conf - l, "%s%s", l ? "、" : "", nm); pthread_mutex_unlock(&g_cc_mu); }
|
||||
int dm_cloud_char_conflict_take(char *out, size_t n) { pthread_mutex_lock(&g_cc_mu); int r = g_char_conf[0] != 0; if (r) strlcpy(out, g_char_conf, n); g_char_conf[0] = 0; pthread_mutex_unlock(&g_cc_mu); return r; }
|
||||
|
||||
static int is_stash(const char *nm) { return !strncmp(nm, "SharedStash", 11) || !strncmp(nm, "ModernSharedStash", 17); }
|
||||
static int is_char_dir(const char *save, const char *nm) { char p[1600]; struct stat st; snprintf(p, sizeof p, "%s/%s/%s.d2s", save, nm, nm); return nm[0] != '.' && nm[0] != '_' && !stat(p, &st) && S_ISREG(st.st_mode); }
|
||||
@@ -215,6 +245,42 @@ static cs_state *state_get(cs_state *s, int *n, int cap, const char *unit, int a
|
||||
}
|
||||
static void add_name(char (*names)[64], int *n, const char *nm) { for (int i = 0; i < *n; i++) if (!strcmp(names[i], nm)) return; if (*n < 256 && strlen(nm) < 64) strlcpy(names[(*n)++], nm, 64); }
|
||||
|
||||
// ---- 待合并收件箱与基准(见文件头「共享仓库分叉」)
|
||||
// ---- To-merge inbox and base (see "Shared stash fork" in the file header)
|
||||
static void base_path(const char *statef, char *o, size_t n) { snprintf(o, n, "%s.stash_base", statef); }
|
||||
static int base_missing(const char *statef) { char bp[1300]; struct stat st; base_path(statef, bp, sizeof bp); return stat(bp, &st) != 0; } // 升级上来的设备第一次补写 | first write-out on a device upgraded from an older version
|
||||
static void base_put(const char *statef, const cs_unit *u) { // 共享仓库同步成功那一刻的内容,下次分叉时当基准 | the content at the moment of a successful shared stash sync, used as the base at the next fork
|
||||
char bp[1300]; base_path(statef, bp, sizeof bp); cs_unit t = *u; t.tomb = 0;
|
||||
if (pack_write(bp, &t)) LOG("【红】iCloud 同步:共享仓库基准写不进 %s errno=%d", bp, errno); }
|
||||
// 收件箱新条目:<存档>/_cloudinbox/<时刻>-<序号>/mine.pack(+ base.pack:摘要等于 base_hash 时才带;base_hash = 0 不带)。返回 0 = 收好了
|
||||
// New inbox entry: <save>/_cloudinbox/<timestamp>-<seq>/mine.pack (+ base.pack: included only when its digest equals base_hash; not included when base_hash = 0). Returns 0 = stored
|
||||
static int inbox_put(const char *save, const char *statef, const cs_unit *u, uint64_t base_hash, const char *why, const char *who) {
|
||||
char ib[1300], d[1400], f[1500]; snprintf(ib, sizeof ib, "%s/_cloudinbox", save); mkdir(ib, 0755);
|
||||
int k = 0; do snprintf(d, sizeof d, "%s/%llu-%d", ib, (unsigned long long)u->stamp, k++); while (mkdir(d, 0755) && errno == EEXIST && k < 100);
|
||||
snprintf(f, sizeof f, "%s/mine.pack", d); cs_unit t = *u; t.tomb = 0;
|
||||
if (pack_write(f, &t)) { LOG("【红】iCloud 同步:共享仓库收件箱写不进 %s errno=%d", f, errno); rm_rf(d); return -1; }
|
||||
int nb = 0; if (base_hash) { char bp[1300]; base_path(statef, bp, sizeof bp); cs_unit *B = calloc(1, sizeof *B);
|
||||
if (B && pack_read(bp, B) == 1 && B->hash == base_hash) { snprintf(f, sizeof f, "%s/base.pack", d); if (pack_write(f, B)) { LOG("【红】iCloud 同步:收件箱基准写不进 %s errno=%d", f, errno); unit_free(B); free(B); rm_rf(d); return -1; } nb = 1; }
|
||||
if (B) { unit_free(B); free(B); } }
|
||||
LOG("iCloud 同步:_stash %s,%s那份收进待合并收件箱 %s(%d 个文件,%s)", why, who, d, u->n, nb ? "带上次同步的基准" : "没有基准:两份当独立来历");
|
||||
__atomic_store_n((int *)&g_conflict, 1, __ATOMIC_SEQ_CST); return 0;
|
||||
}
|
||||
// iCloud 冲突版本(cloud_ios.m):把一份共享仓库包收进收件箱,基准用本机上次同步的那份。返回 0 = 收好了(或没东西不用收),-1 = 坏包 / 写不进
|
||||
// iCloud conflict version (cloud_ios.m): store one shared stash pack in the inbox, with the copy from this device's last sync as the base. Returns 0 = stored (or nothing worth storing), -1 = bad pack / cannot write
|
||||
int dm_cloud_inbox_add(const char *save, const char *statef, const char *pack) {
|
||||
cs_unit *u = calloc(1, sizeof *u); if (!u) return -1; int r = pack_read(pack, u), ret = -1;
|
||||
if (r == 1 && !u->tomb) { if (!stash_has_stuff(u)) ret = 0; else { char bp[1300]; base_path(statef, bp, sizeof bp); cs_unit *B = calloc(1, sizeof *B); uint64_t bh = B && pack_read(bp, B) == 1 ? B->hash : 0; if (B) { unit_free(B); free(B); }
|
||||
ret = inbox_put(save, statef, u, bh, "iCloud 冲突版本", "冲突版本"); } }
|
||||
else if (r == 1) ret = 0; else LOG("【红】iCloud 同步:冲突版本 %s 读不了", pack);
|
||||
unit_free(u); free(u); return ret;
|
||||
}
|
||||
// 角色包的 iCloud 冲突版本(cloud_ios.m):包头时刻(游戏最后写它的时刻)、整份进备份、记名进局提示
|
||||
// iCloud conflict version of a character pack (cloud_ios.m): the pack header timestamp (the moment the game last wrote it), the whole copy goes into the backup, the name is recorded for a notice after entering a run
|
||||
uint64_t dm_cloud_pack_stamp(const char *pack) { cs_unit *u = calloc(1, sizeof *u); uint64_t t = u && pack_read(pack, u) == 1 ? u->stamp : 0; if (u) { unit_free(u); free(u); } return t; }
|
||||
int dm_cloud_bak_pack(const char *bak, const char *unit, const char *pack, const char *why) {
|
||||
cs_unit *u = calloc(1, sizeof *u); int r = u && pack_read(pack, u) == 1 ? (u->tomb ? 0 : backup_copy(bak, unit, u, why)) : -1; if (u) { unit_free(u); free(u); } return r; }
|
||||
void dm_cloud_char_conflict_note(const char *unit) { char_conf_add(unit); }
|
||||
|
||||
// 返回本次动作数(上传 + 下载 + 删除),-1 = 参数错。ready(单位) 返回 0 = 云端那份还没下载好(iCloud 占位),这一单位本次跳过。now_ms = 写删除标记用的时刻
|
||||
// Returns the number of actions this time (uploads + downloads + deletions), -1 = bad arguments. ready(unit) returning 0 = the cloud copy has not finished downloading yet (iCloud placeholder), and this unit is skipped this time. now_ms = the timestamp used when writing a deletion marker
|
||||
int dm_cloud_sync(const char *save, const char *cloud, const char *bak, const char *statef, int allow_down, uint64_t now_ms, int (*ready)(const char *unit)) {
|
||||
@@ -245,19 +311,27 @@ int dm_cloud_sync(const char *save, const char *cloud, const char *bak, const ch
|
||||
else if (lchg && !cchg) act = UP;
|
||||
else act = C->stamp > L->stamp ? (C->tomb ? DEL_LOCAL : DOWN) : UP; // 两边都改了(或从没同步过且内容不同):后写的赢 | both sides changed (or never synced and the contents differ): the later write wins
|
||||
if ((act == DOWN || act == DEL_LOCAL) && !allow_down) { act = NONE; goto next; } // 运行中不改本地:等下次启动,状态不动 | do not change local data while running: wait for the next launch, state untouched
|
||||
if (!strcmp(un, "_stash") && ((act == DOWN && hl) || (act == UP && hc && !C->tomb))) { char why[400]; // 共享仓库:要被覆盖的一方明显更多就不覆盖(见文件头) | shared stash: do not overwrite if the side to be overwritten clearly has more (see the file header)
|
||||
if (act == DOWN ? stash_shrinks(C, L, why, sizeof why) : stash_shrinks(L, C, why, sizeof why)) {
|
||||
LOG("【红】iCloud 同步:_stash %s会丢东西(%s),不覆盖、两边都不动", act == DOWN ? "下载云端那份" : "上传本机那份", why);
|
||||
__atomic_store_n((int *)&g_conflict, 1, __ATOMIC_SEQ_CST); act = NONE; goto next; } }
|
||||
if (!strcmp(un, "_stash") && hl && hc && !C->tomb && L->hash != C->hash) { char why[400] = ""; // 共享仓库分叉(见文件头):云端为现行版,本机那份有东西就进收件箱 | shared stash fork (see the file header): the cloud is the current version; the local copy goes into the inbox if it has anything
|
||||
int fork = 0;
|
||||
if (!S) { snprintf(why, sizeof why, "首次同步两边不同"); fork = 1; }
|
||||
else if (act == DOWN) fork = stash_shrinks(C, L, why, sizeof why) != NULL;
|
||||
else if (act == UP) fork = stash_shrinks(L, C, why, sizeof why) != NULL;
|
||||
if (fork) {
|
||||
if (!allow_down) { LOG("iCloud 同步:_stash 分叉(%s),运行中不动,等下次启动收进收件箱", why); goto next; }
|
||||
if (stash_has_stuff(L) && inbox_put(save, statef, L, S ? S->hash : 0, why, "本机")) goto next; // 收不进收件箱:这次不动 | cannot store it in the inbox: leave everything this time
|
||||
act = DOWN; } }
|
||||
if (act == UP) {
|
||||
if (hc && !C->tomb && C->hash != L->hash && cchg && backup_copy(bak, un, C, "云端(被本机后写覆盖)")) goto next;
|
||||
L->tomb = 0; if (pack_write(cp, L)) { LOG("【红】iCloud 同步:%s 上传失败 errno=%d", un, errno); goto next; }
|
||||
LOG("iCloud 同步:%s 上传(时刻 %llu,%d 个文件)", un, (unsigned long long)L->stamp, L->n); acts++;
|
||||
W = state_get(st, &ns, 256, un, 1); if (W) { W->hash = L->hash; W->stamp = L->stamp; W->tomb = 0; }
|
||||
if (!strcmp(un, "_stash")) base_put(statef, L);
|
||||
} else if (act == DOWN) {
|
||||
if (local_apply(save, bak, un, hl ? L : NULL, C)) { LOG("【红】iCloud 同步:%s 下载后换进本地失败 errno=%d(本地不变)", un, errno); goto next; }
|
||||
LOG("iCloud 同步:%s 下载(时刻 %llu,%d 个文件)", un, (unsigned long long)C->stamp, C->n); acts++;
|
||||
if (!S && hl && strcmp(un, "_stash")) { char_conf_add(un); LOG("iCloud 同步:%s 两台设备各有一份同名角色,用云端那份,本机那份已进备份;进局提示", un); }
|
||||
W = state_get(st, &ns, 256, un, 1); if (W) { W->hash = C->hash; W->stamp = C->stamp; W->tomb = 0; }
|
||||
if (!strcmp(un, "_stash")) base_put(statef, C);
|
||||
} else if (act == DEL_LOCAL) {
|
||||
{ char d[1300]; if (move_to_bak(save, bak, un, L, "本机(另一台删了这个角色)", d, sizeof d)) goto next; } // 删 = 整份挪进备份,挪不动就不删 | delete = move the whole copy into the backup; if it cannot be moved, do not delete
|
||||
LOG("iCloud 同步:%s 另一台删了,本机也删(备份已留)", un); acts++;
|
||||
@@ -266,7 +340,8 @@ int dm_cloud_sync(const char *save, const char *cloud, const char *bak, const ch
|
||||
cs_unit t = { .tomb = 1, .stamp = now_ms }; if (pack_write(cp, &t)) { LOG("【红】iCloud 同步:%s 写删除标记失败 errno=%d", un, errno); goto next; }
|
||||
LOG("iCloud 同步:%s 本机删了,云端记删除标记", un); acts++;
|
||||
W = state_get(st, &ns, 256, un, 1); if (W) { W->hash = 0; W->stamp = now_ms; W->tomb = 1; }
|
||||
} else if (hc) { W = state_get(st, &ns, 256, un, 1); if (W) { W->hash = C->tomb ? 0 : C->hash; W->stamp = C->stamp; W->tomb = C->tomb; } } // 一致:记成已同步 | identical: record as synced
|
||||
} else if (hc) { W = state_get(st, &ns, 256, un, 1); if (W) { W->hash = C->tomb ? 0 : C->hash; W->stamp = C->stamp; W->tomb = C->tomb; } // 一致:记成已同步 | identical: record as synced
|
||||
if (!strcmp(un, "_stash") && !C->tomb && (!S || S->hash != C->hash || base_missing(statef))) base_put(statef, C); }
|
||||
next:
|
||||
unit_free(L); unit_free(C); free(L); free(C);
|
||||
}
|
||||
|
||||
+192
-9
@@ -680,7 +680,15 @@ static int inside_walk(uint64_t w, uint64_t xy, int dep, uint64_t vt_catch) {
|
||||
{ const char *nm = (const char *)*(uint64_t *)(w + 8); // 不画东西、只占位的辅助控件不算(名字来自实测:整屏命中、与面板无关) | Helper widgets that draw nothing and only occupy space do not count (names from measurement: full-screen hit, unrelated to panels)
|
||||
static const char *skip[] = { "PanelBordersPanel", "ControllerCursorBounds", "ShowItemsPanel", "MiniMenuPanel", "TooltipsPanel", "EmoteWheelPanel", "TransparentBG", "SpriteColoringHelper", "LanguageFontRemapper", "ShowItemsParameters", "ControllerCursorParameters", "MoviePlayer", "AutoMap", "TooltipTextBox" }; // TooltipTextBox:说明框伸到面板外时不算面板(点它 = 点面板外 = 关;mini 技能树页 2/5 被它挡住) // AutoMap:小地图面板整屏占位(进局后常开) | TooltipTextBox: when the tooltip box extends outside the panel it does not count as a panel (tapping it = tapping outside the panel = close; on the second Mac it blocked 2/5 on the skill tree page) // AutoMap: the minimap panel is a full-screen placeholder (always open after entering a run)
|
||||
if (nm) for (unsigned i = 0; i < sizeof skip / sizeof *skip; i++) if (!strcmp(nm, skip[i])) return 0; }
|
||||
{ uint64_t rel = vt - (vt_catch - 0x20c1328); // 叶子控件,或带子控件的底板类(九宫格底板 0x20b9580、对话框边框 0x20bc048:设置页的 Background 就是带子控件的底板) | A leaf widget, or a backing-type widget with children (nine-slice backing 0x20b9580, dialog border 0x20bc048: the settings page's Background is a backing with children)
|
||||
{ uint64_t rel = vt - (vt_catch - 0x20c1328); // 叶子控件,或带子控件的底板类(九宫格底板 0x20b9580、对话框边框 0x20bc048:设置页的 Background 就是带子控件的底板; | Leaf widgets, or backing classes with children (nine-slice backing 0x20b9580, dialog frame 0x20bc048: the Background of the settings page is a backing with children;
|
||||
// 带子控件的图片 0x20b8650:编年史「查看奖励」页的整页底板 RewardsBg 就是它,原先不算,卡片之间的空处判成「奖励页没盖住」,
|
||||
// 点下去穿到底下的编年史列表 / 分类 / 页签上,列表容器拿到焦点、金框画在奖励页上面(iPhone 15 Pro 截图)。按它自己的矩形算,同叶子图片;
|
||||
// 先查它的子控件、都没中才算它自己——名字要报到最里层(关闭钮按 TouchClose / close 的名字认)
|
||||
// Image widget with children 0x20b8650: the full-page backing RewardsBg of the Chronicle "View Rewards" page is one. It used to be ignored, so empty space between cards was judged "not covered by the rewards page",
|
||||
// and a tap fell through to the Chronicle list / categories / tabs underneath; the list container got focus and its gold frame was drawn over the rewards page (iPhone 15 Pro screenshot). It now counts with its own rect, like a leaf image;
|
||||
// its children are checked first and only if none is hit does it count itself, so the name is reported down to the innermost widget (the close button is recognized by the names TouchClose / close)
|
||||
if (rel == 0x20b8650 && n && ch && n <= 256) { for (uint64_t i = 0; i < n; i++) if (inside_walk(*(uint64_t *)(ch + 8 * i), xy, dep + 1, vt_catch)) return 1;
|
||||
uint64_t fn = *(uint64_t *)(vt + 0x48); if (((int (*)(uint64_t, uint64_t))fn)(w, xy) & 1) { g_inside_name = *(uint64_t *)(w + 8) ? (const char *)*(uint64_t *)(w + 8) : "?"; return 1; } return 0; }
|
||||
if (!n || !ch || rel == 0x20b9580 || rel == 0x20bc048) { uint64_t fn = *(uint64_t *)(vt + 0x48); int h = ((int (*)(uint64_t, uint64_t))fn)(w, xy) & 1; if (h) { g_inside_name = *(uint64_t *)(w + 8) ? (const char *)*(uint64_t *)(w + 8) : "?"; return 1; } if (!n || !ch) return 0; } }
|
||||
if (n > 256) return 0;
|
||||
for (uint64_t i = 0; i < n; i++) if (inside_walk(*(uint64_t *)(ch + 8 * i), xy, dep + 1, vt_catch)) return 1;
|
||||
@@ -710,6 +718,7 @@ static int ui_inside_panel(module_t *m, uint64_t root, uint64_t xy) { // 从
|
||||
for (int i = (int)n - 1; i >= 0; i--) { uint64_t p = *(uint64_t *)(ch + 8 * i); if (!p || !*(uint8_t *)(p + 0x50)) continue; const char *nm = (const char *)*(uint64_t *)(p + 8);
|
||||
if (nm && !strncmp(nm, "HUD", 3)) continue; // HUD 各层属于游戏画面,不算面板 | HUD layers belong to the game screen and do not count as panels
|
||||
if (nm && !strcmp(nm, "NotificationPanel")) continue; // 系统提示框不接点击(同 panel_skip) | system notifications do not take taps (same as panel_skip)
|
||||
if (nm && !strcmp(nm, "FocusManager")) continue; // 焦点金框只是画在被选中控件上的框,不是可点的东西(同 panel_skip):原先点到金框画着的地方命中「FocusIndicator@FocusManager」,那一下落空 | The focus gold frame is only a frame drawn on the selected widget, not something you can tap (same as panel_skip): before, tapping where the gold frame was drawn hit "FocusIndicator@FocusManager" and the tap went nowhere
|
||||
if (inside_walk(p, xy, 1, (uint64_t)m->base + 0x20c1328)) { g_inside_owner = nm ? nm : "?"; return 1; } }
|
||||
return 0;
|
||||
}
|
||||
@@ -1938,6 +1947,73 @@ int dm_ui_minimap_rect(float r[4]) { if (!atomic_load(&g_mm_have)) return 0; uin
|
||||
// and if the flip waited for the per-frame check of the panel tree in the next frame, the UI would still be laid out centered in the frame the loading screen is removed (in that frame the health globe is at the centered position and the area name is not lifted). -1 = no message received yet, go by the panel tree.
|
||||
static _Atomic int g_load_up = -1;
|
||||
static uint64_t g_lift_next;
|
||||
// 系统提示框(NotificationPanel)的停靠高度分两态。布局里写的是没开面板时的高度(gen_romfs_overlay.py:上提到让开底栏上方的生命 / 法力数值);
|
||||
// 开着大面板时那行数值被面板盖住,上提后的框反而压在背包格子上,所以面板态改停到 NOTE_PANEL_Y(布局单位,同 json 的 y):大面板底边框那一带,在金币 / 存放那排下面。
|
||||
// 大面板 = 下面名单里的界面根直接子可见(NPC 讲话框、对话菜单这类小框不算:那时底栏还在,框要留在上提位)。名单漏了的面板照无面板处理(= 上一版行为)
|
||||
// 改的是对象 +0x19c「停靠目标 y」:原版重排(main+0x3d7e1c)按布局把矩形 y 抄进去,每帧更新(main+0x3d7fbc)滑入滑出时按 (1-t)·目标 插值写 +0x74、
|
||||
// 自己从不写 +0x19c——所以改它不跟动画抢坐标(用位置守卫改 +0x74 就是被动画每帧盖回)。单位换算:矩形高 +0x7c 对应布局高 244。
|
||||
// 写回由我们确定性做(把写 +0x19c 登记成例外的条件;原版控件规则见 tests/native_write_scan.py NATIVE_FIELD_OK):
|
||||
// 我们记下原值,停靠条件一结束——面板关、读取画面开(切场景)、保存并退出、回到前端——当场写回,不靠游戏重排;重排只是第二道保险
|
||||
// (现值不是我们上次写的 = 游戏重排过(换模式 / 改分辨率),当新原值)。消息路(dm_ui_on_uimsg)在消息到达那一刻写,每帧路兜着。
|
||||
// 保存并退出 / 回到前端之后到下一次进局之前不再停靠(暂停菜单在退出那几帧还挂着,不压住的话下一帧又停回面板态)。
|
||||
// 测试开关 DM_TEST_NOTE_PANEL_Y=<单位> 试别的高度
|
||||
// The docking height of the system notice box (NotificationPanel) has two states. The layout holds the height with no panel open (gen_romfs_overlay.py: raised out of the way of the life / mana numbers above the bottom bar);
|
||||
// with a large panel open that row of numbers is covered by the panel, and the raised box would sit on the inventory cells instead, so in panel state it docks at NOTE_PANEL_Y (layout units, like y in the json): the band of the large panel's bottom frame, below the gold / Store row.
|
||||
// Large panel = a root of the list below being a visible direct child (small boxes such as the NPC speech box and dialogue menu do not count: the bottom bar is still there then, and the box stays in the raised position). A panel missing from the list is treated as no panel (= the previous behaviour)
|
||||
// What is changed is the object's +0x19c "docking target y": the original relayout (main+0x3d7e1c) copies the rectangle y into it from the layout, and the per-frame update (main+0x3d7fbc) writes +0x74 interpolated as (1-t)*target during slide-in / slide-out,
|
||||
// never writing +0x19c itself - so changing it does not fight the animation for the position (changing +0x74 with a position guard just gets overwritten by the animation every frame). Unit conversion: rectangle height +0x7c corresponds to layout height 244.
|
||||
// Writing back is done deterministically by us (the condition for registering writes to +0x19c as an exception; the rule for original widgets is in tests/native_write_scan.py NATIVE_FIELD_OK):
|
||||
// we record the original value, and as soon as the docking condition ends - panel closed, loading screen open (scene change), save and exit, back to the front end - it is written back on the spot, without relying on the game's relayout; the relayout is only a second safety net
|
||||
// (current value is not what we last wrote = the game relaid it out (mode change / resolution change), taken as the new original). The message path (dm_ui_on_uimsg) writes the moment the message arrives; the per-frame path covers the rest.
|
||||
// After save and exit / back to the front end, no docking until the next time a game is entered (the pause menu is still up for those few frames of exiting; without holding it, the next frame would dock to the panel state again).
|
||||
// Test switch DM_TEST_NOTE_PANEL_Y=<units> tries another height
|
||||
#define NOTE_PANEL_Y -310
|
||||
// 停靠目标切换的那一刻框已停稳(+0x198 显示中、矩形 y +0x74 正等于旧目标):原版停稳时不再写坐标,只改 +0x19c 它会一直留在旧位置——
|
||||
// 开面板时压着背包格、关面板时压着底栏数值(两个方向都被退回过)。所以两个方向都顺手把 +0x74 一次写成新目标(登记的第二处例外,
|
||||
// 只许 note_dock_snap 写)。滑入滑出期间 +0x74 不等于旧目标、不写;滑出刚开始那一帧即使相等,之后的插值用的也是已改的 +0x19c,同向不打架。
|
||||
// 写完下一帧核:+0x74 还是新目标 = 没在动画期写;被改了记红(g_nd_ychk)
|
||||
// At the moment the docking target switches, the box has already settled (+0x198 showing, rectangle y +0x74 exactly equal to the old target): once settled the original no longer writes the position, and changing only +0x19c leaves it at the old place -
|
||||
// over the inventory cells when a panel opens, over the bottom-bar numbers when it closes (both directions were sent back). So both directions also write +0x74 to the new target in one go (the second registered exception,
|
||||
// written only by note_dock_snap). During slide-in / slide-out +0x74 is not equal to the old target, so nothing is written; even if equal on the first frame of slide-out, the interpolation after that uses the already changed +0x19c, so they move the same way.
|
||||
// Check on the next frame after writing: +0x74 still the new target = not written during animation; if it was changed, log red (g_nd_ychk)
|
||||
static uint64_t g_nd_w; static int32_t g_nd_orig, g_nd_mine; static int g_nd_on = -1, g_nd_hold; // g_nd_hold:1 = 退出中(等出局),2 = 已出局(等进局) | g_nd_hold: 1 = leaving (waiting to be out of the game), 2 = out of the game (waiting to enter)
|
||||
static int g_nd_ychk; static int32_t g_nd_ywant; static unsigned g_nd_ywr, g_nd_ybad; // 写过 +0x74 待下一帧核(核它还是 g_nd_ywant);累计写入次数 / 动画期写入(被改)次数 | +0x74 was written, check it next frame (that it is still g_nd_ywant); total writes / writes during animation (overwritten)
|
||||
static int note_dock_snap(uint64_t w, int32_t from, int32_t to) { // 框已停稳在 from:矩形 y 一次写成 to。返回 1 = 写了 | the box has settled at from: write the rectangle y as to in one go. Returns 1 = written
|
||||
int32_t *ry = (int32_t *)(w + 0x74); if (!*(uint8_t *)(w + 0x198) || *ry != from || from == to) return 0;
|
||||
*ry = to; g_nd_ychk = 1; g_nd_ywant = to; g_nd_ywr++; return 1;
|
||||
}
|
||||
static void note_dock_restore(uint64_t root, const char *why) { // 只许游戏主线程 | game main thread only
|
||||
uint64_t w = root ? ui_find(root, "NotificationPanel", 0) : 0; if (!w || w != g_nd_w) return; // 不在树里 / 不是记下的那个对象:不碰 | not in the tree / not the object we recorded: do not touch
|
||||
int32_t *t = (int32_t *)(w + 0x19c);
|
||||
if (*t == g_nd_mine && g_nd_mine != g_nd_orig) {
|
||||
*t = g_nd_orig; int still = note_dock_snap(w, g_nd_mine, g_nd_orig);
|
||||
static int lg; if (lg++ < 60) LOG("提示框停靠:%s → 写回原值 y %d%s", why, g_nd_orig, still ? "(框已停稳,矩形 y 一并写回)" : ""); }
|
||||
g_nd_mine = *t; g_nd_on = 0;
|
||||
}
|
||||
static void ui_note_dock_pump(uint64_t root) {
|
||||
static const char *const big[] = { "PlayerInventoryExpansionLayout", "SkillsTreePanel", "CharacterStatsPanel", "QuestLogPanelExpansion", "BankExpansionLayout", "HoradricCubeLayout",
|
||||
"WaypointsPanelExpansion", "VendorPanelLayout", "HirelingInventoryPanel", "ImbueItemsPanel", "ChroniclePanel", "MessageLogPanel", "PauseLayout", "PauseLayoutGarden",
|
||||
"SettingsPanel", "SoundOptionsPanel", "VideoOptionsPanel", "GameplayOptionsPanel" };
|
||||
static int py = 1;
|
||||
if (py > 0) { const char *e = getenv("DM_TEST_NOTE_PANEL_Y"); py = e ? atoi(e) : NOTE_PANEL_Y; }
|
||||
uint64_t w = ui_find(root, "NotificationPanel", 0); if (!w) { g_nd_w = 0; return; }
|
||||
int32_t *t = (int32_t *)(w + 0x19c), h = *(int32_t *)(w + 0x7c);
|
||||
if (g_nd_ychk) { g_nd_ychk = 0; int32_t y = *(int32_t *)(w + 0x74); static int lg;
|
||||
if (w != g_nd_w) { if (lg++ < 60) LOG("提示框停靠:写回矩形 y 后提示框对象已换(出局 / 重建),不核"); }
|
||||
else if (y != g_nd_ywant) { g_nd_ybad++; LOG("【红】提示框停靠:矩形 y 写成 %d 后下一帧被改成 %d(动画期写入,第 %u 次)", g_nd_ywant, y, g_nd_ybad); }
|
||||
else if (lg++ < 60) LOG("提示框停靠:停稳的框下一帧在 y %d(%s;矩形 y 写入第 %u 次,动画期 %u 次)", y, y == g_nd_orig ? "原位" : "面板态位", g_nd_ywr, g_nd_ybad); }
|
||||
if (w != g_nd_w || *t != g_nd_mine) { g_nd_w = w; g_nd_orig = *t; g_nd_mine = *t; }
|
||||
int ing = dm_uiscreen_ingame(); if (g_nd_hold == 1 && !ing) g_nd_hold = 2; else if (g_nd_hold == 2 && ing) g_nd_hold = 0;
|
||||
int panel = 0; uint64_t ch = *(uint64_t *)(root + 0x58), n = *(uint64_t *)(root + 0x60); // 名单里的面板在屏上(可见且有可见内容)= 面板态;两种模式通用 | a panel on the list is on screen (visible and with visible content) = panel state; same for both modes
|
||||
for (uint64_t j = 0; ing && !g_nd_hold && j < n && !panel; j++) { uint64_t c = *(uint64_t *)(ch + 8 * j); const char *nm = c ? (const char *)*(uint64_t *)(c + 8) : NULL;
|
||||
if (!nm || !*(uint8_t *)(c + 0x50)) continue;
|
||||
for (unsigned i = 0; i < sizeof big / sizeof *big && !panel; i++) panel = !strcmp(nm, big[i]) && has_visible_leaf(c, 1); }
|
||||
int32_t pv = h > 0 ? (int32_t)lroundf(py * h / 244.0f) : g_nd_orig;
|
||||
if (!(panel && pv > g_nd_orig)) { if (g_nd_on) note_dock_restore(root, ing ? "面板关了" : "不在局内"); } // 只往下挪:布局本来就不低于面板态高度时不动 | only move it down: if the layout is already no higher than the panel-state height, leave it
|
||||
else if (*t != pv) { int32_t was = *t; *t = pv; g_nd_mine = pv;
|
||||
if (note_dock_snap(w, was, pv)) { static int lg; if (lg++ < 60) LOG("提示框停靠:开面板时框已停稳在 y %d,矩形 y 一并写成面板态位 %d", was, pv); } }
|
||||
if (panel != g_nd_on) { g_nd_on = panel; static int lg; if (lg++ < 40) LOG("提示框停靠:%s,目标 y %d(布局原值 %d,矩形高 %d)", panel ? "面板态" : "无面板", *t, g_nd_orig, h); }
|
||||
}
|
||||
static void ui_lift_pump(uint64_t root, uint64_t fr) {
|
||||
if (fr < g_lift_next) return; g_lift_next = fr + 6;
|
||||
int x, y, w, h; dm_ui_rect(&x, &y, &w, &h); int lift = h > 0 && dm_uiscreen_ingame() ? (int)((long)y * 2160 / h) : 0;
|
||||
@@ -2274,6 +2350,72 @@ int dm_ui_panel_resident(const char *name) {
|
||||
"CandidateListPanel" };
|
||||
if (!name) return 0; for (unsigned i = 0; i < sizeof k / sizeof *k; i++) if (!strcmp(name, k[i])) return 1; return 0;
|
||||
}
|
||||
// 面板开合栈(前端「面板模式」的依据,原在 front_ios.m hud_stack_message;搬来,iOS 前端与 Mac touch_mac.c 在各自的界面消息回调里调同一份)。
|
||||
// 底部 UI v4 的 UIKit 底栏只在「局内常态」画:维护面板开合栈,常驻 HUD 层(dm_ui_panel_resident)之外任何面板开着就不画、前端进面板态。
|
||||
// 返回栈读数:开着的非常驻面板数;只开着 NPC 对话菜单 / 说话框时 -1。日志字样「[hud] 面板栈 …」保持原样(回归脚本按它认)
|
||||
// Panel open/close stack (the basis of the front end's "panel mode"; formerly front_ios.m hud_stack_message, moved here so the iOS front end and Mac touch_mac.c call the same one from their UI message callbacks).
|
||||
// The UIKit bottom bar of bottom UI v4 is only drawn in the normal in-game state: maintain the panel stack; whenever any panel other than the resident HUD layers (dm_ui_panel_resident) is open, it is not drawn and the front end enters panel mode.
|
||||
// Returns the stack reading: number of open non-resident panels; -1 when only the NPC dialog menu / speech box is open. The log text "[hud] 面板栈 ..." is kept as is (regression scripts match on it)
|
||||
enum { HUD_STACK_MAX = 64 };
|
||||
static struct { char name[64]; int open; } g_hud_stack[HUD_STACK_MAX];
|
||||
static void hud_stack_update(const char *act, const char *arg) {
|
||||
// 读取画面撤下:清掉此刻在游戏面板树里已经看不见的记录(防只开不关的漏配),屏上还在的照记——
|
||||
// 通关页是读取画面撤下前 0.5 秒开的(OpenExclusivePanel EndScreenPanelExpansion → UnloadPanel LoadScreenPanel),原先整栈清零把它也清了:
|
||||
// 底栏和技能钮盖在通关页上、点「好」变成点世界
|
||||
// Loading screen removed: clear the records no longer visible in the game's panel tree at this moment (guards against open-without-close mismatches), and keep those still on screen --
|
||||
// the game-completion page is opened 0.5 seconds before the loading screen is removed (OpenExclusivePanel EndScreenPanelExpansion → UnloadPanel LoadScreenPanel); previously the whole stack was zeroed, clearing it too:
|
||||
// the bottom bar and skill buttons covered the game-completion page, and tapping 「好」(OK) became a world tap
|
||||
if(!strcmp(act,"UnloadPanel") && !strcmp(arg,"LoadScreenPanel")) {
|
||||
for(int i=0;i<HUD_STACK_MAX;i++) {
|
||||
if(g_hud_stack[i].open>0 && strcmp(g_hud_stack[i].name,"LoadScreenPanel") && dm_ui_panel_shown(g_hud_stack[i].name)) fprintf(stderr,"[hud] 面板栈 读取画面撤下:%s 屏上还在,照记\n",g_hud_stack[i].name);
|
||||
else memset(&g_hud_stack[i],0,sizeof g_hud_stack[i]);
|
||||
}
|
||||
}
|
||||
else if(!strcmp(act,"UnloadAll")) memset(g_hud_stack,0,sizeof g_hud_stack);
|
||||
else {
|
||||
// PanelManager 的面板动作全集(读码:它的消息分发 main+0xb1dc60 只认这 8 个,与全部日志里出现过的一致):
|
||||
// OpenPanel / OpenExclusivePanel = 开;ClosePanel / UnloadPanel = 关(读取画面那条见上);TogglePanel = 按当前记录翻转(高级属性页走它);
|
||||
// UnloadAll = 全清(见上);LoadPanel = 预载、不上屏,不算开关;HideGameInfo = 隐藏游戏信息层,与面板开关无关
|
||||
// Full set of PanelManager panel actions (from reading the code: its message dispatch main+0xb1dc60 only recognizes these 8, matching what has appeared across all logs):
|
||||
// OpenPanel / OpenExclusivePanel = open; ClosePanel / UnloadPanel = close (for the loading screen one see above); TogglePanel = flip according to the current record (the advanced stats page uses it);
|
||||
// UnloadAll = clear all (see above); LoadPanel = preload without showing, not counted as open or close; HideGameInfo = hide the game info layer, unrelated to panel open / close
|
||||
int tog=!strcmp(act,"TogglePanel");
|
||||
int open=!strcmp(act,"OpenPanel")||!strcmp(act,"OpenExclusivePanel"), close=!strcmp(act,"ClosePanel")||!strcmp(act,"UnloadPanel");
|
||||
if(!open && !close && !tog) return;
|
||||
if(dm_ui_panel_resident(arg)) return;
|
||||
int slot=-1; for(int i=0;i<HUD_STACK_MAX;i++) if(!strcmp(g_hud_stack[i].name,arg)) { slot=i; break; }
|
||||
if(slot<0) for(int i=0;i<HUD_STACK_MAX;i++) if(!g_hud_stack[i].name[0]) { slot=i; strlcpy(g_hud_stack[i].name,arg,sizeof g_hud_stack[i].name); break; }
|
||||
if(slot<0) return;
|
||||
if(tog) { open=g_hud_stack[slot].open<=0; close=!open; }
|
||||
// 没开着就收到关闭 = 空操作,不是漏配:游戏开功能页 / 切页签时对一批互斥面板(仓库、方块、商店、小站、对话…)统一发 ClosePanel,不管开没开;
|
||||
// 启动时选角页也是先关再开(读界面消息流水;之前记成红,玩家路径每次启动 14 条假红)。真漏接了打开的后果是底栏不让开,由下面 60 秒巡检兜
|
||||
// A close received while not open = no-op, not a missing mapping: when opening a function page / switching tabs the game sends ClosePanel to a batch of mutually exclusive panels (storage, cube, shop, waypoint, dialog…) regardless of whether they are open;
|
||||
// at launch the character select page is also closed first and then opened (from reading the UI message log; previously logged as a failure, 14 false failures per launch on the player path). The consequence of really missing an open is the bottom bar not yielding, which the 60-second patrol below covers
|
||||
if(close && g_hud_stack[slot].open<=0) return;
|
||||
// 按「开 / 没开」记,不按次数累加:游戏对已经开着的面板再发一次 OpenPanel 是常态——雇佣列表上的替换确认框每被关掉一次,
|
||||
// 就重发一次 OpenPanel HireMenuPanel(中间没有关闭),而整段对话结束时只发固定次数的关闭。按次数加的话多出确认框两回再雇成,计数留在 1:
|
||||
// 屏上已没有面板,前端却一直按面板态(没摇杆、没技能钮、点哪里都是「面板外」)。809 份日志里计数到过 2 以上的只有 4 个面板
|
||||
// (主菜单链接、选角页、起名候选栏、雇佣列表),没有一个是真叠两层要关两次的。dm_tc_navigation 那一路本来就是幂等位图,两路口径一致了
|
||||
// Recorded as "open / not open", not accumulated by count: the game sending OpenPanel again for an already open panel is normal -- each time the replacement confirmation box on the hire list is dismissed,
|
||||
// OpenPanel HireMenuPanel is sent again (with no close in between), while at the end of the whole dialog only a fixed number of closes is sent. Adding by count, when the confirmation box comes up two extra times and the hire then succeeds, leaves the count at 1:
|
||||
// no panel left on screen, yet the front end stays in panel mode (no stick, no skill buttons, every tap is "outside the panel"). Across 809 logs only 4 panels ever reached a count of 2 or more
|
||||
// (main menu links, character select page, naming candidate bar, hire list), and none of them was a real two-layer stack needing two closes. The dm_tc_navigation path was already an idempotent bitmap, so the two paths now agree
|
||||
if(open && g_hud_stack[slot].open>0) { fprintf(stderr,"[hud] 面板栈 %s %s:已经开着,不重复计\n",act,arg); return; }
|
||||
g_hud_stack[slot].open=open?1:0;
|
||||
fprintf(stderr,"[hud] 面板栈 %s %s → %d\n",act,arg,g_hud_stack[slot].open);
|
||||
}
|
||||
}
|
||||
int dm_hud_stack_msg(const char *act, const char *arg) {
|
||||
hud_stack_update(act, arg);
|
||||
// NPC 对话菜单(交谈 / 交易…那一小列)不挡底栏:只开着它时底栏照常显示(否则 UIKit 层让开、露出游戏层那份底栏,难度格和回城书不见、腰带样子也变)。
|
||||
// 编码进同一个数:对话菜单开着且没有别的面板 → -1(底栏不让开、且免除导航态的隐藏)
|
||||
// The NPC dialog menu (the small column of Talk / Trade…) does not block the bottom bar: with only it open the bottom bar shows as usual (otherwise the UIKit layer yields and exposes the game layer's bottom bar; the difficulty cell and Tome of Town Portal disappear and the belt looks different too).
|
||||
// Encoded into the same number: dialog menu open with no other panel → -1 (the bottom bar does not yield, and navigation-mode hiding is waived)
|
||||
int n=0, dlg=0; for(int i=0;i<HUD_STACK_MAX;i++) { if(!strcmp(g_hud_stack[i].name,"NpcDialogPanel")||!strcmp(g_hud_stack[i].name,"ScrollSpeechPanel")) dlg|=g_hud_stack[i].open>0; else n+=g_hud_stack[i].open; } // ScrollSpeechPanel = NPC 说话的滚动文字框(屏幕上方一小块),同样不挡底栏 | ScrollSpeechPanel = the scrolling text box of NPC speech (a small block at the top of the screen); it likewise does not block the bottom bar
|
||||
if(!n && dlg) n=-1;
|
||||
return n;
|
||||
}
|
||||
void dm_hud_stack_dump(void) { for (int i = 0; i < HUD_STACK_MAX; i++) if (g_hud_stack[i].open) fprintf(stderr, "%s×%d ", g_hud_stack[i].name, g_hud_stack[i].open); } // 开着的记录(巡检日志用) | Records currently open (for the patrol log)
|
||||
static struct { char name[48]; int open; } g_pm[48]; // 界面消息上开着的非常驻面板 | Non-persistent panels that are open per the UI messages
|
||||
static void ui_panel_note(const char *act, const char *arg) { // 界面消息回调里调(游戏主线程) | Called from the UI message callback (game main thread)
|
||||
if (!strcmp(act, "UnloadAll")) { memset(g_pm, 0, sizeof g_pm); return; }
|
||||
@@ -2430,14 +2572,51 @@ static void ui_panel_state_pump(uint64_t root) { // 游戏主线程,每帧 |
|
||||
// 触屏专属(带 if (tm)):请求全部来自触摸手势——点世界 / 佣兵头像、长按取物、双击使用、点货买、拖放、点技能绑定、副手组页签、开佣兵页。
|
||||
// 手柄模式与切换事务进行中不跑;在途的请求由切换清理作废(dm_ui_cache_mode_leave)。
|
||||
// 两种模式都跑:ui_target_pump(鉴定目标,含手柄按住 A)、ui_item_pump(命中查询,宿主自己也问)、ui_ptr_pump(指针事件,宿主合成的点击也走)、
|
||||
// ui_safe_pump / ui_lift_pump / ui_trove_tabs_pump / ui_minimap_pump / ui_map_pump / ui_map_geom_pump / ui_map_center(屏幕几何,与输入方式无关)、ui_boss_pct_pump、ui_npcdlg_pump、
|
||||
// ui_safe_pump / ui_lift_pump / ui_note_dock_pump / ui_trove_tabs_pump / ui_minimap_pump / ui_map_pump / ui_map_geom_pump / ui_map_center(屏幕几何,与输入方式无关)、ui_boss_pct_pump、ui_npcdlg_pump、
|
||||
// ui_widestash_pump、mv_audit_pump、ui_pages_pump(含手柄 L / R 翻页)、ui_watch_pump、ui_panel_heal、ui_panel_state_pump、rs_pump(一键重开,在前端泵里调)
|
||||
// Per-frame pumps fall into two classes by mode (the long line in dm_ui_mouse_pump below; tests/mode_scan.py checks that every pump on that line either has if (tm) or is on this "runs in both modes" list; a new pump in neither fails).
|
||||
// Touch only (with if (tm)): requests all come from touch gestures: tap world / mercenary portrait, long-press pickup, double-tap use, tap-to-buy, drag and drop, tap skill binding, off-hand set tab, open mercenary page.
|
||||
// Not run in controller mode or while a mode switch is in progress; in-flight requests are voided by the switch cleanup (dm_ui_cache_mode_leave).
|
||||
// Both modes: ui_target_pump (identify target, including controller hold A), ui_item_pump (hit query, the host asks too), ui_ptr_pump (pointer events, host-synthesized clicks go through it too),
|
||||
// ui_safe_pump / ui_lift_pump / ui_trove_tabs_pump / ui_minimap_pump / ui_map_pump / ui_map_geom_pump / ui_map_center (screen geometry, independent of input method), ui_boss_pct_pump, ui_npcdlg_pump,
|
||||
// ui_widestash_pump, mv_audit_pump, ui_pages_pump (including controller L / R paging), ui_watch_pump, ui_panel_heal, ui_panel_state_pump, rs_pump (Quick Restart, called from the front-end pump)
|
||||
// 物品说明框停靠(观测门 OBS_TOOLTIP,挂在说明框面板的「提交一条说明」函数入口 main+0xb0d560(面板, 文字, 目标矩形左上 x2, 目标矩形宽高 x3, 样式, 文字 2))。
|
||||
// 说明框是即时式的:悬停着的控件每帧重新提交、画完就清,宿主在自己的时机读面板里的记录数一直是 0,所以只能在提交那一刻改输入。
|
||||
// 原版把框摆在目标矩形(被点的那一格)正下 / 正上方:长说明(暗金、符文之语,十几行)盖住腰带、戒指、背包中间几列和「存放」钮,要点被盖住的格子得先点别处。
|
||||
// 触屏、只开着物品栏一个面板、光标下是物品时:把目标矩形换成对侧那块暗格空板(物品栏外框里、中间区域左右各一块)顶上的一个点——
|
||||
// 物品在面板右半停左空板、在左半停右空板,框从上往下排;量字、摆放、推回屏内仍是游戏自己做(离屏幕边的距离走布局里的 screenEdgePadding)。
|
||||
// 空板位置按屏高定(面板按屏高缩放):空板中线离屏幕中线 0.617 × 屏高、顶边 0.117 × 屏高(iPhone 15 Pro 档 2556×1179 截图量:
|
||||
// 667 点宽视图里空板 108–180 / 487–558、屏高 307;拿 16:9 截图验算中线 102 落在那张图的空板 60–145 里)。
|
||||
// 原先按「屏幕边到面板内框的带子正中」算,只在 16:9 碰巧落在空板里,2.17:1 的 iPhone 上落到面板外框外、贴着屏幕边(iPhone 15 Pro 视频)。
|
||||
// 其余一律原样放行:手柄 / 键鼠模式;并排两个面板的页(储藏箱 / 商人 / 魔盒 / 单件槽 / 佣兵页——没有空带);技能、属性、按钮的说明(光标下不是物品);世界里的名牌。
|
||||
// 只许游戏主线程(门回调就在)。
|
||||
// 测试开关 DM_TEST_TIPDOCK=1:不看模式(Mac 宿主是手柄版,用它看效果);=0:整个关掉
|
||||
// The per-frame pumps fall into two classes by mode (the long line in dm_ui_mouse_pump below; tests/mode_scan.py checks that every pump on that line either has if (tm) or is on this "runs in both modes" list; a newly added pump that is in neither is red).
|
||||
// Touch only (with if (tm)): requests all come from touch gestures: tapping the world / mercenary portrait, long-press to pick up, double-tap to use, tap to buy, drag and drop, tapping to bind a skill, the off-hand set tab, opening the mercenary page.
|
||||
// Not run in gamepad mode or while a switch transaction is in progress; requests in flight are cancelled by the switch cleanup (dm_ui_cache_mode_leave).
|
||||
// Run in both modes: ui_target_pump (identify target, including holding A on the gamepad), ui_item_pump (hit queries, the host asks too), ui_ptr_pump (pointer events, host-synthesized clicks go through it as well),
|
||||
// ui_safe_pump / ui_lift_pump / ui_note_dock_pump / ui_trove_tabs_pump / ui_minimap_pump / ui_map_pump / ui_map_geom_pump / ui_map_center (screen geometry, independent of input method), ui_boss_pct_pump, ui_npcdlg_pump,
|
||||
// ui_widestash_pump, mv_audit_pump, ui_pages_pump (including L / R page turning on the gamepad), ui_watch_pump, ui_panel_heal, ui_panel_state_pump, rs_pump (one-tap restart, called from the front end pump)
|
||||
// Item description box docking (observation gate OBS_TOOLTIP, on the entry of the description panel's "submit one description" function main+0xb0d560(panel, text, target rect top-left x2, target rect size x3, style, text 2)).
|
||||
// The description box is immediate-mode: the hovered widget resubmits it every frame and it is cleared after drawing, so when the host reads the panel at its own time the record count is always 0; the input can only be changed at the moment of submission.
|
||||
// The original places the box directly below / above the target rect (the slot that was tapped): long descriptions (uniques, runewords, a dozen lines) cover the belt, rings, the middle columns of the inventory and the Stash button, and you have to tap elsewhere before you can tap a covered slot.
|
||||
// On touch, with only the inventory panel open and an item under the cursor: replace the target rect with a point at the top of the dark empty side panel on the opposite side (inside the inventory frame, one on each side of the middle area):
|
||||
// an item in the right half of the panel docks on the left panel and vice versa, and the box is laid out downward; measuring the text, placing it and pushing it back on screen are still done by the game (the distance from the screen edge uses screenEdgePadding from the layout).
|
||||
// The side panels are positioned by screen height (the panel scales with screen height): panel center line 0.617 x screen height from the screen center line, top edge 0.117 x screen height (measured on an iPhone 15 Pro 2556x1179 screenshot:
|
||||
// in a 667-point-wide view the panels span 108–180 / 487–558 with screen height 307; cross-checked on a 16:9 screenshot, center line 102 falls inside that image's panel at 60–145).
|
||||
// This used to be computed as "the middle of the band between the screen edge and the panel's inner frame", which only happened to land in the side panel on 16:9; on 2.17:1 iPhones it landed outside the panel frame against the screen edge (iPhone 15 Pro video).
|
||||
// Everything else passes through unchanged: gamepad / keyboard and mouse mode; pages with two panels side by side (stash / vendor / Horadric Cube / single-item slot / mercenary page, which have no empty band); descriptions of skills, attributes and buttons (no item under the cursor); name plates in the world.
|
||||
// Game main thread only (the gate callback runs there).
|
||||
// Test switch DM_TEST_TIPDOCK=1: ignore the mode (the Mac host is the gamepad version; use it to see the effect); =0: turn it off entirely
|
||||
static int ui_touch_mode(void);
|
||||
void dm_ui_tooltip_obs(const uint64_t *regs) {
|
||||
static int force = -2; if (force == -2) { const char *e = getenv("DM_TEST_TIPDOCK"); force = e ? atoi(e) : -1; }
|
||||
if (force == 0 || (force < 0 && !ui_touch_mode())) return;
|
||||
module_t *m = main_module(); uint64_t root = 0; if (!m) return; memcpy(&root, m->base + 0x2f05458, 8); if (!root) return;
|
||||
if (atomic_load(&g_pstate) & (DM_PS_BANK | DM_PS_VENDOR | DM_PS_IMBUE | DM_PS_CUBE | DM_PS_VAULT | DM_PS_DEAD)) return;
|
||||
if (!ui_panel(root, "PlayerInventoryExpansionLayout") || ui_panel(root, "HirelingInventoryPanel")) return;
|
||||
dm_cursor_item_info ci; if (!dm_cursor_item(&ci)) return;
|
||||
int W = *(int32_t *)(m->base + 0x211da38), H = *(int32_t *)(m->base + 0x211da3c); if (W <= 0 || H <= 0) return;
|
||||
int tx = (int32_t)regs[2], tw = (int32_t)regs[3], off = (int)lroundf(0.617f * H); if (W / 2 - off < H / 10) return; // 空板贴到屏幕边(比 16:9 还窄的屏)就不挪 | If the side panel would touch the screen edge (screens narrower than 16:9), do not move the box
|
||||
int left = tx + tw / 2 >= W / 2, cx = left ? W / 2 - off : W / 2 + off, y = (int)(0.117f * H);
|
||||
uint64_t *r = (uint64_t *)(uintptr_t)regs; // 门只回写 x0–x8:改 x2 / x3 | the gate writes back only x0-x8: change x2 / x3
|
||||
r[2] = (uint64_t)(uint32_t)cx | (uint64_t)(uint32_t)y << 32; r[3] = 0;
|
||||
static int lg; static int ll = -1; if (ll != left && lg < 40) { ll = left; lg++; LOG("说明框停靠:物品 %s 在面板%s半 → 说明框停到%s侧空板(中线 x %d,顶 y %d;画面 %dx%d)", ci.code, left ? "右" : "左", left ? "左" : "右", cx, y, W, H); }
|
||||
}
|
||||
static int ui_touch_mode(void) { int dm_padmode_current(void), dm_padmode_busy(void); return !dm_padmode_current() && !dm_padmode_busy(); }
|
||||
// Mac App:界面是手柄版(上面答「不是触屏模式」),但真鼠标走的是触屏那套物品手势(touch_mac.c 把鼠标事件喂给触屏状态机)。
|
||||
// 只把物品手势的四个执行泵(长按 / 双击使用 / 买 / 拖放)在真鼠标模式下补跑一遍;绑定框、技能页签对调、佣兵页这些改触屏布局的泵不跑。没有请求时这四个什么都不做,手柄玩家不受影响
|
||||
@@ -2489,7 +2668,7 @@ void dm_ui_mouse_pump(void) { // 游戏取手柄处调(hle_hid fill,主线
|
||||
else fix = 0; }
|
||||
if (th) { ui_auto_key(th); tnext = fr + 8; } } } }
|
||||
{ module_t *pm = main_module(); uint64_t proot = 0; if (pm) { memcpy(&proot, pm->base + 0x2f05458, 8); int32_t pw = *(int32_t *)(pm->base + 0x211da38), phh = *(int32_t *)(pm->base + 0x211da3c);
|
||||
static uint64_t pf = UINT64_MAX; if (proot && pw > 0 && phh > 0 && pf != fr) { pf = fr; { static int dd; const char *dn; if (!dd && (dn = getenv("DM_UI_DUMP")) && atomic_load(&g_taps_base) && fr >= atomic_load(&g_taps_base) + (getenv("DM_UI_DUMP_AT") ? atoi(getenv("DM_UI_DUMP_AT")) : 45)) { dd = 1; ui_dump(proot, 0, dn, 0, pm); } } int tm = ui_touch_mode(); if (tm) ui_wtap_pump(pm, proot, pw, phh); if (tm) ui_long_pump(); ui_target_pump(pm, fr); if (tm) ui_use_pump(); if (tm) ui_buy_pump(pw, phh); ui_item_pump(proot, pw, phh); ui_ptr_pump(pm, proot, pw, phh); if (tm) ui_drag_pump(pm, proot, pw, phh); UI_MOUSE_ITEM_PUMPS(pm, proot, pw, phh); { int lu = atomic_load(&g_load_up); dm_uiscreen_set_ingame(ui_panel(proot, "HUDPanel") && !(lu < 0 ? ui_find(proot, "LoadScreenPanel", 0) != 0 : lu)); } ui_safe_pump(pm, proot, fr); ui_lift_pump(proot, fr); ui_trove_tabs_pump(pm, proot, fr); ui_minimap_pump(pm, proot, pw, phh, fr); ui_map_pump(pm); ui_map_geom_pump(pm, proot); ui_boss_pct_pump(pm, proot); ui_npcdlg_pump(proot); ui_map_center(pm, proot, *(volatile int32_t *)(pm->base + 0x2d5c748)); if (tm) ui_bind_pump(proot, fr); if (tm) swaptab_pump(proot); if (tm) ui_mercpg_pump(pm, proot, fr); ui_widestash_pump(proot); mv_audit_pump(proot, fr); ui_pages_pump(pm, proot); } } }
|
||||
static uint64_t pf = UINT64_MAX; if (proot && pw > 0 && phh > 0 && pf != fr) { pf = fr; { static int dd; const char *dn; if (!dd && (dn = getenv("DM_UI_DUMP")) && atomic_load(&g_taps_base) && fr >= atomic_load(&g_taps_base) + (getenv("DM_UI_DUMP_AT") ? atoi(getenv("DM_UI_DUMP_AT")) : 45)) { dd = 1; ui_dump(proot, 0, dn, 0, pm); } } int tm = ui_touch_mode(); if (tm) ui_wtap_pump(pm, proot, pw, phh); if (tm) ui_long_pump(); ui_target_pump(pm, fr); if (tm) ui_use_pump(); if (tm) ui_buy_pump(pw, phh); ui_item_pump(proot, pw, phh); ui_ptr_pump(pm, proot, pw, phh); if (tm) ui_drag_pump(pm, proot, pw, phh); UI_MOUSE_ITEM_PUMPS(pm, proot, pw, phh); { int lu = atomic_load(&g_load_up); dm_uiscreen_set_ingame(ui_panel(proot, "HUDPanel") && !(lu < 0 ? ui_find(proot, "LoadScreenPanel", 0) != 0 : lu)); } ui_safe_pump(pm, proot, fr); ui_lift_pump(proot, fr); ui_note_dock_pump(proot); ui_trove_tabs_pump(pm, proot, fr); ui_minimap_pump(pm, proot, pw, phh, fr); ui_map_pump(pm); ui_map_geom_pump(pm, proot); ui_boss_pct_pump(pm, proot); ui_npcdlg_pump(proot); ui_map_center(pm, proot, *(volatile int32_t *)(pm->base + 0x2d5c748)); if (tm) ui_bind_pump(proot, fr); if (tm) swaptab_pump(proot); if (tm) ui_mercpg_pump(pm, proot, fr); ui_widestash_pump(proot); mv_audit_pump(proot, fr); ui_pages_pump(pm, proot); } } }
|
||||
if (atomic_load(&g_fe_name_open) && atomic_load(&g_ut_phase) == 2) { // 起名页:点输入框(底板 / 文本框)= 重新弹系统键盘,不发鼠标点击 | naming page: tapping the input box (backplate / text box) = pop up the system keyboard again, no mouse click is sent
|
||||
module_t *nm = main_module(); uint64_t nroot = 0; if (nm) memcpy(&nroot, nm->base + 0x2f05458, 8); uint64_t pn = nroot ? ui_find(nroot, "CharacterCreateNamePanel", 0) : 0;
|
||||
if (pn && nm) { int32_t w = *(int32_t *)(nm->base + 0x211da38), h = *(int32_t *)(nm->base + 0x211da3c); uint64_t v = atomic_load(&g_ut_xy);
|
||||
@@ -2646,6 +2825,10 @@ void dm_ui_on_uimsg(const char *cat, const char *act, const char *arg) {
|
||||
if (!strcmp(cat, "PanelManager") && arg && !strcmp(arg, "LoadScreenPanel") && (!strcmp(act, "OpenPanel") || !strcmp(act, "UnloadPanel"))) { int up = act[0] == 'O'; atomic_store(&g_load_up, up);
|
||||
module_t *pm = main_module(); uint64_t root = 0; if (pm) memcpy(&root, pm->base + 0x2f05458, 8);
|
||||
if (root) { dm_uiscreen_set_ingame(!up && ui_find(root, "HUDPanel", 0)); g_lift_next = 0; ui_lift_pump(root, 0); } }
|
||||
{ int ex = (!strcmp(cat, "PausePanelMessage") && !strcmp(act, "ExitGame")) || (!strcmp(cat, "FrontEndNavigation") && !strcmp(act, "ToFrontEnd")),
|
||||
ld = !strcmp(cat, "PanelManager") && arg && !strcmp(arg, "LoadScreenPanel") && !strcmp(act, "OpenPanel");
|
||||
if (ex || ld) { module_t *pm = main_module(); uint64_t root = 0; if (pm) memcpy(&root, pm->base + 0x2f05458, 8); if (ex) g_nd_hold = 1; // 提示框停靠:停靠条件结束,当场写回原值 | notice docking: the docking condition ended, write the original value back on the spot
|
||||
note_dock_restore(root, ex ? (act[0] == 'E' ? "保存并退出" : "回到前端") : "读取画面(切场景)"); } }
|
||||
if (!strcmp(cat, "QuestLogPanelMessage") && !strcmp(act, "DialogueFinished")) atomic_store(&g_speech_end, dm_guest_frame());
|
||||
if (!strcmp(cat, "PanelManager")) ui_panel_note(act, arg ? arg : "");
|
||||
if (!strcmp(cat, "ChroniclePanelMessage") && !strcmp(act, "ToggleChildPanel") && arg && arg[0]) { int c = 0; while (c < 8 && g_chr_child[c][0] && strcmp(g_chr_child[c], arg)) c++; if (c < 8 && !g_chr_child[c][0]) strlcpy(g_chr_child[c], arg, sizeof g_chr_child[c]); }
|
||||
|
||||
+2
-2
@@ -61,11 +61,11 @@ static void grant(uint8_t *mb, uint64_t unit, int srv) { // 这个单位的技
|
||||
uint64_t nd = ((uint64_t (*)(uint64_t, int))(mb + 0x7bf010))(unit, sk); static int lg; if (lg++ < 8) LOG("免费回城:%s玩家技能链挂上回城技能 %d → %s", srv ? "服务端" : "客户端", sk, nd ? "成" : "【红】失败");
|
||||
}
|
||||
// ZR 这一格现在是不是空的:面 → 格表 main+0x2d13cbc(6 × {逻辑键, 普通格, 替代格},ZR 的逻辑键 0x800)、格 → 技能表 main+0x2d5f0c0(每格 28 字节,首 4 字节技能号;武器第二组在 +16 格),
|
||||
// 读法同前端的技能格快照(dm/ios/Sources/dm_touch_game_bridge.c)。[0] = 没按 ZL 时 ZR 用的那格,[1] = 按着 ZL 时的那格
|
||||
// 读法同前端的技能格快照(dm/touch/dm_touch_game_bridge.c)。[0] = 没按 ZL 时 ZR 用的那格,[1] = 按着 ZL 时的那格
|
||||
// Whether the ZR slot is empty right now: face button -> slot table main+0x2d13cbc (6 x {logical key, normal slot, alternate slot}, the logical key
|
||||
// of ZR is 0x800), slot -> skill table main+0x2d5f0c0 (28 bytes per slot, the first 4 bytes are the skill number; the second weapon set is at
|
||||
// +16 slots),
|
||||
// read the same way as the front end's skill slot snapshot (dm/ios/Sources/dm_touch_game_bridge.c). [0] = the slot ZR uses when ZL is not held,
|
||||
// read the same way as the front end's skill slot snapshot (dm/touch/dm_touch_game_bridge.c). [0] = the slot ZR uses when ZL is not held,
|
||||
// [1] = the slot used while ZL is held
|
||||
static _Atomic int g_zr_free[2];
|
||||
int dm_freetp_zr_free(int zl) { return atomic_load(&g_zr_free[zl != 0]); }
|
||||
|
||||
+21
-1
@@ -137,6 +137,11 @@ static const struct { const char *k, *zh, *en; } k_dm_i18n[] = {
|
||||
{ "dmDlProgress", "正在下载游戏资源\n%.2f / %.2f GB(%.0f%%) %.1f MB/s", "Downloading game resources\n%.2f / %.2f GB (%.0f%%) %.1f MB/s" },
|
||||
{ "dmDlPaused", "下载已暂停(检查网络),恢复后自动继续", "Download paused (check your network). It resumes automatically." },
|
||||
{ "dmDlPackWait", "系统还在准备资源包,完成后自动继续", "The system is still preparing the resource pack. It continues automatically." },
|
||||
{ "dmDlInstalling", "下载完成,系统正在安装资源包\n可能要几分钟,请保持本 App 在前台\n资源包 %.2f GB,本机可用 %.2f GB", "Download complete. The system is installing the resource pack.\nThis can take a few minutes. Keep this app open.\nPack %.2f GB, %.2f GB free on this device" },
|
||||
{ "dmDlInstallSpace", "下载完成,但本机空间不够系统安装资源包\n资源包 %.2f GB,%@ 现在可用 %.2f GB,至少还差 %.2f GB\n请在「设置 → 通用 → %@ 储存空间」清理,清理后自动继续", "Download complete, but there is not enough space to install the resource pack.\nPack %.2f GB; this %@ has %.2f GB free, at least %.2f GB more needed.\nFree up space in Settings → General → %@ Storage. It continues automatically." },
|
||||
{ "dmDlPackSlow", "系统安装资源包已超过 %d 分钟还没完成\n可以继续等,也可以点「改用直接下载」从下载站下载资源(断点续传)", "The system has been installing the resource pack for over %d minutes.\nYou can keep waiting, or tap \"Download Directly\" to get the resources from our download site (resumable)." },
|
||||
{ "dmDlPackSlowNoDl", "系统安装资源包已超过 %d 分钟还没完成\n可以继续等;也可以点「分享诊断日志」把日志发给我们", "The system has been installing the resource pack for over %d minutes.\nYou can keep waiting, or tap \"Share Diagnostics\" to send us the log." },
|
||||
{ "dmDlUseDirect", "改用直接下载", "Download Directly" },
|
||||
{ "dmDlNotReady", "游戏资源还不能用\n%@\n处理后点重试", "Game resources are not ready\n%@\nFix this, then tap Retry" },
|
||||
{ "dmDlWill", "将下载游戏资源:还要下 %@(共 %.1f GB)", "Downloading game resources: %@ remaining (%.1f GB total)" },
|
||||
{ "dmDlNotStarted", "%@游戏资源下载没开始:%@\n%@\n也可以从内测页手动下载资源包,放进「我的 iPhone → D2R Mobile」", "%@The resource download could not start: %@\n%@\nYou can also download the resource pack from the beta page and put it in \"On My iPhone → D2R Mobile\"" },
|
||||
@@ -160,6 +165,12 @@ static const struct { const char *k, *zh, *en; } k_dm_i18n[] = {
|
||||
{ "dmOldDl", "直接下载", "Download" },
|
||||
{ "dmOldCopied", "已经拷好了", "Already Copied" },
|
||||
{ "dmOldQuit", "退出", "Quit" },
|
||||
{ "dmPackBadTitle", "这个安装包还不能玩", "This Package Is Not Ready" },
|
||||
{ "dmPackBadMiss", "安装包里缺游戏内容(缺 %d 项,如 %@)。", "The package is missing game content (%d items, e.g. %@)." },
|
||||
{ "dmPackBadProd", "安装包是用不同版本拼成的(壳是 %@,做进去的内容是 %@)。", "The package mixes versions (shell %@, built-in content %@)." },
|
||||
{ "dmPackBadHow", "发布页上的壳是做安装包的原料,不能直接装来玩。\n\n怎么做:在电脑上打开 github.com/jhaizhou-ops/d2r-mobile,照 docs/NO_XCODE 的第一步用 d2rm_pack.py 把你的游戏内容做进同一版本的壳,再装它输出的那个安装包。", "The shell on the releases page is build input, not an app to install.\n\nWhat to do: on a computer, open github.com/jhaizhou-ops/d2r-mobile and follow step 1 of docs/NO_XCODE — run d2rm_pack.py to build your game content into the shell of the same release, then install the package it outputs." },
|
||||
{ "dmGpuOldTitle", "这台设备玩不了", "This Device Is Not Supported" },
|
||||
{ "dmGpuOldMsg", "这台设备的图形芯片不支持 Metal 3,本游戏的图形层需要它。\n\n需要 A14 / M1 及以后的芯片(iPhone 12 及以后、2021 年及以后的 iPad Pro 等);A13 及更早的芯片(包括 2020 年的 iPad Pro)玩不了。", "This device's graphics chip does not support Metal 3, which the game's graphics layer needs.\n\nAn A14 / M1 chip or later is required (iPhone 12 and later, iPad Pro from 2021 and later, and so on); A13 and earlier chips, including the 2020 iPad Pro, cannot run it." },
|
||||
{ "dmOldConnecting", "正在连接下载服务器…", "Connecting to the download server…" },
|
||||
{ "dmOldDlFail", "下载失败:%s", "Download failed: %s" },
|
||||
{ "dmOldProgress", "正在下载老机型补充包\n%.2f / %.2f GB(%.0f%%)%@", "Downloading the supplementary pack\n%.2f / %.2f GB (%.0f%%)%@" },
|
||||
@@ -206,7 +217,11 @@ static const struct { const char *k, *zh, *en; } k_dm_i18n[] = {
|
||||
{ "dmRiftSayStart", "第 %d 层开始,限时 15 分钟", "Level %d: 15 minute time limit" },
|
||||
{ "dmRiftSayGift", "赠彩虹刻面一颗,已掉在脚下", "A Rainbow Facet has dropped" },
|
||||
{ "dmRiftSayTimeout", "时间到:本层未过关,守护者仍会掉落", "Time's up: level not cleared" },
|
||||
{ "dmRiftSayFoes", "本场有 %d 位强敌", "%d powerful foes this run" },
|
||||
{ "dmRiftSayInvader", "强敌逼近!", "A powerful foe approaches!" },
|
||||
{ "dmRiftSayInvaderGone", "闯入者退去了", "The intruder withdraws" },
|
||||
{ "dmRiftSayGuardians", "进度已满:两位守护者现身!", "Two Rift Guardians appear!" },
|
||||
{ "dmRiftSayWave", "守护者第 %d 波现身(共 %d 波)", "Guardian wave %d of %d" },
|
||||
{ "dmRiftSayGuardian", "进度已满:守护者现身!", "The Rift Guardian appears!" },
|
||||
{ "dmElyToaGround", "背包已满,赦免之证掉在脚边", "Inventory full: Token of Absolution dropped" },
|
||||
{ "dmMercSlotLocked", "通关地狱后打通秘境10层解锁", "Clear Greater Rift Level 10 to unlock" },
|
||||
@@ -253,7 +268,8 @@ static const struct { const char *k, *zh, *en; } k_dm_i18n[] = {
|
||||
{ "dmKbRiftFast", "最快 %d:%02d", "Best Time %d:%02d" },
|
||||
{ "dmKbRiftMsGot", "首通奖励已领取", "First clear reward claimed" },
|
||||
{ "dmKbRiftTotal", "最高 %d 层", "Best Level: %d" },
|
||||
{ "dmCloudConflict", "iCloud 共享仓库两边不一致,已保留本机,请联系我们", "iCloud shared stash mismatch: kept this device. Please contact us" },
|
||||
{ "dmCloudConflict", "iCloud:两台设备的共享仓库各有内容,已用云端那份,本机那份已完整保存待并回", "iCloud: both devices had shared stash contents. Using the cloud copy; this device's copy is kept to be merged back" },
|
||||
{ "dmCloudCharConflict", "iCloud:角色 %s 两台设备各有一份,已用云端那份,本机那份已备份", "iCloud: both devices had character %s. Using the cloud copy; this device's copy is backed up" },
|
||||
{ "dmRiftHudTitle", "秘境", "Rift" },
|
||||
{ "dmRiftHudDone", "第 %d 层完成", "Level %d complete" },
|
||||
{ "dmRiftHudLate", "第 %d 层超时", "Level %d overtime" },
|
||||
@@ -261,6 +277,10 @@ static const struct { const char *k, *zh, *en; } k_dm_i18n[] = {
|
||||
{ "dmRiftHudNext", "下次第 %d 层", "Next: Level %d" },
|
||||
{ "dmRiftHudTop", "已通关最高层", "Highest level cleared" },
|
||||
{ "dmRiftHudOver", "已超时:打完仍有掉落,不计通关", "Overtime: drops, no clear" },
|
||||
{ "dmRiftHudKillWave", "守护者 第 %d/%d 波(%d/%d)", "Guardians %d/%d (%d/%d)" },
|
||||
{ "dmRiftHudKillN", "击败守护者(%d/%d)", "Slay the Guardians (%d/%d)" },
|
||||
{ "dmRiftHudOverKill", "已超时:击败守护者仍有掉落", "Overtime: slay it for drops" },
|
||||
{ "dmRiftHudOverKillN", "已超时:击败守护者(%d/%d)仍有掉落", "Overtime: slay %d/%d for drops" },
|
||||
{ "dmRiftHudSame", "下次仍是这一层", "Next: same level" },
|
||||
{ "dmRiftHudKill", "击败守护者", "Slay the Rift Guardian" },
|
||||
{ "dmRiftHudGoal", "消灭秘境中的怪物 %d%%", "Slay the monsters %d%%" },
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
// 平台差异的最小公共面:信号上下文寄存器、宿主登记段。Darwin 与 Linux 各一份定义,其余差异见 compat/linux/compat_linux.h。
|
||||
// Minimal common surface of platform differences: signal-context registers and host registration sections. One definition each for Darwin and Linux;
|
||||
// other differences are in compat/linux/compat_linux.h.
|
||||
#pragma once
|
||||
#if defined(__APPLE__)
|
||||
#define UC_X(uc, i) ((uc)->uc_mcontext->__ss.__x[i])
|
||||
#define UC_PC(uc) ((uc)->uc_mcontext->__ss.__pc)
|
||||
#define UC_LR(uc) ((uc)->uc_mcontext->__ss.__lr)
|
||||
#define UC_FP(uc) ((uc)->uc_mcontext->__ss.__fp)
|
||||
#define UC_SP(uc) ((uc)->uc_mcontext->__ss.__sp)
|
||||
#define UC_ESR(uc) ((uint64_t)(uc)->uc_mcontext->__es.__esr)
|
||||
// 登记段:Mach-O 段名 "__DATA,<名>"
|
||||
// Registration section: Mach-O section name "__DATA,<name>"
|
||||
#define DM_SECT(name) section("__DATA," name)
|
||||
#else
|
||||
#define UC_X(uc, i) ((uc)->uc_mcontext.regs[i])
|
||||
#define UC_PC(uc) ((uc)->uc_mcontext.pc)
|
||||
#define UC_LR(uc) ((uc)->uc_mcontext.regs[30])
|
||||
#define UC_FP(uc) ((uc)->uc_mcontext.regs[29])
|
||||
#define UC_SP(uc) ((uc)->uc_mcontext.sp)
|
||||
#define UC_ESR(uc) dm_uc_esr(uc)
|
||||
// 登记段:ELF 段名须是 C 标识符,链接器才给 __start_<名> / __stop_<名>;retain 防 --gc-sections 丢弃
|
||||
// Registration section: the ELF section name must be a C identifier for the linker to provide __start_<name> / __stop_<name>; retain keeps --gc-sections from dropping it
|
||||
#define DM_SECT(name) section(name), retain
|
||||
#endif
|
||||
// 触摸产品(iOS 包、Android 包):设置缺省、掉落过滤规则、自动补增益这类「产品缺省开、Mac 宿主对拍时缺省关」的开关看它,不看 TARGET_OS_IPHONE。
|
||||
// 展开时才读 TARGET_OS_IPHONE,用处须已包含 TargetConditionals(Linux 由 compat_linux.h 定义)。
|
||||
// Touch product (iOS build, Android build): switches that are "on by default in the product, off by default for Mac host parity" (settings defaults, loot filter rules, auto-buff)
|
||||
// check this rather than TARGET_OS_IPHONE. TARGET_OS_IPHONE is read at expansion, so the use site must already include TargetConditionals (compat_linux.h defines it on Linux).
|
||||
#if defined(__ANDROID__)
|
||||
#define DM_TOUCH_PRODUCT 1
|
||||
#else
|
||||
#define DM_TOUCH_PRODUCT TARGET_OS_IPHONE
|
||||
#endif
|
||||
+315
-30
@@ -99,7 +99,11 @@ static void say(const char *key, ...) { char line[160], full[180]; va_list ap; v
|
||||
enum { ST_IDLE, ST_RUN, ST_DONE };
|
||||
static struct {
|
||||
_Atomic int st; int tier, maps[3], nmaps, cur; // 本次层数、串起来的图、正在第几张 | This rift's level, the chained maps, which map we are on
|
||||
_Atomic int gdead, gtotal; // 守护者:当前这一波已倒下几位 / 这一波刷出几位(顶部条用) | Guardians: how many of the current wave are down / how many this wave spawned (for the top bar)
|
||||
int nwave, wave, wcls[3][2], wn[3], whp[3], wdm[3]; uint32_t wave_t; // 守护者分几波(95 层起 2 波、100 层 3 波)、当前第几波(0 起)、各波的类号 / 人数 / 生命与伤害系数(×1000)、上一波全倒那一拍(0 = 不在两波之间) | how many Guardian waves (2 from level 95, 3 at level 100), the current wave (from 0), each wave's class ids / count / life and damage factors (x1000), the tick the previous wave was all down (0 = not between two waves)
|
||||
_Atomic int score, need; uint64_t t0_ns; _Atomic int timeout, guard_dead; // 分数(客户端加)、开局时刻(客体时钟)、超时、守护者已死 | Score (added by the client), start time (guest clock), timed out, guardian dead
|
||||
int su_order[43], su_next, su_cnt; uint32_t su_live[3], su_seen[3], su_near[3], su_last; // 特殊精英(75 层起):本场的出场次序(池洗过的牌)、下一位、已放几组;在场各组本体的单位 id、最后一次找到它的拍、最后一次离玩家 60 格以内的拍、上次放组的拍 | special elites (from level 75): this run's order of appearance (the shuffled pool), the next one, how many groups placed; for each group present, the body's unit id, the tick it was last found, the tick it was last within 60 tiles of the player; the tick of the last placement
|
||||
int inv_n, inv_cls[2], inv_pct[2], inv_st[2]; uint32_t inv_id[2], inv_t[2]; // 闯入首领(80 层起):本场几位、各自类号、在进度百分之几闯入、状态(0 未到 / 1 已预警 / 2 在场 / 3 已死 / 4 作罢)、单位 id、预警那一拍 | Invading bosses (from level 80): how many this run, their class ids, at what percentage of progress they invade, state (0 not yet / 1 warned / 2 present / 3 dead / 4 called off), unit id, the tick of the warning
|
||||
uint32_t guard, guards[3]; int guard_cls, gcls[3], nplan, inc; // 守护者:guards[] 各位的单位 id(guard = 第一位,非 0 即「已刷出」)、gcls[] 开局抽好的类号、nplan 本场几位;inc 成功涨了几层 | Guardians: guards[] unit id of each (guard = the first, non-zero meaning "spawned"), gcls[] class ids drawn at the start, nplan how many in this run; inc how many levels were gained on success
|
||||
int players_old; // 开局前的 /players 档 | The /players setting from before the start of the run
|
||||
char who[64]; // 角色名(层数侧文件) | Character name (level sidecar file)
|
||||
@@ -298,6 +302,10 @@ int dm_rift_hud(dm_rift_hud_t *o) {
|
||||
int el = K.t0_ns ? (int)((now - K.t0_ns) / 1000000000ull) : 0; int need = atomic_load(&K.need);
|
||||
o->tier = K.tier; o->progress = need > 0 ? (float)atomic_load(&K.score) / need : 0; if (o->progress > 1) o->progress = 1;
|
||||
o->secs_left = st == ST_DONE ? g_left_done : RIFT_SECS - el; o->done = st == ST_DONE; o->guardian = K.guard != 0 && !atomic_load(&K.guard_dead); o->inc = K.inc; o->next = next_tier(); o->overtime = rift_overtime();
|
||||
// 第二行写哪一句在这里定(一个来源):超时优先说明「已超时」,守护者在场就把「击败守护者」合进同一句;两位以上带(已倒 / 总数)
|
||||
// Which sentence the second line shows is decided here (one source): overtime takes priority with "Overtime", and when Guardians are present "Slay the Rift Guardian" is merged into the same sentence; with two or more it carries (fallen / total)
|
||||
o->gdead = atomic_load(&K.gdead); o->gtotal = atomic_load(&K.gtotal); o->wave = K.wave + 1 - (K.wave_t != 0); o->nwave = K.nwave;
|
||||
o->goal = o->overtime ? (o->guardian ? (o->gtotal >= 2 ? 5 : 4) : 3) : o->guardian ? (o->gtotal >= 2 ? 2 : 1) : 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -311,16 +319,67 @@ static uint32_t g_swept[1024]; int dm_rift_swept(uint32_t id) { return id && g_s
|
||||
static int hi_on(const char *seg, int from) { static int off = -1; if (off < 0) { const char *e = getenv("DM_RIFT_HI"); off = e && !strcmp(e, "0"); } if (off) return 0;
|
||||
const char *f = getenv("DM_RIFT_TEST_HI"); return (f && strstr(f, seg)) || K.tier >= from; }
|
||||
// 双守护者每位的生命系数 s、伤害系数 d(×1000):75 层 0.51 / 0.75,线性到 100 层 0.775 / 1.0;低于 75 层被测试开关强制时取 75 层的值。
|
||||
// s 的两端:75 层双守护者期望总量 = 74 层单守护者的 1.16 倍(不跳变;双守护者的池是四位,见 k_duo);100 层最大的单体(巴尔)正好不过属性上限。d 未用读数校过
|
||||
// s 的两端:75 层双守护者期望总量 = 74 层单守护者的 1.16 倍(不跳变;双守护者的池是四位,见 k_duo);100 层最大的单体(巴尔)正好不过属性上限。d 用替身读数校过一轮(设计稿第十五节:75 层六对的承伤每秒峰值最高是 74 层最重单体的 1.06 倍,各 1 局)
|
||||
// Life factor s and damage factor d of each of two Guardians (x1000): 0.51 / 0.75 at level 75, linear to 0.775 / 1.0 at level 100; below level 75 (forced by a test switch) the level-75 values are used.
|
||||
// The two ends of s: the expected total of two Guardians at level 75 = 1.16 times a single Guardian at level 74 (no jump; the dual pool has four bosses, see k_duo); at level 100 the largest single one (Baal) stays just within the stat limit. d has not been calibrated with readouts
|
||||
// The two ends of s: the expected total of two Guardians at level 75 = 1.16 times a single Guardian at level 74 (no jump; the dual pool has four bosses, see k_duo); at level 100 the largest single one (Baal) stays just within the stat limit. d has been calibrated once with stand-in readouts (for the six pairs at level 75 the highest per-second peak of damage taken is 1.06 times the heaviest single Guardian at level 74, one run each)
|
||||
static int hi_duo_x1000(int which) { int t = K.tier < 75 ? 75 : K.tier > 100 ? 100 : K.tier; return which ? 750 + 250 * (t - 75) / 25 : 510 + 265 * (t - 75) / 25; }
|
||||
// 多位首领同场的池不含安达利尔(156):她死后十几到四十拍,同场的另一位首领会跟着死——与巴尔、迪亚波罗各试过,3 + 1 局必现,那时另一位还剩大半生命、
|
||||
// 不是被伤害打死的;带不带任务事件门都一样;对照组(都瑞尔 + 迪亚波罗)没有这回事。看起来是她原版的死亡过程带的,没读到那段代码。单守护者(74 层及以下)仍是五位
|
||||
// The pool for several bosses in one fight does not include Andariel (156): ten-odd to forty ticks after she dies, the other boss in the same fight dies too - tried with Baal and with Diablo, reproduced in 3 + 1 runs, with the other one still at most of its life at that point,
|
||||
// not killed by damage; the same with or without the quest-event gate; the control pair (Duriel + Diablo) shows nothing of the kind. It appears to come with her original death sequence; that code has not been read. A single Guardian (level 74 and below) is still drawn from all five
|
||||
static const int k_duo[] = { 211, 242, 243, 544 };
|
||||
static int is_guard(uint32_t id) { return id && (id == K.guards[0] || id == K.guards[1] || id == K.guards[2]); }
|
||||
static int g_entry_lv, g_entry_x, g_entry_y; // 玩家进当前这张秘境图时的落点(退场找不到远处空地时的兜底去处:一定可达) | where the player entered the current rift map (the fallback destination when no distant open ground is found for leaving: always reachable)
|
||||
// ---- 特殊精英(75 层起;设计稿第二十四节):层数越高原生怪越少、特殊精英越多,90 层起随机生成的原生怪为 0。
|
||||
// 池:超级金怪表(66 行)里去掉带任务掉落 / 固定场地 / 脚本的 23 行(设计稿第二十三节;按原版常识圈的),剩 43 行,女伯爵(行 6)在内。掉落一律照原版。
|
||||
// 放法:不在开局定点,跟着玩家推进一组一组放——在场组数低于上限、玩家 40 格内敌对单位少于 SU_NEAR 只时,在玩家前方约 70 格的空地用原版函数
|
||||
// main+0x69b310(游戏, 房间, x, y, 行号, 0) 连随从一起刷一组(第六个参数含义没查到,取 0 的依据是探路与验收轮的局)。守护者现身后不再放新的。
|
||||
// 它们走现有的「客户端见到 → 认作敌对 → 按层改属性 → 计分(本体 15、随从 2)」流程;本体(怪物数据带超级独特标志的,含地图自带的)生命另乘 SU_HP_X,到软顶为止;
|
||||
// 我们刷的组里的随从生命另乘 SU_MINION_X1000 ÷ 1000。两个系数按「一场的生命和 ≈ 74 层一场 × 层倍率之比」校(设计稿第二十五节):池里高幕的行多、随从按原生等级起算偏肉。
|
||||
// 追击:在场的本体离玩家 80 格以外满 5 秒,挪到玩家前方约 70 格——不会被甩在卸载的房间里占着名额,玩家不动它们也会找上来。
|
||||
// 两个距离都按「屏幕外」取(推算:一格横向约 16 像素、纵向约 8 像素,1952×900 的画面半宽约 61 格、半高约 56 格;没用截图核),玩家看不到它消失、也看不到它出现
|
||||
// 本场有巴尔(守护者或闯入)时不抽随从 9 只的三行(24、36、38):巴尔自己召的触手已占同屏余量。
|
||||
// 总开关 DM_RIFT_HI=0;测试开关 DM_RIFT_TEST_HI=su(低层强开)、DM_RIFT_TEST_SUROWS=<行号>,…(指定出场次序)、DM_RIFT_TEST_NAT=<百分数>(指定原生怪比例)
|
||||
// ---- Special elites (from level 75; design draft section 24): the higher the level, the fewer native monsters and the more special elites; from level 90 randomly generated native monsters are 0.
|
||||
// Pool: the super unique table (66 rows) minus the 23 rows with quest drops / fixed locations / scripts (design draft section 23; picked by common knowledge of the original), leaving 43 rows, the Countess (row 6) included. Drops always follow the original.
|
||||
// Placement: not at fixed points at the start, but one group at a time as the player advances - when the number of groups present is below the limit and there are fewer than SU_NEAR hostile units within 40 tiles of the player, a group is spawned with its minions on open ground about 70 tiles ahead of the player with the original function
|
||||
// main+0x69b310(game, room, x, y, row, 0) (the meaning of the sixth argument was not found; 0 is used on the basis of the exploratory and acceptance runs). No new ones are placed after the Guardians appear.
|
||||
// They go through the existing "client sees it -> treated as hostile -> attributes scaled by level -> scored (body 15, minion 2)" flow; the body (monster data with the super unique flag, including ones placed by the map) has its life additionally multiplied by SU_HP_X, up to the soft cap;
|
||||
// minions in the groups we spawned have their life additionally multiplied by SU_MINION_X1000 / 1000. Both factors are calibrated so that "total life in one run ~= one level-74 run x ratio of level multipliers" (design draft section 25): the pool has many high-act rows, and minions starting from their native level are on the tanky side.
|
||||
// Pursuit: a body present more than 80 tiles from the player for 5 seconds is moved to about 70 tiles ahead of the player - it is not left behind in an unloaded room holding a slot, and comes to the player even if the player stays put.
|
||||
// Both distances are chosen to be "off screen" (estimate: one tile is about 16 pixels horizontally and about 8 vertically; a 1952x900 view is about 61 tiles half-wide and about 56 tiles half-high; not checked with screenshots), so the player sees it neither disappear nor appear
|
||||
// When this run has Baal (as Guardian or invader), the three rows with 9 minions (24, 36, 38) are not drawn: the tentacles Baal summons himself already use up the on-screen headroom.
|
||||
// Master switch DM_RIFT_HI=0; test switches DM_RIFT_TEST_HI=su (force on at low levels), DM_RIFT_TEST_SUROWS=<row>,... (set the order of appearance), DM_RIFT_TEST_NAT=<percent> (set the native monster share)
|
||||
#define SU_NEAR 12
|
||||
#define SU_HP_X 3
|
||||
#define SU_MINION_X1000 800 // 特殊精英的随从生命另乘 0.8 | special elite minions' life additionally x0.8
|
||||
static uint32_t g_su_min[64]; static unsigned g_su_min_w; // 我们刷的特殊精英组里的随从(单位 id):刷出当拍在本体 15 格内找新单位记下 | minions in the special elite groups we spawned (unit ids): on the tick of spawning, new units within 15 tiles of the body are recorded
|
||||
static int su_minion(uint32_t id) { for (int i = 0; i < 64; i++) if (id && g_su_min[i] == id) return 1; return 0; }
|
||||
#define SU_HP_SOFT 225000 // 本体生命乘 SU_HP_X 的软顶:× 本层总倍率,90 层约 100 万点(读数:不设顶时攻城兽那一行 383 万) | soft cap for multiplying body life by SU_HP_X: x this level's total multiplier, about 1 million points at level 90 (reading: without a cap the siege beast row reached 3.83 million)
|
||||
static int su_nat_pct(int tier) { return tier >= 90 ? 0 : tier >= 85 ? 30 : tier >= 80 ? 55 : tier >= 75 ? 80 : 100; } // 原生怪(密度与精英组数)留几成 | what share of native monsters (density and elite pack count) is kept
|
||||
static int su_quota(int tier) { return tier >= 90 ? 1 << 30 : tier >= 85 ? 7 : tier >= 80 ? 5 : tier >= 75 ? 2 : 0; } // 一场最多放几组(90 层起放到守护者现身为止) | at most this many groups placed in one run (from level 90, placed until the Guardians appear)
|
||||
static int su_cap(int tier) { return tier >= 90 ? 3 : 2; } // 同时在场最多几组 | at most this many groups present at the same time
|
||||
// 刷一位超级金怪(连随从)。原版 main+0x69b310 对「表里 +0x21 字节为 0 的行」查本局已出现位图(游戏 +0x5668,第 行号 位):出现过就返回 0、不刷——
|
||||
// 同一局里一位超级金怪只出一次(地图上自带的那位,例如图 111 的 Eldritch = 行 49,也算)。秘境同一局连开多场、池放完一轮从头,都会撞上它。
|
||||
// 做法:刷之前把这一位清掉、刷完写回原值——原版地图自带的那位该不该出现照旧,我们刷的不受这条限制
|
||||
// Spawn one super unique (with minions). The original main+0x69b310, for "rows whose byte +0x21 in the table is 0", checks this game's has-appeared bitmap (game +0x5668, bit <row>): if it has appeared, it returns 0 and spawns nothing -
|
||||
// in one game a super unique appears only once (the one placed by the map itself also counts, e.g. Eldritch on map 111 = row 49). Several rifts in a row in one game, and the pool starting again after a full round, both run into this.
|
||||
// Approach: clear this one's bit before spawning and write the original value back afterwards - whether the one the original map places should appear stays as before, and the ones we spawn are not limited by this
|
||||
static uint64_t su_spawn(uint64_t G, uint64_t room, int x, int y, int row) {
|
||||
uint8_t *bm = (uint8_t *)(uintptr_t)(G + 0x5668 + (row >> 3)), bit = (uint8_t)(1u << (row & 7)), old = *bm & bit; *bm &= (uint8_t)~bit;
|
||||
uint64_t u = ((uint64_t (*)(uint64_t, uint64_t, int, int, int, int))(B + 0x69b310))(G, room, x, y, row, 0);
|
||||
uint8_t mid = *bm & bit; *bm = (uint8_t)((*bm & ~bit) | old); static int n; if (n++ < 3) LOG("秘境:刷超级金怪 行 %d:本局已出现位 刷前 %d、刷完原版置成 %d、写回 %d", row, old != 0, mid != 0, (*bm & bit) != 0); return u; }
|
||||
static int g_near_now; // 玩家 40 格内的敌对单位数(hs_tick 每秒数一次) | number of hostile units within 40 tiles of the player (counted once a second by hs_tick)
|
||||
static const uint8_t k_su_pool[] = { 0, 1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 19, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 40, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59 };
|
||||
static uint32_t g_inv_gone[2]; static int g_inv_gone_xy[2][2];
|
||||
static uint32_t g_suseq_id; // 测试开关 DM_RIFT_TEST_SUSEQ 当前在场的那位(任务事件的门见到它死要记一行) // 已退场的闯入首领:单位 id(等它所在的房间被游戏卸载后,把它那条存档记录改成不还原;见 inv_gone_pump)与退场落点 | the one currently present for test switch DM_RIFT_TEST_SUSEQ (the quest-event gate records a line when it sees it die) // an invading boss that has left: its unit id (once the game unloads the room it is in, its saved record is changed to do-not-restore; see inv_gone_pump) and where it was sent
|
||||
// 首领自己召出来的单位(现在只有巴尔的:触手 562–566、分身 570)。75 层以上它们不按层改属性、保持原版数值——它们是首领技能的一部分,不是秘境的怪;
|
||||
// 按层放大会让触手变成打不完的墙,并且随战斗时长在场上越积越多(实测巴尔在场 36 秒同屏多 26 只、141 秒多 44 只)。74 层及以下照旧(那条「逐位不变」的线不为此破例)。
|
||||
// 按类号认:单位上「召唤者是谁」的字段没读到;以后别的首领有召唤物要加进来
|
||||
// Units summoned by a boss itself (currently only Baal's: tentacles 562–566, clone 570). Above level 75 they are not scaled by level and keep the original values - they are part of the boss's skills, not monsters of the rift;
|
||||
// scaling them by level turns the tentacles into a wall that cannot be cleared, and they pile up on the field as the fight goes on (measured: 26 more on screen after Baal has been present for 36 seconds, 44 more after 141 seconds). Level 74 and below stay as they were (the "nothing changes" line is not broken for this).
|
||||
// Recognised by class id: the "who summoned it" field on the unit has not been read; summons of other bosses will have to be added later
|
||||
static int boss_summon(uint32_t cls) { return (cls >= 562 && cls <= 566) || cls == 570; }
|
||||
static int is_guard(uint32_t id) { return id && (id == K.guards[0] || id == K.guards[1] || id == K.guards[2] || id == K.inv_id[0] || id == K.inv_id[1] || id == g_inv_gone[0] || id == g_inv_gone[1]); } // 守护者与闯入首领:不按普通怪再改一遍属性、不按普通怪计分 | Guardians and invading bosses: not scaled again as ordinary monsters, not scored as ordinary monsters
|
||||
static int pts_of(uint8_t fl) { return fl & 0x02 ? 15 : fl & 0x08 ? 10 : fl & 0x04 ? 5 : fl & 0x10 ? 2 : 1; } // 怪物数据 +0x1a:超级独特 / 金怪 / 冠军 / 随从 / 普通(同 hle_target.c) | Monster data +0x1a: super unique / unique (gold) monster / champion / minion / normal (same as hle_target.c)
|
||||
// ---- 每场读数(75 层以上内容曲线的量具,docs 设计稿第 0 步):只记、不改任何玩法。结算时打一行:
|
||||
// 用时;击杀只数与这些怪的生命上限之和(按层改完之后的值,守护者另加);本场认作敌对并改过属性的怪的只数与生命和;
|
||||
@@ -348,7 +407,7 @@ static void hs_tick(uint64_t G, uint64_t player, uint32_t t, int lv) {
|
||||
int px, py, n = 0; if (!unit_xy(player, &px, &py)) return;
|
||||
for (int b = 0; b < 128; b++) for (uint64_t u = rd(G + 0x2230 + 1 * 0x400 + 8 * b); u; u = rd(u + 0x158)) { uint32_t m = *(uint32_t *)(uintptr_t)(u + 0xc); int x, y;
|
||||
if (m == 0 || m == 12 || unit_level(u) != lv || !unit_xy(u, &x, &y) || abs(x - px) > 40 || abs(y - py) > 40 || unit_align(u)) continue; n++; }
|
||||
HS.near_sum += n; HS.near_n++; if (n > HS.near_peak) HS.near_peak = n;
|
||||
HS.near_sum += n; HS.near_n++; if (n > HS.near_peak) HS.near_peak = n; g_near_now = n;
|
||||
}
|
||||
static void hs_report(int secs) {
|
||||
LOG("秘境:读数 第 %d 层 用时 %d 秒:击杀 %d 只、生命和 %lld 点(另守护者 %lld 点);改过属性的敌对怪 %d 只、生命和 %lld 点;承伤和 %lld 点、每秒峰值 %lld 点、死亡 %d 次;40 格内敌对单位 峰值 %d / 均值 %.1f(采样 %d 次)",
|
||||
@@ -452,13 +511,15 @@ static uint32_t monlvl(uint64_t G, int lvl, int grp) { uint64_t T = tables(G), a
|
||||
// for a unit with a percentage life bonus, writing the base up to the limit makes the total overflow to a negative number, which is read as 1 point (this is how minions fell back to 1). So headroom is left according to the current total / base.
|
||||
// base / full = the base entry and the total at this moment (raw fixed-point values); with no bonus (total not greater than base) or when the base entry cannot be read, it is the stat limit itself
|
||||
static long long hp_base_limit(int base, int full) { return base > 0 && full > base ? 0x7fffff00LL * base / full : 0x7fffff00LL; }
|
||||
static int g_hp_soft; // 额外系数的软顶(点数,按「本层总倍率 = 1」计;0 = 没有):特殊精英本体用,免得天生就肉的怪种(攻城兽)再乘 4 变成半个守护者 | soft cap of the extra factor (points, counted with "this level's total multiplier = 1"; 0 = none): used for special elite bodies, so that naturally tanky monster types (siege beasts) do not become half a Guardian after another x4
|
||||
static int g_hp_mul = 1000; // scale_monster 的生命额外系数(×1000):双守护者的 s 在截顶之前乘进去——先截顶再乘的话,规则值过上限的那位(巴尔)会被多砍一刀 | extra life factor of scale_monster (x1000): the dual-Guardian s is multiplied in before the clamp - clamping first and multiplying afterwards would cut the one whose rule value exceeds the limit (Baal) a second time
|
||||
static void scale_monster(uint64_t G, uint64_t u, int lt, int l9) { // lt = 本层的等级(守护者 + 3)、l9 = 起算层的等级 | lt = this level's level (Guardian + 3), l9 = the baseline level's level
|
||||
int l0 = gs(u, 12); if (l0 <= 0) return; if (lt > lvl_cap()) lt = lvl_cap(); if (l9 > lt) l9 = lt;
|
||||
int tx = tier_total_x1000(K.tier, 0), lb = l0 > l9 ? l0 : l9, le = l0 > lt ? l0 : lt; // lb:「起算层那只怪」的等级;le:写进单位的等级(不降级) | lb: the level of "that monster at the baseline level"; le: the level written into the unit (never lowered)
|
||||
if (le == l0 && lb == l0 && tx == 1000) return; // 9 层、原生等级已不低于目标:什么都不用改 | level 9 and the native level is already no lower than the target: nothing to change
|
||||
uint32_t h0 = monlvl(G, l0, 2), hb = monlvl(G, lb, 2), d0 = monlvl(G, l0, 3), db = monlvl(G, lb, 3), a0 = monlvl(G, l0, 0), a1 = monlvl(G, le, 0); if (!h0 || !d0 || !a0) return;
|
||||
long long want = (long long)gs(u, 7) * hb / h0 * tx / 1000 * g_hp_mul / 1000, hp = want, lim = hp_base_limit(gsb(u, 7), gs(u, 7)); if (hp > lim) hp = lim; // 定点 ×256;原版上限 2²³ 点,带百分比生命加成的怪按比例留余量(hp_base_limit) | fixed point x256; the original's limit is 2^23 points, and monsters with a percentage life bonus get proportional headroom (hp_base_limit)
|
||||
long long want = (long long)gs(u, 7) * hb / h0 * tx / 1000 * g_hp_mul / 1000; if (g_hp_soft > 0 && g_hp_mul > 1000) { long long w1 = want * 1000 / g_hp_mul, sf = (long long)g_hp_soft * 256 * tx / 1000; if (want > sf) want = w1 > sf ? w1 : sf; } /* 软顶:额外系数最多把它乘到软顶,本来就过软顶的不再乘 | soft cap: the extra factor raises it at most to the soft cap; one already above the soft cap is not multiplied further */
|
||||
long long hp = want, lim = hp_base_limit(gsb(u, 7), gs(u, 7)); if (hp > lim) hp = lim; // 定点 ×256;原版上限 2²³ 点,带百分比生命加成的怪按比例留余量(hp_base_limit) | fixed point x256; the original's limit is 2^23 points, and monsters with a percentage life bonus get proportional headroom (hp_base_limit)
|
||||
// 顶到上限不静默:这只怪(多半是守护者)的生命没按线涨足,只剩伤害在涨。每开一层记前 3 只
|
||||
// Hitting the cap is not silent: this monster (most likely the Guardian) did not get its full life according to the line, and only its damage keeps
|
||||
// growing. The first 3 are logged for each level opened
|
||||
@@ -831,10 +892,40 @@ static void merc_test(uint64_t G, uint64_t pl, uint32_t t) {
|
||||
static void rift_quest_obs(const uint64_t *regs) {
|
||||
static uint8_t stand_in[0x200]; uint64_t G = regs[0], mon = regs[1]; int st = atomic_load(&K.st);
|
||||
if ((st != ST_RUN && st != ST_DONE) || !G || G != L.G || !mon || !in_rift_map(any_level(mon))) return;
|
||||
static int n; if (n++ < 6) LOG("秘境:怪物类号 %u(单位 id %u)死在秘境图里,不走原版任务事件", *(uint32_t *)(uintptr_t)(mon + 4), *(uint32_t *)(uintptr_t)(mon + 8));
|
||||
static int n; if (n++ < 6 || (g_suseq_id && *(uint32_t *)(uintptr_t)(mon + 8) == g_suseq_id)) LOG("秘境:怪物类号 %u(单位 id %u)死在秘境图里,不走原版任务事件", *(uint32_t *)(uintptr_t)(mon + 4), *(uint32_t *)(uintptr_t)(mon + 8));
|
||||
((uint64_t *)(uintptr_t)regs)[1] = (uint64_t)(uintptr_t)stand_in;
|
||||
}
|
||||
// 90 层起秘境图里不放普通预设怪(90 层以上没有其它怪、全是特殊精英)。观测门 OBS_PRESET_SPAWN 挂在「放一条预设单位记录」main+0x7ce800(游戏, 房间, 记录) 的入口,
|
||||
// 它只由房间激活时的放预设单位 0x7ce930 调(8 处);我们自己刷守护者 / 闯入首领直接调 0x7ce630,刷特殊精英调 0x69b310,都不经过这里。
|
||||
// 记录 {+0 模式, +4 类号, +8 / +0x24 房内坐标, +0x18 地图 AI, +0x20 单位类型 1 怪 / 2 物件};怪的类号分三段(原版 0x6910d0):
|
||||
// 小于 monstats 行数(表 +0xf98)= 普通怪,再往上超级独特行数(表 +0x10b8)以内 = 超级独特,再往上 = monplace 放置码。
|
||||
// 拦的:会打人 / 刷怪的普通怪(投石车 497–500、观察员 516–519、邪恶小屋 528);放置码里的随机怪群、金怪群、冠军、营地、group25–100 等。
|
||||
// 留的:超级独特;门 / 墙 / 攻城塔 / 监狱门 / 陷阱 / 友军野蛮人(场景,拿掉会改通行);放置码 0 空、4 / 14–16 NPC、5 血鸦、29–31 尸体。
|
||||
// 拦法:x2 换成一份类号 −1 的副本,原版 0x6910d0 入口自己返回空(tbnz w2, #31),0x7ce630 / 0x7ce800 随之走各自的收尾,不碰任何状态;原记录不动。
|
||||
// From level 90, no ordinary preset monsters are placed in rift maps (above level 90 there are no other monsters, only special elites). Observation gate OBS_PRESET_SPAWN is hooked at the entry of "place one preset unit record" main+0x7ce800(game, room, record);
|
||||
// it is only called by the room-activation preset placement 0x7ce930 (8 call sites); our own Guardian / invading boss spawns call 0x7ce630 directly and special elite spawns call 0x69b310, neither goes through here.
|
||||
// Record {+0 mode, +4 class id, +8 / +0x24 in-room coordinates, +0x18 map AI, +0x20 unit type 1 monster / 2 object}; monster class ids fall into three ranges (original 0x6910d0):
|
||||
// below the monstats row count (table +0xf98) = ordinary monster, above that within the super unique row count (table +0x10b8) = super unique, above that = monplace placement code.
|
||||
// Blocked: ordinary monsters that attack or spawn monsters (catapults 497–500, watchers 516–519, evil hut 528); in the placement codes, random monster packs, unique packs, champions, camps, group25–100 etc.
|
||||
// Kept: super uniques; doors / walls / siege towers / prison doors / traps / friendly barbarians (scenery; removing them changes passability); placement codes 0 empty, 4 / 14–16 NPCs, 5 Blood Raven, 29–31 corpses.
|
||||
// How it is blocked: x2 is replaced by a copy with class id -1, the original 0x6910d0 entry returns null by itself (tbnz w2, #31), 0x7ce630 / 0x7ce800 then go through their own exits without touching any state; the original record is untouched.
|
||||
static void rift_preset_obs(const uint64_t *regs) {
|
||||
static uint8_t stand_in[0x40]; static int n_blk; uint64_t G = regs[0], room = regs[1], rec = regs[2]; int st = atomic_load(&K.st);
|
||||
if ((st != ST_RUN && st != ST_DONE) || !G || G != L.G || !room || !rec || *(int32_t *)(uintptr_t)(rec + 0x20) != 1 || !hi_on("pre", 90)) return;
|
||||
uint64_t ex = rd(room + 0x18), lv = ex ? rd(ex + 0x90) : 0; int lvno = lv ? *(int32_t *)(uintptr_t)(lv + 0x1f8) : 0; if (!in_rift_map(lvno)) return;
|
||||
uint64_t T = tables(G); if (!T) return; int N = *(int32_t *)(uintptr_t)(T + 0xf98), S = *(int32_t *)(uintptr_t)(T + 0x10b8), c = *(int32_t *)(uintptr_t)(rec + 4), blk;
|
||||
if (c < 0) return;
|
||||
if (c < N) blk = (c >= 497 && c <= 500) || (c >= 516 && c <= 519) || c == 528;
|
||||
else if (c < N + S) blk = 0;
|
||||
else { int p = c - N - S; blk = !(p == 0 || p == 4 || p == 5 || (p >= 14 && p <= 16) || (p >= 29 && p <= 31)); }
|
||||
if (!blk) return;
|
||||
memcpy(stand_in, (const void *)(uintptr_t)rec, 0x30); *(int32_t *)(stand_in + 4) = -1; *(uint64_t *)(stand_in + 0x18) = 0;
|
||||
((uint64_t *)(uintptr_t)regs)[2] = (uint64_t)(uintptr_t)stand_in;
|
||||
static int all = -1; if (all < 0) all = getenv("DM_RIFT_TEST_TOUR") != NULL;
|
||||
if (n_blk++ < 6 || n_blk % 100 == 0 || all) LOG("秘境:第 %d 层 关卡 %d 不放预设怪 类号 %d(%s %d;monstats %d 行、超级独特 %d 行;本进程累计 %d 条)", K.tier, lvno, c, c < N ? "普通" : "放置码", c < N ? c : c - N - S, N, S, n_blk);
|
||||
}
|
||||
static void rift_gates(void) { static int once; if (once) return; once = 1;
|
||||
if (gate_obs_present(OBS_PRESET_SPAWN)) gate_obs_set(OBS_PRESET_SPAWN, rift_preset_obs); else LOG("秘境:这个产物不带放预设单位的门(r44 起的 touch 产物才带),90 层起普通预设怪照原版放");
|
||||
if (gate_obs_present(OBS_QUEST_KILL)) gate_obs_set(OBS_QUEST_KILL, rift_quest_obs); else LOG("秘境:这个产物不带任务事件的门(r36 起的 touch 产物才带),秘境里的首领死亡会走原版任务");
|
||||
if (gate_obs_present(OBS_LEVEL_WARP)) gate_obs_set(OBS_LEVEL_WARP, rift_level_obs);
|
||||
else LOG("秘境:这个产物不带出口换目的地的门(只有 r36 起的 touch 产物带),走出口会先落到原版的下一关、再由每拍检测送进下一张图"); }
|
||||
@@ -877,6 +968,20 @@ static void region_set(uint64_t G, int mode) { // mode 0 写回原值、1 置
|
||||
for (int i = 0; i < K.nmaps; i++) { int lv = K.maps[i]; uint8_t *umin, *umax; int32_t *den = region_of(G, lv, &umin, &umax); if (!den) continue;
|
||||
int d = mode ? 0 : g_reg[lv].den, a = mode ? 0 : g_reg[lv].umin, b = mode ? 0 : g_reg[lv].umax; if (*den == d && *umin == a && *umax == b) continue;
|
||||
LOG("秘境:关卡 %d 本局怪物区域 密度 %d → %d、精英组 %d–%d → %d–%d(%s)", lv, *den, d, *umin, *umax, a, b, mode ? "已结算,不再填怪" : "写回原值"); *den = d; *umin = (uint8_t)a; *umax = (uint8_t)b; } }
|
||||
// 退场的闯入首领的真移除:它被传到远处后,那间房离玩家远、游戏自己会把房间卸载(实测约 150 拍),单位随之从单位表里拿掉、存成房间存档里的一条怪物记录
|
||||
// (记录 +0xc 是单位号)。这时把那条记录照 saved_purge 的做法改成「不还原」(标志 +0x14 置 0x100、单位号写成全 1)——以后玩家走回去,房间重新载入也不会再把它放出来。
|
||||
// 全程不走死亡 / 掉落 / 击杀计数。房间还没卸载时什么都不做(它在 150 格外原地站着)
|
||||
// True removal of an invading boss that has left: after it is teleported far away, its room is far from the player and the game unloads the room by itself (about 150 ticks, measured), taking the unit out of the unit table and storing it as one monster record in the room's saved state
|
||||
// (record +0xc is the unit id). At that point the record is changed to "do not restore" the way saved_purge does it (flag +0x14 set to 0x100, unit id written as all ones) - if the player walks back later and the room is loaded again, it is not brought out again.
|
||||
// No death / drop / kill count is involved at any point. Nothing is done while the room is not yet unloaded (it stands in place more than 150 tiles away)
|
||||
static void inv_gone_pump(uint64_t G, uint32_t t) {
|
||||
for (int i = 0; i < 2; i++) { uint32_t id = g_inv_gone[i]; if (!id || find_unit(G, 1, id)) continue;
|
||||
uint64_t T = tables(G), heads = rd(G + 0x1b0); int acts = T ? *(int32_t *)(uintptr_t)(T + 0x108) : 0, hit = 0; if (!heads || acts <= 0 || acts > 8) continue;
|
||||
for (int a = 0; a < acts && !hit; a++) for (uint64_t nd = rd(heads + 8ull * a), k = 0; nd && k < 4096 && !hit; nd = rd(nd + 0x20), k++) for (uint64_t r = rd(nd + 0x10), j = 0; r && j < 1024; r = rd(r + 0xb0), j++)
|
||||
if (*(uint32_t *)(uintptr_t)(r + 0xc) == id) { *(uint32_t *)(uintptr_t)(r + 0x14) |= 0x100; *(uint32_t *)(uintptr_t)(r + 0xc) = 0xffffffffu; hit = 1; break; }
|
||||
if (hit) { LOG("秘境:拍 %u 退场的闯入首领(单位 id %u)所在房间已卸载,它的存档记录改成不还原", t, id); g_inv_gone[i] = 0; }
|
||||
else { static uint32_t warned; if (warned != id && t % 250 == 0) { warned = id; LOG("秘境:拍 %u 退场的闯入首领(单位 id %u)不在单位表里,房间存档里也没找到它的记录", t, id); } } }
|
||||
}
|
||||
// 已结算的图里,地图预设点上的怪也不再放:给预设记录置原版自己的「跳过」位(记录 +0x28 位 0,放预设单位的循环 main+0x7ce9bc 读它;+0x20 = 1 是怪)。记录在房间初始化时才有,所以每拍对一遍
|
||||
// 单位阵营(0 敌对 / 2 玩家一方):原版存房间时自己的读法(main+0x7e0f3c 起)——单位 +0x88 的属性表,+0x1c 位 31 没置 = 0;否则在 +0xd0 / +0xd8 两条链(下一条 +0x68)里找状态 0x69 的节点,
|
||||
// 对它取属性 0xac:main+0x5bc810([单位 +0x1bd] 字节, 节点, 0xac, 0);没有这个节点 = 0
|
||||
@@ -911,7 +1016,8 @@ static void rift_setup(uint64_t G) {
|
||||
uint64_t T = tables(G), a = T ? rd(T + 0x18f8) : 0, n = T ? rd(T + 0x1900) : 0;
|
||||
for (int i = 0; i < K.nmaps; i++) { int lv = K.maps[i]; uint64_t r = rd(G + 0x1d0 + 8ull * lv); if (!r) { LOG("【红】秘境:关卡 %d 没有怪物区域", lv); continue; }
|
||||
uint8_t *umin, *umax; int32_t *den = region_of(G, lv, &umin, &umax); int d0 = g_reg[lv].den, a0 = g_reg[lv].umin, b0 = g_reg[lv].umax; // 从原值算(上一次秘境结算后置过 0) | Computed from the original values (they were set to 0 after the previous rift completion)
|
||||
int e2 = tier_elite_x2(K.tier); *den = d0 * 3 > 10000 ? 10000 : d0 * 3; *umin = a0 * e2 / 2 > 255 ? 255 : a0 * e2 / 2; *umax = b0 * e2 / 2 > 255 ? 255 : b0 * e2 / 2; // 精英组倍数按层(tier_elite_x2) | elite pack multiplier by level (tier_elite_x2)
|
||||
int e2 = tier_elite_x2(K.tier); *den = d0 * 3 > 10000 ? 10000 : d0 * 3; *umin = a0 * e2 / 2 > 255 ? 255 : a0 * e2 / 2; *umax = b0 * e2 / 2 > 255 ? 255 : b0 * e2 / 2;
|
||||
{ const char *e = getenv("DM_RIFT_TEST_NAT"); int pct = e ? atoi(e) : hi_on("su", 75) ? su_nat_pct(K.tier) : 100; *den = (int)((long long)*den * pct / 100); *umin = (uint8_t)(*umin * pct / 100); *umax = (uint8_t)(*umax * pct / 100); } // 75 层起原生怪按层减少,位置让给特殊精英 | from level 75, native monsters are reduced level by level, making room for special elites
|
||||
LOG("秘境:关卡 %d 本局怪物区域 密度 %d → %d、精英组 %d–%d → %d–%d(第 %d 层 ×%d.%d)", lv, d0, *den, a0, b0, *umin, *umax, K.tier, e2 / 2, e2 % 2 * 5);
|
||||
for (uint64_t k = 0; a && k < n; k++) if (*(int32_t *)(uintptr_t)(a + k * 0x1c) == lv) { int32_t *rm = (int32_t *)(uintptr_t)(a + k * 0x1c + 0xc); int had = 0; for (int q = 0; q < g_nmz; q++) had |= g_mz[q].lv == lv;
|
||||
if (g_built[lv]) LOG("秘境:关卡 %d 服务端已建,LvlMaze 地狱房间数不动(%d)", lv, *rm);
|
||||
@@ -1101,13 +1207,47 @@ static int start_rift(uint64_t G, uint64_t player, uint32_t t, int tier) {
|
||||
for (int q = 0; q < K.nmaps && L.nused < 24; q++) L.used[L.nused++] = K.maps[q];
|
||||
atomic_fetch_add(&g_run_seq, 1);
|
||||
rift_setup(G); K.cur = 0; atomic_store(&K.score, getenv("DM_RIFT_TEST_SCORE") ? atoi(getenv("DM_RIFT_TEST_SCORE")) : 0); // 测试:初始分数(看进度条) | Test: initial score (to see the progress bar)
|
||||
atomic_store(&K.guard_dead, 0); atomic_store(&K.timeout, 0); K.guard = 0; memset(K.guards, 0, sizeof K.guards); K.inc = 0;
|
||||
atomic_store(&K.guard_dead, 0); atomic_store(&K.timeout, 0); atomic_store(&K.gdead, 0); atomic_store(&K.gtotal, 0); K.guard = 0; memset(K.guards, 0, sizeof K.guards); K.inc = 0;
|
||||
// 本场的守护者开局就抽好(之后回城再来、继续,都是这几位):75 层起两位不同的。测试开关 DM_RIFT_TEST_GUARDS=<类号>[,<类号>] 指定(逐对验收用)
|
||||
// This run's Guardians are drawn at the start (returning to town and coming back, or continuing, gives the same ones): from level 75 two different ones. Test switch DM_RIFT_TEST_GUARDS=<class id>[,<class id>] specifies them (for pair-by-pair acceptance)
|
||||
{ K.nplan = hi_on("duo", 75) ? 2 : 1; K.gcls[2] = 0;
|
||||
if (K.nplan == 2) { int a = rnd(4), b = (a + 1 + rnd(3)) % 4; K.gcls[0] = k_duo[a]; K.gcls[1] = k_duo[b]; } else { K.gcls[0] = k_guard[rnd(5)]; K.gcls[1] = 0; }
|
||||
const char *e = getenv("DM_RIFT_TEST_GUARDS"); if (e) { int x = 0, y = 0, n = sscanf(e, "%d,%d", &x, &y); if (n >= 1 && x > 0) K.gcls[0] = x; if (n >= 2 && y > 0) K.gcls[1] = y; }
|
||||
K.guard_cls = K.gcls[0]; if (K.nplan == 2) LOG("秘境:本场守护者两位,类号 %d 与 %d(生命 ×%d.%03d、伤害 ×%d.%03d)", K.gcls[0], K.gcls[1], hi_duo_x1000(0) / 1000, hi_duo_x1000(0) % 1000, hi_duo_x1000(1) / 1000, hi_duo_x1000(1) % 1000); }
|
||||
// 闯入首领(设计稿第二、十七、十八节):80 层起 1 位、90 层起 2 位,开局抽好——是谁(多首领同场的池里、不与本场守护者同类号的那几位,两位不重样)、
|
||||
// 在进度百分之几闯入(1 位:30–70;2 位:25–45 与 55–80)。同一场不重抽。掉落不干预:它被打死就照自己在当前难度的原版表掉。
|
||||
// 测试开关:DM_RIFT_TEST_INVADE=<类号>[,<类号>] 指定是谁、DM_RIFT_TEST_INVPCT=<百分数> 指定第一位的闯入点
|
||||
// Invading bosses (design draft): 1 from level 80, 2 from level 90, drawn at the start - who (from the pool for several bosses in one fight, not sharing a class id with this run's Guardians, the two being different),
|
||||
// and at what percentage of progress they invade (1 boss: 30–70; 2 bosses: 25–45 and 55–80). Not redrawn within a run. Drops are not interfered with: when killed it drops from its own original table for the current difficulty.
|
||||
// Test switches: DM_RIFT_TEST_INVADE=<class id>[,<class id>] chooses who, DM_RIFT_TEST_INVPCT=<percent> the first one's invasion point
|
||||
{ memset(K.inv_cls, 0, sizeof K.inv_cls); memset(K.inv_st, 0, sizeof K.inv_st); memset(K.inv_id, 0, sizeof K.inv_id); K.inv_n = !hi_on("invade", 80) ? 0 : (K.tier >= 90 || (getenv("DM_RIFT_TEST_HI") && strstr(getenv("DM_RIFT_TEST_HI"), "invade2"))) ? 2 : 1;
|
||||
int pool[4], np = 0; for (int q = 0; q < 4; q++) pool[np++] = k_duo[q]; // 可以与本场守护者同类号:守护者现身时在场的闯入首领退场(见刷守护者处),两者不会同场 | it may share a class id with this run's Guardians: when the Guardians appear an invading boss that is present leaves (see where the Guardians are spawned), so the two are never on the field together
|
||||
if (K.inv_n > np) K.inv_n = np;
|
||||
for (int q = 0; q < K.inv_n; q++) { int j = rnd(np); K.inv_cls[q] = pool[j]; pool[j] = pool[--np];
|
||||
K.inv_pct[q] = K.inv_n == 1 ? 30 + rnd(41) : q == 0 ? 25 + rnd(21) : 55 + rnd(26); }
|
||||
const char *e = getenv("DM_RIFT_TEST_INVADE"); if (e && K.inv_n) { int x = 0, y = 0, n = sscanf(e, "%d,%d", &x, &y); if (n >= 1 && x > 0) K.inv_cls[0] = x; if (n >= 2 && y > 0 && K.inv_n > 1) K.inv_cls[1] = y; }
|
||||
if ((e = getenv("DM_RIFT_TEST_INVPCT")) && K.inv_n) K.inv_pct[0] = atoi(e);
|
||||
if (K.inv_n) { int nd = atomic_load(&K.need); atomic_store(&K.need, nd * (100 + 12 * K.inv_n) / 100); // 打掉一位 +12% 进度:进度需求同步上调,免得内容更多反而更快出守护者 | +12% progress for each one killed: the progress requirement is raised to match, so that more content does not make the Guardians appear sooner
|
||||
if (K.inv_n >= 2) say("dmRiftSayFoes", K.inv_n); // 90 层起开局说一声本场有几位强敌(不说是谁、不说何时) | from level 90, say at the start how many strong enemies this run has (not who, not when)
|
||||
LOG("秘境:本场闯入首领 %d 位:类号 %d(进度 %d%% 时)%s;进度需求 %d → %d", K.inv_n, K.inv_cls[0], K.inv_pct[0], K.inv_n > 1 ? "与另一位(见闯入时的日志)" : "", nd, atomic_load(&K.need)); } }
|
||||
// 特殊精英:开局把池洗成本场的出场次序(放完一轮再从头)
|
||||
// Special elites: at the start, shuffle the pool into this run's order of appearance (after a full round, start again from the top)
|
||||
{ K.su_next = K.su_cnt = 0; K.su_last = 0; memset(K.su_live, 0, sizeof K.su_live); int np = (int)sizeof k_su_pool; for (int q = 0; q < np; q++) K.su_order[q] = k_su_pool[q];
|
||||
for (int q = np - 1; q > 0; q--) { int j = rnd(q + 1), x = K.su_order[q]; K.su_order[q] = K.su_order[j]; K.su_order[j] = x; }
|
||||
const char *e = getenv("DM_RIFT_TEST_SUROWS"); if (e) { char bf[200]; strlcpy(bf, e, sizeof bf); int q = 0; for (char *sv, *k = strtok_r(bf, ",", &sv); k && q < np; k = strtok_r(NULL, ",", &sv)) K.su_order[q++] = atoi(k); }
|
||||
if (hi_on("su", 75)) LOG("秘境:本场特殊精英:原生怪留 %d%%,同时在场最多 %d 组,头几位的行号 %d、%d、%d", su_nat_pct(K.tier), su_cap(K.tier), K.su_order[0], K.su_order[1], K.su_order[2]); }
|
||||
// 守护者分波(设计稿第二十四节第 3 问):安达利尔死时会连带杀死同场的其它首领,所以她单独一波、先出;她倒下 WAVE_GAP 拍后下一波才刷
|
||||
// (实测她死后 0 / 25 / 75 拍刷出的迪亚波罗都活着,各 1 局;取 75 拍留余量,也给玩家喘口气)。
|
||||
// 95–99 层:安达利尔(生命 ×0.5 → ×0.9)→ 本场那一对(照双守护者的 s / d);100 层:安达利尔(×1.0)→ 一对 → 另一对(四位各 ×0.5、伤害 ×1.0)。94 层及以下一波不变
|
||||
// Guardian waves (design draft section 24, question 3): when Andariel dies she also kills the other bosses on the field, so she is a wave of her own and comes first; the next wave is spawned WAVE_GAP ticks after she falls
|
||||
// (measured: Diablo spawned 0 / 25 / 75 ticks after her death stayed alive, 1 run each; 75 ticks is taken to leave margin, and it also gives the player a breather).
|
||||
// Levels 95–99: Andariel (life x0.5 -> x0.9) -> this run's pair (with the s / d of the two-Guardian fight); level 100: Andariel (x1.0) -> a pair -> the other pair (each of the four x0.5, damage x1.0). Level 94 and below: one wave, unchanged
|
||||
K.wave = 0; K.wave_t = 0; K.nwave = 1; K.wn[0] = K.nplan; K.wcls[0][0] = K.gcls[0]; K.wcls[0][1] = K.gcls[1]; K.whp[0] = K.nplan == 2 ? hi_duo_x1000(0) : 1000; K.wdm[0] = K.nplan == 2 ? hi_duo_x1000(1) : 1000;
|
||||
if (K.nplan == 2 && hi_on("wave", 95)) { const char *tw = getenv("DM_RIFT_TEST_HI"); int three = K.tier >= 100 || (tw && strstr(tw, "wave3"));
|
||||
K.wn[0] = 1; K.wcls[0][0] = 156; K.wcls[0][1] = 0; K.wdm[0] = 1000; K.whp[0] = three ? 1000 : 500 + 100 * ((K.tier < 95 ? 95 : K.tier > 99 ? 99 : K.tier) - 95);
|
||||
K.wn[1] = 2; K.wcls[1][0] = K.gcls[0]; K.wcls[1][1] = K.gcls[1]; K.whp[1] = three ? 500 : hi_duo_x1000(0); K.wdm[1] = three ? 1000 : hi_duo_x1000(1); K.nwave = 2;
|
||||
if (three) { int q = 0; for (int k = 0; k < 4; k++) if (k_duo[k] != K.gcls[0] && k_duo[k] != K.gcls[1] && q < 2) K.wcls[2][q++] = k_duo[k]; K.wn[2] = q; K.whp[2] = 500; K.wdm[2] = 1000; K.nwave = 3; }
|
||||
LOG("秘境:本场守护者分 %d 波:安达利尔(生命 ×%d.%03d)→ 类号 %d 与 %d(×%d.%03d)%s", K.nwave, K.whp[0] / 1000, K.whp[0] % 1000, K.wcls[1][0], K.wcls[1][1], K.whp[1] / 1000, K.whp[1] % 1000, K.nwave == 3 ? " → 另外两位(×0.500)" : ""); }
|
||||
K.guard_cls = K.gcls[0]; if (K.nplan == 2 && K.nwave == 1) LOG("秘境:本场守护者两位,类号 %d 与 %d(生命 ×%d.%03d、伤害 ×%d.%03d)", K.gcls[0], K.gcls[1], hi_duo_x1000(0) / 1000, hi_duo_x1000(0) % 1000, hi_duo_x1000(1) / 1000, hi_duo_x1000(1) % 1000); }
|
||||
K.t0_ns = guest_ns();
|
||||
if (getenv("DM_RIFT_TEST_LATE")) { K.t0_ns -= (uint64_t)RIFT_SECS * 1000000000ull; LOG("秘境:测试 DM_RIFT_TEST_LATE 开局即超时"); } // 造「超时打倒守护者」现场 | set up the "Guardian defeated after time ran out" test case
|
||||
K.players_old = dm_hud_requested_players(); if (!K.players_old) K.players_old = 1;
|
||||
@@ -1125,6 +1265,23 @@ static int start_rift(uint64_t G, uint64_t player, uint32_t t, int tier) {
|
||||
if (!R.gift) L.gift_due = 1; // 第一次进秘境送一颗彩虹刻面,只送一次:落到秘境图里再掉在脚下 | The first rift entry gives one Rainbow Facet, only once: dropped at the player's feet after landing on a rift map
|
||||
return 1;
|
||||
}
|
||||
// 刷当前这一波守护者(K.wave)。一位:人右下 6 格;两位:一左一右各 6 格。每位先照常按层改(守护者 = 本层怪物等级 + 3,起算层也 + 3,同吃本层总倍率),
|
||||
// 再乘这一波的生命系数(截顶之前乘)与伤害系数
|
||||
// Spawn the Guardians of the current wave (K.wave). One: 6 tiles to the player's lower right; two: 6 tiles to the left and 6 to the right. Each is first scaled by level as usual (Guardian = this level's monster level + 3, the starting level also + 3, taking this level's total multiplier as well),
|
||||
// then multiplied by this wave's life factor (before capping) and damage factor
|
||||
#define WAVE_GAP 75
|
||||
static void guard_wave(uint64_t G, uint64_t player, uint32_t t, int lowhp) {
|
||||
static const int ox[2][2] = { { 6, 0 }, { 6, -6 } }, oy[2][2] = { { 6, 0 }, { 6, 6 } }; int w = K.wave, nw = K.wn[w] < 1 ? 1 : K.wn[w] > 2 ? 2 : K.wn[w], x, y, n = 0; unit_xy(player, &x, &y); hs_sync();
|
||||
for (int i = 0; i < nw; i++) { int32_t pos[2] = { x + ox[nw - 1][i], y + oy[nw - 1][i] }; uint64_t rr = free_spot(G, unit_room(player), pos);
|
||||
uint64_t u = rr ? ((uint64_t (*)(uint64_t, uint64_t, int, int, int, int, int, int, uint64_t))(B + 0x7ce630))(G, rr, 1, K.wcls[w][i], pos[0], pos[1], 1, 0, 0x10) : 0;
|
||||
if (!u) { LOG("【红】秘境:守护者第 %d 波第 %d 位(类号 %d)没刷出来", w + 1, i + 1, K.wcls[w][i]); continue; }
|
||||
K.guards[i] = *(uint32_t *)(uintptr_t)(u + 8); K.gcls[i] = K.wcls[w][i]; if (!K.guard) K.guard = K.guards[i]; n++;
|
||||
if (lowhp) ss(u, 6, 256); else if (K.tier >= 9) { g_hp_mul = K.whp[w]; scale_monster(G, u, target_level(player) + 3, dm_rift_tier_level(9, gs(player, 12)) + 3); g_hp_mul = 1000; }
|
||||
if (K.wdm[w] != 1000 && !lowhp) ss(u, 25, (int)((100LL + gs(u, 25)) * K.wdm[w] / 1000 - 100)); // 伤害:属性 25 是「伤害 +N%」,整体乘 d 即 (100 + N) × d − 100 | damage: stat 25 is "damage +N%", so multiplying the whole by d gives (100 + N) x d - 100
|
||||
HS.guard_hp += gs(u, 7) >> 8;
|
||||
LOG("秘境:拍 %u 刷守护者%s%s 类号 %d id %u 等级 %d 生命 %d 伤害百分比 %d", t, K.nwave > 1 ? (w == 0 ? "(第 1 波)" : w == 1 ? "(第 2 波)" : "(第 3 波)") : "", nw == 2 ? (i ? "(第二位)" : "(第一位)") : "", K.wcls[w][i], K.guards[i], gs(u, 12), gs(u, 7) >> 8, gs(u, 25)); }
|
||||
atomic_store(&K.gdead, 0); atomic_store(&K.gtotal, n);
|
||||
if (n) { if (w == 0) say(nw == 2 && n == 2 ? "dmRiftSayGuardians" : "dmRiftSayGuardian"); else say("dmRiftSayWave", w + 1, K.nwave); } }
|
||||
void dm_rift_tick(uint64_t G, uint64_t player, uint8_t *main_base) {
|
||||
B = main_base; if (!G || !player || !B) return;
|
||||
atomic_store(&g_merc_req, 0); if (getenv("DM_TEST_MERC_EQUIP") || getenv("DM_TEST_MERC_DUMP")) merc_test(G, player, *(uint32_t *)(uintptr_t)(G + 0x170));
|
||||
@@ -1269,51 +1426,179 @@ void dm_rift_tick(uint64_t G, uint64_t player, uint8_t *main_base) {
|
||||
// Newly spawned hostile monsters get their stats changed by level (from level 9). Test switch DM_RIFT_TEST_LOWHP=1: change to 1 life point (hold the main attack button and kill all the way through; verifies scoring / guardian / level increase)
|
||||
static int lowhp = -1; if (lowhp < 0) lowhp = getenv("DM_RIFT_TEST_LOWHP") != NULL;
|
||||
if (K.tier >= 9 || lowhp) { static uint32_t r_; uint32_t w = atomic_load(&g_newq_w); if (w - r_ > NQ) r_ = w - NQ; int lt = target_level(player);
|
||||
for (; r_ != w; r_++) { uint32_t id = atomic_load(&g_newq[r_ % NQ]); uint64_t u = find_unit(G, 1, id); if (u && !is_guard(id)) { if (K.tier >= 9) scale_monster(G, u, lt, dm_rift_tier_level(9, gs(player, 12))); if (lowhp) ss(u, 6, 256); dmg_probe_add(id, t); hs_spawn(id, gs(u, 7) >> 8); } } }
|
||||
for (; r_ != w; r_++) { uint32_t id = atomic_load(&g_newq[r_ % NQ]); uint64_t u = find_unit(G, 1, id); if (u && !is_guard(id) && hi_on("summon", 75) && boss_summon(*(uint32_t *)(uintptr_t)(u + 4))) { static int n, sq = -1; int cur = atomic_load(&g_run_seq); if (cur != sq) { sq = cur; n = 0; }
|
||||
if (n++ < 4) LOG("秘境:首领召唤物 id %u(类号 %u)不按层改,保持原版:等级 %d 生命 %d", id, *(uint32_t *)(uintptr_t)(u + 4), gs(u, 12), gs(u, 7) >> 8); hs_spawn(id, gs(u, 7) >> 8); continue; }
|
||||
if (u && !is_guard(id)) { uint64_t md = rd(u + 0x10); int su = md && (*(uint8_t *)(uintptr_t)(md + 0x1a) & 0x02) && hi_on("su", 75), sm = !su && su_minion(id); /* 特殊精英本体:生命另乘 SU_HP_X;组里的随从另乘 SU_MINION_X1000 | special elite body: life additionally multiplied by SU_HP_X; minions in the group additionally by SU_MINION_X1000 */
|
||||
if (K.tier >= 9) { if (su) { g_hp_mul = SU_HP_X * 1000; g_hp_soft = SU_HP_SOFT; } else if (sm) g_hp_mul = SU_MINION_X1000; scale_monster(G, u, lt, dm_rift_tier_level(9, gs(player, 12))); g_hp_mul = 1000; g_hp_soft = 0; } if (su) { static int n; if (n++ < 12) LOG("秘境:特殊精英本体 id %u(类号 %u,超级独特号 %d)生命另乘 %d:等级 %d 生命 %d", id, *(uint32_t *)(uintptr_t)(u + 4), *(int16_t *)(uintptr_t)(md + 0x2a), SU_HP_X, gs(u, 12), gs(u, 7) >> 8); } if (lowhp) ss(u, 6, 256); dmg_probe_add(id, t); hs_spawn(id, gs(u, 7) >> 8); } } }
|
||||
dmg_probe_pump(G, t); hs_tick(G, player, t, lv);
|
||||
// 测试开关 DM_RIFT_TEST_PETGOD=1:每 10 拍把秘境图里友方怪物单位(玩家的随从)的当前生命回满——自动局靠随从代打,随从被围死后就没人补最后一下了
|
||||
// Test switch DM_RIFT_TEST_PETGOD=1: every 10 ticks, refill the current life of friendly monster units (the player's minions) in the rift map - unattended runs rely on minions to do the fighting, and once the minions are surrounded and killed nobody lands the last hit
|
||||
{ static int on = -1; if (on < 0) on = getenv("DM_RIFT_TEST_PETGOD") != NULL; if (on && t % 10 == 0 && in_rift_map(lv)) for (int b = 0; b < 128; b++) for (uint64_t u = rd(G + 0x2230 + 1 * 0x400 + 8 * b); u; u = rd(u + 0x158)) {
|
||||
uint32_t m = *(uint32_t *)(uintptr_t)(u + 0xc); if (m != 0 && m != 12 && unit_align(u)) ss(u, 6, gs(u, 7)); } }
|
||||
// 测试读数 DM_RIFT_TEST_ILVL=1:每 10 秒数一次地上的物品(服务端物品表 G+0x2e30,模式 3),报物品等级(数据块 +0x38)范围——验 B 方案下掉落物品等级跟不跟改过的怪物等级
|
||||
// Test readout DM_RIFT_TEST_ILVL=1: every 10 seconds count the items on the ground (server item table G+0x2e30, mode 3) and report the item level (data block +0x38) range -- verifies whether drop item levels follow the modified monster level under plan B
|
||||
{ static int il = -1; if (il < 0) il = getenv("DM_RIFT_TEST_ILVL") != NULL;
|
||||
if (il && t % 250 == 0) { int n = 0, mn = 999, mx = 0; for (int bb = 0; bb < 128; bb++) for (uint64_t it = rd(G + 0x2e30 + 8 * bb); it; it = rd(it + 0x158)) { uint64_t d = rd(it + 0x10); if (!d || *(uint32_t *)(uintptr_t)(it + 0xc) != 3) continue; int v = *(int32_t *)(uintptr_t)(d + 0x38); n++; if (v < mn) mn = v; if (v > mx) mx = v; }
|
||||
LOG("秘境:测试读数 拍 %u 地上物品 %d 件,物品等级 %d–%d", t, n, n ? mn : 0, mx); } }
|
||||
|
||||
// 测试开关 DM_RIFT_TEST_TOUR=1:秘境进行中每秒用原版传送把人放到本图房间链里的下一间(中心附近的空地),整张图的房间都激活一遍——验「90 层起不放普通预设怪」要整图的读数
|
||||
// Test switch DM_RIFT_TEST_TOUR=1: during a rift, every second the original teleport puts the player in the next room of this map's room chain (open ground near the centre), so every room of the whole map gets activated - verifying "no ordinary preset monsters from level 90" needs readings from the whole map
|
||||
{ static int tour = -1, k; if (tour < 0) tour = getenv("DM_RIFT_TEST_TOUR") != NULL;
|
||||
if (tour && t % 25 == 0 && in_rift_map(lv) && atomic_load(&K.st) == ST_RUN) { uint64_t lvp = level_of(player), r = dm_level_rooms(lvp); int i = 0, nr = 0;
|
||||
for (uint64_t q = r; q && nr < 2000; q = rd(q + 0x48)) nr++;
|
||||
for (; r && i < k % (nr ? nr : 1); r = rd(r + 0x48)) i++;
|
||||
if (r) { int32_t pos[2] = { *(int32_t *)(uintptr_t)(r + 0x60) * 5 + *(int32_t *)(uintptr_t)(r + 0x68) * 5 / 2, *(int32_t *)(uintptr_t)(r + 0x64) * 5 + *(int32_t *)(uintptr_t)(r + 0x6c) * 5 / 2 };
|
||||
uint64_t rs = room_load(G, lvp, pos[0], pos[1]), rr = rs ? free_spot(G, rs, pos) : 0; int ok = rr && dm_teleport(B, G, player, rr, pos[0], pos[1]);
|
||||
static int ln; if (ln++ < 3 || k == nr - 1) LOG("秘境:测试逐间跳 第 %d / %d 间 → %d,%d %s", k + 1, nr, pos[0], pos[1], ok ? "成" : "不成"); }
|
||||
{ static uint32_t seen[8192]; static int scls[8192], sfl[8192], ns; /* 逐间跳全程:本图出现过的怪按单位 id 去重累计;走完一轮后 5 秒按类号报 | over the whole room-by-room jump: monsters seen in this map are accumulated, de-duplicated by unit id; 5 seconds after a full round, reported by class id */
|
||||
for (int b = 0; b < 128; b++) for (uint64_t v = rd(G + 0x2230 + 1 * 0x400 + 8 * b); v; v = rd(v + 0x158)) { uint32_t id = *(uint32_t *)(uintptr_t)(v + 8); if (any_level(v) != lv) continue; int q = 0; for (; q < ns && seen[q] != id; q++) {}
|
||||
if (q == ns && ns < 8192) { uint64_t md = rd(v + 0x10); uint32_t mo = *(uint32_t *)(uintptr_t)(v + 0xc); seen[ns] = id; scls[ns] = *(int32_t *)(uintptr_t)(v + 4); sfl[ns] = (md ? *(uint8_t *)(uintptr_t)(md + 0x1a) : 0) | (mo == 0 || mo == 12 ? 0x100 : 0); ns++; } }
|
||||
if (k == nr + 5) { static int cl[1024], cn[1024], cf[1024]; int nc = 0;
|
||||
for (int q = 0; q < ns; q++) { int j2 = 0; for (; j2 < nc && cl[j2] != scls[q]; j2++) {} if (j2 == nc && nc < 1024) { cl[nc] = scls[q]; cn[nc] = cf[nc] = 0; nc++; } if (j2 < 1024) { cn[j2]++; cf[j2] |= sfl[q]; } }
|
||||
LOG("[逐间跳读数] 关卡 %d 出现过的怪 %d 只、%d 种", lv, ns, nc); for (int j2 = 0; j2 < nc; j2++) LOG("[逐间跳读数] 类号 %d ×%d 标志 0x%03x(0x100 = 有一只首次见到时已是死的)", cl[j2], cn[j2], cf[j2]); } }
|
||||
k++; } }
|
||||
// 测试开关 DM_RIFT_TEST_PULL=1:每 3 秒用原版传送 0x7cc530 把人放到一只还活着的敌对怪(客户端认的)旁边——脚本按主攻击键就能一路打(验计分 / 守护者)
|
||||
// Test switch DM_RIFT_TEST_PULL=1: every 3 seconds use the original game's teleport 0x7cc530 to put the player next to a still-living hostile monster (as recognized by the client) -- a script only has to press the main attack button to fight all the way through (verifies scoring / guardian)
|
||||
{ static int pull = -1; if (pull < 0) pull = getenv("DM_RIFT_TEST_PULL") != NULL;
|
||||
if (pull && t % 38 == 0 && in_rift_map(lv) && K.guard && !atomic_load(&K.guard_dead)) { uint64_t g = 0; for (int i = 0; i < 3 && !g; i++) { uint64_t gu = K.guards[i] ? find_unit(G, 1, K.guards[i]) : 0; uint32_t gm = gu ? *(uint32_t *)(uintptr_t)(gu + 0xc) : 0; if (gu && gm != 0 && gm != 12) g = gu; } int x, y; if (g && unit_xy(g, &x, &y)) dm_teleport(B, G, player, unit_room(g), x + 2, y + 2); }
|
||||
else if (pull && t % 38 == 0 && in_rift_map(lv)) { uint32_t w = atomic_load(&g_newq_w); int px, py, bd = 1 << 30, bx = 0, by = 0; unit_xy(player, &px, &py); // 最近的那只 | The nearest one
|
||||
for (uint32_t k = 0; k < NQ && k < w; k++) { uint64_t u = find_unit(G, 1, atomic_load(&g_newq[(w - 1 - k) % NQ])); if (!u || unit_level(u) != lv) continue; uint32_t m = *(uint32_t *)(uintptr_t)(u + 0xc); if (m == 0 || m == 12) continue;
|
||||
int x, y; if (!unit_xy(u, &x, &y)) continue; int d = abs(x - px) + abs(y - py); if (d < bd) { bd = d; bx = x; by = y; } }
|
||||
if (pull && t % 38 == 0 && in_rift_map(lv) && ((K.guard && !atomic_load(&K.guard_dead)) || K.inv_st[0] == 2 || K.inv_st[1] == 2)) { uint64_t g = 0; for (int i = 0; i < 2 && !g; i++) { uint64_t gu = K.inv_st[i] == 2 ? find_unit(G, 1, K.inv_id[i]) : 0; uint32_t gm = gu ? *(uint32_t *)(uintptr_t)(gu + 0xc) : 0; if (gu && gm != 0 && gm != 12) g = gu; } /* 在场的闯入首领优先 | an invading boss that is present takes priority */
|
||||
for (int i = 0; i < 3 && !g; i++) { uint64_t gu = K.guards[i] ? find_unit(G, 1, K.guards[i]) : 0; uint32_t gm = gu ? *(uint32_t *)(uintptr_t)(gu + 0xc) : 0; if (gu && gm != 0 && gm != 12) g = gu; } int x, y; if (g && unit_xy(g, &x, &y)) dm_teleport(B, G, player, unit_room(g), x + 2, y + 2); }
|
||||
else if (pull && t % 38 == 0 && in_rift_map(lv)) { uint32_t w = atomic_load(&g_newq_w); int px, py, bd = 1 << 30, bx = 0, by = 0; unit_xy(player, &px, &py); // 最近的那只;同一只连着 4 次(约 6 秒)都是最近的还没死,就当它打不死(投石车一类的预设单位、卡在墙里的),以后不再找它 | the nearest one; if the same one is the nearest 4 times in a row (about 6 seconds) and still not dead, treat it as unkillable (preset units such as catapults, ones stuck in walls) and never look for it again
|
||||
static uint32_t bl[64], last; static int nbl, rep; uint32_t bid = 0;
|
||||
for (uint32_t k = 0; k < NQ && k < w; k++) { uint32_t id = atomic_load(&g_newq[(w - 1 - k) % NQ]); uint64_t u = find_unit(G, 1, id); if (!u || unit_level(u) != lv) continue; uint32_t m = *(uint32_t *)(uintptr_t)(u + 0xc); if (m == 0 || m == 12) continue;
|
||||
int x, y, skip = 0; for (int q = 0; q < nbl && q < 64; q++) skip |= bl[q] == id; if (skip || !unit_xy(u, &x, &y)) continue; int d = abs(x - px) + abs(y - py); if (d < bd) { bd = d; bx = x; by = y; bid = id; } }
|
||||
if (bid && bid == last) { if (++rep >= 4) { bl[nbl++ % 64] = bid; rep = 0; LOG("秘境:测试拉人 单位 id %u 连着 4 次是最近的还没死,不再找它", bid); } } else { last = bid; rep = 0; }
|
||||
if (bd < (1 << 30) && bd > 3) { uint64_t lvp = level_of(player); int32_t pos[2] = { bx + 1, by + 1 }; uint64_t rs = room_at(lvp, pos[0], pos[1]), rr = rs ? free_spot(G, rs, pos) : 0;
|
||||
int ok = dm_teleport(B, G, player, rr, pos[0], pos[1]); static int ln; if (ln++ < 5) LOG("秘境:测试拉人 → %d,%d(最近的怪 %d 格)%s", pos[0], pos[1], bd, ok ? "成" : "不成"); } } }
|
||||
int ok = dm_teleport(B, G, player, rr, pos[0], pos[1]); static int ln; if (ln++ < 5 || ln % 20 == 0) LOG("秘境:测试拉人 → %d,%d(最近的怪 id %u,%d 格)%s", pos[0], pos[1], bid, bd, ok ? "成" : "不成"); }
|
||||
else { static int ln2; if (ln2++ % 20 == 0) LOG("秘境:测试拉人 这一次没拉(最近的怪 id %u,%d 格;新怪队列写到 %u)", bid, bd == 1 << 30 ? -1 : bd, w); } } }
|
||||
// 计时
|
||||
// Timer
|
||||
{ uint64_t now = guest_ns();
|
||||
if (!atomic_load(&K.timeout) && now - K.t0_ns > (uint64_t)RIFT_SECS * 1000000000ull) { atomic_store(&K.timeout, 1); say("dmRiftSayTimeout"); } }
|
||||
// 守护者
|
||||
// Guardian
|
||||
inv_gone_pump(G, t);
|
||||
if (in_rift_map(lv) && g_entry_lv != lv) { int ex, ey; if (unit_xy(player, &ex, &ey)) { g_entry_lv = lv; g_entry_x = ex; g_entry_y = ey; } } else if (!in_rift_map(lv)) g_entry_lv = 0;
|
||||
// 特殊精英:每秒看一次要不要放下一组(规则见池那段注释)。「前方」= 玩家最近 2 秒走的方向;八个方向从它起、左右交替着找空地,离人不足 45 格或离本图入口不足 40 格的不要
|
||||
// Special elites: once a second, check whether to place the next group (rules in the comment on the pool). "Ahead" = the direction the player walked in the last 2 seconds; the eight directions are searched for open ground starting from it, alternating left and right; spots less than 45 tiles from the player or less than 40 tiles from this map's entrance are rejected
|
||||
if (t % 25 == 0 && hi_on("su", 75) && atomic_load(&K.st) == ST_RUN && g_entry_lv == lv) { static int hx[2], hy[2], hk; int px, py, live = 0; unit_xy(player, &px, &py);
|
||||
int dx = hx[hk] ? px - hx[hk] : 0, dy = hx[hk] ? py - hy[hk] : 0; hx[hk] = px; hy[hk] = py; hk ^= 1;
|
||||
for (int i = 0; i < 3; i++) { if (!K.su_live[i]) continue; uint64_t u = find_unit(G, 1, K.su_live[i]); uint32_t m = u ? *(uint32_t *)(uintptr_t)(u + 0xc) : 1;
|
||||
if (u && (m == 0 || m == 12)) K.su_live[i] = 0; else if (!u) { if (t - K.su_seen[i] > 750) K.su_live[i] = 0; } /* 本体死了这一组就算打完;30 秒找不到单位(玩家换了图 / 回了城,房间卸载)也不再占名额 | once the body is dead this group counts as finished; if its unit cannot be found for 30 seconds (the player changed map / went to town, the room was unloaded) it no longer takes up a slot either */
|
||||
else { K.su_seen[i] = t; int x, y; unit_xy(u, &x, &y); /* 追击(见池那段注释):本体离玩家 80 格以外满 5 秒,挪到玩家前方约 70 格的空地(随从照原版自己跟着首领) | pursuit (see the comment on the pool): once the body has been more than 80 tiles from the player for 5 seconds, move it to open ground about 70 tiles ahead of the player (the minions follow their boss on their own, as in the original) */
|
||||
if (abs(x - px) + abs(y - py) <= 80) K.su_near[i] = t;
|
||||
else if (t - K.su_near[i] >= 125) { static const int cx[8] = { 70, 50, 0, -50, -70, -50, 0, 50 }, cy[8] = { 0, 50, 70, 50, 0, -50, -70, -50 }; int d0 = rnd(8), best = 0, ok = 0; int32_t pos[2];
|
||||
if (dx || dy) for (int d = 0; d < 8; d++) { int v = dx * cx[d] + dy * cy[d]; if (v > best) { best = v; d0 = d; } }
|
||||
for (int k = 0; k < 8 && !ok; k++) { int d = (d0 + (k & 1 ? (k + 1) / 2 : 8 - k / 2)) % 8; pos[0] = px + cx[d]; pos[1] = py + cy[d]; uint64_t rs = room_load(G, level_of(player), pos[0], pos[1]), rr = rs ? free_spot(G, rs, pos) : 0;
|
||||
if (rr && abs(pos[0] - px) + abs(pos[1] - py) >= 60) ok = dm_teleport(B, G, u, rr, pos[0], pos[1]); }
|
||||
K.su_near[i] = t; static int n; if (n++ < 8) LOG("秘境:拍 %u 特殊精英(id %u)离玩家 %d 格满 5 秒,%s", t, K.su_live[i], abs(x - px) + abs(y - py), ok ? "挪到玩家前方" : "周围没有空地,下次再挪"); } }
|
||||
live += K.su_live[i] != 0; }
|
||||
if (!K.guard && live < su_cap(K.tier) && K.su_cnt < su_quota(K.tier) && g_near_now < SU_NEAR && t - K.su_last >= 75) {
|
||||
static const int sx[8] = { 70, 50, 0, -50, -70, -50, 0, 50 }, sy[8] = { 0, 50, 70, 50, 0, -50, -70, -50 }; int d0 = rnd(8), best = 0, np = (int)sizeof k_su_pool, baal = 0, row;
|
||||
if (dx || dy) for (int d = 0; d < 8; d++) { int v = dx * sx[d] + dy * sy[d]; if (v > best) { best = v; d0 = d; } }
|
||||
for (int w = 0; w < K.nwave; w++) for (int q = 0; q < K.wn[w]; q++) baal |= K.wcls[w][q] == 544; for (int q = 0; q < K.inv_n; q++) baal |= K.inv_cls[q] == 544;
|
||||
do row = K.su_order[K.su_next++ % np]; while (baal && (row == 24 || row == 36 || row == 38));
|
||||
uint64_t u = 0; int32_t pos[2] = { 0, 0 }; int f_room = 0, f_near = 0, f_fn = 0;
|
||||
for (int k = 0; k < 8 && !u; k++) { int d = (d0 + (k & 1 ? (k + 1) / 2 : 8 - k / 2)) % 8; pos[0] = px + sx[d]; pos[1] = py + sy[d]; uint64_t rs = room_load(G, level_of(player), pos[0], pos[1]), rr = rs ? free_spot(G, rs, pos) : 0;
|
||||
if (!rr) { f_room++; continue; } if (abs(pos[0] - px) + abs(pos[1] - py) < 45 || abs(pos[0] - g_entry_x) + abs(pos[1] - g_entry_y) < 40) { f_near++; continue; } f_fn++;
|
||||
u = su_spawn(G, rr, pos[0], pos[1], row); }
|
||||
static int fails; if (u) fails = 0; else if (++fails < 10) K.su_next--; else fails = 0; /* 放不成:这一位留着 1 秒后再试;同一位连着 10 次放不成就跳过它,免得一行卡住整场 | could not place it: keep this one and try again in 1 second; after 10 failures in a row for the same one, skip it so that one row does not hold up the whole run */
|
||||
if (!u) { K.su_last = t - 50; static int n; if (n++ % 20 == 0) LOG("秘境:拍 %u 特殊精英(行 %d)这一秒没放成(第 %d 次):八个方向里没有房间 / 空地的 %d 个、离人或离入口太近的 %d 个、原版函数没刷出来的 %d 个", t, row, n, f_room, f_near, f_fn); } /* 周围没有合适的空地(或原版函数没刷出来):这一位留着,1 秒后再试 | no suitable open ground around (or the original function spawned nothing): keep this one and try again in 1 second */
|
||||
else { uint32_t uid = *(uint32_t *)(uintptr_t)(u + 8); int ux = pos[0], uy = pos[1], nm = 0;
|
||||
for (int b = 0; b < 128; b++) for (uint64_t v = rd(G + 0x2230 + 1 * 0x400 + 8 * b); v; v = rd(v + 0x158)) { uint32_t vid = *(uint32_t *)(uintptr_t)(v + 8); uint64_t md = rd(v + 0x10); int x, y;
|
||||
if (vid > uid && md && (*(uint8_t *)(uintptr_t)(md + 0x1a) & 0x10) && unit_xy(v, &x, &y) && abs(x - ux) + abs(y - uy) <= 15) { g_su_min[g_su_min_w++ % 64] = vid; nm++; } }
|
||||
for (int i = 0; i < 3; i++) if (!K.su_live[i]) { K.su_live[i] = uid; K.su_seen[i] = K.su_near[i] = t; break; } K.su_cnt++; K.su_last = t;
|
||||
LOG("秘境:拍 %u 特殊精英第 %d 组刷出:行 %d 类号 %u id %u 在 %d,%d(离人 %d 格、离入口 %d 格;此前在场 %d 组、40 格内敌对 %d 只;随从 %d 只)", t, K.su_cnt, row, *(uint32_t *)(uintptr_t)(u + 4), *(uint32_t *)(uintptr_t)(u + 8), pos[0], pos[1],
|
||||
abs(pos[0] - px) + abs(pos[1] - py), abs(pos[0] - g_entry_x) + abs(pos[1] - g_entry_y), live, g_near_now, nm); } } }
|
||||
// 测试读数 DM_RIFT_TEST_GONE=<拍>:退场的闯入首领每 25 拍报一次位置 / 模式 / 生命 / 离人多远;到 <拍> 时把人传到它跟前,并让固定输出替身开始打它(验:退场后它动不动、走过去会不会打起来、打死给不给进度 / 掉不掉东西)
|
||||
// Test readout DM_RIFT_TEST_GONE=<tick>: an invading boss that has left reports its position / mode / life / distance from the player every 25 ticks; at <tick> the player is teleported next to it and the fixed-output stand-in starts hitting it (to verify: whether it moves after leaving, whether walking up to it starts a fight, whether killing it gives progress / drops)
|
||||
{ static int at = -1, hit, gx, gy, cls; static uint32_t hit_t; if (at < 0) { const char *e = getenv("DM_RIFT_TEST_GONE"); at = e ? atoi(e) : 0; }
|
||||
// 测试开关 DM_RIFT_TEST_GONEKILL=1:退场后第 10 拍把人传到它跟前、把它当前血置 1(由随从补刀)——验「退场到被真移除之间被打死」给不给进度、掉不掉东西
|
||||
// Test switch DM_RIFT_TEST_GONEKILL=1: at the 10th tick after it leaves, teleport the player next to it and set its current life to 1 (a minion delivers the last hit) - to verify whether "killed between leaving and being truly removed" gives progress or drops anything
|
||||
if (getenv("DM_RIFT_TEST_GONEKILL")) for (int i = 0; i < 2; i++) { static uint32_t t0[2], did[2]; uint64_t u = g_inv_gone[i] ? find_unit(G, 1, g_inv_gone[i]) : 0; if (!u) continue; if (did[i] != g_inv_gone[i]) { did[i] = g_inv_gone[i]; t0[i] = t; }
|
||||
uint32_t m = *(uint32_t *)(uintptr_t)(u + 0xc); int x, y; unit_xy(u, &x, &y);
|
||||
if (t - t0[i] == 10) { LOG("[退场读数] 拍 %u 把人传到退场的闯入首领跟前(它在 %d,%d,进度 %d)", t, x, y, atomic_load(&K.score)); dm_teleport(B, G, player, unit_room(u), x + 2, y + 2); }
|
||||
if (t - t0[i] >= 10 && m != 0 && m != 12) ss(u, 6, 256);
|
||||
if ((m == 0 || m == 12) && t0[i] != 1) { t0[i] = 1; LOG("[退场读数] 拍 %u 退场的闯入首领被打死了(模式 %u),进度 %d", t, m, atomic_load(&K.score)); } }
|
||||
if (at > 0) { for (int i = 0; i < 2; i++) { uint64_t u = g_inv_gone[i] ? find_unit(G, 1, g_inv_gone[i]) : 0; if (g_inv_gone_xy[i][0]) { gx = g_inv_gone_xy[i][0]; gy = g_inv_gone_xy[i][1]; cls = K.inv_cls[i]; } if (!u || t % 25) continue;
|
||||
int x, y, px, py; unit_xy(u, &x, &y); unit_xy(player, &px, &py); LOG("[退场读数] 拍 %u 第 %d 位:位置 %d,%d 模式 %u 生命 %d / %d 离人 %d 格", t, i + 1, x, y, *(uint32_t *)(uintptr_t)(u + 0xc), gs(u, 6) >> 8, gs(u, 7) >> 8, abs(x - px) + abs(y - py)); }
|
||||
if (gx && t >= (uint32_t)at && !hit) { int32_t pos[2] = { gx, gy }; uint64_t rs = room_load(G, level_of(player), gx, gy), rr = rs ? free_spot(G, rs, pos) : 0; hit = 1; hit_t = t; LOG("[退场读数] 拍 %u 把人传到退场落点 %d,%d(%s)", t, gx, gy, rr && dm_teleport(B, G, player, rr, pos[0], pos[1]) ? "成" : "没成"); }
|
||||
if (hit == 1 && t - hit_t >= 150) { hit = 2; int n = 0, px, py; unit_xy(player, &px, &py); for (int b = 0; b < 128; b++) for (uint64_t u = rd(G + 0x2230 + 1 * 0x400 + 8 * b); u; u = rd(u + 0x158)) { int x, y; if ((int)*(uint32_t *)(uintptr_t)(u + 4) == cls && unit_xy(u, &x, &y) && abs(x - px) + abs(y - py) < 80) n++; }
|
||||
LOG("[退场读数] 拍 %u 人已在退场落点 150 拍:80 格内类号 %d 的单位 %d 只(人在 %d,%d)", t, cls, n, px, py); } } }
|
||||
// 测试开关 DM_RIFT_TEST_SUSEQ=<起始拍>:<行号>,<行号>…(特殊精英的验收轮):秘境进行中从这一拍起,在人旁边用原版函数 main+0x69b310(游戏, 房间, x, y, 行号, 0) 依次刷超级金怪,
|
||||
// 每秒把人放到它旁边(配 DM_RIFT_TEST_LOWHP=1,新刷的怪只剩 1 点血,随从补一下就死);它死后 40 拍报一行:随从几只、这段时间新掉在地上的物品(类号:品质),再刷下一位。600 拍没死记「没打死」照样往下。
|
||||
// 第六个参数含义没查到,取 0 的依据是探路那一局(行 3,本体 + 8 只随从照表刷出)与这一轮
|
||||
// Test switch DM_RIFT_TEST_SUSEQ=<start tick>:<row>,<row>... (acceptance round for special elites): from this tick during a rift, super uniques are spawned one after another next to the player with the original function main+0x69b310(game, room, x, y, row, 0),
|
||||
// and every second the player is put next to it (with DM_RIFT_TEST_LOWHP=1 a freshly spawned monster has only 1 life left and dies from one hit by a minion); 40 ticks after it dies one line is reported: how many minions, the items newly dropped on the ground in that time (class id:quality), then the next one is spawned. If it is not dead after 600 ticks, "not killed" is recorded and it moves on anyway.
|
||||
// The meaning of the sixth argument was not found; 0 is used on the basis of the exploratory run (row 3, body + 8 minions spawned as in the table) and this round
|
||||
{ static int at = -1, rows[66], nr, idx, ph, row, minions; static uint32_t t0, hi, cls;
|
||||
if (at < 0) { const char *e = getenv("DM_RIFT_TEST_SUSEQ"); at = e ? atoi(e) : 0; const char *c = e ? strchr(e, ':') : NULL; char bf[400]; strlcpy(bf, c ? c + 1 : "", sizeof bf); for (char *sv, *k = strtok_r(bf, ",", &sv); k && nr < 66; k = strtok_r(NULL, ",", &sv)) rows[nr++] = atoi(k); }
|
||||
if (at > 0 && idx < nr && in_rift_map(lv) && atomic_load(&K.st) == ST_RUN) {
|
||||
if (ph == 0 && t >= (uint32_t)at && t >= t0 + 10) { row = rows[idx]; int x, y; unit_xy(player, &x, &y); int32_t pos[2] = { 0, 0 }; uint64_t rr = 0, u = 0; hi = 0; minions = 0;
|
||||
for (int b = 0; b < 128; b++) for (uint64_t it = rd(G + 0x2e30 + 8 * b); it; it = rd(it + 0x158)) if (*(uint32_t *)(uintptr_t)(it + 8) > hi) hi = *(uint32_t *)(uintptr_t)(it + 8);
|
||||
for (int d = 0; d < 8 && !u; d++) { static const int ox[8] = { 12, 9, 0, -9, -12, -9, 0, 9 }, oy[8] = { 0, 9, 12, 9, 0, -9, -12, -9 }; pos[0] = x + ox[d]; pos[1] = y + oy[d]; rr = free_spot(G, unit_room(player), pos); /* 原版函数在同一点试 5 次,那点被残留的随从占着就返回 0:换个方向再试 | the original function tries 5 times at the same point and returns 0 if that point is occupied by leftover minions: try again in another direction */
|
||||
u = rr ? su_spawn(G, rr, pos[0], pos[1], row) : 0; }
|
||||
if (!u) { LOG("[验收轮] 拍 %u 行 %d 刷不出(房间 %s,函数返回 0)", t, row, rr ? "有" : "无"); idx++; t0 = t; }
|
||||
else { g_suseq_id = *(uint32_t *)(uintptr_t)(u + 8); cls = *(uint32_t *)(uintptr_t)(u + 4); t0 = t; ph = 1; } }
|
||||
else if (ph == 1) { uint64_t u = find_unit(G, 1, g_suseq_id); uint32_t m = u ? *(uint32_t *)(uintptr_t)(u + 0xc) : 0; int dead = !u || m == 0 || m == 12, x, y;
|
||||
if (t - t0 == 20) { int px, py; unit_xy(player, &px, &py); for (int b = 0; b < 128; b++) for (uint64_t v = rd(G + 0x2230 + 1 * 0x400 + 8 * b); v; v = rd(v + 0x158)) { uint64_t md = rd(v + 0x10); if (md && (*(uint8_t *)(uintptr_t)(md + 0x1a) & 0x10) && unit_xy(v, &x, &y) && abs(x - px) + abs(y - py) <= 40) minions++; } }
|
||||
if (!dead && t % 25 == 0 && unit_xy(u, &x, &y)) dm_teleport(B, G, player, unit_room(u), x + 2, y + 2);
|
||||
if (dead || t - t0 > 600) { LOG("[验收轮] 拍 %u 行 %d 类号 %u id %u %s(刷出后 %u 拍),40 格内带随从标志的 %d 只", t, row, cls, g_suseq_id, dead ? "已死" : "【没打死】", t - t0, minions); ph = 2; t0 = t; } }
|
||||
else if (ph == 2 && t - t0 >= 40) { char ln[700]; int o = 0, n = 0; ln[0] = 0;
|
||||
for (int b = 0; b < 128; b++) for (uint64_t it = rd(G + 0x2e30 + 8 * b); it; it = rd(it + 0x158)) { uint64_t d = rd(it + 0x10); if (!d || *(uint32_t *)(uintptr_t)(it + 0xc) != 3 || *(uint32_t *)(uintptr_t)(it + 8) <= hi) continue; n++; if (o < (int)sizeof ln - 16) o += snprintf(ln + o, sizeof ln - o, " %u:%d", *(uint32_t *)(uintptr_t)(it + 4), *(int32_t *)(uintptr_t)d); }
|
||||
LOG("[验收轮] 拍 %u 行 %d 之后新掉在地上的物品 %d 件(类号:品质):%s", t, row, n, ln); g_suseq_id = 0; ph = 0; t0 = t; if (++idx == nr) LOG("[验收轮] 拍 %u 全部 %d 行走完", t, nr); } } }
|
||||
// 测试开关 DM_RIFT_TEST_SCOREAT=<拍>:<分数>:到这一拍把进度分数直接设成这个数(造「闯入首领还活着时进度满了」这类现场)
|
||||
// Test switch DM_RIFT_TEST_SCOREAT=<tick>:<score>: at this tick set the progress score directly to this number (to stage scenes such as "progress fills while an invading boss is still alive")
|
||||
{ static int at = -1, sc; if (at < 0) { const char *e = getenv("DM_RIFT_TEST_SCOREAT"); at = e ? atoi(e) : 0; const char *c = e ? strchr(e, ':') : NULL; sc = c ? atoi(c + 1) : 0; }
|
||||
if (at > 0 && t >= (uint32_t)at && atomic_load(&K.st) == ST_RUN) { at = 0; atomic_store(&K.score, sc); LOG("秘境:测试 DM_RIFT_TEST_SCOREAT 拍 %u 把进度分数设成 %d", t, sc); } }
|
||||
// 闯入首领:进度走到抽好的那一点 → 提示(约 3 秒预警)→ 在离人 36 格左右的空地刷出;生命 = 规则应得值 × 0.30;死了 +12% 进度。
|
||||
// 同一时刻最多一位;守护者出来之后不再预警 / 不再刷(已在场的那位留着,它与守护者不同类号)。它不是结算条件
|
||||
// Invading boss: progress reaches the drawn point -> message (about 3 seconds of warning) -> spawned on open ground about 36 tiles from the player; life = the rule value x 0.30; +12% progress on death.
|
||||
// At most one at a time; after the Guardians appear there are no more warnings / spawns (one already present stays; it has a different class id from the Guardians). It is not a completion condition
|
||||
if (K.inv_n && atomic_load(&K.st) == ST_RUN && in_rift_map(lv)) { int nd = atomic_load(&K.need), busy = 0; for (int i = 0; i < K.inv_n; i++) busy |= K.inv_st[i] == 1 || K.inv_st[i] == 2;
|
||||
for (int i = 0; i < K.inv_n; i++) {
|
||||
if (K.inv_st[i] == 0 && !busy && !K.guard && nd > 0 && atomic_load(&K.score) * 100 >= (long long)nd * K.inv_pct[i]) { K.inv_st[i] = 1; K.inv_t[i] = t; busy = 1; say("dmRiftSayInvader"); LOG("秘境:拍 %u 闯入首领预警(第 %d 位,类号 %d,进度 %d%%)", t, i + 1, K.inv_cls[i], K.inv_pct[i]); }
|
||||
else if (K.inv_st[i] == 1 && K.guard) { K.inv_st[i] = 4; LOG("秘境:守护者已现身,第 %d 位闯入首领作罢", i + 1); }
|
||||
else if (K.inv_st[i] == 1 && t - K.inv_t[i] >= 75) { static const int dx[8] = { 36, 26, 0, -26, -36, -26, 0, 26 }, dy[8] = { 0, 26, 36, 26, 0, -26, -36, -26 }; int x, y; unit_xy(player, &x, &y); uint64_t u = 0; int32_t pos[2] = { 0, 0 };
|
||||
for (int k = 0, d0 = rnd(8); k < 8 && !u; k++) { int d = (d0 + k) % 8; pos[0] = x + dx[d]; pos[1] = y + dy[d]; uint64_t rs = room_load(G, level_of(player), pos[0], pos[1]), rr = rs ? free_spot(G, rs, pos) : 0;
|
||||
if (!rr || abs(pos[0] - x) + abs(pos[1] - y) < 24) continue; /* 找到的空地被挪到人跟前就不要 | open ground that got moved right next to the player is not accepted */
|
||||
u = ((uint64_t (*)(uint64_t, uint64_t, int, int, int, int, int, int, uint64_t))(B + 0x7ce630))(G, rr, 1, K.inv_cls[i], pos[0], pos[1], 1, 0, 0x10); }
|
||||
if (!u) { if (t - K.inv_t[i] > 325) { K.inv_st[i] = 4; LOG("秘境:第 %d 位闯入首领 10 秒内没找到落点,作罢", i + 1); } continue; }
|
||||
K.inv_id[i] = *(uint32_t *)(uintptr_t)(u + 8); K.inv_st[i] = 2;
|
||||
if (K.tier >= 9) { g_hp_mul = 300; scale_monster(G, u, target_level(player) + 3, dm_rift_tier_level(9, gs(player, 12)) + 3); g_hp_mul = 1000; }
|
||||
LOG("秘境:拍 %u 闯入首领刷出(第 %d 位)类号 %d id %u 在 %d,%d(离人 %d 格)等级 %d 生命 %d", t, i + 1, K.inv_cls[i], K.inv_id[i], pos[0], pos[1], abs(pos[0] - x) + abs(pos[1] - y), gs(u, 12), gs(u, 7) >> 8); }
|
||||
else if (K.inv_st[i] == 2) { uint64_t u = find_unit(G, 1, K.inv_id[i]); uint32_t m = u ? *(uint32_t *)(uintptr_t)(u + 0xc) : 1;
|
||||
if (u && (m == 0 || m == 12)) { K.inv_st[i] = 3; int add = nd * 12 / (100 + 12 * K.inv_n); if (add < 1) add = 1; int sc = atomic_fetch_add(&K.score, add) + add; /* 12% 按上调前的进度需求算 | 12% is computed on the progress requirement before the increase */
|
||||
LOG("秘境:拍 %u 闯入首领死亡(第 %d 位,类号 %d)→ 进度 +%d,现 %d / %d", t, i + 1, K.inv_cls[i], add, sc, nd); } } } }
|
||||
if (!K.guard && atomic_load(&K.score) >= atomic_load(&K.need) && in_rift_map(lv)) {
|
||||
// 一位:人右下 6 格;两位:一左一右各 6 格。每位先照常按层改(守护者 = 本层怪物等级 + 3,起算层也 + 3,同吃本层总倍率),两位时再各乘 s(生命)与 d(伤害)
|
||||
// One Guardian: 6 tiles to the lower right of the player; two: 6 tiles to the left and to the right. Each is first scaled by level as usual (Guardian = this level's monster level + 3, the starting level + 3 as well, with this level's total multiplier), and with two each is additionally multiplied by s (life) and d (damage)
|
||||
static const int ox[2][2] = { { 6, 0 }, { 6, -6 } }, oy[2][2] = { { 6, 0 }, { 6, 6 } }; int x, y, n = 0; unit_xy(player, &x, &y); hs_sync();
|
||||
for (int i = 0; i < K.nplan && i < 2; i++) { int32_t pos[2] = { x + ox[K.nplan - 1][i], y + oy[K.nplan - 1][i] }; uint64_t rr = free_spot(G, unit_room(player), pos);
|
||||
uint64_t u = rr ? ((uint64_t (*)(uint64_t, uint64_t, int, int, int, int, int, int, uint64_t))(B + 0x7ce630))(G, rr, 1, K.gcls[i], pos[0], pos[1], 1, 0, 0x10) : 0;
|
||||
if (!u) { LOG("【红】秘境:守护者第 %d 位(类号 %d)没刷出来", i + 1, K.gcls[i]); continue; }
|
||||
K.guards[i] = *(uint32_t *)(uintptr_t)(u + 8); if (!K.guard) K.guard = K.guards[i]; n++;
|
||||
if (lowhp) ss(u, 6, 256); else if (K.tier >= 9) { g_hp_mul = K.nplan == 2 ? hi_duo_x1000(0) : 1000; scale_monster(G, u, target_level(player) + 3, dm_rift_tier_level(9, gs(player, 12)) + 3); g_hp_mul = 1000; }
|
||||
if (K.nplan == 2 && !lowhp) ss(u, 25, (int)((100LL + gs(u, 25)) * hi_duo_x1000(1) / 1000 - 100)); // 伤害:属性 25 是「伤害 +N%」,整体乘 d 即 (100 + N) × d − 100 | damage: stat 25 is "damage +N%", so multiplying the whole by d gives (100 + N) x d - 100
|
||||
HS.guard_hp += gs(u, 7) >> 8;
|
||||
LOG("秘境:拍 %u 刷守护者%s 类号 %d id %u 等级 %d 生命 %d 伤害百分比 %d", t, K.nplan == 2 ? (i ? "(第二位)" : "(第一位)") : "", K.gcls[i], K.guards[i], gs(u, 12), gs(u, 7) >> 8, gs(u, 25)); }
|
||||
if (n) say(K.nplan == 2 && n == 2 ? "dmRiftSayGuardians" : "dmRiftSayGuardian"); }
|
||||
// 守护者现身:还在场的闯入首领退场——守护者战期间场上只有守护者。原版没有读到能安全移除一个单位的入口,用已验证过的定点传送把它送到这张图的远处(不触发死亡 / 掉落 / 击杀计数),
|
||||
// 状态记作罢:之后它死不死都不给进度。玩家想要它的进度与掉落,就得在进度满之前解决它
|
||||
// Guardians appear: an invading boss still present leaves - during the Guardian fight only the Guardians are on the field. No entry was found in the original for safely removing a unit, so the already-verified fixed-point teleport sends it far away on this map (no death / drop / kill count is triggered),
|
||||
// and its state is recorded as called off: whether or not it dies afterwards, it gives no progress. A player who wants its progress and drops has to deal with it before progress is full
|
||||
for (int i = 0; i < K.inv_n; i++) { if (K.inv_st[i] == 1) { K.inv_st[i] = 4; continue; } if (K.inv_st[i] != 2) continue;
|
||||
static const int fx[8] = { 150, 106, 0, -106, -150, -106, 0, 106 }, fy[8] = { 0, 106, 150, 106, 0, -106, -150, -106 }; uint64_t iu = find_unit(G, 1, K.inv_id[i]); int px, py, moved = 0; unit_xy(player, &px, &py);
|
||||
for (int k = 0; iu && k < 8 && !moved && !getenv("DM_RIFT_TEST_NOFAR"); k++) { int32_t fp[2] = { px + fx[k], py + fy[k] }; /* 测试开关 DM_RIFT_TEST_NOFAR=1:当作远处没有空地,走兜底 | test switch DM_RIFT_TEST_NOFAR=1: act as if there were no open ground far away, taking the fallback */ uint64_t rs = room_load(G, level_of(player), fp[0], fp[1]), rr = rs ? free_spot(G, rs, fp) : 0;
|
||||
if (rr && abs(fp[0] - px) + abs(fp[1] - py) >= 100 && dm_teleport(B, G, iu, rr, fp[0], fp[1])) { moved = 1; LOG("秘境:拍 %u 守护者现身,闯入首领(第 %d 位,类号 %d)退场到 %d,%d(离人 %d 格),不再给进度", t, i + 1, K.inv_cls[i], fp[0], fp[1], abs(fp[0] - px) + abs(fp[1] - py)); } }
|
||||
if (!moved && iu && g_entry_lv == lv) { int32_t fp[2] = { g_entry_x, g_entry_y }; uint64_t rs = room_load(G, level_of(player), fp[0], fp[1]), rr = rs ? free_spot(G, rs, fp) : 0; // 兜底:传到玩家进这张图时的落点(一定可达) | fallback: teleport to the point where the player entered this map (always reachable)
|
||||
if (rr && dm_teleport(B, G, iu, rr, fp[0], fp[1])) { moved = 1; LOG("秘境:拍 %u 守护者现身,闯入首领(第 %d 位,类号 %d)远处没有空地,退场到本图入口 %d,%d(离人 %d 格)", t, i + 1, K.inv_cls[i], fp[0], fp[1], abs(fp[0] - px) + abs(fp[1] - py)); } }
|
||||
if (!moved) LOG("【红】秘境:拍 %u 守护者现身,闯入首领(第 %d 位)退场落点与本图入口都没传成,留在场上(作罢,不给进度)", t, i + 1);
|
||||
g_inv_gone[i] = K.inv_id[i]; if (iu) unit_xy(iu, &g_inv_gone_xy[i][0], &g_inv_gone_xy[i][1]); K.inv_st[i] = 4; K.inv_id[i] = 0; say("dmRiftSayInvaderGone"); }
|
||||
guard_wave(G, player, t, lowhp); }
|
||||
// 两波之间:上一波全倒 WAVE_GAP 拍后刷下一波
|
||||
// Between two waves: WAVE_GAP ticks after the previous wave is all down, the next wave is spawned
|
||||
if (K.wave_t && t >= K.wave_t + WAVE_GAP && atomic_load(&K.st) == ST_RUN) { guard_wave(G, player, t, lowhp); K.wave_t = 0; } /* 先刷、再清「两波之间」:顶部条在两波之间报刚打完的那一波,刷出来才跳到下一波 | spawn first, then clear "between two waves": between waves the top bar reports the wave just finished, and moves to the next wave only once it has spawned */
|
||||
// 测试替身 DM_RIFT_TEST_DUMMY=<每秒点数>:对在场的每位守护者按固定输出扣当前生命(留 1 点,由随从补最后一下)——人物不用真打,用来出「承伤每秒峰值」的相对值
|
||||
// Test stand-in DM_RIFT_TEST_DUMMY=<points per second>: deduct current life from every Guardian present at a fixed output (leaving 1 point, with a minion delivering the last hit) - the character does not have to fight for real; used to obtain relative values of the "per-second peak of damage taken"
|
||||
{ static int dps = -1; if (dps < 0) { const char *e = getenv("DM_RIFT_TEST_DUMMY"); dps = e ? atoi(e) : 0; }
|
||||
if (dps > 0) for (int i = 0; i < 2; i++) { uint64_t u = K.inv_st[i] == 2 ? find_unit(G, 1, K.inv_id[i]) : 0; uint32_t m = u ? *(uint32_t *)(uintptr_t)(u + 0xc) : 0; if (!u || m == 0 || m == 12) continue; /* 在场的闯入首领同样按固定输出扣 | an invading boss that is present is deducted at the fixed output as well */
|
||||
long long h = (long long)gs(u, 6) - (long long)dps * 256 / 25; ss(u, 6, h < 256 ? 256 : (int)h); }
|
||||
if (dps > 0 && K.guard && !atomic_load(&K.guard_dead)) for (int i = 0; i < 3; i++) { uint64_t u = K.guards[i] ? find_unit(G, 1, K.guards[i]) : 0; uint32_t m = u ? *(uint32_t *)(uintptr_t)(u + 0xc) : 0; if (!u || m == 0 || m == 12) continue;
|
||||
long long h = (long long)gs(u, 6) - (long long)dps * 256 / 25; ss(u, 6, h < 256 ? 256 : (int)h); } }
|
||||
// 结算条件:本场刷出的守护者全部死亡。任一位还活着(或还在单位表里没判死)都不结算、不开门
|
||||
// Completion condition: all the Guardians spawned in this run are dead. While any one is alive (or still in the unit table and not judged dead) there is no completion and no door
|
||||
if (K.guard && !atomic_load(&K.guard_dead)) { int alive = 0; uint64_t last = 0;
|
||||
if (K.guard && !atomic_load(&K.guard_dead)) { int alive = 0, deadn = 0; uint64_t last = 0;
|
||||
for (int i = 0; i < 3; i++) { if (!K.guards[i]) continue; uint64_t u = find_unit(G, 1, K.guards[i]); if (!u) { alive++; continue; } /* 不在单位表里(房间卸载):不当它死了 | not in the unit table (room unloaded): do not treat it as dead */
|
||||
uint32_t m = *(uint32_t *)(uintptr_t)(u + 0xc); if (m == 0 || m == 12) { last = u; static uint32_t said[3]; if (said[i] != K.guards[i]) { said[i] = K.guards[i]; LOG("秘境:拍 %u 守护者死亡(类号 %d id %u)", t, K.gcls[i], K.guards[i]); } } else alive++; }
|
||||
if (!alive && last) { atomic_store(&K.guard_dead, 1); LOG("秘境:拍 %u 守护者全部死亡 → 结算", t); finish(G, player, last); } }
|
||||
uint32_t m = *(uint32_t *)(uintptr_t)(u + 0xc); if (m == 0 || m == 12) { last = u; deadn++; static uint32_t said[3]; if (said[i] != K.guards[i]) { said[i] = K.guards[i]; LOG("秘境:拍 %u 守护者死亡(类号 %d id %u)", t, K.gcls[i], K.guards[i]); } } else alive++; }
|
||||
if (!K.wave_t) atomic_store(&K.gdead, deadn); /* 两波之间 guards 已清空,计数留着上一波的(全倒)给顶部条 | between two waves guards is already cleared; the count keeps the previous wave's (all down) for the top bar */
|
||||
if (!alive && last && K.wave + 1 < K.nwave) { memset(K.guards, 0, sizeof K.guards); K.wave++; K.wave_t = t; LOG("秘境:拍 %u 守护者第 %d 波全部倒下,%d 拍后刷第 %d 波", t, K.wave, WAVE_GAP, K.wave + 1); }
|
||||
else if (!alive && last) { atomic_store(&K.guard_dead, 1); LOG("秘境:拍 %u 守护者全部死亡 → 结算", t); finish(G, player, last); } }
|
||||
}
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
// Rift tower climb (dm_rift.c)
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
typedef struct { int tier; float progress; int secs_left, done, guardian, inc, next, overtime; } dm_rift_hud_t; // overtime = 进行中且限时已到(还能打完拿掉落,不计通关);与菜单里的同名量同源;next = 本层完成后下一次打第几层(封顶 100;等于 tier = 不涨:超时,或已在最高层)。显示方只读它,不自己用 tier + inc 算 | overtime = in progress and the time limit has passed (can still be finished for loot, does not count as a clear); the same source as the quantity of the same name in the menu; next = which level will be played after this one is completed (capped at 100; equal to tier = no increase: overtime, or already at the highest level). Display code only reads it and does not compute tier + inc itself
|
||||
typedef struct { int tier; float progress; int secs_left, done, guardian, inc, next, overtime, goal, gdead, gtotal, wave, nwave; } dm_rift_hud_t; /* goal = 没结算时第二行该写哪一句(宿主定,显示方只照着选串):0 进度目标、1 击败守护者、2 击败守护者(已倒 / 总数)、3 已超时、4 已超时 + 击败守护者、5 已超时 + 击败守护者(已倒 / 总数);gdead / gtotal = 已倒下与本场已刷出的守护者数 | goal = which sentence the second line should show before completion (decided by the host; the display only picks the string accordingly): 0 progress goal, 1 slay the Guardian, 2 slay the Guardians (fallen / total), 3 overtime, 4 overtime + slay the Guardian, 5 overtime + slay the Guardians (fallen / total); gdead / gtotal = Guardians fallen and Guardians spawned this run */ // overtime = 进行中且限时已到(还能打完拿掉落,不计通关);与菜单里的同名量同源;next = 本层完成后下一次打第几层(封顶 100;等于 tier = 不涨:超时,或已在最高层)。显示方只读它,不自己用 tier + inc 算 | overtime = in progress and the time limit has passed (can still be finished for loot, does not count as a clear); the same source as the quantity of the same name in the menu; next = which level will be played after this one is completed (capped at 100; equal to tier = no increase: overtime, or already at the highest level). Display code only reads it and does not compute tier + inc itself
|
||||
void dm_rift_tick(uint64_t G, uint64_t player, uint8_t *main_base); // 服务端拍(diag.c) | Server tick (diag.c)
|
||||
void dm_rift_c2s(uint64_t G, const uint8_t *pkt, uint32_t len); // 客户端命令(点门) | Client command (door tap)
|
||||
void dm_rift_client_pump(uint8_t *main_base); // 取手柄处(dm_world.c):认击杀、新刷出的怪 | At the controller sampling point (dm_world.c): recognize kills and newly spawned monsters
|
||||
|
||||
+65
-20
@@ -8,6 +8,7 @@
|
||||
#include <sys/sysctl.h>
|
||||
#import <QuartzCore/QuartzCore.h>
|
||||
#import <Metal/Metal.h>
|
||||
#import <ImageIO/ImageIO.h>
|
||||
#include "dm.h"
|
||||
#include "dm_input.h"
|
||||
#include "dm_uiscreen.h"
|
||||
@@ -23,35 +24,50 @@ static int g_live; // App 形态(或 DM_TOUCH_LIVE=1):鼠标进我们的
|
||||
static CAMetalLayer *g_layer;
|
||||
static NSWindow *g_win;
|
||||
static NSView *g_view;
|
||||
// 窗口不是 16:9(拉伸窗口、全屏到 16:10 的屏):游戏画面保持 16:9 居中,四周留黑边;鼠标位置按游戏画面这一块算
|
||||
// The window is not 16:9 (stretched window, full screen on a 16:10 display): the game picture stays 16:9 and centred with black bars around it; the mouse position is computed against the game picture
|
||||
// 真全屏(App 形态,屏幕比 16:9 窄——16:10 的 MacBook,「不能全屏」:全屏后上下各 56 点黑边):照 iPad 那套(front_ios.m、dm_uiscreen.c)——
|
||||
// 启动时按屏幕比例(全屏时的内容区:屏幕扣掉刘海安全区)定游戏分辨率,局内 3D 铺满、界面按 16:9 贴底(开大面板居中),前端各页与读取画面游戏自己按 16:9 出、上下留边。
|
||||
// 窗口锁成同一比例,窗口态与全屏态都铺满。屏幕不比 16:9 窄(外接 16:9 / 更宽的屏):照旧全程 16:9。比例在启动时按主屏定,之后挪到别的屏不重算(游戏分辨率只在启动时定)。
|
||||
// 测试开关 DM_TEST_SCREEN_ASPECT=<宽>x<高>:当作主屏是这个比例(16x9 = 外接 16:9 屏的口径)
|
||||
// True full screen (App form, screen narrower than 16:9 - a 16:10 MacBook, "cannot go full screen": 56 points of black bar above and below in full screen): the iPad approach (front_ios.m, dm_uiscreen.c) -
|
||||
// at launch the game resolution is set from the screen's aspect ratio (the full-screen content area: the screen minus the notch safe area); in game the 3D fills the screen, the interface is 16:9 along the bottom (centred with a large panel open), and the front-end pages and the loading screen are drawn by the game at 16:9 with bars above and below.
|
||||
// The window is locked to the same ratio, so both windowed and full screen are filled. Screens not narrower than 16:9 (external 16:9 / wider screens): 16:9 throughout as before. The ratio is set from the main screen at launch and not recomputed when moved to another screen (the game resolution is only set at launch).
|
||||
// Test switch DM_TEST_SCREEN_ASPECT=<w>x<h>: treat the main screen as this ratio (16x9 = the external 16:9 screen case)
|
||||
static double g_aspect = 16.0 / 9; // 游戏画面比例(宽 ÷ 高) | aspect ratio of the game picture (width / height)
|
||||
static int g_full; // 1 = 真全屏已开 | 1 = true full screen is on
|
||||
static void full_setup(void) {
|
||||
if (!getenv("DM_APP") || getenv("DM_GAME_RES")) return;
|
||||
NSScreen *sc = NSScreen.mainScreen; double w = sc.frame.size.width, h = sc.frame.size.height - sc.safeAreaInsets.top; const char *e = getenv("DM_TEST_SCREEN_ASPECT"); unsigned tw, th;
|
||||
if (e && sscanf(e, "%ux%u", &tw, &th) == 2 && tw && th) { w = tw; h = th; }
|
||||
if (h <= 0 || w / h >= 16.0 / 9 - 0.01) { LOG("画面:主屏 %.0fx%.0f 不比 16:9 窄 → 全程 16:9", w, h); return; }
|
||||
g_aspect = w / h; g_full = 1; dm_uiscreen_enable(DM_UISCREEN_BOTTOM);
|
||||
LOG("画面:主屏全屏内容区 %.0fx%.0f(比例 %.3f)比 16:9 窄 → 真全屏:窗口锁这个比例,局内铺满、界面贴底,前端 16:9 留边", w, h, g_aspect);
|
||||
}
|
||||
// 游戏画面在视图里的位置:按游戏画面比例放进视图(比例对得上就是整个视图;对不上的四周留黑边)
|
||||
// Where the game picture sits in the view: fitted into the view by the picture's aspect ratio (if the ratios match, the whole view; otherwise black bars around)
|
||||
static NSRect game_rect(void) {
|
||||
NSSize b = g_view.bounds.size; CGFloat w = b.width, h = b.height;
|
||||
if (w * 9 > h * 16) w = floor(h * 16 / 9); else h = floor(w * 9 / 16);
|
||||
if (fabs(w / h / g_aspect - 1) < 0.003) { } // 比例差 0.3% 以内(窗口高取整的零头、全屏内容区比按刘海安全区算的少 1 点)当对得上,铺满 | within 0.3% (the remainder from rounding the window height, and the full-screen content area being 1 point less than computed from the notch safe area) counts as matching, and it fills
|
||||
else if (w > h * g_aspect) w = round(h * g_aspect); else h = round(w / g_aspect);
|
||||
return NSMakeRect(floor((b.width - w) / 2), floor((b.height - h) / 2), w, h);
|
||||
}
|
||||
static void layout_game(void) {
|
||||
NSRect r = game_rect(); if (NSEqualRects(r, g_layer.frame)) return;
|
||||
[CATransaction begin]; [CATransaction setDisableActions:YES]; g_layer.frame = r; g_layer.contentsScale = g_view.window.backingScaleFactor; [CATransaction commit];
|
||||
CGFloat sc = g_view.window.backingScaleFactor ?: 2; // 画布跟着改:作为子层的 CAMetalLayer 改 frame 不会自己改 drawableSize,原先进全屏后一直用窗口态的画布放大显示(发糊) | the canvas follows: a CAMetalLayer used as a sublayer does not change its drawableSize when its frame changes, so after going full screen it used to keep the windowed canvas and scale it up (blurry)
|
||||
[CATransaction begin]; [CATransaction setDisableActions:YES]; g_layer.frame = r; g_layer.contentsScale = sc; g_layer.drawableSize = CGSizeMake(round(r.size.width * sc), round(r.size.height * sc)); [CATransaction commit];
|
||||
LOG("窗口:内容区 %.0f×%.0f,游戏画面 %.0f×%.0f 放在 (%.0f,%.0f)", g_view.bounds.size.width, g_view.bounds.size.height, r.size.width, r.size.height, r.origin.x, r.origin.y);
|
||||
}
|
||||
// 退出(关窗口 / ⌘Q / 菜单):有局在就先请游戏走一次它自己的存盘并等存档提交(做法同 iOS 壳进后台),最多 3 秒,再有序收尾。
|
||||
// 暂停菜单 / 大秘境面板开着时游戏停拍:先放开暂停让拍走起来;读取画面里等它进到局内再请。3 秒到了还没有提交就照实记「未存盘退出」
|
||||
// Quit (closing the window / ⌘Q / menu): if a game is in progress, first ask the game to do its own save and wait for the save to be committed (the same way the iOS shell does when going to the background), for at most 3 seconds, then shut down in order.
|
||||
// With the pause menu / rift panel open the game is not ticking: release the pause first so the ticks run; in a loading screen wait until it is in the game, then ask. If nothing is committed when the 3 seconds are up, truthfully log "quit without saving"
|
||||
// 暂停菜单 / 大秘境面板开着时游戏停拍:冻住世界、临时放开暂停存这一次(diag.c dm_save_wait,与 iOS 进后台同一个函数);读取画面里等它进到局内再请。3 秒到了还没有提交就照实记「未存盘退出」
|
||||
// Quit (close window / Cmd-Q / menu): if a game is running, first ask the game to do one of its own saves and wait for the save commit (same as the iOS shell going to the background), at most 3 s, then shut down in order.
|
||||
// When the pause menu / Greater Rift panel is open the game does not tick: freeze the world and temporarily release the pause for this one save (diag.c dm_save_wait, the same function as iOS going to the background); on the loading screen wait until in game before asking. If there is still no commit after 3 s, log "quit without saving" as is
|
||||
static void app_quit(const char *why) {
|
||||
static int once; if (once++) return;
|
||||
int dm_ingame_now(void); int dm_request_save(void); int dm_unpause_for_exit(void); uint64_t dm_fs_commit_count(void); uint64_t now_ns(void);
|
||||
{ uint64_t dm_audio_render_calls(void); LOG("窗口:退出(%s);声卡回调累计 %llu(0 = 这次没出声)", why, (unsigned long long)dm_audio_render_calls()); }
|
||||
int dm_ingame_now(void); int dm_save_wait(double max_s, uint64_t *commits, int *froze, double *ms);
|
||||
if (!dm_ingame_now() && !dm_uiscreen_ingame()) { LOG("窗口:退出(不在局内,没有待存的进度)"); dm_host_shutdown(why); return; }
|
||||
uint64_t c0 = dm_fs_commit_count(), t0 = now_ns(), last = c0, last_t = 0; int asked = 0, paused = 0;
|
||||
for (;;) {
|
||||
paused |= dm_unpause_for_exit(); if (!asked) asked = dm_request_save();
|
||||
usleep(20000); uint64_t c = dm_fs_commit_count(), t = now_ns();
|
||||
if (c != last) { last = c; last_t = t; }
|
||||
if ((asked && last_t && t - last_t >= 200000000ull) || t - t0 >= 3000000000ull) break;
|
||||
}
|
||||
if (last != c0 && asked) LOG("窗口:退出前等游戏存盘 %.0f ms,期间存档提交 %llu 次%s", (now_ns() - t0) / 1e6, (unsigned long long)(last - c0), paused ? "(原先停在暂停菜单 / 面板,已放开)" : "");
|
||||
else LOG("【红】窗口:未存盘退出——3 秒内没等到存档提交(%s%s)", asked ? "已请游戏存盘" : "一直没到能请存盘的状态(读取画面?)", paused ? ",原先暂停着、已放开" : "");
|
||||
uint64_t n = 0; int froze = 0; double ms = 0; int asked = dm_save_wait(3, &n, &froze, &ms);
|
||||
if (n && asked) LOG("窗口:退出前等游戏存盘 %.0f ms,期间存档提交 %llu 次%s", ms, (unsigned long long)n, froze ? "(原先暂停着:冻结世界存盘、已恢复暂停)" : "");
|
||||
else LOG("【红】窗口:未存盘退出——3 秒内没等到存档提交(%s%s)", asked ? "已请游戏存盘" : "一直没到能请存盘的状态(读取画面?)", froze ? ",原先暂停着、冻结放开过" : "");
|
||||
{ int dm_cloud_flush_wait(double sec); dm_cloud_flush_wait(10); } // 存盘之后把这一局传上 iCloud 再退(没开同步时立即返回) | after saving, upload this session to iCloud before quitting (returns immediately when sync is off)
|
||||
dm_host_shutdown(why);
|
||||
}
|
||||
@@ -112,6 +128,7 @@ void *front_metal_layer(void) { return (__bridge void *)g_layer; }
|
||||
uint64_t front_game_res(int docked) {
|
||||
unsigned w, h; const char *e = getenv("DM_GAME_RES");
|
||||
if (e && sscanf(e, "%ux%u", &w, &h) == 2) return docked ? (uint64_t)h << 32 | w : (uint64_t)(h * 4 / 5) << 32 | (w * 4 / 5 + 3) / 4 * 4;
|
||||
if (g_full) return docked ? (uint64_t)(llround(1600 / g_aspect / 2) * 2) << 32 | 1600 : 720ull << 32 | (uint64_t)(llround(720 * g_aspect / 8) * 8); // 真全屏:宽 1600、高按屏幕比例(16:10 → 1600x1004) | true full screen: width 1600, height by the screen's aspect ratio (16:10 -> 1600x1004)
|
||||
return docked ? 900ull << 32 | 1600 : 720ull << 32 | 1280;
|
||||
}
|
||||
|
||||
@@ -155,14 +172,15 @@ void front_run(void (*guest)(void)) {
|
||||
@autoreleasepool {
|
||||
[NSApplication sharedApplication];
|
||||
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
|
||||
NSRect r = NSMakeRect(0, 0, 1280, 720);
|
||||
full_setup();
|
||||
NSRect r = NSMakeRect(0, 0, 1280, floor(1280 / g_aspect));
|
||||
NSWindow *win = [[NSWindow alloc] initWithContentRect:r
|
||||
styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable
|
||||
backing:NSBackingStoreBuffered defer:NO];
|
||||
win.title = @"D2R Mobile"; win.restorable = NO; g_win = win;
|
||||
NSView *v = win.contentView; g_view = v;
|
||||
v.wantsLayer = YES; v.layer.backgroundColor = CGColorGetConstantColor(kCGColorBlack);
|
||||
win.collectionBehavior = NSWindowCollectionBehaviorFullScreenPrimary; win.contentMinSize = NSMakeSize(640, 360);
|
||||
win.collectionBehavior = NSWindowCollectionBehaviorFullScreenPrimary; win.contentMinSize = NSMakeSize(640, floor(640 / g_aspect)); if (g_full) win.contentAspectRatio = NSMakeSize(1280, 1280 / g_aspect);
|
||||
static DmWinCtl *ctl; ctl = [DmWinCtl new]; win.delegate = ctl;
|
||||
g_layer = [CAMetalLayer layer];
|
||||
g_layer.device = MTLCreateSystemDefaultDevice();
|
||||
@@ -196,6 +214,18 @@ void front_run(void (*guest)(void)) {
|
||||
if (gr.size.width <= 0 || gr.size.height <= 0) return e;
|
||||
float nx = (float)((p.x - gr.origin.x) / gr.size.width), ny = (float)(1.0 - (p.y - gr.origin.y) / gr.size.height); // AppKit 视图原点在左下,触屏原点在左上 | The AppKit view origin is at bottom left, the touchscreen origin is at top left
|
||||
if (e.type == NSEventTypeLeftMouseDown && (nx < 0 || nx > 1 || ny < 0 || ny > 1)) return nil; // 按在黑边上:不算点 | Pressed on the black bars: not a click
|
||||
if (g_full && g_live) { // 真全屏:状态机吃界面矩形里的归一化坐标(同 iOS 的游戏视图)。两步: | true full screen: the state machine takes normalised coordinates inside the interface rectangle (like the iOS game view). Two steps:
|
||||
// ① 先换到「实际显示的那块」:游戏当前分辨率(前端 16:9、局内整屏)按比例居中放进游戏画面,与上屏同一口径(nvn_mtl.m present_encode:比例差 1% 内铺满);
|
||||
// ② 再换到界面矩形(局内贴底)。局内界面矩形外是 3D 世界,带符号交下去(点世界换回整屏,touch_mac.c);不在局内时显示块外是黑边,不算点
|
||||
// (1) First map to "the block actually shown": the game's current resolution (16:9 in the front end, the whole screen in game) placed centred in the game picture by aspect ratio, the same measure as presentation (nvn_mtl.m present_encode: fill when the aspect ratios differ by less than 1%);
|
||||
// (2) then map to the interface rectangle (along the bottom in game). In game, outside the interface rectangle is the 3D world, passed down with a sign (tapping the world maps back to the whole screen, touch_mac.c); outside the game the area beyond the shown block is the black bars, not counted as a tap
|
||||
int rw = 0, rh = 0; double cx = 0, cy = 0, cw = 1, ch = 1;
|
||||
if (dm_screen_real(&rw, &rh) && rw > 0 && rh > 0) { double ca = (double)rw / rh, ga = gr.size.width / gr.size.height;
|
||||
if (fabs(ga / ca - 1) >= 0.01) { if (ga > ca) { cw = ca / ga; cx = (1 - cw) / 2; } else { ch = ga / ca; cy = (1 - ch) / 2; } } }
|
||||
float vx = (float)((nx - cx) / cw), vy = (float)((ny - cy) / ch);
|
||||
double fy = 0, fh = 1; ui_rect_frac(&fy, &fh); float uy = fh > 0 ? (float)((vy - fy) / fh) : vy;
|
||||
if (e.type == NSEventTypeLeftMouseDown && !dm_uiscreen_ingame() && (vx < 0 || vx > 1 || uy < 0 || uy > 1)) return nil;
|
||||
dm_touch_host_live(e.type == NSEventTypeLeftMouseDown ? 0 : 1, vx, uy); return nil; }
|
||||
dm_touch t = {0, nx < 0 ? 0 : nx > 1 ? 1 : nx, ny < 0 ? 0 : ny > 1 ? 1 : ny};
|
||||
if (g_live) { dm_touch_host_live(e.type == NSEventTypeLeftMouseDown ? 0 : 1, t.x, t.y); return nil; }
|
||||
dm_touch_set(&t, 1); return nil;
|
||||
@@ -218,7 +248,22 @@ void front_run(void (*guest)(void)) {
|
||||
if (getenv("DM_APP") && !getenv("DM_APP_ROMFS") && ![NSUserDefaults.standardUserDefaults boolForKey:@"KeysShown"]) { show_keys(); [NSUserDefaults.standardUserDefaults setBool:YES forKey:@"KeysShown"]; } // 第一次启动给一次键位对照(界面上的按键提示是手柄字母);以后在「帮助」菜单里 | Show the key mapping once on first launch (button prompts on screen are gamepad letters); afterwards it is in the Help menu
|
||||
{ const char *e; // 测试(没人点窗口时用):DM_TEST_WINSIZE=宽x高 设内容区大小;DM_TEST_FULLSCREEN_AT=<秒> 进全屏;DM_TEST_QUIT_AT=<秒> 走一次退出 | Tests (for when nobody is there to click the window): DM_TEST_WINSIZE=WxH sets the content size; DM_TEST_FULLSCREEN_AT=<seconds> enters full screen; DM_TEST_QUIT_AT=<seconds> goes through one quit
|
||||
int w, h; if ((e = getenv("DM_TEST_WINSIZE")) && sscanf(e, "%dx%d", &w, &h) == 2) { [win setContentSize:NSMakeSize(w, h)]; layout_game(); }
|
||||
if ((e = getenv("DM_TEST_FULLSCREEN_AT"))) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(atof(e) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [win toggleFullScreen:nil]; });
|
||||
if ((e = getenv("DM_TEST_FULLSCREEN_AT"))) for (const char *q = e; q && *q; q = strchr(q, ';') ? strchr(q, ';') + 1 : NULL) // 「秒[;秒…]」:每个时刻切一次全屏(来回切) | "seconds[;seconds...]": toggle full screen at each time (back and forth)
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(atof(q) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [win toggleFullScreen:nil]; });
|
||||
// DM_TEST_PRESENT_SHOT=<秒>:<路径>[;<秒>:<路径>…]:到点取下一次上屏的画面(图形层与上屏同一套编码,见 nvn_mtl.m mtl_grab_next_present)写成 PNG——
|
||||
// 看的是玩家真看到的(含留边位置),不是游戏出图贴图(DM_NVN_SHOT_UI 取的那张,裁切区不居中)
|
||||
// DM_TEST_PRESENT_SHOT=<seconds>:<path>[;<seconds>:<path>...]: at the given time, grab the next presented picture (the graphics layer uses the same encoding as presentation, see nvn_mtl.m mtl_grab_next_present) and write it as PNG -
|
||||
// this is what the player actually sees (including where the bars are), not the game's output texture (the one DM_NVN_SHOT_UI takes, whose crop is not centred)
|
||||
if ((e = getenv("DM_TEST_PRESENT_SHOT"))) { void mtl_grab_next_present(void (^cb)(CGImageRef img));
|
||||
for (NSString *it in [@(e) componentsSeparatedByString:@";"]) { NSRange c = [it rangeOfString:@":"]; if (c.location == NSNotFound) continue;
|
||||
double at = [it substringToIndex:c.location].doubleValue; NSString *path = [it substringFromIndex:c.location + 1];
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(at * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
|
||||
NSSize vb = v.bounds.size; NSRect gr = game_rect(); double fy = 0, fh = 1; ui_rect_frac(&fy, &fh);
|
||||
mtl_grab_next_present(^(CGImageRef img) { if (!img) { LOG("【红】DM_TEST_PRESENT_SHOT:%s 没取到", path.UTF8String); return; }
|
||||
CGImageDestinationRef d = CGImageDestinationCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:path], (__bridge CFStringRef)@"public.png", 1, NULL);
|
||||
if (d) { CGImageDestinationAddImage(d, img, NULL); CGImageDestinationFinalize(d); CFRelease(d); }
|
||||
LOG("DM_TEST_PRESENT_SHOT:%s %zux%zu(内容区 %.0fx%.0f,游戏画面 %.0fx%.0f 在 (%.0f,%.0f),界面矩形纵向 %.3f 高 %.3f,%s)", path.UTF8String, CGImageGetWidth(img), CGImageGetHeight(img),
|
||||
vb.width, vb.height, gr.size.width, gr.size.height, gr.origin.x, gr.origin.y, fy, fh, dm_uiscreen_ingame() ? "局内" : "局外"); }); }); } }
|
||||
// DM_TEST_NSMOUSE=<文件>:合成真正的系统鼠标事件(NSEvent)投进 App 的事件队列,走与真人点击同一条分发路(事件监视器 → 换算 → 状态机),不经测试入口。
|
||||
// 每行「秒 down|move|up x,y」,x,y 是内容区里的点(左上角为原点;窗口缺省 1280×720),时刻自窗口建好起算
|
||||
// DM_TEST_NSMOUSE=<file>: 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.
|
||||
|
||||
+2
-2
@@ -9,7 +9,7 @@
|
||||
typedef struct { const char *name; void *fn; } hle_ent;
|
||||
#define HLE(mangled, ret, cname, ...) \
|
||||
static ret cname(__VA_ARGS__); \
|
||||
__attribute__((used, section("__DATA,swhle"))) static const hle_ent hle_ent_##cname = {mangled, (void *)cname}; \
|
||||
__attribute__((used, DM_SECT("swhle"))) static const hle_ent hle_ent_##cname = {mangled, (void *)cname}; \
|
||||
static ret cname(__VA_ARGS__)
|
||||
|
||||
typedef uint32_t Result; // nn::Result:w0,0 = 成功 | nn::Result: w0, 0 = success
|
||||
@@ -39,7 +39,7 @@ void guest_clock_freeze_for(int reason, int on); // 按原因冻结(1 后台
|
||||
typedef struct { const char *name; void *fn; const char *why; } hle_force_ent;
|
||||
#define HLE_FORCE(mangled, why, ret, cname, ...) \
|
||||
static ret cname(__VA_ARGS__); \
|
||||
__attribute__((used, section("__DATA,swforce"))) static const hle_force_ent hle_force_##cname = {mangled, (void *)cname, why}; \
|
||||
__attribute__((used, DM_SECT("swforce"))) static const hle_force_ent hle_force_##cname = {mangled, (void *)cname, why}; \
|
||||
static ret cname(__VA_ARGS__)
|
||||
|
||||
// 运行模式(0 掌机 / 1 主机):hle_oe.c 持有,hid 的手柄样式跟它走;前端可在运行中切换
|
||||
|
||||
+189
-16
@@ -1,13 +1,38 @@
|
||||
// nn::audio AudioOut:游戏(FMOD nx 输出层)按块追加 PCM 缓冲,播完由系统放回「已释放」队列并触发事件。
|
||||
// 宿主:真出声 = CoreAudio AudioUnit(Mac DefaultOutput / iOS RemoteIO);静音接收端 = 按真实时间消耗缓冲(不出声,节奏与真机一致)。
|
||||
// iOS 缺省真出声(产品必须有声音),测试要静音显式 DM_AUDIO=0;Mac 缺省静音接收端(回放 / 闸门不出声),DM_AUDIO=1 真出声。
|
||||
// iOS 缺省真出声(产品必须有声音),测试要静音显式 DM_AUDIO=0;Mac 命令行宿主缺省静音接收端(回放 / 闸门不出声),DM_AUDIO=1 真出声;
|
||||
// Mac App(app_mac.m)是产品,启动时设 DM_AUDIO=1(「没有声音」:之前 App 也走了命令行的缺省,从来不出声)。
|
||||
// 声卡打不开(没有输出设备等)不再退出:记红,这一路改由静音接收端按实时消耗,游戏照常跑。
|
||||
// AudioOut / AudioOutBuffer / AudioOutParameter 的内容只经下列接口读写,宿主自定内部布局,只写结构体前部。
|
||||
// nn::audio AudioOut: the game (FMOD nx output layer) appends PCM buffers block by block; once played the system puts them back on the "released" queue and signals the event.
|
||||
// Host: real audio output = CoreAudio AudioUnit (Mac DefaultOutput / iOS RemoteIO); silent sink = consumes buffers in real time (no sound, pacing matches the real device).
|
||||
// iOS defaults to real audio output (the product must have sound), tests that want silence set DM_AUDIO=0 explicitly; Mac defaults to the silent sink (replay / gate checks are silent), DM_AUDIO=1 for real audio output.
|
||||
// The contents of AudioOut / AudioOutBuffer / AudioOutParameter are read and written only through the interfaces below; the host defines its own internal layout and only writes the front part of the structs.
|
||||
// nn::audio AudioOut: the game (FMOD's nx output layer) appends PCM buffers in blocks; once played the system puts them back on the "released" queue and signals an event.
|
||||
// Host: real sound = CoreAudio AudioUnit (Mac DefaultOutput / iOS RemoteIO); silent sink = buffers consumed in real time (no sound, same pacing as the device).
|
||||
// iOS plays real sound by default (the product must have sound), tests set DM_AUDIO=0 explicitly for silence; the Mac command-line host defaults to the silent sink (replays / gates are silent), DM_AUDIO=1 for real sound;
|
||||
// the Mac App (app_mac.m) is the product and sets DM_AUDIO=1 at launch ("no sound": the App used to take the command-line default and never played sound).
|
||||
// If the sound card cannot be opened (no output device etc.) it no longer exits: logs red, and this channel is consumed in real time by the silent sink while the game runs on.
|
||||
// The contents of AudioOut / AudioOutBuffer / AudioOutParameter are read and written only through the interfaces below; the host defines its own internal layout and writes only the front part of each struct.
|
||||
#include "hle.h"
|
||||
#if defined(__APPLE__)
|
||||
#include <AudioToolbox/AudioToolbox.h>
|
||||
#elif defined(__ANDROID__)
|
||||
// Android:出声端 = AAudio 流(数据回调拉同一条待播队列);句柄借 AudioUnit 这个名字,开 / 起 / 停 / 关见下方 au_open 一节
|
||||
// Android: the output = an AAudio stream (its data callback pulls the same pending queue); the handle borrows the AudioUnit name, open / start / stop / close are in the au_open section below
|
||||
#include <aaudio/AAudio.h>
|
||||
typedef AAudioStream *AudioUnit;
|
||||
typedef int OSStatus;
|
||||
static OSStatus AudioOutputUnitStart(AudioUnit au);
|
||||
static OSStatus AudioOutputUnitStop(AudioUnit au);
|
||||
#define AudioUnitUninitialize(au) 0
|
||||
#define AudioComponentInstanceDispose(au) AAudioStream_close(au)
|
||||
#else
|
||||
// Linux:真出声后端没接,只有静音接收端;AudioUnit 句柄恒空,下列调用不会走到
|
||||
// Linux: no real audio backend, only the silent sink; the AudioUnit handle is always null and the calls below are never reached
|
||||
typedef void *AudioUnit;
|
||||
typedef int OSStatus;
|
||||
#define AudioOutputUnitStart(au) 0
|
||||
#define AudioOutputUnitStop(au) 0
|
||||
#define AudioUnitUninitialize(au) 0
|
||||
#define AudioComponentInstanceDispose(au) 0
|
||||
#endif
|
||||
#include <TargetConditionals.h>
|
||||
#include <dispatch/dispatch.h>
|
||||
#include <stdatomic.h>
|
||||
@@ -27,6 +52,13 @@ typedef struct {
|
||||
gbuf *rel[RELMAX]; _Atomic uint32_t rel_head, rel_tail; // 已释放:出声端写,游戏侧读 | Released: written by the output side, read by the game side
|
||||
uint64_t pos; // 当前块已播字节 | Bytes already played of the current block
|
||||
AudioUnit au;
|
||||
#if defined(__ANDROID__)
|
||||
int out_ch; // 流的声道数:设备收原声道数就等于 ch,否则 2(回调里自己下混) | the stream's channel count: equal to ch when the device takes the original count, otherwise 2 (downmixed in the callback)
|
||||
_Atomic int lost; // 设备断开(换耳机 / 蓝牙):等普通线程重开 | device disconnected (headphones / Bluetooth switch): waiting for an ordinary thread to reopen
|
||||
#else
|
||||
int mix; // 1 = 游戏给 5.1(6 声道),交给 CoreAudio 前我们自己下混成双声道(au_render) | 1 = the game gives 5.1 (6 channels), downmixed to stereo by us before handing to CoreAudio (au_render)
|
||||
#endif
|
||||
int16_t *mixbuf; // 下混用的暂存(ch 声道) | staging for the downmix (ch channels)
|
||||
pthread_t null_th; _Atomic int null_run;
|
||||
dispatch_semaphore_t notify_sem;
|
||||
pthread_t notify_th; _Atomic int notify_run, notify_pending, notify_armed;
|
||||
@@ -89,14 +121,40 @@ static void pull(aout *a, uint8_t *dst, uint64_t n) {
|
||||
|
||||
static _Atomic uint64_t g_render_calls; // 声卡回调累计(生命周期验证:恢复后须继续增长) | Cumulative sound card callbacks (lifecycle verification: must keep growing after resume)
|
||||
uint64_t dm_audio_render_calls(void) { return atomic_load_explicit(&g_render_calls, memory_order_relaxed); }
|
||||
#if defined(__APPLE__)
|
||||
// 5.1 → 双声道(公开 的:原先把游戏的 6 声道原样交给 AudioUnit、不设声道布局,系统隐式转换只取前两路,中置——NPC 对白——整路丢掉)。
|
||||
// 游戏的声道顺序(Mac App 走到阿卡拉跟前、对白开口那半秒按声道量能量实测:只有第 3 路跳起来):左前、右前、中置、低音、左后、右后。
|
||||
// 系数照 ITU-R BS.775 的 Lo/Ro:L = 左前 + 0.707·中置 + 0.707·左后,R 对称;低音不并入(标准下混不含 LFE,并进去会让低频发闷);
|
||||
// 整体再乘 0.707 留 3 dB 余量,仍超出 16 位的饱和截断。Q15 定点:0.707 = 23170,0.707 × 0.707 = 16384
|
||||
// 5.1 -> stereo (previously: the game's 6 channels were handed to the AudioUnit as is without a channel layout; the system's implicit conversion took only the first two, and the centre - NPC dialogue - was dropped entirely).
|
||||
// The game's channel order (measured in the Mac App by per-channel energy during the half second Akara starts speaking: only channel 3 jumps): front left, front right, centre, LFE, rear left, rear right.
|
||||
// Coefficients from the ITU-R BS.775 Lo/Ro downmix: L = front left + 0.707*centre + 0.707*rear left, R symmetric; LFE is not mixed in (the standard downmix excludes LFE, and mixing it in muddies the low end);
|
||||
// the whole is multiplied by 0.707 again for 3 dB of headroom, and anything still beyond 16 bits is saturated. Q15 fixed point: 0.707 = 23170, 0.707 x 0.707 = 16384
|
||||
#define MIXMAX 4096
|
||||
static void downmix51(const int16_t *in, int16_t *out, unsigned frames) {
|
||||
for (unsigned i = 0; i < frames; i++, in += 6, out += 2) {
|
||||
int32_t l = (23170 * in[0] + 16384 * in[2] + 16384 * in[4]) >> 15, r = (23170 * in[1] + 16384 * in[2] + 16384 * in[5]) >> 15;
|
||||
out[0] = (int16_t)(l > 32767 ? 32767 : l < -32768 ? -32768 : l); out[1] = (int16_t)(r > 32767 ? 32767 : r < -32768 ? -32768 : r); }
|
||||
}
|
||||
static OSStatus au_render(void *ctx, AudioUnitRenderActionFlags *f, const AudioTimeStamp *ts, UInt32 bus, UInt32 frames, AudioBufferList *bl) {
|
||||
(void)f; (void)ts; (void)bus; (void)frames;
|
||||
aout *a = ctx;
|
||||
atomic_fetch_add_explicit(&g_render_calls, 1, memory_order_relaxed);
|
||||
pull(a, bl->mBuffers[0].mData, bl->mBuffers[0].mDataByteSize);
|
||||
if (!a->mix) pull(a, bl->mBuffers[0].mData, bl->mBuffers[0].mDataByteSize);
|
||||
else { int16_t *o = bl->mBuffers[0].mData; unsigned left = bl->mBuffers[0].mDataByteSize / 4; // 双声道 16 位:每帧 4 字节 | stereo 16-bit: 4 bytes per frame
|
||||
while (left) { unsigned k = left < MIXMAX ? left : MIXMAX; pull(a, (uint8_t *)a->mixbuf, (uint64_t)k * 12); downmix51(a->mixbuf, o, k); o += 2 * k; left -= k; } }
|
||||
// 诊断开关 DM_AUDIO_OUT_DUMP=<文件>:交给 CoreAudio 的那份数据原样续写(下混后是双声道)。本机没有回环设备录不到系统输出,判「对白有没有交出去」看这份
|
||||
// Diagnostic switch DM_AUDIO_OUT_DUMP=<file>: append the data handed to CoreAudio as is (stereo after the downmix). This machine has no loopback device and cannot record the system output; to tell whether the dialogue was handed over, look at this file
|
||||
{ static FILE *df; static int on = -1; if (on < 0) { const char *e = getenv("DM_AUDIO_OUT_DUMP"); on = e != NULL; if (on && !(df = fopen(e, "wb"))) LOG("【红】DM_AUDIO_OUT_DUMP 打不开 %s", e); }
|
||||
if (df) fwrite(bl->mBuffers[0].mData, 1, bl->mBuffers[0].mDataByteSize, df); }
|
||||
return noErr;
|
||||
}
|
||||
static void au_open(aout *a) {
|
||||
#if !TARGET_OS_IPHONE
|
||||
static void dev_name(AudioObjectID id, char *o, size_t n) { // 输出设备名(日志用) | output device name (for the log)
|
||||
CFStringRef nm = NULL; UInt32 sz = sizeof nm; AudioObjectPropertyAddress pa = { kAudioObjectPropertyName, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain };
|
||||
o[0] = 0; if (!AudioObjectGetPropertyData(id, &pa, 0, NULL, &sz, &nm) && nm) { CFStringGetCString(nm, o, (CFIndex)n, kCFStringEncodingUTF8); CFRelease(nm); } }
|
||||
#endif
|
||||
static int au_open(aout *a) { // 0 = 声卡开好了;-1 = 开不了(a->au 置空,调用方走静音接收端) | 0 = the sound card is open; -1 = it cannot be opened (a->au set to null, the caller uses the silent sink)
|
||||
AudioComponentDescription d = {.componentType = kAudioUnitType_Output,
|
||||
#if TARGET_OS_IPHONE
|
||||
.componentSubType = kAudioUnitSubType_RemoteIO,
|
||||
@@ -105,16 +163,120 @@ static void au_open(aout *a) {
|
||||
#endif
|
||||
.componentManufacturer = kAudioUnitManufacturer_Apple};
|
||||
AudioComponent c = AudioComponentFindNext(NULL, &d);
|
||||
if (!c || AudioComponentInstanceNew(c, &a->au)) die("AudioUnit 建不出来");
|
||||
if (!c || AudioComponentInstanceNew(c, &a->au)) { a->au = NULL; LOG("【红】AudioUnit 建不出来:这一路改用静音接收端(不出声)"); return -1; }
|
||||
a->mix = a->ch == 6; if (a->mix && !a->mixbuf) a->mixbuf = malloc(MIXMAX * 12); // 5.1:我们自己下混,AudioUnit 只收双声道(单 / 双声道照旧原样交) | 5.1: we downmix ourselves and the AudioUnit only takes stereo (mono / stereo are passed through as before)
|
||||
if (a->mix && !a->mixbuf) { AudioComponentInstanceDispose(a->au); a->au = NULL; LOG("【红】下混暂存申请不到:这一路改用静音接收端(不出声)"); return -1; }
|
||||
int och = a->mix ? 2 : a->ch;
|
||||
AudioStreamBasicDescription f = {.mSampleRate = RATE, .mFormatID = kAudioFormatLinearPCM,
|
||||
.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked,
|
||||
.mBytesPerPacket = 2u * a->ch, .mFramesPerPacket = 1, .mBytesPerFrame = 2u * a->ch,
|
||||
.mChannelsPerFrame = (UInt32)a->ch, .mBitsPerChannel = 16};
|
||||
.mBytesPerPacket = 2u * och, .mFramesPerPacket = 1, .mBytesPerFrame = 2u * och,
|
||||
.mChannelsPerFrame = (UInt32)och, .mBitsPerChannel = 16};
|
||||
if (a->mix) LOG("audio:游戏给 6 声道(5.1)→ 交给声卡前自己下混成双声道(中置 / 后环绕 ×0.707 并入左右,低音不并入,整体 −3 dB、饱和截断)");
|
||||
AURenderCallbackStruct cb = {au_render, a};
|
||||
if (AudioUnitSetProperty(a->au, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &f, sizeof f) ||
|
||||
AudioUnitSetProperty(a->au, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &cb, sizeof cb) ||
|
||||
AudioUnitInitialize(a->au)) die("AudioUnit 设置失败");
|
||||
AudioUnitInitialize(a->au)) { AudioComponentInstanceDispose(a->au); a->au = NULL; LOG("【红】AudioUnit 设置失败(没有输出设备?):这一路改用静音接收端(不出声)"); return -1; }
|
||||
#if !TARGET_OS_IPHONE
|
||||
{ // 缺省输出单元跟随系统缺省输出设备:两个都记下来,核「声音从系统选的那个设备出」 | the default output unit follows the system default output device: record both, to check that "the sound comes out of the device the system chose"
|
||||
AudioObjectID cur = 0, def = 0; UInt32 sz = sizeof cur; char cn[128], dn[128];
|
||||
AudioUnitGetProperty(a->au, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &cur, &sz);
|
||||
AudioObjectPropertyAddress pa = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain }; sz = sizeof def;
|
||||
AudioObjectGetPropertyData(kAudioObjectSystemObject, &pa, 0, NULL, &sz, &def); dev_name(cur, cn, sizeof cn); dev_name(def, dn, sizeof dn);
|
||||
LOG("audio:输出设备「%s」(%u),系统缺省输出「%s」(%u)%s", cn, (unsigned)cur, dn, (unsigned)def, cur == def ? ",一致" : "【红】不一致"); }
|
||||
#endif
|
||||
return 0;
|
||||
}
|
||||
#elif defined(__ANDROID__)
|
||||
// AAudio:48 kHz PCM16,先按游戏的声道数(常见 6)开;设备不收就开双声道,回调里按 ITU 系数把 5.1 下混成立体声
|
||||
// AAudio: 48 kHz PCM16, opened first with the game's channel count (usually 6); if the device refuses, open stereo and downmix 5.1 to stereo with ITU coefficients in the callback
|
||||
enum { MIX_FRAMES = 1024 };
|
||||
static void downmix(const int16_t *in, int16_t *out, int frames, int ch) {
|
||||
for (int i = 0; i < frames; i++, in += ch, out += 2) {
|
||||
float l = in[0], r = ch > 1 ? in[1] : in[0];
|
||||
if (ch >= 6) { float c = in[2] * .7071f; l += c + in[4] * .7071f; r += c + in[5] * .7071f; } // FL FR C LFE SL SR;低音声道不混 | FL FR C LFE SL SR; the LFE channel is not mixed in
|
||||
else if (ch >= 4) { l += in[2] * .7071f; r += in[3] * .7071f; }
|
||||
if (ch >= 4) { l *= .5858f; r *= .5858f; } // 1/(1+.7071+.7071):不削波 | 1/(1+.7071+.7071): no clipping
|
||||
out[0] = (int16_t)(l > 32767 ? 32767 : l < -32768 ? -32768 : l); out[1] = (int16_t)(r > 32767 ? 32767 : r < -32768 ? -32768 : r);
|
||||
}
|
||||
}
|
||||
static aaudio_data_callback_result_t au_render(AAudioStream *st, void *ctx, void *data, int32_t frames) {
|
||||
(void)st; aout *a = ctx;
|
||||
atomic_fetch_add_explicit(&g_render_calls, 1, memory_order_relaxed);
|
||||
if (a->out_ch == a->ch) { pull(a, data, (uint64_t)frames * 2 * a->ch); return AAUDIO_CALLBACK_RESULT_CONTINUE; }
|
||||
int16_t *out = data;
|
||||
while (frames > 0) { int n = frames < MIX_FRAMES ? frames : MIX_FRAMES;
|
||||
pull(a, (uint8_t *)a->mixbuf, (uint64_t)n * 2 * a->ch); downmix(a->mixbuf, out, n, a->ch);
|
||||
out += n * 2; frames -= n; }
|
||||
return AAUDIO_CALLBACK_RESULT_CONTINUE;
|
||||
}
|
||||
static void au_reopen(aout *a);
|
||||
static void *null_sink(void *p);
|
||||
// 设备断开(拔耳机、切蓝牙):AAudio 的回调线程里不许关流重开,交给一条普通线程 | device disconnected (headphones unplugged, Bluetooth switched): the stream must not be closed / reopened on AAudio's callback thread, hand it to an ordinary thread
|
||||
static void *au_reopen_th(void *p) { au_reopen(p); return NULL; }
|
||||
static void au_error(AAudioStream *st, void *ctx, aaudio_result_t err) {
|
||||
(void)st; aout *a = ctx;
|
||||
LOG("【红】AAudio 出错 %d(%s):换设备重开", err, AAudio_convertResultToText(err));
|
||||
if (atomic_exchange(&a->lost, 1)) return;
|
||||
pthread_t t; if (!pthread_create(&t, NULL, au_reopen_th, a)) pthread_detach(t);
|
||||
}
|
||||
static AAudioStream *au_stream(aout *a, int ch, int low_latency) {
|
||||
AAudioStreamBuilder *b; AAudioStream *st = NULL;
|
||||
if (AAudio_createStreamBuilder(&b) != AAUDIO_OK) return NULL;
|
||||
AAudioStreamBuilder_setDirection(b, AAUDIO_DIRECTION_OUTPUT);
|
||||
AAudioStreamBuilder_setSharingMode(b, AAUDIO_SHARING_MODE_SHARED);
|
||||
AAudioStreamBuilder_setSampleRate(b, RATE); AAudioStreamBuilder_setChannelCount(b, ch);
|
||||
AAudioStreamBuilder_setFormat(b, AAUDIO_FORMAT_PCM_I16);
|
||||
AAudioStreamBuilder_setUsage(b, AAUDIO_USAGE_GAME); AAudioStreamBuilder_setContentType(b, AAUDIO_CONTENT_TYPE_MUSIC);
|
||||
AAudioStreamBuilder_setPerformanceMode(b, low_latency ? AAUDIO_PERFORMANCE_MODE_LOW_LATENCY : AAUDIO_PERFORMANCE_MODE_NONE);
|
||||
AAudioStreamBuilder_setDataCallback(b, au_render, a); AAudioStreamBuilder_setErrorCallback(b, au_error, a);
|
||||
if (AAudioStreamBuilder_openStream(b, &st) != AAUDIO_OK) st = NULL;
|
||||
AAudioStreamBuilder_delete(b);
|
||||
// 系统可能悄悄改格式(重采样到别的率、改声道):不是要的就不用 | the system may silently change the format (resample to another rate, change channels): reject it if it is not what was asked for
|
||||
if (st && (AAudioStream_getSampleRate(st) != RATE || AAudioStream_getChannelCount(st) != ch || AAudioStream_getFormat(st) != AAUDIO_FORMAT_PCM_I16)) { AAudioStream_close(st); st = NULL; }
|
||||
return st;
|
||||
}
|
||||
static int au_try_open(aout *a) {
|
||||
for (int lat = 1; lat >= 0; lat--) {
|
||||
if ((a->au = au_stream(a, a->ch, lat))) { a->out_ch = a->ch; break; }
|
||||
if (a->ch != 2 && (a->au = au_stream(a, 2, lat))) { a->out_ch = 2; break; }
|
||||
}
|
||||
if (!a->au) return 0;
|
||||
if (a->out_ch != a->ch && !a->mixbuf) a->mixbuf = malloc((size_t)MIX_FRAMES * 2 * a->ch);
|
||||
int burst = AAudioStream_getFramesPerBurst(a->au);
|
||||
if (burst > 0) AAudioStream_setBufferSizeInFrames(a->au, burst * 4); // 4 个突发 ≈ 几毫秒:游戏自己有 FMOD 缓冲,这里少留防爆音 | 4 bursts ≈ a few ms: the game has its own FMOD buffering, keep a little here against crackles
|
||||
LOG("AAudio 打开:48 kHz PCM16 声道 %d(游戏 %d%s)突发 %d 帧 性能模式 %d", a->out_ch, a->ch, a->out_ch != a->ch ? ",下混" : "", burst, AAudioStream_getPerformanceMode(a->au));
|
||||
return 1;
|
||||
}
|
||||
static void au_open(aout *a) { if (!au_try_open(a)) LOG("【红】AAudio 打不开:用静音接收端"); }
|
||||
static OSStatus au_wait(AudioUnit au, aaudio_stream_state_t want) {
|
||||
aaudio_stream_state_t st = AAudioStream_getState(au), next;
|
||||
for (int i = 0; i < 10 && st != want; i++) { // 超时不算失败(回前台时 STARTING 常要一百多毫秒):最多等 1 秒 | a timeout is not a failure (STARTING often takes 100+ ms when returning to foreground): wait up to 1 s
|
||||
aaudio_result_t r = AAudioStream_waitForStateChange(au, st, &next, 100000000);
|
||||
if (r == AAUDIO_OK) st = next; else if (r == AAUDIO_ERROR_TIMEOUT) st = AAudioStream_getState(au); else break; }
|
||||
return st == want ? 0 : -1;
|
||||
}
|
||||
static OSStatus AudioOutputUnitStart(AudioUnit au) {
|
||||
aaudio_result_t r = AAudioStream_requestStart(au); OSStatus st = r == AAUDIO_OK ? au_wait(au, AAUDIO_STREAM_STATE_STARTED) : -1;
|
||||
if (st) LOG("AAudio 启动失败:%s,流状态 %s", AAudio_convertResultToText(r), AAudio_convertStreamStateToText(AAudioStream_getState(au)));
|
||||
return st;
|
||||
}
|
||||
// 停要等回调真停:之后静音接收端接手同一条队列,两边不能同时拉 | stopping waits until callbacks have really stopped: afterwards the silent sink takes over the same queue, the two must not pull at once
|
||||
static OSStatus AudioOutputUnitStop(AudioUnit au) { return AAudioStream_requestStop(au) == AAUDIO_OK ? au_wait(au, AAUDIO_STREAM_STATE_STOPPED) : -1; }
|
||||
static void au_reopen(aout *a) {
|
||||
pthread_mutex_lock(&g_aos_lock);
|
||||
int live = 0; for (int i = 0; i < AOMAX; i++) live |= g_aos[i] == a;
|
||||
if (live && a->au) {
|
||||
AAudioStream_close(a->au); a->au = NULL; // 断开的流回调已停 | callbacks of a disconnected stream have stopped
|
||||
if (!au_try_open(a)) { LOG("【红】AAudio 重开失败:改用静音接收端");
|
||||
if (atomic_load(&a->state) == STATE_STARTED && !g_suspended) { atomic_store(&a->null_run, 1); pthread_create(&a->null_th, NULL, null_sink, a); } }
|
||||
else if (atomic_load(&a->state) == STATE_STARTED && !g_suspended && AudioOutputUnitStart(a->au)) LOG("【红】AAudio 重开后启动失败");
|
||||
}
|
||||
atomic_store(&a->lost, 0);
|
||||
pthread_mutex_unlock(&g_aos_lock);
|
||||
}
|
||||
#else
|
||||
static void au_open(aout *a) { (void)a; die("Linux 宿主还没有真出声后端:用 DM_AUDIO=0(静音接收端)"); }
|
||||
#endif
|
||||
// 静音接收端:每 5 ms 按 48 kHz 实时消耗
|
||||
// Silent sink: consumes in real time at 48 kHz every 5 ms
|
||||
static void *null_sink(void *p) {
|
||||
@@ -126,7 +288,12 @@ static void *null_sink(void *p) {
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
static int real_audio(void) { const char *e = getenv("DM_AUDIO"); return e ? atoi(e) != 0 : TARGET_OS_IPHONE; }
|
||||
#if defined(__ANDROID__)
|
||||
#define DM_AUDIO_DEFAULT 1 // Android App 同 iOS:缺省真出声 | Android app, like iOS: real audio by default
|
||||
#else
|
||||
#define DM_AUDIO_DEFAULT TARGET_OS_IPHONE
|
||||
#endif
|
||||
static int real_audio(void) { const char *e = getenv("DM_AUDIO"); return e ? atoi(e) != 0 : DM_AUDIO_DEFAULT; }
|
||||
|
||||
// AudioOutParameter = { int32 sampleRate; uint16 channelCount; uint16 _r; ... },0 = 系统默认(48 kHz / 2 声道)
|
||||
// AudioOutParameter = { int32 sampleRate; uint16 channelCount; uint16 _r; ... }, 0 = system default (48 kHz / 2 channels)
|
||||
@@ -158,15 +325,15 @@ HLE_FORCE("_ZN2nn5audio12OpenAudioOutEPNS0_8AudioOutEPNS_2os11SystemEventEPKcRKN
|
||||
g_aos[slot] = a;
|
||||
pthread_mutex_unlock(&g_aos_lock);
|
||||
LOG("audio::OpenAudioOut %s 声道 %d %s", name ? name : "(默认)", ch, real_audio() ? "真出声" : "静音接收端");
|
||||
if (real_audio()) au_open(a);
|
||||
if (real_audio()) au_open(a); // 开不了就 a->au 为空,开始播放时走静音接收端 | if it cannot be opened, a->au is null, and playback goes to the silent sink when it starts
|
||||
return RES_OK;
|
||||
}
|
||||
HLE_FORCE("_ZN2nn5audio13StartAudioOutEPNS0_8AudioOutE", "开始播放", Result, h_au_Start, void *g) {
|
||||
aout *a = ao(g);
|
||||
pthread_mutex_lock(&a->m); int was = atomic_load_explicit(&a->state, memory_order_relaxed); atomic_store_explicit(&a->state, STATE_STARTED, memory_order_release); pthread_mutex_unlock(&a->m);
|
||||
if (was == STATE_STARTED) return RES_OK;
|
||||
if (a->au && !g_suspended) { if (AudioOutputUnitStart(a->au)) die("AudioUnit 启动失败"); }
|
||||
else { atomic_store_explicit(&a->null_run, 1, memory_order_release); pthread_create(&a->null_th, NULL, null_sink, a); }
|
||||
if (a->au && !g_suspended && AudioOutputUnitStart(a->au)) { LOG("【红】AudioUnit 启动失败:这一路改用静音接收端(不出声)"); AudioUnitUninitialize(a->au); AudioComponentInstanceDispose(a->au); a->au = NULL; }
|
||||
if (!a->au || g_suspended) { atomic_store_explicit(&a->null_run, 1, memory_order_release); pthread_create(&a->null_th, NULL, null_sink, a); }
|
||||
return RES_OK;
|
||||
}
|
||||
HLE_FORCE("_ZN2nn5audio12StopAudioOutEPNS0_8AudioOutE", "停止播放", void, h_au_Stop, void *g) {
|
||||
@@ -188,7 +355,7 @@ HLE_FORCE("_ZN2nn5audio13CloseAudioOutEPNS0_8AudioOutE", "关闭音频输出", v
|
||||
pthread_mutex_unlock(&g_aos_lock);
|
||||
if (a->au) { AudioUnitUninitialize(a->au); AudioComponentInstanceDispose(a->au); }
|
||||
dispatch_release(a->notify_sem);
|
||||
pthread_mutex_destroy(&a->m); free(a);
|
||||
free(a->mixbuf); pthread_mutex_destroy(&a->m); free(a);
|
||||
}
|
||||
HLE_FORCE("_ZN2nn5audio16GetAudioOutStateEPKNS0_8AudioOutE", "播放状态", int, h_au_State, const void *g) { return atomic_load_explicit(&ao(g)->state, memory_order_acquire); }
|
||||
HLE_FORCE("_ZN2nn5audio21GetAudioOutSampleRateEPKNS0_8AudioOutE", "采样率", int, h_au_Rate, const void *g) { (void)ao(g); return RATE; }
|
||||
@@ -242,6 +409,12 @@ void dm_audio_suspend(int on) {
|
||||
if (on) { AudioOutputUnitStop(a->au); atomic_store_explicit(&a->null_run, 1, memory_order_release); pthread_create(&a->null_th, NULL, null_sink, a); }
|
||||
else { atomic_store_explicit(&a->null_run, 0, memory_order_release); pthread_join(a->null_th, NULL);
|
||||
OSStatus st = AudioOutputUnitStart(a->au);
|
||||
#if defined(__ANDROID__)
|
||||
if (st) { // 后台期间流被系统收走(断开 / 起不来):关掉重开一次再起 | the stream was taken away by the system while in the background (disconnected / won't start): close, reopen once and start again
|
||||
AAudioStream_close(a->au); a->au = NULL;
|
||||
st = au_try_open(a) ? AudioOutputUnitStart(a->au) : -1;
|
||||
LOG("AAudio 回前台重开%s", st ? "仍失败" : "后起来了"); }
|
||||
#endif
|
||||
if (st) { // 会话还被别人占着(通话没挂就切回游戏、打断结束时人还在别的 App):不致命,继续由静音接收端顶着,等下一次恢复再试 | The session is still held by someone else (switched back to the game with a call not yet hung up, or the user is still in another app when the interruption ends): not fatal, the silent sink keeps covering, and we retry at the next resume
|
||||
LOG("【红】AudioUnit 恢复失败(状态 %d):保持静音接收端,等下次恢复重试", (int)st);
|
||||
atomic_store_explicit(&a->null_run, 1, memory_order_release); pthread_create(&a->null_th, NULL, null_sink, a); failed = 1; } }
|
||||
|
||||
+68
-17
@@ -76,6 +76,20 @@ static const char *envdir(const char *var, const char *rel, char *buf, size_t n)
|
||||
snprintf(buf, n, "%s%s/%s", getenv("DM_ROOT") ?: getenv("HOME"), getenv("DM_ROOT") ? "" : "/dm-work", rel); return buf;
|
||||
}
|
||||
|
||||
// 测试注入 DM_TEST_FS_FAILAT=<点>[:<次数>][,…]:存档事务里写失败收场的几步(mountclone 挂载时克隆工作目录、reclone 提交被拒后重新克隆、
|
||||
// guestname 改名后写客体名、renameback 改名回退)前 <次数> 次(缺省 1)按 ENOSPC 失败,验「不退出、已提交版本不变、下次提交照常」(tests/t_fs.c)
|
||||
// Test injection DM_TEST_FS_FAILAT=<point>[:<count>][,...]: the steps of a save transaction that end in a failed write (mountclone = clone the work directory at mount, reclone = reclone after a refused commit,
|
||||
// guestname = write the guest name after a rename, renameback = rename rollback) fail with ENOSPC for the first <count> times (default 1), to check "no exit, committed version unchanged, next commit works" (tests/t_fs.c)
|
||||
static int dm_fs_test_fail(const char *pt) {
|
||||
static char spec[256]; static int cnt[8]; const char *e = getenv("DM_TEST_FS_FAILAT"); if (!e || !e[0]) return 0;
|
||||
if (strcmp(spec, e)) { strlcpy(spec, e, sizeof spec); memset(cnt, 0, sizeof cnt); } // 换了一组注入就从头数 | A new set of injections starts counting from zero
|
||||
size_t L = strlen(pt); int k = 0;
|
||||
for (const char *q = spec; *q && k < 8; k++) { const char *end = strchr(q, ','); size_t n = end ? (size_t)(end - q) : strlen(q);
|
||||
if (n >= L && !strncmp(q, pt, L) && (n == L || q[L] == ':')) { int lim = n > L ? atoi(q + L + 1) : 1; if (cnt[k] < lim) { cnt[k]++; errno = ENOSPC; LOG("DM_TEST_FS_FAILAT:%s 第 %d 次按 ENOSPC 失败", pt, cnt[k]); return 1; } return 0; }
|
||||
q = end ? end + 1 : q + n; }
|
||||
return 0;
|
||||
}
|
||||
static int in_txn_dir(const char *hp) { for (int i = 0; i < g_nmnt; i++) { size_t n = strlen(g_mnt[i].dir); if (g_mnt[i].commit[0] && !strncmp(hp, g_mnt[i].dir, n) && (hp[n] == '/' || !hp[n])) return 1; } return 0; }
|
||||
static int rm_tree(const char *p);
|
||||
static Result mount_ex(const char *name, const char *dir, int ro, int txn) {
|
||||
PATH_LOCK(); pthread_mutex_lock(&g_lock);
|
||||
@@ -86,20 +100,26 @@ static Result mount_ex(const char *name, const char *dir, int ro, int txn) {
|
||||
g_mnt[g_nmnt].ro = ro; g_mnt[g_nmnt].overlay[0] = 0; g_mnt[g_nmnt].commit[0] = 0;
|
||||
if (!strcmp(name, "rom") && getenv("DM_ROMFS_OVERLAY"))
|
||||
strlcpy(g_mnt[g_nmnt].overlay, getenv("DM_ROMFS_OVERLAY"), sizeof g_mnt[0].overlay);
|
||||
int txn_err = 0; // 事务目录建不起来(清不掉残留 / 克隆失败,盘满时真实可能):不退出,改成只读挂载已提交目录——角色照常读得到,写一律失败、提交为空操作,已提交版本一个字节不动 | The transaction directory cannot be set up (leftovers cannot be cleared / clone failed, which really happens on a full disk): do not exit; mount the committed directory read-only instead. Characters still load, every write fails, commits are no-ops, and not one byte of the committed version changes
|
||||
if (txn) {
|
||||
char work[1100], neu[1100]; snprintf(work, sizeof work, "%s.work", dir); snprintf(neu, sizeof neu, "%s.new", dir);
|
||||
mkdir(dir, 0755);
|
||||
if (!access(work, F_OK) && rm_tree(work)) die("存档事务:清不掉上次残留的工作目录 %s", work);
|
||||
if (!access(neu, F_OK) && rm_tree(neu)) die("存档事务:清不掉上次残留的 %s", neu);
|
||||
if (clonefile(dir, work, 0)) die("存档事务:clonefile %s → %s 失败 errno=%d", dir, work, errno);
|
||||
strlcpy(g_mnt[g_nmnt].commit, dir, sizeof g_mnt[0].commit);
|
||||
atomic_store(&g_save_poison, 0); // 工作目录刚从已提交版克隆,完好 | the working directory was just cloned from the committed version, intact
|
||||
strlcpy(g_mnt[g_nmnt].dir, work, sizeof g_mnt[0].dir);
|
||||
const char *why = NULL;
|
||||
if (!access(work, F_OK) && rm_tree(work)) why = "清不掉上次残留的工作目录";
|
||||
else if (!access(neu, F_OK) && rm_tree(neu)) why = "清不掉上次残留的 .new";
|
||||
else if (dm_fs_test_fail("mountclone") || clonefile(dir, work, 0)) why = "克隆工作目录失败";
|
||||
if (why) { txn_err = errno ? errno : EIO; g_mnt[g_nmnt].ro = 1; strlcpy(g_mnt[g_nmnt].dir, dir, sizeof g_mnt[0].dir);
|
||||
LOG("【红】存档事务:%s(%s,errno=%d)——改为只读挂载已提交目录 %s:本局存档写不进去,已提交版本不变", why, work, txn_err, dir); }
|
||||
else {
|
||||
strlcpy(g_mnt[g_nmnt].commit, dir, sizeof g_mnt[0].commit);
|
||||
atomic_store(&g_save_poison, 0); // 工作目录刚从已提交版克隆,完好 | the working directory was just cloned from the committed version, intact
|
||||
strlcpy(g_mnt[g_nmnt].dir, work, sizeof g_mnt[0].dir); }
|
||||
} else strlcpy(g_mnt[g_nmnt].dir, dir, sizeof g_mnt[0].dir);
|
||||
g_nmnt++;
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
if (txn_err) front_save_failed(txn_err);
|
||||
if (!ro && !txn) mkdir(dir, 0755);
|
||||
LOG("fs 挂载 %s: → %s%s%s", name, txn ? g_mnt[g_nmnt - 1].dir : dir, ro ? "(只读)" : txn ? "(事务式存档:工作目录,Commit 原子换入)" : "", g_mnt[g_nmnt - 1].overlay[0] ? "(overlay 优先)" : "");
|
||||
LOG("fs 挂载 %s: → %s%s%s", name, txn ? g_mnt[g_nmnt - 1].dir : dir, ro || txn_err ? "(只读)" : txn ? "(事务式存档:工作目录,Commit 原子换入)" : "", g_mnt[g_nmnt - 1].overlay[0] ? "(overlay 优先)" : "");
|
||||
return RES_OK;
|
||||
}
|
||||
static Result mount(const char *name, const char *dir, int ro) { return mount_ex(name, dir, ro, 0); }
|
||||
@@ -110,7 +130,16 @@ static Result mount(const char *name, const char *dir, int ro) { return mount_ex
|
||||
// APFS is case-insensitive by default, Horizon paths are case-sensitive: every component is looked up exactly by guest name.
|
||||
// Ordinary host names are unchanged; only when a name collides on the host is a separate physical name chosen, with the guest name stored in an xattr.
|
||||
// clonefile preserves xattr, so save Commit/remount needs no separate mapping table; enumeration must not leak physical aliases.
|
||||
#if defined(__APPLE__)
|
||||
#define FS_GUEST_NAME "org.d2rmobile.guest-name"
|
||||
#else
|
||||
// Linux:非特权进程只能写 user.* 命名空间;不跟随符号链接用 l* 版本,Darwin 的 position / options 参数丢弃
|
||||
// Linux: unprivileged processes may only write the user.* namespace; not following symlinks uses the l* variants, Darwin's position / options arguments are dropped
|
||||
#define FS_GUEST_NAME "user.d2rmobile.guest-name"
|
||||
#define getxattr(p, k, v, n, pos, opt) lgetxattr(p, k, v, n)
|
||||
#define setxattr(p, k, v, n, pos, opt) lsetxattr(p, k, v, n, 0)
|
||||
#define removexattr(p, k, opt) lremovexattr(p, k)
|
||||
#endif
|
||||
static int guest_name(const char *parent, const char *physical, char *out, size_t n) {
|
||||
char p[1280]; snprintf(p, sizeof p, "%s/%s", parent, physical);
|
||||
ssize_t k = getxattr(p, FS_GUEST_NAME, out, n - 1, 0, XATTR_NOFOLLOW);
|
||||
@@ -239,6 +268,9 @@ static Result err_res(const char *op, const char *path) {
|
||||
#define HP_EX(path, create) PATH_LOCK(); char hp[1024]; int ro = 0; if (!host_path_ex(path, hp, sizeof hp, &ro, create)) return err_res("path", path)
|
||||
#define HP(path) HP_EX(path, 0)
|
||||
#define RW() if (ro) { LOG("fs 写只读挂载:%s", hp); return RES_FAIL; }
|
||||
// 建目录 / 建文件:目标已存在就照可写挂载的语义回「已存在」——游戏只认得这一种失败(原版存档盘不会写失败),回通用失败它会拿空句柄继续走(iOS 只读回退局在 CloseDirectory 崩)
|
||||
// Create directory / create file: if the target exists, answer "already exists" as a writable mount would. That is the only failure the game understands (the original save storage never fails to write); with a generic failure it carries on with a null handle (the iOS read-only fallback crashed in CloseDirectory)
|
||||
#define RW_CREATE() if (ro) { if (!access(hp, F_OK)) return RES_PATH_EXISTS; LOG("fs 写只读挂载:%s", hp); return RES_FAIL; }
|
||||
|
||||
// ---------- 挂载 ----------
|
||||
// ---------- Mount ----------
|
||||
@@ -297,7 +329,7 @@ static void stash_seed_one(const char *save_dir, const char *name) {
|
||||
// 标准级与专家级各一份,各判各的(游戏按角色类型选文件名,main+0x2ce1e8:DLC 类型标准 = ModernSharedStashSoftCoreV2、专家 = ModernSharedStashHardCoreV2;文件格式相同)
|
||||
// One copy each for standard and hardcore, each judged on its own (the game picks the file name by character type, main+0x2ce1e8: DLC type standard = ModernSharedStashSoftCoreV2, hardcore = ModernSharedStashHardCoreV2; same file format)
|
||||
static void stash_seed(const char *save_dir) {
|
||||
const char *e = getenv("DM_STASH_SEED"); int on = e ? strcmp(e, "0") != 0 : TARGET_OS_IPHONE; if (!on) return; // iOS 上缺省开;Mac 宿主缺省关(对拍 / 存档事务这些闸门逐字节比存档目录,多出一个文件就红),要验时设 DM_STASH_SEED=1 | on by default on iOS; off by default on the Mac host (gate checks such as lockstep comparison / save transaction compare the save directory byte by byte, one extra file turns them red), set DM_STASH_SEED=1 to verify
|
||||
const char *e = getenv("DM_STASH_SEED"); int on = e ? strcmp(e, "0") != 0 : DM_TOUCH_PRODUCT; if (!on) return; // iOS 上缺省开;Mac 宿主缺省关(对拍 / 存档事务这些闸门逐字节比存档目录,多出一个文件就红),要验时设 DM_STASH_SEED=1 | on by default on iOS; off by default on the Mac host (gate checks such as lockstep comparison / save transaction compare the save directory byte by byte, one extra file turns them red), set DM_STASH_SEED=1 to verify
|
||||
stash_seed_one(save_dir, "ModernSharedStashSoftCoreV2"); stash_seed_one(save_dir, "ModernSharedStashHardCoreV2");
|
||||
}
|
||||
#else
|
||||
@@ -308,7 +340,7 @@ static void stash_seed(const char *save_dir) { (void)save_dir; }
|
||||
// Fallback for 「大字体」(Large Font) (settings key "Low Vision Mode"): if it is 1 in the settings file, change it back to 0. It switches the UI to the original game's low-vision layout profile, which our touch UI was never built for; it hangs after being turned on in the settings page.
|
||||
// This item in the settings page is separately hidden by the UI overlay; this here guarantees that devices where it was already turned on recover on restart. Same switch as settings_seed (on by default on iOS, on the Mac host only with DM_TOUCH_DEFAULTS=1)
|
||||
static void low_vision_off(const char *save_dir) {
|
||||
const char *e = getenv("DM_TOUCH_DEFAULTS"); int on = e ? strcmp(e, "0") != 0 : TARGET_OS_IPHONE; if (!on) return;
|
||||
const char *e = getenv("DM_TOUCH_DEFAULTS"); int on = e ? strcmp(e, "0") != 0 : DM_TOUCH_PRODUCT; if (!on) return;
|
||||
char path[1200]; snprintf(path, sizeof path, "%s/Settings/Settings.json", save_dir); static char buf[65536]; FILE *f = fopen(path, "rb"); if (!f) return;
|
||||
size_t n = fread(buf, 1, sizeof buf - 1, f); fclose(f); if (n == sizeof buf - 1) return; buf[n] = 0;
|
||||
char *k = strstr(buf, "\"Low Vision Mode\""); if (!k) return; char *v = strchr(k + 17, ':'); if (!v) return; v++; while (*v == ' ' || *v == '\t') v++;
|
||||
@@ -317,7 +349,7 @@ static void low_vision_off(const char *save_dir) {
|
||||
if (ok && !rename(tmp, path)) LOG("设置兜底:「大字体」(Low Vision Mode)是开着的,已改回关"); else remove(tmp);
|
||||
}
|
||||
static void settings_seed(const char *save_dir) {
|
||||
const char *e = getenv("DM_TOUCH_DEFAULTS"); int on = e ? strcmp(e, "0") != 0 : TARGET_OS_IPHONE; if (!on) return;
|
||||
const char *e = getenv("DM_TOUCH_DEFAULTS"); int on = e ? strcmp(e, "0") != 0 : DM_TOUCH_PRODUCT; if (!on) return;
|
||||
static const char *kv[][2] = {{"\"Item Name Display\"", "1"}, {"\"Item Tooltip Hotkey Appender\"", "0"},
|
||||
{"\"AutoMapMode\"", "2"}, {"\"AutoMap Open On Load\"", "1"}};
|
||||
char dir[1100], path[1200]; snprintf(dir, sizeof dir, "%s/Settings", save_dir); snprintf(path, sizeof path, "%s/Settings.json", dir);
|
||||
@@ -388,7 +420,7 @@ HLE_FORCE("_ZN2nn2fs13MountSaveDataEPKcRKNS_7account3UidE", "fsp-srv;存档
|
||||
// iOS 上缺省写;Mac 宿主的对拍闸门(存档要和真机真值逐文件相同)不写
|
||||
// Rule files for the loot filter (the game loads them at startup; dm_lootfilter.c registers this hook from a constructor; it is null in unit tests that link only hle_fs.c). Same switch as settings_seed:
|
||||
// written by default on iOS; not written under the Mac host's parity gate (saves must match the device ground truth file by file)
|
||||
{ const char *e = getenv("DM_TOUCH_DEFAULTS"); if (g_dm_mount_seed_hook && (e ? strcmp(e, "0") != 0 : TARGET_OS_IPHONE)) g_dm_mount_seed_hook(dd); }
|
||||
{ const char *e = getenv("DM_TOUCH_DEFAULTS"); if (g_dm_mount_seed_hook && (e ? strcmp(e, "0") != 0 : DM_TOUCH_PRODUCT)) g_dm_mount_seed_hook(dd); }
|
||||
return mount_ex(name, dd, 0, 1);
|
||||
}
|
||||
void (*g_dm_pre_commit_hook[4])(const char *workdir); // 提交前调(工作目录):宿主旁路文件按工作目录里的存档内容核对后再写([0] 个人仓库多页 dm_pages.c、[2] 百宝囊 dm_pouch.c、[1] 编年史仓库 dm_vault.c、[3] 秘境进度 dm_rift.c) | called before commit (working directory): host side files are checked against the save contents in the working directory before being written ([0] personal stash pages dm_pages.c, [2] pouch dm_pouch.c, [1] chronicle vault dm_vault.c, [3] rift progress dm_rift.c)
|
||||
@@ -415,9 +447,18 @@ HLE_FORCE("_ZN2nn2fs6CommitEPKc", "fsp-srv;事务式存档:工作目录整
|
||||
}
|
||||
if (d0) closedir(d0);
|
||||
int nopen = 0; for (int k = 0; k < 65536; k++) nopen += g_fsave[k]; // 仍开着的存档文件:重新克隆后这些句柄指向被删的旧工作目录 | save files still open: after re-cloning, these handles point into the deleted old working directory
|
||||
if (rm_tree(g_mnt[i].dir) || clonefile(g_mnt[i].commit, g_mnt[i].dir, 0)) die("存档事务:丢弃工作目录 %s 后重新克隆失败 errno=%d", g_mnt[i].dir, errno);
|
||||
// 先把已提交版克隆到同级临时目录,成了再与被污染的工作目录原子互换、删掉换下来的;任一步失败都不退出:工作目录留着、「已污染」标记放回去
|
||||
// (下次提交照样拒绝、再试一次重新克隆),已提交版本不变(原先先删工作目录再克隆,克隆失败就 die,盘满时进程直接退出、工作目录也没了)
|
||||
// First clone the committed version into a sibling temporary directory; once that succeeds, atomically swap it with the tainted work directory and delete the swapped-out one. If any step fails, do not exit: the work directory stays and the "tainted" mark is put back
|
||||
// (the next commit is refused again and recloning is retried); the committed version is unchanged (before, the work directory was deleted first and then recloned, and a failed clone called die, so with a full disk the process exited and the work directory was gone)
|
||||
char re[1100]; snprintf(re, sizeof re, "%s.re", g_mnt[i].dir); int rerr = 0;
|
||||
if (!access(re, F_OK) && rm_tree(re)) rerr = errno ? errno : EIO;
|
||||
else if (dm_fs_test_fail("reclone") || clonefile(g_mnt[i].commit, re, 0)) { rerr = errno ? errno : EIO; rm_tree(re); }
|
||||
else if (renamex_np(re, g_mnt[i].dir, RENAME_SWAP)) { rerr = errno ? errno : EIO; rm_tree(re); }
|
||||
else rm_tree(re); // 换下来的被污染工作目录 | The swapped-out tainted work directory
|
||||
if (rerr) { save_poison(perr); LOG("【红】存档事务:重新克隆工作目录失败 errno=%d——工作目录不动、保持已污染(下次提交照样拒绝并重试),已提交版本不变", rerr); }
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
LOG("【红】存档提交拒绝:本事务有存档写失败 errno=%d(工作目录里 0 字节文件:%s);已提交版本不变,工作目录已从已提交版重新克隆%s", perr, tl ? torn + 1 : "无", nopen ? ";【红】仍有存档文件开着" : "");
|
||||
LOG("【红】存档提交拒绝:本事务有存档写失败 errno=%d(工作目录里 0 字节文件:%s);已提交版本不变,工作目录%s%s", perr, tl ? torn + 1 : "无", rerr ? "没能重新克隆(见上一行)" : "已从已提交版重新克隆", nopen ? ";【红】仍有存档文件开着" : "");
|
||||
front_save_failed(perr);
|
||||
return RES_FAIL;
|
||||
}
|
||||
@@ -526,6 +567,7 @@ HLE_FORCE("_ZN2nn2fs8OpenFileEPNS0_10FileHandleEPKci", "fsp-srv → open(2)", Re
|
||||
return RES_OK;
|
||||
}
|
||||
HLE_FORCE("_ZN2nn2fs8ReadFileEPmNS0_10FileHandleElPvm", "fsp-srv → pread(2)", Result, h_fs_ReadFile, size_t *out, uint64_t h, int64_t off, void *buf, size_t sz) {
|
||||
if (!h) { *out = 0; return RES_FAIL; } // 文件句柄就是 fd,0 是标准输入、不会是游戏打开的文件:打开失败后照用的空句柄 | A file handle is an fd; 0 is standard input and never a file the game opened: it is the null handle the game keeps using after a failed open
|
||||
size_t got = 0; uint64_t t0 = g_flag.bootprof ? now_ns() : 0;
|
||||
dm_guest_write_prepare(buf, sz); // 目标可能是图形层写保护的贴图池页:内核写只读页返回 EFAULT 而不缺页,先解保护并标脏 | The destination may be a texture pool page write-protected by the graphics layer: a kernel write to a read-only page returns EFAULT instead of page-faulting, so unprotect and mark dirty first
|
||||
while (got < sz) {
|
||||
@@ -551,6 +593,7 @@ HLE_FORCE("_ZN2nn2fs8ReadFileEPmNS0_10FileHandleElPvm", "fsp-srv → pread(2)",
|
||||
return RES_OK;
|
||||
}
|
||||
HLE_FORCE("_ZN2nn2fs9WriteFileENS0_10FileHandleElPKvmRKNS0_11WriteOptionE", "fsp-srv → pwrite(2)", Result, h_fs_WriteFile, uint64_t h, int64_t off, const void *buf, size_t sz, const void *opt) {
|
||||
if (!h) return RES_FAIL;
|
||||
(void)opt; size_t put = 0;
|
||||
if (g_fsave[(int)h & 0xffff]) { // 存档写注入点(确定性回归用;只数存档挂载上的写) | Save write injection point (for deterministic regression; only writes on the save mount are counted)
|
||||
static int cfg = -1, kill_n, fail_n, fail_e;
|
||||
@@ -572,16 +615,19 @@ HLE_FORCE("_ZN2nn2fs9WriteFileENS0_10FileHandleElPKvmRKNS0_11WriteOptionE", "fsp
|
||||
return RES_OK;
|
||||
}
|
||||
HLE_FORCE("_ZN2nn2fs11GetFileSizeEPlNS0_10FileHandleE", "fsp-srv → fstat(2)", Result, h_fs_GetFileSize, int64_t *out, uint64_t h) {
|
||||
if (!h) return RES_FAIL;
|
||||
struct stat st; if (fstat((int)h, &st)) return err_res("fstat", "fd");
|
||||
*out = (int)h < 4096 && g_hm[(int)h] ? g_hm[(int)h]->size : st.st_size; return RES_OK;
|
||||
}
|
||||
HLE_FORCE("_ZN2nn2fs11SetFileSizeENS0_10FileHandleEl", "fsp-srv → ftruncate(2)", Result, h_fs_SetFileSize, uint64_t h, int64_t sz) {
|
||||
if (!h) return RES_FAIL;
|
||||
if (!ftruncate((int)h, sz)) return RES_OK;
|
||||
if (g_fsave[(int)h & 0xffff]) save_poison(errno);
|
||||
return err_res("ftruncate", "fd");
|
||||
}
|
||||
HLE_FORCE("_ZN2nn2fs9FlushFileENS0_10FileHandleE", "fsp-srv;宿主 write 已进页缓存,刷新为空操作", Result, h_fs_FlushFile, uint64_t h) { (void)h; return RES_OK; }
|
||||
HLE_FORCE("_ZN2nn2fs9CloseFileENS0_10FileHandleE", "fsp-srv → close(2)", void, h_fs_CloseFile, uint64_t h) { g_fmode[(int)h & 0xffff] = 0; g_fsave[(int)h & 0xffff] = 0;
|
||||
HLE_FORCE("_ZN2nn2fs9CloseFileENS0_10FileHandleE", "fsp-srv → close(2)", void, h_fs_CloseFile, uint64_t h) {
|
||||
if (!h) return; g_fmode[(int)h & 0xffff] = 0; g_fsave[(int)h & 0xffff] = 0;
|
||||
if ((int)h >= 0 && (int)h < 4096 && g_hm[(int)h]) { holemap *m = g_hm[(int)h]; g_hm[(int)h] = NULL; free(m->log); free(m->len); free(m->phys); free(m); }
|
||||
close((int)h); }
|
||||
HLE_FORCE("_ZN2nn2fs15GetFileOpenModeENS0_10FileHandleE", "fsp-srv;打开方式由宿主记录", int, h_fs_GetFileOpenMode, uint64_t h) { return g_fmode[(int)h & 0xffff]; }
|
||||
@@ -589,7 +635,7 @@ HLE_FORCE("_ZN2nn2fs15GetFileOpenModeENS0_10FileHandleE", "fsp-srv;打开方
|
||||
// ---------- 路径操作 ----------
|
||||
// ---------- Path operations ----------
|
||||
HLE_FORCE("_ZN2nn2fs10CreateFileEPKcl", "fsp-srv → open(O_CREAT|O_EXCL)+ftruncate", Result, h_fs_CreateFile, const char *path, int64_t sz) {
|
||||
HP_EX(path, 1); RW();
|
||||
HP_EX(path, 1); RW_CREATE();
|
||||
int fd = open(hp, O_WRONLY | O_CREAT | O_EXCL, 0644);
|
||||
if (fd < 0) return err_res("create", hp);
|
||||
int rc = ftruncate(fd, sz); int e = errno; close(fd);
|
||||
@@ -598,7 +644,7 @@ HLE_FORCE("_ZN2nn2fs10CreateFileEPKcl", "fsp-srv → open(O_CREAT|O_EXCL)+ftrunc
|
||||
errno = e; return rc ? err_res("create", hp) : RES_OK;
|
||||
}
|
||||
HLE_FORCE("_ZN2nn2fs10DeleteFileEPKc", "fsp-srv → unlink(2)", Result, h_fs_DeleteFile, const char *path) { HP(path); RW(); return unlink(hp) ? err_res("unlink", hp) : RES_OK; }
|
||||
HLE_FORCE("_ZN2nn2fs15CreateDirectoryEPKc", "fsp-srv → mkdir(2)", Result, h_fs_CreateDirectory, const char *path) { HP_EX(path, 1); RW();
|
||||
HLE_FORCE("_ZN2nn2fs15CreateDirectoryEPKc", "fsp-srv → mkdir(2)", Result, h_fs_CreateDirectory, const char *path) { HP_EX(path, 1); RW_CREATE();
|
||||
if (mkdir(hp, 0755)) return err_res("mkdir", hp);
|
||||
if (set_guest_name(hp, path)) { int e = errno; rmdir(hp); errno = e; return err_res("mkdir name", hp); }
|
||||
return RES_OK; }
|
||||
@@ -621,7 +667,10 @@ HLE_FORCE("_ZN2nn2fs10RenameFileEPKcS2_", "fsp-srv → rename(2)", Result, h_fs_
|
||||
if (!host_path_ex(to, hp2, sizeof hp2, NULL, 1)) return err_res("rename path", to);
|
||||
if (!access(hp2, F_OK)) return RES_PATH_EXISTS;
|
||||
if (rename(hp, hp2)) return err_res("rename", hp);
|
||||
if (set_guest_name(hp2, to)) { int e = errno; if (rename(hp2, hp)) die("fs 改名元数据失败且回退失败 errno=%d", errno); errno = e; return err_res("rename name", hp2); }
|
||||
if (dm_fs_test_fail("guestname") || set_guest_name(hp2, to)) { int e = errno ? errno : EIO;
|
||||
if (dm_fs_test_fail("renameback") || rename(hp2, hp)) { // 回退也失败:文件留在新路径、客体名元数据不对;不退出——在事务存档里就让本事务提交被拒(已提交版本不变,重新克隆即复原) | Rollback also failed: the file stays at the new path with wrong guest-name metadata; do not exit. In a transactional save, this transaction's commit is refused (the committed version is unchanged and recloning restores it)
|
||||
LOG("【红】fs 改名元数据失败且回退失败 errno=%d:%s 留在新路径%s", errno, hp2, in_txn_dir(hp2) ? ",本事务存档提交将被拒" : ""); if (in_txn_dir(hp2)) save_poison(e); }
|
||||
errno = e; return err_res("rename name", hp2); }
|
||||
return RES_OK;
|
||||
}
|
||||
HLE_FORCE("_ZN2nn2fs12GetEntryTypeEPNS0_18DirectoryEntryTypeEPKc", "fsp-srv → stat(2)", Result, h_fs_GetEntryType, int32_t *out, const char *path) {
|
||||
@@ -678,6 +727,7 @@ HLE_FORCE("_ZN2nn2fs13OpenDirectoryEPNS0_15DirectoryHandleEPKci", "fsp-srv → o
|
||||
*out = (uint64_t)h; return RES_OK;
|
||||
}
|
||||
HLE_FORCE("_ZN2nn2fs13ReadDirectoryEPlPNS0_14DirectoryEntryENS0_15DirectoryHandleEl", "fsp-srv → readdir(3)", Result, h_fs_ReadDirectory, int64_t *count, DirectoryEntry *ents, uint64_t hh, int64_t max) {
|
||||
if (!hh) { *count = 0; return RES_FAIL; }
|
||||
PATH_LOCK(); dirh_t *h = (dirh_t *)hh; int64_t n = 0; struct dirent *e;
|
||||
if (h->snap) { while (n < max && h->psnap < h->nsnap) { DirectoryEntry *src = &h->snap[h->psnap++]; if (!(h->mode & (src->type == ENT_DIR ? DIRMODE_DIR : DIRMODE_FILE))) continue; ents[n++] = *src; } *count = n; return RES_OK; }
|
||||
while (n < max && (e = readdir(h->d))) {
|
||||
@@ -694,5 +744,6 @@ HLE_FORCE("_ZN2nn2fs13ReadDirectoryEPlPNS0_14DirectoryEntryENS0_15DirectoryHandl
|
||||
*count = n; return RES_OK;
|
||||
}
|
||||
HLE_FORCE("_ZN2nn2fs14CloseDirectoryENS0_15DirectoryHandleE", "fsp-srv → closedir(3)", void, h_fs_CloseDirectory, uint64_t hh) {
|
||||
if (!hh) return; // 游戏在打开失败后也会关(句柄是 0):原版无事可做 | The game also closes after a failed open (handle 0): nothing to do in the original either
|
||||
dirh_t *h = (dirh_t *)hh; closedir(h->d); if (h->od) closedir(h->od); free(h->snap); free(h);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,30 @@
|
||||
// Stop background threads (boot block prefetch), pause audio, suspend graphics (wait for in-flight NVN calls to end and drain GPU work), then _exit(0); a 1.5 s fallback goes straight to _exit(0).
|
||||
// The default action also exits in about 0.08 s (exit code 143); the value of this function is stopping background threads in order, exit code 0, and giving the iOS lifecycle callback an entry.
|
||||
#include "hle.h"
|
||||
#if defined(__APPLE__)
|
||||
#include <dispatch/dispatch.h>
|
||||
#else
|
||||
#include <pthread.h>
|
||||
#include <time.h>
|
||||
// Linux 无 GCD:兜底计时与 SIGTERM 收尾各用一个分离线程;信号处理器只往自管道写一个字节(异步信号安全)
|
||||
// Linux has no GCD: the fallback timer and the SIGTERM wrap-up each use a detached thread; the signal handler only writes one byte to a self-pipe (async-signal-safe)
|
||||
static void *shutdown_watchdog(void *arg) {
|
||||
(void)arg; struct timespec ts = {1, 500000000}; while (nanosleep(&ts, &ts)) {}
|
||||
LOG("【红】优雅退出 1.5 秒未完成,直接退出"); _exit(0);
|
||||
}
|
||||
static int g_term_pipe[2] = {-1, -1};
|
||||
static void term_handler(int sig) { (void)sig; char c = 1; ssize_t r = write(g_term_pipe[1], &c, 1); (void)r; }
|
||||
void dm_host_shutdown(const char *why);
|
||||
static void *term_thread(void *arg) {
|
||||
(void)arg; char c;
|
||||
while (read(g_term_pipe[0], &c, 1) != 1) {}
|
||||
dm_host_shutdown("SIGTERM"); return NULL;
|
||||
}
|
||||
static void spawn_detached(void *(*fn)(void *)) {
|
||||
pthread_t t; pthread_attr_t a; pthread_attr_init(&a); pthread_attr_setdetachstate(&a, PTHREAD_CREATE_DETACHED);
|
||||
pthread_create(&t, &a, fn, NULL); pthread_attr_destroy(&a);
|
||||
}
|
||||
#endif
|
||||
#include <stdatomic.h>
|
||||
#include <signal.h>
|
||||
#include <unistd.h>
|
||||
@@ -15,8 +38,12 @@ void hlecount_flush(void);
|
||||
void dm_host_shutdown(const char *why) {
|
||||
static _Atomic int once; if (atomic_exchange(&once, 1)) return;
|
||||
uint64_t t0 = now_ns(); LOG("收到 %s:优雅退出", why);
|
||||
#if defined(__APPLE__)
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1500 * NSEC_PER_MSEC), dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), ^{
|
||||
LOG("【红】优雅退出 1.5 秒未完成,直接退出"); _exit(0); });
|
||||
#else
|
||||
spawn_detached(shutdown_watchdog);
|
||||
#endif
|
||||
tact_prefetch_stop();
|
||||
granny_prof_dump();
|
||||
hlecount_flush(); // DM_HLECOUNT:_exit 不走 atexit,这里写一份 | DM_HLECOUNT: _exit does not run atexit, write a copy here
|
||||
@@ -26,9 +53,16 @@ void dm_host_shutdown(const char *why) {
|
||||
_exit(0);
|
||||
}
|
||||
void dm_term_install(void) {
|
||||
#if !defined(__APPLE__)
|
||||
if (pipe(g_term_pipe)) return;
|
||||
spawn_detached(term_thread);
|
||||
struct sigaction sa = {0}; sa.sa_handler = term_handler; sa.sa_flags = SA_RESTART | SA_ONSTACK; sigemptyset(&sa.sa_mask);
|
||||
sigaction(SIGTERM, &sa, NULL);
|
||||
#else
|
||||
signal(SIGTERM, SIG_IGN); // 不走缺省动作:交给 GCD 信号源在普通线程上收尾 | do not take the default action: hand over to the GCD signal source to wrap up on an ordinary thread
|
||||
static dispatch_source_t src;
|
||||
src = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGTERM, 0, dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0));
|
||||
dispatch_source_set_event_handler(src, ^{ dm_host_shutdown("SIGTERM"); });
|
||||
dispatch_resume(src);
|
||||
#endif
|
||||
}
|
||||
|
||||
+32
-4
@@ -133,7 +133,7 @@ HLE_FORCE("_ZN2nn2oe20SetFocusHandlingModeENS0_17FocusHandlingModeE", "前后台
|
||||
// 界面层与 Final Result 仍按输出尺寸(+0xee88 / +0xee8c)建,末端由游戏自己的放大着色器 ps_upsample_p 放回输出尺寸。
|
||||
// 启动流程不调 0x8582f0,所以要主动调一次;调用点必须是游戏主线程取系统通知处——游戏自己处理模式切换的同一上下文
|
||||
// (在出图 HLE 里调会自锁:渲染锁已被出图路径持有)。
|
||||
// 缺省:iOS 0.75,Mac 宿主 1.0(画面闸门对 Switch 真值比);DM_3D_SCALE=0.5–1.0 覆盖。
|
||||
// 缺省:iOS 0.75,安卓 0.8(3D 720 档),Mac 宿主 1.0(画面闸门对 Switch 真值比);DM_3D_SCALE=0.5–1.0 覆盖。
|
||||
// 视觉尺子真值阶段(DM_NVN_RULER=1 的 A / B)强制 1.0,切到被测模式后才生效。
|
||||
// 动态比例(系统降频看的是占用率,温控档位只是粗信号 → 按实际掉帧调):控制器吃出图线程报来的实际上屏间隔
|
||||
// (与 perf.txt 同源),三级 配置值(0.75) → 0.72 → 0.70;下限 0.70(实看 0.65 有差别)。规则见 scale3d_ctl_step。
|
||||
@@ -146,7 +146,7 @@ HLE_FORCE("_ZN2nn2oe20SetFocusHandlingModeENS0_17FocusHandlingModeE", "前后台
|
||||
// the UI layer and Final Result are still built at the output size (+0xee88 / +0xee8c), and at the end the game's own upscale shader ps_upsample_p brings it back to the output size.
|
||||
// The boot flow does not call 0x8582f0, so it has to be called once actively; the call site must be where the game main thread fetches system notifications -- the same context in which the game itself handles mode switches
|
||||
// (calling it in the present HLE self-deadlocks: the render lock is already held by the present path).
|
||||
// Default: iOS 0.75, Mac host 1.0 (the screenshot gate compares against Switch ground truth); DM_3D_SCALE=0.5–1.0 overrides.
|
||||
// Default: iOS 0.75, Android 0.8 (3D at the 720 level), Mac host 1.0 (the screenshot gate compares against Switch ground truth); DM_3D_SCALE=0.5–1.0 overrides.
|
||||
// The visual ruler ground truth phase (A / B of DM_NVN_RULER=1) forces 1.0, it only takes effect after switching to the mode under test.
|
||||
// Dynamic scale (system throttling looks at utilization, the thermal state is only a coarse signal → adjust by actual dropped frames): the controller consumes the actual present intervals reported by the present thread
|
||||
// (same source as perf.txt), three levels configured value (0.75) → 0.72 → 0.70; lower limit 0.70 (0.65 is visibly different). For the rules see scale3d_ctl_step.
|
||||
@@ -155,6 +155,14 @@ HLE_FORCE("_ZN2nn2oe20SetFocusHandlingModeENS0_17FocusHandlingModeE", "前后台
|
||||
#include <TargetConditionals.h>
|
||||
#define SCALE3D_MIN 0.70f
|
||||
#define SCALE3D_MID 0.72f
|
||||
// 安卓缺省按 3D 目标高 720 定比例(掌机档;输出高 1080 时 0.667、900 时 0.8),界面按输出高画;动态两级按同一比例跟着降(720 → 648 → 630 高,即旧的 0.72 / 0.70 × 900)。
|
||||
// DM_3D_SCALE 给了就照旧按绝对比例
|
||||
// Android default derives the scale from a 720-high 3D target (handheld level; 0.667 at output height 1080, 0.8 at 900), the UI is drawn at the output height; the two dynamic levels drop in the same proportion (720 -> 648 -> 630 high, i.e. the old 0.72 / 0.70 x 900).
|
||||
// When DM_3D_SCALE is given, absolute scales as before
|
||||
#ifdef __ANDROID__
|
||||
#define DM_3D_H_ANDROID 720.0f
|
||||
#endif
|
||||
#define DM_3D_SCALE_ANDROID 1.0f
|
||||
// 纯函数控制器(单测 t_oe.c 直接喂序列):level 0 = 配置值,越大越低。安全阀:只在可感的掉帧时动。
|
||||
// 窗:每累计 2 秒的上屏间隔一个窗,窗内帧率 = 上屏帧数 ÷ 间隔之和(被系统丢掉的帧不计数,那段时间落在下一张上屏帧的间隔里)。
|
||||
// 降:连续两个窗的帧率都 < 目标 × 0.92(60 帧时 55.2)→ 降一级。
|
||||
@@ -219,11 +227,31 @@ float dm_3d_scale_cur(void) { return atomic_load(&g_scale3d_cur); }
|
||||
static void scale3d_tick(void) {
|
||||
static float want_cfg = -1, cur = 1.0f; static module_t *main;
|
||||
if (want_cfg < 0) {
|
||||
const char *e = getenv("DM_3D_SCALE"); want_cfg = TARGET_OS_IPHONE ? 0.75f : 1.0f;
|
||||
const char *e = getenv("DM_3D_SCALE"); want_cfg = TARGET_OS_IPHONE ? 0.75f : DM_3D_SCALE_ANDROID;
|
||||
if (e) { char *end; float v = strtof(e, &end); if (end == e || *end || !(v >= 0.5f && v <= 1.0f)) die("DM_3D_SCALE 非法:%s(要求 0.5–1.0)", e); want_cfg = v; }
|
||||
#ifdef DM_3D_H_ANDROID
|
||||
else want_cfg = 0; // 0 = 按 3D 目标高算(要等读到输出高) | 0 = derive from the 3D target height (needs the output height first)
|
||||
#endif
|
||||
for (int i = 0; i < g_nmod; i++) if (!strcmp(g_mod[i].name, "main")) main = &g_mod[i];
|
||||
}
|
||||
int lv = atomic_load(&g_scale3d_level); // 动态级:0 = 配置值,1 = 0.72,2 = 0.70(都不高于配置值) | dynamic level: 0 = configured value, 1 = 0.72, 2 = 0.70 (none higher than the configured value)
|
||||
#ifdef DM_3D_H_ANDROID
|
||||
if (!want_cfg) {
|
||||
if (!main || dm_nvn_frame_count() < 30) return;
|
||||
uintptr_t renderer = *(uintptr_t *)(main->base + 0x31e0848); if (!renderer) return;
|
||||
uint32_t oh = *(uint32_t *)(renderer + 0xee8c); if (!oh) return;
|
||||
float cfg = DM_3D_H_ANDROID / oh; if (cfg > 1.0f) cfg = 1.0f; if (cfg < 0.5f) cfg = 0.5f;
|
||||
float dyn = lv == 0 ? cfg : cfg * (lv == 1 ? SCALE3D_MID : SCALE3D_MIN) / 0.8f, want = dm_nvn_ruler_truth() ? 1.0f : dyn;
|
||||
if (want == cur) return;
|
||||
uint32_t ow = *(uint32_t *)(renderer + 0xee88); if (!ow) return;
|
||||
{ extern void mtl_rt_force_full(int) __attribute__((weak)); if (mtl_rt_force_full) mtl_rt_force_full(4); }
|
||||
float *scale = (float *)(renderer + 0x66a4); dm_guest_write_prepare(scale, sizeof *scale); *scale = want;
|
||||
((void (*)(uint32_t, uint32_t))(main->base + 0x8582f0))(ow, oh);
|
||||
cur = want; atomic_store(&g_scale3d_cur, want);
|
||||
LOG("3D 渲染比例 %.3f:3D 目标 %ux%u,输出 %ux%u(帧 %llu)", want, *(uint32_t *)(renderer + 0xee78), *(uint32_t *)(renderer + 0xee7c), ow, oh, (unsigned long long)dm_nvn_frame_count());
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
float dyn = lv == 0 ? want_cfg : lv == 1 ? SCALE3D_MID : SCALE3D_MIN; if (dyn > want_cfg) dyn = want_cfg;
|
||||
float want = dm_nvn_ruler_truth() ? 1.0f : dyn;
|
||||
if (want == cur || !main || dm_nvn_frame_count() < 30) return;
|
||||
@@ -249,7 +277,7 @@ HLE_FORCE("_ZN2nn2oe25TryPopNotificationMessageEPj", "系统通知队列;前
|
||||
// The resolution parameter bits live in the thread slot, and the game reads them on the thread that fetches notifications to change the render size (on receiving 31 "performance mode changed", from main+0xe10ddc; 30 only updates a flag).
|
||||
// When they are read: each time the handler is entered, once after the first notification is fetched (0xe10d5c / 0xe10d60), and notifications fetched later in the loop still use the values from that read. So every time one is taken, the value due at this moment is written into the current thread's slot --
|
||||
// writing only when 31 is taken is not enough: when 31 is queued behind another notification (e.g. focus 15), the parameter bits have already been read after fetching 15 (iOS app: the front end did not switch to 16:9, in the Mac host run 31 happened to be queued first).
|
||||
if (ok) for (int i = 0; i < 2; i++) if (g_keyres[i]) pthread_setspecific(g_keyres[i], (void *)dm_game_res(i));
|
||||
if (ok) for (int i = 0; i < 2; i++) if (g_keyres[i]) dm_slot_set(g_keyres[i], (void *)dm_game_res(i));
|
||||
if (ok && *msg == MSG_PERFMODE) dm_uiscreen_res_reread();
|
||||
if (ok) LOG("oe 通知被游戏取走:%u", *msg); // 状态变化很少,逐条打不刷屏 | state changes are rare, printing each one does not flood the log
|
||||
return ok;
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
#include <ctype.h>
|
||||
#include <time.h>
|
||||
typedef struct { const char *name; void *fn; } hle_ent;
|
||||
#define L(n) __attribute__((used, section("__DATA,swhle"))) static const hle_ent hle_lib_##n = { #n, (void *)n };
|
||||
#define L(n) __attribute__((used, DM_SECT("swhle"))) static const hle_ent hle_lib_##n = { #n, (void *)n };
|
||||
L(memcpy) L(memset) L(memmove) L(memcmp) L(memchr) L(strlen) L(strnlen) L(strcmp) L(strncmp)
|
||||
L(strcpy) L(strncpy) L(strcat) L(strncat) L(strchr) L(strrchr) L(strstr) L(strspn) L(strcspn)
|
||||
L(strpbrk) L(strcasecmp) L(strncasecmp) L(atoi) L(atof) L(strtol) L(strtoul) L(strtoll) L(strtoull)
|
||||
|
||||
+54
-4
@@ -28,6 +28,41 @@ static pthread_key_t key_value(unsigned i) {
|
||||
case KEY_KASPECT: return g_keyaspect; default: return g_keyaspectui;
|
||||
}
|
||||
}
|
||||
#ifndef __APPLE__
|
||||
// Linux / Android:槽块挂在 tp[2](bionic TLS_SLOT_APP,留给应用、libc 不用);块随线程退出释放并清 tp[2]
|
||||
// Linux / Android: the slot block hangs off tp[2] (bionic TLS_SLOT_APP, reserved for the app and unused by libc); the block is freed and tp[2] cleared when the thread exits
|
||||
#define SLOT_N 16
|
||||
static pthread_key_t g_slot_owner;
|
||||
static pthread_once_t g_slot_once = PTHREAD_ONCE_INIT;
|
||||
static void slot_free(void *p) {
|
||||
uint64_t *tp = __builtin_thread_pointer();
|
||||
if (tp[2] == (uint64_t)p) tp[2] = 0;
|
||||
free(p);
|
||||
}
|
||||
static void slot_once(void) { if (pthread_key_create(&g_slot_owner, slot_free)) die("创建槽块键失败"); }
|
||||
uint64_t *dm_slot_block(void) {
|
||||
uint64_t *tp = __builtin_thread_pointer();
|
||||
if (tp[2]) return (uint64_t *)tp[2];
|
||||
pthread_once(&g_slot_once, slot_once);
|
||||
uint64_t *b = calloc(SLOT_N, 8);
|
||||
if (!b || pthread_setspecific(g_slot_owner, b)) die("分配槽块失败");
|
||||
tp[2] = (uint64_t)b;
|
||||
return b;
|
||||
}
|
||||
void dm_slot_set(pthread_key_t k, void *v) {
|
||||
if (!k || k >= SLOT_N) die("槽号越界 %lu", (unsigned long)k);
|
||||
dm_slot_block()[k] = (uint64_t)v;
|
||||
}
|
||||
static void create_keys(void) {
|
||||
// 键号从 1 起(键页项为 0 视为没建)
|
||||
// Key numbers start at 1 (a key page entry of 0 means "not created")
|
||||
pthread_key_t *ks[] = {&g_key18, &g_keytls, &g_keytlr, &g_keygate, &g_keyres[0], &g_keyres[1], &g_keyaspect, &g_keyaspectui};
|
||||
for (unsigned i = 0; i < 8; i++) *ks[i] = i + 1;
|
||||
LOG("槽号 K18=%lu KTLS=%lu KTLR=%lu KGATE=%lu KRES0=%lu KRES1=%lu KASPECT=%lu KASPECTUI=%lu",
|
||||
(unsigned long)g_key18, (unsigned long)g_keytls, (unsigned long)g_keytlr, (unsigned long)g_keygate,
|
||||
(unsigned long)g_keyres[0], (unsigned long)g_keyres[1], (unsigned long)g_keyaspect, (unsigned long)g_keyaspectui);
|
||||
}
|
||||
#else
|
||||
static void create_keys(void) {
|
||||
if (pthread_key_create(&g_key18, NULL) || pthread_key_create(&g_keytls, NULL) ||
|
||||
pthread_key_create(&g_keytlr, NULL) || pthread_key_create(&g_keygate, NULL)) die("创建宿主键失败");
|
||||
@@ -38,15 +73,20 @@ static void create_keys(void) {
|
||||
LOG("键号 K18=%lu KTLS=%lu KTLR=%lu KGATE=%lu KRES0=%lu KRES1=%lu KASPECT=%lu KASPECTUI=%lu",
|
||||
g_key18, g_keytls, g_keytlr, g_keygate, g_keyres[0], g_keyres[1], g_keyaspect, g_keyaspectui);
|
||||
}
|
||||
#endif
|
||||
|
||||
// K 槽校验:pthread TSD 布局固定,槽 = tpidrro_el0 + 8*key
|
||||
// K slot check: the pthread TSD layout is fixed, slot = tpidrro_el0 + 8*key
|
||||
static void tsd_check(void) {
|
||||
pthread_setspecific(g_key18, (void *)0x1234);
|
||||
dm_slot_set(g_key18, (void *)0x1234);
|
||||
#ifdef __APPLE__
|
||||
uint64_t base; __asm__ volatile("mrs %0, tpidrro_el0" : "=r"(base));
|
||||
#else
|
||||
uint64_t base = ((uint64_t *)__builtin_thread_pointer())[2];
|
||||
#endif
|
||||
uint64_t off = *(uint64_t *)(g_mod[0].base + g_mod[0].key_page_off + g_mod[0].key_idx[KEY_K18] * 8);
|
||||
if (((uint64_t *)(base & ~7ull))[off / 8] != 0x1234) die("TSD 布局不符");
|
||||
pthread_setspecific(g_key18, 0);
|
||||
dm_slot_set(g_key18, 0);
|
||||
}
|
||||
|
||||
static void build_symhash(module_t *m);
|
||||
@@ -154,8 +194,12 @@ static void read_layout(module_t *m, const char *dir) {
|
||||
FILE *f = fopen(path, "r");
|
||||
if (!f) die("open %s", path);
|
||||
static const char *kn[8] = {"K18", "KTLS", "KTLR", "KGATE", "KRES0", "KRES1", "KASPECT", "KASPECTUI"};
|
||||
char line[256], key[32]; unsigned long v; unsigned seen = 0;
|
||||
char line[256], key[32], abi[32] = "apple"; unsigned long v, tp_off = 0; unsigned seen = 0;
|
||||
while (fgets(line, sizeof line, f)) {
|
||||
// 改写器 ABI(DM_ABI=android 出 linux-bionic,槽基址取 [tpidr_el0 + TP_SLOT_OFF]);Apple 产物没有这行
|
||||
// Rewriter ABI (DM_ABI=android emits linux-bionic, slot base taken from [tpidr_el0 + TP_SLOT_OFF]); Apple outputs have no such line
|
||||
if (sscanf(line, "# ABI %31s", abi) == 1) continue;
|
||||
if (sscanf(line, "# TP_SLOT_OFF %lx", &tp_off) == 1) continue;
|
||||
if (sscanf(line, "# %31s %lx", key, &v) != 2) die("%s: 产物是旧改写器出的,换成当前代号(dm/PRODUCT)的产物", path);
|
||||
if (!strcmp(key, "PATCH_OFF")) m->patch_off = v;
|
||||
else if (!strcmp(key, "KEY_PAGE_OFF")) m->key_page_off = v;
|
||||
@@ -171,6 +215,11 @@ static void read_layout(module_t *m, const char *dir) {
|
||||
}
|
||||
}
|
||||
fclose(f);
|
||||
#ifdef __APPLE__
|
||||
if (strcmp(abi, "apple")) die("%s: 产物 ABI 是 %s,Apple 宿主要 DM_ABI=apple 的产物", path, abi);
|
||||
#else
|
||||
if (strcmp(abi, "linux-bionic") || tp_off != 0x10) die("%s: 产物 ABI 是 %s(TP_SLOT_OFF %#lx),Android 宿主要 DM_ABI=android 的产物", path, abi, tp_off);
|
||||
#endif
|
||||
if (!m->patch_off || m->key_page_off % 0x4000 || m->key_page_size != 0x4000 || seen != 0xff)
|
||||
die("%s: 产物是旧改写器出的,换成当前代号(dm/PRODUCT)的产物", path);
|
||||
}
|
||||
@@ -196,7 +245,8 @@ static void register_gates(module_t *m, const char *dir) {
|
||||
if (sscanf(line, "%lx %15s %d %lx", &ret, kind, &arg, &orig) == 4) { gate_register((uint64_t)m->base + ret, kind, arg, orig); ng++; }
|
||||
fclose(f);
|
||||
}
|
||||
LOG("%s: gates %d patch_off %#llx keys %lu/%lu/%lu/%lu", m->name, ng, m->patch_off, g_key18, g_keytls, g_keytlr, g_keygate);
|
||||
LOG("%s: gates %d patch_off %#llx keys %lu/%lu/%lu/%lu", m->name, ng, m->patch_off,
|
||||
(unsigned long)g_key18, (unsigned long)g_keytls, (unsigned long)g_keytlr, (unsigned long)g_keygate);
|
||||
}
|
||||
|
||||
static void relocate(module_t *m) {
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
#include "dm.h"
|
||||
#include "front.h"
|
||||
#include <stdatomic.h>
|
||||
#if defined(__APPLE__)
|
||||
#include <sys/sysctl.h>
|
||||
#endif
|
||||
#include <sys/time.h>
|
||||
#include <unistd.h>
|
||||
void probe_install(void); void ticks_install(void); void hid_keys_init(void); void tact_prefetch_start(const char *outdir); void tact_chk_init(void); void stubs_report(void); void crash_install(void); void guest_thread_init(void); uint32_t svc_thread_main_init(void);
|
||||
@@ -90,11 +92,25 @@ static void flags_init(void) {
|
||||
// 启动时间线零点 = 进程创建时刻(sysctl KERN_PROC_PID 的 p_starttime,墙钟)换算到 now_ns 单调时基;Mac / iOS 同口径
|
||||
// Zero point of the boot timeline = process creation time (p_starttime from sysctl KERN_PROC_PID, wall clock) converted to the now_ns monotonic time base; same definition on Mac / iOS
|
||||
static uint64_t proc_start_mono_ns(void) {
|
||||
#if !defined(__APPLE__)
|
||||
// Linux:/proc/self/stat 第 22 字段 starttime(开机起的时钟滴答,含挂起)对 CLOCK_BOOTTIME 求进程年龄
|
||||
// Linux: field 22 of /proc/self/stat, starttime (clock ticks since boot, including suspend), against CLOCK_BOOTTIME gives the process age
|
||||
uint64_t mono = now_ns(); char b[1024] = {0};
|
||||
FILE *f = fopen("/proc/self/stat", "r"); if (!f) return mono;
|
||||
size_t n = fread(b, 1, sizeof b - 1, f); fclose(f); b[n] = 0;
|
||||
char *p = strrchr(b, ')'); unsigned long long st = 0;
|
||||
for (int i = 2; p && i < 22; i++) p = strchr(p + 1, ' '); // ')' 之后是第 3 字段 | field 3 follows ')'
|
||||
if (!p || sscanf(p + 1, "%llu", &st) != 1) return mono;
|
||||
struct timespec ts; clock_gettime(CLOCK_BOOTTIME, &ts);
|
||||
int64_t age = (int64_t)ts.tv_sec * 1000000000ll + ts.tv_nsec - (int64_t)(st * 1000000000ull / (unsigned long long)sysconf(_SC_CLK_TCK));
|
||||
return age > 0 ? mono - (uint64_t)age : mono;
|
||||
#else
|
||||
struct kinfo_proc kp; size_t n = sizeof kp; int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()};
|
||||
uint64_t mono = now_ns(); struct timeval tv; gettimeofday(&tv, NULL);
|
||||
if (sysctl(mib, 4, &kp, &n, NULL, 0) || !n) return mono;
|
||||
int64_t age = (int64_t)(tv.tv_sec - kp.kp_proc.p_starttime.tv_sec) * 1000000000ll + (tv.tv_usec - kp.kp_proc.p_starttime.tv_usec) * 1000ll;
|
||||
return age > 0 ? mono - (uint64_t)age : mono;
|
||||
#endif
|
||||
}
|
||||
|
||||
// 宿主装载(与 UIKit / Metal 无关):读 NSO、重定位、强制接管、探针 / 拍门 / 按键、预取起跑。缺省在 main 里同步跑;
|
||||
|
||||
@@ -104,11 +104,11 @@ $(B)/t_touch: t_touch.c ../hle_touch.c ../front.h ../dm.h | $(B)
|
||||
$(B)/t_fs: t_fs.c t_fs_stub.c ../hle_fs.c ../hle.h ../dm.h ../dm_i18n.c | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -o $@ t_fs.c t_fs_stub.c ../dm_i18n.c
|
||||
$(B)/t_audio: t_audio.c ../hle_audio.c ../hle.h ../dm.h | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -o $@ t_audio.c -framework AudioToolbox
|
||||
clang -O1 -Wno-unused-function -I.. -o $@ t_audio.c -framework AudioToolbox -framework CoreAudio -framework CoreFoundation
|
||||
$(B)/t_audio_spsc: t_audio_spsc.c ../hle_audio.c ../hle.h ../dm.h | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -o $@ t_audio_spsc.c -framework AudioToolbox
|
||||
clang -O1 -Wno-unused-function -I.. -o $@ t_audio_spsc.c -framework AudioToolbox -framework CoreAudio -framework CoreFoundation
|
||||
$(B)/t_audio_spsc_tsan: t_audio_spsc.c ../hle_audio.c ../hle.h ../dm.h | $(B)
|
||||
clang -O1 -g -O1 -fsanitize=thread -Wno-unused-function -I.. -o $@ t_audio_spsc.c -framework AudioToolbox
|
||||
clang -O1 -g -O1 -fsanitize=thread -Wno-unused-function -I.. -o $@ t_audio_spsc.c -framework AudioToolbox -framework CoreAudio -framework CoreFoundation
|
||||
$(B)/t_swkbd: t_swkbd.c ../hle_swkbd.c ../hle.h ../dm.h | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -o $@ t_swkbd.c ../hle_swkbd.c
|
||||
$(B)/t_movie: t_movie.c ../hle_movie.c ../hle.h ../dm.h | $(B)
|
||||
@@ -132,16 +132,16 @@ $(B)/t_fs_case: t_fs_case.c ../hle_fs.c ../hle.h ../dm.h ../dm_i18n.c | $(B)
|
||||
$(B)/t_romfs_validate: t_romfs_validate.c ../romfs_validate.c ../romfs_validate.h ../dm_i18n.c ../dm_i18n_tab.h | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -o $@ t_romfs_validate.c ../romfs_validate.c ../dm_i18n.c
|
||||
|
||||
$(B)/t_hid_script: t_hid_script.c t_touch_tick_stub.c ../hle_hid.c ../dm_cursor.c ../dm_hud.c ../dm_hud.h ../touch_mac.c ../../ios/Sources/dm_touch_controls.c ../hle.h ../dm.h ../dm_input.h ../front.h | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -I../../ios/Sources -o $@ t_hid_script.c t_touch_tick_stub.c ../dm_cursor.c ../dm_hud.c ../touch_mac.c ../../ios/Sources/dm_touch_controls.c -lm
|
||||
$(B)/t_hid_script: t_hid_script.c t_touch_tick_stub.c ../hle_hid.c ../dm_cursor.c ../dm_hud.c ../dm_hud.h ../touch_mac.c ../../touch/dm_touch_controls.c ../hle.h ../dm.h ../dm_input.h ../front.h | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -I../../touch -o $@ t_hid_script.c t_touch_tick_stub.c ../dm_cursor.c ../dm_hud.c ../touch_mac.c ../../touch/dm_touch_controls.c -lm
|
||||
|
||||
$(B)/t_oe: t_oe.c ../hle_oe.c ../hle.h ../dm.h | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -o $@ t_oe.c
|
||||
|
||||
$(B)/t_hid_receipt: t_hid_receipt.c t_touch_tick_stub.c ../hle_hid.c ../dm_cursor.c ../dm_hud.c ../dm_hud.h ../touch_mac.c ../../ios/Sources/dm_touch_controls.c ../hle.h ../dm.h ../dm_input.h ../front.h | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -I../../ios/Sources -o $@ t_hid_receipt.c t_touch_tick_stub.c ../dm_cursor.c ../dm_hud.c ../touch_mac.c ../../ios/Sources/dm_touch_controls.c -lm
|
||||
$(B)/t_touch_mac: t_touch_mac.c ../touch_mac.c ../dm_cursor.c ../dm_hud.c ../dm_hud.h ../../ios/Sources/dm_touch_controls.c ../../ios/Sources/dm_touch_controls.h ../../host/dm_input.h | $(B) # 测试 #include 了 touch_mac.c 与 dm_touch_controls.c,须列为依赖(漏列致改源不重编) | the test #includes touch_mac.c and dm_touch_controls.c, which must be listed as dependencies (omitting them means source changes do not trigger a rebuild)
|
||||
clang -std=c11 -Wall -Wextra -Werror -I.. -I../../ios/Sources -o $@ t_touch_mac.c ../dm_cursor.c ../dm_hud.c -lm
|
||||
$(B)/t_hid_receipt: t_hid_receipt.c t_touch_tick_stub.c ../hle_hid.c ../dm_cursor.c ../dm_hud.c ../dm_hud.h ../touch_mac.c ../../touch/dm_touch_controls.c ../hle.h ../dm.h ../dm_input.h ../front.h | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -I../../touch -o $@ t_hid_receipt.c t_touch_tick_stub.c ../dm_cursor.c ../dm_hud.c ../touch_mac.c ../../touch/dm_touch_controls.c -lm
|
||||
$(B)/t_touch_mac: t_touch_mac.c ../touch_mac.c ../dm_cursor.c ../dm_hud.c ../dm_hud.h ../../touch/dm_touch_controls.c ../../touch/dm_touch_controls.h ../../host/dm_input.h | $(B) # 测试 #include 了 touch_mac.c 与 dm_touch_controls.c,须列为依赖(漏列致改源不重编) | the test #includes touch_mac.c and dm_touch_controls.c, which must be listed as dependencies (omitting them means source changes do not trigger a rebuild)
|
||||
clang -std=c11 -Wall -Wextra -Werror -I.. -I../../touch -o $@ t_touch_mac.c ../dm_cursor.c ../dm_hud.c -lm
|
||||
$(B)/t_target_rank: t_target_rank.c ../hle_target.c ../dm.h | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -o $@ t_target_rank.c ../hle_target.c
|
||||
$(B)/t_rift_clock: t_rift_clock.c ../dm_rift.c ../dm_rift.h ../hle_os.c ../hle.h ../dm.h | $(B)
|
||||
|
||||
@@ -41,18 +41,32 @@ def vis_scan(text, where): # 直接写可见位的行;在带守卫的函数
|
||||
# Third check (position guard): in dm_cursor.c, writing a widget rectangle (+0x70 x, +0x74 y, +0x78 width, +0x7c height) is allowed only in mv_offset (original-game widgets, allow list + record original value + must write back)
|
||||
# and in ui_move_ours (only names starting with Touch). Two forms are recognized: a direct *(int32_t *)(... + 0x7?) = ...; or, within the same function, first taking int32_t *name = (int32_t *)(... + 0x7?) and then writing name[k] = / *name =
|
||||
RECT_OK = ('mv_offset', 'ui_move_ours')
|
||||
RECT_PTR = re.compile(r'int32_t\s*\*\s*(\w+)\s*=\s*\(int32_t\s*\*\)\s*\([^;]*\+\s*0x7[0-9a-c]\b')
|
||||
RECT_DIRECT = re.compile(r'\*\s*\(int32_t\s*\*\)\s*\([^)]*\+\s*0x7[0-9a-c]\)\s*=(?!=)')
|
||||
def rect_scan(text, where):
|
||||
RECT_OFFS = ['0x7%x' % i for i in range(13)] # 0x70–0x7c
|
||||
# 原版控件字段写入的登记例外(一项一行:文件、字段、只许在哪些函数里写、理由)。名单外的函数写这些字段一律报红
|
||||
# Registered exceptions for writes to original widget fields (one per line: file, field, which functions may write it, reason). Writes to these fields from functions not on the list are always red
|
||||
NATIVE_FIELD_OK = {
|
||||
('dm_cursor.c', '0x19c'): (('ui_note_dock_pump', 'note_dock_restore'), 'NotificationPanel 停靠目标 y:原版只在重排时按布局抄进、滑入滑出按它插值写 +0x74;'
|
||||
'改 +0x74 会被动画每帧盖回(试过)。原值我们自己记、停靠条件一结束当场写回(面板关 / 读取画面 / 保存并退出 / 回到前端)'),
|
||||
('dm_cursor.c', '0x74'): (('note_dock_snap',), 'NotificationPanel 矩形 y:停靠目标切换(开 / 关面板)那一刻框已停稳(原版停稳不写坐标)才写成新目标一次,动画期不写;写后下一帧核'),
|
||||
}
|
||||
def field_write_scan(text, where, off, ok, what):
|
||||
ptr = re.compile(r'(?:int32_t|,)\s*\*\s*(\w+)\s*=\s*\(int32_t\s*\*\)\s*\([^;)]*\+\s*%s' % off) # 基址只看本括号:同一行别的变量读别的字段不算;逗号后的第二个声明也认 | the base only counts within its own parentheses: other variables on the same line reading other fields do not count; a second declaration after a comma is recognised too
|
||||
direct = re.compile(r'\*\s*\(int32_t\s*\*\)\s*\([^)]*\+\s*%s\)\s*=(?!=)' % off)
|
||||
bad, fn, ptrs = [], None, set()
|
||||
for no, line in enumerate(text.split('\n'), 1):
|
||||
m = re.match(r'(?:static\s+)?\w+\s+\*?(\w+)\(', line)
|
||||
if m and not line.startswith(' '): fn, ptrs = m.group(1), set()
|
||||
code = line.split('//', 1)[0]
|
||||
for pm in RECT_PTR.finditer(code): ptrs.add(pm.group(1))
|
||||
code = RECT_PTR.sub('', code) # 声明那一处(int32_t *名 = …)本身不算写 | the declaration itself (int32_t *name = ...) does not count as a write
|
||||
hit = RECT_DIRECT.search(code) or any(re.search(r'(?<![\w.>])(?:\*\s*%s|%s\s*\[\s*\d\s*\])\s*=(?!=)' % (q, q), code) for q in ptrs)
|
||||
if hit and fn not in RECT_OK: bad.append('%s:%d 在 %s 里直接写了控件矩形(原版控件走 mv_offset、我们的走 ui_move_ours):%s' % (where, no, fn, line.strip()[:120]))
|
||||
for pm in ptr.finditer(code): ptrs.add(pm.group(1))
|
||||
code = ptr.sub('', code) # 声明那一处(int32_t *名 = …)本身不算写 | the declaration itself (int32_t *name = ...) does not count as a write
|
||||
hit = direct.search(code) or any(re.search(r'(?<![\w.>])(?:\*\s*%s|%s\s*\[\s*\d\s*\])\s*=(?!=)' % (q, q), code) for q in ptrs)
|
||||
if hit and fn not in ok: bad.append('%s:%d 在 %s 里直接写了%s:%s' % (where, no, fn, what, line.strip()[:120]))
|
||||
return bad
|
||||
def rect_scan(text, where):
|
||||
exc = [off for (f, off) in NATIVE_FIELD_OK if where.startswith(f) and off in RECT_OFFS] # 矩形字段的登记例外:从矩形扫描里拿出来,按例外单独扫 | registered exceptions for rectangle fields: taken out of the rectangle scan and scanned separately as exceptions
|
||||
bad = field_write_scan(text, where, '(?:%s)\\b' % '|'.join(o for o in RECT_OFFS if o not in exc), RECT_OK, '控件矩形(原版控件走 mv_offset、我们的走 ui_move_ours)')
|
||||
for (f, off), (fns, why) in NATIVE_FIELD_OK.items():
|
||||
if where.startswith(f): bad += field_write_scan(text, where, re.escape(off) + r'\b', fns + (RECT_OK if off in RECT_OFFS else ()), '原版控件字段 +%s(登记例外只许在 %s 里写)' % (off, ' / '.join(fns)))
|
||||
return bad
|
||||
|
||||
def pages_pump(src):
|
||||
@@ -66,6 +80,9 @@ def main():
|
||||
if not scan(' vu_show(vu_find(bk, "grid", 2), 0);', 'selftest') or scan(' vu_show(vu_find(vt, "TouchV_Back", 0), 1); // "grid" 只在注释里', 'selftest') \
|
||||
or not vis_scan('static void f(uint64_t w) {\n *(uint8_t *)(w + 0x50) = 0;\n}', 'selftest') or vis_scan('static void ui_show_ours(uint64_t w, int on) {\n *(uint8_t *)(w + 0x50) = 1;\n}\n if (*(uint8_t *)(w + 0x50) == 1) x();', 'selftest') \
|
||||
or not rect_scan('static void f(uint64_t w) {\n int32_t *r = (int32_t *)(w + 0x70); r[0] = 5;\n}', 'selftest') or not rect_scan('static void g(uint64_t w) {\n *(int32_t *)(w + 0x74) = 3;\n}', 'selftest') \
|
||||
or rect_scan('static void ui_note_dock_pump(uint64_t w) {\n int32_t *t = (int32_t *)(w + 0x19c), h = *(int32_t *)(w + 0x7c); *t = h;\n}', 'dm_cursor.c') \
|
||||
or not rect_scan('static void n(uint64_t w) {\n int32_t *t = (int32_t *)(w + 0x19c); *t = 1;\n}', 'dm_cursor.c') \
|
||||
or not rect_scan('static void n2(uint64_t w) {\n int32_t *t = (int32_t *)(w + 0x19c), *ry = (int32_t *)(w + 0x74); *ry = 1;\n}', 'dm_cursor.c') \
|
||||
or rect_scan('static void k(uint64_t w) {\n int32_t *rx = (int32_t *)(w + 0x70), ww = *(int32_t *)(w + 0x78); if (*rx) x();\n}\nstatic void mv_offset(uint64_t w) {\n int32_t *v = (int32_t *)(w + 0x70); *v = 1;\n}\nstatic int h(float *r) {\n r[0] = 1.0f; int x = *(int32_t *)(w + 0x70); return x;\n}', 'selftest'):
|
||||
print('✗ native_write_scan 自检失败:该报的没报或不该报的报了'); return 1
|
||||
print('✓ native_write_scan 自检:违规行会报红、注释里的名字不算')
|
||||
|
||||
@@ -13,6 +13,18 @@ static _Atomic int g_sig;
|
||||
void hle_signal_system_event(void *g) { (void)g; atomic_fetch_add_explicit(&g_sig, 1, memory_order_seq_cst); }
|
||||
void hle_bind_system_event(void *g, int autoclear) { (void)g; (void)autoclear; } // 真实现要客体线程 + SDK 内核事件;单测只数触发次数 | the real implementation needs a guest thread + SDK kernel event; the unit test only counts triggers
|
||||
int main(void) {
|
||||
{ // 5.1 下混(期望按 Q15 系数手算:0.707·0.707 = 16384/32768 = 0.5,0.707 = 23170/32768):顺序 左前 右前 中置 低音 左后 右后 | 5.1 downmix (expected values worked out by hand from the Q15 coefficients: 0.707*0.707 = 16384/32768 = 0.5, 0.707 = 23170/32768): order front left, front right, centre, LFE, rear left, rear right
|
||||
static const struct { int16_t in[6]; int16_t l, r; const char *what; } c[] = {
|
||||
{ { 0, 0, 10000, 0, 0, 0 }, 5000, 5000, "只有中置(对白)→ 左右各 5000" },
|
||||
{ { 0, 0, 0, 0, 10000, 0 }, 5000, 0, "只有左后 → 左 5000、右 0" },
|
||||
{ { 10000, 0, 0, 0, 0, 0 }, 7070, 0, "只有左前 → 左 7070(−3 dB)" },
|
||||
{ { 0, 0, 0, 30000, 0, 0 }, 0, 0, "只有低音 → 不并入,0" },
|
||||
{ { 32767, 32767, 32767, 0, 32767, 32767 }, 32767, 32767, "满幅叠加 → 饱和到 32767" },
|
||||
{ { -32768, -32768, -32768, 0, -32768, -32768 }, -32768, -32768, "负满幅叠加 → 饱和到 −32768" } };
|
||||
int bad = 0;
|
||||
for (unsigned i = 0; i < sizeof c / sizeof *c; i++) { int16_t o[2]; downmix51(c[i].in, o, 1); int ok = o[0] == c[i].l && o[1] == c[i].r; bad |= !ok;
|
||||
printf("下混:%s:期望 (%d,%d) → 真结果 (%d,%d) %s\n", c[i].what, c[i].l, c[i].r, o[0], o[1], ok ? "✓" : "✗"); }
|
||||
if (bad) return 1; }
|
||||
char out[64], ev[64]; uint8_t prm[16]; gbuf b[3]; static int16_t pcm[3][4800 * 2];
|
||||
h_au_InitParam(prm);
|
||||
if (h_au_Open(out, ev, NULL, prm)) return 1;
|
||||
|
||||
+75
-10
@@ -10,6 +10,8 @@
|
||||
#include <unistd.h>
|
||||
int dm_cloud_sync(const char *save, const char *cloud, const char *bak, const char *statef, int allow_down, uint64_t now_ms, int (*ready)(const char *unit));
|
||||
int dm_cloud_conflict_take(void);
|
||||
int dm_cloud_char_conflict_take(char *out, size_t n);
|
||||
int dm_cloud_inbox_add(const char *save, const char *statef, const char *pack);
|
||||
#if __has_include("../stash_seed.h") // 公开仓库不带这份预置(它是游戏生成的一份存档的字节):不在时跳过用到它的 ⑱ ⑲ 两组 | the public repository does not ship this seed (it is the bytes of a save the game generated): when it is absent, the two groups that use it, 18 and 19, are skipped
|
||||
#include "../stash_seed.h"
|
||||
#define T_HAVE_STASH_SEED 1
|
||||
@@ -41,6 +43,10 @@ static void put_d2i(const char *dev, int items, int chron, long sec) {
|
||||
put_bin(dev, "save/ModernSharedStashSoftCoreV2/ModernSharedStashSoftCoreV2.d2i", b, 68 + l2, sec);
|
||||
}
|
||||
static void put_vault(const char *dev, int n, long sec) { uint8_t b[8] = { 'S', 'W', 'V', 'T', 1, 0, (uint8_t)n, 0 }; put_bin(dev, "save/ModernSharedStashSoftCoreV2.swvault", b, 8, sec); }
|
||||
static int inbox_n(const char *dev) { char d[1024]; path(d, dev, "save/_cloudinbox"); DIR *dp = opendir(d); struct dirent *e; int n = 0; while (dp && (e = readdir(dp))) n += e->d_name[0] != '.'; if (dp) closedir(dp); return n; }
|
||||
static int inbox_has(const char *dev, const char *f) { // 收件箱里有没有哪个条目带这个文件 | whether any inbox entry carries this file
|
||||
char d[1024]; path(d, dev, "save/_cloudinbox"); DIR *dp = opendir(d); struct dirent *e; int k = 0; struct stat st;
|
||||
while (dp && (e = readdir(dp))) { if (e->d_name[0] == '.') continue; char p[1400]; snprintf(p, sizeof p, "%s/%s/%s", d, e->d_name, f); k |= !stat(p, &st); } if (dp) closedir(dp); return k; }
|
||||
static int d2i_items(const char *dev, const char *rel) { char p[1024]; path(p, dev, rel); FILE *f = fopen(p, "rb"); if (!f) return -1; uint8_t b[70]; size_t n = fread(b, 1, 70, f); fclose(f); return n >= 67 ? b[66] : -1; }
|
||||
|
||||
int main(void) {
|
||||
@@ -139,20 +145,24 @@ int main(void) {
|
||||
CHECK(S3("H", 0) == 0 && d2i_items("H", D2I) == 0, "⑪ 新设备运行中首次同步:不传不改(不能拿空仓库盖云端)");
|
||||
CHECK(S3("H", 1) == 1 && d2i_items("H", D2I) == 5 && get("H", "save/ModernSharedStashSoftCoreV2.swvault"), "⑪ 新设备启动首次同步:以云端为准,拿到 5 件与编年史仓库");
|
||||
CHECK(count_bak("H", "_stash-") == 1, "⑪ 新设备本来那份空仓库进备份");
|
||||
CHECK(!dm_cloud_conflict_take(), "⑪ 正常首次同步不算冲突");
|
||||
CHECK(!dm_cloud_conflict_take() && inbox_n("H") == 0, "⑪ 本机那份是新建空档:不进收件箱、不提示");
|
||||
put_d2i("G", 6, 400, 6000); CHECK(S3("G", 0) == 1, "⑭ G 编年史变长(400)照常上传");
|
||||
CHECK(S3("H", 1) == 1 && d2i_items("H", D2I) == 6, "⑭ H 启动拿到 G 的新版");
|
||||
put_d2i("H", 0, 148, 7000); // H 上的共享仓库不知为何变空(编年史 148、0 件),时刻更新 | the shared stash on H somehow became empty (chronicle 148, 0 items), with a newer timestamp
|
||||
CHECK(S3("H", 0) == 0, "⑬ H 运行中要上传变空的那份:拦下");
|
||||
CHECK(dm_cloud_conflict_take() == 1, "⑬ 拦下记冲突(进局弹提示)");
|
||||
CHECK(S3("H", 0) == 0, "⑬ H 运行中要上传变空的那份:分叉,运行中不动");
|
||||
CHECK(!dm_cloud_conflict_take(), "⑬ 运行中不提示(不再永久拦)");
|
||||
CHECK(S3("G", 1) == 0 && d2i_items("G", D2I) == 6, "⑬ 云端没被盖:G 仍是 6 件");
|
||||
CHECK(S3("H", 1) == 1 && d2i_items("H", D2I) == 6, "⑬ H 启动:云端为现行版,拿回 6 件");
|
||||
CHECK(inbox_n("H") == 1 && dm_cloud_conflict_take() == 1, "⑬ 本机那份共享仓库空了、但编年史仓库侧文件还有 3 件:进收件箱、提示一次");
|
||||
put_d2i("H", 7, 500, 7500); CHECK(S3("H", 0) == 1, "⑮ H 正常玩:编年史 500 上传");
|
||||
put_d2i("G", 6, 450, 7600); // G 没同步到 H 的 500 就自己写了 450(两边都改,G 后写) | G wrote 450 itself without having synced H's 500 (both sides changed, G wrote later)
|
||||
CHECK(S3("G", 0) == 0, "⑮ G 运行中要拿编年史 450 盖云端的 500:拦下");
|
||||
CHECK(S3("G", 1) == 0 && d2i_items("G", D2I) == 6, "⑮ G 启动:云端 500 比本机 450 时刻早但编年史长——按后写赢会上传,被拦;本机不动");
|
||||
CHECK(dm_cloud_conflict_take() == 1, "⑮ 记冲突");
|
||||
CHECK(S3("G", 0) == 0, "⑮ G 运行中要拿编年史 450 盖云端的 500:分叉,运行中不动");
|
||||
CHECK(S3("G", 1) == 1 && d2i_items("G", D2I) == 7, "⑮ G 启动:云端(7 件、500)为现行版");
|
||||
CHECK(inbox_n("G") == 1 && inbox_has("G", "mine.pack") && inbox_has("G", "base.pack"), "⑮ G 本机那份(6 件、450)进收件箱,带上次同步的基准(6 件、400)");
|
||||
CHECK(dm_cloud_conflict_take() == 1, "⑮ 收进收件箱:进局提示一次");
|
||||
CHECK(S3("G", 1) == 0 && inbox_n("G") == 1, "⑮ 再启动:一致、无动作、不再收(不是永久状态)");
|
||||
{ char p3[1024]; path(p3, "H", "save/ModernSharedStashSoftCoreV2.swvault"); unlink(p3); } put_d2i("H", 7, 500, 8000);
|
||||
CHECK(S3("H", 0) == 0 && dm_cloud_conflict_take() == 1, "⑬ 编年史仓库侧文件没了(云端有 3 件):拦下");
|
||||
CHECK(S3("H", 0) == 0 && !dm_cloud_conflict_take(), "⑬ 编年史仓库侧文件没了(云端有 3 件):分叉,运行中不动");
|
||||
put_vault("H", 0, 8100); put_d2i("H", 0, 500, 8100);
|
||||
CHECK(S3("H", 0) == 1 && !dm_cloud_conflict_take(), "⑯ 正常玩法:共享仓库物品取空、编年史仓库取空(文件还在,0 件),编年史没变短——照常上传");
|
||||
// ⑰ rf3 那个形状:云端专家仓库 2 件、编年史还是新建的 148;本机这份被换成游戏新建的空档(0 件、148),状态记录还在、云端没变 = 走「只本机改了」的上传
|
||||
@@ -161,8 +171,8 @@ int main(void) {
|
||||
#define S4(dev, down) (path(s3, dev, "save"), path(b3, dev, "bak"), path(t3, dev, "state"), dm_cloud_sync(s3, cd, b3, t3, down, 0, NULL))
|
||||
put_d2i("J", 2, 148, 1000); CHECK(S4("J", 1) == 1, "⑰ 准备:J 上传 2 件、编年史 148 的仓库");
|
||||
put_d2i("J", 0, 148, 2000); dm_cloud_conflict_take();
|
||||
CHECK(S4("J", 0) == 0 && dm_cloud_conflict_take() == 1, "⑰ 运行中要拿新建空档(0 件、148)盖 2 件的那份:拦下");
|
||||
CHECK(S4("J", 1) == 0, "⑰ 启动时同样拦下(不上传)");
|
||||
CHECK(S4("J", 0) == 0 && !dm_cloud_conflict_take(), "⑰ 运行中要拿新建空档(0 件、148)盖 2 件的那份:分叉,运行中不动");
|
||||
CHECK(S4("J", 1) == 1 && d2i_items("J", D2I) == 2 && inbox_n("J") == 0, "⑰ 启动:拿回云端 2 件;本机空档不进收件箱");
|
||||
put_d2i("J", 0, 300, 3000); CHECK(S4("J", 0) == 1, "⑰ 编年史长过新建大小的仓库取空:照常上传");
|
||||
// ⑱ rf3 真形状:云端专家仓库是另一台的预置(stash_seed.h),本机还没有专家仓库档(启动同步跑在写预置之前)→ 不拦、不弹;本机写了预置后上传也不拦
|
||||
// (18) The real rf3 shape: the cloud hardcore stash is another device's preset (stash_seed.h), and the local device has no hardcore stash file yet (startup sync runs before the preset is written) -> not blocked, no prompt; uploading after the local device writes the preset is not blocked either
|
||||
@@ -180,7 +190,7 @@ int main(void) {
|
||||
{ uint8_t big[700]; memset(big, 0, sizeof big); uint32_t l1 = 68, l2 = 300; memcpy(big, "\x55\xaa\x55\xaa", 4); memcpy(big + 16, &l1, 4); memcpy(big + 64, "JM", 2); big[66] = 9; memcpy(big + 68, "\x55\xaa\x55\xaa", 4); memcpy(big + 84, &l2, 4); big[132] = 0xc0;
|
||||
put_bin("K", HC, big, 68 + 300, 5000); CHECK(S5("K", 0) == 1, "⑲ 准备:专家仓库有 9 件、编年史 300 上传"); }
|
||||
put_bin("K", HC, g_stash_seed, sizeof g_stash_seed, 6000);
|
||||
CHECK(S5("K", 0) == 0 && dm_cloud_conflict_take() == 1, "⑲ 本机变回预置要盖 9 件的那份:拦下");
|
||||
CHECK(S5("K", 0) == 0 && !dm_cloud_conflict_take(), "⑲ 本机变回预置要盖 9 件的那份:分叉,运行中不动");
|
||||
#undef HC
|
||||
#undef S5
|
||||
}
|
||||
@@ -192,6 +202,61 @@ int main(void) {
|
||||
#undef D2I
|
||||
#undef S3
|
||||
}
|
||||
// ⑳ 同名角色(iCloud 离线冲突第 3 条):云端有 P 的 Foo(1000 秒);新设备 Q 从没同步过、离线建了同名 Foo(5000 秒)和 Bar → 首次同步:Foo 用云端那份、
|
||||
// 本机 Foo 整份进备份 Foo-5000000、记下名字待进局提示(取一次后清空);Bar 上传、不进提示
|
||||
// (20) Same-name character (iCloud offline conflict item 3): the cloud has P's Foo (1000 s); new device Q has never synced and created a Foo with the same name (5000 s) and a Bar offline -> first sync: Foo uses the cloud copy,
|
||||
// the local Foo goes into the backup whole as Foo-5000000, the name is recorded for a notice after entering a run (cleared once taken); Bar is uploaded and not part of the notice
|
||||
{ char c6[1024], s6[1024], b6[1024], t6[1024]; snprintf(c6, sizeof c6, "%s/cloud6", R); mkdir(c6, 0755); char nm[256];
|
||||
#define S6(dev, down) (path(s6, dev, "save"), path(b6, dev, "bak"), path(t6, dev, "state"), dm_cloud_sync(s6, c6, b6, t6, down, 0, NULL))
|
||||
put("P", "save/Foo/Foo.d2s", "fooP", 1000); CHECK(S6("P", 1) == 1, "⑳ 准备:P 上传 Foo");
|
||||
dm_cloud_char_conflict_take(nm, sizeof nm);
|
||||
put("Q", "save/Foo/Foo.d2s", "fooQ", 5000); put("Q", "save/Bar/Bar.d2s", "barQ", 5000);
|
||||
CHECK(S6("Q", 1) == 2, "⑳ Q 首次同步:Foo 下载、Bar 上传,共 2 个动作");
|
||||
CHECK(get("Q", "save/Foo/Foo.d2s") && !strcmp(get("Q", "save/Foo/Foo.d2s"), "fooP"), "⑳ Q 的 Foo 应换成云端那份 fooP");
|
||||
CHECK(count_bak("Q", "Foo-5000000") == 1, "⑳ Q 本机那份 Foo 应进备份 Foo-5000000");
|
||||
CHECK(dm_cloud_char_conflict_take(nm, sizeof nm) == 1 && !strcmp(nm, "Foo"), "⑳ 记下同名角色 Foo 待提示,实为「%s」", nm);
|
||||
CHECK(dm_cloud_char_conflict_take(nm, sizeof nm) == 0, "⑳ 取过一次后清空");
|
||||
CHECK(S6("Q", 1) == 0 && dm_cloud_char_conflict_take(nm, sizeof nm) == 0, "⑳ 再同步无动作、不再提示");
|
||||
#undef S6
|
||||
}
|
||||
// ㉑ iCloud 离线冲突三个场景(第一笔口径:两台设备的全部数据都在——仓库或收件箱,且没有永久拦截)。老设备 A:10 件、编年史 600,已上云
|
||||
// (21) Three iCloud offline conflict scenarios (first-step criterion: all data of both devices is kept - in the stash or the inbox - and nothing is blocked forever). Old device A: 10 items, chronicle 600, already in the cloud
|
||||
{ char c7[1024], s7[1024], b7[1024], t7[1024], cq[1024]; snprintf(c7, sizeof c7, "%s/cloud7", R); mkdir(c7, 0755); snprintf(cq, sizeof cq, "%s/cloud7q", R); mkdir(cq, 0755);
|
||||
#define S7(dev, cl, down) (path(s7, dev, "save"), path(b7, dev, "bak"), path(t7, dev, "state"), dm_cloud_sync(s7, cl, b7, t7, down, 0, NULL))
|
||||
#define D2I7 "save/ModernSharedStashSoftCoreV2/ModernSharedStashSoftCoreV2.d2i"
|
||||
put_d2i("A7", 10, 600, 1000); CHECK(S7("A7", c7, 1) == 1, "㉑ 准备:A 上传 10 件");
|
||||
dm_cloud_conflict_take();
|
||||
// ① 新设备 N 没登录时离线玩(3 件、编年史 300),之后登录、启动同步
|
||||
// (1) new device N plays offline while not signed in (3 items, chronicle 300), then signs in and syncs at launch
|
||||
put_d2i("N7", 3, 300, 5000);
|
||||
CHECK(S7("N7", c7, 1) == 1 && d2i_items("N7", D2I7) == 10, "㉑① N 首次同步:仓库是云端的 10 件");
|
||||
CHECK(inbox_n("N7") == 1 && inbox_has("N7", "mine.pack") && !inbox_has("N7", "base.pack") && dm_cloud_conflict_take() == 1, "㉑① N 本机 3 件进收件箱(没有基准)、提示一次");
|
||||
CHECK(S7("N7", c7, 1) == 0 && inbox_n("N7") == 1 && d2i_items("A7", D2I7) == 10, "㉑① 再启动无动作(没有永久状态);A 的 10 件不动");
|
||||
// ② 新设备 M 离线期间编年史比云端长(900 > 600):原先永久拦住,现在同样云端为现行版 + 收件箱
|
||||
// (2) new device M's chronicle grew longer than the cloud's while offline (900 > 600): previously blocked forever, now likewise the cloud is the current version + inbox
|
||||
put_d2i("M7", 3, 900, 5000);
|
||||
CHECK(S7("M7", c7, 0) == 0 && inbox_n("M7") == 0, "㉑② M 运行中:不动、不收(等启动)");
|
||||
CHECK(S7("M7", c7, 1) == 1 && d2i_items("M7", D2I7) == 10 && inbox_n("M7") == 1 && dm_cloud_conflict_take() == 1, "㉑② M 启动:仓库 10 件,本机 3 件进收件箱");
|
||||
CHECK(S7("M7", c7, 1) == 0 && S7("M7", c7, 0) == 0 && inbox_n("M7") == 1, "㉑② 再启动、再运行中都无动作:不是永久拦截");
|
||||
// ③ 新设备 Q 登录但离线、看到的云端是空的(cloud7q),上传了 3 件;联网后 iCloud 拿 Q 的包当现行版(盖到 cloud7 上)
|
||||
// (3) new device Q signs in but is offline and sees an empty cloud (cloud7q), uploads 3 items; once online, iCloud takes Q's pack as the current version (overwriting cloud7)
|
||||
put_d2i("Q7", 3, 300, 5000); CHECK(S7("Q7", cq, 1) == 1, "㉑③ 准备:Q 往看着是空的云端传了 3 件");
|
||||
char sp[1300], dp[1300], keep[1300]; snprintf(sp, sizeof sp, "%s/_stash.pack", cq); snprintf(dp, sizeof dp, "%s/_stash.pack", c7); snprintf(keep, sizeof keep, "%s/a_old.pack", R);
|
||||
rename(dp, keep); { FILE *fi = fopen(sp, "rb"), *fo = fopen(dp, "wb"); char buf[8192]; size_t k; while ((k = fread(buf, 1, sizeof buf, fi)) > 0) fwrite(buf, 1, k, fo); fclose(fi); fclose(fo); }
|
||||
CHECK(S7("A7", c7, 1) == 1 && d2i_items("A7", D2I7) == 3, "㉑③ A 启动:云端(Q 的 3 件)为现行版");
|
||||
CHECK(inbox_n("A7") == 1 && inbox_has("A7", "base.pack") && dm_cloud_conflict_take() == 1, "㉑③ A 本机 10 件进收件箱,带上次同步的基准");
|
||||
CHECK(S7("A7", c7, 1) == 0 && inbox_n("A7") == 1, "㉑③ 再启动无动作");
|
||||
// iCloud 冲突版本:A 那台读出被换下的旧版本(a_old.pack,10 件)收进收件箱;只有预置 / 空档的版本不收
|
||||
// iCloud conflict version: device A reads out the replaced old version (a_old.pack, 10 items) and stores it in the inbox; a version with only the preset / an empty save is not stored
|
||||
{ char ts7[1100]; path(s7, "A7", "save"); path(ts7, "A7", "state");
|
||||
CHECK(dm_cloud_inbox_add(s7, ts7, keep) == 0 && inbox_n("A7") == 2 && dm_cloud_conflict_take() == 1, "㉑③ 冲突版本(10 件)收进收件箱");
|
||||
put_d2i("E7", 0, 148, 100); { char e7[1100], ee[1100], et[1100], pk[1300]; path(e7, "E7", "save"); path(ee, "E7", "bak"); path(et, "E7", "state"); char ce[1300]; snprintf(ce, sizeof ce, "%s/cloud7e", R); mkdir(ce, 0755);
|
||||
dm_cloud_sync(e7, ce, ee, et, 1, 0, NULL); snprintf(pk, sizeof pk, "%s/_stash.pack", ce);
|
||||
CHECK(dm_cloud_inbox_add(s7, ts7, pk) == 0 && inbox_n("A7") == 2, "㉑③ 空档的冲突版本:没东西,不收"); }
|
||||
CHECK(dm_cloud_inbox_add(s7, ts7, "/nonexistent.pack") == -1, "㉑③ 读不了的冲突版本:返回 -1"); }
|
||||
#undef S7
|
||||
#undef D2I7
|
||||
}
|
||||
printf("t_cloudsync: %d 项,%d 失败\n", checks, fails);
|
||||
return fails != 0;
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ ssize_t pwrite(int, const void *, size_t, off_t);
|
||||
|
||||
struct dm_flags g_flag; uint64_t g_t0_ns; uint64_t now_ns(void) { return 0; } // 日志时间戳与读路径的桩(写路径不用) | stubs for log timestamps and the read path (not used by the write path)
|
||||
void dm_prof_add(int id, uint64_t ns, uint64_t b) { (void)id; (void)ns; (void)b; } void dm_guest_write_prepare(void *a, size_t n) { (void)a; (void)n; }
|
||||
void dm_fs_save_poison(int e);
|
||||
extern int g_nfail, g_lasterr; // 前端通知计数(t_fs_stub.c 的强实现替掉 hle_fs.c 的弱实现) | front-end notification count (the strong implementation in t_fs_stub.c replaces the weak one in hle_fs.c)
|
||||
static int g_mode, g_calls; // 0 照常写;1 一律返回 0;2 第一次只写 3 字节 | 0 write normally; 1 always return 0; 2 write only 3 bytes the first time
|
||||
static ssize_t fake_pwrite(int fd, const void *buf, size_t n, off_t off) {
|
||||
@@ -143,6 +144,44 @@ int main(void) {
|
||||
snprintf(p, sizeof p, "%s/a", work); CHECK(same(p, "new"), "工作目录 a 回到已提交版 new");
|
||||
snprintf(p, sizeof p, "%s/b", work); CHECK(same(p, "7"), "工作目录 b = 已提交的 7");
|
||||
|
||||
printf("⑥ 写失败收场不退出(DM_TEST_FS_FAILAT)\n");
|
||||
unsetenv("DM_TEST_FS_FAIL");
|
||||
// ⑥a 提交被拒后重新克隆失败:不退出、工作目录不动、已提交版不变;下次提交照样拒绝并重新克隆成功;再下一个事务照常提交
|
||||
// 6a Recloning after a refused commit fails: do not exit, the work directory is untouched and the committed version unchanged; the next commit is refused again and the reclone succeeds; the transaction after that commits normally
|
||||
setenv("DM_TEST_FS_FAILAT", "reclone:1", 1);
|
||||
CHECK(write_save("save:/a", "bad") == RES_OK, "写 a=bad");
|
||||
dm_fs_save_poison(ENOSPC); int nf0 = g_nfail;
|
||||
CHECK(h_fs_Commit("save") == RES_FAIL && g_nfail == nf0 + 1, "本事务被拒(重新克隆注入失败),进程还在,前端通知 1 次");
|
||||
snprintf(p, sizeof p, "%s/a", save); CHECK(same(p, "new"), "已提交目录 a 仍是 new");
|
||||
snprintf(p, sizeof p, "%s/a", work); CHECK(same(p, "bad"), "工作目录没删(a 还是 bad)");
|
||||
CHECK(h_fs_Commit("save") == RES_FAIL && g_nfail == nf0 + 2, "仍是已污染:下一次提交照样拒绝");
|
||||
snprintf(p, sizeof p, "%s/a", work); CHECK(same(p, "new"), "这次重新克隆成了:工作目录 a 回到 new");
|
||||
snprintf(p, sizeof p, "%s.re", work); CHECK(access(p, F_OK) != 0, "没有 .re 残留");
|
||||
CHECK(write_save("save:/a", "good") == RES_OK && h_fs_Commit("save") == RES_OK, "下一个事务写 a=good,提交成功");
|
||||
snprintf(p, sizeof p, "%s/a", save); CHECK(same(p, "good"), "已提交 a = good");
|
||||
// ⑥b 改名后写客体名失败、回退也失败:不退出;文件在事务存档里 → 本事务提交被拒、已提交版不变;重新克隆后照常
|
||||
// 6b Writing the guest name after a rename fails and the rollback fails too: do not exit; the file is in a transactional save, so this transaction's commit is refused and the committed version is unchanged; after recloning everything works
|
||||
setenv("DM_TEST_FS_FAILAT", "guestname:1,renameback:1", 1);
|
||||
h_fs_CreateFile("save:/c", 0); CHECK(write_save("save:/c", "c") == RES_OK, "写 c");
|
||||
CHECK(h_fs_RenameFile("save:/c", "save:/d") != RES_OK, "改名 c → d 返回失败(两步都注入失败),进程还在");
|
||||
nf0 = g_nfail; CHECK(h_fs_Commit("save") == RES_FAIL && g_nfail == nf0 + 1, "本事务提交被拒");
|
||||
snprintf(p, sizeof p, "%s/c", save); CHECK(access(p, F_OK) != 0, "已提交目录没有 c");
|
||||
snprintf(p, sizeof p, "%s/d", save); CHECK(access(p, F_OK) != 0, "已提交目录没有 d");
|
||||
snprintf(p, sizeof p, "%s/a", save); CHECK(same(p, "good"), "已提交 a 仍是 good");
|
||||
CHECK(write_save("save:/a", "ok2") == RES_OK && h_fs_Commit("save") == RES_OK, "下一个事务照常提交");
|
||||
// ⑥c 挂载时克隆工作目录失败:不退出,改成只读挂载已提交目录——读得到、写不进、提交是空操作、已提交版不变、前端通知 1 次;下次正常挂载照旧
|
||||
// 6c Cloning the work directory at mount fails: do not exit; mount the committed directory read-only instead. Reads work, writes fail, commits are no-ops, the committed version is unchanged, and the front end is notified once; the next normal mount works as before
|
||||
setenv("DM_TEST_FS_FAILAT", "mountclone:1", 1); g_nmnt = 0; nf0 = g_nfail;
|
||||
snprintf(p, sizeof p, "rm -rf '%s'", work); system(p);
|
||||
CHECK(h_fs_MountSave("save", NULL) == RES_OK && g_nfail == nf0 + 1, "挂载返回成功、前端通知 1 次(实际 %d 次)", g_nfail - nf0);
|
||||
CHECK(read_fs("save:/a", got, sizeof got) && !strcmp(got, "ok2"), "只读挂载下读得到已提交的 a=ok2(读到 %s)", got);
|
||||
CHECK(write_save("save:/a", "zzz") != RES_OK, "写不进去");
|
||||
CHECK(h_fs_Commit("save") == RES_OK, "提交是空操作");
|
||||
snprintf(p, sizeof p, "%s/a", save); CHECK(same(p, "ok2"), "已提交 a 仍是 ok2");
|
||||
unsetenv("DM_TEST_FS_FAILAT"); g_nmnt = 0;
|
||||
CHECK(h_fs_MountSave("save", NULL) == RES_OK && write_save("save:/a", "ok3") == RES_OK && h_fs_Commit("save") == RES_OK, "去掉注入重新挂载:事务式照常,写 a=ok3 提交成功");
|
||||
snprintf(p, sizeof p, "%s/a", save); CHECK(same(p, "ok3"), "已提交 a = ok3");
|
||||
|
||||
// 语言开关改写设置文件(settings_lang_apply):期望值按规则手算——只在「与开关不符」时把 Language / VoiceLanguage 改成 0(英文)或 8(简中),别的键和别的语言不动
|
||||
// Language switch rewriting the settings file (settings_lang_apply): expected values computed by hand from the rule -- only when it "does not match the switch" are Language / VoiceLanguage changed to 0 (English) or 8 (Simplified Chinese); other keys and other languages are untouched
|
||||
{ extern int g_t_lang; char sd[1200], sf[1300], gotj[512]; snprintf(sd, sizeof sd, "%s/langt", root); mkdir(sd, 0755); snprintf(sf, sizeof sf, "%s/Settings", sd); mkdir(sf, 0755); snprintf(sf, sizeof sf, "%s/Settings/Settings.json", sd);
|
||||
|
||||
@@ -51,6 +51,28 @@ int main(void) {
|
||||
K.tier = 100; if (10819454LL * hi_duo_x1000(0) / 1000 > 8388607LL) { fails++; printf(" ✗ 100 层巴尔 × s 过了属性上限\n"); }
|
||||
K.guards[0] = 7; K.guards[1] = 9; K.guards[2] = 0; if (!is_guard(7) || !is_guard(9) || is_guard(0) || is_guard(8)) { fails++; printf(" ✗ is_guard 认错\n"); }
|
||||
printf("hi_duo %s:4 格系数 + 巴尔不过上限 + 认守护者\n", fails ? "失败" : "OK");
|
||||
// 闯入首领也算「特殊单位」(不按普通怪计分、不按普通怪再改属性):在场的(K.inv_id)与已退场、还没被真移除的(g_inv_gone)都算——
|
||||
// 后者漏掉的话,退场后那几秒里被打死会按普通金怪计 10 分(实测过:进度 400 → 410)
|
||||
// Invading bosses also count as "special units" (not scored as ordinary monsters, not scaled again as ordinary monsters): both the one present (K.inv_id) and one that has left but is not yet truly removed (g_inv_gone) -
|
||||
// if the latter is missed, being killed in the few seconds after leaving would score 10 points as an ordinary unique monster (measured: progress 400 -> 410)
|
||||
K.guards[0] = K.guards[1] = K.guards[2] = 0; K.inv_id[0] = 21; K.inv_id[1] = 0; g_inv_gone[0] = 0; g_inv_gone[1] = 33;
|
||||
if (!is_guard(21) || !is_guard(33) || is_guard(22) || is_guard(0)) { fails++; printf(" ✗ is_guard 没认全闯入首领(在场 21、已退场 33)\n"); }
|
||||
K.inv_id[0] = 0; g_inv_gone[1] = 0; if (is_guard(21) || is_guard(33)) { fails++; printf(" ✗ 清掉之后 is_guard 还认\n"); }
|
||||
// 首领召唤物按类号认:巴尔触手 562–566、分身 570;巴尔本体 544、它的小怪 571、普通怪不算
|
||||
// Boss summons are recognised by class id: Baal's tentacles 562–566 and clone 570; Baal himself 544, his minions 571 and ordinary monsters do not count
|
||||
{ static const struct { uint32_t cls; int want; } bc[] = { { 561, 0 }, { 562, 1 }, { 564, 1 }, { 566, 1 }, { 567, 0 }, { 570, 1 }, { 571, 0 }, { 544, 0 }, { 45, 0 } };
|
||||
for (unsigned i = 0; i < sizeof bc / sizeof *bc; i++) if (boss_summon(bc[i].cls) != bc[i].want) { fails++; printf(" ✗ boss_summon(%u) 应为 %d\n", bc[i].cls, bc[i].want); } }
|
||||
printf("invader_guard %s:在场与已退场的闯入首领都算特殊单位\n", fails ? "失败" : "OK");
|
||||
// 特殊精英的梯度(设计稿第二十四节):原生怪留几成 / 一场最多几组 / 同时在场几组。74 层及以下 = 100% / 0 / —(逐位不变)
|
||||
// Special elite gradient (design draft section 24): share of native monsters kept / max groups per run / groups present at once. Level 74 and below = 100% / 0 / - (unchanged bit for bit)
|
||||
{ static const struct { int tier, nat, quota, cap; } sc[] = { { 1, 100, 0, 2 }, { 74, 100, 0, 2 }, { 75, 80, 2, 2 }, { 79, 80, 2, 2 }, { 80, 55, 5, 2 }, { 84, 55, 5, 2 }, { 85, 30, 7, 2 }, { 89, 30, 7, 2 }, { 90, 0, 1 << 30, 3 }, { 100, 0, 1 << 30, 3 } };
|
||||
for (unsigned i = 0; i < sizeof sc / sizeof *sc; i++) if (su_nat_pct(sc[i].tier) != sc[i].nat || su_quota(sc[i].tier) != sc[i].quota || su_cap(sc[i].tier) != sc[i].cap) { fails++; printf(" ✗ 第 %d 层特殊精英梯度应为 %d%% / %d 组 / 同时 %d 组\n", sc[i].tier, sc[i].nat, sc[i].quota, sc[i].cap); }
|
||||
// 池:43 行、不重样、不含剔掉的 23 行、含女伯爵(6)与随从 9 只的三行(24、36、38,有巴尔的场在抽的时候跳过)
|
||||
// Pool: 43 rows, no duplicates, none of the 23 removed rows, includes the Countess (6) and the three rows with 9 minions (24, 36, 38; skipped when drawing for a run with Baal)
|
||||
static const uint8_t out[] = { 5, 10, 15, 18, 20, 26, 27, 28, 29, 30, 31, 39, 41, 42, 43, 44, 45, 60, 61, 62, 63, 64, 65 }; int seen[66] = { 0 }, bad = sizeof k_su_pool != 43;
|
||||
for (unsigned i = 0; i < sizeof k_su_pool; i++) { if (k_su_pool[i] > 65 || seen[k_su_pool[i]]++) bad = 1; } for (unsigned i = 0; i < sizeof out; i++) bad |= seen[out[i]]; bad |= !seen[6] || !seen[24] || !seen[36] || !seen[38];
|
||||
if (bad) { fails++; printf(" ✗ 特殊精英的池不对(应 43 行、不重样、不含剔掉的 23 行)\n"); }
|
||||
printf("su_tiers %s:10 格梯度 + 池 43 行\n", fails ? "失败" : "OK"); }
|
||||
printf("t_rift_next %s:%d 格(层 × 晋级量)下一层 = 手写期望且 ≤ 100,宿主与顶部条同值\n", fails ? "失败" : "OK", n);
|
||||
return fails != 0;
|
||||
}
|
||||
|
||||
@@ -33,6 +33,12 @@ int main(void) {
|
||||
for (unsigned i = 0; i < sizeof oc / sizeof *oc; i++) { atomic_store(&K.st, oc[i].st); K.t0_ns = guest_ns() - (uint64_t)oc[i].ago * 1000000000ull; dm_rift_hud_t h = {0}; dm_rift_menu_t m = {0}; dm_rift_hud(&h); menu_fill(&m, 2);
|
||||
if (rift_overtime() != oc[i].want || m.overtime != oc[i].want || (oc[i].st != ST_IDLE && h.overtime != oc[i].want)) { fails++; printf(" ✗ 状态 %d 开局 %d 秒前:超时量应为 %d,得 %d(顶部条 %d、菜单 %d)\n", oc[i].st, oc[i].ago, oc[i].want, rift_overtime(), h.overtime, m.overtime); } }
|
||||
printf("rift_overtime %s:6 格\n", fails ? "失败" : "OK");
|
||||
// 顶部条第二行写哪一句(dm_rift_hud 的 goal,宿主一处定):按「是否超时 × 守护者是否在场 × 守护者几位」手写期望
|
||||
// Which sentence the second line of the top bar shows (goal of dm_rift_hud, decided in one place in the host): expected values written by hand over "overtime or not x Guardians present or not x how many Guardians"
|
||||
static const struct { int ago, guard, dead, total, want; } gc[] = { { 100, 0, 0, 0, 0 }, { 100, 1, 0, 1, 1 }, { 100, 1, 0, 2, 2 }, { 100, 1, 1, 2, 2 }, { 100, 1, 1, 3, 2 }, { 901, 0, 0, 0, 3 }, { 901, 1, 0, 1, 4 }, { 901, 1, 1, 2, 5 } };
|
||||
for (unsigned i = 0; i < sizeof gc / sizeof *gc; i++) { atomic_store(&K.st, ST_RUN); K.t0_ns = guest_ns() - (uint64_t)gc[i].ago * 1000000000ull; K.guard = gc[i].guard ? 7 : 0; atomic_store(&K.guard_dead, 0); atomic_store(&K.gdead, gc[i].dead); atomic_store(&K.gtotal, gc[i].total);
|
||||
dm_rift_hud_t h = {0}; dm_rift_hud(&h); if (h.goal != gc[i].want || h.gdead != gc[i].dead || h.gtotal != gc[i].total) { fails++; printf(" ✗ 开局 %d 秒前 守护者在场 %d(%d/%d):第二行应为 %d,得 %d\n", gc[i].ago, gc[i].guard, gc[i].dead, gc[i].total, gc[i].want, h.goal); } }
|
||||
K.guard = 0; printf("hud_goal %s:8 格\n", fails ? "失败" : "OK");
|
||||
printf("t_rift_oldrun %s:%d 格城里入口给页 + 新局重置清请求\n", fails ? "失败" : "OK", n);
|
||||
return fails != 0;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
#include <stdlib.h>
|
||||
#include "../dm.h"
|
||||
#include "../touch_mac.c"
|
||||
#include "../../ios/Sources/dm_touch_controls.c"
|
||||
#include "../../touch/dm_touch_controls.c"
|
||||
|
||||
uint64_t now_ns(void) { return 0; }
|
||||
void (*dm_pad_hook)(uint64_t, uint64_t *, int32_t *, int32_t *, int32_t *, int32_t *);
|
||||
@@ -33,6 +33,7 @@ void dm_elysium_arm(int on) { (void)on; } // 极乐世界勾选(dm_elysium.c
|
||||
void dm_custom_on_uimsg(const char *cat, const char *act, const char *arg) { (void)cat; (void)act; (void)arg; } // 「自定义」设置(dm_custom.c)的桩 | stub for the "Custom" settings (dm_custom.c)
|
||||
void dm_belt_put(unsigned id) { (void)id; }
|
||||
void dm_ui_rect(int *x, int *y, int *w, int *h) { *x = *y = *w = *h = 0; }
|
||||
void dm_uiscreen_set_panel(int on) { (void)on; }
|
||||
int dm_screen_real(int *w, int *h) { (void)w; (void)h; return 0; }
|
||||
int dm_uiscreen_ingame(void) { return 0; }
|
||||
void dm_uiscreen_set_ingame(int on) { (void)on; } // 界面矩形(dm_uiscreen.c)的桩:没开真全屏 | stub for the UI rectangle (dm_uiscreen.c): true full screen not enabled
|
||||
|
||||
@@ -79,6 +79,7 @@ float dm_ui_ny(float ny) { return ny; }
|
||||
int dm_screen_real(int *w, int *h) { (void)w; (void)h; return 0; }
|
||||
void dm_uiscreen_enable(int m) { (void)m; }
|
||||
void dm_ui_rect(int *x, int *y, int *w, int *h) { *x = *y = *w = *h = 0; }
|
||||
void dm_uiscreen_set_panel(int on) { (void)on; }
|
||||
int dm_uiscreen_ingame(void) { return 0; }
|
||||
void dm_uiscreen_set_ingame(int on) { (void)on; }
|
||||
void dm_held_stow(void) {}
|
||||
|
||||
+6
-6
@@ -14,8 +14,8 @@ static pthread_once_t g_keyown_once = PTHREAD_ONCE_INIT;
|
||||
static void own_free(void *p) { void **own = p; free(own[0]); free(own[1]); free(own); }
|
||||
static void own_key_init(void) { if (pthread_key_create(&g_keyown, own_free)) die("创建线程本地块的释放键失败"); }
|
||||
void guest_thread_init(void) {
|
||||
pthread_setspecific(g_keygate, (void *)dm_gate);
|
||||
for (int i = 0; i < 2; i++) if (g_keyres[i]) pthread_setspecific(g_keyres[i], (void *)dm_game_res(i)); // 分辨率参数位:{u32 宽, u32 高} 打包 | resolution parameter slot: {u32 width, u32 height} packed
|
||||
dm_slot_set(g_keygate, (void *)dm_gate);
|
||||
for (int i = 0; i < 2; i++) if (g_keyres[i]) dm_slot_set(g_keyres[i], (void *)dm_game_res(i)); // 分辨率参数位:{u32 宽, u32 高} 打包 | resolution parameter slot: {u32 width, u32 height} packed
|
||||
if (g_keyaspect || g_keyaspectui) { // 宽高比上限参数位:max(19/9, 两种模式输出宽 / 高),float 位模式放低 32 位 | aspect ratio limit parameter slot: max(19/9, output width / height of the two modes), float bit pattern in the low 32 bits
|
||||
float a = 19.0f / 9.0f; int wide = 0;
|
||||
for (int i = 0; i < 2; i++) { uint64_t r = front_game_res(i); float w = (float)(uint32_t)r, h = (float)(uint32_t)(r >> 32); if (h > 0 && w / h > a) { a = w / h; wide = 1; } }
|
||||
@@ -29,10 +29,10 @@ void guest_thread_init(void) {
|
||||
// Not a magic number: when the screen height grows the margin stays proportional (delta is relative to screen height)
|
||||
float ui = wide ? a + 0.15f : a;
|
||||
uint32_t bits;
|
||||
if (g_keyaspect) { memcpy(&bits, &a, 4); pthread_setspecific(g_keyaspect, (void *)(uintptr_t)bits); }
|
||||
if (g_keyaspectui) { memcpy(&bits, &ui, 4); pthread_setspecific(g_keyaspectui, (void *)(uintptr_t)bits); }
|
||||
if (g_keyaspect) { memcpy(&bits, &a, 4); dm_slot_set(g_keyaspect, (void *)(uintptr_t)bits); }
|
||||
if (g_keyaspectui) { memcpy(&bits, &ui, 4); dm_slot_set(g_keyaspectui, (void *)(uintptr_t)bits); }
|
||||
}
|
||||
pthread_setspecific(g_key18, 0);
|
||||
dm_slot_set(g_key18, 0);
|
||||
// 这两块随线程退出释放。客体会改写 TLS / 线程本地区这两把键的槽(它自己设线程指针),所以不能按键里的当前值去 free:
|
||||
// 申请到的原始指针另记在本文件自己的键 g_keyown 上,由它的析构放(键析构在 pthread_exit 时调用,同信号备用栈 crash.c altstack_free;
|
||||
// 析构里只有 free,客体线程的小栈上也安全)。原先不放:游戏频繁起短命线程,每条漏 8192 + 0x200 + 0x400 = 9728 字节。
|
||||
@@ -44,5 +44,5 @@ void guest_thread_init(void) {
|
||||
void **own = calloc(2, sizeof *own); uint8_t *tlr = calloc(1, TLR_SIZE + THREAD_OBJ_SIZE);
|
||||
own[0] = calloc(1, TLS_SIZE); own[1] = tlr;
|
||||
*(void **)(tlr + 0x1f8) = tlr + TLR_SIZE; // 当前线程对象 | current thread object
|
||||
pthread_once(&g_keyown_once, own_key_init); pthread_setspecific(g_keytls, own[0]); pthread_setspecific(g_keytlr, tlr); pthread_setspecific(g_keyown, own);
|
||||
pthread_once(&g_keyown_once, own_key_init); dm_slot_set(g_keytls, own[0]); dm_slot_set(g_keytlr, tlr); pthread_setspecific(g_keyown, own);
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user