返回 WTOffline 主页 Back to WTOffline Home
DEVELOPER HANDBOOK

开发者手册(全 5 章) Developer Handbook (5 Chapters)

与仓库 dev-docs/ 1:1 同源生成的完整手册:从核心黑话翻译、服务端完整请求走读、EXE 逐字节拆解与 Native 6 文件接线,到 AI 辅助开发约束提示词与流量日志排错法。 Compiled 1:1 from repository dev-docs/: plain-language glossary, end-to-end server action trace, 57-byte EXE patch anatomy, 6-file Native C wiring, AI coding assistant prompt, and traffic-log debugging.

01 · 导览、核心术语词典与任务入口

欢迎参与 WTOffline 开发。本目录面向项目贡献者、客户端新版本适配者,以及使用 AI 编程工具辅助逆向定位与编写代码的协作者。无论你之前是否接触过 Dagor 引擎或《战争雷霆》客户端内部结构,都可以按本指南一步步上手。

如果你只是想制作载具属性魔改、自定义地图池、全新 3D 载具模型或服务端脚本模组:你完全不需要修改 WTOffline 核心源码,请直接阅读 模组开发文档(mod-dev-docs) 或访问 在线模组文档。


第一次来,建议按什么顺序读?

不要一上来就啃二进制补丁字段或反汇编地址。按下面三步顺读,大约 15–20 分钟就能建立完整的全局认知:

  1. 开发理念、架构分层与工程规范(必读第一站):搞清楚启动器、单端口本地模拟服务器(apps/server)与进程内网络/对局桥接库(wto_ws.dll)是如何协同工作的;顺着一个真实的 cln_set_researchable 动作看懂服务端四层代码怎么流转;掌握「三类数值放哪里」「好代码 vs 坏代码」真实对比,以及可直接复制给 AI 编程助手的工程约束提示词。
  2. 补丁编写与新版本适配指南:当确认本地服务器与原版配置确实无法解决问题、必须修改客户端时,按这篇手把手教程拆包查看原版文件、用 tools/re/cli.py 反汇编定位,并对照完整无省略的 GUI(patches/gui/)、EXE(patches/exe/)和 Native(patches/native/ + native/wto-net/)真实案例编写跨版本自适应补丁。
  3. 环境搭建、流量调试与提交自查:配齐本地开发环境,学会直接阅读 <数据目录>/logs/ 下自动解码的明文 BLK 流量日志快速抓 Bug,按改动类型运行对应的必跑检查命令,并对照 PR 模板 提交高质量改动。

核心概念与术语词典

