From 8fbaeb422887c910cfcf2577a277f36ffea4c97c Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:42:26 +0800 Subject: [PATCH 01/12] feat(mods): add core mod manifest, resolver, BLK/CSV patchers, and server API types --- package-lock.json | 12 + packages/blk/src/index.ts | 3 +- packages/blk/src/text/parse-text.ts | 317 ++++++++++++++++++++ packages/blk/src/tree.ts | 25 ++ packages/mods/package.json | 13 + packages/mods/src/blk-patch.ts | 450 ++++++++++++++++++++++++++++ packages/mods/src/csv-patch.ts | 140 +++++++++ packages/mods/src/discovery.ts | 252 ++++++++++++++++ packages/mods/src/index.ts | 79 +++++ packages/mods/src/manifest.ts | 159 ++++++++++ packages/mods/src/resolve.ts | 333 ++++++++++++++++++++ packages/mods/src/server-api.ts | 184 ++++++++++++ packages/mods/src/tuning-merge.ts | 77 +++++ packages/mods/src/types.ts | 154 ++++++++++ 14 files changed, 2197 insertions(+), 1 deletion(-) create mode 100644 packages/blk/src/text/parse-text.ts create mode 100644 packages/mods/package.json create mode 100644 packages/mods/src/blk-patch.ts create mode 100644 packages/mods/src/csv-patch.ts create mode 100644 packages/mods/src/discovery.ts create mode 100644 packages/mods/src/index.ts create mode 100644 packages/mods/src/manifest.ts create mode 100644 packages/mods/src/resolve.ts create mode 100644 packages/mods/src/server-api.ts create mode 100644 packages/mods/src/tuning-merge.ts create mode 100644 packages/mods/src/types.ts diff --git a/package-lock.json b/package-lock.json index 11d935b..900ac2a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1934,6 +1934,10 @@ "resolved": "apps/launcher", "link": true }, + "node_modules/@wto/mods": { + "resolved": "packages/mods", + "link": true + }, "node_modules/@wto/patcher": { "resolved": "packages/patcher", "link": true @@ -6151,6 +6155,14 @@ "name": "@wto/jsonc", "version": "0.1.0" }, + "packages/mods": { + "name": "@wto/mods", + "version": "0.1.0", + "dependencies": { + "@wto/blk": "*", + "@wto/jsonc": "*" + } + }, "packages/patcher": { "name": "@wto/patcher", "version": "0.1.0", diff --git a/packages/blk/src/index.ts b/packages/blk/src/index.ts index 9e376ad..1b2c5d2 100644 --- a/packages/blk/src/index.ts +++ b/packages/blk/src/index.ts @@ -10,6 +10,7 @@ export { emptyBlock } from './model.ts'; export { BlkFormatError } from './errors.ts'; export { BlkLabel, decodeBlk, encodeBlk, type SharedNameContext } from './binary/format.ts'; export { parseSharedNameMap, type SharedNameMap } from './shared-name-map.ts'; -export { appendParam, ensureBlock, findBlock, findParam, setParam, visitParams } from './tree.ts'; +export { appendParam, cloneBlock, ensureBlock, findBlock, findParam, setParam, visitParams } from './tree.ts'; export { formatBlkText } from './text/format-text.ts'; +export { isBinaryBlk, parseBlkText } from './text/parse-text.ts'; export { singleVehiclePackId, stableGuid } from './stable-guid.ts'; diff --git a/packages/blk/src/text/parse-text.ts b/packages/blk/src/text/parse-text.ts new file mode 100644 index 0000000..78be12a --- /dev/null +++ b/packages/blk/src/text/parse-text.ts @@ -0,0 +1,317 @@ +/** + * Parse a BLK document in Dagor's text syntax back into the typed in-memory model. + * + * Syntax source: DagorEngine prog/engine/ioSys/dataBlock/blk_read.cpp (BSD-3). + * Supports C/C++ comments, quoted and bare identifiers, `~` string escapes, nested blocks, + * optional semicolons, and every typed parameter suffix emitted by `format-text.ts`. + */ +import { BlkFormatError } from '../errors.ts'; +import { emptyBlock, type BlkBlock, type BlkValue } from '../model.ts'; + +export function isBinaryBlk(bytes: Uint8Array): boolean { + if (bytes.length === 0) return false; + const first = bytes[0]!; + // Binary BLK labels used by DagorEngine (see binary/format.ts BlkLabel: 0x00..0x06, zstd 0x28). + return first <= 0x06 || first === 0x28; +} + +export function parseBlkText(source: string): BlkBlock { + const parser = new BlkTextParser(source); + const root = emptyBlock(''); + parser.readBlockBody(root, false); + return root; +} + +class BlkTextParser { + readonly #text: string; + #pos = 0; + + constructor(text: string) { + // Strip UTF-8 BOM if present. + this.#text = text.startsWith('\uFEFF') ? text.slice(1) : text; + } + + readBlockBody(target: BlkBlock, expectClosingBrace: boolean): void { + while (true) { + this.#skipIgnored(); + if (this.#eof()) { + if (expectClosingBrace) this.#fail('unexpected end of BLK text inside block'); + return; + } + if (this.#peek() === '}') { + if (!expectClosingBrace) this.#fail('unexpected closing brace "}" at root'); + this.#pos += 1; + return; + } + const key = this.#readIdentifierOrString(); + this.#skipIgnored(); + const ch = this.#peek(); + if (ch === '{') { + this.#pos += 1; + const child = emptyBlock(key); + this.readBlockBody(child, true); + target.blocks.push(child); + continue; + } + if (ch === ':') { + this.#pos += 1; + const suffix = this.#readTypeSuffix(); + this.#skipHorizontalAndComments(); + if (this.#peek() !== '=') this.#fail(`expected "=" after type suffix ":${suffix}"`); + this.#pos += 1; + const value = this.#readValue(suffix); + target.params.push({ name: key, value }); + continue; + } + // Untyped `include "..."` directive or unknown syntax. + if (key === 'include' && (ch === '"' || ch === "'")) { + const included = this.#readQuotedString(); + target.params.push({ name: 'include', value: { type: 'string', value: included } }); + continue; + } + this.#fail(`expected "{" or ":" after "${key}"`); + } + } + + #readIdentifierOrString(): string { + const ch = this.#peek(); + if (ch === '"' || ch === "'") return this.#readQuotedString(); + const start = this.#pos; + while (!this.#eof()) { + const c = this.#text[this.#pos]!; + if (c === ':' || c === '{' || c === '}' || c === '=' || c === ';' || /\s/.test(c)) break; + if (c === '/' && (this.#text[this.#pos + 1] === '/' || this.#text[this.#pos + 1] === '*')) break; + this.#pos += 1; + } + if (this.#pos === start) this.#fail(`unexpected character "${ch ?? ''}"`); + return this.#text.slice(start, this.#pos); + } + + #readTypeSuffix(): string { + const start = this.#pos; + while (!this.#eof() && /[A-Za-z0-9]/.test(this.#text[this.#pos]!)) this.#pos += 1; + const suffix = this.#text.slice(start, this.#pos); + if (!suffix) this.#fail('missing BLK type suffix after ":"'); + return suffix; + } + + #readValue(suffix: string): BlkValue { + this.#skipHorizontalAndComments(); + switch (suffix) { + case 't': return { type: 'string', value: this.#readStringValue() }; + case 'i': return { type: 'int', value: this.#readInt() }; + case 'i64': return { type: 'int64', value: this.#readBigInt() }; + case 'r': return { type: 'real', value: this.#readReal() }; + case 'b': return { type: 'bool', value: this.#readBool() }; + case 'p2': return { type: 'point2', value: this.#readReals(2) as [number, number] }; + case 'p3': return { type: 'point3', value: this.#readReals(3) as [number, number, number] }; + case 'p4': return { type: 'point4', value: this.#readReals(4) as [number, number, number, number] }; + case 'ip2': return { type: 'ipoint2', value: this.#readInts(2) as [number, number] }; + case 'ip3': return { type: 'ipoint3', value: this.#readInts(3) as [number, number, number] }; + case 'ip4': return { type: 'ipoint4', value: this.#readInts(4) as [number, number, number, number] }; + case 'c': return { type: 'color', value: this.#readColor() }; + case 'm': return { type: 'matrix', value: this.#readMatrix() }; + default: this.#fail(`unsupported BLK type suffix ":${suffix}"`); + } + } + + #readStringValue(): string { + const ch = this.#peek(); + if (ch === '"' || ch === "'") return this.#readQuotedString(); + // Unquoted single-line string terminated by newline, semicolon, brace, or comment. + const start = this.#pos; + while (!this.#eof()) { + const c = this.#text[this.#pos]!; + if (c === '\r' || c === '\n' || c === ';' || c === '}') break; + if (c === '/' && (this.#text[this.#pos + 1] === '/' || this.#text[this.#pos + 1] === '*')) break; + this.#pos += 1; + } + return this.#text.slice(start, this.#pos).trim(); + } + + #readQuotedString(): string { + const quote = this.#text[this.#pos]!; + this.#pos += 1; + let out = ''; + while (!this.#eof()) { + const c = this.#text[this.#pos]!; + this.#pos += 1; + if (c === quote) return out; + if (c === '~' && !this.#eof()) { + const next = this.#text[this.#pos]!; + this.#pos += 1; + switch (next) { + case 'n': out += '\n'; break; + case 'r': out += '\r'; break; + case 't': out += '\t'; break; + case '~': out += '~'; break; + case '"': out += '"'; break; + case "'": out += "'"; break; + default: out += next; break; + } + continue; + } + out += c; + } + this.#fail('unterminated string literal'); + } + + #readToken(): string { + this.#skipHorizontalAndComments(); + const start = this.#pos; + while (!this.#eof()) { + const c = this.#text[this.#pos]!; + if (c === ',' || c === ';' || c === '}' || c === ']' || /\s/.test(c)) break; + if (c === '/' && (this.#text[this.#pos + 1] === '/' || this.#text[this.#pos + 1] === '*')) break; + this.#pos += 1; + } + if (this.#pos === start) this.#fail('expected value token'); + return this.#text.slice(start, this.#pos); + } + + #readInt(): number { + const raw = this.#readToken(); + const parsed = raw.startsWith('0x') || raw.startsWith('0X') ? Number.parseInt(raw, 16) : Number(raw); + if (!Number.isFinite(parsed) || !Number.isInteger(parsed)) this.#fail(`invalid integer "${raw}"`); + return parsed | 0; + } + + #readBigInt(): bigint { + const raw = this.#readToken(); + try { + return BigInt(raw); + } catch { + this.#fail(`invalid int64 "${raw}"`); + } + } + + #readReal(): number { + const raw = this.#readToken(); + const parsed = Number(raw); + if (!Number.isFinite(parsed)) this.#fail(`invalid real "${raw}"`); + return parsed; + } + + #readBool(): boolean { + const raw = this.#readToken().toLowerCase(); + if (raw === 'yes' || raw === 'true' || raw === '1') return true; + if (raw === 'no' || raw === 'false' || raw === '0') return false; + this.#fail(`invalid bool "${raw}"`); + } + + #readReals(count: number): number[] { + const values: number[] = []; + for (let i = 0; i < count; i += 1) { + if (i > 0) this.#expectComma(); + values.push(this.#readReal()); + } + return values; + } + + #readInts(count: number): number[] { + const values: number[] = []; + for (let i = 0; i < count; i += 1) { + if (i > 0) this.#expectComma(); + values.push(this.#readInt()); + } + return values; + } + + #readColor(): number { + const channels = this.#readInts(4); + const [r, g, b, a] = channels as [number, number, number, number]; + return (((a & 0xff) << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff)) >>> 0; + } + + #readMatrix(): number[] { + this.#expectChar('['); + const values: number[] = []; + for (let row = 0; row < 4; row += 1) { + this.#skipIgnored(); + this.#expectChar('['); + for (let col = 0; col < 3; col += 1) { + if (col > 0) this.#expectComma(); + values.push(this.#readReal()); + } + this.#skipHorizontalAndComments(); + this.#expectChar(']'); + this.#skipHorizontalAndComments(); + if (this.#peek() === ',') this.#pos += 1; + } + this.#skipIgnored(); + this.#expectChar(']'); + return values; + } + + #expectComma(): void { + this.#skipHorizontalAndComments(); + if (this.#peek() !== ',') this.#fail('expected "," between tuple components'); + this.#pos += 1; + } + + #expectChar(expected: string): void { + this.#skipHorizontalAndComments(); + if (this.#peek() !== expected) this.#fail(`expected "${expected}"`); + this.#pos += 1; + } + + #skipIgnored(): void { + while (!this.#eof()) { + const c = this.#text[this.#pos]!; + if (c === ';' || /\s/.test(c)) { + this.#pos += 1; + continue; + } + if (this.#skipComment()) continue; + break; + } + } + + #skipHorizontalAndComments(): void { + while (!this.#eof()) { + const c = this.#text[this.#pos]!; + if (c === ' ' || c === '\t') { + this.#pos += 1; + continue; + } + if (this.#skipComment()) continue; + break; + } + } + + #skipComment(): boolean { + if (this.#text[this.#pos] !== '/') return false; + const next = this.#text[this.#pos + 1]; + if (next === '/') { + this.#pos += 2; + while (!this.#eof() && this.#text[this.#pos] !== '\n') this.#pos += 1; + return true; + } + if (next === '*') { + this.#pos += 2; + while (!this.#eof()) { + if (this.#text[this.#pos] === '*' && this.#text[this.#pos + 1] === '/') { + this.#pos += 2; + return true; + } + this.#pos += 1; + } + this.#fail('unterminated block comment'); + } + return false; + } + + #peek(): string | undefined { + return this.#text[this.#pos]; + } + + #eof(): boolean { + return this.#pos >= this.#text.length; + } + + #fail(message: string): never { + const prefix = this.#text.slice(0, this.#pos); + const line = prefix.split('\n').length; + throw new BlkFormatError(`BLK text parse error on line ${line}: ${message}`); + } +} diff --git a/packages/blk/src/tree.ts b/packages/blk/src/tree.ts index c1c1a85..087825c 100644 --- a/packages/blk/src/tree.ts +++ b/packages/blk/src/tree.ts @@ -34,6 +34,31 @@ export function appendParam(block: BlkBlock, name: string, value: BlkValue): voi block.params.push({ name, value }); } +/** Deep-clone a BLK block tree, optionally under a new block name. */ +export function cloneBlock(block: BlkBlock, newName = block.name): BlkBlock { + return { + name: newName, + params: block.params.map((param) => ({ + name: param.name, + value: cloneValue(param.value), + })), + blocks: block.blocks.map((child) => cloneBlock(child)), + }; +} + +function cloneValue(value: BlkValue): BlkValue { + switch (value.type) { + case 'point2': return { type: 'point2', value: [...value.value] as [number, number] }; + case 'point3': return { type: 'point3', value: [...value.value] as [number, number, number] }; + case 'point4': return { type: 'point4', value: [...value.value] as [number, number, number, number] }; + case 'ipoint2': return { type: 'ipoint2', value: [...value.value] as [number, number] }; + case 'ipoint3': return { type: 'ipoint3', value: [...value.value] as [number, number, number] }; + case 'ipoint4': return { type: 'ipoint4', value: [...value.value] as [number, number, number, number] }; + case 'matrix': return { type: 'matrix', value: [...value.value] }; + default: return { ...value }; + } +} + /** Visit every parameter of the tree, depth first, with the path of block names leading to it. */ export function visitParams(block: BlkBlock, visit: (param: BlkParam, path: readonly string[]) => void, path: readonly string[] = []): void { diff --git a/packages/mods/package.json b/packages/mods/package.json new file mode 100644 index 0000000..c08bf07 --- /dev/null +++ b/packages/mods/package.json @@ -0,0 +1,13 @@ +{ + "name": "@wto/mods", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts" + }, + "dependencies": { + "@wto/blk": "*", + "@wto/jsonc": "*" + } +} diff --git a/packages/mods/src/blk-patch.ts b/packages/mods/src/blk-patch.ts new file mode 100644 index 0000000..08433e5 --- /dev/null +++ b/packages/mods/src/blk-patch.ts @@ -0,0 +1,450 @@ +/** + * Structured, type-preserving incremental patches for BLK documents (`*.blk.patch.jsonc`). + * + * Allows multiple mods to add vehicles to config/shop.blk, adjust prices/BR in config/wpcost.blk, + * tweak weapon/FM parameters, or clone an existing vehicle block and customize it without + * shipping whole stock files. + */ +import { + appendParam, + cloneBlock, + emptyBlock, + ensureBlock, + findParam, + setParam, + type BlkBlock, + type BlkValue, + type BlkValueType, +} from '@wto/blk'; +import { parseJsonc } from '@wto/jsonc'; + +export interface BlkPathStep { + readonly name: string; + /** Zero-based occurrence index when multiple sibling blocks share the same name (e.g. `range[2]`). */ + readonly index?: number; +} + +export type BlkPatchValueInput = + | string + | number + | boolean + | { readonly type: BlkValueType; readonly value: unknown }; + +export interface BlkBlockBlueprint { + readonly name?: string; + readonly params?: ReadonlyArray<{ readonly name: string; readonly value: BlkPatchValueInput }>; + readonly blocks?: readonly BlkBlockBlueprint[]; +} + +export type BlkPatchOp = + | { + readonly op: 'setParam'; + readonly path: readonly string[]; + readonly name: string; + readonly value: BlkPatchValueInput; + readonly createBlocks?: boolean; + } + | { + readonly op: 'addParam'; + readonly path: readonly string[]; + readonly name: string; + readonly value: BlkPatchValueInput; + readonly createBlocks?: boolean; + } + | { + readonly op: 'removeParam'; + readonly path: readonly string[]; + readonly name: string; + readonly value?: string | number | boolean; + } + | { + readonly op: 'upsertBlock'; + readonly path: readonly string[]; + readonly block?: BlkBlockBlueprint; + } + | { + readonly op: 'addBlock'; + readonly path: readonly string[]; + readonly name: string; + readonly block?: BlkBlockBlueprint; + readonly before?: string; + readonly after?: string; + readonly createBlocks?: boolean; + } + | { + readonly op: 'removeBlock'; + readonly path: readonly string[]; + } + | { + readonly op: 'cloneBlock'; + readonly from: readonly string[]; + readonly toParent: readonly string[]; + readonly newName: string; + readonly replaceExisting?: boolean; + readonly before?: string; + readonly after?: string; + readonly ops?: readonly BlkPatchOp[]; + }; + +export interface BlkPatchDocument { + readonly ops: readonly BlkPatchOp[]; +} + +export class BlkPatchError extends Error { + override name = 'BlkPatchError'; +} + +export function parseBlkPatchDocument(text: string, where = 'blk patch'): BlkPatchDocument { + let raw: unknown; + try { + raw = parseJsonc(text); + } catch (error) { + throw new BlkPatchError(`${where}: cannot parse JSONC: ${error instanceof Error ? error.message : String(error)}`); + } + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) { + throw new BlkPatchError(`${where}: root must be an object with an "ops" array`); + } + const opsRaw = (raw as Record).ops; + if (!Array.isArray(opsRaw)) { + throw new BlkPatchError(`${where}: missing "ops" array`); + } + return { ops: opsRaw.map((item, idx) => validateOp(item, `${where}.ops[${idx}]`)) }; +} + +export function applyBlkPatch(root: BlkBlock, patch: BlkPatchDocument, where = 'blk patch'): void { + for (let i = 0; i < patch.ops.length; i += 1) { + applyOp(root, patch.ops[i]!, `${where}.ops[${i}]`); + } +} + +function applyOp(root: BlkBlock, op: BlkPatchOp, where: string): void { + switch (op.op) { + case 'setParam': { + const target = resolveBlock(root, op.path, op.createBlocks ?? false, where); + const existing = findParam(target, op.name); + const value = toBlkValue(op.value, existing?.value.type, where); + setParam(target, op.name, value); + return; + } + case 'addParam': { + const target = resolveBlock(root, op.path, op.createBlocks ?? false, where); + const existing = findParam(target, op.name); + const value = toBlkValue(op.value, existing?.value.type, where); + appendParam(target, op.name, value); + return; + } + case 'removeParam': { + const target = tryResolveBlock(root, op.path); + if (!target) return; + target.params = target.params.filter((param) => { + if (param.name !== op.name) return true; + if (op.value === undefined) return false; + return !paramValueMatchesPrimitive(param.value, op.value); + }); + return; + } + case 'upsertBlock': { + const target = resolveBlock(root, op.path, true, where); + if (op.block) mergeBlockBlueprint(target, op.block, where); + return; + } + case 'addBlock': { + const parent = resolveBlock(root, op.path, op.createBlocks ?? false, where); + const created = emptyBlock(op.name); + if (op.block) mergeBlockBlueprint(created, op.block, where); + insertBlockPositioned(parent, created, op.before, op.after); + return; + } + case 'removeBlock': { + if (op.path.length === 0) throw new BlkPatchError(`${where}: cannot remove root block`); + const parent = tryResolveBlock(root, op.path.slice(0, -1)); + if (!parent) return; + const step = parsePathStep(op.path[op.path.length - 1]!, where); + const index = findChildBlockIndex(parent, step); + if (index >= 0) parent.blocks.splice(index, 1); + return; + } + case 'cloneBlock': { + const source = resolveBlock(root, op.from, false, `${where}.from`); + const parent = resolveBlock(root, op.toParent, true, `${where}.toParent`); + const cloned = cloneBlock(source, op.newName); + if (op.ops) { + for (let i = 0; i < op.ops.length; i += 1) { + applyOp(cloned, op.ops[i]!, `${where}.ops[${i}]`); + } + } + if (op.replaceExisting) { + const existingIdx = parent.blocks.findIndex((child) => child.name === op.newName); + if (existingIdx >= 0) { + parent.blocks[existingIdx] = cloned; + return; + } + } + insertBlockPositioned(parent, cloned, op.before, op.after); + return; + } + } +} + +function insertBlockPositioned(parent: BlkBlock, block: BlkBlock, before?: string, after?: string): void { + if (before !== undefined) { + const idx = parent.blocks.findIndex((child) => child.name === before); + if (idx >= 0) { + parent.blocks.splice(idx, 0, block); + return; + } + } + if (after !== undefined) { + const idx = parent.blocks.findIndex((child) => child.name === after); + if (idx >= 0) { + parent.blocks.splice(idx + 1, 0, block); + return; + } + } + parent.blocks.push(block); +} + +function mergeBlockBlueprint(target: BlkBlock, blueprint: BlkBlockBlueprint, where: string): void { + if (blueprint.params) { + for (const [idx, param] of blueprint.params.entries()) { + const existing = findParam(target, param.name); + const value = toBlkValue(param.value, existing?.value.type, `${where}.params[${idx}]`); + appendParam(target, param.name, value); + } + } + if (blueprint.blocks) { + for (const [idx, childBlueprint] of blueprint.blocks.entries()) { + const name = childBlueprint.name; + if (!name) throw new BlkPatchError(`${where}.blocks[${idx}]: child block must have a "name"`); + const child = emptyBlock(name); + mergeBlockBlueprint(child, childBlueprint, `${where}.blocks[${idx}]`); + target.blocks.push(child); + } + } +} + +function resolveBlock(root: BlkBlock, path: readonly string[], createMissing: boolean, where: string): BlkBlock { + let current = root; + for (const rawStep of path) { + const step = parsePathStep(rawStep, where); + const idx = findChildBlockIndex(current, step); + if (idx >= 0) { + current = current.blocks[idx]!; + } else if (createMissing && step.index === undefined) { + current = ensureBlock(current, step.name); + } else { + throw new BlkPatchError(`${where}: block "${rawStep}" not found along path [${path.join(' / ')}]`); + } + } + return current; +} + +function tryResolveBlock(root: BlkBlock, path: readonly string[]): BlkBlock | undefined { + let current = root; + for (const rawStep of path) { + const step = parsePathStep(rawStep, 'path'); + const idx = findChildBlockIndex(current, step); + if (idx < 0) return undefined; + current = current.blocks[idx]!; + } + return current; +} + +function parsePathStep(raw: string, where: string): BlkPathStep { + const match = /^(.+)\[(\d+)\]$/.exec(raw); + if (!match) { + if (!raw) throw new BlkPatchError(`${where}: empty path segment`); + return { name: raw }; + } + return { name: match[1]!, index: Number(match[2]!) }; +} + +function findChildBlockIndex(parent: BlkBlock, step: BlkPathStep): number { + const wanted = step.index ?? 0; + let seen = 0; + for (let i = 0; i < parent.blocks.length; i += 1) { + if (parent.blocks[i]!.name !== step.name) continue; + if (seen === wanted) return i; + seen += 1; + } + return -1; +} + +function toBlkValue(input: BlkPatchValueInput, inferredType: BlkValueType | undefined, where: string): BlkValue { + if (typeof input === 'string') return { type: 'string', value: input }; + if (typeof input === 'boolean') return { type: 'bool', value: input }; + if (typeof input === 'number') { + if (inferredType === 'real') return { type: 'real', value: input }; + if (inferredType === 'int') return { type: 'int', value: input | 0 }; + if (inferredType === 'int64') return { type: 'int64', value: BigInt(Math.trunc(input)) }; + return Number.isInteger(input) ? { type: 'int', value: input | 0 } : { type: 'real', value: input }; + } + if (!input || typeof input !== 'object') { + throw new BlkPatchError(`${where}: invalid BLK value`); + } + const { type, value } = input; + switch (type) { + case 'string': + if (typeof value !== 'string') throw new BlkPatchError(`${where}: string value expected`); + return { type: 'string', value }; + case 'bool': + if (typeof value !== 'boolean') throw new BlkPatchError(`${where}: bool value expected`); + return { type: 'bool', value }; + case 'int': + if (typeof value !== 'number' || !Number.isInteger(value)) throw new BlkPatchError(`${where}: int value expected`); + return { type: 'int', value: value | 0 }; + case 'real': + if (typeof value !== 'number' || !Number.isFinite(value)) throw new BlkPatchError(`${where}: real value expected`); + return { type: 'real', value }; + case 'int64': + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'bigint') { + return { type: 'int64', value: BigInt(value) }; + } + throw new BlkPatchError(`${where}: int64 value expected`); + case 'color': + if (typeof value === 'number' && Number.isInteger(value)) return { type: 'color', value: value >>> 0 }; + if (Array.isArray(value) && value.length === 4 && value.every((n) => typeof n === 'number')) { + const [r, g, b, a] = value as [number, number, number, number]; + return { type: 'color', value: (((a & 0xff) << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff)) >>> 0 }; + } + throw new BlkPatchError(`${where}: color expects integer or [r,g,b,a]`); + case 'point2': return { type: 'point2', value: expectNumberTuple(value, 2, false, where) as [number, number] }; + case 'point3': return { type: 'point3', value: expectNumberTuple(value, 3, false, where) as [number, number, number] }; + case 'point4': return { type: 'point4', value: expectNumberTuple(value, 4, false, where) as [number, number, number, number] }; + case 'ipoint2': return { type: 'ipoint2', value: expectNumberTuple(value, 2, true, where) as [number, number] }; + case 'ipoint3': return { type: 'ipoint3', value: expectNumberTuple(value, 3, true, where) as [number, number, number] }; + case 'ipoint4': return { type: 'ipoint4', value: expectNumberTuple(value, 4, true, where) as [number, number, number, number] }; + case 'matrix': return { type: 'matrix', value: expectNumberTuple(value, 12, false, where) }; + default: + throw new BlkPatchError(`${where}: unsupported BLK type "${String(type)}"`); + } +} + +function expectNumberTuple(raw: unknown, length: number, integerOnly: boolean, where: string): number[] { + if (!Array.isArray(raw) || raw.length !== length) { + throw new BlkPatchError(`${where}: expected array of ${length} numbers`); + } + return raw.map((item) => { + if (typeof item !== 'number' || !Number.isFinite(item) || (integerOnly && !Number.isInteger(item))) { + throw new BlkPatchError(`${where}: invalid numeric element in tuple`); + } + return integerOnly ? (item | 0) : item; + }); +} + +function paramValueMatchesPrimitive(value: BlkValue, expected: string | number | boolean): boolean { + if (typeof expected === 'string') return value.type === 'string' && value.value === expected; + if (typeof expected === 'boolean') return value.type === 'bool' && value.value === expected; + return (value.type === 'int' || value.type === 'real') && value.value === expected; +} + +function validateOp(raw: unknown, where: string): BlkPatchOp { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) { + throw new BlkPatchError(`${where}: operation must be an object`); + } + const obj = raw as Record; + const op = obj.op; + switch (op) { + case 'setParam': + case 'addParam': + return { + op, + path: expectStringArray(obj.path ?? [], `${where}.path`), + name: expectNonEmptyString(obj.name, `${where}.name`), + value: obj.value as BlkPatchValueInput, + ...(typeof obj.createBlocks === 'boolean' ? { createBlocks: obj.createBlocks } : {}), + }; + case 'removeParam': + return { + op, + path: expectStringArray(obj.path ?? [], `${where}.path`), + name: expectNonEmptyString(obj.name, `${where}.name`), + ...(typeof obj.value === 'string' || typeof obj.value === 'number' || typeof obj.value === 'boolean' + ? { value: obj.value } + : {}), + }; + case 'upsertBlock': + return { + op, + path: expectStringArray(obj.path, `${where}.path`), + ...(obj.block !== undefined ? { block: validateBlueprint(obj.block, `${where}.block`) } : {}), + }; + case 'addBlock': + return { + op, + path: expectStringArray(obj.path ?? [], `${where}.path`), + name: expectNonEmptyString(obj.name, `${where}.name`), + ...(obj.block !== undefined ? { block: validateBlueprint(obj.block, `${where}.block`) } : {}), + ...(typeof obj.before === 'string' ? { before: obj.before } : {}), + ...(typeof obj.after === 'string' ? { after: obj.after } : {}), + ...(typeof obj.createBlocks === 'boolean' ? { createBlocks: obj.createBlocks } : {}), + }; + case 'removeBlock': + return { + op, + path: expectStringArray(obj.path, `${where}.path`), + }; + case 'cloneBlock': + return { + op, + from: expectStringArray(obj.from, `${where}.from`), + toParent: expectStringArray(obj.toParent ?? [], `${where}.toParent`), + newName: expectNonEmptyString(obj.newName, `${where}.newName`), + ...(typeof obj.replaceExisting === 'boolean' ? { replaceExisting: obj.replaceExisting } : {}), + ...(typeof obj.before === 'string' ? { before: obj.before } : {}), + ...(typeof obj.after === 'string' ? { after: obj.after } : {}), + ...(Array.isArray(obj.ops) + ? { ops: obj.ops.map((nested, idx) => validateOp(nested, `${where}.ops[${idx}]`)) } + : {}), + }; + default: + throw new BlkPatchError(`${where}: unsupported op "${String(op)}"`); + } +} + +function validateBlueprint(raw: unknown, where: string): BlkBlockBlueprint { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) { + throw new BlkPatchError(`${where}: block blueprint must be an object`); + } + const obj = raw as Record; + const name = obj.name === undefined ? undefined : expectNonEmptyString(obj.name, `${where}.name`); + const params = obj.params === undefined ? undefined : expectParamList(obj.params, `${where}.params`); + const blocks = obj.blocks === undefined + ? undefined + : (Array.isArray(obj.blocks) + ? obj.blocks.map((child, idx) => validateBlueprint(child, `${where}.blocks[${idx}]`)) + : (() => { throw new BlkPatchError(`${where}.blocks: must be an array`); })()); + return { + ...(name !== undefined ? { name } : {}), + ...(params !== undefined ? { params } : {}), + ...(blocks !== undefined ? { blocks } : {}), + }; +} + +function expectParamList(raw: unknown, where: string): Array<{ readonly name: string; readonly value: BlkPatchValueInput }> { + if (!Array.isArray(raw)) throw new BlkPatchError(`${where}: must be an array`); + return raw.map((item, idx) => { + if (!item || typeof item !== 'object' || Array.isArray(item)) { + throw new BlkPatchError(`${where}[${idx}]: expected { name, value }`); + } + const entry = item as Record; + return { + name: expectNonEmptyString(entry.name, `${where}[${idx}].name`), + value: entry.value as BlkPatchValueInput, + }; + }); +} + +function expectStringArray(raw: unknown, where: string): string[] { + if (!Array.isArray(raw) || raw.some((item) => typeof item !== 'string' || item.length === 0)) { + throw new BlkPatchError(`${where}: must be an array of non-empty strings`); + } + return raw as string[]; +} + +function expectNonEmptyString(raw: unknown, where: string): string { + if (typeof raw !== 'string' || raw.length === 0) { + throw new BlkPatchError(`${where}: must be a non-empty string`); + } + return raw; +} diff --git a/packages/mods/src/csv-patch.ts b/packages/mods/src/csv-patch.ts new file mode 100644 index 0000000..52c52eb --- /dev/null +++ b/packages/mods/src/csv-patch.ts @@ -0,0 +1,140 @@ +/** + * Incremental semicolon-separated localization CSV merger for `lang.vromfs.bin` (`*.csv.patch.csv`). + * + * Keeps the stock file's column layout and quoting conventions while merging matching row keys + * (column 0) and appending new entries from each enabled mod in load order. + */ + +export function mergeLocalizationCsv(baseCsv: string, patchCsv: string): string { + const hasBom = baseCsv.startsWith('\uFEFF'); + const newline = baseCsv.includes('\r\n') ? '\r\n' : '\n'; + const cleanBase = hasBom ? baseCsv.slice(1) : baseCsv; + const cleanPatch = patchCsv.startsWith('\uFEFF') ? patchCsv.slice(1) : patchCsv; + + const baseLines = splitCsvLines(cleanBase); + const patchLines = splitCsvLines(cleanPatch); + if (baseLines.length === 0 || patchLines.length <= 1) return baseCsv; + + const baseHeader = parseSemicolonRow(baseLines[0]!); + const patchHeader = parseSemicolonRow(patchLines[0]!); + const baseColIndex = new Map(); + baseHeader.forEach((name, idx) => baseColIndex.set(name.trim(), idx)); + + const colMapping: Array<{ readonly patchIdx: number; readonly baseIdx: number }> = []; + for (let pIdx = 1; pIdx < patchHeader.length; pIdx += 1) { + const colName = patchHeader[pIdx]!.trim(); + const bIdx = baseColIndex.get(colName); + if (bIdx !== undefined) colMapping.push({ patchIdx: pIdx, baseIdx: bIdx }); + } + if (colMapping.length === 0) return baseCsv; + + // Map existing key -> line index in baseLines for fast in-place updates. + const rowIndexByKey = new Map(); + for (let i = 1; i < baseLines.length; i += 1) { + const line = baseLines[i]!; + if (!line.trim()) continue; + const key = firstField(line); + if (key) rowIndexByKey.set(key, i); + } + + const outLines = [...baseLines]; + const trailingBlank = outLines.length > 0 && outLines[outLines.length - 1] === ''; + if (trailingBlank) outLines.pop(); + + for (let i = 1; i < patchLines.length; i += 1) { + const line = patchLines[i]!; + if (!line.trim()) continue; + const patchCols = parseSemicolonRow(line); + const key = patchCols[0] ?? ''; + if (!key) continue; + + const existingIdx = rowIndexByKey.get(key); + if (existingIdx !== undefined) { + const merged = parseSemicolonRow(outLines[existingIdx]!); + while (merged.length < baseHeader.length) merged.push(''); + for (const { patchIdx, baseIdx } of colMapping) { + const replacement = patchCols[patchIdx]; + if (replacement !== undefined && replacement !== '') merged[baseIdx] = replacement; + } + outLines[existingIdx] = formatSemicolonRow(merged); + } else { + const created = new Array(baseHeader.length).fill(''); + created[0] = key; + for (const { patchIdx, baseIdx } of colMapping) { + const val = patchCols[patchIdx]; + if (val !== undefined) created[baseIdx] = val; + } + rowIndexByKey.set(key, outLines.length); + outLines.push(formatSemicolonRow(created)); + } + } + + const result = outLines.join(newline) + (trailingBlank ? newline : ''); + return hasBom ? `\uFEFF${result}` : result; +} + +function splitCsvLines(text: string): string[] { + // Handle quoted fields that may span multiple lines. + const lines: string[] = []; + let current = ''; + let inQuotes = false; + for (let i = 0; i < text.length; i += 1) { + const ch = text[i]!; + if (ch === '"') { + if (inQuotes && text[i + 1] === '"') { + current += '""'; + i += 1; + } else { + inQuotes = !inQuotes; + current += ch; + } + continue; + } + if (!inQuotes && (ch === '\n' || (ch === '\r' && text[i + 1] === '\n'))) { + lines.push(current); + current = ''; + if (ch === '\r') i += 1; + continue; + } + current += ch; + } + lines.push(current); + return lines; +} + +function parseSemicolonRow(line: string): string[] { + const fields: string[] = []; + let current = ''; + let inQuotes = false; + for (let i = 0; i < line.length; i += 1) { + const ch = line[i]!; + if (ch === '"') { + if (inQuotes && line[i + 1] === '"') { + current += '"'; + i += 1; + } else { + inQuotes = !inQuotes; + } + } else if (ch === ';' && !inQuotes) { + fields.push(current); + current = ''; + } else { + current += ch; + } + } + fields.push(current); + return fields; +} + +function firstField(line: string): string { + if (line.startsWith('"')) { + const cols = parseSemicolonRow(line); + return cols[0] ?? ''; + } + const semi = line.indexOf(';'); + return semi >= 0 ? line.slice(0, semi) : line; +} + +function formatSemicolonRow(fields: readonly string[]): string { + return fields.map((field) => `"${field.replaceAll('"', '""')}"`).join(';'); +} diff --git a/packages/mods/src/discovery.ts b/packages/mods/src/discovery.ts new file mode 100644 index 0000000..459ed69 --- /dev/null +++ b/packages/mods/src/discovery.ts @@ -0,0 +1,252 @@ +/** + * Discover installed mods inside the global mods directory and inspect their capabilities + * (server tuning/script, client pack patches, GUI patches, declarative exe patches, + * 3D model addons, and optional companion files). + */ +import { existsSync, readdirSync, statSync } from 'node:fs'; +import { join, relative } from 'node:path'; +import { MOD_MANIFEST_FILE, readModManifest } from './manifest.ts'; +import { + MODDABLE_CLIENT_PACKS, + type DiscoveredMod, + type ModContentSummary, + type ModDiscoveryError, + type ModDiscoveryResult, + type ModManifest, + type ModPackOperation, + type ModRiskBadge, + type ModdableClientPack, +} from './types.ts'; + +const DEFAULT_SERVER_ENTRIES = ['server/index.ts', 'server/index.mjs', 'server/index.js'] as const; +const DEFAULT_SERVER_TUNING_DIR = 'server/tuning'; +const BLK_PATCH_SUFFIX = '.patch.jsonc'; +const CSV_PATCH_SUFFIX = '.patch.csv'; +const CONFIG_BLK_PATCH_PATH = 'client/config-blk.patch.jsonc'; + +export function discoverMods(modsRootDir: string): ModDiscoveryResult { + if (!existsSync(modsRootDir)) return { mods: [], errors: [] }; + + const mods: DiscoveredMod[] = []; + const errors: ModDiscoveryError[] = []; + const seenIds = new Map(); + + let entries; + try { + entries = readdirSync(modsRootDir, { withFileTypes: true }); + } catch (error) { + return { + mods: [], + errors: [{ folderName: '.', rootDir: modsRootDir, reason: error instanceof Error ? error.message : String(error) }], + }; + } + + for (const entry of entries) { + if (!entry.isDirectory()) continue; + const rootDir = join(modsRootDir, entry.name); + if (!existsSync(join(rootDir, MOD_MANIFEST_FILE))) continue; + try { + const manifest = readModManifest(rootDir); + const duplicateFolder = seenIds.get(manifest.id); + if (duplicateFolder) { + errors.push({ + folderName: entry.name, + rootDir, + reason: `duplicate mod id "${manifest.id}" (already provided by folder "${duplicateFolder}")`, + }); + continue; + } + seenIds.set(manifest.id, entry.name); + const content = inspectModContent(rootDir, manifest); + mods.push({ folderName: entry.name, rootDir, manifest, content }); + } catch (error) { + errors.push({ + folderName: entry.name, + rootDir, + reason: error instanceof Error ? error.message : String(error), + }); + } + } + + mods.sort((left, right) => left.manifest.id.localeCompare(right.manifest.id)); + errors.sort((left, right) => left.folderName.localeCompare(right.folderName)); + return { mods, errors }; +} + +export function inspectModContent(rootDir: string, manifest: ModManifest): ModContentSummary { + const serverEntry = resolveServerEntry(rootDir, manifest); + const tuningDirRel = manifest.server?.tuning ?? DEFAULT_SERVER_TUNING_DIR; + const serverTuningFiles = listTuningFiles(rootDir, tuningDirRel); + const packOperations = scanClientPackOperations(rootDir); + const guiPatchDirs = scanPatchDirectories(rootDir, 'client/gui-patches'); + const exePatchDirs = scanPatchDirectories(rootDir, 'client/exe-patches'); + + const addonDir = join(rootDir, 'client', 'addon'); + const addonRelativeFiles = existsSync(addonDir) && isDirectory(addonDir) + ? listRelativeFiles(addonDir) + : []; + const hasClientAddon = addonRelativeFiles.length > 0; + const addonHasGrpHdr = addonRelativeFiles.some((file) => file.toLowerCase() === 'res/grp_hdr.vromfs.bin'); + + const filesDir = join(rootDir, 'client', 'files'); + const clientFiles = existsSync(filesDir) && isDirectory(filesDir) + ? listRelativeFiles(filesDir) + : []; + + const configBlkPatch = isFile(join(rootDir, ...CONFIG_BLK_PATCH_PATH.split('/'))) + ? CONFIG_BLK_PATCH_PATH + : undefined; + + const badges = computeRiskBadges({ + hasData: serverTuningFiles.length > 0 || packOperations.length > 0 || hasClientAddon || clientFiles.length > 0 || configBlkPatch !== undefined, + hasGui: guiPatchDirs.length > 0, + hasScript: serverEntry !== undefined, + hasExe: exePatchDirs.length > 0, + }); + + return { + ...(serverEntry !== undefined ? { serverEntry } : {}), + serverTuningFiles, + packOperations, + guiPatchDirs, + exePatchDirs, + hasClientAddon, + addonHasGrpHdr, + addonRelativeFiles, + clientFiles, + ...(configBlkPatch !== undefined ? { configBlkPatch } : {}), + badges, + }; +} + +function resolveServerEntry(rootDir: string, manifest: ModManifest): string | undefined { + if (manifest.server?.entry) { + const full = join(rootDir, ...manifest.server.entry.split('/')); + if (!isFile(full)) { + throw new Error(`declared server.entry "${manifest.server.entry}" does not exist`); + } + return manifest.server.entry; + } + for (const candidate of DEFAULT_SERVER_ENTRIES) { + if (isFile(join(rootDir, ...candidate.split('/')))) return candidate; + } + return undefined; +} + +function listTuningFiles(rootDir: string, tuningDirRel: string): string[] { + const dir = join(rootDir, ...tuningDirRel.split('/')); + if (!isDirectory(dir)) return []; + return readdirSync(dir, { withFileTypes: true }) + .filter((entry) => entry.isFile() && entry.name.endsWith('.jsonc')) + .map((entry) => entry.name.slice(0, -'.jsonc'.length)) + .sort(); +} + +function scanClientPackOperations(rootDir: string): ModPackOperation[] { + const packsRoot = join(rootDir, 'client', 'packs'); + if (!isDirectory(packsRoot)) return []; + + const ops: ModPackOperation[] = []; + for (const pack of MODDABLE_CLIENT_PACKS) { + const packDir = join(packsRoot, ...pack.split('/')); + if (!isDirectory(packDir)) continue; + for (const rel of listRelativeFiles(packDir)) { + const sourceRelativePath = `client/packs/${pack}/${rel}`; + if (rel.toLowerCase().endsWith(BLK_PATCH_SUFFIX)) { + ops.push({ + pack, + targetPath: rel.slice(0, -BLK_PATCH_SUFFIX.length), + action: 'blk-patch', + sourceRelativePath, + }); + } else if (rel.toLowerCase().endsWith(CSV_PATCH_SUFFIX)) { + ops.push({ + pack, + targetPath: rel.slice(0, -CSV_PATCH_SUFFIX.length), + action: 'csv-patch', + sourceRelativePath, + }); + } else { + ops.push({ + pack, + targetPath: rel, + action: 'file', + sourceRelativePath, + }); + } + } + } + return ops; +} + +function scanPatchDirectories(rootDir: string, subPath: string): string[] { + const base = join(rootDir, ...subPath.split('/')); + if (!isDirectory(base)) return []; + const results: string[] = []; + const walk = (current: string) => { + for (const entry of readdirSync(current, { withFileTypes: true })) { + if (!entry.isDirectory()) continue; + const full = join(current, entry.name); + if (isFile(join(full, 'patch.jsonc'))) { + results.push(relative(rootDir, full).replaceAll('\\', '/')); + } else { + walk(full); + } + } + }; + walk(base); + return results.sort(); +} + +function listRelativeFiles(dir: string): string[] { + const out: string[] = []; + const walk = (current: string) => { + for (const entry of readdirSync(current, { withFileTypes: true })) { + const full = join(current, entry.name); + if (entry.isDirectory()) walk(full); + else if (entry.isFile()) out.push(relative(dir, full).replaceAll('\\', '/')); + } + }; + walk(dir); + return out.sort(); +} + +function computeRiskBadges(flags: { + readonly hasData: boolean; + readonly hasGui: boolean; + readonly hasScript: boolean; + readonly hasExe: boolean; +}): ModRiskBadge[] { + const badges: ModRiskBadge[] = []; + if (flags.hasData || (!flags.hasGui && !flags.hasScript && !flags.hasExe)) badges.push('data'); + if (flags.hasGui) badges.push('gui'); + if (flags.hasScript) badges.push('script'); + if (flags.hasExe) badges.push('exe'); + return badges; +} + +function isFile(path: string): boolean { + try { + return statSync(path).isFile(); + } catch { + return false; + } +} + +function isDirectory(path: string): boolean { + try { + return statSync(path).isDirectory(); + } catch { + return false; + } +} + +export function touchedClientPacks(mods: readonly DiscoveredMod[]): ModdableClientPack[] { + const set = new Set(); + for (const mod of mods) { + for (const op of mod.content.packOperations) set.add(op.pack); + if (mod.content.guiPatchDirs.length > 0) set.add('gui.vromfs.bin'); + if (mod.content.hasClientAddon) set.add('aces.vromfs.bin'); + } + return MODDABLE_CLIENT_PACKS.filter((pack) => set.has(pack)); +} diff --git a/packages/mods/src/index.ts b/packages/mods/src/index.ts new file mode 100644 index 0000000..efd11dc --- /dev/null +++ b/packages/mods/src/index.ts @@ -0,0 +1,79 @@ +/** + * Shared additive mod system core: manifest parsing, mod discovery, load-order & conflict + * resolution, type-preserving BLK incremental patching, localization CSV merging, multi-layer + * tuning `$listOps` merging, and experimental server mod contracts. + */ +export { + MOD_API_VERSION, + MOD_FORMAT_VERSION, + MODDABLE_CLIENT_PACKS, + resolveLocalizedText, + type ClientModsConfig, + type DiscoveredMod, + type LocalizedText, + type ModContentSummary, + type ModDiscoveryError, + type ModDiscoveryResult, + type ModIssue, + type ModIssueKind, + type ModIssueSeverity, + type ModManifest, + type ModPackOperation, + type ModPreset, + type ModRiskBadge, + type ModServerConfig, + type ModdableClientPack, + type PackFileAction, + type ResolvedModLoadOrder, +} from './types.ts'; +export { + MOD_MANIFEST_FILE, + ModManifestError, + expectSafeRelativePath, + parseModManifest, + readModManifest, +} from './manifest.ts'; +export { discoverMods, inspectModContent, touchedClientPacks } from './discovery.ts'; +export { + computeAutoSortOrder, + emptyClientModsConfig, + matchesVersionPattern, + normalizeClientModsConfig, + resolveModLoadOrder, +} from './resolve.ts'; +export { + BlkPatchError, + applyBlkPatch, + parseBlkPatchDocument, + type BlkBlockBlueprint, + type BlkPatchDocument, + type BlkPatchOp, + type BlkPatchValueInput, + type BlkPathStep, +} from './blk-patch.ts'; +export { mergeLocalizationCsv } from './csv-patch.ts'; +export { mergeTuningLayer, type TuningListOp } from './tuning-merge.ts'; +export type { + BattleLiveFactContext, + BattleMatchmakeContext, + BattleSettlementContext, + ModCharHandler, + ModCharRequest, + ModCharResponse, + ModCharWrapper, + ModHttpHandler, + ModHttpRequest, + ModHttpResponse, + ModLogger, + ModMatchingHandler, + ModMatchingRequest, + ModMatchingWrapper, + ModPlayerStorage, + ModStorageApi, + ServerModCataloguesView, + ServerModDatasetsView, + ServerModHooksApi, + ServerModRoutesApi, + WtoServerMod, + WtoServerModContext, +} from './server-api.ts'; diff --git a/packages/mods/src/manifest.ts b/packages/mods/src/manifest.ts new file mode 100644 index 0000000..d521e07 --- /dev/null +++ b/packages/mods/src/manifest.ts @@ -0,0 +1,159 @@ +/** + * Parse and validate `mod.jsonc` manifests. + */ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { parseJsonc } from '@wto/jsonc'; +import { MOD_FORMAT_VERSION, type LocalizedText, type ModManifest, type ModServerConfig } from './types.ts'; + +export const MOD_MANIFEST_FILE = 'mod.jsonc'; + +const MOD_ID_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/; +const ALLOWED_ROOT_KEYS = new Set([ + 'format', + 'id', + 'name', + 'version', + 'author', + 'description', + 'api_version', + 'game_versions', + 'requires', + 'conflicts', + 'load_after', + 'load_before', + 'server', +]); +const ALLOWED_SERVER_KEYS = new Set(['entry', 'tuning']); + +export class ModManifestError extends Error { + override name = 'ModManifestError'; +} + +export function readModManifest(modDir: string): ModManifest { + const filePath = join(modDir, MOD_MANIFEST_FILE); + let raw: unknown; + try { + raw = parseJsonc(readFileSync(filePath, 'utf8')); + } catch (error) { + throw new ModManifestError(`cannot parse ${MOD_MANIFEST_FILE}: ${error instanceof Error ? error.message : String(error)}`); + } + return parseModManifest(raw, filePath); +} + +export function parseModManifest(raw: unknown, where = MOD_MANIFEST_FILE): ModManifest { + const obj = expectObject(raw, where); + rejectUnknownKeys(obj, ALLOWED_ROOT_KEYS, where); + + if (obj.format !== MOD_FORMAT_VERSION) { + throw new ModManifestError(`${where}: "format" must be ${MOD_FORMAT_VERSION}`); + } + const id = expectString(obj.id, `${where} "id"`); + if (!MOD_ID_PATTERN.test(id)) { + throw new ModManifestError(`${where}: "id" must match ${MOD_ID_PATTERN.source} (got "${id}")`); + } + const name = expectLocalizedText(obj.name, `${where} "name"`); + const version = expectString(obj.version, `${where} "version"`); + const author = expectString(obj.author, `${where} "author"`); + const description = obj.description === undefined ? undefined : expectLocalizedText(obj.description, `${where} "description"`); + const apiVersion = expectString(obj.api_version, `${where} "api_version"`); + const gameVersions = optionalStringList(obj.game_versions, `${where} "game_versions"`); + const requires = optionalIdList(obj.requires, `${where} "requires"`, id); + const conflicts = optionalIdList(obj.conflicts, `${where} "conflicts"`, id); + const loadAfter = optionalIdList(obj.load_after, `${where} "load_after"`, id); + const loadBefore = optionalIdList(obj.load_before, `${where} "load_before"`, id); + const server = obj.server === undefined ? undefined : parseServerConfig(obj.server, `${where} "server"`); + + return { + format: MOD_FORMAT_VERSION, + id, + name, + version, + author, + ...(description !== undefined ? { description } : {}), + apiVersion, + gameVersions, + requires, + conflicts, + loadAfter, + loadBefore, + ...(server !== undefined ? { server } : {}), + }; +} + +function parseServerConfig(raw: unknown, where: string): ModServerConfig { + const obj = expectObject(raw, where); + rejectUnknownKeys(obj, ALLOWED_SERVER_KEYS, where); + const entry = obj.entry === undefined ? undefined : expectSafeRelativePath(obj.entry, `${where} "entry"`); + const tuning = obj.tuning === undefined ? undefined : expectSafeRelativePath(obj.tuning, `${where} "tuning"`); + return { + ...(entry !== undefined ? { entry } : {}), + ...(tuning !== undefined ? { tuning } : {}), + }; +} + +export function expectSafeRelativePath(raw: unknown, where: string): string { + const text = expectString(raw, where).replaceAll('\\', '/'); + if (text.startsWith('/') || /^[A-Za-z]:/.test(text)) { + throw new ModManifestError(`${where}: path must be relative to the mod folder (got "${text}")`); + } + const segments = text.split('/').filter((segment) => segment.length > 0); + if (segments.length === 0 || segments.some((segment) => segment === '.' || segment === '..')) { + throw new ModManifestError(`${where}: path must not contain "." or ".." segments (got "${text}")`); + } + return segments.join('/'); +} + +function expectObject(value: unknown, where: string): Record { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + throw new ModManifestError(`${where}: expected an object`); + } + return value as Record; +} + +function rejectUnknownKeys(obj: Record, allowed: ReadonlySet, where: string): void { + const unknown = Object.keys(obj).filter((key) => !allowed.has(key)); + if (unknown.length > 0) { + throw new ModManifestError(`${where}: unknown field(s): ${unknown.join(', ')}`); + } +} + +function expectString(value: unknown, where: string): string { + if (typeof value !== 'string' || value.trim().length === 0) { + throw new ModManifestError(`${where}: must be a non-empty string`); + } + return value.trim(); +} + +function expectLocalizedText(value: unknown, where: string): LocalizedText { + if (typeof value === 'string') { + if (value.trim().length === 0) throw new ModManifestError(`${where}: must not be empty`); + return value.trim(); + } + const obj = expectObject(value, where); + const entries = Object.entries(obj); + if (entries.length === 0) throw new ModManifestError(`${where}: localized map must not be empty`); + const out: Record = {}; + for (const [lang, text] of entries) { + out[lang] = expectString(text, `${where}.${lang}`); + } + return out; +} + +function optionalStringList(value: unknown, where: string): readonly string[] { + if (value === undefined) return []; + if (!Array.isArray(value)) throw new ModManifestError(`${where}: must be an array of strings`); + return value.map((item, index) => expectString(item, `${where}[${index}]`)); +} + +function optionalIdList(value: unknown, where: string, selfId: string): readonly string[] { + const ids = optionalStringList(value, where); + const seen = new Set(); + for (const id of ids) { + if (!MOD_ID_PATTERN.test(id)) throw new ModManifestError(`${where}: invalid mod id "${id}"`); + if (id === selfId) throw new ModManifestError(`${where}: mod cannot reference itself ("${id}")`); + if (seen.has(id)) throw new ModManifestError(`${where}: duplicate mod id "${id}"`); + seen.add(id); + } + return ids; +} diff --git a/packages/mods/src/resolve.ts b/packages/mods/src/resolve.ts new file mode 100644 index 0000000..8900e4e --- /dev/null +++ b/packages/mods/src/resolve.ts @@ -0,0 +1,333 @@ +/** + * Resolve effective mod load order, check dependencies/conflicts/version compatibility, + * detect overlapping pack or companion file targets, and offer topological auto-sorting. + */ +import { + MOD_API_VERSION, + type ClientModsConfig, + type DiscoveredMod, + type ModIssue, + type ResolvedModLoadOrder, +} from './types.ts'; + +export function emptyClientModsConfig(): ClientModsConfig { + return { + format: 1, + order: [], + enabled: {}, + activePresetId: null, + presets: [], + }; +} + +/** + * Reconcile a saved client config with the currently discovered mods: + * keep saved order for known mods, append newly discovered mods alphabetically (disabled by default), + * and drop removed mod ids from the active ordering without destroying saved presets. + */ +export function normalizeClientModsConfig( + config: ClientModsConfig, + discovered: readonly DiscoveredMod[], +): ClientModsConfig { + const knownIds = new Set(discovered.map((mod) => mod.manifest.id)); + const seen = new Set(); + const order: string[] = []; + for (const id of config.order) { + if (knownIds.has(id) && !seen.has(id)) { + seen.add(id); + order.push(id); + } + } + for (const mod of discovered) { + if (!seen.has(mod.manifest.id)) { + seen.add(mod.manifest.id); + order.push(mod.manifest.id); + } + } + const enabled: Record = {}; + for (const id of order) { + enabled[id] = config.enabled[id] === true; + } + return { + format: 1, + order, + enabled, + activePresetId: config.activePresetId, + presets: config.presets, + }; +} + +export function resolveModLoadOrder( + discovered: readonly DiscoveredMod[], + config: Pick, + gameVersion?: string | null, +): ResolvedModLoadOrder { + const byId = new Map(discovered.map((mod) => [mod.manifest.id, mod])); + const orderedIds: string[] = []; + const seen = new Set(); + for (const id of config.order) { + if (byId.has(id) && !seen.has(id)) { + seen.add(id); + orderedIds.push(id); + } + } + for (const mod of discovered) { + if (!seen.has(mod.manifest.id)) { + seen.add(mod.manifest.id); + orderedIds.push(mod.manifest.id); + } + } + + const enabledMods = orderedIds + .filter((id) => config.enabled[id] === true) + .map((id) => byId.get(id)!); + const enabledIndex = new Map(enabledMods.map((mod, index) => [mod.manifest.id, index])); + const issues: ModIssue[] = []; + + for (const mod of enabledMods) { + const id = mod.manifest.id; + const pos = enabledIndex.get(id)!; + + if (mod.manifest.apiVersion !== MOD_API_VERSION) { + issues.push({ + severity: 'warning', + kind: 'api-version-mismatch', + modId: id, + detail: `mod targets api_version "${mod.manifest.apiVersion}", current experimental API is "${MOD_API_VERSION}"`, + }); + } + + if (gameVersion && mod.manifest.gameVersions.length > 0 && !matchesAnyVersionPattern(gameVersion, mod.manifest.gameVersions)) { + issues.push({ + severity: 'warning', + kind: 'game-version-mismatch', + modId: id, + detail: `mod lists game_versions [${mod.manifest.gameVersions.join(', ')}], client is ${gameVersion}`, + }); + } + + for (const reqId of mod.manifest.requires) { + if (!byId.has(reqId)) { + issues.push({ + severity: 'error', + kind: 'missing-dependency', + modId: id, + otherModId: reqId, + detail: `requires missing mod "${reqId}"`, + }); + } else if (!enabledIndex.has(reqId)) { + issues.push({ + severity: 'error', + kind: 'dependency-disabled', + modId: id, + otherModId: reqId, + detail: `requires disabled mod "${reqId}"`, + }); + } else if (enabledIndex.get(reqId)! > pos) { + issues.push({ + severity: 'warning', + kind: 'dependency-order', + modId: id, + otherModId: reqId, + detail: `loaded before required dependency "${reqId}"`, + }); + } + } + + for (const conflictId of mod.manifest.conflicts) { + if (enabledIndex.has(conflictId) && id < conflictId) { + issues.push({ + severity: 'error', + kind: 'declared-conflict', + modId: id, + otherModId: conflictId, + detail: `declares incompatibility with "${conflictId}"`, + }); + } + } + + for (const afterId of mod.manifest.loadAfter) { + const otherPos = enabledIndex.get(afterId); + if (otherPos !== undefined && otherPos > pos) { + issues.push({ + severity: 'warning', + kind: 'load-order-hint', + modId: id, + otherModId: afterId, + detail: `recommends loading after "${afterId}"`, + }); + } + } + + for (const beforeId of mod.manifest.loadBefore) { + const otherPos = enabledIndex.get(beforeId); + if (otherPos !== undefined && otherPos < pos) { + issues.push({ + severity: 'warning', + kind: 'load-order-hint', + modId: id, + otherModId: beforeId, + detail: `recommends loading before "${beforeId}"`, + }); + } + } + } + + detectTargetOverlaps(enabledMods, issues); + + return { + enabledMods, + issues, + hasBlockingErrors: issues.some((issue) => issue.severity === 'error'), + }; +} + +/** + * Topologically sort mods using `requires`, `load_after`, and `load_before` constraints. + * Falls back gracefully to existing relative order when cycles exist. + */ +export function computeAutoSortOrder( + discovered: readonly DiscoveredMod[], + currentOrder: readonly string[], +): string[] { + const rank = new Map(); + currentOrder.forEach((id, index) => rank.set(id, index)); + const ids = discovered.map((mod) => mod.manifest.id); + const idSet = new Set(ids); + const edges = new Map>(ids.map((id) => [id, new Set()])); + const inDegree = new Map(ids.map((id) => [id, 0])); + + const addEdge = (before: string, after: string) => { + if (!idSet.has(before) || !idSet.has(after) || before === after) return; + const outgoing = edges.get(before)!; + if (!outgoing.has(after)) { + outgoing.add(after); + inDegree.set(after, (inDegree.get(after) ?? 0) + 1); + } + }; + + for (const mod of discovered) { + const id = mod.manifest.id; + for (const req of mod.manifest.requires) addEdge(req, id); + for (const after of mod.manifest.loadAfter) addEdge(after, id); + for (const before of mod.manifest.loadBefore) addEdge(id, before); + } + + const comparePriority = (a: string, b: string) => { + const ra = rank.get(a) ?? Number.MAX_SAFE_INTEGER; + const rb = rank.get(b) ?? Number.MAX_SAFE_INTEGER; + return ra !== rb ? ra - rb : a.localeCompare(b); + }; + + const ready = ids.filter((id) => (inDegree.get(id) ?? 0) === 0).sort(comparePriority); + const result: string[] = []; + + while (ready.length > 0) { + const next = ready.shift()!; + result.push(next); + for (const target of edges.get(next)!) { + const deg = (inDegree.get(target) ?? 1) - 1; + inDegree.set(target, deg); + if (deg === 0) { + ready.push(target); + ready.sort(comparePriority); + } + } + } + + if (result.length < ids.length) { + const placed = new Set(result); + const remaining = ids.filter((id) => !placed.has(id)).sort(comparePriority); + result.push(...remaining); + } + return result; +} + +function detectTargetOverlaps(enabledMods: readonly DiscoveredMod[], issues: ModIssue[]): void { + const packFiles = new Map(); + const packPatches = new Map(); + const companionFiles = new Map(); + const tuningFiles = new Map(); + + for (const mod of enabledMods) { + const id = mod.manifest.id; + + for (const op of mod.content.packOperations) { + const key = `${op.pack}:${op.targetPath.toLowerCase()}`; + if (op.action === 'file') { + const previous = packFiles.get(key) ?? packPatches.get(key); + if (previous && previous !== id) { + issues.push({ + severity: 'warning', + kind: 'pack-file-override', + modId: id, + otherModId: previous, + detail: `replaces "${op.pack}/${op.targetPath}" already modified by "${previous}"`, + }); + } + packFiles.set(key, id); + } else { + const previousFile = packFiles.get(key); + const previousPatch = packPatches.get(key); + if (previousFile && previousFile !== id) { + issues.push({ + severity: 'info', + kind: 'pack-blk-shared-target', + modId: id, + otherModId: previousFile, + detail: `patches "${op.pack}/${op.targetPath}" after "${previousFile}"`, + }); + } else if (previousPatch && previousPatch !== id) { + issues.push({ + severity: 'info', + kind: 'pack-blk-shared-target', + modId: id, + otherModId: previousPatch, + detail: `merges into "${op.pack}/${op.targetPath}" after "${previousPatch}"`, + }); + } + packPatches.set(key, id); + } + } + + for (const file of mod.content.clientFiles) { + const key = file.toLowerCase(); + const previous = companionFiles.get(key); + if (previous && previous !== id) { + issues.push({ + severity: 'warning', + kind: 'client-file-conflict', + modId: id, + otherModId: previous, + detail: `companion file "${file}" overrides "${previous}"`, + }); + } + companionFiles.set(key, id); + } + + for (const tuning of mod.content.serverTuningFiles) { + const key = tuning.toLowerCase(); + const previous = tuningFiles.get(key); + if (previous && previous !== id) { + issues.push({ + severity: 'info', + kind: 'tuning-file-shared', + modId: id, + otherModId: previous, + detail: `merges server tuning "${tuning}.jsonc" after "${previous}"`, + }); + } + tuningFiles.set(key, id); + } + } +} + +export function matchesVersionPattern(version: string, pattern: string): boolean { + if (pattern === '*') return true; + const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replaceAll('*', '.*'); + return new RegExp(`^${escaped}$`).test(version); +} + +function matchesAnyVersionPattern(version: string, patterns: readonly string[]): boolean { + return patterns.some((pattern) => matchesVersionPattern(version, pattern)); +} diff --git a/packages/mods/src/server-api.ts b/packages/mods/src/server-api.ts new file mode 100644 index 0000000..1ac4dca --- /dev/null +++ b/packages/mods/src/server-api.ts @@ -0,0 +1,184 @@ +/** + * Public TypeScript contract for WTOffline server-side JS/TS mods. + * + * EXPERIMENTAL / UNSTABLE: + * WTOffline is in early development. Internal server types, dataset shapes, hook signatures, + * and route contracts may change without backwards compatibility across releases. Mod authors + * using server scripts should expect breaking changes and maintain compatibility with updates. + */ +import type { BlkBlock } from '@wto/blk'; +import type { ModManifest } from './types.ts'; + +export interface ModLogger { + info(message: string): void; + warn(message: string): void; + error(message: string): void; +} + +/** Per-account JSON storage isolated under `/saves//mods/.json`. */ +export interface ModPlayerStorage { + read(): T | undefined; + write(value: unknown): void; + remove(): void; +} + +export interface ModStorageApi { + /** Storage scoped to one local player account (never mutates stock `profile.blk`). */ + forPlayer(userId: string): ModPlayerStorage; + /** Shared mod storage under `/mods-data/.json`. */ + shared(): ModPlayerStorage; +} + +/** Mutable snapshot of extracted static datasets exposed before domain catalogues are built. */ +export interface ServerModDatasetsView { + readonly vehicles: unknown[]; + readonly battleEconomy: Record; + readonly battleSpawnRules: unknown; + readonly multiplayerMissions: unknown[]; + readonly uiLabels: Record; + readonly unitNames: Record; + /** Escape hatch: read or replace any dataset object by its dataset id. */ + get(datasetId: string): T | undefined; + set(datasetId: string, value: unknown): void; +} + +/** Exposed domain catalogues and services after server initialization. */ +export interface ServerModCataloguesView { + readonly tuning: Readonly>; + readonly gameModes: unknown; + readonly profiles: unknown; + readonly accounts: unknown; + readonly research: unknown; + readonly equipment: unknown; + readonly repair: unknown; + readonly store: unknown; + readonly inventory: unknown; + readonly trophies: unknown; + readonly items: unknown; + readonly crew: unknown; + readonly decor: unknown; + readonly unlocks: unknown; + readonly clans: unknown; + readonly battleMatchmaker: unknown; + readonly battleEconomy: unknown; + readonly battleStreaks: unknown; + readonly notifyInventoryChanged: () => void; + readonly notifyUser: (userId: string, eventName: string, payload: Record) => void; +} + +export interface BattleMatchmakeContext { + readonly userId: string; + readonly eventName: string; + /** Mutable room / matchmake request parameters or generated launch plan. */ + readonly request: Record; +} + +export interface BattleLiveFactContext { + readonly userId: string; + readonly roomId: string; + readonly fact: Record; +} + +export interface BattleSettlementContext { + readonly userId: string; + readonly roomId: string; + /** Mutable settlement payload before final rewards are committed to the profile. */ + readonly summary: Record; +} + +export interface ModCharRequest { + readonly action: string; + readonly userId: string; + readonly headers: Readonly>; + readonly body: Buffer; + readonly query: Readonly>; +} + +export interface ModCharResponse { + readonly status?: number; + readonly contentType?: string; + readonly headers?: Readonly>; + readonly body: Buffer | Uint8Array | string; +} + +export type ModCharHandler = (request: ModCharRequest) => ModCharResponse | Promise; +export type ModCharWrapper = ( + request: ModCharRequest, + next: (request: ModCharRequest) => Promise, +) => ModCharResponse | Promise; + +export interface ModMatchingRequest { + readonly method: string; + readonly params: Readonly>; + readonly userId: string | undefined; +} + +export type ModMatchingHandler = (request: ModMatchingRequest) => Record; +export type ModMatchingWrapper = ( + request: ModMatchingRequest, + next: (request: ModMatchingRequest) => Record, +) => Record; + +export interface ModHttpRequest { + readonly method: string; + readonly path: string; + readonly query: Readonly>; + readonly headers: Readonly>; + readonly body: Buffer; +} + +export interface ModHttpResponse { + readonly status?: number; + readonly contentType?: string; + readonly headers?: Readonly>; + readonly body: Buffer | Uint8Array | string; +} + +export type ModHttpHandler = (request: ModHttpRequest) => ModHttpResponse | Promise; + +export interface ServerModHooksApi { + onDatasetsLoaded(handler: (datasets: ServerModDatasetsView) => void | Promise): void; + onCataloguesReady(handler: (catalogues: ServerModCataloguesView) => void | Promise): void; + onServerListening(handler: (info: { readonly port: number }) => void | Promise): void; + onServerClosing(handler: () => void | Promise): void; + readonly profile: { + onRefresh(handler: (profile: BlkBlock, userId: string) => void): void; + }; + readonly battle: { + onBeforeMatchmake(handler: (ctx: BattleMatchmakeContext) => void): void; + onLiveFact(handler: (ctx: BattleLiveFactContext) => void): void; + onAfterSettle(handler: (ctx: BattleSettlementContext) => void): void; + }; +} + +export interface ServerModRoutesApi { + readonly char: { + register(action: string, handler: ModCharHandler): void; + wrap(action: string, wrapper: ModCharWrapper): void; + }; + readonly matching: { + register(method: string, handler: ModMatchingHandler): void; + wrap(method: string, wrapper: ModMatchingWrapper): void; + }; + readonly http: { + /** Register a route under `/mods//...` (automatically namespaced to this mod). */ + register(subPath: string, handler: ModHttpHandler): void; + }; +} + +export interface WtoServerModContext { + readonly apiVersion: string; + readonly manifest: ModManifest; + readonly modDir: string; + readonly gameFolder: string; + readonly dataFolder: string; + readonly port: number; + readonly logger: ModLogger; + readonly storage: ModStorageApi; + readonly hooks: ServerModHooksApi; + readonly routes: ServerModRoutesApi; +} + +export interface WtoServerMod { + setup(ctx: WtoServerModContext): void | Promise; +} diff --git a/packages/mods/src/tuning-merge.ts b/packages/mods/src/tuning-merge.ts new file mode 100644 index 0000000..efb005f --- /dev/null +++ b/packages/mods/src/tuning-merge.ts @@ -0,0 +1,77 @@ +/** + * Multi-layer tuning merge helper with additive list operations (`$listOps`). + * + * Objects merge key-by-key. Plain arrays replace the base value (preserving existing player + * override behaviour). An object containing only `{ "$listOps": [...] }` applies incremental + * append/prepend/upsertBy/removeBy operations to the base array so multiple mods can add + * store packs, redeem codes, trophies, or preset clans without clobbering one another. + */ + +export type TuningListOp = + | { readonly op: 'append'; readonly items: readonly unknown[] } + | { readonly op: 'prepend'; readonly items: readonly unknown[] } + | { readonly op: 'upsertBy'; readonly key: string; readonly item: Record } + | { readonly op: 'removeBy'; readonly key: string; readonly value: unknown }; + +export function mergeTuningLayer(base: unknown, override: unknown): unknown { + if (isListOpsEnvelope(override)) { + const list = Array.isArray(base) ? [...base] : []; + return applyListOps(list, override.$listOps); + } + if (!isPlainObject(base) || !isPlainObject(override)) return override; + const merged: Record = { ...base }; + for (const [key, value] of Object.entries(override)) { + merged[key] = key in base ? mergeTuningLayer(base[key], value) : value; + } + return merged; +} + +function applyListOps(base: unknown[], ops: readonly unknown[]): unknown[] { + const result = [...base]; + for (const rawOp of ops) { + if (!isPlainObject(rawOp) || typeof rawOp.op !== 'string') { + throw new Error('invalid $listOps entry: expected object with string "op"'); + } + switch (rawOp.op) { + case 'append': + if (!Array.isArray(rawOp.items)) throw new Error('$listOps append requires an "items" array'); + result.push(...rawOp.items); + break; + case 'prepend': + if (!Array.isArray(rawOp.items)) throw new Error('$listOps prepend requires an "items" array'); + result.unshift(...rawOp.items); + break; + case 'upsertBy': { + if (typeof rawOp.key !== 'string' || !isPlainObject(rawOp.item)) { + throw new Error('$listOps upsertBy requires string "key" and object "item"'); + } + const matchValue = rawOp.item[rawOp.key]; + const idx = result.findIndex((entry) => isPlainObject(entry) && entry[rawOp.key as string] === matchValue); + if (idx >= 0) result[idx] = mergeTuningLayer(result[idx], rawOp.item); + else result.push(rawOp.item); + break; + } + case 'removeBy': { + if (typeof rawOp.key !== 'string') throw new Error('$listOps removeBy requires string "key"'); + for (let i = result.length - 1; i >= 0; i -= 1) { + const entry = result[i]; + if (isPlainObject(entry) && entry[rawOp.key] === rawOp.value) result.splice(i, 1); + } + break; + } + default: + throw new Error(`unsupported $listOps operation "${rawOp.op}"`); + } + } + return result; +} + +function isListOpsEnvelope(value: unknown): value is { readonly $listOps: readonly unknown[] } { + if (!isPlainObject(value)) return false; + const keys = Object.keys(value); + return keys.length === 1 && keys[0] === '$listOps' && Array.isArray(value.$listOps); +} + +function isPlainObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} diff --git a/packages/mods/src/types.ts b/packages/mods/src/types.ts new file mode 100644 index 0000000..c07126a --- /dev/null +++ b/packages/mods/src/types.ts @@ -0,0 +1,154 @@ +/** + * Shared types for the additive mod system. + * + * EXPERIMENTAL: Mod manifest fields, conflict structures, and runtime contracts are under active + * early development and may change without backwards compatibility. + */ + +export const MOD_FORMAT_VERSION = 1; +export const MOD_API_VERSION = '0.1-experimental'; + +/** Supported client .vromfs.bin packs that mods may patch or add files to. */ +export const MODDABLE_CLIENT_PACKS = [ + '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', +] as const; + +export type ModdableClientPack = (typeof MODDABLE_CLIENT_PACKS)[number]; + +export type LocalizedText = string | Readonly>; + +export type ModRiskBadge = 'data' | 'gui' | 'script' | 'exe'; + +export interface ModServerConfig { + /** Relative path to the server script entry (.ts, .mjs, or .js), when present. */ + readonly entry?: string; + /** Relative path to the server tuning override directory (defaults to "server/tuning"). */ + readonly tuning?: string; +} + +export interface ModManifest { + readonly format: 1; + readonly id: string; + readonly name: LocalizedText; + readonly version: string; + readonly author: string; + readonly description?: LocalizedText; + readonly apiVersion: string; + readonly gameVersions: readonly string[]; + readonly requires: readonly string[]; + readonly conflicts: readonly string[]; + readonly loadAfter: readonly string[]; + readonly loadBefore: readonly string[]; + readonly server?: ModServerConfig; +} + +export type PackFileAction = 'blk-patch' | 'csv-patch' | 'file'; + +export interface ModPackOperation { + readonly pack: ModdableClientPack; + /** Target path inside the pack (without .patch.jsonc / .patch.csv suffix). */ + readonly targetPath: string; + readonly action: PackFileAction; + /** Path relative to the mod root folder. */ + readonly sourceRelativePath: string; +} + +export interface ModContentSummary { + readonly serverEntry?: string; + readonly serverTuningFiles: readonly string[]; + readonly packOperations: readonly ModPackOperation[]; + readonly guiPatchDirs: readonly string[]; + readonly exePatchDirs: readonly string[]; + readonly hasClientAddon: boolean; + /** True when client/addon includes a compiled res/grp_hdr.vromfs.bin index. */ + readonly addonHasGrpHdr: boolean; + readonly addonRelativeFiles: readonly string[]; + /** Relative paths under client/files (mapped into the game copy root). */ + readonly clientFiles: readonly string[]; + /** Optional relative path to client/config-blk.patch.jsonc. */ + readonly configBlkPatch?: string; + readonly badges: readonly ModRiskBadge[]; +} + +export interface DiscoveredMod { + readonly folderName: string; + readonly rootDir: string; + readonly manifest: ModManifest; + readonly content: ModContentSummary; +} + +export interface ModDiscoveryError { + readonly folderName: string; + readonly rootDir: string; + readonly reason: string; +} + +export interface ModDiscoveryResult { + readonly mods: readonly DiscoveredMod[]; + readonly errors: readonly ModDiscoveryError[]; +} + +export interface ModPreset { + readonly id: string; + readonly name: string; + readonly order: readonly string[]; + readonly enabled: Readonly>; + readonly updatedAt: string; +} + +export interface ClientModsConfig { + readonly format: 1; + readonly order: readonly string[]; + readonly enabled: Readonly>; + readonly activePresetId: string | null; + readonly presets: readonly ModPreset[]; +} + +export type ModIssueSeverity = 'error' | 'warning' | 'info'; + +export type ModIssueKind = + | 'missing-dependency' + | 'dependency-disabled' + | 'dependency-order' + | 'declared-conflict' + | 'load-order-hint' + | 'game-version-mismatch' + | 'api-version-mismatch' + | 'pack-file-override' + | 'pack-blk-shared-target' + | 'client-file-conflict' + | 'tuning-file-shared'; + +export interface ModIssue { + readonly severity: ModIssueSeverity; + readonly kind: ModIssueKind; + readonly modId: string; + readonly otherModId?: string; + readonly detail: string; +} + +export interface ResolvedModLoadOrder { + readonly enabledMods: readonly DiscoveredMod[]; + readonly issues: readonly ModIssue[]; + readonly hasBlockingErrors: boolean; +} + +/** Pick the best localized display string for a mod field. */ +export function resolveLocalizedText(value: LocalizedText, language: string): string { + if (typeof value === 'string') return value; + const exact = value[language]; + if (exact) return exact; + const prefix = language.split('-')[0]; + if (prefix) { + const partial = Object.entries(value).find(([key]) => key === prefix || key.startsWith(`${prefix}-`)); + if (partial?.[1]) return partial[1]; + } + return value.en ?? value['en-US'] ?? Object.values(value)[0] ?? ''; +} From fd9d25d3469cda10c0575e48bb423ddb51abdc7c Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:48:34 +0800 Subject: [PATCH 02/12] feat(patcher): support additive mod pack overlays, addon mounts, and protected exe patches --- packages/exepatch/src/index.ts | 2 +- packages/exepatch/src/plan.ts | 61 +++ packages/patcher/package.json | 1 + packages/patcher/src/build-game-copy.ts | 102 +++- packages/patcher/src/executable.ts | 99 +++- packages/patcher/src/index.ts | 31 +- packages/patcher/src/main-pack.ts | 3 + packages/patcher/src/mods/addon-register.ts | 57 ++ packages/patcher/src/mods/deploy-external.ts | 541 +++++++++++++++++++ packages/patcher/src/mods/gui-overlay.ts | 112 ++++ packages/patcher/src/mods/pack-overlay.ts | 103 ++++ 11 files changed, 1088 insertions(+), 24 deletions(-) create mode 100644 packages/patcher/src/mods/addon-register.ts create mode 100644 packages/patcher/src/mods/deploy-external.ts create mode 100644 packages/patcher/src/mods/gui-overlay.ts create mode 100644 packages/patcher/src/mods/pack-overlay.ts diff --git a/packages/exepatch/src/index.ts b/packages/exepatch/src/index.ts index 70bbd4e..506ffc4 100644 --- a/packages/exepatch/src/index.ts +++ b/packages/exepatch/src/index.ts @@ -13,6 +13,6 @@ export { DefinitionError, LocateError, PatchError, PeFormatError, VerifyError } export { asObject, readJsonObject, rejectUnknownKeys, requiredString, stringList, variantObjects } from './json-fields.ts'; export { NO_CONTEXT, type LocateContext } from './locate/index.ts'; export { PeImage, type FunctionRange, type Section } from './pe-image.ts'; -export { describePlan, planPatches, type PatchFailure, type PatchPlan, type PlannedWrite } from './plan.ts'; +export { describePlan, planAdditionalPatches, planPatches, type PatchFailure, type PatchPlan, type PlannedWrite } from './plan.ts'; export { findSite, readSiteSpec, type FoundSite, type SiteSpec } from './site.ts'; export { chooseVariant, type Chosen, type Variant } from './variants.ts'; diff --git a/packages/exepatch/src/plan.ts b/packages/exepatch/src/plan.ts index d7ac99a..c175650 100644 --- a/packages/exepatch/src/plan.ts +++ b/packages/exepatch/src/plan.ts @@ -58,6 +58,67 @@ export function planPatches(image: PeImage, definitions: readonly PatchDefinitio return { writes, failures }; } +/** + * Plan additive patches (such as declarative mod exe patches) on top of locked core writes. + * Any patch that fails to locate/verify, depends on a failed patch, overlaps a protected core + * write, or overlaps an earlier accepted additive write is recorded in `failures` rather than + * throwing, so core offline isolation patches are never overwritten or broken. + */ +export function planAdditionalPatches( + image: PeImage, + definitions: readonly PatchDefinition[], + protectedWrites: readonly PlannedWrite[], +): PatchPlan { + const planned = new Map(); + const failed = new Map(); + for (const definition of definitions) { + try { + const chosen = chooseVariant(definition.variants, (variant) => planVariant(image, variant)); + planned.set(definition.id, { patchId: definition.id, variant: chosen.variant.writtenFor, ...chosen.value }); + } catch (error) { + if (!(error instanceof PatchError)) throw error; + failed.set(definition.id, error.message); + } + } + propagateFailures(definitions, failed); + + const accepted: PlannedWrite[] = []; + for (const definition of definitions) { + if (failed.has(definition.id)) continue; + const candidate = planned.get(definition.id)!; + const coreConflict = findOverlappingWrite(candidate, protectedWrites); + if (coreConflict) { + failed.set(definition.id, `overlaps protected core patch "${coreConflict.patchId}" at ${hex(candidate.rva)}`); + continue; + } + const earlierConflict = findOverlappingWrite(candidate, accepted); + if (earlierConflict) { + failed.set(definition.id, `overlaps earlier patch "${earlierConflict.patchId}" at ${hex(candidate.rva)}`); + continue; + } + accepted.push(candidate); + } + // Re-propagate if an overlap rejection broke a downstream dependency. + const beforeSecondPass = failed.size; + propagateFailures(definitions, failed); + const writes = failed.size === beforeSecondPass + ? accepted + : accepted.filter((write) => !failed.has(write.patchId)); + const failures = definitions.filter((item) => failed.has(item.id)) + .map((item) => ({ patchId: item.id, features: item.features, reason: failed.get(item.id)! })); + return { writes, failures }; +} + +function findOverlappingWrite(candidate: PlannedWrite, existing: readonly PlannedWrite[]): PlannedWrite | undefined { + const cStart = candidate.fileOffset; + const cEnd = cStart + candidate.payload.length; + return existing.find((write) => { + const wStart = write.fileOffset; + const wEnd = wStart + write.payload.length; + return cStart < wEnd && wStart < cEnd; + }); +} + export function describePlan(plan: PatchPlan): string { const lines = [`${plan.writes.length} patch(es) ready, ${plan.failures.length} unavailable`]; for (const write of plan.writes) lines.push(` ready ${write.patchId} at ${hex(write.rva)} (variant ${write.variant})`); diff --git a/packages/patcher/package.json b/packages/patcher/package.json index 078bc2a..9ddca54 100644 --- a/packages/patcher/package.json +++ b/packages/patcher/package.json @@ -10,6 +10,7 @@ "@wto/blk": "*", "@wto/exepatch": "*", "@wto/jsonc": "*", + "@wto/mods": "*", "@wto/vromfs": "*", "fflate": "^0.8.2" } diff --git a/packages/patcher/src/build-game-copy.ts b/packages/patcher/src/build-game-copy.ts index a62de2a..66c8e88 100644 --- a/packages/patcher/src/build-game-copy.ts +++ b/packages/patcher/src/build-game-copy.ts @@ -1,21 +1,27 @@ /** - * Build the files of the game copy in memory: the three rebuilt data packs, - * the patched executable, the network hook library and its settings. Nothing is written here + * Build the files of the game copy in memory: the rebuilt data packs (with optional additive mod + * overlays), the patched executable (with protected core patches + optional declarative mod exe + * patches), the network hook library and its settings. Nothing is written here * (write-game-copy.ts does that), so a caller can show the report first and let the player decide. * * Everything the build needs from outside comes in as an input: the stock files, the patch set - * (patch-set.ts), the hook library, and the multi-vehicle pack ids the local server will sell from its - * data folder. + * (patch-set.ts), the hook library, the multi-vehicle pack ids the local server will sell, and + * optionally the ordered list of enabled mods with any additional stock packs they touch. */ import { readFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { PeImage, type PatchFailure } from '@wto/exepatch'; +import { touchedClientPacks, type DiscoveredMod, type ModdableClientPack } from '@wto/mods'; import { rebuildCharPack, type CharPackResult } from './char-pack.ts'; import { blockingFailures } from './essential-features.ts'; -import { patchExecutable } from './executable.ts'; +import { patchExecutableWithMods, type ModExePatchFailure } from './executable.ts'; import { GAME_FILES } from './game-copy.ts'; import { rebuildGuiPack } from './gui-pack.ts'; import { rebuildMainPack } from './main-pack.ts'; +import { collectModAddonMounts, type ModAddonMount } from './mods/addon-register.ts'; +import { CORE_BUILD_PACKS } from './mods/deploy-external.ts'; +import { applyModGuiPatches } from './mods/gui-overlay.ts'; +import { applyModPackOverlays, type PackOverlayReport } from './mods/pack-overlay.ts'; import type { AddressChange } from './network/address-rewrite.ts'; import { localEndpoint, type LocalEndpoint } from './network/local-endpoint.ts'; import { NETWORK_HOOK_LIBRARY, networkHookSettings } from './network/network-hook.ts'; @@ -46,6 +52,10 @@ export interface GameCopyInputs { readonly placeholderDecals: boolean; /** Whether wto_ws.dll writes win64/wto_ws.log; defaults to true. */ readonly hookLogging?: boolean; + /** Ordered list of enabled additive mods to overlay onto this build. */ + readonly mods?: readonly DiscoveredMod[]; + /** Stock bytes of optional packs (lang/mis/game/ui/*) touched by enabled mods. */ + readonly extraStockPacks?: Partial>; } /** One file of the game copy, by its path relative to the copy folder. */ @@ -54,6 +64,20 @@ export interface GameCopyFile { readonly content: Uint8Array; } +export interface ModBuildReport { + readonly enabledModIds: readonly string[]; + readonly packOverlays: readonly PackOverlayReport[]; + readonly addonMounts: readonly ModAddonMount[]; + readonly guiPatches: { + readonly applied: readonly { readonly modId: string; readonly patchId: string }[]; + readonly failures: readonly (PatchFailure & { readonly modId: string })[]; + }; + readonly exePatches: { + readonly applied: readonly { readonly modId: string; readonly patchId: string; readonly rva: number }[]; + readonly failures: readonly ModExePatchFailure[]; + }; +} + export interface GameCopyBuild { /** Every file to write, with unavailable patches left out. */ readonly files: readonly GameCopyFile[]; @@ -69,6 +93,8 @@ export interface GameCopyBuild { readonly engineAddresses: readonly AddressChange[]; /** Store bundle GUIDs registered in config/gui.blk. */ readonly bundleGuids: number; + /** Details of additive mod overlays applied during this build. */ + readonly mods: ModBuildReport; } export function readStockGameFiles(folder: string): StockGameFiles { @@ -83,43 +109,85 @@ export function readStockGameFiles(folder: string): StockGameFiles { export function buildGameCopy(inputs: GameCopyInputs): GameCopyBuild { const endpoint = localEndpoint(inputs.port); const folders = patchSetFolders(inputs.patches); - const executable = patchExecutable(inputs.stock.executable, folders.exe); + const enabledMods = inputs.mods ?? []; + const packOverlays: PackOverlayReport[] = []; + + const executable = patchExecutableWithMods(inputs.stock.executable, folders.exe, enabledMods); const stockImage = new PeImage(inputs.stock.executable); const native = resolveNativeModules(stockImage, loadNativeModules(folders.native)); - const guiPack = rebuildGuiPack(inputs.stock.guiPack, endpoint, folders.gui); - const appliedGuiPatches = guiPack.applied.map((item) => item.patch.id); + + const coreGuiPack = rebuildGuiPack(inputs.stock.guiPack, endpoint, folders.gui); + const appliedGuiPatches = coreGuiPack.applied.map((item) => item.patch.id); + const guiPackFileOverlay = applyModPackOverlays(coreGuiPack.pack, 'gui.vromfs.bin', enabledMods); + if (guiPackFileOverlay.report.operationsApplied > 0) packOverlays.push(guiPackFileOverlay.report); + const modGuiResult = applyModGuiPatches(guiPackFileOverlay.pack, endpoint, enabledMods); + const localRegistration = appliedGuiPatches.includes('registration/open-local-page') && appliedGuiPatches.includes('registration/keep-local-page-embedded'); - const { pack: charPack, ...charReport } = rebuildCharPack(inputs.stock.charPack, endpoint, { + const { pack: coreCharPack, ...charReport } = rebuildCharPack(inputs.stock.charPack, endpoint, { placeholderDecals: inputs.placeholderDecals, localRegistration, }); - const bundles = offlinePackBundleGuids(inputs.stock.charPack, inputs.multiVehiclePackIds); - const mainPack = rebuildMainPack(inputs.stock.mainPack, endpoint, bundles); + const charOverlay = applyModPackOverlays(coreCharPack, 'char.vromfs.bin', enabledMods); + if (charOverlay.report.operationsApplied > 0) packOverlays.push(charOverlay.report); + + // Derive store bundle GUIDs from the mod-overlaid charPack so newly added mod gift vehicles + // automatically receive deterministic offline store bundle GUIDs. + const bundles = offlinePackBundleGuids(charOverlay.pack, inputs.multiVehiclePackIds); + const addonMounts = collectModAddonMounts(enabledMods); + const coreMainPack = rebuildMainPack( + inputs.stock.mainPack, + endpoint, + bundles, + addonMounts.map((mount) => mount.mountFolder), + ); + const mainOverlay = applyModPackOverlays(coreMainPack.pack, 'aces.vromfs.bin', enabledMods); + if (mainOverlay.report.operationsApplied > 0) packOverlays.push(mainOverlay.report); const executableFolder = dirname(GAME_FILES.executable); const hookSettings = networkHookSettings(endpoint, stockImage, native.values, { loggingEnabled: inputs.hookLogging ?? true, }); const files: GameCopyFile[] = [ - { path: GAME_FILES.charPack, content: charPack }, - { path: GAME_FILES.mainPack, content: mainPack.pack }, - { path: GAME_FILES.guiPack, content: guiPack.pack }, + { path: GAME_FILES.charPack, content: charOverlay.pack }, + { path: GAME_FILES.mainPack, content: mainOverlay.pack }, + { path: GAME_FILES.guiPack, content: modGuiResult.pack }, { path: GAME_FILES.executable, content: executable.executable }, { path: join(executableFolder, NETWORK_HOOK_LIBRARY), content: inputs.networkHookLibrary }, { path: join(executableFolder, hookSettings.name), content: hookSettings.content }, ]; - const failures = [...executable.plan.failures, ...guiPack.failures, ...native.failures]; + // Rebuild any optional client packs (lang, mis, game, ui/atlases, ui/images) touched by enabled mods. + for (const pack of touchedClientPacks(enabledMods)) { + if (CORE_BUILD_PACKS.has(pack)) continue; + const stockBytes = inputs.extraStockPacks?.[pack]; + if (!stockBytes) { + throw new Error(`mod overlay requires stock pack "${pack}" in extraStockPacks`); + } + const overlay = applyModPackOverlays(stockBytes, pack, enabledMods); + if (overlay.report.operationsApplied > 0) { + packOverlays.push(overlay.report); + files.push({ path: join(...pack.split('/')), content: overlay.pack }); + } + } + + const failures = [...executable.plan.failures, ...coreGuiPack.failures, ...native.failures]; return { files, endpoint, exePatches: { applied: executable.plan.writes.map((write) => ({ patchId: write.patchId, rva: write.rva })), failures: executable.plan.failures }, - guiPatches: { applied: appliedGuiPatches, failures: guiPack.failures }, + guiPatches: { applied: appliedGuiPatches, failures: coreGuiPack.failures }, nativeModules: { available: [...native.available.keys()], failures: native.failures }, blocking: blockingFailures(failures), charPack: charReport, - engineAddresses: mainPack.addresses, + engineAddresses: coreMainPack.addresses, bundleGuids: bundles.length, + mods: { + enabledModIds: enabledMods.map((mod) => mod.manifest.id), + packOverlays, + addonMounts, + guiPatches: { applied: modGuiResult.applied, failures: modGuiResult.failures }, + exePatches: { applied: executable.modApplied, failures: executable.modFailures }, + }, }; } diff --git a/packages/patcher/src/executable.ts b/packages/patcher/src/executable.ts index 1ae1fa8..7b63787 100644 --- a/packages/patcher/src/executable.ts +++ b/packages/patcher/src/executable.ts @@ -1,10 +1,21 @@ /** - * Patch a copy of aces.exe with every definition under the exe patch folder. A patch that cannot - * be applied (site missing or ambiguous, original bytes differ, or a patch it requires failed) is - * left out and listed with the features it covers; whether a copy with - * patches missing may be installed is the caller's decision (essential-features.ts). + * Patch a copy of aces.exe with every definition under the core exe patch folder, and optionally + * apply declarative mod exe patches on top while keeping every core patch byte range locked. */ -import { applyWrites, describePlan, loadPatches, PeImage, planPatches, type PatchPlan } from '@wto/exepatch'; +import { join } from 'node:path'; +import { + applyWrites, + describePlan, + loadPatches, + PeImage, + planAdditionalPatches, + planPatches, + type PatchDefinition, + type PatchFailure, + type PatchPlan, + type PlannedWrite, +} from '@wto/exepatch'; +import type { DiscoveredMod } from '@wto/mods'; export interface ExecutableResult { /** The executable with every available patch written. */ @@ -13,7 +24,85 @@ export interface ExecutableResult { readonly description: string; } +export interface ModExePatchFailure extends PatchFailure { + readonly modId: string; +} + +export interface ModExecutableResult extends ExecutableResult { + readonly modApplied: readonly { readonly modId: string; readonly patchId: string; readonly rva: number }[]; + readonly modFailures: readonly ModExePatchFailure[]; +} + export function patchExecutable(stockExecutable: Uint8Array, patchesRoot: string): ExecutableResult { const plan = planPatches(new PeImage(stockExecutable), loadPatches(patchesRoot)); return { executable: applyWrites(stockExecutable, plan.writes), plan, description: describePlan(plan) }; } + +export function patchExecutableWithMods( + stockExecutable: Uint8Array, + corePatchesRoot: string, + mods: readonly DiscoveredMod[], +): ModExecutableResult { + const image = new PeImage(stockExecutable); + const corePlan = planPatches(image, loadPatches(corePatchesRoot)); + const modsWithExe = mods.filter((mod) => mod.content.exePatchDirs.length > 0); + if (modsWithExe.length === 0) { + return { + executable: applyWrites(stockExecutable, corePlan.writes), + plan: corePlan, + description: describePlan(corePlan), + modApplied: [], + modFailures: [], + }; + } + + const allModDefs: PatchDefinition[] = []; + const ownerById = new Map(); + const loadFailures: ModExePatchFailure[] = []; + + for (const mod of modsWithExe) { + const exeRoot = join(mod.rootDir, 'client', 'exe-patches'); + try { + const defs = loadPatches(exeRoot); + for (const def of defs) { + const namespacedId = `${mod.manifest.id}/${def.id}`; + ownerById.set(namespacedId, mod.manifest.id); + allModDefs.push({ + ...def, + id: namespacedId, + requires: def.requires.map((req) => (req.includes('/') ? req : `${mod.manifest.id}/${req}`)), + }); + } + } catch (error) { + loadFailures.push({ + modId: mod.manifest.id, + patchId: `${mod.manifest.id}:exe-patches`, + features: [], + reason: error instanceof Error ? error.message : String(error), + }); + } + } + + const modPlan = planAdditionalPatches(image, allModDefs, corePlan.writes); + const combinedWrites: readonly PlannedWrite[] = [...corePlan.writes, ...modPlan.writes]; + const modApplied = modPlan.writes.map((write) => ({ + modId: ownerById.get(write.patchId) ?? 'unknown', + patchId: write.patchId, + rva: write.rva, + })); + const modFailures: ModExePatchFailure[] = [ + ...loadFailures, + ...modPlan.failures.map((failure) => ({ + ...failure, + modId: ownerById.get(failure.patchId) ?? 'unknown', + })), + ]; + + return { + executable: applyWrites(stockExecutable, combinedWrites), + plan: corePlan, + description: describePlan(corePlan), + modApplied, + modFailures, + }; +} diff --git a/packages/patcher/src/index.ts b/packages/patcher/src/index.ts index 5559b99..6e264d2 100644 --- a/packages/patcher/src/index.ts +++ b/packages/patcher/src/index.ts @@ -10,12 +10,41 @@ export { type GameCopyBuild, type GameCopyFile, type GameCopyInputs, + type ModBuildReport, type StockGameFiles, } from './build-game-copy.ts'; export { NETWORK_CONFIG_PATH, rebuildCharPack, type CharPackResult } from './char-pack.ts'; export { copyPlayerDecalCache, playerDecalCacheProblem } from './decals/player-decal-cache.ts'; export { blockingFailures, ESSENTIAL_FEATURES } from './essential-features.ts'; -export { patchExecutable, type ExecutableResult } from './executable.ts'; +export { + patchExecutable, + patchExecutableWithMods, + type ExecutableResult, + type ModExecutableResult, + type ModExePatchFailure, +} from './executable.ts'; +export { + addonMountFolderForMod, + collectModAddonMounts, + registerModAddonsInSettings, + type ModAddonMount, +} from './mods/addon-register.ts'; +export { + computeModsBuildFingerprint, + CORE_BUILD_PACKS, + MODS_STATE_FILE, + prepareOptionalStockPacks, + readModsDeployState, + syncExternalModFiles, + writeModsDeployState, + type DeployedModEntry, + type DeployEntryKind, + type ModDeployWarning, + type ModExternalDeployResult, + type ModsDeployState, +} from './mods/deploy-external.ts'; +export { applyModGuiPatches, type ModGuiPatchResult } from './mods/gui-overlay.ts'; +export { applyModPackOverlays, type PackOverlayReport } from './mods/pack-overlay.ts'; export { assertWritableCopy, GAME_FILES, isInSteamLibrary, type WritableCopyOptions } from './game-copy.ts'; export { executableVersion } from './game-version.ts'; export { diff --git a/packages/patcher/src/main-pack.ts b/packages/patcher/src/main-pack.ts index f51ad5c..26a6123 100644 --- a/packages/patcher/src/main-pack.ts +++ b/packages/patcher/src/main-pack.ts @@ -13,6 +13,7 @@ * server addresses. */ import { ensureBlock, findBlock, setParam, type BlkBlock } from '@wto/blk'; +import { registerModAddonsInSettings } from './mods/addon-register.ts'; import { redirectAddresses, type AddressChange } from './network/address-rewrite.ts'; import type { LocalEndpoint } from './network/local-endpoint.ts'; import { editPackBlks } from './pack-edit.ts'; @@ -42,6 +43,7 @@ export function rebuildMainPack( stockPack: Uint8Array, endpoint: LocalEndpoint, extraBundles: ReadonlyArray = [], + extraAddonFolders: readonly string[] = [], ): MainPackResult { let addresses: AddressChange[] = []; const pack = editPackBlks(stockPack, [ @@ -51,6 +53,7 @@ export function rebuildMainPack( const network = findBlock(root, NETWORK_BLOCK); if (!network) throw new Error(`${ENGINE_SETTINGS_PATH} has no "${NETWORK_BLOCK}" block; this game build differs from the verified ones`); addresses = redirectAddresses(network, endpoint, [NETWORK_BLOCK]); + registerModAddonsInSettings(root, extraAddonFolders); }, }, { diff --git a/packages/patcher/src/mods/addon-register.ts b/packages/patcher/src/mods/addon-register.ts new file mode 100644 index 0000000..eae97d4 --- /dev/null +++ b/packages/patcher/src/mods/addon-register.ts @@ -0,0 +1,57 @@ +/** + * Compute engine addon mount paths for mods shipping 3D models/textures (`client/addon/`) + * and register them into `aces.vromfs.bin` `config/settings.blk`. + * + * Engine behaviour verified in 2.61.0.x aces.exe (0xc90932..0xc92754): + * - Paths containing `/pkg_user/` skip the mandatory `res/grp_hdr.vromfs.bin` check and + * directly scan `%s/res/` for all `.grp` and `.dxp.bin` archives. + * - Addons that ship a compiled `res/grp_hdr.vromfs.bin` use a dedicated `content/pkg_wto_` + * folder so the native grp_hdr loader handles them. + */ +import { appendParam, ensureBlock, type BlkBlock } from '@wto/blk'; +import type { DiscoveredMod } from '@wto/mods'; + +export interface ModAddonMount { + readonly modId: string; + /** Relative folder inside the game copy, e.g. `content/pkg_user/example_mod`. */ + readonly mountFolder: string; + /** Absolute source folder `/client/addon`. */ + readonly sourceDir: string; +} + +export function addonMountFolderForMod(mod: DiscoveredMod): string { + const safeName = mod.manifest.id.replace(/[^a-z0-9_-]/g, '_'); + return mod.content.addonHasGrpHdr + ? `content/pkg_wto_${safeName}` + : `content/pkg_user/${safeName}`; +} + +export function collectModAddonMounts(mods: readonly DiscoveredMod[]): ModAddonMount[] { + const mounts: ModAddonMount[] = []; + for (const mod of mods) { + if (!mod.content.hasClientAddon) continue; + mounts.push({ + modId: mod.manifest.id, + mountFolder: addonMountFolderForMod(mod), + sourceDir: `${mod.rootDir}/client/addon`, + }); + } + return mounts; +} + +export function registerModAddonsInSettings(settingsRoot: BlkBlock, mountFolders: readonly string[]): void { + if (mountFolders.length === 0) return; + for (const blockName of ['addons', 'addons_no_check', 'addonsWithBasePath'] as const) { + const block = ensureBlock(settingsRoot, blockName); + const existing = new Set( + block.params + .filter((param) => param.name === 'folder' && param.value.type === 'string') + .map((param) => (param.value as { readonly type: 'string'; readonly value: string }).value.toLowerCase()), + ); + for (const folder of mountFolders) { + if (existing.has(folder.toLowerCase())) continue; + appendParam(block, 'folder', { type: 'string', value: folder }); + existing.add(folder.toLowerCase()); + } + } +} diff --git a/packages/patcher/src/mods/deploy-external.ts b/packages/patcher/src/mods/deploy-external.ts new file mode 100644 index 0000000..890d54d --- /dev/null +++ b/packages/patcher/src/mods/deploy-external.ts @@ -0,0 +1,541 @@ +/** + * Deploy and cleanly roll back external mod assets (3D model addons, optional companion files, + * on-demand stock pack backups, and `config.blk` patches) in the game copy. + * + * Cross-drive zero-copy strategy (Option A): + * 1. Dedicated folders (`content/pkg_user/` and exclusive subdirectories under `client/files`, + * such as `UserSkins/`) use NTFS Directory Junctions — works across drives, needs no admin + * privileges, uses 0 extra bytes, and mounts/unmounts in ~1 ms. + * 2. Shared flat files (such as `sound/mod/*.bank`) try file symlink (works across drives when + * Windows Developer Mode is on) -> NTFS hardlink (same drive) -> size/mtime cached copy. + * 3. Player-owned native files (e.g. manually installed UserSkins/UserSights) are never overwritten; + * conflicts are reported and skipped. + * 4. Hard-linked stock files are unlinked before replacing so online client files are never mutated. + */ +import { createHash } from 'node:crypto'; +import { + copyFileSync, + existsSync, + linkSync, + lstatSync, + mkdirSync, + readdirSync, + readFileSync, + rmdirSync, + rmSync, + statSync, + symlinkSync, + unlinkSync, + writeFileSync, +} from 'node:fs'; +import { dirname, join, relative } from 'node:path'; +import { formatBlkText, parseBlkText } from '@wto/blk'; +import { + applyBlkPatch, + parseBlkPatchDocument, + type DiscoveredMod, + type ModdableClientPack, +} from '@wto/mods'; +import { addonMountFolderForMod } from './addon-register.ts'; + +export const MODS_STATE_FILE = join('wtoffline', 'mods-state.json'); +export const CORE_BUILD_PACKS: ReadonlySet = new Set([ + 'char.vromfs.bin', + 'aces.vromfs.bin', + 'gui.vromfs.bin', +]); + +export type DeployEntryKind = 'junction' | 'symlink' | 'hardlink' | 'copy'; + +export interface DeployedModEntry { + readonly modId: string; + /** Copy-relative path with forward slashes. */ + readonly targetRelPath: string; + readonly sourcePath: string; + readonly kind: DeployEntryKind; + readonly size?: number; + readonly mtimeMs?: number; +} + +export interface ModsDeployState { + readonly format: 1; + readonly entries: readonly DeployedModEntry[]; + /** Optional stock packs backed up on demand under `wtoffline/stock/`. */ + readonly optionalPacksModified: readonly ModdableClientPack[]; + readonly configBlkModified: boolean; + readonly fingerprint?: string; +} + +export interface ModDeployWarning { + readonly modId: string; + readonly targetRelPath: string; + readonly reason: string; +} + +export interface ModExternalDeployResult { + readonly deployed: readonly DeployedModEntry[]; + readonly warnings: readonly ModDeployWarning[]; + readonly restoredOptionalPacks: readonly ModdableClientPack[]; + readonly configBlkPatched: boolean; +} + +export function readModsDeployState(copyFolder: string): ModsDeployState { + const path = join(copyFolder, MODS_STATE_FILE); + if (!existsSync(path)) { + return { format: 1, entries: [], optionalPacksModified: [], configBlkModified: false }; + } + try { + const parsed = JSON.parse(readFileSync(path, 'utf8')) as Partial; + return { + format: 1, + entries: Array.isArray(parsed.entries) ? parsed.entries : [], + optionalPacksModified: Array.isArray(parsed.optionalPacksModified) ? parsed.optionalPacksModified : [], + configBlkModified: parsed.configBlkModified === true, + ...(typeof parsed.fingerprint === 'string' ? { fingerprint: parsed.fingerprint } : {}), + }; + } catch { + return { format: 1, entries: [], optionalPacksModified: [], configBlkModified: false }; + } +} + +export function writeModsDeployState(copyFolder: string, state: ModsDeployState): void { + const path = join(copyFolder, MODS_STATE_FILE); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, JSON.stringify(state, null, 2), 'utf8'); +} + +/** + * Ensure stock copies exist under `` for any optional .vromfs.bin pack + * touched by enabled mods, then read and return their stock bytes for overlay building. + */ +export function prepareOptionalStockPacks( + copyFolder: string, + stockBackupFolder: string, + touchedPacks: readonly ModdableClientPack[], +): Partial> { + const result: Partial> = {}; + for (const pack of touchedPacks) { + if (CORE_BUILD_PACKS.has(pack)) continue; + const backupPath = join(stockBackupFolder, ...pack.split('/')); + if (!existsSync(backupPath)) { + const livePath = join(copyFolder, ...pack.split('/')); + if (!existsSync(livePath)) { + throw new Error(`optional game pack "${pack}" does not exist in copy folder ${copyFolder}`); + } + mkdirSync(dirname(backupPath), { recursive: true }); + copyFileSync(livePath, backupPath); + } + result[pack] = readFileSync(backupPath); + } + return result; +} + +/** + * Synchronize external mod mounts (`client/addon/`, `client/files/`, `config.blk` patches) + * and restore any previously modified optional packs that are no longer touched. + */ +export function syncExternalModFiles( + copyFolder: string, + stockBackupFolder: string, + mods: readonly DiscoveredMod[], + optionalPacksInBuild: readonly ModdableClientPack[], + fingerprint?: string, +): ModExternalDeployResult { + const previous = readModsDeployState(copyFolder); + const warnings: ModDeployWarning[] = []; + + // Plan desired external mounts for this launch. + const desired = planExternalEntries(mods); + const desiredByTarget = new Map(desired.map((item) => [item.targetRelPath.toLowerCase(), item])); + const previousByTarget = new Map(previous.entries.map((item) => [item.targetRelPath.toLowerCase(), item])); + + // 1. Remove previous entries that are no longer wanted or changed source/mode. + for (const oldEntry of previous.entries) { + const key = oldEntry.targetRelPath.toLowerCase(); + const next = desiredByTarget.get(key); + const keepUnchanged = next !== undefined + && next.sourcePath === oldEntry.sourcePath + && isEntryStillValid(copyFolder, oldEntry); + if (!keepUnchanged) { + removeDeployedEntry(copyFolder, oldEntry); + } + } + + // 2. Restore optional packs that were modified previously but are no longer touched. + const activeOptionalSet = new Set(optionalPacksInBuild.filter((pack) => !CORE_BUILD_PACKS.has(pack))); + const restoredOptionalPacks: ModdableClientPack[] = []; + for (const oldPack of previous.optionalPacksModified) { + if (activeOptionalSet.has(oldPack)) continue; + const backupPath = join(stockBackupFolder, ...oldPack.split('/')); + const livePath = join(copyFolder, ...oldPack.split('/')); + if (existsSync(backupPath)) { + unlinkIfExists(livePath); + mkdirSync(dirname(livePath), { recursive: true }); + copyFileSync(backupPath, livePath); + restoredOptionalPacks.push(oldPack); + } + } + + // 3. Deploy desired mounts (skipping already-valid unchanged mounts and protecting native player files). + const deployed: DeployedModEntry[] = []; + for (const plan of desired) { + const key = plan.targetRelPath.toLowerCase(); + const prev = previousByTarget.get(key); + if (prev && prev.sourcePath === plan.sourcePath && isEntryStillValid(copyFolder, prev)) { + deployed.push(prev); + continue; + } + + const targetAbs = join(copyFolder, ...plan.targetRelPath.split('/')); + // Protect player-managed native files (e.g. manually installed UserSkins/UserSights). + if (existsSyncSafe(targetAbs) && !previousByTarget.has(key)) { + warnings.push({ + modId: plan.modId, + targetRelPath: plan.targetRelPath, + reason: 'target already exists as a native/player file; skipped to avoid overwriting player content', + }); + continue; + } + + const mounted = mountPlannedEntry(copyFolder, plan); + deployed.push(mounted); + } + + // 4. Apply or restore config.blk patches. + const configBlkPatched = syncConfigBlkPatches(copyFolder, stockBackupFolder, mods, previous.configBlkModified); + + writeModsDeployState(copyFolder, { + format: 1, + entries: deployed, + optionalPacksModified: [...activeOptionalSet], + configBlkModified: configBlkPatched, + ...(fingerprint !== undefined ? { fingerprint } : {}), + }); + + return { deployed, warnings, restoredOptionalPacks, configBlkPatched }; +} + +/** Compute a deterministic fingerprint of enabled mods and their source file stamps. */ +export function computeModsBuildFingerprint( + mods: readonly DiscoveredMod[], + port: number, + extraSalt = '', +): string { + const hash = createHash('sha256'); + hash.update(`port=${port};salt=${extraSalt}\n`); + for (const mod of mods) { + hash.update(`mod=${mod.manifest.id}@${mod.manifest.version}\n`); + const filesToStamp = [ + ...mod.content.packOperations.map((op) => op.sourceRelativePath), + ...mod.content.guiPatchDirs, + ...mod.content.exePatchDirs, + ...(mod.content.configBlkPatch ? [mod.content.configBlkPatch] : []), + ]; + for (const rel of filesToStamp) { + const abs = join(mod.rootDir, ...rel.split('/')); + try { + const st = statSync(abs); + hash.update(`${rel}:${st.size}:${Math.trunc(st.mtimeMs)}\n`); + } catch { + hash.update(`${rel}:missing\n`); + } + } + } + return hash.digest('hex'); +} + +interface PlannedMount { + readonly modId: string; + readonly targetRelPath: string; + readonly sourcePath: string; + readonly isDirectory: boolean; +} + +function planExternalEntries(mods: readonly DiscoveredMod[]): PlannedMount[] { + const plans: PlannedMount[] = []; + const seenTargets = new Map(); + + const register = (plan: PlannedMount) => { + const key = plan.targetRelPath.toLowerCase(); + const existingIdx = seenTargets.get(key); + if (existingIdx !== undefined) { + plans[existingIdx] = plan; + } else { + seenTargets.set(key, plans.length); + plans.push(plan); + } + }; + + // Addons are always mod-exclusive directories -> ideal for cross-drive Junctions. + for (const mod of mods) { + if (!mod.content.hasClientAddon) continue; + register({ + modId: mod.manifest.id, + targetRelPath: addonMountFolderForMod(mod), + sourcePath: join(mod.rootDir, 'client', 'addon'), + isDirectory: true, + }); + } + + // Companion files under `client/files`: group exclusive leaf directories (e.g. `UserSkins/my_skin`) + // as cross-drive Junctions whenever only one mod touches that subdirectory. + const folderOwners = new Map>(); + for (const mod of mods) { + for (const rel of mod.content.clientFiles) { + const topSub = exclusiveSubdirCandidate(rel); + if (!topSub) continue; + const key = topSub.toLowerCase(); + let set = folderOwners.get(key); + if (!set) { + set = new Set(); + folderOwners.set(key, set); + } + set.add(mod.manifest.id); + } + } + + for (const mod of mods) { + const claimedDirs = new Set(); + for (const rel of mod.content.clientFiles) { + const topSub = exclusiveSubdirCandidate(rel); + if (topSub && folderOwners.get(topSub.toLowerCase())?.size === 1) { + const key = topSub.toLowerCase(); + if (!claimedDirs.has(key)) { + claimedDirs.add(key); + register({ + modId: mod.manifest.id, + targetRelPath: topSub, + sourcePath: join(mod.rootDir, 'client', 'files', ...topSub.split('/')), + isDirectory: true, + }); + } + continue; + } + register({ + modId: mod.manifest.id, + targetRelPath: rel, + sourcePath: join(mod.rootDir, 'client', 'files', ...rel.split('/')), + isDirectory: false, + }); + } + } + + return plans; +} + +/** + * Return a safe exclusive subdirectory candidate (e.g. `UserSkins/foo`, `UserSights/bar`, + * `UserMissions/baz`) that can be mounted as one cross-drive Junction instead of linking + * every file inside it. Flat shared folders like `sound/mod/*.bank` return undefined. + */ +function exclusiveSubdirCandidate(relPath: string): string | undefined { + const parts = relPath.split('/'); + if (parts.length < 3) return undefined; + const root = parts[0]!.toLowerCase(); + if (root === 'userskins' || root === 'usersights' || root === 'usermissions') { + return `${parts[0]!}/${parts[1]!}`; + } + return undefined; +} + +function mountPlannedEntry(copyFolder: string, plan: PlannedMount): DeployedModEntry { + const targetAbs = join(copyFolder, ...plan.targetRelPath.split('/')); + mkdirSync(dirname(targetAbs), { recursive: true }); + + if (plan.isDirectory) { + try { + symlinkSync(plan.sourcePath, targetAbs, 'junction'); + return { + modId: plan.modId, + targetRelPath: plan.targetRelPath, + sourcePath: plan.sourcePath, + kind: 'junction', + }; + } catch { + // Fallback for non-NTFS volumes (e.g. exFAT): incremental directory copy. + copyDirectoryIncremental(plan.sourcePath, targetAbs); + return { + modId: plan.modId, + targetRelPath: plan.targetRelPath, + sourcePath: plan.sourcePath, + kind: 'copy', + }; + } + } + + // Flat single file: try file symlink (cross-drive when Developer Mode is enabled), + // then same-drive NTFS hardlink, then cached copy. + unlinkIfExists(targetAbs); + try { + symlinkSync(plan.sourcePath, targetAbs, 'file'); + return { + modId: plan.modId, + targetRelPath: plan.targetRelPath, + sourcePath: plan.sourcePath, + kind: 'symlink', + }; + } catch { /* fall through */ } + + try { + linkSync(plan.sourcePath, targetAbs); + return { + modId: plan.modId, + targetRelPath: plan.targetRelPath, + sourcePath: plan.sourcePath, + kind: 'hardlink', + }; + } catch { /* fall through */ } + + const st = statSync(plan.sourcePath); + copyFileSync(plan.sourcePath, targetAbs); + return { + modId: plan.modId, + targetRelPath: plan.targetRelPath, + sourcePath: plan.sourcePath, + kind: 'copy', + size: st.size, + mtimeMs: st.mtimeMs, + }; +} + +function isEntryStillValid(copyFolder: string, entry: DeployedModEntry): boolean { + const targetAbs = join(copyFolder, ...entry.targetRelPath.split('/')); + if (!existsSyncSafe(targetAbs)) return false; + if (entry.kind === 'junction' || entry.kind === 'symlink') { + try { + return lstatSync(targetAbs).isSymbolicLink() && existsSync(entry.sourcePath); + } catch { + return false; + } + } + if (entry.kind === 'hardlink') { + try { + const a = statSync(targetAbs); + const b = statSync(entry.sourcePath); + return a.ino !== 0 && a.ino === b.ino && a.dev === b.dev; + } catch { + return false; + } + } + // Cached copy check. + if (entry.size !== undefined && entry.mtimeMs !== undefined) { + try { + const src = statSync(entry.sourcePath); + const dst = statSync(targetAbs); + return src.size === entry.size && Math.abs(src.mtimeMs - entry.mtimeMs) < 2 && dst.size === src.size; + } catch { + return false; + } + } + return false; +} + +function removeDeployedEntry(copyFolder: string, entry: DeployedModEntry): void { + const targetAbs = join(copyFolder, ...entry.targetRelPath.split('/')); + if (!existsSyncSafe(targetAbs)) return; + try { + const stat = lstatSync(targetAbs); + if (entry.kind === 'junction' || stat.isSymbolicLink()) { + // Remove only the reparse point / symlink, never descending into the source mod folder. + try { + unlinkSync(targetAbs); + } catch { + rmdirSync(targetAbs); + } + } else if (stat.isDirectory()) { + rmSync(targetAbs, { recursive: true, force: true }); + } else { + unlinkSync(targetAbs); + } + } catch { /* ignore */ } + pruneEmptyParents(dirname(targetAbs), copyFolder); +} + +function copyDirectoryIncremental(srcDir: string, dstDir: string): void { + mkdirSync(dstDir, { recursive: true }); + for (const entry of readdirSync(srcDir, { withFileTypes: true })) { + const src = join(srcDir, entry.name); + const dst = join(dstDir, entry.name); + if (entry.isDirectory()) { + copyDirectoryIncremental(src, dst); + } else if (entry.isFile()) { + const st = statSync(src); + let same = false; + try { + const dstStat = statSync(dst); + same = dstStat.size === st.size && Math.abs(dstStat.mtimeMs - st.mtimeMs) < 2; + } catch { /* missing */ } + if (!same) { + unlinkIfExists(dst); + copyFileSync(src, dst); + } + } + } +} + +function syncConfigBlkPatches( + copyFolder: string, + stockBackupFolder: string, + mods: readonly DiscoveredMod[], + previouslyModified: boolean, +): boolean { + const patchingMods = mods.filter((mod) => mod.content.configBlkPatch !== undefined); + const liveConfig = join(copyFolder, 'config.blk'); + const backupConfig = join(stockBackupFolder, 'config.blk'); + + if (patchingMods.length === 0) { + if (previouslyModified && existsSync(backupConfig)) { + unlinkIfExists(liveConfig); + copyFileSync(backupConfig, liveConfig); + } + return false; + } + + if (!existsSync(backupConfig) && existsSync(liveConfig)) { + mkdirSync(dirname(backupConfig), { recursive: true }); + copyFileSync(liveConfig, backupConfig); + } + const sourceText = existsSync(backupConfig) + ? readFileSync(backupConfig, 'utf8') + : existsSync(liveConfig) ? readFileSync(liveConfig, 'utf8') : ''; + const root = parseBlkText(sourceText); + + for (const mod of patchingMods) { + const patchPath = join(mod.rootDir, ...mod.content.configBlkPatch!.split('/')); + const patch = parseBlkPatchDocument(readFileSync(patchPath, 'utf8'), `mod "${mod.manifest.id}" config.blk patch`); + applyBlkPatch(root, patch, `mod "${mod.manifest.id}" config.blk patch`); + } + + unlinkIfExists(liveConfig); + writeFileSync(liveConfig, formatBlkText(root), 'utf8'); + return true; +} + +function pruneEmptyParents(dir: string, stopAt: string): void { + let current = dir; + while (relative(stopAt, current) !== '' && !relative(stopAt, current).startsWith('..')) { + try { + if (readdirSync(current).length > 0) return; + rmdirSync(current); + current = dirname(current); + } catch { + return; + } + } +} + +function existsSyncSafe(path: string): boolean { + try { + lstatSync(path); + return true; + } catch { + return false; + } +} + +function unlinkIfExists(path: string): void { + if (!existsSyncSafe(path)) return; + try { + unlinkSync(path); + } catch { /* ignore */ } +} diff --git a/packages/patcher/src/mods/gui-overlay.ts b/packages/patcher/src/mods/gui-overlay.ts new file mode 100644 index 0000000..45a7eda --- /dev/null +++ b/packages/patcher/src/mods/gui-overlay.ts @@ -0,0 +1,112 @@ +/** + * Apply mod GUI script patches (`client/gui-patches//patch.jsonc`) on top of an already + * core-patched gui.vromfs.bin archive. Failures are collected per mod rather than breaking core + * offline GUI patches. + */ +import { join } from 'node:path'; +import { chooseVariant, PatchError, type PatchFailure } from '@wto/exepatch'; +import type { DiscoveredMod } from '@wto/mods'; +import { getFile, putFile, readArchive, writeArchive, type Archive } from '@wto/vromfs'; +import { loadGuiPatches, type GuiScriptVariant } from '../gui-patch-definition.ts'; +import type { LocalEndpoint } from '../network/local-endpoint.ts'; + +const ENDPOINT_PLACEHOLDER = '{{LOCAL_ENDPOINT}}'; + +export interface ModGuiPatchResult { + readonly pack: Uint8Array; + readonly applied: readonly { readonly modId: string; readonly patchId: string }[]; + readonly failures: readonly (PatchFailure & { readonly modId: string })[]; +} + +class ModGuiPatchMismatch extends PatchError { + override name = 'ModGuiPatchMismatch'; +} + +export function applyModGuiPatches( + baseGuiPack: Uint8Array, + endpoint: LocalEndpoint, + mods: readonly DiscoveredMod[], +): ModGuiPatchResult { + const modsWithGui = mods.filter((mod) => mod.content.guiPatchDirs.length > 0); + if (modsWithGui.length === 0) { + return { pack: baseGuiPack, applied: [], failures: [] }; + } + + const archive = readArchive(baseGuiPack); + const hostPortText = `${endpoint.host}:${endpoint.port}`; + const applied: { readonly modId: string; readonly patchId: string }[] = []; + const failures: (PatchFailure & { readonly modId: string })[] = []; + + for (const mod of modsWithGui) { + const patchesRoot = join(mod.rootDir, 'client', 'gui-patches'); + let patches; + try { + patches = loadGuiPatches(patchesRoot); + } catch (error) { + failures.push({ + modId: mod.manifest.id, + patchId: `${mod.manifest.id}:gui-patches`, + features: [], + reason: error instanceof Error ? error.message : String(error), + }); + continue; + } + + for (const patch of patches) { + try { + const chosen = chooseVariant(patch.variants, (variant) => patchedScript(archive, variant, hostPortText)); + putFile(archive, chosen.variant.file, Buffer.from(chosen.value, 'utf8')); + applied.push({ modId: mod.manifest.id, patchId: patch.id }); + } catch (error) { + if (!(error instanceof PatchError)) throw error; + failures.push({ + modId: mod.manifest.id, + patchId: patch.id, + features: patch.features, + reason: error.message, + }); + } + } + } + + return { pack: writeArchive(archive), applied, failures }; +} + +function patchedScript(archive: Archive, variant: GuiScriptVariant, hostPortText: string): string { + if (!archive.files.has(variant.file)) throw new ModGuiPatchMismatch(`the data pack has no script ${variant.file}`); + let current = Buffer.from(getFile(archive, variant.file)).toString('utf8'); + const newline = current.includes('\r\n') ? '\r\n' : '\n'; + for (const [index, edit] of variant.edits.entries()) { + const replace = edit.replace.replaceAll('\n', newline).replaceAll(ENDPOINT_PLACEHOLDER, hostPortText); + current = replaceUnique(current, edit.find, replace, `edit ${index + 1} in ${variant.file}`); + } + return current; +} + +function replaceUnique(text: string, find: string, replace: string, label: string): string { + const { normalized, original } = withoutCarriageReturns(text); + const first = normalized.indexOf(find); + if (first === -1) throw new ModGuiPatchMismatch(`${label}: target text not found`); + if (normalized.indexOf(find, first + find.length) !== -1) { + throw new ModGuiPatchMismatch(`${label}: target text appears more than once`); + } + return text.slice(0, original[first]!) + replace + text.slice(original[first + find.length]!); +} + +function withoutCarriageReturns(text: string): { readonly normalized: string; readonly original: readonly number[] } { + const kept: string[] = []; + const original: number[] = []; + let index = 0; + while (index < text.length) { + original.push(index); + if (text[index] === '\r' && text[index + 1] === '\n') { + kept.push('\n'); + index += 2; + } else { + kept.push(text[index]!); + index += 1; + } + } + original.push(text.length); + return { normalized: kept.join(''), original }; +} diff --git a/packages/patcher/src/mods/pack-overlay.ts b/packages/patcher/src/mods/pack-overlay.ts new file mode 100644 index 0000000..9154035 --- /dev/null +++ b/packages/patcher/src/mods/pack-overlay.ts @@ -0,0 +1,103 @@ +/** + * Apply ordered mod pack operations (`blk-patch`, `csv-patch`, or added/replaced files) + * onto an in-memory .vromfs.bin archive without modifying stock backups. + */ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { decodeBlk, encodeBlk, isBinaryBlk, parseBlkText, parseSharedNameMap } from '@wto/blk'; +import { + applyBlkPatch, + mergeLocalizationCsv, + parseBlkPatchDocument, + type DiscoveredMod, + type ModdableClientPack, +} from '@wto/mods'; +import { getFile, NAME_MAP_PATH, putFile, readArchive, writeArchive, type Archive } from '@wto/vromfs'; + +export interface PackOverlayReport { + readonly pack: ModdableClientPack; + readonly operationsApplied: number; +} + +export function applyModPackOverlays( + basePack: Uint8Array, + packName: ModdableClientPack, + mods: readonly DiscoveredMod[], +): { readonly pack: Uint8Array; readonly report: PackOverlayReport } { + const relevant = mods.flatMap((mod) => + mod.content.packOperations + .filter((op) => op.pack === packName) + .map((op) => ({ mod, op })), + ); + if (relevant.length === 0) { + return { pack: basePack, report: { pack: packName, operationsApplied: 0 } }; + } + + const archive = readArchive(basePack); + const dictionary = findDictionary(archive); + const names = archive.files.has(NAME_MAP_PATH) + ? parseSharedNameMap(getFile(archive, NAME_MAP_PATH), dictionary).names + : []; + + for (const { mod, op } of relevant) { + const sourcePath = join(mod.rootDir, ...op.sourceRelativePath.split('/')); + const where = `mod "${mod.manifest.id}" (${op.sourceRelativePath})`; + switch (op.action) { + case 'blk-patch': { + const resolvedPath = findArchivePath(archive, op.targetPath); + if (!resolvedPath) { + throw new Error(`${where}: target BLK "${op.targetPath}" not found in ${packName}`); + } + const raw = getFile(archive, resolvedPath); + const root = isBinaryBlk(raw) + ? decodeBlk(raw, { names, dictionary }) + : parseBlkText(Buffer.from(raw).toString('utf8')); + const patch = parseBlkPatchDocument(readFileSync(sourcePath, 'utf8'), where); + applyBlkPatch(root, patch, where); + putFile(archive, resolvedPath, encodeBlk(root)); + break; + } + case 'csv-patch': { + const resolvedPath = findArchivePath(archive, op.targetPath); + if (!resolvedPath) { + throw new Error(`${where}: target CSV "${op.targetPath}" not found in ${packName}`); + } + const baseText = Buffer.from(getFile(archive, resolvedPath)).toString('utf8'); + const patchText = readFileSync(sourcePath, 'utf8'); + const merged = mergeLocalizationCsv(baseText, patchText); + putFile(archive, resolvedPath, Buffer.from(merged, 'utf8')); + break; + } + case 'file': { + const bytes = readFileSync(sourcePath); + const resolvedPath = findArchivePath(archive, op.targetPath) ?? op.targetPath; + if (op.targetPath.toLowerCase().endsWith('.blk') && !isBinaryBlk(bytes)) { + const parsed = parseBlkText(bytes.toString('utf8')); + putFile(archive, resolvedPath, encodeBlk(parsed)); + } else { + putFile(archive, resolvedPath, bytes); + } + break; + } + } + } + + return { + pack: writeArchive(archive), + report: { pack: packName, operationsApplied: relevant.length }, + }; +} + +function findArchivePath(archive: Archive, wanted: string): string | undefined { + if (archive.files.has(wanted)) return wanted; + const lower = wanted.toLowerCase(); + for (const key of archive.files.keys()) { + if (key.toLowerCase() === lower) return key; + } + return undefined; +} + +function findDictionary(archive: Archive): Uint8Array | undefined { + const dictionaries = [...archive.files.keys()].filter((path) => path.endsWith('.dict')); + return dictionaries.length === 1 ? archive.files.get(dictionaries[0]!) : undefined; +} From aa7a6e7d02a684b88658841673a3b8c70897e8c6 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Thu, 3 Dec 2026 00:00:36 +0800 Subject: [PATCH 03/12] feat(server): add experimental JS/TS mod runtime, hooks, tuning list ops, and isolated mod storage --- apps/server/package.json | 1 + .../server/src/char/actions/battle-actions.ts | 7 + apps/server/src/char/char-service.ts | 55 ++- .../src/matching/battle-live-requests.ts | 7 + .../src/matching/battle-queue-requests.ts | 7 + apps/server/src/mods/mod-http-service.ts | 82 +++++ apps/server/src/mods/mod-storage.ts | 55 +++ apps/server/src/mods/server-mod-runtime.ts | 334 ++++++++++++++++++ apps/server/src/profiles-setup.ts | 3 + apps/server/src/server.ts | 183 ++++++++-- apps/server/src/store/store-pack-ids.ts | 9 +- apps/server/src/tuning/tuning-loader.ts | 50 +-- apps/server/src/tuning/tuning.ts | 9 +- packages/mods/src/server-api.ts | 2 +- 14 files changed, 743 insertions(+), 61 deletions(-) create mode 100644 apps/server/src/mods/mod-http-service.ts create mode 100644 apps/server/src/mods/mod-storage.ts create mode 100644 apps/server/src/mods/server-mod-runtime.ts diff --git a/apps/server/package.json b/apps/server/package.json index 762e9d8..3d67703 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -9,6 +9,7 @@ "dependencies": { "@wto/blk": "*", "@wto/jsonc": "*", + "@wto/mods": "*", "@wto/vromfs": "*" } } \ No newline at end of file diff --git a/apps/server/src/char/actions/battle-actions.ts b/apps/server/src/char/actions/battle-actions.ts index 228a960..47f8499 100644 --- a/apps/server/src/char/actions/battle-actions.ts +++ b/apps/server/src/char/actions/battle-actions.ts @@ -3,6 +3,7 @@ * settles them into the player's save (battle-settlement.ts) and answers the updated profile, * whose new `EULT_SESSION_RESULT` log carries the debriefing table. */ +import type { BattleSettlementContext } from '@wto/mods'; import type { AccountStore } from '../../accounts/account-store.ts'; import { parseBattleReport } from '../../battle/battle-report.ts'; import type { BattleSessionStore } from '../../battle/battle-session-store.ts'; @@ -28,6 +29,7 @@ export interface BattleActionDependencies { readonly streaks: BattleStreaks; /** Units whose lives and events are not settled (battle-support-planes.ts). */ readonly supportPlanes: ReadonlySet; + readonly onAfterSettle?: (ctx: BattleSettlementContext) => void; } export interface FinishBattleContext { @@ -62,6 +64,11 @@ export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActio } const updated = ctx.profiles.update(account.userId, (profile) => { settleBattle(profile, report, session, settlementDeps); + battle.onAfterSettle?.({ + userId: account.userId, + roomId: session.sessionId, + summary: { profile, report, session }, + }); }); battle.sessions.markSettled(session.sessionId); return { kind: 'data', blk: clientProfile(updated, account) }; diff --git a/apps/server/src/char/char-service.ts b/apps/server/src/char/char-service.ts index f5bc19a..53c65ae 100644 --- a/apps/server/src/char/char-service.ts +++ b/apps/server/src/char/char-service.ts @@ -13,6 +13,8 @@ * default lets the client continue and reveal what it asks for next. */ import { emptyBlock } from '@wto/blk'; +import type { ModCharRequest, ModCharResponse } from '@wto/mods'; +import type { ServerModRuntime } from '../mods/server-mod-runtime.ts'; import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts'; import type { CharActionHandler } from './char-action.ts'; import { toResponse, type CharAnswer } from './char-answers.ts'; @@ -23,17 +25,26 @@ const CHAR_HOST = /^char-[a-z0-9-]+\.warthunder\.com$/; export class CharService implements Service { readonly name = 'char'; readonly #actions: ReadonlyMap; + readonly #modRuntime: ServerModRuntime | undefined; - constructor(actions: ReadonlyMap) { + constructor(actions: ReadonlyMap, modRuntime?: ServerModRuntime) { this.#actions = actions; + this.#modRuntime = modRuntime; } accepts(request: ServiceRequest): boolean { return request.originalHost !== undefined && CHAR_HOST.test(request.originalHost); } - handle(request: ServiceRequest): ServiceResponse { + handle(request: ServiceRequest): ServiceResponse | Promise { const action = header(request, 'action') ?? '(no action header)'; + if (this.#modRuntime?.hasCharOverride(action)) { + return this.#handleWithModOverride(action, request); + } + return this.#handleCore(action, request); + } + + #handleCore(action: string, request: ServiceRequest): ServiceResponse { const payload = decodeRequestPayload(request.body); const handler = this.#actions.get(action); const answer: CharAnswer = handler @@ -56,6 +67,46 @@ export class CharService implements Service { }, }; } + + async #handleWithModOverride(action: string, request: ServiceRequest): Promise { + const headers: Record = {}; + for (const [key, value] of Object.entries(request.headers)) { + headers[key] = Array.isArray(value) ? value[0] : value; + } + const query: Record = {}; + for (const [key, value] of request.query.entries()) query[key] = value; + + const modReq: ModCharRequest = { + action, + userId: header(request, 'uidhint') ?? '', + headers, + body: request.body, + query, + }; + + const result = await this.#modRuntime!.dispatchCharOverride(action, modReq, async (nextReq): Promise => { + const forwarded: ServiceRequest = { ...request, body: nextReq.body }; + const coreResp = this.#handleCore(nextReq.action, forwarded); + return { + status: coreResp.status, + ...(coreResp.headers ? { headers: coreResp.headers } : {}), + body: coreResp.body ?? '', + }; + }); + + const responseHeaders: Record = { ...(result.headers ?? {}) }; + if (result.contentType && !responseHeaders['content-type'] && !responseHeaders['Content-Type']) { + responseHeaders['content-type'] = result.contentType; + } + return { + status: result.status ?? 200, + headers: responseHeaders, + body: result.body, + logNotes: { + summary: `${action} [mod handler] -> ${result.status ?? 200}`, + }, + }; + } } function header(request: ServiceRequest, name: string): string | undefined { diff --git a/apps/server/src/matching/battle-live-requests.ts b/apps/server/src/matching/battle-live-requests.ts index 0d0607c..66ad586 100644 --- a/apps/server/src/matching/battle-live-requests.ts +++ b/apps/server/src/matching/battle-live-requests.ts @@ -11,6 +11,7 @@ * "strike": time:f the local player's nuclear bomb exploded * answer: { streaks: [{ id:s stage:i (-1 = single-stage) stageParam:i wp:i exp:i }] } */ +import type { BattleLiveFactContext } from '@wto/mods'; import type { BattleLiveLogs } from '../battle/battle-live-log.ts'; import type { BattleSessionStore } from '../battle/battle-session-store.ts'; import type { BattleStreaks } from '../battle/battle-streaks.ts'; @@ -23,6 +24,7 @@ export interface BattleLiveDependencies { readonly streaks: BattleStreaks; /** Units whose lives and events earn no awards (battle-support-planes.ts). */ readonly supportPlanes: ReadonlySet; + readonly onLiveFact?: (ctx: BattleLiveFactContext) => void; } export function battleLiveRequests(deps: BattleLiveDependencies): Array<[string, MatchingRequestHandler]> { @@ -34,6 +36,11 @@ export function battleLiveRequests(deps: BattleLiveDependencies): Array<[string, if (!session || session.settled) return { streaks: [] }; const log = deps.liveLogs.of(session.sessionId); if (!recordFact(log, p)) return { streaks: [] }; + deps.onLiveFact?.({ + userId: userId!, + roomId: session.sessionId, + fact: p as Record, + }); const awarded = deps.streaks.evaluate({ ...withoutSupportPlanes({ events: log.events, lives: log.lives }, deps.supportPlanes), feed: log.feed, diff --git a/apps/server/src/matching/battle-queue-requests.ts b/apps/server/src/matching/battle-queue-requests.ts index efa424d..5ff92d2 100644 --- a/apps/server/src/matching/battle-queue-requests.ts +++ b/apps/server/src/matching/battle-queue-requests.ts @@ -5,6 +5,7 @@ * - `match.leave_queue` (scripts/queue/queuestate.nut:28) * - `match.check_reconnect` */ +import type { BattleMatchmakeContext } from '@wto/mods'; import { MAX_BATTLE_CREW_SLOTS } from '../battle/battle-extra-slots.ts'; import { economyDifficulty, type BattleEconomy } from '../battle/battle-economy.ts'; import type { BattleMatchmaker } from '../battle/battle-matchmaker.ts'; @@ -24,6 +25,7 @@ export interface BattleQueueDependencies { readonly sessions: BattleSessionStore; readonly economy: BattleEconomy; readonly notifyLaunch: (userId: string, payload: BattleLaunchNotify) => void; + readonly onBeforeMatchmake?: (ctx: BattleMatchmakeContext) => void; } export function battleQueueRequests(deps: BattleQueueDependencies): Array<[string, MatchingRequestHandler]> { @@ -85,6 +87,11 @@ function handleEnqueue( const slotVehicles = crewVehiclesOfCountry(profile, playerEntry.country); const idInCountry = playerEntry.selectedSlot; const selectedSlotVehicle = idInCountry === undefined ? undefined : crewSlotVehicleOfCountry(profile, playerEntry.country, idInCountry); + deps.onBeforeMatchmake?.({ + userId, + eventName: modes[0]!.declaration.name, + request: params as Record, + }); const outcome = deps.matchmaker.enqueue({ userId, mode: modes[0]!, diff --git a/apps/server/src/mods/mod-http-service.ts b/apps/server/src/mods/mod-http-service.ts new file mode 100644 index 0000000..696dbe2 --- /dev/null +++ b/apps/server/src/mods/mod-http-service.ts @@ -0,0 +1,82 @@ +/** + * HTTP router service that exposes mod-registered routes under `/mods//...` + * so mods can provide custom APIs or embedded-browser pages without touching core routes. + */ +import type { ModHttpHandler, ModHttpRequest } from '@wto/mods'; +import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts'; + +export interface RegisteredModHttpRoute { + readonly modId: string; + /** Full normalized path prefix or exact path under `/mods//...`. */ + readonly pattern: string; + readonly isWildcard: boolean; + readonly prefix: string; + readonly handler: ModHttpHandler; +} + +export class ModHttpService implements Service { + readonly name = 'mods-http'; + readonly #routes: readonly RegisteredModHttpRoute[]; + + constructor(routes: readonly RegisteredModHttpRoute[]) { + this.#routes = routes; + } + + accepts(request: ServiceRequest): boolean { + if (request.originalHost !== undefined) return false; + return this.#match(request.path) !== undefined; + } + + async handle(request: ServiceRequest): Promise { + const matched = this.#match(request.path); + if (!matched) { + return { status: 404, body: 'mod route not found' }; + } + const headers: Record = {}; + for (const [key, value] of Object.entries(request.headers)) { + headers[key] = Array.isArray(value) ? value[0] : value; + } + const query: Record = {}; + for (const [key, value] of request.query.entries()) query[key] = value; + + const modReq: ModHttpRequest = { + method: request.method, + path: request.path, + query, + headers, + body: request.body, + }; + const answer = await matched.handler(modReq); + const responseHeaders: Record = { ...(answer.headers ?? {}) }; + if (answer.contentType && !responseHeaders['content-type'] && !responseHeaders['Content-Type']) { + responseHeaders['content-type'] = answer.contentType; + } + return { + status: answer.status ?? 200, + headers: responseHeaders, + body: answer.body, + logNotes: { summary: `mod:${matched.modId} ${request.method} ${request.path}` }, + }; + } + + #match(path: string): RegisteredModHttpRoute | undefined { + for (const route of this.#routes) { + if (route.isWildcard) { + if (path.startsWith(route.prefix)) return route; + } else if (path === route.pattern) { + return route; + } + } + return undefined; + } +} + +export function buildModHttpRoute(modId: string, subPath: string, handler: ModHttpHandler): RegisteredModHttpRoute { + const cleaned = subPath.startsWith('/') ? subPath : `/${subPath}`; + const full = `/mods/${modId}${cleaned === '/' ? '' : cleaned}`; + if (full.endsWith('/*')) { + const prefix = full.slice(0, -1); // keeps trailing '/' + return { modId, pattern: full, isWildcard: true, prefix, handler }; + } + return { modId, pattern: full, isWildcard: false, prefix: full, handler }; +} diff --git a/apps/server/src/mods/mod-storage.ts b/apps/server/src/mods/mod-storage.ts new file mode 100644 index 0000000..838c418 --- /dev/null +++ b/apps/server/src/mods/mod-storage.ts @@ -0,0 +1,55 @@ +/** + * Isolated JSON storage for server mods: + * - per-player files under `/saves//mods/.json` + * - shared mod state under `/mods-data/.json` + * + * Keeping mod state outside `profile.blk` guarantees uninstalling a mod never corrupts stock saves. + */ +import { existsSync, readFileSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import type { ModPlayerStorage, ModStorageApi } from '@wto/mods'; +import { writeFileAtomic } from '../storage/atomic-file.ts'; + +export function createModStorage(dataFolder: string, modId: string): ModStorageApi { + const safeMod = sanitizeSegment(modId); + return { + forPlayer(userId: string): ModPlayerStorage { + const safeUser = sanitizeSegment(userId); + const filePath = join(dataFolder, 'saves', safeUser, 'mods', `${safeMod}.json`); + return createJsonFileStorage(filePath); + }, + shared(): ModPlayerStorage { + const filePath = join(dataFolder, 'mods-data', `${safeMod}.json`); + return createJsonFileStorage(filePath); + }, + }; +} + +function createJsonFileStorage(filePath: string): ModPlayerStorage { + return { + read(): T | undefined { + if (!existsSync(filePath)) return undefined; + try { + return JSON.parse(readFileSync(filePath, 'utf8')) as T; + } catch { + return undefined; + } + }, + write(value: unknown): void { + writeFileAtomic(filePath, JSON.stringify(value, null, 2)); + }, + remove(): void { + try { + rmSync(filePath, { force: true }); + } catch { /* ignore */ } + }, + }; +} + +function sanitizeSegment(raw: string): string { + const cleaned = raw.replace(/[^A-Za-z0-9._-]/g, '_'); + if (!cleaned || cleaned === '.' || cleaned === '..') { + throw new Error(`invalid storage path segment "${raw}"`); + } + return cleaned; +} diff --git a/apps/server/src/mods/server-mod-runtime.ts b/apps/server/src/mods/server-mod-runtime.ts new file mode 100644 index 0000000..64c3ca5 --- /dev/null +++ b/apps/server/src/mods/server-mod-runtime.ts @@ -0,0 +1,334 @@ +/** + * Experimental server-side JS/TS mod runtime. + * + * Loads each enabled mod's server script entry (`.ts`, `.mjs`, or `.js` via Node 24's built-in + * TypeScript stripping and ESM dynamic import), injects an isolated `WtoServerModContext`, and + * coordinates lifecycle hooks, profile/battle hooks, char/matching wrappers, and `/mods//*` + * HTTP routes. + */ +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import type { BlkBlock } from '@wto/blk'; +import { + MOD_API_VERSION, + type BattleLiveFactContext, + type BattleMatchmakeContext, + type BattleSettlementContext, + type DiscoveredMod, + type ModCharHandler, + type ModCharRequest, + type ModCharResponse, + type ModCharWrapper, + type ModHttpHandler, + type ModMatchingHandler, + type ModMatchingRequest, + type ModMatchingWrapper, + type ServerModCataloguesView, + type ServerModDatasetsView, + type WtoServerMod, + type WtoServerModContext, +} from '@wto/mods'; +import type { MatchingRequestHandler, MatchingRequestTable } from '../matching/matching-requests.ts'; +import { buildModHttpRoute, ModHttpService, type RegisteredModHttpRoute } from './mod-http-service.ts'; +import { createModStorage } from './mod-storage.ts'; + +interface RuntimeInitOptions { + readonly mods: readonly DiscoveredMod[]; + readonly gameFolder: string; + readonly dataFolder: string; + readonly port: number; + readonly report: (line: string) => void; +} + +interface ScopedHandler { + readonly modId: string; + readonly fn: T; +} + +export class ServerModRuntime { + readonly #report: (line: string) => void; + readonly #loadedModIds: string[] = []; + readonly #onDatasetsLoaded: ScopedHandler<(datasets: ServerModDatasetsView) => void | Promise>[] = []; + readonly #onCataloguesReady: ScopedHandler<(catalogues: ServerModCataloguesView) => void | Promise>[] = []; + readonly #onServerListening: ScopedHandler<(info: { readonly port: number }) => void | Promise>[] = []; + readonly #onServerClosing: ScopedHandler<() => void | Promise>[] = []; + readonly #onProfileRefresh: ScopedHandler<(profile: BlkBlock, userId: string) => void>[] = []; + readonly #onBeforeMatchmake: ScopedHandler<(ctx: BattleMatchmakeContext) => void>[] = []; + readonly #onLiveFact: ScopedHandler<(ctx: BattleLiveFactContext) => void>[] = []; + readonly #onAfterSettle: ScopedHandler<(ctx: BattleSettlementContext) => void>[] = []; + readonly #charHandlers = new Map>(); + readonly #charWrappers = new Map[]>(); + readonly #matchingHandlers = new Map>(); + readonly #matchingWrappers = new Map[]>(); + readonly #httpRoutes: RegisteredModHttpRoute[] = []; + + private constructor(report: (line: string) => void) { + this.#report = report; + } + + static async load(options: RuntimeInitOptions): Promise { + const runtime = new ServerModRuntime(options.report); + const scriptMods = options.mods.filter((mod) => mod.content.serverEntry !== undefined); + if (scriptMods.length === 0) return runtime; + + const cacheBust = Date.now(); + for (const mod of scriptMods) { + const entryRel = mod.content.serverEntry!; + const entryAbs = join(mod.rootDir, ...entryRel.split('/')); + const modId = mod.manifest.id; + const url = `${pathToFileURL(entryAbs).href}?wto_mod=${cacheBust}`; + + let loadedModule: Record; + try { + loadedModule = (await import(url)) as Record; + } catch (error) { + throw new Error( + `Failed to load server mod "${modId}" (${entryRel}): ${error instanceof Error ? error.stack ?? error.message : String(error)}`, + ); + } + + const modExport = resolveModExport(loadedModule); + if (!modExport) { + throw new Error( + `Server mod "${modId}" (${entryRel}) must export default { setup(ctx) { ... } } or named setup(ctx)`, + ); + } + + const ctx = runtime.#createContext(mod, options); + try { + await modExport.setup(ctx); + } catch (error) { + throw new Error( + `Server mod "${modId}" setup() failed: ${error instanceof Error ? error.stack ?? error.message : String(error)}`, + ); + } + runtime.#loadedModIds.push(modId); + options.report(`mod ${modId}: server script loaded (${entryRel})`); + } + return runtime; + } + + get loadedModIds(): readonly string[] { + return this.#loadedModIds; + } + + async runDatasetsLoaded(view: ServerModDatasetsView): Promise { + for (const { modId, fn } of this.#onDatasetsLoaded) { + try { + await fn(view); + } catch (error) { + throw new Error(`Server mod "${modId}" onDatasetsLoaded failed: ${formatError(error)}`); + } + } + } + + async runCataloguesReady(view: ServerModCataloguesView): Promise { + for (const { modId, fn } of this.#onCataloguesReady) { + try { + await fn(view); + } catch (error) { + throw new Error(`Server mod "${modId}" onCataloguesReady failed: ${formatError(error)}`); + } + } + } + + async runServerListening(port: number): Promise { + for (const { modId, fn } of this.#onServerListening) { + try { + await fn({ port }); + } catch (error) { + this.#report(`[mod:${modId}] onServerListening error: ${formatError(error)}`); + } + } + } + + async runServerClosing(): Promise { + for (const { modId, fn } of [...this.#onServerClosing].reverse()) { + try { + await fn(); + } catch (error) { + this.#report(`[mod:${modId}] onServerClosing error: ${formatError(error)}`); + } + } + } + + runProfileRefresh(profile: BlkBlock, userId: string): void { + for (const { modId, fn } of this.#onProfileRefresh) { + try { + fn(profile, userId); + } catch (error) { + this.#report(`[mod:${modId}] profile.onRefresh error: ${formatError(error)}`); + } + } + } + + runBattleBeforeMatchmake(ctx: BattleMatchmakeContext): void { + for (const { modId, fn } of this.#onBeforeMatchmake) { + try { + fn(ctx); + } catch (error) { + this.#report(`[mod:${modId}] battle.onBeforeMatchmake error: ${formatError(error)}`); + } + } + } + + runBattleLiveFact(ctx: BattleLiveFactContext): void { + for (const { modId, fn } of this.#onLiveFact) { + try { + fn(ctx); + } catch (error) { + this.#report(`[mod:${modId}] battle.onLiveFact error: ${formatError(error)}`); + } + } + } + + runBattleAfterSettle(ctx: BattleSettlementContext): void { + for (const { modId, fn } of this.#onAfterSettle) { + try { + fn(ctx); + } catch (error) { + this.#report(`[mod:${modId}] battle.onAfterSettle error: ${formatError(error)}`); + } + } + } + + hasCharOverride(action: string): boolean { + return this.#charHandlers.has(action) || this.#charWrappers.has(action); + } + + async dispatchCharOverride( + action: string, + request: ModCharRequest, + baseDispatch: (req: ModCharRequest) => Promise, + ): Promise { + const custom = this.#charHandlers.get(action); + const terminal: (req: ModCharRequest) => Promise = custom + ? async (req) => await custom.fn(req) + : baseDispatch; + + const wrappers = this.#charWrappers.get(action); + if (!wrappers || wrappers.length === 0) return terminal(request); + + let chain = terminal; + for (let i = wrappers.length - 1; i >= 0; i -= 1) { + const wrapper = wrappers[i]!.fn; + const next = chain; + chain = async (req) => await wrapper(req, next); + } + return chain(request); + } + + applyMatchingRoutes(baseTable: MatchingRequestTable): MatchingRequestTable { + if (this.#matchingHandlers.size === 0 && this.#matchingWrappers.size === 0) { + return baseTable; + } + const merged = new Map(baseTable); + + for (const [method, custom] of this.#matchingHandlers) { + merged.set(method, (request, session) => custom.fn({ + method, + params: request.params, + userId: session.authenticatedUserId(), + })); + } + + for (const [method, wrappers] of this.#matchingWrappers) { + const original = merged.get(method); + merged.set(method, (request, session) => { + const baseFn = (req: ModMatchingRequest): Record => ( + original ? original({ ...request, params: req.params }, session) : {} + ); + let chain = baseFn; + for (let i = wrappers.length - 1; i >= 0; i -= 1) { + const wrap = wrappers[i]!.fn; + const next = chain; + chain = (req) => wrap(req, next); + } + return chain({ + method, + params: request.params, + userId: session.authenticatedUserId(), + }); + }); + } + + return merged; + } + + httpService(): ModHttpService { + return new ModHttpService(this.#httpRoutes); + } + + #createContext(mod: DiscoveredMod, options: RuntimeInitOptions): WtoServerModContext { + const modId = mod.manifest.id; + return { + apiVersion: MOD_API_VERSION, + manifest: mod.manifest, + modDir: mod.rootDir, + gameFolder: options.gameFolder, + dataFolder: options.dataFolder, + port: options.port, + logger: { + info: (message) => options.report(`[mod:${modId}] ${message}`), + warn: (message) => options.report(`[mod:${modId}] WARN: ${message}`), + error: (message) => options.report(`[mod:${modId}] ERROR: ${message}`), + }, + storage: createModStorage(options.dataFolder, modId), + hooks: { + onDatasetsLoaded: (fn) => { this.#onDatasetsLoaded.push({ modId, fn }); }, + onCataloguesReady: (fn) => { this.#onCataloguesReady.push({ modId, fn }); }, + onServerListening: (fn) => { this.#onServerListening.push({ modId, fn }); }, + onServerClosing: (fn) => { this.#onServerClosing.push({ modId, fn }); }, + profile: { + onRefresh: (fn) => { this.#onProfileRefresh.push({ modId, fn }); }, + }, + battle: { + onBeforeMatchmake: (fn) => { this.#onBeforeMatchmake.push({ modId, fn }); }, + onLiveFact: (fn) => { this.#onLiveFact.push({ modId, fn }); }, + onAfterSettle: (fn) => { this.#onAfterSettle.push({ modId, fn }); }, + }, + }, + routes: { + char: { + register: (action, fn) => { this.#charHandlers.set(action, { modId, fn }); }, + wrap: (action, fn) => { + const list = this.#charWrappers.get(action) ?? []; + list.push({ modId, fn }); + this.#charWrappers.set(action, list); + }, + }, + matching: { + register: (method, fn) => { this.#matchingHandlers.set(method, { modId, fn }); }, + wrap: (method, fn) => { + const list = this.#matchingWrappers.get(method) ?? []; + list.push({ modId, fn }); + this.#matchingWrappers.set(method, list); + }, + }, + http: { + register: (subPath: string, handler: ModHttpHandler) => { + this.#httpRoutes.push(buildModHttpRoute(modId, subPath, handler)); + }, + }, + }, + }; + } +} + +function resolveModExport(mod: Record): WtoServerMod | undefined { + const def = mod.default; + if (def && typeof def === 'object' && typeof (def as Record).setup === 'function') { + return def as WtoServerMod; + } + if (typeof def === 'function') { + return { setup: def as WtoServerMod['setup'] }; + } + if (typeof mod.setup === 'function') { + return { setup: mod.setup as WtoServerMod['setup'] }; + } + return undefined; +} + +function formatError(error: unknown): string { + return error instanceof Error ? error.stack ?? error.message : String(error); +} diff --git a/apps/server/src/profiles-setup.ts b/apps/server/src/profiles-setup.ts index 594c133..afccb06 100644 --- a/apps/server/src/profiles-setup.ts +++ b/apps/server/src/profiles-setup.ts @@ -5,6 +5,7 @@ * (with the modifications the mission support planes' presets need) and the free repair over time (repair/repair-over-time.ts) kept up to date and persisted on * every read or write. */ +import type { BlkBlock } from '@wto/blk'; import type { AccountStore } from './accounts/account-store.ts'; import type { ClanStore } from './clans/clan-store.ts'; import type { DatasetCache } from './game-data/datasets/dataset-cache.ts'; @@ -50,6 +51,7 @@ export function setUpProfiles( tuning: Tuning, sync?: ProfileSyncContext, vehicles: readonly CatalogueVehicle[] = datasets.load(vehicleCatalogue), + onProfileRefresh?: (profile: BlkBlock, userId: string) => void, ): ProfileServices { const startingContent: StartingContent = { reserveVehicles: datasets.load(reserveVehicles), @@ -70,6 +72,7 @@ export function setUpProfiles( removeExpiredItems(profile, serverTimeNow()); repairVehiclesOverTime(profile, repair, serverTimeNow()); trimUserLogs(profile, tuning.limits.userLogsKept); + onProfileRefresh?.(profile, userId); }); return { profiles, research, equipment, repair }; } diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index ae8c1f6..9a2192c 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -1,8 +1,9 @@ /** - * Assemble the local server: data layer, save layer, rules, + * Assemble the local server: data layer, save layer, rules, experimental additive mod runtime, * protocol-layer services, and the single loopback listening port. */ import type { Server } from 'node:net'; +import type { DiscoveredMod, ServerModDatasetsView } from '@wto/mods'; import { AccountStore } from './accounts/account-store.ts'; import { RegistrationService } from './accounts/registration-service.ts'; import { BattleEconomy } from './battle/battle-economy.ts'; @@ -16,7 +17,7 @@ import { CloudSettingsStore } from './cloud-settings/cloud-settings-store.ts'; import { CrewSkillCatalogue } from './crew/crew-skill-rules.ts'; import { DecorShop } from './decor/decor-purchase.ts'; import { DownloadableContentService } from './downloadable-content/downloadable-content-service.ts'; -import { battleEconomy } from './game-data/datasets/battle-economy.ts'; +import { battleEconomy, type BattleEconomyData } from './game-data/datasets/battle-economy.ts'; import { battleSpawnRules } from './game-data/datasets/battle-spawn-rules.ts'; import { researchEfficiency } from './game-data/datasets/research-efficiency.ts'; import { ResearchEfficiency } from './research/research-efficiency.ts'; @@ -31,11 +32,11 @@ import { decorCatalogue } from './game-data/datasets/decor-catalogue.ts'; import { externalItemSources } from './game-data/datasets/external-item-sources.ts'; import { flightModelPresets } from './game-data/datasets/flight-model-presets.ts'; import { itemCatalogue } from './game-data/datasets/item-catalogue.ts'; -import { multiplayerMissions } from './game-data/datasets/multiplayer-missions.ts'; +import { multiplayerMissions, type MultiplayerMissions } from './game-data/datasets/multiplayer-missions.ts'; import { shopCountries } from './game-data/datasets/shop-countries.ts'; import { storeBundles } from './game-data/datasets/store-bundles.ts'; import { uiLabels, type UiLabels } from './game-data/datasets/ui-labels.ts'; -import { unitNames } from './game-data/datasets/unit-names.ts'; +import { unitNames, type UnitNamesMap } from './game-data/datasets/unit-names.ts'; import { unlockPrices } from './game-data/datasets/unlock-prices.ts'; import { vehicleCatalogue, type CatalogueVehicle } from './game-data/datasets/vehicle-catalogue.ts'; import { webIcons } from './game-data/datasets/web-icons.ts'; @@ -49,6 +50,7 @@ import { ItemCatalogue } from './items/item-catalogue.ts'; import { LoginService } from './login/login-service.ts'; import { matchingRequests } from './matching/matching-requests.ts'; import type { MatchingService } from './matching/matching-service.ts'; +import { ServerModRuntime } from './mods/server-mod-runtime.ts'; import { setUpProfiles } from './profiles-setup.ts'; import { createPortListener } from './transport/port-listener.ts'; import { Router } from './transport/router.ts'; @@ -67,39 +69,100 @@ export interface ServerOptions { /** Accounts, saves and logs. */ readonly dataFolder: string; readonly port: number; - /** Start-up progress lines (static data extraction, game modes). */ + /** Start-up progress lines (static data extraction, game modes, mod loading). */ readonly report?: (line: string) => void; /** Whether to write traffic logs under `/logs`; defaults to true. */ readonly loggingEnabled?: boolean; + /** Ordered list of enabled additive mods to load for this session. */ + readonly mods?: readonly DiscoveredMod[]; } export const LOOPBACK = '127.0.0.1'; export interface RunningServer { readonly logFolder: string; + readonly loadedModIds: readonly string[]; close(): Promise; } export async function startServer(options: ServerOptions): Promise { const report = options.report ?? (() => {}); + const enabledMods = options.mods ?? []; + const modRuntime = await ServerModRuntime.load({ + mods: enabledMods, + gameFolder: options.gameFolder, + dataFolder: options.dataFolder, + port: options.port, + report, + }); + const gameFiles = new GameFiles(options.gameFolder); // Static data and stores first, before the port opens. const datasets = new DatasetCache(options.dataFolder, gameFiles, report); - const tuning = loadTuning(options.dataFolder, report); + const tuning = loadTuning(options.dataFolder, report, enabledMods); + + const mutableDatasets = new Map(); + const vehiclesList: CatalogueVehicle[] = [...datasets.load(vehicleCatalogue)]; + const rawMissions = datasets.load(multiplayerMissions); + const missionsObj: MultiplayerMissions = { + categories: [...rawMissions.categories], + missions: { ...rawMissions.missions }, + }; + const spawnRulesObj = datasets.load(battleSpawnRules); + const economyDataObj: BattleEconomyData = { ...datasets.load(battleEconomy), vehicles: { ...datasets.load(battleEconomy).vehicles } }; + const labelsObj: UiLabels = { ...datasets.load(uiLabels) }; + const localizedUnitNamesObj: UnitNamesMap = { ...datasets.load(unitNames) }; + + mutableDatasets.set('vehicle-catalogue', vehiclesList); + mutableDatasets.set('multiplayer-missions', missionsObj); + mutableDatasets.set('battle-spawn-rules', spawnRulesObj); + mutableDatasets.set('battle-economy', economyDataObj); + mutableDatasets.set('ui-labels', labelsObj); + mutableDatasets.set('unit-names', localizedUnitNamesObj); + + const datasetsView: ServerModDatasetsView = { + vehicles: vehiclesList, + battleEconomy: economyDataObj as unknown as Record, + battleSpawnRules: spawnRulesObj, + multiplayerMissions: missionsObj as unknown as Record, + uiLabels: labelsObj as unknown as Record, + unitNames: localizedUnitNamesObj as unknown as Record, + get: (id: string) => mutableDatasets.get(id) as T | undefined, + set: (id: string, value: unknown) => { mutableDatasets.set(id, value); }, + }; + await modRuntime.runDatasetsLoaded(datasetsView); + + const vehicles = (mutableDatasets.get('vehicle-catalogue') as readonly CatalogueVehicle[]) ?? vehiclesList; + const missions = (mutableDatasets.get('multiplayer-missions') as MultiplayerMissions) ?? missionsObj; + const spawnRules = (mutableDatasets.get('battle-spawn-rules') as typeof spawnRulesObj) ?? spawnRulesObj; + const economyData = (mutableDatasets.get('battle-economy') as BattleEconomyData) ?? economyDataObj; + const labels = (mutableDatasets.get('ui-labels') as UiLabels) ?? labelsObj; + const localizedUnitNames = (mutableDatasets.get('unit-names') as UnitNamesMap) ?? localizedUnitNamesObj; + const gameModes = new GameModes( - datasets.load(multiplayerMissions), datasets.load(shopCountries), report, tuning.battle.fixedAirRealisticMaxMrank, + missions, datasets.load(shopCountries), report, tuning.battle.fixedAirRealisticMaxMrank, ); const accounts = new AccountStore(options.dataFolder); const clans = new ClanStore(options.dataFolder, tuning.clans); const cloudSettings = new CloudSettingsStore(options.dataFolder); - const vehicles = datasets.load(vehicleCatalogue); - const spawnRules = datasets.load(battleSpawnRules); - const economyData = datasets.load(battleEconomy); const efficiencyData = datasets.load(researchEfficiency); const streakDefinitions = datasets.load(battleStreaks); - const labels = datasets.load(uiLabels); - const { profiles, research, equipment, repair } = setUpProfiles(options.dataFolder, gameFiles, datasets, tuning, { accounts, clans }, vehicles); - const { clanEconomy: squadronEconomy, ...catalogues } = loadDomainCatalogues(datasets, tuning, vehicles, labels); + const { profiles, research, equipment, repair } = setUpProfiles( + options.dataFolder, + gameFiles, + datasets, + tuning, + { accounts, clans }, + vehicles, + (profile, userId) => modRuntime.runProfileRefresh(profile, userId), + ); + const { clanEconomy: squadronEconomy, ...catalogues } = loadDomainCatalogues( + datasets, + tuning, + vehicles, + labels, + localizedUnitNames, + ); const storeProducts = catalogues.store.allProducts(); const artwork = new GameArtwork(options.gameFolder, { vehicles: storeProducts.flatMap((product) => product.vehicles?.map((vehicle) => vehicle.name) ?? []), @@ -112,6 +175,9 @@ export async function startServer(options: ServerOptions): Promise matching?.broadcastNotify('mrpc.generic_notify', { from: 'inventory', func: 'changed' }); + const notifyUser = (userId: string, eventName: string, payload: Record) => { + matching?.notifyUser(userId, eventName, payload); + }; const battleSessions = new BattleSessionStore(tuning.limits.battleSessionsKept); const battleMatchmaker = new BattleMatchmaker(gameModes, vehicles, battleSessions, tuning.battle, spawnRules, botAircraftLoadouts); const economy = new BattleEconomy( @@ -124,7 +190,31 @@ export async function startServer(options: ServerOptions): Promise>, + gameModes, + profiles, + accounts, + research, + equipment, + repair, + store: catalogues.store, + inventory: catalogues.inventory, + trophies: catalogues.trophies, + items: catalogues.items, + crew: catalogues.crew, + decor: catalogues.decor, + unlocks: catalogues.unlocks, + clans, + battleMatchmaker, + battleEconomy: economy, + battleStreaks: streaks, + notifyInventoryChanged, + notifyUser, + }); + const router = new Router([ + modRuntime.httpService(), webUi, new RegistrationService(accounts), new StoreService(accounts, profiles, catalogues.store, tuning.redeemCodes, options.port), @@ -140,44 +230,69 @@ export async function startServer(options: ServerOptions): Promise modRuntime.runBattleAfterSettle(ctx), + }, notifyInventoryChanged, - })), + }), modRuntime), new DownloadableContentService(), ]); const log = new TrafficLog(options.dataFolder, options.loggingEnabled ?? true); + const matchingTable = modRuntime.applyMatchingRoutes(matchingRequests({ + gameModes, + accounts, + battle: { + gameModes, + profiles, + matchmaker: battleMatchmaker, + sessions: battleSessions, + economy, + notifyLaunch: (userId, payload) => matching?.notifyUser(userId, 'mrpc.generic_notify', payload), + onBeforeMatchmake: (ctx) => modRuntime.runBattleBeforeMatchmake(ctx), + }, + battleLive: { + sessions: battleSessions, + liveLogs: new BattleLiveLogs(tuning.limits.battleSessionsKept), + streaks, + supportPlanes, + onLiveFact: (ctx) => modRuntime.runBattleLiveFact(ctx), + }, + })); const listener = createPortListener( router, - matchingRequests({ - gameModes, - accounts, - battle: { - gameModes, - profiles, - matchmaker: battleMatchmaker, - sessions: battleSessions, - economy, - notifyLaunch: (userId, payload) => matching?.notifyUser(userId, 'mrpc.generic_notify', payload), - }, - battleLive: { sessions: battleSessions, liveLogs: new BattleLiveLogs(tuning.limits.battleSessionsKept), streaks, supportPlanes }, - }), + matchingTable, log, loadOrCreateCredentials(options.dataFolder), ); matching = listener.matching; await listen(listener.server, options.port); + await modRuntime.runServerListening(options.port); return { logFolder: log.folder, - close: () => new Promise((resolve) => { - listener.server.close(() => resolve()); - listener.destroyConnections(); - }), + loadedModIds: modRuntime.loadedModIds, + close: async () => { + await modRuntime.runServerClosing(); + await new Promise((resolve) => { + listener.server.close(() => resolve()); + listener.destroyConnections(); + }); + }, }; } -function loadDomainCatalogues(datasets: DatasetCache, tuning: Tuning, vehicles: readonly CatalogueVehicle[], labels: UiLabels) { +function loadDomainCatalogues( + datasets: DatasetCache, + tuning: Tuning, + vehicles: readonly CatalogueVehicle[], + labels: UiLabels, + localizedUnitNames: UnitNamesMap, +) { const classicItemDefs = datasets.load(itemCatalogue); - const localizedUnitNames = datasets.load(unitNames); return { crew: new CrewSkillCatalogue(datasets.load(crewSkillData)), decor: new DecorShop(datasets.load(decorCatalogue)), diff --git a/apps/server/src/store/store-pack-ids.ts b/apps/server/src/store/store-pack-ids.ts index c8b17c7..df62f77 100644 --- a/apps/server/src/store/store-pack-ids.ts +++ b/apps/server/src/store/store-pack-ids.ts @@ -6,9 +6,14 @@ * `bundles/guid` registers a GUID for its id, so the build must register every pack this server * will sell from the same data folder. */ +import type { DiscoveredMod } from '@wto/mods'; import { tuningFiles } from '../tuning/tuning-loader.ts'; import { readStoreTuning } from './store-tuning.ts'; -export function multiVehiclePackIds(dataFolder: string, report: (line: string) => void): string[] { - return readStoreTuning(tuningFiles(dataFolder, report).read('store')).multiVehiclePacks.map((pack) => pack.id); +export function multiVehiclePackIds( + dataFolder: string, + report: (line: string) => void, + mods: readonly DiscoveredMod[] = [], +): string[] { + return readStoreTuning(tuningFiles(dataFolder, report, undefined, mods).read('store')).multiVehiclePacks.map((pack) => pack.id); } diff --git a/apps/server/src/tuning/tuning-loader.ts b/apps/server/src/tuning/tuning-loader.ts index ed2d795..7218328 100644 --- a/apps/server/src/tuning/tuning-loader.ts +++ b/apps/server/src/tuning/tuning-loader.ts @@ -1,16 +1,21 @@ /** - * Load one tuning file: the defaults shipped in - * apps/server/tuning/.jsonc, with /tuning/.jsonc laid - * over them field by field when the player or a developer put one there. Objects merge key - * by key; any other value (numbers, texts, lists) in the override replaces the default. + * Load one tuning file with multi-layer overrides: + * shipped defaults (`apps/server/tuning/.jsonc`) + * -> each enabled mod's `/.jsonc` in load order + * -> player overrides (`/tuning/.jsonc`). + * + * Objects merge key by key; plain lists replace the base list; `{ "$listOps": [...] }` + * performs additive append/prepend/upsertBy/removeBy operations across layers. */ import { existsSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { parseJsonc } from '@wto/jsonc'; +import { mergeTuningLayer, type DiscoveredMod } from '@wto/mods'; import { TuningError, TuningReader } from './tuning-reader.ts'; const DEFAULTS_FOLDER = fileURLToPath(new URL('../../tuning/', import.meta.url)); +const DEFAULT_MOD_TUNING_DIR = 'server/tuning'; export interface TuningFiles { /** The merged content of .jsonc, ready for typed reads. */ @@ -21,19 +26,35 @@ export function tuningFiles( dataFolder: string | null, report: (line: string) => void, proposed?: ReadonlyMap>, + mods: readonly DiscoveredMod[] = [], ): TuningFiles { const overridesFolder = dataFolder === null ? null : join(dataFolder, 'tuning'); return { read(name: string): TuningReader { const fileName = `${name}.jsonc`; - const defaults = parseFile(join(DEFAULTS_FOLDER, fileName)); + let merged = parseFile(join(DEFAULTS_FOLDER, fileName)); + + for (const mod of mods) { + const modTuningDir = mod.manifest.server?.tuning ?? DEFAULT_MOD_TUNING_DIR; + const modFilePath = join(mod.rootDir, ...modTuningDir.split('/'), fileName); + if (!existsSync(modFilePath)) continue; + report(`tuning ${fileName}: applying mod "${mod.manifest.id}" overrides`); + try { + merged = mergeTuningLayer(merged, parseFile(modFilePath)); + } catch (error) { + throw new TuningError( + `mod "${mod.manifest.id}" tuning ${fileName} merge failed: ${error instanceof Error ? error.message : String(error)}`, + ); + } + } + const candidate = proposed?.get(name); - if (candidate) return new TuningReader(fileName, mergeOverride(defaults, candidate)); - if (overridesFolder === null) return new TuningReader(fileName, defaults); + if (candidate) return new TuningReader(fileName, mergeTuningLayer(merged, candidate)); + if (overridesFolder === null) return new TuningReader(fileName, merged); const overridePath = join(overridesFolder, fileName); - if (!existsSync(overridePath)) return new TuningReader(fileName, defaults); + if (!existsSync(overridePath)) return new TuningReader(fileName, merged); report(`tuning ${fileName}: using overrides from ${overridePath}`); - return new TuningReader(fileName, mergeOverride(defaults, parseFile(overridePath))); + return new TuningReader(fileName, mergeTuningLayer(merged, parseFile(overridePath))); }, }; } @@ -45,14 +66,3 @@ function parseFile(path: string): unknown { throw new TuningError(`tuning file ${path} cannot be read: ${error instanceof Error ? error.message : String(error)}`); } } - -function mergeOverride(base: unknown, override: unknown): unknown { - if (!isObject(base) || !isObject(override)) return override; - const merged: Record = { ...base }; - for (const [key, value] of Object.entries(override)) merged[key] = key in base ? mergeOverride(base[key], value) : value; - return merged; -} - -function isObject(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value); -} diff --git a/apps/server/src/tuning/tuning.ts b/apps/server/src/tuning/tuning.ts index e7e7ae8..047859c 100644 --- a/apps/server/src/tuning/tuning.ts +++ b/apps/server/src/tuning/tuning.ts @@ -13,6 +13,7 @@ import { readNewProfileTuning, type NewProfileTuning } from '../profile/new-prof import { readResearchTuning, type ResearchTuning } from '../research/research-tuning.ts'; import { readRedeemTuning, type RedeemTuning } from '../store/redeem-tuning.ts'; import { readStoreTuning, type StoreTuning } from '../store/store-tuning.ts'; +import type { DiscoveredMod } from '@wto/mods'; import { readLimitsTuning, type LimitsTuning } from './limits-tuning.ts'; import { tuningFiles } from './tuning-loader.ts'; @@ -31,8 +32,12 @@ export interface Tuning { readonly limits: LimitsTuning; } -export function loadTuning(dataFolder: string, report: (line: string) => void): Tuning { - const files = tuningFiles(dataFolder, report); +export function loadTuning( + dataFolder: string, + report: (line: string) => void, + mods: readonly DiscoveredMod[] = [], +): Tuning { + const files = tuningFiles(dataFolder, report, undefined, mods); return { store: readStoreTuning(files.read('store')), redeemCodes: readRedeemTuning(files.read('redeem-codes')), diff --git a/packages/mods/src/server-api.ts b/packages/mods/src/server-api.ts index 1ac4dca..91d1d99 100644 --- a/packages/mods/src/server-api.ts +++ b/packages/mods/src/server-api.ts @@ -34,7 +34,7 @@ export interface ServerModDatasetsView { readonly vehicles: unknown[]; readonly battleEconomy: Record; readonly battleSpawnRules: unknown; - readonly multiplayerMissions: unknown[]; + readonly multiplayerMissions: Record; readonly uiLabels: Record; readonly unitNames: Record; /** Escape hatch: read or replace any dataset object by its dataset id. */ From dbc21182a2bcad113ff498b4b498ccb32dc68ece Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Thu, 3 Dec 2026 00:34:07 +0800 Subject: [PATCH 04/12] feat(launcher): add Mods page, per-client presets, custom repo folder, and launch integration --- apps/launcher/package.json | 1 + apps/launcher/src/main/ipc/handlers.ts | 55 ++ .../main/services/launch/launch-controller.ts | 23 +- .../src/main/services/launch/local-server.ts | 13 +- .../main/services/launch/ordinary-launch.ts | 9 +- .../src/main/services/mods/mods-service.ts | 351 +++++++++++ .../src/main/workers/build-protocol.ts | 2 + .../launcher/src/main/workers/build-worker.ts | 67 ++- .../src/main/workers/server-worker.ts | 30 +- apps/launcher/src/renderer/src/App.tsx | 11 +- .../src/renderer/src/i18n/locales/en.json | 184 +++++- .../src/renderer/src/i18n/locales/zh-CN.json | 184 +++++- .../src/renderer/src/pages/mods/ModsPage.tsx | 565 ++++++++++++++++++ .../src/renderer/src/shell/navigation.ts | 19 +- .../src/renderer/src/styles/pages.css | 324 ++++++++++ apps/launcher/src/shared/errors.ts | 5 + apps/launcher/src/shared/ipc/channels.ts | 2 + apps/launcher/src/shared/ipc/contract.ts | 45 ++ apps/launcher/src/shared/schemas/mods.ts | 87 +++ apps/launcher/src/shared/schemas/settings.ts | 3 + scripts/build-windows-installer.ts | 2 +- 21 files changed, 1961 insertions(+), 21 deletions(-) create mode 100644 apps/launcher/src/main/services/mods/mods-service.ts create mode 100644 apps/launcher/src/renderer/src/pages/mods/ModsPage.tsx create mode 100644 apps/launcher/src/shared/schemas/mods.ts diff --git a/apps/launcher/package.json b/apps/launcher/package.json index 5b1f07f..94ae17b 100644 --- a/apps/launcher/package.json +++ b/apps/launcher/package.json @@ -14,6 +14,7 @@ }, "dependencies": { "@fontsource/roboto-condensed": "^5.3.0", + "@wto/mods": "*", "@wto/patcher": "*", "@wto/server": "*", "fflate": "^0.8.2", diff --git a/apps/launcher/src/main/ipc/handlers.ts b/apps/launcher/src/main/ipc/handlers.ts index 2260df0..f08af21 100644 --- a/apps/launcher/src/main/ipc/handlers.ts +++ b/apps/launcher/src/main/ipc/handlers.ts @@ -17,6 +17,19 @@ import { canonicalCopyPath, copyFolderMissing, createCopyDraft, hydrateCopiesSta import { readInstalledLab } from '../services/launch/lab-handoff.ts'; import { getLaunchState, launchInProgress, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts'; import { activePatchSet, applyPackUpdate, checkPackUpdate, revertToBundledPatchSet } from '../services/patch-pack/pack-update.ts'; +import { + applyModPreset, + autoSortMods, + deleteModPreset, + exportModPreset, + getModsState, + importModPreset, + openModsFolder, + saveModPreset, + setModEnabled, + setModsFolder, + setModsOrder, +} from '../services/mods/mods-service.ts'; import { resourcePaths } from '../services/resources/resource-paths.ts'; import { changeSaveAccount, changeSaveResearch, copyOnlineData, createSave, discoverOnlineData, exportSave, getSaveAvatarChoices, getSaveAvatarPreview, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts'; import { broadcast, handle } from './register.ts'; @@ -175,6 +188,48 @@ export function registerIpcHandlers(): void { handle('tuning:get', ({ copyId }) => getCopyTuning(copyId)); handle('tuning:update', ({ copyId, patch }) => updateCopyTuning(copyId, patch)); + const requireModsWritable = (): void => { + if (launchInProgress() || maintenanceInProgress()) throw new AppError('mods_read_only'); + }; + handle('mods:getState', ({ copyId }) => getModsState(copyId)); + handle('mods:setEnabled', ({ copyId, modId, enabled }) => { + requireModsWritable(); + return setModEnabled(copyId, modId, enabled); + }); + handle('mods:setOrder', ({ copyId, order }) => { + requireModsWritable(); + return setModsOrder(copyId, order); + }); + handle('mods:autoSort', ({ copyId }) => { + requireModsWritable(); + return autoSortMods(copyId); + }); + handle('mods:savePreset', ({ copyId, name, overwriteId }) => { + requireModsWritable(); + return saveModPreset(copyId, name, overwriteId); + }); + handle('mods:applyPreset', ({ copyId, presetId }) => { + requireModsWritable(); + return applyModPreset(copyId, presetId); + }); + handle('mods:deletePreset', ({ copyId, presetId }) => { + requireModsWritable(); + return deleteModPreset(copyId, presetId); + }); + handle('mods:exportPreset', ({ copyId, presetId }, sender) => + exportModPreset(copyId, presetId, BrowserWindow.fromWebContents(sender))); + handle('mods:importPreset', ({ copyId }, sender) => { + requireModsWritable(); + return importModPreset(copyId, BrowserWindow.fromWebContents(sender)); + }); + handle('mods:openFolder', () => openModsFolder()); + handle('mods:setFolder', async ({ copyId, path }) => { + requireModsWritable(); + const state = await setModsFolder(copyId, path); + broadcast('event:settings-changed', await getSettings()); + return state; + }); + handle('launch:getState', () => getLaunchState()); handle('launch:getLabInfo', () => readInstalledLab().catch(() => null)); handle('launch:start', () => { diff --git a/apps/launcher/src/main/services/launch/launch-controller.ts b/apps/launcher/src/main/services/launch/launch-controller.ts index cff4d82..235d38f 100644 --- a/apps/launcher/src/main/services/launch/launch-controller.ts +++ b/apps/launcher/src/main/services/launch/launch-controller.ts @@ -11,6 +11,7 @@ import type { Settings } from '@shared/schemas/settings.ts'; import { getSettings } from '../config/settings-store.ts'; import { decalCachePath } from '../install/decals.ts'; import { canonicalCopyPath, copyPathContains, readInstallRecord } from '../install/install-record.ts'; +import { resolveEnabledModsForLaunch } from '../mods/mods-service.ts'; import { resourcePaths } from '../resources/resource-paths.ts'; import { saveBackup } from '../saves/save-archive.ts'; import { buildCopy } from './build-copy.ts'; @@ -108,7 +109,7 @@ async function launch(job: LaunchJob): Promise { job.copyId = record.id; const plan = await planLaunch(job, record, settings); if (plan === null) return; - const { lab, copyPath, stockPath, dataPath, port } = plan; + const { lab, copyPath, stockPath, dataPath, port, modsDir, enabledModIds } = plan; await buildForLaunch(job, record, plan, settings); const publish = (phase: LaunchState['phase'], gameExit?: GameExit): void => { @@ -123,7 +124,15 @@ async function launch(job: LaunchJob): Promise { update(job, { phase: 'ready' }); return; } - const gameExit = await runOrdinaryLaunch(copyPath, dataPath, port, settings, signal, publish); + const gameExit = await runOrdinaryLaunch( + copyPath, + dataPath, + port, + settings, + signal, + publish, + { modsDir, enabledModIds }, + ); update(job, { phase: 'game-exited', gameExit }); } @@ -134,6 +143,8 @@ interface LaunchPlan { readonly dataPath: string; readonly steamLibraryConfirmed: boolean; readonly port: number; + readonly modsDir: string; + readonly enabledModIds: readonly string[]; } async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Settings): Promise { @@ -183,13 +194,15 @@ async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Setti throw new AppError(lab ? 'launch_lab_version' : 'launch_stock_version'); } if (games) throw new AppError('launch_game_running'); + const { modsDir, enabledMods } = await resolveEnabledModsForLaunch(dataPath, copyVersion); + const enabledModIds = enabledMods.map((mod) => mod.manifest.id); const port = await selectPort(requestedPort); - return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port }; + return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port, modsDir, enabledModIds }; } async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, settings: Settings): Promise { const signal = job.stop.signal; - const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed } = plan; + const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed, modsDir, enabledModIds } = plan; if (settings.autoSaveBackups) { for (const { userId } of new AccountStore(dataPath).all()) { signal.throwIfAborted(); @@ -211,6 +224,8 @@ async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: Launc ...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}), hookLogging: settings.loggingEnabled, acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId), + modsDir, + enabledModIds, }, signal, (filesWritten, filesTotal, file) => { writtenFiles = filesWritten; if (!signal.aborted) update(job, { diff --git a/apps/launcher/src/main/services/launch/local-server.ts b/apps/launcher/src/main/services/launch/local-server.ts index 8ea0eee..7c73413 100644 --- a/apps/launcher/src/main/services/launch/local-server.ts +++ b/apps/launcher/src/main/services/launch/local-server.ts @@ -33,13 +33,22 @@ export async function localServerReady(port: number, pid?: number, signal?: Abor } } +export interface StartLocalServerOptions extends Omit { + readonly modsDir?: string; + readonly enabledModIds?: readonly string[]; +} + export async function startLocalServer( - { gameFolder, dataFolder, port, loggingEnabled = true }: Omit, signal: AbortSignal, + { gameFolder, dataFolder, port, loggingEnabled = true, modsDir, enabledModIds }: StartLocalServerOptions, signal: AbortSignal, ): Promise { signal.throwIfAborted(); + const workerArgs = [gameFolder, dataFolder, String(port), loggingEnabled ? '1' : '0']; + if (modsDir && enabledModIds && enabledModIds.length > 0) { + workerArgs.push(modsDir, JSON.stringify(enabledModIds)); + } const worker = utilityProcess.fork( join(import.meta.dirname, 'server-worker.js'), - [gameFolder, dataFolder, String(port), loggingEnabled ? '1' : '0'], + workerArgs, { serviceName: 'WTOffline local server', stdio: 'pipe', diff --git a/apps/launcher/src/main/services/launch/ordinary-launch.ts b/apps/launcher/src/main/services/launch/ordinary-launch.ts index 533b646..ce609ed 100644 --- a/apps/launcher/src/main/services/launch/ordinary-launch.ts +++ b/apps/launcher/src/main/services/launch/ordinary-launch.ts @@ -45,12 +45,19 @@ type OrdinaryPhase = 'starting-server' | 'starting-game' | 'running' | 'server-r export async function runOrdinaryLaunch( copyPath: string, dataPath: string, port: number, settings: Settings, signal: AbortSignal, publish: (phase: OrdinaryPhase, gameExit?: GameExit) => void, + mods?: { readonly modsDir: string; readonly enabledModIds: readonly string[] }, ): Promise { const args = parseLaunchArguments(settings.launchArguments); if (!args) throw new AppError('launch_game_failed'); publish('starting-server'); const server = await startLocalServer( - { gameFolder: copyPath, dataFolder: dataPath, port, loggingEnabled: settings.loggingEnabled }, + { + gameFolder: copyPath, + dataFolder: dataPath, + port, + loggingEnabled: settings.loggingEnabled, + ...(mods && mods.enabledModIds.length > 0 ? { modsDir: mods.modsDir, enabledModIds: mods.enabledModIds } : {}), + }, signal, ); const stop = new AbortController(); diff --git a/apps/launcher/src/main/services/mods/mods-service.ts b/apps/launcher/src/main/services/mods/mods-service.ts new file mode 100644 index 0000000..fca9e9b --- /dev/null +++ b/apps/launcher/src/main/services/mods/mods-service.ts @@ -0,0 +1,351 @@ +import { randomUUID } from 'node:crypto'; +import { mkdir, readFile, stat, writeFile } from 'node:fs/promises'; +import { isAbsolute, join } from 'node:path'; +import { app, BrowserWindow, dialog, shell } from 'electron'; +import { + computeAutoSortOrder, + discoverMods, + emptyClientModsConfig, + MOD_API_VERSION, + normalizeClientModsConfig, + resolveModLoadOrder, + type ClientModsConfig, + type DiscoveredMod, + type ModPreset, +} from '@wto/mods'; +import { AppError } from '@shared/errors.ts'; +import type { InstallRecord } from '@shared/schemas/install.ts'; +import { ModPresetTransferSchema, type ModListItem, type ModsStateView } from '@shared/schemas/mods.ts'; +import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts'; +import { getSettings, updateSettings } from '../config/settings-store.ts'; +import { listCopies } from '../install/install-record.ts'; + +const CLIENT_MODS_CONFIG_FILE = 'mods-config.json'; + +export function defaultModsFolder(): string { + return join(app.getPath('userData'), 'mods'); +} + +export async function resolveModsFolder(): Promise<{ readonly modsDir: string; readonly defaultModsDir: string; readonly isCustomModsDir: boolean }> { + const settings = await getSettings(); + const defaultModsDir = defaultModsFolder(); + const isCustomModsDir = settings.modsFolder !== null; + const modsDir = settings.modsFolder ?? defaultModsDir; + await mkdir(modsDir, { recursive: true }); + return { modsDir, defaultModsDir, isCustomModsDir }; +} + +export async function openModsFolder(): Promise { + const { modsDir } = await resolveModsFolder(); + const failure = await shell.openPath(modsDir); + if (failure) console.warn('[mods] opening the mods folder failed:', modsDir, failure); +} + +export async function getModsState(copyId: string): Promise { + const copy = await requireCopy(copyId); + return buildModsStateView(copy); +} + +export async function setModEnabled(copyId: string, modId: string, enabled: boolean): Promise { + const copy = await requireCopy(copyId); + const { modsDir } = await resolveModsFolder(); + const discovered = discoverMods(modsDir); + const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods); + const next: ClientModsConfig = { + ...current, + activePresetId: null, + enabled: { ...current.enabled, [modId]: enabled }, + }; + await writeClientModsConfig(copy.dataPath, next); + return buildModsStateView(copy, next); +} + +export async function setModsOrder(copyId: string, order: readonly string[]): Promise { + const copy = await requireCopy(copyId); + const { modsDir } = await resolveModsFolder(); + const discovered = discoverMods(modsDir); + const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods); + const next = normalizeClientModsConfig({ ...current, activePresetId: null, order }, discovered.mods); + await writeClientModsConfig(copy.dataPath, next); + return buildModsStateView(copy, next); +} + +export async function autoSortMods(copyId: string): Promise { + const copy = await requireCopy(copyId); + const { modsDir } = await resolveModsFolder(); + const discovered = discoverMods(modsDir); + const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods); + const sortedOrder = computeAutoSortOrder(discovered.mods, current.order); + const next: ClientModsConfig = { + ...current, + activePresetId: null, + order: sortedOrder, + }; + await writeClientModsConfig(copy.dataPath, next); + return buildModsStateView(copy, next); +} + +export async function saveModPreset(copyId: string, name: string, overwriteId?: string): Promise { + const copy = await requireCopy(copyId); + const { modsDir } = await resolveModsFolder(); + const discovered = discoverMods(modsDir); + const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods); + const now = new Date().toISOString(); + + let presets: ModPreset[]; + let presetId: string; + if (overwriteId && current.presets.some((preset) => preset.id === overwriteId)) { + presetId = overwriteId; + presets = current.presets.map((preset) => ( + preset.id === overwriteId + ? { id: preset.id, name, order: [...current.order], enabled: { ...current.enabled }, updatedAt: now } + : preset + )); + } else { + presetId = randomUUID(); + presets = [ + ...current.presets, + { id: presetId, name, order: [...current.order], enabled: { ...current.enabled }, updatedAt: now }, + ]; + } + + const next: ClientModsConfig = { + ...current, + activePresetId: presetId, + presets, + }; + await writeClientModsConfig(copy.dataPath, next); + return buildModsStateView(copy, next); +} + +export async function applyModPreset(copyId: string, presetId: string): Promise { + const copy = await requireCopy(copyId); + const { modsDir } = await resolveModsFolder(); + const discovered = discoverMods(modsDir); + const current = normalizeClientModsConfig(await readClientModsConfig(copy.dataPath), discovered.mods); + const preset = current.presets.find((item) => item.id === presetId); + if (!preset) throw new AppError('mods_preset_invalid'); + + const next = normalizeClientModsConfig({ + ...current, + order: preset.order, + enabled: preset.enabled, + activePresetId: preset.id, + }, discovered.mods); + await writeClientModsConfig(copy.dataPath, next); + return buildModsStateView(copy, next); +} + +export async function deleteModPreset(copyId: string, presetId: string): Promise { + const copy = await requireCopy(copyId); + const current = await readClientModsConfig(copy.dataPath); + const next: ClientModsConfig = { + ...current, + activePresetId: current.activePresetId === presetId ? null : current.activePresetId, + presets: current.presets.filter((preset) => preset.id !== presetId), + }; + await writeClientModsConfig(copy.dataPath, next); + return buildModsStateView(copy, next); +} + +export async function exportModPreset( + copyId: string, + presetId: string, + window: BrowserWindow | null, +): Promise<{ readonly path: string | null }> { + const copy = await requireCopy(copyId); + const current = await readClientModsConfig(copy.dataPath); + const preset = current.presets.find((item) => item.id === presetId); + if (!preset) throw new AppError('mods_preset_invalid'); + + const safeName = preset.name.replace(/[^A-Za-z0-9\u4e00-\u9fa5._-]+/g, '-').replace(/^-+|-+$/g, '') || 'preset'; + const dialogOptions = { + defaultPath: `${safeName}.wto-mods-preset.json`, + filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }], + }; + const choice = window + ? await dialog.showSaveDialog(window, dialogOptions) + : await dialog.showSaveDialog(dialogOptions); + if (choice.canceled || !choice.filePath) return { path: null }; + + const payload = { + format: 1 as const, + name: preset.name, + order: [...preset.order], + enabled: { ...preset.enabled }, + }; + await writeFile(choice.filePath, JSON.stringify(payload, null, 2) + '\n', 'utf8'); + return { path: choice.filePath }; +} + +export async function importModPreset( + copyId: string, + window: BrowserWindow | null, +): Promise<{ readonly imported: boolean; readonly state: ModsStateView }> { + const copy = await requireCopy(copyId); + const dialogOptions = { + properties: ['openFile'] as Array<'openFile'>, + filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }], + }; + const choice = window + ? await dialog.showOpenDialog(window, dialogOptions) + : await dialog.showOpenDialog(dialogOptions); + if (choice.canceled || !choice.filePaths[0]) { + return { imported: false, state: await buildModsStateView(copy) }; + } + + let parsedRaw: unknown; + try { + parsedRaw = JSON.parse(await readFile(choice.filePaths[0], 'utf8')) as unknown; + } catch { + throw new AppError('mods_preset_invalid'); + } + const validated = ModPresetTransferSchema.safeParse(parsedRaw); + if (!validated.success) throw new AppError('mods_preset_invalid'); + + const current = await readClientModsConfig(copy.dataPath); + const newPreset: ModPreset = { + id: randomUUID(), + name: validated.data.name, + order: validated.data.order, + enabled: validated.data.enabled, + updatedAt: new Date().toISOString(), + }; + const next: ClientModsConfig = { + ...current, + presets: [...current.presets, newPreset], + }; + await writeClientModsConfig(copy.dataPath, next); + return { imported: true, state: await buildModsStateView(copy, next) }; +} + +export async function setModsFolder(copyId: string, folderPath: string | null): Promise { + if (folderPath !== null) { + if (!isAbsolute(folderPath)) throw new AppError('mods_folder_invalid'); + try { + await mkdir(folderPath, { recursive: true }); + const info = await stat(folderPath); + if (!info.isDirectory()) throw new AppError('mods_folder_invalid'); + } catch (error) { + if (error instanceof AppError) throw error; + throw new AppError('mods_folder_invalid'); + } + } + await updateSettings({ modsFolder: folderPath }); + const copy = await requireCopy(copyId); + return buildModsStateView(copy); +} + +/** Resolve ordered enabled mods for a launch; rejects when blocking dependency/conflict errors exist. */ +export async function resolveEnabledModsForLaunch( + dataPath: string, + gameVersion: string | null, +): Promise<{ readonly modsDir: string; readonly enabledMods: readonly DiscoveredMod[] }> { + const { modsDir } = await resolveModsFolder(); + const discovered = discoverMods(modsDir); + const config = normalizeClientModsConfig(await readClientModsConfig(dataPath), discovered.mods); + const resolved = resolveModLoadOrder(discovered.mods, config, gameVersion); + if (resolved.hasBlockingErrors) { + console.error('[mods] blocking mod issues prevented launch:', resolved.issues.filter((i) => i.severity === 'error')); + throw new AppError('mods_blocking_issues'); + } + return { modsDir, enabledMods: resolved.enabledMods }; +} + +async function buildModsStateView(copy: InstallRecord, preloadedConfig?: ClientModsConfig): Promise { + const { modsDir, defaultModsDir, isCustomModsDir } = await resolveModsFolder(); + const discovered = discoverMods(modsDir); + const rawConfig = preloadedConfig ?? await readClientModsConfig(copy.dataPath); + const config = normalizeClientModsConfig(rawConfig, discovered.mods); + const resolved = resolveModLoadOrder(discovered.mods, config, copy.gameVersion); + + const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod])); + const orderedMods: ModListItem[] = config.order + .map((id) => byId.get(id)) + .filter((mod): mod is DiscoveredMod => mod !== undefined) + .map(toModListItem); + + return { + modsDir, + defaultModsDir, + isCustomModsDir, + apiVersion: MOD_API_VERSION, + mods: orderedMods, + discoveryErrors: [...discovered.errors], + order: [...config.order], + enabled: { ...config.enabled }, + activePresetId: config.activePresetId, + presets: config.presets.map((preset) => ({ + id: preset.id, + name: preset.name, + order: [...preset.order], + enabled: { ...preset.enabled }, + updatedAt: preset.updatedAt, + })), + issues: [...resolved.issues], + hasBlockingErrors: resolved.hasBlockingErrors, + }; +} + +function toModListItem(mod: DiscoveredMod): ModListItem { + return { + id: mod.manifest.id, + folderName: mod.folderName, + rootDir: mod.rootDir, + name: mod.manifest.name, + ...(mod.manifest.description !== undefined ? { description: mod.manifest.description } : {}), + version: mod.manifest.version, + author: mod.manifest.author, + apiVersion: mod.manifest.apiVersion, + gameVersions: [...mod.manifest.gameVersions], + requires: [...mod.manifest.requires], + conflicts: [...mod.manifest.conflicts], + loadAfter: [...mod.manifest.loadAfter], + loadBefore: [...mod.manifest.loadBefore], + badges: [...mod.content.badges], + hasServerScript: mod.content.serverEntry !== undefined, + serverTuningFiles: [...mod.content.serverTuningFiles], + packOperations: [...mod.content.packOperations], + guiPatchCount: mod.content.guiPatchDirs.length, + exePatchCount: mod.content.exePatchDirs.length, + hasClientAddon: mod.content.hasClientAddon, + addonFileCount: mod.content.addonRelativeFiles.length, + clientFileCount: mod.content.clientFiles.length, + hasConfigBlkPatch: mod.content.configBlkPatch !== undefined, + }; +} + +async function requireCopy(copyId: string): Promise { + const copies = await listCopies(); + const copy = copies.copies.find((entry) => entry.id === copyId); + if (!copy) throw new AppError('copy_not_found'); + return copy; +} + +async function readClientModsConfig(dataPath: string): Promise { + const path = join(dataPath, CLIENT_MODS_CONFIG_FILE); + try { + const raw = await readJsonOr(path, null); + if (!raw || typeof raw !== 'object') return emptyClientModsConfig(); + const obj = raw as Partial; + return { + format: 1, + order: Array.isArray(obj.order) ? obj.order.filter((item): item is string => typeof item === 'string') : [], + enabled: obj.enabled && typeof obj.enabled === 'object' ? { ...obj.enabled } : {}, + activePresetId: typeof obj.activePresetId === 'string' ? obj.activePresetId : null, + presets: Array.isArray(obj.presets) ? obj.presets : [], + }; + } catch (error) { + console.warn('[mods] unreadable client mods config, using defaults:', path, error); + return emptyClientModsConfig(); + } +} + +async function writeClientModsConfig(dataPath: string, config: ClientModsConfig): Promise { + try { + await writeJsonAtomic(join(dataPath, CLIENT_MODS_CONFIG_FILE), config); + } catch (error) { + console.error('[mods] writing client mods config failed:', error); + throw new AppError('mods_write_failed'); + } +} diff --git a/apps/launcher/src/main/workers/build-protocol.ts b/apps/launcher/src/main/workers/build-protocol.ts index 4b1f2e1..317e4e7 100644 --- a/apps/launcher/src/main/workers/build-protocol.ts +++ b/apps/launcher/src/main/workers/build-protocol.ts @@ -12,6 +12,8 @@ export interface BuildRequest { readonly decalCache?: string; readonly hookLogging: boolean; readonly acceptedUnavailable: readonly string[]; + readonly modsDir?: string; + readonly enabledModIds?: readonly string[]; } export type BuildCommand = BuildRequest | { readonly kind: 'write' }; diff --git a/apps/launcher/src/main/workers/build-worker.ts b/apps/launcher/src/main/workers/build-worker.ts index dfac45c..94332cd 100644 --- a/apps/launcher/src/main/workers/build-worker.ts +++ b/apps/launcher/src/main/workers/build-worker.ts @@ -1,7 +1,20 @@ import { readFileSync, realpathSync } from 'node:fs'; import { relative } from 'node:path'; import type { MessageEvent } from 'electron'; -import { assertWritableCopy, buildGameCopy, copyPlayerDecalCache, playerDecalCacheProblem, readStockGameFiles, writeGameCopy, type GameCopyFile } from '@wto/patcher'; +import { discoverMods, touchedClientPacks, type DiscoveredMod, type ModdableClientPack } from '@wto/mods'; +import { + assertWritableCopy, + buildGameCopy, + computeModsBuildFingerprint, + copyPlayerDecalCache, + CORE_BUILD_PACKS, + playerDecalCacheProblem, + prepareOptionalStockPacks, + readStockGameFiles, + syncExternalModFiles, + writeGameCopy, + type GameCopyFile, +} from '@wto/patcher'; import { multiVehiclePackIds } from '@wto/server'; import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts'; @@ -9,6 +22,9 @@ let prepared: { readonly request: BuildRequest; readonly files: readonly GameCopyFile[]; readonly decalCache: string | undefined; + readonly enabledMods: readonly DiscoveredMod[]; + readonly optionalPacksInBuild: readonly ModdableClientPack[]; + readonly fingerprint: string; } | null = null; function checkBuildLocation({ stockPath, copyPath, steamLibraryConfirmed }: BuildRequest): void { @@ -31,17 +47,39 @@ function importedDecals(path: string | undefined): string | undefined { return undefined; } +function resolveOrderedMods(modsDir: string | undefined, enabledModIds: readonly string[] | undefined): DiscoveredMod[] { + if (!modsDir || !enabledModIds || enabledModIds.length === 0) return []; + const discovered = discoverMods(modsDir); + const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod])); + const ordered: DiscoveredMod[] = []; + for (const id of enabledModIds) { + const mod = byId.get(id); + if (!mod) throw new Error(`enabled mod "${id}" was not found in ${modsDir}`); + ordered.push(mod); + } + return ordered; +} + function build(request: BuildRequest): void { checkBuildLocation(request); const decalCache = importedDecals(request.decalCache); + const enabledMods = resolveOrderedMods(request.modsDir, request.enabledModIds); + const touchedPacks = touchedClientPacks(enabledMods); + const optionalPacksInBuild = touchedPacks.filter((pack) => !CORE_BUILD_PACKS.has(pack)); + const extraStockPacks = optionalPacksInBuild.length > 0 + ? prepareOptionalStockPacks(request.copyPath, request.stockPath, optionalPacksInBuild) + : undefined; + const result = buildGameCopy({ stock: readStockGameFiles(request.stockPath), patches: request.patches, networkHookLibrary: readFileSync(request.networkHookLibrary), port: request.port, - multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info), + multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info, enabledMods), placeholderDecals: decalCache === undefined, hookLogging: request.hookLogging, + ...(enabledMods.length > 0 ? { mods: enabledMods } : {}), + ...(extraStockPacks ? { extraStockPacks } : {}), }); const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures]; const accepted = new Set(request.acceptedUnavailable); @@ -50,7 +88,19 @@ function build(request: BuildRequest): void { send({ kind: 'failed', error: 'launch_build_unavailable' }); return; } - prepared = { request, files: result.files, decalCache }; + if (result.mods.enabledModIds.length > 0) { + console.info( + `[build] applied ${result.mods.enabledModIds.length} mod(s): ${result.mods.enabledModIds.join(', ')} ` + + `(pack overlays=${result.mods.packOverlays.length}, addons=${result.mods.addonMounts.length}, ` + + `gui=${result.mods.guiPatches.applied.length} ok/${result.mods.guiPatches.failures.length} failed, ` + + `exe=${result.mods.exePatches.applied.length} ok/${result.mods.exePatches.failures.length} failed)`, + ); + for (const failure of [...result.mods.guiPatches.failures, ...result.mods.exePatches.failures]) { + console.warn(`[build] mod "${failure.modId}" patch "${failure.patchId}" skipped: ${failure.reason}`); + } + } + const fingerprint = computeModsBuildFingerprint(enabledMods, request.port, request.patches); + prepared = { request, files: result.files, decalCache, enabledMods, optionalPacksInBuild, fingerprint }; send({ kind: 'prepared', total: prepared.files.length }); } @@ -62,15 +112,22 @@ process.parentPort.on('message', (event: MessageEvent) => { return; } if (!prepared) throw new Error('No build is ready to write.'); - const { request, files, decalCache } = prepared; + const { request, files, decalCache, enabledMods, optionalPacksInBuild, fingerprint } = prepared; prepared = null; checkBuildLocation(request); - const { copyPath } = request; + const { copyPath, stockPath } = request; if (decalCache) copyPlayerDecalCache(decalCache, copyPath); for (const [index, file] of files.entries()) { writeGameCopy(copyPath, [file]); send({ kind: 'progress', written: index + 1, total: files.length, file: file.path }); } + const deployResult = syncExternalModFiles(copyPath, stockPath, enabledMods, optionalPacksInBuild, fingerprint); + for (const warning of deployResult.warnings) { + console.warn(`[mods] skipped "${warning.targetRelPath}" from "${warning.modId}": ${warning.reason}`); + } + if (deployResult.restoredOptionalPacks.length > 0) { + console.info(`[mods] restored stock pack(s): ${deployResult.restoredOptionalPacks.join(', ')}`); + } send({ kind: 'written' }); } catch (error) { console.error('[build] preparing the game copy failed:', error); diff --git a/apps/launcher/src/main/workers/server-worker.ts b/apps/launcher/src/main/workers/server-worker.ts index 90e125c..24aaf99 100644 --- a/apps/launcher/src/main/workers/server-worker.ts +++ b/apps/launcher/src/main/workers/server-worker.ts @@ -1,16 +1,42 @@ +import { discoverMods, type DiscoveredMod } from '@wto/mods'; import { startServer } from '@wto/server'; export type ServerWorkerStatus = 'listening' | 'port-busy' | 'failed'; +function loadOrderedMods(modsDir: string | undefined, enabledJson: string | undefined): DiscoveredMod[] { + if (!modsDir || !enabledJson) return []; + const ids = JSON.parse(enabledJson) as unknown; + if (!Array.isArray(ids) || ids.length === 0) return []; + const discovered = discoverMods(modsDir); + const byId = new Map(discovered.mods.map((mod) => [mod.manifest.id, mod])); + const mods: DiscoveredMod[] = []; + for (const id of ids) { + if (typeof id !== 'string') continue; + const mod = byId.get(id); + if (!mod) throw new Error(`Enabled mod "${id}" not found in ${modsDir}`); + mods.push(mod); + } + return mods; +} + async function serve(): Promise { - const [gameFolder, dataFolder, portText, loggingFlag] = process.argv.slice(2); + const [gameFolder, dataFolder, portText, loggingFlag, modsDir, enabledModIdsJson] = process.argv.slice(2); const port = Number(portText); if (!gameFolder || !dataFolder || !Number.isInteger(port) || port < 1 || port > 65535) { throw new Error('Invalid local server arguments.'); } const loggingEnabled = loggingFlag !== '0'; - const server = await startServer({ gameFolder, dataFolder, port, loggingEnabled, report: console.info }); + const mods = loadOrderedMods(modsDir, enabledModIdsJson); + const server = await startServer({ + gameFolder, + dataFolder, + port, + loggingEnabled, + ...(mods.length > 0 ? { mods } : {}), + report: console.info, + }); if (server.logFolder) console.info('Traffic log:', server.logFolder); + if (server.loadedModIds.length > 0) console.info('Loaded server script mods:', server.loadedModIds.join(', ')); process.parentPort.once('message', () => { void server.close().then(() => process.exit(0)).catch((error: unknown) => { console.error('Could not close the local server:', error); diff --git a/apps/launcher/src/renderer/src/App.tsx b/apps/launcher/src/renderer/src/App.tsx index 1ee6b22..50a4c90 100644 --- a/apps/launcher/src/renderer/src/App.tsx +++ b/apps/launcher/src/renderer/src/App.tsx @@ -22,6 +22,7 @@ import { useInstallWizard } from './pages/install/useInstallWizard.ts'; import { WizardMain } from './pages/install/WizardMain.tsx'; import { WizardSide } from './pages/install/WizardSide.tsx'; import { wizardBar } from './pages/install/wizard-bar.ts'; +import { ModsPage } from './pages/mods/ModsPage.tsx'; import { TuningPage } from './pages/tuning/TuningPage.tsx'; import { SavesPage } from './pages/saves/SavesPage.tsx'; import { DeveloperSettings } from './pages/settings/DeveloperSettings.tsx'; @@ -32,7 +33,7 @@ import { Background } from './shell/Background.tsx'; import { BottomBar } from './shell/BottomBar.tsx'; import type { BarModel } from './shell/bar-model.ts'; import { Footer } from './shell/Footer.tsx'; -import { COPY_SECTIONS, navigate, SAVE_SECTIONS, SETTINGS_SECTIONS, START_ROUTE, TUNING_SECTIONS, type Destination, type Route } from './shell/navigation.ts'; +import { COPY_SECTIONS, MODS_SECTIONS, navigate, SAVE_SECTIONS, SETTINGS_SECTIONS, START_ROUTE, TUNING_SECTIONS, type Destination, type Route } from './shell/navigation.ts'; import { SubNav } from './shell/SubNav.tsx'; import { TitleBar } from './shell/TitleBar.tsx'; import { useBackgrounds } from './shell/useBackgrounds.ts'; @@ -195,6 +196,14 @@ export function App({ info, initialSettings, initialCopies }: AppProps) { :

{t('tuning.noCopy')}

, bar: home, }; + case 'mods': + return { + side: t(`mods.sections.${section}`)} onSelect={(section) => go({ page: 'mods', section })} />, + main: record + ? + :

{t('mods.noCopy')}

, + bar: home, + }; case 'copies': { const side = t(`copies.sections.${section}`)} onSelect={(section) => go({ page: 'copies', section })} />; if (route.copies === 'list') { diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index af4fe17..976d004 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -7,6 +7,7 @@ "home": "Home", "saves": "Saves", "tuning": "Tuning", + "mods": "Mods", "copies": "Clients", "settings": "Settings", "about": "About" @@ -629,7 +630,95 @@ "download": "Download update", "install": "Quit and install", "installing": "Opening the installer…", - "errors": { + "mods": { + "sections": { + "list": "Mod list", + "presets": "Presets & repository" + }, + "loading": "Loading mods…", + "noCopy": "Install or select an offline client first to configure its mods.", + "enabledSummary": "{{enabled}} / {{total}} enabled", + "experimentalTitle": "Experimental mod API notice:", + "experimentalBody": "WTOffline is in early development (API {{api}}). Server script hooks, internal data structures, and declarative exe patch contracts may change at any time without backwards compatibility; only enable mods from trusted sources.", + "readOnlyNotice": "Mod toggles, load order, and presets are read-only while the game, local server, or maintenance is running.", + "searchPlaceholder": "Filter by mod name, ID, or author…", + "autoSort": "Auto-sort by dependencies", + "autoSorted": "Reordered mods based on dependencies and load-order hints.", + "refresh": "Refresh", + "openFolder": "Open mods folder", + "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):", + "severity": { + "error": "Error", + "warning": "Warning", + "info": "Info" + }, + "emptyTitle": "No mods found in the global mods folder yet.", + "emptyHint": "Place mod folders containing mod.jsonc into {{path}}, then click Refresh. Standalone skins, sights, and user missions continue to work directly via the game's native UserSkins / UserSights / UserMissions folders.", + "noSearchMatch": "No mods match the current search filter.", + "loadOrderHint": "Load order: lower items load later and take higher priority (drag or use arrows)", + "moveUp": "Move up", + "moveDown": "Move down", + "showDetails": "Details", + "hideDetails": "Hide", + "errorCount": "{{count}} error", + "warnCount": "{{count}} warn", + "badges": { + "data": "Data / Assets", + "gui": "GUI Patch", + "script": "Server Script", + "exe": "Exe Patch" + }, + "details": { + "folder": "Folder", + "gameVersions": "Declared game versions", + "requires": "Requires", + "conflicts": "Conflicts", + "tuning": "Server tuning overlays: {{count}}", + "serverScript": "Executable server JS/TS script", + "packOps": "Client pack operations: {{count}}", + "addon": "3D model / texture addon: {{count}} file(s)", + "guiPatches": "GUI script patches: {{count}}", + "exePatches": "Declarative exe patches: {{count}}", + "companionFiles": "Companion files: {{count}}", + "configBlk": "Includes config.blk patch" + }, + "presets": { + "heading": "Mod presets (saved per client)", + "description": "Save the current mod toggles and load order as named presets for quick switching or JSON export/import.", + "quickSwitch": "Switch mod preset", + "customOption": "Custom active selection", + "namePlaceholder": "New preset name, e.g. Modern Vehicles", + "saveCurrent": "Save preset", + "import": "Import preset…", + "empty": "No presets saved for this client yet.", + "activeTag": "Active", + "summary": "{{count}} enabled / {{total}} tracked", + "apply": "Apply", + "overwrite": "Update", + "export": "Export", + "delete": "Delete", + "saved": "Saved preset \"{{name}}\".", + "applied": "Applied preset \"{{name}}\".", + "updated": "Updated preset \"{{name}}\" with current setup.", + "exported": "Exported preset to: {{path}}", + "imported": "Imported mod preset." + }, + "repo": { + "heading": "Global mods repository", + "description": "All clients share one mod folder (large 3D model and texture addons mount across drives via NTFS Junctions with zero copying), while each client keeps its own toggles, load order, and presets.", + "pathLabel": "Repository folder", + "defaultNote": "Using launcher default mods folder", + "customNote": "Using custom mods folder (can live on a larger drive or the same drive as your client)", + "changeFolder": "Change folder…", + "resetDefault": "Reset to default", + "pickTitle": "Select global mods repository folder", + "updated": "Updated global mods repository folder.", + "resetDone": "Reset to default mods repository folder." + } + }, + "errors": { "network": "The update source could not be reached.", "page_limit": "Could not confirm whether a newer version is available.", "contents": "The launcher release information is invalid.", @@ -680,6 +769,94 @@ "L-Debriefing": "Battle results", "L-Battle awards": "Battle awards" }, + "mods": { + "sections": { + "list": "Mod list", + "presets": "Presets & repository" + }, + "loading": "Loading mods…", + "noCopy": "Install or select an offline client first to configure its mods.", + "enabledSummary": "{{enabled}} / {{total}} enabled", + "experimentalTitle": "Experimental mod API notice:", + "experimentalBody": "WTOffline is in early development (API {{api}}). Server script hooks, internal data structures, and declarative exe patch contracts may change at any time without backwards compatibility; only enable mods from trusted sources.", + "readOnlyNotice": "Mod toggles, load order, and presets are read-only while the game, local server, or maintenance is running.", + "searchPlaceholder": "Filter by mod name, ID, or author…", + "autoSort": "Auto-sort by dependencies", + "autoSorted": "Reordered mods based on dependencies and load-order hints.", + "refresh": "Refresh", + "openFolder": "Open mods folder", + "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):", + "severity": { + "error": "Error", + "warning": "Warning", + "info": "Info" + }, + "emptyTitle": "No mods found in the global mods folder yet.", + "emptyHint": "Place mod folders containing mod.jsonc into {{path}}, then click Refresh. Standalone skins, sights, and user missions continue to work directly via the game's native UserSkins / UserSights / UserMissions folders.", + "noSearchMatch": "No mods match the current search filter.", + "loadOrderHint": "Load order: lower items load later and take higher priority (drag or use arrows)", + "moveUp": "Move up", + "moveDown": "Move down", + "showDetails": "Details", + "hideDetails": "Hide", + "errorCount": "{{count}} error", + "warnCount": "{{count}} warn", + "badges": { + "data": "Data / Assets", + "gui": "GUI Patch", + "script": "Server Script", + "exe": "Exe Patch" + }, + "details": { + "folder": "Folder", + "gameVersions": "Declared game versions", + "requires": "Requires", + "conflicts": "Conflicts", + "tuning": "Server tuning overlays: {{count}}", + "serverScript": "Executable server JS/TS script", + "packOps": "Client pack operations: {{count}}", + "addon": "3D model / texture addon: {{count}} file(s)", + "guiPatches": "GUI script patches: {{count}}", + "exePatches": "Declarative exe patches: {{count}}", + "companionFiles": "Companion files: {{count}}", + "configBlk": "Includes config.blk patch" + }, + "presets": { + "heading": "Mod presets (saved per client)", + "description": "Save the current mod toggles and load order as named presets for quick switching or JSON export/import.", + "quickSwitch": "Switch mod preset", + "customOption": "Custom active selection", + "namePlaceholder": "New preset name, e.g. Modern Vehicles", + "saveCurrent": "Save preset", + "import": "Import preset…", + "empty": "No presets saved for this client yet.", + "activeTag": "Active", + "summary": "{{count}} enabled / {{total}} tracked", + "apply": "Apply", + "overwrite": "Update", + "export": "Export", + "delete": "Delete", + "saved": "Saved preset \"{{name}}\".", + "applied": "Applied preset \"{{name}}\".", + "updated": "Updated preset \"{{name}}\" with current setup.", + "exported": "Exported preset to: {{path}}", + "imported": "Imported mod preset." + }, + "repo": { + "heading": "Global mods repository", + "description": "All clients share one mod folder (large 3D model and texture addons mount across drives via NTFS Junctions with zero copying), while each client keeps its own toggles, load order, and presets.", + "pathLabel": "Repository folder", + "defaultNote": "Using launcher default mods folder", + "customNote": "Using custom mods folder (can live on a larger drive or the same drive as your client)", + "changeFolder": "Change folder…", + "resetDefault": "Reset to default", + "pickTitle": "Select global mods repository folder", + "updated": "Updated global mods repository folder.", + "resetDone": "Reset to default mods repository folder." + } + }, "errors": { "app_update_unavailable": "There is no launcher update available to install.", "app_update_busy": "A launcher update operation is already in progress.", @@ -703,6 +880,11 @@ "save_avatar_invalid": "Select an avatar available in this client.", "save_level_invalid": "Enter a level supported by this client.", "tuning_invalid": "The tuning values could not be read or saved. Check the session limits and the launcher log.", + "mods_read_only": "Mods cannot be changed while the game, local server, or maintenance is running.", + "mods_write_failed": "The mod configuration could not be saved. See the launcher log.", + "mods_preset_invalid": "The selected file is not a valid WTOffline mod preset.", + "mods_blocking_issues": "Enabled mods have missing dependencies or conflicts. Resolve them on the Mods page before launching.", + "mods_folder_invalid": "The selected global mods folder is invalid or not writable.", "copy_not_found": "The selected client is no longer available.", "copies_write_failed": "The client registry could not be saved.", "copy_location_in_use": "The client or data location overlaps an existing client.", 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 40e6b22..3536f7e 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -7,6 +7,7 @@ "home": "首页", "saves": "存档", "tuning": "数值", + "mods": "模组", "copies": "客户端", "settings": "设置", "about": "关于" @@ -629,7 +630,95 @@ "download": "下载更新", "install": "退出并安装", "installing": "正在打开安装包…", - "errors": { + "mods": { + "sections": { + "list": "模组列表", + "presets": "预设与仓库" + }, + "loading": "正在读取模组信息…", + "noCopy": "请先安装或选择一个离线客户端,再为它配置模组。", + "enabledSummary": "已启用 {{enabled}} / {{total}}", + "experimentalTitle": "实验期模组接口提示:", + "experimentalBody": "离线版当前处于极初期开发阶段(API {{api}})。服务端脚本钩子、内部数据结构及声明式 exe 补丁契约随时可能随本体更新变动且不保证向下兼容;请仅启用来源可信的模组。", + "readOnlyNotice": "游戏、本地服务器或维护任务运行期间,模组开关、排序与预设为只读。", + "searchPlaceholder": "搜索模组名称、ID 或作者…", + "autoSort": "按依赖自动排序", + "autoSorted": "已按前置与排序建议重新排列模组顺序。", + "refresh": "刷新", + "openFolder": "打开模组目录", + "discoveryErrorsTitle": "有 {{count}} 个模组目录读取失败:", + "blockingIssuesTitle": "存在 {{count}} 项阻塞性模组错误(处理前无法启动):", + "issuesTitle": "检测到 {{count}} 项模组提示或冲突:", + "severity": { + "error": "错误", + "warning": "警告", + "info": "提示" + }, + "emptyTitle": "当前模组目录里还没有模组。", + "emptyHint": "将包含 mod.jsonc 的模组文件夹放入 {{path}},点击「刷新」即可识别。独立涂装、瞄具与单人任务继续沿用游戏原生的 UserSkins / UserSights / UserMissions 目录即可。", + "noSearchMatch": "没有匹配当前搜索条件的模组。", + "loadOrderHint": "加载顺序:越靠后优先级越高(可拖动或使用上下按钮调整)", + "moveUp": "上移", + "moveDown": "下移", + "showDetails": "详情", + "hideDetails": "收起", + "errorCount": "{{count}} 错误", + "warnCount": "{{count}} 警告", + "badges": { + "data": "数据/资源", + "gui": "界面补丁", + "script": "服务端脚本", + "exe": "二进制补丁" + }, + "details": { + "folder": "目录", + "gameVersions": "声明适配版本", + "requires": "前置依赖", + "conflicts": "已知互斥", + "tuning": "服务端数值叠加:{{count}} 份", + "serverScript": "含可执行服务端 JS/TS 脚本", + "packOps": "客户端数据包操作:{{count}} 项", + "addon": "独立 3D 模型/贴图扩展包:{{count}} 个文件", + "guiPatches": "界面脚本补丁:{{count}} 项", + "exePatches": "声明式 exe 补丁:{{count}} 项", + "companionFiles": "附带外置文件:{{count}} 个", + "configBlk": "含 config.blk 增量补丁" + }, + "presets": { + "heading": "模组序列预设(当前客户端独立保存)", + "description": "将当前的启用开关与加载顺序保存为预设,方便在不同玩法配置间一键切换,或导出 JSON 分享给其他玩家。", + "quickSwitch": "快速切换模组预设", + "customOption": "当前自定义配置", + "namePlaceholder": "输入新预设名称,例如:现代载具包", + "saveCurrent": "保存为预设", + "import": "导入预设…", + "empty": "当前客户端尚未保存任何模组预设。", + "activeTag": "当前使用", + "summary": "启用 {{count}} / 共 {{total}} 个模组", + "apply": "应用", + "overwrite": "覆盖更新", + "export": "导出", + "delete": "删除", + "saved": "已保存预设「{{name}}」。", + "applied": "已切换至预设「{{name}}」。", + "updated": "已用当前配置覆盖预设「{{name}}」。", + "exported": "预设已导出到:{{path}}", + "imported": "已导入模组预设。" + }, + "repo": { + "heading": "全局模组仓库位置", + "description": "所有客户端共享同一份模组文件仓库(大体积 3D 模型与贴图包通过跨盘目录联接点零拷贝挂载,不重复占用磁盘);每个客户端独立保存自己的开关、排序和预设。", + "pathLabel": "当前仓库目录", + "defaultNote": "使用启动器默认模组目录", + "customNote": "使用自定义模组目录(可放在大容量硬盘或游戏同盘)", + "changeFolder": "更改目录…", + "resetDefault": "恢复默认目录", + "pickTitle": "选择全局模组仓库目录", + "updated": "已更新全局模组仓库目录。", + "resetDone": "已恢复为默认模组仓库目录。" + } + }, + "errors": { "network": "暂时无法访问更新源。", "page_limit": "无法确认是否有新版本。", "contents": "本体更新的发布信息无效。", @@ -680,6 +769,94 @@ "L-Debriefing": "战后结算", "L-Battle awards": "战斗嘉奖" }, + "mods": { + "sections": { + "list": "模组列表", + "presets": "预设与仓库" + }, + "loading": "正在读取模组信息…", + "noCopy": "请先安装或选择一个离线客户端,再为它配置模组。", + "enabledSummary": "已启用 {{enabled}} / {{total}}", + "experimentalTitle": "实验期模组接口提示:", + "experimentalBody": "离线版当前处于极初期开发阶段(API {{api}})。服务端脚本钩子、内部数据结构及声明式 exe 补丁契约随时可能随本体更新变动且不保证向下兼容;请仅启用来源可信的模组。", + "readOnlyNotice": "游戏、本地服务器或维护任务运行期间,模组开关、排序与预设为只读。", + "searchPlaceholder": "搜索模组名称、ID 或作者…", + "autoSort": "按依赖自动排序", + "autoSorted": "已按前置与排序建议重新排列模组顺序。", + "refresh": "刷新", + "openFolder": "打开模组目录", + "discoveryErrorsTitle": "有 {{count}} 个模组目录读取失败:", + "blockingIssuesTitle": "存在 {{count}} 项阻塞性模组错误(处理前无法启动):", + "issuesTitle": "检测到 {{count}} 项模组提示或冲突:", + "severity": { + "error": "错误", + "warning": "警告", + "info": "提示" + }, + "emptyTitle": "当前模组目录里还没有模组。", + "emptyHint": "将包含 mod.jsonc 的模组文件夹放入 {{path}},点击「刷新」即可识别。独立涂装、瞄具与单人任务继续沿用游戏原生的 UserSkins / UserSights / UserMissions 目录即可。", + "noSearchMatch": "没有匹配当前搜索条件的模组。", + "loadOrderHint": "加载顺序:越靠后优先级越高(可拖动或使用上下按钮调整)", + "moveUp": "上移", + "moveDown": "下移", + "showDetails": "详情", + "hideDetails": "收起", + "errorCount": "{{count}} 错误", + "warnCount": "{{count}} 警告", + "badges": { + "data": "数据/资源", + "gui": "界面补丁", + "script": "服务端脚本", + "exe": "二进制补丁" + }, + "details": { + "folder": "目录", + "gameVersions": "声明适配版本", + "requires": "前置依赖", + "conflicts": "已知互斥", + "tuning": "服务端数值叠加:{{count}} 份", + "serverScript": "含可执行服务端 JS/TS 脚本", + "packOps": "客户端数据包操作:{{count}} 项", + "addon": "独立 3D 模型/贴图扩展包:{{count}} 个文件", + "guiPatches": "界面脚本补丁:{{count}} 项", + "exePatches": "声明式 exe 补丁:{{count}} 项", + "companionFiles": "附带外置文件:{{count}} 个", + "configBlk": "含 config.blk 增量补丁" + }, + "presets": { + "heading": "模组序列预设(当前客户端独立保存)", + "description": "将当前的启用开关与加载顺序保存为预设,方便在不同玩法配置间一键切换,或导出 JSON 分享给其他玩家。", + "quickSwitch": "快速切换模组预设", + "customOption": "当前自定义配置", + "namePlaceholder": "输入新预设名称,例如:现代载具包", + "saveCurrent": "保存为预设", + "import": "导入预设…", + "empty": "当前客户端尚未保存任何模组预设。", + "activeTag": "当前使用", + "summary": "启用 {{count}} / 共 {{total}} 个模组", + "apply": "应用", + "overwrite": "覆盖更新", + "export": "导出", + "delete": "删除", + "saved": "已保存预设「{{name}}」。", + "applied": "已切换至预设「{{name}}」。", + "updated": "已用当前配置覆盖预设「{{name}}」。", + "exported": "预设已导出到:{{path}}", + "imported": "已导入模组预设。" + }, + "repo": { + "heading": "全局模组仓库位置", + "description": "所有客户端共享同一份模组文件仓库(大体积 3D 模型与贴图包通过跨盘目录联接点零拷贝挂载,不重复占用磁盘);每个客户端独立保存自己的开关、排序和预设。", + "pathLabel": "当前仓库目录", + "defaultNote": "使用启动器默认模组目录", + "customNote": "使用自定义模组目录(可放在大容量硬盘或游戏同盘)", + "changeFolder": "更改目录…", + "resetDefault": "恢复默认目录", + "pickTitle": "选择全局模组仓库目录", + "updated": "已更新全局模组仓库目录。", + "resetDone": "已恢复为默认模组仓库目录。" + } + }, "errors": { "app_update_unavailable": "当前没有可安装的本体更新。", "app_update_busy": "本体更新操作正在进行。", @@ -703,6 +880,11 @@ "save_avatar_invalid": "请选择此客户端中可用的头像。", "save_level_invalid": "请输入此客户端支持的账号等级。", "tuning_invalid": "无法读取或保存数值。请核对对局人数限制和启动器日志。", + "mods_read_only": "游戏、本地服务器或维护任务运行期间无法修改模组配置。", + "mods_write_failed": "无法保存模组配置,请查看启动器日志。", + "mods_preset_invalid": "所选文件不是有效的 WTOffline 模组预设。", + "mods_blocking_issues": "当前启用的模组存在缺失前置或互斥冲突,请先在「模组」页面处理后再启动。", + "mods_folder_invalid": "所选全局模组目录无效或无法写入。", "copy_not_found": "所选客户端已不可用。", "copies_write_failed": "无法保存客户端记录。", "copy_location_in_use": "客户端位置或数据目录与已有客户端重叠。", diff --git a/apps/launcher/src/renderer/src/pages/mods/ModsPage.tsx b/apps/launcher/src/renderer/src/pages/mods/ModsPage.tsx new file mode 100644 index 0000000..ca39159 --- /dev/null +++ b/apps/launcher/src/renderer/src/pages/mods/ModsPage.tsx @@ -0,0 +1,565 @@ +import { useCallback, useEffect, useMemo, useState, type DragEvent, type FormEvent } from 'react'; +import { useTranslation } from 'react-i18next'; +import type { InstallRecord } from '@shared/schemas/install.ts'; +import type { ModIssueView, ModListItem, ModsStateView } from '@shared/schemas/mods.ts'; +import { Row } from '../../components/Row.tsx'; +import { Sheet } from '../../components/Sheet.tsx'; +import { ipcInvoke } from '../../ipc.ts'; +import type { ModsSection } from '../../shell/navigation.ts'; + +interface Props { + readonly copy: InstallRecord; + readonly section: ModsSection; + readonly readOnly: boolean; + readonly onError: (error: unknown) => void; +} + +function localized(value: string | Readonly> | undefined, language: string): string { + if (!value) return ''; + if (typeof value === 'string') return value; + const exact = value[language]; + if (exact) return exact; + const prefix = language.split('-')[0]; + if (prefix) { + const match = Object.entries(value).find(([key]) => key === prefix || key.startsWith(`${prefix}-`)); + if (match?.[1]) return match[1]; + } + return value.en ?? value['en-US'] ?? Object.values(value)[0] ?? ''; +} + +export function ModsPage({ copy, section, readOnly, onError }: Props) { + const { t, i18n } = useTranslation(); + const [state, setState] = useState(null); + const [busy, setBusy] = useState(false); + const [query, setQuery] = useState(''); + const [expandedId, setExpandedId] = useState(null); + const [draggedId, setDraggedId] = useState(null); + const [presetName, setPresetName] = useState(''); + const [notice, setNotice] = useState(null); + + const load = useCallback(() => { + setBusy(true); + ipcInvoke('mods:getState', { copyId: copy.id }) + .then(setState) + .catch(onError) + .finally(() => setBusy(false)); + }, [copy.id, onError]); + + useEffect(() => { + let mounted = true; + ipcInvoke('mods:getState', { copyId: copy.id }) + .then((result) => { if (mounted) setState(result); }) + .catch(onError); + return () => { mounted = false; }; + }, [copy.id, onError]); + + const runAction = (action: Promise, successNotice?: string): void => { + setBusy(true); + setNotice(null); + action + .then((next) => { + setState(next); + if (successNotice) setNotice(successNotice); + }) + .catch(onError) + .finally(() => setBusy(false)); + }; + + const issuesByMod = useMemo(() => { + const map = new Map(); + for (const issue of state?.issues ?? []) { + const list = map.get(issue.modId) ?? []; + list.push(issue); + map.set(issue.modId, list); + } + return map; + }, [state]); + + const title = t(`mods.sections.${section}`); + if (!state) { + return

{t('mods.loading')}

; + } + + const disabled = readOnly || busy; + const enabledCount = state.mods.filter((mod) => state.enabled[mod.id] === true).length; + + const toggleMod = (modId: string, nextEnabled: boolean): void => { + runAction(ipcInvoke('mods:setEnabled', { copyId: copy.id, modId, enabled: nextEnabled })); + }; + + const reorder = (nextOrder: string[]): void => { + runAction(ipcInvoke('mods:setOrder', { copyId: copy.id, order: nextOrder })); + }; + + const moveMod = (modId: string, delta: -1 | 1): void => { + const idx = state.order.indexOf(modId); + const target = idx + delta; + if (idx < 0 || target < 0 || target >= state.order.length) return; + const next = [...state.order]; + const [item] = next.splice(idx, 1); + next.splice(target, 0, item!); + reorder(next); + }; + + const handleDrop = (targetId: string, event: DragEvent): void => { + event.preventDefault(); + const sourceId = draggedId; + setDraggedId(null); + if (!sourceId || sourceId === targetId || disabled) return; + const from = state.order.indexOf(sourceId); + const to = state.order.indexOf(targetId); + if (from < 0 || to < 0) return; + const next = [...state.order]; + const [moved] = next.splice(from, 1); + next.splice(to, 0, moved!); + reorder(next); + }; + + const savePreset = (event: FormEvent): void => { + event.preventDefault(); + const trimmed = presetName.trim(); + if (!trimmed) return; + runAction( + ipcInvoke('mods:savePreset', { copyId: copy.id, name: trimmed }), + t('mods.presets.saved', { name: trimmed }), + ); + setPresetName(''); + }; + + const pickCustomFolder = (): void => { + ipcInvoke('dialog:pickFolder', { title: t('mods.repo.pickTitle') }) + .then(({ path }) => { + if (!path) return; + runAction(ipcInvoke('mods:setFolder', { copyId: copy.id, path }), t('mods.repo.updated')); + }) + .catch(onError); + }; + + const resetFolder = (): void => { + runAction(ipcInvoke('mods:setFolder', { copyId: copy.id, path: null }), t('mods.repo.resetDone')); + }; + + const exportPreset = (presetId: string): void => { + setBusy(true); + setNotice(null); + ipcInvoke('mods:exportPreset', { copyId: copy.id, presetId }) + .then(({ path }) => { + if (path) setNotice(t('mods.presets.exported', { path })); + }) + .catch(onError) + .finally(() => setBusy(false)); + }; + + const importPreset = (): void => { + setBusy(true); + setNotice(null); + ipcInvoke('mods:importPreset', { copyId: copy.id }) + .then(({ imported, state: next }) => { + setState(next); + if (imported) setNotice(t('mods.presets.imported')); + }) + .catch(onError) + .finally(() => setBusy(false)); + }; + + const normalizedQuery = query.trim().toLowerCase(); + const visibleMods = normalizedQuery + ? state.mods.filter((mod) => { + const displayName = localized(mod.name, i18n.language).toLowerCase(); + return displayName.includes(normalizedQuery) + || mod.id.toLowerCase().includes(normalizedQuery) + || mod.author.toLowerCase().includes(normalizedQuery); + }) + : state.mods; + + const canDrag = !disabled && normalizedQuery.length === 0; + + return ( + +
+ {t('mods.experimentalTitle')} + {t('mods.experimentalBody', { api: state.apiVersion })} +
+ + {readOnly && ( +
+ {t('mods.readOnlyNotice')} +
+ )} + + {notice && ( +
+ {notice} +
+ )} + + {section === 'list' ? ( + <> +
+ setQuery(event.target.value)} + /> + {state.presets.length > 0 && ( + + )} + + + +
+ + {state.discoveryErrors.length > 0 && ( +
+
{t('mods.discoveryErrorsTitle', { count: state.discoveryErrors.length })}
+
    + {state.discoveryErrors.map((err) => ( +
  • + {err.folderName}: {err.reason} +
  • + ))} +
+
+ )} + + {state.issues.length > 0 && ( +
+
+ {state.hasBlockingErrors + ? t('mods.blockingIssuesTitle', { count: state.issues.filter((i) => i.severity === 'error').length }) + : t('mods.issuesTitle', { count: state.issues.length })} +
+
    + {state.issues.map((issue, idx) => ( +
  • + {t(`mods.severity.${issue.severity}`)} + {issue.modId}: {issue.detail} +
  • + ))} +
+
+ )} + + {visibleMods.length === 0 ? ( +
+

{state.mods.length === 0 ? t('mods.emptyTitle') : t('mods.noSearchMatch')}

+ {state.mods.length === 0 && ( + <> +

{t('mods.emptyHint', { path: state.modsDir })}

+ + + )} +
+ ) : ( +
+ {visibleMods.map((mod) => { + const index = state.order.indexOf(mod.id); + const isEnabled = state.enabled[mod.id] === true; + const isExpanded = expandedId === mod.id; + const modIssues = issuesByMod.get(mod.id) ?? []; + return ( + toggleMod(mod.id, next)} + onMove={(delta) => moveMod(mod.id, delta)} + onToggleExpand={() => setExpandedId(isExpanded ? null : mod.id)} + onDragStart={() => setDraggedId(mod.id)} + onDrop={(event) => handleDrop(mod.id, event)} + /> + ); + })} +
+ )} + + ) : ( + <> +
+

{t('mods.presets.heading')}

+

{t('mods.presets.description')}

+
+ setPresetName(event.target.value)} + /> + + +
+ + {state.presets.length === 0 ? ( +

{t('mods.presets.empty')}

+ ) : ( +
+ {state.presets.map((preset) => { + const active = state.activePresetId === preset.id; + const count = Object.values(preset.enabled).filter(Boolean).length; + return ( +
+
+
+ {preset.name} + {active && {t('mods.presets.activeTag')}} +
+
+ {t('mods.presets.summary', { count, total: preset.order.length })} +
+
+
+ + + + +
+
+ ); + })} +
+ )} +
+ +
+

{t('mods.repo.heading')}

+

{t('mods.repo.description')}

+ + {state.modsDir} + +
+ + + {state.isCustomModsDir && ( + + )} +
+
+ + )} +
+ ); +} + +interface ModCardProps { + readonly mod: ModListItem; + readonly index: number; + readonly total: number; + readonly enabled: boolean; + readonly expanded: boolean; + readonly disabled: boolean; + readonly canDrag: boolean; + readonly language: string; + readonly issues: readonly ModIssueView[]; + readonly onToggle: (next: boolean) => void; + readonly onMove: (delta: -1 | 1) => void; + readonly onToggleExpand: () => void; + readonly onDragStart: () => void; + readonly onDrop: (event: DragEvent) => void; +} + +function ModCard({ + mod, + index, + total, + enabled, + expanded, + disabled, + canDrag, + language, + issues, + onToggle, + onMove, + onToggleExpand, + onDragStart, + onDrop, +}: ModCardProps) { + const { t } = useTranslation(); + const displayName = localized(mod.name, language) || mod.id; + const description = localized(mod.description, language); + const errorCount = issues.filter((i) => i.severity === 'error').length; + const warnCount = issues.filter((i) => i.severity === 'warning').length; + + return ( +
{ if (canDrag) event.preventDefault(); }} + onDrop={onDrop} + > +
+ #{index + 1} + onToggle(event.target.checked)} + /> +
+
+ {displayName} + v{mod.version} + · {mod.author} +
+ {mod.badges.map((badge) => ( + + {t(`mods.badges.${badge}`)} + + ))} + {errorCount > 0 && {t('mods.errorCount', { count: errorCount })}} + {warnCount > 0 && {t('mods.warnCount', { count: warnCount })}} +
+
+ {description &&
{description}
} +
+
+ + + +
+
+ + {expanded && ( +
+
+
ID: {mod.id}
+
API: {mod.apiVersion}
+
{t('mods.details.folder')}: {mod.folderName}
+ {mod.gameVersions.length > 0 && ( +
{t('mods.details.gameVersions')}: {mod.gameVersions.join(', ')}
+ )} + {mod.requires.length > 0 && ( +
{t('mods.details.requires')}: {mod.requires.join(', ')}
+ )} + {mod.conflicts.length > 0 && ( +
{t('mods.details.conflicts')}: {mod.conflicts.join(', ')}
+ )} +
+
+ {mod.serverTuningFiles.length > 0 && ( + {t('mods.details.tuning', { count: mod.serverTuningFiles.length })} + )} + {mod.hasServerScript && {t('mods.details.serverScript')}} + {mod.packOperations.length > 0 && ( + {t('mods.details.packOps', { count: mod.packOperations.length })} + )} + {mod.hasClientAddon && ( + {t('mods.details.addon', { count: mod.addonFileCount })} + )} + {mod.guiPatchCount > 0 && ( + {t('mods.details.guiPatches', { count: mod.guiPatchCount })} + )} + {mod.exePatchCount > 0 && ( + {t('mods.details.exePatches', { count: mod.exePatchCount })} + )} + {mod.clientFileCount > 0 && ( + {t('mods.details.companionFiles', { count: mod.clientFileCount })} + )} + {mod.hasConfigBlkPatch && {t('mods.details.configBlk')}} +
+
+ )} +
+ ); +} diff --git a/apps/launcher/src/renderer/src/shell/navigation.ts b/apps/launcher/src/renderer/src/shell/navigation.ts index 36a418b..e435cbe 100644 --- a/apps/launcher/src/renderer/src/shell/navigation.ts +++ b/apps/launcher/src/renderer/src/shell/navigation.ts @@ -1,9 +1,8 @@ /** * The window's pages and the sections of those that have a section list in the side panel. - * Pages for later features (saves, tuning) join this list when they are built. */ -export const PAGES = ['home', 'saves', 'tuning', 'copies', 'settings', 'about'] as const; +export const PAGES = ['home', 'saves', 'tuning', 'mods', 'copies', 'settings', 'about'] as const; export type PageId = (typeof PAGES)[number]; export const SAVE_SECTIONS = ['list', 'overview', 'battles', 'vehicles', 'official', 'backup'] as const; @@ -12,6 +11,9 @@ export type SaveSection = (typeof SAVE_SECTIONS)[number]; export const TUNING_SECTIONS = ['rewards', 'battle', 'newProfile', 'research'] as const; export type TuningSection = (typeof TUNING_SECTIONS)[number]; +export const MODS_SECTIONS = ['list', 'presets'] as const; +export type ModsSection = (typeof MODS_SECTIONS)[number]; + export const COPY_SECTIONS = ['list', 'summary', 'features', 'maintain'] as const; export type CopySection = (typeof COPY_SECTIONS)[number]; @@ -23,16 +25,25 @@ export interface Route { readonly copies: CopySection; readonly saves: SaveSection; readonly tuning: TuningSection; + readonly mods: ModsSection; readonly settings: SettingsSection; } -export const START_ROUTE: Route = { page: 'home', saves: 'list', tuning: 'rewards', copies: 'list', settings: 'general' }; +export const START_ROUTE: Route = { + page: 'home', + saves: 'list', + tuning: 'rewards', + mods: 'list', + copies: 'list', + settings: 'general', +}; /** Where a link points: a page, and for pages with sections, which one. */ export type Destination = | { readonly page: 'home' | 'about' } | { readonly page: 'saves'; readonly section?: SaveSection } | { readonly page: 'tuning'; readonly section?: TuningSection } + | { readonly page: 'mods'; readonly section?: ModsSection } | { readonly page: 'copies'; readonly section?: CopySection } | { readonly page: 'settings'; readonly section?: SettingsSection }; @@ -42,6 +53,8 @@ export function navigate(route: Route, to: Destination): Route { return { ...route, page: 'saves', saves: to.section ?? route.saves }; case 'tuning': return { ...route, page: 'tuning', tuning: to.section ?? route.tuning }; + case 'mods': + return { ...route, page: 'mods', mods: to.section ?? route.mods }; case 'copies': return { ...route, page: 'copies', copies: to.section ?? route.copies }; case 'settings': diff --git a/apps/launcher/src/renderer/src/styles/pages.css b/apps/launcher/src/renderer/src/styles/pages.css index bef5000..fcead22 100644 --- a/apps/launcher/src/renderer/src/styles/pages.css +++ b/apps/launcher/src/renderer/src/styles/pages.css @@ -435,3 +435,327 @@ .about-card .notice .button { margin-top: 8px; } + +/* ===== Mods ===== */ +.mods-banner { + display: flex; + flex-direction: column; + gap: 3px; + padding: 10px 12px; + margin-bottom: 12px; + font-size: 12.5px; + line-height: 1.5; + border: 1px solid var(--line); + border-radius: var(--radius); +} + +.mods-banner-experimental { + background: rgba(214, 158, 46, 0.14); + border-color: rgba(214, 158, 46, 0.45); + color: rgba(255, 241, 204, 0.94); +} + +.mods-banner-warn { + background: rgba(206, 65, 55, 0.16); + border-color: rgba(206, 65, 55, 0.5); + color: #ffd7d4; +} + +.mods-banner-ok { + background: rgba(68, 170, 102, 0.16); + border-color: rgba(68, 170, 102, 0.5); + color: #d7ffe4; +} + +.mods-toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + margin-bottom: 12px; +} + +.mods-search { + flex: 1 1 180px; + min-width: 140px; +} + +.mods-preset-select { + max-width: 210px; +} + +.mods-issues-box { + padding: 10px 12px; + margin-bottom: 12px; + font-size: 12.5px; + border-radius: var(--radius); + border: 1px solid var(--line); +} + +.mods-issues-error { + background: rgba(206, 65, 55, 0.15); + border-color: rgba(206, 65, 55, 0.55); +} + +.mods-issues-warn { + background: rgba(214, 158, 46, 0.13); + border-color: rgba(214, 158, 46, 0.45); +} + +.mods-issues-title { + font-weight: 600; + margin-bottom: 6px; +} + +.mods-issues-box ul { + margin: 0; + padding-left: 18px; + display: flex; + flex-direction: column; + gap: 4px; +} + +.mods-issue-tag { + display: inline-block; + margin-right: 6px; + padding: 1px 5px; + font-size: 11px; + border-radius: 2px; + background: rgba(255, 255, 255, 0.12); +} + +.mods-empty { + padding: 20px 14px; + text-align: center; + border: 1px dashed var(--line); + border-radius: var(--radius); +} + +.mods-hint { + font-size: 12.5px; + color: var(--text-dim); + line-height: 1.5; + margin: 6px 0 12px; +} + +.mods-list { + display: flex; + flex-direction: column; + gap: 8px; +} + +.mods-card { + border: 1px solid var(--line); + border-radius: var(--radius); + background: rgba(12, 16, 19, 0.62); + transition: border-color 120ms ease; +} + +.mods-card-enabled { + border-left: 3px solid var(--red); + background: rgba(18, 24, 29, 0.78); +} + +.mods-card-row { + display: flex; + align-items: center; + gap: 10px; + padding: 10px 12px; +} + +.mods-order-num { + min-width: 26px; + font-size: 12px; + color: var(--text-dim); + text-align: right; + cursor: grab; +} + +.mods-checkbox { + width: 16px; + height: 16px; + flex: none; + cursor: pointer; +} + +.mods-card-main { + flex: 1; + min-width: 0; + cursor: pointer; +} + +.mods-card-title { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; +} + +.mods-name { + font-weight: 600; + color: var(--white); +} + +.mods-version, +.mods-author { + font-size: 12px; + color: var(--text-dim); +} + +.mods-card-desc { + margin-top: 3px; + font-size: 12px; + color: var(--text-dim); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.mods-badges { + display: inline-flex; + flex-wrap: wrap; + gap: 4px; +} + +.mods-badge { + padding: 1px 6px; + font-size: 11px; + border-radius: 2px; + border: 1px solid rgba(255, 255, 255, 0.16); +} + +.mods-badge-data { + background: rgba(88, 166, 255, 0.16); + color: #b7d7ff; +} + +.mods-badge-gui { + background: rgba(163, 113, 247, 0.18); + color: #dec8ff; +} + +.mods-badge-script { + background: rgba(214, 158, 46, 0.22); + color: #ffe3a3; +} + +.mods-badge-exe { + background: rgba(206, 65, 55, 0.28); + color: #ffc2be; + border-color: rgba(206, 65, 55, 0.55); +} + +.mods-badge-error { + background: rgba(206, 65, 55, 0.35); + color: #ffd5d2; +} + +.mods-badge-warn { + background: rgba(214, 158, 46, 0.25); + color: #ffe8b3; +} + +.mods-card-actions { + display: flex; + align-items: center; + gap: 4px; + flex: none; +} + +.mods-move-btn { + min-width: 28px; + padding: 4px 6px; +} + +.mods-card-details { + padding: 10px 12px 12px 48px; + border-top: 1px solid var(--line); + font-size: 12px; + color: var(--text-dim); +} + +.mods-detail-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); + gap: 4px 12px; + margin-bottom: 8px; +} + +.mods-detail-summary { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.mods-detail-summary span { + padding: 2px 7px; + border-radius: 2px; + background: rgba(255, 255, 255, 0.08); + color: rgba(255, 255, 255, 0.85); +} + +.mods-section { + margin-bottom: 22px; +} + +.mods-subheading { + margin: 0 0 4px; + font: 600 15px var(--font-display); + color: var(--white); +} + +.mods-preset-form { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin: 10px 0 14px; +} + +.mods-preset-form .input { + flex: 1 1 200px; +} + +.mods-preset-list { + display: flex; + flex-direction: column; + gap: 8px; +} + +.mods-preset-item { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 10px; + padding: 10px 12px; + border: 1px solid var(--line); + border-radius: var(--radius); + background: rgba(12, 16, 19, 0.62); +} + +.mods-preset-active { + border-left: 3px solid var(--red); +} + +.mods-preset-meta { + min-width: 0; +} + +.mods-preset-name { + display: flex; + align-items: center; + gap: 8px; + font-weight: 600; + color: var(--white); +} + +.mods-preset-sub { + font-size: 12px; + color: var(--text-dim); + margin-top: 2px; +} + +.mods-path { + font-size: 12px; + word-break: break-all; +} diff --git a/apps/launcher/src/shared/errors.ts b/apps/launcher/src/shared/errors.ts index dfdd5ac..672eba6 100644 --- a/apps/launcher/src/shared/errors.ts +++ b/apps/launcher/src/shared/errors.ts @@ -24,6 +24,11 @@ export const APP_ERROR_CODES = [ 'diagnostics_export_failed', 'copy_not_found', 'tuning_invalid', + 'mods_read_only', + 'mods_write_failed', + 'mods_preset_invalid', + 'mods_blocking_issues', + 'mods_folder_invalid', 'save_not_found', 'save_archive_invalid', 'save_official_invalid', diff --git a/apps/launcher/src/shared/ipc/channels.ts b/apps/launcher/src/shared/ipc/channels.ts index a94a63a..c6c433e 100644 --- a/apps/launcher/src/shared/ipc/channels.ts +++ b/apps/launcher/src/shared/ipc/channels.ts @@ -16,6 +16,8 @@ export const IPC_CHANNEL_PREFIXES = [ 'copies:', /** Settings shared by the saves of a game copy. */ 'tuning:', + /** Additive mods repository, per-copy ordering/toggles, and presets. */ + 'mods:', /** Local account and save management. */ 'saves:', /** Starting and stopping the active copy. */ diff --git a/apps/launcher/src/shared/ipc/contract.ts b/apps/launcher/src/shared/ipc/contract.ts index ca7332f..d87aa0f 100644 --- a/apps/launcher/src/shared/ipc/contract.ts +++ b/apps/launcher/src/shared/ipc/contract.ts @@ -17,6 +17,7 @@ import { } from '../schemas/install.ts'; import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts'; import { MaintenanceInfoSchema, MaintenanceProgressSchema, MaintenanceRequestSchema } from '../schemas/maintenance.ts'; +import { ModsStateViewSchema } from '../schemas/mods.ts'; import { ActivePatchSetSchema, PackApplyResultSchema, PackCheckSchema, PackReleaseSchema } from '../schemas/patch-pack.ts'; import { AccountEditsSchema, SaveAvatarChoicesSchema, SaveAvatarIdSchema, ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, OnlineDataSourceSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts'; import { TuningPatchSchema, TuningViewSchema } from '../schemas/tuning.ts'; @@ -262,6 +263,50 @@ export const ipcContract = { input: z.object({ copyId: CopyIdSchema, patch: TuningPatchSchema }), output: TuningViewSchema, }, + 'mods:getState': { + input: z.object({ copyId: CopyIdSchema }), + output: ModsStateViewSchema, + }, + 'mods:setEnabled': { + input: z.object({ copyId: CopyIdSchema, modId: z.string().min(1), enabled: z.boolean() }), + output: ModsStateViewSchema, + }, + 'mods:setOrder': { + input: z.object({ copyId: CopyIdSchema, order: z.array(z.string()) }), + output: ModsStateViewSchema, + }, + 'mods:autoSort': { + input: z.object({ copyId: CopyIdSchema }), + output: ModsStateViewSchema, + }, + 'mods:savePreset': { + input: z.object({ copyId: CopyIdSchema, name: z.string().trim().min(1).max(80), overwriteId: z.string().min(1).optional() }), + output: ModsStateViewSchema, + }, + 'mods:applyPreset': { + input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }), + output: ModsStateViewSchema, + }, + 'mods:deletePreset': { + input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }), + output: ModsStateViewSchema, + }, + 'mods:exportPreset': { + input: z.object({ copyId: CopyIdSchema, presetId: z.string().min(1) }), + output: z.object({ path: z.string().nullable() }), + }, + 'mods:importPreset': { + input: z.object({ copyId: CopyIdSchema }), + output: z.object({ imported: z.boolean(), state: ModsStateViewSchema }), + }, + 'mods:openFolder': { + input: z.void(), + output: z.void(), + }, + 'mods:setFolder': { + input: z.object({ copyId: CopyIdSchema, path: z.string().min(1).nullable() }), + output: ModsStateViewSchema, + }, 'launch:getState': { input: z.void(), output: LaunchStateSchema, diff --git a/apps/launcher/src/shared/schemas/mods.ts b/apps/launcher/src/shared/schemas/mods.ts new file mode 100644 index 0000000..fb6bddd --- /dev/null +++ b/apps/launcher/src/shared/schemas/mods.ts @@ -0,0 +1,87 @@ +import { z } from 'zod'; + +export const ModRiskBadgeSchema = z.enum(['data', 'gui', 'script', 'exe']); +export const ModIssueSeveritySchema = z.enum(['error', 'warning', 'info']); +export const LocalizedTextSchema = z.union([z.string(), z.record(z.string(), z.string())]); + +export const ModPackOperationSchema = z.object({ + pack: z.string(), + targetPath: z.string(), + action: z.enum(['blk-patch', 'csv-patch', 'file']), + sourceRelativePath: z.string(), +}); + +export const ModListItemSchema = z.object({ + id: z.string(), + folderName: z.string(), + rootDir: z.string(), + name: LocalizedTextSchema, + description: LocalizedTextSchema.optional(), + version: z.string(), + author: z.string(), + apiVersion: z.string(), + gameVersions: z.array(z.string()), + requires: z.array(z.string()), + conflicts: z.array(z.string()), + loadAfter: z.array(z.string()), + loadBefore: z.array(z.string()), + badges: z.array(ModRiskBadgeSchema), + hasServerScript: z.boolean(), + serverTuningFiles: z.array(z.string()), + packOperations: z.array(ModPackOperationSchema), + guiPatchCount: z.number().int().nonnegative(), + exePatchCount: z.number().int().nonnegative(), + hasClientAddon: z.boolean(), + addonFileCount: z.number().int().nonnegative(), + clientFileCount: z.number().int().nonnegative(), + hasConfigBlkPatch: z.boolean(), +}); + +export const ModDiscoveryErrorSchema = z.object({ + folderName: z.string(), + rootDir: z.string(), + reason: z.string(), +}); + +export const ModIssueSchema = z.object({ + severity: ModIssueSeveritySchema, + kind: z.string(), + modId: z.string(), + otherModId: z.string().optional(), + detail: z.string(), +}); + +export const ModPresetSchema = z.object({ + id: z.string().min(1), + name: z.string().min(1).max(80), + order: z.array(z.string()), + enabled: z.record(z.string(), z.boolean()), + updatedAt: z.string(), +}); + +export const ModsStateViewSchema = z.object({ + modsDir: z.string(), + defaultModsDir: z.string(), + isCustomModsDir: z.boolean(), + apiVersion: z.string(), + mods: z.array(ModListItemSchema), + discoveryErrors: z.array(ModDiscoveryErrorSchema), + order: z.array(z.string()), + enabled: z.record(z.string(), z.boolean()), + activePresetId: z.string().nullable(), + presets: z.array(ModPresetSchema), + issues: z.array(ModIssueSchema), + hasBlockingErrors: z.boolean(), +}); + +export const ModPresetTransferSchema = z.object({ + format: z.literal(1), + name: z.string().min(1).max(80), + order: z.array(z.string()), + enabled: z.record(z.string(), z.boolean()), +}); + +export type ModListItem = z.output; +export type ModPresetView = z.output; +export type ModIssueView = z.output; +export type ModsStateView = z.output; diff --git a/apps/launcher/src/shared/schemas/settings.ts b/apps/launcher/src/shared/schemas/settings.ts index ebfd269..d0aa05d 100644 --- a/apps/launcher/src/shared/schemas/settings.ts +++ b/apps/launcher/src/shared/schemas/settings.ts @@ -37,6 +37,8 @@ export const SettingsSchema = z.object({ developerMode: z.boolean().default(true), labStockPath: LabPathSchema.default(null), labDataPath: LabPathSchema.default(null), + /** Custom global mods repository directory; null uses `/mods`. */ + modsFolder: LabPathSchema.default(null), }); export type Settings = z.output; @@ -60,6 +62,7 @@ export const SettingsPatchSchema = z.object({ developerMode: z.boolean().optional(), labStockPath: LabPathSchema.optional(), labDataPath: LabPathSchema.optional(), + modsFolder: LabPathSchema.optional(), }); export type SettingsPatch = z.output; diff --git a/scripts/build-windows-installer.ts b/scripts/build-windows-installer.ts index b8588b0..9bf3ff0 100644 --- a/scripts/build-windows-installer.ts +++ b/scripts/build-windows-installer.ts @@ -11,7 +11,7 @@ const launcher = join(repository, 'apps', 'launcher'); const modules = join(repository, 'node_modules'); const buildFolder = join(repository, 'build'); const output = join(buildFolder, 'windows-installer'); -const workspacePackages = ['apps/server', 'packages/blk', 'packages/exepatch', 'packages/jsonc', 'packages/patcher', 'packages/vromfs']; +const workspacePackages = ['apps/server', 'packages/blk', 'packages/exepatch', 'packages/jsonc', 'packages/mods', 'packages/patcher', 'packages/vromfs']; interface LauncherManifest { readonly productName: string; From 3aac60c8a3151bf3fc3036bdc895431b63c665a6 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Thu, 3 Dec 2026 00:41:47 +0800 Subject: [PATCH 05/12] docs(mods): add bilingual mod authoring guide and runnable example mod templates --- dev-docs/README.md | 2 + dev-docs/mods.md | 143 ++++++++++++++++++ .../mods/example-server-script/mod.jsonc | 19 +++ .../example-server-script/server/index.ts | 60 ++++++++ .../mods/example-vehicle-tweak/mod.jsonc | 18 +++ .../server/tuning/battle.jsonc | 5 + 6 files changed, 247 insertions(+) create mode 100644 dev-docs/mods.md create mode 100644 dev-docs/templates/mods/example-server-script/mod.jsonc create mode 100644 dev-docs/templates/mods/example-server-script/server/index.ts create mode 100644 dev-docs/templates/mods/example-vehicle-tweak/mod.jsonc create mode 100644 dev-docs/templates/mods/example-vehicle-tweak/server/tuning/battle.jsonc diff --git a/dev-docs/README.md b/dev-docs/README.md index ada721d..e009877 100644 --- a/dev-docs/README.md +++ b/dev-docs/README.md @@ -12,6 +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) | 提交前按[自查清单](contributing.md#zh-cn)整理依据、运行适用的[检查命令](contributing.md#checks),并把检查结果和实机步骤写进 [PR 模板](templates/pull-request.md)。 @@ -27,5 +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) | 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 new file mode 100644 index 0000000..2e0e468 --- /dev/null +++ b/dev-docs/mods.md @@ -0,0 +1,143 @@ +# 模组开发指南 / 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/dev-docs/templates/mods/example-server-script/mod.jsonc b/dev-docs/templates/mods/example-server-script/mod.jsonc new file mode 100644 index 0000000..3627145 --- /dev/null +++ b/dev-docs/templates/mods/example-server-script/mod.jsonc @@ -0,0 +1,19 @@ +// Example experimental server-side TypeScript mod. +// Demonstrates dataset/catalogue hooks, per-account isolated storage, and a custom HTTP endpoint. +{ + "format": 1, + "id": "example.server-script", + "name": { + "zh-CN": "示例:服务端 TS 脚本钩子", + "en": "Example: Server TS Script Hooks" + }, + "version": "0.1.0", + "author": "WTOffline", + "description": { + "zh-CN": "演示实验期服务端 TypeScript 钩子、独立存档区与自定义 /mods//status 网页接口。", + "en": "Demonstrates experimental server TypeScript hooks, isolated mod storage, and a custom /mods//status HTTP route." + }, + "api_version": "0.1-experimental", + "game_versions": ["2.61.0.*"], + "load_after": ["example.vehicle-tweak"] +} diff --git a/dev-docs/templates/mods/example-server-script/server/index.ts b/dev-docs/templates/mods/example-server-script/server/index.ts new file mode 100644 index 0000000..63a009a --- /dev/null +++ b/dev-docs/templates/mods/example-server-script/server/index.ts @@ -0,0 +1,60 @@ +/** + * Example server-side TypeScript mod (erasable TypeScript syntax, runs directly on Electron's Node 24). + * + * EXPERIMENTAL: Internal server contracts and hook shapes may change across WTOffline releases. + */ +interface ModState { + refreshes: number; + lastUpdated: string; +} + +export default { + setup(ctx: { + readonly apiVersion: string; + readonly manifest: { readonly id: string; readonly version: string }; + readonly logger: { info(msg: string): void }; + readonly storage: { + forPlayer(userId: string): { read(): T | undefined; write(value: unknown): void }; + }; + readonly hooks: { + onDatasetsLoaded(fn: (datasets: { readonly vehicles: unknown[] }) => void): void; + onServerListening(fn: (info: { readonly port: number }) => void): void; + readonly profile: { + onRefresh(fn: (profile: unknown, userId: string) => void): void; + }; + }; + readonly routes: { + readonly http: { + register(subPath: string, fn: () => { status: number; contentType: string; body: string }): void; + }; + }; + }) { + let vehicleCount = 0; + + ctx.hooks.onDatasetsLoaded((datasets) => { + vehicleCount = datasets.vehicles.length; + ctx.logger.info(`observed ${vehicleCount} vehicles in merged dataset`); + }); + + ctx.hooks.profile.onRefresh((_profile, userId) => { + const store = ctx.storage.forPlayer(userId); + const prev = store.read() ?? { refreshes: 0, lastUpdated: '' }; + store.write({ refreshes: prev.refreshes + 1, lastUpdated: new Date().toISOString() }); + }); + + ctx.hooks.onServerListening(({ port }) => { + ctx.logger.info(`custom status endpoint ready at http://127.0.0.1:${port}/mods/${ctx.manifest.id}/status`); + }); + + ctx.routes.http.register('/status', () => ({ + status: 200, + contentType: 'application/json; charset=utf-8', + body: JSON.stringify({ + modId: ctx.manifest.id, + version: ctx.manifest.version, + apiVersion: ctx.apiVersion, + vehicleCount, + }), + })); + }, +}; diff --git a/dev-docs/templates/mods/example-vehicle-tweak/mod.jsonc b/dev-docs/templates/mods/example-vehicle-tweak/mod.jsonc new file mode 100644 index 0000000..7dfbbaa --- /dev/null +++ b/dev-docs/templates/mods/example-vehicle-tweak/mod.jsonc @@ -0,0 +1,18 @@ +// Example additive data mod: adjusts battle rewards via server tuning, patches a stock +// vehicle's economy block in char.vromfs.bin, and updates a localization label in lang.vromfs.bin. +{ + "format": 1, + "id": "example.vehicle-tweak", + "name": { + "zh-CN": "示例:载具数值与收益微调", + "en": "Example: Vehicle & Economy Tweak" + }, + "version": "0.1.0", + "author": "WTOffline", + "description": { + "zh-CN": "演示零代码叠加:修改对局收益倍率、增量修补 wpcost.blk 与本地化词条。", + "en": "Demonstrates code-free stacking: battle reward tuning, incremental wpcost.blk patching, and localization CSV merging." + }, + "api_version": "0.1-experimental", + "game_versions": ["2.61.0.*"] +} diff --git a/dev-docs/templates/mods/example-vehicle-tweak/server/tuning/battle.jsonc b/dev-docs/templates/mods/example-vehicle-tweak/server/tuning/battle.jsonc new file mode 100644 index 0000000..29accd0 --- /dev/null +++ b/dev-docs/templates/mods/example-vehicle-tweak/server/tuning/battle.jsonc @@ -0,0 +1,5 @@ +// Server tuning overlay: multiplies Silver Lions and Research Points rewards by 1.5x. +{ + "rewardMultiplierSilverLions": 1.5, + "rewardMultiplierResearchPoints": 1.5 +} From ada635ecc7ac7fad478ac559205b3b9a0c53edba Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:48:47 +0800 Subject: [PATCH 06/12] refactor(launcher): move experimental mod notice to hover tooltip chip --- .../src/renderer/src/i18n/locales/en.json | 1795 ++++++++--------- .../src/renderer/src/i18n/locales/zh-CN.json | 1795 ++++++++--------- .../src/renderer/src/pages/mods/ModsPage.tsx | 26 +- .../src/renderer/src/styles/pages.css | 82 +- 4 files changed, 1808 insertions(+), 1890 deletions(-) diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 976d004..6bd335b 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -1,939 +1,856 @@ -{ - "app": { - "title": "War Thunder Offline", - "subtitle": "War Thunder offline edition" - }, - "nav": { - "home": "Home", - "saves": "Saves", - "tuning": "Tuning", - "mods": "Mods", - "copies": "Clients", - "settings": "Settings", - "about": "About" - }, - "window": { - "minimize": "Minimize", - "close": "Close" - }, - "language": { - "label": "Language", - "system": "System default", - "zh-CN": "简体中文", - "en": "English" - }, - "footer": { - "launcher": "Launcher {{version}}", - "game": "{{name}} · Game {{version}}", - "notInstalled": "Not installed", - "packUpdate": "Adaptation pack {{version}} available · Update ›", - "appUpdate": "Launcher {{version}} available · Update ›" - }, - "home": { - "kicker": "Local server · AI battles", - "installedKicker": "Game {{version}}", - "body": "Select Install to set up an offline client.", - "steps": { - "choose": "Select game", - "chooseBody": "Locate the game installation", - "method": "Choose installation type", - "methodBody": "Create a client or use an existing folder", - "check": "Check patches", - "checkBody": "Review the features available for this version" - } - }, - "side": { - "requirements": "Installation requirements", - "game": "Game", - "gameValue": "War Thunder (online client)", - "versions": "Verified versions", - "space": "Disk space", - "spaceValue": "About 97 GB (copy installation)", - "currentCopy": "Current client", - "copyName": "Offline client", - "adaptation": "Check status", - "features": "Features", - "allAvailable": "✓ All available", - "someMissing": "⚠ {{count}} unavailable", - "details": "Details" - }, - "adaptation": { - "verified": "✓ Verified", - "unverified": "⚠ Not verified" - }, - "bar": { - "notInstalled": "Not installed", - "notInstalledDetail": "Requires an installed online client of War Thunder", - "install": "Install", - "ready": "Ready", - "readyMissing": "Ready · {{count}} features unavailable", - "readyDetail": "Game {{version}}", - "missingFolder": "Client folder not found", - "launch": "Launch" - }, - "launch": { - "checking": "Checking the client", - "building": "Generating game files", - "starting-server": "Starting local server", - "starting-game": "Starting game", - "starting": "Starting…", - "running": "Game running", - "runningDetail": "Local server · Port {{port}}", - "server-running": "Local server running", - "game-exited": "Game exited", - "gameExitedServerRunning": "Game exited. The local server is still running.", - "exitDetail": "Exit code {{code}}. Game logs: {{path}}", - "exitCodeUnknown": "unknown", - "stopping": "Stopping", - "stopServer": "Close local server", - "cancel": "Cancel", - "stop": "End game", - "retry": "Retry", - "check": "Check", - "version-changed": "The client version has changed", - "versionDetail": "Game version {{version}}", - "port-busy": "Port {{port}} is already in use", - "server-exited": "The local server exited unexpectedly" - }, - "decals": { - "source": "Decal source", - "hint": "Import the online game's cache/content folder. The client uses placeholder decals when no cache is available.", - "choose": "Choose decal cache…", - "useDefault": "Use placeholder decals", - "importing": "Importing decal cache", - "imported": "Imported cache", - "default": "Placeholder decals" - }, - "folder": { - "none": "Not selected", - "choose": "Browse…", - "change": "Change…" - }, - "wizard": { - "title": "Add a client", - "steps": { - "mode": "Setup mode", - "source": "Game location", - "method": "Installation type", - "data": "Data folder", - "check": "Patch check", - "installing": "Install" - }, - "barTitle": "Add a client · {{step}}", - "stepOf": "Step {{index}} of {{total}}", - "back": "Back", - "next": "Next", - "cancel": "Cancel", - "install": "Install", - "installing": "Installing", - "checking": "Checking patches", - "checkingDetail": "Checking which patches apply to the selected game" - }, - "mode": { - "body": "Choose how to add an offline client.", - "newTitle": "Fresh installation from online client", - "newBody": "Create a new offline client from an installed online War Thunder folder via full copy, space-saving copy, or in-place setup.", - "existingTitle": "Add existing offline client", - "existingBody": "Register an already prepared offline client folder directly without copying game files." - }, - "source": { - "body": "Select the folder where War Thunder is installed.", - "dialogTitle": "Select the War Thunder installation folder", - "existingBody": "Select an existing offline client folder.", - "existingDialogTitle": "Select an existing offline client folder", - "offlineBackupDetected": "An existing offline original-file backup (wtoffline\\stock) was detected. This client can be added directly without copying.", - "patchedNeedsStock": "This folder already has offline patches applied but is missing the 4 original core files (wtoffline\\stock). Select an unpatched game folder of the same version; the launcher will read-only copy only those 4 files (~150 MB) without recopying the game.", - "stockSourceTitle": "Select an unpatched War Thunder folder of the same version", - "stockSourcePatched": "The selected folder is also patched and missing an original backup. Choose an unpatched game folder.", - "stockSourceVersionMismatch": "The selected original game version ({{actual}}) does not match this client ({{expected}}).", - "stockSourceReady": "Original core file source ready (version {{version}}). Only the 4 core files will be copied into wtoffline\\stock.", - "notAGame": "The selected folder is not a War Thunder installation. Missing: {{files}}", - "versionVerified": "Game version {{version}} (verified)", - "versionUnverified": "Game version {{version}} has no check record yet. Installing still tries every patch; the patch check shows which features are available.", - "versionUnknown": "unknown", - "size": "Size {{size}} · {{files}} files", - "measuring": "Calculating size…" - }, - "method": { - "copy": "Copy installation (recommended)", - "copyBody": "Copies the game to a new folder. Requires about {{size}} of free space.", - "spaceSaving": "Space-saving copy", - "spaceSavingBody": "Shares read-only resource archives on the same volume. Estimated space required is {{size}}. An in-place update to the source client can change shared files in this client.", - "spaceSavingPending": "Calculating how much space can be saved.", - "spaceSavingUnavailable": "This installation has no read-only resource archives eligible for space-saving copying.", - "sameVolumeRequired": "Select a destination on the same volume as the original installation.", - "targetTitle": "Select an install location (a WTOffline subfolder will be created)", - "targetSubfolderHint": "A dedicated WTOffline folder is automatically created under the selected location to keep game files organized.", - "inPlace": "In-place installation", - "inPlaceBody": "Uses the selected game folder directly as the client. Original files are backed up to wtoffline\\stock, and patches are applied on first launch.", - "existing": "Add existing client", - "existingBody": "Registers the selected existing game folder directly without copying files. If no original backup exists yet, one will be created in wtoffline\\stock.", - "existingBodyWithBackup": "Registers the existing offline client directly, preserving its wtoffline\\stock original-file backup without copying game files.", - "existingBodyWithStockSource": "Registers the existing offline client directly and copies only the 4 original core files from the selected stock folder into wtoffline\\stock.", - "room": "Free space on target drive: {{free}}", - "noRoom": "Not enough free space: {{needed}} required, {{free}} available on the target drive.", - "problem": { - "not_empty": "The selected folder is not empty. Select an empty or new folder.", - "overlaps_stock": "The folder cannot be the online installation folder, or a folder inside or above it.", - "not_a_folder": "The selected path is not a folder." - }, - "copyBodyPending": "Copies the game to a new folder. Calculating the required space." - }, - "steam": { - "inPlaceWarning": "Launching offline will modify the game files in this Steam installation. Steam updates or file verification may overwrite the changes. Launching the online game with modified files may result in an account ban.", - "copyWarning": "The destination is in a Steam library. Choose a folder outside the library to keep the offline client separate.", - "confirm": "Confirm this folder", - "dataWarning": "Steam may remove saves, caches, and logs stored under the game folder when uninstalling the game.", - "maintenanceWarning": "This client or its data folder is in a Steam library. Offline play can change game files in the library. Steam can replace them during an update or file verification. Using modified files online may result in an account ban. Uninstalling the game through Steam may also remove any saves stored under its folder.", - "confirmLocations": "Confirm these locations" - }, - "data": { - "body": "Select a folder for saves, caches, and logs.", - "dialogTitle": "Select the data folder", - "problem": { - "overlaps_client": "The data folder cannot be the client folder, contain the client folder, or lie inside its wtoffline folder. Choose a separate folder or a dedicated subfolder inside the client (for example, data).", - "overlaps_stock": "The data folder cannot lie inside the online installation folder." - } - }, - "check": { - "running": "Checking patches for the selected game version.", - "allFit": "All {{count}} patches apply to this game version.", - "essentialMissing": "A required patch could not be applied. Installation cannot continue. Affected features:", - "someMissing": "{{count}} patches do not apply to this game version. The following features will be unavailable:", - "details": "Patch details", - "accept": "Accept the unavailable features and continue" - }, - "progress": { - "phase": { - "checking": "Checking game files", - "measuring": "Counting files", - "verifying": "Verifying resources to share", - "copying": "Copying game files", - "importing-decals": "Importing decal cache", - "backing-up": "Backing up original files", - "recording": "Finishing installation" - }, - "copied": "Copied {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files", - "verified": "Verified {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files", - "prepared": "Prepared {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files", - "cancelHint": "Can be cancelled at any time; copied files will be deleted", - "cancel": "Cancel installation", - "cancelling": "Cancelling…" - }, - "copies": { - "sections": { - "list": "All clients", - "summary": "Client details", - "features": "Feature status", - "maintain": "Maintenance" - }, - "add": "Add a client", - "missingFolder": "Folder missing", - "relocate": "Relocate…", - "relocateDialogTitle": "Select the moved client folder", - "list": { "current": "Current", "select": "Set as current" }, - "none": "The offline edition is not installed yet.", - "maintenance": { - "update": "Update from online installation", - "updateAction": "Update client", - "newVersion": "Version {{version}} is available from the installation source.", - "updateKeepsSpaceSaving": "Version {{version}} is available. Updating continues sharing read-only resource archives with the source.", - "updateDetaches": "Version {{version}} is available. Because the client and source are on different volumes, updating copies shared resources into independent files and requires additional space.", - "currentVersion": "Installation source version {{version}}", - "noSource": "Installation source unavailable", - "spaceSaving": "Save space", - "spaceSavingHint": "Share identical read-only resource archives with the source. An in-place update to the source client can change the shared files.", - "spaceSavingUnavailable": "Requires a client and source installation of the same version on the same volume.", - "compactAction": "Convert", - "check": "Recheck patches", - "checkHint": "Check the original file backup.", - "lastCheck": "Last checked {{date}}", - "repair": "Repair client", - "repairAction": "Repair", - "repairHint": "Restore the original files from the backup. Game files will be generated again at launch.", - "delete": "Delete client", - "deleteAction": "Delete…", - "deleteHint": "The data folder is kept by default.", - "unlink": "Remove registration", - "unlinkAction": "Remove…", - "unlinkHint": "The launcher keeps the Steam game files and data folder in place.", - "unlinkLocation": "Remove the launcher's registration for {{path}}? Steam game files and data will stay in place.", - "deleteLocation": "Delete the offline client at {{path}}?", - "deleteData": "Also delete the data folder at {{path}}", - "confirm": "Confirm deletion", - "phase": { - "checking": "Checking the client", - "copying": "Copying changed files", - "applying": "Applying changes" - }, - "result": { - "confirm-steam": "Steam locations confirmed.", - "check": "Patch check complete.", - "repair": "Original files restored.", - "update": "Client updated.", - "compact": "Space-saving conversion complete.", - "delete": "Client deleted.", - "cancelled": "Maintenance cancelled." - } - }, - "summary": { - "name": "Client name", - "rename": "Rename", - "source": "Installation source", - "version": "Game version", - "adaptation": "Check status", - "adaptationHint": "Whether every patch was checked on this game version and verified in game", - "location": "Location", - "missingHint": "Game files were not found at this path. Relocate to the moved folder to keep existing saves and tuning.", - "method": "Installation type", - "methods": { - "copy": "Copy installation", - "hardlink": "Space-saving copy", - "in-place": "In-place installation", - "existing": "Existing client" - }, - "stock": "Original file backup", - "stockHint": "Patched files are generated from it at each launch", - "data": "Data folder", - "dataHint": "Saves, caches and logs", - "installedAt": "Installed", - "features": "Features", - "open": "Open" - }, - "features": { - "lead": "Patch compatibility determines which features are available. Installation requires all essential patches.", - "essential": "Required", - "verifiedOn": "Verified: {{version}}", - "passedCheck": "Passed the patch check (this game version is not verified)", - "unavailable": "Patch does not apply: {{patches}}", - "allAvailable": "All available", - "someMissing": "{{count}} unavailable", - "checkedAt": "Checked {{time}} (at installation)" - } - }, - "featureSections": { - "A": "Startup and account", - "B": "Hangar and vehicles", - "C": "Tech tree and research", - "D": "Modifications, weapons and ammunition", - "E": "Crew", - "F": "Customization", - "G": "Economy and store", - "H": "Items and inventory", - "I": "Squadrons", - "J": "Game modes", - "K": "In battle", - "L": "After battle and statistics", - "M": "Replays", - "N": "Settings, controls and mods", - "O": "Multiplayer social features" - }, - "saves": { - "sections": { - "list": "All saves", - "overview": "Overview", - "battles": "Battle history", - "vehicles": "Vehicles and research", - "official": "Import online data", - "backup": "Backup and restore" - }, - "tree": { - "branch": "Country and vehicle type", - "country": "Country", - "type": "Vehicle type", - "actions": "Bulk actions", - "research": "Research all", - "purchase": "Grant regular vehicles", - "equipment": "Unlock modifications", - "empty": "This client has no eligible research branches.", - "rank": "Rank {{rank}}", - "owned": "Owned", - "points": "{{earned}} / {{needed}} RP", - "countries": { - "country_usa": "United States", - "country_germany": "Germany", - "country_ussr": "USSR", - "country_britain": "Great Britain", - "country_japan": "Japan", - "country_china": "China", - "country_italy": "Italy", - "country_france": "France", - "country_sweden": "Sweden", - "country_israel": "Israel" - }, - "types": { - "Aircraft": "Aircraft", - "Tank": "Ground vehicles", - "Ship": "Bluewater fleet", - "Boat": "Coastal fleet", - "Helicopter": "Helicopters" - } - }, - "official": { - "auto": "Automatic import", - "autoHint": "Locates local online data read-only, copies it into the offline folder, and imports from the copy without modifying the online files.", - "oneClick": "Find and import", - "discover": "Find and preview", - "notFound": "No online data was found in the default Documents folder. Use manual file selection below.", - "account": "Online account", - "multipleAccounts": "{{count}} online account folders were found. Select the account to import.", - "accountOption": "Account {{id}} ({{files}} · updated {{time}})", - "files": "Manual selection", - "fileHint": "Or select copied global.blk, machine.blk or storage.blk files manually.", - "choose": "Choose files…", - "content": "Import contents", - "settings": "Game settings and controls", - "unlock": "Unlock vehicles from presets", - "equipment": "Modifications", - "equipmentHint": "All equipment unlocks regular modifications and ammunition only, without talismans.", - "full": "All equipment", - "basic": "Essential equipment", - "stock": "Stock configuration", - "preview": "Preview", - "import": "Import", - "summary": "{{files}} file(s) · {{presets}} preset(s) · {{vehicles}} available vehicle(s)", - "omitted": "Unavailable vehicles to skip · {{names}}", - "done": "Online data imported. The previous save is available in Backup and restore." - }, - "archive": { - "fromCopy": "Copy from another client", - "import": "Import save file…", - "sourceCopy": "Source client", - "transfer": "Create from save", - "copy": "Copy", - "export": "Export…", - "delete": "Delete…", - "confirmDelete": "Delete the local account and save for {{name}}?", - "automatic": "Back up before launch", - "retention": "The latest 10 automatic backups are retained for each save.", - "backup": "Back up now", - "restore": "Restore", - "noBackups": "There are no backups for this save.", - "confirmRestore": "Restore this backup? The current save will be backed up first.", - "type": { - "manual": "Manual backup", - "launch": "Before launch", - "restore": "Before restore", - "import": "Before import" - } - }, - "create": "Create save", - "login": "Login", - "nick": "Nickname", - "password": "Password", - "confirmPassword": "Confirm password", - "passwordMismatch": "The passwords do not match.", - "readOnly": "The local server or game is running. Saves are read-only.", - "noCopy": "Select an offline client to manage its saves.", - "empty": "There are no local saves for this client.", - "loading": "Loading save", - "silverLions": "Silver Lions", - "goldenEagles": "Golden Eagles", - "gjnCents": "GJN", - "freeRp": "Free research points", - "vehicles": "Vehicles", - "battles": "Recorded battles", - "lastBattle": "Last battle", - "premiumDays": "Premium account days", - "avatar": "Avatar", - "avatarUnavailable": "Avatar unavailable", - "level": "Account level", "apply": "Save changes", - "saved": "Changes saved.", - "noBattles": "The save has no recorded battles.", - "win": "Victory", - "loss": "Defeat", - "battleRewards": "{{sl}} Silver Lions · {{rp}} research points", - "owned": "Owned vehicles", - "research": "Research progress" - }, - "tuning": { - "sections": { - "rewards": "Rewards", - "battle": "Battles", - "newProfile": "New saves", - "research": "Research" - }, - "fields": { - "rewardMultiplierSilverLions": "Silver Lions multiplier", - "rewardMultiplierResearchPoints": "Research points multiplier", - "friendlyKillPenaltyMul": "Friendly-fire penalty multiplier", - "maxPlayers": "Player limit per battle", - "smallTeamsMaxPlayers": "Small teams player limit", - "brSpreadMrank": "Matchmaking BR range", - "subModeChance": "Sub-mode probability", - "tankBotRespawns": "AI tank respawns", - "airBotRespawns": "AI aircraft respawns", - "strikeUcavSpawnScore": "Strike UCAV spawn points", - "silverLions": "Starting Silver Lions", - "goldenEagles": "Starting Golden Eagles", - "preferLineSuccessor": "Prefer the next vehicle in the line", - "autoTargetPick": "Automatic research target" - }, - "target": { - "lowestRank": "Lowest rank", - "highestRank": "Highest rank", - "treeOrder": "Research tree order" - }, - "shared": "These settings apply to all saves in this client.", - "nextLaunch": "Changes take effect the next time the local server starts.", - "reset": "Restore defaults for this section", - "default": "Default {{value}}", - "on": "Enabled", - "off": "Disabled", - "saved": "Tuning values saved.", - "invalid": "Enter values within the supported range.", - "loading": "Loading tuning values", - "noCopy": "Select an offline client to edit its tuning values." - }, - "settings": { - "sections": { - "general": "General", - "launch": "Launch", - "dev": "Developer", - "diag": "Diagnostics" - }, - "appUpdates": "Launcher updates", - "appUpdatesToggle": "Check for launcher updates at start", - "patchPacks": "Adaptation pack updates", - "patchPacksHint": "After a game update, the patches for the new version are released on GitHub as an adaptation pack.", - "updateMirror": "Update mirror repository", - "updateMirrorHint": "Enter an HTTPS mirror with a GitHub-compatible releases list. It is used if the primary source is unreachable. Leave blank to disable it.", - "updateMirrorInvalid": "Enter a valid HTTPS repository address or leave the field blank.", - "patchPacksToggle": "Check for a new adaptation pack at start", - "windowClose": "When closing the window", - "windowQuit": "Quit launcher", - "windowTray": "Minimize to system tray", - "afterGameStarts": "When the game starts", - "windowMinimize": "Minimize launcher", - "windowKeep": "Keep window open", - "launch": { - "port": "Local server port", - "portHint": "Port set by the installed lab automation", - "exit": "When the game exits", - "exitHint": "Isolated launch", - "automatic": "Close local server", - "portMode": "Port assignment", - "autoPort": "Assign automatically", - "fixedPort": "Specify port", - "arguments": "Additional arguments", - "argumentsHint": "Command-line arguments passed to the game", - "argumentsInvalid": "Close each double quote in the launch arguments." - }, - "developer": { - "mode": "Developer mode", - "modeHint": "Launches the lab client under the wto-lab Windows account", - "enabled": "Enabled", - "stock": "Stock backup", - "stockHint": "Defaults to the selected client’s stock backup", - "data": "Lab data folder", - "dataHint": "Defaults to the selected client’s data folder", - "reset": "Restore default" - }, - "diagnostics": { - "recordLogs": "Record runtime logs", - "recordLogsToggle": "Write launcher, local server, and hook logs", - "recordLogsHint": "When disabled, stops writing launcher logs, local server traffic logs, and wto_ws.log (the game engine's own .game_logs are unaffected). Re-enable before exporting logs for troubleshooting.", - "loggingDisabledNotice": "Runtime logging is currently disabled; exported archives include only existing logs and configuration.", - "logs": "Logs", - "logsHint": "Logs recorded by the launcher", - "openLogs": "Open log folder", - "export": "Export diagnostics", - "exportHint": "Save launcher, local server, and game logs, settings, and the installation record to a ZIP file (excludes saves)", - "save": "Export…", - "saved": "Diagnostics saved to {{path}}.", - "serverStatus": "Local server status", - "openStatus": "Open in browser" - }, - "language": "Language", - "languageHint": "Display language of the launcher" - }, - "background": { - "title": "Background", - "hint": "Game backgrounds come from the current client.", - "official": "Website wallpapers", - "officialHint": "Downloads wallpapers from the official website. Downloaded wallpapers are available offline.", - "officialToggle": "Get wallpapers from the War Thunder website", - "officialItem": "Website · {{name}}", - "random": "Random", - "none": "No background pictures are available. Install a client to use the game pictures, or turn on website wallpapers.", - "current": "Background: {{name}}", - "previous": "Previous", - "next": "Next", - "nations": { - "default": "General", - "usa": "USA", - "germany": "Germany", - "ussr": "USSR", - "uk": "Great Britain", - "japan": "Japan", - "china": "China", - "italy": "Italy", - "france": "France", - "sweden": "Sweden", - "israel": "Israel" - } - }, - "about": { - "launcher": "Launcher {{version}}", - "supported": "Supported game versions: {{versions}}", - "feedback": { - "title": "Feedback and logs", - "export": "Save all logs", - "exportHint": "Pack launcher, local server, and game logs into a ZIP file for issue reports (excludes saves).", - "exportButton": "Save log ZIP…" - }, - "pack": { - "title": "Adaptation data", - "current": "In use", - "currentHint": "The patches used to install and update clients.", - "bundled": "Included with the launcher", - "bundledVersion": "Included with the launcher ({{version}})", - "downloaded": "Adaptation pack {{version}}", - "useBundled": "Go back to the included patches", - "check": "Check for updates", - "checkHint": "Checks for a new adaptation pack.", - "checkButton": "Check", - "checking": "Checking…", - "applying": "Downloading and verifying the adaptation pack…", - "upToDate": "Up to date (the newest adaptation pack is {{version}}).", - "noneReleased": "No adaptation pack has been released yet.", - "available": "Adaptation pack {{version}} is available. Supported game versions: {{versions}}.", - "availableHint": "Its signature is verified before it is used. Installing and updating clients then use the new patches.", - "apply": "Download and use {{version}}", - "needsAppUpdate": "Adaptation pack {{version}} needs offline version {{app}} or newer. Update the offline version first.", - "checkFailed": { - "no_signing_key": "This launcher has no signing key built in, so it accepts no adaptation pack.", - "network": "The update source could not be reached. Try again later.", - "page_limit": "Could not confirm whether a newer adaptation pack is available.", - "contents": "The released adaptation pack is incomplete or malformed.", - "signature": "The adaptation pack's signature is wrong. It was refused.", - "size": "The adaptation pack is larger than allowed. It was refused." - }, - "applyFailed": { - "no_signing_key": "This launcher has no signing key built in, so it accepts no adaptation pack.", - "network": "Could not reach the update source to download the adaptation pack. Try again later.", - "page_limit": "Could not confirm whether a newer adaptation pack is available.", - "contents": "The adaptation pack is incomplete or malformed. It is not in use.", - "signature": "The adaptation pack's signature is wrong. It was refused and is not in use.", - "size": "The adaptation pack is larger than allowed. It was refused.", - "needs_app_update": "This adaptation pack needs a newer offline version. Update the offline version first.", - "up_to_date": "Up to date: there is no adaptation pack to download." - } - }, - "update": { - "title": "Launcher update", - "check": "Launcher version check", - "checking": "Checking…", - "current": "The launcher is up to date.", - "available": "Version {{version}} is available. Installer size {{size}}.", - "downloading": "Downloading the installer…", - "download": "Download update", - "install": "Quit and install", - "installing": "Opening the installer…", - "mods": { - "sections": { - "list": "Mod list", - "presets": "Presets & repository" - }, - "loading": "Loading mods…", - "noCopy": "Install or select an offline client first to configure its mods.", - "enabledSummary": "{{enabled}} / {{total}} enabled", - "experimentalTitle": "Experimental mod API notice:", - "experimentalBody": "WTOffline is in early development (API {{api}}). Server script hooks, internal data structures, and declarative exe patch contracts may change at any time without backwards compatibility; only enable mods from trusted sources.", - "readOnlyNotice": "Mod toggles, load order, and presets are read-only while the game, local server, or maintenance is running.", - "searchPlaceholder": "Filter by mod name, ID, or author…", - "autoSort": "Auto-sort by dependencies", - "autoSorted": "Reordered mods based on dependencies and load-order hints.", - "refresh": "Refresh", - "openFolder": "Open mods folder", - "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):", - "severity": { - "error": "Error", - "warning": "Warning", - "info": "Info" - }, - "emptyTitle": "No mods found in the global mods folder yet.", - "emptyHint": "Place mod folders containing mod.jsonc into {{path}}, then click Refresh. Standalone skins, sights, and user missions continue to work directly via the game's native UserSkins / UserSights / UserMissions folders.", - "noSearchMatch": "No mods match the current search filter.", - "loadOrderHint": "Load order: lower items load later and take higher priority (drag or use arrows)", - "moveUp": "Move up", - "moveDown": "Move down", - "showDetails": "Details", - "hideDetails": "Hide", - "errorCount": "{{count}} error", - "warnCount": "{{count}} warn", - "badges": { - "data": "Data / Assets", - "gui": "GUI Patch", - "script": "Server Script", - "exe": "Exe Patch" - }, - "details": { - "folder": "Folder", - "gameVersions": "Declared game versions", - "requires": "Requires", - "conflicts": "Conflicts", - "tuning": "Server tuning overlays: {{count}}", - "serverScript": "Executable server JS/TS script", - "packOps": "Client pack operations: {{count}}", - "addon": "3D model / texture addon: {{count}} file(s)", - "guiPatches": "GUI script patches: {{count}}", - "exePatches": "Declarative exe patches: {{count}}", - "companionFiles": "Companion files: {{count}}", - "configBlk": "Includes config.blk patch" - }, - "presets": { - "heading": "Mod presets (saved per client)", - "description": "Save the current mod toggles and load order as named presets for quick switching or JSON export/import.", - "quickSwitch": "Switch mod preset", - "customOption": "Custom active selection", - "namePlaceholder": "New preset name, e.g. Modern Vehicles", - "saveCurrent": "Save preset", - "import": "Import preset…", - "empty": "No presets saved for this client yet.", - "activeTag": "Active", - "summary": "{{count}} enabled / {{total}} tracked", - "apply": "Apply", - "overwrite": "Update", - "export": "Export", - "delete": "Delete", - "saved": "Saved preset \"{{name}}\".", - "applied": "Applied preset \"{{name}}\".", - "updated": "Updated preset \"{{name}}\" with current setup.", - "exported": "Exported preset to: {{path}}", - "imported": "Imported mod preset." - }, - "repo": { - "heading": "Global mods repository", - "description": "All clients share one mod folder (large 3D model and texture addons mount across drives via NTFS Junctions with zero copying), while each client keeps its own toggles, load order, and presets.", - "pathLabel": "Repository folder", - "defaultNote": "Using launcher default mods folder", - "customNote": "Using custom mods folder (can live on a larger drive or the same drive as your client)", - "changeFolder": "Change folder…", - "resetDefault": "Reset to default", - "pickTitle": "Select global mods repository folder", - "updated": "Updated global mods repository folder.", - "resetDone": "Reset to default mods repository folder." - } - }, - "errors": { - "network": "The update source could not be reached.", - "page_limit": "Could not confirm whether a newer version is available.", - "contents": "The launcher release information is invalid.", - "signature": "The launcher update signature could not be verified.", - "no_signing_key": "The launcher update verification key is unavailable." - } - }, - "statement": "Project information", - "statementBody": "WTOffline is a noncommercial hobby project independent of Gaijin. Running it requires your own War Thunder base game files.", - "community": { - "discord": "Discord", - "discordHint": "Development discussion, general chat, troubleshooting, and bug reports.", - "openDiscord": "Open Discord" - } - }, - "features": { - "A-Offline startup": "Offline startup", - "A-Local accounts": "Local accounts", - "A-Isolation from the official game": "Isolation from the online game", - "A-No Gaijin connections": "Gaijin connections blocked", - "A-Tutorials": "Tutorial", - "B-Hangar and vehicles": "Hangar and vehicles", - "G-Store": "Store", - "G-Redeem codes": "Redeem codes", - "G-Marketplace": "Marketplace", - "G-Currencies": "Currency purchase", - "G-Premium account": "Premium account", - "G-Boosters": "Boosters", - "H-Contracts and wagers": "Battle contracts", - "H-Supply chests": "Supply chests", - "H-Recycling and crafting": "Item recycling and crafting", - "H-Coupons": "Coupons", - "J-Game modes": "Game modes", - "J-Ground arcade and realistic": "Ground battles (arcade, realistic)", - "J-Air arcade and realistic": "Air battles (arcade, realistic)", - "J-Naval arcade and realistic": "Naval battles (arcade, realistic)", - "E-Crew skills in battle": "Crew skills and qualifications in battle", - "J-Sub-modes": "Additional modes (such as night battles)", - "K-AI opponents and teammates": "AI opponents and allies", - "K-Spawn score and respawns": "Spawn points and respawning", - "K-Scouting": "Scouting and drones", - "K-Kill, assist and capture scoring": "Kill, assist and capture scoring", - "K-Player damage notices": "Player damage notices", - "K-Additional vehicles": "Additional vehicles", - "K-Scoreboard": "Scoreboard", - "K-Chat and radio": "Chat and radio", - "K-Nuclear bomb": "Nuclear bomb", - "L-Debriefing": "Battle results", - "L-Battle awards": "Battle awards" - }, - "mods": { - "sections": { - "list": "Mod list", - "presets": "Presets & repository" - }, - "loading": "Loading mods…", - "noCopy": "Install or select an offline client first to configure its mods.", - "enabledSummary": "{{enabled}} / {{total}} enabled", - "experimentalTitle": "Experimental mod API notice:", - "experimentalBody": "WTOffline is in early development (API {{api}}). Server script hooks, internal data structures, and declarative exe patch contracts may change at any time without backwards compatibility; only enable mods from trusted sources.", - "readOnlyNotice": "Mod toggles, load order, and presets are read-only while the game, local server, or maintenance is running.", - "searchPlaceholder": "Filter by mod name, ID, or author…", - "autoSort": "Auto-sort by dependencies", - "autoSorted": "Reordered mods based on dependencies and load-order hints.", - "refresh": "Refresh", - "openFolder": "Open mods folder", - "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):", - "severity": { - "error": "Error", - "warning": "Warning", - "info": "Info" - }, - "emptyTitle": "No mods found in the global mods folder yet.", - "emptyHint": "Place mod folders containing mod.jsonc into {{path}}, then click Refresh. Standalone skins, sights, and user missions continue to work directly via the game's native UserSkins / UserSights / UserMissions folders.", - "noSearchMatch": "No mods match the current search filter.", - "loadOrderHint": "Load order: lower items load later and take higher priority (drag or use arrows)", - "moveUp": "Move up", - "moveDown": "Move down", - "showDetails": "Details", - "hideDetails": "Hide", - "errorCount": "{{count}} error", - "warnCount": "{{count}} warn", - "badges": { - "data": "Data / Assets", - "gui": "GUI Patch", - "script": "Server Script", - "exe": "Exe Patch" - }, - "details": { - "folder": "Folder", - "gameVersions": "Declared game versions", - "requires": "Requires", - "conflicts": "Conflicts", - "tuning": "Server tuning overlays: {{count}}", - "serverScript": "Executable server JS/TS script", - "packOps": "Client pack operations: {{count}}", - "addon": "3D model / texture addon: {{count}} file(s)", - "guiPatches": "GUI script patches: {{count}}", - "exePatches": "Declarative exe patches: {{count}}", - "companionFiles": "Companion files: {{count}}", - "configBlk": "Includes config.blk patch" - }, - "presets": { - "heading": "Mod presets (saved per client)", - "description": "Save the current mod toggles and load order as named presets for quick switching or JSON export/import.", - "quickSwitch": "Switch mod preset", - "customOption": "Custom active selection", - "namePlaceholder": "New preset name, e.g. Modern Vehicles", - "saveCurrent": "Save preset", - "import": "Import preset…", - "empty": "No presets saved for this client yet.", - "activeTag": "Active", - "summary": "{{count}} enabled / {{total}} tracked", - "apply": "Apply", - "overwrite": "Update", - "export": "Export", - "delete": "Delete", - "saved": "Saved preset \"{{name}}\".", - "applied": "Applied preset \"{{name}}\".", - "updated": "Updated preset \"{{name}}\" with current setup.", - "exported": "Exported preset to: {{path}}", - "imported": "Imported mod preset." - }, - "repo": { - "heading": "Global mods repository", - "description": "All clients share one mod folder (large 3D model and texture addons mount across drives via NTFS Junctions with zero copying), while each client keeps its own toggles, load order, and presets.", - "pathLabel": "Repository folder", - "defaultNote": "Using launcher default mods folder", - "customNote": "Using custom mods folder (can live on a larger drive or the same drive as your client)", - "changeFolder": "Change folder…", - "resetDefault": "Reset to default", - "pickTitle": "Select global mods repository folder", - "updated": "Updated global mods repository folder.", - "resetDone": "Reset to default mods repository folder." - } - }, - "errors": { - "app_update_unavailable": "There is no launcher update available to install.", - "app_update_busy": "A launcher update operation is already in progress.", - "app_update_launcher_busy": "Close the game and local server and finish any client or save operations before updating.", - "app_update_download_failed": "The launcher installer could not be downloaded and verified. See the launcher log.", - "app_update_installer_invalid": "The installer failed verification. Download it again.", - "app_update_install_failed": "The launcher installer could not be opened. See the launcher log.", - "internal_error": "An internal launcher error occurred.", - "logs_folder_open_failed": "The launcher log folder could not be opened.", - "diagnostics_export_failed": "The diagnostics archive could not be saved.", - "save_official_invalid": "The selected files are not supported online data files.", - "save_official_location": "Choose data files copied outside the online game's folders.", - "save_archive_invalid": "The selected file is not a supported WTOffline save archive.", - "save_not_found": "The selected save could not be found.", - "save_read_only": "Saves are read-only while the game or local server is running.", - "save_operation_failed": "The save operation failed. See the launcher log.", - "save_login_invalid": "Enter a login without spaces.", - "save_login_exists": "An account with this login already exists.", - "save_password_invalid": "Enter a password.", - "save_nick_invalid": "Enter a nickname with up to 16 characters.", - "save_avatar_invalid": "Select an avatar available in this client.", - "save_level_invalid": "Enter a level supported by this client.", - "tuning_invalid": "The tuning values could not be read or saved. Check the session limits and the launcher log.", - "mods_read_only": "Mods cannot be changed while the game, local server, or maintenance is running.", - "mods_write_failed": "The mod configuration could not be saved. See the launcher log.", - "mods_preset_invalid": "The selected file is not a valid WTOffline mod preset.", - "mods_blocking_issues": "Enabled mods have missing dependencies or conflicts. Resolve them on the Mods page before launching.", - "mods_folder_invalid": "The selected global mods folder is invalid or not writable.", - "copy_not_found": "The selected client is no longer available.", - "copies_write_failed": "The client registry could not be saved.", - "copy_location_in_use": "The client or data location overlaps an existing client.", - "decal_source_invalid": "The selected folder does not contain a usable decal cache.", - "decal_import_failed": "The decal cache could not be imported into the client's data folder. See the launcher log.", - "maintenance_busy": "Maintenance requires the game, local server and other client operations to be stopped.", - "maintenance_location": "The operation would affect files outside the registered client or data folder.", - "maintenance_no_update": "A newer version is unavailable at the installation source.", - "maintenance_cancelled": "The client update was cancelled.", - "maintenance_failed": "Client maintenance failed. See the launcher log.", - "maintenance_source_changed": "The installation source changed during the update. Retry once its update is complete.", - "launch_no_copy": "An offline client must be installed before launching.", - "launch_busy": "A launch is already in progress.", - "launch_failed": "Launch failed. See the launcher log.", - "launch_platform_unsupported": "Game launch requires Windows.", - "launch_lab_required": "Enable developer mode to launch through the isolated lab.", - "launch_lab_missing": "The isolated lab automation could not be loaded.", - "launch_lab_version": "The lab client and the stock backup must use the same game version.", - "launch_lab_failed": "The isolated launch failed. See the launcher log.", - "launch_game_running": "Another game process is running.", - "launch_copy_in_steam": "The development lab requires a client and data folder outside Steam.", - "launch_steam_confirmation_required": "Confirm the Steam locations in Client Maintenance before launching.", - "launch_location": "The client, stock backup, or data folder location is invalid.", - "launch_stock_version": "The stock backup and client versions do not match.", - "launch_stock_missing": "The original file backup (wtoffline\\stock) is missing or unreadable. Check your security software, or remove this client entry and add it again.", - "launch_build_failed": "The game files could not be generated.", - "launch_build_unavailable": "The build found unavailable patches that require review.", - "launch_port_busy": "The local server port is already in use.", - "launch_server_failed": "The local server could not be started. See the launcher log.", - "launch_server_exited": "The local server is unavailable.", - "launch_game_failed": "The game process could not start. See the launcher log.", - "launch_game_files_missing": "Required game launch files are missing or unreadable (they may have been quarantined by antivirus software). Check your security software and the launcher log.", - "settings_write_failed": "The settings could not be saved.", - "folder_unreadable": "The folder cannot be read: {{path}}", - "not_a_game_folder": "The selected folder is not a War Thunder installation: {{path}}", - "stock_source_invalid": "This client is already patched and lacks an original backup. Select an unpatched game folder of the same version.", - "stock_source_version_mismatch": "The selected original game version ({{actual}}) does not match the client version ({{expected}}).", - "target_not_usable": "The selected folder cannot be used for installation.", - "steam_library_not_confirmed": "The client or data folder is in a Steam library. Confirm the risk notice first.", - "not_enough_space": "Not enough disk space: {{neededGb}} GB required, {{freeGb}} GB available.", - "essential_patches_unavailable": "Patches required by the offline edition do not apply to this game version. Installation is not possible: {{patches}}", - "missing_features_not_accepted": "Some patches do not apply. Confirm whether to continue without the affected features.", - "patch_check_failed": "An error occurred while checking patches.", - "copy_failed": "Copying the game files failed. The copied files have been deleted.", - "hardlink_unavailable": "Space-saving copying requires the destination and source to be on the same volume, and converting an existing client also requires matching versions.", - "hardlink_no_match": "No matching read-only resource archives were found, or their contents differ from the source.", - "hardlink_file_changed": "A resource changed during verification or copying. Finish any other file operation, then retry.", - "install_cancelled": "Installation cancelled. The copied files have been deleted.", - "install_busy": "An installation is already in progress.", - "unknown": "An unknown error occurred." - } -} +{ + "app": { + "title": "War Thunder Offline", + "subtitle": "War Thunder offline edition" + }, + "nav": { + "home": "Home", + "saves": "Saves", + "tuning": "Tuning", + "mods": "Mods", + "copies": "Clients", + "settings": "Settings", + "about": "About" + }, + "window": { + "minimize": "Minimize", + "close": "Close" + }, + "language": { + "label": "Language", + "system": "System default", + "zh-CN": "简体中文", + "en": "English" + }, + "footer": { + "launcher": "Launcher {{version}}", + "game": "{{name}} · Game {{version}}", + "notInstalled": "Not installed", + "packUpdate": "Adaptation pack {{version}} available · Update ›", + "appUpdate": "Launcher {{version}} available · Update ›" + }, + "home": { + "kicker": "Local server · AI battles", + "installedKicker": "Game {{version}}", + "body": "Select Install to set up an offline client.", + "steps": { + "choose": "Select game", + "chooseBody": "Locate the game installation", + "method": "Choose installation type", + "methodBody": "Create a client or use an existing folder", + "check": "Check patches", + "checkBody": "Review the features available for this version" + } + }, + "side": { + "requirements": "Installation requirements", + "game": "Game", + "gameValue": "War Thunder (online client)", + "versions": "Verified versions", + "space": "Disk space", + "spaceValue": "About 97 GB (copy installation)", + "currentCopy": "Current client", + "copyName": "Offline client", + "adaptation": "Check status", + "features": "Features", + "allAvailable": "✓ All available", + "someMissing": "⚠ {{count}} unavailable", + "details": "Details" + }, + "adaptation": { + "verified": "✓ Verified", + "unverified": "⚠ Not verified" + }, + "bar": { + "notInstalled": "Not installed", + "notInstalledDetail": "Requires an installed online client of War Thunder", + "install": "Install", + "ready": "Ready", + "readyMissing": "Ready · {{count}} features unavailable", + "readyDetail": "Game {{version}}", + "missingFolder": "Client folder not found", + "launch": "Launch" + }, + "launch": { + "checking": "Checking the client", + "building": "Generating game files", + "starting-server": "Starting local server", + "starting-game": "Starting game", + "starting": "Starting…", + "running": "Game running", + "runningDetail": "Local server · Port {{port}}", + "server-running": "Local server running", + "game-exited": "Game exited", + "gameExitedServerRunning": "Game exited. The local server is still running.", + "exitDetail": "Exit code {{code}}. Game logs: {{path}}", + "exitCodeUnknown": "unknown", + "stopping": "Stopping", + "stopServer": "Close local server", + "cancel": "Cancel", + "stop": "End game", + "retry": "Retry", + "check": "Check", + "version-changed": "The client version has changed", + "versionDetail": "Game version {{version}}", + "port-busy": "Port {{port}} is already in use", + "server-exited": "The local server exited unexpectedly" + }, + "decals": { + "source": "Decal source", + "hint": "Import the online game's cache/content folder. The client uses placeholder decals when no cache is available.", + "choose": "Choose decal cache…", + "useDefault": "Use placeholder decals", + "importing": "Importing decal cache", + "imported": "Imported cache", + "default": "Placeholder decals" + }, + "folder": { + "none": "Not selected", + "choose": "Browse…", + "change": "Change…" + }, + "wizard": { + "title": "Add a client", + "steps": { + "mode": "Setup mode", + "source": "Game location", + "method": "Installation type", + "data": "Data folder", + "check": "Patch check", + "installing": "Install" + }, + "barTitle": "Add a client · {{step}}", + "stepOf": "Step {{index}} of {{total}}", + "back": "Back", + "next": "Next", + "cancel": "Cancel", + "install": "Install", + "installing": "Installing", + "checking": "Checking patches", + "checkingDetail": "Checking which patches apply to the selected game" + }, + "mode": { + "body": "Choose how to add an offline client.", + "newTitle": "Fresh installation from online client", + "newBody": "Create a new offline client from an installed online War Thunder folder via full copy, space-saving copy, or in-place setup.", + "existingTitle": "Add existing offline client", + "existingBody": "Register an already prepared offline client folder directly without copying game files." + }, + "source": { + "body": "Select the folder where War Thunder is installed.", + "dialogTitle": "Select the War Thunder installation folder", + "existingBody": "Select an existing offline client folder.", + "existingDialogTitle": "Select an existing offline client folder", + "offlineBackupDetected": "An existing offline original-file backup (wtoffline\\stock) was detected. This client can be added directly without copying.", + "patchedNeedsStock": "This folder already has offline patches applied but is missing the 4 original core files (wtoffline\\stock). Select an unpatched game folder of the same version; the launcher will read-only copy only those 4 files (~150 MB) without recopying the game.", + "stockSourceTitle": "Select an unpatched War Thunder folder of the same version", + "stockSourcePatched": "The selected folder is also patched and missing an original backup. Choose an unpatched game folder.", + "stockSourceVersionMismatch": "The selected original game version ({{actual}}) does not match this client ({{expected}}).", + "stockSourceReady": "Original core file source ready (version {{version}}). Only the 4 core files will be copied into wtoffline\\stock.", + "notAGame": "The selected folder is not a War Thunder installation. Missing: {{files}}", + "versionVerified": "Game version {{version}} (verified)", + "versionUnverified": "Game version {{version}} has no check record yet. Installing still tries every patch; the patch check shows which features are available.", + "versionUnknown": "unknown", + "size": "Size {{size}} · {{files}} files", + "measuring": "Calculating size…" + }, + "method": { + "copy": "Copy installation (recommended)", + "copyBody": "Copies the game to a new folder. Requires about {{size}} of free space.", + "spaceSaving": "Space-saving copy", + "spaceSavingBody": "Shares read-only resource archives on the same volume. Estimated space required is {{size}}. An in-place update to the source client can change shared files in this client.", + "spaceSavingPending": "Calculating how much space can be saved.", + "spaceSavingUnavailable": "This installation has no read-only resource archives eligible for space-saving copying.", + "sameVolumeRequired": "Select a destination on the same volume as the original installation.", + "targetTitle": "Select an install location (a WTOffline subfolder will be created)", + "targetSubfolderHint": "A dedicated WTOffline folder is automatically created under the selected location to keep game files organized.", + "inPlace": "In-place installation", + "inPlaceBody": "Uses the selected game folder directly as the client. Original files are backed up to wtoffline\\stock, and patches are applied on first launch.", + "existing": "Add existing client", + "existingBody": "Registers the selected existing game folder directly without copying files. If no original backup exists yet, one will be created in wtoffline\\stock.", + "existingBodyWithBackup": "Registers the existing offline client directly, preserving its wtoffline\\stock original-file backup without copying game files.", + "existingBodyWithStockSource": "Registers the existing offline client directly and copies only the 4 original core files from the selected stock folder into wtoffline\\stock.", + "room": "Free space on target drive: {{free}}", + "noRoom": "Not enough free space: {{needed}} required, {{free}} available on the target drive.", + "problem": { + "not_empty": "The selected folder is not empty. Select an empty or new folder.", + "overlaps_stock": "The folder cannot be the online installation folder, or a folder inside or above it.", + "not_a_folder": "The selected path is not a folder." + }, + "copyBodyPending": "Copies the game to a new folder. Calculating the required space." + }, + "steam": { + "inPlaceWarning": "Launching offline will modify the game files in this Steam installation. Steam updates or file verification may overwrite the changes. Launching the online game with modified files may result in an account ban.", + "copyWarning": "The destination is in a Steam library. Choose a folder outside the library to keep the offline client separate.", + "confirm": "Confirm this folder", + "dataWarning": "Steam may remove saves, caches, and logs stored under the game folder when uninstalling the game.", + "maintenanceWarning": "This client or its data folder is in a Steam library. Offline play can change game files in the library. Steam can replace them during an update or file verification. Using modified files online may result in an account ban. Uninstalling the game through Steam may also remove any saves stored under its folder.", + "confirmLocations": "Confirm these locations" + }, + "data": { + "body": "Select a folder for saves, caches, and logs.", + "dialogTitle": "Select the data folder", + "problem": { + "overlaps_client": "The data folder cannot be the client folder, contain the client folder, or lie inside its wtoffline folder. Choose a separate folder or a dedicated subfolder inside the client (for example, data).", + "overlaps_stock": "The data folder cannot lie inside the online installation folder." + } + }, + "check": { + "running": "Checking patches for the selected game version.", + "allFit": "All {{count}} patches apply to this game version.", + "essentialMissing": "A required patch could not be applied. Installation cannot continue. Affected features:", + "someMissing": "{{count}} patches do not apply to this game version. The following features will be unavailable:", + "details": "Patch details", + "accept": "Accept the unavailable features and continue" + }, + "progress": { + "phase": { + "checking": "Checking game files", + "measuring": "Counting files", + "verifying": "Verifying resources to share", + "copying": "Copying game files", + "importing-decals": "Importing decal cache", + "backing-up": "Backing up original files", + "recording": "Finishing installation" + }, + "copied": "Copied {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files", + "verified": "Verified {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files", + "prepared": "Prepared {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} files", + "cancelHint": "Can be cancelled at any time; copied files will be deleted", + "cancel": "Cancel installation", + "cancelling": "Cancelling…" + }, + "copies": { + "sections": { + "list": "All clients", + "summary": "Client details", + "features": "Feature status", + "maintain": "Maintenance" + }, + "add": "Add a client", + "missingFolder": "Folder missing", + "relocate": "Relocate…", + "relocateDialogTitle": "Select the moved client folder", + "list": { + "current": "Current", + "select": "Set as current" + }, + "none": "The offline edition is not installed yet.", + "maintenance": { + "update": "Update from online installation", + "updateAction": "Update client", + "newVersion": "Version {{version}} is available from the installation source.", + "updateKeepsSpaceSaving": "Version {{version}} is available. Updating continues sharing read-only resource archives with the source.", + "updateDetaches": "Version {{version}} is available. Because the client and source are on different volumes, updating copies shared resources into independent files and requires additional space.", + "currentVersion": "Installation source version {{version}}", + "noSource": "Installation source unavailable", + "spaceSaving": "Save space", + "spaceSavingHint": "Share identical read-only resource archives with the source. An in-place update to the source client can change the shared files.", + "spaceSavingUnavailable": "Requires a client and source installation of the same version on the same volume.", + "compactAction": "Convert", + "check": "Recheck patches", + "checkHint": "Check the original file backup.", + "lastCheck": "Last checked {{date}}", + "repair": "Repair client", + "repairAction": "Repair", + "repairHint": "Restore the original files from the backup. Game files will be generated again at launch.", + "delete": "Delete client", + "deleteAction": "Delete…", + "deleteHint": "The data folder is kept by default.", + "unlink": "Remove registration", + "unlinkAction": "Remove…", + "unlinkHint": "The launcher keeps the Steam game files and data folder in place.", + "unlinkLocation": "Remove the launcher's registration for {{path}}? Steam game files and data will stay in place.", + "deleteLocation": "Delete the offline client at {{path}}?", + "deleteData": "Also delete the data folder at {{path}}", + "confirm": "Confirm deletion", + "phase": { + "checking": "Checking the client", + "copying": "Copying changed files", + "applying": "Applying changes" + }, + "result": { + "confirm-steam": "Steam locations confirmed.", + "check": "Patch check complete.", + "repair": "Original files restored.", + "update": "Client updated.", + "compact": "Space-saving conversion complete.", + "delete": "Client deleted.", + "cancelled": "Maintenance cancelled." + } + }, + "summary": { + "name": "Client name", + "rename": "Rename", + "source": "Installation source", + "version": "Game version", + "adaptation": "Check status", + "adaptationHint": "Whether every patch was checked on this game version and verified in game", + "location": "Location", + "missingHint": "Game files were not found at this path. Relocate to the moved folder to keep existing saves and tuning.", + "method": "Installation type", + "methods": { + "copy": "Copy installation", + "hardlink": "Space-saving copy", + "in-place": "In-place installation", + "existing": "Existing client" + }, + "stock": "Original file backup", + "stockHint": "Patched files are generated from it at each launch", + "data": "Data folder", + "dataHint": "Saves, caches and logs", + "installedAt": "Installed", + "features": "Features", + "open": "Open" + }, + "features": { + "lead": "Patch compatibility determines which features are available. Installation requires all essential patches.", + "essential": "Required", + "verifiedOn": "Verified: {{version}}", + "passedCheck": "Passed the patch check (this game version is not verified)", + "unavailable": "Patch does not apply: {{patches}}", + "allAvailable": "All available", + "someMissing": "{{count}} unavailable", + "checkedAt": "Checked {{time}} (at installation)" + } + }, + "featureSections": { + "A": "Startup and account", + "B": "Hangar and vehicles", + "C": "Tech tree and research", + "D": "Modifications, weapons and ammunition", + "E": "Crew", + "F": "Customization", + "G": "Economy and store", + "H": "Items and inventory", + "I": "Squadrons", + "J": "Game modes", + "K": "In battle", + "L": "After battle and statistics", + "M": "Replays", + "N": "Settings, controls and mods", + "O": "Multiplayer social features" + }, + "saves": { + "sections": { + "list": "All saves", + "overview": "Overview", + "battles": "Battle history", + "vehicles": "Vehicles and research", + "official": "Import online data", + "backup": "Backup and restore" + }, + "tree": { + "branch": "Country and vehicle type", + "country": "Country", + "type": "Vehicle type", + "actions": "Bulk actions", + "research": "Research all", + "purchase": "Grant regular vehicles", + "equipment": "Unlock modifications", + "empty": "This client has no eligible research branches.", + "rank": "Rank {{rank}}", + "owned": "Owned", + "points": "{{earned}} / {{needed}} RP", + "countries": { + "country_usa": "United States", + "country_germany": "Germany", + "country_ussr": "USSR", + "country_britain": "Great Britain", + "country_japan": "Japan", + "country_china": "China", + "country_italy": "Italy", + "country_france": "France", + "country_sweden": "Sweden", + "country_israel": "Israel" + }, + "types": { + "Aircraft": "Aircraft", + "Tank": "Ground vehicles", + "Ship": "Bluewater fleet", + "Boat": "Coastal fleet", + "Helicopter": "Helicopters" + } + }, + "official": { + "auto": "Automatic import", + "autoHint": "Locates local online data read-only, copies it into the offline folder, and imports from the copy without modifying the online files.", + "oneClick": "Find and import", + "discover": "Find and preview", + "notFound": "No online data was found in the default Documents folder. Use manual file selection below.", + "account": "Online account", + "multipleAccounts": "{{count}} online account folders were found. Select the account to import.", + "accountOption": "Account {{id}} ({{files}} · updated {{time}})", + "files": "Manual selection", + "fileHint": "Or select copied global.blk, machine.blk or storage.blk files manually.", + "choose": "Choose files…", + "content": "Import contents", + "settings": "Game settings and controls", + "unlock": "Unlock vehicles from presets", + "equipment": "Modifications", + "equipmentHint": "All equipment unlocks regular modifications and ammunition only, without talismans.", + "full": "All equipment", + "basic": "Essential equipment", + "stock": "Stock configuration", + "preview": "Preview", + "import": "Import", + "summary": "{{files}} file(s) · {{presets}} preset(s) · {{vehicles}} available vehicle(s)", + "omitted": "Unavailable vehicles to skip · {{names}}", + "done": "Online data imported. The previous save is available in Backup and restore." + }, + "archive": { + "fromCopy": "Copy from another client", + "import": "Import save file…", + "sourceCopy": "Source client", + "transfer": "Create from save", + "copy": "Copy", + "export": "Export…", + "delete": "Delete…", + "confirmDelete": "Delete the local account and save for {{name}}?", + "automatic": "Back up before launch", + "retention": "The latest 10 automatic backups are retained for each save.", + "backup": "Back up now", + "restore": "Restore", + "noBackups": "There are no backups for this save.", + "confirmRestore": "Restore this backup? The current save will be backed up first.", + "type": { + "manual": "Manual backup", + "launch": "Before launch", + "restore": "Before restore", + "import": "Before import" + } + }, + "create": "Create save", + "login": "Login", + "nick": "Nickname", + "password": "Password", + "confirmPassword": "Confirm password", + "passwordMismatch": "The passwords do not match.", + "readOnly": "The local server or game is running. Saves are read-only.", + "noCopy": "Select an offline client to manage its saves.", + "empty": "There are no local saves for this client.", + "loading": "Loading save", + "silverLions": "Silver Lions", + "goldenEagles": "Golden Eagles", + "gjnCents": "GJN", + "freeRp": "Free research points", + "vehicles": "Vehicles", + "battles": "Recorded battles", + "lastBattle": "Last battle", + "premiumDays": "Premium account days", + "avatar": "Avatar", + "avatarUnavailable": "Avatar unavailable", + "level": "Account level", + "apply": "Save changes", + "saved": "Changes saved.", + "noBattles": "The save has no recorded battles.", + "win": "Victory", + "loss": "Defeat", + "battleRewards": "{{sl}} Silver Lions · {{rp}} research points", + "owned": "Owned vehicles", + "research": "Research progress" + }, + "tuning": { + "sections": { + "rewards": "Rewards", + "battle": "Battles", + "newProfile": "New saves", + "research": "Research" + }, + "fields": { + "rewardMultiplierSilverLions": "Silver Lions multiplier", + "rewardMultiplierResearchPoints": "Research points multiplier", + "friendlyKillPenaltyMul": "Friendly-fire penalty multiplier", + "maxPlayers": "Player limit per battle", + "smallTeamsMaxPlayers": "Small teams player limit", + "brSpreadMrank": "Matchmaking BR range", + "subModeChance": "Sub-mode probability", + "tankBotRespawns": "AI tank respawns", + "airBotRespawns": "AI aircraft respawns", + "strikeUcavSpawnScore": "Strike UCAV spawn points", + "silverLions": "Starting Silver Lions", + "goldenEagles": "Starting Golden Eagles", + "preferLineSuccessor": "Prefer the next vehicle in the line", + "autoTargetPick": "Automatic research target" + }, + "target": { + "lowestRank": "Lowest rank", + "highestRank": "Highest rank", + "treeOrder": "Research tree order" + }, + "shared": "These settings apply to all saves in this client.", + "nextLaunch": "Changes take effect the next time the local server starts.", + "reset": "Restore defaults for this section", + "default": "Default {{value}}", + "on": "Enabled", + "off": "Disabled", + "saved": "Tuning values saved.", + "invalid": "Enter values within the supported range.", + "loading": "Loading tuning values", + "noCopy": "Select an offline client to edit its tuning values." + }, + "settings": { + "sections": { + "general": "General", + "launch": "Launch", + "dev": "Developer", + "diag": "Diagnostics" + }, + "appUpdates": "Launcher updates", + "appUpdatesToggle": "Check for launcher updates at start", + "patchPacks": "Adaptation pack updates", + "patchPacksHint": "After a game update, the patches for the new version are released on GitHub as an adaptation pack.", + "updateMirror": "Update mirror repository", + "updateMirrorHint": "Enter an HTTPS mirror with a GitHub-compatible releases list. It is used if the primary source is unreachable. Leave blank to disable it.", + "updateMirrorInvalid": "Enter a valid HTTPS repository address or leave the field blank.", + "patchPacksToggle": "Check for a new adaptation pack at start", + "windowClose": "When closing the window", + "windowQuit": "Quit launcher", + "windowTray": "Minimize to system tray", + "afterGameStarts": "When the game starts", + "windowMinimize": "Minimize launcher", + "windowKeep": "Keep window open", + "launch": { + "port": "Local server port", + "portHint": "Port set by the installed lab automation", + "exit": "When the game exits", + "exitHint": "Isolated launch", + "automatic": "Close local server", + "portMode": "Port assignment", + "autoPort": "Assign automatically", + "fixedPort": "Specify port", + "arguments": "Additional arguments", + "argumentsHint": "Command-line arguments passed to the game", + "argumentsInvalid": "Close each double quote in the launch arguments." + }, + "developer": { + "mode": "Developer mode", + "modeHint": "Launches the lab client under the wto-lab Windows account", + "enabled": "Enabled", + "stock": "Stock backup", + "stockHint": "Defaults to the selected client’s stock backup", + "data": "Lab data folder", + "dataHint": "Defaults to the selected client’s data folder", + "reset": "Restore default" + }, + "diagnostics": { + "recordLogs": "Record runtime logs", + "recordLogsToggle": "Write launcher, local server, and hook logs", + "recordLogsHint": "When disabled, stops writing launcher logs, local server traffic logs, and wto_ws.log (the game engine's own .game_logs are unaffected). Re-enable before exporting logs for troubleshooting.", + "loggingDisabledNotice": "Runtime logging is currently disabled; exported archives include only existing logs and configuration.", + "logs": "Logs", + "logsHint": "Logs recorded by the launcher", + "openLogs": "Open log folder", + "export": "Export diagnostics", + "exportHint": "Save launcher, local server, and game logs, settings, and the installation record to a ZIP file (excludes saves)", + "save": "Export…", + "saved": "Diagnostics saved to {{path}}.", + "serverStatus": "Local server status", + "openStatus": "Open in browser" + }, + "language": "Language", + "languageHint": "Display language of the launcher" + }, + "background": { + "title": "Background", + "hint": "Game backgrounds come from the current client.", + "official": "Website wallpapers", + "officialHint": "Downloads wallpapers from the official website. Downloaded wallpapers are available offline.", + "officialToggle": "Get wallpapers from the War Thunder website", + "officialItem": "Website · {{name}}", + "random": "Random", + "none": "No background pictures are available. Install a client to use the game pictures, or turn on website wallpapers.", + "current": "Background: {{name}}", + "previous": "Previous", + "next": "Next", + "nations": { + "default": "General", + "usa": "USA", + "germany": "Germany", + "ussr": "USSR", + "uk": "Great Britain", + "japan": "Japan", + "china": "China", + "italy": "Italy", + "france": "France", + "sweden": "Sweden", + "israel": "Israel" + } + }, + "about": { + "launcher": "Launcher {{version}}", + "supported": "Supported game versions: {{versions}}", + "feedback": { + "title": "Feedback and logs", + "export": "Save all logs", + "exportHint": "Pack launcher, local server, and game logs into a ZIP file for issue reports (excludes saves).", + "exportButton": "Save log ZIP…" + }, + "pack": { + "title": "Adaptation data", + "current": "In use", + "currentHint": "The patches used to install and update clients.", + "bundled": "Included with the launcher", + "bundledVersion": "Included with the launcher ({{version}})", + "downloaded": "Adaptation pack {{version}}", + "useBundled": "Go back to the included patches", + "check": "Check for updates", + "checkHint": "Checks for a new adaptation pack.", + "checkButton": "Check", + "checking": "Checking…", + "applying": "Downloading and verifying the adaptation pack…", + "upToDate": "Up to date (the newest adaptation pack is {{version}}).", + "noneReleased": "No adaptation pack has been released yet.", + "available": "Adaptation pack {{version}} is available. Supported game versions: {{versions}}.", + "availableHint": "Its signature is verified before it is used. Installing and updating clients then use the new patches.", + "apply": "Download and use {{version}}", + "needsAppUpdate": "Adaptation pack {{version}} needs offline version {{app}} or newer. Update the offline version first.", + "checkFailed": { + "no_signing_key": "This launcher has no signing key built in, so it accepts no adaptation pack.", + "network": "The update source could not be reached. Try again later.", + "page_limit": "Could not confirm whether a newer adaptation pack is available.", + "contents": "The released adaptation pack is incomplete or malformed.", + "signature": "The adaptation pack's signature is wrong. It was refused.", + "size": "The adaptation pack is larger than allowed. It was refused." + }, + "applyFailed": { + "no_signing_key": "This launcher has no signing key built in, so it accepts no adaptation pack.", + "network": "Could not reach the update source to download the adaptation pack. Try again later.", + "page_limit": "Could not confirm whether a newer adaptation pack is available.", + "contents": "The adaptation pack is incomplete or malformed. It is not in use.", + "signature": "The adaptation pack's signature is wrong. It was refused and is not in use.", + "size": "The adaptation pack is larger than allowed. It was refused.", + "needs_app_update": "This adaptation pack needs a newer offline version. Update the offline version first.", + "up_to_date": "Up to date: there is no adaptation pack to download." + } + }, + "update": { + "title": "Launcher update", + "check": "Launcher version check", + "checking": "Checking…", + "current": "The launcher is up to date.", + "available": "Version {{version}} is available. Installer size {{size}}.", + "downloading": "Downloading the installer…", + "download": "Download update", + "install": "Quit and install", + "installing": "Opening the installer…", + "errors": { + "network": "The update source could not be reached.", + "page_limit": "Could not confirm whether a newer version is available.", + "contents": "The launcher release information is invalid.", + "signature": "The launcher update signature could not be verified.", + "no_signing_key": "The launcher update verification key is unavailable." + } + }, + "statement": "Project information", + "statementBody": "WTOffline is a noncommercial hobby project independent of Gaijin. Running it requires your own War Thunder base game files.", + "community": { + "discord": "Discord", + "discordHint": "Development discussion, general chat, troubleshooting, and bug reports.", + "openDiscord": "Open Discord" + } + }, + "features": { + "A-Offline startup": "Offline startup", + "A-Local accounts": "Local accounts", + "A-Isolation from the official game": "Isolation from the online game", + "A-No Gaijin connections": "Gaijin connections blocked", + "A-Tutorials": "Tutorial", + "B-Hangar and vehicles": "Hangar and vehicles", + "G-Store": "Store", + "G-Redeem codes": "Redeem codes", + "G-Marketplace": "Marketplace", + "G-Currencies": "Currency purchase", + "G-Premium account": "Premium account", + "G-Boosters": "Boosters", + "H-Contracts and wagers": "Battle contracts", + "H-Supply chests": "Supply chests", + "H-Recycling and crafting": "Item recycling and crafting", + "H-Coupons": "Coupons", + "J-Game modes": "Game modes", + "J-Ground arcade and realistic": "Ground battles (arcade, realistic)", + "J-Air arcade and realistic": "Air battles (arcade, realistic)", + "J-Naval arcade and realistic": "Naval battles (arcade, realistic)", + "E-Crew skills in battle": "Crew skills and qualifications in battle", + "J-Sub-modes": "Additional modes (such as night battles)", + "K-AI opponents and teammates": "AI opponents and allies", + "K-Spawn score and respawns": "Spawn points and respawning", + "K-Scouting": "Scouting and drones", + "K-Kill, assist and capture scoring": "Kill, assist and capture scoring", + "K-Player damage notices": "Player damage notices", + "K-Additional vehicles": "Additional vehicles", + "K-Scoreboard": "Scoreboard", + "K-Chat and radio": "Chat and radio", + "K-Nuclear bomb": "Nuclear bomb", + "L-Debriefing": "Battle results", + "L-Battle awards": "Battle awards" + }, + "mods": { + "sections": { + "list": "Mod list", + "presets": "Presets & repository" + }, + "loading": "Loading mods…", + "noCopy": "Install or select an offline client first to configure its mods.", + "enabledSummary": "{{enabled}} / {{total}} enabled", + "experimentalChip": "Experimental", + "experimentalTitle": "Experimental mod API notice:", + "experimentalBody": "WTOffline is in early development (API {{api}}). Server script hooks, internal data structures, and declarative exe patch contracts may change at any time without backwards compatibility; only enable mods from trusted sources.", + "readOnlyNotice": "Mod toggles, load order, and presets are read-only while the game, local server, or maintenance is running.", + "searchPlaceholder": "Filter by mod name, ID, or author…", + "autoSort": "Auto-sort by dependencies", + "autoSorted": "Reordered mods based on dependencies and load-order hints.", + "refresh": "Refresh", + "openFolder": "Open mods folder", + "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):", + "severity": { + "error": "Error", + "warning": "Warning", + "info": "Info" + }, + "emptyTitle": "No mods found in the global mods folder yet.", + "emptyHint": "Place mod folders containing mod.jsonc into {{path}}, then click Refresh. Standalone skins, sights, and user missions continue to work directly via the game's native UserSkins / UserSights / UserMissions folders.", + "noSearchMatch": "No mods match the current search filter.", + "loadOrderHint": "Load order: lower items load later and take higher priority (drag or use arrows)", + "moveUp": "Move up", + "moveDown": "Move down", + "showDetails": "Details", + "hideDetails": "Hide", + "errorCount": "{{count}} error", + "warnCount": "{{count}} warn", + "badges": { + "data": "Data / Assets", + "gui": "GUI Patch", + "script": "Server Script", + "exe": "Exe Patch" + }, + "details": { + "folder": "Folder", + "gameVersions": "Declared game versions", + "requires": "Requires", + "conflicts": "Conflicts", + "tuning": "Server tuning overlays: {{count}}", + "serverScript": "Executable server JS/TS script", + "packOps": "Client pack operations: {{count}}", + "addon": "3D model / texture addon: {{count}} file(s)", + "guiPatches": "GUI script patches: {{count}}", + "exePatches": "Declarative exe patches: {{count}}", + "companionFiles": "Companion files: {{count}}", + "configBlk": "Includes config.blk patch" + }, + "presets": { + "heading": "Mod presets (saved per client)", + "description": "Save the current mod toggles and load order as named presets for quick switching or JSON export/import.", + "quickSwitch": "Switch mod preset", + "customOption": "Custom active selection", + "namePlaceholder": "New preset name, e.g. Modern Vehicles", + "saveCurrent": "Save preset", + "import": "Import preset…", + "empty": "No presets saved for this client yet.", + "activeTag": "Active", + "summary": "{{count}} enabled / {{total}} tracked", + "apply": "Apply", + "overwrite": "Update", + "export": "Export", + "delete": "Delete", + "saved": "Saved preset \"{{name}}\".", + "applied": "Applied preset \"{{name}}\".", + "updated": "Updated preset \"{{name}}\" with current setup.", + "exported": "Exported preset to: {{path}}", + "imported": "Imported mod preset." + }, + "repo": { + "heading": "Global mods repository", + "description": "All clients share one mod folder (large 3D model and texture addons mount across drives via NTFS Junctions with zero copying), while each client keeps its own toggles, load order, and presets.", + "pathLabel": "Repository folder", + "defaultNote": "Using launcher default mods folder", + "customNote": "Using custom mods folder (can live on a larger drive or the same drive as your client)", + "changeFolder": "Change folder…", + "resetDefault": "Reset to default", + "pickTitle": "Select global mods repository folder", + "updated": "Updated global mods repository folder.", + "resetDone": "Reset to default mods repository folder." + } + }, + "errors": { + "app_update_unavailable": "There is no launcher update available to install.", + "app_update_busy": "A launcher update operation is already in progress.", + "app_update_launcher_busy": "Close the game and local server and finish any client or save operations before updating.", + "app_update_download_failed": "The launcher installer could not be downloaded and verified. See the launcher log.", + "app_update_installer_invalid": "The installer failed verification. Download it again.", + "app_update_install_failed": "The launcher installer could not be opened. See the launcher log.", + "internal_error": "An internal launcher error occurred.", + "logs_folder_open_failed": "The launcher log folder could not be opened.", + "diagnostics_export_failed": "The diagnostics archive could not be saved.", + "save_official_invalid": "The selected files are not supported online data files.", + "save_official_location": "Choose data files copied outside the online game's folders.", + "save_archive_invalid": "The selected file is not a supported WTOffline save archive.", + "save_not_found": "The selected save could not be found.", + "save_read_only": "Saves are read-only while the game or local server is running.", + "save_operation_failed": "The save operation failed. See the launcher log.", + "save_login_invalid": "Enter a login without spaces.", + "save_login_exists": "An account with this login already exists.", + "save_password_invalid": "Enter a password.", + "save_nick_invalid": "Enter a nickname with up to 16 characters.", + "save_avatar_invalid": "Select an avatar available in this client.", + "save_level_invalid": "Enter a level supported by this client.", + "tuning_invalid": "The tuning values could not be read or saved. Check the session limits and the launcher log.", + "mods_read_only": "Mods cannot be changed while the game, local server, or maintenance is running.", + "mods_write_failed": "The mod configuration could not be saved. See the launcher log.", + "mods_preset_invalid": "The selected file is not a valid WTOffline mod preset.", + "mods_blocking_issues": "Enabled mods have missing dependencies or conflicts. Resolve them on the Mods page before launching.", + "mods_folder_invalid": "The selected global mods folder is invalid or not writable.", + "copy_not_found": "The selected client is no longer available.", + "copies_write_failed": "The client registry could not be saved.", + "copy_location_in_use": "The client or data location overlaps an existing client.", + "decal_source_invalid": "The selected folder does not contain a usable decal cache.", + "decal_import_failed": "The decal cache could not be imported into the client's data folder. See the launcher log.", + "maintenance_busy": "Maintenance requires the game, local server and other client operations to be stopped.", + "maintenance_location": "The operation would affect files outside the registered client or data folder.", + "maintenance_no_update": "A newer version is unavailable at the installation source.", + "maintenance_cancelled": "The client update was cancelled.", + "maintenance_failed": "Client maintenance failed. See the launcher log.", + "maintenance_source_changed": "The installation source changed during the update. Retry once its update is complete.", + "launch_no_copy": "An offline client must be installed before launching.", + "launch_busy": "A launch is already in progress.", + "launch_failed": "Launch failed. See the launcher log.", + "launch_platform_unsupported": "Game launch requires Windows.", + "launch_lab_required": "Enable developer mode to launch through the isolated lab.", + "launch_lab_missing": "The isolated lab automation could not be loaded.", + "launch_lab_version": "The lab client and the stock backup must use the same game version.", + "launch_lab_failed": "The isolated launch failed. See the launcher log.", + "launch_game_running": "Another game process is running.", + "launch_copy_in_steam": "The development lab requires a client and data folder outside Steam.", + "launch_steam_confirmation_required": "Confirm the Steam locations in Client Maintenance before launching.", + "launch_location": "The client, stock backup, or data folder location is invalid.", + "launch_stock_version": "The stock backup and client versions do not match.", + "launch_stock_missing": "The original file backup (wtoffline\\stock) is missing or unreadable. Check your security software, or remove this client entry and add it again.", + "launch_build_failed": "The game files could not be generated.", + "launch_build_unavailable": "The build found unavailable patches that require review.", + "launch_port_busy": "The local server port is already in use.", + "launch_server_failed": "The local server could not be started. See the launcher log.", + "launch_server_exited": "The local server is unavailable.", + "launch_game_failed": "The game process could not start. See the launcher log.", + "launch_game_files_missing": "Required game launch files are missing or unreadable (they may have been quarantined by antivirus software). Check your security software and the launcher log.", + "settings_write_failed": "The settings could not be saved.", + "folder_unreadable": "The folder cannot be read: {{path}}", + "not_a_game_folder": "The selected folder is not a War Thunder installation: {{path}}", + "stock_source_invalid": "This client is already patched and lacks an original backup. Select an unpatched game folder of the same version.", + "stock_source_version_mismatch": "The selected original game version ({{actual}}) does not match the client version ({{expected}}).", + "target_not_usable": "The selected folder cannot be used for installation.", + "steam_library_not_confirmed": "The client or data folder is in a Steam library. Confirm the risk notice first.", + "not_enough_space": "Not enough disk space: {{neededGb}} GB required, {{freeGb}} GB available.", + "essential_patches_unavailable": "Patches required by the offline edition do not apply to this game version. Installation is not possible: {{patches}}", + "missing_features_not_accepted": "Some patches do not apply. Confirm whether to continue without the affected features.", + "patch_check_failed": "An error occurred while checking patches.", + "copy_failed": "Copying the game files failed. The copied files have been deleted.", + "hardlink_unavailable": "Space-saving copying requires the destination and source to be on the same volume, and converting an existing client also requires matching versions.", + "hardlink_no_match": "No matching read-only resource archives were found, or their contents differ from the source.", + "hardlink_file_changed": "A resource changed during verification or copying. Finish any other file operation, then retry.", + "install_cancelled": "Installation cancelled. The copied files have been deleted.", + "install_busy": "An installation is already in progress.", + "unknown": "An unknown error occurred." + } +} 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 3536f7e..9b7c364 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -1,939 +1,856 @@ -{ - "app": { - "title": "战争雷霆离线版", - "subtitle": "战争雷霆离线版" - }, - "nav": { - "home": "首页", - "saves": "存档", - "tuning": "数值", - "mods": "模组", - "copies": "客户端", - "settings": "设置", - "about": "关于" - }, - "window": { - "minimize": "最小化", - "close": "关闭" - }, - "language": { - "label": "语言", - "system": "跟随系统", - "zh-CN": "简体中文", - "en": "English" - }, - "footer": { - "launcher": "启动器 {{version}}", - "game": "{{name}} · 游戏 {{version}}", - "notInstalled": "未安装", - "packUpdate": "适配包 {{version}} 可用 · 更新 ›", - "appUpdate": "本体 {{version}} 可用 · 更新 ›" - }, - "home": { - "kicker": "本地服务器 · AI 对局", - "installedKicker": "游戏 {{version}}", - "body": "选择「安装」以配置离线客户端。", - "steps": { - "choose": "选择游戏", - "chooseBody": "指定游戏的安装位置", - "method": "选择安装方式", - "methodBody": "创建客户端或使用已有文件夹", - "check": "检查补丁", - "checkBody": "核对所选版本的功能状态" - } - }, - "side": { - "requirements": "安装要求", - "game": "游戏", - "gameValue": "战争雷霆在线版客户端", - "versions": "已验证版本", - "space": "磁盘空间", - "spaceValue": "约 97 GB(复制安装)", - "currentCopy": "当前客户端", - "copyName": "离线客户端", - "adaptation": "核对状态", - "features": "功能", - "allAvailable": "✓ 全部可用", - "someMissing": "⚠ {{count}} 项不可用", - "details": "详情" - }, - "adaptation": { - "verified": "✓ 已核对", - "unverified": "⚠ 未核对" - }, - "bar": { - "notInstalled": "未安装", - "notInstalledDetail": "需要已安装的战争雷霆在线版客户端", - "install": "安装", - "ready": "就绪", - "readyMissing": "就绪 · {{count}} 项功能不可用", - "readyDetail": "游戏 {{version}}", - "missingFolder": "客户端目录不存在", - "launch": "启动" - }, - "launch": { - "checking": "正在检查客户端", - "building": "正在生成游戏文件", - "starting-server": "正在启动本地服务器", - "starting-game": "正在启动游戏", - "starting": "启动中…", - "running": "游戏运行中", - "runningDetail": "本地服务器 · 端口 {{port}}", - "server-running": "本地服务器运行中", - "game-exited": "游戏已退出", - "gameExitedServerRunning": "游戏已退出。本地服务器仍在运行。", - "exitDetail": "退出码 {{code}}。游戏日志位于 {{path}}。", - "exitCodeUnknown": "未知", - "stopping": "正在关闭", - "stopServer": "关闭本地服务器", - "cancel": "取消", - "stop": "结束游戏", - "retry": "重试", - "check": "检查", - "version-changed": "客户端版本已变更", - "versionDetail": "游戏版本 {{version}}", - "port-busy": "端口 {{port}} 已被占用", - "server-exited": "本地服务器意外退出" - }, - "decals": { - "source": "贴花来源", - "hint": "可导入在线版游戏的 cache/content。未导入时使用占位贴花。", - "choose": "选择贴花缓存…", - "useDefault": "使用占位贴花", - "importing": "正在导入贴花缓存", - "imported": "已导入缓存", - "default": "占位贴花" - }, - "folder": { - "none": "未选择", - "choose": "浏览…", - "change": "更改…" - }, - "wizard": { - "title": "添加客户端", - "steps": { - "mode": "添加方式", - "source": "游戏位置", - "method": "安装方式", - "data": "数据目录", - "check": "补丁检查", - "installing": "安装" - }, - "barTitle": "添加客户端 · {{step}}", - "stepOf": "第 {{index}} 步,共 {{total}} 步", - "back": "上一步", - "next": "下一步", - "cancel": "取消", - "install": "开始安装", - "installing": "安装中", - "checking": "正在检查补丁", - "checkingDetail": "正在核对补丁对所选游戏的适用情况" - }, - "mode": { - "body": "选择添加离线客户端的方式。", - "newTitle": "从在线版全新安装", - "newBody": "从已安装的战争雷霆在线版创建新的离线客户端,支持完整复制、省空间复制或原位安装。", - "existingTitle": "添加已有离线客户端", - "existingBody": "直接登记已准备好的离线客户端文件夹,不重新复制游戏文件。" - }, - "source": { - "body": "选择已安装的战争雷霆文件夹。", - "dialogTitle": "选择战争雷霆安装文件夹", - "existingBody": "选择已准备好的离线客户端文件夹。", - "existingDialogTitle": "选择已有离线客户端文件夹", - "offlineBackupDetected": "已检测到离线客户端的原版文件备份(wtoffline\\stock),可直接添加,无需重新复制。", - "patchedNeedsStock": "所选文件夹已包含离线补丁,但缺少 4 个原版核心文件(wtoffline\\stock)。请选择同版本的原版游戏目录,启动器将只读复制这 4 个文件(约 150 MB),无需重新复制整包游戏。", - "stockSourceTitle": "选择同版本的原版战争雷霆目录", - "stockSourcePatched": "所选目录同样已打过离线补丁且缺少原版文件备份,请选择未打补丁的原版游戏目录。", - "stockSourceVersionMismatch": "所选原版目录版本({{actual}})与当前客户端版本({{expected}})不一致。", - "stockSourceReady": "原版核心文件来源就绪(版本 {{version}}),添加时将仅复制 4 个核心文件至 wtoffline\\stock。", - "notAGame": "所选文件夹不是战争雷霆的安装文件夹,缺少:{{files}}", - "versionVerified": "游戏版本 {{version}}(已核对)", - "versionUnverified": "游戏版本 {{version}} 还没有核对记录。安装时仍会逐个尝试全部补丁,可用功能以补丁检查结果为准。", - "versionUnknown": "未知", - "size": "大小 {{size}} · {{files}} 个文件", - "measuring": "正在统计大小…" - }, - "method": { - "copy": "复制安装(推荐)", - "copyBody": "将游戏复制到新文件夹。需要约 {{size}} 的可用空间。", - "spaceSaving": "节省空间的复制", - "spaceSavingBody": "与同一磁盘卷上的原版共用只读资源包,预计需要 {{size}}。原版就地更新可能改变客户端中的共享文件。", - "spaceSavingPending": "正在估算可节省的空间。", - "spaceSavingUnavailable": "该安装目录没有可用于省空间复制的只读资源包。", - "sameVolumeRequired": "请选择与原版位于同一磁盘卷的目标文件夹。", - "targetTitle": "选择安装位置(将自动创建 WTOffline 子文件夹)", - "targetSubfolderHint": "将在所选位置下自动创建独立的 WTOffline 文件夹存放游戏文件,避免文件散落。", - "inPlace": "原位安装", - "inPlaceBody": "使用所选游戏文件夹作为客户端。原版文件备份至 wtoffline\\stock,首次启动时将应用补丁。", - "existing": "添加已有客户端", - "existingBody": "直接登记所选的已有游戏文件夹,不复制游戏文件;如尚未建立原版备份将自动备份至 wtoffline\\stock。", - "existingBodyWithBackup": "直接登记已存在的离线客户端,保留现有的 wtoffline\\stock 原版文件备份,不复制游戏文件。", - "existingBodyWithStockSource": "直接登记已存在的离线客户端,仅从所选原版目录补齐 4 个核心文件至 wtoffline\\stock,不重新复制游戏。", - "room": "目标磁盘可用空间:{{free}}", - "noRoom": "可用空间不足:需要 {{needed}},目标磁盘仅剩 {{free}}。", - "problem": { - "not_empty": "所选文件夹不为空。请选择空文件夹或新建文件夹。", - "overlaps_stock": "不能选择在线版安装文件夹本身,或其上级、下级文件夹。", - "not_a_folder": "所选路径不是文件夹。" - }, - "copyBodyPending": "将游戏复制到新文件夹。正在统计所需空间。" - }, - "steam": { - "inPlaceWarning": "离线启动会修改此 Steam 安装中的游戏文件。Steam 更新或文件校验可能覆盖改动。使用修改后的文件联网启动在线版可能导致账号封禁。", - "copyWarning": "目标文件夹位于 Steam 游戏库。建议将客户端放在游戏库之外。", - "confirm": "确认使用此文件夹", - "dataWarning": "数据目录放在 Steam 游戏文件夹内时,在 Steam 中卸载游戏可能一并删除存档、缓存和日志。", - "maintenanceWarning": "客户端或数据目录位于 Steam 游戏库中。离线启动可能修改库内的游戏文件。Steam 更新或校验可能覆盖改动,使用修改后的文件联网启动可能导致账号封禁。在 Steam 中卸载游戏还可能删除保存在该游戏文件夹内的存档。", - "confirmLocations": "确认使用这些位置" - }, - "data": { - "body": "选择用于保存存档、缓存和日志的文件夹。", - "dialogTitle": "选择数据目录", - "problem": { - "overlaps_client": "数据目录不能与客户端目录相同、包含客户端目录,或位于客户端的 wtoffline 目录内。请选择独立文件夹或客户端内的专用子文件夹(例如 data)。", - "overlaps_stock": "数据目录不能位于在线版安装目录内。" - } - }, - "check": { - "running": "正在检查所选游戏版本的补丁。", - "allFit": "全部 {{count}} 个补丁均适用于此游戏版本。", - "essentialMissing": "必需补丁无法应用,安装无法继续。受影响的功能:", - "someMissing": "{{count}} 个补丁不适用于此游戏版本,以下功能将不可用:", - "details": "查看补丁详情", - "accept": "接受上述功能不可用并继续安装" - }, - "progress": { - "phase": { - "checking": "检查游戏文件", - "measuring": "统计文件", - "verifying": "核对可共用的资源", - "copying": "复制游戏文件", - "importing-decals": "正在导入贴花缓存", - "backing-up": "备份原版文件", - "recording": "完成安装" - }, - "copied": "已复制 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件", - "verified": "已核对 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件", - "prepared": "已处理 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件", - "cancelHint": "可随时取消,已复制的文件将被删除", - "cancel": "取消安装", - "cancelling": "正在取消…" - }, - "copies": { - "sections": { - "list": "全部客户端", - "summary": "客户端详情", - "features": "功能状态", - "maintain": "维护" - }, - "add": "添加客户端", - "missingFolder": "目录不存在", - "relocate": "重新定位…", - "relocateDialogTitle": "选择挪动后的客户端文件夹", - "list": { "current": "当前", "select": "设为当前" }, - "none": "尚未安装离线版。", - "maintenance": { - "update": "从在线版更新", - "updateAction": "更新客户端", - "newVersion": "安装来源已更新至 {{version}}。", - "updateKeepsSpaceSaving": "安装来源中有新版本 {{version}}。更新时会继续与原版共用只读资源包。", - "updateDetaches": "安装来源中有新版本 {{version}}。当前与安装来源不在同一磁盘卷,更新会把共享资源复制为独立文件,需要额外空间。", - "currentVersion": "安装来源版本 {{version}}", - "noSource": "安装来源不可用", - "spaceSaving": "节省空间", - "spaceSavingHint": "将内容一致的只读资源包与原版共用。原版就地更新可能改变这些文件。", - "spaceSavingUnavailable": "客户端和安装来源须位于同一磁盘卷,并且版本一致。", - "compactAction": "转换", - "check": "重新检查补丁", - "checkHint": "核对原版文件备份。", - "lastCheck": "上次检查 {{date}}", - "repair": "修复客户端", - "repairAction": "修复", - "repairHint": "从原版文件备份还原文件。下次启动时重新生成游戏文件。", - "delete": "删除客户端", - "deleteAction": "删除…", - "deleteHint": "默认保留数据目录。", - "unlink": "解除登记", - "unlinkAction": "解除登记…", - "unlinkHint": "Steam 游戏文件和数据目录将留在原处。", - "unlinkLocation": "从启动器中解除 {{path}} 的登记?Steam 游戏文件和数据将留在原处。", - "deleteLocation": "确认删除 {{path}} 中的离线客户端?", - "deleteData": "同时删除 {{path}} 中的数据", - "confirm": "确认删除", - "phase": { - "checking": "正在检查客户端", - "copying": "正在复制有变化的文件", - "applying": "正在应用更改" - }, - "result": { - "confirm-steam": "已确认 Steam 目录。", - "check": "补丁检查已完成。", - "repair": "原版文件已还原。", - "update": "客户端已更新。", - "compact": "省空间转换已完成。", - "delete": "客户端已删除。", - "cancelled": "维护已取消。" - } - }, - "summary": { - "name": "客户端名称", - "rename": "重命名", - "source": "安装来源", - "version": "游戏版本", - "adaptation": "核对状态", - "adaptationHint": "这个游戏版本是否检查过全部补丁并在游戏里验证过", - "location": "位置", - "missingHint": "未在原位置找到游戏文件。可重新定位至挪动后的文件夹,保留现有存档和数值。", - "method": "安装方式", - "methods": { - "copy": "复制安装", - "hardlink": "节省空间的复制", - "in-place": "原位安装", - "existing": "已有客户端" - }, - "stock": "原版文件备份", - "stockHint": "每次启动时据此生成补丁文件", - "data": "数据目录", - "dataHint": "存档、缓存与日志", - "installedAt": "安装时间", - "features": "功能", - "open": "打开" - }, - "features": { - "lead": "补丁检查结果决定功能是否可用。安装需要全部必需补丁。", - "essential": "必需", - "verifiedOn": "已核对:{{version}}", - "passedCheck": "补丁检查通过(这个游戏版本未核对)", - "unavailable": "补丁不适用:{{patches}}", - "allAvailable": "全部可用", - "someMissing": "{{count}} 项不可用", - "checkedAt": "检查时间:{{time}}(安装时)" - } - }, - "featureSections": { - "A": "启动与账号", - "B": "机库与载具", - "C": "科技树与研发", - "D": "改装、武器与弹药", - "E": "乘员", - "F": "外观定制", - "G": "经济与商店", - "H": "道具与库存", - "I": "联队", - "J": "对局模式", - "K": "对局内", - "L": "战后与统计", - "M": "回放", - "N": "设置、操控与模组", - "O": "多人社交" - }, - "saves": { - "sections": { - "list": "全部存档", - "overview": "概览", - "battles": "战绩", - "vehicles": "载具与研发", - "official": "导入在线版数据", - "backup": "备份与还原" - }, - "tree": { - "branch": "国家与兵种", - "country": "国家", - "type": "兵种", - "actions": "批量操作", - "research": "全部研发", - "purchase": "获得常规载具", - "equipment": "解锁改装件", - "empty": "此客户端没有可编辑的研发分支。", - "rank": "等级 {{rank}}", - "owned": "已拥有", - "points": "{{earned}} / {{needed}} 研发点", - "countries": { - "country_usa": "美国", - "country_germany": "德国", - "country_ussr": "苏联", - "country_britain": "英国", - "country_japan": "日本", - "country_china": "中国", - "country_italy": "意大利", - "country_france": "法国", - "country_sweden": "瑞典", - "country_israel": "以色列" - }, - "types": { - "Aircraft": "空军", - "Tank": "陆军", - "Ship": "远洋舰队", - "Boat": "近岸舰队", - "Helicopter": "直升机" - } - }, - "official": { - "auto": "自动导入", - "autoHint": "只读查找本机在线版数据并复制到离线目录后再导入,不修改在线版原文件。", - "oneClick": "一键查找并导入", - "discover": "仅查找并预览", - "notFound": "未在默认文档目录中找到在线版数据,请使用下方手动选择。", - "account": "在线版账号", - "multipleAccounts": "检测到 {{count}} 个在线版账号目录,请选择要导入的账号。", - "accountOption": "账号 {{id}}({{files}} · 更新于 {{time}})", - "files": "手动选择文件", - "fileHint": "也可手动选择复制备份的 global.blk、machine.blk 或 storage.blk。", - "choose": "选择文件…", - "content": "导入内容", - "settings": "游戏设置与键位", - "unlock": "解锁预设中的载具", - "equipment": "改装件", - "equipmentHint": "完全体仅解锁常规改装件与弹药,不包含护身符。", - "full": "完全体", - "basic": "基础生存配件", - "stock": "白板状态", - "preview": "预览", - "import": "导入", - "summary": "{{files}} 个文件 · {{presets}} 套预设 · {{vehicles}} 辆可用载具", - "omitted": "将跳过的不可用载具 · {{names}}", - "done": "在线版数据已导入。原存档可在「备份与还原」中恢复。" - }, - "archive": { - "fromCopy": "从其他客户端复制", - "import": "导入存档文件…", - "sourceCopy": "来源客户端", - "transfer": "创建存档", - "copy": "复制", - "export": "导出…", - "delete": "删除…", - "confirmDelete": "确认删除 {{name}} 的本地账号和存档?", - "automatic": "启动前自动备份", - "retention": "每个存档保留最近 10 份自动备份。", - "backup": "立即备份", - "restore": "还原", - "noBackups": "此存档没有备份。", - "confirmRestore": "还原此备份?将先备份当前存档。", - "type": { - "manual": "手动备份", - "launch": "启动前自动备份", - "restore": "还原前自动备份", - "import": "导入前自动备份" - } - }, - "create": "新建存档", - "login": "登录账号", - "nick": "昵称", - "password": "密码", - "confirmPassword": "确认密码", - "passwordMismatch": "两次输入的密码不一致。", - "readOnly": "游戏或本地服务器正在运行,存档为只读。", - "noCopy": "选择离线客户端后即可管理该客户端的存档。", - "empty": "此客户端没有本地存档。", - "loading": "正在读取存档", - "silverLions": "银狮", - "goldenEagles": "金鹰", - "gjnCents": "GJN", - "freeRp": "通用研发点", - "vehicles": "载具", - "battles": "已记录对局", - "lastBattle": "上次对局", - "premiumDays": "高级账户剩余天数", - "avatar": "头像", - "avatarUnavailable": "头像不可用", - "level": "账号等级", "apply": "保存更改", - "saved": "更改已保存。", - "noBattles": "此存档没有对局记录。", - "win": "胜利", - "loss": "失败", - "battleRewards": "{{sl}} 银狮 · {{rp}} 研发点", - "owned": "已拥有载具", - "research": "研发进度" - }, - "tuning": { - "sections": { - "rewards": "收益", - "battle": "对局", - "newProfile": "新存档", - "research": "研发" - }, - "fields": { - "rewardMultiplierSilverLions": "银狮倍率", - "rewardMultiplierResearchPoints": "研发点倍率", - "friendlyKillPenaltyMul": "误伤惩罚倍率", - "maxPlayers": "每局人数上限(含 AI)", - "smallTeamsMaxPlayers": "小规模模式人数上限", - "brSpreadMrank": "匹配范围", - "subModeChance": "附加模式概率", - "tankBotRespawns": "AI 坦克重生次数", - "airBotRespawns": "AI 飞机重生次数", - "strikeUcavSpawnScore": "打击无人机所需出生点数", - "silverLions": "初始银狮", - "goldenEagles": "初始金鹰", - "preferLineSuccessor": "优先研发同系载具", - "autoTargetPick": "自动研发目标" - }, - "target": { - "lowestRank": "最低等级", - "highestRank": "最高等级", - "treeOrder": "研发树顺序" - }, - "shared": "这些数值适用于此客户端的全部存档。", - "nextLaunch": "更改将在下次启动本地服务器时生效。", - "reset": "恢复本页默认值", - "default": "默认 {{value}}", - "on": "启用", - "off": "停用", - "saved": "数值已保存。", - "invalid": "请输入受支持范围内的数值。", - "loading": "正在读取数值", - "noCopy": "选择离线客户端后即可编辑数值。" - }, - "settings": { - "sections": { - "general": "常规", - "launch": "启动", - "dev": "开发者", - "diag": "诊断" - }, - "appUpdates": "启动器本体更新", - "appUpdatesToggle": "启动时检查本体更新", - "patchPacks": "适配包更新", - "patchPacksHint": "游戏更新后,新版本的补丁会以适配包的形式发布在 GitHub 上。", - "updateMirror": "备用更新仓库", - "updateMirrorHint": "填写支持 GitHub Releases 格式的 HTTPS 镜像地址。主源连接失败时使用,留空关闭。", - "updateMirrorInvalid": "请输入有效的 HTTPS 仓库地址,或留空。", - "patchPacksToggle": "启动时检查有没有新的适配包", - "windowClose": "关闭窗口时", - "windowQuit": "退出启动器", - "windowTray": "最小化到系统托盘", - "afterGameStarts": "游戏启动后", - "windowMinimize": "最小化启动器", - "windowKeep": "保持窗口", - "launch": { - "port": "本地服务器端口", - "portHint": "使用已安装实验自动化的端口设置", - "exit": "游戏退出后", - "exitHint": "隔离启动", - "automatic": "关闭本地服务器", - "portMode": "端口分配方式", - "autoPort": "自动分配", - "fixedPort": "指定端口", - "arguments": "附加启动参数", - "argumentsHint": "传递给游戏的命令行参数", - "argumentsInvalid": "请补全启动参数中的双引号。" - }, - "developer": { - "mode": "开发模式", - "modeHint": "以 wto-lab 用户身份启动实验客户端", - "enabled": "启用", - "stock": "原版文件备份", - "stockHint": "默认使用当前客户端的原版文件备份", - "data": "实验数据目录", - "dataHint": "默认使用当前客户端的数据目录", - "reset": "恢复默认" - }, - "diagnostics": { - "recordLogs": "生成运行日志", - "recordLogsToggle": "记录启动器、本地服务器和钩子日志", - "recordLogsHint": "关闭后停止写入启动器日志、本地服务器流量日志和 wto_ws.log(不影响游戏引擎原生的 .game_logs)。导出日志排查问题前建议重新开启。", - "loggingDisabledNotice": "当前已关闭运行日志记录,导出的压缩包仅包含已有历史日志和配置。", - "logs": "日志", - "logsHint": "启动器运行日志", - "openLogs": "打开日志文件夹", - "export": "导出诊断信息", - "exportHint": "导出包含启动器、本地服务器与游戏日志、设置和安装记录的 ZIP 文件(不含存档)", - "save": "导出…", - "saved": "诊断信息已保存到 {{path}}。", - "serverStatus": "本地服务器状态页", - "openStatus": "在浏览器中打开" - }, - "language": "语言", - "languageHint": "启动器界面的显示语言" - }, - "background": { - "title": "背景图", - "hint": "游戏背景图来自当前客户端。", - "official": "官网壁纸", - "officialHint": "联网下载官网壁纸。已下载的壁纸可离线使用。", - "officialToggle": "从战争雷霆官网获取壁纸", - "officialItem": "官网壁纸 · {{name}}", - "random": "随机", - "none": "暂无可用的背景图。安装后可使用游戏图片,或开启官网壁纸。", - "current": "背景:{{name}}", - "previous": "上一张", - "next": "下一张", - "nations": { - "default": "通用", - "usa": "美国", - "germany": "德国", - "ussr": "苏联", - "uk": "英国", - "japan": "日本", - "china": "中国", - "italy": "意大利", - "france": "法国", - "sweden": "瑞典", - "israel": "以色列" - } - }, - "about": { - "launcher": "启动器 {{version}}", - "supported": "支持的游戏版本:{{versions}}", - "feedback": { - "title": "问题反馈", - "export": "保存全部日志", - "exportHint": "打包启动器、本地服务器及游戏日志为 ZIP 文件以便反馈问题(不含存档)。", - "exportButton": "保存日志 ZIP…" - }, - "pack": { - "title": "适配数据", - "current": "当前使用", - "currentHint": "安装和更新客户端时使用的补丁。", - "bundled": "启动器自带", - "bundledVersion": "启动器自带({{version}})", - "downloaded": "适配包 {{version}}", - "useBundled": "改回启动器自带", - "check": "检查更新", - "checkHint": "检查是否有新的适配包。", - "checkButton": "检查", - "checking": "正在检查…", - "applying": "正在下载并校验适配包…", - "upToDate": "已是最新(最新的适配包是 {{version}})。", - "noneReleased": "还没有发布适配包。", - "available": "适配包 {{version}} 可用,支持的游戏版本:{{versions}}。", - "availableHint": "下载后会先校验签名,通过后才启用;之后安装和更新客户端都使用新的补丁。", - "apply": "下载并启用 {{version}}", - "needsAppUpdate": "适配包 {{version}} 需要离线版 {{app}} 或更新的版本,请先更新离线版。", - "checkFailed": { - "no_signing_key": "这个启动器没有内置签名公钥,不接受适配包。", - "network": "无法连接更新源,请稍后再试。", - "page_limit": "无法确认是否有新的适配包。", - "contents": "发布的适配包信息不完整或格式不对。", - "signature": "适配包的签名不对,已拒绝。", - "size": "适配包超出大小上限,已拒绝。" - }, - "applyFailed": { - "no_signing_key": "这个启动器没有内置签名公钥,不接受适配包。", - "network": "无法连接更新源来下载适配包,请稍后再试。", - "page_limit": "无法确认是否有新的适配包。", - "contents": "适配包内容不完整或格式不对,没有启用。", - "signature": "适配包的签名不对,已拒绝,没有启用。", - "size": "适配包超出大小上限,已拒绝。", - "needs_app_update": "这个适配包需要更新版本的离线版,请先更新离线版。", - "up_to_date": "已是最新,没有需要下载的适配包。" - } - }, - "update": { - "title": "本体更新", - "check": "检查本体版本", - "checking": "正在检查…", - "current": "当前已是最新版本。", - "available": "版本 {{version}} 可用,安装包 {{size}}。", - "downloading": "正在下载安装包…", - "download": "下载更新", - "install": "退出并安装", - "installing": "正在打开安装包…", - "mods": { - "sections": { - "list": "模组列表", - "presets": "预设与仓库" - }, - "loading": "正在读取模组信息…", - "noCopy": "请先安装或选择一个离线客户端,再为它配置模组。", - "enabledSummary": "已启用 {{enabled}} / {{total}}", - "experimentalTitle": "实验期模组接口提示:", - "experimentalBody": "离线版当前处于极初期开发阶段(API {{api}})。服务端脚本钩子、内部数据结构及声明式 exe 补丁契约随时可能随本体更新变动且不保证向下兼容;请仅启用来源可信的模组。", - "readOnlyNotice": "游戏、本地服务器或维护任务运行期间,模组开关、排序与预设为只读。", - "searchPlaceholder": "搜索模组名称、ID 或作者…", - "autoSort": "按依赖自动排序", - "autoSorted": "已按前置与排序建议重新排列模组顺序。", - "refresh": "刷新", - "openFolder": "打开模组目录", - "discoveryErrorsTitle": "有 {{count}} 个模组目录读取失败:", - "blockingIssuesTitle": "存在 {{count}} 项阻塞性模组错误(处理前无法启动):", - "issuesTitle": "检测到 {{count}} 项模组提示或冲突:", - "severity": { - "error": "错误", - "warning": "警告", - "info": "提示" - }, - "emptyTitle": "当前模组目录里还没有模组。", - "emptyHint": "将包含 mod.jsonc 的模组文件夹放入 {{path}},点击「刷新」即可识别。独立涂装、瞄具与单人任务继续沿用游戏原生的 UserSkins / UserSights / UserMissions 目录即可。", - "noSearchMatch": "没有匹配当前搜索条件的模组。", - "loadOrderHint": "加载顺序:越靠后优先级越高(可拖动或使用上下按钮调整)", - "moveUp": "上移", - "moveDown": "下移", - "showDetails": "详情", - "hideDetails": "收起", - "errorCount": "{{count}} 错误", - "warnCount": "{{count}} 警告", - "badges": { - "data": "数据/资源", - "gui": "界面补丁", - "script": "服务端脚本", - "exe": "二进制补丁" - }, - "details": { - "folder": "目录", - "gameVersions": "声明适配版本", - "requires": "前置依赖", - "conflicts": "已知互斥", - "tuning": "服务端数值叠加:{{count}} 份", - "serverScript": "含可执行服务端 JS/TS 脚本", - "packOps": "客户端数据包操作:{{count}} 项", - "addon": "独立 3D 模型/贴图扩展包:{{count}} 个文件", - "guiPatches": "界面脚本补丁:{{count}} 项", - "exePatches": "声明式 exe 补丁:{{count}} 项", - "companionFiles": "附带外置文件:{{count}} 个", - "configBlk": "含 config.blk 增量补丁" - }, - "presets": { - "heading": "模组序列预设(当前客户端独立保存)", - "description": "将当前的启用开关与加载顺序保存为预设,方便在不同玩法配置间一键切换,或导出 JSON 分享给其他玩家。", - "quickSwitch": "快速切换模组预设", - "customOption": "当前自定义配置", - "namePlaceholder": "输入新预设名称,例如:现代载具包", - "saveCurrent": "保存为预设", - "import": "导入预设…", - "empty": "当前客户端尚未保存任何模组预设。", - "activeTag": "当前使用", - "summary": "启用 {{count}} / 共 {{total}} 个模组", - "apply": "应用", - "overwrite": "覆盖更新", - "export": "导出", - "delete": "删除", - "saved": "已保存预设「{{name}}」。", - "applied": "已切换至预设「{{name}}」。", - "updated": "已用当前配置覆盖预设「{{name}}」。", - "exported": "预设已导出到:{{path}}", - "imported": "已导入模组预设。" - }, - "repo": { - "heading": "全局模组仓库位置", - "description": "所有客户端共享同一份模组文件仓库(大体积 3D 模型与贴图包通过跨盘目录联接点零拷贝挂载,不重复占用磁盘);每个客户端独立保存自己的开关、排序和预设。", - "pathLabel": "当前仓库目录", - "defaultNote": "使用启动器默认模组目录", - "customNote": "使用自定义模组目录(可放在大容量硬盘或游戏同盘)", - "changeFolder": "更改目录…", - "resetDefault": "恢复默认目录", - "pickTitle": "选择全局模组仓库目录", - "updated": "已更新全局模组仓库目录。", - "resetDone": "已恢复为默认模组仓库目录。" - } - }, - "errors": { - "network": "暂时无法访问更新源。", - "page_limit": "无法确认是否有新版本。", - "contents": "本体更新的发布信息无效。", - "signature": "本体更新签名校验失败。", - "no_signing_key": "本体更新公钥不可用。" - } - }, - "statement": "项目信息", - "statementBody": "WTOffline 是一个独立于 Gaijin 的非商业兴趣项目。运行需要自备战争雷霆游戏本体文件。", - "community": { - "discord": "Discord", - "discordHint": "开发讨论、日常交流、使用求助与问题反馈。", - "openDiscord": "打开 Discord" - } - }, - "features": { - "A-Offline startup": "离线启动", - "A-Local accounts": "本地账号", - "A-Isolation from the official game": "与在线版隔离", - "A-No Gaijin connections": "阻断 Gaijin 连接", - "A-Tutorials": "新手教程", - "B-Hangar and vehicles": "机库与载具", - "G-Store": "商店", - "G-Redeem codes": "兑换码", - "G-Marketplace": "交易所", - "G-Currencies": "货币购买", - "G-Premium account": "高级账户", - "G-Boosters": "加成道具", - "H-Contracts and wagers": "作战合约", - "H-Supply chests": "补给箱", - "H-Recycling and crafting": "物品回收与合成", - "H-Coupons": "兑换券", - "J-Game modes": "对局模式", - "J-Ground arcade and realistic": "陆战(街机、历史)", - "J-Air arcade and realistic": "空战(街机、历史)", - "J-Naval arcade and realistic": "海战(街机、历史)", - "E-Crew skills in battle": "战局乘员技能与资格", - "J-Sub-modes": "附加模式(如夜战)", - "K-AI opponents and teammates": "AI 对手与队友", - "K-Spawn score and respawns": "出生点数与重生", - "K-Scouting": "侦察与无人机", - "K-Kill, assist and capture scoring": "击杀、助攻与占点计分", - "K-Player damage notices": "玩家载具受损提示", - "K-Additional vehicles": "补充载具", - "K-Scoreboard": "计分板", - "K-Chat and radio": "聊天与无线电", - "K-Nuclear bomb": "核弹", - "L-Debriefing": "战后结算", - "L-Battle awards": "战斗嘉奖" - }, - "mods": { - "sections": { - "list": "模组列表", - "presets": "预设与仓库" - }, - "loading": "正在读取模组信息…", - "noCopy": "请先安装或选择一个离线客户端,再为它配置模组。", - "enabledSummary": "已启用 {{enabled}} / {{total}}", - "experimentalTitle": "实验期模组接口提示:", - "experimentalBody": "离线版当前处于极初期开发阶段(API {{api}})。服务端脚本钩子、内部数据结构及声明式 exe 补丁契约随时可能随本体更新变动且不保证向下兼容;请仅启用来源可信的模组。", - "readOnlyNotice": "游戏、本地服务器或维护任务运行期间,模组开关、排序与预设为只读。", - "searchPlaceholder": "搜索模组名称、ID 或作者…", - "autoSort": "按依赖自动排序", - "autoSorted": "已按前置与排序建议重新排列模组顺序。", - "refresh": "刷新", - "openFolder": "打开模组目录", - "discoveryErrorsTitle": "有 {{count}} 个模组目录读取失败:", - "blockingIssuesTitle": "存在 {{count}} 项阻塞性模组错误(处理前无法启动):", - "issuesTitle": "检测到 {{count}} 项模组提示或冲突:", - "severity": { - "error": "错误", - "warning": "警告", - "info": "提示" - }, - "emptyTitle": "当前模组目录里还没有模组。", - "emptyHint": "将包含 mod.jsonc 的模组文件夹放入 {{path}},点击「刷新」即可识别。独立涂装、瞄具与单人任务继续沿用游戏原生的 UserSkins / UserSights / UserMissions 目录即可。", - "noSearchMatch": "没有匹配当前搜索条件的模组。", - "loadOrderHint": "加载顺序:越靠后优先级越高(可拖动或使用上下按钮调整)", - "moveUp": "上移", - "moveDown": "下移", - "showDetails": "详情", - "hideDetails": "收起", - "errorCount": "{{count}} 错误", - "warnCount": "{{count}} 警告", - "badges": { - "data": "数据/资源", - "gui": "界面补丁", - "script": "服务端脚本", - "exe": "二进制补丁" - }, - "details": { - "folder": "目录", - "gameVersions": "声明适配版本", - "requires": "前置依赖", - "conflicts": "已知互斥", - "tuning": "服务端数值叠加:{{count}} 份", - "serverScript": "含可执行服务端 JS/TS 脚本", - "packOps": "客户端数据包操作:{{count}} 项", - "addon": "独立 3D 模型/贴图扩展包:{{count}} 个文件", - "guiPatches": "界面脚本补丁:{{count}} 项", - "exePatches": "声明式 exe 补丁:{{count}} 项", - "companionFiles": "附带外置文件:{{count}} 个", - "configBlk": "含 config.blk 增量补丁" - }, - "presets": { - "heading": "模组序列预设(当前客户端独立保存)", - "description": "将当前的启用开关与加载顺序保存为预设,方便在不同玩法配置间一键切换,或导出 JSON 分享给其他玩家。", - "quickSwitch": "快速切换模组预设", - "customOption": "当前自定义配置", - "namePlaceholder": "输入新预设名称,例如:现代载具包", - "saveCurrent": "保存为预设", - "import": "导入预设…", - "empty": "当前客户端尚未保存任何模组预设。", - "activeTag": "当前使用", - "summary": "启用 {{count}} / 共 {{total}} 个模组", - "apply": "应用", - "overwrite": "覆盖更新", - "export": "导出", - "delete": "删除", - "saved": "已保存预设「{{name}}」。", - "applied": "已切换至预设「{{name}}」。", - "updated": "已用当前配置覆盖预设「{{name}}」。", - "exported": "预设已导出到:{{path}}", - "imported": "已导入模组预设。" - }, - "repo": { - "heading": "全局模组仓库位置", - "description": "所有客户端共享同一份模组文件仓库(大体积 3D 模型与贴图包通过跨盘目录联接点零拷贝挂载,不重复占用磁盘);每个客户端独立保存自己的开关、排序和预设。", - "pathLabel": "当前仓库目录", - "defaultNote": "使用启动器默认模组目录", - "customNote": "使用自定义模组目录(可放在大容量硬盘或游戏同盘)", - "changeFolder": "更改目录…", - "resetDefault": "恢复默认目录", - "pickTitle": "选择全局模组仓库目录", - "updated": "已更新全局模组仓库目录。", - "resetDone": "已恢复为默认模组仓库目录。" - } - }, - "errors": { - "app_update_unavailable": "当前没有可安装的本体更新。", - "app_update_busy": "本体更新操作正在进行。", - "app_update_launcher_busy": "请在游戏退出、服务器关闭及客户端和存档操作完成后安装更新。", - "app_update_download_failed": "无法下载并验证本体安装包。请查看启动器日志。", - "app_update_installer_invalid": "安装包校验失败。请重新下载。", - "app_update_install_failed": "无法打开本体安装包。请查看启动器日志。", - "internal_error": "启动器内部错误。", - "logs_folder_open_failed": "无法打开启动器日志文件夹。", - "diagnostics_export_failed": "无法保存诊断信息。", - "save_official_invalid": "所选文件不是受支持的在线版数据文件。", - "save_official_location": "请选择复制到在线版目录以外的数据文件。", - "save_archive_invalid": "所选文件不是受支持的 WTOffline 存档归档。", - "save_not_found": "找不到所选存档。", - "save_read_only": "游戏或本地服务器运行期间存档为只读。", - "save_operation_failed": "存档操作失败。请查看启动器日志。", - "save_login_invalid": "登录账号不能包含空格。", - "save_login_exists": "该登录账号已注册。", - "save_password_invalid": "请输入密码。", - "save_nick_invalid": "请输入最多 16 个字符的昵称。", - "save_avatar_invalid": "请选择此客户端中可用的头像。", - "save_level_invalid": "请输入此客户端支持的账号等级。", - "tuning_invalid": "无法读取或保存数值。请核对对局人数限制和启动器日志。", - "mods_read_only": "游戏、本地服务器或维护任务运行期间无法修改模组配置。", - "mods_write_failed": "无法保存模组配置,请查看启动器日志。", - "mods_preset_invalid": "所选文件不是有效的 WTOffline 模组预设。", - "mods_blocking_issues": "当前启用的模组存在缺失前置或互斥冲突,请先在「模组」页面处理后再启动。", - "mods_folder_invalid": "所选全局模组目录无效或无法写入。", - "copy_not_found": "所选客户端已不可用。", - "copies_write_failed": "无法保存客户端记录。", - "copy_location_in_use": "客户端位置或数据目录与已有客户端重叠。", - "decal_source_invalid": "选定的目录缺少有效的贴花缓存。", - "decal_import_failed": "无法把贴花缓存导入客户端数据目录。请查看启动器日志。", - "maintenance_busy": "维护前需结束游戏、本地服务器和其他客户端操作。", - "maintenance_location": "操作会影响登记的客户端或数据目录之外的文件。", - "maintenance_no_update": "安装来源没有可用的新版本。", - "maintenance_cancelled": "客户端更新已取消。", - "maintenance_failed": "客户端维护失败。请查看启动器日志。", - "maintenance_source_changed": "安装来源在更新过程中发生变化。请在在线版更新完成后重试。", - "launch_no_copy": "启动前需要安装离线客户端。", - "launch_busy": "启动流程正在运行。", - "launch_failed": "启动失败。请查看启动器日志。", - "launch_platform_unsupported": "启动游戏需要 Windows。", - "launch_lab_required": "请启用开发模式以通过隔离实验客户端启动。", - "launch_lab_missing": "无法读取隔离实验自动化配置。", - "launch_lab_version": "实验客户端和原版文件备份必须使用同一游戏版本。", - "launch_lab_failed": "隔离启动失败。请查看启动器日志。", - "launch_game_running": "已有游戏进程在运行。", - "launch_copy_in_steam": "隔离实验需使用 Steam 目录外的客户端和数据目录。", - "launch_steam_confirmation_required": "请在客户端维护中确认 Steam 目录后再启动。", - "launch_location": "客户端、原版文件备份或数据目录的位置无效。", - "launch_stock_version": "原版文件备份的版本与客户端不一致。", - "launch_stock_missing": "缺少或无法读取原版文件备份(wtoffline\\stock)。请检查安全软件拦截记录,或移除此客户端登记后重新添加。", - "launch_build_failed": "无法生成游戏文件。", - "launch_build_unavailable": "生成游戏文件时发现需要重新确认的不可用补丁。", - "launch_port_busy": "本地服务器端口已被占用。", - "launch_server_failed": "无法启动本地服务器。请查看启动器日志。", - "launch_server_exited": "本地服务器不可用。", - "launch_game_failed": "游戏进程无法启动。请查看启动器日志。", - "launch_game_files_missing": "启动所需的核心文件缺失或无法访问(可能已被安全软件隔离)。请检查安全软件拦截记录或查看启动器日志。", - "settings_write_failed": "无法保存设置。", - "folder_unreadable": "无法读取文件夹:{{path}}", - "not_a_game_folder": "所选文件夹不是战争雷霆的安装文件夹:{{path}}", - "stock_source_invalid": "所选客户端已打过离线补丁且缺少原版文件备份,请指定一份未打补丁的同版本原版游戏目录。", - "stock_source_version_mismatch": "所选原版游戏目录版本({{actual}})与当前客户端版本({{expected}})不一致。", - "target_not_usable": "所选文件夹不能用于安装。", - "steam_library_not_confirmed": "客户端或数据目录位于 Steam 游戏库中,请先确认风险提示。", - "not_enough_space": "磁盘空间不足:需要 {{neededGb}} GB,仅剩 {{freeGb}} GB。", - "essential_patches_unavailable": "此游戏版本缺少离线版运行所必需的补丁,无法安装:{{patches}}", - "missing_features_not_accepted": "部分补丁不适用,请先确认是否在缺少相应功能的情况下继续。", - "patch_check_failed": "检查补丁时出错。", - "copy_failed": "复制游戏文件失败,已复制的文件已删除。", - "hardlink_unavailable": "省空间复制要求目标与原版位于同一磁盘卷,转换已有客户端还要求版本一致。", - "hardlink_no_match": "未找到可共用的只读资源包,或文件内容与原版不一致。", - "hardlink_file_changed": "核对或复制过程中有资源文件发生变化。请等待其他文件操作完成后重试。", - "install_cancelled": "安装已取消,已复制的文件已删除。", - "install_busy": "已有安装正在进行。", - "unknown": "发生未知错误。" - } -} +{ + "app": { + "title": "战争雷霆离线版", + "subtitle": "战争雷霆离线版" + }, + "nav": { + "home": "首页", + "saves": "存档", + "tuning": "数值", + "mods": "模组", + "copies": "客户端", + "settings": "设置", + "about": "关于" + }, + "window": { + "minimize": "最小化", + "close": "关闭" + }, + "language": { + "label": "语言", + "system": "跟随系统", + "zh-CN": "简体中文", + "en": "English" + }, + "footer": { + "launcher": "启动器 {{version}}", + "game": "{{name}} · 游戏 {{version}}", + "notInstalled": "未安装", + "packUpdate": "适配包 {{version}} 可用 · 更新 ›", + "appUpdate": "本体 {{version}} 可用 · 更新 ›" + }, + "home": { + "kicker": "本地服务器 · AI 对局", + "installedKicker": "游戏 {{version}}", + "body": "选择「安装」以配置离线客户端。", + "steps": { + "choose": "选择游戏", + "chooseBody": "指定游戏的安装位置", + "method": "选择安装方式", + "methodBody": "创建客户端或使用已有文件夹", + "check": "检查补丁", + "checkBody": "核对所选版本的功能状态" + } + }, + "side": { + "requirements": "安装要求", + "game": "游戏", + "gameValue": "战争雷霆在线版客户端", + "versions": "已验证版本", + "space": "磁盘空间", + "spaceValue": "约 97 GB(复制安装)", + "currentCopy": "当前客户端", + "copyName": "离线客户端", + "adaptation": "核对状态", + "features": "功能", + "allAvailable": "✓ 全部可用", + "someMissing": "⚠ {{count}} 项不可用", + "details": "详情" + }, + "adaptation": { + "verified": "✓ 已核对", + "unverified": "⚠ 未核对" + }, + "bar": { + "notInstalled": "未安装", + "notInstalledDetail": "需要已安装的战争雷霆在线版客户端", + "install": "安装", + "ready": "就绪", + "readyMissing": "就绪 · {{count}} 项功能不可用", + "readyDetail": "游戏 {{version}}", + "missingFolder": "客户端目录不存在", + "launch": "启动" + }, + "launch": { + "checking": "正在检查客户端", + "building": "正在生成游戏文件", + "starting-server": "正在启动本地服务器", + "starting-game": "正在启动游戏", + "starting": "启动中…", + "running": "游戏运行中", + "runningDetail": "本地服务器 · 端口 {{port}}", + "server-running": "本地服务器运行中", + "game-exited": "游戏已退出", + "gameExitedServerRunning": "游戏已退出。本地服务器仍在运行。", + "exitDetail": "退出码 {{code}}。游戏日志位于 {{path}}。", + "exitCodeUnknown": "未知", + "stopping": "正在关闭", + "stopServer": "关闭本地服务器", + "cancel": "取消", + "stop": "结束游戏", + "retry": "重试", + "check": "检查", + "version-changed": "客户端版本已变更", + "versionDetail": "游戏版本 {{version}}", + "port-busy": "端口 {{port}} 已被占用", + "server-exited": "本地服务器意外退出" + }, + "decals": { + "source": "贴花来源", + "hint": "可导入在线版游戏的 cache/content。未导入时使用占位贴花。", + "choose": "选择贴花缓存…", + "useDefault": "使用占位贴花", + "importing": "正在导入贴花缓存", + "imported": "已导入缓存", + "default": "占位贴花" + }, + "folder": { + "none": "未选择", + "choose": "浏览…", + "change": "更改…" + }, + "wizard": { + "title": "添加客户端", + "steps": { + "mode": "添加方式", + "source": "游戏位置", + "method": "安装方式", + "data": "数据目录", + "check": "补丁检查", + "installing": "安装" + }, + "barTitle": "添加客户端 · {{step}}", + "stepOf": "第 {{index}} 步,共 {{total}} 步", + "back": "上一步", + "next": "下一步", + "cancel": "取消", + "install": "开始安装", + "installing": "安装中", + "checking": "正在检查补丁", + "checkingDetail": "正在核对补丁对所选游戏的适用情况" + }, + "mode": { + "body": "选择添加离线客户端的方式。", + "newTitle": "从在线版全新安装", + "newBody": "从已安装的战争雷霆在线版创建新的离线客户端,支持完整复制、省空间复制或原位安装。", + "existingTitle": "添加已有离线客户端", + "existingBody": "直接登记已准备好的离线客户端文件夹,不重新复制游戏文件。" + }, + "source": { + "body": "选择已安装的战争雷霆文件夹。", + "dialogTitle": "选择战争雷霆安装文件夹", + "existingBody": "选择已准备好的离线客户端文件夹。", + "existingDialogTitle": "选择已有离线客户端文件夹", + "offlineBackupDetected": "已检测到离线客户端的原版文件备份(wtoffline\\stock),可直接添加,无需重新复制。", + "patchedNeedsStock": "所选文件夹已包含离线补丁,但缺少 4 个原版核心文件(wtoffline\\stock)。请选择同版本的原版游戏目录,启动器将只读复制这 4 个文件(约 150 MB),无需重新复制整包游戏。", + "stockSourceTitle": "选择同版本的原版战争雷霆目录", + "stockSourcePatched": "所选目录同样已打过离线补丁且缺少原版文件备份,请选择未打补丁的原版游戏目录。", + "stockSourceVersionMismatch": "所选原版目录版本({{actual}})与当前客户端版本({{expected}})不一致。", + "stockSourceReady": "原版核心文件来源就绪(版本 {{version}}),添加时将仅复制 4 个核心文件至 wtoffline\\stock。", + "notAGame": "所选文件夹不是战争雷霆的安装文件夹,缺少:{{files}}", + "versionVerified": "游戏版本 {{version}}(已核对)", + "versionUnverified": "游戏版本 {{version}} 还没有核对记录。安装时仍会逐个尝试全部补丁,可用功能以补丁检查结果为准。", + "versionUnknown": "未知", + "size": "大小 {{size}} · {{files}} 个文件", + "measuring": "正在统计大小…" + }, + "method": { + "copy": "复制安装(推荐)", + "copyBody": "将游戏复制到新文件夹。需要约 {{size}} 的可用空间。", + "spaceSaving": "节省空间的复制", + "spaceSavingBody": "与同一磁盘卷上的原版共用只读资源包,预计需要 {{size}}。原版就地更新可能改变客户端中的共享文件。", + "spaceSavingPending": "正在估算可节省的空间。", + "spaceSavingUnavailable": "该安装目录没有可用于省空间复制的只读资源包。", + "sameVolumeRequired": "请选择与原版位于同一磁盘卷的目标文件夹。", + "targetTitle": "选择安装位置(将自动创建 WTOffline 子文件夹)", + "targetSubfolderHint": "将在所选位置下自动创建独立的 WTOffline 文件夹存放游戏文件,避免文件散落。", + "inPlace": "原位安装", + "inPlaceBody": "使用所选游戏文件夹作为客户端。原版文件备份至 wtoffline\\stock,首次启动时将应用补丁。", + "existing": "添加已有客户端", + "existingBody": "直接登记所选的已有游戏文件夹,不复制游戏文件;如尚未建立原版备份将自动备份至 wtoffline\\stock。", + "existingBodyWithBackup": "直接登记已存在的离线客户端,保留现有的 wtoffline\\stock 原版文件备份,不复制游戏文件。", + "existingBodyWithStockSource": "直接登记已存在的离线客户端,仅从所选原版目录补齐 4 个核心文件至 wtoffline\\stock,不重新复制游戏。", + "room": "目标磁盘可用空间:{{free}}", + "noRoom": "可用空间不足:需要 {{needed}},目标磁盘仅剩 {{free}}。", + "problem": { + "not_empty": "所选文件夹不为空。请选择空文件夹或新建文件夹。", + "overlaps_stock": "不能选择在线版安装文件夹本身,或其上级、下级文件夹。", + "not_a_folder": "所选路径不是文件夹。" + }, + "copyBodyPending": "将游戏复制到新文件夹。正在统计所需空间。" + }, + "steam": { + "inPlaceWarning": "离线启动会修改此 Steam 安装中的游戏文件。Steam 更新或文件校验可能覆盖改动。使用修改后的文件联网启动在线版可能导致账号封禁。", + "copyWarning": "目标文件夹位于 Steam 游戏库。建议将客户端放在游戏库之外。", + "confirm": "确认使用此文件夹", + "dataWarning": "数据目录放在 Steam 游戏文件夹内时,在 Steam 中卸载游戏可能一并删除存档、缓存和日志。", + "maintenanceWarning": "客户端或数据目录位于 Steam 游戏库中。离线启动可能修改库内的游戏文件。Steam 更新或校验可能覆盖改动,使用修改后的文件联网启动可能导致账号封禁。在 Steam 中卸载游戏还可能删除保存在该游戏文件夹内的存档。", + "confirmLocations": "确认使用这些位置" + }, + "data": { + "body": "选择用于保存存档、缓存和日志的文件夹。", + "dialogTitle": "选择数据目录", + "problem": { + "overlaps_client": "数据目录不能与客户端目录相同、包含客户端目录,或位于客户端的 wtoffline 目录内。请选择独立文件夹或客户端内的专用子文件夹(例如 data)。", + "overlaps_stock": "数据目录不能位于在线版安装目录内。" + } + }, + "check": { + "running": "正在检查所选游戏版本的补丁。", + "allFit": "全部 {{count}} 个补丁均适用于此游戏版本。", + "essentialMissing": "必需补丁无法应用,安装无法继续。受影响的功能:", + "someMissing": "{{count}} 个补丁不适用于此游戏版本,以下功能将不可用:", + "details": "查看补丁详情", + "accept": "接受上述功能不可用并继续安装" + }, + "progress": { + "phase": { + "checking": "检查游戏文件", + "measuring": "统计文件", + "verifying": "核对可共用的资源", + "copying": "复制游戏文件", + "importing-decals": "正在导入贴花缓存", + "backing-up": "备份原版文件", + "recording": "完成安装" + }, + "copied": "已复制 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件", + "verified": "已核对 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件", + "prepared": "已处理 {{done}} / {{total}} · {{doneFiles}} / {{totalFiles}} 个文件", + "cancelHint": "可随时取消,已复制的文件将被删除", + "cancel": "取消安装", + "cancelling": "正在取消…" + }, + "copies": { + "sections": { + "list": "全部客户端", + "summary": "客户端详情", + "features": "功能状态", + "maintain": "维护" + }, + "add": "添加客户端", + "missingFolder": "目录不存在", + "relocate": "重新定位…", + "relocateDialogTitle": "选择挪动后的客户端文件夹", + "list": { + "current": "当前", + "select": "设为当前" + }, + "none": "尚未安装离线版。", + "maintenance": { + "update": "从在线版更新", + "updateAction": "更新客户端", + "newVersion": "安装来源已更新至 {{version}}。", + "updateKeepsSpaceSaving": "安装来源中有新版本 {{version}}。更新时会继续与原版共用只读资源包。", + "updateDetaches": "安装来源中有新版本 {{version}}。当前与安装来源不在同一磁盘卷,更新会把共享资源复制为独立文件,需要额外空间。", + "currentVersion": "安装来源版本 {{version}}", + "noSource": "安装来源不可用", + "spaceSaving": "节省空间", + "spaceSavingHint": "将内容一致的只读资源包与原版共用。原版就地更新可能改变这些文件。", + "spaceSavingUnavailable": "客户端和安装来源须位于同一磁盘卷,并且版本一致。", + "compactAction": "转换", + "check": "重新检查补丁", + "checkHint": "核对原版文件备份。", + "lastCheck": "上次检查 {{date}}", + "repair": "修复客户端", + "repairAction": "修复", + "repairHint": "从原版文件备份还原文件。下次启动时重新生成游戏文件。", + "delete": "删除客户端", + "deleteAction": "删除…", + "deleteHint": "默认保留数据目录。", + "unlink": "解除登记", + "unlinkAction": "解除登记…", + "unlinkHint": "Steam 游戏文件和数据目录将留在原处。", + "unlinkLocation": "从启动器中解除 {{path}} 的登记?Steam 游戏文件和数据将留在原处。", + "deleteLocation": "确认删除 {{path}} 中的离线客户端?", + "deleteData": "同时删除 {{path}} 中的数据", + "confirm": "确认删除", + "phase": { + "checking": "正在检查客户端", + "copying": "正在复制有变化的文件", + "applying": "正在应用更改" + }, + "result": { + "confirm-steam": "已确认 Steam 目录。", + "check": "补丁检查已完成。", + "repair": "原版文件已还原。", + "update": "客户端已更新。", + "compact": "省空间转换已完成。", + "delete": "客户端已删除。", + "cancelled": "维护已取消。" + } + }, + "summary": { + "name": "客户端名称", + "rename": "重命名", + "source": "安装来源", + "version": "游戏版本", + "adaptation": "核对状态", + "adaptationHint": "这个游戏版本是否检查过全部补丁并在游戏里验证过", + "location": "位置", + "missingHint": "未在原位置找到游戏文件。可重新定位至挪动后的文件夹,保留现有存档和数值。", + "method": "安装方式", + "methods": { + "copy": "复制安装", + "hardlink": "节省空间的复制", + "in-place": "原位安装", + "existing": "已有客户端" + }, + "stock": "原版文件备份", + "stockHint": "每次启动时据此生成补丁文件", + "data": "数据目录", + "dataHint": "存档、缓存与日志", + "installedAt": "安装时间", + "features": "功能", + "open": "打开" + }, + "features": { + "lead": "补丁检查结果决定功能是否可用。安装需要全部必需补丁。", + "essential": "必需", + "verifiedOn": "已核对:{{version}}", + "passedCheck": "补丁检查通过(这个游戏版本未核对)", + "unavailable": "补丁不适用:{{patches}}", + "allAvailable": "全部可用", + "someMissing": "{{count}} 项不可用", + "checkedAt": "检查时间:{{time}}(安装时)" + } + }, + "featureSections": { + "A": "启动与账号", + "B": "机库与载具", + "C": "科技树与研发", + "D": "改装、武器与弹药", + "E": "乘员", + "F": "外观定制", + "G": "经济与商店", + "H": "道具与库存", + "I": "联队", + "J": "对局模式", + "K": "对局内", + "L": "战后与统计", + "M": "回放", + "N": "设置、操控与模组", + "O": "多人社交" + }, + "saves": { + "sections": { + "list": "全部存档", + "overview": "概览", + "battles": "战绩", + "vehicles": "载具与研发", + "official": "导入在线版数据", + "backup": "备份与还原" + }, + "tree": { + "branch": "国家与兵种", + "country": "国家", + "type": "兵种", + "actions": "批量操作", + "research": "全部研发", + "purchase": "获得常规载具", + "equipment": "解锁改装件", + "empty": "此客户端没有可编辑的研发分支。", + "rank": "等级 {{rank}}", + "owned": "已拥有", + "points": "{{earned}} / {{needed}} 研发点", + "countries": { + "country_usa": "美国", + "country_germany": "德国", + "country_ussr": "苏联", + "country_britain": "英国", + "country_japan": "日本", + "country_china": "中国", + "country_italy": "意大利", + "country_france": "法国", + "country_sweden": "瑞典", + "country_israel": "以色列" + }, + "types": { + "Aircraft": "空军", + "Tank": "陆军", + "Ship": "远洋舰队", + "Boat": "近岸舰队", + "Helicopter": "直升机" + } + }, + "official": { + "auto": "自动导入", + "autoHint": "只读查找本机在线版数据并复制到离线目录后再导入,不修改在线版原文件。", + "oneClick": "一键查找并导入", + "discover": "仅查找并预览", + "notFound": "未在默认文档目录中找到在线版数据,请使用下方手动选择。", + "account": "在线版账号", + "multipleAccounts": "检测到 {{count}} 个在线版账号目录,请选择要导入的账号。", + "accountOption": "账号 {{id}}({{files}} · 更新于 {{time}})", + "files": "手动选择文件", + "fileHint": "也可手动选择复制备份的 global.blk、machine.blk 或 storage.blk。", + "choose": "选择文件…", + "content": "导入内容", + "settings": "游戏设置与键位", + "unlock": "解锁预设中的载具", + "equipment": "改装件", + "equipmentHint": "完全体仅解锁常规改装件与弹药,不包含护身符。", + "full": "完全体", + "basic": "基础生存配件", + "stock": "白板状态", + "preview": "预览", + "import": "导入", + "summary": "{{files}} 个文件 · {{presets}} 套预设 · {{vehicles}} 辆可用载具", + "omitted": "将跳过的不可用载具 · {{names}}", + "done": "在线版数据已导入。原存档可在「备份与还原」中恢复。" + }, + "archive": { + "fromCopy": "从其他客户端复制", + "import": "导入存档文件…", + "sourceCopy": "来源客户端", + "transfer": "创建存档", + "copy": "复制", + "export": "导出…", + "delete": "删除…", + "confirmDelete": "确认删除 {{name}} 的本地账号和存档?", + "automatic": "启动前自动备份", + "retention": "每个存档保留最近 10 份自动备份。", + "backup": "立即备份", + "restore": "还原", + "noBackups": "此存档没有备份。", + "confirmRestore": "还原此备份?将先备份当前存档。", + "type": { + "manual": "手动备份", + "launch": "启动前自动备份", + "restore": "还原前自动备份", + "import": "导入前自动备份" + } + }, + "create": "新建存档", + "login": "登录账号", + "nick": "昵称", + "password": "密码", + "confirmPassword": "确认密码", + "passwordMismatch": "两次输入的密码不一致。", + "readOnly": "游戏或本地服务器正在运行,存档为只读。", + "noCopy": "选择离线客户端后即可管理该客户端的存档。", + "empty": "此客户端没有本地存档。", + "loading": "正在读取存档", + "silverLions": "银狮", + "goldenEagles": "金鹰", + "gjnCents": "GJN", + "freeRp": "通用研发点", + "vehicles": "载具", + "battles": "已记录对局", + "lastBattle": "上次对局", + "premiumDays": "高级账户剩余天数", + "avatar": "头像", + "avatarUnavailable": "头像不可用", + "level": "账号等级", + "apply": "保存更改", + "saved": "更改已保存。", + "noBattles": "此存档没有对局记录。", + "win": "胜利", + "loss": "失败", + "battleRewards": "{{sl}} 银狮 · {{rp}} 研发点", + "owned": "已拥有载具", + "research": "研发进度" + }, + "tuning": { + "sections": { + "rewards": "收益", + "battle": "对局", + "newProfile": "新存档", + "research": "研发" + }, + "fields": { + "rewardMultiplierSilverLions": "银狮倍率", + "rewardMultiplierResearchPoints": "研发点倍率", + "friendlyKillPenaltyMul": "误伤惩罚倍率", + "maxPlayers": "每局人数上限(含 AI)", + "smallTeamsMaxPlayers": "小规模模式人数上限", + "brSpreadMrank": "匹配范围", + "subModeChance": "附加模式概率", + "tankBotRespawns": "AI 坦克重生次数", + "airBotRespawns": "AI 飞机重生次数", + "strikeUcavSpawnScore": "打击无人机所需出生点数", + "silverLions": "初始银狮", + "goldenEagles": "初始金鹰", + "preferLineSuccessor": "优先研发同系载具", + "autoTargetPick": "自动研发目标" + }, + "target": { + "lowestRank": "最低等级", + "highestRank": "最高等级", + "treeOrder": "研发树顺序" + }, + "shared": "这些数值适用于此客户端的全部存档。", + "nextLaunch": "更改将在下次启动本地服务器时生效。", + "reset": "恢复本页默认值", + "default": "默认 {{value}}", + "on": "启用", + "off": "停用", + "saved": "数值已保存。", + "invalid": "请输入受支持范围内的数值。", + "loading": "正在读取数值", + "noCopy": "选择离线客户端后即可编辑数值。" + }, + "settings": { + "sections": { + "general": "常规", + "launch": "启动", + "dev": "开发者", + "diag": "诊断" + }, + "appUpdates": "启动器本体更新", + "appUpdatesToggle": "启动时检查本体更新", + "patchPacks": "适配包更新", + "patchPacksHint": "游戏更新后,新版本的补丁会以适配包的形式发布在 GitHub 上。", + "updateMirror": "备用更新仓库", + "updateMirrorHint": "填写支持 GitHub Releases 格式的 HTTPS 镜像地址。主源连接失败时使用,留空关闭。", + "updateMirrorInvalid": "请输入有效的 HTTPS 仓库地址,或留空。", + "patchPacksToggle": "启动时检查有没有新的适配包", + "windowClose": "关闭窗口时", + "windowQuit": "退出启动器", + "windowTray": "最小化到系统托盘", + "afterGameStarts": "游戏启动后", + "windowMinimize": "最小化启动器", + "windowKeep": "保持窗口", + "launch": { + "port": "本地服务器端口", + "portHint": "使用已安装实验自动化的端口设置", + "exit": "游戏退出后", + "exitHint": "隔离启动", + "automatic": "关闭本地服务器", + "portMode": "端口分配方式", + "autoPort": "自动分配", + "fixedPort": "指定端口", + "arguments": "附加启动参数", + "argumentsHint": "传递给游戏的命令行参数", + "argumentsInvalid": "请补全启动参数中的双引号。" + }, + "developer": { + "mode": "开发模式", + "modeHint": "以 wto-lab 用户身份启动实验客户端", + "enabled": "启用", + "stock": "原版文件备份", + "stockHint": "默认使用当前客户端的原版文件备份", + "data": "实验数据目录", + "dataHint": "默认使用当前客户端的数据目录", + "reset": "恢复默认" + }, + "diagnostics": { + "recordLogs": "生成运行日志", + "recordLogsToggle": "记录启动器、本地服务器和钩子日志", + "recordLogsHint": "关闭后停止写入启动器日志、本地服务器流量日志和 wto_ws.log(不影响游戏引擎原生的 .game_logs)。导出日志排查问题前建议重新开启。", + "loggingDisabledNotice": "当前已关闭运行日志记录,导出的压缩包仅包含已有历史日志和配置。", + "logs": "日志", + "logsHint": "启动器运行日志", + "openLogs": "打开日志文件夹", + "export": "导出诊断信息", + "exportHint": "导出包含启动器、本地服务器与游戏日志、设置和安装记录的 ZIP 文件(不含存档)", + "save": "导出…", + "saved": "诊断信息已保存到 {{path}}。", + "serverStatus": "本地服务器状态页", + "openStatus": "在浏览器中打开" + }, + "language": "语言", + "languageHint": "启动器界面的显示语言" + }, + "background": { + "title": "背景图", + "hint": "游戏背景图来自当前客户端。", + "official": "官网壁纸", + "officialHint": "联网下载官网壁纸。已下载的壁纸可离线使用。", + "officialToggle": "从战争雷霆官网获取壁纸", + "officialItem": "官网壁纸 · {{name}}", + "random": "随机", + "none": "暂无可用的背景图。安装后可使用游戏图片,或开启官网壁纸。", + "current": "背景:{{name}}", + "previous": "上一张", + "next": "下一张", + "nations": { + "default": "通用", + "usa": "美国", + "germany": "德国", + "ussr": "苏联", + "uk": "英国", + "japan": "日本", + "china": "中国", + "italy": "意大利", + "france": "法国", + "sweden": "瑞典", + "israel": "以色列" + } + }, + "about": { + "launcher": "启动器 {{version}}", + "supported": "支持的游戏版本:{{versions}}", + "feedback": { + "title": "问题反馈", + "export": "保存全部日志", + "exportHint": "打包启动器、本地服务器及游戏日志为 ZIP 文件以便反馈问题(不含存档)。", + "exportButton": "保存日志 ZIP…" + }, + "pack": { + "title": "适配数据", + "current": "当前使用", + "currentHint": "安装和更新客户端时使用的补丁。", + "bundled": "启动器自带", + "bundledVersion": "启动器自带({{version}})", + "downloaded": "适配包 {{version}}", + "useBundled": "改回启动器自带", + "check": "检查更新", + "checkHint": "检查是否有新的适配包。", + "checkButton": "检查", + "checking": "正在检查…", + "applying": "正在下载并校验适配包…", + "upToDate": "已是最新(最新的适配包是 {{version}})。", + "noneReleased": "还没有发布适配包。", + "available": "适配包 {{version}} 可用,支持的游戏版本:{{versions}}。", + "availableHint": "下载后会先校验签名,通过后才启用;之后安装和更新客户端都使用新的补丁。", + "apply": "下载并启用 {{version}}", + "needsAppUpdate": "适配包 {{version}} 需要离线版 {{app}} 或更新的版本,请先更新离线版。", + "checkFailed": { + "no_signing_key": "这个启动器没有内置签名公钥,不接受适配包。", + "network": "无法连接更新源,请稍后再试。", + "page_limit": "无法确认是否有新的适配包。", + "contents": "发布的适配包信息不完整或格式不对。", + "signature": "适配包的签名不对,已拒绝。", + "size": "适配包超出大小上限,已拒绝。" + }, + "applyFailed": { + "no_signing_key": "这个启动器没有内置签名公钥,不接受适配包。", + "network": "无法连接更新源来下载适配包,请稍后再试。", + "page_limit": "无法确认是否有新的适配包。", + "contents": "适配包内容不完整或格式不对,没有启用。", + "signature": "适配包的签名不对,已拒绝,没有启用。", + "size": "适配包超出大小上限,已拒绝。", + "needs_app_update": "这个适配包需要更新版本的离线版,请先更新离线版。", + "up_to_date": "已是最新,没有需要下载的适配包。" + } + }, + "update": { + "title": "本体更新", + "check": "检查本体版本", + "checking": "正在检查…", + "current": "当前已是最新版本。", + "available": "版本 {{version}} 可用,安装包 {{size}}。", + "downloading": "正在下载安装包…", + "download": "下载更新", + "install": "退出并安装", + "installing": "正在打开安装包…", + "errors": { + "network": "暂时无法访问更新源。", + "page_limit": "无法确认是否有新版本。", + "contents": "本体更新的发布信息无效。", + "signature": "本体更新签名校验失败。", + "no_signing_key": "本体更新公钥不可用。" + } + }, + "statement": "项目信息", + "statementBody": "WTOffline 是一个独立于 Gaijin 的非商业兴趣项目。运行需要自备战争雷霆游戏本体文件。", + "community": { + "discord": "Discord", + "discordHint": "开发讨论、日常交流、使用求助与问题反馈。", + "openDiscord": "打开 Discord" + } + }, + "features": { + "A-Offline startup": "离线启动", + "A-Local accounts": "本地账号", + "A-Isolation from the official game": "与在线版隔离", + "A-No Gaijin connections": "阻断 Gaijin 连接", + "A-Tutorials": "新手教程", + "B-Hangar and vehicles": "机库与载具", + "G-Store": "商店", + "G-Redeem codes": "兑换码", + "G-Marketplace": "交易所", + "G-Currencies": "货币购买", + "G-Premium account": "高级账户", + "G-Boosters": "加成道具", + "H-Contracts and wagers": "作战合约", + "H-Supply chests": "补给箱", + "H-Recycling and crafting": "物品回收与合成", + "H-Coupons": "兑换券", + "J-Game modes": "对局模式", + "J-Ground arcade and realistic": "陆战(街机、历史)", + "J-Air arcade and realistic": "空战(街机、历史)", + "J-Naval arcade and realistic": "海战(街机、历史)", + "E-Crew skills in battle": "战局乘员技能与资格", + "J-Sub-modes": "附加模式(如夜战)", + "K-AI opponents and teammates": "AI 对手与队友", + "K-Spawn score and respawns": "出生点数与重生", + "K-Scouting": "侦察与无人机", + "K-Kill, assist and capture scoring": "击杀、助攻与占点计分", + "K-Player damage notices": "玩家载具受损提示", + "K-Additional vehicles": "补充载具", + "K-Scoreboard": "计分板", + "K-Chat and radio": "聊天与无线电", + "K-Nuclear bomb": "核弹", + "L-Debriefing": "战后结算", + "L-Battle awards": "战斗嘉奖" + }, + "mods": { + "sections": { + "list": "模组列表", + "presets": "预设与仓库" + }, + "loading": "正在读取模组信息…", + "noCopy": "请先安装或选择一个离线客户端,再为它配置模组。", + "enabledSummary": "已启用 {{enabled}} / {{total}}", + "experimentalChip": "实验功能", + "experimentalTitle": "实验期模组接口提示:", + "experimentalBody": "离线版当前处于极初期开发阶段(API {{api}})。服务端脚本钩子、内部数据结构及声明式 exe 补丁契约随时可能随本体更新变动且不保证向下兼容;请仅启用来源可信的模组。", + "readOnlyNotice": "游戏、本地服务器或维护任务运行期间,模组开关、排序与预设为只读。", + "searchPlaceholder": "搜索模组名称、ID 或作者…", + "autoSort": "按依赖自动排序", + "autoSorted": "已按前置与排序建议重新排列模组顺序。", + "refresh": "刷新", + "openFolder": "打开模组目录", + "discoveryErrorsTitle": "有 {{count}} 个模组目录读取失败:", + "blockingIssuesTitle": "存在 {{count}} 项阻塞性模组错误(处理前无法启动):", + "issuesTitle": "检测到 {{count}} 项模组提示或冲突:", + "severity": { + "error": "错误", + "warning": "警告", + "info": "提示" + }, + "emptyTitle": "当前模组目录里还没有模组。", + "emptyHint": "将包含 mod.jsonc 的模组文件夹放入 {{path}},点击「刷新」即可识别。独立涂装、瞄具与单人任务继续沿用游戏原生的 UserSkins / UserSights / UserMissions 目录即可。", + "noSearchMatch": "没有匹配当前搜索条件的模组。", + "loadOrderHint": "加载顺序:越靠后优先级越高(可拖动或使用上下按钮调整)", + "moveUp": "上移", + "moveDown": "下移", + "showDetails": "详情", + "hideDetails": "收起", + "errorCount": "{{count}} 错误", + "warnCount": "{{count}} 警告", + "badges": { + "data": "数据/资源", + "gui": "界面补丁", + "script": "服务端脚本", + "exe": "二进制补丁" + }, + "details": { + "folder": "目录", + "gameVersions": "声明适配版本", + "requires": "前置依赖", + "conflicts": "已知互斥", + "tuning": "服务端数值叠加:{{count}} 份", + "serverScript": "含可执行服务端 JS/TS 脚本", + "packOps": "客户端数据包操作:{{count}} 项", + "addon": "独立 3D 模型/贴图扩展包:{{count}} 个文件", + "guiPatches": "界面脚本补丁:{{count}} 项", + "exePatches": "声明式 exe 补丁:{{count}} 项", + "companionFiles": "附带外置文件:{{count}} 个", + "configBlk": "含 config.blk 增量补丁" + }, + "presets": { + "heading": "模组序列预设(当前客户端独立保存)", + "description": "将当前的启用开关与加载顺序保存为预设,方便在不同玩法配置间一键切换,或导出 JSON 分享给其他玩家。", + "quickSwitch": "快速切换模组预设", + "customOption": "当前自定义配置", + "namePlaceholder": "输入新预设名称,例如:现代载具包", + "saveCurrent": "保存为预设", + "import": "导入预设…", + "empty": "当前客户端尚未保存任何模组预设。", + "activeTag": "当前使用", + "summary": "启用 {{count}} / 共 {{total}} 个模组", + "apply": "应用", + "overwrite": "覆盖更新", + "export": "导出", + "delete": "删除", + "saved": "已保存预设「{{name}}」。", + "applied": "已切换至预设「{{name}}」。", + "updated": "已用当前配置覆盖预设「{{name}}」。", + "exported": "预设已导出到:{{path}}", + "imported": "已导入模组预设。" + }, + "repo": { + "heading": "全局模组仓库位置", + "description": "所有客户端共享同一份模组文件仓库(大体积 3D 模型与贴图包通过跨盘目录联接点零拷贝挂载,不重复占用磁盘);每个客户端独立保存自己的开关、排序和预设。", + "pathLabel": "当前仓库目录", + "defaultNote": "使用启动器默认模组目录", + "customNote": "使用自定义模组目录(可放在大容量硬盘或游戏同盘)", + "changeFolder": "更改目录…", + "resetDefault": "恢复默认目录", + "pickTitle": "选择全局模组仓库目录", + "updated": "已更新全局模组仓库目录。", + "resetDone": "已恢复为默认模组仓库目录。" + } + }, + "errors": { + "app_update_unavailable": "当前没有可安装的本体更新。", + "app_update_busy": "本体更新操作正在进行。", + "app_update_launcher_busy": "请在游戏退出、服务器关闭及客户端和存档操作完成后安装更新。", + "app_update_download_failed": "无法下载并验证本体安装包。请查看启动器日志。", + "app_update_installer_invalid": "安装包校验失败。请重新下载。", + "app_update_install_failed": "无法打开本体安装包。请查看启动器日志。", + "internal_error": "启动器内部错误。", + "logs_folder_open_failed": "无法打开启动器日志文件夹。", + "diagnostics_export_failed": "无法保存诊断信息。", + "save_official_invalid": "所选文件不是受支持的在线版数据文件。", + "save_official_location": "请选择复制到在线版目录以外的数据文件。", + "save_archive_invalid": "所选文件不是受支持的 WTOffline 存档归档。", + "save_not_found": "找不到所选存档。", + "save_read_only": "游戏或本地服务器运行期间存档为只读。", + "save_operation_failed": "存档操作失败。请查看启动器日志。", + "save_login_invalid": "登录账号不能包含空格。", + "save_login_exists": "该登录账号已注册。", + "save_password_invalid": "请输入密码。", + "save_nick_invalid": "请输入最多 16 个字符的昵称。", + "save_avatar_invalid": "请选择此客户端中可用的头像。", + "save_level_invalid": "请输入此客户端支持的账号等级。", + "tuning_invalid": "无法读取或保存数值。请核对对局人数限制和启动器日志。", + "mods_read_only": "游戏、本地服务器或维护任务运行期间无法修改模组配置。", + "mods_write_failed": "无法保存模组配置,请查看启动器日志。", + "mods_preset_invalid": "所选文件不是有效的 WTOffline 模组预设。", + "mods_blocking_issues": "当前启用的模组存在缺失前置或互斥冲突,请先在「模组」页面处理后再启动。", + "mods_folder_invalid": "所选全局模组目录无效或无法写入。", + "copy_not_found": "所选客户端已不可用。", + "copies_write_failed": "无法保存客户端记录。", + "copy_location_in_use": "客户端位置或数据目录与已有客户端重叠。", + "decal_source_invalid": "选定的目录缺少有效的贴花缓存。", + "decal_import_failed": "无法把贴花缓存导入客户端数据目录。请查看启动器日志。", + "maintenance_busy": "维护前需结束游戏、本地服务器和其他客户端操作。", + "maintenance_location": "操作会影响登记的客户端或数据目录之外的文件。", + "maintenance_no_update": "安装来源没有可用的新版本。", + "maintenance_cancelled": "客户端更新已取消。", + "maintenance_failed": "客户端维护失败。请查看启动器日志。", + "maintenance_source_changed": "安装来源在更新过程中发生变化。请在在线版更新完成后重试。", + "launch_no_copy": "启动前需要安装离线客户端。", + "launch_busy": "启动流程正在运行。", + "launch_failed": "启动失败。请查看启动器日志。", + "launch_platform_unsupported": "启动游戏需要 Windows。", + "launch_lab_required": "请启用开发模式以通过隔离实验客户端启动。", + "launch_lab_missing": "无法读取隔离实验自动化配置。", + "launch_lab_version": "实验客户端和原版文件备份必须使用同一游戏版本。", + "launch_lab_failed": "隔离启动失败。请查看启动器日志。", + "launch_game_running": "已有游戏进程在运行。", + "launch_copy_in_steam": "隔离实验需使用 Steam 目录外的客户端和数据目录。", + "launch_steam_confirmation_required": "请在客户端维护中确认 Steam 目录后再启动。", + "launch_location": "客户端、原版文件备份或数据目录的位置无效。", + "launch_stock_version": "原版文件备份的版本与客户端不一致。", + "launch_stock_missing": "缺少或无法读取原版文件备份(wtoffline\\stock)。请检查安全软件拦截记录,或移除此客户端登记后重新添加。", + "launch_build_failed": "无法生成游戏文件。", + "launch_build_unavailable": "生成游戏文件时发现需要重新确认的不可用补丁。", + "launch_port_busy": "本地服务器端口已被占用。", + "launch_server_failed": "无法启动本地服务器。请查看启动器日志。", + "launch_server_exited": "本地服务器不可用。", + "launch_game_failed": "游戏进程无法启动。请查看启动器日志。", + "launch_game_files_missing": "启动所需的核心文件缺失或无法访问(可能已被安全软件隔离)。请检查安全软件拦截记录或查看启动器日志。", + "settings_write_failed": "无法保存设置。", + "folder_unreadable": "无法读取文件夹:{{path}}", + "not_a_game_folder": "所选文件夹不是战争雷霆的安装文件夹:{{path}}", + "stock_source_invalid": "所选客户端已打过离线补丁且缺少原版文件备份,请指定一份未打补丁的同版本原版游戏目录。", + "stock_source_version_mismatch": "所选原版游戏目录版本({{actual}})与当前客户端版本({{expected}})不一致。", + "target_not_usable": "所选文件夹不能用于安装。", + "steam_library_not_confirmed": "客户端或数据目录位于 Steam 游戏库中,请先确认风险提示。", + "not_enough_space": "磁盘空间不足:需要 {{neededGb}} GB,仅剩 {{freeGb}} GB。", + "essential_patches_unavailable": "此游戏版本缺少离线版运行所必需的补丁,无法安装:{{patches}}", + "missing_features_not_accepted": "部分补丁不适用,请先确认是否在缺少相应功能的情况下继续。", + "patch_check_failed": "检查补丁时出错。", + "copy_failed": "复制游戏文件失败,已复制的文件已删除。", + "hardlink_unavailable": "省空间复制要求目标与原版位于同一磁盘卷,转换已有客户端还要求版本一致。", + "hardlink_no_match": "未找到可共用的只读资源包,或文件内容与原版不一致。", + "hardlink_file_changed": "核对或复制过程中有资源文件发生变化。请等待其他文件操作完成后重试。", + "install_cancelled": "安装已取消,已复制的文件已删除。", + "install_busy": "已有安装正在进行。", + "unknown": "发生未知错误。" + } +} diff --git a/apps/launcher/src/renderer/src/pages/mods/ModsPage.tsx b/apps/launcher/src/renderer/src/pages/mods/ModsPage.tsx index ca39159..120cfc7 100644 --- a/apps/launcher/src/renderer/src/pages/mods/ModsPage.tsx +++ b/apps/launcher/src/renderer/src/pages/mods/ModsPage.tsx @@ -175,12 +175,26 @@ export function ModsPage({ copy, section, readOnly, onError }: Props) { const canDrag = !disabled && normalizedQuery.length === 0; return ( - -
- {t('mods.experimentalTitle')} - {t('mods.experimentalBody', { api: state.apiVersion })} -
- + + {copy.name} · {t('mods.enabledSummary', { enabled: enabledCount, total: state.mods.length })} + + {t('mods.experimentalChip')} + + + {t('mods.experimentalTitle')} + {t('mods.experimentalBody', { api: state.apiVersion })} + + + + )} + > {readOnly && (
{t('mods.readOnlyNotice')} diff --git a/apps/launcher/src/renderer/src/styles/pages.css b/apps/launcher/src/renderer/src/styles/pages.css index fcead22..bbfda5d 100644 --- a/apps/launcher/src/renderer/src/styles/pages.css +++ b/apps/launcher/src/renderer/src/styles/pages.css @@ -437,6 +437,82 @@ } /* ===== Mods ===== */ +.mods-aside { + display: inline-flex; + align-items: center; + gap: 10px; +} + +.mods-exp-chip { + position: relative; + display: inline-flex; + align-items: center; + gap: 5px; + padding: 2px 7px; + font-size: 11.5px; + line-height: 1.3; + color: rgba(255, 227, 163, 0.9); + background: rgba(214, 158, 46, 0.14); + border: 1px solid rgba(214, 158, 46, 0.38); + border-radius: var(--radius); + cursor: help; + user-select: none; +} + +.mods-exp-chip:hover, +.mods-exp-chip:focus-visible { + background: rgba(214, 158, 46, 0.22); + border-color: rgba(214, 158, 46, 0.6); + outline: none; +} + +.mods-exp-icon { + display: inline-flex; + align-items: center; + justify-content: center; + width: 14px; + height: 14px; + font-size: 10px; + font-weight: 700; + font-style: normal; + border-radius: 50%; + border: 1px solid rgba(255, 227, 163, 0.55); +} + +.mods-exp-popover { + position: absolute; + top: calc(100% + 8px); + right: 0; + z-index: 40; + width: 340px; + max-width: min(340px, 70vw); + display: flex; + flex-direction: column; + gap: 4px; + padding: 10px 12px; + font-size: 12px; + line-height: 1.5; + text-align: left; + white-space: normal; + color: rgba(255, 244, 218, 0.94); + background: rgba(16, 20, 24, 0.97); + border: 1px solid rgba(214, 158, 46, 0.5); + border-radius: var(--radius); + box-shadow: 0 10px 26px rgba(0, 0, 0, 0.55); + opacity: 0; + visibility: hidden; + pointer-events: none; + transform: translateY(-2px); + transition: opacity 140ms ease, transform 140ms ease, visibility 140ms ease; +} + +.mods-exp-chip:hover .mods-exp-popover, +.mods-exp-chip:focus-visible .mods-exp-popover { + opacity: 1; + visibility: visible; + transform: translateY(0); +} + .mods-banner { display: flex; flex-direction: column; @@ -449,12 +525,6 @@ border-radius: var(--radius); } -.mods-banner-experimental { - background: rgba(214, 158, 46, 0.14); - border-color: rgba(214, 158, 46, 0.45); - color: rgba(255, 241, 204, 0.94); -} - .mods-banner-warn { background: rgba(206, 65, 55, 0.16); border-color: rgba(206, 65, 55, 0.5); From 97707f533d2b1945cf22fafbb0abebcc1721bf69 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:51:43 +0800 Subject: [PATCH 07/12] feat(launcher): bundle example mod templates and seed fresh mods folder once --- .../src/main/services/mods/mods-service.ts | 42 ++++++++++++++++++- .../main/services/resources/resource-paths.ts | 4 ++ scripts/build-windows-installer.ts | 1 + 3 files changed, 46 insertions(+), 1 deletion(-) diff --git a/apps/launcher/src/main/services/mods/mods-service.ts b/apps/launcher/src/main/services/mods/mods-service.ts index fca9e9b..e92670b 100644 --- a/apps/launcher/src/main/services/mods/mods-service.ts +++ b/apps/launcher/src/main/services/mods/mods-service.ts @@ -1,5 +1,5 @@ import { randomUUID } from 'node:crypto'; -import { mkdir, readFile, stat, writeFile } from 'node:fs/promises'; +import { access, cp, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises'; import { isAbsolute, join } from 'node:path'; import { app, BrowserWindow, dialog, shell } from 'electron'; import { @@ -19,8 +19,10 @@ import { ModPresetTransferSchema, type ModListItem, type ModsStateView } from '@ import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts'; import { getSettings, updateSettings } from '../config/settings-store.ts'; import { listCopies } from '../install/install-record.ts'; +import { resourcePaths } from '../resources/resource-paths.ts'; const CLIENT_MODS_CONFIG_FILE = 'mods-config.json'; +const EXAMPLES_SEEDED_MARKER = '.wto-examples-seeded'; export function defaultModsFolder(): string { return join(app.getPath('userData'), 'mods'); @@ -32,9 +34,47 @@ export async function resolveModsFolder(): Promise<{ readonly modsDir: string; r const isCustomModsDir = settings.modsFolder !== null; const modsDir = settings.modsFolder ?? defaultModsDir; await mkdir(modsDir, { recursive: true }); + await seedBundledExampleModsOnce(modsDir); return { modsDir, defaultModsDir, isCustomModsDir }; } +/** + * Copy the bundled example mod templates into a fresh mods folder once so players and authors + * have ready-to-inspect templates (disabled by default). Writing a marker ensures deleting the + * examples later does not re-create them. + */ +async function seedBundledExampleModsOnce(modsDir: string): Promise { + const markerPath = join(modsDir, EXAMPLES_SEEDED_MARKER); + if (await pathExists(markerPath)) return; + try { + const existingEntries = await readdir(modsDir); + if (existingEntries.length === 0) { + const templatesRoot = resourcePaths().modTemplates; + if (await pathExists(templatesRoot)) { + const templates = await readdir(templatesRoot, { withFileTypes: true }); + for (const entry of templates) { + if (!entry.isDirectory()) continue; + const dest = join(modsDir, entry.name); + if (await pathExists(dest)) continue; + await cp(join(templatesRoot, entry.name), dest, { recursive: true }); + } + } + } + await writeFile(markerPath, '1\n', 'utf8'); + } catch (error) { + console.warn('[mods] seeding bundled example mods skipped:', error); + } +} + +async function pathExists(path: string): Promise { + try { + await access(path); + return true; + } catch { + return false; + } +} + export async function openModsFolder(): Promise { const { modsDir } = await resolveModsFolder(); const failure = await shell.openPath(modsDir); diff --git a/apps/launcher/src/main/services/resources/resource-paths.ts b/apps/launcher/src/main/services/resources/resource-paths.ts index ca43202..68ec76c 100644 --- a/apps/launcher/src/main/services/resources/resource-paths.ts +++ b/apps/launcher/src/main/services/resources/resource-paths.ts @@ -17,6 +17,8 @@ export interface ResourcePaths { readonly networkHookLibrary: string; /** Multi-resolution Windows icon for the window and system tray. */ readonly appIcon: string; + /** Bundled example mod templates seeded into an empty mods folder on first use. */ + readonly modTemplates: string; } export function resourcePaths(): ResourcePaths { @@ -32,6 +34,7 @@ export function bundledResourcePaths(): ResourcePaths { patches: join(process.resourcesPath, 'patches'), networkHookLibrary: join(process.resourcesPath, 'native', 'wto_ws.dll'), appIcon: join(process.resourcesPath, 'icon.ico'), + modTemplates: join(process.resourcesPath, 'mod-templates'), }; } // The app path is apps/launcher; the repository is two levels up. @@ -40,6 +43,7 @@ export function bundledResourcePaths(): ResourcePaths { patches: join(repository, 'patches'), networkHookLibrary: join(repository, 'build', 'native', 'wto_ws.dll'), appIcon: join(repository, 'apps', 'launcher', 'resources', 'icon.ico'), + modTemplates: join(repository, 'dev-docs', 'templates', 'mods'), }; } diff --git a/scripts/build-windows-installer.ts b/scripts/build-windows-installer.ts index 9bf3ff0..5219cf3 100644 --- a/scripts/build-windows-installer.ts +++ b/scripts/build-windows-installer.ts @@ -70,6 +70,7 @@ async function stageInstaller(stage: string, manifest: LauncherManifest): Promis await cp(join(launcher, 'resources', 'icon.png'), join(resources, 'icon.png')); 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 }); for (const folder of ['exe', 'gui', 'native', 'versions']) { await cp(join(repository, 'patches', folder), join(resources, 'patches', folder), { recursive: true }); } From 8636d0b71d38875e109460c5681ace902b20a7a1 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:55:20 +0800 Subject: [PATCH 08/12] fix(mods): serialize initial example seeding and refresh on window focus --- .../src/main/services/mods/mods-service.ts | 52 ++++++++++++------- .../src/renderer/src/pages/mods/ModsPage.tsx | 15 ++++-- 2 files changed, 44 insertions(+), 23 deletions(-) diff --git a/apps/launcher/src/main/services/mods/mods-service.ts b/apps/launcher/src/main/services/mods/mods-service.ts index e92670b..e374bd3 100644 --- a/apps/launcher/src/main/services/mods/mods-service.ts +++ b/apps/launcher/src/main/services/mods/mods-service.ts @@ -23,6 +23,7 @@ import { resourcePaths } from '../resources/resource-paths.ts'; const CLIENT_MODS_CONFIG_FILE = 'mods-config.json'; const EXAMPLES_SEEDED_MARKER = '.wto-examples-seeded'; +const inFlightSeeds = new Map>(); export function defaultModsFolder(): string { return join(app.getPath('userData'), 'mods'); @@ -40,30 +41,43 @@ export async function resolveModsFolder(): Promise<{ readonly modsDir: string; r /** * Copy the bundled example mod templates into a fresh mods folder once so players and authors - * have ready-to-inspect templates (disabled by default). Writing a marker ensures deleting the - * examples later does not re-create them. + * have ready-to-inspect templates (disabled by default). Serialized per directory so concurrent + * startup calls (such as React StrictMode double mounts) wait for the copy to finish before + * scanning mods. */ async function seedBundledExampleModsOnce(modsDir: string): Promise { - const markerPath = join(modsDir, EXAMPLES_SEEDED_MARKER); - if (await pathExists(markerPath)) return; - try { - const existingEntries = await readdir(modsDir); - if (existingEntries.length === 0) { - const templatesRoot = resourcePaths().modTemplates; - if (await pathExists(templatesRoot)) { - const templates = await readdir(templatesRoot, { withFileTypes: true }); - for (const entry of templates) { - if (!entry.isDirectory()) continue; - const dest = join(modsDir, entry.name); - if (await pathExists(dest)) continue; - await cp(join(templatesRoot, entry.name), dest, { recursive: true }); + const key = modsDir.toLowerCase(); + const pending = inFlightSeeds.get(key); + if (pending) { + await pending; + return; + } + const task = (async () => { + const markerPath = join(modsDir, EXAMPLES_SEEDED_MARKER); + if (await pathExists(markerPath)) return; + try { + const existingEntries = await readdir(modsDir); + if (existingEntries.length === 0) { + const templatesRoot = resourcePaths().modTemplates; + if (await pathExists(templatesRoot)) { + const templates = await readdir(templatesRoot, { withFileTypes: true }); + for (const entry of templates) { + if (!entry.isDirectory()) continue; + const dest = join(modsDir, entry.name); + if (await pathExists(dest)) continue; + await cp(join(templatesRoot, entry.name), dest, { recursive: true }); + } } } + await writeFile(markerPath, '1\n', 'utf8'); + } catch (error) { + console.warn('[mods] seeding bundled example mods skipped:', error); } - await writeFile(markerPath, '1\n', 'utf8'); - } catch (error) { - console.warn('[mods] seeding bundled example mods skipped:', error); - } + })().finally(() => { + inFlightSeeds.delete(key); + }); + inFlightSeeds.set(key, task); + await task; } async function pathExists(path: string): Promise { diff --git a/apps/launcher/src/renderer/src/pages/mods/ModsPage.tsx b/apps/launcher/src/renderer/src/pages/mods/ModsPage.tsx index 120cfc7..d0e9de0 100644 --- a/apps/launcher/src/renderer/src/pages/mods/ModsPage.tsx +++ b/apps/launcher/src/renderer/src/pages/mods/ModsPage.tsx @@ -47,10 +47,17 @@ export function ModsPage({ copy, section, readOnly, onError }: Props) { useEffect(() => { let mounted = true; - ipcInvoke('mods:getState', { copyId: copy.id }) - .then((result) => { if (mounted) setState(result); }) - .catch(onError); - return () => { mounted = false; }; + const sync = (): void => { + ipcInvoke('mods:getState', { copyId: copy.id }) + .then((result) => { if (mounted) setState(result); }) + .catch(onError); + }; + sync(); + window.addEventListener('focus', sync); + return () => { + mounted = false; + window.removeEventListener('focus', sync); + }; }, [copy.id, onError]); const runAction = (action: Promise, successNotice?: string): void => { From 5983e3f3e23a63abe9360acdbc4a148a1ab9d179 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Thu, 3 Dec 2026 02:40:38 +0800 Subject: [PATCH 09/12] feat(mods): add battle.onFilterMissions hook and per-template bundled seeding --- .../src/main/services/mods/mods-service.ts | 57 +++++++++++++------ apps/server/src/battle/battle-matchmaker.ts | 29 +++++++++- apps/server/src/mods/server-mod-runtime.ts | 28 +++++++++ apps/server/src/server.ts | 10 +++- packages/mods/src/index.ts | 2 + packages/mods/src/server-api.ts | 21 +++++++ 6 files changed, 127 insertions(+), 20 deletions(-) diff --git a/apps/launcher/src/main/services/mods/mods-service.ts b/apps/launcher/src/main/services/mods/mods-service.ts index e374bd3..46dc6af 100644 --- a/apps/launcher/src/main/services/mods/mods-service.ts +++ b/apps/launcher/src/main/services/mods/mods-service.ts @@ -40,10 +40,10 @@ export async function resolveModsFolder(): Promise<{ readonly modsDir: string; r } /** - * Copy the bundled example mod templates into a fresh mods folder once so players and authors - * have ready-to-inspect templates (disabled by default). Serialized per directory so concurrent - * startup calls (such as React StrictMode double mounts) wait for the copy to finish before - * scanning mods. + * Copy newly shipped bundled template mods into the mods folder once each (disabled by default). + * Tracks which template folder names have already been seeded in `.wto-examples-seeded` so + * deleting a bundled template never restores it, while newly added official templates still + * appear for existing users. Serialized per directory to prevent concurrent seeding races. */ async function seedBundledExampleModsOnce(modsDir: string): Promise { const key = modsDir.toLowerCase(); @@ -54,22 +54,25 @@ async function seedBundledExampleModsOnce(modsDir: string): Promise { } const task = (async () => { const markerPath = join(modsDir, EXAMPLES_SEEDED_MARKER); - if (await pathExists(markerPath)) return; try { - const existingEntries = await readdir(modsDir); - if (existingEntries.length === 0) { - const templatesRoot = resourcePaths().modTemplates; - if (await pathExists(templatesRoot)) { - const templates = await readdir(templatesRoot, { withFileTypes: true }); - for (const entry of templates) { - if (!entry.isDirectory()) continue; - const dest = join(modsDir, entry.name); - if (await pathExists(dest)) continue; - await cp(join(templatesRoot, entry.name), dest, { recursive: true }); - } + const templatesRoot = resourcePaths().modTemplates; + if (!(await pathExists(templatesRoot))) return; + const seeded = await readSeededTemplateNames(markerPath, modsDir); + const templates = await readdir(templatesRoot, { withFileTypes: true }); + let changed = false; + for (const entry of templates) { + if (!entry.isDirectory()) continue; + if (seeded.has(entry.name)) continue; + const dest = join(modsDir, entry.name); + if (!(await pathExists(dest))) { + await cp(join(templatesRoot, entry.name), dest, { recursive: true }); } + seeded.add(entry.name); + changed = true; + } + if (changed || !(await pathExists(markerPath))) { + await writeFile(markerPath, JSON.stringify({ seeded: [...seeded].sort() }, null, 2) + '\n', 'utf8'); } - await writeFile(markerPath, '1\n', 'utf8'); } catch (error) { console.warn('[mods] seeding bundled example mods skipped:', error); } @@ -80,6 +83,26 @@ async function seedBundledExampleModsOnce(modsDir: string): Promise { await task; } +async function readSeededTemplateNames(markerPath: string, modsDir: string): Promise> { + if (!(await pathExists(markerPath))) return new Set(); + try { + const raw = (await readFile(markerPath, 'utf8')).trim(); + if (raw === '1') { + // Legacy marker from initial 2-template version: mark existing folders as already seeded + // so newly added official templates (e.g. official-map-selector) are still delivered once. + const existing = await readdir(modsDir); + const set = new Set(['example-vehicle-tweak', 'example-server-script']); + for (const name of existing) set.add(name); + return set; + } + const parsed = JSON.parse(raw) as { seeded?: unknown }; + if (Array.isArray(parsed.seeded)) { + return new Set(parsed.seeded.filter((item): item is string => typeof item === 'string')); + } + } catch { /* ignore */ } + return new Set(); +} + async function pathExists(path: string): Promise { try { await access(path); diff --git a/apps/server/src/battle/battle-matchmaker.ts b/apps/server/src/battle/battle-matchmaker.ts index 20a9b01..c88353a 100644 --- a/apps/server/src/battle/battle-matchmaker.ts +++ b/apps/server/src/battle/battle-matchmaker.ts @@ -85,6 +85,16 @@ export type MatchmakeOutcome = | { readonly ok: true; readonly launch: BattleLaunchPlan } | { readonly ok: false; readonly error: string }; +export type MissionPoolFilter = (ctx: { + readonly userId: string; + readonly modeId: number; + readonly modeName: string; + readonly economicName: string; + readonly minMrank: number; + readonly maxMrank: number; + readonly missions: readonly MissionHeader[]; +}) => readonly MissionHeader[]; + export class BattleMatchmaker { readonly #gameModes: GameModes; readonly #vehicles: readonly CatalogueVehicle[]; @@ -93,6 +103,7 @@ export class BattleMatchmaker { readonly #tuning: BattleTuning; readonly #spawnRules: BattleSpawnRulesData; readonly #aircraftLoadouts: ReadonlyMap; + readonly #filterMissions: MissionPoolFilter | undefined; constructor( gameModes: GameModes, @@ -101,6 +112,7 @@ export class BattleMatchmaker { tuning: BattleTuning, spawnRules: BattleSpawnRulesData, aircraftLoadouts: ReadonlyMap, + filterMissions?: MissionPoolFilter, ) { this.#gameModes = gameModes; this.#vehicles = vehicles; @@ -109,6 +121,7 @@ export class BattleMatchmaker { this.#tuning = tuning; this.#spawnRules = spawnRules; this.#aircraftLoadouts = aircraftLoadouts; + this.#filterMissions = filterMissions; } enqueue(input: EnqueueBattleInput): MatchmakeOutcome { @@ -132,8 +145,20 @@ export class BattleMatchmaker { const minMrank = Math.max(declaration.minQueueMrank ?? 0, playerMrank - this.#tuning.brSpreadMrank); const roomCeiling = chosenMode.missionRanks?.maxMrank ?? Infinity; const maxMrank = Math.max(minMrank, playerMrank, Math.min(roomCeiling, playerMrank + this.#tuning.brSpreadMrank)); - const missions = twoSidedMissionsOf(chosenMode, maxMrank); - if (missions.length === 0) return { ok: false, error: 'NO_MISSION_FOR_BR' }; + const rawMissions = twoSidedMissionsOf(chosenMode, maxMrank); + if (rawMissions.length === 0) return { ok: false, error: 'NO_MISSION_FOR_BR' }; + const filteredMissions = this.#filterMissions + ? this.#filterMissions({ + userId: input.userId, + modeId: declaration.gameModeId, + modeName: declaration.name, + economicName: declaration.economicName, + minMrank, + maxMrank, + missions: rawMissions, + }) + : rawMissions; + const missions = filteredMissions.length > 0 ? filteredMissions : rawMissions; const mission = pickMission(missions, input.bannedMissions, input.dislikedMissions); const coalitions = selectBattleCoalitions({ vehicles: this.#vehicles, diff --git a/apps/server/src/mods/server-mod-runtime.ts b/apps/server/src/mods/server-mod-runtime.ts index 64c3ca5..c75e93c 100644 --- a/apps/server/src/mods/server-mod-runtime.ts +++ b/apps/server/src/mods/server-mod-runtime.ts @@ -11,8 +11,10 @@ import { pathToFileURL } from 'node:url'; import type { BlkBlock } from '@wto/blk'; import { MOD_API_VERSION, + type BattleFilterMissionsContext, type BattleLiveFactContext, type BattleMatchmakeContext, + type BattleMissionCandidate, type BattleSettlementContext, type DiscoveredMod, type ModCharHandler, @@ -54,6 +56,7 @@ export class ServerModRuntime { readonly #onServerClosing: ScopedHandler<() => void | Promise>[] = []; readonly #onProfileRefresh: ScopedHandler<(profile: BlkBlock, userId: string) => void>[] = []; readonly #onBeforeMatchmake: ScopedHandler<(ctx: BattleMatchmakeContext) => void>[] = []; + readonly #onFilterMissions: ScopedHandler<(ctx: BattleFilterMissionsContext) => readonly BattleMissionCandidate[] | void>[] = []; readonly #onLiveFact: ScopedHandler<(ctx: BattleLiveFactContext) => void>[] = []; readonly #onAfterSettle: ScopedHandler<(ctx: BattleSettlementContext) => void>[] = []; readonly #charHandlers = new Map>(); @@ -172,6 +175,30 @@ export class ServerModRuntime { } } + runBattleFilterMissions( + ctx: Omit & { readonly missions: readonly T[] }, + ): readonly T[] { + if (this.#onFilterMissions.length === 0) return ctx.missions; + let current: readonly T[] = ctx.missions; + for (const { modId, fn } of this.#onFilterMissions) { + try { + const next = fn({ ...ctx, missions: current }); + if (Array.isArray(next)) { + const allowed = new Set(next.map((item) => item.name)); + const filtered = current.filter((item) => allowed.has(item.name)); + if (filtered.length > 0) { + current = filtered; + } else { + this.#report(`[mod:${modId}] battle.onFilterMissions returned 0 matching candidates for ${ctx.modeName}; keeping previous pool`); + } + } + } catch (error) { + this.#report(`[mod:${modId}] battle.onFilterMissions error: ${formatError(error)}`); + } + } + return current; + } + runBattleLiveFact(ctx: BattleLiveFactContext): void { for (const { modId, fn } of this.#onLiveFact) { try { @@ -284,6 +311,7 @@ export class ServerModRuntime { }, battle: { onBeforeMatchmake: (fn) => { this.#onBeforeMatchmake.push({ modId, fn }); }, + onFilterMissions: (fn) => { this.#onFilterMissions.push({ modId, fn }); }, onLiveFact: (fn) => { this.#onLiveFact.push({ modId, fn }); }, onAfterSettle: (fn) => { this.#onAfterSettle.push({ modId, fn }); }, }, diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 9a2192c..6f90f2b 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -179,7 +179,15 @@ export async function startServer(options: ServerOptions): Promise modRuntime.runBattleFilterMissions(ctx), + ); const economy = new BattleEconomy( economyData, tuning.battleEconomy, diff --git a/packages/mods/src/index.ts b/packages/mods/src/index.ts index efd11dc..dc3905c 100644 --- a/packages/mods/src/index.ts +++ b/packages/mods/src/index.ts @@ -54,8 +54,10 @@ export { export { mergeLocalizationCsv } from './csv-patch.ts'; export { mergeTuningLayer, type TuningListOp } from './tuning-merge.ts'; export type { + BattleFilterMissionsContext, BattleLiveFactContext, BattleMatchmakeContext, + BattleMissionCandidate, BattleSettlementContext, ModCharHandler, ModCharRequest, diff --git a/packages/mods/src/server-api.ts b/packages/mods/src/server-api.ts index 91d1d99..22f6eb5 100644 --- a/packages/mods/src/server-api.ts +++ b/packages/mods/src/server-api.ts @@ -73,6 +73,25 @@ export interface BattleMatchmakeContext { readonly request: Record; } +export interface BattleMissionCandidate { + readonly name: string; + readonly path: string; + readonly level?: string; + readonly type?: string; + readonly locName?: string; + readonly postfix?: string; +} + +export interface BattleFilterMissionsContext { + readonly userId: string; + readonly modeId: number; + readonly modeName: string; + readonly economicName: string; + readonly minMrank: number; + readonly maxMrank: number; + readonly missions: readonly BattleMissionCandidate[]; +} + export interface BattleLiveFactContext { readonly userId: string; readonly roomId: string; @@ -146,6 +165,8 @@ export interface ServerModHooksApi { }; readonly battle: { onBeforeMatchmake(handler: (ctx: BattleMatchmakeContext) => void): void; + /** Filter or reorder candidate missions before matchmaking picks one; return the desired subset. */ + onFilterMissions(handler: (ctx: BattleFilterMissionsContext) => readonly BattleMissionCandidate[] | void): void; onLiveFact(handler: (ctx: BattleLiveFactContext) => void): void; onAfterSettle(handler: (ctx: BattleSettlementContext) => void): void; }; 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 10/12] 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 }); } From 6e65cec4c0eabc568106ee6cd71fa18827248655 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Thu, 3 Dec 2026 03:01:18 +0800 Subject: [PATCH 11/12] feat(mods): add official map selector mod template and move templates into mod-dev-docs --- .../main/services/resources/resource-paths.ts | 2 +- .../example-server-script/mod.jsonc | 0 .../example-server-script/server/index.ts | 0 .../example-vehicle-tweak/mod.jsonc | 0 .../server/tuning/battle.jsonc | 0 .../css/find-css.css | 1 + .../css/patch.jsonc | 20 + .../css/replace-css.css | 2 + .../script/find-buttons.nut | 4 + .../script/find-imports.nut | 3 + .../script/patch.jsonc | 25 ++ .../script/replace-buttons.nut | 31 ++ .../script/replace-imports.nut | 4 + .../tpl/find-nav-right.tpl | 7 + .../tpl/patch.jsonc | 20 + .../tpl/replace-nav-right.tpl | 16 + .../templates/official-map-selector/mod.jsonc | 19 + .../official-map-selector/server/index.ts | 420 ++++++++++++++++++ scripts/build-windows-installer.ts | 2 +- 19 files changed, 574 insertions(+), 2 deletions(-) rename {dev-docs/templates/mods => mod-dev-docs/templates}/example-server-script/mod.jsonc (100%) rename {dev-docs/templates/mods => mod-dev-docs/templates}/example-server-script/server/index.ts (100%) rename {dev-docs/templates/mods => mod-dev-docs/templates}/example-vehicle-tweak/mod.jsonc (100%) rename {dev-docs/templates/mods => mod-dev-docs/templates}/example-vehicle-tweak/server/tuning/battle.jsonc (100%) create mode 100644 mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/css/find-css.css create mode 100644 mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/css/patch.jsonc create mode 100644 mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/css/replace-css.css create mode 100644 mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/script/find-buttons.nut create mode 100644 mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/script/find-imports.nut create mode 100644 mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/script/patch.jsonc create mode 100644 mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/script/replace-buttons.nut create mode 100644 mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/script/replace-imports.nut create mode 100644 mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/tpl/find-nav-right.tpl create mode 100644 mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/tpl/patch.jsonc create mode 100644 mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/tpl/replace-nav-right.tpl create mode 100644 mod-dev-docs/templates/official-map-selector/mod.jsonc create mode 100644 mod-dev-docs/templates/official-map-selector/server/index.ts diff --git a/apps/launcher/src/main/services/resources/resource-paths.ts b/apps/launcher/src/main/services/resources/resource-paths.ts index acf0692..50dfa77 100644 --- a/apps/launcher/src/main/services/resources/resource-paths.ts +++ b/apps/launcher/src/main/services/resources/resource-paths.ts @@ -46,7 +46,7 @@ export function bundledResourcePaths(): ResourcePaths { patches: join(repository, 'patches'), networkHookLibrary: join(repository, 'build', 'native', 'wto_ws.dll'), appIcon: join(repository, 'apps', 'launcher', 'resources', 'icon.ico'), - modTemplates: join(repository, 'dev-docs', 'templates', 'mods'), + modTemplates: join(repository, 'mod-dev-docs', 'templates'), modDocs: join(repository, 'build', 'mod-dev-docs'), }; } diff --git a/dev-docs/templates/mods/example-server-script/mod.jsonc b/mod-dev-docs/templates/example-server-script/mod.jsonc similarity index 100% rename from dev-docs/templates/mods/example-server-script/mod.jsonc rename to mod-dev-docs/templates/example-server-script/mod.jsonc diff --git a/dev-docs/templates/mods/example-server-script/server/index.ts b/mod-dev-docs/templates/example-server-script/server/index.ts similarity index 100% rename from dev-docs/templates/mods/example-server-script/server/index.ts rename to mod-dev-docs/templates/example-server-script/server/index.ts diff --git a/dev-docs/templates/mods/example-vehicle-tweak/mod.jsonc b/mod-dev-docs/templates/example-vehicle-tweak/mod.jsonc similarity index 100% rename from dev-docs/templates/mods/example-vehicle-tweak/mod.jsonc rename to mod-dev-docs/templates/example-vehicle-tweak/mod.jsonc diff --git a/dev-docs/templates/mods/example-vehicle-tweak/server/tuning/battle.jsonc b/mod-dev-docs/templates/example-vehicle-tweak/server/tuning/battle.jsonc similarity index 100% rename from dev-docs/templates/mods/example-vehicle-tweak/server/tuning/battle.jsonc rename to mod-dev-docs/templates/example-vehicle-tweak/server/tuning/battle.jsonc diff --git a/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/css/find-css.css b/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/css/find-css.css new file mode 100644 index 0000000..5b59963 --- /dev/null +++ b/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/css/find-css.css @@ -0,0 +1 @@ +@import "missions\mapPreferences.css" diff --git a/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/css/patch.jsonc b/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/css/patch.jsonc new file mode 100644 index 0000000..97bbd0c --- /dev/null +++ b/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/css/patch.jsonc @@ -0,0 +1,20 @@ +// Register the Custom Map Pool Selector DaGui stylesheet in the root CSS manifest. +{ + "id": "official-map-selector/register-css", + "title": "Include wtomapselector.css in gui/css.css", + "features": [ + "Custom Map Pool Selector" + ], + "variants": [ + { + "written_for": "2.61.0.58", + "file": "gui/css.css", + "edits": [ + { + "find": "find-css.css", + "replace": "replace-css.css" + } + ] + } + ] +} diff --git a/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/css/replace-css.css b/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/css/replace-css.css new file mode 100644 index 0000000..9e8d1dd --- /dev/null +++ b/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/css/replace-css.css @@ -0,0 +1,2 @@ +@import "missions\mapPreferences.css" +@import "missions\wtomapselector.css" diff --git a/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/script/find-buttons.nut b/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/script/find-buttons.nut new file mode 100644 index 0000000..77a340a --- /dev/null +++ b/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/script/find-buttons.nut @@ -0,0 +1,4 @@ + function updateButtons() { + let wikiLinkBtn = showObjById("wiki_link", hasFeature("AllowExternalLink"), this.scene) + wikiLinkBtn.link = getCurCircuitOverride("wikiMatchmakerURL", loc("url/wiki_matchmaker")) + } diff --git a/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/script/find-imports.nut b/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/script/find-imports.nut new file mode 100644 index 0000000..582585a --- /dev/null +++ b/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/script/find-imports.nut @@ -0,0 +1,3 @@ +from "dagor.workcycle" import defer +import "%scripts/missions/mapPreferencesModal.nut" as mapPreferencesModal +import "%scripts/missions/mapPreferencesParams.nut" as mapPreferencesParams diff --git a/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/script/patch.jsonc b/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/script/patch.jsonc new file mode 100644 index 0000000..eb183da --- /dev/null +++ b/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/script/patch.jsonc @@ -0,0 +1,25 @@ +// Wire the Custom Map Pool button in GameModeSelect to open the native WtoMapSelectorModal +// for the currently selected game mode and display the target mode name on the button. +{ + "id": "official-map-selector/mode-select-button-script", + "title": "Wire Custom Map Pool button in GameModeSelect handler", + "features": [ + "Custom Map Pool Selector" + ], + "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" + } + ] + } + ] +} diff --git a/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/script/replace-buttons.nut b/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/script/replace-buttons.nut new file mode 100644 index 0000000..bf3ff9d --- /dev/null +++ b/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/script/replace-buttons.nut @@ -0,0 +1,31 @@ + function updateButtons() { + let wikiLinkBtn = showObjById("wiki_link", hasFeature("AllowExternalLink"), this.scene) + wikiLinkBtn.link = getCurCircuitOverride("wikiMatchmakerURL", loc("url/wiki_matchmaker")) + this.updateWtoMapSelectorButton() + } + + function updateWtoMapSelectorButton() { + let btnObj = this.scene.findObject("wto_map_selector_button") + if (!checkObj(btnObj)) + return + let curGm = getCurrentGameMode() + let hasMode = curGm != null + btnObj.show(hasMode) + btnObj.enable(hasMode) + if (!hasMode) + return + let modeTitle = (curGm?.getText != null) ? curGm.getText() : (curGm?.id ?? "") + btnObj.setValue(modeTitle != "" + ? loc("wto/mapSelector/btnWithMode", { mode = modeTitle }) + : loc("wto/mapSelector/btnTitle")) + btnObj.tooltip = modeTitle != "" + ? loc("wto/mapSelector/btnTooltipWithMode", { mode = modeTitle }) + : loc("wto/mapSelector/btnTooltip") + } + + function onOpenWtoMapSelector(_obj) { + let curGm = getCurrentGameMode() + if (curGm == null) + return + wtoMapSelectorModal.open({ gameMode = curGm }) + } diff --git a/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/script/replace-imports.nut b/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/script/replace-imports.nut new file mode 100644 index 0000000..5b0d85f --- /dev/null +++ b/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/script/replace-imports.nut @@ -0,0 +1,4 @@ +from "dagor.workcycle" import defer +import "%scripts/missions/mapPreferencesModal.nut" as mapPreferencesModal +import "%scripts/missions/mapPreferencesParams.nut" as mapPreferencesParams +import "%scripts/missions/wtomapselectormodal.nut" as wtoMapSelectorModal diff --git a/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/tpl/find-nav-right.tpl b/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/tpl/find-nav-right.tpl new file mode 100644 index 0000000..bd9e2b2 --- /dev/null +++ b/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/tpl/find-nav-right.tpl @@ -0,0 +1,7 @@ + Button_text { + id:t='back_button' + text:t = '#mainmenu/btnBack' + _on_click:t = 'goBack' + btnName:t='B' + ButtonImg {} + } diff --git a/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/tpl/patch.jsonc b/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/tpl/patch.jsonc new file mode 100644 index 0000000..312f88b --- /dev/null +++ b/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/tpl/patch.jsonc @@ -0,0 +1,20 @@ +// Add the Custom Map Pool button on the right side of the Mode Selection footer bar. +{ + "id": "official-map-selector/mode-select-button-tpl", + "title": "Add Custom Map Pool button to Mode Selection template", + "features": [ + "Custom Map Pool Selector" + ], + "variants": [ + { + "written_for": "2.61.0.58", + "file": "gui/gamemodeselect/gamemodeselect.tpl", + "edits": [ + { + "find": "find-nav-right.tpl", + "replace": "replace-nav-right.tpl" + } + ] + } + ] +} diff --git a/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/tpl/replace-nav-right.tpl b/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/tpl/replace-nav-right.tpl new file mode 100644 index 0000000..8a9b494 --- /dev/null +++ b/mod-dev-docs/templates/official-map-selector/client/gui-patches/mode-select-map-selector-button/tpl/replace-nav-right.tpl @@ -0,0 +1,16 @@ + Button_text { + id:t='wto_map_selector_button' + text:t='#wto/mapSelector/btnTitle' + tooltip:t='#wto/mapSelector/btnTooltip' + on_click:t='onOpenWtoMapSelector' + visualStyle:t='secondary' + ButtonImg {} + } + + Button_text { + id:t='back_button' + text:t = '#mainmenu/btnBack' + _on_click:t = 'goBack' + btnName:t='B' + ButtonImg {} + } diff --git a/mod-dev-docs/templates/official-map-selector/mod.jsonc b/mod-dev-docs/templates/official-map-selector/mod.jsonc new file mode 100644 index 0000000..c8e0228 --- /dev/null +++ b/mod-dev-docs/templates/official-map-selector/mod.jsonc @@ -0,0 +1,19 @@ +// Official bundled additive mod: Custom Map Pool Selector. +// Adds a native DaGui map pool selector modal to the Mode Selection UI and enforces per-mode +// whitelist / unlimited blacklist rules during local battle matchmaking. +{ + "format": 1, + "id": "official.map-selector", + "name": { + "zh-CN": "官方模组:自定义匹配地图池", + "en": "Official Mod: Custom Map Pool Selector" + }, + "version": "0.1.0", + "author": "WTOffline", + "description": { + "zh-CN": "在模式选择界面新增自定义地图池弹窗,支持按模式设置全部地图、白名单(仅匹配所选)或无上限黑名单(排除所选),并附带原生小地图预览。", + "en": "Adds a native Custom Map Pool modal to the Mode Selection screen with per-mode All, Whitelist (only selected), and unlimited Blacklist (exclude selected) rules plus native map thumbnails." + }, + "api_version": "0.1-experimental", + "game_versions": ["2.61.0.*"] +} diff --git a/mod-dev-docs/templates/official-map-selector/server/index.ts b/mod-dev-docs/templates/official-map-selector/server/index.ts new file mode 100644 index 0000000..808b7cf --- /dev/null +++ b/mod-dev-docs/templates/official-map-selector/server/index.ts @@ -0,0 +1,420 @@ +/** + * Official WTOffline Mod: Custom Map Pool Selector (`official.map-selector`). + * + * Indexes each offered PvP game mode's playable two-sided missions grouped by location/level id, + * exposes matching RPC endpoints (`wto_mod.map_selector.get` / `wto_mod.map_selector.set`) backed + * by per-account isolated mod storage, and enforces whitelist/blacklist rules via + * `battle.onFilterMissions`. + */ + +type FilterMode = 'all' | 'include' | 'exclude'; + +interface ModeMapRule { + filterMode: FilterMode; + selectedMaps: string[]; +} + +interface PlayerMapSelectorStore { + version: 1; + modes: Record; +} + +interface MissionSlotsView { + readonly teamA: number; + readonly teamB: number; +} + +interface MissionHeaderView { + readonly name: string; + readonly path: string; + readonly level?: string; + readonly playerSlots?: MissionSlotsView; +} + +interface GameModeDeclarationView { + readonly gameModeId: number; + readonly name: string; + readonly tag?: string; + readonly economicName: string; + readonly displayType?: string; +} + +interface OfferedGameModeView { + readonly declaration: GameModeDeclarationView; + readonly missions: readonly MissionHeaderView[]; +} + +interface GameModesCatalogueView { + ids(): number[]; + byId(id: number): OfferedGameModeView | undefined; + byName(name: string): OfferedGameModeView | undefined; + byEconomicName(economicName: string): readonly OfferedGameModeView[]; +} + +interface MapPoolItem { + readonly id: string; + readonly sampleMission: string; + readonly missionCount: number; +} + +interface ModeMapPool { + readonly modeName: string; + readonly economicName: string; + readonly maps: readonly MapPoolItem[]; + readonly mapIdSet: ReadonlySet; +} + +interface BattleMissionCandidateView { + readonly name: string; + readonly path: string; + readonly level?: string; +} + +interface BattleFilterContextView { + readonly userId: string; + readonly modeId: number; + readonly modeName: string; + readonly economicName: string; + readonly minMrank: number; + readonly maxMrank: number; + readonly missions: readonly BattleMissionCandidateView[]; +} + +interface ModMatchingRequestView { + readonly method: string; + readonly params: Readonly>; + readonly userId: string | undefined; +} + +interface ServerModContextView { + readonly logger: { + info(message: string): void; + warn(message: string): void; + error(message: string): void; + }; + readonly storage: { + forPlayer(userId: string): { + read(): T | undefined; + write(value: unknown): void; + }; + }; + readonly hooks: { + onCataloguesReady(handler: (catalogues: { readonly gameModes: unknown }) => void): void; + readonly battle: { + onFilterMissions( + handler: (ctx: BattleFilterContextView) => readonly BattleMissionCandidateView[] | void, + ): void; + }; + }; + readonly routes: { + readonly matching: { + register(method: string, handler: (request: ModMatchingRequestView) => Record): void; + }; + }; +} + +const VALID_FILTER_MODES = new Set(['all', 'include', 'exclude']); + +/** + * Normalize a mission's `level` path (e.g. `levels/avg_poland.bin`) into a lowercase location id + * (`avg_poland`). Falls back to the mission name when `level` is absent. + */ +function normalizeMapId(level: string | undefined, missionName: string): string { + const raw = typeof level === 'string' ? level.trim() : ''; + if (raw.length > 0) { + const unified = raw.replaceAll('\\', '/'); + const slashIdx = unified.lastIndexOf('/'); + const baseName = slashIdx >= 0 ? unified.slice(slashIdx + 1) : unified; + const withoutBin = baseName.toLowerCase().endsWith('.bin') + ? baseName.slice(0, -4) + : baseName; + const normalized = withoutBin.trim().toLowerCase(); + if (normalized.length > 0) return normalized; + } + return missionName.trim().toLowerCase(); +} + +function isTwoSidedMission(mission: MissionHeaderView): boolean { + if (!mission.playerSlots) return true; + return mission.playerSlots.teamA > 0 && mission.playerSlots.teamB > 0; +} + +function isGameModesCatalogue(value: unknown): value is GameModesCatalogueView { + if (typeof value !== 'object' || value === null) return false; + const candidate = value as Record; + return ( + typeof candidate.ids === 'function' && + typeof candidate.byId === 'function' && + typeof candidate.byName === 'function' && + typeof candidate.byEconomicName === 'function' + ); +} + +function sanitizeFilterMode(raw: unknown): FilterMode | undefined { + if (typeof raw !== 'string') return undefined; + const lowered = raw.trim().toLowerCase() as FilterMode; + return VALID_FILTER_MODES.has(lowered) ? lowered : undefined; +} + +function sanitizeSelectedMaps(raw: unknown): string[] { + if (!Array.isArray(raw)) return []; + const seen = new Set(); + const out: string[] = []; + for (const item of raw) { + if (typeof item !== 'string') continue; + const id = item.trim().toLowerCase(); + if (id.length === 0 || seen.has(id)) continue; + seen.add(id); + out.push(id); + } + return out; +} + +function readPlayerStore( + storage: ServerModContextView['storage'], + userId: string, +): PlayerMapSelectorStore { + const raw = storage.forPlayer(userId).read(); + if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) { + return { version: 1, modes: {} }; + } + const obj = raw as Record; + const rawModes = obj.modes; + if (typeof rawModes !== 'object' || rawModes === null || Array.isArray(rawModes)) { + return { version: 1, modes: {} }; + } + const modes: Record = {}; + for (const [modeKey, entry] of Object.entries(rawModes as Record)) { + if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) continue; + const rec = entry as Record; + const filterMode = sanitizeFilterMode(rec.filterMode) ?? 'all'; + const selectedMaps = sanitizeSelectedMaps(rec.selectedMaps); + modes[modeKey] = { filterMode, selectedMaps }; + } + return { version: 1, modes }; +} + +function buildModePools(gameModes: GameModesCatalogueView): { + readonly byModeName: Map; + readonly byEconomicName: Map; +} { + const byModeName = new Map(); + const byEconomicName = new Map(); + + // Group offered PvP modes by their primary mode name, keeping primary (untagged) modes first + // so sample missions come from the classic pool before sub-mode additions. + const groupedModes = new Map(); + for (const id of gameModes.ids()) { + const offered = gameModes.byId(id); + if (!offered) continue; + if (offered.declaration.displayType === 'pve_battle') continue; + const key = offered.declaration.name; + const bucket = groupedModes.get(key) ?? []; + bucket.push(offered); + groupedModes.set(key, bucket); + } + + for (const [modeName, modes] of groupedModes) { + modes.sort((left, right) => { + const leftTagged = left.declaration.tag ? 1 : 0; + const rightTagged = right.declaration.tag ? 1 : 0; + return leftTagged - rightTagged || left.declaration.gameModeId - right.declaration.gameModeId; + }); + + const economicName = modes[0]!.declaration.economicName; + const byMapId = new Map }>(); + + for (const offered of modes) { + for (const mission of offered.missions) { + if (!isTwoSidedMission(mission)) continue; + const mapId = normalizeMapId(mission.level, mission.name); + const existing = byMapId.get(mapId); + if (existing) { + existing.missionNames.add(mission.name); + } else { + byMapId.set(mapId, { + sampleMission: mission.name, + missionNames: new Set([mission.name]), + }); + } + } + } + + if (byMapId.size === 0) continue; + + const maps: MapPoolItem[] = [...byMapId.entries()] + .sort(([leftId], [rightId]) => leftId.localeCompare(rightId)) + .map(([id, info]) => ({ + id, + sampleMission: info.sampleMission, + missionCount: info.missionNames.size, + })); + + const pool: ModeMapPool = { + modeName, + economicName, + maps, + mapIdSet: new Set(maps.map((item) => item.id)), + }; + + byModeName.set(modeName, pool); + if (!byEconomicName.has(economicName)) { + byEconomicName.set(economicName, pool); + } + } + + return { byModeName, byEconomicName }; +} + +function readOptionalString(params: Readonly>, key: string): string { + const value = params[key]; + return typeof value === 'string' ? value.trim() : ''; +} + +export default { + setup(ctx: ServerModContextView) { + let poolsByModeName = new Map(); + let poolsByEconomicName = new Map(); + + const resolvePool = (modeName: string, economicName: string): ModeMapPool | undefined => { + if (modeName) { + const direct = poolsByModeName.get(modeName) ?? poolsByEconomicName.get(modeName); + if (direct) return direct; + } + if (economicName) { + return poolsByEconomicName.get(economicName) ?? poolsByModeName.get(economicName); + } + return undefined; + }; + + const lookupSavedRule = ( + store: PlayerMapSelectorStore, + modeName: string, + economicName: string, + ): ModeMapRule | undefined => { + if (modeName && store.modes[modeName]) return store.modes[modeName]; + if (economicName && store.modes[economicName]) return store.modes[economicName]; + return undefined; + }; + + ctx.hooks.onCataloguesReady((catalogues) => { + if (!isGameModesCatalogue(catalogues.gameModes)) { + ctx.logger.warn('gameModes catalogue did not match expected shape; map selector pools remain empty'); + return; + } + const indexed = buildModePools(catalogues.gameModes); + poolsByModeName = indexed.byModeName; + poolsByEconomicName = indexed.byEconomicName; + ctx.logger.info(`indexed map pools for ${poolsByModeName.size} game modes`); + }); + + ctx.routes.matching.register('wto_mod.map_selector.get', (request) => { + const userId = request.userId; + if (!userId) { + return { + ok: false, + error: 'AUTH_REQUIRED', + modeName: '', + filterMode: 'all', + selectedMaps: [], + maps: [], + }; + } + + const requestedMode = readOptionalString(request.params, 'modeName'); + const requestedEconomic = readOptionalString(request.params, 'economicName'); + const pool = resolvePool(requestedMode, requestedEconomic); + if (!pool) { + return { + ok: true, + modeName: requestedMode || requestedEconomic, + filterMode: 'all', + selectedMaps: [], + maps: [], + }; + } + + const store = readPlayerStore(ctx.storage, userId); + const saved = lookupSavedRule(store, pool.modeName, pool.economicName); + const filterMode: FilterMode = saved?.filterMode ?? 'all'; + const selectedMaps = saved + ? saved.selectedMaps.filter((mapId) => pool.mapIdSet.has(mapId)) + : []; + + return { + ok: true, + modeName: pool.modeName, + economicName: pool.economicName, + filterMode, + selectedMaps, + maps: pool.maps.map((item) => ({ + id: item.id, + sampleMission: item.sampleMission, + missionCount: item.missionCount, + })), + }; + }); + + ctx.routes.matching.register('wto_mod.map_selector.set', (request) => { + const userId = request.userId; + if (!userId) { + return { ok: false, error: 'AUTH_REQUIRED' }; + } + + const requestedMode = readOptionalString(request.params, 'modeName'); + const requestedEconomic = readOptionalString(request.params, 'economicName'); + const pool = resolvePool(requestedMode, requestedEconomic); + const canonicalMode = pool?.modeName ?? requestedMode; + if (!canonicalMode) { + return { ok: false, error: 'INVALID_MODE' }; + } + + const filterMode = sanitizeFilterMode(request.params.filterMode); + if (!filterMode) { + return { ok: false, error: 'INVALID_FILTER_MODE' }; + } + + const rawSelected = sanitizeSelectedMaps(request.params.selectedMaps); + const selectedMaps = pool + ? rawSelected.filter((mapId) => pool.mapIdSet.has(mapId)) + : rawSelected; + + const store = readPlayerStore(ctx.storage, userId); + store.modes[canonicalMode] = { filterMode, selectedMaps }; + ctx.storage.forPlayer(userId).write(store); + + ctx.logger.info( + `saved map rule for user=${userId} mode=${canonicalMode} filter=${filterMode} selected=${selectedMaps.length}`, + ); + return { + ok: true, + modeName: canonicalMode, + filterMode, + selectedMaps, + }; + }); + + ctx.hooks.battle.onFilterMissions((battleCtx) => { + const store = readPlayerStore(ctx.storage, battleCtx.userId); + const rule = lookupSavedRule(store, battleCtx.modeName, battleCtx.economicName); + if (!rule || rule.filterMode === 'all' || rule.selectedMaps.length === 0) { + return undefined; + } + + const selectedSet = new Set(rule.selectedMaps); + const filtered = battleCtx.missions.filter((mission) => { + const mapId = normalizeMapId(mission.level, mission.name); + return rule.filterMode === 'include' ? selectedSet.has(mapId) : !selectedSet.has(mapId); + }); + + if (filtered.length === 0) { + ctx.logger.warn( + `map filter (${rule.filterMode}, ${rule.selectedMaps.length} selected) matched 0/${battleCtx.missions.length} missions for ${battleCtx.modeName} (mrank ${battleCtx.minMrank}..${battleCtx.maxMrank}); falling back to full pool`, + ); + return undefined; + } + + return filtered; + }); + }, +}; diff --git a/scripts/build-windows-installer.ts b/scripts/build-windows-installer.ts index cafb96f..75e231a 100644 --- a/scripts/build-windows-installer.ts +++ b/scripts/build-windows-installer.ts @@ -71,7 +71,7 @@ async function stageInstaller(stage: string, manifest: LauncherManifest): Promis await cp(join(launcher, 'resources', 'icon.png'), join(resources, 'icon.png')); 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 }); + await cp(join(repository, 'mod-dev-docs', 'templates'), 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 }); From dc5e637e20960e54cb696f259095e8df4caf4496 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Thu, 3 Dec 2026 03:02:19 +0800 Subject: [PATCH 12/12] fix(mods): track additive pack overlay folders inside mod templates --- .gitignore | 3 + .../config/wpcost.blk.patch.jsonc | 12 + .../lang.vromfs.bin/lang/units.csv.patch.csv | 2 + .../gui/missions/wtomapselector.css | 104 ++++ .../gui/missions/wtomapselectorcards.tpl | 35 ++ .../gui/missions/wtomapselectormodal.tpl | 265 ++++++++++ .../scripts/missions/wtomapselectormodal.nut | 488 ++++++++++++++++++ .../lang.vromfs.bin/lang/menu.csv.patch.csv | 32 ++ 8 files changed, 941 insertions(+) create mode 100644 mod-dev-docs/templates/example-vehicle-tweak/client/packs/char.vromfs.bin/config/wpcost.blk.patch.jsonc create mode 100644 mod-dev-docs/templates/example-vehicle-tweak/client/packs/lang.vromfs.bin/lang/units.csv.patch.csv create mode 100644 mod-dev-docs/templates/official-map-selector/client/packs/gui.vromfs.bin/gui/missions/wtomapselector.css create mode 100644 mod-dev-docs/templates/official-map-selector/client/packs/gui.vromfs.bin/gui/missions/wtomapselectorcards.tpl create mode 100644 mod-dev-docs/templates/official-map-selector/client/packs/gui.vromfs.bin/gui/missions/wtomapselectormodal.tpl create mode 100644 mod-dev-docs/templates/official-map-selector/client/packs/gui.vromfs.bin/scripts/missions/wtomapselectormodal.nut create mode 100644 mod-dev-docs/templates/official-map-selector/client/packs/lang.vromfs.bin/lang/menu.csv.patch.csv diff --git a/.gitignore b/.gitignore index dbfc10f..0a0eada 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,8 @@ # Never commit game files (copyright, size). The build reads them from a game folder. *.vromfs.bin +# Allow additive patch directories named after target packs inside mod templates (never binary archives). +!mod-dev-docs/templates/**/client/packs/*.vromfs.bin/ +!mod-dev-docs/templates/**/client/packs/ui/*.vromfs.bin/ *.vromfs.bin.orig aces.exe aces*.exe diff --git a/mod-dev-docs/templates/example-vehicle-tweak/client/packs/char.vromfs.bin/config/wpcost.blk.patch.jsonc b/mod-dev-docs/templates/example-vehicle-tweak/client/packs/char.vromfs.bin/config/wpcost.blk.patch.jsonc new file mode 100644 index 0000000..15c3c49 --- /dev/null +++ b/mod-dev-docs/templates/example-vehicle-tweak/client/packs/char.vromfs.bin/config/wpcost.blk.patch.jsonc @@ -0,0 +1,12 @@ +// Incremental BLK patch applied to char.vromfs.bin config/wpcost.blk. +// Only touches the target vehicle block so other mods editing different vehicles stack cleanly. +{ + "ops": [ + { + "op": "setParam", + "path": ["us_m2a4"], + "name": "rewardMulHistorical", + "value": { "type": "real", "value": 1.2 } + } + ] +} diff --git a/mod-dev-docs/templates/example-vehicle-tweak/client/packs/lang.vromfs.bin/lang/units.csv.patch.csv b/mod-dev-docs/templates/example-vehicle-tweak/client/packs/lang.vromfs.bin/lang/units.csv.patch.csv new file mode 100644 index 0000000..94399ae --- /dev/null +++ b/mod-dev-docs/templates/example-vehicle-tweak/client/packs/lang.vromfs.bin/lang/units.csv.patch.csv @@ -0,0 +1,2 @@ +"";"";"";"" +"us_m2a4_shop";"M2A4 (Modded)";"M2A4(模组示例)";"M2A4(模組示例)" diff --git a/mod-dev-docs/templates/official-map-selector/client/packs/gui.vromfs.bin/gui/missions/wtomapselector.css b/mod-dev-docs/templates/official-map-selector/client/packs/gui.vromfs.bin/gui/missions/wtomapselector.css new file mode 100644 index 0000000..2899166 --- /dev/null +++ b/mod-dev-docs/templates/official-map-selector/client/packs/gui.vromfs.bin/gui/missions/wtomapselector.css @@ -0,0 +1,104 @@ +wtoMapCard { + behavior: button; + snd_click: click; + width: 1@mapPreferenceIconSize + 2@blockInterval; + flow: vertical; + margin: 1@mapPreferenceIconMargin, 1@blockInterval; + padding: 1@blockInterval; + background-color: #36101418; + border: yes; + border-color: #38ffffff; + css-hier-invalidate: yes; +} + +wtoMapCard:hover { + background-color: #58202c38; + border-color: @hoverMenuButtonColor; +} + +[wtoFilterMode=include] wtoMapCard[wtoSelected=yes] { + background-color: #48184222; + border-color: @checkBoxLikedCheckColor; +} + +[wtoFilterMode=exclude] wtoMapCard[wtoSelected=yes] { + background-color: #484a1818; + border-color: @checkBoxBannedCheckColor; +} + +[wtoFilterMode=all] wtoMapCard[wtoSelected=yes] { + background-color: #3a243242; + border-color: #88b8d8ff; +} + +wtoMapThumb { + size: 1@mapPreferenceIconSize, 1@mapPreferenceIconSize; + position: relative; + background-color: #cccccc; + input-transparent: yes; + css-hier-invalidate: yes; +} + +wtoMapCard:hover > wtoMapThumb, +wtoMapCard[wtoSelected=yes] > wtoMapThumb { + background-color: @white; +} + +wtoMapCheckBox { + position: absolute; + pos: pw - w - 4@dp, 4@dp; + size: 1@checkboxImgSize, 1@checkboxImgSize; + border: yes; + background-color: #c8101418; + border-color: @checkboxBorderColor; + input-transparent: yes; + css-hier-invalidate: yes; +} + +wtoMapCheckIcon { + position: relative; + pos: 0.5pw - 0.5w, 0.5ph - 0.5h; + size: 1@checkboxImgSize - 4@dp, 1@checkboxImgSize - 4@dp; + background-svg-size: 1@checkboxImgSize - 4@dp, 1@checkboxImgSize - 4@dp; + display: hide; + input-transparent: yes; +} + +[wtoFilterMode=include] wtoMapCard[wtoSelected=yes] wtoMapCheckBox { + border-color: @checkBoxLikedCheckColor; +} + +[wtoFilterMode=include] wtoMapCard[wtoSelected=yes] wtoMapCheckIcon { + display: show; + background-image: #ui/gameuiskin#check.svg; + background-color: @checkBoxLikedCheckColor; +} + +[wtoFilterMode=exclude] wtoMapCard[wtoSelected=yes] wtoMapCheckBox { + border-color: @checkBoxBannedCheckColor; +} + +[wtoFilterMode=exclude] wtoMapCard[wtoSelected=yes] wtoMapCheckIcon { + display: show; + background-image: #ui/gameuiskin#ban_icon.svg; + background-color: @checkBoxBannedCheckColor; +} + +[wtoFilterMode=all] wtoMapCard[wtoSelected=yes] wtoMapCheckIcon { + display: show; + background-image: #ui/gameuiskin#check.svg; + background-color: @commonTextColor; +} + +wtoMapCard > textareaNoTab { + width: 1@mapPreferenceIconSize; + font: @fontSmall; + color: @commonTextColor; + margin-top: 1@blockInterval; + input-transparent: yes; +} + +wtoMapCard:hover > textareaNoTab, +wtoMapCard[wtoSelected=yes] > textareaNoTab { + color: @highlightedTextColor; +} diff --git a/mod-dev-docs/templates/official-map-selector/client/packs/gui.vromfs.bin/gui/missions/wtomapselectorcards.tpl b/mod-dev-docs/templates/official-map-selector/client/packs/gui.vromfs.bin/gui/missions/wtomapselectorcards.tpl new file mode 100644 index 0000000..03fd3d2 --- /dev/null +++ b/mod-dev-docs/templates/official-map-selector/client/packs/gui.vromfs.bin/gui/missions/wtomapselectorcards.tpl @@ -0,0 +1,35 @@ +<<#cards>> +wtoMapCard { + id:t='card_<>' + wtoMapKey:t='<>' + wtoSelected:t='<<#isSelected>>yes<><<^isSelected>>no<>' + on_click:t='onToggleMapCard' + on_hover:t='onHoverMapCard' + + wtoMapThumb { + background-image:t='<>' + + wtoMapCheckBox { + wtoMapCheckIcon {} + } + + <<#variantBadge>> + textareaNoTab { + padding:t='4@sf/@pf, 0' + valign:t='bottom' + style:t='color:@white' + background-color:t='@blurBgrColor' + input-transparent:t='yes' + text:t='<>' + } + <> + } + + textareaNoTab { + id:t='card_title' + word-wrap:t='no' + pare-text:t='yes' + text:t='' + } +} +<> diff --git a/mod-dev-docs/templates/official-map-selector/client/packs/gui.vromfs.bin/gui/missions/wtomapselectormodal.tpl b/mod-dev-docs/templates/official-map-selector/client/packs/gui.vromfs.bin/gui/missions/wtomapselectormodal.tpl new file mode 100644 index 0000000..521e095 --- /dev/null +++ b/mod-dev-docs/templates/official-map-selector/client/packs/gui.vromfs.bin/gui/missions/wtomapselectormodal.tpl @@ -0,0 +1,265 @@ +root { + blur {} + blur_foreground {} + + frame { + width:t='0.92@rw' + max-width:t='1@rw' + height:t='1@maxWindowHeight' + class:t='wnd' + css-hier-invalidate:t='yes' + isCenteredUnderLogo:t='yes' + + frame_header { + activeText { + id:t='wnd_title' + caption:t='yes' + text:t='<>' + } + + textareaNoTab { + id:t='selected_counter' + position:t='relative' + pos:t='0, 0.5ph-0.5h' + margin-left:t='2@blockInterval' + text:t='' + } + + Button_close { id:t='btn_back' } + } + + tdiv { + size:t='pw, fh' + flow:t='vertical' + css-hier-invalidate:t='yes' + + tdiv { + width:t='pw' + padding:t='1@blockInterval, 1@blockInterval' + flow:t='vertical' + + tdiv { + width:t='pw' + flow:t='horizontal' + + HorizontalListBox { + id:t='filter_mode_tabs' + position:t='relative' + on_select:t='onFilterModeChange' + + shopFilter { + id:t='mode_all' + selected:t='yes' + shopFilterText { text:t='#wto/mapSelector/modeAll' } + } + shopFilter { + id:t='mode_include' + shopFilterText { text:t='#wto/mapSelector/modeInclude' } + } + shopFilter { + id:t='mode_exclude' + shopFilterText { text:t='#wto/mapSelector/modeExclude' } + } + } + } + + textareaNoTab { + id:t='filter_mode_hint' + width:t='pw' + smallFont:t='yes' + overlayTextColor:t='silver' + margin-top:t='0.5@blockInterval' + text:t='#wto/mapSelector/hintAll' + } + } + + tdiv { + width:t='pw' + padding:t='1@blockInterval, 0' + padding-bottom:t='1@blockInterval' + flow:t='horizontal' + + tdiv { + id:t='search_container' + width:t='fw' + margin-right:t='1@blockInterval' + + EditBox { + id:t='filter_edit_box' + pos:t='0, 0.5ph-0.5h' + position:t='relative' + width:t='fw' + on_activate:t='onFilterEditBoxActivate' + on_change_value:t='onFilterEditBoxChangeValue' + on_cancel_edit:t='onFilterEditBoxCancel' + text:t='' + edit-hint:t='#wto/mapSelector/searchHint' + } + + Button_text { + id:t='filter_edit_cancel_btn' + pos:t='0, 0.5ph-0.5h' + position:t='relative' + class:t='image' + showConsoleImage:t='no' + noMargin:t='yes' + tooltip:t='#mainmenu/btnReset' + on_click:t='onFilterEditBoxCancel' + display:t='hide' + + img { + background-image:t='#ui/gameuiskin#btn_close.svg' + } + } + } + + Button_text { + id:t='btn_select_all' + text:t='#wto/mapSelector/selectAllVisible' + on_click:t='onSelectAllVisible' + margin-right:t='1@blockInterval' + ButtonImg {} + } + + Button_text { + id:t='btn_clear_selection' + text:t='#wto/mapSelector/clearSelection' + on_click:t='onClearSelection' + ButtonImg {} + } + } + + rowSeparator {} + + tdiv { + size:t='pw, fh' + flow:t='horizontal' + css-hier-invalidate:t='yes' + + tdiv { + size:t='fw, ph' + position:t='relative' + + tdiv { + id:t='maps_list' + size:t='pw, ph' + flow:t='h-flow' + overflow-y:t='auto' + scrollbarShortcuts:t='yes' + position:t='relative' + css-hier-invalidate:t='yes' + wtoFilterMode:t='all' + } + + textAreaCentered { + id:t='empty_list_label' + width:t='0.8pw' + pos:t='0.5pw-0.5w, 0.5ph-0.5h' + position:t='absolute' + text:t='#wto/mapSelector/loading' + } + } + + blockSeparator {} + + tdiv { + id:t='map_preview' + width:t='1@mapPreferencePreviewSize + 2@framePadding' + height:t='ph' + padding:t='1@framePadding' + flow:t='vertical' + position:t='relative' + css-hier-invalidate:t='yes' + + tdiv { + size:t='pw, 1@mapPreferencePreviewSize' + position:t='relative' + + img { + id:t='img_preview' + size:t='pw, 1@mapPreferencePreviewSize' + max-width:t='h' + max-height:t='w' + pos:t='0.5pw-0.5w, 0' + position:t='absolute' + background-image:t='' + display:t='hide' + } + + tdiv { + id:t='tactical-map' + size:t='pw, 1@mapPreferencePreviewSize' + max-width:t='h' + max-height:t='w' + pos:t='0.5pw-0.5w, 0' + position:t='absolute' + display:t='hide' + + tacticalMap { + size:t='pw, ph' + } + } + } + + textAreaCentered { + id:t='preview_title' + width:t='pw' + margin-top:t='1@blockInterval' + class:t='active' + text:t='' + } + + textAreaCentered { + id:t='preview_variants' + width:t='pw' + smallFont:t='yes' + margin-top:t='0.5@blockInterval' + text:t='' + } + + textAreaCentered { + id:t='preview_status' + width:t='pw' + smallFont:t='yes' + overlayTextColor:t='silver' + margin-top:t='0.5@blockInterval' + text:t='#wto/mapSelector/previewHint' + } + } + } + } + + navBar { + navLeft { + textareaNoTab { + id:t='footer_summary' + pos:t='0, 0.5ph-0.5h' + position:t='relative' + smallFont:t='yes' + text:t='' + } + } + + navRight { + Button_text { + id:t='btn_cancel' + text:t='#wto/mapSelector/btnCancel' + _on_click:t='goBack' + btnName:t='B' + ButtonImg {} + } + + Button_text { + id:t='btn_save' + text:t='#wto/mapSelector/btnSave' + on_click:t='onSave' + visualStyle:t='secondary' + btnName:t='A' + ButtonImg {} + } + } + } + } + + gamercard_div {} +} diff --git a/mod-dev-docs/templates/official-map-selector/client/packs/gui.vromfs.bin/scripts/missions/wtomapselectormodal.nut b/mod-dev-docs/templates/official-map-selector/client/packs/gui.vromfs.bin/scripts/missions/wtomapselectormodal.nut new file mode 100644 index 0000000..e730f48 --- /dev/null +++ b/mod-dev-docs/templates/official-map-selector/client/packs/gui.vromfs.bin/scripts/missions/wtomapselectormodal.nut @@ -0,0 +1,488 @@ +// Official WTOffline Mod: Native DaGui Custom Map Pool Selector modal. +// Communicates with the local server's wto_mod.map_selector.get and wto_mod.map_selector.set +// matching RPC endpoints and reuses War Thunder's native map thumbnails and setMapPreview. + +import "regexp2" as regexp2 +from "%scripts/sqDagui/framework/gui_handlers.nut" import register_gui_handler +from "%scripts/baseGuiHandlerWT.nut" import BaseGuiHandlerWT +from "%scripts/sqDagui/framework/handlerType.nut" import handlerType +from "%sqStdLibs/helpers/handyman.nut" import handyman +from "%scripts/missions/mapPreview.nut" import setMapPreview, getMissionBriefingConfig +from "%scripts/missions/missionsText.nut" import getMissionLocName +from "%scripts/events/eventInfo.nut" import getEventEconomicName +from "%scripts/gameModes/gameModeManagerState.nut" import getCurrentGameMode, getGameModeEvent +from "%scripts/popups/popups.nut" import addPopup +from "%scripts/matching/api.nut" import matchingApiFunc +from "%sqstd/string.nut" import trim, utf8ToLower +from "guiMission" import get_meta_mission_info_by_name +from "%scripts/dagui_natives.nut" import get_level_texture, map_to_location +from "%scripts/dagui_library.nut" import * + +let { handlersManager } = require("%scripts/baseGuiHandlerManagerWT.nut") + +dagui_propid_add_name_id("wtoSelected") +dagui_propid_add_name_id("wtoFilterMode") +dagui_propid_add_name_id("wtoMapKey") + +let FILTER_MODES = ["all", "include", "exclude"] +let GROUND_OR_NAVAL_LEVEL_RE = regexp2(@"^av(n|g)") + +function resolveMapThumbnail(mapId, missionInfo) { + let levelPath = missionInfo?.level ?? "" + if (levelPath == "") + return "" + let isGroundOrNaval = GROUND_OR_NAVAL_LEVEL_RE.match(mapId) + let rawTex = get_level_texture(levelPath, isGroundOrNaval) + if (rawTex.len() > 1 && rawTex.endswith("*")) + return $"{rawTex.slice(0, -1)}_thumb*" + return rawTex +} + +function resolveMapTitle(mapId, sampleMission, missionInfo) { + let byDirectLoc = loc($"location/{mapId}", "") + if (byDirectLoc != "") + return byDirectLoc + + let levelPath = missionInfo?.level ?? "" + if (levelPath != "") { + let mappedLocId = map_to_location(levelPath) + if ((mappedLocId ?? "") != "") { + let byMappedLoc = loc($"location/{mappedLocId}", "") + if (byMappedLoc != "") + return byMappedLoc + } + } + + if (missionInfo != null) { + let byMissionLoc = getMissionLocName(missionInfo, "locName") + if ((byMissionLoc ?? "") != "") + return byMissionLoc + } + + let bySampleId = loc($"missions/{sampleMission}", "") + if (bySampleId != "") + return bySampleId + + return mapId +} + +let WtoMapSelectorModal = class (BaseGuiHandlerWT) { + wndType = handlerType.MODAL + sceneTplName = "%gui/missions/wtomapselectormodal.tpl" + + gameMode = null + modeName = "" + economicName = "" + modeDisplayName = "" + + filterMode = "all" + mapsList = null + mapByKey = null + selectedSet = null + focusedMapKey = "" + isLoading = true + isSaving = false + + function getSceneTplView() { + let gm = this.gameMode ?? getCurrentGameMode() + this.gameMode = gm + let event = getGameModeEvent(gm) + this.modeName = event?.name ?? gm?.id ?? "" + this.economicName = event != null ? getEventEconomicName(event) : "" + this.modeDisplayName = (gm?.getText != null) ? gm.getText() : this.modeName + let title = this.modeDisplayName != "" + ? loc("wto/mapSelector/titleWithMode", { mode = this.modeDisplayName }) + : loc("wto/mapSelector/title") + return { + wndTitle = title + } + } + + function initScreen() { + this.mapsList = [] + this.mapByKey = {} + this.selectedSet = {} + this.focusedMapKey = "" + this.isLoading = true + this.isSaving = false + + this.updateActionButtonsState() + this.updateFilterModeUi() + this.updateCounterText() + this.requestMapPool() + } + + function requestMapPool() { + if (this.modeName == "" && this.economicName == "") { + this.isLoading = false + this.showEmptyLabel(loc("wto/mapSelector/emptyMode")) + this.updateActionButtonsState() + return + } + + this.showEmptyLabel(loc("wto/mapSelector/loading")) + matchingApiFunc("wto_mod.map_selector.get", + Callback(@(resp) this.onMapPoolLoaded(resp), this), + { + modeName = this.modeName + economicName = this.economicName + }) + } + + function onMapPoolLoaded(resp) { + if (!this.isValid()) + return + + this.isLoading = false + if ((resp?.error ?? 0) != 0 || !(resp?.ok ?? false)) { + this.showEmptyLabel(loc("wto/mapSelector/loadFailed")) + this.updateActionButtonsState() + return + } + + let resolvedMode = resp?.modeName ?? "" + if (resolvedMode != "") + this.modeName = resolvedMode + + let serverFilter = resp?.filterMode ?? "all" + this.filterMode = FILTER_MODES.indexof(serverFilter) != null ? serverFilter : "all" + + this.selectedSet = {} + foreach (mapId in (resp?.selectedMaps ?? [])) + this.selectedSet[mapId] <- true + + this.mapsList = [] + this.mapByKey = {} + foreach (entry in (resp?.maps ?? [])) { + let mapId = entry?.id ?? "" + if (mapId == "") + continue + let sampleMission = entry?.sampleMission ?? "" + let missionCount = entry?.missionCount ?? 1 + let missionInfo = sampleMission != "" ? get_meta_mission_info_by_name(sampleMission) : null + let title = resolveMapTitle(mapId, sampleMission, missionInfo) + let image = resolveMapThumbnail(mapId, missionInfo) + let item = { + idx = 0 + mapId = mapId + sampleMission = sampleMission + missionCount = missionCount + title = title + searchKey = utf8ToLower(title) + image = image + variantBadge = missionCount > 1 ? $"{missionCount}x" : "" + isSelected = mapId in this.selectedSet + } + this.mapsList.append(item) + this.mapByKey[mapId] <- item + } + + this.mapsList.sort(@(a, b) a.searchKey <=> b.searchKey || a.mapId <=> b.mapId) + foreach (idx, item in this.mapsList) + item.idx = idx + + this.syncFilterTabsToState() + this.renderMapCards() + this.updateFilterModeUi() + this.updateCounterText() + this.updateActionButtonsState() + + if (this.mapsList.len() > 0) + this.focusMapPreview(this.mapsList[0].mapId) + else + this.showEmptyLabel(loc("wto/mapSelector/emptyMode")) + } + + function renderMapCards() { + let listObj = this.scene.findObject("maps_list") + if (!checkObj(listObj)) + return + + let markup = handyman.renderCached("%gui/missions/wtomapselectorcards.tpl", { cards = this.mapsList }) + this.guiScene.replaceContentFromText(listObj, markup, markup.len(), this) + + foreach (item in this.mapsList) { + let cardObj = listObj.findObject($"card_{item.idx}") + if (checkObj(cardObj)) { + cardObj.findObject("card_title")?.setValue(item.title) + cardObj.tooltip = item.title + } + } + + this.applySearchFilter() + } + + function showEmptyLabel(text) { + let labelObj = this.scene.findObject("empty_list_label") + if (!checkObj(labelObj)) + return + labelObj.setValue(text) + labelObj.show(text != "") + } + + function syncFilterTabsToState() { + let tabsObj = this.scene.findObject("filter_mode_tabs") + if (!checkObj(tabsObj)) + return + let idx = FILTER_MODES.indexof(this.filterMode) ?? 0 + if (tabsObj.getValue() != idx) + tabsObj.setValue(idx) + } + + function onFilterModeChange(obj) { + if (!checkObj(obj)) + return + let idx = obj.getValue() + if (idx < 0 || idx >= FILTER_MODES.len()) + return + this.filterMode = FILTER_MODES[idx] + this.updateFilterModeUi() + this.updateCounterText() + this.updatePreviewStatusText() + } + + function updateFilterModeUi() { + let listObj = this.scene.findObject("maps_list") + if (checkObj(listObj)) + listObj.wtoFilterMode = this.filterMode + + let hintKey = this.filterMode == "include" ? "wto/mapSelector/hintInclude" + : this.filterMode == "exclude" ? "wto/mapSelector/hintExclude" + : "wto/mapSelector/hintAll" + this.scene.findObject("filter_mode_hint")?.setValue(loc(hintKey)) + } + + function updateCounterText() { + let selectedCount = this.selectedSet.len() + let totalCount = this.mapsList.len() + let text = loc("wto/mapSelector/counter", { + selected = selectedCount + total = totalCount + }) + this.scene.findObject("selected_counter")?.setValue(text) + this.scene.findObject("footer_summary")?.setValue(text) + } + + function updateActionButtonsState() { + let hasMaps = !this.isLoading && this.mapsList.len() > 0 + let canSave = hasMaps && !this.isSaving + this.scene.findObject("btn_select_all")?.enable(hasMaps) + this.scene.findObject("btn_clear_selection")?.enable(hasMaps) + this.scene.findObject("btn_save")?.enable(canSave) + } + + function onToggleMapCard(obj) { + let mapId = obj?.wtoMapKey ?? "" + if (mapId == "" || !(mapId in this.mapByKey)) + return + + let isNowSelected = !(mapId in this.selectedSet) + if (isNowSelected) + this.selectedSet[mapId] <- true + else + this.selectedSet.$rawdelete(mapId) + + let item = this.mapByKey[mapId] + item.isSelected = isNowSelected + obj.wtoSelected = isNowSelected ? "yes" : "no" + + // Selecting a map while in "all" mode smoothly switches to Whitelist if user hasn't picked one yet? + // Keep the chosen mode explicit so users never lose track of which filter tab is active. + this.updateCounterText() + this.focusMapPreview(mapId) + } + + function onHoverMapCard(obj) { + let mapId = obj?.wtoMapKey ?? "" + if (mapId != "" && mapId != this.focusedMapKey && (mapId in this.mapByKey)) + this.focusMapPreview(mapId) + } + + function focusMapPreview(mapId) { + let item = this.mapByKey?[mapId] + if (item == null) + return + + this.focusedMapKey = mapId + let previewObj = this.scene.findObject("map_preview") + if (!checkObj(previewObj)) + return + + previewObj.findObject("preview_title")?.setValue(item.title) + previewObj.findObject("preview_variants")?.setValue( + loc("wto/mapSelector/variantsCount", { count = item.missionCount })) + this.updatePreviewStatusText() + + let curMission = item.sampleMission != "" + ? get_meta_mission_info_by_name(item.sampleMission) + : null + let tacticalObj = previewObj.findObject("tactical-map") + let imgObj = previewObj.findObject("img_preview") + + if (curMission != null && checkObj(tacticalObj)) { + let config = getMissionBriefingConfig({ blk = curMission }) + setMapPreview(tacticalObj, config) + tacticalObj.show(true) + imgObj?.show(false) + } + else if (checkObj(imgObj)) { + imgObj["background-image"] = item.image + imgObj.show(item.image != "") + tacticalObj?.show(false) + } + } + + function updatePreviewStatusText() { + let statusObj = this.scene.findObject("preview_status") + if (!checkObj(statusObj)) + return + + if (this.focusedMapKey == "" || !(this.focusedMapKey in this.mapByKey)) { + statusObj.setValue(loc("wto/mapSelector/previewHint")) + return + } + + let isSelected = this.focusedMapKey in this.selectedSet + let key = !isSelected || this.filterMode == "all" + ? "wto/mapSelector/statusNormal" + : this.filterMode == "include" + ? "wto/mapSelector/statusIncluded" + : "wto/mapSelector/statusExcluded" + statusObj.setValue(loc(key)) + } + + function getSearchQuery() { + let editObj = this.scene.findObject("filter_edit_box") + return checkObj(editObj) ? utf8ToLower(trim(editObj.getValue())) : "" + } + + function applySearchFilter() { + let listObj = this.scene.findObject("maps_list") + if (!checkObj(listObj)) + return + + let query = this.getSearchQuery() + local visibleCount = 0 + foreach (item in this.mapsList) { + let isVisible = query == "" || item.searchKey.indexof(query) != null || item.mapId.indexof(query) != null + listObj.findObject($"card_{item.idx}")?.show(isVisible) + if (isVisible) + visibleCount++ + } + + if (this.mapsList.len() == 0) + this.showEmptyLabel(loc("wto/mapSelector/emptyMode")) + else if (visibleCount == 0) + this.showEmptyLabel(loc("wto/mapSelector/noSearchResults")) + else + this.showEmptyLabel("") + } + + function onFilterEditBoxChangeValue(obj) { + let value = obj.getValue() + this.scene.findObject("filter_edit_cancel_btn")?.show(value.len() != 0) + this.applySearchFilter() + } + + function onFilterEditBoxActivate() { + this.applySearchFilter() + } + + function onFilterEditBoxCancel() { + let editObj = this.scene.findObject("filter_edit_box") + if (checkObj(editObj) && editObj.getValue() != "") { + editObj.setValue("") + this.scene.findObject("filter_edit_cancel_btn")?.show(false) + this.applySearchFilter() + } + else + this.goBack() + } + + function onSelectAllVisible(_obj) { + let listObj = this.scene.findObject("maps_list") + if (!checkObj(listObj)) + return + + let query = this.getSearchQuery() + foreach (item in this.mapsList) { + let isVisible = query == "" || item.searchKey.indexof(query) != null || item.mapId.indexof(query) != null + if (!isVisible) + continue + this.selectedSet[item.mapId] <- true + item.isSelected = true + let cardObj = listObj.findObject($"card_{item.idx}") + if (checkObj(cardObj)) + cardObj.wtoSelected = "yes" + } + this.updateCounterText() + this.updatePreviewStatusText() + } + + function onClearSelection(_obj) { + let listObj = this.scene.findObject("maps_list") + this.selectedSet.clear() + foreach (item in this.mapsList) { + item.isSelected = false + if (checkObj(listObj)) { + let cardObj = listObj.findObject($"card_{item.idx}") + if (checkObj(cardObj)) + cardObj.wtoSelected = "no" + } + } + this.updateCounterText() + this.updatePreviewStatusText() + } + + function onSave(_obj) { + if (this.isSaving || this.isLoading || this.modeName == "") + return + + this.isSaving = true + this.updateActionButtonsState() + + let selectedMaps = [] + foreach (item in this.mapsList) + if (item.mapId in this.selectedSet) + selectedMaps.append(item.mapId) + + matchingApiFunc("wto_mod.map_selector.set", + Callback(@(resp) this.onSaveComplete(resp, selectedMaps.len()), this), + { + modeName = this.modeName + economicName = this.economicName + filterMode = this.filterMode + selectedMaps = selectedMaps + }) + } + + function onSaveComplete(resp, selectedCount) { + if (!this.isValid()) + return + + this.isSaving = false + if ((resp?.error ?? 0) != 0 || !(resp?.ok ?? false)) { + this.updateActionButtonsState() + addPopup(loc("wto/mapSelector/title"), loc("wto/mapSelector/saveFailed"), null, null, null, "wto_map_selector_err") + return + } + + let modeLabel = this.modeDisplayName != "" ? this.modeDisplayName : this.modeName + let notice = this.filterMode == "include" && selectedCount > 0 + ? loc("wto/mapSelector/savedInclude", { mode = modeLabel, count = selectedCount }) + : this.filterMode == "exclude" && selectedCount > 0 + ? loc("wto/mapSelector/savedExclude", { mode = modeLabel, count = selectedCount }) + : loc("wto/mapSelector/savedAll", { mode = modeLabel }) + + addPopup(loc("wto/mapSelector/title"), notice, null, null, null, "wto_map_selector_saved") + this.goBack() + } +} + +register_gui_handler("WtoMapSelectorModal", WtoMapSelectorModal) + +return freeze({ + open = function(params = null) { + handlersManager.loadHandler(WtoMapSelectorModal, params ?? {}) + } +}) diff --git a/mod-dev-docs/templates/official-map-selector/client/packs/lang.vromfs.bin/lang/menu.csv.patch.csv b/mod-dev-docs/templates/official-map-selector/client/packs/lang.vromfs.bin/lang/menu.csv.patch.csv new file mode 100644 index 0000000..736a4fe --- /dev/null +++ b/mod-dev-docs/templates/official-map-selector/client/packs/lang.vromfs.bin/lang/menu.csv.patch.csv @@ -0,0 +1,32 @@ +"";"";"";"";"" +"wto/mapSelector/btnTitle";"Map Pool";"自定义地图池";"自訂地圖池";"自定义地图池" +"wto/mapSelector/btnWithMode";"Map Pool: {mode}";"地图池:{mode}";"地圖池:{mode}";"地图池:{mode}" +"wto/mapSelector/btnTooltip";"Configure custom map pool (whitelist / blacklist) for the current game mode";"为当前游戏模式配置自定义匹配地图池(白名单 / 黑名单)";"為目前遊戲模式設定自訂配對地圖池(白名單 / 黑名單)";"为当前游戏模式配置自定义匹配地图池(白名单 / 黑名单)" +"wto/mapSelector/btnTooltipWithMode";"Configure custom map pool for {mode}";"为「{mode}」配置自定义匹配地图池(白名单 / 无上限黑名单)";"為「{mode}」設定自訂配對地圖池(白名單 / 無上限黑名單)";"为「{mode}」配置自定义匹配地图池(白名单 / 无上限黑名单)" +"wto/mapSelector/title";"Custom Map Pool";"自定义匹配地图池";"自訂配對地圖池";"自定义匹配地图池" +"wto/mapSelector/titleWithMode";"Custom Map Pool - {mode}";"自定义匹配地图池 - {mode}";"自訂配對地圖池 - {mode}";"自定义匹配地图池 - {mode}" +"wto/mapSelector/counter";"Selected: {selected} / {total}";"已选:{selected} / {total}";"已選:{selected} / {total}";"已选:{selected} / {total}" +"wto/mapSelector/modeAll";"All Maps";"全部地图";"全部地圖";"全部地图" +"wto/mapSelector/modeInclude";"Whitelist (Only Selected)";"白名单(仅匹配所选)";"白名單(僅配對所選)";"白名单(仅匹配所选)" +"wto/mapSelector/modeExclude";"Blacklist (Exclude Selected)";"黑名单(排除所选)";"黑名單(排除所選)";"黑名单(排除所选)" +"wto/mapSelector/hintAll";"No restriction. Matchmaker can pick any map in this mode.";"无限制:匹配将从当前模式的全部地图中随机抽取。";"無限制:配對將從目前模式的全部地圖中隨機抽取。";"无限制:匹配将从当前模式的全部地图中随机抽取。" +"wto/mapSelector/hintInclude";"Whitelist active: matchmaker only picks from checked maps. If none are checked, all maps are used.";"白名单生效:仅会匹配下方勾选的地图;若未勾选任何地图则回退为全部地图。";"白名單生效:僅會配對下方勾選的地圖;若未勾選任何地圖則回退為全部地圖。";"白名单生效:仅会匹配下方勾选的地图;若未勾选任何地图则回退为全部地图。" +"wto/mapSelector/hintExclude";"Blacklist active: checked maps are never matched (unlimited count, no premium required).";"黑名单生效:已勾选的地图不会被匹配到(无数量限制,无需高级账号)。";"黑名單生效:已勾選的地圖不會被配對到(無數量限制,無需高級帳號)。";"黑名单生效:已勾选的地图不会被匹配到(无数量限制,无需高级账号)。" +"wto/mapSelector/searchHint";"Search maps...";"搜索地图名称...";"搜尋地圖名稱...";"搜索地图名称..." +"wto/mapSelector/selectAllVisible";"Select All Visible";"全选可见";"全選可見";"全选可见" +"wto/mapSelector/clearSelection";"Clear Selection";"清空选择";"清空選擇";"清空选择" +"wto/mapSelector/loading";"Loading map pool...";"正在加载地图列表...";"正在載入地圖清單...";"正在加载地图列表..." +"wto/mapSelector/emptyMode";"This mode does not have a configurable PvP map pool.";"当前模式没有可配置的 PvP 地图池。";"目前模式沒有可設定的 PvP 地圖池。";"当前模式没有可配置的 PvP 地图池。" +"wto/mapSelector/noSearchResults";"No maps match the current search filter.";"没有符合搜索条件的地图。";"沒有符合搜尋條件的地圖。";"没有符合搜索条件的地图。" +"wto/mapSelector/loadFailed";"Failed to load map pool from local server.";"无法从本地服务器加载地图池。";"無法從本機伺服器載入地圖池。";"无法从本地服务器加载地图池。" +"wto/mapSelector/saveFailed";"Failed to save map pool settings.";"保存地图池设置失败。";"儲存地圖池設定失敗。";"保存地图池设置失败。" +"wto/mapSelector/savedAll";"Map pool reset to all maps for {mode}.";"已将「{mode}」恢复为匹配全部地图。";"已將「{mode}」恢復為配對全部地圖。";"已将「{mode}」恢复为匹配全部地图。" +"wto/mapSelector/savedInclude";"Saved whitelist ({count} maps) for {mode}.";"已为「{mode}」保存白名单(共 {count} 张地图)。";"已為「{mode}」儲存白名單(共 {count} 張地圖)。";"已为「{mode}」保存白名单(共 {count} 张地图)。" +"wto/mapSelector/savedExclude";"Saved blacklist ({count} maps) for {mode}.";"已为「{mode}」保存黑名单(排除 {count} 张地图)。";"已為「{mode}」儲存黑名單(排除 {count} 張地圖)。";"已为「{mode}」保存黑名单(排除 {count} 张地图)。" +"wto/mapSelector/variantsCount";"Mission variants: {count}";"包含任务变体:{count} 个";"包含任務變體:{count} 個";"包含任务变体:{count} 个" +"wto/mapSelector/previewHint";"Hover or click a map card to preview its tactical map.";"悬停或点击地图卡片以预览战术地图。";"懸停或點擊地圖卡片以預覽戰術地圖。";"悬停或点击地图卡片以预览战术地图。" +"wto/mapSelector/statusIncluded";"Status: Included in whitelist";"状态:已加入白名单";"狀態:已加入白名單";"状态:已加入白名单" +"wto/mapSelector/statusExcluded";"Status: Excluded by blacklist";"状态:已加入黑名单";"狀態:已加入黑名單";"状态:已加入黑名单" +"wto/mapSelector/statusNormal";"Status: Default";"状态:默认";"狀態:預設";"状态:默认" +"wto/mapSelector/btnSave";"Save";"保存";"儲存";"保存" +"wto/mapSelector/btnCancel";"Cancel";"取消";"取消";"取消"