Files
WT-Offline/dev-docs/development-rules.md
T
N0VAN0M4LY e79866b96e 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.
2026-12-03 11:25:53 +08:00

600 lines
61 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 开发理念、架构分层与工程规范 / Development Rules
<a id="zh-cn"></a>
简体中文 · [English](#english) · [返回 Dev Docs](README.md#zh-cn)
这篇文档不只罗列「能做什么、不能做什么」,而是先把 **WTOffline 为什么这样分层、客户端与本地服务器各自承担什么角色** 彻底讲透。只要底层运行模型在脑子里立住了,项目里的每一条工程规范都是自然而然的推论。
---
<a id="architecture-zh"></a>
## 1. 先建立全景图:WTOffline 到底是怎么跑起来的?
WTOffline 采用与《逃离塔科夫》单机版(SPT)一脉相承的本地模拟架构:**不推翻重写游戏引擎,而是让原版客户端相信自己正连着完整的线上后端,把它的全部网络请求收口到本机 `127.0.0.1` 的模拟服务器,并仅在进程内补齐客户端被裁剪掉的局内主机裁判函数。**
```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 结算银狮/研发点并落盘
```
### 1.1 单端口多协议分流细节(`apps/server/src/transport/`)
客户端内部既有读取 `config/network.blk` 的模块,也有把域名、端口甚至 `https://` 写死在二进制常量里的模块。为了不占用一串本地端口,本地服务器在 `apps/server/src/transport/port-listener.ts` 中用**单个 TCP 监听端口**接住所有流量,在 `socket.once('data', ...)` 窥探首批字节后原样退回缓冲区(`socket.unshift`)并精准派发:
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` 是如何在零外联风险下接管网络的?
在 `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 · [Back to Dev Docs](README.md#english)
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.
---
<a id="architecture-en"></a>
## 1. End-to-End Architecture: How WTOffline Works
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.**
```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
```
### 1.1 Single-Port Protocol Multiplexing (`apps/server/src/transport/`)
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:
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()`.
### 1.2 How `wto_ws.dll` Intercepts All Outbound Traffic Safely
`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.