在阅读后续文档或翻阅源码时,你会频繁遇到以下专有名词。这里用大白话一次性讲透:

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.blkpackages/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。客户端在玩家点击登录、进入机库前会一次性编译加载大批 .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/)架构分层与真实动作追踪
修改玩家档案字段读写、新号初始资产或存档落盘格式apps/server/src/profile/、apps/server/src/saves/、apps/server/src/storage/存档层与原子写盘规范
从游戏原版数据包提取新的载具/经济/任务/本地化静态数据apps/server/src/game-data/datasets/三类数值与缓存数据集
调整离线版默认倍率、商店定价、补给箱权重、AI 重生数或上限参数apps/server/tuning/*.jsonc + apps/server/src/tuning/ + 各领域 *-tuning.ts三类数值放哪里
修改本地内嵌网页商店、模拟交易所或服务器脚本模组运行时apps/server/src/store/、apps/server/src/inventory/、apps/server/src/web-ui/、apps/server/src/mods/服务器目录全景图
修改桌面启动器界面、安装向导、存档管理页、模组管理页或更新器apps/launcher/src/检查命令清单
修改离线副本构建管线、归档包改写、BLK 编解码、EXE 补丁引擎或模组加载器packages/patcher/、packages/blk/、packages/vromfs/、packages/exepatch/、packages/mods/仓库级单向依赖约定
修改游戏内界面弹窗、按钮或结算页脚本(Quirrel .nut)patches/gui/<领域>/<名称>/GUI 补丁完整范例
修改 aces.exe 机器码分支或只读常量字符串patches/exe/<领域>/<名称>/EXE 补丁 57 字节逐指令拆解
编写或修复 wto_ws.dll 局内 LocalMP 原生裁判钩子patches/native/<模块>.jsonc + native/wto-net/src/Native 模块 6 文件串联教程
协助适配刚发布的《战争雷霆》客户端小版本更新patches/versions/、scripts/record-game-version.ts适配新版本客户端四步流程

01 · Overview, Core Glossary & Task Map

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.

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) or the online Mod Docs.


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 (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: 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: 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.

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 storesHow WTOffline uses it
char.vromfs.binTech-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.blkpackages/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.binMatch 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.binAll 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.binMultiplayer 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.binSemicolon-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.binTech-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.binUI 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 userIds, 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, 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 doSpecific codebase directoriesPrimary 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
Change player profile fields, new-account defaults, or save persistence / format upgradesapps/server/src/profile/, apps/server/src/saves/, apps/server/src/storage/Persistence & Atomic Writes
Extract new static vehicle, economy, mission, or localization data from stock archivesapps/server/src/game-data/datasets/Three Categories of Values
Adjust offline reward multipliers, store prices, supply-chest weights, AI respawn counts, or limitsapps/server/tuning/*.jsonc + apps/server/src/tuning/ + <domain>/*-tuning.tsThree Categories of Values
Work on the in-game web store, simulated marketplace, or server script mod runtimeapps/server/src/store/, apps/server/src/inventory/, apps/server/src/web-ui/, apps/server/src/mods/Server Directory Map
Change the desktop launcher UI, install wizard, saves manager, mods page, or auto-updaterapps/launcher/src/Required Check Commands
Modify copy building, archive patching, BLK/vromfs codecs, EXE patch engine, or mod loaderpackages/patcher/, packages/blk/, packages/vromfs/, packages/exepatch/, packages/mods/Workspace Dependency Rule
Patch in-game UI modals, buttons, or debriefing Quirrel scripts (.nut)patches/gui/<domain>/<name>/GUI Patches Full Example
Patch machine instructions or constant .rdata strings in aces.exepatches/exe/<domain>/<name>/EXE Patch 57-Byte Anatomy
Write or fix wto_ws.dll in-process LocalMP battle host hookspatches/native/<module>.jsonc + native/wto-net/src/Native Modules 6-File Wiring
Adapt WTOffline to a newly released minor War Thunder client buildpatches/versions/, scripts/record-game-version.tsAdapting a New Client Build

02 · 架构原理、真实目录分层与好坏代码对比

这篇文档不只罗列「能做什么、不能做什么」,而是先把 WTOffline 为什么这样分层、客户端与本地服务器各自承担什么角色 彻底讲透。只要底层运行模型在脑子里立住了,项目里的每一条工程规范都是自然而然的推论。


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 客户端补丁。客户端补丁留给原版客户端确实缺少对应通路的场景——因为游戏每次小版本更新都会重排二进制代码,而服务端协议与配置字段跨版本稳定得多。


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/* 下的代码或配置文件。
  • 当共享包需要补丁集目录、数据目录、端口或礼包列表时,一律由上层调用方通过函数参数显式传入。

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),尽量复用而不是重复实现。

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 原子回写磁盘。仍在同一分支开发调试、尚未发布的草稿改动无需写迁移代码。

3. 三类数值放哪里(保持边界清晰)

在代码审查中,最常见的返工原因就是把不同性质的数字混写在了业务逻辑里。写下任何一个字面量前,先问它属于下面哪一类:

数值类别典型例子唯一正确的存放位置常见错误示范
① 协议与引擎固定常量匹配/局内消息号(如 LMP_MPI_MSG_UNIT_RESPAWN = 0xf030u)、PBBD 魔数(0x44424250)、Dagor 容器布局(dag::Vector 偏移、FastNameMap 移位)、状态位掩码定义为具名常量放在对应协议或头文件中,并用英文注释写明一手来源(目标客户端版本号 + RVA,或 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/ 调参

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 描述中如实把「已在命令行跑过的检查」与「尚待在隔离副本进游戏实机验收的步骤」分开写清楚。

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`。

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 仓库。

02 · Architecture, Real Directory Map & Code Patterns

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.


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.


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.

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:

LayerReal directories under apps/server/src/What belongs hereWhat must NOT go here
1. Transport & Protocoltransport/ (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 formatsDo 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 Rulesbattle/ (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 & Persistenceprofile/ (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 renameDo not embed shop pricing or research formulas here; every profile mutation must finish writing to disk before replying to the client
4. Datasets & Tuninggame-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.tsExtract 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/ overridesNever 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.

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 renameSyncs 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.

3. Three Categories of Values (Keep Boundaries Clear)

Every number or constant in WTOffline belongs to exactly one of three categories:

CategoryConcrete examplesWhere it MUST liveAnti-pattern to avoid
1. Protocol & engine constantsWire/MPI message IDs (LMP_MPI_MSG_UNIT_RESPAWN = 0xf030u), PBBD magic (0x44424250), Dagor container layouts (dag::Vector offsets, FastNameMap shifts), bitmasksNamed constants in the relevant protocol module or header, with an English comment citing the primary source (client version + RVA, or DagorEngine open-source file path)Bare magic numbers like if (msgId == 61488) or if (st == 64) with zero provenance comment
2. Stock game factsVehicle SL/GE prices, RP requirements, battle ratings, repair costs, modification trees, mission lists, tutorial first-win rewards, killstreak spawn altitude/distance/speedExtracted 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 missingCopying 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 & defaultsSL/RP reward multipliers, new-profile starting balances, local store bundle prices, supply-chest drop weights, AI bot respawn counts, request caps, gameplay togglesShipped 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 overridesHardcoding const RP_MULTIPLIER = 3.0 or arbitrary caps inside a settlement function where players and mods cannot override them

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.

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.

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.

03 · 补丁编写、逐字节拆解与 Native 完整接线

这篇手册面向需要修改客户端(Quirrel 界面脚本、aces.exe 二进制指令、或 wto_ws.dll 局内 LocalMP 原生裁判模块)以及协助适配游戏新版本的开发者。

动手前的第一道自检:请先阅读 开发规范第 1 节,确认问题确实无法通过修改 apps/server 协议响应或下发原版任务/配置 BLK 字段解决。只有原版客户端真正缺失对应通路时,才编写客户端补丁。


1. 第 0 步:只读拆包、查看二进制 BLK、反汇编定位与选型

请将原版客户端目录视为只读,不要直接修改其中的文件。利用仓库自带的 @wto/vromfs、@wto/blk 和 Python 静态分析工具 tools/re/cli.py,你可以在内存中直接查看原版脚本、配置与反汇编代码。

1.1 一行命令读取原版 .vromfs.bin 中的 .nut 脚本或解码二进制 .blk

无需安装第三方解包器,在仓库根目录运行下面这段 Node.js 脚本(把 <原版目录> 换成你的官方客户端路径,只读不写):

powershell
# 示例 A:列出 gui.vromfs.bin 中匹配关键字的脚本路径,并直接打印某个 .nut 原文
node --input-type=module -e "
import { readFileSync } from 'node:fs';
import { getFile, readArchive } from '@wto/vromfs';
const archive = readArchive(readFileSync(String.raw`<原版目录>\gui.vromfs.bin`));
console.log([...archive.files.keys()].filter((p) => p.includes('tutorial')));
console.log(Buffer.from(getFile(archive, 'scripts/tutorials/nexttutorialhandler.nut')).toString('utf8'));
"

# 示例 B:读取 char.vromfs.bin(或 aces.vromfs.bin)里的紧凑二进制 .blk 并格式化为可读文本
# (自动加载包内共享键名表 nm 与可选的 .dict 压缩字典)
node --input-type=module -e "
import { readFileSync } from 'node:fs';
import { decodeBlk, formatBlkText, parseSharedNameMap } from '@wto/blk';
import { getFile, NAME_MAP_PATH, readArchive } from '@wto/vromfs';
const archive = readArchive(readFileSync(String.raw`<原版目录>\char.vromfs.bin`));
const dictionary = [...archive.files.entries()].find(([p]) => p.endsWith('.dict'))?.[1];
const names = archive.files.has(NAME_MAP_PATH) ? parseSharedNameMap(getFile(archive, NAME_MAP_PATH), dictionary).names : [];
const blk = decodeBlk(getFile(archive, 'config/pve_awards.blk'), { names, dictionary });
console.log(formatBlkText(blk).slice(0, 2000));
"

1.2 使用 tools/re/cli.py 对 aces.exe 做只读静态逆向定位

先按 环境准备 初始化 .venv(pip install -e ./tools)。随后即可直接在命令行查字符串交叉引用、查调用者、反汇编函数(注意:所有地址参数均为十六进制 RVA,且务必显式传入 --exe "<原版目录>\win64\aces.exe"):

powershell
# 1. 查找固定英文字符串在 .rdata 中的 RVA,以及所有通过 rip-relative lea 引用它的代码位置与所属函数
.\.venv\Scripts\python.exe tools\re\cli.py find-string "customScoreParams" --exe "<原版目录>\win64\aces.exe"

# 2. 查找所有以 rip-relative 方式读写某个全局变量 RVA 的指令
.\.venv\Scripts\python.exe tools\re\cli.py xref 0x7bad2f0 --exe "<原版目录>\win64\aces.exe"

# 3. 查找所有直接 call 或 jmp 到目标函数 RVA 的调用点
.\.venv\Scripts\python.exe tools\re\cli.py callers 0x5445270 --exe "<原版目录>\win64\aces.exe"

# 4. 反汇编指定 RVA(默认打印 40 条指令,带字符串和调用注释;可传 --count、--end 或 --function 反汇编整函数)
.\.venv\Scripts\python.exe tools\re\cli.py disasm 0x11b2c14 --count 20 --exe "<原版目录>\win64\aces.exe"
.\.venv\Scripts\python.exe tools\re\cli.py disasm 0x126d762 --function --exe "<原版目录>\win64\aces.exe"

1.3 选对客户端修改方式与通用编写规范

你要改什么代码放哪里真实参考例子
修改机库/弹窗/结算界面脚本(Quirrel .nut)patches/gui/<领域>/<名称>/patches/gui/tutorials/immediate-save-skip-tutorial/
改写 aces.exe 内寥寥几条跳转/比较指令或 .rdata 固定字符串patches/exe/<领域>/<名称>/patches/exe/battle/allow-local-host-bot-spawns/
用 C 语言写 MinHook 钩子补齐 LocalMP 局内裁判逻辑(wto_ws.dll)patches/native/<模块>.jsonc + native/wto-net/src/<模块>.cpatches/native/local_mp_scores.jsonc
改写 network.blk、shop.blk、gui.blk 等数据包静态配置packages/patcher/src/(不放 patches/)packages/patcher/src/char-pack.ts、main-pack.ts

所有 patches/ 定义共享的四条基本约定:

  1. 一处独立行为对应一个目录/模块,不在同一个补丁里顺手塞两件不相关的改动;
  2. patch.jsonc / <模块>.jsonc 顶部必须写三行英文注释:
    • 第 1 行:这个补丁具体改了什么;
    • 第 2 行(Why the client: / Why the exe:):为什么本地服务器或原版配置解决不了;
    • 第 3 行(Without it:):如果不打这个补丁,玩家会遇到什么具体现象。
  3. title 与 features 统一写英文(注:仓库内个别早期补丁保留了中文 title 历史遗留,所有新增补丁请一律使用清晰的英文 title),并优先复用现有的 A-..K- 功能标签(见 核心概念词典第 7 节);
  4. 唯一命中校验:无论多少个 variants,对任意一个客户端版本必须且只能有恰好 1 个 variant 命中(且单次定位全局唯一命中 1 处);0 命中或多处命中都会被补丁引擎安全拒绝,避免误写。

2. GUI 补丁(patches/gui/)—— 完整三文件实例与严格 Schema 校验

2.1 看一个完整的真实 GUI 补丁:tutorials/immediate-save-skip-tutorial

在原版 scripts/tutorials/nexttutorialhandler.nut 中,当玩家弹出「是否参加新手教程」询问框并勾选「不再询问」时,脚本调用 saveLocalByAccount(skipTutorialBitmaskId, skipTutorial) 时没传第 3 个参数,默认走延迟 60 秒防抖的 saveProfile()——如果玩家勾选后在 60 秒内重启或崩溃退出,设置根本没发到服务端落盘,下次进机库弹窗又会冒出来。服务端无法替客户端缩短前端自己的 60 秒定时器,因此需要补上第 3 个回调参数 @() save_profile(false) 立即保存。

该补丁目录 patches/gui/tutorials/immediate-save-skip-tutorial/ 下共有 3 个文件,完整内容如下:

① patch.jsonc(注:此早期补丁保留了中文 title,你编写新补丁时请将 title 写为英文,如 "Save tutorial opt-out immediately after ticking 'do not ask again'"):

jsonc
// Save the tutorial opt-out immediately via save_profile(false).
// Why the client: the stock callback waits 60 s before writing or sending anything to the service.
// Without it: a crash within 60 s of ticking "do not ask again" brings the tutorial prompt back.
{
  "id": "tutorials/immediate-save-skip-tutorial",
  "title": "新手教程询问窗勾选「不再询问」后立即落盘保存",
  "features": [
    "A-Tutorials"
  ],
  "variants": [
    {
      "written_for": "2.61.0.37",
      "file": "scripts/tutorials/nexttutorialhandler.nut",
      "edits": [
        {
          "find": "find.nut",
          "replace": "replace.nut"
        }
      ]
    }
  ]
}

② find.nut(原版脚本中最小且在目标文件内唯一出现 1 次的原文,保留原始 4 空格缩进):

squirrel
    skipTutorial = stdMath.change_bit(skipTutorial, this.checkIdx, obj.getValue())
    saveLocalByAccount(skipTutorialBitmaskId, skipTutorial)
  }

③ replace.nut(替换后的脚本片段):

squirrel
    skipTutorial = stdMath.change_bit(skipTutorial, this.checkIdx, obj.getValue())
    saveLocalByAccount(skipTutorialBitmaskId, skipTutorial, @() save_profile(false))
  }

2.2 gui-patch-definition.ts 严格 Schema 白名单与编写细节(极易踩坑!)

packages/patcher/src/gui-patch-definition.ts 会调用 rejectUnknownKeys 对每一层字段做严格白名单检查,多写任何一个未定义字段都会直接抛出 DefinitionError:

  • 顶层只允许 4 个键:"id"、"title"、"features"、"variants"。

    特别警告:GUI 的 patch.jsonc 没有 "requires" 字段! 不要把 EXE 补丁里的 "requires": [] 复制到 patches/gui/ 里,否则加载器会当场抛错拒绝构建!

  • variants[] 元素只允许 3 个键:"written_for"、"file"、"edits"。其中 "file" 必须是 gui.vromfs.bin 内部全小写、以 / 分隔且不带前导 / 的相对路径(例如 "scripts/tutorials/nexttutorialhandler.nut",注意原版归档内文件名全被转为小写!)。
  • edits[] 元素只允许 2 个键:"find"、"replace",值必须是同一补丁目录下的纯文件名(不允许包含 / 或 \ 子路径)。
  • 换行与唯一匹配规则:读取 .nut 片段时会自动剥离 UTF-8 BOM、将 \r\n 归一化为 \n,并去掉文件末尾的单个终止换行符(因此 Git 自动换行转换不会破坏匹配);find.nut 的内容在目标脚本里必须精确出现 1 次(0 次或 ≥2 次均报错)。
  • 本地服务地址占位符:如果 replace.nut 里需要拼出本地服务器地址,直接写 {{LOCAL_ENDPOINT}},构建副本时 gui-pack.ts 会自动替换成 127.0.0.1:<实际端口>。
  • 跨版本演进:如果新版本游戏修改了附近代码导致 find.nut 不再命中,切勿直接覆盖旧片段破坏老版本兼容性——新建 find-58.nut 与 replace-58.nut,在 variants 数组里追加一条 "written_for": "<新版本号>" 的记录即可。
  • 必跑 sq.exe 字节码检查:只要改过任何 patches/gui/ 文件,提交前必须运行:
    powershell
    .\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "<原版目录>\gui.vromfs.bin" --sq "build\quirrel-cli\bin\Release\sq.exe"

    它会把补丁打在内存里的原版脚本上并调用 sq.exe 执行 compilestring 字节码编译,精准拦截与顶部 from ... import * 词法重名、未绑定函数前向引用以及误用 base 等保留字导致的进机库无限卡加载 Bug。


3. EXE 补丁(patches/exe/)—— 57 字节完整逐指令解剖与进阶参考

当需要改动 aces.exe 内部某条分支判断或常量字符串时,我们使用 @wto/exepatch 的声明式补丁格式,做到零硬编码地址、跨小版本自动重定位。

3.1 完整无省略实例:patches/exe/battle/allow-local-host-bot-spawns/patch.jsonc

在 LocalMP 对局中,原版 BotSystem::changeUnit 在通过出生点检查后,会检查全局变量 g_multiplayer 是否为空(cmp qword ptr [rip + disp32], 0):单机试驾时 g_multiplayer == NULL,直接 jz 跳去调用 Unit::changeAircraft 刷出 AI;一旦处于 LocalMP 多人会话(g_multiplayer != NULL),零售客户端因为裁掉了专用服务器的脚本刷怪许可,落入后续分支只会打印 "spawn denied by scripts",导致整场对局一辆 AI 载具都刷不出来。

下面是仓库中 patches/exe/battle/allow-local-host-bot-spawns/patch.jsonc 的一字不差完整原文(pattern 共 57 字节,无任何省略号):

jsonc
// Let BotSystem::changeUnit spawn the AI players' vehicles on a LocalMP host (0x11b2c3a: the g_multiplayer
// null guard becomes a jump to the Unit::changeAircraft call at 0x11b314e).
// Why the exe: the build drops the dedicated server's script spawn permission, so with a multiplayer
// session the function only logs "spawn denied by scripts"; non-host sessions already return at its start.
// Without it: no AI vehicle ever spawns in a LocalMP battle.
{
  "id": "battle/allow-local-host-bot-spawns",
  "title": "Let BotSystem spawn AI vehicles on a LocalMP host",
  "features": [
    "K-AI opponents and teammates"
  ],
  "requires": [],
  "variants": [
    // Masked signature of BotSystem::changeUnit from the spawn point check (call 0x111a010)
    // to the g_multiplayer null guard, 0x3c bytes; rip-relative and branch targets are wildcards.
    // 2.61.0.37: unique hit at 0x11b2c14, edited instruction at +38 (0x11b2c3a).
    // spawn_call: where the null guard's jz goes (the Unit::changeAircraft call); the edit jumps there
    // unconditionally. The guard's rip displacement differs between builds, so it is a wildcard.
    {
      "written_for": "2.61.0.37",
      "locate": {
        "method": "signature",
        "section": ".text",
        "pattern": "48 8b 05 ?? ?? ?? ?? 48 8b 88 e0 03 00 00 48 8b 5c 24 20 48 89 da 4d 89 f0 e8 ?? ?? ?? ?? 84 c0 0f 84 ?? ?? ?? ?? 48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ?? 48 8b 54 24 20",
        "captures": {
          "spawn_call": {
            "offset": 48,
            "type": "rel32"
          }
        }
      },
      "edit": {
        "offset": 38,
        "asm": [
          "jmp {spawn_call}",
          "nop",
          "nop",
          "nop",
          "nop",
          "nop",
          "nop",
          "nop",
          "nop",
          "nop"
        ],
        "bytes": "e9 ?? ?? ?? ?? 90 90 90 90 90 90 90 90 90",
        "expect_original": "48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ??",
        "fixups": [
          {
            "at": 1,
            "type": "rel32",
            "target": "spawn_call"
          }
        ]
      }
    }
  ]
}

3.2 +0..+56 全部 57 字节逐指令拆解表

为什么 edit.offset 是 38?为什么 spawn_call 的 offset 是 48?为什么 fixups[0].at 又是 1?把这 57 个字节按 x86-64 指令逐条摊开,一眼就彻底明白了(以 2.61.0.37 命中起点 site = 0x11b2c14 为例):

相对 site 偏移长度pattern 中的十六进制字节对应的 x86-64 反汇编指令在补丁中扮演的角色
+0 .. +67 B48 8b 05 ?? ?? ?? ??mov rax, qword ptr [rip + disp32]前置上下文锚点;?? 通配随版本变化的全局变量 RIP 位移
+7 .. +137 B48 8b 88 e0 03 00 00mov rcx, qword ptr [rax + 0x3e0]前置上下文锚点
+14 .. +185 B48 8b 5c 24 20mov rbx, qword ptr [rsp + 0x20]前置上下文锚点
+19 .. +213 B48 89 damov rdx, rbx前置上下文锚点
+22 .. +243 B4d 89 f0mov r8, r14前置上下文锚点
+25 .. +295 Be8 ?? ?? ?? ??call rel32(出生点检查函数)前置上下文锚点;?? 通配被调函数相对距离
+30 .. +312 B84 c0test al, al前置上下文锚点
+32 .. +376 B0f 84 ?? ?? ?? ??jz rel32(无可用出生点则提前返回)前置上下文锚点;确保我们不会覆盖到前面的合法返回分支
+38 .. +458 B48 83 3d ?? ?? ?? ?? 00cmp qword ptr [rip + disp32], 0被改写区第 1 条指令(起点 edit.offset = 38):原版 g_multiplayer == 0 判空检查
+46 .. +516 B0f 84 ?? ?? ?? ??jz rel32(跳向 Unit::changeAircraft)被改写区第 2 条指令:操作码 0f 84 占 +46..+47,4 字节 rel32 位移位于 +48..+51,由 captures.spawn_call(offset: 48)动态读出跳转目标 RVA!
+52 .. +565 B48 8b 54 24 20mov rdx, qword ptr [rsp + 0x20]后置上下文锚点:锁死指令边界,确认 +51 之后紧跟预期的下一条指令

从上面这张表可以提炼出编写任何 EXE 补丁的 5 个核心要点:

  1. 首尾锚点保证 .text 全局唯一命中:单靠 48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ??(判空后条件跳转)在整个 aces.exe 里会撞上成百上千处;加上前后 +0..+37 与 +52..+56 的寄存器与调用序列后,80 MB 代码段里就只剩这唯一 1 处命中。
  2. edit.offset: 38 精准对齐被替换指令首字节:只改写 +38..+51 这两条指令(8 + 6 = 14 字节),前后的上下文锚点纹丝不动。
  3. captures.spawn_call 动态抠出跳转目的地:原 jz rel32 的 4 字节有符号位移位于 site + 48..51,未传 end 时默认指令结尾为 offset + 4 = 52,因此补丁引擎自动算出目标 RVA = site + 52 + disp32(在 2.61.0.37 上即 0x11b2c14 + 52 + disp32 = 0x11b314e)。哪怕下个版本目标函数挪到了别的地址,只要相对跳转还在,捕获出的目标就永远准确!
  4. expect_original、bytes 与 asm 三重互锁:expect_original(8 + 6 = 14 字节)与写入的 bytes(5 字节 e9 ?? ?? ?? ?? 无条件跳转 + 9 个 90 nop = 14 字节)长度必须严丝合缝相等;运行 wtotools check-patches 时还会调用汇编器把 asm 编译成机器码与 bytes 逐字节比对,杜绝手算机器码出错。
  5. 务必分清两套偏移基准点(新手头号易混点!):
    • edit.offset(38)和 locate.captures.*.offset(48)都是从 locate 匹配起点 site(+0)开始算的;
    • 而 edit.fixups[].at(1)和 edit.fixups[].end(默认 at + 4 = 5)是从 edit.bytes 的第 0 字节(即 site + edit.offset = site + 38)开始算的!因为 bytes 第 0 字节是 e9(jmp 操作码),紧跟其后的 4 个 ?? 洞口就在 at: 1,回填位移公式为 spawn_call - ((site + 38) + 5)。

3.3 EXE 与 Native 定位进阶参考(必读防坑指南)

(1)rel32 捕获的 "end" 陷阱:带尾随立即数的 RIP 相对寻址指令!

x86-64 CPU 计算 [rip + disp32] 内存地址时,基准点永远是整条指令结束处(下一条指令的首地址),而不是 disp32 这 4 个字节结束的位置!

  • 对于 mov rax, [rip + disp32](48 8b 05 ?? ?? ?? ??,共 7 字节)或 jz rel32(0f 84 ?? ?? ?? ??,共 6 字节),disp32 恰好位于指令最末尾,所以默认的 end = offset + 4 刚好等于指令结尾,无需写 "end"。
  • 但如果指令在 disp32 后面还跟着立即数操作数,默认 end 就会算错地址!例如单条指令: c6 05 ?? ?? ?? ?? 00 —— mov byte ptr [rip + disp32], 0(整条指令共 7 字节:c6 05 占 0..1,disp32 占 2..5,末尾立即数 00 占第 6 字节,指令在偏移 7 处结束)。如果你只写 { "offset": 2, "type": "rel32" },默认 end 会取 2 + 4 = 6,算出来的全局变量 RVA 就会偏小 1 个字节!此时必须显式加上 "end": 7:
    jsonc
    "captures": {
      "some_flag": { "offset": 2, "type": "rel32", "end": 7 }
    }

    仓库真实范例见 patches/native/local_mp_core.jsonc 的 disabled_slots_mask 站点:31 c0(+0..+1)后面紧跟 48 83 3d ?? ?? ?? ?? 00(+2..+9,cmp qword ptr [rip + disp32], 0),disp32 在 offset: 5,末尾还有 1 字节立即数 00(+9),因此显式声明了 "multiplayer": { "offset": 5, "type": "rel32", "end": 10 }。

(2)captures 支持的全部 7 种数值类型(packages/exepatch/src/captures.ts)
type字节宽度读取语义典型用途
"rel32"4 B(小端有符号)计算并返回 site + end + int32(即目标 RVA)捕获 call、jmp/jcc 跳转目标或 [rip + disp32] 全局变量地址
"u8"1 B(无符号)原样读取 0..255捕获短位移成员偏移(如 [r8 + 0x61] 中的 0x61)
"u16"2 B(小端无符号)原样读取 0..65535捕获 16 位消息号或协议常量(如 MPI 消息 ID)
"u32"4 B(小端无符号)原样读取 32 位无符号整数捕获常规 C++ 结构体大偏移(如 [rax + 0x6d8] 中的 0x6d8)或元素步长
"i8"1 B(有符号)原样读取 -128..127捕获带负号的单字节指针偏置(如循环步进指针向回偏移 -0x10)
"i16"2 B(小端有符号)原样读取 -32768..32767捕获 16 位有符号位移
"i32"4 B(小端有符号)原样读取 32 位有符号整数捕获可能为负数的 32 位有符号结构体/栈位移
(3)改写 .rdata 只读字符串的 "data" 写法

当你在 .rdata 数据段替换等长 ASCII 字符串(而不是改 .text 汇编指令)时,在 edit 中用 "data" 代替 "asm"(真实范例见 patches/exe/online/network-hook-library/patch.jsonc):

jsonc
"edit": {
  "offset": 0,
  "data": {
    "encoding": "ascii",
    "text": "wto_ws.dll"
  },
  "bytes": "77 74 6f 5f 77 73 2e 64 6c 6c 00",
  "expect_original": "57 53 32 5f 33 32 2e 64 6c 6c 00"
}

注意:bytes 与 expect_original 都包含末尾的 C 字符串终止零字节 00(共 11 字节),wtotools check-patches 会自动核对 "text" 的 ASCII 编码加终止零与 "bytes" 完全一致。


4. Native 模块(patches/native/ + native/wto-net/)—— 三种定位器与 6 文件完整串联教程

当需要在 wto_ws.dll 中用 C 语言挂载 MinHook 钩子或调用引擎内部函数时,不要在 C 源码里写死十六进制地址或游戏结构体偏移常量——所有值都由 patches/native/<模块>.jsonc 定位,经 wto_ws.cfg 传入 C 侧全局结构体 g_lmp。

4.1 三种代码定位方法详解(signature / string_ref / within)

  1. "method": "signature":在指定段(默认 ".text",可通过 "section" 覆盖)搜索全局唯一命中的字节特征码,支持 captures。
  2. "method": "string_ref"(packages/exepatch/src/locate/string-ref.ts,最抗编译器重排与小版本更新的利器!):先在 ".rdata"(或指定 "section")中找到以 \0 结尾的 UTF-8 字符串,再检索 .text 中所有加载该字符串地址的 7 字节 RIP 相对 lea 指令(48 8d / 4c 8d)。它共有 3 种工作模式:
    • 模式 A(默认 "target": "reference",不带 "pattern"):直接返回那条 7 字节 lea 指令本身的 RVA(可校验字节长度为 7);
    • 模式 B("target": "function"):通过 PE 异常表(.pdata)反查包含该 lea 引用的外层函数起始 RVA 并去重返回(注意:此模式可校验字节长度为 0,不能直接在它上面挂 captures,专门用来定位函数入口供 MinHook 挂钩或作为下方 within 的父锚点!);
    • 模式 C("pattern" + "lea_at",此时 "target" 必须保持默认 "reference"):围绕字符串 lea 匹配一段局部指令序列,要求加载该字符串的 7 字节 lea 恰好位于 pattern 内部偏移 lea_at 处,返回 pattern 起点 RVA——这样就能顺手用 captures 把紧挨着字符串引用的结构体字段偏移抠出来!(例如通过字段名 "kills" 直接抠出 MPlayer 里的击杀计数字段偏移)。
  3. "method": "within"(packages/exepatch/src/locate/within.ts):在同一个或被 requires 依赖的模块中已经先行定位好的站点 "in" 所属函数的 .pdata [begin, end) 范围内搜索 "pattern"。因为在单个函数内部搜索,哪怕只有一两条指令的短特征码也能唯一命中,彻底避免全程序撞码。

4.2 跟着 local_mp_scores 走完从 JSONC 到 C 落地的全部 6 个文件

假设我们要实现 LocalMP 局内记分牌分值读取模块 local_mp_scores(本地服务器把各事件得分写进任务配置的 customScoreParams 子块,客户端 MissionSettings::load 会把它拷进 MissionSettings 结构体内部某偏移处,但客户端自己从不读它;我们的 C 模块需要调用引擎的 DataBlock::getReal 从该偏移处读出分值)。看看这 6 个真实文件是怎么严丝合缝串起来的:

第 1 步:编写定位定义 patches/native/local_mp_scores.jsonc

文件名必须与 "module" 字段完全同名。由于我们要复用 local_mp_core.jsonc 里已经用 "string_ref"("string": "customScoreParams", "target": "function")定位好的函数 "mission_settings_load",在 "requires" 中声明 "local_mp_core":

jsonc
// Score table of a LocalMP battle (native/wto-net/src/local_mp_scores.c): the local server puts it
// in the mission's customScoreParams; the host reads it there.
// Without it: kills, assists and captures score nothing.
{
  "module": "local_mp_scores",
  "features": [
    "K-Kill, assist and capture scoring"
  ],
  "requires": [
    "local_mp_core"
  ],
  "sites": {
    // DataBlock::getReal wrapper.
    // 2.61.0.37: 0x5445270
    "datablock_get_real": {
      "variants": [
        {
          "written_for": "2.61.0.37",
          "locate": {
            "method": "signature",
            "pattern": "48 83 ec 28 f3 0f 11 54 24 24 4c 8d 44 24 24 e8 ?? ?? ?? ?? 90 48 83 c4 28 c3 cc cc cc cc cc cc 56 57 53 48 83 ec 30 48 89 d7 48 89 ce 48 8d 15"
          }
        }
      ]
    },
    // MissionSettings customScoreParams copy.
    // 2.61.0.37: 0x126d762 (lea rcx, [rax + 0x6d8]; mov eax, dword ptr [r13 + 0x10]; cmp eax, -1; ...)
    "mission_score_params": {
      "variants": [
        {
          "written_for": "2.61.0.37",
          "locate": {
            "method": "within",
            "in": "mission_settings_load",
            "pattern": "48 8d 88 ?? ?? ?? ?? 41 8b 45 10 83 f8 ff 74 ?? 45 0f b7 45 0e 46 8d 0c 00 31 d2 44 39 c8 0f 8d ?? ?? ?? ?? ff c7 4d 8b 4d 00 45 8b 51 5c 4d 01 d1 49 81 c1 90 00 00 00 41 bb ff ff ff 3f 45 31 d2 66 66 66 66 2e 0f 1f 84 00 00 00 00 00 42 8d 34 10 48 c1 e6 05 41 8b 5c 31 08 44 21 db 39 fb 74 ?? 41 ff c2 45 39 d0 75 ?? eb ?? 41 0f b7 45 0e 31 d2 85 c0 74 ?? ff c7 4d 8b 4d 18 4d 8b 01 45 8b 49 08 44 8d 14 c5 00 00 00 00 45 29 d1 41 ba ff ff ff 3f 45 31 db 66 0f 1f 44 00 00 4b 8b 34 08 8b 76 08 44 21 d6 39 fe 74 ?? 41 ff c3 49 83 c1 08 44 39 d8 75 ?? eb ?? 49 01 f1 31 d2 45 39 c2 49 0f 42 d1 eb ?? 41 39 c3 73 ?? 44 89 c8 49 8b 14 00 eb ?? 31 d2 48 85 d2 49 0f 44 d6 31 f6 45 31 c0 e8 ?? ?? ?? ?? 49 8b 5d 00 bf ff ff ff ff 48 85 db 74 ?? 48 8d 0d ?? ?? ?? ?? ba 16 00 00 00",
            "captures": {
              "custom_score_params": {
                "offset": 3,
                "type": "u32"
              }
            }
          }
        }
      ]
    }
  }
}

看 mission_score_params 首条指令 48 8d 88 ?? ?? ?? ??(lea rcx, [rax + disp32]):前 3 字节是 48 8d 88,第 3..6 字节就是 MissionSettings 里的结构体偏移,因此 "offset": 3, "type": "u32" 直接把 0x6d8 抠了出来!

第 2 步:构建器自动生成 <离线副本>/win64/wto_ws.cfg(packages/patcher/src/native/)

构建副本时,native-resolve.ts 与 native-settings.ts 会把当前 aces.exe 的 PE 头指纹连同所有已就绪模块的 <站点> 与 <站点>.<捕获名> 写入 win64/wto_ws.cfg:

ini
port=27015
exe.time_date_stamp=0x67e5a1b2
exe.size_of_image=0x83f4000
native.datablock_get_real=0x5445270
native.mission_score_params=0x126d762
native.mission_score_params.custom_score_params=0x6d8
第 3 步:在 native/wto-net/src/local_mp_values.h 声明 LmpValues 字段

地址一律声明为 uint8_t *,无符号偏移/大小声明为 size_t(有符号位移声明为 ptrdiff_t):

c
typedef struct LmpValues {
    /* ... 其他模块字段 ... */

    /* local_mp_scores */
    uint8_t *datablock_get_real;
    size_t mis_custom_score_params;
} LmpValues;

