返回 WTOffline 主页 Back to WTOffline Home
MOD AUTHORING HANDBOOK · API 0.1-EXPERIMENTAL

模组制作完整手册(全 7 章) Mod Authoring Handbook (7 Chapters)

面向模组创作者的完整在线手册:从解包查看原版文件、5 分钟入门、BLK/CSV 增量补丁、自定义 3D 载具、GUI/EXE 补丁到服务端零代码调参与全栈脚本案例,中英双语零删减呈现。 The complete unabridged 7-chapter handbook for mod authors—from inspecting stock archives and 5-minute quick start to BLK/CSV patches, custom 3D vehicles, GUI/EXE hooks, tuning overlays, and full-stack server scripts.

01 · 快速入门与清单规范

适用版本:format: 1 · api_version: "0.1-experimental"(实验期接口,随本体开发可能调整)

1. 核心思路:添加式叠加架构

WTOffline 采用添加式、按加载顺序逐层叠加的模组架构。模组通过增量补丁与新增文件作用于客户端与服务端,不支持直接整包替换原版 .vromfs.bin 归档文件:

  1. 启动游戏前,启动器从纯净原版备份(<游戏副本>/wtoffline/stock/)出发,先应用离线版核心补丁,再按玩家在「模组」页排好的顺序,依次叠加所有已启用模组的客户端补丁与新增文件;
  2. 大体积 3D 模型和贴图包通过 Windows NTFS 目录联接点(Junction) 跨盘零拷贝挂载;
  3. 本地服务器启动时自动读取叠加后的客户端数据包,再按同一顺序合并各模组的 server/tuning/*.jsonc 并加载 server/index.ts 脚本;
  4. 关掉模组或切换预设时,启动器自动拆除联接点并从 wtoffline/stock/ 还原原版文件,不破坏客户端本体。
  • 全局模组仓库:默认位于 %APPDATA%\WTOffline Launcher\mods(可在启动器「模组 › 预设与仓库」修改到任意硬盘)。
  • 首次启动自带 3 个官方模板:启动器首次初始化全局 mods/ 目录时,会自动放入 example-vehicle-tweak(零代码改车与译名)、example-server-script(服务端 TS 脚本最小示例)和 official-map-selector(原生 DaGui 弹窗 + 服务端选图全栈模组)三个现成模组(默认未勾选)。点击「模组 › 打开模组目录」即可直接阅读源码或复制改造!
  • 每客户端独立配置:模组开关、加载顺序和命名预设分别保存在各自客户端的数据目录 <数据目录>/mods-config.json 中。

2. 前置准备:如何解包与查阅原版游戏数据

在动手改载具属性、挂科技树或写界面补丁之前,你需要先知道原版游戏里的内部载具 ID(例如美系初始轻坦 M2A4 的内部 ID 是 us_m2a4,M1A2 SEP V2 是 us_m1a2_sep2_abrams)以及原版文件的目录结构。

2.1 原版核心归档文件在哪里?

在你的《战争雷霆》客户端目录(以及离线副本目录)下,核心数据存放在以下 .vromfs.bin 虚拟文件系统包中:

原版包路径(相对于客户端根目录)里面的核心内容
char.vromfs.bin科技树排布(config/shop.blk)、载具价格/研发点/权重/改装件(config/wpcost.blk)、载具分类标签(config/unittags.blk)、道具与解锁配置
aces.vromfs.bin坦克模型与装甲参数(gamedata/units/tankmodels/*.blk)、飞机气动(gamedata/flightmodels/*.blk)、舰船、炮弹与导弹参数(gamedata/weapons/...)
gui.vromfs.bin客户端全部界面逻辑脚本(scripts/**/*.nut)、界面模板(gui/**/*.tpl)与样式表(gui/**/*.css)
lang.vromfs.bin多语言本地化词条表(lang/units.csv 载具名、lang/menu.csv 界面文本、lang/units_weaponry.csv 武器弹药名)
ui/atlases.vromfs.bin科技树与商店使用的载具剪影图标(gameuiskin/<载具id>_ico.svg)
ui/images.vromfs.bin资料卡与乘员槽位载具大图(units/<载具id>.ddsx)

备份目录说明:<游戏副本>/wtoffline/stock/ 是启动器用来重建和还原纯净客户端的原版备份目录,请按只读方式对待,不要手动修改或覆盖其中的文件,以免影响关闭模组后的自动还原。所有模组改动都放在 mods/<你的模组>/ 下即可。

2.2 查阅与解包原版数据的方法

你可以根据自己的习惯,直接从本机原版客户端查阅 .blk、.csv 和 .nut 文件:

  1. 使用社区解包工具在本地查阅: 将客户端里的 char.vromfs.bin、aces.vromfs.bin、gui.vromfs.bin 等归档复制到单独的临时工作文件夹(不要在游戏目录原地解包),使用常见的 .vromfs.bin / .blk 社区解包工具提取目录并将二进制 .blk 转为可读文本,即可查找任意载具的内部 ID、科技树路径和字段名。
  2. 用 WTOffline 仓库自带库直接读取(适合拉取了源码仓库的开发者): 如果你在本地克隆了 WTOffline 仓库,可以直接在仓库根目录用 Node 24 调用内置的 @wto/vromfs 与 @wto/blk 读取任意原版包内的二进制 .blk 并打印为标准文本 BLK:
js
import { readFileSync } from 'node:fs';
import { getFile, NAME_MAP_PATH, readArchive } from './packages/vromfs/src/index.ts';
import { decodeBlk, formatBlkText, parseSharedNameMap } from './packages/blk/src/index.ts';
const ar = readArchive(readFileSync('C:/WarThunder/char.vromfs.bin'));
const dict = [...ar.files.entries()].find(([k]) => k.endsWith('.dict'))?.[1];
console.log(formatBlkText(decodeBlk(getFile(ar, 'config/wpcost.blk'), { names: ar.files.has(NAME_MAP_PATH) ? parseSharedNameMap(getFile(ar, NAME_MAP_PATH), dict).names : [], dictionary: dict })));

3. 5 分钟做出你的第一个模组

  1. 在启动器里打开 「模组 › 打开模组目录」(你会看到里面已经有 3 个官方示例模组可供参考);
  2. 在里面新建文件夹 my-first-mod;
  3. 创建清单文件 my-first-mod/mod.jsonc:
jsonc
{
  "format": 1,
  "id": "demo.my-first-mod",
  "name": {
    "zh-CN": "我的第一个模组",
    "en": "My First Mod"
  },
  "version": "0.1.0",
  "author": "YourName",
  "description": {
    "zh-CN": "把对局银狮和研发点倍率调整为 2 倍。",
    "en": "Doubles Silver Lions and Research Points battle rewards."
  },
  "api_version": "0.1-experimental",
  "game_versions": ["2.61.0.*"]
}
  1. 创建 my-first-mod/server/tuning/battle.jsonc:
jsonc
{
  "rewardMultiplierSilverLions": 2.0,
  "rewardMultiplierResearchPoints": 2.0
}
  1. 切回启动器窗口(页面获得焦点时会自动刷新,也可点击「刷新」),勾选启用你的模组并点击「启动游戏」即可生效。

4. 完整标准目录结构

按需创建你实际用到的子目录,未用到的部分完全不必建立:

text
<mod-folder>/
├─ mod.jsonc                          # 必需:模组清单
├─ server/                            # 可选:服务端部分
│  ├─ tuning/                         #   可调数值增量覆盖(*.jsonc)
│  └─ index.ts (或 index.mjs / .js)   #   服务端脚本入口(默认自动探测)
└─ client/                            # 可选:客户端部分
   ├─ packs/                          #   .vromfs.bin 数据包增量叠加
   │  ├─ char.vromfs.bin/
   │  ├─ aces.vromfs.bin/
   │  ├─ gui.vromfs.bin/
   │  ├─ lang.vromfs.bin/
   │  ├─ mis.vromfs.bin/
   │  ├─ game.vromfs.bin/
   │  ├─ ui/atlases.vromfs.bin/
   │  └─ ui/images.vromfs.bin/
   ├─ addon/                          #   3D 模型与贴图扩展包(res/*.grp, res/*.dxp.bin)
   ├─ gui-patches/                    #   GUI 脚本/模板/样式增量补丁(与本体 patches/gui 同格式)
   ├─ exe-patches/                    #   声明式 exe 补丁(与本体 patches/exe 同格式)
   ├─ files/                          #   可选:大型整合包附带的配套涂装/瞄具/音效/任务
   └─ config-blk.patch.jsonc          #   可选:游戏根目录 config.blk 的增量补丁

5. mod.jsonc 全字段参考

清单元数据解析采用严格白名单校验,写错字段名或出现未定义字段会被直接拒绝,并在启动器报错区显示具体原因。

字段必填类型说明
format是1清单格式版本号,目前固定为整数 1
id是string全局唯一模组 ID,匹配 /^[a-z0-9][a-z0-9._-]{0,63}$/(仅小写字母、数字、.、_、-,首字符须为字母或数字,最长 64 位;推荐 <作者>.<模组名>)
name是string | { [lang]: string }展示名称,支持单字符串或按语言代码映射(如 zh-CN、en)
version是string模组版本号(推荐语义化版本,如 0.1.0)
author是string作者或制作组名称
description否string | { [lang]: string }模组简介,支持单字符串或多语言对象
api_version是string目标接口标识,当前固定填 "0.1-experimental"
game_versions否string[]声明适配的游戏版本通配符列表(如 ["2.61.0.*"]);与客户端版本不符时仅发出警告,不强行阻断启动
requires否string[]前置依赖模组 ID 列表:缺失或未启用时作为阻塞错误阻止启动;同时约束加载顺序(若排在前置模组上方会触发 dependency-order 顺序警告,并参与启动器「按依赖自动排序」)
conflicts否string[]已知互斥模组 ID 列表;同时启用时作为阻塞错误阻止启动
load_after否string[]建议排在这些可选模组 ID 之后(越靠下越晚加载、优先级越高);不强制要求对方启用,若同时启用则参与顺序提示与「按依赖自动排序」
load_before否string[]建议排在这些可选模组 ID 之前;同样参与顺序提示与「按依赖自动排序」
server否{ entry?: string, tuning?: string }显式覆盖服务端入口文件(相对路径,不得含 ..)和 tuning 目录路径(默认自动探测 server/index.{ts,mjs,js} 与 server/tuning)

6. 启动器自动计算的能力与风险徽标(多徽标叠加)

启动器扫描模组目录后会自动计算并展示能力徽标。徽标是多选累加(非互斥)的——例如同时包含数据包修改与服务端脚本的模组会同时显示 data 和 script 两个徽标,而 official-map-selector 会同时显示 data、gui、script 三个徽标:

  • 数据/资源(data):包含 server/tuning/、client/packs/、client/addon/、client/files/ 或 client/config-blk.patch.jsonc(若模组仅含清单且无 gui/script/exe,也默认归类显示 data);
  • 界面补丁(gui):包含 client/gui-patches/;
  • 服务端脚本(script):包含可执行服务端 JS/TS 入口脚本;
  • 二进制补丁(exe):包含 client/exe-patches/(高风险,且受离线核心隔离补丁锁保护)。

7. 排序规则与冲突检测

  • 加载顺序与优先级:列表中从上到下依次加载;越靠下(序号越大)越晚加载、覆盖优先级越高;
  • 一键自动排序:启动器的「按依赖自动排序」会综合全部模组的 requires、load_after 与 load_before 进行拓扑排序;
  • 叠加合并(提示 info):两个模组对同一个 BLK / CSV / tuning 文件做增量补丁时,按顺序先后安全叠加;
  • 顺序与覆写警告(警告 warning):模组排在了 requires / load_after 目标之前、目标游戏版本不匹配、或后序模组用整文件替换了前序模组修改过的数据包文件/外置配套文件;
  • 阻塞错误(错误 error):缺少 requires 前置模组、前置模组未启用、或同时启用了声明 conflicts 互斥的模组时,启动器禁止启动并高亮提示处理。

01 · Quick Start & Manifest Reference

Target Spec: format: 1 · api_version: "0.1-experimental" (experimental API; subject to breaking changes as core development progresses)

1. Core Concept: Additive Overlay Architecture

WTOffline uses a stackable, load-order additive mod architecture. Mods supply incremental patches and added files to the client and server, and do not replace whole stock .vromfs.bin archives:

  1. Before launching the game, the launcher starts from clean stock backups (<copy>/wtoffline/stock/), applies core offline patches first, and then layers every enabled mod's client patches and added files in the exact order shown on the Mods page;
  2. Large 3D model and texture addons mount across drives with zero file copying via Windows NTFS Directory Junctions;
  3. When the local server starts, it automatically extracts static game data from the overlaid client packs, merges each mod's server/tuning/*.jsonc in the same order, and loads server/index.ts scripts;
  4. When you disable a mod or switch presets, the launcher automatically unmounts junctions and restores clean files from wtoffline/stock/ without corrupting the client copy.
  • Global mod repository: defaults to %APPDATA%\WTOffline Launcher\mods (configurable to any drive under Mods › Presets & repository).
  • 3 official templates seeded on first launch: the first time the launcher initializes the global mods/ folder, it automatically seeds example-vehicle-tweak (code-free vehicle & localization tweak), example-server-script (minimal server TypeScript mod), and official-map-selector (full-stack native DaGui modal + server map filter), all disabled by default. Click Mods › Open mods folder right away to inspect their code or duplicate one as a starting point!
  • Per-client configuration: mod toggles, load order, and named presets are saved independently per client in <dataFolder>/mods-config.json.

2. Prerequisite: How to Unpack & Inspect Stock Game Files

Before tweaking vehicle stats, wiring tech-tree entries, or patching UI scripts, you need to look up stock internal vehicle IDs (for example, the US reserve light tank M2A4 is us_m2a4, and the M1A2 SEP V2 is us_m1a2_sep2_abrams) and stock file paths.

2.1 Where Stock Archives Live in the Game Client

Inside your War Thunder client folder (and offline copy folder), stock game data lives inside .vromfs.bin virtual filesystem archives:

Stock Archive Path (relative to client root)Key Contents Inside
char.vromfs.binTech-tree layout (config/shop.blk), vehicle prices/RP/BR/modifications (config/wpcost.blk), unit classification tags (config/unittags.blk), items, and unlocks
aces.vromfs.binTank models & armor (gamedata/units/tankmodels/*.blk), aircraft flight models (gamedata/flightmodels/*.blk), ships, shells, and missiles (gamedata/weapons/...)
gui.vromfs.binAll client UI Quirrel scripts (scripts/**/*.nut), Handyman templates (gui/**/*.tpl), and DaGui stylesheets (gui/**/*.css)
lang.vromfs.binLocalization tables (lang/units.csv vehicle names, lang/menu.csv UI strings, lang/units_weaponry.csv weapons & ammo names)
ui/atlases.vromfs.binTech-tree and local web store vehicle silhouette icons (gameuiskin/<unit_id>_ico.svg)
ui/images.vromfs.binStat-card and crew-slot vehicle portraits (units/<unit_id>.ddsx)

Note on the backup folder: Treat <copy>/wtoffline/stock/ as read-only. The launcher relies on wtoffline/stock/ to rebuild overlays and restore clean files when mods are disabled; modifying files inside stock/ can prevent automatic restoration. Place all mod changes under mods/<your-mod>/.

2.2 Practical Ways to Inspect Stock Files

You can inspect stock .blk, .csv, and .nut files directly from your own local game installation:

  1. Local unpacking with community tools: Copy char.vromfs.bin, aces.vromfs.bin, or gui.vromfs.bin from your client into a separate scratch folder (avoid unpacking in-place inside the game directory) and use standard community .vromfs.bin / .blk unpacking tools to extract readable text .blk and .nut files, vehicle IDs, and tech-tree paths.
  2. 5-line Node 24 snippet using @wto/vromfs + @wto/blk (if you cloned the WTOffline repo): If you have the WTOffline repository checked out locally, run Node 24 from the repo root to decode any binary .blk straight out of a .vromfs.bin archive and print formatted text BLK:
js
import { readFileSync } from 'node:fs';
import { getFile, NAME_MAP_PATH, readArchive } from './packages/vromfs/src/index.ts';
import { decodeBlk, formatBlkText, parseSharedNameMap } from './packages/blk/src/index.ts';
const ar = readArchive(readFileSync('C:/WarThunder/char.vromfs.bin'));
const dict = [...ar.files.entries()].find(([k]) => k.endsWith('.dict'))?.[1];
console.log(formatBlkText(decodeBlk(getFile(ar, 'config/wpcost.blk'), { names: ar.files.has(NAME_MAP_PATH) ? parseSharedNameMap(getFile(ar, NAME_MAP_PATH), dict).names : [], dictionary: dict })));

3. Build Your First Mod in 5 Minutes

  1. Open Mods › Open mods folder in the launcher (you will already see the 3 official template folders inside for reference);
  2. Create a new folder named my-first-mod;
  3. Create the manifest file my-first-mod/mod.jsonc:
jsonc
{
  "format": 1,
  "id": "demo.my-first-mod",
  "name": {
    "zh-CN": "我的第一个模组",
    "en": "My First Mod"
  },
  "version": "0.1.0",
  "author": "YourName",
  "description": {
    "zh-CN": "把对局银狮和研发点倍率调整为 2 倍。",
    "en": "Doubles Silver Lions and Research Points battle rewards."
  },
  "api_version": "0.1-experimental",
  "game_versions": ["2.61.0.*"]
}
  1. Create my-first-mod/server/tuning/battle.jsonc:
jsonc
{
  "rewardMultiplierSilverLions": 2.0,
  "rewardMultiplierResearchPoints": 2.0
}
  1. Switch back to the launcher window (the Mods page refreshes automatically on focus, or click Refresh), enable your mod, and click Launch.

4. Complete Standard Folder Layout

Create only the subdirectories your mod actually uses—unused folders can be omitted completely:

text
<mod-folder>/
├─ mod.jsonc                          # Required: mod manifest
├─ server/                            # Optional: server-side extensions
│  ├─ tuning/                         #   incremental tuning overlays (*.jsonc)
│  └─ index.ts (or index.mjs / .js)   #   server script entry (auto-detected by default)
└─ client/                            # Optional: client-side extensions
   ├─ packs/                          #   .vromfs.bin archive overlays
   │  ├─ char.vromfs.bin/
   │  ├─ aces.vromfs.bin/
   │  ├─ gui.vromfs.bin/
   │  ├─ lang.vromfs.bin/
   │  ├─ mis.vromfs.bin/
   │  ├─ game.vromfs.bin/
   │  ├─ ui/atlases.vromfs.bin/
   │  └─ ui/images.vromfs.bin/
   ├─ addon/                          #   3D model & texture addon (res/*.grp, res/*.dxp.bin)
   ├─ gui-patches/                    #   incremental GUI script/tpl/css patches (same format as patches/gui)
   ├─ exe-patches/                    #   declarative exe patches (same format as patches/exe)
   ├─ files/                          #   optional companion skins/sights/sounds/missions
   └─ config-blk.patch.jsonc          #   optional root config.blk incremental patch

5. Full mod.jsonc Schema Reference

Manifest parsing enforces strict whitelist validation: typos or unknown keys are rejected immediately with a detailed error message on the Launcher Mods page.

FieldRequiredTypeDescription
formatYes1Manifest schema version, currently fixed to integer 1
idYesstringGlobally unique mod ID matching /^[a-z0-9][a-z0-9._-]{0,63}$/ (lowercase letters, digits, ., _, -; must start with letter/digit; max 64 chars; <author>.<mod-name> recommended)
nameYesstring | { [lang]: string }Display name as a plain string or locale map (e.g. zh-CN, en)
versionYesstringMod version string (SemVer such as 0.1.0 recommended)
authorYesstringAuthor or team name
descriptionNostring | { [lang]: string }Short summary as a plain string or locale map
api_versionYesstringTarget API version tag, currently fixed to "0.1-experimental"
game_versionsNostring[]Supported game build wildcards (e.g. ["2.61.0.*"]); mismatches emit a warning without blocking launch
requiresNostring[]Required dependency mod IDs: missing or disabled dependencies raise a blocking error; also enforces load order (emits a dependency-order warning if placed above its dependency and participates in Auto-Sort)
conflictsNostring[]Mutually incompatible mod IDs; enabling both raises a blocking error
load_afterNostring[]Optional mods this mod should load after (lower in the list = higher priority); does not require them to be enabled, and participates in order hints & Auto-Sort
load_beforeNostring[]Optional mods this mod should load before; also participates in order hints & Auto-Sort
serverNo{ entry?: string, tuning?: string }Explicit relative paths (no ..) overriding default auto-detection of server/index.{ts,mjs,js} and server/tuning

6. Automatically Computed Capability & Risk Badges (Additive Multi-Badge)

After scanning each mod folder, the launcher computes capability badges automatically. Badges are additive, not mutually exclusive—for example, a mod with pack overlays and a server script displays both data and script, while official-map-selector displays data, gui, and script:

  • Data / Assets (data): contains server/tuning/, client/packs/, client/addon/, client/files/, or client/config-blk.patch.jsonc (a manifest-only mod with none of gui/script/exe also defaults to data);
  • UI Patches (gui): contains client/gui-patches/;
  • Server Script (script): contains an executable server JS/TS entry script;
  • Binary Patches (exe): contains client/exe-patches/ (high-risk; guarded by the core offline isolation patch lock).

7. Load Order Rules & Conflict Detection

  • Load order & priority: mods load top-to-bottom; items lower in the list (larger index) load later and take higher priority;
  • One-click Auto-Sort: the launcher's Auto-sort by dependencies button topologically sorts mods using requires, load_after, and load_before together;
  • Additive merge (info): when multiple mods patch the same BLK, CSV, or tuning file, their edits stack cleanly in load order;
  • Order & override warnings (warning): emitted when a mod sits above a requires / load_after target, mismatches game_versions, or replaces an entire pack/companion file already modified by an earlier mod;
  • Blocking errors (error): missing requires dependencies, disabled dependencies, or simultaneously enabled conflicts prevent launch and highlight the exact items to fix.

