From aa952e7cca5efd01e30f2c11d821f047b7eb1fd7 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Thu, 3 Dec 2026 02:51:54 +0800 Subject: [PATCH] docs(mods): add standalone mod-dev-docs handbook and launcher quick-open button --- apps/launcher/src/main/ipc/handlers.ts | 2 + .../src/main/services/mods/mods-service.ts | 14 + .../main/services/resources/resource-paths.ts | 4 + .../src/renderer/src/i18n/locales/en.json | 1 + .../src/renderer/src/i18n/locales/zh-CN.json | 1 + .../src/renderer/src/pages/mods/ModsPage.tsx | 3 + apps/launcher/src/shared/ipc/contract.ts | 4 + dev-docs/README.md | 4 +- dev-docs/mods.md | 143 ------ mod-dev-docs/README.md | 49 +++ mod-dev-docs/en/01-quick-start.md | 105 +++++ mod-dev-docs/en/02-client-packs-and-blk.md | 53 +++ mod-dev-docs/en/03-custom-3d-vehicles.md | 33 ++ mod-dev-docs/en/04-client-gui-and-exe.md | 33 ++ mod-dev-docs/en/05-server-tuning.md | 31 ++ mod-dev-docs/en/06-server-scripting-api.md | 40 ++ mod-dev-docs/en/07-troubleshooting-and-faq.md | 21 + mod-dev-docs/zh-CN/01-quick-start.md | 124 ++++++ mod-dev-docs/zh-CN/02-client-packs-and-blk.md | 195 +++++++++ mod-dev-docs/zh-CN/03-custom-3d-vehicles.md | 75 ++++ mod-dev-docs/zh-CN/04-client-gui-and-exe.md | 125 ++++++ mod-dev-docs/zh-CN/05-server-tuning.md | 90 ++++ mod-dev-docs/zh-CN/06-server-scripting-api.md | 157 +++++++ .../zh-CN/07-troubleshooting-and-faq.md | 44 ++ scripts/build-mod-docs-html.ts | 411 ++++++++++++++++++ scripts/build-windows-installer.ts | 2 + 26 files changed, 1619 insertions(+), 145 deletions(-) delete mode 100644 dev-docs/mods.md create mode 100644 mod-dev-docs/README.md create mode 100644 mod-dev-docs/en/01-quick-start.md create mode 100644 mod-dev-docs/en/02-client-packs-and-blk.md create mode 100644 mod-dev-docs/en/03-custom-3d-vehicles.md create mode 100644 mod-dev-docs/en/04-client-gui-and-exe.md create mode 100644 mod-dev-docs/en/05-server-tuning.md create mode 100644 mod-dev-docs/en/06-server-scripting-api.md create mode 100644 mod-dev-docs/en/07-troubleshooting-and-faq.md create mode 100644 mod-dev-docs/zh-CN/01-quick-start.md create mode 100644 mod-dev-docs/zh-CN/02-client-packs-and-blk.md create mode 100644 mod-dev-docs/zh-CN/03-custom-3d-vehicles.md create mode 100644 mod-dev-docs/zh-CN/04-client-gui-and-exe.md create mode 100644 mod-dev-docs/zh-CN/05-server-tuning.md create mode 100644 mod-dev-docs/zh-CN/06-server-scripting-api.md create mode 100644 mod-dev-docs/zh-CN/07-troubleshooting-and-faq.md create mode 100644 scripts/build-mod-docs-html.ts diff --git a/apps/launcher/src/main/ipc/handlers.ts b/apps/launcher/src/main/ipc/handlers.ts index f08af21..02dac46 100644 --- a/apps/launcher/src/main/ipc/handlers.ts +++ b/apps/launcher/src/main/ipc/handlers.ts @@ -24,6 +24,7 @@ import { exportModPreset, getModsState, importModPreset, + openModDocs, openModsFolder, saveModPreset, setModEnabled, @@ -223,6 +224,7 @@ export function registerIpcHandlers(): void { return importModPreset(copyId, BrowserWindow.fromWebContents(sender)); }); handle('mods:openFolder', () => openModsFolder()); + handle('mods:openDocs', (input) => openModDocs(input?.language)); handle('mods:setFolder', async ({ copyId, path }) => { requireModsWritable(); const state = await setModsFolder(copyId, path); diff --git a/apps/launcher/src/main/services/mods/mods-service.ts b/apps/launcher/src/main/services/mods/mods-service.ts index 46dc6af..99c78d3 100644 --- a/apps/launcher/src/main/services/mods/mods-service.ts +++ b/apps/launcher/src/main/services/mods/mods-service.ts @@ -118,6 +118,20 @@ export async function openModsFolder(): Promise { if (failure) console.warn('[mods] opening the mods folder failed:', modsDir, failure); } +export async function openModDocs(language?: string): Promise { + const docsRoot = resourcePaths().modDocs; + const preferred = language && language.toLowerCase().startsWith('zh') ? 'zh-CN.html' : 'en.html'; + const fallback = preferred === 'zh-CN.html' ? 'en.html' : 'zh-CN.html'; + const target = (await pathExists(join(docsRoot, preferred))) + ? join(docsRoot, preferred) + : join(docsRoot, fallback); + if (!(await pathExists(target))) { + throw new AppError('folder_unreadable', { path: docsRoot }); + } + const failure = await shell.openPath(target); + if (failure) console.warn('[mods] opening the mod docs failed:', target, failure); +} + export async function getModsState(copyId: string): Promise { const copy = await requireCopy(copyId); return buildModsStateView(copy); diff --git a/apps/launcher/src/main/services/resources/resource-paths.ts b/apps/launcher/src/main/services/resources/resource-paths.ts index 68ec76c..acf0692 100644 --- a/apps/launcher/src/main/services/resources/resource-paths.ts +++ b/apps/launcher/src/main/services/resources/resource-paths.ts @@ -19,6 +19,8 @@ export interface ResourcePaths { readonly appIcon: string; /** Bundled example mod templates seeded into an empty mods folder on first use. */ readonly modTemplates: string; + /** Offline HTML mod development handbook (zh-CN.html and en.html). */ + readonly modDocs: string; } export function resourcePaths(): ResourcePaths { @@ -35,6 +37,7 @@ export function bundledResourcePaths(): ResourcePaths { networkHookLibrary: join(process.resourcesPath, 'native', 'wto_ws.dll'), appIcon: join(process.resourcesPath, 'icon.ico'), modTemplates: join(process.resourcesPath, 'mod-templates'), + modDocs: join(process.resourcesPath, 'mod-dev-docs'), }; } // The app path is apps/launcher; the repository is two levels up. @@ -44,6 +47,7 @@ export function bundledResourcePaths(): ResourcePaths { networkHookLibrary: join(repository, 'build', 'native', 'wto_ws.dll'), appIcon: join(repository, 'apps', 'launcher', 'resources', 'icon.ico'), modTemplates: join(repository, 'dev-docs', 'templates', 'mods'), + modDocs: join(repository, 'build', 'mod-dev-docs'), }; } diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 6bd335b..48961ff 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -702,6 +702,7 @@ "autoSorted": "Reordered mods based on dependencies and load-order hints.", "refresh": "Refresh", "openFolder": "Open mods folder", + "openDocs": "Mod docs", "discoveryErrorsTitle": "{{count}} mod folder(s) could not be loaded:", "blockingIssuesTitle": "{{count}} blocking mod error(s) prevent launching:", "issuesTitle": "{{count}} mod notice(s) or overlap(s):", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index 9b7c364..52ef4ae 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -702,6 +702,7 @@ "autoSorted": "已按前置与排序建议重新排列模组顺序。", "refresh": "刷新", "openFolder": "打开模组目录", + "openDocs": "开发文档", "discoveryErrorsTitle": "有 {{count}} 个模组目录读取失败:", "blockingIssuesTitle": "存在 {{count}} 项阻塞性模组错误(处理前无法启动):", "issuesTitle": "检测到 {{count}} 项模组提示或冲突:", diff --git a/apps/launcher/src/renderer/src/pages/mods/ModsPage.tsx b/apps/launcher/src/renderer/src/pages/mods/ModsPage.tsx index d0e9de0..74db439 100644 --- a/apps/launcher/src/renderer/src/pages/mods/ModsPage.tsx +++ b/apps/launcher/src/renderer/src/pages/mods/ModsPage.tsx @@ -255,6 +255,9 @@ export function ModsPage({ copy, section, readOnly, onError }: Props) { + {state.discoveryErrors.length > 0 && ( diff --git a/apps/launcher/src/shared/ipc/contract.ts b/apps/launcher/src/shared/ipc/contract.ts index d87aa0f..d3eaeeb 100644 --- a/apps/launcher/src/shared/ipc/contract.ts +++ b/apps/launcher/src/shared/ipc/contract.ts @@ -303,6 +303,10 @@ export const ipcContract = { input: z.void(), output: z.void(), }, + 'mods:openDocs': { + input: z.object({ language: z.string().optional() }).optional(), + output: z.void(), + }, 'mods:setFolder': { input: z.object({ copyId: CopyIdSchema, path: z.string().min(1).nullable() }), output: ModsStateViewSchema, diff --git a/dev-docs/README.md b/dev-docs/README.md index e009877..a7441fb 100644 --- a/dev-docs/README.md +++ b/dev-docs/README.md @@ -12,7 +12,7 @@ | 改游戏规则、档案或本地服务 | [apps/server](../apps/server) | | 改游戏副本的构建或补丁检查 | [packages/patcher](../packages/patcher)、[scripts](../scripts)、[tools](../tools) | | 写客户端补丁或适配新的游戏版本 | [补丁指南](patches.md#zh-cn)和[补丁集](../patches) | -| 制作添加式模组(实验期) | [模组开发指南](mods.md#zh-cn)和[示例模组](templates/mods) | +| 制作添加式模组(实验期) | [模组开发文档(mod-dev-docs)](../mod-dev-docs/README.md) | 提交前按[自查清单](contributing.md#zh-cn)整理依据、运行适用的[检查命令](contributing.md#checks),并把检查结果和实机步骤写进 [PR 模板](templates/pull-request.md)。 @@ -28,6 +28,6 @@ Start with a stock client you own and use it as a read-only source. Install the | Change game rules, saves, or local services | [apps/server](../apps/server) | | Change the game copy build or patch checks | [packages/patcher](../packages/patcher), [scripts](../scripts), [tools](../tools) | | Write a client patch or adapt a new game build | [Patch guide](patches.md#english) and the [patch set](../patches) | -| Author additive mods (experimental) | [Mod authoring guide](mods.md#english) and [mod templates](templates/mods) | +| Author additive mods (experimental) | [Mod development docs (mod-dev-docs)](../mod-dev-docs/README.md#english) | Before submitting, follow the [review checklist](contributing.md#english), run the applicable [checks](contributing.md#checks), and record the results and in-game steps in the [PR template](templates/pull-request.md). diff --git a/dev-docs/mods.md b/dev-docs/mods.md deleted file mode 100644 index 2e0e468..0000000 --- a/dev-docs/mods.md +++ /dev/null @@ -1,143 +0,0 @@ -# 模组开发指南 / Mod Authoring Guide - - - -简体中文 · [English](#english) · [返回 Dev Docs](README.md#zh-cn) - -> **实验期免责声明(API `0.1-experimental`)** -> WTOffline 仍处于极初期开发阶段。服务端脚本接口、内部数据结构、钩子签名与声明式 `exe` 补丁格式均可能随本体开发随时调整,**当前阶段不承诺向后兼容**。涉及服务端脚本或客户端二进制补丁的模组,请作者做好跟随本体更新维护的准备。 - -## 1. 设计理念与目录位置 - -WTOffline 采用**添加式、可叠加**模组架构,不支持整包覆盖 `.vromfs.bin`。多个模组启用时按启动器「模组」页的顺序依次合并(越靠后优先级越高),关闭模组或切换预设即可干净还原。 - -- **全局模组仓库**:所有客户端共享一份模组目录(默认 `<启动器用户数据>/mods`,可在启动器「模组 › 预设与仓库」改为任意硬盘位置)。 -- **按客户端独立配置**:每个离线客户端单独保存自己的启用开关、加载顺序与命名预设(支持 JSON 导入/导出)。 -- **原生资源边界**:独立的涂装(`UserSkins/`)、瞄具(`UserSights/`)与单人任务(`UserMissions/`)继续沿用游戏原生放置方式;启动器绝不干涉或覆盖玩家原生目录中的文件。 - -## 2. 标准模组目录结构 - -在全局 `mods/` 目录下新建一个子文件夹,根目录放置 `mod.jsonc`,其余子目录按需创建: - -```text -my-mod/ -├─ mod.jsonc # 必需:清单(ID、名称、版本、作者、依赖、互斥、排序) -├─ server/ # 可选:服务端扩展 -│ ├─ tuning/ # 服务端数值增量覆盖(*.jsonc,支持 $listOps) -│ └─ index.ts # 服务端 JS/TS 脚本入口(支持 .ts / .mjs / .js) -└─ client/ # 可选:客户端扩展 - ├─ packs/ # .vromfs.bin 增量叠加(按目标包名分目录) - │ ├─ char.vromfs.bin/ # 例:config/shop.blk.patch.jsonc, config/wpcost.blk.patch.jsonc - │ ├─ aces.vromfs.bin/ # 例:gamedata/units/tankmodels/my_tank.blk(支持文本 BLK) - │ ├─ lang.vromfs.bin/ # 例:lang/units.csv.patch.csv - │ ├─ mis.vromfs.bin/ # 例:自定义任务 .blk - │ ├─ ui/atlases.vromfs.bin/ # 例:gameuiskin/my_tank_ico.svg - │ └─ ui/images.vromfs.bin/ # 例:units/my_tank.ddsx - ├─ addon/ # 独立 3D 模型与贴图扩展包(res/*.grp, res/*.dxp.bin) - ├─ gui-patches/ # GUI 界面脚本补丁(复用 patches/gui//patch.jsonc 格式) - ├─ exe-patches/ # 声明式 exe 补丁(复用 patches/exe//patch.jsonc 格式) - ├─ files/ # 可选:大型整合包附带的配套涂装/瞄具/音效/任务 - └─ config-blk.patch.jsonc # 可选:游戏根目录 config.blk 的增量补丁 -``` - -## 3. 清单文件(`mod.jsonc`) - -```jsonc -{ - "format": 1, - "id": "author.my-mod", - "name": { "zh-CN": "我的载具模组", "en": "My Vehicle Mod" }, - "version": "0.1.0", - "author": "YourName", - "description": { "zh-CN": "示例说明。", "en": "Example description." }, - "api_version": "0.1-experimental", - "game_versions": ["2.61.0.*"], - "requires": [], - "conflicts": [], - "load_after": [], - "load_before": [] -} -``` - -## 4. 魔改载具与添加全新 3D 模型载具 - -### 4.1 增量 BLK 补丁(`*.blk.patch.jsonc`) - -对公共大表(如 `char.vromfs.bin/config/shop.blk`、`config/wpcost.blk` 或原版载具 `.blk`),使用 `.patch.jsonc` 描述操作,保留精确 BLK 数据类型: -- `setParam` / `addParam` / `removeParam`:修改、追加或删除参数; -- `upsertBlock` / `addBlock` / `removeBlock`:创建、合并或删除子块(路径支持 `range[2]` 索引定位同名块); -- `cloneBlock`:从同文件复制已有载具块为新名称并嵌套 `ops` 修改字段(衍生魔改车的最快方式)。 - -在 `client/packs/aces.vromfs.bin/` 中直接放入文本格式的 `.blk` 文件(如新建载具物理或炮弹定义)时,构建器会自动编译为游戏需要的二进制 BLK。 - -### 4.2 添加全新 3D 模型与贴图(跨盘零拷贝) - -将 CDK 导出的 `.grp` 3D 模型和 `.dxp.bin` 贴图包放入 `client/addon/res/`: -- 不含 `res/grp_hdr.vromfs.bin` 的散装模型/贴图包,启动器会通过 **Windows NTFS 目录联接点(Junction)** 零拷贝跨盘挂载到 `<客户端>/content/pkg_user//`,并自动注册进 `aces.vromfs.bin` `config/settings.blk`,引擎会自动扫描 `res/` 下的所有 `.grp` 和 `.dxp.bin`; -- 自带 `res/grp_hdr.vromfs.bin` 的正式包会挂载到 `content/pkg_wto_/`; -- 配合 `char.vromfs.bin/config/shop.blk.patch.jsonc`、`config/wpcost.blk.patch.jsonc`、`lang.vromfs.bin/lang/units.csv.patch.csv` 以及 `ui/atlases.vromfs.bin` / `ui/images.vromfs.bin` 图标,本地服务器启动时会自动从叠加后的数据包识别新载具的价格、研发、改装件与商城礼包。 - -## 5. 服务端数值叠加与 JS/TS 脚本接口 - -### 5.1 `server/tuning/*.jsonc` 与 `$listOps` - -合并顺序:`内置默认 → Mod 1 → Mod 2 → … → 玩家在启动器「数值」页的覆盖`。 -列表型配置支持 `$listOps` 增量操作(`append`、`prepend`、`upsertBy`、`removeBy`),避免多个模组互相覆盖礼包或兑换码列表: - -```jsonc -{ - "codes": { - "$listOps": [ - { "op": "append", "items": [{ "code": "MY-MOD-GIFT", "silverLions": 500000 }] } - ] - } -} -``` - -### 5.2 服务端 JS/TS 脚本(`server/index.ts`) - -启动器内置 Node 24 原生支持可擦除类型语法的 `.ts`(不使用 `enum`、`namespace` 或构造函数参数属性),也可自行编译为 `.mjs`/`.js` 分发。完整类型定义见 `packages/mods/src/server-api.ts`: - -- `ctx.hooks.onDatasetsLoaded(datasets)`:修改或追加已提取的载具、经济、任务数据集; -- `ctx.hooks.onCataloguesReady(catalogues)`:访问商店、交易所、箱子、游戏模式、档案与匹配推送; -- `ctx.hooks.profile.onRefresh(profile, userId)`:每次档案刷新时运行; -- `ctx.hooks.battle.onBeforeMatchmake / onLiveFact / onAfterSettle`:介入匹配、局内实时事件与战后结算; -- `ctx.storage.forPlayer(userId)` / `ctx.storage.shared()`:按账号隔离的独立 JSON 存档区(不污染原版 `profile.blk`); -- `ctx.routes.char / matching / http`:拦截或注册自定义 `cln_*` 动作、匹配服 RPC,或挂载 `/mods//*` 本地网页路由。 - -## 6. 声明式 `exe` 与 `gui` 补丁 - -`client/exe-patches/` 与 `client/gui-patches/` 直接复用项目本体的补丁格式(见 [补丁指南](patches.md#zh-cn))。 -离线版核心隔离补丁永远最先规划并锁定字节区间:**任何与核心补丁字节重叠的模组 `exe` 补丁会被直接拒绝并记录在日志中**。 - -参考模板见 `dev-docs/templates/mods/` 下的两份可直接运行的示例模组。 - ---- - - - -[简体中文](#zh-cn) · English · [Back to Dev Docs](README.md#english) - -> **Experimental Notice (API `0.1-experimental`)** -> WTOffline is in early development. Server script APIs, internal server structures, hook signatures, and declarative `exe` patch contracts may change at any time without backwards compatibility. Mod authors using server scripts or binary patches should be prepared to update their mods alongside core releases. - -## 1. Architecture & Repository Layout - -WTOffline uses an **additive, stackable** mod system and does not support whole-pack `.vromfs.bin` replacements. Enabled mods merge in the load order configured on the launcher's Mods page (later entries take higher priority) and roll back cleanly when disabled. - -- **Global mod repository**: shared across all clients (default `/mods`, configurable to any drive from Mods › Presets & repository). -- **Per-client configuration**: toggles, load order, and named presets (with JSON import/export) are stored separately for each offline client. -- **Native content boundary**: standalone skins (`UserSkins/`), sights (`UserSights/`), and missions (`UserMissions/`) continue to use War Thunder's native folders; the launcher never overwrites player-managed native files. - -## 2. Standard Mod Folder Layout - -Place each mod in its own folder under `mods/` with a `mod.jsonc` manifest at its root: - -- `server/tuning/*.jsonc`: multi-layer tuning overlays supporting `$listOps` (`append`, `prepend`, `upsertBy`, `removeBy`). -- `server/index.ts` (or `.mjs` / `.js`): server script entry exporting `default { setup(ctx) { ... } }`. Runs directly on Electron's bundled Node 24 (erasable TypeScript syntax supported natively). -- `client/packs//`: additive overlays for `char.vromfs.bin`, `aces.vromfs.bin`, `gui.vromfs.bin`, `lang.vromfs.bin`, `mis.vromfs.bin`, `game.vromfs.bin`, `ui/atlases.vromfs.bin`, and `ui/images.vromfs.bin` (`*.blk.patch.jsonc`, `*.csv.patch.csv`, or added files; text `.blk` files compile to binary BLK automatically). -- `client/addon/`: 3D models and textures (`res/*.grp`, `res/*.dxp.bin`). Mounted zero-copy across drives via NTFS Directory Junctions into `content/pkg_user/` (or `content/pkg_wto_` when a compiled `res/grp_hdr.vromfs.bin` is included) and registered in `aces.vromfs.bin` `config/settings.blk`. -- `client/gui-patches/` & `client/exe-patches/`: declarative patches using the same format as `patches/gui/` and `patches/exe/` (see [Patch guide](patches.md#english)). Core offline isolation exe patches remain locked; any overlapping mod exe patch is rejected. -- `client/files/` & `client/config-blk.patch.jsonc`: optional companion assets and `config.blk` patches. - -See the runnable templates in `dev-docs/templates/mods/` and full TypeScript API definitions in `packages/mods/src/server-api.ts`. diff --git a/mod-dev-docs/README.md b/mod-dev-docs/README.md new file mode 100644 index 0000000..832f49b --- /dev/null +++ b/mod-dev-docs/README.md @@ -0,0 +1,49 @@ +# WTOffline 模组开发文档 / Mod Development Documentation + +简体中文 · [English](#english) + +> **实验期声明(API `0.1-experimental`)** +> WTOffline 当前处于极初期开发阶段。服务端脚本接口、内部数据结构、钩子契约及声明式 `exe` 补丁格式均可能随本体开发随时调整,**现阶段不承诺向后兼容**。模组作者使用服务端脚本或客户端二进制补丁时,请做好跟随本体更新维护的准备。 + +--- + +## 中文文档目录(`zh-CN/`) + +| 章节 | 内容概览 | +| --- | --- | +| [01 · 快速入门与清单规范](zh-CN/01-quick-start.md) | 5 分钟做出第一个模组、目录结构、`mod.jsonc` 全字段表、依赖/互斥/排序、风险徽标与启动器调试 | +| [02 · 客户端数据包与 BLK 增量补丁](zh-CN/02-client-packs-and-blk.md) | 8 个可叠加 `.vromfs.bin` 包、BLK 补丁全部 7 种操作(含 `cloneBlock`)、13 种 BLK 类型写法、文本 `.blk` 自动编译、CSV 词条合并、`config.blk` 补丁 | +| [03 · 添加全新 3D 模型与贴图载具](zh-CN/03-custom-3d-vehicles.md) | `client/addon/res/`(`.grp` + `.dxp.bin`)跨盘 NTFS Junction 零拷贝挂载、挂进科技树/经济/图标/译名、原生涂装瞄具边界说明 | +| [04 · 客户端 GUI 补丁与声明式 EXE 补丁](zh-CN/04-client-gui-and-exe.md) | 增量 GUI 脚本补丁、新增原生 DaGui 弹窗、`sq.exe` Quirrel 完整字节码检查、声明式 `exe` 补丁与核心隔离保护红线 | +| [05 · 服务端零代码数值叠加(Tuning)](zh-CN/05-server-tuning.md) | 12 份 `server/tuning/*.jsonc` 说明、多层合并顺序、`$listOps` 列表增量操作(`append` / `prepend` / `upsertBy` / `removeBy`) | +| [06 · 服务端 JS/TS 脚本完整接口手册](zh-CN/06-server-scripting-api.md) | Node 24 原生 TS 语法要求、`WtoServerModContext`、独立存档区 `storage`、全部生命周期与对局钩子(含 `onFilterMissions`)、`char` / `matching` / `http` 路由与完整范例 | +| [07 · 排错、日志与最佳实践](zh-CN/07-troubleshooting-and-faq.md) | 定位 `launcher.log` 与本地服务器日志、冲突分析、防止损坏玩家存档、跨盘与非 NTFS 磁盘行为说明 | + +### 自带官方模组模板(`templates/`) + +以下 3 个模组会随 WTOffline 启动器自动分发到玩家首次初始化的全局 `mods/` 目录(默认关闭,勾选即用),可直接对照源码学习或复制改造: + +| 模板目录 | 定位 | 演示的核心能力 | +| --- | --- | --- | +| `templates/example-vehicle-tweak/` | 零代码数据与本地化示例 | `server/tuning/battle.jsonc` + `wpcost.blk.patch.jsonc` + `lang/units.csv.patch.csv` | +| `templates/example-server-script/` | 服务端脚本最小示例 | `server/index.ts`、`onDatasetsLoaded`、`profile.onRefresh`、独立存档区、自定义 `/mods//status` 路由 | +| `templates/official-map-selector/` | 实用全栈官方模组 | 模式选择 UI 按钮补丁 + 原生 DaGui 小地图网格弹窗 + 多语言词条 + 自定义匹配 RPC + 独立存档 + `battle.onFilterMissions` 白/黑名单选图 | + +--- + + + +## English Documentation (`en/`) + +> **Experimental Notice (API `0.1-experimental`)** +> WTOffline is in early development. Server script APIs, internal data structures, hook contracts, and declarative `exe` patch formats may change without backwards compatibility across releases. Authors using server scripts or binary patches should be ready to update alongside core releases. + +| Chapter | Topics | +| --- | --- | +| [01 · Quick Start & Manifest](en/01-quick-start.md) | Build your first mod in 5 minutes, folder layout, full `mod.jsonc` schema, dependencies/conflicts/ordering, risk badges | +| [02 · Client Packs & BLK Patching](en/02-client-packs-and-blk.md) | 8 overlayable `.vromfs.bin` packs, all 7 BLK patch ops (including `cloneBlock`), all 13 BLK types, auto text-BLK compilation, CSV merging, `config.blk` patches | +| [03 · Custom 3D Vehicle Models](en/03-custom-3d-vehicles.md) | `client/addon/res/` (`.grp` + `.dxp.bin`) cross-drive zero-copy NTFS Junction mounting, tech tree/economy/icons/localization wiring, native skins/sights boundary | +| [04 · Client GUI & Declarative EXE Patches](en/04-client-gui-and-exe.md) | Incremental GUI script patches, adding standalone native DaGui modals, full Quirrel bytecode checks (`sq.exe`), declarative `exe` patches & core isolation lock | +| [05 · Server Code-Free Tuning Overlays](en/05-server-tuning.md) | All 12 `server/tuning/*.jsonc` files, multi-layer precedence, `$listOps` (`append`, `prepend`, `upsertBy`, `removeBy`) | +| [06 · Server JS/TS Scripting API Reference](en/06-server-scripting-api.md) | Node 24 erasable TypeScript rules, `WtoServerModContext`, isolated `storage`, all lifecycle & battle hooks (including `onFilterMissions`), `char` / `matching` / `http` routes | +| [07 · Troubleshooting & FAQ](en/07-troubleshooting-and-faq.md) | Reading logs, diagnosing conflicts, keeping player saves clean, cross-drive and exFAT fallback behavior | diff --git a/mod-dev-docs/en/01-quick-start.md b/mod-dev-docs/en/01-quick-start.md new file mode 100644 index 0000000..4073db3 --- /dev/null +++ b/mod-dev-docs/en/01-quick-start.md @@ -0,0 +1,105 @@ +# 01 · Quick Start & Manifest Reference + +> **Target Spec**: `format: 1` · `api_version: "0.1-experimental"` (experimental; subject to breaking changes) + +## 1. Additive Mod Architecture + +WTOffline uses a **stackable, additive** mod system and does **not** accept whole-pack `.vromfs.bin` replacements: + +1. Before launching the game, the launcher starts from clean stock backups (`wtoffline/stock/`), applies core offline patches first, then layers every enabled mod's client patches and added files in the order shown on the **Mods** page; +2. Large 3D model and texture addons mount across drives with zero copying via **Windows NTFS Directory Junctions**; +3. The local server extracts static data from the overlaid packs, layers `server/tuning/*.jsonc` in the same order, and loads `server/index.ts` scripts; +4. Disabling a mod or switching presets cleanly unmounts junctions and restores stock packs. + +- **Global repository**: defaults to `%APPDATA%\WTOffline Launcher\mods` (configurable to any drive under **Mods › Presets & repository**). +- **Per-client configuration**: toggles, load order, and presets live in each client's `/mods-config.json`. + +--- + +## 2. Build Your First Mod in 5 Minutes + +1. Open **Mods › Open mods folder** in the launcher. +2. Create a folder `my-first-mod` containing `mod.jsonc`: + +```jsonc +{ + "format": 1, + "id": "demo.my-first-mod", + "name": { "en": "My First Mod", "zh-CN": "我的第一个模组" }, + "version": "0.1.0", + "author": "YourName", + "description": "Doubles Silver Lions and Research Points battle rewards.", + "api_version": "0.1-experimental", + "game_versions": ["2.61.0.*"] +} +``` + +3. Create `my-first-mod/server/tuning/battle.jsonc`: + +```jsonc +{ + "rewardMultiplierSilverLions": 2.0, + "rewardMultiplierResearchPoints": 2.0 +} +``` + +4. Return to the launcher (the Mods page refreshes automatically on focus), enable your mod, and click **Launch**. + +--- + +## 3. Standard Folder Layout + +Create only the folders your mod actually needs: + +```text +/ +├─ mod.jsonc # Required: manifest +├─ server/ # Optional: server extensions +│ ├─ tuning/ # *.jsonc tuning overlays +│ └─ index.ts (or index.mjs / .js) # server script entry +└─ client/ # Optional: client extensions + ├─ packs/ # .vromfs.bin additive 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 pack (res/*.grp, res/*.dxp.bin) + ├─ gui-patches/ # declarative GUI script patches + ├─ exe-patches/ # declarative exe patches + ├─ files/ # optional companion skins/sights/sounds/missions + └─ config-blk.patch.jsonc # optional root config.blk patch +``` + +--- + +## 4. `mod.jsonc` Schema Reference + +Unknown fields are rejected by strict validation. + +| Field | Required | Type | Description | +| --- | --- | --- | --- | +| `format` | Yes | `1` | Manifest format version (currently `1`) | +| `id` | Yes | `string` | Globally unique ID matching `/^[a-z0-9][a-z0-9._-]{0,63}$/` | +| `name` | Yes | `string \| { [lang]: string }` | Display name (plain string or locale map) | +| `version` | Yes | `string` | Mod version (SemVer recommended) | +| `author` | Yes | `string` | Author or team name | +| `description` | No | `string \| { [lang]: string }` | Short description | +| `api_version` | Yes | `string` | Target API tag, currently `"0.1-experimental"` | +| `game_versions` | No | `string[]` | Game version wildcards (e.g. `["2.61.0.*"]`); mismatch warns only | +| `requires` | No | `string[]` | Required dependency mod IDs (blocking error if missing/disabled) | +| `conflicts` | No | `string[]` | Incompatible mod IDs (blocking error if both enabled) | +| `load_after` | No | `string[]` | Recommended load-order predecessors (used by Auto-sort) | +| `load_before` | No | `string[]` | Recommended load-order successors | +| `server` | No | `{ entry?: string, tuning?: string }` | Custom relative paths for server script entry and tuning folder | + +--- + +## 5. Load Order, Risk Badges & Conflict Detection + +- **Priority**: items lower in the list load later and take higher priority. +- **Risk badges**: automatically inferred as `data`, `gui`, `script`, and `exe`. +- **Conflict checks**: missing/disabled dependencies and declared conflicts block launching; whole-file overrides warn; shared BLK/CSV/tuning overlays report informational merge notices. diff --git a/mod-dev-docs/en/02-client-packs-and-blk.md b/mod-dev-docs/en/02-client-packs-and-blk.md new file mode 100644 index 0000000..3faa4bc --- /dev/null +++ b/mod-dev-docs/en/02-client-packs-and-blk.md @@ -0,0 +1,53 @@ +# 02 · Client Packs & BLK Incremental Patching + +## 1. Supported `.vromfs.bin` Packs + +Place overlays under `client/packs//`: +- **Always rebuilt from stock**: `char.vromfs.bin`, `aces.vromfs.bin`, `gui.vromfs.bin` +- **On-demand backup & restore**: `lang.vromfs.bin`, `mis.vromfs.bin`, `game.vromfs.bin`, `ui/atlases.vromfs.bin`, `ui/images.vromfs.bin` + +Because the local server extracts static datasets directly from the overlaid packs on startup, vehicles added or edited in `shop.blk` and `wpcost.blk` automatically flow into research trees, prices, modifications, AI pools, and offline store bundle GUIDs. + +--- + +## 2. File Handling Rules + +1. **`.patch.jsonc`** — Type-preserving structured BLK patch applied to `` inside the pack. +2. **`.patch.csv`** — Semicolon-separated localization CSV merger keyed by column 0. +3. **Any other file** — Added or replaced directly. Plain text `.blk` files are compiled to binary BLK automatically before packing. + +--- + +## 3. BLK Patch Operations (`*.blk.patch.jsonc`) + +Every patch file has `{ "ops": [...] }`. Path segments support indexed sibling selectors such as `"range[2]"` (zero-based). + +- **`setParam`**: `{ "op": "setParam", "path": [...], "name": "...", "value": ..., "createBlocks": false }` +- **`addParam`**: appends a repeated parameter without removing existing entries (ideal for `slaveUnit`, `folder`, `aircraftGift`). +- **`removeParam`**: removes all matching params by `name` (or only those matching optional `value`). +- **`upsertBlock`**: finds or creates a block along `path` and merges `block.params` and `block.blocks`. +- **`addBlock`**: inserts a new child block (`before` / `after` sibling anchor optional). +- **`removeBlock`**: deletes the block at `path`. +- **`cloneBlock`**: deep-clones an existing block (`from`) into `toParent` under `newName`, optionally applying nested `ops` rooted at the cloned block (fastest way to derive a modded vehicle in `wpcost.blk`). + +### Explicit BLK Types + +Use `{ "type": "", "value": }` whenever an exact Dagor BLK type is needed: +`string`, `int`, `real`, `bool`, `int64`, `point2`, `point3`, `point4`, `ipoint2`, `ipoint3`, `ipoint4`, `color` (`[r,g,b,a]` or packed `0xAARRGGBB`), `matrix` (12 reals). + +--- + +## 4. Localization CSV Patches (`*.csv.patch.csv`) + +```csv +"";"";"";"" +"my_custom_tank_shop";"M1A2 Mod";"M1A2 魔改型";"M1A2 魔改型" +``` + +Existing keys update only the supplied non-empty language columns; new keys are appended cleanly. + +--- + +## 5. Root `config.blk` Patches (`client/config-blk.patch.jsonc`) + +Uses the exact same BLK patch format against `/config.blk`. The launcher backs up the stock `config.blk` automatically and restores it when no enabled mod patches it. diff --git a/mod-dev-docs/en/03-custom-3d-vehicles.md b/mod-dev-docs/en/03-custom-3d-vehicles.md new file mode 100644 index 0000000..6461d81 --- /dev/null +++ b/mod-dev-docs/en/03-custom-3d-vehicles.md @@ -0,0 +1,33 @@ +# 03 · Adding Custom 3D Vehicle Models & Textures + +## 1. How 3D Asset Mounting Works + +Verified directly against 2.61.0.x `aces.exe` (`dlContent.cpp`) and `config/settings.blk`: +- Any addon path under `/pkg_user/` skips the `res/grp_hdr.vromfs.bin` check and directly scans `/res/` for all `.grp` (3D geometry/skeleton/collision) and `.dxp.bin` (DDSx texture) archives; +- If a mod ships a compiled CDK `res/grp_hdr.vromfs.bin`, the patcher mounts it under `content/pkg_wto_` so the native `grp_hdr` loader handles it; +- The patcher automatically registers all enabled mod addon folders in `aces.vromfs.bin` `config/settings.blk` (`addons`, `addons_no_check`, `addonsWithBasePath`). + +### Cross-Drive Zero-Copy Mounting + +Each mod's `client/addon/` is mounted into `/content/pkg_user/` via a **Windows NTFS Directory Junction**: +- Works across drives (e.g. `mods/` on C: or D:, client on J:); +- Requires no administrator privileges; +- Uses 0 extra bytes and mounts/unmounts in ~1 ms without touching source files in `mods/`. + +--- + +## 2. 6-Step Checklist for a Custom 3D Vehicle + +1. **`client/addon/res/.grp` + `.dxp.bin`**: 3D model and textures exported via War Thunder CDK; +2. **`client/packs/aces.vromfs.bin/gamedata/units/.../.blk`**: vehicle FM/DM/weapons (plain text BLK compiles automatically); +3. **`client/packs/char.vromfs.bin/config/wpcost.blk.patch.jsonc`**: economy, BR, modifications (use `cloneBlock` from a similar stock vehicle); +4. **`client/packs/char.vromfs.bin/config/shop.blk.patch.jsonc`** & **`unittags.blk.patch.jsonc`**: tech tree slot and unit tags; +5. **`client/packs/lang.vromfs.bin/lang/units.csv.patch.csv`**: localized names (`_shop`, `_0`, `_1`, `_2`); +6. **`client/packs/ui/atlases.vromfs.bin/gameuiskin/_ico.svg`** & optional **`ui/images.vromfs.bin/units/.ddsx`**: silhouette icon (used in tech tree and local web store) and statcard image. + +--- + +## 3. Native Skins, Sights & Companion Files Boundary + +- Standalone user skins (`UserSkins/`), sights (`UserSights/`), and missions (`UserMissions/`) continue to use the game's native folders and are never managed or deleted by the launcher. +- Large overhaul/vehicle mods may optionally bundle companion skins, sights, or sound banks under `client/files/`. Exclusive subdirectories under `UserSkins/`, `UserSights/`, and `UserMissions/` mount via cross-drive Junctions; any target colliding with a player-owned native file is skipped with a warning and never overwritten. diff --git a/mod-dev-docs/en/04-client-gui-and-exe.md b/mod-dev-docs/en/04-client-gui-and-exe.md new file mode 100644 index 0000000..ec34528 --- /dev/null +++ b/mod-dev-docs/en/04-client-gui-and-exe.md @@ -0,0 +1,33 @@ +# 04 · Client GUI Patches & Declarative EXE Patches + +> **Experimental Notice**: GUI script patches and declarative `exe` patches depend on target client builds and may need updates after game or core patches. + +--- + +## 1. Extending Client UI (Recommended Pattern) + +1. Place new standalone `.nut`, `.tpl`, and `.css` files under `client/packs/gui.vromfs.bin/` (keep paths lowercase to match stock archive conventions); +2. Place minimal entry-point edits under `client/gui-patches//` using `patch.jsonc` + `find.nut` / `replace.nut` fragments. + +Core offline GUI patches always run first; mod GUI patches apply afterward in load order. Every `find` snippet must match uniquely once or the patch is skipped safely. `{{LOCAL_ENDPOINT}}` in replacement text expands to `127.0.0.1:`. + +### Mandatory Quirrel Bytecode Check + +Before shipping any new or patched `.nut` script, compile the complete resulting script with `compilestring` via `sq.exe` to catch lexical scope conflicts, reserved keywords (such as `base`), and forward references that would otherwise hang login at "Loading": + +```powershell +& "build\quirrel-cli\bin\Release\sq.exe" -e "local f = compilestring(readfile('your_script.nut'), 'your_script.nut'); println('OK')" +``` + +--- + +## 2. Declarative EXE Patches (`client/exe-patches/`) + +Mods reuse WTOffline's `@wto/exepatch` format (`patch.jsonc` with `id`, `title`, `features`, `requires`, and `variants` using `signature`, `string_ref`, or `within` locators). **Never distribute modified `aces.exe` binaries.** + +### Core Isolation Lock (Hard Security Boundary) + +1. Core offline and isolation patches are planned first and their byte ranges are locked; +2. Any mod `exe` patch whose write range overlaps a protected core patch is **rejected** (`overlaps protected core patch`); +3. Overlapping patches between two mods reject the later patch with the conflicting mod ID; +4. Unmatched patterns on another game build are skipped cleanly and logged without breaking the core build. diff --git a/mod-dev-docs/en/05-server-tuning.md b/mod-dev-docs/en/05-server-tuning.md new file mode 100644 index 0000000..ed53f89 --- /dev/null +++ b/mod-dev-docs/en/05-server-tuning.md @@ -0,0 +1,31 @@ +# 05 · Server Code-Free Tuning Overlays + +The local server stores all offline-defined economy, battle, store, marketplace, chest, redeem-code, clan, and limit values in **12 `.jsonc` tuning files**. Mods can overlay any of them under `server/tuning/.jsonc` without writing code. + +## 1. Merge Precedence + +1. Shipped defaults (`apps/server/tuning/.jsonc`) +2. Enabled mods' `server/tuning/.jsonc` in load order +3. Player overrides (`/tuning/.jsonc`, highest priority) + +## 2. All 12 Tuning Files + +`battle.jsonc`, `battle-economy.jsonc`, `store.jsonc`, `marketplace.jsonc`, `trophies.jsonc`, `supply-chests.jsonc`, `recycling.jsonc`, `redeem-codes.jsonc`, `new-profile.jsonc`, `research.jsonc`, `clans.jsonc`, `limits.jsonc`. + +## 3. Additive List Operations (`$listOps`) + +Objects merge recursively by key; plain arrays replace the previous array. To stack items across multiple mods without clobbering, wrap list edits in `{ "$listOps": [...] }`: + +```jsonc +{ + "multiVehiclePacks": { + "$listOps": [ + { "op": "append", "items": [{ "id": "mod_duo_pack", "priceGjn": 49.99, "vehicles": ["us_m2a4"] }] }, + { "op": "upsertBy", "key": "id", "item": { "id": "wto_pack_two_fronts", "priceGjn": 19.99 } }, + { "op": "removeBy", "key": "id", "value": "some_pack_id" } + ] + } +} +``` + +Supported ops: `append`, `prepend`, `upsertBy`, `removeBy`. diff --git a/mod-dev-docs/en/06-server-scripting-api.md b/mod-dev-docs/en/06-server-scripting-api.md new file mode 100644 index 0000000..1cf12df --- /dev/null +++ b/mod-dev-docs/en/06-server-scripting-api.md @@ -0,0 +1,40 @@ +# 06 · Server JS/TS Scripting API Reference + +> **Experimental Warning (API `0.1-experimental`)**: All server script contracts, internal catalogue classes, and hook shapes are unstable and may change across releases without backwards compatibility. + +## 1. Runtime & TypeScript Rules + +Server scripts run inside Electron 43's bundled **Node.js 24** with built-in TypeScript type stripping (`erasableSyntaxOnly` syntax: no `enum`, `namespace`, or parameter properties). Pre-bundled `.mjs` / `.js` files are also supported. + +Default entry lookup order: `server/index.ts` → `server/index.mjs` → `server/index.js` (or explicit `server.entry` in `mod.jsonc`). + +```ts +export default { + async setup(ctx) { + ctx.logger.info('mod initialized'); + }, +}; +``` + +Full TypeScript definitions live in `packages/mods/src/server-api.ts`. + +## 2. `WtoServerModContext` + +- `apiVersion`, `manifest`, `modDir`, `gameFolder`, `dataFolder`, `port` +- `logger`: `{ info(msg), warn(msg), error(msg) }` (prefixed with `[mod:]`) +- `storage`: + - `storage.forPlayer(userId)` → atomic JSON file under `/saves//mods/.json` (never mutate stock `profile.blk` with custom keys) + - `storage.shared()` → `/mods-data/.json` +- `hooks`: + - `onDatasetsLoaded(datasets)` — inspect/mutate `vehicles`, `battleEconomy`, `battleSpawnRules`, `multiplayerMissions`, `uiLabels`, `unitNames`, or `get(id)` / `set(id, value)` + - `onCataloguesReady(catalogues)` — access `tuning`, `gameModes`, `profiles`, `accounts`, `research`, `equipment`, `repair`, `store`, `inventory`, `trophies`, `items`, `crew`, `decor`, `unlocks`, `clans`, `battleMatchmaker`, `battleEconomy`, `battleStreaks`, `notifyInventoryChanged()`, `notifyUser(userId, eventName, payload)` + - `onServerListening({ port })` / `onServerClosing()` + - `profile.onRefresh(profile, userId)` + - `battle.onBeforeMatchmake({ userId, eventName, request })` + - `battle.onFilterMissions({ userId, modeId, modeName, economicName, minMrank, maxMrank, missions })` — return a filtered/reordered subset of candidate missions (empty results safely fall back to the prior pool) + - `battle.onLiveFact({ userId, roomId, fact })` + - `battle.onAfterSettle({ userId, roomId, summary })` +- `routes`: + - `routes.char.register(action, handler)` / `routes.char.wrap(action, wrapper)` + - `routes.matching.register(method, handler)` / `routes.matching.wrap(method, wrapper)` (callable from client Quirrel via `matchingApiFunc`) + - `routes.http.register(subPath, handler)` — automatically namespaced under `/mods//...` (supports exact paths and `/*` wildcards) diff --git a/mod-dev-docs/en/07-troubleshooting-and-faq.md b/mod-dev-docs/en/07-troubleshooting-and-faq.md new file mode 100644 index 0000000..4faa480 --- /dev/null +++ b/mod-dev-docs/en/07-troubleshooting-and-faq.md @@ -0,0 +1,21 @@ +# 07 · Troubleshooting & Best Practices + +## 1. Where to Check Logs + +Open **Settings › Diagnostics › Open logs folder** or **About › Export diagnostics**: +- **`launcher.log`**: filter `[build]` for pack/GUI/exe patch reports, `[mods]` for Junction mount and native-file conflict warnings, and `[mod:]` for server script logs and stack traces. +- **`/.game_logs/*.clog`**: client Quirrel runtime errors and `[PACK]` / `pkg_user` asset loading logs. + +## 2. Common Issues + +- **Discovery error in Mods page**: check `mod.jsonc` JSON syntax, unknown keys, `id` format, and `server.entry` path. +- **Blocking errors on Launch**: enable missing `requires` dependencies or disable one of two mutually conflicting mods. +- **Node TS syntax error**: avoid `enum`/`namespace`/parameter properties in raw `.ts`, or bundle to `.mjs`. +- **`overlaps protected core patch`**: mod `exe` patch collided with a locked core isolation patch; choose a non-overlapping site. +- **Client hangs at "Loading"**: run full `sq.exe` `compilestring` bytecode checks on all modified/added `.nut` files. + +## 3. Cross-Drive & Non-NTFS Behavior + +- NTFS drives mount `client/addon/` and exclusive `UserSkins/`/`UserSights/`/`UserMissions/` folders via cross-drive **NTFS Directory Junctions** (no admin required, 0 extra space). +- Flat shared files (`sound/mod/*.bank`) try file symlink → same-drive hardlink → size/mtime cached copy. +- exFAT drives automatically fall back to incremental cached copies. diff --git a/mod-dev-docs/zh-CN/01-quick-start.md b/mod-dev-docs/zh-CN/01-quick-start.md new file mode 100644 index 0000000..5cc4b5b --- /dev/null +++ b/mod-dev-docs/zh-CN/01-quick-start.md @@ -0,0 +1,124 @@ +# 01 · 快速入门与清单规范 + +> **适用版本**:`format: 1` · `api_version: "0.1-experimental"`(实验期接口,随本体开发可能调整) + +## 1. 核心思路:为什么是「添加式」模组? + +WTOffline **不接受**整包覆盖原版 `char.vromfs.bin` / `aces.vromfs.bin` 的旧做法,而是采用**按加载顺序逐层叠加**的架构: + +1. 启动游戏前,启动器从纯净原版备份(`wtoffline/stock/`)出发,先应用离线版核心补丁,再按玩家在「模组」页排好的顺序,依次叠加所有启用模组的客户端补丁与新增文件; +2. 大体积 3D 模型和贴图包通过 **Windows NTFS 目录联接点(Junction)** 跨盘零拷贝挂载; +3. 本地服务器启动时自动读取叠加后的客户端数据包,再按同一顺序合并各模组的 `server/tuning/*.jsonc` 与加载 `server/index.ts` 脚本; +4. 关掉模组或切换预设,启动器自动拆除联接点并还原原版文件,不破坏客户端本体。 + +- **全局模组仓库**:默认位于 `%APPDATA%\WTOffline Launcher\mods`(可在启动器「模组 › 预设与仓库」修改到任意硬盘)。 +- **每客户端独立配置**:开关、加载顺序和命名预设分别保存在各自客户端的数据目录 `mods-config.json` 里。 + +--- + +## 2. 5 分钟做出你的第一个模组 + +1. 在启动器里打开 **「模组 › 打开模组目录」**; +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.*"] +} +``` + +4. 创建 `my-first-mod/server/tuning/battle.jsonc`: + +```jsonc +{ + "rewardMultiplierSilverLions": 2.0, + "rewardMultiplierResearchPoints": 2.0 +} +``` + +5. 切回启动器窗口(页面会自动刷新,或点击「刷新」),勾选启用并启动游戏即可生效。 + +--- + +## 3. 完整标准目录结构 + +只创建你用到的目录,未用到的部分完全不必建立: + +```text +/ +├─ 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 的增量补丁 +``` + +--- + +## 4. `mod.jsonc` 全字段参考 + +清单元数据解析采用**严格白名单校验**,写错字段名或出现未定义字段会被拒绝并在启动器报错区显示具体原因。 + +| 字段 | 必填 | 类型 | 说明 | +| --- | --- | --- | --- | +| `format` | 是 | `1` | 清单格式版本号,目前固定为整数 `1` | +| `id` | 是 | `string` | 全局唯一模组 ID,仅允许小写字母、数字、`.`、`_`、`-`,首字符须为字母或数字,最长 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 列表;缺失或未启用时作为**阻塞错误**阻止启动 | +| `conflicts` | 否 | `string[]` | 已知互斥模组 ID 列表;同时启用时作为**阻塞错误**阻止启动 | +| `load_after` | 否 | `string[]` | 建议排在这些模组 ID 之后(越靠后优先级越高);供启动器「按依赖自动排序」使用 | +| `load_before` | 否 | `string[]` | 建议排在这些模组 ID 之前 | +| `server` | 否 | `{ entry?: string, tuning?: string }` | 显式覆盖服务端入口文件(相对路径,不得含 `..`)和 `tuning` 目录路径(默认自动探测 `server/index.{ts,mjs,js}` 与 `server/tuning`) | + +--- + +## 5. 启动器自动计算的能力与风险徽标 + +启动器扫描模组目录后会自动标注以下徽标,帮助玩家判断安全性: + +- **数据/资源(`data`)**:仅包含 `server/tuning`、`client/packs`、`client/addon`、`client/files`、`config-blk.patch.jsonc`; +- **界面补丁(`gui`)**:包含 `client/gui-patches/`; +- **服务端脚本(`script`)**:包含可执行服务端 JS/TS 脚本; +- **二进制补丁(`exe`)**:包含 `client/exe-patches/`(高风险,且受核心隔离补丁锁保护)。 + +--- + +## 6. 排序规则与冲突检测 + +- **优先级**:列表中**越靠下(序号越大)越晚加载、优先级越高**; +- **叠加合并**(提示 `info`):两个模组对同一个 BLK / CSV / `tuning` 文件做增量补丁时,按顺序先后叠加; +- **文件覆写**(警告 `warning`):后序模组用整文件替换了前序模组改过的数据包文件或外置文件; +- **阻塞错误**(错误 `error`):缺少 `requires` 前置、前置未启用、或触发 `conflicts` 互斥时,启动器禁止启动并高亮提示处理。 diff --git a/mod-dev-docs/zh-CN/02-client-packs-and-blk.md b/mod-dev-docs/zh-CN/02-client-packs-and-blk.md new file mode 100644 index 0000000..3d748b3 --- /dev/null +++ b/mod-dev-docs/zh-CN/02-client-packs-and-blk.md @@ -0,0 +1,195 @@ +# 02 · 客户端数据包与 BLK 增量补丁 + +大多数战雷模组(魔改载具性能、炮弹穿深、导弹机动、科技树排布、价格权重、新任务、新译名、载具图标)都落在游戏的数据包(`.vromfs.bin`)里。本章介绍如何以**完全可叠加、互不顶掉**的方式修改这些数据包。 + +--- + +## 1. 支持叠加的 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/<载具名>_ico.svg`(科技树与本地商城剪影图标) | 按需自动备份,关闭还原 | +| `client/packs/ui/images.vromfs.bin/` | `units/<载具名>.ddsx` 或 `.png`(资料卡/乘员栏载具图) | 按需自动备份,关闭还原 | + +> **自动联动服务端**:本地服务器在启动时直接读取叠加后的 `.vromfs.bin`。因此你通过补丁往 `shop.blk` / `wpcost.blk` 新增或修改载具后,服务端会自动识别新车价格、前置科技树、研发点、改装件、权重、AI 池与礼包 GUID,无需手工同步两遍。 + +--- + +## 2. 包内文件的 3 种处理模式(按后缀自动识别) + +构建器根据你在 `client/packs/<包>/` 下放置的文件名自动决定处理方式: + +1. **`<原路径>.patch.jsonc` → BLK 结构化增量补丁**:解析目标 `.blk` 为保留类型的内存树,按 `ops` 逐条修改后重新编码为自包容二进制 BLK 写回; +2. **`<原路径>.patch.csv` → CSV 本地化增量合并**:按第 1 列词条键合并进目标 `.csv`(已有键更新对应语言列,新键追加到表尾); +3. **其余文件(如 `my_tank.blk`、`my_tank_ico.svg`)→ 新增或替换文件**: + - 如果路径以 `.blk` 结尾且你的源文件是**可读文本 BLK**(如从 CDK/解包工具改出来的),构建器会自动将其编译为游戏引擎所需的**二进制 BLK** 写进包内; + - 如果已经是二进制 BLK 或 `.svg` / `.ddsx` / `.nut` / `.tpl`,则原样写入包内。 + +--- + +## 3. BLK 增量补丁(`*.blk.patch.jsonc`)完整手册 + +### 3.1 基本格式与路径寻址 + +```jsonc +{ + "ops": [ + // 按顺序执行的操作列表 + ] +} +``` + +- `path` 是从 BLK 根节点出发的子块名数组,例如 `["country_usa", "army", "range[0]"]`; +- 同名子块(如 `shop.blk` 里连续多个 `range` 块)可以用 **`名称[索引]`**(0 起始)精确定位,不写索引默认命中第 0 个; +- `[]` 表示根节点本身。 + +### 3.2 全部 7 种操作(`op`) + +#### ① `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" } + ] + } +} +``` + +#### ⑤ `addBlock`:在父块下新增一个子块(支持 `before` / `after` 指定插入位置) +```jsonc +{ + "op": "addBlock", + "path": ["country_usa", "army", "range[0]"], + "name": "my_custom_tank", + "after": "us_m1a2_sep2_abrams", + "block": { + "params": [ + { "name": "rank", "value": { "type": "int", "value": 8 } } + ] + } +} +``` + +#### ⑥ `removeBlock`:删除指定路径的子块 +```jsonc +{ + "op": "removeBlock", + "path": ["country_usa", "army", "range[0]", "some_vehicle"] +} +``` + +#### ⑦ `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` 写 `[]`)。 + +### 3.3 全部 13 种 BLK 数据类型写法 + +直接写 JS 原始值时,构建器会优先沿用原字段的 BLK 类型(找不到原字段时:字符串→`string`,布尔→`bool`,整数→`int`,小数→`real`)。需要强制指定类型时,写 `{ "type": "<类型>", "value": <值> }`: + +| `type` | BLK 文本后缀 | `value` 示例 | +| --- | --- | --- | +| `string` | `:t` | `"us_m2a4"` | +| `int` | `:i` | `120` | +| `real` | `:r` | `1.5`(即使数值为 `2`,也会严格按浮点写入) | +| `bool` | `:b` | `true` / `false` | +| `int64` | `:i64` | `"133700000000000000"` 或整数 | +| `point2` | `:p2` | `[1.0, 2.5]` | +| `point3` | `:p3` | `[0.0, 1.5, -2.0]` | +| `point4` | `:p4` | `[0.0, 1.0, 0.0, 1.0]` | +| `ipoint2` | `:ip2` | `[10, 20]` | +| `ipoint3` | `:ip3` | `[1, 2, 3]` | +| `ipoint4` | `:ip4` | `[0, 1, 2, 3]` | +| `color` | `:c` | `[255, 128, 0, 255]`(`[r, g, b, a]`)或打包整数 `0xAARRGGBB` | +| `matrix` | `:m` | 12 个浮点数的数组(4 行 × 3 列) | + +--- + +## 4. CSV 本地化增量合并(`*.csv.patch.csv`) + +在 `client/packs/lang.vromfs.bin/lang/` 下放置与原文件同名加 `.patch.csv` 的文件(如 `units.csv.patch.csv`、`menu.csv.patch.csv`): + +```csv +"";"";"";"" +"my_custom_tank_shop";"M1A2 Mod";"M1A2 魔改型";"M1A2 魔改型" +"my_custom_tank_0";"M1A2 Mod Experimental";"M1A2 实验魔改型";"M1A2 實驗魔改型" +``` + +- 必须以分号 `;` 分隔并用双引号包裹字段,第一行写表头列名(只需列出你要填的语言列,缺失语言列会自动留空或保留原值); +- 如果第 1 列 ID 在原表已存在,只更新你提供的非空语言列;不存在则追加到表尾。 + +--- + +## 5. 修改游戏根目录 `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`,关掉模组后自动还原。 diff --git a/mod-dev-docs/zh-CN/03-custom-3d-vehicles.md b/mod-dev-docs/zh-CN/03-custom-3d-vehicles.md new file mode 100644 index 0000000..9bec5b2 --- /dev/null +++ b/mod-dev-docs/zh-CN/03-custom-3d-vehicles.md @@ -0,0 +1,75 @@ +# 03 · 添加全新 3D 模型与贴图载具 + +本章专门讲解如何在 WTOffline 中制作**带自定义 3D 模型(`.grp`)和贴图(`.dxp.bin`)的全新载具模组**,并让多款不同作者的新车模组同时叠加共存、跨盘零拷贝秒挂、关闭即还原。 + +--- + +## 1. 引擎加载机制(为什么放 `client/addon/` 就够了) + +经对 2.61.0.x 客户端 `aces.exe` 与 `config/settings.blk` 核对: +- 引擎启动时会读取 `aces.vromfs.bin` `config/settings.blk` 中的 `addons`、`addons_no_check` 与 `addonsWithBasePath` 三个列表; +- 凡是路径包含 `/pkg_user/` 的扩展目录,引擎会**跳过 `res/grp_hdr.vromfs.bin` 强制校验,直接扫描 `<目录>/res/` 下的全部 `.grp` 模型与 `.dxp.bin` 贴图包并注册进全局资源管理器**,同时读取里面的 `gamedata/units/unitsList.blk`; +- 如果模组自带正式 War Thunder CDK 编译的 `res/grp_hdr.vromfs.bin`,启动器会自动改挂到 `content/pkg_wto_` 走原生 `grp_hdr` 路径。 + +### 跨盘零拷贝挂载(不复制几个 GB 的模型!) + +无论全局 `mods/` 目录在 C 盘还是 D 盘、游戏副本在 J 盘,启动器都会用 **Windows NTFS 目录联接点(Junction)** 把你的 `client/addon/` 直接挂载到 `<游戏副本>/content/pkg_user/<安全模组ID>`: +- **不需要管理员权限**; +- **支持跨盘符**; +- **0 字节额外空间、约 1 毫秒完成**; +- 关闭模组时只拆除联接点本身,绝不删改 `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. **确保 `wpcost.blk` 与 `shop.blk` 的载具块名完全一致**: + - 本地服务器会从叠加后的 `char.vromfs.bin` 自动提取这辆车的研发链、银狮/金鹰/礼包价格、分房权重、改装件与挂载预设; + - 如果在 `wpcost.blk` 里设置了 `gift:t="msi_notebook"`,构建器会自动给这辆新车分配确定性的本地商城 GUID,玩家可以立刻在本地网页商店看到并购买它(还可以在 `server/tuning/store.jsonc` 里给它定自定义 GJN 价格和附赠内容!)。 +2. **`ui/atlases.vromfs.bin` 路径大小写**: + - 原版图标包内部路径统一为**全小写**,请把图标命名为 `gameuiskin/<全小写载具id>_ico.svg`。 +3. **验证 3D 模型资源名匹配**: + - `gamedata/units/tankmodels/us_mbt_demo.blk` 里的 `model:t="..."` 与 `animChar` 名称必须与 `.grp` 内部导出的资产名一致。 + +--- + +## 3. 配套涂装、瞄具、音效与原生目录的边界 + +- **独立涂装 / 瞄具 / 单人任务**:玩家照旧直接放进游戏目录的 `UserSkins/`、`UserSights/`、`UserMissions/` 即可,**不需要**封装成模组; +- **大型新车整合包附带配套资源**:如果你的新车模组顺手附带了专属涂装、火控瞄具或音效包,可以放进 `client/files/`: + - `client/files/UserSkins/us_mbt_demo_camo/...`(独占子目录 → 跨盘 Junction 零拷贝) + - `client/files/UserSights/us_mbt_demo/...`(独占子目录 → 跨盘 Junction 零拷贝) + - `client/files/sound/mod/my_cannon.bank`(平铺散文件 → 优先符号链接/同盘硬链接,跨盘退化增量缓存) +- **原生文件保护红线**:如果 `client/files/` 中的某路径与玩家自己手动放进 `UserSkins/` / `UserSights/` 的文件重名,启动器会跳过并在日志中提示冲突,**绝不覆盖玩家原生文件**。 diff --git a/mod-dev-docs/zh-CN/04-client-gui-and-exe.md b/mod-dev-docs/zh-CN/04-client-gui-and-exe.md new file mode 100644 index 0000000..ba61ed4 --- /dev/null +++ b/mod-dev-docs/zh-CN/04-client-gui-and-exe.md @@ -0,0 +1,125 @@ +# 04 · 客户端 GUI 补丁与声明式 EXE 补丁 + +> **实验期提示**:界面脚本补丁(`gui-patches`)与声明式 `exe` 补丁(`exe-patches`)依赖目标游戏客户端的代码结构,游戏更新或本体补丁演进时可能需要同步维护。 + +--- + +## 1. 客户端界面扩展的两种组合做法(推荐最佳实践) + +如果你要给游戏加一个新界面(例如自带的 `official-map-selector` 地图池弹窗),最佳实践是**“大块逻辑独立新建 + 极简增量补丁挂入口”**: + +1. **新增独立的 `.nut` / `.tpl` / `.css` 文件**:直接放进 `client/packs/gui.vromfs.bin/` 下(例如 `scripts/missions/wtoMapSelectorModal.nut`、`gui/missions/wtoMapSelectorModal.tpl`、`gui/missions/wtoMapSelector.css`)。独立文件零冲突、极易维护; +2. **用最小 GUI 增量补丁挂载入口按钮**:把修改原版脚本的几行放进 `client/gui-patches/<补丁名>/`。 + +> 注意:`gui.vromfs.bin` 内部路径为**全小写**。虽然 Quirrel 的 `import` 路径大小写不敏感,但放进 `client/packs/gui.vromfs.bin/` 的文件名建议保持小写或与原版一致。 + +--- + +## 2. `client/gui-patches/` 补丁格式 + +每个补丁一个子目录,内含 `patch.jsonc` 和引用的原文/替换片段文件: + +```text +client/gui-patches/ +└─ my-button-patch/ + ├─ patch.jsonc + ├─ find.nut + └─ replace.nut +``` + +`patch.jsonc` 示例: + +```jsonc +// Adds a custom entry button to the mode selection panel. +// Needed because the stock UI has no hook for custom modal windows. +// Without this patch, the custom map selector button is not shown. +{ + "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.nut", + "replace": "replace.nut" + } + ] + } + ] +} +``` + +### 规则与注意事项 +- **执行顺序**:离线版核心 GUI 补丁永远先应用,各模组的 `gui-patches` 在其后按启动器排序依次应用; +- **唯一命中保护**:每条 `edit` 的 `find` 文本必须在目标脚本中**恰好出现 1 次**,否则该补丁整条跳过并写入日志,绝不半应用写坏脚本; +- 替换文本里可以使用占位符 `{{LOCAL_ENDPOINT}}`,构建器会自动替换为当前本地服务器地址(`127.0.0.1:<端口>`); +- **多版本适配**:当游戏版本更新导致原文变化时,只需在 `variants` 数组里追加一个新的写法条目,构建器会自动选取恰好命中的那一条。 + +### 必做检查:用 Quirrel `compilestring` 做完整字节码检查 + +战雷使用的 Quirrel 脚本在登录阶段预加载。如果 `.nut` 存在**词法作用域冲突**(例如局部变量和顶部 `from ... import *` 常量重名)、**前向引用未声明函数**、或误用 **Quirrel 保留字(如 `base`)**,会导致登录一直卡在「正在加载」。 + +只做 AST 语法检查会漏掉这些错误,**必须**用项目匹配的 Quirrel 编译器(`sq.exe`)通过 `compilestring` 跑完整字节码编译: + +```powershell +# 示例:用 sq.exe 验证单个 .nut 文件能否通过完整字节码编译 +& "build\quirrel-cli\bin\Release\sq.exe" -e "local f = compilestring(readfile('your_script.nut'), 'your_script.nut'); println('OK')" +``` + +--- + +## 3. 声明式 `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": [] + } + } + ] +} +``` + +### 定位方式(`locate.kind`) +- `signature`:字节特征码扫描(支持 `??` 通配与 `captures` 捕获偏移/相对跳转目标); +- `string_ref`:按代码引用的固定 ASCII 字符串定位,可附加局部指令特征校验; +- `within`:在依赖补丁或锚点所在的函数范围(按 PE 异常表边界)内搜索局部特征。 + +### 安全红线与核心补丁锁(不可绕过) + +1. **核心离线与隔离补丁永远最先规划并锁定字节区间**(包括不连 Gaijin、不加载反作弊、目录与注册表隔离、禁止拉起官方启动器、本地 TLS/匹配公钥等); +2. **任何模组 `exe` 补丁如果与核心补丁字节重叠,会被构建器硬拒绝**并在日志中报错 `overlaps protected core patch`; +3. 如果两个模组的 `exe` 补丁写入同一段字节,后序补丁会被拒绝并标注冲突模组 ID; +4. 如果当前游戏版本找不到特征码或原字节不匹配,该补丁会被跳过并写入日志,不会导致核心构建崩溃。 diff --git a/mod-dev-docs/zh-CN/05-server-tuning.md b/mod-dev-docs/zh-CN/05-server-tuning.md new file mode 100644 index 0000000..4caf76b --- /dev/null +++ b/mod-dev-docs/zh-CN/05-server-tuning.md @@ -0,0 +1,90 @@ +# 05 · 服务端零代码数值叠加(Tuning) + +本地服务器把离线版自定的经济、对局、商城、补给箱、兑换码、联队、研发策略等数值统一放进了 **12 份 `.jsonc` 配置文件**。模组作者一行代码都不用写,只需在 `server/tuning/` 下放同名 `.jsonc` 文件即可按字段叠加修改。 + +--- + +## 1. 多层合并优先级 + +从低到高依次合并(后者覆盖前者): + +```text +1. 离线版内置默认配置(apps/server/tuning/<名称>.jsonc) +2. 已启用模组 1 的 server/tuning/<名称>.jsonc +3. 已启用模组 2 的 server/tuning/<名称>.jsonc + ...(按启动器「模组」页从上到下顺序) +N. 玩家在启动器「数值」页的手动设置(<客户端数据目录>/tuning/<名称>.jsonc,最高优先级) +``` + +> 所有合并结果在服务器启动时都会经过严格类型和范围校验;字段类型或范围不合法时会直接报出模组 ID、文件名与期望值。 + +--- + +## 2. 全部 12 份可叠加配置文件一览 + +| 文件名 | 管辖内容 | 典型模组用途 | +| --- | --- | --- | +| `battle.jsonc` | 银狮/研发倍率、房间人数、AI 数量与重生次数、分房权重跨度(`brSpreadMrank`)、子模式概率、攻击无人机出生分 | 爽游倍率、大混战人数、无分房压权、无限 AI 重生 | +| `battle-economy.jsonc` | 各类战斗行为基价与对局结算经济参数 | 精细调整击杀/占点/助攻收益占比 | +| `store.jsonc` | 金鹰包、银狮包、高账价格、单车礼包价(`byVehicle`/`byRank`)、多车礼包(`multiVehiclePacks`) | 为新增载具定礼包价、打包自定义多车特惠礼包 | +| `marketplace.jsonc` | 交易所载具券与外观券参考价、品质与手续费 | 调整市场物价、给新增市场车定价 | +| `trophies.jsonc` | 经典战利品箱(银狮箱、老兵箱、奖池直购价)与权重规则 | 新增自定义抽卡箱、调整稀有载具掉率 | +| `supply-chests.jsonc` | 新版外部库存补给箱与掉落池 | 新增自制外部库存箱子 | +| `recycling.jsonc` | 道具回收与零件再合成配方 | 修改合成消耗或产出权重 | +| `redeem-codes.jsonc` | 离线兑换码与作弊码规则 | 添加专属模组礼包兑换码 | +| `new-profile.jsonc` | 新建存档初始银狮、金鹰与 GJN 余额 | 自定义开荒或全解锁爽游开局 | +| `research.jsonc` | 自动挑选默认研发目标策略 | 修改研发体验 | +| `clans.jsonc` | 联队活跃度、人数上限、预置联队 | 新增自定义预置联队 | +| `limits.jsonc` | 单次购买道具上限、战报/日志保留条数 | 提高单次购买上限或日志保留量 | + +--- + +## 3. 列表增量合并语法(`$listOps`) + +默认情况下,JSON 对象按字段递归合并,普通数组会**整体替换**上一层的数组。 +为了避免两个模组同时往多车礼包、兑换码、补给箱列表里加内容时互相顶掉,任何数组字段都支持用 **`{ "$listOps": [...] }`** 做增量操作: + +```jsonc +// 示例:server/tuning/store.jsonc +{ + "multiVehiclePacks": { + "$listOps": [ + // ① 追加新条目到列表末尾 + { + "op": "append", + "items": [ + { + "id": "mod_modern_duo_pack", + "title": { "en": "Modern Duo Pack", "zh": "现代双车组合包" }, + "priceGjn": 49.99, + "goldenEagles": 2000, + "premiumDays": 15, + "vehicles": ["us_m1a2_sep2_abrams", "germ_leopard_2a7v"] + } + ] + }, + // ② 按指定键(如 id)查找:存在则按对象递归合并修改,不存在则追加 + { + "op": "upsertBy", + "key": "id", + "item": { + "id": "wto_pack_two_fronts", + "priceGjn": 19.99 + } + }, + // ③ 按指定键与值删除某一项 + { + "op": "removeBy", + "key": "id", + "value": "some_unwanted_pack_id" + } + ] + } +} +``` + +支持的 4 种 `$listOps` 操作: +- `append`:`{ "op": "append", "items": [...] }` — 追加到末尾; +- `prepend`:`{ "op": "prepend", "items": [...] }` — 插入到开头; +- `upsertBy`:`{ "op": "upsertBy", "key": "<字段名>", "item": { ... } }` — 按字段匹配合并,找不到就追加; +- `removeBy`:`{ "op": "removeBy", "key": "<字段名>", "value": <匹配值> }` — 删除全部匹配条目。 diff --git a/mod-dev-docs/zh-CN/06-server-scripting-api.md b/mod-dev-docs/zh-CN/06-server-scripting-api.md new file mode 100644 index 0000000..ea5c143 --- /dev/null +++ b/mod-dev-docs/zh-CN/06-server-scripting-api.md @@ -0,0 +1,157 @@ +# 06 · 服务端 JS/TS 脚本完整接口手册 + +> **实验期警告(API `0.1-experimental`)** +> 本章描述的所有服务端脚本接口与内部对象均处于极初期开发阶段,随时可能随本体开发变动,不保证向后兼容。 + +--- + +## 1. 运行环境与语法规则 + +本地服务器运行在启动器内置的 **Electron 43 / Node.js 24** 上,**原生开启 TypeScript 类型剥离(`strip`)**,玩家电脑无需安装 Node 或 TypeScript。 + +- **入口探测顺序**:默认依次查找 `server/index.ts` → `server/index.mjs` → `server/index.js`(也可在 `mod.jsonc` 的 `server.entry` 中自定义相对路径); +- **直接写 `.ts` 的语法约定**:遵循 TypeScript 的 `erasableSyntaxOnly` 规则——支持全部类型注解、`interface`、`type`、泛型与 `as`,但**不要使用**需要代码生成的 `enum`、`namespace` 或构造函数参数属性(改用 `as const` 对象与联合类型即可); +- 如果你的项目想使用任意 TS 语法或第三方 npm 包,自行用 esbuild / tsc 打包成单文件 `.mjs` 分发即可。 + +### 标准导出写法 + +```ts +export default { + async setup(ctx) { + ctx.logger.info('mod initialized'); + // 在此注册钩子、路由与初始化逻辑 + }, +}; +``` +(也支持直接导出默认函数 `export default function (ctx) { ... }` 或具名导出 `export function setup(ctx) { ... }`。) + +--- + +## 2. `WtoServerModContext`(注入给 `setup(ctx)` 的上下文对象) + +| 属性 | 类型 | 说明 | +| --- | --- | --- | +| `ctx.apiVersion` | `string` | 当前运行时的实验期 API 版本号(`"0.1-experimental"`) | +| `ctx.manifest` | `ModManifest` | 本模组解析后的 `mod.jsonc` 清单对象 | +| `ctx.modDir` | `string` | 本模组根目录的绝对路径(可用 `node:fs` 读取模组自带的配置文件) | +| `ctx.gameFolder` | `string` | 当前运行的离线游戏副本根目录 | +| `ctx.dataFolder` | `string` | 当前客户端的数据目录(含存档、缓存、日志) | +| `ctx.port` | `number` | 本次启动的本地服务器监听端口 | +| `ctx.logger` | `{ info, warn, error }` | 带 `[mod:]` 前缀的日志输出器,自动进入启动器日志与诊断导出 | +| `ctx.storage` | `ModStorageApi` | 按账号隔离或全局共享的独立 JSON 存档区(见第 3 节) | +| `ctx.hooks` | `ServerModHooksApi` | 生命周期、档案、匹配与对局钩子(见第 4 节) | +| `ctx.routes` | `ServerModRoutesApi` | `char`、`matching` 与本地 HTTP 路由扩展(见第 5 节) | + +完整 TypeScript 定义源码见仓库 `packages/mods/src/server-api.ts`。 + +--- + +## 3. 独立存档区(`ctx.storage`) + +**硬性最佳实践**:请勿往原版 `profile.blk` 写入非标准字段(容易影响客户端序列化或卸载模组后污染存档)。统一使用 `ctx.storage`: + +```ts +// ① 按本地玩家账号隔离:/saves//mods/.json +const playerStore = ctx.storage.forPlayer(userId); +const prev = playerStore.read<{ wins: number }>() ?? { wins: 0 }; +playerStore.write({ wins: prev.wins + 1 }); // 原子写盘 +// playerStore.remove(); + +// ② 模组全局共享存储:/mods-data/.json +const sharedStore = ctx.storage.shared(); +``` + +--- + +## 4. 全部生命周期与业务钩子(`ctx.hooks`) + +### 4.1 `ctx.hooks.onDatasetsLoaded(async (datasets) => { ... })` +在本地服务器从叠加后的 `.vromfs.bin` 提取完静态数据集、尚未组装业务目录前触发。可读取或原地修改: +- `datasets.vehicles`:载具目录数组(含价格、研发点、权重、科技树信息) +- `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(() => { ... })` +服务器开始监听端口后、以及关闭前触发(适合启动/清理定时器或打印日志)。 + +### 4.4 档案钩子:`ctx.hooks.profile.onRefresh((profile, userId) => { ... })` +每次读取或更新玩家档案并执行完原生刷新管线后调用(`profile` 是 `@wto/blk` 的 `BlkBlock`)。 + +### 4.5 对局与匹配钩子(`ctx.hooks.battle`) + +#### ① `ctx.hooks.battle.onBeforeMatchmake((ctx) => { ... })` +玩家点击「加入战斗」进入匹配队列、尚未调用 `BattleMatchmaker` 之前触发: +- `ctx`:`{ userId, eventName, request }`(`request` 为客户端发来的原始 `match.enqueue` 参数对象)。 + +#### ② `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((ctx) => { ... })` +对局进行中收到客户端上报的实时战斗事实(击杀、占点、生命段、核弹爆炸)时触发: +- `ctx`:`{ userId, roomId, fact }`。 + +#### ④ `ctx.hooks.battle.onAfterSettle((ctx) => { ... })` +对局结束并写入原生结算后、档案落盘前触发: +- `ctx`:`{ userId, roomId, summary }`(`summary` 含 `{ profile, report, session }`),可在此发放额外自定义奖励或累计模组统计。 + +--- + +## 5. 协议路由与本地网页扩展(`ctx.routes`) + +### 5.1 Char 动作扩展(`ctx.routes.char`) +- `ctx.routes.char.register(action, handler)`:注册全新的自定义 `cln_*` 动作(如配合客户端 GUI 补丁发来的请求); +- `ctx.routes.char.wrap(action, async (req, next) => { ... })`:拦截并包装现有 `cln_*` 动作(可在调用 `await next(req)` 前后改请求或改响应)。 + +### 5.2 匹配服 RPC 扩展(`ctx.routes.matching`) +客户端 Quirrel 脚本可以直接用 `matchingApiFunc("wto_mod.<你的方法>", params, callback)` 调用本地服务器匹配接口! +- `ctx.routes.matching.register(method, (req) => ({ ... }))`:注册自定义 RPC(`req` 含 `{ method, params, userId }`,直接返回 JSON 对象); +- `ctx.routes.matching.wrap(method, (req, next) => { ... })`:包装现有匹配服 RPC。 + +```ts +ctx.routes.matching.register('wto_mod.my_mod.ping', ({ userId, params }) => ({ + ok: true, + userId, + echo: params, +})); +``` + +### 5.3 本地 HTTP / 内置浏览器网页路由(`ctx.routes.http`) +自动挂载在 **`/mods/<你的modId>/...`** 命名空间下,支持精确路径和 `/*` 通配后缀,既可用系统浏览器访问,也可以通过游戏内置浏览器直接打开: + +```ts +ctx.routes.http.register('/panel', () => ({ + status: 200, + contentType: 'text/html; charset=utf-8', + body: '

My Mod Panel

', +})); + +ctx.routes.http.register('/api/*', (req) => ({ + status: 200, + contentType: 'application/json; charset=utf-8', + body: JSON.stringify({ path: req.path, query: req.query }), +})); +``` diff --git a/mod-dev-docs/zh-CN/07-troubleshooting-and-faq.md b/mod-dev-docs/zh-CN/07-troubleshooting-and-faq.md new file mode 100644 index 0000000..6dfc894 --- /dev/null +++ b/mod-dev-docs/zh-CN/07-troubleshooting-and-faq.md @@ -0,0 +1,44 @@ +# 07 · 排错、日志与最佳实践 + +## 1. 模组出错了去哪里看日志? + +启动器所有模组构建与运行日志都会汇入标准日志目录,可在 **「设置 › 诊断 › 打开日志目录」** 或 **「关于 › 导出诊断日志」** 直接查看: + +1. **启动器主日志(`launcher.log`)**: + - 搜索 `[build]`:查看本轮启用了哪些模组、各数据包叠加统计、以及哪条 GUI 补丁或 `exe` 补丁被跳过及精确原因; + - 搜索 `[mods]`:查看跨盘 Junction 挂载结果、被跳过的原生文件冲突告警、以及还原的可选数据包; + - 搜索 `[server]` 或 `[mod:<你的modId>]`:查看服务端脚本加载报错、堆栈、以及你在脚本里调用 `ctx.logger.info/warn/error` 打印的全部输出。 +2. **游戏客户端日志(`<客户端目录>/.game_logs/*.clog`)**: + - 若客户端 GUI 脚本报错或卡在「正在加载」,查看最新的 `.clog`(或先用 `sq.exe` 做完整字节码检查定位); + - 若新增 3D 模型未渲染,搜索 `.clog` 中的 `[PACK]`、`pkg_user` 或模型资源名确认是否被引擎加载。 + +--- + +## 2. 常见报错速查 + +| 现象 / 报错 | 原因 | 解决方法 | +| --- | --- | --- | +| 启动器提示某模组目录读取失败 | `mod.jsonc` JSON 语法错误、含未知字段、`id` 不合规范或 `server.entry` 路径不存在 | 对照第 01 章字段表核对 `mod.jsonc` | +| 点启动提示「存在阻塞性模组错误」 | 启用的模组缺少 `requires` 前置、前置未勾选,或同时启用了声明 `conflicts` 互斥的模组 | 按「模组」页顶部的红色错误列表补齐前置或关闭互斥项 | +| 服务端加载 `.ts` 报语法错(如 `enum` 不支持) | Node 24 原生 TS 剥离不支持需要代码生成的旧语法 | 改用 `as const` 对象 + 联合类型,或自行编译为 `.mjs` | +| 日志提示 `overlaps protected core patch` | 模组的 `client/exe-patches/` 试图修改离线版核心隔离补丁锁定的字节 | 不可覆盖核心隔离区段,请改用其他钩点或服务端方案 | +| 日志提示 `target already exists as a native/player file` | `client/files/` 中的某文件与玩家自己在 `UserSkins/` 或 `UserSights/` 手动放的文件重名 | 给模组自带的配套子目录加上专属前缀(如 `mod_<你的id>_...`)避免撞名 | +| 进机库一直卡在「正在加载」 | 新增或修补的 `.nut` 脚本存在 Quirrel 词法作用域冲突、保留字误用或前向引用 | 用 `sq.exe` 对最终 `.nut` 跑完整 `compilestring` 字节码检查 | + +--- + +## 3. 跨盘与非 NTFS 磁盘说明 + +- **NTFS 硬盘(绝大多数 Windows 电脑)**:`client/addon/`(3D 模型与贴图)和独占子目录(如 `UserSkins/<子目录>`)全部通过 **NTFS Directory Junction** 挂载——**跨盘可用、免管理员、0 额外空间、1 毫秒完成**; +- **平铺散文件(如 `sound/mod/*.bank`)**:依次尝试文件符号链接(开 Windows 开发者模式时跨盘零拷贝)→ 同盘硬链接 → 增量缓存复制(未修改文件下次启动自动跳过); +- **exFAT 移动硬盘**:因文件系统不支持 Junction 和硬链接,自动退化为按大小与修改时间比对的增量缓存复制,功能照常可用。 + +--- + +## 4. 给模组制作组的 5 条黄金习惯 + +1. **命名空间隔离一切**:模组 ID 用 `<作者>.<模组名>`;新增载具、武器、涂装子目录、自定义匹配 RPC、自定义 Char 动作全部带自己前缀(如 `wto_mod.<名称>`),避免和其他模组撞车; +2. **公共表一律用补丁,绝不整文件覆盖**:修改 `shop.blk`、`wpcost.blk`、`unittags.blk`、`units.csv` 时永远用 `.patch.jsonc` / `.patch.csv`; +3. **只读原版,不污染主存档**:模组持久化数据全部写进 `ctx.storage.forPlayer(userId)`,卸载模组后玩家主存档干干净净; +4. **界面大逻辑拆独立文件**:新弹窗放 `client/packs/gui.vromfs.bin/`,`gui-patches/` 里只留几行挂入口按钮的代码,换版本几乎不用重写; +5. **发布前做一次“开 → 玩 → 关 → 重启”循环**:确认启用时生效、关掉后彻底还原,且与其他模组一起开不冲突。 diff --git a/scripts/build-mod-docs-html.ts b/scripts/build-mod-docs-html.ts new file mode 100644 index 0000000..075f66d --- /dev/null +++ b/scripts/build-mod-docs-html.ts @@ -0,0 +1,411 @@ +/** + * Generate self-contained offline HTML mod authoring guides (zh-CN.html and en.html) + * from `mod-dev-docs//01..07.md`. Supports built-in sidebar navigation, copyable code + * blocks, language switching, and clean print-to-PDF styling with zero external dependencies. + */ +import { mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +interface Chapter { + readonly slug: string; + readonly title: string; + readonly html: string; +} + +export function buildOfflineModDocs(docsRoot: string, outputDir: string): { readonly zh: string; readonly en: string } { + mkdirSync(outputDir, { recursive: true }); + const zhPath = join(outputDir, 'zh-CN.html'); + const enPath = join(outputDir, 'en.html'); + writeFileSync(zhPath, renderHandbook(docsRoot, 'zh-CN'), 'utf8'); + writeFileSync(enPath, renderHandbook(docsRoot, 'en'), 'utf8'); + return { zh: zhPath, en: enPath }; +} + +function renderHandbook(docsRoot: string, lang: 'zh-CN' | 'en'): string { + const dir = join(docsRoot, lang); + const files = readdirSync(dir) + .filter((name) => name.endsWith('.md')) + .sort((a, b) => a.localeCompare(b)); + + const chapters: Chapter[] = files.map((file) => { + const markdown = readFileSync(join(dir, file), 'utf8'); + const titleMatch = /^#\s+(.+)$/m.exec(markdown); + const title = titleMatch ? titleMatch[1]!.trim() : file.replace(/\.md$/, ''); + const slug = file.replace(/\.md$/, ''); + return { slug, title, html: renderMarkdown(markdown) }; + }); + + const isZh = lang === 'zh-CN'; + const pageTitle = isZh ? 'WTOffline 模组开发手册(离线版)' : 'WTOffline Mod Development Handbook (Offline)'; + const subtitle = isZh ? 'API 0.1-experimental · 实验期随时可能变动' : 'API 0.1-experimental · Subject to breaking changes'; + const switchHref = isZh ? 'en.html' : 'zh-CN.html'; + const switchLabel = isZh ? 'English' : '简体中文'; + const printLabel = isZh ? '打印 / 另存为 PDF' : 'Print / Save as PDF'; + const copyLabel = isZh ? '复制' : 'Copy'; + const copiedLabel = isZh ? '已复制' : 'Copied'; + + const navLinks = chapters + .map((ch) => `${escapeHtml(ch.title)}`) + .join('\n'); + + const sections = chapters + .map((ch) => `
${ch.html}
`) + .join('\n
\n'); + + return ` + + + + +${escapeHtml(pageTitle)} + + + + +
+ ${sections} +
+ + + +`; +} + +function renderMarkdown(source: string): string { + const lines = source.replace(/\r\n/g, '\n').split('\n'); + const out: string[] = []; + let i = 0; + + while (i < lines.length) { + const line = lines[i]!; + + if (line.trim() === '') { + i += 1; + continue; + } + + // Fenced code block. + const fence = /^```([A-Za-z0-9_-]*)/.exec(line); + if (fence) { + const codeLines: string[] = []; + i += 1; + while (i < lines.length && !lines[i]!.startsWith('```')) { + codeLines.push(lines[i]!); + i += 1; + } + if (i < lines.length) i += 1; + out.push(`
${escapeHtml(codeLines.join('\n'))}
`); + continue; + } + + // Horizontal rule. + if (/^---+$/.test(line.trim())) { + out.push('
'); + i += 1; + continue; + } + + // Headings. + const heading = /^(#{1,4})\s+(.+)$/.exec(line); + if (heading) { + const level = heading[1]!.length; + out.push(`${renderInline(heading[2]!)}`); + i += 1; + continue; + } + + // Blockquote. + if (line.startsWith('>')) { + const quoteLines: string[] = []; + while (i < lines.length && lines[i]!.startsWith('>')) { + quoteLines.push(lines[i]!.replace(/^>\s?/, '')); + i += 1; + } + out.push(`

${quoteLines.map(renderInline).join('
')}

`); + continue; + } + + // GFM table. + if (line.includes('|') && i + 1 < lines.length && /^\s*\|?[\s:-]+\|[\s|:-]*$/.test(lines[i + 1]!)) { + const headers = splitTableRow(line); + i += 2; + const rows: string[][] = []; + while (i < lines.length && lines[i]!.includes('|') && lines[i]!.trim() !== '') { + rows.push(splitTableRow(lines[i]!)); + i += 1; + } + const thead = `${headers.map((cell) => `${renderInline(cell)}`).join('')}`; + const tbody = `${rows.map((row) => `${row.map((cell) => `${renderInline(cell)}`).join('')}`).join('')}`; + out.push(`${thead}${tbody}
`); + continue; + } + + // Unordered or ordered list. + if (/^\s*[-*]\s+/.test(line) || /^\s*\d+\.\s+/.test(line)) { + const ordered = /^\s*\d+\.\s+/.test(line); + const tag = ordered ? 'ol' : 'ul'; + const items: string[] = []; + while (i < lines.length && (ordered ? /^\s*\d+\.\s+/.test(lines[i]!) : /^\s*[-*]\s+/.test(lines[i]!))) { + items.push(lines[i]!.replace(ordered ? /^\s*\d+\.\s+/ : /^\s*[-*]\s+/, '')); + i += 1; + } + out.push(`<${tag}>${items.map((item) => `
  • ${renderInline(item)}
  • `).join('')}`); + continue; + } + + // Paragraph. + const para: string[] = []; + while ( + i < lines.length + && lines[i]!.trim() !== '' + && !lines[i]!.startsWith('#') + && !lines[i]!.startsWith('```') + && !lines[i]!.startsWith('>') + && !/^---+$/.test(lines[i]!.trim()) + && !/^\s*[-*]\s+/.test(lines[i]!) + && !/^\s*\d+\.\s+/.test(lines[i]!) + ) { + para.push(lines[i]!); + i += 1; + } + out.push(`

    ${para.map(renderInline).join(' ')}

    `); + } + + return out.join('\n'); +} + +function splitTableRow(line: string): string[] { + return line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map((cell) => cell.trim()); +} + +function renderInline(text: string): string { + const tokens: string[] = []; + let work = text.replace(/`([^`]+)`/g, (_m, code: string) => { + const idx = tokens.length; + tokens.push(`${escapeHtml(code)}`); + return `\u0000T${idx}\u0000`; + }); + work = escapeHtml(work); + work = work.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1'); + work = work.replace(/\*\*([^*]+)\*\*/g, '$1'); + work = work.replace(/\u0000T(\d+)\u0000/g, (_m, idx: string) => tokens[Number(idx)] ?? ''); + return work; +} + +function escapeHtml(text: string): string { + return text + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"'); +} + +if (process.argv[1] && resolve(process.argv[1]) === resolve(import.meta.filename)) { + const repo = resolve(import.meta.dirname, '..'); + const outArgIdx = process.argv.indexOf('--out'); + const outDir = outArgIdx >= 0 && process.argv[outArgIdx + 1] + ? resolve(process.argv[outArgIdx + 1]!) + : join(repo, 'build', 'mod-dev-docs'); + const result = buildOfflineModDocs(join(repo, 'mod-dev-docs'), outDir); + console.log('Generated offline mod docs:', result.zh, result.en); +} diff --git a/scripts/build-windows-installer.ts b/scripts/build-windows-installer.ts index 5219cf3..cafb96f 100644 --- a/scripts/build-windows-installer.ts +++ b/scripts/build-windows-installer.ts @@ -5,6 +5,7 @@ import { dirname, join, relative, resolve, sep } from 'node:path'; import { Arch, build, Platform } from 'electron-builder'; import { launcherReleaseFiles, portableLauncherReleaseFiles } from '../apps/launcher/src/shared/schemas/app-update.ts'; import { formatManifest, MANIFEST_FILE, PATCH_PACK_FORMAT, recordedGameVersions } from '../packages/patcher/src/index.ts'; +import { buildOfflineModDocs } from './build-mod-docs-html.ts'; const repository = resolve(import.meta.dirname, '..'); const launcher = join(repository, 'apps', 'launcher'); @@ -71,6 +72,7 @@ async function stageInstaller(stage: string, manifest: LauncherManifest): Promis await cp(join(repository, 'LICENSE'), join(resources, 'LICENSE-WTOffline')); await cp(join(native, 'wto_ws.dll'), join(resources, 'native', 'wto_ws.dll')); await cp(join(repository, 'dev-docs', 'templates', 'mods'), join(resources, 'mod-templates'), { recursive: true }); + buildOfflineModDocs(join(repository, 'mod-dev-docs'), join(resources, 'mod-dev-docs')); for (const folder of ['exe', 'gui', 'native', 'versions']) { await cp(join(repository, 'patches', folder), join(resources, 'patches', folder), { recursive: true }); }