extern LmpValues g_lmp;
第 4 步:在 native/wto-net/src/local_mp_values.c 绑定 SPECS[] 映射表

local_mp_values.c 通过三个宏把 wto_ws.cfg 里的键名映射到 g_lmp 的成员:

  • A(module, name, field)(LMP_ADDRESS):读取 RVA 后自动加上当次进程基址 (uint8_t *)GetModuleHandleW(NULL) + value,存成可直接调用的运行时指针;
  • O(module, name, field)(LMP_OFFSET):存为无符号 size_t 结构体偏移或步长;
  • S(module, name, field)(LMP_SIGNED):存为有符号 ptrdiff_t 位移;
  • 如果某个复合偏移需要由两个捕获值相加减(客户端没有单独访问它的指令),则写在同文件的 derive_values() 中。
c
#define SCORES "local_mp_scores"

static const LmpValueSpec SPECS[] = {
    /* ... */
    A(SCORES, "datablock_get_real", datablock_get_real),
    O(SCORES, "mission_score_params.custom_score_params", mis_custom_score_params),
    /* ... */
};
第 5 步:在 native/wto-net/src/local_mp_offsets.h 定义可读偏移宏
c
#define LMP_MIS_OFF_CUSTOM_SCORE_PARAMS (g_lmp.mis_custom_score_params)
第 6 步:实现 local_mp_scores.c、注册到 local_mp_core.c 并加入 build.ps1
  • 在 local_mp_scores.c 中只读取 g_lmp 与 local_mp_core 导出的公共指针:
    c
    typedef float (__fastcall *DataBlockGetRealFn)(const void *blk, const char *name, float def);
    static DataBlockGetRealFn fn_datablock_get_real;
    
    float local_mp_score_param(const char *key)
    {
        if (fn_datablock_get_real == NULL || g_local_mp_mission_settings == NULL || key == NULL)
            return 0.0f;
        return fn_datablock_get_real(g_local_mp_mission_settings + LMP_MIS_OFF_CUSTOM_SCORE_PARAMS, key, 0.0f);
    }
    
    int install_local_mp_score_reader(void)
    {
        fn_datablock_get_real = (DataBlockGetRealFn)g_lmp.datablock_get_real;
        return 1;
    }
  • 在 local_mp_core.c 中,启动时 install_local_mp_hooks() 会先用 config_native_matches_executable() 核对当前运行中 aces.exe 的 PE TimeDateStamp 与 SizeOfImage 是否与 wto_ws.cfg 完全一致(不一致则整套 LocalMP 桥接器安全关闭),然后按依赖顺序遍历 MODULES[] 数组,对每个模块先跑 lmp_values_load(MODULES[i].name) 确认值一个不少,再调用安装函数并在最后统一 MH_ApplyQueued()。
  • 如果新增了一个全新的 .c 源文件:除了在 local_mp_internal.h 声明安装函数并加入 local_mp_core.c 的 MODULES[],还必须把该 .c 文件路径加进 native/wto-net/build.ps1 的 $sources 数组!
  • 多模块共享钩子:如果两个模块都需要拦截或调用同一个引擎函数(例如 Unit::onEvent 同时被 local_mp_damage_notifications 和 local_mp_air_events 使用),请把站点放进 local_mp_core.jsonc 统一解析分发,避免在两个模块里用 MinHook 重复挂钩同一个目标地址。