02 · 客户端数据包与 BLK 增量补丁

绝大多数《战争雷霆》数据模组(调整载具性能、炮弹穿深、导弹机动、科技树排布、银狮/研发点价格、分房权重、本地化译名、载具图标)都落在游戏的 .vromfs.bin 数据包中。本章讲解如何以完全可叠加、多模组互不顶掉的方式修改这些数据包,并在章末带你从零克隆出一辆能在美系科技树看到并直接试驾的独立新坦克。


1. 先懂概念:什么是 BLK?它为什么和 JSON 不一样?

Dagor 引擎使用自研的 BLK(DataBlock) 格式存储几乎所有游戏配置(在数据包内编译为紧凑二进制,解包后可读为文本 .blk)。初看很像 JSON,但它有三个关键差异:

  1. 每个参数都带显式静态类型后缀:例如 :i(32 位整数)、:r(单精度浮点)、:t(字符串)、:b(布尔 yes/no);把 :r 误写成 :i 会导致引擎读不到小数参数;
  2. 同一个块内允许出现多个同名参数:例如 slaveUnit:t="launcher_a" 下面紧跟第二行 slaveUnit:t="launcher_b"(如果直接转成普通 JSON 对象,前一行就会被后一行覆盖丢失!);
  3. 同一个父块下允许并列多个同名子块:最典型的就是科技树 shop.blk,每个陆军/空军分支下并列着好几个同名的 range { ... } 子块。

对比下面这段 8 行原版文本 .blk(节选自 wpcost.blk 的 us_m2a4)与对应的 .blk.patch.jsonc 增量补丁,你立刻就能看懂两者的对应关系:

blk
// 原版可读文本 BLK(char.vromfs.bin -> config/wpcost.blk 节选)
us_m2a4 {
  value:i = 0
  rank:i = 1
  economicRankHistorical:i = 0
  rewardMulHistorical:r = 0.1
  country:t = "country_usa"
  unitClass:t = "exp_tank"
}
jsonc
// 对应的增量补丁:client/packs/char.vromfs.bin/config/wpcost.blk.patch.jsonc
// 只修改 us_m2a4 的历史模式收益倍率,不会影响其他模组对别的字段或载具的改动
{
  "ops": [
    {
      "op": "setParam",
      "path": ["us_m2a4"],
      "name": "rewardMulHistorical",
      "value": { "type": "real", "value": 1.2 }
    }
  ]
}

2. 支持叠加的 8 个客户端数据包

把文件按目标包路径放进 client/packs/<包路径>/ 下即可:

