docs(dev-docs): rewrite bilingual developer handbook with real code and byte walkthroughs
Expand dev-docs with a plain-language glossary, accurate single-port server flow, real apps/server directory map and cln_set_researchable trace, un-elided 57-byte EXE patch anatomy, 6-file Native C wiring guide, real Good vs. Bad code comparisons, AI constraint prompt, and traffic-log debugging steps at 1:1 zh-CN/en parity.
This commit is contained in:
1 parent
e2ac4fa744
commit
e79866b96e
5 files changed
+2013
-183
No files matched your search
+231
-21
@@ -1,33 +1,243 @@
|
||||
# Dev Docs
|
||||
# WTOffline Developer Documentation / 开发者文档
|
||||
|
||||
<a id="zh-cn"></a>
|
||||
|
||||
简体中文 · [English](#english)
|
||||
简体中文 · [English](#english) · [在线文档站](https://wto-project.net/dev-docs)
|
||||
|
||||
这是 WTOffline 的开发与贡献入口。请先准备一份自己持有的原版客户端,只读使用,并从 [主 README 的开发章节](../README.md#开发)安装工具和依赖。要启动游戏验证时,另备一份 Steam 游戏库之外的离线副本和独立的数据目录,先按[开发规范](development-rules.md#zh-cn)核实隔离。
|
||||
欢迎参与 WTOffline 开发。本目录面向**项目贡献者、客户端新版本适配者,以及使用 AI 编程工具辅助逆向定位与编写代码的协作者**。无论你之前是否接触过 Dagor 引擎或《战争雷霆》客户端内部结构,都可以按本指南一步步上手。
|
||||
|
||||
| 要做的事 | 从这里开始 |
|
||||
| --- | --- |
|
||||
| 改启动器或安装流程 | [apps/launcher](../apps/launcher) |
|
||||
| 改游戏规则、档案或本地服务 | [apps/server](../apps/server) |
|
||||
| 改游戏副本的构建或补丁检查 | [packages/patcher](../packages/patcher)、[scripts](../scripts)、[tools](../tools) |
|
||||
| 写客户端补丁或适配新的游戏版本 | [补丁指南](patches.md#zh-cn)和[补丁集](../patches) |
|
||||
| 制作添加式模组(实验期) | [模组开发文档(mod-dev-docs)](../mod-dev-docs/README.md) |
|
||||
> **如果你只是想制作载具属性魔改、自定义地图池、全新 3D 载具模型或服务端脚本模组**:你完全不需要修改 WTOffline 核心源码,请直接阅读 [模组开发文档(mod-dev-docs)](../mod-dev-docs/README.md) 或访问 [在线模组文档](https://wto-project.net/mod-docs)。
|
||||
|
||||
提交前按[自查清单](contributing.md#zh-cn)整理依据、运行适用的[检查命令](contributing.md#checks),并把检查结果和实机步骤写进 [PR 模板](templates/pull-request.md)。
|
||||
---
|
||||
|
||||
## 第一次来,建议按什么顺序读?
|
||||
|
||||
不要一上来就啃二进制补丁字段或反汇编地址。按下面三步顺读,大约 15–20 分钟就能建立完整的全局认知:
|
||||
|
||||
1. **[开发理念、架构分层与工程规范](development-rules.md#zh-cn)**(**必读第一站**):搞清楚启动器、单端口本地模拟服务器(`apps/server`)与进程内网络/对局桥接库(`wto_ws.dll`)是如何协同工作的;顺着一个真实的 `cln_set_researchable` 动作看懂服务端四层代码怎么流转;掌握「三类数值放哪里」「好代码 vs 坏代码」真实对比,以及可直接复制给 AI 编程助手的工程约束提示词。
|
||||
2. **[补丁编写与新版本适配指南](patches.md#zh-cn)**:当确认本地服务器与原版配置确实无法解决问题、必须修改客户端时,按这篇手把手教程拆包查看原版文件、用 `tools/re/cli.py` 反汇编定位,并对照完整无省略的 GUI(`patches/gui/`)、EXE(`patches/exe/`)和 Native(`patches/native/` + `native/wto-net/`)真实案例编写跨版本自适应补丁。
|
||||
3. **[环境搭建、流量调试与提交自查](contributing.md#zh-cn)**:配齐本地开发环境,学会直接阅读 `<数据目录>/logs/` 下自动解码的明文 BLK 流量日志快速抓 Bug,按改动类型运行对应的必跑检查命令,并对照 [PR 模板](templates/pull-request.md) 提交高质量改动。
|
||||
|
||||
---
|
||||
|
||||
<a id="glossary-zh"></a>
|
||||
|
||||
## 核心概念与术语词典
|
||||
|
||||
在阅读后续文档或翻阅源码时,你会频繁遇到以下专有名词。这里用大白话一次性讲透:
|
||||
|
||||
### 1. `vromfs.bin`(Dagor 虚拟只读归档包)
|
||||
|
||||
《战争雷霆》不会把成千上万个零散脚本和配置文件直接摊在硬盘上,而是打包进若干个 `.vromfs.bin` 归档文件中。它在结构上分两层:外层是带简单异或混淆的 Zstandard(zstd)压缩容器、内部镜像 MD5 与末尾 256 字节签名;内层是文件表(全小写相对路径、偏移量、可选 SHA-1 摘要,以及可选的共享键名表 `nm` 与 `.dict` 压缩字典)。项目中的 `@wto/vromfs`(`readArchive` / `getFile` / `putFile` / `writeArchive`)负责无损读写这些归档包。
|
||||
|
||||
不同归档包各司其职,查数据时按下面这张表找最快:
|
||||
|
||||
| 归档包路径(相对于游戏根目录) | 里面装什么核心内容 | WTOffline 哪里会用到它 |
|
||||
| --- | --- | --- |
|
||||
| `char.vromfs.bin` | 科技树排布(`config/shop.blk`)、载具价格/研发点/修车费/改装件(`config/wpcost.blk`)、全局经济与分房公式(`config/warpoints.blk`、`config/rank.blk`)、初始档案模板(`config/default_user.blk`)、任务列表与成就解锁(`config/mislist.blk`、`config/pve_awards.blk`、`config/unlocks.blk`)、涂装/贴花/挂件/道具定义(`config/skins.blk`、`config/decals.blk`、`config/attachable.blk`、`config/items.blk`)以及 `config/network.blk` | `packages/patcher` 构建副本时改写服务地址与隐藏载具可见性;`apps/server` 启动时从中提取绝大部分静态经济与科技树数据集 |
|
||||
| `aces.vromfs.bin` | 局内玩法与连杀支援规则(`config/gameplay.blk`)、界面与礼包 GUID 映射(`config/gui.blk`)、工坊配方(`config/workshop.blk`)以及全部载具的气动/损伤/武器预设模型(`gamedata/flightmodels/…`、`gamedata/units/…`) | `packages/patcher` 写入本地商店礼包 GUID;`apps/server` 提取对局出生规则、礼包映射与载具武器预设 |
|
||||
| `gui.vromfs.bin` | 客户端全部机库、弹窗、商店、战后结算与 HUD 界面的 Quirrel 脚本(`scripts/**/*.nut`)与布局模板(`.blk` / `.css`) | `patches/gui/` 在构建副本时对少数客户端界面脚本做精确片段替换 |
|
||||
| `mis.vromfs.bin` | 多人对战与单人任务的地图逻辑、出生点区域、战区与胜利条件定义(`gamedata/missions/**/*.blk`) | `apps/server` 启动时扫描提取多人任务目录(`multiplayer-missions` 数据集),用于匹配开局 |
|
||||
| `lang.vromfs.bin` | 分号分隔的多语言本地化词条表(`lang/units.csv`、`lang/menu.csv`、`lang/unlocks_achievements.csv` 等) | `apps/server` 提取载具、国家与物品的多语言显示名称,供本地网页商店、交易所和启动器展示 |
|
||||
| `ui/atlases.vromfs.bin` | 科技树载具剪影与阵营国旗等矢量图标(`gameuiskin/*.svg`) | `apps/server` 按需提取金币车/礼包车/市场车图标与国旗(`web-icons` 数据集)供游戏内嵌网页商店渲染 |
|
||||
| `ui/images.vromfs.bin` | 界面位图插画、礼包封面与飞行员头像贴图(`images/**`) | `apps/server` 为内嵌网页商店展示商品封面,并为启动器存档页渲染玩家头像 |
|
||||
|
||||
### 2. `BLK` / `DataBlock`(Dagor 树状键值与块数据格式)
|
||||
|
||||
`BLK`(引擎 C++ 类名为 `DataBlock`)是贯穿整个游戏的通用配置与通信载体,结构类似「带严格值类型的树状 JSON」:每个节点既可以挂载带类型的参数(如整数 `:i`、浮点 `:r`、字符串 `:t`、布尔 `:b`、三维向量 `:p3`、矩阵 `:m` 等),也可以嵌套任意多层同名或异名子块。在 WTOffline 中你会见到它的四种形态,全部由 `@wto/blk`(`decodeBlk`、`encodeBlk`、`formatBlkText`、`parseBlkText`)统一处理:
|
||||
|
||||
- **归档包内的紧凑二进制 BLK**:`char.vromfs.bin` 与 `aces.vromfs.bin` 里的 `.blk` 通常将键名抽离到包内共享键名表 `nm`(甚至配合 `.dict` 字典做二次 zstd 压缩),解码时需传入 `SharedNameContext`;
|
||||
- **`char` 协议单包二进制 BLK**:HTTP 响应体首字节带压缩标记(例如 `0x69` 即 `'i'` 表示未压缩二进制 BLK,另有 zlib / zstd 标记),后面紧跟自包含二进制 BLK;
|
||||
- **`PBBD` 批处理流**:客户端上传云端键位与设置(`cln_bulk_set_gblk`)时使用的多段二进制容器(魔数 `"PBBD"`),每段内嵌独立 BLK 块;
|
||||
- **本地存档自包含二进制 BLK**:`<数据目录>/saves/<userId>/profile.blk` 直接用 `encodeBlk()` 落盘,完整保留每个字段的原始值类型,避免整数与浮点数混淆导致客户端解析异常。
|
||||
|
||||
### 3. 本地模拟的四大 Gaijin 后端服务
|
||||
|
||||
原版联网客户端并不是只跟一台服务器通信,而是同时访问多套职责不同的后端服务。`apps/server` 在本机 `127.0.0.1:<端口>` 上把这四大核心服务全部接管并模拟:
|
||||
|
||||
- **`yuplay2`(登录与权益服务,`login/`、`store/`)**:处理客户端启动时的账号密码表单登录(`POST /login.php`),签发本地会话凭据与 `userId`,并提供商店礼包与激活码相关的 Web 接口;
|
||||
- **`char`(角色档案服务器 Character Server,`char/`)**:机库阶段最核心的请求入口(原域名 `char-*.warthunder.com`)。客户端通过 HTTP 请求头 `action` 指明动作名(如 `cln_get_user_stat`、`cln_buy_aircraft`、`cln_set_researchable`、`cln_update`),通过 `uidhint` 指明当前账号,请求与响应主体以二进制 BLK 为主,负责完整玩家档案下发、科技树研发、买车买改装、乘员组训练、联队、云端键位设置及战后经济结算;
|
||||
- **`matching`(匹配与开局二进制长连接服务,`matching/`)**:基于 TCP 的自定义二进制长连接协议(首字节固定为 `0x01`,9 字节包头 + LZ4 压缩负载,握手后启用流加密)。负责向客户端下发可用游戏模式列表、接收排队与小队状态,并在匹配成功时向客户端下发完整的对局启动参数(地图、天气、AI 名单、自定义计分参数等);
|
||||
- **`inventory`(外部物品库与交易所服务,`inventory/`)**:模拟 `inventory-proxy-*.gaijin.net/char` 接口(动作名如 `GetInventory`、`GetItemDefsClient`、`GetItemPrices`、`GetItemDefChances`、`ExchangeItems`)。与 `char` 不同,客户端 `charsq` 模块直接将响应解析为 UTF-8 JSON,且要求关键响应附带 RSA 内容签名;用于驱动补给箱开箱、载具兑换券、工坊合成与本地模拟交易所。
|
||||
|
||||
### 4. `LocalMP`(为什么既要有 `apps/server`,又必须有 `wto_ws.dll`?)
|
||||
|
||||
初看代码库时最容易产生的疑问是:**既然已经用 Node.js 写了本地服务器 `apps/server`,为什么还要用 C 写一个 `native/wto-net/`(编译为 `wto_ws.dll`)注入进游戏进程?**
|
||||
|
||||
原因在于《战争雷霆》客户端与专用对局服务器(Dedicated Server)的代码裁剪边界:
|
||||
|
||||
- 原版零售客户端 `aces.exe` 内部其实保留了一套名为 **`LocalMP`(本地多人主机,`mp_is_host == 1 && mp_is_local_mp == 1`)** 的局内会话模式,能够在本机直接跑完整的物理引擎、弹道解算、损伤模型与 AI 驾驶逻辑,因此 WTOffline 不需要重写整套游戏物理服务器;
|
||||
- **但是**,Gaijin 在编译零售版 `aces.exe` 时,把原本只在云端专用对局服务器上运行的大量「对局裁判(Host Referee)」处理逻辑裁掉了——包括:**响应玩家选车与挂载弹药并生成实体、允许 `BotSystem` 刷出 AI 载具、判定击杀/助攻/占点并往记分牌加分、陆战街机连杀空中支援事件生成、核弹落地直接判胜,以及过滤本不该发给受害者之外玩家的炮管/炮闩受损提示**;
|
||||
- 因此两套组件分工明确、缺一不可:**`apps/server` 负责对局之外的一切**(登录、机库养成、商店市场、排队拼装任务配置、战后发银狮/研发点与存档持久化);而 **`wto_ws.dll` 在对局进行期间通过 MinHook 挂载在 `aces.exe` 进程内**,一方面把所有硬编码外网 Socket 连接重定向回 `127.0.0.1`,另一方面通过 `local_mp_*` 模块把被客户端裁掉的局内主机裁判逻辑原原本本补齐。
|
||||
|
||||
### 5. `Quirrel (.nut)` 与 `sq.exe` 字节码编译器
|
||||
|
||||
`gui.vromfs.bin` 中的 `.nut` 文件使用的是 Gaijin 基于 Squirrel 深度定制的强词法作用域脚本语言 **[Quirrel](https://quirrel.io/)**。客户端在玩家点击登录、进入机库前会一次性编译加载大批 `.nut` 脚本。
|
||||
|
||||
为什么修改 `patches/gui/` 后**不能只靠肉眼或普通语法树(AST)检查**,而需要用对应提交版本的原生编译器 `sq.exe` 跑 `wtotools check-gui`?因为 Quirrel 的 `compilestring` 字节码编译阶段会执行严格的词法绑定检查:
|
||||
|
||||
- 如果你在 `replace.nut` 里声明了一个 `local` 变量,恰好与该文件顶部 `from ... import *` 通配导入的某个全局常量重名;
|
||||
- 或者在函数尚未定义/绑定前做了前向调用;
|
||||
- 或者把 Quirrel 保留字(最典型的坑是 `base`)当成了普通变量名;
|
||||
|
||||
普通语法检查器都会放行,但真进游戏时 Quirrel 虚拟机就会直接中断模块加载,导致客户端**永远卡死在登录后的「正在加载…」转圈界面**。`wtotools check-gui` 会在内存中打上所有 GUI 补丁并逐个调用 `sq.exe` 编译字节码,把这类致命隐患在提交前 100% 拦住。
|
||||
|
||||
### 6. `RVA`、虚拟地址(`VA`)与进程运行时指针
|
||||
|
||||
在看 `patches/exe/`、`patches/native/` 或使用逆向工具时,务必分清这三种地址表示:
|
||||
|
||||
- **`VA`(Virtual Address,静态虚拟地址)**:Ghidra 或 IDA 打开 64 位 Windows 程序 `aces.exe` 时,默认镜像基址(`ImageBase`)是 `0x140000000`,因此反编译器里显示的函数地址往往长这样:`0x1412657a0`;
|
||||
- **`RVA`(Relative Virtual Address,相对虚拟地址)**:减去镜像基址后的纯偏移,即 **`RVA = VA - ImageBase`**(例如 `0x1412657a0 - 0x140000000 = 0x12657a0`)。因为 Windows 的 ASLR(地址空间布局随机化)每次启动游戏都会把 `aces.exe` 加载到不同的内存基址,**仓库内所有补丁注释、`tools/re/cli.py` 参数以及生成的 `win64/wto_ws.cfg` 一律使用 RVA**;
|
||||
- **运行时绝对指针(Runtime Pointer)**:游戏启动后,`wto_ws.dll`(见 `native/wto-net/src/local_mp_values.c`)通过 `(uint8_t *)GetModuleHandleW(NULL) + rva` 把 `wto_ws.cfg` 里的 RVA 换算成当次进程内的真实内存地址存入 `g_lmp`。
|
||||
|
||||
### 7. `features` 功能标签与三条「核心安全锁」(`ESSENTIAL_FEATURES`)
|
||||
|
||||
每个 `patches/exe/**/patch.jsonc`、`patches/gui/**/patch.jsonc` 和 `patches/native/*.jsonc` 都包含一个 `features` 字符串数组,标签以功能分组字母 `A-`..`K-` 开头(例如 `"G-Store"`、`"K-AI opponents and teammates"`、`"K-Kill, assist and capture scoring"`)。当游戏刚发布小版本更新、个别非关键补丁暂时失配时,启动器依靠这些标签清晰告知玩家「当前版本哪一项具体子功能暂不可用」,其余功能仍可正常游玩。
|
||||
|
||||
但其中有 **3 个定义在 `packages/patcher/src/essential-features.ts`(`ESSENTIAL_FEATURES`)中的硬阻断安全标签**例外:
|
||||
|
||||
1. **`A-Offline startup`**:离线副本能否启动的根基(例如跳过修改后 `.vromfs.bin` 的官方签名校验);
|
||||
2. **`A-Isolation from the official game`**:与官方正版客户端的完全隔离(将用户配置存档改到独立 `WTOffline` 目录、注册表改到 `Software\WTOffline`、剥离反作弊启动器与崩溃上报);
|
||||
3. **`A-No Gaijin connections`**:彻底阻断连向 Gaijin 官方服务器(例如将导入表 `WS2_32.dll` 替换为 `wto_ws.dll` 并在加载时强制挂载网络重定向钩子)。
|
||||
|
||||
只要带有上述任一标签的补丁未能成功定位和应用,`blockingFailures()` 就会**终止副本构建与启动**,防止离线客户端触碰玩家的线上正版数据或直连官方服务器,从而保护玩家的线上账号安全。
|
||||
|
||||
---
|
||||
|
||||
## 按你想做的事,直接定位代码目录
|
||||
|
||||
| 你想做什么 | 具体源码子目录 | 对口参考章节 |
|
||||
| --- | --- | --- |
|
||||
| 新增或修复机库动作路由(买车、研发、乘员、联队、贴花、战后结算等 `char` 接口) | `apps/server/src/char/actions/`(协议适配)+ `apps/server/src/<领域>/`(纯业务规则,如 `research/`、`modifications/`、`crew/`、`battle/`) | [架构分层与真实动作追踪](development-rules.md#server-layers-zh) |
|
||||
| 修改玩家档案字段读写、新号初始资产或存档落盘格式 | `apps/server/src/profile/`、`apps/server/src/saves/`、`apps/server/src/storage/` | [存档层与原子写盘规范](development-rules.md#walkthrough-zh) |
|
||||
| 从游戏原版数据包提取新的载具/经济/任务/本地化静态数据 | `apps/server/src/game-data/datasets/` | [三类数值与缓存数据集](development-rules.md#values-zh) |
|
||||
| 调整离线版默认倍率、商店定价、补给箱权重、AI 重生数或上限参数 | `apps/server/tuning/*.jsonc` + `apps/server/src/tuning/` + 各领域 `*-tuning.ts` | [三类数值放哪里](development-rules.md#values-zh) |
|
||||
| 修改本地内嵌网页商店、模拟交易所或服务器脚本模组运行时 | `apps/server/src/store/`、`apps/server/src/inventory/`、`apps/server/src/web-ui/`、`apps/server/src/mods/` | [服务器目录全景图](development-rules.md#server-layers-zh) |
|
||||
| 修改桌面启动器界面、安装向导、存档管理页、模组管理页或更新器 | `apps/launcher/src/` | [检查命令清单](contributing.md#checks) |
|
||||
| 修改离线副本构建管线、归档包改写、BLK 编解码、EXE 补丁引擎或模组加载器 | `packages/patcher/`、`packages/blk/`、`packages/vromfs/`、`packages/exepatch/`、`packages/mods/` | [仓库级单向依赖约定](development-rules.md#workspace-rule-zh) |
|
||||
| 修改游戏内界面弹窗、按钮或结算页脚本(Quirrel `.nut`) | `patches/gui/<领域>/<名称>/` | [GUI 补丁完整范例](patches.md#gui-patches-zh) |
|
||||
| 修改 `aces.exe` 机器码分支或只读常量字符串 | `patches/exe/<领域>/<名称>/` | [EXE 补丁 57 字节逐指令拆解](patches.md#exe-patches-zh) |
|
||||
| 编写或修复 `wto_ws.dll` 局内 `LocalMP` 原生裁判钩子 | `patches/native/<模块>.jsonc` + `native/wto-net/src/` | [Native 模块 6 文件串联教程](patches.md#native-modules-zh) |
|
||||
| 协助适配刚发布的《战争雷霆》客户端小版本更新 | `patches/versions/`、`scripts/record-game-version.ts` | [适配新版本客户端四步流程](patches.md#adapt-version-zh) |
|
||||
|
||||
---
|
||||
|
||||
<a id="english"></a>
|
||||
|
||||
[简体中文](#zh-cn) · English
|
||||
[简体中文](#zh-cn) · English · [Online Docs](https://wto-project.net/dev-docs)
|
||||
|
||||
Start with a stock client you own and use it as a read-only source. Install the tools and dependencies listed in the [main README](../README.md#development). To launch the game for verification, prepare an offline copy outside the Steam library and a separate data directory, then verify isolation using the [development rules](development-rules.md#english).
|
||||
Welcome to WTOffline development. This directory is written for **project contributors, client build adapters, and collaborators using AI coding assistants to reverse-engineer, investigate, and fix issues**. Even if you have never worked with the Dagor Engine or War Thunder internals before, these guides walk you through every layer from first principles.
|
||||
|
||||
| Task | Start here |
|
||||
| --- | --- |
|
||||
| Change the launcher or installer | [apps/launcher](../apps/launcher) |
|
||||
| Change game rules, saves, or local services | [apps/server](../apps/server) |
|
||||
| Change the game copy build or patch checks | [packages/patcher](../packages/patcher), [scripts](../scripts), [tools](../tools) |
|
||||
| Write a client patch or adapt a new game build | [Patch guide](patches.md#english) and the [patch set](../patches) |
|
||||
| Author additive mods (experimental) | [Mod development docs (mod-dev-docs)](../mod-dev-docs/README.md#english) |
|
||||
> **Just want to create vehicle stat tweaks, custom map pools, standalone 3D vehicles, or server script mods?** You do not need to modify WTOffline's core source code at all—head straight to the [Mod Development Docs (`mod-dev-docs`)](../mod-dev-docs/README.md#english) or the [online Mod Docs](https://wto-project.net/mod-docs).
|
||||
|
||||
Before submitting, follow the [review checklist](contributing.md#english), run the applicable [checks](contributing.md#checks), and record the results and in-game steps in the [PR template](templates/pull-request.md).
|
||||
---
|
||||
|
||||
## Recommended Reading Order
|
||||
|
||||
Do not jump straight into raw byte patterns or disassembly offsets on your first visit. Reading the three core guides in this order builds the full mental model in 15–20 minutes:
|
||||
|
||||
1. **[Design Philosophy, Architecture & Engineering Rules](development-rules.md#english)** (**Start here**): Understand how the launcher, single-port local server (`apps/server`), and in-process Winsock/LocalMP bridge (`wto_ws.dll`) fit together; trace one real `cln_set_researchable` request end-to-end across all four server layers; learn where the three categories of numbers belong; review four real Good vs. Bad code comparisons; and grab the copy-paste prompt block for AI coding assistants.
|
||||
2. **[Patch Authoring & Version Adaptation Guide](patches.md#english)**: Once you have confirmed that the local server and stock configuration genuinely cannot solve an issue, follow step-by-step instructions to unpack stock archives, disassemble `aces.exe` with `tools/re/cli.py`, and study un-elided real patches across `patches/gui/`, `patches/exe/`, and `patches/native/` + `native/wto-net/`.
|
||||
3. **[Environment Setup, Traffic Debugging & PR Guide](contributing.md#english)**: Set up the Windows x64 toolchain, inspect auto-decoded readable BLK payloads under `<data-dir>/logs/` to pinpoint bugs in minutes, run the required verification commands for your change type, and fill out the [PR template](templates/pull-request.md).
|
||||
|
||||
---
|
||||
|
||||
<a id="glossary-en"></a>
|
||||
|
||||
## Core Concepts & Glossary
|
||||
|
||||
You will encounter these War Thunder and WTOffline terms throughout the codebase and documentation. Here is what each one means in plain language:
|
||||
|
||||
### 1. `vromfs.bin` (Dagor Virtual Read-Only File System Archive)
|
||||
|
||||
Instead of shipping tens of thousands of loose scripts and config files on disk, War Thunder bundles them into `.vromfs.bin` archives. Each archive has two layers: an outer container (Zstandard compression with lightweight XOR obfuscation, an MD5 digest of the inner image, and a 256-byte signature tail) and an inner image (a lowercase relative path table, byte offsets, optional SHA-1 digests, plus an optional shared name map `nm` and `.dict` zstd dictionary). `@wto/vromfs` (`readArchive`, `getFile`, `putFile`, `writeArchive`) reads and repacks these archives losslessly.
|
||||
|
||||
Use this lookup table whenever you need to find where a stock script, config, or asset lives:
|
||||
|
||||
| Archive path (relative to game root) | What it stores | How WTOffline uses it |
|
||||
| --- | --- | --- |
|
||||
| `char.vromfs.bin` | Tech-tree layout (`config/shop.blk`), per-vehicle prices, RP, repair costs, and modifications (`config/wpcost.blk`), global economy and BR formulas (`config/warpoints.blk`, `config/rank.blk`), new-account profile template (`config/default_user.blk`), mission lists and unlock definitions (`config/mislist.blk`, `config/pve_awards.blk`, `config/unlocks.blk`), camos/decals/decorators/classic items (`config/skins.blk`, `config/decals.blk`, `config/attachable.blk`, `config/items.blk`), and `config/network.blk` | `packages/patcher` rewrites backend URLs and hidden-vehicle visibility during copy builds; `apps/server` extracts most economy, tech-tree, unlock, and mission datasets from it at startup |
|
||||
| `aces.vromfs.bin` | Match gameplay and killstreak rules (`config/gameplay.blk`), UI config and store bundle GUID mappings (`config/gui.blk`), workshop recipes (`config/workshop.blk`), and all vehicle flight/damage/weapon preset files (`gamedata/flightmodels/…`, `gamedata/units/…`) | `packages/patcher` injects offline store bundle GUIDs; `apps/server` extracts spawn rules, bundle mappings, and weapon presets |
|
||||
| `gui.vromfs.bin` | All in-game hangar, modal, store, debriefing, and HUD Quirrel scripts (`scripts/**/*.nut`) and layout templates (`.blk` / `.css`) | `patches/gui/` applies minimal surgical text replacements to UI scripts when building the offline copy |
|
||||
| `mis.vromfs.bin` | Multiplayer and single-player mission logic, spawn zones, capture points, and victory rules (`gamedata/missions/**/*.blk`) | `apps/server` scans it at startup (`multiplayer-missions` dataset) to build matchmaking mission definitions |
|
||||
| `lang.vromfs.bin` | Semicolon-separated localization CSV tables (`lang/units.csv`, `lang/menu.csv`, `lang/unlocks_achievements.csv`, etc.) | `apps/server` extracts localized vehicle, country, and item names for the in-game web store, marketplace, and launcher |
|
||||
| `ui/atlases.vromfs.bin` | Tech-tree vehicle silhouettes and country flags in SVG format (`gameuiskin/*.svg`) | `apps/server` extracts icons for gift/premium/market vehicles and flags (`web-icons` dataset) for the local web store and marketplace |
|
||||
| `ui/images.vromfs.bin` | UI raster artwork, bundle cover images, and pilot avatar textures (`images/**`) | `apps/server` serves store/marketplace item artwork and renders player profile icons for the launcher's saves page |
|
||||
|
||||
### 2. `BLK` / `DataBlock` (Dagor Typed Hierarchical Data Format)
|
||||
|
||||
`BLK` (named `DataBlock` in Dagor Engine C++ code) is the typed tree format used everywhere in War Thunder for configs, network payloads, and player profiles. Think of it as a tree of named blocks and typed key-value parameters (`:i` integers, `:r` floats, `:t` strings, `:b` booleans, `:p3` 3D vectors, `:m` matrices, etc.). You will encounter four binary/wire representations in WTOffline, all handled by `@wto/blk` (`decodeBlk`, `encodeBlk`, `formatBlkText`, `parseBlkText`):
|
||||
|
||||
- **Slimmed binary BLK inside `.vromfs.bin`**: `.blk` files inside `char.vromfs.bin` and `aces.vromfs.bin` strip repeated key names into the archive's shared name map `nm` (and may compress payloads with an archive `.dict` zstd dictionary), decoded by passing `SharedNameContext` to `decodeBlk`;
|
||||
- **Framed binary BLK on `char` HTTP exchanges**: Single-document HTTP payloads prefixed with a 1-byte compression marker (e.g., `0x69` / `'i'` for uncompressed binary BLK, or zlib/zstd markers);
|
||||
- **`PBBD` batch streams**: Multi-chunk binary streams (magic `"PBBD"`) used by `online_storage` (`cln_bulk_set_gblk`) when uploading keybindings and cloud settings, where each chunk carries an embedded BLK block;
|
||||
- **Self-contained binary BLK on disk**: Player profiles saved at `<data>/saves/<userId>/profile.blk` via `encodeBlk()`, preserving every parameter's exact scalar/vector type so the game client never misinterprets ints as floats or vice versa.
|
||||
|
||||
### 3. The Four Gaijin Backend Services Emulated Locally
|
||||
|
||||
A live War Thunder client talks to several distinct backend services rather than a single monolithic API. `apps/server` emulates all four locally on a single `127.0.0.1:<port>` listener:
|
||||
|
||||
- **`yuplay2` (Login & Entitlement APIs, `login/`, `store/`)**: Handles form-encoded credential sign-in (`POST /login.php`), issues local session tokens and `userId`s, and serves store/redeem-code web endpoints;
|
||||
- **`char` (Character Server, `char/`)**: The primary hangar RPC service (`char-*.warthunder.com`). Requests specify the operation via the `action` HTTP header (such as `cln_get_user_stat`, `cln_buy_aircraft`, `cln_set_researchable`, `cln_update`) and identify the player via `uidhint`, exchanging binary BLK payloads for full profile sync, tech-tree research, vehicle/modification/crew purchases, squadrons, cloud settings, and post-battle settlement;
|
||||
- **`matching` (Binary Matchmaking & Session RPC, `matching/`)**: A persistent binary TCP protocol (first byte `0x01`, 9-byte header + LZ4-compressed frame, stream-encrypted after handshake) that serves game-mode lists, manages queues and squad state, and dispatches complete battle launch configurations (map, weather, AI bot rosters, `customScoreParams`, etc.);
|
||||
- **`inventory` (External Inventory & Marketplace Service, `inventory/`)**: Emulates `inventory-proxy-*.gaijin.net/char` (`GetInventory`, `GetItemDefsClient`, `GetItemPrices`, `GetItemDefChances`, `ExchangeItems`). Unlike `char`, the client's `charsq` subsystem parses raw HTTP bodies directly as UTF-8 JSON and verifies RSA content signatures—powering supply chests, vehicle coupons, workshop crafting, and the simulated marketplace.
|
||||
|
||||
### 4. `LocalMP` (Why WTOffline Needs Both `apps/server` AND `wto_ws.dll`)
|
||||
|
||||
A natural question for newcomers is: **If `apps/server` already emulates Gaijin's backend in TypeScript, why do we also compile `native/wto-net/` into `wto_ws.dll` and load it inside `aces.exe`?**
|
||||
|
||||
The answer comes down to what Gaijin kept vs. stripped in the retail game client:
|
||||
|
||||
- Retail `aces.exe` still contains an in-process **`LocalMP` session mode (`mp_is_host == 1 && mp_is_local_mp == 1`)** capable of running full physics, ballistics, damage models, and AI piloting/driving locally—meaning WTOffline does not have to reimplement a Dedicated Server physics engine from scratch;
|
||||
- **However**, when building retail `aces.exe`, Gaijin compiled out many **Dedicated Server battle referee handlers** that normally run only in the cloud during live matches: **spawning player vehicles and weapon loadouts on selection, granting `BotSystem` permission to spawn AI vehicles, awarding kill/assist/capture scoreboard points, running Ground Arcade killstreak air events, triggering nuclear instant victories, and filtering barrel/breech/part-damage HUD notices so enemy hits are not misdelivered to the local player**;
|
||||
- Consequently, the two halves have a crisp boundary: **`apps/server` owns everything before and after a battle** (login, hangar progression, economy, store/market, matchmaking setup, post-battle Silver Lions/RP settlement, and atomic save persistence), while **`wto_ws.dll` hooks `aces.exe` in-process via MinHook**—redirecting hardcoded outbound Winsock traffic to `127.0.0.1` and restoring stripped host-side referee logic **during** live `LocalMP` battles via modular `local_mp_*` bridges.
|
||||
|
||||
### 5. `Quirrel (.nut)` & the `sq.exe` Bytecode Compiler
|
||||
|
||||
UI scripts inside `gui.vromfs.bin` (`.nut` files) are written in **[Quirrel](https://quirrel.io/)**, Gaijin's Squirrel-derived scripting language with strict lexical scoping. When logging into the hangar, the client preloads and compiles UI script modules en masse.
|
||||
|
||||
Why is running `wtotools check-gui` with the matching `sq.exe` compiler mandatory whenever you touch `patches/gui/`, instead of eyeballing diffs or running an AST-only syntax check? Because Quirrel's `compilestring` bytecode compiler enforces lexical binding rules that AST parsers ignore:
|
||||
|
||||
- Declaring a `local` identifier that collides with a constant imported via `from ... import *` at the top of the file;
|
||||
- Referencing an unbound local/module function before its declaration;
|
||||
- Using a Quirrel reserved keyword (most notoriously `base`) as a variable name.
|
||||
|
||||
Any of those mistakes looks syntactically innocent on paper, yet aborts module compilation inside the game client and **freezes login indefinitely on the `"Loading..."` spinner**. `wtotools check-gui` applies every GUI patch in memory and compiles each modified `.nut` file to Quirrel bytecode via `sq.exe`, catching 100% of lexical and constant-binding errors before commit.
|
||||
|
||||
### 6. `RVA` vs. Virtual Address (`VA`) vs. Runtime Pointer
|
||||
|
||||
Keep these three address forms straight whenever you read disassembly or write `patches/`:
|
||||
|
||||
- **`VA` (Virtual Address)**: When you open 64-bit `aces.exe` in Ghidra or IDA, the default PE `ImageBase` is `0x140000000`, so addresses appear as `0x1412657a0`;
|
||||
- **`RVA` (Relative Virtual Address)**: Offset from the image base, i.e., **`RVA = VA - ImageBase`** (`0x1412657a0 - 0x140000000 = 0x12657a0`). Because Windows ASLR loads `aces.exe` at a fresh random base address on every launch, **every `patches/` comment, `tools/re/cli.py` argument, and `win64/wto_ws.cfg` entry uses RVAs exclusively**;
|
||||
- **Runtime Pointer**: When the game starts, `wto_ws.dll` (`native/wto-net/src/local_mp_values.c`) adds the live module base `(uint8_t *)GetModuleHandleW(NULL) + rva` and stores the resulting process pointer in `g_lmp`.
|
||||
|
||||
### 7. `features` Tags & the Three Essential Safety Locks (`ESSENTIAL_FEATURES`)
|
||||
|
||||
Every definition in `patches/exe/**/patch.jsonc`, `patches/gui/**/patch.jsonc`, and `patches/native/*.jsonc` lists one or more `features` tags prefixed by inventory category (`A-` through `K-`, such as `"G-Store"`, `"K-AI opponents and teammates"`, or `"K-Kill, assist and capture scoring"`). If a minor client update breaks an optional patch, the launcher uses these tags to show the player exactly which non-essential gameplay feature is degraded while still letting them play.
|
||||
|
||||
Three tags defined in `packages/patcher/src/essential-features.ts` (`ESSENTIAL_FEATURES`) are **hard-blocking safety locks**:
|
||||
|
||||
1. **`A-Offline startup`**: Required for the offline copy to boot at all (e.g., bypassing `.vromfs.bin` pack signature checks so modified archives load);
|
||||
2. **`A-Isolation from the official game`**: Keeps the offline copy completely separate from the official client (redirecting user saves/settings to `WTOffline`, registry keys to `Software\WTOffline`, and disabling the anti-cheat launcher and crash reporter);
|
||||
3. **`A-No Gaijin connections`**: Guarantees zero traffic reaches Gaijin's live servers (e.g., rewriting the PE import descriptor from `WS2_32.dll` to `wto_ws.dll` and enforcing Winsock redirection hooks on attach).
|
||||
|
||||
If **any** patch carrying one of these three tags fails to resolve, `blockingFailures()` immediately aborts copy installation and launch—protecting the player's official online installation and account from ever being touched.
|
||||
|
||||
---
|
||||
|
||||
## Jump Straight to Your Task
|
||||
|
||||
| What you want to do | Specific codebase directories | Primary reference |
|
||||
| --- | --- | --- |
|
||||
| Add or fix hangar actions (research, purchases, crews, squadrons, decals, post-battle settlement, etc.) | `apps/server/src/char/actions/` (wire handlers) + `apps/server/src/<domain>/` (pure rules: `research/`, `modifications/`, `crew/`, `battle/`, etc.) | [Server Layers & Action Walkthrough](development-rules.md#server-layers-en) |
|
||||
| Change player profile fields, new-account defaults, or save persistence / format upgrades | `apps/server/src/profile/`, `apps/server/src/saves/`, `apps/server/src/storage/` | [Persistence & Atomic Writes](development-rules.md#walkthrough-en) |
|
||||
| Extract new static vehicle, economy, mission, or localization data from stock archives | `apps/server/src/game-data/datasets/` | [Three Categories of Values](development-rules.md#values-en) |
|
||||
| Adjust offline reward multipliers, store prices, supply-chest weights, AI respawn counts, or limits | `apps/server/tuning/*.jsonc` + `apps/server/src/tuning/` + `<domain>/*-tuning.ts` | [Three Categories of Values](development-rules.md#values-en) |
|
||||
| Work on the in-game web store, simulated marketplace, or server script mod runtime | `apps/server/src/store/`, `apps/server/src/inventory/`, `apps/server/src/web-ui/`, `apps/server/src/mods/` | [Server Directory Map](development-rules.md#server-layers-en) |
|
||||
| Change the desktop launcher UI, install wizard, saves manager, mods page, or auto-updater | `apps/launcher/src/` | [Required Check Commands](contributing.md#checks-en) |
|
||||
| Modify copy building, archive patching, BLK/vromfs codecs, EXE patch engine, or mod loader | `packages/patcher/`, `packages/blk/`, `packages/vromfs/`, `packages/exepatch/`, `packages/mods/` | [Workspace Dependency Rule](development-rules.md#workspace-rule-en) |
|
||||
| Patch in-game UI modals, buttons, or debriefing Quirrel scripts (`.nut`) | `patches/gui/<domain>/<name>/` | [GUI Patches Full Example](patches.md#gui-patches-en) |
|
||||
| Patch machine instructions or constant `.rdata` strings in `aces.exe` | `patches/exe/<domain>/<name>/` | [EXE Patch 57-Byte Anatomy](patches.md#exe-patches-en) |
|
||||
| Write or fix `wto_ws.dll` in-process `LocalMP` battle host hooks | `patches/native/<module>.jsonc` + `native/wto-net/src/` | [Native Modules 6-File Wiring](patches.md#native-modules-en) |
|
||||
| Adapt WTOffline to a newly released minor War Thunder client build | `patches/versions/`, `scripts/record-game-version.ts` | [Adapting a New Client Build](patches.md#adapt-version-en) |
|
||||
+254
-48
@@ -1,81 +1,122 @@
|
||||
# Contributing
|
||||
# 环境搭建、流量调试与提交指南 / Contributing Guide
|
||||
|
||||
<a id="zh-cn"></a>
|
||||
|
||||
简体中文 · [English](#english) · [返回 Dev Docs](README.md#zh-cn)
|
||||
|
||||
## 提交前自查
|
||||
这篇指南带你从零搭好本地开发环境、用内置的自动解码流量日志快速定位机库与对局问题,并在发起 Pull Request 前跑通对应的真实工程检查。
|
||||
|
||||
- 改动只解决一个目标。实现、配置、补丁说明和相关开发文档一致。提交标题用英文 `type(scope): description`,scope 用小写模块名,仓库级改动用 `repo`。破坏兼容时用 `type(scope)!: description`,并在 `BREAKING CHANGE:` 脚注说明影响和处理方式。正文交代原因、依据和验证结果,代码注释也用英文。联署留给实际协作的开发者。
|
||||
- 游戏行为的判断有目标版本和一手出处。新动作写清客户端怎样发请求、怎样读取应答。客户端改动登记到对应补丁或构建模块,并说明为何需要。涉及新数值时,按[三类数值规则](development-rules.md#数值和数据来源)检查来源、配置和校验。
|
||||
- 检查模块职责、依赖方向和重复逻辑。涉及账号、余额和档案时,检查错误输入、写盘顺序,以及多个账号之间的数据隔离。选择奖品或其他数据项时,按明确规则排序和筛选。
|
||||
- 若借助 AI 助手编写代码,提交前请人工逐行对照 [常见实现陷阱与工程红线](development-rules.md#常见实现陷阱与工程红线含-ai-辅助开发对照):确认没有硬编码偏移/地址、没有写死原版数据或魔法数字、没有越层修改或夹带无关改动,并且每一条写进 PR 的检查命令都在本机真实运行过。
|
||||
- 只做类型、补丁、构建和可运行检查。功能验收由人使用隔离副本在游戏里做。注明实际执行过的命令、对应版本和结果。还要实机核对时写出入口、操作和预期现象。商城或交易所改动覆盖内置浏览器打开、相关操作和关窗后的档案刷新。
|
||||
- 提交前看一遍差异,确认来源、路径、记录和玩家数据可以分享。用 [PR 模板](templates/pull-request.md) 提供复核所需的信息。
|
||||
---
|
||||
|
||||
<a id="english"></a>
|
||||
## 1. 开发环境准备
|
||||
|
||||
[简体中文](#zh-cn) · English · [Dev Docs](README.md#english)
|
||||
你需要一台 **Windows x64** 电脑,并安装以下基础工具:
|
||||
|
||||
## Review before submitting
|
||||
1. **Node.js 24+**:仓库内的 CLI 脚本与 `apps/server` 直接以 Node 24 原生类型剥离模式运行 `.ts` 源码(Node 20/22 旧版本会因 `.ts` 扩展名或模块解析报错)。
|
||||
2. **Visual Studio 2022 或 Build Tools(勾选「使用 C++ 的桌面开发」x64 工具链与 CMake)**:用于通过 `cl.exe` 编译 `native/wto-net/`(生成 `wto_ws.dll`),以及一次性编译 Quirrel 字节码检查器 `sq.exe`。
|
||||
3. **Python 3.12+**:用于运行补丁校验器 `wtotools`、静态逆向工具 `tools/re/cli.py` 与客户端 `.clog` 日志解密命令。
|
||||
4. **一份玩家本人合法持有的官方原版客户端(严格保持只读)**,以及在 Steam 游戏库目录之外单独准备的**离线副本目录**与**本地服务器数据目录**。
|
||||
|
||||
- Keep one purpose per change. Update the affected implementation, configuration, patch notes, and developer docs together. Use English `type(scope): description` commit subjects with a lowercase module scope or `repo` for repository-wide changes. For a breaking change, use `type(scope)!: description` and a `BREAKING CHANGE:` footer that explains the impact and what to do. Explain the reason, evidence, and verification in the commit body. Use English comments and reserve co-author credits for developers who actually collaborated.
|
||||
- Cite the target build and primary evidence for game behavior. For new actions, explain how the client sends the request and consumes the reply. Register client edits in their patch or build module and explain why they are needed. For new values, check the source, tuning, and validation using the [three kinds of values](development-rules.md#data-and-tuning).
|
||||
- Check module responsibilities, dependency direction, and reuse. For accounts, currency, and saves, check bad inputs, when updates reach disk, and separation between accounts. Use explicit ordering and selection rules for prize pools and other lists.
|
||||
- When using AI tools to draft code, review the diff line by line against [common implementation pitfalls](development-rules.md#common-implementation-pitfalls-especially-with-ai-assisted-prs): confirm there are no hardcoded addresses/offsets, no copied stock numbers or magic constants, no layer violations or unrelated edits, and that every check reported in the PR was actually executed.
|
||||
- Limit automated checks to type, patch, build, and startup checks. Functional acceptance is performed by a person in an isolated game copy. Report the commands actually run, the client builds, and the results. For pending in-game checks, give the entry point, action, and expected result. Store and marketplace changes cover opening the embedded browser, the affected action, and the profile refresh on close.
|
||||
- Review the diff for shareable sources, paths, records, and player data. Use the [PR template](templates/pull-request.md) to provide enough detail for review.
|
||||
首次克隆仓库后,在仓库根目录依次执行:
|
||||
|
||||
```powershell
|
||||
# 1. 安装工作区依赖
|
||||
npm install
|
||||
|
||||
# 2. 编译进程内网络重定向与 LocalMP 桥接库 -> build\native\wto_ws.dll
|
||||
powershell -NoProfile -File .\native\wto-net\build.ps1
|
||||
|
||||
# 3. 下载桌面启动器所需的 Electron 二进制运行时
|
||||
node node_modules/electron/install.js
|
||||
|
||||
# 4. 初始化 Python 虚拟环境并安装本地补丁/逆向工具包 wtotools
|
||||
python -m venv .venv
|
||||
.\.venv\Scripts\python.exe -m pip install -e ./tools
|
||||
```
|
||||
|
||||
如果你想脱离桌面启动器,直接从命令行快速构建一份离线副本并以前台模式启动本地服务器查看实时输出(注意:**`--game` 在构建时传只读原版目录、启动服务器时传离线副本目录,两条命令的 `--data` 与 `--port` 必须完全一致**):
|
||||
|
||||
```powershell
|
||||
node scripts/build-game-copy.ts --game "<原版目录>" --out "<离线副本目录>" --data "<独立数据目录>" --port 27015
|
||||
node apps/server/src/cli.ts --game "<离线副本目录>" --data "<独立数据目录>" --port 27015
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
<a id="debugging-zh"></a>
|
||||
|
||||
## 2. 怎么调试与查日志(排查 Bug 最快的路径)
|
||||
|
||||
排查机库动作报错、购买失败、匹配卡住或对局计分异常时,**千万不要靠盲猜客户端发了什么包**。WTOffline 在四处关键节点都留有可直接阅读的诊断日志:
|
||||
|
||||
### 2.1 本地服务器流量日志:`<数据目录>/logs/<启动时间戳>/`(第一站!)
|
||||
|
||||
每次启动 `apps/server`,`TrafficLog`(`apps/server/src/traffic-log/traffic-log.ts`)都会在 `<数据目录>/logs/` 下新建一个带 ISO 时间戳的会话文件夹,里面包含两部分:
|
||||
|
||||
1. **`requests.jsonl`(全量请求索引流)**
|
||||
每行是一条 JSON 记录,按全局递增序号 `id` 记录每一次 HTTP 交互(`kind: "http"`)、每一条匹配服双向消息(`kind: "matching"`)、被拒绝的 WebSocket 升级请求(`kind: "websocket"`)以及连接开关事件:
|
||||
- **一秒定位未实现接口**:直接在 `requests.jsonl` 中搜索 `"unhandled":true`(或看终端输出末尾带 `[UNHANDLED]` 标记的行),就能立刻抓出客户端刚发了哪个尚未挂载处理器的 `char` 动作、`yuplay2` 路径或 `matching` 消息!
|
||||
- 每条记录中的 `files` 字段直接指明该次请求与响应对应的负载文件名。
|
||||
2. **`bodies/` 子目录(自动解码的可读明文负载!)**
|
||||
每个序号 `id`(补零至 6 位,如 `000042`)按需生成以下文件:
|
||||
- `000042.req.bin` / `000042.resp.bin`:原始线上传输字节(登录表单中的密码字段会自动脱敏);
|
||||
- **`000042.req.txt` / `000042.resp.txt`**:**自动解包并格式化好的可读明文 BLK 文本**(无论是带 `0x69` / zlib / zstd 标记的 `char` 二进制 BLK,还是 `cln_bulk_set_gblk` 上传的 `PBBD` 多段批处理流,都会自动转成缩进清晰的文本 BLK!)或 UTF-8 JSON 文本——你无需手写任何解包脚本,直接用编辑器打开 `.txt` 就能看清每一个字段与类型;
|
||||
- **`000042.matching-in.json` / `000042.matching-out.json`**:解密并解压后的匹配长连接双向 RPC 消息(`in` 为客户端发来,`out` 为本地服务器下发)。
|
||||
|
||||
### 2.2 其余三类配套诊断日志
|
||||
|
||||
- **进程内钩子与 `LocalMP` 日志:`<离线副本目录>/win64/wto_ws.log`**
|
||||
由 `wto_ws.dll` 每次启动游戏时重写。记录本地服务器端口号、每一次域名拦截与 Socket 连接重定向结果、`wto_ws.cfg` 与当前 `aces.exe` 的 PE 头校验结果,以及 **11 个 `local_mp_*` 模块中哪些成功安装、哪些因缺少 `wto_ws.cfg` 键值被优雅跳过**(并打印缺失的具体键名)。排查局内不刷 AI、选车无响应、记分牌为 0 或连杀飞机异常时先看这里。
|
||||
- **游戏引擎客户端日志:`<离线副本目录>/.game_logs/*.clog`**
|
||||
Dagor 引擎原生日志,记录 Quirrel 脚本编译/运行期报错、进机库卡死在「正在加载…」的具体栈信息、任务脚本报错与资源缺失。由于 `.clog` 是二进制异或加密格式,直接用 `tools/re/cli.py` 解密成纯文本再查阅:
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe tools\re\cli.py decrypt-clog "<离线副本目录>\.game_logs\<最新文件>.clog" --out "<临时目录>\game.clog.txt"
|
||||
```
|
||||
- **桌面启动器日志:`launcher.log`**
|
||||
在启动器界面打开「设置 → 诊断 → 打开日志目录」即可查看,记录副本构建、补丁包校验、子进程启停与更新器状态。
|
||||
|
||||
---
|
||||
|
||||
<a id="checks"></a>
|
||||
|
||||
## 检查命令 / Check commands
|
||||
## 3. 提交前必跑的工程检查命令(按改动范围对照执行)
|
||||
|
||||
在仓库根目录执行适用于本次改动的命令。尖括号内的占位内容换成自己的实际值。所有游戏输入文件用只读原版来源,构建输出用单独目录。
|
||||
WTOffline **不要求也不提倡编写庞大的模拟(Mock)单元测试套件**,而是要求你按实际触碰的代码目录,跑通下面对应的**真实编译器、补丁字节核对与 Quirrel 字节码检查**;最终交互体验则在独立隔离副本中进游戏实机验收。
|
||||
|
||||
Run the applicable commands from the repository root. Replace placeholders in angle brackets with your own values. Use read-only stock inputs and a separate build output directory.
|
||||
|
||||
| 改动 / Change | 检查 / Check |
|
||||
| 你修改了哪里 | 提交前必须跑通的检查 |
|
||||
| --- | --- |
|
||||
| 共用库或本地服务器 / Shared packages or local server | 根目录类型检查,必要时用独立数据目录确认服务器能启动<br>Root type check and server startup with separate data when applicable |
|
||||
| 启动器 / Launcher | 启动器的类型检查和构建<br>Launcher type check and build |
|
||||
| exe 补丁 / Exe patch | `check-patches` 核对定位、原字节和源码<br>Verify matches, original bytes, and the patch source with `check-patches` |
|
||||
| 修改 `patch.jsonc` 或 GUI 片段 / Edits to `patch.jsonc` or GUI fragments | 完整 `check-gui` 检查所有 GUI 补丁的命中、词法作用域和字节码编译<br>Run the full `check-gui` location, lexical scope, and bytecode checks |
|
||||
| Native 或构建流程 / Native or copy build | Native 改动先编译 DLL,再用临时输出目录构建,核对定位和可用性<br>Build the DLL for native changes, then check locations and availability with a temporary copy build |
|
||||
| 版本适配 / New client build | 生成版本核对记录,完成适用的补丁和构建检查,再走实机验收<br>Generate a version record, run the applicable checks, then perform in-game acceptance |
|
||||
| 共享库 `packages/*`、本地服务器 `apps/server` 或 `scripts/*` | 根目录 `npm run typecheck`;若动了服务端启动逻辑或 `tuning/*.jsonc`,用临时数据目录启动一次 `apps/server/src/cli.ts` 确认数据集提取与配置校验零报错 |
|
||||
| 桌面启动器 `apps/launcher` | 启动器 `typecheck` + `electron-vite build`;若增改了界面多语言词条,确认 `en.json` 与 `zh-CN.json` 键名完全对齐 |
|
||||
| `patches/exe/`(任何 `patch.jsonc`) | `wtotools check-patches`(验证特征码唯一命中、`expect_original` 匹配,且 `asm`/`data` 编译结果与 `bytes` 逐字节一致) |
|
||||
| `patches/gui/`(任何 `patch.jsonc` 或 `.nut` 片段) | **完整** `wtotools check-gui`(调用 `sq.exe` 执行 `compilestring` 词法作用域与字节码编译检查) + 临时副本构建确认 `gui-patch-definition.ts` Schema 无未知键报错 |
|
||||
| `native/wto-net/` 或 `patches/native/` | MSVC `native\wto-net\build.ps1`(`/W4` **零警告**)+ 临时目录 `scripts/build-game-copy.ts` 确认所有原生站点全部解析就绪 |
|
||||
| 适配客户端新版本(`patches/versions/`) | `scripts/record-game-version.ts` + 上述全部适用检查 + **在隔离副本中实机登录进机库并完成 `LocalMP` 对局验收后**,方可提交 `patches/versions/<版本号>.jsonc` |
|
||||
|
||||
常用检查命令汇总(均在仓库根目录执行,将尖括号替换为你的本地路径):
|
||||
|
||||
```powershell
|
||||
# TypeScript / launcher
|
||||
# 1. TypeScript 类型与语法剥离约束检查(校验 .ts 后缀、import type、erasableSyntaxOnly 等)
|
||||
npm run typecheck
|
||||
npm run typecheck --workspace "@wto/launcher"
|
||||
npm run build --workspace "@wto/launcher"
|
||||
|
||||
# Patch tool setup
|
||||
python -m venv .venv
|
||||
.\.venv\Scripts\python.exe -m pip install -e ./tools
|
||||
# 2. EXE 与 GUI 补丁核对(输入源必须是只读原版客户端目录!)
|
||||
.\.venv\Scripts\python.exe -m wtotools.cli check-patches --exe "<原版目录>\win64\aces.exe"
|
||||
.\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "<原版目录>\gui.vromfs.bin" --sq "build\quirrel-cli\bin\Release\sq.exe"
|
||||
|
||||
# Patch verification
|
||||
.\.venv\Scripts\python.exe -m wtotools.cli check-patches --exe "<stock-client-dir>\win64\aces.exe"
|
||||
.\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "<stock-client-dir>\gui.vromfs.bin" --sq "build\quirrel-cli\bin\Release\sq.exe"
|
||||
|
||||
# Native build and copy build check
|
||||
# 3. Native DLL 编译(MSVC /W4 零警告)与完整离线副本试构建
|
||||
powershell -NoProfile -File .\native\wto-net\build.ps1
|
||||
node scripts/build-game-copy.ts --game "<stock-client-dir>" --out "<temporary-output-dir>" --data "<separate-data-dir>" --port <port>
|
||||
node scripts/build-game-copy.ts --game "<原版目录>" --out "<临时副本目录>" --data "<临时数据目录>" --port 27015
|
||||
|
||||
# Version adaptation
|
||||
node scripts/record-game-version.ts --game "<stock-client-dir>"
|
||||
# 4. 客户端版本适配记录核对
|
||||
node scripts/record-game-version.ts --game "<原版目录>"
|
||||
```
|
||||
|
||||
实际启动时,离线副本需要包含完整游戏文件,本地服务器与副本构建使用同一端口和数据目录。版本记录命令会写入 `patches/versions/`,按[补丁指南](patches.md#核对版本与提交)核对后再提交。[服务器启动命令](../README.md#构建副本并启动服务器)
|
||||
|
||||
For an actual launch, use a full offline copy and match the server's port and data directory to the copy build. The record generator writes to `patches/versions/`. Follow the [patch guide](patches.md#check-versions-and-submit) before committing a record. [Server startup command](../README.md#build-the-copy-and-start-the-server)
|
||||
|
||||
<a id="quirrel"></a>
|
||||
|
||||
## 构建 Quirrel 编译器 / Build the Quirrel compiler
|
||||
### 一次性编译 Quirrel 字节码检查器 `sq.exe`(注意 `--sq` 路径参数!)
|
||||
|
||||
GUI 检查使用 `sq.exe` 调用 `compilestring`,检查词法作用域和字节码编译。成功时会报告所有改动脚本都编译通过。以下步骤使用 Visual Studio 2022 的 x64 C++ 工具和 CMake 3.31。将实际编译器路径传给 `check-gui --sq`。[Quirrel 源码版本](https://github.com/GaijinEntertainment/quirrel/tree/19f17df9b6ee43c91ef5c635fd45970ec76c5dbe)
|
||||
|
||||
The GUI checker uses `sq.exe` and `compilestring` to check lexical scope and compile bytecode. A passing run reports successful compilation for all changed scripts. These steps use the Visual Studio 2022 x64 C++ tools and CMake 3.31. Pass the path to your compiler to `check-gui --sq`. [Quirrel source revision](https://github.com/GaijinEntertainment/quirrel/tree/19f17df9b6ee43c91ef5c635fd45970ec76c5dbe)
|
||||
`check-gui` 需要调用与《战争雷霆》客户端同代的官方 Quirrel 编译器(固定在 [Quirrel 仓库提交 `19f17df9b6ee43c91ef5c635fd45970ec76c5dbe`](https://github.com/GaijinEntertainment/quirrel/tree/19f17df9b6ee43c91ef5c635fd45970ec76c5dbe))。使用 Visual Studio 2022 C++ 工具链与 CMake 编译一次即可长期复用:
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/GaijinEntertainment/quirrel.git build/quirrel-source
|
||||
@@ -83,3 +124,168 @@ git -C build/quirrel-source checkout --detach 19f17df9b6ee43c91ef5c635fd45970ec7
|
||||
cmake -S build/quirrel-source -B build/quirrel-cli -G "Visual Studio 17 2022" -A x64
|
||||
cmake --build build/quirrel-cli --config Release --target sq
|
||||
```
|
||||
|
||||
> **关于 `--sq` 参数的重要说明**:`wtotools check-gui` 在不传 `--sq` 时的默认查找路径是 `build/quirrel-check/sq.exe`(见 `tools/src/wtotools/cli/gui_commands.py`),而上面这条 Visual Studio CMake 多配置构建命令会把可执行文件生成在 **`build\quirrel-cli\bin\Release\sq.exe`**。因此运行 `check-gui` 时请像上方命令一样显式传入 `--sq "build\quirrel-cli\bin\Release\sq.exe"`(或者手动把生成的 `sq.exe` 复制一份到 `build\quirrel-check\sq.exe`)。
|
||||
|
||||
---
|
||||
|
||||
## 4. 提交消息规范与 PR 自查清单
|
||||
|
||||
- **一笔 PR 只聚焦一个清晰目标**:不要在修某个结算 Bug 的 PR 里顺手重排无关目录或大面积格式化其他文件。
|
||||
- **全英文约定式提交(Conventional Commits)与英文注释**:
|
||||
- 提交标题格式:`type(scope): concise summary`(例如 `fix(battle): credit Ground Arcade air event kills from AI victims`、`feat(launcher): show missing optional patch features`;仓库级工程或文档改动用 `repo` 或 `docs`);
|
||||
- 若包含破坏性变更,在 `scope` 后加 `!` 并在正文末尾附上 `BREAKING CHANGE:` 说明;
|
||||
- 代码注释、补丁顶部三行说明、补丁 `title` 与 Git 提交消息正文统一使用英文;
|
||||
- `Co-authored-by` 尾注仅用于署名实际参与协作的人类开发者,不要填写 AI 模型或编程工具。
|
||||
- **发起 PR 前最后 5 项自检**:
|
||||
1. 对照 [开发规范第 4 节](development-rules.md#good-vs-bad-zh):零硬编码 RVA/结构体偏移/`_ReturnAddress()`、零手抄游戏静态数值、零越层 I/O;
|
||||
2. 核对语法与 Schema 细节:TS 相对导入全部带 `.ts` 后缀且遵守 `erasableSyntaxOnly`;补丁 JSONC 无多余未知键(特别是 `patches/gui/**/patch.jsonc` 未误写 `requires`);带尾随立即数的 `rel32` 捕获已显式填写 `"end"`;
|
||||
3. 涉及货币、研发、库存或存档改动时,确认所有修改均通过 `PlayerProfiles` / `SaveStore` **先完成原子写盘再向客户端返回响应**,且多账号目录严格隔离;
|
||||
4. 通读一遍 `git diff`,确认没有带入任何本机个人路径、原版游戏文件、解包产物、测试存档或未脱敏日志;
|
||||
5. 完整填写 [PR 模板](templates/pull-request.md),如实列出实际运行过的命令与输出结论,并把「已在隔离副本实机验收的界面步骤」与「尚待维护者实机验收的步骤」明确区分开。
|
||||
|
||||
---
|
||||
|
||||
<a id="english"></a>
|
||||
|
||||
[简体中文](#zh-cn) · English · [Back to Dev Docs](README.md#english)
|
||||
|
||||
This guide walks you through setting up a Windows x64 development environment, diagnosing bugs rapidly with auto-decoded local traffic logs, and running the required verification checks before opening a Pull Request.
|
||||
|
||||
---
|
||||
|
||||
## 1. Environment Setup
|
||||
|
||||
You need a **Windows x64** machine with:
|
||||
|
||||
1. **Node.js 24+**: Repository CLI scripts and `apps/server` execute `.ts` files directly via Node 24's native type-stripping (older Node 20/22 releases will fail on `.ts` import specifiers).
|
||||
2. **Visual Studio 2022 or Build Tools (with "Desktop development with C++" x64 tools & CMake)**: Used by `native/wto-net/build.ps1` (`cl.exe`) to build `wto_ws.dll` and once to compile the Quirrel bytecode checker `sq.exe`.
|
||||
3. **Python 3.12+**: Used for the patch verifier (`wtotools`), static disassembler (`tools/re/cli.py`), and `.clog` log decryptor.
|
||||
4. **Your own legitimate stock War Thunder installation (kept strictly read-only)**, plus a separate **offline copy folder** and **server data folder** located outside any Steam library directory.
|
||||
|
||||
After cloning the repository, bootstrap everything from the repo root:
|
||||
|
||||
```powershell
|
||||
# 1. Install npm workspace dependencies
|
||||
npm install
|
||||
|
||||
# 2. Compile the Winsock redirector & LocalMP host bridge -> build\native\wto_ws.dll
|
||||
powershell -NoProfile -File .\native\wto-net\build.ps1
|
||||
|
||||
# 3. Download the Electron runtime binary for the desktop launcher
|
||||
node node_modules/electron/install.js
|
||||
|
||||
# 4. Create the Python virtual environment and install `wtotools` in editable mode
|
||||
python -m venv .venv
|
||||
.\.venv\Scripts\python.exe -m pip install -e ./tools
|
||||
```
|
||||
|
||||
To build an offline game copy and run the local server directly from the terminal without the desktop launcher (note: pass the **read-only stock folder** to `build-game-copy.ts --game`, pass the **offline copy folder** to `cli.ts --game`, and keep `--data` and `--port` identical across both commands):
|
||||
|
||||
```powershell
|
||||
node scripts/build-game-copy.ts --game "<stock-dir>" --out "<copy-dir>" --data "<data-dir>" --port 27015
|
||||
node apps/server/src/cli.ts --game "<copy-dir>" --data "<data-dir>" --port 27015
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
<a id="debugging-en"></a>
|
||||
|
||||
## 2. Traffic Log Debugging & Diagnostic Logs
|
||||
|
||||
Never guess what payload the game client sent or why a hangar action failed—WTOffline records human-readable diagnostics across four log locations:
|
||||
|
||||
### 2.1 Local Server Traffic Logs: `<data-dir>/logs/<ISO-timestamp>/` (Check Here First!)
|
||||
|
||||
Every time `apps/server` starts, `TrafficLog` (`apps/server/src/traffic-log/traffic-log.ts`) creates a timestamped session folder under `<data-dir>/logs/` containing:
|
||||
|
||||
1. **`requests.jsonl` (Indexed Exchange Log)**
|
||||
One JSON line per HTTP request/response (`kind: "http"`), matching message (`kind: "matching"`), refused WebSocket upgrade (`kind: "websocket"`), or TCP connection open/close, numbered sequentially by `id`:
|
||||
- **Spot missing endpoints instantly**: Search `requests.jsonl` for `"unhandled":true` (or look for `[UNHANDLED]` in the server console) to immediately see any unimplemented `char` action, `yuplay2` endpoint, or `matching` RPC!
|
||||
- Each entry's `files` object points directly to its corresponding payload files inside `bodies/`.
|
||||
2. **`bodies/` Subdirectory (Auto-Decoded Readable BLK & JSON Payloads!)**
|
||||
Numbered by zero-padded sequence ID (e.g., `000042.*`):
|
||||
- `000042.req.bin` / `000042.resp.bin`: Raw wire bytes (with sign-in passwords automatically redacted);
|
||||
- **`000042.req.txt` / `000042.resp.txt`**: **Automatically unpacked and formatted readable BLK text** (covering `0x69`/zlib/zstd-framed `char` binary BLK payloads as well as multi-chunk `PBBD` streams on `cln_bulk_set_gblk`!) or UTF-8 JSON/form text—open any `.txt` file directly in your editor to inspect exact block trees and parameter types without manual decoding;
|
||||
- **`000042.matching-in.json` / `000042.matching-out.json`**: Decrypted, LZ4-decompressed inbound (`in`) and outbound (`out`) `matching` binary RPC messages.
|
||||
|
||||
### 2.2 The Other Three Diagnostic Logs
|
||||
|
||||
- **Native Hook & `LocalMP` Log: `<copy-dir>/win64/wto_ws.log`**
|
||||
Rewritten on every client launch by `wto_ws.dll`. Logs the active local port, every locally answered hostname and redirected/refused socket, whether `wto_ws.cfg` matched the running `aces.exe` PE `TimeDateStamp` / `SizeOfImage`, and **which of the 11 `local_mp_*` modules installed vs. were skipped** (naming the exact missing `wto_ws.cfg` key when skipped), plus live battle referee events.
|
||||
- **Dagor Client Log: `<copy-dir>/.game_logs/*.clog`**
|
||||
Records Quirrel script compilation/runtime errors, exact call stacks behind `"Loading..."` login hangs, mission errors, and missing assets. Because `.clog` files are XOR-encrypted binary logs, decrypt them to plain text with `tools/re/cli.py`:
|
||||
```powershell
|
||||
.\.venv\Scripts\python.exe tools\re\cli.py decrypt-clog "<copy-dir>\.game_logs\<latest>.clog" --out "<temp-dir>\game.clog.txt"
|
||||
```
|
||||
- **Desktop Launcher Log: `launcher.log`**
|
||||
Accessible from Launcher **Settings -> Diagnostics -> Open log folder**, covering copy builds, patch-pack checks, server process lifecycle, and updater activity.
|
||||
|
||||
---
|
||||
|
||||
<a id="checks-en"></a>
|
||||
|
||||
## 3. Required Checks Before Submitting
|
||||
|
||||
WTOffline **does not require or encourage large mock unit test suites**. Instead, run the real compiler, binary-patch, and Quirrel bytecode verifiers matching the files you touched, followed by live acceptance in an isolated game copy:
|
||||
|
||||
| What you changed | Required checks before opening a PR |
|
||||
| --- | --- |
|
||||
| `packages/*`, `apps/server`, or `scripts/*` | Root `npm run typecheck`; if you touched server startup or `tuning/*.jsonc`, boot `apps/server/src/cli.ts` against a temporary data folder to confirm clean dataset extraction and tuning validation |
|
||||
| `apps/launcher` | Launcher `typecheck` + `electron-vite build`; if you edited UI strings, verify `en.json` and `zh-CN.json` locale key parity |
|
||||
| `patches/exe/` (any `patch.jsonc`) | `wtotools check-patches` (verifies unique signature hits, `expect_original` bytes, and exact byte-for-byte agreement between `asm`/`data` and `bytes`) |
|
||||
| `patches/gui/` (any `patch.jsonc` or `.nut` fragment) | **Full** `wtotools check-gui` using `sq.exe` `compilestring` (required) + a temporary copy build to confirm zero unknown schema keys in `gui-patch-definition.ts` |
|
||||
| `native/wto-net/` or `patches/native/` | MSVC `native\wto-net\build.ps1` (`/W4`, **zero warnings**) + temporary `scripts/build-game-copy.ts` run confirming every native module resolves cleanly |
|
||||
| Adapting a new client build (`patches/versions/`) | `scripts/record-game-version.ts` + all applicable checks above + **live in-game verification in an isolated copy (hangar login + `LocalMP` battle)** before committing `patches/versions/<version>.jsonc` |
|
||||
|
||||
Complete command reference (run from the repository root, substituting bracketed paths):
|
||||
|
||||
```powershell
|
||||
# 1. TypeScript typecheck & Node 24 erasable-syntax checks (.ts extensions, import type, etc.)
|
||||
npm run typecheck
|
||||
npm run typecheck --workspace "@wto/launcher"
|
||||
npm run build --workspace "@wto/launcher"
|
||||
|
||||
# 2. EXE & GUI patch verification (always point at your READ-ONLY stock folder!)
|
||||
.\.venv\Scripts\python.exe -m wtotools.cli check-patches --exe "<stock-dir>\win64\aces.exe"
|
||||
.\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "<stock-dir>\gui.vromfs.bin" --sq "build\quirrel-cli\bin\Release\sq.exe"
|
||||
|
||||
# 3. Native DLL build (MSVC /W4 zero warnings) & temporary offline copy build
|
||||
powershell -NoProfile -File .\native\wto-net\build.ps1
|
||||
node scripts/build-game-copy.ts --game "<stock-dir>" --out "<temp-copy-dir>" --data "<temp-data-dir>" --port 27015
|
||||
|
||||
# 4. Client build compatibility record
|
||||
node scripts/record-game-version.ts --game "<stock-dir>"
|
||||
```
|
||||
|
||||
<a id="quirrel-en"></a>
|
||||
|
||||
### One-Time Build of the Quirrel Bytecode Compiler `sq.exe` (Note the `--sq` Flag!)
|
||||
|
||||
`check-gui` requires the official Quirrel compiler pinned to the revision matching War Thunder's client VM ([Quirrel commit `19f17df9b6ee43c91ef5c635fd45970ec76c5dbe`](https://github.com/GaijinEntertainment/quirrel/tree/19f17df9b6ee43c91ef5c635fd45970ec76c5dbe)). Build it once with Visual Studio 2022 C++ tools and CMake:
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/GaijinEntertainment/quirrel.git build/quirrel-source
|
||||
git -C build/quirrel-source checkout --detach 19f17df9b6ee43c91ef5c635fd45970ec76c5dbe
|
||||
cmake -S build/quirrel-source -B build/quirrel-cli -G "Visual Studio 17 2022" -A x64
|
||||
cmake --build build/quirrel-cli --config Release --target sq
|
||||
```
|
||||
|
||||
> **Important note on `--sq`**: `wtotools check-gui` defaults `--sq` to `build/quirrel-check/sq.exe` (`tools/src/wtotools/cli/gui_commands.py`), whereas the multi-config Visual Studio CMake build above outputs **`build\quirrel-cli\bin\Release\sq.exe`**. Always pass `--sq "build\quirrel-cli\bin\Release\sq.exe"` explicitly as shown in the command block above (or copy `sq.exe` to `build\quirrel-check\sq.exe`).
|
||||
|
||||
---
|
||||
|
||||
## 4. Commit Conventions & Pre-PR Checklist
|
||||
|
||||
- **One focused goal per PR**: Avoid mixing unrelated refactors or repo-wide formatting into a bugfix or feature PR.
|
||||
- **English Conventional Commits & English code comments**:
|
||||
- Format commit titles as `type(scope): concise summary` (e.g., `fix(battle): credit Ground Arcade air event kills from AI victims`, `feat(launcher): show missing optional patch features`; use `repo` or `docs` for repository-level or documentation changes);
|
||||
- Mark breaking changes with `!` after the scope and a `BREAKING CHANGE:` footer;
|
||||
- Write all code comments, 3-line patch header comments, patch `title` fields, and commit bodies in English;
|
||||
- Reserve `Co-authored-by` trailers strictly for human collaborators—never list AI models or coding tools.
|
||||
- **Final 5-point self-check before opening a PR**:
|
||||
1. Check against [Development Rules — Section 4](development-rules.md#good-vs-bad-en): zero hardcoded RVAs, struct offsets, or `_ReturnAddress()` checks; zero hardcoded stock game numbers; zero cross-layer I/O;
|
||||
2. Verify syntax & schema discipline: explicit `.ts` extensions on relative imports, `import type` for types, no `enum`/`namespace`/parameter properties; strict patch JSONC keys (no `requires` in `patches/gui/**/patch.jsonc`, explicit `"end"` on `rel32` captures with trailing immediates);
|
||||
3. For currency, research, inventory, or profile mutations, verify changes persist atomically via `PlayerProfiles` / `SaveStore` **before** replying to the client, with strict per-account isolation;
|
||||
4. Review `git diff` to ensure zero personal machine paths, copyrighted game files, extracted stock scripts, personal saves, or unredacted logs slipped in;
|
||||
5. Fill out the [PR template](templates/pull-request.md) completely, recording exact commands run and clearly separating observed in-game checks from pending in-game acceptance steps.
|
||||
+570
-58
@@ -1,87 +1,599 @@
|
||||
# Development rules
|
||||
# 开发理念、架构分层与工程规范 / Development Rules
|
||||
|
||||
<a id="zh-cn"></a>
|
||||
|
||||
简体中文 · [English](#english) · [返回 Dev Docs](README.md#zh-cn)
|
||||
|
||||
## 实现位置
|
||||
这篇文档不只罗列「能做什么、不能做什么」,而是先把 **WTOffline 为什么这样分层、客户端与本地服务器各自承担什么角色** 彻底讲透。只要底层运行模型在脑子里立住了,项目里的每一条工程规范都是自然而然的推论。
|
||||
|
||||
- 开工前明确玩家会看到什么变化和准备改的范围。涉及玩法或架构取舍,先和维护者对齐。先查目标版本的游戏文件、原版界面脚本和官方公开源码,记录版本、文件或函数以及支持结论的事实。把推测标为推测。需要读写游戏格式时,先评估已有工具的许可、维护情况和版本适用性。[DagorEngine 源码](https://github.com/GaijinEntertainment/DagorEngine)
|
||||
- 客户端沿用原有流程,由本地服务器按协议回应。先看服务器或游戏自带配置能否解决。确实需要改客户端时,注明对应功能、原有行为和更小的改动为什么不够。界面脚本进 `patches/gui/`,数据包配置改动归 `packages/patcher/`,其他补丁按[补丁指南](patches.md#zh-cn)登记。
|
||||
- 服务端按领域分模块。协议层处理请求和应答格式,规则层处理游戏规则,存档层负责持久化,数据层只提取游戏文件中的事实。修改档案的动作写盘成功后再回复。无法识别账号、缺必填参数或余额不足时,明确拒绝。初期开发用新存档验收,无需增加旧存档迁移。
|
||||
- 应用通过参数把配置和路径交给共享库。按职责拆文件、函数和类,复用现有逻辑和常量。文件接近 300 行或函数接近 50 行就检查是否该拆分。商城与交易所的 HTML、CSS、JS 使用独立文件并复用[网页模块](../apps/server/src/web-ui)。
|
||||
---
|
||||
|
||||
## 数值和数据来源
|
||||
<a id="architecture-zh"></a>
|
||||
|
||||
| 数值类别 | 做法 |
|
||||
| --- | --- |
|
||||
| 协议规定的值,如包头长度和消息类型 | 保留在代码中,注明版本和出处。 |
|
||||
| 游戏文件已有的值,如车价、改装件价格 | 启动时从玩家的游戏文件读取。缺少必需值时报告具体字段并停止,避免悄悄代入编造的默认值。 |
|
||||
| 离线版决定的值,如奖励、价格、权重、倍率、等级门槛、数量上限 | 写进对应模块的 `tuning/`。服务端默认值位于 [apps/server/tuning](../apps/server/tuning),启动时校验类型、范围和必填字段。 |
|
||||
## 1. 先建立全景图:WTOffline 到底是怎么跑起来的?
|
||||
|
||||
经济数值先查游戏数据和官方资料。商城以官方美元价作为 GJN 标价依据。官方资料缺项时,沿用已有出处的参考数据,或说明它属于离线设计。配置注释或 PR 记录出处、单位和取值规则,具体数值以配置为准。展示给玩家的数字也从同一数据来源生成。
|
||||
WTOffline 采用与《逃离塔科夫》单机版(SPT)一脉相承的本地模拟架构:**不推翻重写游戏引擎,而是让原版客户端相信自己正连着完整的线上后端,把它的全部网络请求收口到本机 `127.0.0.1` 的模拟服务器,并仅在进程内补齐客户端被裁剪掉的局内主机裁判函数。**
|
||||
|
||||
本地服务器每次启动加载数值配置。数据目录下的同名 `tuning/*.jsonc` 可逐键覆盖默认对象。数字、字符串和列表整体替换。
|
||||
```text
|
||||
玩家在启动器点击「启动游戏」
|
||||
│
|
||||
├─ 1. 桌面启动器(apps/launcher)调用构建引擎(packages/patcher)
|
||||
│ └─ 以「严格只读」方式读取玩家的官方原版客户端目录,向独立离线副本目录生成:
|
||||
│ ├─ char.vromfs.bin / aces.vromfs.bin:改写 network.blk 服务地址 -> 127.0.0.1:<端口>,注入本地商店礼包 GUID
|
||||
│ ├─ gui.vromfs.bin:应用 patches/gui/(仅修补本地服务器无法覆盖的极少数界面脚本点)
|
||||
│ ├─ win64/aces.exe:应用 patches/exe/(跳过包验签、隔离存档与注册表、禁用反作弊、把导入表 WS2_32.dll 改为 wto_ws.dll)
|
||||
│ └─ win64/wto_ws.dll + win64/wto_ws.cfg:按 patches/native/*.jsonc 动态解析函数 RVA 与结构体偏移写入配置文件
|
||||
│
|
||||
├─ 2. 本地模拟服务器(apps/server,仅绑定 127.0.0.1:<端口> 单端口监听)
|
||||
│ ├─ 启动阶段:通过 DatasetCache 从游戏归档包提取静态事实(科技树、价格、改装件、任务、多语言词条),加载 tuning/*.jsonc
|
||||
│ └─ 运行阶段:port-listener.ts 按每个 TCP 连接的首批字节自动分流多协议:
|
||||
│ ├─ 首字节 0x01 ──▶ MatchingService(9 字节头 + LZ4 压缩帧,握手后流加密)
|
||||
│ ├─ 明文 PASS/NICK/USER/CAP/PING ──▶ IrcServer(机库与小队聊天)
|
||||
│ ├─ 首字节 0x16(TLS ClientHello) ──▶ 本地证书 TLSSocket 解密后再二次分流至 IrcServer 或 HTTP
|
||||
│ └─ 其余全部明文连接 ──▶ HTTP 服务器(yuplay2 登录、char 二进制 BLK 档案、inventory 签名 JSON、内嵌网页商店)
|
||||
│ (注:HTTP WebSocket upgrade 请求会被记录日志后直接 socket.destroy() 拒绝)
|
||||
│
|
||||
└─ 3. 隔离离线副本(win64/aces.exe + win64/wto_ws.dll)
|
||||
├─ 进程加载时(DllMain):wto_ws.dll 通过 wto_ws.def 把全部 Winsock 导出(含序号导出)转发至系统 ws2_32.dll,
|
||||
│ 同时用 MinHook 挂钩系统 ws2_32.dll 的域名解析与连接函数;若任一网络钩子安装失败,DllMain 直接返回 FALSE 终止启动!
|
||||
├─ 机库阶段:登录、拉取档案、科技树研发、买车买改装、乘员训练、开箱、逛商店,全部走原版协议由 apps/server 处理并原子落盘
|
||||
└─ 对局阶段:MatchingService 下发任务参数使客户端以 LocalMP 本地主机开局;
|
||||
wto_ws.dll 校验 PE 指纹匹配后启用 local_mp_* 模块,在进程内补齐选车出生、AI 刷出、击杀助攻占点计分、
|
||||
陆战街机空中支援、核弹判胜与受损提示过滤;战后由客户端经 cln_update 回传 apps/server 结算银狮/研发点并落盘
|
||||
```
|
||||
|
||||
## 常见实现陷阱与工程红线(含 AI 辅助开发对照)
|
||||
### 1.1 单端口多协议分流细节(`apps/server/src/transport/`)
|
||||
|
||||
欢迎借助 AI 助手阅读反汇编、排查日志和定位根因。实际提交改动时,请按下列正反对照逐条收口实现,确保补丁在后续小版本更新与长期维护中依然健壮:
|
||||
客户端内部既有读取 `config/network.blk` 的模块,也有把域名、端口甚至 `https://` 写死在二进制常量里的模块。为了不占用一串本地端口,本地服务器在 `apps/server/src/transport/port-listener.ts` 中用**单个 TCP 监听端口**接住所有流量,在 `socket.once('data', ...)` 窥探首批字节后原样退回缓冲区(`socket.unshift`)并精准派发:
|
||||
|
||||
| 维度 | 推荐做法 | 避免做法 |
|
||||
| --- | --- | --- |
|
||||
| 定位与偏移 | exe 补丁与 native 模块一律通过 `patches/exe/`、`patches/native/` 的 `signature`、`string_ref`、`within` 动态捕获地址、跳转目标和结构体偏移 | 在 C/TS 代码中硬编码 RVA、结构体偏移、函数地址或 `_ReturnAddress` |
|
||||
| 改动分层 | 先核对服务端协议、任务根字段与原版配置能否解决;协议层、规则层、存档层、数据层职责分离,修改档案先写盘再回复 | 用客户端硬补丁绕开本该由本地服务器解决的问题,或在协议处理器里堆砌业务规则、先回成功再写盘 |
|
||||
| 静态数据与数值 | 游戏文件已有的载具、任务、奖励、出生点等一律通过缓存 `datasets/` 从玩家原版文件读取;离线自定参数进 `apps/server/tuning/*.jsonc` 并做启动校验 | 在代码里手抄原版数值、写死兜底坐标或散落魔法数字 |
|
||||
| 复用与粒度 | 复用 `local_mp_core` 等公共站点与现有模块;共享库 `packages/*` 通过参数收配置;文件接近 300 行、函数接近 50 行时拆分职责 | 重复挂钩同一原生函数、让 `packages/*` 反向读取 `apps/*`、把多类职责塞进单个大文件或大函数 |
|
||||
| 编译器与运行环境 | Native C 代码严格兼容 MSVC(`native/wto-net/build.ps1` 0 警告);TS 代码兼容 Node 24 原生类型剥离(`erasableSyntaxOnly`) | 引入 GCC 专属扩展或未在 MSVC 编译核对的 C 语法 |
|
||||
| 校验与验收 | 按改动执行对应的 `typecheck`、`check-patches`、完整 `check-gui`(Quirrel 字节码检查)与临时副本构建,如实记录未实机项 | 只靠单测或静态推演就宣称已验证通过;跳过 `check-gui`;在未实机验收前提交 `patches/versions/*.jsonc` |
|
||||
| 范围与协作规范 | 一笔 PR 专注单一目标,使用英文约定式提交与英文代码注释,只保留实际人类协作者的 `Co-authored-by` | 夹带无关格式化/重构、写入个人本机路径或把 AI 助手署名为 `Co-authored-by` |
|
||||
1. **匹配二进制协议(首字节 `0x01`)**:匹配 `startsMatchingPacket(first)` 后交由 `MatchingService` 处理(9 字节小端包头 + LZ4 数据块,见 `matching/matching-frame.ts`);
|
||||
2. **明文 IRC 握手**:首行以 `PASS`、`NICK`、`USER`、`CAP` 或 `PING` 开头时交由 `IrcServer` 处理;
|
||||
3. **TLS 加密连接(首字节 `0x16`)**:使用本地动态生成的自签名证书建立 `TLSSocket` 解密,再窥探解密后的首包字节——若是 TLS 承载的 IRC 握手则交由 `IrcServer`,否则派发给 HTTP 服务器;
|
||||
4. **常规 HTTP 连接**:其余连接直接进入 `http-listener.ts` 的 `createHttpServer`,由 `Router` 按原始目标域名(`originalHost`)和路径分发给 `login`、`char`、`inventory`、`store`、`downloadable-content` 等服务。注意:**WTOffline 不使用 WebSocket**——客户端偶然发起的 HTTP `upgrade` 请求会在 `http-listener.ts` 中记入流量日志(`WebSocket ... (refused)`)并立即调用 `socket.destroy()` 断开。
|
||||
|
||||
## 本地开发与材料
|
||||
### 1.2 `wto_ws.dll` 是如何在零外联风险下接管网络的?
|
||||
|
||||
- 游戏只在专用副本和隔离环境里启动。启动前验证断网限制、本地服务、Steam 和账号身份,以及文件、注册表、机器标识、反作弊和崩溃上报的隔离。需要观察启动行为时,在一次性环境里核对前后变化。原版来源只读,通过离线副本启动并使用本地账号。
|
||||
- 商城和交易所通过游戏内置浏览器访问本地服务。改动时核对该客户端内置浏览器支持的语法,沿用游戏语言和游戏文件中的本地化文字。包括浏览器子进程在内都要检查网络和缓存位置。
|
||||
- 提交材料使用自己的代码和最小改动片段。游戏文件、解包产物和玩家数据留在本机。PR 使用可公开复核的出处和已清理的日志节选。
|
||||
在 `patches/exe/online/network-hook-library/patch.jsonc` 中,补丁将 `aces.exe` 只读数据段(`.rdata`)导入描述符引用的字符串 `"WS2_32.dll\0"`(`57 53 32 5f 33 32 2e 64 6c 6c 00`,共 **11 字节**)原位替换为等长的 `"wto_ws.dll\0"`(`77 74 6f 5f 77 73 2e 64 6c 6c 00`,同样 **11 字节**):
|
||||
|
||||
- Windows 加载器启动 `aces.exe` 时会自动加载同目录下的 `win64/wto_ws.dll`,由 `native/wto-net/src/wto_ws.def` 将客户端导入的全部 Winsock API(包含 31 个按 `@序号` 导入的函数)无缝转发给系统 `ws2_32.dll`;
|
||||
- 在 `native/wto-net/src/dll_main.c` 的 `DllMain(DLL_PROCESS_ATTACH)` 中,DLL 读取同目录 `wto_ws.cfg`,通过 MinHook 直接挂钩系统 `ws2_32.dll` 本身的域名解析与连接/数据报函数(这样进程内**所有模块**的网络调用都会经过重定向,而不只是主程序);
|
||||
- **安全熔断**:如果 `MH_Initialize`、`install_resolver_hooks`、`install_connection_hooks` 或 `MH_ApplyQueued` 中任何一步失败,`DllMain` 会记录日志并直接返回 `FALSE`,让 Windows 加载器中止启动游戏进程,避免游戏在未挂钩状态下连接外网。
|
||||
|
||||
### 1.3 基本设计原则
|
||||
|
||||
> **遇到功能缺失或 Bug 时,先评估能否在 `apps/server` 或通过下发原版配置字段解决。**
|
||||
> 能通过修正服务端协议响应、补齐下发给客户端的任务 BLK 字段、或读取原版静态配置解决的问题,优先在服务端解决,不新增 `.nut` 界面脚本或 `aces.exe` / `wto_ws.dll` 客户端补丁。客户端补丁留给原版客户端确实缺少对应通路的场景——因为游戏每次小版本更新都会重排二进制代码,而服务端协议与配置字段跨版本稳定得多。
|
||||
|
||||
---
|
||||
|
||||
<a id="2-代码地图与分层边界"></a>
|
||||
<a id="workspace-rule-zh"></a>
|
||||
|
||||
## 2. 仓库依赖约定与 `apps/server` 真实代码地图
|
||||
|
||||
### 2.1 仓库级单向依赖约定
|
||||
|
||||
```text
|
||||
apps/launcher ──┐
|
||||
├──▶ packages/* (@wto/blk · @wto/vromfs · @wto/jsonc · @wto/exepatch · @wto/patcher · @wto/mods)
|
||||
apps/server ──┘
|
||||
```
|
||||
|
||||
- **依赖方向单向朝下**:应用层 `apps/*` 可以导入共享包 `packages/*`(开发脚本 `scripts/*` 可组合两者),`packages/*` 不应反向导入、引用或硬编码读取 `apps/*` 下的代码或配置文件。
|
||||
- 当共享包需要补丁集目录、数据目录、端口或礼包列表时,一律由上层调用方通过函数参数显式传入。
|
||||
|
||||
<a id="server-layers-zh"></a>
|
||||
|
||||
### 2.2 本地服务器 `apps/server/src/` 四层目录全景图
|
||||
|
||||
注意:**`apps/server/src/` 下并没有一个笼统的 `rules/` 文件夹**——业务规则是按游戏业务领域拆分成独立目录的。动手写代码前请对照下面这张真实目录表放对位置:
|
||||
|
||||
| 职责分层 | `apps/server/src/` 下的真实子目录 | 这一层负责什么 | 应避免放在这一层的内容 |
|
||||
| --- | --- | --- | --- |
|
||||
| **1. 传输与协议层**(Transport & Protocol) | `transport/`(单端口分流、HTTP 路由、TLS 证书)、`traffic-log/`(流量落盘)、`login/`(`yuplay2` 登录与会话凭据)、`char/`(含 `char-service.ts`、`pbbd-stream.ts`、`char/actions/*-actions.ts` 与路由总表 `char/actions/action-table.ts`)、`matching/`(LZ4 帧、流加密与排队 RPC)、`inventory/`(外部物品库与 RSA 内容签名)、`store/`(礼包与激活码路由)、`chat/`(IRC 服务端)、`cloud-settings/`、`downloadable-content/`、`web-ui/`(内嵌商店/市场页面渲染)、`mods/`(服务端模组运行时) | 解码线上传输格式(表单、JSON、压缩标记二进制 BLK、`PBBD` 流、LZ4 帧),提取并校验请求参数,调用对应领域规则,再把结果编码回客户端期待的原版响应格式 | 避免在 `*-actions.ts` 里堆砌几百行扣钱、算研发点或改档案树的业务逻辑;不要绕过 `PlayerProfiles` / `SaveStore` 直接读写磁盘文件 |
|
||||
| **2. 领域规则层**(Domain Rules) | `battle/`(开局配置与战后经济结算)、`research/`(科技树状态、选定研发、自由研发点兑换)、`modifications/`(改装件、弹链、备用载具、自定义挂载)、`crew/`(乘员组槽位与技能加点)、`items/`(加成卡、赌注、折扣券)、`repair/`(战损折算与免费修车时间)、`clans/`(联队管理与联队载具研发)、`decor/`(涂装、贴花、3D 挂件)、`unlocks/`(成就、头衔、阶段解锁)、`player-card/`(头像、资料卡展柜)、`training/`(新手教程首通奖励)、`game-modes/` | **纯业务逻辑**:接收内存中的档案 `BlkBlock`、已加载的静态数据集与可调参数,校验前置条件,计算并更新档案状态,返回明确的成功或拒绝错误码(如 `RuleOutcome`) | **零网络、零磁盘 I/O**:不导入 `node:http`、`node:net` 或 `node:fs`,也不要感知外层是 HTTP 还是匹配长连接 |
|
||||
| **3. 档案与持久化层**(Profile & Persistence) | `profile/`(`player-profiles.ts` 及按领域拆分的 `profile-*.ts` 档案节点读写器、派生状态刷新器)、`saves/`(`save-store.ts` 账号存档读写、`save-upgrades.ts` 版本演进)、`accounts/`(本地多账号密码与隔离)、`storage/`(`atomic-file.ts` 原子落盘) | 封装档案 BLK 树的底层字段读写,管理多账号目录隔离(`<data>/saves/<userId>/`),维护存档 `formatVersion`,并通过临时文件 + `fsync` + 原子重命名保证断电不坏档 | 不掺杂具体购买价格或研发公式;**任何修改档案的动作必须在磁盘原子写入完成后才能向客户端返回成功响应** |
|
||||
| **4. 静态数据集与可调配置层**(Datasets & Tuning) | `game-data/`(`game-files.ts`、`game-pack.ts`、`datasets/*.ts`、`datasets/dataset-cache.ts`)、仓库默认配置 `apps/server/tuning/*.jsonc` + 加载校验器 `src/tuning/`(`tuning-loader.ts`、`tuning-reader.ts`、`limits-tuning.ts`、`launcher-tuning.ts`)+ 各领域 `<领域>/*-tuning.ts` | 启动时从玩家原版 `.vromfs.bin` 提取静态事实并按包时间戳 + 内部文件 SHA-1 缓存到 `<data>/cache/datasets/`;按「仓库默认 → 已启用模组 → 玩家 `<data>/tuning/` 覆盖」三层合并 JSONC 并做严格类型与范围校验 | 不要凭空编造原版数据;必填字段缺失时应明确报错停止启动,避免用隐式假默认值掩盖问题 |
|
||||
|
||||
**模块粒度与复用准则**:
|
||||
- 当单个源文件接近 **300 行** 或单个函数接近 **50 行** 时,主动检查是否把协议拆包、档案树遍历和业务公式塞进了同一个文件,及时按上表拆开;
|
||||
- 动手前先搜现有公共基础设施(如 `char/actions/rule-answer.ts`、`profile/profile-*.ts`、`modifications/equipment-catalogue.ts`、`web-ui/` 公共组件、`native` 侧的 `local_mp_core`),尽量复用而不是重复实现。
|
||||
|
||||
---
|
||||
|
||||
<a id="walkthrough-zh"></a>
|
||||
|
||||
### 2.3 跟着真实代码走一遍:`cln_set_researchable` 是怎么穿透四层的?
|
||||
|
||||
光看分层表还不够直观。下面我们顺着玩家在科技树点击「研发此载具」时触发的真实动作 **`cln_set_researchable`**,逐文件看一遍标准请求流(你在写任何新 `char` 动作时直接照这个模板写即可):
|
||||
|
||||
1. **客户端发包 → 协议入口解码(`apps/server/src/char/char-service.ts`)**
|
||||
客户端向 `char-*.warthunder.com` 发送 HTTP POST,请求头带 `action: cln_set_researchable` 与 `uidhint: <userId>`,请求体是带压缩标记的二进制 BLK(包含 `unit:t = "us_m4a1_1942_sherman"` 与 `type:i = 0`)。`CharService.#handleCore` 调用 `decodeRequestPayload(request.body)`(`char/char-payload.ts`)把二进制负载解码为 `BlkBlock`(同时生成可读文本供流量日志记录),然后从 `char/actions/action-table.ts` 注册表里查出对应的处理器 `setResearchable`。
|
||||
2. **协议动作适配与参数提取(`apps/server/src/char/actions/research-actions.ts`)**
|
||||
`setResearchable` 本身只有十几行:它使用公共包装器 `ruleAction`(`char/actions/rule-answer.ts`),通过 `stringParam(payload, 'unit')` 和 `intParam(payload, 'type')`(`char/actions/payload-params.ts`)做基础类型提取。如果缺字段就返回 `undefined`(由 `ruleAction` 统一回 `!ERROR:BAD_PARAMS`);参数齐全则返回一个闭包:
|
||||
`(profile) => chooseResearchTarget(profile, rules, vehicle, type)`。
|
||||
3. **加载档案与执行纯领域规则(`apps/server/src/research/research-progress.ts`)**
|
||||
`ruleAction` 校验完账号后调用 `profiles.updateWhen(account.userId, ...)`(`profile/player-profiles.ts`),由 `SaveStore.loadProfile` 从 `<data>/saves/<userId>/profile.blk` 读出当前档案并交给纯规则函数 `chooseResearchTarget`:
|
||||
- 先从启动期提取好的科技树数据集 `rules.techTree.vehicle(vehicleName)` 查找该载具并核对 `typeId`;
|
||||
- 调用 `currentStatus(profile, rules, vehicleName)` 确认该载具在玩家当前档案下确实处于 `VehicleStatus.CAN_RESEARCH` 状态;若尚未解锁前置车或已拥有,则返回 `refused('NOT_AVAILABLE')`(`{ ok: false, refusal: 'NOT_AVAILABLE' }`),`updateWhen` 看到 `false` **不触碰磁盘**,`ruleAction` 向客户端回复纯文本 `!ERROR:NOT_AVAILABLE`;
|
||||
- 校验通过后,调用 `profile/profile-research-targets.ts` 的访问器写入新研发目标、清空刚完成研发弹窗标记,返回 `ACCEPTED`(`{ ok: true }`)。
|
||||
4. **先原子落盘,再回包给客户端(`profile/player-profiles.ts` → `saves/save-store.ts` → `storage/atomic-file.ts`)**
|
||||
`updateWhen` 收到 `true` 后,先运行 `#refresh(profile, userId)` 同步档案内的派生状态(解锁阶段、头衔、联队同步等),随即调用 `SaveStore.saveProfile(userId, profile)`。`saveProfile` 使用 `writeFileAtomic` 先在同目录写出临时文件 `profile.blk.<pid>.<rand>.tmp`、调用 `fsyncSync(fd)` 刷入物理磁盘、再原位 `renameSync` 覆盖目标文件并更新 `save.json`。**只有在磁盘写入彻底成功后**,`ruleAction` 才调用 `clientProfile(profile, account)` 组装客户端视图,由 `toResponse`(`char/char-answers.ts`)加上 `0x69` 标记编码成二进制 BLK 返回 HTTP 200。
|
||||
|
||||
### 2.4 存档结构演进规则(`saves/save-upgrades.ts`)
|
||||
|
||||
- **领域规则只面向「当前最新版」存档结构编程**:避免在 `research/`、`modifications/`、`battle/` 等业务代码里散落兼容旧测试字段的 `if/else` 分支;
|
||||
- 当正式版本演进确实改变了 `profile.blk` 的存储结构时,统一在档案升级链(`saves/save-upgrades.ts` 的 `SaveUpgrades`)中追加一步升级函数(`steps[n]` 负责把 `formatVersion` 从 `n + 1` 原地升级到 `n + 2`)。`SaveStore.loadProfile` 打开旧版存档时会按顺序跑完升级步骤并立即以最新 `formatVersion` 原子回写磁盘。仍在同一分支开发调试、尚未发布的草稿改动无需写迁移代码。
|
||||
|
||||
---
|
||||
|
||||
<a id="values-zh"></a>
|
||||
|
||||
## 3. 三类数值放哪里(保持边界清晰)
|
||||
|
||||
在代码审查中,最常见的返工原因就是把不同性质的数字混写在了业务逻辑里。写下任何一个字面量前,先问它属于下面哪一类:
|
||||
|
||||
| 数值类别 | 典型例子 | 唯一正确的存放位置 | 常见错误示范 |
|
||||
| --- | --- | --- | --- |
|
||||
| **① 协议与引擎固定常量** | 匹配/局内消息号(如 `LMP_MPI_MSG_UNIT_RESPAWN = 0xf030u`)、`PBBD` 魔数(`0x44424250`)、Dagor 容器布局(`dag::Vector` 偏移、`FastNameMap` 移位)、状态位掩码 | 定义为具名常量放在对应协议或头文件中,并用**英文注释写明一手来源**(目标客户端版本号 + RVA,或 [DagorEngine 公开源码](https://github.com/GaijinEntertainment/DagorEngine) 文件路径) | 在函数中间裸写 `if (msgId == 61488)` 或 `if (status == 64)` 且没有任何来源注释 |
|
||||
| **② 原版游戏包里本来就有的静态事实** | 载具购买银狮/金鹰价、研发点需求、分房权重、维修费、改装件树、多人地图列表、新手教程首通奖励、连杀支援出生高度/距离/速度 | 在 `apps/server/src/game-data/datasets/` 编写 `Dataset<T>`,服务启动时经 `DatasetCache` 从玩家原版 `.vromfs.bin` 动态读取并缓存在 `<data>/cache/datasets/<id>.json`;若原版文件缺失必填块/字段,直接 `throw new Error(...)` 明确报错停止 | 把某一个客户端版本的载具表、奖励金额或出生坐标手抄成 TS/C 常量表;或者读不到原版字段时悄悄 `?? 10000` 填个假默认值蒙混过关 |
|
||||
| **③ 离线版自己决定的可调参数** | 银狮/研发点收益倍率、新账号初始货币、本地商店礼包定价、补给箱掉落权重、AI 机器人重生次数、单次请求数量上限、玩法开关 | 仓库默认值放进 `apps/server/tuning/<领域>.jsonc`,在对应 `<领域>/*-tuning.ts` 用 `TuningReader` 做启动期类型与上下界校验;运行期由 `tuning-loader.ts` 自动按「仓库默认 → 已启用模组覆盖 → 玩家 `<data>/tuning/<领域>.jsonc` 覆盖」合并 | 把 `const RP_MULTIPLIER = 3.0` 或硬上限直接写死在结算函数内部,导致玩家和模组作者无法通过 `tuning/` 调参 |
|
||||
|
||||
---
|
||||
|
||||
<a id="4-好代码-vs-坏代码4-组最常见的真实对比"></a>
|
||||
<a id="good-vs-bad-zh"></a>
|
||||
|
||||
## 4. 好代码 vs 坏代码:4 组来自真实仓库的代码对比
|
||||
|
||||
下面所有正面代码全部取自仓库内的真实文件与真实符号,提交前请逐条对照自查。
|
||||
|
||||
### 对比 1:Native C 钩子 —— `g_lmp` 动态捕获与外层作用域标志 vs 硬编码偏移与 `_ReturnAddress()`
|
||||
|
||||
客户端只要发一个小版本更新(例如 `2.61.0.37` → `2.61.0.58`),函数 RVA 会整体漂移,C++ 类成员偏移也会随着字段增删而移动(例如 `gameplay` 里的连杀规则表偏移就会跨版本变化)。
|
||||
|
||||
```c
|
||||
// ❌ 坏写法:硬编码 RVA、硬编码结构体偏移 +0x3798、用 _ReturnAddress() 猜调用栈
|
||||
// 只要游戏发一个小补丁,轻则功能静默失效,重则当场非法内存访问崩溃!
|
||||
static void __fastcall bad_hook_send_unit_respawn(uint8_t *unit, const void *spawn)
|
||||
{
|
||||
uintptr_t base = (uintptr_t)GetModuleHandleW(NULL);
|
||||
if ((uintptr_t)_ReturnAddress() != base + 0x1281280)
|
||||
return;
|
||||
const uint8_t *gameplay = *(const uint8_t *const *)(base + 0x7bad2f0);
|
||||
const uint8_t *rules = *(const uint8_t *const *)(gameplay + 0x3798);
|
||||
/* ... */
|
||||
}
|
||||
```
|
||||
|
||||
```c
|
||||
// ✅ 好写法(真实代码:native/wto-net/src/local_mp_air_events.c + local_mp_offsets.h + local_mp_values.h):
|
||||
// 1. 所有函数地址与结构体偏移均在 patches/native/local_mp_air_events.jsonc 动态捕获写入 wto_ws.cfg,
|
||||
// 运行时由 local_mp_values.c 填入全局 extern LmpValues g_lmp(LMP_GP_OFF_KS_RULES 展开为 g_lmp.gp_ks_rules);
|
||||
// 2. 用外层函数钩子 + 线程局部标志(__declspec(thread))精确界定调用上下文,彻底告别脆弱的 _ReturnAddress()。
|
||||
static SwitchPlayerUnitFn orig_switch_player_unit;
|
||||
static __declspec(thread) int g_in_air_event_switch;
|
||||
|
||||
static void __fastcall hook_switch_player_unit(void *event_mgr, void *participant, uint8_t to_air)
|
||||
{
|
||||
int previous = g_in_air_event_switch;
|
||||
|
||||
if (to_air != 0 && ground_arcade_air_events_enabled())
|
||||
g_in_air_event_switch = 1;
|
||||
orig_switch_player_unit(event_mgr, participant, to_air);
|
||||
g_in_air_event_switch = previous;
|
||||
}
|
||||
|
||||
// 读取连杀规则表时全部走 g_lmp 动态解析值,跨小版本自动适配:
|
||||
const uint8_t *gameplay = g_lmp.gameplay ? *(const uint8_t *const *)g_lmp.gameplay : NULL;
|
||||
const uint8_t *rules = *(const uint8_t *const *)(gameplay + LMP_GP_OFF_KS_RULES);
|
||||
uint32_t rule_count = *(const uint32_t *)(gameplay + LMP_GP_OFF_KS_RULE_COUNT);
|
||||
```
|
||||
|
||||
### 对比 2:原版静态数据 —— `DatasetCache` 提取与纯领域目录消费 vs 在业务里手抄常量表
|
||||
|
||||
```ts
|
||||
// ❌ 坏写法:把某一个版本的新手教程首通银狮/金鹰奖励硬编码成服务端字典
|
||||
const TUTORIAL_REWARDS: Record<string, { silverLions: number; goldenEagles: number }> = {
|
||||
'tutorialB_fighter': { silverLions: 5000, goldenEagles: 100 },
|
||||
'tutorialB_assaulter': { silverLions: 5000, goldenEagles: 0 },
|
||||
};
|
||||
```
|
||||
|
||||
```ts
|
||||
// ✅ 好写法(真实代码:apps/server/src/game-data/datasets/training-missions.ts
|
||||
// + apps/server/src/training/training-completion.ts):
|
||||
// 1. 在 datasets/ 定义带版本号的 Dataset,从玩家原版 char.vromfs.bin 的
|
||||
// config/mislist.blk、config/pve_awards.blk、config/unlocks.blk 提取真实配置;缺失必填块立即抛错。
|
||||
export const trainingMissions: Dataset<TrainingMissionsData> = {
|
||||
id: 'training-missions',
|
||||
version: 1,
|
||||
extract(source: DatasetSource): TrainingMissionsData {
|
||||
const misSection = blockAt(source.readBlk('char.vromfs.bin', 'config/mislist.blk'), 'training');
|
||||
if (!misSection) throw new Error('config/mislist.blk has no "training" block');
|
||||
const awardSection = blockAt(source.readBlk('char.vromfs.bin', 'config/pve_awards.blk'), 'training');
|
||||
if (!awardSection) throw new Error('config/pve_awards.blk has no "training" block');
|
||||
// ... 组装 missions 列表并返回纯数据对象
|
||||
return { missions };
|
||||
},
|
||||
};
|
||||
|
||||
// 2. 启动时通过 DatasetCache 加载(包未变直接命中缓存),交由纯领域类 TrainingCatalogue 执行幂等发奖:
|
||||
const trainingCatalogue = new TrainingCatalogue(datasets.load(trainingMissions));
|
||||
trainingCatalogue.applyCompletion(profile, { chapter, mission, difficulty });
|
||||
```
|
||||
|
||||
### 对比 3:找准修复层级与严格遵守工具链语法(MSVC C 与 Node 24 原生 TS)
|
||||
|
||||
**(A)先查原版读取逻辑,别急着动刀写客户端补丁**
|
||||
|
||||
- ❌ **坏思路**:发现多载具出击模式下 AI 机器人死一次就不再重生,立刻去反汇编 `BotSystem` 准备写 `patches/exe/` 强改内存计数器。
|
||||
- ✅ **好思路**:先看 `MissionSettings::load` 是怎么读任务配置的——结果发现原版客户端本来就会读取任务 BLK 根节点的 `numBotRespawns` 与 `numTankBotRespawns`,只是服务端组装匹配开局配置时漏填了这两个根字段。在 `apps/server` 补上几行配置下发即可解决,**零客户端补丁、跨版本永久免疫失效**。
|
||||
|
||||
**(B)MSVC C 编译规范与 Node 24 原生 TypeScript 语法规范**
|
||||
|
||||
- **Native C(`native/wto-net/`)**:由 `native/wto-net/build.ps1` 调用 Visual Studio `cl.exe` 以 `/W4` 编译,要求**零编译警告**。校验自定义结构体大小与成员偏移时使用 `<windows.h>` 的编译期断言 `C_ASSERT(sizeof(LocalMpAirSpawn) == 0x48);`,线程局部存储使用 `__declspec(thread)`,内存对齐使用 `__declspec(align(16))`;避免使用 `__attribute__((...))`、零长数组、可变长数组(VLA)或 `void *` 算术运算等 GCC/Clang 专属扩展。
|
||||
- **TypeScript(`tsconfig.json`)**:Node.js 24 直接剥离类型运行 `.ts` 源码,仓库开启了 `erasableSyntaxOnly: true`、`verbatimModuleSyntax: true`、`allowImportingTsExtensions: true` 与 `exactOptionalPropertyTypes: true`:
|
||||
|
||||
```ts
|
||||
// ❌ 坏写法:省略 .ts 后缀、值导入混用纯类型、使用 enum 或构造函数参数属性(Node 24 类型剥离与 tsc 均会报错!)
|
||||
import { SaveStore, SaveUpgrades } from '../saves/save-store';
|
||||
export enum ResearchState { Locked = 0, Available = 1 }
|
||||
export class Handler {
|
||||
constructor(private readonly saves: SaveStore) {}
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
// ✅ 好写法:相对路径一律写明 .ts 扩展名;纯类型必须用 import type;用 as const 对象或联合类型代替 enum;用 #私有字段
|
||||
import { decodeBlk, encodeBlk, type BlkBlock } from '@wto/blk';
|
||||
import { writeFileAtomic } from '../storage/atomic-file.ts';
|
||||
import type { SaveUpgrades } from './save-upgrades.ts';
|
||||
|
||||
export const VehicleStatus = {
|
||||
CAN_RESEARCH: 2,
|
||||
OWNED: 4,
|
||||
} as const;
|
||||
```
|
||||
|
||||
### 对比 4:工程验证 —— 跑真实工具链检查 vs 写几百行假 Mock 单元测试
|
||||
|
||||
- ❌ **坏写法**:改了 `patches/gui/` 只肉眼扫一眼 `.nut` 缩进,或者自己造一套模拟客户端行为的 300 行 Mock 单测跑绿就宣称「测试全部通过」——结果真进游戏时因为 Quirrel 词法作用域冲突卡死在登录界面,或者 `patch.jsonc` 多写了一个非法键在构建副本时直接抛 `DefinitionError`。
|
||||
- ✅ **好写法**:按改动范围老老实实运行真实检查工具(`npm run typecheck`、`wtotools check-patches`、带 `sq.exe` 的完整 `wtotools check-gui`、`native\wto-net\build.ps1`、`scripts/build-game-copy.ts`),并在 PR 描述中**如实把「已在命令行跑过的检查」与「尚待在隔离副本进游戏实机验收的步骤」分开写清楚**。
|
||||
|
||||
---
|
||||
|
||||
<a id="ai-guide-zh"></a>
|
||||
|
||||
## 5. 使用 AI 编程助手协作指南(含一键复制约束提示词)
|
||||
|
||||
我们非常鼓励你使用 Claude Code、Codex、Cursor 等 AI 工具协助阅读反汇编、梳理 `.nut` 界面调用链、核对 BLK 字段以及快速定位协议差异。
|
||||
|
||||
但 AI 如果事先不知道 WTOffline 的工程边界,很容易顺手写出硬编码 RVA、在 `patches/gui/**/patch.jsonc` 里误加 `requires` 字段、漏写 `.ts` 导入后缀、用 `enum` 语法或生成一大堆无意义的 Mock 测试。**在让 AI 动手修改任何文件之前,请先把下面这段完整提示词发给它**:
|
||||
|
||||
```text
|
||||
我正在为 WTOffline 仓库开发改动。在编写或修改代码前,请遵循以下项目规范(写任何符号、结构体字段、CLI 参数前先读取仓库真实源文件核实):
|
||||
|
||||
1. 修复层级优先顺序:先查原版一手依据(玩家只读原版 .vromfs.bin、gui.vromfs.bin 里的 .nut 脚本、DagorEngine 公开源码)。凡是能在本地服务器(apps/server)协议响应、任务配置字段或静态数据集里解决的问题,不要新增 patches/gui/、patches/exe/ 或 native/wto-net/ 客户端补丁。
|
||||
2. 动态定位,不硬编码地址与偏移:不要在 C 或 TS 代码里写死 exe 函数地址、RVA、C++ 结构体偏移或 _ReturnAddress() 调用栈判断。所有原生地址与偏移通过 patches/exe/ 或 patches/native/*.jsonc 的 signature / string_ref / within 动态捕获写入 wto_ws.cfg,C 侧通过 extern LmpValues g_lmp(local_mp_values.h / local_mp_offsets.h)读取,并用外层钩子 + __declspec(thread) 标志替代返回地址检查。带尾随立即数的 rip-relative 指令捕获 rel32 时需显式指定 "end"(指令总字节长度)。
|
||||
3. 三类数值严格归位:原版游戏自带数值(载具价格、研发点、奖励、任务、出生参数)必须通过 apps/server/src/game-data/datasets/(DatasetCache)从原版归档提取,缺必填字段直接抛错;离线版自定参数与开关统一放入 apps/server/tuning/*.jsonc 并在对应 *-tuning.ts 做启动校验;协议/引擎常量写英文注释注明客户端版本 RVA 或 DagorEngine 源码路径。
|
||||
4. 分层与依赖方向:packages/* 不导入或读取 apps/*。apps/server/src/ 内区分传输协议层(char/actions/ 等)、领域规则层(research/、battle/、modifications/ 等纯逻辑目录,无 rules/ 目录,零网络零磁盘 I/O)、档案持久化层(profile/、saves/、storage/atomic-file.ts —— 改档动作先原子写盘成功再回包);存档兼容升级统一通过 saves/save-upgrades.ts 的 formatVersion 步骤处理,不在业务规则里散落旧版兼容分支。单文件接近 300 行或函数接近 50 行时主动拆分。
|
||||
5. 严格语法与 Schema 约束:
|
||||
- TypeScript 运行在 Node 24 原生类型剥离模式(erasableSyntaxOnly + verbatimModuleSyntax + allowImportingTsExtensions):所有相对导入必须带显式 `.ts` 后缀,纯类型必须用 `import type`,禁止使用 `enum`、`namespace` 和构造函数参数属性。
|
||||
- Native C 必须通过 MSVC `native/wto-net/build.ps1`(/W4 零警告),使用 `C_ASSERT` 做编译期布局检查,禁止 GCC 扩展;新增 `.c` 文件需同步加入 `build.ps1` 的 `$sources`。
|
||||
- 补丁 JSONC 严格校检未知键:特别是 `patches/gui/**/patch.jsonc` 顶层只允许 `id`、`title`、`features`、`variants`(不要写 `requires`,否则会抛出 DefinitionError)。
|
||||
6. 真实工具验证:不要编写庞大的模拟(mock)单元测试套件。按改动运行真实检查命令(`npm run typecheck`、`wtotools check-patches`、带 `--sq` 的完整 `wtotools check-gui`、`native/wto-net/build.ps1`、`scripts/build-game-copy.ts`),并如实区分已跑过的命令与待隔离副本实机验收项。
|
||||
7. 提交规范:一笔 PR 只聚焦单一目标;代码注释、补丁 `title`/头部三行说明与约定式提交消息统一使用英文;不把 AI 写入 Co-authored-by;在隔离副本实机进游戏验收前不提交 `patches/versions/*.jsonc`。
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
<a id="isolation-zh"></a>
|
||||
|
||||
## 6. 隔离安全与资产边界
|
||||
|
||||
1. **官方原版客户端目录保持只读**:无论是拆包查 `.blk`、跑 `tools/re/cli.py` 反汇编、`wtotools` 核对补丁还是构建游戏副本,原版目录都只作为只读输入源,不要向 Steam 或官方启动器安装目录写入、覆盖或残留文件。
|
||||
2. **仅在独立隔离副本中运行测试**:实机运行客户端必须在 Steam 库目录之外的独立离线副本中进行,并确保三大核心安全锁(`ESSENTIAL_FEATURES`)全部生效——所有联网请求经 `wto_ws.dll` 收口至 `127.0.0.1`、本地配置落入独立 `WTOffline` 用户目录与 `Software\WTOffline` 注册表路径、反作弊与崩溃上报已剥离,且只使用离线本地账号登录。
|
||||
3. **代码仓库不包含受版权保护资产与隐私信息**:不要将 `.vromfs.bin`、`aces.exe`、解包出的原版 `.nut` / `.blk` 完整文件、真实玩家存档、本机绝对路径或未脱敏日志提交进 Git 仓库。
|
||||
|
||||
---
|
||||
|
||||
<a id="english"></a>
|
||||
|
||||
[简体中文](#zh-cn) · English · [Dev Docs](README.md#english)
|
||||
[简体中文](#zh-cn) · English · [Back to Dev Docs](README.md#english)
|
||||
|
||||
## Where changes belong
|
||||
Rather than handing you a dry list of dos and don'ts, this guide first explains **how WTOffline actually works under the hood and why its layers are separated the way they are**. Once that architecture clicks, every engineering rule follows naturally.
|
||||
|
||||
- State the player-visible result and the intended scope before starting. Discuss gameplay or architectural changes with maintainers. Check the target build, stock UI scripts, and official public source. Record the version, file or symbol, and the evidence for the behavior. Mark any inference as such. For game formats, look for existing tools and review their licensing, maintenance, and version support. [DagorEngine source](https://github.com/GaijinEntertainment/DagorEngine)
|
||||
- Keep the client's normal flow by responding from the local server. Check the server and stock configuration first. When a client change is necessary, document the feature, the stock behavior, and why a lighter change is insufficient. Put UI edits in `patches/gui/` and archive configuration edits in `packages/patcher/`. See the [patch guide](patches.md#english) for the other patch types.
|
||||
- Keep protocol encoding, game rules, persistence, and game data extraction in their own layers. Persist a save change before returning success. Reject unknown accounts, missing required inputs, and insufficient balances. During early development, use fresh saves for acceptance and omit legacy migrations.
|
||||
- Pass configuration and paths from applications into shared packages. Reuse existing logic and constants. Review files near 300 lines or functions near 50 lines for responsibilities that can be split. Store shop and marketplace HTML, CSS, and JavaScript in separate files and reuse the [web UI module](../apps/server/src/web-ui).
|
||||
---
|
||||
|
||||
## Data and tuning
|
||||
<a id="architecture-en"></a>
|
||||
|
||||
| Kind of value | Where it belongs |
|
||||
| --- | --- |
|
||||
| Protocol constants such as header sizes and message types | Keep them in code with the source and relevant version. |
|
||||
| Values already in the game files such as vehicle and modification prices | Read them from the player's game files at startup. Report the field and stop if a required value is missing. |
|
||||
| Offline defaults such as rewards, prices, weights, multipliers, rank thresholds, and limits | Put them in the module's `tuning/` directory. Server defaults are in [apps/server/tuning](../apps/server/tuning) and are validated at startup. |
|
||||
## 1. End-to-End Architecture: How WTOffline Works
|
||||
|
||||
Use game data and official material as the first sources for economic defaults. The local store uses official USD prices as the basis for GJN prices. For gaps, use reference data with a recorded source or document the offline design choice. Put the source, unit, and reasoning in a comment or the PR. Read the exact values and any player-facing numbers from the configuration.
|
||||
WTOffline uses the same core philosophy as Single Player Tarkov (SPT): **do not rewrite the game engine—keep the retail client running its native code paths, redirect all network traffic to a local emulation server on `127.0.0.1`, and hook `aces.exe` in-process only where retail builds stripped Dedicated Server battle handlers.**
|
||||
|
||||
At startup, the server can load a same-named `tuning/*.jsonc` file from the data directory. Object keys merge. Numbers, strings, and arrays are replaced as a whole.
|
||||
```text
|
||||
Player clicks "Launch" in the Launcher
|
||||
│
|
||||
├─ 1. Desktop Launcher (apps/launcher) invokes Copy Builder (packages/patcher)
|
||||
│ └─ Reads the player's official stock install STRICTLY READ-ONLY and writes an isolated copy:
|
||||
│ ├─ char.vromfs.bin / aces.vromfs.bin: rewrite network.blk endpoints -> 127.0.0.1:<port>, inject store bundle GUIDs
|
||||
│ ├─ gui.vromfs.bin: apply patches/gui/ (surgical UI script edits only where server responses cannot suffice)
|
||||
│ ├─ win64/aces.exe: apply patches/exe/ (bypass pack signature checks, isolate user dir & registry, disable anti-cheat,
|
||||
│ │ rewrite PE import name "WS2_32.dll\0" -> "wto_ws.dll\0")
|
||||
│ └─ win64/wto_ws.dll + win64/wto_ws.cfg: resolve patches/native/*.jsonc RVAs & struct offsets into wto_ws.cfg
|
||||
│
|
||||
├─ 2. Local Emulation Server (apps/server, bound strictly to 127.0.0.1:<port>)
|
||||
│ ├─ Startup: DatasetCache extracts static facts from stock .vromfs.bin archives; tuning-loader merges tuning/*.jsonc
|
||||
│ └─ Runtime: transport/port-listener.ts peeks at the first bytes of every TCP socket on that single port:
|
||||
│ ├─ First byte 0x01 ──▶ MatchingService (9-byte header + LZ4 frames, encrypted after handshake)
|
||||
│ ├─ Plaintext PASS/NICK/USER/CAP/PING ──▶ IrcServer (hangar & squad chat)
|
||||
│ ├─ First byte 0x16 (TLS ClientHello) ──▶ Local-cert TLSSocket decrypts, then routes to IrcServer or HTTP
|
||||
│ └─ Everything else ──▶ HTTP server (yuplay2 login, char binary BLK RPC, signed inventory JSON, web store)
|
||||
│ (Note: HTTP WebSocket `upgrade` requests are logged and explicitly refused via socket.destroy()!)
|
||||
│
|
||||
└─ 3. Isolated Offline Client Copy (win64/aces.exe + win64/wto_ws.dll)
|
||||
├─ Process attach (DllMain): wto_ws.dll forwards all Winsock exports (including 31 ordinal imports) via wto_ws.def
|
||||
│ to system ws2_32.dll and installs MinHook detours on ws2_32's resolver/connect APIs; if ANY network hook fails,
|
||||
│ DllMain returns FALSE so Windows immediately aborts launch before a single packet can go online!
|
||||
├─ Hangar phase: sign-in, profile load, tech-tree research, purchases, crews, chests, and store all run over stock
|
||||
│ protocols against apps/server with atomic disk persistence
|
||||
└─ Battle phase: MatchingService launches a LocalMP host session; after verifying PE headers against wto_ws.cfg,
|
||||
wto_ws.dll activates local_mp_* modules to restore stripped host handlers (vehicle/loadout spawn, AI bot spawn,
|
||||
kill/assist/capture scoring, Ground Arcade air events, nuclear instant win, damage-notice filtering), and post-battle
|
||||
results return to apps/server via cln_update for reward settlement and save persistence
|
||||
```
|
||||
|
||||
## Common implementation pitfalls (especially with AI-assisted PRs)
|
||||
### 1.1 Single-Port Protocol Multiplexing (`apps/server/src/transport/`)
|
||||
|
||||
Using AI tools to inspect binaries, trace logs, and pinpoint root causes is welcome. Before opening a PR, verify the implementation itself against these engineering guardrails so changes stay maintainable across game updates:
|
||||
Because some client subsystems read URLs from `config/network.blk` while others use compiled-in hostnames, ports, and `https://` URLs, `apps/server/src/transport/port-listener.ts` multiplexes every protocol over **one `127.0.0.1` TCP port**. On each incoming connection, `socket.once('data', ...)` inspects the initial bytes, pushes them back with `socket.unshift(first)`, and hands the socket to the matching protocol handler:
|
||||
|
||||
| Area | Preferred practice | Avoid |
|
||||
| --- | --- | --- |
|
||||
| Locating & offsets | Resolve addresses, jump targets, and struct offsets dynamically via `signature`, `string_ref`, or `within` captures in `patches/exe/` and `patches/native/` | Hardcoding RVAs, struct offsets, raw function pointers, or `_ReturnAddress` checks in C or TypeScript |
|
||||
| Layering | Solve in the local server or stock config first; separate protocol, rules, persistence, and datasets, and write saves to disk before returning success | Adding client workarounds for server-solvable issues, mixing game rules into protocol handlers, or replying before persistence |
|
||||
| Static data & tuning | Extract stock vehicle, mission, reward, and spawn data from player archives via cached `datasets/`; put offline defaults in `apps/server/tuning/*.jsonc` with startup validation | Copying stock numbers into source code, hardcoding fallback coordinates, or scattering magic constants |
|
||||
| Reuse & modularity | Reuse shared native sites (`local_mp_core`) and existing helpers; pass paths/config into `packages/*`; split files near 300 lines or functions near 50 lines | Registering duplicate hooks for the same symbol, reading `apps/*` from `packages/*`, or growing monolithic handlers |
|
||||
| Toolchains | Keep native C code cleanly buildable with MSVC (`native/wto-net/build.ps1`, zero warnings) and TS compatible with Node 24 erasable syntax | Relying on GCC-only extensions or submitting C changes without an MSVC build |
|
||||
| Verification | Run the matching `typecheck`, `check-patches`, full `check-gui` (Quirrel bytecode check), and temporary copy build; clearly mark pending in-game checks | Relying on mock/unit tests as proof of in-game correctness, skipping `check-gui`, or committing `patches/versions/*.jsonc` before live acceptance |
|
||||
| Scope & hygiene | Keep each PR focused on one change, use English conventional commits and English comments, and reserve `Co-authored-by` for human collaborators | Mixing unrelated refactors, leaking local paths, or attributing AI tools in `Co-authored-by` |
|
||||
1. **Matching binary RPC (`first[0] === 0x01`)**: Matched by `startsMatchingPacket(first)` (`matching/matching-frame.ts` — 9-byte little-endian header + LZ4 block) and handed to `MatchingService`;
|
||||
2. **Plaintext IRC handshake**: Connections starting with `PASS`, `NICK`, `USER`, `CAP`, or `PING` (`startsIrcHandshake`) go straight to `IrcServer`;
|
||||
3. **TLS ClientHello (`first[0] === 0x16`)**: Wrapped in a `TLSSocket` using the local certificate, after which the first decrypted bytes are inspected again—routing TLS-wrapped IRC handshakes to `IrcServer` and all other decrypted streams to the HTTP server;
|
||||
4. **Plaintext HTTP**: All remaining connections go to `createHttpServer` (`transport/http-listener.ts`), where `Router` dispatches requests by `originalHost` and path across `login`, `char`, `inventory`, `store`, `downloadable-content`, etc. **Note on WebSockets**: WTOffline does **not** use WebSockets—any HTTP `upgrade` request hits `server.on('upgrade', ...)` in `http-listener.ts`, which logs `WebSocket <host><path> (refused)` in the traffic log and immediately closes the socket with `socket.destroy()`.
|
||||
|
||||
## Local development and contributions
|
||||
### 1.2 How `wto_ws.dll` Intercepts All Outbound Traffic Safely
|
||||
|
||||
- Launch the game in a dedicated copy and isolated environment. Before launch, verify the network restrictions, local service, and isolation of Steam identity, accounts, files, registry, machine identifiers, anti-cheat, and crash reporting. Observe before and after effects in a disposable environment when needed. Use a read-only stock source and a local account, and launch from the offline copy.
|
||||
- The store and marketplace use the game's embedded browser and the local service. Check the browser features supported by the target build and reuse the game's language and localized data. Include the browser subprocess when checking network access and cache paths.
|
||||
- Submit your own code and the smallest fragments needed for a patch. Keep game files, extracted assets, and player data local. Use sources that reviewers can access and redact any log excerpts.
|
||||
`patches/exe/online/network-hook-library/patch.jsonc` locates the 11-byte import descriptor name `"WS2_32.dll\0"` (`57 53 32 5f 33 32 2e 64 6c 6c 00`) in `aces.exe`'s `.rdata` section and overwrites it in place with `"wto_ws.dll\0"` (`77 74 6f 5f 77 73 2e 64 6c 6c 00`, also **11 bytes**):
|
||||
|
||||
- When Windows loads `aces.exe`, it loads `win64/wto_ws.dll` instead of `WS2_32.dll`. `native/wto-net/src/wto_ws.def` forwards every imported Winsock symbol (preserving exact `@ordinal` numbers for all 31 ordinal-imported functions) to the operating system's `ws2_32.dll`;
|
||||
- Inside `DllMain` (`native/wto-net/src/dll_main.c`), `wto_ws.dll` loads `wto_ws.cfg` and uses MinHook to hook the name-resolution, `connect`, and datagram functions inside the system's `ws2_32.dll` itself—so network calls from **every module** in the process pass through local redirection, not just calls made directly by `aces.exe`;
|
||||
- **Hard fail-closed guarantee**: If `MH_Initialize`, `install_resolver_hooks()`, `install_connection_hooks()`, or `MH_ApplyQueued()` fails for any reason, `DllMain` logs the failure and **returns `FALSE`**, causing the Windows loader to abort process startup immediately rather than risking an unhooked online connection.
|
||||
|
||||
### 1.3 The Golden Priority Rule
|
||||
|
||||
> **Before touching any client file, always ask: "Can `apps/server` or stock mission/config fields solve this?"**
|
||||
> If a bug or feature can be implemented by returning the right server payload, populating a stock BLK field in the mission launch config, or extracting stock archive data, **never add a `.nut`, `aces.exe`, or `wto_ws.dll` patch**. Client patches are strictly a last resort when retail `aces.exe` or `gui.vromfs.bin` genuinely lacks the path—because minor game updates frequently shift binary code while wire protocols and BLK schemas remain stable across builds.
|
||||
|
||||
---
|
||||
|
||||
<a id="2-code-map-and-layer-boundaries"></a>
|
||||
<a id="workspace-rule-en"></a>
|
||||
|
||||
## 2. Workspace Dependency Rule & Real `apps/server` Directory Map
|
||||
|
||||
### 2.1 One-Way Workspace Dependency Rule
|
||||
|
||||
```text
|
||||
apps/launcher ──┐
|
||||
├──▶ packages/* (@wto/blk · @wto/vromfs · @wto/jsonc · @wto/exepatch · @wto/patcher · @wto/mods)
|
||||
apps/server ──┘
|
||||
```
|
||||
|
||||
- **Dependencies flow strictly downward**: `apps/*` may import from `packages/*` (and developer CLI scripts under `scripts/*` may compose both), **but `packages/*` must never import from, reference, or hardcode paths into `apps/*`**.
|
||||
- Whenever a shared package needs a patch directory, data folder, port number, or bundle list, pass it explicitly as a function parameter from the caller.
|
||||
|
||||
<a id="server-layers-en"></a>
|
||||
|
||||
### 2.2 Complete `apps/server/src/` Four-Layer Directory Map
|
||||
|
||||
Note that **there is NO monolithic `rules/` folder in `apps/server/src/`**—domain rules live in dedicated per-domain directories. Use this map to place every file in the right layer:
|
||||
|
||||
| Layer | Real directories under `apps/server/src/` | What belongs here | What must NOT go here |
|
||||
| --- | --- | --- | --- |
|
||||
| **1. Transport & Protocol** | `transport/` (single-port listener, HTTP router, TLS cert), `traffic-log/` (JSONL + decoded body logger), `login/` (`yuplay2` sign-in & session tokens), `char/` (`char-service.ts`, `pbbd-stream.ts`, `char/actions/*-actions.ts`, and `char/actions/action-table.ts`), `matching/` (LZ4 framing, stream cipher, queue/battle RPC), `inventory/` (external inventory & RSA content signing), `store/` (bundle & redeem-code endpoints), `chat/` (IRC server), `cloud-settings/`, `downloadable-content/`, `web-ui/` (in-game store & market HTML/CSS), `mods/` (server mod runtime) | Decode wire payloads (HTML forms, JSON, marker-prefixed binary BLK, `PBBD` streams, LZ4 packets), validate request parameters, invoke domain rules, and serialize results back into stock wire formats | Do not write multi-hundred-line currency, research, or profile-mutation logic inside `*-actions.ts`; never read or write save files directly bypassing `PlayerProfiles` / `SaveStore` |
|
||||
| **2. Domain Rules** | `battle/` (mission setup & post-battle economy settlement), `research/` (tech-tree state, target selection, free-RP conversion), `modifications/` (modules, ammo belts, spares, custom weapon presets), `crew/` (slots & skill progression), `items/` (boosters, wagers, discounts), `repair/` (battle damage & timed free repair), `clans/` (squadrons & squadron vehicle RP), `decor/` (skins, decals, 3D attachables), `unlocks/` (streaks, titles, progression unlocks), `player-card/` (pilot icons & showcases), `training/` (tutorial completion rewards), `game-modes/` | **Pure domain logic**: take an in-memory profile `BlkBlock`, loaded datasets, and validated tuning; verify preconditions; mutate or compute the next state; return an explicit `RuleOutcome` (`ACCEPTED` or `refused('CODE')`) | **Zero network or filesystem I/O**: never import `node:http`, `node:net`, or `node:fs`, and keep domain logic agnostic of HTTP headers or sockets |
|
||||
| **3. Profile & Persistence** | `profile/` (`player-profiles.ts` plus focused `profile-*.ts` BLK accessors and derived-state refresh), `saves/` (`save-store.ts` & `save-upgrades.ts` `formatVersion`), `accounts/` (multi-account credentials & isolation), `storage/` (`atomic-file.ts` `writeFileAtomic`) | Encapsulate typed `BlkBlock` profile accessors, isolate per-account saves under `<data>/saves/<userId>/`, run ordered `formatVersion` upgrades, and guarantee crash-safe writes via temp file + `fsync` + atomic rename | Do not embed shop pricing or research formulas here; **every profile mutation must finish writing to disk before replying to the client** |
|
||||
| **4. Datasets & Tuning** | `game-data/` (`game-files.ts`, `game-pack.ts`, `datasets/*.ts`, `datasets/dataset-cache.ts`), shipped defaults in `apps/server/tuning/*.jsonc` + loader/validators in `src/tuning/` (`tuning-loader.ts`, `tuning-reader.ts`, `limits-tuning.ts`, `launcher-tuning.ts`) + per-domain `<domain>/*-tuning.ts` | Extract static facts from stock `.vromfs.bin` archives at startup (cached in `<data>/cache/datasets/<id>.json` by pack size/mtime and inner file SHA-1 digests), and merge/validate JSONC tuning across shipped defaults -> enabled mods -> player `<data>/tuning/` overrides | Never invent stock game numbers; if a required stock block or field is missing, throw an explicit error at startup instead of silently substituting a fake default |
|
||||
|
||||
**File granularity & reuse**:
|
||||
- When a file approaches **300 lines** or a function approaches **50 lines**, check whether wire parsing, BLK tree traversal, and domain rules have been mixed together and split them cleanly along the table above;
|
||||
- Reuse existing building blocks (`char/actions/rule-answer.ts`, `profile/profile-*.ts`, `modifications/equipment-catalogue.ts`, shared `web-ui/` helpers, and `local_mp_core` in C) instead of duplicating helpers.
|
||||
|
||||
---
|
||||
|
||||
<a id="walkthrough-en"></a>
|
||||
|
||||
### 2.3 End-to-End Walkthrough of One Real Action: `cln_set_researchable`
|
||||
|
||||
To see how those four layers collaborate in practice, let's trace what happens when a player clicks **"Research"** on a vehicle in the tech tree and the client sends **`cln_set_researchable`** (use this exact pattern whenever you add a new profile-mutating `char` action):
|
||||
|
||||
1. **Wire Arrival & Payload Decoding (`apps/server/src/char/char-service.ts`)**
|
||||
The client sends an HTTP POST to `char-*.warthunder.com` with headers `action: cln_set_researchable` and `uidhint: <userId>`, carrying a marker-prefixed binary BLK body (`unit:t = "us_m4a1_1942_sherman"`, `type:i = 0`). `CharService.#handleCore` calls `decodeRequestPayload(request.body)` (`char/char-payload.ts`) to decode the `BlkBlock` (and format readable BLK text for the traffic log), then looks up `'cln_set_researchable'` in `char/actions/action-table.ts` to invoke `setResearchable`.
|
||||
2. **Protocol Adapter & Parameter Extraction (`apps/server/src/char/actions/research-actions.ts`)**
|
||||
`setResearchable` is a thin 14-line adapter built on `ruleAction` (`char/actions/rule-answer.ts`). It extracts `unit` and `type` (or `mod` for module research) using `stringParam` and `intParam` (`char/actions/payload-params.ts`). Missing parameters return `undefined` (which `ruleAction` turns into `!ERROR:BAD_PARAMS`); valid parameters return a pure rule closure:
|
||||
`(profile) => chooseResearchTarget(profile, rules, vehicle, type)`.
|
||||
3. **Profile Load & Pure Domain Rule (`apps/server/src/research/research-progress.ts`)**
|
||||
After resolving the account via `withAccount`, `ruleAction` calls `profiles.updateWhen(account.userId, ...)` (`profile/player-profiles.ts`), which loads `<data>/saves/<userId>/profile.blk` through `SaveStore.loadProfile` and passes the `BlkBlock` into `chooseResearchTarget`:
|
||||
- Looks up the vehicle in the startup-extracted tech-tree dataset via `rules.techTree.vehicle(vehicleName)` and verifies `vehicleTypeById(typeId) === vehicle.type`;
|
||||
- Verifies `currentStatus(profile, rules, vehicleName) === VehicleStatus.CAN_RESEARCH`. If the vehicle is locked or already owned, it returns `refused('NOT_AVAILABLE')` (`{ ok: false, refusal: 'NOT_AVAILABLE' }`)—causing `updateWhen` to return `undefined` **without touching the disk** and `ruleAction` to reply `!ERROR:NOT_AVAILABLE`;
|
||||
- Otherwise, updates the active target and clears any pending finished-research prompt via `profile/profile-research-targets.ts`, returning `ACCEPTED` (`{ ok: true }`).
|
||||
4. **Atomic Disk Persistence BEFORE Replying (`profile/player-profiles.ts` -> `saves/save-store.ts` -> `storage/atomic-file.ts`)**
|
||||
When the closure accepts, `PlayerProfiles.updateWhen` runs `#refresh(profile, userId)` to bring derived profile state (unlocked ranks, statuses, clan sync, earned unlocks) up to date, then calls `SaveStore.saveProfile(userId, profile)`. `saveProfile` calls `writeFileAtomic` (`storage/atomic-file.ts`), which writes `profile.blk.<pid>.<rand>.tmp`, flushes hardware buffers via `fsyncSync(fd)`, and atomically `renameSync`s it over `profile.blk` (with Windows transient-lock retries) before updating `save.json`. **Only after both atomic writes succeed** does `ruleAction` project `clientProfile(profile, account)` and `toResponse` (`char/char-answers.ts`) send HTTP 200 (`0x69` uncompressed marker + binary BLK) back to `aces.exe`.
|
||||
|
||||
### 2.4 Save Schema Upgrades (`saves/save-upgrades.ts`)
|
||||
|
||||
- **Domain rules always target only the current profile schema**: never scatter ad-hoc legacy compatibility branches (`if (oldFieldExists) ...`) across `research/`, `modifications/`, or `battle/`.
|
||||
- When a release changes what `profile.blk` stores, append an ordered `SaveUpgrade` step to `SaveUpgrades` (`saves/save-upgrades.ts`, where `steps[n]` transforms a `formatVersion` `n + 1` profile into `n + 2` in place, bumping `currentFormat`). When `SaveStore.loadProfile` opens a save from an earlier release, it runs the missing steps in order and immediately persists the upgraded profile at `currentFormat`. Unreleased work-in-progress structures on a development branch do not need migration shims.
|
||||
|
||||
---
|
||||
|
||||
<a id="values-en"></a>
|
||||
|
||||
## 3. Three Categories of Values (Keep Boundaries Clear)
|
||||
|
||||
Every number or constant in WTOffline belongs to exactly one of three categories:
|
||||
|
||||
| Category | Concrete examples | Where it MUST live | Anti-pattern to avoid |
|
||||
| --- | --- | --- | --- |
|
||||
| **1. Protocol & engine constants** | Wire/MPI message IDs (`LMP_MPI_MSG_UNIT_RESPAWN = 0xf030u`), `PBBD` magic (`0x44424250`), Dagor container layouts (`dag::Vector` offsets, `FastNameMap` shifts), bitmasks | Named constants in the relevant protocol module or header, with an **English comment citing the primary source** (client version + RVA, or [DagorEngine open-source](https://github.com/GaijinEntertainment/DagorEngine) file path) | Bare magic numbers like `if (msgId == 61488)` or `if (st == 64)` with zero provenance comment |
|
||||
| **2. Stock game facts** | Vehicle SL/GE prices, RP requirements, battle ratings, repair costs, modification trees, mission lists, tutorial first-win rewards, killstreak spawn altitude/distance/speed | Extracted from the player's read-only `.vromfs.bin` archives at startup via `apps/server/src/game-data/datasets/` (`Dataset<T>`) and cached in `<data>/cache/datasets/<id>.json` by `DatasetCache`. Throw an explicit `Error` if a required block/field is missing | Copying a table of vehicle costs, tutorial rewards, or spawn coordinates from one client build into TS/C code, or silently falling back to `?? 10000` when a lookup fails |
|
||||
| **3. Offline tuning & defaults** | SL/RP reward multipliers, new-profile starting balances, local store bundle prices, supply-chest drop weights, AI bot respawn counts, request caps, gameplay toggles | Shipped defaults in `apps/server/tuning/<domain>.jsonc`, validated for type and bounds at startup via `TuningReader` in `<domain>/*-tuning.ts`, and merged by `tuning-loader.ts` across shipped defaults -> enabled mod overrides -> player `<data>/tuning/<domain>.jsonc` overrides | Hardcoding `const RP_MULTIPLIER = 3.0` or arbitrary caps inside a settlement function where players and mods cannot override them |
|
||||
|
||||
---
|
||||
|
||||
<a id="4-good-vs-bad-code-patterns-real-pitfalls"></a>
|
||||
<a id="good-vs-bad-en"></a>
|
||||
|
||||
## 4. Good vs. Bad Code: 4 Real Codebase Comparisons
|
||||
|
||||
Every "✅ Good" snippet below uses the exact symbols and files from this repository. Check your changes against all four before opening a PR.
|
||||
|
||||
### Comparison 1: Native C Hooks — `g_lmp` Dynamic Captures & Scoped TLS Flags vs. Hardcoded Offsets & `_ReturnAddress()`
|
||||
|
||||
Whenever War Thunder ships a minor patch (e.g., `2.61.0.37` -> `2.61.0.58`), function RVAs shift across `.text` and C++ class member offsets move whenever fields are added or reordered.
|
||||
|
||||
```c
|
||||
// ❌ BAD: Hardcoded RVAs, hardcoded struct offset (+0x3798), and brittle _ReturnAddress() caller check.
|
||||
// The very next minor game update will silently break the feature or crash the client!
|
||||
static void __fastcall bad_hook_send_unit_respawn(uint8_t *unit, const void *spawn)
|
||||
{
|
||||
uintptr_t base = (uintptr_t)GetModuleHandleW(NULL);
|
||||
if ((uintptr_t)_ReturnAddress() != base + 0x1281280)
|
||||
return;
|
||||
const uint8_t *gameplay = *(const uint8_t *const *)(base + 0x7bad2f0);
|
||||
const uint8_t *rules = *(const uint8_t *const *)(gameplay + 0x3798);
|
||||
/* ... */
|
||||
}
|
||||
```
|
||||
|
||||
```c
|
||||
// ✅ GOOD (Real code: native/wto-net/src/local_mp_air_events.c + local_mp_offsets.h + local_mp_values.h):
|
||||
// 1. Every RVA and struct offset is dynamically captured in patches/native/local_mp_air_events.jsonc,
|
||||
// written to wto_ws.cfg, and loaded into extern LmpValues g_lmp (LMP_GP_OFF_KS_RULES -> g_lmp.gp_ks_rules);
|
||||
// 2. An outer detour + thread-local flag (__declspec(thread)) scopes the call cleanly without _ReturnAddress().
|
||||
static SwitchPlayerUnitFn orig_switch_player_unit;
|
||||
static __declspec(thread) int g_in_air_event_switch;
|
||||
|
||||
static void __fastcall hook_switch_player_unit(void *event_mgr, void *participant, uint8_t to_air)
|
||||
{
|
||||
int previous = g_in_air_event_switch;
|
||||
|
||||
if (to_air != 0 && ground_arcade_air_events_enabled())
|
||||
g_in_air_event_switch = 1;
|
||||
orig_switch_player_unit(event_mgr, participant, to_air);
|
||||
g_in_air_event_switch = previous;
|
||||
}
|
||||
|
||||
// Struct offsets come from g_lmp, surviving minor client updates automatically:
|
||||
const uint8_t *gameplay = g_lmp.gameplay ? *(const uint8_t *const *)g_lmp.gameplay : NULL;
|
||||
const uint8_t *rules = *(const uint8_t *const *)(gameplay + LMP_GP_OFF_KS_RULES);
|
||||
uint32_t rule_count = *(const uint32_t *)(gameplay + LMP_GP_OFF_KS_RULE_COUNT);
|
||||
```
|
||||
|
||||
### Comparison 2: Stock Game Data — `DatasetCache` Extraction + Pure Catalogue vs. Hardcoded TS Maps
|
||||
|
||||
```ts
|
||||
// ❌ BAD: Hardcoding tutorial mission rewards from one client build directly in server code
|
||||
const TUTORIAL_REWARDS: Record<string, { silverLions: number; goldenEagles: number }> = {
|
||||
'tutorialB_fighter': { silverLions: 5000, goldenEagles: 100 },
|
||||
'tutorialB_assaulter': { silverLions: 5000, goldenEagles: 0 },
|
||||
};
|
||||
```
|
||||
|
||||
```ts
|
||||
// ✅ GOOD (Real code: apps/server/src/game-data/datasets/training-missions.ts
|
||||
// + apps/server/src/training/training-completion.ts):
|
||||
// 1. Define a versioned Dataset<T> that extracts stock data from char.vromfs.bin
|
||||
// (config/mislist.blk, config/pve_awards.blk, config/unlocks.blk) and throws if required blocks are missing.
|
||||
export const trainingMissions: Dataset<TrainingMissionsData> = {
|
||||
id: 'training-missions',
|
||||
version: 1,
|
||||
extract(source: DatasetSource): TrainingMissionsData {
|
||||
const misSection = blockAt(source.readBlk('char.vromfs.bin', 'config/mislist.blk'), 'training');
|
||||
if (!misSection) throw new Error('config/mislist.blk has no "training" block');
|
||||
const awardSection = blockAt(source.readBlk('char.vromfs.bin', 'config/pve_awards.blk'), 'training');
|
||||
if (!awardSection) throw new Error('config/pve_awards.blk has no "training" block');
|
||||
// ... build and return { missions }
|
||||
return { missions };
|
||||
},
|
||||
};
|
||||
|
||||
// 2. Load through DatasetCache at startup and pass pure data into TrainingCatalogue:
|
||||
const trainingCatalogue = new TrainingCatalogue(datasets.load(trainingMissions));
|
||||
trainingCatalogue.applyCompletion(profile, { chapter, mission, difficulty });
|
||||
```
|
||||
|
||||
### Comparison 3: Fixing at the Right Layer & Toolchain Discipline (MSVC C & Node 24 TypeScript)
|
||||
|
||||
**(A) Check stock loader fields before writing a client patch**
|
||||
|
||||
- ❌ **Bad instinct**: Notice AI bots only respawn once in multi-slot Air Arcade battles and immediately start reversing `BotSystem` to write an `aces.exe` memory patch.
|
||||
- ✅ **Good engineering**: Inspect `MissionSettings::load` first and discover that the stock client already reads `numBotRespawns` and `numTankBotRespawns` from the mission root `DataBlock`—the local server simply omitted those two root parameters when assembling multi-slot missions. Adding them in `apps/server` fixes the issue in 5 lines with **zero client patches** and permanent cross-version stability.
|
||||
|
||||
**(B) MSVC C rules & Node 24 native TypeScript rules**
|
||||
|
||||
- **Native C (`native/wto-net/`)**: Compiled by Visual Studio `cl.exe` via `native/wto-net/build.ps1` with `/W4` and **zero warnings**. Verify stack/wire struct layouts at compile time with `C_ASSERT(sizeof(LocalMpAirSpawn) == 0x48);`, use `__declspec(thread)` for TLS and `__declspec(align(16))` for alignment, and **never use GCC/Clang extensions** (`__attribute__`, VLAs, zero-length arrays, or `void *` pointer arithmetic).
|
||||
- **TypeScript (`tsconfig.json`)**: Executed directly by Node.js 24 native type-stripping with `erasableSyntaxOnly: true`, `verbatimModuleSyntax: true`, `allowImportingTsExtensions: true`, and `exactOptionalPropertyTypes: true`:
|
||||
|
||||
```ts
|
||||
// ❌ BAD: Extensionless relative import, value-importing a type, using `enum`, and constructor parameter properties
|
||||
import { SaveStore, SaveUpgrades } from '../saves/save-store';
|
||||
export enum ResearchState { Locked = 0, Available = 1 }
|
||||
export class Handler {
|
||||
constructor(private readonly saves: SaveStore) {}
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
// ✅ GOOD: Explicit `.ts` extension on all relative imports, `import type` for types, `as const` objects instead of `enum`, and `#private` fields
|
||||
import { decodeBlk, encodeBlk, type BlkBlock } from '@wto/blk';
|
||||
import { writeFileAtomic } from '../storage/atomic-file.ts';
|
||||
import type { SaveUpgrades } from './save-upgrades.ts';
|
||||
|
||||
export const VehicleStatus = {
|
||||
CAN_RESEARCH: 2,
|
||||
OWNED: 4,
|
||||
} as const;
|
||||
```
|
||||
|
||||
### Comparison 4: Real Verification vs. Mock Test Suites
|
||||
|
||||
- ❌ **Bad practice**: Editing `patches/gui/` and only eyeballing indentation—or writing 300 lines of mock unit tests that simulate fake server/client calls—and declaring the change "fully tested", only for login to hang forever on a Quirrel `from ... import *` scope collision or `loadGuiPatches` to throw `DefinitionError` on an unknown JSONC key.
|
||||
- ✅ **Good practice**: Run the real verification tools matching your change (`npm run typecheck`, `wtotools check-patches`, full `wtotools check-gui` with `sq.exe`, MSVC `native\wto-net\build.ps1`, `scripts/build-game-copy.ts`), and **honestly separate executed CLI checks from pending in-game acceptance steps** in your PR description.
|
||||
|
||||
---
|
||||
|
||||
<a id="ai-guide-en"></a>
|
||||
|
||||
## 5. Working Effectively with AI Coding Assistants (Copy-Paste Prompt Block)
|
||||
|
||||
Using AI assistants (Claude Code, Codex, Cursor, etc.) to read disassembly, trace `.nut` UI call chains, inspect BLK schemas, and pinpoint protocol mismatches is warmly welcomed.
|
||||
|
||||
However, without explicit project context, AI tools frequently invent hardcoded RVAs, add an invalid `requires` field to `patches/gui/**/patch.jsonc`, omit `.ts` import extensions, write `enum` declarations, or generate bloated mock test suites. **Paste the constraint block below into your AI session before asking it to write or edit code**:
|
||||
|
||||
```text
|
||||
I am preparing a change for the WTOffline repository. Before writing any code, always read the real source files to verify symbols, struct fields, and CLI flags, and follow these engineering rules strictly:
|
||||
|
||||
1. Layer priority: Ground every change in primary sources (read-only stock .vromfs.bin archives, gui.vromfs.bin .nut scripts, DagorEngine open-source code). Solve issues in apps/server protocol answers, mission BLK fields, or stock datasets before adding any client patch under patches/gui/, patches/exe/, or native/wto-net/.
|
||||
2. Zero hardcoded addresses or offsets: Never hardcode function RVAs, global addresses, C++ struct offsets, or _ReturnAddress() caller checks in C or TS. Capture all native symbols and offsets dynamically via patches/exe/ or patches/native/*.jsonc (signature / string_ref / within) into wto_ws.cfg, read them in C exclusively through `extern LmpValues g_lmp` (local_mp_values.h / local_mp_offsets.h), and replace caller checks with an outer hook + `__declspec(thread)` flag. When capturing a `rel32` from an instruction that has trailing immediate bytes after disp32, always pass `"end"` set to the full instruction byte length.
|
||||
3. Three value categories: Extract stock game numbers (vehicle prices, RP, rewards, missions, spawn params) from stock archives via `apps/server/src/game-data/datasets/` (`DatasetCache`), throwing explicitly if required fields are missing. Put offline defaults/multipliers/toggles in `apps/server/tuning/*.jsonc` validated via `*-tuning.ts`. Keep protocol/engine constants in code with English comments citing the client build RVA or DagorEngine source path.
|
||||
4. Layer & dependency rules: `packages/*` must never import or read from `apps/*`. Inside `apps/server/src/`, keep transport/protocol (`char/actions/`, etc.), pure domain rules (`research/`, `battle/`, `modifications/`, etc. — note there is NO `rules/` folder; zero network/disk I/O in domain modules), and profile/persistence (`profile/`, `saves/`, `storage/atomic-file.ts` — always persist atomically to disk BEFORE replying) cleanly separated. Handle save schema evolution only via `formatVersion` steps in `saves/save-upgrades.ts`, never ad-hoc legacy branches in domain rules. Split files near 300 lines or functions near 50 lines.
|
||||
5. Strict toolchain & schema rules:
|
||||
- TypeScript runs on Node 24 native type-stripping (`erasableSyntaxOnly`, `verbatimModuleSyntax`, `allowImportingTsExtensions`): include explicit `.ts` extensions on all relative imports, use `import type` for type-only imports, and never use `enum`, `namespace`, or constructor parameter properties.
|
||||
- Native C must compile cleanly with MSVC `native/wto-net/build.ps1` (`/W4`, zero warnings), using `C_ASSERT` for layout checks and zero GCC extensions; register any new `.c` file in `build.ps1`'s `$sources` list.
|
||||
- Patch JSONC files reject unknown keys: in particular, `patches/gui/**/patch.jsonc` allows ONLY `id`, `title`, `features`, and `variants` at top level (adding `requires` throws `DefinitionError`!).
|
||||
6. Real verification: Do not add large mock unit test suites. Run the applicable real checks (`npm run typecheck`, `wtotools check-patches`, full `wtotools check-gui` with `--sq`, `native/wto-net/build.ps1`, `scripts/build-game-copy.ts`) and clearly separate executed CLI checks from pending isolated in-game acceptance steps.
|
||||
7. PR hygiene: Keep one focused goal per PR; write code comments, patch `title`/3-line header comments, and conventional commit messages in English; never list AI tools in `Co-authored-by`; and never commit `patches/versions/*.jsonc` before live in-game verification in an isolated copy.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
<a id="isolation-en"></a>
|
||||
|
||||
## 6. Isolation & Asset Boundaries (Non-Negotiable)
|
||||
|
||||
1. **Keep the official stock installation strictly read-only**: Unpacking archives, running `tools/re/cli.py`, checking patches with `wtotools`, and building game copies must only ever read the stock client folder—**never write, modify, or drop files inside a Steam or official launcher installation**.
|
||||
2. **Test exclusively in an isolated offline copy**: Run the patched client only from a separate directory outside your Steam library, with all three `ESSENTIAL_FEATURES` safety locks active—all network calls redirected to `127.0.0.1` by `wto_ws.dll`, user files isolated under `WTOffline`, registry state under `Software\WTOffline`, anti-cheat and crash reporting disabled, and signed in only with a local offline account.
|
||||
3. **Zero copyrighted assets or private data in Git**: Never commit `.vromfs.bin` packs, `aces.exe`, full extracted stock `.nut` / `.blk` files, personal player saves, machine-specific paths, or unredacted logs to the repository.
|
||||
+943
-44
File diff suppressed because it is too large.
Load diff
@@ -1,31 +1,34 @@
|
||||
## Change
|
||||
|
||||
<!-- Describe the player-visible result and the scope of this PR. -->
|
||||
<!-- Describe the player-visible result and the single focused goal of this PR. -->
|
||||
|
||||
## Reason and evidence
|
||||
|
||||
<!-- Give the target client build and the relevant game file, script, or official source. -->
|
||||
<!-- For a client patch, explain why the local service or game configuration is insufficient. -->
|
||||
<!-- For tuning changes, record the source and unit of the new defaults. -->
|
||||
<!-- Give the target client build (e.g. 2.61.0.37) and cite the primary source: stock archive file, .nut script, RVA, or DagorEngine source path. -->
|
||||
<!-- For any client patch (patches/gui, patches/exe, native/wto-net), explain why apps/server or stock BLK configuration cannot solve it. -->
|
||||
<!-- For tuning changes (apps/server/tuning/*.jsonc), record the rationale, bounds, and units of the new defaults. -->
|
||||
|
||||
## Client compatibility
|
||||
|
||||
<!-- List the affected builds and any change to patch variants or version records. -->
|
||||
<!-- List the tested/affected client builds and any added patch variants or patches/versions/<version>.jsonc updates. -->
|
||||
<!-- Reminder: never commit patches/versions/<version>.jsonc until live isolated in-game acceptance is complete. -->
|
||||
|
||||
## Self-check
|
||||
|
||||
- [ ] No hardcoded addresses, RVAs, struct offsets, or `_ReturnAddress` checks (dynamic `patches/` captures used instead)
|
||||
- [ ] No hardcoded stock game numbers or magic defaults (read from stock archives via `datasets/` or placed in `tuning/*.jsonc`)
|
||||
- [ ] Layer boundaries preserved (protocol / rules / persistence / datasets; `packages/*` does not read `apps/*`)
|
||||
- [ ] Scope is focused on one goal, code comments and commit messages are in English, and no unrelated files were modified
|
||||
- [ ] Every command listed in **Checks run** was actually executed (including `check-gui` for `patches/gui/` and MSVC `build.ps1` for `native/`)
|
||||
- [ ] No hardcoded addresses, RVAs, C++ struct offsets, or `_ReturnAddress()` checks (all native values resolved dynamically into `g_lmp` via `patches/`, with explicit `"end"` on `rel32` captures that have trailing immediate bytes)
|
||||
- [ ] No hardcoded stock game numbers or silent fallback defaults (extracted from stock archives via `game-data/datasets/` or validated in `tuning/*.jsonc`)
|
||||
- [ ] Layer & persistence rules preserved (`packages/*` never imports `apps/*`; domain modules stay free of network/disk I/O; profile mutations persist atomically via `PlayerProfiles` / `SaveStore` before replying)
|
||||
- [ ] Toolchain & schema rules met (explicit `.ts` extensions on relative imports, `import type` for types, no `enum`/`namespace`/parameter properties; strict patch JSONC keys—e.g., no `requires` in `patches/gui/**/patch.jsonc`; new `.c` files added to `native/wto-net/build.ps1`)
|
||||
- [ ] Focused on one goal, English comments / patch `title` / conventional commit message used, no AI `Co-authored-by` trailers, and no personal paths, game assets, or unredacted logs in `git diff`
|
||||
- [ ] Every command listed in **Checks run** was actually executed (including `wtotools check-gui --sq ...` for `patches/gui/` and MSVC `native/wto-net/build.ps1` with zero warnings for `native/`)
|
||||
|
||||
## Checks run
|
||||
|
||||
| Command or check | Client build if relevant | Result |
|
||||
| Command or check | Client build (if relevant) | Result |
|
||||
| --- | --- | --- |
|
||||
| | | |
|
||||
|
||||
## In-game acceptance
|
||||
|
||||
<!-- Give the screen or entry point, the action, and the expected result. Record what was observed or mark the check pending. -->
|
||||
<!-- Give the exact screen or entry point, the action to perform, and the expected result in an isolated offline copy. -->
|
||||
<!-- Clearly state what was observed in-game, or explicitly mark steps that are still pending live verification. -->
|
||||
Reference in new issue
Block a user