5. 适配新版本客户端(标准四步流程)

每当《战争雷霆》发布小版本更新(例如 2.61.0.37 → 2.61.0.58)时,按下面四步跟进适配:

  1. 对只读原版客户端运行版本核对脚本:
    powershell
     node scripts/record-game-version.ts --game "<原版目录>"

    该脚本会只读扫描原版客户端,一次性跑完所有 patches/exe/、patches/gui/ 和 patches/native/ 的定位测试。如果三条核心安全锁(ESSENTIAL_FEATURES)中有补丁失效,脚本会直接拒绝生成版本记录并列出阻断项;若核心安全锁全部命中,则会写出 patches/versions/<版本号>.jsonc 并打印所有 unavailable(暂不可用)的非关键补丁/模块。

  2. 排查失配项并追加新 variant: 打开失配的补丁或原生站点,用第 1 节的 Node 拆包脚本或 tools/re/cli.py(优先用 find-string 找不变的字符串锚点!)查看新版本原版文件发生了什么变化。保留原有旧版本的 variant 不动,在 variants 数组中追加一条 "written_for": "<新版本号>" 的新写法。
  3. 跑完完整工具链核对: 重新运行 record-game-version.ts 确认 unavailable 清零,并依次跑通:
    • .\.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"
    • 若改了 native/wto-net/,运行 powershell -NoProfile -File .\native\wto-net\build.ps1
    • 用临时输出目录跑一遍 node scripts/build-game-copy.ts 确认副本完整生成。
  4. 隔离副本实机进游戏验收后再提交 patches/versions/<版本号>.jsonc: 启动器依赖 patches/versions/<版本号>.jsonc 向玩家展示「该客户端版本已核对通过」。请在隔离副本里实际登录进机库并完成一局 LocalMP 对局验收后,再提交 patches/versions/<版本号>.jsonc,不要仅凭命令行脚本通过就直接入库。