目标目录名常见内容备份方式
client/packs/char.vromfs.bin/config/shop.blk(科技树)、config/wpcost.blk(经济/权重/改装件)、config/unittags.blk、config/items.blk、config/modifications.blk常驻备份
client/packs/aces.vromfs.bin/gamedata/units/.../*.blk(载具模型/DM/炮塔)、gamedata/flightmodels/...(气动)、gamedata/weapons/...(武器/炮弹/导弹)、config/settings.blk常驻备份
client/packs/gui.vromfs.bin/新增独立 .nut 脚本、.tpl 模板、.css 样式(修改已有脚本/样式请看第 04 章 gui-patches)常驻备份
client/packs/lang.vromfs.bin/lang/units.csv、lang/menu.csv、lang/units_weaponry.csv 等本地化表按需自动备份,关闭还原
client/packs/mis.vromfs.bin/gamedata/missions/.../*.blk 联机/自定义任务按需自动备份,关闭还原
client/packs/game.vromfs.bin/danetlibs/...、game/... 脚本与配置按需自动备份,关闭还原
client/packs/ui/atlases.vromfs.bin/gameuiskin/<全小写载具id>_ico.svg(科技树与本地商城剪影图标)按需自动备份,关闭还原
client/packs/ui/images.vromfs.bin/units/<载具id>.ddsx 或 .png(资料卡/乘员栏载具图)按需自动备份,关闭还原

自动联动服务端:本地服务器在启动时直接读取叠加后的 .vromfs.bin。因此你通过补丁往 shop.blk / wpcost.blk 新增或修改载具后,服务端会自动识别新车价格、前置科技树、研发点、改装件、分房权重、AI 机器人池与礼包 GUID,无需手工同步两遍。


3. 包内文件的 3 种处理模式(按后缀自动识别)

构建器根据你在 client/packs/<包>/ 下放置的文件名自动决定处理方式:

  1. <原路径>.patch.jsonc → BLK 结构化增量补丁:解析目标 .blk 为保留完整类型的内存树,按 ops 逐条修改后重新编码为自包含二进制 BLK 写回;
  2. <原路径>.patch.csv → CSV 本地化增量合并:按第 1 列词条键合并进目标 .csv(已有键只更新你填写的语言列,新键追加到表尾);
  3. 其余文件(如 us_m2a4_mod_demo.blk、us_m2a4_mod_demo_ico.svg)→ 新增或替换文件:
    • 如果路径以 .blk 结尾且你的源文件是可读文本 BLK(如从原版客户端解包修改得到的),构建器会自动将其编译为游戏引擎所需的二进制 BLK 写进包内;
    • 如果已经是二进制 BLK,或是 .svg / .ddsx / .nut / .tpl / .css,则原样写入包内。

4. BLK 增量补丁(*.blk.patch.jsonc)完整手册

4.1 基本格式与路径寻址

jsonc
{
  "ops": [
    // 按顺序执行的操作列表
  ]
}
  • path 是从 BLK 根节点出发的子块名数组,例如 ["country_usa", "army", "range[0]"];
  • 同名并列子块(如 shop.blk 里连续多个 range 块)可以用 名称[索引](0 起始)精确定位;不写索引默认命中第 0 个同名子块;
  • [] 表示当前文档根节点本身。

4.2 全部 7 种操作(op)

① setParam:设置参数(存在则覆盖并去重同名项,不存在则新增)

修改已有块上的单个字段时,永远优先用 setParam:

jsonc
{
  "op": "setParam",
  "path": ["us_m2a4"],
  "name": "rewardMulHistorical",
  "value": { "type": "real", "value": 1.2 },
  "createBlocks": false // 可选,默认 false;设为 true 时自动补建缺失路径子块
}
② addParam:追加同名参数(不删除已有同名项,适合 slaveUnit、folder、aircraftGift 等可重复键)
jsonc
{
  "op": "addParam",
  "path": ["country_usa", "army", "range[0]", "us_m2a4"],
  "name": "slaveUnit",
  "value": "my_extra_launcher"
}
③ removeParam:删除参数(不填 value 删除全部同名参数;填 value 只删值匹配的项)
jsonc
{
  "op": "removeParam",
  "path": ["us_m2a4"],
  "name": "showOnlyWhenBought"
}
④ upsertBlock:确保路径子块存在,并向其追加 params 与 blocks
jsonc
{
  "op": "upsertBlock",
  "path": ["country_usa", "army", "range[0]", "my_custom_tank"],
  "block": {
    "params": [
      { "name": "rank", "value": { "type": "int", "value": 8 } },
      { "name": "reqAir", "value": "us_m1a2_sep2_abrams" }
    ]
  }
}

重要行为说明(避免重复键踩坑):如果目标路径的块原本不存在,upsertBlock 会自动创建它并写入 block.params 和 block.blocks;但如果目标块已经存在,upsertBlock 会把传入的 params(通过 appendParam)和 blocks 直接追加到块末尾,而不会覆盖已有同名参数!因此:新建子块或有意追加多值字段时可用 upsertBlock;若要覆盖已有块上的某个参数值,请务必使用 setParam。

⑤ addBlock:在父块下新增一个子块(支持 before / after 指定锚点位置)
jsonc
{
  "op": "addBlock",
  "path": ["country_usa", "army", "range[0]"],
  "name": "my_custom_tank",
  "after": "us_m3a1_stuart",
  "block": {
    "params": [
      { "name": "rank", "value": { "type": "int", "value": 1 } },
      { "name": "reqAir", "value": "us_m2a4" }
    ]
  }
}
⑥ removeBlock:删除指定路径的子块
jsonc
{
  "op": "removeBlock",
  "path": ["country_usa", "army", "range[0]", "some_vehicle"]
}
⑦ cloneBlock:深拷贝同文档里的已有块为新名称并嵌套 ops 微调(衍生新车神器!)

在 wpcost.blk 和 unittags.blk 里,一辆载具包含几十个维修/乘员/改装件/武器预设子块。用 cloneBlock 可以一键完整克隆原版原型车,再用嵌套 ops 只改差异字段:

jsonc
{
  "op": "cloneBlock",
  "from": ["us_m1a2_sep2_abrams"],
  "toParent": [],
  "newName": "us_m1a2_mod_example",
  "replaceExisting": true,
  "ops": [
    { "op": "setParam", "path": [], "name": "value", "value": { "type": "int", "value": 10000 } },
    { "op": "setParam", "path": [], "name": "reqExp", "value": { "type": "int", "value": 50000 } },
    { "op": "setParam", "path": [], "name": "economicRankHistorical", "value": { "type": "int", "value": 34 } }
  ]
}

注意:cloneBlock 内部的嵌套 ops 是以刚克隆出来的新块为根节点运行的,所以修改新块自身顶层参数时 path 写 []。

4.3 全部 13 种 BLK 数据类型写法

直接写 JSON 原始值时,构建器会优先沿用目标块已有同名字段的 BLK 类型(若无同名字段:字符串 → string,布尔 → bool,整数 → int,含小数 → real)。为确保万无一失(尤其是把浮点字段设为 2.0 时 JSON 解析为整数 2),推荐显式写成 { "type": "<类型>", "value": <值> }:

typeBLK 文本后缀value 示例与说明
string:t"us_m2a4"
int:i120(32 位有符号整数)
real:r1.5(即使写 2,也会严格按 32 位浮点 :r 编码)
bool:btrue / false(对应文本 BLK 的 yes / no)
int64:i64"133700000000000000" 或整数(64 位整数)
point2:p2[1.0, 2.5](2 个浮点数)
point3:p3[0.0, 1.5, -2.0](3 个浮点数)
point4:p4[0.0, 1.0, 0.0, 1.0](4 个浮点数)
ipoint2:ip2[10, 20](2 个整数)
ipoint3:ip3[1, 2, 3](3 个整数)
ipoint4:ip4[0, 1, 2, 3](4 个整数)
color:c[255, 128, 0, 255]([r, g, b, a])或无符号打包整数 0xAARRGGBB
matrix:m12 个浮点数的数组(4 行 × 3 列变换矩阵)

5. 分房权重(BR)与内部 mrank(economicRank*)换算表

新手打开 wpcost.blk 最常困惑的一点是:为什么里面找不到 11.7 或 12.7 这样的分房权重数字?

在战雷内部,面板显示的 分房权重(Battle Rating, BR) 存储为从 0 开始的非负整数 mrank(字段名为 economicRank*),每 3 级整数对应 1.0 权重,小数位按 .0 → .3 → .7 循环:

  • 正向换算公式(mrank → 面板 BR):BR = 1.0 + Math.floor(mrank / 3) + [0, 0.3, 0.7][mrank % 3]
  • 反向换算口诀(面板 BR → mrank):(整数部分 - 1) × 3,再加小数档位(.0 加 0,.3 加 1,.7 加 2)。例如 11.7 → (11 - 1) × 3 + 2 = 32!

5.1 完整 mrank ↔ 面板 BR 速查表

mrank面板 BRmrank面板 BRmrank面板 BRmrank面板 BR
01.0104.3207.73011.0
11.3114.7218.03111.3
21.7125.0228.33211.7
32.0135.3238.73312.0
42.3145.7249.03412.3
52.7156.0259.33512.7
63.0166.3269.73613.0
73.3176.72710.03713.3
83.7187.02810.33813.7
94.0197.32910.73914.0

5.2 wpcost.blk 模式后缀与科技树等级 rank 的区别

战雷沿用了远古内测时期的模式英文名,千万不要把科技树大等级 rank 和分房权重 economicRank* 搞混:

字段名取值范围真实含义
rank1 .. 8科技树时代等级(Rank I – VIII):决定它在科技树第几大行、受哪一级的开线数量门槛限制,以及默认套用哪一档商店礼包价格
economicRankArcade0 .. 39+街机娱乐(AB, Arcade Battles) 的分房 mrank
economicRankHistorical0 .. 39+历史性能(RB, Realistic Battles) 的默认分房 mrank(战雷早期将历史模式称为 *Historical Battles*)
economicRankSimulation0 .. 39+全真模拟(SB, Simulator Battles) 的默认分房 mrank
economicRankTankHistorical0 .. 39+(可选)飞机/直升机进入陆战历史(Ground RB)时的独立对地分房权重;不填时沿用 economicRankHistorical
economicRankTankSimulation0 .. 39+(可选)飞机/直升机进入陆战全真(Ground SB)时的独立分房权重

6. shop.blk 科技树结构与 units.csv 四大词条后缀详解

6.1 config/shop.blk 的四层树状结构

打开 char.vromfs.bin 里的 config/shop.blk,所有国家的科技树都遵循统一的四层结构:

text
country_usa (或 country_germany / country_ussr / country_britain / country_japan / country_china / ...)
 └─ army (陆军) | helicopters (直升机) | aviation (空军) | ships (远洋海军) | boats (近岸海军)
     ├─ range { ... }       <-- range[0]:科技树第 1 纵列(如美系轻坦线)
     ├─ range { ... }       <-- range[1]:科技树第 2 纵列(如美系中坦线,内部含折叠组 us_sherman_group)
     ├─ range { ... }       <-- range[2]..range[4]:其余常规银狮研发纵列
     └─ range { ... }       <-- range[5]..range[6]:右侧金币车 / 礼包车 / 活动车 / 联队车独立纵列

编写 shop.blk.patch.jsonc 时只需记住三条核心规则:

  1. 每个 range 就是科技树上的一条纵向列:因为它们都叫 range,在补丁 path 里用 "range[0]"、"range[1]"、"range[5]" 按从左到右(0 起始)定位;
  2. 折叠文件夹(*_group):当同一格折叠了多辆同系载具时,range 下会放一个以 _group 结尾的子块(例如 us_sherman_group),里面再嵌套各辆具体载具子块,折叠封面标题来自 units.csv 的 shop/group/<组名>;
  3. 为什么坦克和军舰的前置研发箭头也叫 reqAir? 因为《战争雷霆》最早立项时是纯空战游戏(*World of Planes*),所有载具在底层代码里都沿用了 air / aircraft 命名,因此无论是坦克、直升机还是战列舰,指定“上一辆前置研发载具”的字段一律叫 reqAir!
    • 在 wpcost.blk 中设置 reqAir:t="us_m2a4":声明玩家必须先拥有 us_m2a4 才能研发本车;
    • 在 shop.blk 的同一 range 列中:连续排列且未写 reqAir 的两辆车默认自动画纵向实线箭头;写 reqAir:t="us_m2a4" 会显式从 us_m2a4 连出箭头;而写 reqAir:t=""(空字符串)则会显式断开与上方载具的箭头连接(科技树断线处以及右侧金币/礼包列里的车都用 reqAir:t="")。

6.2 lang/units.csv 的 4 个载具译名后缀与 CSV 增量合并

在 client/packs/lang.vromfs.bin/lang/units.csv.patch.csv 中为新载具添加译名时,每辆载具 <id> 共有 4 个标准词条键,分别对应不同界面与视距:

词条键格式游戏内显示位置示例(以 us_m2a4_mod_demo 为例)
<id>_shop科技树格子、底部乘员槽位、本地网页商店卡片上的简短名称"M2A4 (Mod Demo)" / "M2A4(教学改型)"
<id>_0资料卡顶部标题、研发完成弹窗、战后结算详单里的完整正式全称"Light Tank M2A4 (Mod Demo)" / "M2A4 轻型坦克(教学改型)"
<id>_1战斗中中距离 3D 视野目标标记上显示的中等长度名称"M2A4 Demo" / "M2A4 教学型"
<id>_2战斗中远距离目标标记 / 极简击杀播报显示的超短型号或车种名"M2A4" / "M2A4"

CSV 补丁文件写法示例(client/packs/lang.vromfs.bin/lang/units.csv.patch.csv):

csv
"<ID|readonly|noverify>";"<English>";"<Chinese>";"<HChinese>"
"us_m2a4_mod_demo_shop";"M2A4 (Mod Demo)";"M2A4(教学改型)";"M2A4(教學改型)"
"us_m2a4_mod_demo_0";"Light Tank M2A4 (Mod Demo)";"M2A4 轻型坦克(教学改型)";"M2A4 輕型坦克(教學改型)"
"us_m2a4_mod_demo_1";"M2A4 Demo";"M2A4 教学型";"M2A4 教學型"
"us_m2a4_mod_demo_2";"M2A4";"M2A4";"M2A4"
  • 必须以分号 ; 分隔并用双引号包裹每个字段,第 1 行写表头列名(只需列出你要填的语言列,未列出的语言列会自动保留原值或留空);
  • 如果第 1 列 ID 在原表已存在,只更新你提供的非空语言列;不存在则自动追加到表尾。

7. 修改游戏根目录 config.blk(client/config-blk.patch.jsonc)

如果模组需要调整游戏根目录的 config.blk(例如开启音效模组开关 sound{ enable_mod:b=yes } 或指定自定义机库 hangarBlk:t="..."),放一份标准 BLK 补丁到 client/config-blk.patch.jsonc 即可:

jsonc
{
  "ops": [
    {
      "op": "setParam",
      "path": ["sound"],
      "name": "enable_mod",
      "value": { "type": "bool", "value": true },
      "createBlocks": true
    }
  ]
}

启动器会在首次修改前自动将原版 config.blk 备份到 wtoffline/stock/config.blk,关闭相关模组后自动还原。


8. 端到端完整实战:5 分钟克隆一辆可试驾独立新坦克(us_m2a4_mod_demo)

下面我们把前面学到的知识串成一条完整闭环:复用原版美系初始轻坦 us_m2a4 的外观模型,衍生出一辆极速提升到 90 km/h、权重 1.3(mrank = 1)、挂在美系陆军 I 级科技树 M2A4 旁边的独立新载具 us_m2a4_mod_demo。由于每个存档天生拥有初始车 us_m2a4,你进游戏就能直接在美系陆军科技树看到它并点击「试驾」!

8.1 模组目录结构

在全局 mods/ 目录下新建 demo-standalone-m2a4/,结构如下:

text
mods/demo-standalone-m2a4/
├─ mod.jsonc
└─ client/
   └─ packs/
      ├─ aces.vromfs.bin/
      │  └─ gamedata/units/tankmodels/
      │     └─ us_m2a4_mod_demo.blk          # ① 载具物理/装甲/武器定义(基于原版 us_m2a4.blk 修改)
      ├─ char.vromfs.bin/
      │  └─ config/
      │     ├─ wpcost.blk.patch.jsonc        # ② 克隆经济、分房权重、改装件与弹药架
      │     ├─ shop.blk.patch.jsonc          # ③ 挂入美系陆军第 1 列 I 级科技树
      │     └─ unittags.blk.patch.jsonc      # ④ 克隆载具分类标签与试车场配置
      └─ lang.vromfs.bin/
         └─ lang/
            └─ units.csv.patch.csv           # ⑤ 注册 _shop / _0 / _1 / _2 中英文名称

8.2 各文件完整内容

清单 mod.jsonc
jsonc
{
  "format": 1,
  "id": "demo.standalone-m2a4",
  "name": {
    "zh-CN": "独立衍生载具示例:M2A4 教学改型",
    "en": "Standalone Vehicle Demo: M2A4 Mod Demo"
  },
  "version": "0.1.0",
  "author": "YourName",
  "description": {
    "zh-CN": "克隆原版 us_m2a4 新增一辆独立可研发、可试驾的 90km/h 高速轻坦。",
    "en": "Clones stock us_m2a4 into a playable 90 km/h standalone tank in the US Rank I tree."
  },
  "api_version": "0.1-experimental",
  "game_versions": ["2.61.0.*"]
}
① 载具实体参数 client/packs/aces.vromfs.bin/gamedata/units/tankmodels/us_m2a4_mod_demo.blk

按第 01 章第 2 节任一方式取出原版 aces.vromfs.bin 中的 gamedata/units/tankmodels/us_m2a4.blk(文本或二进制均可),另存为 us_m2a4_mod_demo.blk。保持顶部的 model:t="m2a4" 不变(这样它会直接复用原版 M2A4 的 3D 模型和贴图),把里面的最大前进速度和加速改快即可(文本 .blk 在构建时会自动编译为二进制 .blk):

blk
model:t="m2a4"
// ...(保留原版 us_m2a4.blk 其余内容不变,仅调高以下机动参数体验效果)...
maxFwdSpeed:r=90.0
maxRevSpeed:r=25.0
maxAccel:r=12.0
② 经济与权重补丁 client/packs/char.vromfs.bin/config/wpcost.blk.patch.jsonc

用 cloneBlock 一键复制 us_m2a4(自动继承全部武器、弹种、改装件与备用车配置),并把研发前提设为 us_m2a4、研发点设为 1000、银狮价格设为 500、三模式分房权重设为 1(即面板 1.3):

jsonc
{
  "ops": [
    {
      "op": "cloneBlock",
      "from": ["us_m2a4"],
      "toParent": [],
      "newName": "us_m2a4_mod_demo",
      "replaceExisting": true,
      "ops": [
        { "op": "setParam", "path": [], "name": "reqAir", "value": "us_m2a4" },
        { "op": "setParam", "path": [], "name": "reqExp", "value": { "type": "int", "value": 1000 } },
        { "op": "setParam", "path": [], "name": "value", "value": { "type": "int", "value": 500 } },
        { "op": "setParam", "path": [], "name": "economicRank", "value": { "type": "int", "value": 1 } },
        { "op": "setParam", "path": [], "name": "economicRankArcade", "value": { "type": "int", "value": 1 } },
        { "op": "setParam", "path": [], "name": "economicRankHistorical", "value": { "type": "int", "value": 1 } },
        { "op": "setParam", "path": [], "name": "economicRankSimulation", "value": { "type": "int", "value": 1 } }
      ]
    }
  ]
}
③ 科技树位置补丁 client/packs/char.vromfs.bin/config/shop.blk.patch.jsonc

在 country_usa -> army -> range[0] 的 I 级段末尾(us_m3a1_stuart 之后、us_m5a1_stuart 断线之前)插入新车块,并显式声明 reqAir: "us_m2a4",游戏就会在不打断原有斯图亚特研发线的前提下,从 M2A4 连出一条侧支研发箭头指向你的新车:

jsonc
{
  "ops": [
    {
      "op": "addBlock",
      "path": ["country_usa", "army", "range[0]"],
      "name": "us_m2a4_mod_demo",
      "after": "us_m3a1_stuart",
      "block": {
        "params": [
          { "name": "rank", "value": { "type": "int", "value": 1 } },
          { "name": "reqAir", "value": "us_m2a4" }
        ]
      }
    }
  ]
}
④ 载具标签与试驾场补丁 client/packs/char.vromfs.bin/config/unittags.blk.patch.jsonc

同样用 cloneBlock 从 us_m2a4 克隆出 type:t="tank"、机库车位 hangar_place:t="tank"、陆战试车场 testFlight 与轻坦标签:

jsonc
{
  "ops": [
    {
      "op": "cloneBlock",
      "from": ["us_m2a4"],
      "toParent": [],
      "newName": "us_m2a4_mod_demo",
      "replaceExisting": true
    }
  ]
}
⑤ 多语言名称补丁 client/packs/lang.vromfs.bin/lang/units.csv.patch.csv

直接复用上面第 6.2 节的 4 行 CSV 内容即可。保存后在启动器勾选启用模组并启动游戏,切到美国陆军科技树 I 级,就能看到 M2A4(教学改型) 并立刻右键「试驾」体验 90 km/h 飙车!

02 · Client Packs & BLK Incremental Patching

Most War Thunder data mods—tweaking vehicle performance, shell penetration, missile maneuverability, tech-tree layouts, Silver Lion / Research Point prices, Battle Ratings, localized names, and vehicle icons—live inside .vromfs.bin data packs. This chapter explains how to modify those packs in a 100% stackable, conflict-free way, ending with a copy-pasteable walkthrough that clones a playable standalone tank into the US Rank I tech tree.


1. Plain-Language Intro: What Is BLK & Why Does It Differ from JSON?

War Thunder's Dagor Engine stores nearly all game configurations in BLK (DataBlock) files—compiled to compact binary inside .vromfs.bin packs, and readable as plain text .blk when unpacked. While text BLK looks superficially similar to JSON, it differs in three fundamental ways:

  1. Every parameter carries an explicit static type suffix: such as :i (32-bit integer), :r (32-bit float), :t (string), or :b (boolean yes/no). Writing :i where the engine expects :r causes the engine to ignore decimal values;
  2. Duplicate parameter names are allowed inside the same block: for instance, slaveUnit:t="launcher_a" followed immediately by slaveUnit:t="launcher_b" (converting naively to a plain JSON object would overwrite the first key!);
  3. Duplicate sibling block names are allowed under the same parent: most notably in shop.blk, where every army/aviation branch contains multiple sibling range { ... } blocks side by side.

Compare this 8-line stock text .blk excerpt (us_m2a4 in wpcost.blk) side by side with its .blk.patch.jsonc patch operation:

blk
// Stock readable text BLK (excerpt from char.vromfs.bin -> config/wpcost.blk)
us_m2a4 {
  value:i = 0
  rank:i = 1
  economicRankHistorical:i = 0
  rewardMulHistorical:r = 0.1
  country:t = "country_usa"
  unitClass:t = "exp_tank"
}
jsonc
// Matching incremental patch: client/packs/char.vromfs.bin/config/wpcost.blk.patch.jsonc
// Touches ONLY us_m2a4's Realistic reward multiplier without clobbering other fields or other mods!
{
  "ops": [
    {
      "op": "setParam",
      "path": ["us_m2a4"],
      "name": "rewardMulHistorical",
      "value": { "type": "real", "value": 1.2 }
    }
  ]
}

2. The 8 Overlayable Client Data Packs

Place your files under client/packs/<pack-path>/ matching the target archive's internal path:

Target DirectoryCommon ContentsBackup Strategy
client/packs/char.vromfs.bin/config/shop.blk (tech tree), config/wpcost.blk (economy/BR/modifications), config/unittags.blk, config/items.blk, config/modifications.blkAlways rebuilt from stock
client/packs/aces.vromfs.bin/gamedata/units/.../*.blk (vehicle models/DM/turrets), gamedata/flightmodels/... (FMs), gamedata/weapons/... (guns/shells/missiles), config/settings.blkAlways rebuilt from stock
client/packs/gui.vromfs.bin/New standalone .nut scripts, .tpl templates, .css stylesheets (to edit stock UI files, see Chapter 04 gui-patches)Always rebuilt from stock
client/packs/lang.vromfs.bin/lang/units.csv, lang/menu.csv, lang/units_weaponry.csv, and other localization CSVsBacked up on demand, restored on disable
client/packs/mis.vromfs.bin/gamedata/missions/.../*.blk multiplayer and custom missionsBacked up on demand, restored on disable
client/packs/game.vromfs.bin/danetlibs/..., game/... scripts and configsBacked up on demand, restored on disable
client/packs/ui/atlases.vromfs.bin/gameuiskin/<lowercase_unit_id>_ico.svg (tech-tree & local web store silhouette icons)Backed up on demand, restored on disable
client/packs/ui/images.vromfs.bin/units/<unit_id>.ddsx or .png (stat-card / crew-slot vehicle images)Backed up on demand, restored on disable

Automatic Server Sync: The local server reads static datasets directly from the overlaid .vromfs.bin packs on startup. Any vehicle added or tweaked in shop.blk / wpcost.blk is automatically picked up for prices, tech-tree prerequisites, Research Points, modifications, Battle Ratings, AI bot pools, and store pack GUIDs—no duplicate server registration needed.


3. Three File Handling Modes Inside Packs (Auto-Detected by Suffix)

The patcher determines how to process each file under client/packs/<pack>/ by its filename suffix:

  1. <target-path>.patch.jsonc → Structured Incremental BLK Patch: decodes the target .blk into a type-preserving tree, applies ops in order, and re-encodes a self-contained binary BLK;
  2. <target-path>.patch.csv → Incremental Localization CSV Merge: merges rows by column 0 (updating only the non-empty language columns you provide on existing keys, and appending new keys at the end);
  3. Any other file (e.g. us_m2a4_mod_demo.blk, us_m2a4_mod_demo_ico.svg) → Add or Replace File:
    • If the path ends with .blk and your source file is plain text BLK (for example, extracted and edited from your stock client), the builder automatically compiles it into binary BLK for the engine;
    • Binary .blk files and other assets (.svg, .ddsx, .nut, .tpl, .css) are written into the archive as-is.

4. Complete BLK Incremental Patch (*.blk.patch.jsonc) Reference

4.1 Document Format & Path Addressing

jsonc
{
  "ops": [
    // Ordered list of patch operations
  ]
}
  • path is an array of child block names starting from the BLK root, e.g. ["country_usa", "army", "range[0]"];
  • Duplicate sibling blocks (such as consecutive range blocks in shop.blk) can be addressed precisely with name[index] (zero-based); omitting [index] selects occurrence 0;
  • [] refers to the root block of the current document.

4.2 All 7 Patch Operations (op)

① setParam: Set a parameter (overwrites & deduplicates same-named params if present; appends if absent)

Always prefer setParam when updating a single parameter on an existing block:

jsonc
{
  "op": "setParam",
  "path": ["us_m2a4"],
  "name": "rewardMulHistorical",
  "value": { "type": "real", "value": 1.2 },
  "createBlocks": false // Optional (default false); set true to auto-create missing blocks along path
}
② addParam: Append a duplicate-named parameter (preserves existing entries; ideal for slaveUnit, folder, aircraftGift)
jsonc
{
  "op": "addParam",
  "path": ["country_usa", "army", "range[0]", "us_m2a4"],
  "name": "slaveUnit",
  "value": "my_extra_launcher"
}
③ removeParam: Delete parameters (deletes all matching name when value is omitted, or only entries matching value)
jsonc
{
  "op": "removeParam",
  "path": ["us_m2a4"],
  "name": "showOnlyWhenBought"
}
④ upsertBlock: Find or create a child block and append params & blocks
jsonc
{
  "op": "upsertBlock",
  "path": ["country_usa", "army", "range[0]", "my_custom_tank"],
  "block": {
    "params": [
      { "name": "rank", "value": { "type": "int", "value": 8 } },
      { "name": "reqAir", "value": "us_m1a2_sep2_abrams" }
    ]
  }
}

Important Behavior Note (Avoid Duplicate Keys): If the target block along path does not exist, upsertBlock creates it and populates block.params and block.blocks. However, if the target block already exists, upsertBlock appends every entry in block.params (via appendParam) and block.blocks to the end of the block without overwriting existing same-named parameters! Use upsertBlock to create new blocks or append multi-value params; to overwrite an existing parameter on an existing block, always use setParam.

⑤ addBlock: Insert a new child block under a parent (supports before / after sibling anchors)
jsonc
{
  "op": "addBlock",
  "path": ["country_usa", "army", "range[0]"],
  "name": "my_custom_tank",
  "after": "us_m3a1_stuart",
  "block": {
    "params": [
      { "name": "rank", "value": { "type": "int", "value": 1 } },
      { "name": "reqAir", "value": "us_m2a4" }
    ]
  }
}
⑥ removeBlock: Delete a child block at path
jsonc
{
  "op": "removeBlock",
  "path": ["country_usa", "army", "range[0]", "some_vehicle"]
}
⑦ cloneBlock: Deep-clone an existing block in the same file under newName with nested ops (essential for derived vehicles!)

In wpcost.blk and unittags.blk, each vehicle block contains dozens of repair, crew, modification, and weapon-preset sub-blocks. cloneBlock copies a stock donor vehicle completely in one step and lets you tweak only the differences via nested ops:

jsonc
{
  "op": "cloneBlock",
  "from": ["us_m1a2_sep2_abrams"],
  "toParent": [],
  "newName": "us_m1a2_mod_example",
  "replaceExisting": true,
  "ops": [
    { "op": "setParam", "path": [], "name": "value", "value": { "type": "int", "value": 10000 } },
    { "op": "setParam", "path": [], "name": "reqExp", "value": { "type": "int", "value": 50000 } },
    { "op": "setParam", "path": [], "name": "economicRankHistorical", "value": { "type": "int", "value": 34 } }
  ]
}

Note: Nested ops inside cloneBlock run with the newly cloned block itself as the root, so use "path": [] when editing top-level fields on the cloned block.

4.3 All 13 BLK Data Types

When you write a plain JSON primitive, the patcher infers the BLK type from any existing parameter of the same name on that block (falling back to string, bool, int for integers, or real for non-integers). To guarantee exact binary types—especially when setting a float parameter to a whole number like 2.0, which JSON parses as integer 2—write { "type": "<type>", "value": <val> }:

typeText BLK Suffixvalue Example & Notes
string:t"us_m2a4"
int:i120 (signed 32-bit integer)
real:r1.5 (encoded strictly as 32-bit float :r even if written as 2)
bool:btrue / false (yes / no in text BLK)
int64:i64"133700000000000000" or integer (signed 64-bit integer)
point2:p2[1.0, 2.5] (2 floats)
point3:p3[0.0, 1.5, -2.0] (3 floats)
point4:p4[0.0, 1.0, 0.0, 1.0] (4 floats)
ipoint2:ip2[10, 20] (2 integers)
ipoint3:ip3[1, 2, 3] (3 integers)
ipoint4:ip4[0, 1, 2, 3] (4 integers)
color:c[255, 128, 0, 255] ([r, g, b, a]) or unsigned packed integer 0xAARRGGBB
matrix:mArray of 12 floats (4×3 transform matrix)

5. Battle Rating (BR) ↔ Internal mrank (economicRank*) Conversion & Lookup Table

A classic question when opening wpcost.blk for the first time is: why are there no 11.7 or 12.7 Battle Rating numbers anywhere in the file?

Internally, War Thunder stores displayed Battle Ratings (BR) as zero-based non-negative integers called mrank (stored in economicRank* fields), where every 3 integer steps equal 1.0 BR and fractional steps cycle .0 → .3 → .7:

  • Forward formula (mrank → displayed BR): BR = 1.0 + Math.floor(mrank / 3) + [0, 0.3, 0.7][mrank % 3]
  • Reverse formula (displayed BR → mrank): (wholePart - 1) × 3 plus the decimal step (+0 for .0, +1 for .3, +2 for .7). For example, 11.7 → (11 - 1) × 3 + 2 = 32!

5.1 Complete mrank ↔ Displayed BR Lookup Table

mrankDisplayed BRmrankDisplayed BRmrankDisplayed BRmrankDisplayed BR
01.0104.3207.73011.0
11.3114.7218.03111.3
21.7125.0228.33211.7
32.0135.3238.73312.0
42.3145.7249.03412.3
52.7156.0259.33512.7
63.0166.3269.73613.0
73.3176.72710.03713.3
83.7187.02810.33813.7
94.0197.32910.73914.0

5.2 Legacy Mode Suffixes in wpcost.blk vs Tech-Tree Tier rank

War Thunder retains internal field names from its alpha era—be careful not to confuse tech-tree tier rank with matchmaking BR economicRank*:

Field NameValue RangeMeaning
rank1 .. 8Tech-Tree Era Tier (Rank I – VIII): controls which horizontal tier row the vehicle occupies, tier unlock gates, and default store rank-tier pricing
economicRankArcade0 .. 39+Arcade Battles (AB) matchmaking mrank
economicRankHistorical0 .. 39+Realistic Battles (RB) default matchmaking mrank (RB was originally called *Historical Battles*)
economicRankSimulation0 .. 39+Simulator Battles (SB) default matchmaking mrank
economicRankTankHistorical0 .. 39+*(Optional)* Split Ground RB mrank for aircraft/helicopters with separate air vs ground BRs; falls back to economicRankHistorical when omitted
economicRankTankSimulation0 .. 39+*(Optional)* Split Ground SB mrank for aircraft/helicopters

6. shop.blk Anatomy & units.csv Localization Suffixes

6.1 The 4-Level Hierarchy of config/shop.blk

Inside char.vromfs.bin, config/shop.blk organizes every nation's research tree into a uniform 4-level hierarchy:

text
country_usa (or country_germany / country_ussr / country_britain / country_japan / country_china / ...)
 └─ army | helicopters | aviation | ships | boats
     ├─ range { ... }       <-- range[0]: 1st vertical column (e.g. US Light Tank line)
     ├─ range { ... }       <-- range[1]: 2nd vertical column (e.g. US Medium Tank line, containing folder us_sherman_group)
     ├─ range { ... }       <-- range[2]..range[4]: remaining regular Silver Lions research columns
     └─ range { ... }       <-- range[5]..range[6]: right-hand Golden Eagle / Pack / Event / Squadron columns

Keep three rules in mind when writing shop.blk.patch.jsonc:

  1. Each sibling range block is one vertical column in the tech tree: since every column block is named range, address them left-to-right (zero-based) as "range[0]", "range[1]", "range[5]", etc.;
  2. Collapsible folder groups (*_group): when multiple variants share one tech-tree folder, range contains a child block ending in _group (e.g. us_sherman_group) whose children are the grouped vehicles; the folder's display label comes from shop/group/<group_name> in units.csv;
  3. Why is the prerequisite arrow field named reqAir even on tanks and ships? War Thunder began life as an aviation-only game (*World of Planes*), so air / aircraft remained the universal internal noun for any unit. Consequently, reqAir defines the research prerequisite vehicle across tanks, helicopters, aircraft, and ships alike!
    • Setting reqAir:t="us_m2a4" in wpcost.blk requires owning us_m2a4 before researching the unit;
    • Inside a range column in shop.blk: consecutive vehicles with no reqAir property automatically connect with vertical arrows; reqAir:t="us_m2a4" draws an explicit arrow from us_m2a4; and reqAir:t="" (empty string) explicitly breaks the arrow from the vehicle above it (used at mid-column gaps and throughout the right-hand premium/pack columns).

6.2 All 4 lang/units.csv Keys & Incremental CSV Merging

When localizing a vehicle <id> in client/packs/lang.vromfs.bin/lang/units.csv.patch.csv, War Thunder uses 4 standard localization keys for different UI contexts and HUD distances:

Key PatternWhere It Appears in GameExample (for us_m2a4_mod_demo)
<id>_shopTech-tree card, crew slot bar, and local web store card short name"M2A4 (Mod Demo)" / "M2A4(教学改型)"
<id>_0Stat-card header, research completion modal, and battle debriefing full formal title"Light Tank M2A4 (Mod Demo)" / "M2A4 轻型坦克(教学改型)"
<id>_1In-battle medium-distance 3D HUD marker name"M2A4 Demo" / "M2A4 教学型"
<id>_2In-battle far-distance HUD marker / compact killfeed short name"M2A4" / "M2A4"

Example client/packs/lang.vromfs.bin/lang/units.csv.patch.csv:

csv
"<ID|readonly|noverify>";"<English>";"<Chinese>";"<HChinese>"
"us_m2a4_mod_demo_shop";"M2A4 (Mod Demo)";"M2A4(教学改型)";"M2A4(教學改型)"
"us_m2a4_mod_demo_0";"Light Tank M2A4 (Mod Demo)";"M2A4 轻型坦克(教学改型)";"M2A4 輕型坦克(教學改型)"
"us_m2a4_mod_demo_1";"M2A4 Demo";"M2A4 教学型";"M2A4 教學型"
"us_m2a4_mod_demo_2";"M2A4";"M2A4";"M2A4"
  • Fields must be separated by semicolons ; and wrapped in double quotes, with column headers on line 1 (list only the language columns you want to populate; omitted columns keep their stock values or default to empty);
  • Existing row keys update only your non-empty columns in place; new keys are appended to the end of the file.

7. Patching Root config.blk (client/config-blk.patch.jsonc)

If your mod needs to adjust the client root config.blk (for example enabling sound mods via sound{ enable_mod:b=yes } or setting a custom hangar hangarBlk:t="..."), place a standard BLK patch at client/config-blk.patch.jsonc:

jsonc
{
  "ops": [
    {
      "op": "setParam",
      "path": ["sound"],
      "name": "enable_mod",
      "value": { "type": "bool", "value": true },
      "createBlocks": true
    }
  ]
}

The launcher backs up the stock config.blk to wtoffline/stock/config.blk before applying patches and restores it automatically when no enabled mod touches config.blk.


8. End-to-End Walkthrough: Clone a Playable Standalone Tank (us_m2a4_mod_demo) in 5 Minutes

Let's connect every piece from this chapter into a complete, copy-pasteable mod that derives a standalone us_m2a4_mod_demo light tank from stock us_m2a4—boosted to 90 km/h, rated at BR 1.3 (mrank = 1), and wired into US Ground Rank I with a research arrow from M2A4. Because every player profile owns the reserve us_m2a4 from the start, you can see the new tank in the US tree and Test Drive it immediately!

8.1 Mod Folder Tree

Create demo-standalone-m2a4/ inside your global mods/ directory:

text
mods/demo-standalone-m2a4/
├─ mod.jsonc
└─ client/
   └─ packs/
      ├─ aces.vromfs.bin/
      │  └─ gamedata/units/tankmodels/
      │     └─ us_m2a4_mod_demo.blk          # ① Tank physics/armor/weapons (copied from stock us_m2a4.blk)
      ├─ char.vromfs.bin/
      │  └─ config/
      │     ├─ wpcost.blk.patch.jsonc        # ② Clone economy, BR, modifications & ammo racks
      │     ├─ shop.blk.patch.jsonc          # ③ Insert into US Army column 0 (Rank I)
      │     └─ unittags.blk.patch.jsonc      # ④ Clone unit class tags & test-drive mission
      └─ lang.vromfs.bin/
         └─ lang/
            └─ units.csv.patch.csv           # ⑤ Localized _shop / _0 / _1 / _2 names

8.2 Complete File Contents

Manifest mod.jsonc
jsonc
{
  "format": 1,
  "id": "demo.standalone-m2a4",
  "name": {
    "zh-CN": "独立衍生载具示例:M2A4 教学改型",
    "en": "Standalone Vehicle Demo: M2A4 Mod Demo"
  },
  "version": "0.1.0",
  "author": "YourName",
  "description": {
    "zh-CN": "克隆原版 us_m2a4 新增一辆独立可研发、可试驾的 90km/h 高速轻坦。",
    "en": "Clones stock us_m2a4 into a playable 90 km/h standalone tank in the US Rank I tree."
  },
  "api_version": "0.1-experimental",
  "game_versions": ["2.61.0.*"]
}
① Tank Model Definition client/packs/aces.vromfs.bin/gamedata/units/tankmodels/us_m2a4_mod_demo.blk

Extract stock gamedata/units/tankmodels/us_m2a4.blk from aces.vromfs.bin using any method from Chapter 01 Section 2, and save it as us_m2a4_mod_demo.blk. Keep model:t="m2a4" at the top (so the engine reuses the stock M2A4 3D mesh and textures) and raise its speed and acceleration (plain text .blk compiles to binary automatically on build):

blk
model:t="m2a4"
// ... (keep the rest of stock us_m2a4.blk unchanged; tweak mobility below to feel the difference) ...
maxFwdSpeed:r=90.0
maxRevSpeed:r=25.0
maxAccel:r=12.0
② Economy & BR Patch client/packs/char.vromfs.bin/config/wpcost.blk.patch.jsonc

Use cloneBlock to copy us_m2a4 (inheriting all weapons, shells, modifications, and backup settings), and set reqAir to "us_m2a4", RP cost to 1000, SL price to 500, and all mode mrank values to 1 (displayed BR 1.3):

jsonc
{
  "ops": [
    {
      "op": "cloneBlock",
      "from": ["us_m2a4"],
      "toParent": [],
      "newName": "us_m2a4_mod_demo",
      "replaceExisting": true,
      "ops": [
        { "op": "setParam", "path": [], "name": "reqAir", "value": "us_m2a4" },
        { "op": "setParam", "path": [], "name": "reqExp", "value": { "type": "int", "value": 1000 } },
        { "op": "setParam", "path": [], "name": "value", "value": { "type": "int", "value": 500 } },
        { "op": "setParam", "path": [], "name": "economicRank", "value": { "type": "int", "value": 1 } },
        { "op": "setParam", "path": [], "name": "economicRankArcade", "value": { "type": "int", "value": 1 } },
        { "op": "setParam", "path": [], "name": "economicRankHistorical", "value": { "type": "int", "value": 1 } },
        { "op": "setParam", "path": [], "name": "economicRankSimulation", "value": { "type": "int", "value": 1 } }
      ]
    }
  ]
}
③ Tech-Tree Slot Patch client/packs/char.vromfs.bin/config/shop.blk.patch.jsonc

Insert us_m2a4_mod_demo into country_usa -> army -> range[0] right after us_m3a1_stuart (just before the us_m5a1_stuart Rank II break) with an explicit reqAir: "us_m2a4", creating a clean Rank I side-branch arrow from M2A4 without disturbing the stock Stuart chain:

jsonc
{
  "ops": [
    {
      "op": "addBlock",
      "path": ["country_usa", "army", "range[0]"],
      "name": "us_m2a4_mod_demo",
      "after": "us_m3a1_stuart",
      "block": {
        "params": [
          { "name": "rank", "value": { "type": "int", "value": 1 } },
          { "name": "reqAir", "value": "us_m2a4" }
        ]
      }
    }
  ]
}
④ Unit Tags & Test-Drive Patch client/packs/char.vromfs.bin/config/unittags.blk.patch.jsonc

Clone us_m2a4 in unittags.blk so the new ID inherits type:t="tank", hangar_place:t="tank", the ground testFlight mission, and light-tank tags:

jsonc
{
  "ops": [
    {
      "op": "cloneBlock",
      "from": ["us_m2a4"],
      "toParent": [],
      "newName": "us_m2a4_mod_demo",
      "replaceExisting": true
    }
  ]
}
⑤ Localization Patch client/packs/lang.vromfs.bin/lang/units.csv.patch.csv

Copy the 4-row CSV snippet from Section 6.2 above. Enable the mod in the launcher, start the game, open the US Ground Rank I tree, and right-click M2A4 (Mod Demo) › Test Drive to take your 90 km/h light tank for a spin!

03 · 添加全新 3D 模型与贴图载具

本章专门讲解如何在 WTOffline 中制作带自定义 3D 模型(.grp)和贴图包(.dxp.bin)的全新载具模组,让多款不同作者的新车模组同时叠加共存、跨盘零拷贝秒挂、关闭即还原。


1. 核心术语通俗说明与跨盘零拷贝机制

在接触 3D 载具模组时,你会遇到以下 4 个高频底层名词——其实它们非常直观:

名词 / 后缀通俗解释
.grpDagor 引擎的 3D 模型与骨架归档文件(由官方 War Thunder CDK AssetViewer / 导出器编译生成),内含多级细节网格(LOD)、骨骼动画节点(animChar)、碰撞体与内构损伤模块(DM)几何体。
.dxp.binDagor 引擎的批量压缩贴图包,把一辆或多辆载具用到的多张漫反射、法线、金属度贴图打包在同一个文件里供 .grp 材质按名索引。
.ddsx单张 Dagor 压缩贴图文件(DDSx),常用于 UI 资料卡载具立绘(如 ui/images.vromfs.bin/units/<载具id>.ddsx)或涂装单贴图。
NTFS 目录联接点(Junction)可以理解成 Windows 文件系统底层的“零拷贝文件夹快捷方式”:游戏引擎访问 <游戏副本>/content/pkg_user/<模组ID> 时,操作系统直接把读写透明指向你放在任意盘符 mods/ 里的源文件夹——无需管理员权限、跨盘可用、占用 0 字节额外硬盘空间、挂载和拆除只需约 1 毫秒!

引擎是如何自动发现 client/addon/ 的?

经对 2.61.0.x 客户端 aces.exe 与 aces.vromfs.bin/config/settings.blk 核实:

  • 构建器会自动把所有已启用模组的挂载路径注册进 config/settings.blk 的 addons、addons_no_check 与 addonsWithBasePath 三个列表;
  • 凡是路径位于 /pkg_user/ 下的扩展目录(默认挂载到 <游戏副本>/content/pkg_user/<安全模组ID>),引擎会自动跳过 res/grp_hdr.vromfs.bin 包头强制校验,直接扫描 <目录>/res/ 下的全部 .grp 模型与 .dxp.bin 贴图包并注册进全局资源管理器;
  • 如果你的模组附带了正式 CDK 编译生成的 res/grp_hdr.vromfs.bin,构建器会自动改挂到 <游戏副本>/content/pkg_wto_<安全模组ID>,交给引擎原生的 grp_hdr 加载器处理;
  • 关闭模组时启动器只拆除该目录联接点本身,不会删改 mods/ 里的源文件。

2. 添加一辆全新 3D 模型载具的 6 步清单

假设你的模组 ID 是 demo.new-mbt,新车内部 ID 叫 us_mbt_demo:

text
mods/demo-new-mbt/
├─ mod.jsonc
└─ client/
   ├─ addon/
   │  └─ res/
   │     ├─ us_mbt_demo.grp                # ① 3D 模型、骨架、碰撞体(CDK 导出)
   │     └─ us_mbt_demo.dxp.bin            # ① 压缩贴图包(DDSx)
   └─ packs/
      ├─ aces.vromfs.bin/
      │  └─ gamedata/units/tankmodels/
      │     └─ us_mbt_demo.blk             # ② 载具物理、装甲、炮塔、武器配置(文本 BLK 自动编译)
      ├─ char.vromfs.bin/
      │  └─ config/
      │     ├─ wpcost.blk.patch.jsonc      # ③ 价格、研发点、权重、改装件(用 cloneBlock 最快)
      │     ├─ shop.blk.patch.jsonc        # ④ 挂进对应国家科技树纵列位置
      │     └─ unittags.blk.patch.jsonc    # ④ 注册载具类型、机库车位、试车场与标签
      ├─ lang.vromfs.bin/
      │  └─ lang/
      │     └─ units.csv.patch.csv         # ⑤ 中英文名称(_shop、_0、_1、_2)
      ├─ ui/atlases.vromfs.bin/
      │  └─ gameuiskin/
      │     └─ us_mbt_demo_ico.svg         # ⑥ 科技树与本地商城剪影图标(文件名必须全小写)
      └─ ui/images.vromfs.bin/
         └─ units/
            └─ us_mbt_demo.ddsx            # ⑥ 资料卡/乘员栏载具大图(可选,缺失时自动回退占位图)

关键核对要点

  1. 保持三处载具内部 ID 完全一致:tankmodels/us_mbt_demo.blk 文件名(或空军 flightmodels/us_jet_demo.blk)、wpcost.blk 块名、shop.blk 块名与 unittags.blk 块名必须一字不差。
  2. ui/atlases.vromfs.bin 图标路径必须全小写:原版图标包内部键名统一为全小写,请命名为 gameuiskin/<全小写载具id>_ico.svg(本地网页商店的商品卡片也会自动读取这张 SVG 图标!)。
  3. 验证 .blk 里的模型资产名与 .grp 一致:gamedata/units/tankmodels/us_mbt_demo.blk 顶部的 model:t="..." 名称必须与你在 CDK 中导出 .grp 时的资产名完全一致。

3. 银狮研发车 vs gift 商城礼包车(以及 AI 机器人池准入规则)

在 wpcost.blk.patch.jsonc 和 shop.blk.patch.jsonc 中,你可以自由决定这辆新车是走常规银狮研发线还是走本地网页商城礼包:

方式 A:常规银狮科技树研发车(推荐希望 AI 也能开这辆车出战时使用)

  • 在 wpcost.blk 中设置常规 value(银狮售价)与 reqExp(研发点),不要设置 gift、premPackAir、costGold、event 或 researchType(联队车标记),也不要在 shop.blk 设置 showOnlyWhenBought:b=yes;
  • 自动进入对局 AI 机器人池:本地服务器的分房机器人选择器(battle-ranks.ts)会自动把已挂入科技树(shop.blk)且不含 gift、premPackAir、event、researchType、showOnlyWhenBought 标记的常规银狮科技树载具纳入对应国家与分房权重的 AI 出战池!这意味着你在单机对局里也能遇到驾驶你自制新车的友军和敌军 AI。

方式 B:本地网页商城礼包车(gift:t="msi_notebook")

很多模组作者在翻看原版 wpcost.blk / shop.blk 时会好奇:为什么满地都是 gift:t="msi_notebook"?

  • 在原版战雷中,只要载具块带有任意非空的 gift:t="..." 字符串(官方历史遗留常填 "msi_notebook" 等推广代号),客户端就会把该车识别为“需通过商店礼包购买解锁的礼品车”,点击「购买」按钮时会拉起商店页面而非扣除银狮/金鹰;
  • WTOffline 自动生成本地商店商品:构建器扫描 wpcost.blk 时,会自动为每一辆带 gift 参数的载具注册确定性的本地商城商品 ID wto_pack_<载具ID>(例如 wto_pack_us_mbt_demo)与对应 GUID:
    • 哪怕你一行服务端配置都不写,本地网页商店也会按该车的 rank 等级自动套用默认档位定价与金鹰/高账赠品,玩家点开游戏内置商店就能直接购买解锁!
    • 如果想给它单独定 GJN 售价和附赠金鹰/高账天数,只需在 server/tuning/store.jsonc 的 vehiclePacks.byVehicle 下加一行即可(详见第 05 章)。
  • 注意 AI 机器人池边界:带 gift、premPackAir、event、researchType 或 showOnlyWhenBought 标记的特殊载具不会自动混入常规 AI 机器人池,避免稀有礼包原型车在普通对局满街跑。

4. 配套涂装、瞄具、音效与原生目录的边界

  • 独立涂装 / 瞄具 / 单人任务:玩家照旧直接放进游戏目录原生的 UserSkins/、UserSights/、UserMissions/ 即可,启动器完全不会干预或清理这些原生文件夹,无需封装成模组;
  • 大型新车整合包顺带附赠的配套资源:如果你的新车模组配套做好了专属涂装、现代火控瞄具或专属火炮音效包,可以放进 client/files/ 随模组一起启停:
    • client/files/UserSkins/mod_us_mbt_demo_camo/...(单模组独占子目录 → 自动走跨盘 NTFS Junction 零拷贝秒挂)
    • client/files/UserSights/us_mbt_demo/...(单模组独占子目录 → 自动走跨盘 NTFS Junction 零拷贝秒挂)
    • client/files/sound/mod/my_cannon.bank(多模组共享的平铺目录散文件 → 依次尝试文件符号链接 → 同盘硬链接 → 按大小与修改时间比对的增量缓存复制)
  • 玩家原生文件保护:如果 client/files/ 中的目标路径在游戏目录里已经作为玩家手动放置的原生文件/文件夹存在,启动器会自动跳过该项并在日志中输出冲突告警,不会覆盖或删除玩家的自有文件。

03 · Adding Custom 3D Vehicle Models & Textures

This chapter explains how to build brand-new 3D vehicle mods shipping custom geometry (.grp) and texture packs (.dxp.bin) in WTOffline so multiple vehicle packs from different authors stack cleanly, mount across drives with zero copying, and roll back cleanly when disabled.


1. Plain-Language Asset Glossary & Zero-Copy Mounting

When working with 3D vehicle mods, you will encounter four core asset and filesystem terms:

Term / ExtensionPlain-Language Meaning
.grpDagor Engine 3D geometry & skeleton archive (exported from the official War Thunder CDK AssetViewer / exporter), containing multi-LOD meshes, animation skeleton nodes (animChar), collision volumes, and internal damage-model (DM) parts.
.dxp.binDagor Engine compressed texture pack, bundling multiple diffuse, normal, and metallic/roughness DDSx textures referenced by name inside .grp materials.
.ddsxA single Dagor compressed texture file (DDSx), commonly used for UI stat-card vehicle portraits (ui/images.vromfs.bin/units/<unit_id>.ddsx) or standalone skin textures.
NTFS Directory JunctionThink of it as an OS-level zero-copy folder shortcut built into Windows NTFS: when the game engine opens <copy>/content/pkg_user/<modId>, Windows transparently serves the files straight from your mods/ folder on any drive—no administrator rights needed, works across drives, consumes 0 extra disk bytes, and mounts/unmounts in ~1 ms!

How the Engine Discovers client/addon/ Automatically

Verified directly against 2.61.0.x aces.exe (dlContent.cpp) and aces.vromfs.bin/config/settings.blk:

  • The patcher automatically registers every enabled mod's addon mount path into addons, addons_no_check, and addonsWithBasePath inside config/settings.blk;
  • Any addon path under /pkg_user/ (mounted by default at <copy>/content/pkg_user/<safeModId>) skips the mandatory res/grp_hdr.vromfs.bin header check and directly scans <addon>/res/ for all .grp model and .dxp.bin texture archives, registering them into the global asset manager;
  • If your mod ships an official CDK-compiled res/grp_hdr.vromfs.bin, the patcher mounts it at <copy>/content/pkg_wto_<safeModId> so the native grp_hdr loader handles it;
  • Disabling a mod removes only the directory junction itself and never deletes or modifies your source files inside mods/.

2. 6-Step Checklist for a Custom 3D Vehicle

Suppose your mod ID is demo.new-mbt and your new vehicle's internal ID is us_mbt_demo:

text
mods/demo-new-mbt/
├─ mod.jsonc
└─ client/
   ├─ addon/
   │  └─ res/
   │     ├─ us_mbt_demo.grp                # ① 3D meshes, skeleton & collision (CDK export)
   │     └─ us_mbt_demo.dxp.bin            # ① Compressed texture pack (DDSx)
   └─ packs/
      ├─ aces.vromfs.bin/
      │  └─ gamedata/units/tankmodels/
      │     └─ us_mbt_demo.blk             # ② Physics, armor, turret & weapons (text BLK compiles automatically)
      ├─ char.vromfs.bin/
      │  └─ config/
      │     ├─ wpcost.blk.patch.jsonc      # ③ Price, RP, BR & modifications (fastest via cloneBlock)
      │     ├─ shop.blk.patch.jsonc        # ④ Tech-tree column & position
      │     └─ unittags.blk.patch.jsonc    # ④ Unit class, hangar slot, test-drive mission & tags
      ├─ lang.vromfs.bin/
      │  └─ lang/
      │     └─ units.csv.patch.csv         # ⑤ Localized names (_shop, _0, _1, _2)
      ├─ ui/atlases.vromfs.bin/
      │  └─ gameuiskin/
      │     └─ us_mbt_demo_ico.svg         # ⑥ Tech-tree & local web store silhouette icon (all lowercase!)
      └─ ui/images.vromfs.bin/
         └─ units/
            └─ us_mbt_demo.ddsx            # ⑥ Stat-card / crew-slot portrait (optional; falls back to placeholder)

Key Verification Checks

  1. Keep the vehicle's internal ID identical everywhere: the tankmodels/us_mbt_demo.blk filename (or flightmodels/us_jet_demo.blk for aircraft) and the block names in wpcost.blk, shop.blk, and unittags.blk must match character for character.
  2. ui/atlases.vromfs.bin icon paths must be all lowercase: stock icon packs store paths in lowercase, so name your icon gameuiskin/<lowercase_unit_id>_ico.svg (the local web store also displays this exact SVG on pack cards!).
  3. Match .blk asset names to .grp exports: model:t="..." inside gamedata/units/tankmodels/us_mbt_demo.blk must match the exact asset name exported into your .grp archive from the CDK.

3. Regular Tech-Tree Vehicles vs gift Store Packs (& AI Bot Pool Rules)

In wpcost.blk.patch.jsonc and shop.blk.patch.jsonc, you can wire your custom vehicle either as a regular Silver Lions researchable vehicle or as a local web store pack vehicle:

  • Set normal value (Silver Lions price) and reqExp (Research Points) in wpcost.blk, and omit gift, premPackAir, costGold, event, and researchType (squadron tag), as well as showOnlyWhenBought:b=yes in shop.blk;
  • Automatically joins the AI bot pool: the local server's matchmaking bot selector (battle-ranks.ts) automatically includes tech-tree vehicles (inTechTree in shop.blk) that have none of gift, premPackAir, event, researchType, or showOnlyWhenBought! Both friendly and enemy AI bots at matching BRs and nations will spawn in your custom vehicle during offline battles.

Option B: Local Web Store Pack Vehicle (gift:t="msi_notebook")

Modders inspecting stock wpcost.blk / shop.blk often wonder: why do dozens of pack vehicles say gift:t="msi_notebook"?

  • In stock War Thunder, any non-empty gift:t="..." string (Gaijin historically reused promo strings like "msi_notebook" across countless store vehicles) marks the vehicle as an external store pack/gift unit whose Order button opens the web store instead of spending Silver Lions or Golden Eagles;
  • WTOffline auto-generates a local web store bundle: during copy building, WTOffline scans every vehicle carrying gift in wpcost.blk and automatically registers a deterministic local store product ID wto_pack_<unitId> (e.g. wto_pack_us_mbt_demo) and bundle GUID:
    • Even with zero server config, the local web store automatically prices the pack using vehiclePacks.byRank for the vehicle's rank tier so players can buy and unlock it right away in the in-game store!
    • To customize its GJN price, Golden Eagles bonus, or Premium days, simply add an entry under vehiclePacks.byVehicle in server/tuning/store.jsonc (see Chapter 05).
  • AI Bot Pool Note: vehicles carrying gift, premPackAir, event, researchType, or showOnlyWhenBought are intentionally excluded from the automatic AI bot pool so rare pack prototypes do not flood standard bot lineups.

4. Companion Skins, Sights, Sounds & the Native Folder Boundary

  • Standalone skins, sights & single-player missions: players should continue placing standalone files directly into the game's native UserSkins/, UserSights/, and UserMissions/ folders—the launcher never touches or deletes player-managed native folders, and they do not need to be wrapped as mods;
  • Companion assets bundled inside a large vehicle overhaul mod: if your custom vehicle mod includes dedicated camouflages, custom FCS gun sights, or custom cannon sound banks, place them under client/files/ so they mount and unmount together with the mod:
    • client/files/UserSkins/mod_us_mbt_demo_camo/... (mod-exclusive subfolder → mounts across drives via zero-copy NTFS Junction)
    • client/files/UserSights/us_mbt_demo/... (mod-exclusive subfolder → mounts across drives via zero-copy NTFS Junction)
    • client/files/sound/mod/my_cannon.bank (shared flat directory file → tries file symlink → same-drive hardlink → size/mtime incremental cached copy)
  • Native Player File Protection: if any target path under client/files/ already exists in the game folder as a player-created native file or folder, the launcher skips that item with a log warning and never overwrites or deletes player content.

04 · 客户端 GUI 补丁与声明式 EXE 补丁

实验期提示:界面脚本补丁(gui-patches)与声明式 exe 补丁(exe-patches)直接依赖目标游戏客户端的代码结构,游戏版本更新或离线核心补丁演进时可能需要同步维护。


1. 先懂概念:战雷原生 DaGui 界面三件套(.tpl + .css + .nut)

《战争雷霆》机库与大厅界面由 Dagor 自研的 DaGui 框架驱动(全部存放在 gui.vromfs.bin 包内)。一个完整的界面弹窗通常由三类文本文件配合完成:

文件后缀角色定位通俗解释
.tplHandyman 布局模板类似 HTML + Mustache 模板(如 gui/missions/wtomapselectormodal.tpl),声明窗口骨架、按钮节点、id 与数据占位符(如 <<wndTitle>>、{{#cards}}...{{/cards}})。
.cssDaGui 样式表定义节点宽高、边距、背景色、字体大小以及自定义状态属性选择器(如 [wtoSelected=yes])。
.nutQuirrel 界面逻辑脚本战雷使用的类 JS/Lua 强作用域脚本语言(Squirrel 衍生版),继承 BaseGuiHandlerWT 处理按钮点击、渲染 .tpl 并与本地服务器通信。

客户端界面扩展黄金准则:「大块逻辑独立新建 + 极简增量补丁挂入口」

像官方模板 templates/official-map-selector 一样,给游戏做新功能界面的最佳做法是:

  1. 把你自己的弹窗 .nut、.tpl、.css 作为新文件放进 client/packs/gui.vromfs.bin/:独立文件与其他模组零冲突、极易维护;
  2. 只用几行 client/gui-patches/ 增量补丁修改原版文件:挂一个入口按钮,并在全局样式表入口 gui/css.css 里注册你的新 .css!

必看高频踩坑:新增的独立 .css 不会被 DaGui 自动加载!
仅仅把 gui/missions/wtomapselector.css 放进 client/packs/gui.vromfs.bin/ 是不会生效的!DaGui 只从根入口 gui/css.css 加载样式表,因此你必须同时在 client/gui-patches/ 里给 gui/css.css 打一条补丁,追加一行 @import "missions\wtomapselector.css"(注意:DaGui 的 gui/css.css 路径相对于 gui/ 目录,使用反斜杠 \ 且行尾不写分号,详见下方 2.2 节真实示例)。


2. client/gui-patches/ 增量补丁格式与匹配规则

client/gui-patches/ 不仅能改 .nut 脚本,对 gui.vromfs.bin 里的 .nut、.tpl 和 .css 文本文件完全通用!每个补丁放在一个含 patch.jsonc 的子目录(支持多层子目录组织):

text
client/gui-patches/
└─ mode-select-map-selector-button/
   ├─ css/
   │  ├─ patch.jsonc
   │  ├─ find-css.css
   │  └─ replace-css.css
   ├─ tpl/
   │  ├─ patch.jsonc
   │  ├─ find-nav-right.tpl
   │  └─ replace-nav-right.tpl
   └─ script/
      ├─ patch.jsonc
      ├─ find-imports.nut
      ├─ replace-imports.nut
      ├─ find-buttons.nut
      └─ replace-buttons.nut

2.1 .nut 脚本补丁示例

jsonc
// Adds a custom entry button to the mode selection panel.
{
  "id": "my-mod/add-button",
  "title": "Add custom button to mode selector",
  "features": [],
  "variants": [
    {
      "written_for": "2.61.0.58",
      "file": "scripts/gamemodes/gamemodeselect.nut",
      "edits": [
        {
          "find": "find-imports.nut",
          "replace": "replace-imports.nut"
        },
        {
          "find": "find-buttons.nut",
          "replace": "replace-buttons.nut"
        }
      ]
    }
  ]
}

2.2 注册独立 .css 到 gui/css.css 的真实补丁示例

jsonc
// client/gui-patches/my-style/patch.jsonc
{
  "id": "my-mod/register-css",
  "title": "Include custom stylesheet in gui/css.css",
  "features": [],
  "variants": [
    {
      "written_for": "2.61.0.58",
      "file": "gui/css.css",
      "edits": [
        {
          "find": "find-css.css",
          "replace": "replace-css.css"
        }
      ]
    }
  ]
}

find-css.css:

css
@import "missions\mapPreferences.css"

replace-css.css:

css
@import "missions\mapPreferences.css"
@import "missions\wtomapselector.css"

2.3 匹配规则与大小写注意事项

  1. variant.file 必须全小写、精确区分大小写! 原版 gui.vromfs.bin 归档内的所有文件路径均为全小写(例如 scripts/gamemodes/gamemodeselect.nut、gui/gamemodeselect/gamemodeselect.tpl、gui/css.css)。虽然 Quirrel 代码里的 from "%scripts/gameModes/..." 导入语句不区分大小写,但 gui-patches 构建器在包内查找 variant.file 时做的是严格区分大小写的精确键匹配——如果写成驼峰 scripts/gameModes/gameModeSelect.nut,会直接报错 the data pack has no script ...!放进 client/packs/gui.vromfs.bin/ 的新增文件也请统一使用全小写路径。
  2. 每条 find 必须唯一命中 1 次: 每条 edit 的 find 原文片段在目标文件中需要恰好出现 1 次(自动兼容 \r\n 与 \n 换行差异);若出现 0 次或 ≥2 次,该补丁会整条跳过并记入 launcher.log,避免半应用写坏脚本。
  3. variants 与 written_for 的真实选择机制: written_for 只是便于阅读和报错排查的版本标注字符串,构建器不会按版本号盲选——它会对当前客户端文件逐一测试 variants 数组里的全部候选条目,且要求有且仅有 1 个 variant 能够完整命中(0 个命中 = 视为版本不匹配安全跳过;≥2 个同时命中 = 视为变体定义歧义直接拒绝)。
  4. 本地服务器地址占位符 {{LOCAL_ENDPOINT}}: 在任何 replace 文本中写入 {{LOCAL_ENDPOINT}},构建器都会自动将其替换为当前客户端绑定的本地服务器 127.0.0.1:<端口>(例如拼接内置浏览器 URL http://{{LOCAL_ENDPOINT}}/mods/demo.my-mod/panel)。离线版核心 GUI 补丁永远最先应用,各模组的 gui-patches 在其后按加载顺序依次叠加。

3. 必做检查:编译 sq.exe 并对完整 .nut 做字节码校验

战雷的 Quirrel 脚本在登录阶段预编译加载。如果 .nut 存在以下错误,游戏会在进入机库前一直卡死在「正在加载」界面:

  • 词法作用域重名冲突:局部变量名(let / local)与文件顶部 from "..." import * 导入的常量或原生函数重名;
  • 前向引用未声明函数或误用 Quirrel 保留字(如 base);
  • 误用反引号字符串 ` ... **:战雷内置 Quirrel VM 不支持 JS 风格反引号模板字符串,请统一使用 Quirrel 原生插值字符串 **$"hello {name}"`!

注意:sq.exe --syntax-check 只跑语法树解析,会漏掉作用域重名和未声明标识符错误;必须通过 compilestring(...) 触发完整字节码生成检查!

3.1 外部模组作者如何自行获取匹配的 sq.exe?

克隆 Gaijin 官方开源的 GaijinEntertainment/quirrel 仓库,检出与 2.61 客户端匹配的提交 19f17df9b6ee43c91ef5c635fd45970ec76c5dbe,用 CMake + Visual Studio(C++17)即可在数秒内编译出 sq.exe:

powershell
git clone https://github.com/GaijinEntertainment/quirrel.git quirrel-src
git -C quirrel-src checkout 19f17df9b6ee43c91ef5c635fd45970ec76c5dbe
cmake -S quirrel-src -B quirrel-build
cmake --build quirrel-build --config Release --target sq
# 产物位于 quirrel-build\bin\Release\sq.exe

3.2 正确用法:必须对「完整 .nut 文件」执行 compilestring

切勿拿半截 replace.nut 片段直接喂给 compilestring!
replace.nut 只是补丁上下文中的几行代码片段,单独编译必然报语法或未定义变量错误。你必须针对完整的 .nut 文件(即你新建的独立 .nut 全文,或者将 find/replace 应用到原版 .nut 之后的完整结果文件)运行检查:

  • 如果克隆了 WTOffline 源码仓库:仓库内的 tools/src/wtotools/gui_check.py 已经封装好全自动导入符号解析与 compilestring 沙箱,可一键对解包的 gui.vromfs.bin 应用补丁并完成全量字节码校验;
  • 单文件快速自检示例(将文件内顶部 import 绑定名作为第 3 参数占位表传入 compilestring):
powershell
& "quirrel-build\bin\Release\sq.exe" -e "let io = require('io'); let f = io.file('your_complete_script.nut', 'rb'); let src = f.readblob(f.len()).as_string(); f.close(); compilestring(src, 'your_complete_script.nut'); print('OK\n')"

4. 声明式 exe 补丁(client/exe-patches/)

高级模组可以直接复用 WTOffline 本体的 @wto/exepatch 引擎对 win64/aces.exe 做特征码定位补丁。请使用声明式补丁文件,不要直接打包或分发修改后的 aces.exe 可执行文件。

text
client/exe-patches/
└─ my-tweak/
   └─ patch.jsonc

patch.jsonc 结构示例:

jsonc
// Brief description of what this binary patch changes.
// Why the local server cannot do this alone.
// What happens if this patch is skipped.
{
  "id": "my-tweak",
  "title": "Example declarative exe patch",
  "features": [],
  "requires": [],
  "variants": [
    {
      "written_for": "2.61.0.58",
      "locate": {
        "kind": "signature",
        "pattern": "48 8B ?? ?? ?? ?? ?? 84 C0 74 ??",
        "captures": []
      },
      "edit": {
        "offset": 9,
        "asm": "nop; nop",
        "bytes": "90 90",
        "expect_original": "74 ??",
        "fixups": []
      }
    }
  ]
}

支持的 3 种定位器(locate.kind)

  • signature:字节特征码扫描(支持 ?? 通配字节与 captures 捕获相对偏移/跳转目标);
  • string_ref:按代码引用的固定 ASCII 字符串定位,可附加局部指令特征校验;
  • within:在依赖补丁或锚点所在的函数边界(基于 PE .pdata 异常表起止范围)内搜索局部特征。

核心隔离保护与冲突处理

  1. 核心离线与隔离补丁永远最先规划并锁定字节区间(涵盖断网隔离不连 Gaijin、不加载反作弊、存档目录与注册表隔离、禁止拉起官方启动器、本地 TLS/匹配公钥替换等);
  2. 任何模组 exe 补丁只要写入范围与核心补丁重叠 1 个字节,就会被构建器硬拒绝,并在日志中报错 overlaps protected core patch;
  3. 若两个不同模组的 exe 补丁写入同一段字节,后加载的补丁会被拒绝并明确报出冲突模组 ID;
  4. 若客户端更新后特征码未命中或 expect_original 不匹配,该模组补丁会安全跳过并记入 launcher.log,不会导致离线副本构建崩溃。

04 · Client GUI Patches & Declarative EXE Patches

Experimental Notice: GUI script patches (gui-patches) and declarative exe patches (exe-patches) depend directly on target client code layout and may require maintenance when the game or core offline patches update.


1. Plain-Language Intro: War Thunder's DaGui UI Triad (.tpl + .css + .nut)

War Thunder's hangar and lobby screens are powered by Dagor's native DaGui framework (packaged inside gui.vromfs.bin). Every screen or modal window combines three plain-text file types:

ExtensionRolePlain-Language Explanation
.tplHandyman Layout TemplateSimilar to HTML + Mustache (e.g. gui/missions/wtomapselectormodal.tpl); declares UI containers, buttons, element ids, and data-binding tags (<<wndTitle>>, {{#cards}}...{{/cards}}).
.cssDaGui StylesheetControls widths, heights, margins, colors, fonts, and custom attribute state selectors (such as [wtoSelected=yes]).
.nutQuirrel UI ScriptWar Thunder's statically-scoped scripting language (derived from Squirrel); subclasses BaseGuiHandlerWT to render .tpl views, handle button clicks, and call local server RPCs.

Best-Practice UI Pattern: "Standalone Files for Logic + Minimal Patch for Entry Hook"

Just like the bundled templates/official-map-selector mod, the cleanest way to add new UI is:

  1. Place your new standalone .nut, .tpl, and .css files under client/packs/gui.vromfs.bin/: standalone files have zero collision risk with other mods and survive game updates cleanly;
  2. Use minimal client/gui-patches/ edits on stock files: wire a button into an existing screen and register your stylesheet in gui/css.css!

Critical Rule: Standalone .css Files Are NOT Auto-Loaded by DaGui!
Dropping gui/missions/wtomapselector.css into client/packs/gui.vromfs.bin/ alone has no effect! DaGui loads stylesheets solely through the root manifest gui/css.css, so you must also patch gui/css.css via client/gui-patches/ to append @import "missions\wtomapselector.css" (note: paths inside gui/css.css are relative to gui/, use backslashes \, and have no trailing semicolon—see the real example in Section 2.2 below).


2. client/gui-patches/ Format & Matching Rules

client/gui-patches/ is not limited to .nut files—it works identically on .nut scripts, .tpl templates, and .css stylesheets inside gui.vromfs.bin! Each patch lives in a folder containing patch.jsonc (nested subdirectories are supported):

text
client/gui-patches/
└─ mode-select-map-selector-button/
   ├─ css/
   │  ├─ patch.jsonc
   │  ├─ find-css.css
   │  └─ replace-css.css
   ├─ tpl/
   │  ├─ patch.jsonc
   │  ├─ find-nav-right.tpl
   │  └─ replace-nav-right.tpl
   └─ script/
      ├─ patch.jsonc
      ├─ find-imports.nut
      ├─ replace-imports.nut
      ├─ find-buttons.nut
      └─ replace-buttons.nut

2.1 .nut Script Patch Example

jsonc
// Adds a custom entry button to the mode selection panel.
{
  "id": "my-mod/add-button",
  "title": "Add custom button to mode selector",
  "features": [],
  "variants": [
    {
      "written_for": "2.61.0.58",
      "file": "scripts/gamemodes/gamemodeselect.nut",
      "edits": [
        {
          "find": "find-imports.nut",
          "replace": "replace-imports.nut"
        },
        {
          "find": "find-buttons.nut",
          "replace": "replace-buttons.nut"
        }
      ]
    }
  ]
}

2.2 Real Example: Registering a Standalone .css in gui/css.css

jsonc
// client/gui-patches/my-style/patch.jsonc
{
  "id": "my-mod/register-css",
  "title": "Include custom stylesheet in gui/css.css",
  "features": [],
  "variants": [
    {
      "written_for": "2.61.0.58",
      "file": "gui/css.css",
      "edits": [
        {
          "find": "find-css.css",
          "replace": "replace-css.css"
        }
      ]
    }
  ]
}

find-css.css:

css
@import "missions\mapPreferences.css"

replace-css.css:

css
@import "missions\mapPreferences.css"
@import "missions\wtomapselector.css"

2.3 Four Critical Path & Variant Rules (Must-Read)

  1. variant.file Must Be All Lowercase & Exact Case-Sensitive! Every file path inside stock gui.vromfs.bin is all lowercase (e.g. scripts/gamemodes/gamemodeselect.nut, gui/gamemodeselect/gamemodeselect.tpl, gui/css.css). Even though Quirrel from "%scripts/gameModes/..." imports are case-insensitive at runtime, the gui-patches builder looks up variant.file in the archive map via exact case-sensitive string match—writing camelCase like scripts/gameModes/gameModeSelect.nut fails immediately with the data pack has no script ...! Keep added files under client/packs/gui.vromfs.bin/ all lowercase as well.
  2. Every find Snippet Must Match Exactly Once: Each edit's find text must occur uniquely once in the target file (\r\n vs \n line endings are normalized automatically). If it occurs 0 times or ≥2 times, the entire patch is skipped safely and logged to launcher.log without half-applying edits.
  3. How variants and written_for Actually Work: written_for is purely an informational version label for logs and diagnostics. At build time, the builder tests all entries in variants against the client archive and requires an exact single match (1 matching variant applies; 0 matches skips safely as a build mismatch; ≥2 simultaneous matches rejects the patch as an ambiguous variant definition).
  4. {{LOCAL_ENDPOINT}} Placeholder: Any occurrence of {{LOCAL_ENDPOINT}} in replace text is automatically expanded to the client's bound local server 127.0.0.1:<port> (for example http://{{LOCAL_ENDPOINT}}/mods/demo.my-mod/panel for embedded browser pages). Core offline GUI patches always run first; mod gui-patches run afterward in load order.

3. Mandatory Check: Building sq.exe & Full Quirrel Bytecode Verification

War Thunder pre-compiles Quirrel UI scripts during login. Any of the following mistakes in a .nut file will cause the client to hang indefinitely on the "Loading" screen:

  • Lexical scope name collisions: declaring a let / local variable that shadows a symbol imported via from "..." import * at the top of the file;
  • Forward references to undeclared functions or accidental use of Quirrel reserved words (such as base);
  • JS-style backtick strings (` ... )**: unsupported by War Thunder's Quirrel VM—always use Quirrel's native string interpolation **$"hello {name}"` instead!

Note: sq.exe --syntax-check runs AST parsing only and misses lexical collisions and undeclared identifiers—you must invoke compilestring(...) so the full bytecode generator runs!

3.1 How External Modders Build a Matching sq.exe

Clone Gaijin's open-source GaijinEntertainment/quirrel repository, check out commit 19f17df9b6ee43c91ef5c635fd45970ec76c5dbe (matching 2.61 clients), and build sq with CMake + Visual Studio (C++17):

powershell
git clone https://github.com/GaijinEntertainment/quirrel.git quirrel-src
git -C quirrel-src checkout 19f17df9b6ee43c91ef5c635fd45970ec76c5dbe
cmake -S quirrel-src -B quirrel-build
cmake --build quirrel-build --config Release --target sq
# Output binary: quirrel-build\bin\Release\sq.exe

3.2 Run compilestring on a Complete .nut File (Not a Partial Snippet)

Note: Pass a complete .nut file to compilestring rather than an isolated replace.nut fragment.
replace.nut is only an in-place snippet and will fail out of context. Always run compilestring against a complete .nut file—either your standalone .nut script, or the full stock .nut file after applying your find/replace edits:

  • If you cloned the WTOffline repo: tools/src/wtotools/gui_check.py automatically resolves gui.vromfs.bin module exports, applies your gui-patches, and runs compilestring with stub bindings across every touched file;
  • Standalone full-file check example (pass a bindings table as the 3rd argument to compilestring if your file uses top-level from "..." import ... bindings):
powershell
& "quirrel-build\bin\Release\sq.exe" -e "let io = require('io'); let f = io.file('your_complete_script.nut', 'rb'); let src = f.readblob(f.len()).as_string(); f.close(); compilestring(src, 'your_complete_script.nut'); print('OK\n')"

4. Declarative EXE Patches (client/exe-patches/)

Advanced mods can reuse WTOffline's @wto/exepatch engine to apply signature-located binary patches to win64/aces.exe. Use declarative patch files instead of packaging or distributing modified aces.exe binaries.

text
client/exe-patches/
└─ my-tweak/
   └─ patch.jsonc

Example patch.jsonc:

jsonc
// Brief description of what this binary patch changes.
// Why the local server cannot do this alone.
// What happens if this patch is skipped.
{
  "id": "my-tweak",
  "title": "Example declarative exe patch",
  "features": [],
  "requires": [],
  "variants": [
    {
      "written_for": "2.61.0.58",
      "locate": {
        "kind": "signature",
        "pattern": "48 8B ?? ?? ?? ?? ?? 84 C0 74 ??",
        "captures": []
      },
      "edit": {
        "offset": 9,
        "asm": "nop; nop",
        "bytes": "90 90",
        "expect_original": "74 ??",
        "fixups": []
      }
    }
  ]
}

Supported Locators (locate.kind)

  • signature: byte pattern scan supporting ?? wildcards and captures for displacements / relative branch targets;
  • string_ref: locates code referencing a fixed ASCII string literal, with optional local instruction verification;
  • within: searches inside the PE .pdata function boundaries of a required patch or anchor site.

Core Isolation Protection & Conflict Handling

  1. Core offline & isolation patches are always planned first and their byte ranges are locked (covering Gaijin network block, anti-cheat bypass in offline copy, save/registry isolation, launcher suppression, and local TLS/matching keys);
  2. Any mod exe patch overlapping even 1 byte of a core patch is hard-rejected with overlaps protected core patch in launcher.log;
  3. If two mods' exe patches write to overlapping byte ranges, the later mod's patch is rejected with the conflicting mod ID;
  4. If a signature or expect_original check fails on a newer game version, that mod patch is skipped cleanly and logged to launcher.log without breaking the offline copy build.

05 · 服务端零代码数值叠加(Tuning)

本地服务器把离线版自定的对局倍率、房间与 AI 数量、商城礼包、市场物价、战利品箱、兑换码、初始存档货币、联队等规则统一收纳在 12 份 .jsonc 配置文件中。模组作者一行代码都不用写,只需在 server/tuning/ 下放置同名 .jsonc 文件即可按字段精准叠加覆盖。

在线浏览全部 12 份内置默认配置文件全文与注释:
WT-Offline apps/server/tuning/ 源码目录


1. 多层合并优先级(注意启动器玩家覆盖!)

每次启动本地服务器时,同名的 tuning/<名称>.jsonc 按以下顺序从低到高逐层合并(后一层覆盖前一层):

text
1. 离线版内置默认配置(apps/server/tuning/<名称>.jsonc)
2. 已启用模组 1 的 server/tuning/<名称>.jsonc
3. 已启用模组 2 的 server/tuning/<名称>.jsonc
   ...(按启动器「模组」页从上到下顺序依次叠加)
N. 玩家在启动器「数值」页保存的个人覆盖(<客户端数据目录>/tuning/<名称>.jsonc,优先级最高)
  • 排查提示:由于玩家在启动器「数值(Tuning)」页手动改过的项优先级高于模组,如果测试模组时发现某个 battle.jsonc 或 new-profile.jsonc 字段修改没有生效,可以先检查该客户端的启动器「数值」页是否之前手动改过同一项(恢复默认或查看 <数据目录>/tuning/*.jsonc 即可)。
  • 所有合并后的最终结果在服务器启动时都会经过严格类型与数值范围校验;字段名写错或数值越界时会直接报出文件名、字段名与期望范围。

2. 全部 12 份可叠加配置文件一览

文件名管辖内容常用结构类型典型模组用途
battle.jsonc银狮/研发倍率、房间人数、AI 数量与重生次数、分房跨度 brSpreadMrank、子模式概率、攻击无人机出生分平面键值对象自定义收益倍率、调整 16v16 人数、放宽/收紧分房跨度、改 AI 重生次数
battle-economy.jsonc各类战斗行为基价与对局结算经济公式参数嵌套键值对象精细调整击杀、助攻、占点收益占比
store.jsonc金鹰包、银狮包、高账档位、以及 vehiclePacks(含 multiVehiclePacks 列表、byRank 列表、byVehicle 字典)列表($listOps)+ 字典合并为新增 gift 载具定礼包价、打包自定义多车组合包
marketplace.jsonc交易所载具券与涂装券参考价、稀有度与手续费嵌套对象 + 字典合并调整交易所物价、给新增市场载具券定价
trophies.jsonc经典战利品箱 supplyTrophies(银狮箱、老兵箱)与活动车金鹰直购价 directVehicles列表($listOps)+ 对象新增自定义银狮/金鹰抽卡箱、调整稀有车掉率权重
supply-chests.jsonc新版外部库存补给箱与奖池配置列表($listOps)+ 对象新增自制外部库存补给箱
recycling.jsonc道具回收与零件再合成配方嵌套键值对象修改道具回收比例与产出权重
redeem-codes.jsonc高账/GJN 前缀码规则与一次性固定兑换码 fixedCodes对象 + 字典合并为你的整合包添加专属福利兑换码
new-profile.jsonc新建存档初始银狮、金鹰与 GJN 余额平面键值对象制作高起点爽玩预设或硬核白手起家预设
research.jsonc自动挑选默认下一研发目标策略平面键值对象调整自动研发接续行为
clans.jsonc联队人数上限、活跃度与预置离线联队列表对象 + 列表($listOps)添加模组专属预置联队
limits.jsonc单次购买道具数量上限、战报/日志保留上限平面键值对象提高批量开箱/购买上限或历史战报条数

3. 对象字典合并 vs 列表增量语法($listOps)

理解合并器的两条规则,就能避免多模组互相覆盖:

  1. 普通对象 / 键值字典(如 vehiclePacks.byVehicle、redeem-codes.jsonc 的 fixedCodes)→ 自动按字段名递归合并: 你只需要写出新增或要改的那几个键(例如只写 "my_new_tank": { ... }),其他原有的几百个键会自动保留,不需要也不能套 $listOps!
  2. JSON 数组字段(如 vehiclePacks.multiVehiclePacks、goldenEaglePacks、supplyTrophies)→ 默认整数组替换,叠加请用 { "$listOps": [...] }: 如果你直接写 "multiVehiclePacks": [ ... ],它会把原版和前序模组的多车礼包清空替换掉!为了让多个模组安全共存,请把该数组属性写成仅包含唯一键 "$listOps" 的包装对象(注意:该对象内不能有除 "$listOps" 以外的任何其他平级字段,否则不会被识别为列表增量指令!):
jsonc
// 正确示例:server/tuning/store.jsonc
// 注意:multiVehiclePacks、byRank、byVehicle 均嵌套在顶层 "vehiclePacks" 对象内部,且价格字段名为 "gjn"!
{
  "vehiclePacks": {
    // ① multiVehiclePacks 是数组 → 用 { "$listOps": [...] } 无损追加/修改/删除
    "multiVehiclePacks": {
      "$listOps": [
        {
          "op": "append",
          "items": [
            {
              "id": "mod_modern_duo_pack",
              "title": { "en": "Modern Duo Pack", "zh": "现代双车组合包" },
              "gjn": 49.99,
              "goldenEagles": 2000,
              "premiumDays": 15,
              "vehicles": ["us_m1a2_sep2_abrams", "germ_leopard_2a7v"]
            }
          ]
        },
        {
          "op": "upsertBy",
          "key": "id",
          "item": {
            "id": "wto_pack_two_fronts",
            "gjn": 19.99
          }
        },
        {
          "op": "removeBy",
          "key": "id",
          "value": "some_unwanted_pack_id"
        }
      ]
    },

    // ② byVehicle 是键值字典(非数组)→ 直接写载具 ID 即可递归合并,不要写 $listOps!
    "byVehicle": {
      "us_mbt_demo": {
        "gjn": 59.99,
        "goldenEagles": 2000,
        "premiumDays": 15
      }
    }
  }
}

支持的全部 4 种 $listOps 操作

  • append:{ "op": "append", "items": [ ... ] } — 将 items 依次追加到当前数组末尾;
  • prepend:{ "op": "prepend", "items": [ ... ] } — 将 items 插入到当前数组开头;
  • upsertBy:{ "op": "upsertBy", "key": "<唯一键名>", "item": { ... } } — 在数组中查找 [key] === item[key] 的首项,找到则按对象递归合并局部字段,找不到则追加到末尾;
  • removeBy:{ "op": "removeBy", "key": "<键名>", "value": <匹配值> } — 删除数组中全部 [key] === value 的条目。

4. 高频配置文件真实字段速查与即用范例

以下字段名均已对照 apps/server/tuning/*.jsonc 与服务端校验器逐一核实,可直接复制进你的 server/tuning/:

4.1 battle.jsonc(对局收益、人数、分房跨度与 AI 重生)

jsonc
{
  "rewardMultiplierSilverLions": 2.0,       // 银狮结算总倍率(默认 1.0)
  "rewardMultiplierResearchPoints": 2.0,    // 研发点结算总倍率(默认 1.0)
  "maxPlayers": 32,                         // 房间总席位(16v16 = 32:1 名本地玩家 + 最多 31 名 AI)
  "maxBots": 31,                            // AI 机器人上限(默认 31)
  "smallTeamsMaxPlayers": 16,               // 战术天空(small_teams_)小队空战总人数(默认 16 = 8v8)
  "subModeChance": 0.5,                     // 同时勾选子模式与常规模式时抽中子模式的概率(0..1)
  "brSpreadMrank": 3,                       // 分房权重浮动跨度(每 3 级 mrank = ±1.0 BR;设为 0 即严格同权重分房)
  "botPoolLimitPerType": 80,                // 单兵种写入 customBots 的候选载具上限
  "tankBotRespawns": 3,                     // 陆战多槽位对局每个 AI 的最大重生次数
  "airBotRespawns": 2,                      // 空战多槽位对局每个 AI 的最大重生次数
  "strikeUcavSpawnScore": 750,              // 陆战历史攻击无人机出生所需分数(默认 750)
  "nuclearEscalationStrategicBombers": true // 空战核升级子模式是否启用战略核轰炸机(B-52H / Tu-95M)
}

4.2 store.jsonc(本地网页商店与游戏内金鹰/银狮/礼包定价)

  • 顶层共 5 个字段:goldenEaglePacks(数组)、silverLionPacks(数组)、premiumForGoldenEagles(数组)、premiumForGjn(数组)、以及 vehiclePacks(对象);
  • vehiclePacks 下含 3 个子字段:
    • multiVehiclePacks(数组,用 $listOps):每项必填 id、vehicles(非空不重复载具 ID 数组)、gjn(最低 0.01)、goldenEagles(整数 ≥0)、premiumDays(整数 ≥0),可选 silverLions(整数 ≥0),且命名方式必须三选一——自定义双语标题 "title": { "en": "...", "zh": "..." }、复用科技树折叠组名 "groupKey": "shop/group/..."、或国家新手包 "starter": true;
    • byRank(数组,按 upToRank 升序兜底单车礼包价):每项含 upToRank、gjn、goldenEagles、premiumDays(可选 silverLions);
    • byVehicle(键值字典):键为 wpcost.blk 中带 gift 的载具 ID,值为 { "gjn"?, "goldenEagles"?, "premiumDays"?, "silverLions"? }(未填字段自动回退该车 rank 对应的 byRank 档位)。

4.3 new-profile.jsonc(新建存档开局货币)

jsonc
{
  "silverLions": 1000000, // 初始银狮(默认 150000)
  "goldenEagles": 5000,   // 初始金鹰(默认 500)
  "gjn": 50               // 初始 GJN 余额,支持最多两位小数(默认 0)
}

4.4 redeem-codes.jsonc(添加模组专属一次性兑换码)

fixedCodes 是键值字典(每个存档每个兑换码限领一次,不区分大小写,未填奖励项默认为 0),直接按兑换码名合并即可:

jsonc
{
  "fixedCodes": {
    "MYMOD-GIFT-2026": {
      "silverLions": 500000,
      "goldenEagles": 1000,
      "premiumDays": 7,
      "gjn": 25
    }
  }
}

4.5 trophies.jsonc(新增自定义银狮/金鹰战利品抽卡箱)

supplyTrophies 是数组,用 $listOps 追加新箱子,游戏客户端会自动按各奖品的 weight / weightTotal / weightEach 计算并展示公示掉率:

jsonc
{
  "supplyTrophies": {
    "$listOps": [
      {
        "op": "append",
        "items": [
          {
            "id": "mod_lucky_trophy",
            "iconStyle": "big_chest",
            "silverLions": 100000,
            "goldenEagles": 0,
            "prizes": [
              { "silverLions": 50000, "weight": 50 },
              { "silverLions": 250000, "weight": 20 },
              { "goldenEagles": 200, "weight": 10 },
              { "item": "item_universal_spare", "count": 3, "weight": 15 },
              { "eventVehicles": { "minRank": 3, "maxRank": 7, "pick": 6 }, "weightTotal": 5 }
            ]
          }
        ]
      }
    ]
  }
}

05 · Server Code-Free Tuning Overlays

The local server consolidates all offline-defined battle multipliers, session/bot capacities, web store bundles, marketplace prices, trophy chests, redeem codes, starter balances, and clan rules into 12 .jsonc configuration files. Mod authors can overlay individual fields without writing a single line of code simply by placing matching .jsonc files inside server/tuning/.

Browse all 12 default tuning files with full comments online:
WT-Offline apps/server/tuning/ Source Directory


1. Multi-Layer Merge Precedence (Watch Out for Launcher Player Overrides!)

Whenever the local server starts, each tuning/<name>.jsonc file is merged from lowest to highest priority (later layers override earlier ones):

text
1. Shipped offline defaults (apps/server/tuning/<name>.jsonc)
2. Enabled Mod 1's server/tuning/<name>.jsonc
3. Enabled Mod 2's server/tuning/<name>.jsonc
   ... (applied top-to-bottom in Launcher "Mods" load order)
N. Player overrides saved in the Launcher "Tuning" tab (<dataFolder>/tuning/<name>.jsonc — HIGHEST PRIORITY!)
  • Crucial Debugging Tip: Because player overrides saved in the Launcher's "Tuning" tab take highest priority, if a field in your mod's battle.jsonc or new-profile.jsonc appears to be ignored during testing, check whether your test client has a manual override saved in the Launcher Tuning tab (<dataFolder>/tuning/*.jsonc) and reset that field to default!
  • Every merged configuration is validated strictly for types and numeric bounds at server startup; unknown keys or out-of-range numbers immediately report the exact file, key, and expected constraint.

2. All 12 Overlayable Tuning Files at a Glance

File NameGovernsMerge StructureTypical Mod Use Cases
battle.jsoncSL/RP multipliers, room size, AI bot count & respawns, brSpreadMrank, sub-mode chance, Strike UCAV spawn scoreFlat key-value objectCustom reward rates, 16v16 capacity tweaks, tighter/wider BR spread, bot respawn counts
battle-economy.jsoncBase action prices and battle settlement economy curvesNested key-value objectRebalance kills vs captures vs assists rewards
store.jsoncGE packs, SL packs, Premium tiers, and vehiclePacks (multiVehiclePacks list, byRank list, byVehicle map)Lists ($listOps) + map mergePrice custom gift vehicles, create custom multi-vehicle bundles
marketplace.jsoncMarketplace vehicle/skin coupon reference prices, rarity tiers & feesNested object + map mergeAdjust market economy or price custom market coupons
trophies.jsoncClassic supplyTrophies (SL chest, Veteran chest) & directVehicles GE buyout priceList ($listOps) + objectAdd custom gacha chests, tweak rare vehicle drop weights
supply-chests.jsoncExternal-inventory supply chests and drop poolsList ($listOps) + objectAdd custom external-inventory chests
recycling.jsoncItem recycling and crafting/re-roll recipesNested key-value objectCustomize item recycling ratios and output weights
redeem-codes.jsoncDynamic Premium/GJN code prefixes and one-time fixedCodesObject + map mergeAdd custom promo redeem codes for your modpack
new-profile.jsoncStarting Silver Lions, Golden Eagles, and GJN balances for new savesFlat key-value objectHigh-resource sandbox presets or zero-balance hardcore presets
research.jsoncAutomatic default next-research target selectionFlat key-value objectCustomize auto-selected research behavior
clans.jsoncSquadron member caps, activity rules, and preset offline squadronsObject + list ($listOps)Add custom preset squadrons
limits.jsoncMax items per purchase, battle report & log retention capsFlat key-value objectRaise bulk-purchase limits or retained battle log history

3. Recursive Key-Map Merge vs Additive List Operations ($listOps)

Understanding how the merger treats objects versus arrays prevents mods from clobbering one another:

  1. Plain Objects / Key-Value Maps (such as vehiclePacks.byVehicle and redeem-codes.jsonc fixedCodes) → Merge Recursively by Key Automatically: Just write the specific keys you want to add or override (e.g. "my_new_tank": { ... }). All other stock keys remain intact—do not wrap key-value maps in $listOps!
  2. JSON Array Properties (such as vehiclePacks.multiVehiclePacks, goldenEaglePacks, supplyTrophies) → Replace by Default; Use { "$listOps": [...] } to Stack: Writing a raw array "multiVehiclePacks": [ ... ] replaces the entire stock and earlier-mod list! To stack items cleanly across multiple mods, set that array property to an envelope object whose only key is "$listOps" (note: if the object has any sibling keys alongside "$listOps", it will NOT be recognized as a list-ops envelope!):
jsonc
// Correct Example: server/tuning/store.jsonc
// Note: multiVehiclePacks, byRank, and byVehicle live INSIDE "vehiclePacks", and the GJN price key is "gjn"!
{
  "vehiclePacks": {
    // ① multiVehiclePacks is an array -> wrap in { "$listOps": [...] } to stack safely
    "multiVehiclePacks": {
      "$listOps": [
        {
          "op": "append",
          "items": [
            {
              "id": "mod_modern_duo_pack",
              "title": { "en": "Modern Duo Pack", "zh": "现代双车组合包" },
              "gjn": 49.99,
              "goldenEagles": 2000,
              "premiumDays": 15,
              "vehicles": ["us_m1a2_sep2_abrams", "germ_leopard_2a7v"]
            }
          ]
        },
        {
          "op": "upsertBy",
          "key": "id",
          "item": {
            "id": "wto_pack_two_fronts",
            "gjn": 19.99
          }
        },
        {
          "op": "removeBy",
          "key": "id",
          "value": "some_unwanted_pack_id"
        }
      ]
    },

    // ② byVehicle is a key-value map (NOT an array) -> write vehicle IDs directly without $listOps!
    "byVehicle": {
      "us_mbt_demo": {
        "gjn": 59.99,
        "goldenEagles": 2000,
        "premiumDays": 15
      }
    }
  }
}

All 4 Supported $listOps Operations

  • append: { "op": "append", "items": [ ... ] } — appends items to the end of the array;
  • prepend: { "op": "prepend", "items": [ ... ] } — inserts items at the start of the array;
  • upsertBy: { "op": "upsertBy", "key": "<idField>", "item": { ... } } — finds the first element where entry[key] === item[key] and recursively merges item into it, or appends item if absent;
  • removeBy: { "op": "removeBy", "key": "<field>", "value": <matchValue> } — removes every element where entry[key] === value.

4. Practical Field Quick-Reference & Verified Snippets

Every key name below is verified directly against apps/server/tuning/*.jsonc and the server's strict tuning readers:

4.1 battle.jsonc (Multipliers, Session Size, BR Spread & Bot Respawns)

jsonc
{
  "rewardMultiplierSilverLions": 2.0,       // Global Silver Lions reward multiplier (default 1.0)
  "rewardMultiplierResearchPoints": 2.0,    // Global Research Points reward multiplier (default 1.0)
  "maxPlayers": 32,                         // Total session slots (16v16 = 32: 1 local player + up to 31 bots)
  "maxBots": 31,                            // Maximum AI bots (default 31)
  "smallTeamsMaxPlayers": 16,               // Total slots when Tactical Skies (small_teams_) rolls (default 16 = 8v8)
  "subModeChance": 0.5,                     // Probability (0..1) of rolling an enabled sub-mode alongside classic
  "brSpreadMrank": 3,                       // Matchmaking mrank spread (3 steps = +/- 1.0 BR; 0 = exact-BR matches)
  "botPoolLimitPerType": 80,                // Max vehicles per category emitted into customBots
  "tankBotRespawns": 3,                     // Max respawns per AI bot in multi-slot Ground battles
  "airBotRespawns": 2,                      // Max respawns per AI bot in multi-slot Air battles
  "strikeUcavSpawnScore": 750,              // Spawn points required for Strike UCAV in Ground RB (default 750)
  "nuclearEscalationStrategicBombers": true // Enable stage-3 strategic bombers (B-52H / Tu-95M) in Air RB Nuclear Escalation
}

4.2 store.jsonc (Local Web Store & In-Game GE / SL / Vehicle Pack Pricing)

  • Top-level keys: goldenEaglePacks (array), silverLionPacks (array), premiumForGoldenEagles (array), premiumForGjn (array), and vehiclePacks (object);
  • Inside vehiclePacks:
    • multiVehiclePacks (array; use $listOps): each entry requires id, vehicles (non-empty unique vehicle ID array), gjn (min 0.01), goldenEagles (int ≥0), premiumDays (int ≥0), optional silverLions (int ≥0), and exact one naming property—either custom bilingual "title": { "en": "...", "zh": "..." }, tech-tree folder "groupKey": "shop/group/...", or national starter pack "starter": true;
    • byRank (array; fallback single-vehicle pack tiers sorted by upToRank): each entry has upToRank, gjn, goldenEagles, premiumDays (optional silverLions);
    • byVehicle (key-value map): keyed by gift vehicle ID from wpcost.blk, with { "gjn"?, "goldenEagles"?, "premiumDays"?, "silverLions"? } (omitted fields fall back to the matching byRank tier).

4.3 new-profile.jsonc (Starting Balances for Brand-New Saves)

jsonc
{
  "silverLions": 1000000, // Starting Silver Lions (default 150000)
  "goldenEagles": 5000,   // Starting Golden Eagles (default 500)
  "gjn": 50               // Starting GJN balance, up to 2 decimal places (default 0)
}

4.4 redeem-codes.jsonc (Custom One-Time Promo Codes)

fixedCodes is a key-value map (redeemable once per save, case-insensitive; omitted currency fields default to 0)—merge new codes directly by key:

jsonc
{
  "fixedCodes": {
    "MYMOD-GIFT-2026": {
      "silverLions": 500000,
      "goldenEagles": 1000,
      "premiumDays": 7,
      "gjn": 25
    }
  }
}

4.5 trophies.jsonc (Adding Custom Silver Lion / Golden Eagle Trophy Chests)

supplyTrophies is an array—use $listOps to append a custom chest, and the client will automatically compute and display drop probabilities from your weight / weightTotal / weightEach entries:

jsonc
{
  "supplyTrophies": {
    "$listOps": [
      {
        "op": "append",
        "items": [
          {
            "id": "mod_lucky_trophy",
            "iconStyle": "big_chest",
            "silverLions": 100000,
            "goldenEagles": 0,
            "prizes": [
              { "silverLions": 50000, "weight": 50 },
              { "silverLions": 250000, "weight": 20 },
              { "goldenEagles": 200, "weight": 10 },
              { "item": "item_universal_spare", "count": 3, "weight": 15 },
              { "eventVehicles": { "minRank": 3, "maxRank": 7, "pick": 6 }, "weightTotal": 5 }
            ]
          }
        ]
      }
    ]
  }
}

06 · 服务端 JS/TS 脚本完整接口手册

实验期警告(API 0.1-experimental)
本章描述的所有服务端脚本接口与内部目录对象均处于极初期开发阶段,随时可能随本体迭代调整,现阶段不承诺向后兼容。


1. 运行环境、Node 24 可擦除 TS 语法与 VS Code 智能补全

本地服务器运行在启动器内置的 Electron 43 / Node.js 24 上,原生开启 TypeScript 类型剥离(Type Stripping)——玩家电脑上无需安装 Node.js 或 TypeScript 即可直接运行你的 .ts 源码!

  • 入口探测顺序:默认依次查找 server/index.ts → server/index.mjs → server/index.js(也可在 mod.jsonc 的 server.entry 中显式指定相对路径);
  • 若需引入第三方 npm 依赖或特殊语法:自行在发布前用 esbuild / tsc 打包为单文件 server/index.mjs 分发即可。

1.1 直接写 .ts 的语法限制(erasableSyntaxOnly 正误对照)

Node 24 原生类型剥离只会擦除纯类型标注,不会生成额外运行时 JS 代码。因此支持全部 interface、type、泛型与 as,但禁止使用 enum、namespace 或构造函数参数属性(constructor(private x: number)):

ts
// ❌ 错误写法:Node 24 原生 TS 剥离不支持 enum,启动会直接报语法错误!
enum FilterMode { All = 'all', Include = 'include', Exclude = 'exclude' }

// ✅ 正确写法:使用 as const 常量对象 + 联合类型(零运行时开销、100% 兼容!)
const FILTER_MODE = { All: 'all', Include: 'include', Exclude: 'exclude' } as const;
type FilterMode = (typeof FILTER_MODE)[keyof typeof FILTER_MODE];

1.2 外部模组作者如何获得完整的 VS Code 类型提示?

从 WTOffline 源码仓库下载 packages/mods/src/server-api.ts(及其引用的同级 types.ts)放到你的模组 server/ 目录下,然后用 import type 导入上下文类型:

ts
// ✅ 正确:import type 在运行时会被 Node 24 完全擦除,VS Code 拥有完整自动补全!
import type { WtoServerModContext } from './server-api.ts';

// ❌ 不要对 @wto/mods 做运行时值导入(外部独立模组目录没有 monorepo node_modules,运行时会找不到包)
// import { something } from '@wto/mods';

export default {
  async setup(ctx: WtoServerModContext) {
    ctx.logger.info('mod initialized');
  },
};

提示:除 export default { setup(ctx) { ... } } 外,运行时也兼容直接导出默认函数 export default function (ctx) { ... } 或具名导出 export function setup(ctx) { ... }。你也可以像 templates/official-map-selector/server/index.ts 一样直接在文件顶部声明自己用到的精简 interface,做到单文件零外部依赖。


2. WtoServerModContext 上下文对象全属性表

属性类型说明
ctx.apiVersionstring当前运行时的实验期 API 版本号("0.1-experimental")
ctx.manifestModManifest本模组解析后的 mod.jsonc 清单对象
ctx.modDirstring本模组根目录的绝对路径(可用 node:fs 读取模组附带的静态数据文件)
ctx.gameFolderstring当前运行的离线游戏副本根目录
ctx.dataFolderstring当前客户端的数据目录(含存档、缓存、日志)
ctx.portnumber本次启动的本地服务器监听端口
ctx.logger{ info, warn, error }自动带 [mod:<id>] 前缀的日志器,写入 launcher.log 与诊断包
ctx.storageModStorageApi按账号隔离或全局共享的独立原子 JSON 存档区(见第 3 节)
ctx.hooksServerModHooksApi生命周期、档案、匹配与对局结算钩子(见第 4 节)
ctx.routesServerModRoutesApimatching、http 与 char 三大协议路由扩展(见第 5 节)

3. 独立存档区(ctx.storage)

硬性最佳实践:请勿往玩家原版 profile.blk 塞入自定义非标字段(不仅可能干扰客户端反序列化,玩家关闭或卸载模组后还会在主存档残留脏数据)。所有模组自定进度、开关与统计请一律存入 ctx.storage:

ts
// ① 按本地玩家账号隔离:<dataFolder>/saves/<userId>/mods/<modId>.json
const playerStore = ctx.storage.forPlayer(userId);
const prev = playerStore.read<{ wins: number }>() ?? { wins: 0 };
playerStore.write({ wins: prev.wins + 1 }); // 临时文件原子替换写盘,防断电损坏
// playerStore.remove();

// ② 模组跨账号全局共享存储:<dataFolder>/mods-data/<modId>.json
const sharedStore = ctx.storage.shared();

4. 全部生命周期、档案与对局钩子(ctx.hooks)

4.1 ctx.hooks.onDatasetsLoaded(async (datasets) => { ... })

在本地服务器从叠加后的 .vromfs.bin 提取完静态数据集、尚未构建业务服务前触发。可读取或修改:

  • datasets.vehicles:载具目录数组(CatalogueVehicle[],含价格、研发点、权重、科技树信息)
  • datasets.battleEconomy:对局收益基数与单车系数表
  • datasets.battleSpawnRules:出生点、支援机与重生成本规则数据
  • datasets.multiplayerMissions:{ categories, missions } 联机任务元数据
  • datasets.uiLabels / datasets.unitNames:多语言界面标签与载具译名映射
  • datasets.get(datasetId) / datasets.set(datasetId, value):按数据集 ID 读取或替换任意底层数据集

4.2 ctx.hooks.onCataloguesReady(async (catalogues) => { ... })

在所有核心业务目录与服务初始化完毕、开始监听端口之前触发,可访问:

  • catalogues.tuning:合并完成后的全部只读 Tuning
  • catalogues.gameModes:GameModes 实例(提供 ids()、byId(id)、byName(name)、byEconomicName(name)、countries())
  • catalogues.profiles / accounts / research / equipment / repair
  • catalogues.store / inventory / trophies / items / crew / decor / unlocks / clans
  • catalogues.battleMatchmaker / battleEconomy / battleStreaks
  • catalogues.notifyInventoryChanged():通知在线客户端立刻刷新外部库存
  • catalogues.notifyUser(userId, eventName, payload):向指定在线玩家推送 mrpc.generic_notify 实时事件

4.3 ctx.hooks.onServerListening(({ port }) => { ... }) / onServerClosing(() => { ... })

分别在 HTTP/匹配端口监听就绪后、以及服务器关闭前(按模组逆序)触发,适合打印就绪地址或清理后台定时器。

4.4 档案钩子:ctx.hooks.profile.onRefresh((profile, userId) => { ... })

每次读取或更新玩家档案并跑完原生刷新管线后调用(profile 为 @wto/blk 的内存 BlkBlock)。建议只读取档案信息并把衍生数据存入 ctx.storage.forPlayer(userId)。

4.5 对局与匹配钩子(ctx.hooks.battle)

① ctx.hooks.battle.onBeforeMatchmake(({ userId, eventName, request }) => { ... })

玩家点击「加入战斗」发起 match.enqueue、尚未进入 BattleMatchmaker 之前触发,request 为客户端提交的原始入队参数对象。

② ctx.hooks.battle.onFilterMissions((ctx) => { ... })

BattleMatchmaker 已按当前模式与分房权重筛出双边候选任务池、尚未随机抽图时触发:

  • ctx:{ userId, modeId, modeName, economicName, minMrank, maxMrank, missions };
  • 每项 mission 结构为 { name, path, level?, type?, locName?, postfix? };
  • 返回值:返回过滤后的子集数组(返回 undefined 表示不干预)。若返回空数组 [],服务端会打印告警并自动回退到过滤前的候选池,确保玩家永远不会因筛选过严而卡死匹配。
ts
// 示例:只允许匹配关卡路径或名称包含 poland 或 berlin 的地图
ctx.hooks.battle.onFilterMissions(({ missions }) => {
  const picked = missions.filter((m) => /poland|berlin/i.test(m.level ?? m.name));
  return picked.length > 0 ? picked : undefined;
});
③ ctx.hooks.battle.onLiveFact(({ userId, roomId, fact }) => { ... })

对局进行中,每当客户端通过 wto_battle.fact 上报一条实时战斗事件时触发(roomId 为 16 位十六进制对局 sessionId)。fact 公共字段包含 { sessionId, localPlayerId, localTeam, kind },并按 fact.kind 携带以下精确字段:

fact.kind触发时机附加字段结构
"event"本地玩家产生得分/击杀/助攻/占点/伤害事件{ time, unit, code, expClass, victim, victimIsPlayer, friendly, modifier, damage }
"life"本地玩家单次出击生命段更新或阵亡结算{ unit, start, end, died }
"kill"战场右上角击杀播报栏产生任意击杀(含 AI 互杀){ time, killer, killerTeam, victim, victimTeam }(MPlayer ID,无玩家单位为 -1)
"strike"本地玩家投掷的核弹成功引爆{ time }
④ ctx.hooks.battle.onAfterSettle(({ userId, roomId, summary }) => { ... })

对局结束、服务端执行完原生 settleBattle 结算之后、档案正式写盘之前触发。summary 的真实结构为 { profile, report, session }:

  • summary.profile:已完成本局银狮/研发点结算的玩家档案 BlkBlock;
  • summary.report:客户端上报的本局完整事实 BattleReport(含 outcome: 'win' | 'lose' | 'running'、localTeam、teamAScore、teamBScore、sessionStart、sessionEnd、lives、events、feed、players 计分板、nuclearStrikes、spares);
  • summary.session:本局会话元数据 BattleSession(含 sessionId、roomId、modeId、modeName、economicName、difficulty、requiredClass、missionName、country 等)。

再次提醒:统计模组自定成就、连胜或战役进度时,请读写 ctx.storage.forPlayer(userId),切勿往 summary.profile 写入非原版自定义键!


5. 三大通信路由对比与 matchingApiFunc 正确签名(ctx.routes)

5.1 我该选哪种路由?(选型对照表)

路由接口适用场景协议格式客户端调用方式
ctx.routes.matching(最推荐)原生 DaGui .nut 界面弹窗与服务端读写 JSON 数据(如读取/保存选图规则、模组设置)纯 JSON 对象入参 + JSON 对象返回Quirrel 调用 matchingApiFunc("wto_mod.<方法名>", callback, params)
ctx.routes.http用 HTML/CSS/JS 做复杂可视化面板、外部浏览器管理页或 REST 接口(自动隔离在 /mods/<modId>/...)标准 HTTP 请求/响应系统浏览器或游戏内置浏览器打开 http://{{LOCAL_ENDPOINT}}/mods/<modId>/...
ctx.routes.char拦截包装原版 cln_* 档案动作,或注册底层二进制 BLK 动作二进制/文本请求体(Buffer)客户端底层 char 客户端动作请求

5.2 匹配服 JSON RPC(ctx.routes.matching)—— 注意客户端参数顺序!

服务端注册自定义匹配方法非常直观(req 含 { method, params, userId },同步返回任意 JSON 对象即可;也可用 wrap(method, (req, next) => ...) 包装原版匹配方法):

ts
ctx.routes.matching.register('wto_mod.my_mod.ping', ({ userId, params }) => ({
  ok: true,
  userId,
  echo: params,
}));

P0 必看:Quirrel 端 matchingApiFunc 的第 2 个参数是 callback,第 3 个参数才是 params!
在原版 gui.vromfs.bin 的 %scripts/matching/api.nut 中,函数定义为 function matchingApiFunc(name, cb, params = null)。如果把 params 和 callback 写反,请求参数会变成空且回调永远不会触发!

客户端 .nut 正确调用写法:

squirrel
from "%scripts/matching/api.nut" import matchingApiFunc

// ✅ 第 1 参数:方法名 | 第 2 参数:Callback 回调 | 第 3 参数:请求参数表 params
matchingApiFunc("wto_mod.my_mod.ping",
  Callback(@(resp) this.onPingResponse(resp), this),
  {
    hello = "world"
  })

5.3 本地 HTTP 与内置浏览器网页路由(ctx.routes.http)

注册的子路径会自动挂载到 /mods/<你的modId>/... 命名空间下(支持精确路径与 /* 通配后缀):

ts
ctx.routes.http.register('/panel', () => ({
  status: 200,
  contentType: 'text/html; charset=utf-8',
  body: '<!doctype html><meta charset="utf-8"><h1>My Mod Control Panel</h1>',
}));

ctx.routes.http.register('/api/*', (req) => ({
  status: 200,
  contentType: 'application/json; charset=utf-8',
  body: JSON.stringify({ method: req.method, path: req.path, query: req.query }),
}));

如果你想在游戏机库里点一个按钮直接用战雷内置浏览器打开这个网页,只需在 client/gui-patches/ 的替换脚本中引用 {{LOCAL_ENDPOINT}} 占位符即可:

squirrel
from "%scripts/onlineShop/url.nut" import openUrl

openUrl("http://{{LOCAL_ENDPOINT}}/mods/demo.my-mod/panel", false, false)

5.4 Char 动作拦截与扩展(ctx.routes.char)

  • ctx.routes.char.register(action, handler):注册全新的自定义 cln_* 动作;
  • ctx.routes.char.wrap(action, async (req, next) => { ... }):按洋葱模型拦截现有 cln_* 动作(可在调用 await next(req) 前检查请求或在其后观测响应)。

6. 全栈模组实战拆解:官方选图器(official-map-selector)是如何串起来的?

打开 mods/official-map-selector/(仓库源码位于 mod-dev-docs/templates/official-map-selector/),它是学习「客户端原生 UI + 本地服务器 RPC + 独立存档 + 匹配钩子」完整闭环的最佳蓝本。整个模组仅由 5 个环节串联而成:

text
[1. 入口挂载补丁 client/gui-patches/]
   ├─ gui/gamemodeselect/gamemodeselect.tpl  → 在模式选择底栏右侧插入「自定义地图池」按钮节点
   ├─ scripts/gamemodes/gamemodeselect.nut   → 点击按钮调用 WtoMapSelectorModal.open({ gameMode })
   └─ gui/css.css                            → 追加 @import "missions\wtomapselector.css"
          │
          ▼
[2. 独立原生弹窗 client/packs/gui.vromfs.bin/ + lang.vromfs.bin/]
   ├─ scripts/missions/wtomapselectormodal.nut  → 继承 BaseGuiHandlerWT,展示搜索框、黑白名单标签与战术小地图预览
   ├─ gui/missions/wtomapselectormodal.tpl      → 弹窗骨架与卡片网格模板(wtomapselectorcards.tpl)
   ├─ gui/missions/wtomapselector.css           → 卡片选中高亮样式
   └─ lang/menu.csv.patch.csv                   → 注册 wto/mapSelector/* 中英文界面词条
          │
          ▼  matchingApiFunc("wto_mod.map_selector.get" / ".set", Callback(...), { modeName, ... })
[3. 服务端匹配 RPC server/index.ts -> ctx.routes.matching.register]
   ├─ onCataloguesReady 时扫描 catalogues.gameModes 建立各 PvP 模式可用双边地图池索引
   ├─ wto_mod.map_selector.get → 返回该模式地图列表 + 当前玩家已保存的筛选规则
   └─ wto_mod.map_selector.set → 校验参数并保存玩家的 all / include / exclude 选图列表
          │
          ▼
[4. 玩家独立存档 ctx.storage.forPlayer(userId)]
   └─ 原子写入 <dataFolder>/saves/<userId>/mods/official.map-selector.json(不改动 profile.blk)
          │
          ▼
[5. 匹配选图拦截 ctx.hooks.battle.onFilterMissions]
   └─ 玩家点「加入战斗」时按白名单/黑名单过滤候选 missions;若当前权重段过滤后为 0 张图则安全回退全池并记日志

建议把 templates/official-map-selector 从头到尾对照本图通读一遍——你需要的几乎所有全栈模组技巧都在里面有可直接复用的生产级示范代码!

06 · Server JS/TS Scripting API Reference

Experimental Warning (API 0.1-experimental)
All server scripting interfaces and internal catalogue objects documented here are in early active development and may change across WTOffline releases without backwards compatibility.


1. Runtime Environment, Node 24 Erasable TS Rules & VS Code Autocomplete

The local server runs inside the launcher's bundled Electron 43 / Node.js 24 runtime with native TypeScript type stripping enabled—players do not need Node.js or TypeScript installed on their PCs to run your .ts scripts directly!

  • Default entry lookup order: server/index.ts → server/index.mjs → server/index.js (or override via server.entry in mod.jsonc);
  • Third-party npm packages or non-erasable syntax: if needed, bundle your code ahead of time into a single-file server/index.mjs with esbuild or tsc.

1.1 Raw .ts Syntax Rule (erasableSyntaxOnly Do vs Don't)

Node 24's built-in TypeScript stripper erases type annotations without emitting extra runtime JS code. All interface, type, generic, and as constructs work natively, except enum, namespace, and constructor parameter properties (constructor(private x: number)):

ts
// ❌ DON'T: Node 24 native TS stripping rejects `enum` at startup!
enum FilterMode { All = 'all', Include = 'include', Exclude = 'exclude' }

// ✅ DO: Use an `as const` object + union type (zero runtime overhead, 100% compatible!)
const FILTER_MODE = { All: 'all', Include: 'include', Exclude: 'exclude' } as const;
type FilterMode = (typeof FILTER_MODE)[keyof typeof FILTER_MODE];

1.2 How External Modders Get Full VS Code Autocomplete

Download packages/mods/src/server-api.ts (along with its sibling types.ts) from the WTOffline repository into your mod's server/ folder and import types using import type:

ts
// ✅ DO: `import type` is completely erased by Node 24 at runtime while giving full VS Code IntelliSense!
import type { WtoServerModContext } from './server-api.ts';

// ❌ Avoid value-importing `@wto/mods` at runtime (external mod folders do not have monorepo node_modules)
// import { something } from '@wto/mods';

export default {
  async setup(ctx: WtoServerModContext) {
    ctx.logger.info('mod initialized');
  },
};

Tip: Alongside export default { setup(ctx) { ... } }, the runtime also accepts export default function (ctx) { ... } or a named export function setup(ctx) { ... }. You can also declare lightweight structural interface views directly at the top of server/index.ts (just like templates/official-map-selector/server/index.ts) for a zero-dependency single file.


2. WtoServerModContext Property Reference

PropertyTypeDescription
ctx.apiVersionstringActive experimental API tag ("0.1-experimental")
ctx.manifestModManifestParsed mod.jsonc manifest of this mod
ctx.modDirstringAbsolute path to this mod's root directory (read static mod files via node:fs)
ctx.gameFolderstringActive offline game copy root directory
ctx.dataFolderstringActive client data folder (saves, caches, logs)
ctx.portnumberBound local server port for the current session
ctx.logger{ info, warn, error }Logger prefixed with [mod:<id>], written to launcher.log and diagnostic exports
ctx.storageModStorageApiAtomic JSON storage scoped per player or shared across accounts (Section 3)
ctx.hooksServerModHooksApiLifecycle, profile, matchmaking, and battle settlement hooks (Section 4)
ctx.routesServerModRoutesApimatching, http, and char route extensions (Section 5)

3. Isolated Mod Storage (ctx.storage)

Recommended practice: Keep custom mod data out of the player's profile.blk (non-stock keys can interfere with client serialization and remain behind after a mod is removed). Store mod state, settings, and progression in ctx.storage:

ts
// ① Scoped per local player account: <dataFolder>/saves/<userId>/mods/<modId>.json
const playerStore = ctx.storage.forPlayer(userId);
const prev = playerStore.read<{ wins: number }>() ?? { wins: 0 };
playerStore.write({ wins: prev.wins + 1 }); // Atomic temp-file rename write
// playerStore.remove();

// ② Shared across all accounts for this mod: <dataFolder>/mods-data/<modId>.json
const sharedStore = ctx.storage.shared();

4. Lifecycle, Profile & Battle Hooks (ctx.hooks)

4.1 ctx.hooks.onDatasetsLoaded(async (datasets) => { ... })

Fires after static datasets are extracted from the overlaid .vromfs.bin packs and before domain catalogues are constructed. Inspect or mutate:

  • datasets.vehicles: vehicle array (CatalogueVehicle[] with prices, RP, BRs, tech-tree links)
  • datasets.battleEconomy: battle action reward rates and per-vehicle multipliers
  • datasets.battleSpawnRules: spawn costs, support planes, and spawn rules
  • datasets.multiplayerMissions: { categories, missions } mission metadata
  • datasets.uiLabels / datasets.unitNames: localized UI strings and vehicle names
  • datasets.get(datasetId) / datasets.set(datasetId, value): read or replace any raw dataset by ID

4.2 ctx.hooks.onCataloguesReady(async (catalogues) => { ... })

Fires after all domain catalogues and services are assembled, right before the server starts listening:

  • catalogues.tuning: merged read-only Tuning
  • catalogues.gameModes: GameModes instance (ids(), byId(id), byName(name), byEconomicName(name), countries())
  • catalogues.profiles / accounts / research / equipment / repair
  • catalogues.store / inventory / trophies / items / crew / decor / unlocks / clans
  • catalogues.battleMatchmaker / battleEconomy / battleStreaks
  • catalogues.notifyInventoryChanged(): push live external-inventory refresh to connected clients
  • catalogues.notifyUser(userId, eventName, payload): send a live mrpc.generic_notify event to a logged-in player

4.3 ctx.hooks.onServerListening(({ port }) => { ... }) / onServerClosing(() => { ... })

Fires once the HTTP/matching port is listening, and in reverse mod order right before shutdown (ideal for logging URLs or clearing timers).

4.4 Profile Hook: ctx.hooks.profile.onRefresh((profile, userId) => { ... })

Fires whenever a player profile is loaded or updated and finishes the native refresh pipeline (profile is an @wto/blk BlkBlock). Read profile facts here and persist derived mod state in ctx.storage.forPlayer(userId).

4.5 Matchmaking & Battle Hooks (ctx.hooks.battle)

① ctx.hooks.battle.onBeforeMatchmake(({ userId, eventName, request }) => { ... })

Fires when the player clicks To Battle! (match.enqueue) before BattleMatchmaker runs; request holds the raw client enqueue parameters.

② ctx.hooks.battle.onFilterMissions((ctx) => { ... })

Fires after BattleMatchmaker narrows candidate two-sided missions for the chosen mode and BR window, right before random map selection:

  • ctx: { userId, modeId, modeName, economicName, minMrank, maxMrank, missions };
  • Each mission has { name, path, level?, type?, locName?, postfix? };
  • Return value: return your filtered subset array (or undefined to leave unchanged). If an empty array [] is returned, the server logs a warning and safely falls back to the previous candidate pool so matchmaking never deadlocks.
ts
// Example: restrict matches to maps whose level path or name matches poland or berlin
ctx.hooks.battle.onFilterMissions(({ missions }) => {
  const picked = missions.filter((m) => /poland|berlin/i.test(m.level ?? m.name));
  return picked.length > 0 ? picked : undefined;
});
③ ctx.hooks.battle.onLiveFact(({ userId, roomId, fact }) => { ... })

Fires live during a running LocalMP battle whenever the client reports a wto_battle.fact event (roomId is the 16-character hex sessionId). fact always carries { sessionId, localPlayerId, localTeam, kind } plus fields determined by fact.kind:

fact.kindWhen It FiresAdditional fact Fields
"event"Local player scores a kill, assist, capture, hit, or award event{ time, unit, code, expClass, victim, victimIsPlayer, friendly, modifier, damage }
"life"Local player spawn life segment updates or ends in death{ unit, start, end, died }
"kill"Any kill appears in the HUD killfeed (including AI-vs-AI kills){ time, killer, killerTeam, victim, victimTeam } (MPlayer IDs, -1 if unit has no player)
"strike"Local player's nuclear bomb detonates{ time }
④ ctx.hooks.battle.onAfterSettle(({ userId, roomId, summary }) => { ... })

Fires at battle end right after native settleBattle applies SL/RP rewards and right before the updated profile is written to disk. summary has the exact shape { profile, report, session }:

  • summary.profile: the player's BlkBlock profile with post-battle rewards applied;
  • summary.report: parsed BattleReport (outcome: 'win' | 'lose' | 'running', localTeam, teamAScore, teamBScore, sessionStart, sessionEnd, lives, events, feed, players scoreboard rows, nuclearStrikes, spares);
  • summary.session: BattleSession metadata (sessionId, roomId, modeId, modeName, economicName, difficulty, requiredClass, missionName, country, etc.).

Reminder: Persist any custom mod achievements, streaks, or campaign progression in ctx.storage.forPlayer(userId) rather than mutating non-stock keys onto summary.profile!


5. Choosing Between the 3 Route Channels & Exact matchingApiFunc Signature (ctx.routes)

5.1 Which Route API Should I Use?

Route APIBest ForPayload FormatHow the Client Calls It
ctx.routes.matching *(Recommended)*Native DaGui .nut modals exchanging JSON data with your server script (settings, map rules, custom state)Plain JSON params in → JSON object outQuirrel matchingApiFunc("wto_mod.<method>", callback, params)
ctx.routes.httpRich HTML/CSS/JS web dashboards, external browser panels, or REST endpoints (auto-namespaced under /mods/<modId>/...)Standard HTTP request / responseSystem browser or War Thunder's embedded browser at http://{{LOCAL_ENDPOINT}}/mods/<modId>/...
ctx.routes.charWrapping stock cln_* profile actions or adding low-level binary BLK actionsRaw binary/text BufferLow-level client char action requests

5.2 Matching JSON RPC (ctx.routes.matching) — Mind the Client Argument Order!

Registering a custom matching RPC on the server takes just a few lines (req provides { method, params, userId } and returns any JSON object; wrap(method, (req, next) => ...) is also available):

ts
ctx.routes.matching.register('wto_mod.my_mod.ping', ({ userId, params }) => ({
  ok: true,
  userId,
  echo: params,
}));

P0 Gotcha: In Quirrel's matchingApiFunc, callback Is the 2nd Argument and params Is the 3rd Argument!
In stock gui.vromfs.bin %scripts/matching/api.nut, the signature is function matchingApiFunc(name, cb, params = null). Passing (name, params, callback) in the wrong order sends empty params and skips your callback.

Correct Quirrel .nut call:

squirrel
from "%scripts/matching/api.nut" import matchingApiFunc

// ✅ Arg 1: RPC method | Arg 2: Callback | Arg 3: Request params table
matchingApiFunc("wto_mod.my_mod.ping",
  Callback(@(resp) this.onPingResponse(resp), this),
  {
    hello = "world"
  })

5.3 Local HTTP & Embedded Browser Routes (ctx.routes.http)

Routes are automatically namespaced under /mods/<yourModId>/... and support both exact paths and /* wildcards:

ts
ctx.routes.http.register('/panel', () => ({
  status: 200,
  contentType: 'text/html; charset=utf-8',
  body: '<!doctype html><meta charset="utf-8"><h1>My Mod Control Panel</h1>',
}));

ctx.routes.http.register('/api/*', (req) => ({
  status: 200,
  contentType: 'application/json; charset=utf-8',
  body: JSON.stringify({ method: req.method, path: req.path, query: req.query }),
}));

To open that page inside War Thunder's native embedded browser from a hangar button, use the {{LOCAL_ENDPOINT}} placeholder inside a client/gui-patches/ replacement snippet:

squirrel
from "%scripts/onlineShop/url.nut" import openUrl

openUrl("http://{{LOCAL_ENDPOINT}}/mods/demo.my-mod/panel", false, false)

5.4 Char Action Interception & Custom Actions (ctx.routes.char)

  • ctx.routes.char.register(action, handler): register a brand-new cln_* action;
  • ctx.routes.char.wrap(action, async (req, next) => { ... }): wrap an existing cln_* action around await next(req).

6. Full-Stack Case Study: How official-map-selector Connects End to End

Open mods/official-map-selector/ (source in mod-dev-docs/templates/official-map-selector/): it is a complete reference implementation connecting native client UI, matching RPCs, isolated player storage, and server matchmaking hooks across 5 clean layers:

text
[1. Minimal Entry Hooks: client/gui-patches/]
   ├─ gui/gamemodeselect/gamemodeselect.tpl  → Inserts the "Custom Map Pool" button into the footer bar
   ├─ scripts/gamemodes/gamemodeselect.nut   → Wires button click to WtoMapSelectorModal.open({ gameMode })
   └─ gui/css.css                            → Appends @import "missions\wtomapselector.css"
          │
          ▼
[2. Standalone Native Modal: client/packs/gui.vromfs.bin/ + lang.vromfs.bin/]
   ├─ scripts/missions/wtomapselectormodal.nut  → Subclasses BaseGuiHandlerWT; renders search, filter tabs & tactical map preview
   ├─ gui/missions/wtomapselectormodal.tpl      → Modal layout & card grid template (wtomapselectorcards.tpl)
   ├─ gui/missions/wtomapselector.css           → Selected card badge & border styling
   └─ lang/menu.csv.patch.csv                   → Localized wto/mapSelector/* UI strings (EN / ZH)
          │
          ▼  matchingApiFunc("wto_mod.map_selector.get" / ".set", Callback(...), { modeName, ... })
[3. Server Matching RPCs: server/index.ts -> ctx.routes.matching.register]
   ├─ Indexes playable two-sided map pools per PvP mode during onCataloguesReady(catalogues.gameModes)
   ├─ wto_mod.map_selector.get → Returns the mode's map list + the player's saved filter rule
   └─ wto_mod.map_selector.set → Validates & saves the player's all / include / exclude selection
          │
          ▼
[4. Per-Account Isolated Storage: ctx.storage.forPlayer(userId)]
   └─ Atomically writes <dataFolder>/saves/<userId>/mods/official.map-selector.json (never touches profile.blk)
          │
          ▼
[5. Matchmaking Map Filter: ctx.hooks.battle.onFilterMissions]
   └─ Filters candidate missions by whitelist/blacklist on "To Battle!", falling back to the full pool with a log warning if 0 maps match at that BR

Reading templates/official-map-selector alongside this diagram gives you a production-tested blueprint for virtually any full-stack WTOffline mod!

07 · 排错、日志、热重载与打包发布规范

1. 模组出错了去哪里看日志?

启动器的所有模组构建与运行日志都会汇入标准日志目录,可在 「设置 › 诊断 › 打开日志目录」 或 「关于 › 导出诊断日志」 直接打开:

  1. 启动器主日志(launcher.log):
    • 搜索 [build]:查看本轮启用了哪些模组、各 .vromfs.bin 数据包叠加统计、以及哪条 gui-patches 或 exe-patches 被跳过与具体原因;
    • 搜索 [mods]:查看跨盘 Junction 挂载结果、被跳过的玩家原生文件重名告警、以及自动还原的按需备份数据包;
    • 搜索 [server] 或 [mod:<你的modId>]:查看服务端 tuning 校验错误、脚本加载报错堆栈、以及你在脚本里调用 ctx.logger.info/warn/error 打印的全部输出。
  2. 游戏客户端运行日志(<游戏副本目录>/.game_logs/*.clog):
    • 若客户端 GUI 脚本运行报错或卡死在「正在加载」,查看最新的 .clog(并配合第 04 章的 sq.exe 完整字节码检查快速定位);
    • 若新增 3D 模型未渲染,搜索 .clog 中的 [PACK]、pkg_user 或模型资产名确认是否被引擎挂载。

2. 常见报错与疑难杂症速查表

现象 / 日志报错常见原因解决方法
启动器提示某模组目录读取失败mod.jsonc 存在 JSON 语法错误、拼错了未知字段名、id 含大写或非法字符、或声明的 server.entry 文件不存在对照第 01 章第 5 节字段表核对 mod.jsonc
点启动提示「存在阻塞性模组错误」启用的模组缺少 requires 前置、前置未勾选启用,或同时勾选了声明 conflicts 互斥的两个模组按「模组」页顶部的红色错误列表补齐前置或关闭其中一个互斥项
模组里的 server/tuning/*.jsonc 修改似乎没生效测试客户端曾在启动器「数值」页手动改过同一字段(<数据目录>/tuning/*.jsonc 优先级高于模组),或 store.jsonc 把 vehiclePacks 内部字段写到了根级在启动器「数值」页将该项重置为默认,并核对第 05 章的字段层级与 "gjn" 字段名
服务端加载 .ts 报语法错或找不到模块在 .ts 中写了 enum/namespace,或写了运行时值导入 import { ... } from '@wto/mods'改用 as const 对象 + 联合类型;类型提示一律写成 import type { ... } from './server-api.ts'
gui-patches 报错 the data pack has no script ...patch.jsonc 里的 variant.file 含有大写字母(如 scripts/gameModes/...)将 variant.file 改为全小写(如 scripts/gamemodes/gamemodeselect.nut)
新增的独立 .css 样式完全没生效只把 .css 放进了 client/packs/gui.vromfs.bin/,未在根样式表 gui/css.css 中注册在 client/gui-patches/ 给 gui/css.css 增加一条 @import "目录文件名.css" 补丁(见第 04 章 2.2 节)
客户端 matchingApiFunc 回调不触发或服务端收到空 params把 matchingApiFunc 的第 2、第 3 个参数顺序写反了记住签名是 matchingApiFunc(methodName, callback, params)——callback 在第 2 位,params 在第 3 位!
进机库一直卡在「正在加载」新增或修补后的完整 .nut 存在词法作用域重名、未声明标识符、保留字 base 误用或反引号字符串 ` ... | 用 sq.exe 对**完整 .nut 文件**跑 compilestring 字节码校验,插值字符串统一用 $"..."`
日志提示 overlaps protected core patch模组的 client/exe-patches/ 试图修改离线版核心隔离补丁锁定的字节区间核心隔离区段受保护不可覆盖,请改用非重叠地址或服务端方案
日志提示 target already exists as a native/player fileclient/files/ 中的某文件与玩家自己在 UserSkins/ 或 UserSights/ 手动放的文件重名给模组附带的配套子目录加上专属前缀(如 mod_<你的id>_...)避免撞名

3. 开发调试热重载循环(改完文件怎么最快看到效果?)

在本地编写与调试模组时,了解客户端与服务端各自的加载时机能省下大量时间:

  1. 修改客户端内容(client/packs/、client/gui-patches/、client/exe-patches/、client/addon/、client/files/、config-blk.patch.jsonc):
    • 先正常退出游戏客户端;
    • 保存你修改的模组源文件后,直接在启动器点击 「启动游戏」:启动器会自动比对所有启用模组源文件的大小与修改时间指纹(Fingerprint),一旦发现任一补丁或包内文件有改动,就会自动从 wtoffline/stock/ 重新叠加生成最新数据包并启动游戏!
    • 提示:如果只是微调已通过 NTFS Junction 挂载的 client/addon/res/ 或 client/files/UserSkins/<子目录>/ 内部贴图,文件本身已经是零拷贝直连的,重启游戏(或游戏内点刷新涂装)即可直接读取最新文件。
  2. 修改服务端内容(server/index.ts 与 server/tuning/*.jsonc):
    • 每次退出游戏并在启动器重新点击 「启动游戏」拉起新一轮本地服务器会话时,服务器都会重新合并全部 server/tuning/*.jsonc,并通过带时间戳的 ESM 动态导入(?wto_mod=<timestamp>)全新加载 server/index.ts,无需重启启动器本身。

4. 模组打包与发布分享规范(.zip 结构)

当你完成测试准备把模组分享给其他玩家时,请遵循统一的压缩包目录约定,让玩家解压即用、不踩套娃目录坑:

  1. 压缩包内保留且仅保留一层顶层模组文件夹: 假设你的模组目录叫 my-awesome-mod,打包后的 my-awesome-mod.zip 内部结构应当是:
text
my-awesome-mod.zip
└─ my-awesome-mod/          <-- 唯一顶层文件夹(玩家直接解压到 mods/ 即可得到 mods/my-awesome-mod/mod.jsonc)
   ├─ mod.jsonc
   ├─ client/
   └─ server/
  • 不要把 mod.jsonc 裸放在 .zip 根目录(玩家直接“解压到当前文件夹”会把散文件撒满 mods/ 根目录导致无法识别);
  • 也不要套两层文件夹(如 my-awesome-mod/my-awesome-mod/mod.jsonc),启动器只扫描 mods/ 下的一级子目录!
  1. 打包前清理无关开发垃圾文件: 请剔除 .git/、node_modules/(若用第三方库请预打包进单文件 server/index.mjs)、.DS_Store、Thumbs.db、编辑器备份文件(*.bak、*.swp)以及临时解包参考用的原版大文件。

5. 跨盘与非 NTFS 磁盘行为说明

  • NTFS 硬盘(绝大多数 Windows 电脑):client/addon/(3D 模型与贴图)和单模组独占子目录(如 UserSkins/<子目录>)全部通过 NTFS Directory Junction 挂载——跨盘可用、免管理员权限、0 额外空间、约 1 毫秒完成;
  • 平铺共享目录散文件(如 sound/mod/*.bank):依次尝试文件符号链接(开启 Windows 开发者模式时跨盘零拷贝)→ 同盘硬链接 → 按文件大小与修改时间比对的增量缓存复制(未改动文件下次启动自动跳过);
  • exFAT 移动硬盘:因文件系统不支持 Junction 和硬链接,自动退化为按大小与修改时间比对的增量缓存复制,功能照常可用。

6. 开发与发布建议

  1. 命名空间隔离:模组 ID 用 <作者>.<模组名>;新增载具 ID、武器、涂装子目录、自定义匹配 RPC(wto_mod.<模组名>.*)、自定义 Char 动作均加上专属前缀,避免与其他模组撞名;
  2. 公共表优先使用增量补丁而非整文件覆盖:修改 shop.blk、wpcost.blk、unittags.blk、units.csv、menu.csv 时使用 .patch.jsonc / .patch.csv,多车礼包与抽卡箱数组使用 $listOps;
  3. 只读原版,不污染玩家主存档:模组自定数据一律写进 ctx.storage.forPlayer(userId),卸载模组后玩家主存档干干净净;
  4. 界面大逻辑拆独立文件:新弹窗放 client/packs/gui.vromfs.bin/,client/gui-patches/ 里只留几行挂入口按钮与 @import 样式的最小补丁,游戏大版本更新时几乎不用重写;
  5. 发布前做一次完整的「启用 → 进游验证 → 关闭 → 再进游还原」测试循环:确认启用时功能正常、关闭后彻底无痕还原,且能与其他常用模组同时勾选共存。

07 · Troubleshooting, Logs, Reload Loop & Packaging

1. Where to Check Logs When Something Goes Wrong

All mod build and runtime logs flow into the launcher's standard log directory—open Settings › Diagnostics › Open logs folder or About › Export diagnostics:

  1. Launcher Main Log (launcher.log):
    • Filter [build]: see which mods ran in the current build, .vromfs.bin overlay counts, and exact reasons why any gui-patches or exe-patches item was skipped;
    • Filter [mods]: see cross-drive Junction mounts, skipped native player-file collision warnings, and restored on-demand stock packs;
    • Filter [server] or [mod:<yourModId>]: see server tuning validation errors, script load stack traces, and everything printed via ctx.logger.info/warn/error.
  2. Game Client Runtime Logs (<copyFolder>/.game_logs/*.clog):
    • If a client UI script throws at runtime or hangs on "Loading", check the newest .clog (and run sq.exe full bytecode verification from Chapter 04);
    • If a custom 3D model fails to appear, search .clog for [PACK], pkg_user, or your asset name to confirm engine mounting.

2. Common Issues & Solutions Lookup Table

Symptom / Log MessageCommon CauseSolution
Discovery error on Launcher Mods pagemod.jsonc syntax error, unknown field name, uppercase/invalid id, or missing server.entry fileValidate mod.jsonc against the schema table in Chapter 01 Section 5
"Blocking mod errors" when clicking LaunchMissing or disabled requires dependency, or two enabled mods declaring conflictsEnable the missing dependency or disable one of the conflicting mods highlighted in red
server/tuning/*.jsonc changes appear ignoredTest client has a manual override saved in the Launcher Tuning tab (<dataFolder>/tuning/*.jsonc has highest priority), or store.jsonc placed vehiclePacks subkeys at rootReset overridden fields in the Launcher Tuning tab and check vehiclePacks nesting + "gjn" key names in Chapter 05
Server .ts fails with syntax or module-not-found errorRaw .ts used enum/namespace, or value-imported import { ... } from '@wto/mods'Replace enum with as const + union type; use import type { ... } from './server-api.ts' for types
gui-patches fails with the data pack has no script ...variant.file in patch.jsonc used camelCase / uppercase letters (e.g. scripts/gameModes/...)Change variant.file to all lowercase (e.g. scripts/gamemodes/gamemodeselect.nut)
Standalone .css stylesheet has no effectAdded .css to client/packs/gui.vromfs.bin/ without registering it in gui/css.cssAdd a client/gui-patches/ patch on gui/css.css appending @import "folderstyle.css" (Chapter 04 Section 2.2)
Client matchingApiFunc callback does not fire or params arrive emptySwapped the 2nd and 3rd arguments of matchingApiFuncUse matchingApiFunc(methodName, callback, params) (callback is 2nd, params is 3rd)
Game hangs indefinitely on "Loading" before hangarResulting complete .nut file has a lexical scope collision, undeclared identifier, base keyword misuse, or backtick string ` ... | Run sq.exe compilestring on the **complete .nut file** and use $"..."` for string interpolation
Log reports overlaps protected core patchMod client/exe-patches/ overlaps locked core offline/isolation patch bytesCore isolation bytes are protected; pick a non-overlapping site or use a server-side hook
Log reports target already exists as a native/player fileA path under client/files/ collides with a player-owned file in UserSkins/ or UserSights/Prefix bundled companion subfolders with your mod namespace (e.g. mod_<yourId>_...)

3. Development Reload Loop (Fastest Edit-Test Cycle)

Knowing when client builds versus server scripts reload keeps iteration fast while developing:

  1. Client-side edits (client/packs/, client/gui-patches/, client/exe-patches/, client/addon/, client/files/, config-blk.patch.jsonc):
    • Close the running game client first;
    • Save your edited mod files and click Launch in the launcher: the launcher hashes source file sizes and mtime timestamps into a deterministic build fingerprint, automatically rebuilding any affected .vromfs.bin packs from wtoffline/stock/ before starting the game!
    • Tip: textures inside already-mounted NTFS Junction directories (client/addon/res/ or client/files/UserSkins/<subfolder>/) point directly to your mods/ folder with zero copying, so restarting the client (or refreshing skins in-game) reads updated assets immediately.
  2. Server-side edits (server/index.ts & server/tuning/*.jsonc):
    • Every time you exit the game and click Launch to start a new session, the local server restarts cleanly, re-merges all server/tuning/*.jsonc overlays, and reloads server/index.ts with a cache-busting ESM query (?wto_mod=<timestamp>)—no need to restart the launcher itself.

4. Packaging & Sharing Your Mod (.zip Layout Rules)

When packaging your mod for players to download, follow a consistent archive structure so unzipping into mods/ works every time:

  1. Wrap your mod in a single top-level <mod-folder>/ directory inside the .zip: For a mod folder named my-awesome-mod, structure my-awesome-mod.zip as:
text
my-awesome-mod.zip
└─ my-awesome-mod/          <-- Single top-level folder (extracting straight into mods/ yields mods/my-awesome-mod/mod.jsonc)
   ├─ mod.jsonc
   ├─ client/
   └─ server/
  • Do NOT place mod.jsonc loose at the root of the .zip (extracting into mods/ scatters loose files across mods/ where discovery ignores them);
  • Do NOT double-nest folders (my-awesome-mod/my-awesome-mod/mod.jsonc), as the launcher scans direct child directories of mods/ only!
  1. Exclude development & temporary clutter: Omit .git/, node_modules/ (bundle third-party JS dependencies into a single server/index.mjs if needed), .DS_Store, Thumbs.db, editor backup files (*.bak, *.swp), and any unpacked stock game reference files.

5. Cross-Drive & Non-NTFS Disk Behavior

  • NTFS Volumes (standard on Windows): client/addon/ (3D models & textures) and mod-exclusive subfolders (e.g. UserSkins/<subfolder>) mount via NTFS Directory Junctions—works across drives, requires no admin rights, uses 0 extra disk space, and completes in ~1 ms;
  • Shared Flat-Folder Files (e.g. sound/mod/*.bank): tries file symlink (zero-copy across drives when Windows Developer Mode is on) → same-drive NTFS hardlink → incremental size/mtime cached copy (unchanged files are skipped on subsequent launches);
  • exFAT External Drives: since exFAT does not support Junctions or hardlinks, the deployer automatically falls back to incremental size/mtime cached copies with full functional parity.

6. Practical Recommendations for Mod Authors

  1. Namespace Everything: format your mod ID as <author>.<mod-name> and prefix custom vehicle IDs, weapons, skin subfolders, custom matching RPCs (wto_mod.<mod_name>.*), and custom Char actions to avoid collisions between mods;
  2. Prefer Incremental Patches Over Replacing Shared Tables: use .patch.jsonc / .patch.csv for shop.blk, wpcost.blk, unittags.blk, units.csv, and menu.csv, and use $listOps on shared tuning arrays like multiVehiclePacks and supplyTrophies;
  3. Read Stock Profiles, Persist in Isolated Storage: write all custom mod state to ctx.storage.forPlayer(userId) so player saves remain 100% clean if your mod is disabled or uninstalled;
  4. Keep UI Logic in Standalone Files: put custom modals under client/packs/gui.vromfs.bin/ and keep client/gui-patches/ down to a few lines wiring the entry button and gui/css.css @import so game updates rarely break your mod;
  5. Run One Full "Enable → Play → Disable → Relaunch" Cycle Before Release: verify your mod works when enabled, restores stock behavior cleanly when disabled, and coexists peacefully alongside other enabled mods.