新建补丁时可直接复制空白脚手架模板:dev-docs/templates/gui/、dev-docs/templates/exe/、dev-docs/templates/native/。

03 · Patch Authoring, Byte Anatomy & Full Native Wiring

This handbook covers authoring client patches (Quirrel UI scripts, aces.exe machine-code/data patches, and wto_ws.dll LocalMP native modules) and adapting WTOffline to new War Thunder client builds.

Check first before touching the client: Read Development Rules — Section 1 and verify that the issue genuinely cannot be solved in apps/server or via stock mission/config BLK fields. Client patches are strictly for code paths that retail client builds omit or hardcode.


1. Step 0: Unpacking Stock Archives, Reading Binary BLK, Disassembling aces.exe, and Choosing a Patch Type

Never modify any file inside your official stock installation. Using @wto/vromfs, @wto/blk, and tools/re/cli.py, you can inspect every stock script, binary .blk, and aces.exe function purely in memory.

1.1 Inspect .nut Scripts or Binary .blk Files Inside Stock .vromfs.bin Archives

Run these one-liners from the repository root (replacing <stock-dir> with your read-only official War Thunder path):

powershell
# Example A: List matching .nut paths inside gui.vromfs.bin and print a stock Quirrel script
node --input-type=module -e "
import { readFileSync } from 'node:fs';
import { getFile, readArchive } from '@wto/vromfs';
const archive = readArchive(readFileSync(String.raw`<stock-dir>\gui.vromfs.bin`));
console.log([...archive.files.keys()].filter((p) => p.includes('tutorial')));
console.log(Buffer.from(getFile(archive, 'scripts/tutorials/nexttutorialhandler.nut')).toString('utf8'));
"

# Example B: Decode a slimmed binary .blk from char.vromfs.bin (or aces.vromfs.bin) as readable text
# (automatically loads the archive's shared name map `nm` and optional `.dict` zstd dictionary)
node --input-type=module -e "
import { readFileSync } from 'node:fs';
import { decodeBlk, formatBlkText, parseSharedNameMap } from '@wto/blk';
import { getFile, NAME_MAP_PATH, readArchive } from '@wto/vromfs';
const archive = readArchive(readFileSync(String.raw`<stock-dir>\char.vromfs.bin`));
const dictionary = [...archive.files.entries()].find(([p]) => p.endsWith('.dict'))?.[1];
const names = archive.files.has(NAME_MAP_PATH) ? parseSharedNameMap(getFile(archive, NAME_MAP_PATH), dictionary).names : [];
const blk = decodeBlk(getFile(archive, 'config/pve_awards.blk'), { names, dictionary });
console.log(formatBlkText(blk).slice(0, 2000));
"

1.2 Static Reverse Engineering on aces.exe with tools/re/cli.py

Once your .venv is installed (pip install -e ./tools; see Environment Setup), use tools/re/cli.py to locate strings, cross-references, callers, and disassembly (all addresses are hex RVAs, and always pass --exe "<stock-dir>\win64\aces.exe" explicitly):

powershell
# 1. Find where a C string lives in .rdata and every rip-relative `lea` instruction + function referencing it
.\.venv\Scripts\python.exe tools\re\cli.py find-string "customScoreParams" --exe "<stock-dir>\win64\aces.exe"

# 2. Find every instruction with a rip-relative reference to a target RVA (e.g., a global pointer)
.\.venv\Scripts\python.exe tools\re\cli.py xref 0x7bad2f0 --exe "<stock-dir>\win64\aces.exe"

# 3. Find every direct `call` or `jmp` targeting a function RVA
.\.venv\Scripts\python.exe tools\re\cli.py callers 0x5445270 --exe "<stock-dir>\win64\aces.exe"

# 4. Disassemble an RVA with string and call annotations (defaults to 40 instructions; supports --count, --end, or --function)
.\.venv\Scripts\python.exe tools\re\cli.py disasm 0x11b2c14 --count 20 --exe "<stock-dir>\win64\aces.exe"
.\.venv\Scripts\python.exe tools\re\cli.py disasm 0x126d762 --function --exe "<stock-dir>\win64\aces.exe"

1.3 Choosing the Right Patch Type & Universal Conventions

What needs changingWhere it belongsReal codebase example
Hangar, modal, store, or debriefing UI scripts (Quirrel .nut)patches/gui/<domain>/<name>/patches/gui/tutorials/immediate-save-skip-tutorial/
A few machine instructions or a constant .rdata string in aces.exepatches/exe/<domain>/<name>/patches/exe/battle/allow-local-host-bot-spawns/
In-process C hooks restoring LocalMP battle host logic (wto_ws.dll)patches/native/<module>.jsonc + native/wto-net/src/<module>.cpatches/native/local_mp_scores.jsonc
Static archive config rewrites (network.blk, shop.blk, gui.blk)packages/patcher/src/ (not under patches/)packages/patcher/src/char-pack.ts, main-pack.ts

Four universal rules across all patches/ definitions:

  1. One behavior per directory/module—never bundle unrelated fixes into a single patch definition.
  2. Start every patch.jsonc / <module>.jsonc with a 3-line English comment:
    • Line 1: What the patch changes;
    • Line 2 (Why the client: / Why the exe:): Why the local server or stock config cannot provide it;
    • Line 3 (Without it:): What breaks for the player if this patch is missing.
  3. Write title and features in English (note: a few early historical patches still carry Chinese title strings, but all new patches must write title in English), reusing existing A-..K- inventory tags (Glossary — Section 7).
  4. Exact single-variant, single-site match: On any given client build, exactly one variant must apply, and its locator must hit exactly one site; zero hits or multiple hits fail safely rather than corrupting the output copy.

2. GUI Patches (patches/gui/) — Full 3-File Example & Strict Schema Rules

2.1 Complete Real Example: tutorials/immediate-save-skip-tutorial

In stock scripts/tutorials/nexttutorialhandler.nut, when a player ticks "Do not ask me again" on the tutorial prompt, the script calls saveLocalByAccount(skipTutorialBitmaskId, skipTutorial) with no third argument. That falls back to saveProfile(), which waits on a 60-second debounce timer before sending anything to the server—so closing or crashing within 60 seconds loses the opt-out and brings the prompt back on next login. Because apps/server cannot speed up a client-side timer before a request is ever sent, this patch passes @() save_profile(false) as the immediate-save callback.

Here are all three files in patches/gui/tutorials/immediate-save-skip-tutorial/ verbatim (note: this early patch kept a Chinese title, whereas new patches should use an English title such as "Save tutorial opt-out immediately after ticking 'do not ask again'"):

1. patch.jsonc:

jsonc
// Save the tutorial opt-out immediately via save_profile(false).
// Why the client: the stock callback waits 60 s before writing or sending anything to the service.
// Without it: a crash within 60 s of ticking "do not ask again" brings the tutorial prompt back.
{
  "id": "tutorials/immediate-save-skip-tutorial",
  "title": "新手教程询问窗勾选「不再询问」后立即落盘保存",
  "features": [
    "A-Tutorials"
  ],
  "variants": [
    {
      "written_for": "2.61.0.37",
      "file": "scripts/tutorials/nexttutorialhandler.nut",
      "edits": [
        {
          "find": "find.nut",
          "replace": "replace.nut"
        }
      ]
    }
  ]
}

2. find.nut (the smallest verbatim stock snippet occurring exactly once in the target .nut file, preserving exact indentation):

squirrel
    skipTutorial = stdMath.change_bit(skipTutorial, this.checkIdx, obj.getValue())
    saveLocalByAccount(skipTutorialBitmaskId, skipTutorial)
  }

3. replace.nut (the replacement text):

squirrel
    skipTutorial = stdMath.change_bit(skipTutorial, this.checkIdx, obj.getValue())
    saveLocalByAccount(skipTutorialBitmaskId, skipTutorial, @() save_profile(false))
  }

2.2 Strict gui-patch-definition.ts Schema Whitelist & Authoring Rules

packages/patcher/src/gui-patch-definition.ts calls rejectUnknownKeys at every level—any extra property immediately throws DefinitionError:

  • Top-level keys are strictly id, title, features, variants.

    Watch out: GUI patch.jsonc does NOT have a requires key! Do not copy "requires": [] from an EXE patch into patches/gui/, or loadGuiPatches will throw DefinitionError!

  • variants[] keys are strictly written_for, file, edits. file must be the exact lowercase, /-separated relative path inside gui.vromfs.bin without a leading slash (e.g., "scripts/tutorials/nexttutorialhandler.nut"—archive paths are all lowercased!).
  • edits[] keys are strictly find, replace, naming plain filenames directly inside the patch folder (no / or \ subdirectories).
  • Line endings & exact-once matching: readFragment strips any UTF-8 BOM, normalizes \r\n to \n, and removes a single trailing newline at EOF (so Git autocrlf never breaks patches). find.nut must match exactly once in the target script.
  • {{LOCAL_ENDPOINT}} placeholder: Whenever replacement Quirrel code needs the local server address, write {{LOCAL_ENDPOINT}}; gui-pack.ts expands it to 127.0.0.1:<port> during copy builds.
  • Adding a variant for a newer build: Never edit an existing find.nut in a way that breaks older supported builds—create find-58.nut / replace-58.nut and append a new entry to variants.
  • Mandatory sq.exe bytecode check: Every change under patches/gui/ must pass:
    powershell
    .\.venv\Scripts\python.exe -m wtotools.cli check-gui --gui "<stock-dir>\gui.vromfs.bin" --sq "build\quirrel-cli\bin\Release\sq.exe"

    check-gui applies all GUI patches in memory and runs sq.exe (compilestring) on every patched .nut script, catching lexical binding clashes with top-of-file from ... import * imports, unbound forward calls, and reserved keywords like base that otherwise hang the client forever on "Loading...".


3. EXE Patches (patches/exe/) — Full 57-Byte Anatomy & Reference

When modifying instructions or constant data inside aces.exe, @wto/exepatch lets you express edits with zero hardcoded addresses so patches survive minor game updates automatically.

3.1 Un-Elided Real Example: patches/exe/battle/allow-local-host-bot-spawns/patch.jsonc

In BotSystem::changeUnit, after verifying a valid spawn point, stock aces.exe checks whether g_multiplayer is null (cmp qword ptr [rip + disp32], 0): in single-player test flights (g_multiplayer == NULL), jz jumps straight to the Unit::changeAircraft call to spawn the AI unit; in a LocalMP session (g_multiplayer != NULL), because retail aces.exe strips the Dedicated Server's script spawn permission, execution falls through to "spawn denied by scripts" and no AI vehicle ever spawns.

Here is the complete, un-elided patches/exe/battle/allow-local-host-bot-spawns/patch.jsonc (all 57 pattern bytes, zero ...):

jsonc
// Let BotSystem::changeUnit spawn the AI players' vehicles on a LocalMP host (0x11b2c3a: the g_multiplayer
// null guard becomes a jump to the Unit::changeAircraft call at 0x11b314e).
// Why the exe: the build drops the dedicated server's script spawn permission, so with a multiplayer
// session the function only logs "spawn denied by scripts"; non-host sessions already return at its start.
// Without it: no AI vehicle ever spawns in a LocalMP battle.
{
  "id": "battle/allow-local-host-bot-spawns",
  "title": "Let BotSystem spawn AI vehicles on a LocalMP host",
  "features": [
    "K-AI opponents and teammates"
  ],
  "requires": [],
  "variants": [
    // Masked signature of BotSystem::changeUnit from the spawn point check (call 0x111a010)
    // to the g_multiplayer null guard, 0x3c bytes; rip-relative and branch targets are wildcards.
    // 2.61.0.37: unique hit at 0x11b2c14, edited instruction at +38 (0x11b2c3a).
    // spawn_call: where the null guard's jz goes (the Unit::changeAircraft call); the edit jumps there
    // unconditionally. The guard's rip displacement differs between builds, so it is a wildcard.
    {
      "written_for": "2.61.0.37",
      "locate": {
        "method": "signature",
        "section": ".text",
        "pattern": "48 8b 05 ?? ?? ?? ?? 48 8b 88 e0 03 00 00 48 8b 5c 24 20 48 89 da 4d 89 f0 e8 ?? ?? ?? ?? 84 c0 0f 84 ?? ?? ?? ?? 48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ?? 48 8b 54 24 20",
        "captures": {
          "spawn_call": {
            "offset": 48,
            "type": "rel32"
          }
        }
      },
      "edit": {
        "offset": 38,
        "asm": [
          "jmp {spawn_call}",
          "nop",
          "nop",
          "nop",
          "nop",
          "nop",
          "nop",
          "nop",
          "nop",
          "nop"
        ],
        "bytes": "e9 ?? ?? ?? ?? 90 90 90 90 90 90 90 90 90",
        "expect_original": "48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ??",
        "fixups": [
          {
            "at": 1,
            "type": "rel32",
            "target": "spawn_call"
          }
        ]
      }
    }
  ]
}

3.2 Instruction-by-Instruction Breakdown (+0..+56, All 57 Bytes)

Breaking down every byte from the match start site (0x11b2c14 on 2.61.0.37) makes every offset number self-evident:

Offset from siteSizeHex bytes in patternx86-64 instructionRole in this patch
+0 .. +67 B48 8b 05 ?? ?? ?? ??mov rax, qword ptr [rip + disp32]Leading context anchor (?? masks build-varying RIP displacement)
+7 .. +137 B48 8b 88 e0 03 00 00mov rcx, qword ptr [rax + 0x3e0]Leading context anchor
+14 .. +185 B48 8b 5c 24 20mov rbx, qword ptr [rsp + 0x20]Leading context anchor
+19 .. +213 B48 89 damov rdx, rbxLeading context anchor
+22 .. +243 B4d 89 f0mov r8, r14Leading context anchor
+25 .. +295 Be8 ?? ?? ?? ??call rel32 (spawn-point check)Leading context anchor (?? masks call displacement)
+30 .. +312 B84 c0test al, alLeading context anchor
+32 .. +376 B0f 84 ?? ?? ?? ??jz rel32 (early-out if spawn check failed)Leading context anchor (kept intact!)
+38 .. +458 B48 83 3d ?? ?? ?? ?? 00cmp qword ptr [rip + disp32], 0Edited instruction #1 (edit.offset = 38): the g_multiplayer null guard
+46 .. +516 B0f 84 ?? ?? ?? ??jz rel32 (to Unit::changeAircraft call)Edited instruction #2: 2-byte opcode 0f 84 (+46..+47) + 4-byte rel32 at +48..+51, captured as spawn_call (offset: 48)!
+52 .. +565 B48 8b 54 24 20mov rdx, qword ptr [rsp + 0x20]Trailing context anchor verifying exact instruction boundary after +51

Notice the five key mechanics working together here:

  1. Surrounding anchors guarantee a unique hit: 48 83 3d ?? ?? ?? ?? 00 0f 84 ?? ?? ?? ?? alone appears hundreds of times across .text, whereas anchoring +0..+37 before it and +52..+56 after it narrows 80 MB of code down to a single unambiguous hit.
  2. edit.offset: 38 leaves the anchors untouched: Only the 14 bytes at +38..+51 are overwritten.
  3. captures.spawn_call (offset: 48, type: "rel32") resolves the jump target dynamically: The jz instruction's 4-byte displacement sits at +48..+51, so default end = 48 + 4 = 52, yielding target RVA = site + 52 + disp32 (0x11b314e on 2.61.0.37). Even when future builds shift Unit::changeAircraft, the captured RVA updates automatically.
  4. Exact 14-byte parity & asm verification: expect_original is 8 + 6 = 14 bytes and bytes is 5 (e9 ?? ?? ?? ??) + 9 (90 NOPs) = 14 bytes. Running wtotools check-patches assembles asm and verifies byte-for-byte agreement with bytes.
  5. Crucial offset base distinction (most common beginner mistake!):
    • edit.offset (38) and locate.captures.*.offset (48) count from site (+0 of locate.pattern);
    • edit.fixups[].at (1) and edit.fixups[].end (default at + 4 = 5) count from byte 0 of edit.bytes (site + 38), right after the e9 opcode!

3.3 Reference: The rel32 "end" Trap, All 7 Capture Types & .rdata Edits

(1) The rel32 "end" Trap (Instructions with Trailing Immediate Bytes!)

On x86-64, RIP-relative addressing always adds disp32 to the address of the next instruction (where the current instruction ends), NOT where the 4-byte disp32 ends!

  • For mov rax, [rip + disp32] (48 8b 05 ?? ?? ?? ??, 7 B) or jz rel32 (0f 84 ?? ?? ?? ??, 6 B), disp32 is at the very end of the instruction, so the default end = offset + 4 matches the instruction end automatically.
  • However, when an instruction has trailing immediate byte(s) after disp32, omitting "end" resolves the wrong address! Take c6 05 ?? ?? ?? ?? 00 (mov byte ptr [rip + disp32], 0): the instruction is 7 bytes total (c6 05 at 0..1, disp32 at 2..5, trailing immediate 00 at 6, ending at 7). Writing { "offset": 2, "type": "rel32" } defaults end to 2 + 4 = 6, landing 1 byte before the real global variable! You must pass "end": 7:
    jsonc
    "captures": {
      "some_flag": { "offset": 2, "type": "rel32", "end": 7 }
    }

    For a real example in the repo, see disabled_slots_mask.multiplayer in patches/native/local_mp_core.jsonc: after 31 c0 (+0..+1), 48 83 3d ?? ?? ?? ?? 00 (cmp qword ptr [rip + disp32], 0) spans +2..+9 with disp32 at offset: 5 and trailing 00 at +9, so it specifies "end": 10.

(2) All 7 Capture Types (packages/exepatch/src/captures.ts)
typeWidthHow it is readTypical use
"rel32"4 B (signed LE)Computes target RVA = site + end + int32Target of call, jmp/jcc, or [rip + disp32] global variable
"u8"1 B (unsigned)Raw 0..255Compact 8-bit struct field offset (e.g., [r8 + 0x61])
"u16"2 B (unsigned LE)Raw 0..6553516-bit wire/MPI message IDs
"u32"4 B (unsigned LE)Raw 32-bit unsigned integerStandard C++ struct member offsets (e.g., [rax + 0x6d8]) or array strides
"i8"1 B (signed)Raw -128..127Signed 1-byte pointer biases in loop iterators
"i16"2 B (signed LE)Raw -32768..32767Signed 16-bit displacements
"i32"4 B (signed LE)Raw 32-bit signed integerSigned 32-bit stack or struct displacements
(3) Constant String / Data Edits in .rdata

When replacing a fixed-length string in .rdata instead of assembly instructions, use "data" in place of "asm" (real example: patches/exe/online/network-hook-library/patch.jsonc):

jsonc
"edit": {
  "offset": 0,
  "data": {
    "encoding": "ascii",
    "text": "wto_ws.dll"
  },
  "bytes": "77 74 6f 5f 77 73 2e 64 6c 6c 00",
  "expect_original": "57 53 32 5f 33 32 2e 64 6c 6c 00"
}

Both bytes and expect_original include the terminating 00 byte (11 bytes total), and wtotools check-patches verifies that data encodes identically to bytes.


4. Native Modules (patches/native/ + native/wto-net/) — Locators & Complete 6-File Wiring Walkthrough

When writing MinHook detours or calling engine functions in wto_ws.dll, never put a single build-specific RVA or game struct offset in C code. Instead, declare sites in patches/native/<module>.jsonc, let the patcher emit resolved hex values into win64/wto_ws.cfg, and read them in C from extern LmpValues g_lmp.

4.1 All Three Locate Methods (signature, string_ref, within)

  1. "method": "signature": Scans ".text" (or a specified "section") for a unique byte pattern, supporting captures.
  2. "method": "string_ref" (packages/exepatch/src/locate/string-ref.ts — most resilient across compiler codegen shifts!): Finds UTF-8 string + \0 in ".rdata" (or "section") and locates 7-byte RIP-relative lea (48 8d / 4c 8d) instructions loading that string in .text. Supports three modes:
    • Mode A ("target": "reference", default without "pattern"): Returns the RVA of the 7-byte lea instruction itself (checked length = 7 bytes);
    • Mode B ("target": "function"): Looks up the enclosing function's start RVA in the PE .pdata exception directory (checked length = 0, so no direct captures—ideal for locating function entry points to hook or use as within anchors);
    • Mode C ("pattern" + "lea_at", with default "target": "reference"): Matches pattern around the string reference where the 7-byte lea sits at byte offset lea_at, returning the pattern start RVA so captures can read adjacent struct offsets right next to the string reference!
  3. "method": "within" (packages/exepatch/src/locate/within.ts): Searches pattern strictly within the [begin, end) PE .pdata bounds of an already-resolved site named in "in" (from an earlier site in the same module or a requires module), allowing short field-access patterns to match uniquely inside one function.

4.2 Complete 6-File Wiring Walkthrough: local_mp_scores

Here is how local_mp_scores (which reads per-event scoreboard points placed by apps/server into MissionSettings.customScoreParams) connects end-to-end across all 6 real files:

File 1: patches/native/local_mp_scores.jsonc

The filename must match "module". Because "mission_settings_load" is already resolved via string_ref ("string": "customScoreParams", "target": "function") in local_mp_core.jsonc, "local_mp_scores" lists "local_mp_core" in "requires" and searches inside "mission_settings_load" using "within":

jsonc
// Score table of a LocalMP battle (native/wto-net/src/local_mp_scores.c): the local server puts it
// in the mission's customScoreParams; the host reads it there.
// Without it: kills, assists and captures score nothing.
{
  "module": "local_mp_scores",
  "features": [
    "K-Kill, assist and capture scoring"
  ],
  "requires": [
    "local_mp_core"
  ],
  "sites": {
    // DataBlock::getReal wrapper.
    // 2.61.0.37: 0x5445270
    "datablock_get_real": {
      "variants": [
        {
          "written_for": "2.61.0.37",
          "locate": {
            "method": "signature",
            "pattern": "48 83 ec 28 f3 0f 11 54 24 24 4c 8d 44 24 24 e8 ?? ?? ?? ?? 90 48 83 c4 28 c3 cc cc cc cc cc cc 56 57 53 48 83 ec 30 48 89 d7 48 89 ce 48 8d 15"
          }
        }
      ]
    },
    // MissionSettings customScoreParams copy.
    // 2.61.0.37: 0x126d762 (lea rcx, [rax + 0x6d8]; mov eax, dword ptr [r13 + 0x10]; cmp eax, -1; ...)
    "mission_score_params": {
      "variants": [
        {
          "written_for": "2.61.0.37",
          "locate": {
            "method": "within",
            "in": "mission_settings_load",
            "pattern": "48 8d 88 ?? ?? ?? ?? 41 8b 45 10 83 f8 ff 74 ?? 45 0f b7 45 0e 46 8d 0c 00 31 d2 44 39 c8 0f 8d ?? ?? ?? ?? ff c7 4d 8b 4d 00 45 8b 51 5c 4d 01 d1 49 81 c1 90 00 00 00 41 bb ff ff ff 3f 45 31 d2 66 66 66 66 2e 0f 1f 84 00 00 00 00 00 42 8d 34 10 48 c1 e6 05 41 8b 5c 31 08 44 21 db 39 fb 74 ?? 41 ff c2 45 39 d0 75 ?? eb ?? 41 0f b7 45 0e 31 d2 85 c0 74 ?? ff c7 4d 8b 4d 18 4d 8b 01 45 8b 49 08 44 8d 14 c5 00 00 00 00 45 29 d1 41 ba ff ff ff 3f 45 31 db 66 0f 1f 44 00 00 4b 8b 34 08 8b 76 08 44 21 d6 39 fe 74 ?? 41 ff c3 49 83 c1 08 44 39 d8 75 ?? eb ?? 49 01 f1 31 d2 45 39 c2 49 0f 42 d1 eb ?? 41 39 c3 73 ?? 44 89 c8 49 8b 14 00 eb ?? 31 d2 48 85 d2 49 0f 44 d6 31 f6 45 31 c0 e8 ?? ?? ?? ?? 49 8b 5d 00 bf ff ff ff ff 48 85 db 74 ?? 48 8d 0d ?? ?? ?? ?? ba 16 00 00 00",
            "captures": {
              "custom_score_params": {
                "offset": 3,
                "type": "u32"
              }
            }
          }
        }
      ]
    }
  }
}

In 48 8d 88 ?? ?? ?? ?? (lea rcx, [rax + disp32]), bytes 0..2 are 48 8d 88 and bytes 3..6 hold the struct offset (0x6d8 on 2.61.0.37), captured via "offset": 3, "type": "u32".

File 2: Generated <copy>/win64/wto_ws.cfg (packages/patcher/src/native/native-settings.ts)

During copy builds, the patcher writes the executable's PE identity stamps alongside <site> and <site>.<capture> entries for all completely resolved modules:

ini
port=27015
exe.time_date_stamp=0x67e5a1b2
exe.size_of_image=0x83f4000
native.datablock_get_real=0x5445270
native.mission_score_params=0x126d762
native.mission_score_params.custom_score_params=0x6d8
File 3: native/wto-net/src/local_mp_values.h

Add pointer (uint8_t *), unsigned offset (size_t), or signed displacement (ptrdiff_t) fields to struct LmpValues:

c
typedef struct LmpValues {
    /* ... other modules ... */

    /* local_mp_scores */
    uint8_t *datablock_get_real;
    size_t mis_custom_score_params;
} LmpValues;

extern LmpValues g_lmp;
File 4: native/wto-net/src/local_mp_values.c

Wire the wto_ws.cfg keys into SPECS[] using the three storage macros:

  • A(module, name, field) (LMP_ADDRESS): computes (uint8_t *)GetModuleHandleW(NULL) + rva and stores the live process pointer;
  • O(module, name, field) (LMP_OFFSET): stores an unsigned size_t struct offset or stride;
  • S(module, name, field) (LMP_SIGNED): stores a signed ptrdiff_t displacement;
  • Use derive_values() in the same file when a relative offset must be computed from two captured values (e.g., subtracting econ_change_req from an outer econ_req_* offset).
c
#define SCORES "local_mp_scores"

static const LmpValueSpec SPECS[] = {
    /* ... */
    A(SCORES, "datablock_get_real", datablock_get_real),
    O(SCORES, "mission_score_params.custom_score_params", mis_custom_score_params),
    /* ... */
};
File 5: native/wto-net/src/local_mp_offsets.h

Expose a descriptive macro backed by g_lmp:

c
#define LMP_MIS_OFF_CUSTOM_SCORE_PARAMS (g_lmp.mis_custom_score_params)
File 6: local_mp_scores.c, local_mp_core.c & native/wto-net/build.ps1
  • Consume the resolved function and offset in local_mp_scores.c:
    c
    typedef float (__fastcall *DataBlockGetRealFn)(const void *blk, const char *name, float def);
    static DataBlockGetRealFn fn_datablock_get_real;
    
    float local_mp_score_param(const char *key)
    {
        if (fn_datablock_get_real == NULL || g_local_mp_mission_settings == NULL || key == NULL)
            return 0.0f;
        return fn_datablock_get_real(g_local_mp_mission_settings + LMP_MIS_OFF_CUSTOM_SCORE_PARAMS, key, 0.0f);
    }
    
    int install_local_mp_score_reader(void)
    {
        fn_datablock_get_real = (DataBlockGetRealFn)g_lmp.datablock_get_real;
        return 1;
    }
  • In local_mp_core.c, install_local_mp_hooks() first calls config_native_matches_executable() to verify that the running aces.exe's PE TimeDateStamp and SizeOfImage match wto_ws.cfg (disabling the entire LocalMP bridge if wto_ws.cfg came from a different build), loads local_mp_core, iterates MODULES[] in dependency order ({ "local_mp_scores", install_local_mp_score_reader }) calling lmp_values_load(MODULES[i].name) before install(), and enables all queued hooks in one pass via MH_ApplyQueued().
  • Adding a brand-new .c file: Declare its installer in local_mp_internal.h, register it in MODULES[] (local_mp_core.c), and add the .c file to $sources in native/wto-net/build.ps1.
  • Sharing common engine hooks: When two modules need the same target function (e.g., unit_on_event shared by local_mp_damage_notifications and local_mp_air_events), define and dispatch it once in local_mp_core rather than calling MH_CreateHook twice on the same address.

5. Adapting a New Client Build (4-Step Workflow)

When War Thunder releases a minor client update (e.g., 2.61.0.37 -> 2.61.0.58), follow these four steps:

  1. Run the build recorder against your read-only stock client:
    powershell
     node scripts/record-game-version.ts --game "<stock-dir>"

    record-game-version.ts tests every patches/exe/, patches/gui/, and patches/native/ definition without modifying the stock folder. If any essential safety patch (ESSENTIAL_FEATURES) fails, it refuses to write a record and prints the blocking failures; otherwise it writes patches/versions/<version>.jsonc and lists any unavailable optional patches/modules.

  2. Add new variants only for failing patches/sites: Inspect the updated .nut script or aces.exe function using the Step 0 Node snippet or tools/re/cli.py (prefer find-string anchors!). Keep existing variants untouched so earlier builds continue working, and append a new variant with "written_for": "<new-version>".
  3. Run the full verification suite: Re-run record-game-version.ts to confirm zero unavailable items, then run:
    • .\.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"
    • powershell -NoProfile -File .\native\wto-net\build.ps1 (if any C file changed)
    • node scripts/build-game-copy.ts into a temporary copy directory to confirm clean assembly.
  4. Verify live in-game inside an isolated copy BEFORE committing patches/versions/<version>.jsonc: The launcher relies on patches/versions/<version>.jsonc to badge a client build as verified. Boot the isolated copy, sign into the hangar, and play through a LocalMP battle before committing patches/versions/<version>.jsonc rather than relying on CLI checks alone.

Starter templates for new patches live under dev-docs/templates/gui/, dev-docs/templates/exe/, and dev-docs/templates/native/.

04 · 环境搭建、本地流量日志排错与检查命令

这篇指南带你从零搭好本地开发环境、用内置的自动解码流量日志快速定位机库与对局问题,并在发起 Pull Request 前跑通对应的真实工程检查。


1. 开发环境准备

你需要一台 Windows x64 电脑,并安装以下基础工具:

  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 游戏库目录之外单独准备的离线副本目录与本地服务器数据目录。

首次克隆仓库后,在仓库根目录依次执行:

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

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 在启动器界面打开「设置 → 诊断 → 打开日志目录」即可查看,记录副本构建、补丁包校验、子进程启停与更新器状态。

3. 提交前必跑的工程检查命令(按改动范围对照执行)

WTOffline 不要求也不提倡编写庞大的模拟(Mock)单元测试套件,而是要求你按实际触碰的代码目录,跑通下面对应的真实编译器、补丁字节核对与 Quirrel 字节码检查;最终交互体验则在独立隔离副本中进游戏实机验收。

你修改了哪里提交前必须跑通的检查
共享库 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 nativewto-netbuild.ps1(/W4 零警告)+ 临时目录 scripts/build-game-copy.ts 确认所有原生站点全部解析就绪
适配客户端新版本(patches/versions/)scripts/record-game-version.ts + 上述全部适用检查 + 在隔离副本中实机登录进机库并完成 LocalMP 对局验收后,方可提交 patches/versions/<版本号>.jsonc

常用检查命令汇总(均在仓库根目录执行,将尖括号替换为你的本地路径):

powershell
# 1. TypeScript 类型与语法剥离约束检查(校验 .ts 后缀、import type、erasableSyntaxOnly 等)
npm run typecheck
npm run typecheck --workspace "@wto/launcher"
npm run build --workspace "@wto/launcher"

# 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"

# 3. Native DLL 编译(MSVC /W4 零警告)与完整离线副本试构建
powershell -NoProfile -File .\native\wto-net\build.ps1
node scripts/build-game-copy.ts --game "<原版目录>" --out "<临时副本目录>" --data "<临时数据目录>" --port 27015

# 4. 客户端版本适配记录核对
node scripts/record-game-version.ts --game "<原版目录>"

一次性编译 Quirrel 字节码检查器 sq.exe(注意 --sq 路径参数!)

check-gui 需要调用与《战争雷霆》客户端同代的官方 Quirrel 编译器(固定在 Quirrel 仓库提交 19f17df9b6ee43c91ef5c635fd45970ec76c5dbe)。使用 Visual Studio 2022 C++ 工具链与 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

关于 --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 节:零硬编码 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 模板,如实列出实际运行过的命令与输出结论,并把「已在隔离副本实机验收的界面步骤」与「尚待维护者实机验收的步骤」明确区分开。

04 · Setup, Traffic Log Debugging & Check Commands

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

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.

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 changedRequired 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/launcherLauncher 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 nativewto-netbuild.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>"

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). 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: 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 completely, recording exact commands run and clearly separating observed in-game checks from pending in-game acceptance steps.

05 · Pull Request 标准模板与自查清单

提交 PR 时请直接复制下方模板,逐项勾选 Self-check 并如实填写实际运行过的检查命令与待实机验收步骤:

markdown
## Change

<!-- Describe the player-visible result and the single focused goal of this PR. -->

## Reason and evidence

<!-- 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 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, 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 |
| --- | --- | --- |
| | | |

## In-game acceptance

<!-- 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. -->

05 · Pull Request Template & Self-Check

Copy the template below when opening a PR, check every Self-check box, and honestly record executed checks alongside pending in-game verification steps:

markdown
## Change

<!-- Describe the player-visible result and the single focused goal of this PR. -->

## Reason and evidence

<!-- 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 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, 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 |
| --- | --- | --- |
| | | |

## In-game acceptance

<!-- 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. -->