merge: bring main into feat/tank-ai-nav

Takes main's mounted gun traverse limits, capture and hit feedback,
LocalMP air AI sync, mod tech tree insertions and launcher changes.

Conflicts resolved:
- wto_ai_runtime.das: fire update runs before navigation, as on main,
  so a hull-aim request is driven in the same frame; navigation keeps
  the navmesh state and slot arguments of this branch.
- wto_ai_nav_common.das: main's wto_try_hull_aim replaces the old
  limited-traverse pivot and uses this branch's drive command helper
  and stuck-watch reset.
- build.ps1 and local_mp_internal.h: keep both sides' sources and
  declarations.
This commit is contained in:
N0VAN0M4LY committed 2026-12-05 22:14:34 +08:00
commit 77e4806ffc
114 files changed
+4330 -623

No files matched your search

+3 -1
View File
@@ -109,7 +109,8 @@ export function inspectModContent(rootDir: string, manifest: ModManifest): ModCo
: undefined;
const badges = computeRiskBadges({
hasData: serverTuningFiles.length > 0 || packOperations.length > 0 || hasClientAddon || clientFiles.length > 0 || configBlkPatch !== undefined,
hasData: serverTuningFiles.length > 0 || packOperations.length > 0 || hasClientAddon || clientFiles.length > 0
|| configBlkPatch !== undefined || !!manifest.techTreeInsertions?.length,
hasGui: guiPatchDirs.length > 0,
hasScript: serverEntry !== undefined,
hasExe: exePatchDirs.length > 0,
@@ -270,6 +271,7 @@ export function touchedClientPacks(mods: readonly DiscoveredMod[]): ModdableClie
const set = new Set<ModdableClientPack>();
for (const mod of mods) {
for (const op of mod.content.packOperations) set.add(op.pack);
if (mod.manifest.techTreeInsertions?.length) set.add('char.vromfs.bin');
if (mod.content.guiPatchDirs.length > 0) set.add('gui.vromfs.bin');
if (mod.content.hasClientAddon) set.add('aces.vromfs.bin');
}
+1
View File
@@ -22,6 +22,7 @@ export {
type ModPreset,
type ModRiskBadge,
type ModServerConfig,
type ModTechTreeInsertion,
type ModdableClientPack,
type PackFileAction,
type ResolvedModLoadOrder,
+25 -1
View File
@@ -4,7 +4,7 @@
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';
import { MOD_FORMAT_VERSION, type LocalizedText, type ModManifest, type ModServerConfig, type ModTechTreeInsertion } from './types.ts';
export const MOD_MANIFEST_FILE = 'mod.jsonc';
@@ -22,9 +22,11 @@ const ALLOWED_ROOT_KEYS = new Set([
'conflicts',
'load_after',
'load_before',
'tech_tree_insertions',
'server',
]);
const ALLOWED_SERVER_KEYS = new Set(['entry', 'tuning']);
const TECH_TREE_INSERTION_KEYS = new Set(['vehicle', 'after', 'before']);
export class ModManifestError extends Error {
override name = 'ModManifestError';
@@ -62,6 +64,7 @@ export function parseModManifest(raw: unknown, where = MOD_MANIFEST_FILE): ModMa
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 techTreeInsertions = parseTechTreeInsertions(obj.tech_tree_insertions, `${where} "tech_tree_insertions"`);
const server = obj.server === undefined ? undefined : parseServerConfig(obj.server, `${where} "server"`);
return {
@@ -77,10 +80,31 @@ export function parseModManifest(raw: unknown, where = MOD_MANIFEST_FILE): ModMa
conflicts,
loadAfter,
loadBefore,
...(techTreeInsertions.length > 0 ? { techTreeInsertions } : {}),
...(server !== undefined ? { server } : {}),
};
}
function parseTechTreeInsertions(raw: unknown, where: string): ModTechTreeInsertion[] {
if (raw === undefined) return [];
if (!Array.isArray(raw)) throw new ModManifestError(`${where}: expected an array`);
const seen = new Set<string>();
return raw.map((item, index) => {
const location = `${where}[${index}]`;
const value = expectObject(item, location);
rejectUnknownKeys(value, TECH_TREE_INSERTION_KEYS, location);
const vehicle = expectString(value.vehicle, `${location}.vehicle`);
const after = expectString(value.after, `${location}.after`);
const before = expectString(value.before, `${location}.before`);
if (new Set([vehicle, after, before]).size !== 3) {
throw new ModManifestError(`${location}: vehicle, after, and before must be different vehicles`);
}
if (seen.has(vehicle)) throw new ModManifestError(`${location}: duplicate insertion for "${vehicle}"`);
seen.add(vehicle);
return { vehicle, after, before };
});
}
function parseServerConfig(raw: unknown, where: string): ModServerConfig {
const obj = expectObject(raw, where);
rejectUnknownKeys(obj, ALLOWED_SERVER_KEYS, where);
+7
View File
@@ -33,6 +33,12 @@ export interface ModServerConfig {
readonly tuning?: string;
}
export interface ModTechTreeInsertion {
readonly vehicle: string;
readonly after: string;
readonly before: string;
}
export interface ModManifest {
readonly format: 1;
readonly id: string;
@@ -46,6 +52,7 @@ export interface ModManifest {
readonly conflicts: readonly string[];
readonly loadAfter: readonly string[];
readonly loadBefore: readonly string[];
readonly techTreeInsertions?: readonly ModTechTreeInsertion[];
readonly server?: ModServerConfig;
}
+6
View File
@@ -61,6 +61,10 @@ export interface GameCopyInputs {
readonly placeholderDecals: boolean;
/** Real dldata/downloadable_decals.blk and downloadable_skins.blk extracted from the player's cache. */
readonly decalIndexFiles?: readonly AddedFile[];
/** Optional player decal cache folder used to filter cached .ddsx textures when embedding indexes. */
readonly decalCache?: string;
/** Optional pre-scanned set of cached .ddsx relative paths ("<first2>/<rest>.ddsx", lowercased). */
readonly cachedDdsx?: ReadonlySet<string>;
/** 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. */
@@ -194,6 +198,8 @@ function buildCorePacks(
const { pack: coreCharPack, ...charReport } = rebuildCharPack(inputs.stock.charPack, endpoint, {
placeholderDecals: inputs.placeholderDecals,
...(inputs.decalIndexFiles ? { decalIndexFiles: inputs.decalIndexFiles } : {}),
...(inputs.decalCache ? { decalCache: inputs.decalCache } : {}),
...(inputs.cachedDdsx ? { cachedDdsx: inputs.cachedDdsx } : {}),
localRegistration,
});
const charOverlay = applyModPackOverlays(coreCharPack, 'char.vromfs.bin', enabledMods);
+87 -9
View File
@@ -4,7 +4,19 @@
* tech tree (config/shop.blk), and, unless the player gave a decal source, placeholder decal
* and skin indexes (decals/offline-decal-index.ts).
*/
import { DECALS_CONFIG_PATH, offlineDecalIndex } from './decals/offline-decal-index.ts';
import { decodeBlk, emptyBlock, encodeBlk } from '@wto/blk';
import {
DECALS_CONFIG_PATH,
DECALS_INDEX_PATH,
mergePlayerDecalIndex,
offlineDecalIndex,
SKINS_INDEX_PATH,
} from './decals/offline-decal-index.ts';
import {
filterPlayerDecalIndexFiles,
readPlayerDecalIndexFiles,
scanCachedDdsxFiles,
} from './decals/player-decal-cache.ts';
import { enableFeaturesForEveryone, GAME_SETTINGS_PATH, OFFLINE_FEATURES } from './features/offline-features.ts';
import type { LocalEndpoint } from './network/local-endpoint.ts';
import { redirectNetworkConfig, type NetworkRedirectReport } from './network/redirect-network-config.ts';
@@ -20,8 +32,12 @@ export interface CharPackResult {
readonly features: readonly string[];
/** Vehicles that were hidden from players who had not researched or bought them. */
readonly revealedVehicles: number;
/** Decals in the placeholder index; undefined when the player's own decal cache is used. */
/** Decals using placeholder textures; undefined when a legacy web cache supplies its own index. */
readonly placeholderDecals: number | undefined;
/** Decals resolved from locally cached .ddsx textures; undefined unless a player index is merged. */
readonly cachedDecals?: number;
/** Downloadable skins resolved from locally cached .ddsx textures; undefined unless a player index is merged. */
readonly cachedSkins?: number;
}
export interface CharPackOptions {
@@ -29,22 +45,84 @@ export interface CharPackOptions {
readonly placeholderDecals: boolean;
/** Real dldata/downloadable_decals.blk and downloadable_skins.blk extracted from the player's cache. */
readonly decalIndexFiles?: readonly AddedFile[];
/** Optional player decal cache folder (cache/content, cache, or imported snapshot) used to filter cached .ddsx files. */
readonly decalCache?: string;
/** Optional pre-scanned set of cached .ddsx relative paths ("<first2>/<rest>.ddsx", lowercased). */
readonly cachedDdsx?: ReadonlySet<string>;
readonly localRegistration: boolean;
}
interface DecalOverlay {
readonly files: readonly AddedFile[];
readonly placeholderDecals: number | undefined;
readonly cachedDecals?: number;
readonly cachedSkins?: number;
}
export function rebuildCharPack(stockPack: Uint8Array, endpoint: LocalEndpoint, options: CharPackOptions): CharPackResult {
let network: NetworkRedirectReport | undefined;
let features: string[] = [];
let revealedVehicles = 0;
const usePlayerIndex = (options.decalIndexFiles?.length ?? 0) > 0;
const decals = !usePlayerIndex && options.placeholderDecals
? offlineDecalIndex(readPackBlk(stockPack, DECALS_CONFIG_PATH))
: undefined;
const addedFiles = usePlayerIndex ? options.decalIndexFiles! : (decals?.files ?? []);
const decals = resolveDecalOverlay(stockPack, options);
const pack = editPackBlks(stockPack, [
{ path: NETWORK_CONFIG_PATH, edit: (root) => { network = redirectNetworkConfig(root, endpoint, options.localRegistration); } },
{ path: GAME_SETTINGS_PATH, edit: (root) => { features = enableFeaturesForEveryone(root, OFFLINE_FEATURES); } },
{ path: SHOP_PATH, edit: (root) => { revealedVehicles = revealHiddenVehicles(root); } },
], addedFiles);
return { pack, network: network!, features, revealedVehicles, placeholderDecals: decals?.decals };
], decals.files);
return {
pack,
network: network!,
features,
revealedVehicles,
placeholderDecals: decals.placeholderDecals,
...(decals.cachedDecals !== undefined ? { cachedDecals: decals.cachedDecals } : {}),
...(decals.cachedSkins !== undefined ? { cachedSkins: decals.cachedSkins } : {}),
};
}
function resolveDecalOverlay(stockPack: Uint8Array, options: CharPackOptions): DecalOverlay {
const playerIndexFiles = resolvePlayerIndexFiles(options);
if (playerIndexFiles !== undefined && playerIndexFiles.length > 0) {
const decalsConfig = readPackBlk(stockPack, DECALS_CONFIG_PATH);
const decalsFile = playerIndexFiles.find((file) => file.path === DECALS_INDEX_PATH);
const skinsFile = playerIndexFiles.find((file) => file.path === SKINS_INDEX_PATH);
const otherFiles = playerIndexFiles.filter((file) => file.path !== DECALS_INDEX_PATH && file.path !== SKINS_INDEX_PATH);
const merged = mergePlayerDecalIndex(
decalsConfig,
decalsFile ? decodeBlk(decalsFile.content) : emptyBlock(),
);
const skinsContent = skinsFile ? skinsFile.content : encodeBlk(emptyBlock());
const cachedSkins = skinsFile ? decodeBlk(skinsFile.content).blocks.length : 0;
return {
files: [
{ path: SKINS_INDEX_PATH, content: skinsContent },
{ path: DECALS_INDEX_PATH, content: merged.content },
...otherFiles,
],
placeholderDecals: merged.placeholderDecals,
cachedDecals: merged.cachedDecals,
cachedSkins,
};
}
if (options.placeholderDecals) {
const offline = offlineDecalIndex(readPackBlk(stockPack, DECALS_CONFIG_PATH));
return { files: offline.files, placeholderDecals: offline.decals };
}
return { files: [], placeholderDecals: undefined };
}
function resolvePlayerIndexFiles(options: CharPackOptions): readonly AddedFile[] | undefined {
if (options.decalIndexFiles !== undefined) {
if (options.cachedDdsx !== undefined) {
return filterPlayerDecalIndexFiles(options.decalIndexFiles, options.cachedDdsx);
}
if (options.decalCache !== undefined) {
return filterPlayerDecalIndexFiles(options.decalIndexFiles, scanCachedDdsxFiles(options.decalCache));
}
return options.decalIndexFiles;
}
if (options.decalCache !== undefined) {
return readPlayerDecalIndexFiles(options.decalCache);
}
return undefined;
}
@@ -58,17 +58,35 @@ export interface OfflineDecalIndex {
readonly decals: number;
}
export interface MergedDecalIndex {
readonly index: BlkBlock;
readonly content: Uint8Array;
/** Total decals backed by locally cached .ddsx textures (stock + extra). */
readonly cachedDecals: number;
/** Stock config/decals.blk entries resolved from cached .ddsx textures. */
readonly cachedStockDecals: number;
/** Extra entries outside config/decals.blk kept because their .ddsx textures are cached. */
readonly cachedExtraDecals: number;
/** Stock config/decals.blk entries that fell back to built-in placeholder textures. */
readonly placeholderDecals: number;
}
const SQUARE_PARAMS = textureParams(SQUARE_PLACEHOLDER);
const WIDE_PARAMS = textureParams(WIDE_PLACEHOLDER);
export function placeholderDecalBlock(decal: BlkBlock): BlkBlock {
return {
name: decal.name,
params: aspectRatio(decal) >= WIDE_ASPECT_RATIO ? WIDE_PARAMS : SQUARE_PARAMS,
blocks: [],
};
}
export function offlineDecalIndex(decalsConfig: BlkBlock): OfflineDecalIndex {
const square = textureParams(SQUARE_PLACEHOLDER);
const wide = textureParams(WIDE_PLACEHOLDER);
const index: BlkBlock = {
name: '',
params: [],
blocks: decalsConfig.blocks.map((decal) => ({
name: decal.name,
params: aspectRatio(decal) >= WIDE_ASPECT_RATIO ? wide : square,
blocks: [],
})),
blocks: decalsConfig.blocks.map(placeholderDecalBlock),
};
return {
files: [
@@ -79,6 +97,64 @@ export function offlineDecalIndex(decalsConfig: BlkBlock): OfflineDecalIndex {
};
}
/**
* Merge a filtered player downloadable_decals.blk (containing only decals with locally cached
* .ddsx textures) with stock config/decals.blk:
* - Every stock decal present in cachedPlayerDecals keeps its real entry.
* - Every stock decal missing from cachedPlayerDecals falls back to a built-in placeholder
* texture (star/panther) so it never fails to load offline.
* - Extra decals outside config/decals.blk that survived cache filtering are appended.
*/
export function mergePlayerDecalIndex(
decalsConfig: BlkBlock,
cachedPlayerDecals: BlkBlock,
): MergedDecalIndex {
const cachedByName = new Map<string, BlkBlock>();
for (const block of cachedPlayerDecals.blocks) {
cachedByName.set(block.name, block);
}
const stockNames = new Set<string>();
const blocks: BlkBlock[] = [];
let cachedStockDecals = 0;
let placeholderDecals = 0;
for (const decal of decalsConfig.blocks) {
stockNames.add(decal.name);
const cached = cachedByName.get(decal.name);
if (cached !== undefined) {
blocks.push(cached);
cachedStockDecals += 1;
} else {
blocks.push(placeholderDecalBlock(decal));
placeholderDecals += 1;
}
}
const emittedExtra = new Set<string>();
let cachedExtraDecals = 0;
for (const block of cachedPlayerDecals.blocks) {
if (stockNames.has(block.name) || emittedExtra.has(block.name)) continue;
emittedExtra.add(block.name);
blocks.push(block);
cachedExtraDecals += 1;
}
const index: BlkBlock = {
name: '',
params: cachedPlayerDecals.params,
blocks,
};
return {
index,
content: encodeBlk(index),
cachedDecals: cachedStockDecals + cachedExtraDecals,
cachedStockDecals,
cachedExtraDecals,
placeholderDecals,
};
}
function aspectRatio(decal: BlkBlock): number {
const value = decal.params.find((param) => param.name === 'aspect_ratio')?.value;
return value?.type === 'real' && Number.isFinite(value.value) && value.value > 0 ? value.value : 1;
+244 -37
View File
@@ -1,25 +1,28 @@
/**
* Decals and downloadable skins from the player's own online client: the player names the web
* cache folder of an installation they have played online with (<game>/cache/content, or its
* parent <game>/cache), and the build copies the cached textures into the game copy's
* cache/content. The offline version never looks for that folder itself.
* cache folder of an installation they have played online with (<game>/cache/content, its parent
* <game>/cache, or the game root <game>), and the build copies the cached textures into the game
* copy's cache/content. The offline version never looks for that folder itself.
*
* Two layouts exist across War Thunder builds (verified on 2.61.0.37 and 2.61.0.58):
* 1. Modern vromfs-indexed cache (2.61+): cache/content/ holds dldata_s.info and the downloaded
* <first2>/<hash>.ddsx textures, while the decal and skin indexes (dldata/downloadable_decals.blk
* and dldata/downloadable_skins.blk) ship inside sibling cache/binary.<ver>/regional.vromfs.bin
* (mounted by webdlcontent::on_regional_vrom_remounted, 0xd3cf95 -> 0xd3d066). Because the client
* reads the vromfs index first, it never writes downloadable_decals.<hash>.blk into cache/content/.
* We extract both index BLKs into a self-contained snapshot (.wto-index/) on import and embed
* them into char.vromfs.bin during build so webdlcontent::init mounts cache/content/ (0xd3ca11)
* and loads the real hashes from vromfs without signature checks (0xd3cb6b).
* <first2>/<rest>.ddsx textures (where the first 2 characters of each base32 hash form the
* bucket directory and the remaining characters plus ".ddsx" form the filename), while the
* decal and skin indexes (dldata/downloadable_decals.blk and dldata/downloadable_skins.blk)
* ship inside sibling cache/binary.<ver>/regional.vromfs.bin (mounted by
* webdlcontent::on_regional_vrom_remounted, 0xd3cf95 -> 0xd3d066). Because the client reads
* the vromfs index first, it never writes downloadable_decals.<hash>.blk into cache/content/.
* We extract both raw index BLKs into a self-contained snapshot (.wto-index/) on import; when
* building char.vromfs.bin, we filter both indexes against the .ddsx files actually present
* in the cache (backfilling missing single-LOD references from the cached LOD) so uncached
* entries do not fail to load offline.
* 2. Legacy webcache-indexed cache: cache/content/ holds dldata_s.info and signed
* downloadable_decals.<hash>.blk directly; char.vromfs.bin omits dldata/ so the client reads
* the cached index from cache/content/.
*/
import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path';
import { decodeBlk, emptyBlock, encodeBlk, parseSharedNameMap } from '@wto/blk';
import { decodeBlk, emptyBlock, encodeBlk, parseSharedNameMap, type BlkBlock, type BlkParam } from '@wto/blk';
import { getFile, NAME_MAP_PATH, readArchive } from '@wto/vromfs';
import type { AddedFile } from '../pack-edit.ts';
import { compareVersions } from '../version-record.ts';
@@ -33,6 +36,9 @@ const REGIONAL_PACK_NAME = 'regional.vromfs.bin';
const SNAPSHOT_INDEX_DIR = '.wto-index';
const SNAPSHOT_DECALS_FILE = 'downloadable_decals.blk';
const SNAPSHOT_SKINS_FILE = 'downloadable_skins.blk';
const DDSX_EXTENSION = '.ddsx';
const LOD_PARAM = /^lod(\d+)$/;
const HDR_PARAM = /^hdr(\d+)$/;
export interface PlayerDecalCache {
readonly copiedTo: string;
@@ -40,15 +46,16 @@ export interface PlayerDecalCache {
}
/**
* Resolve the actual cache/content folder when the player selects either <game>/cache/content
* or its parent <game>/cache folder.
* Resolve the actual cache/content folder when the player selects <game>/cache/content,
* its parent <game>/cache folder, or the game root <game>.
*/
export function resolvePlayerDecalCacheFolder(source: string): string {
if (!existsSync(source) || !statSync(source).isDirectory()) return source;
if (directDecalCacheProblem(source) === undefined) return source;
const nested = join(source, 'content');
if (existsSync(nested) && statSync(nested).isDirectory() && directDecalCacheProblem(nested) === undefined) {
return nested;
for (const candidate of [join(source, 'content'), join(source, WEB_CACHE_FOLDER)]) {
if (existsSync(candidate) && statSync(candidate).isDirectory() && directDecalCacheProblem(candidate) === undefined) {
return candidate;
}
}
return source;
}
@@ -60,27 +67,133 @@ export function playerDecalCacheProblem(source: string): string | undefined {
}
/**
* Read real dldata/downloadable_decals.blk and dldata/downloadable_skins.blk for embedding into
* char.vromfs.bin when the cache uses either an imported snapshot index or a sibling
* binary.<ver>/regional.vromfs.bin. Returns undefined for legacy downloadable_decals.<hash>.blk
* caches, which supply their index directly inside cache/content/.
* Map a downloadable texture hash (e.g. "nhy6...cyii") to its cache-relative .ddsx path
* ("nh/y6...cyii.ddsx", lowercased). Returns undefined for non-hash values.
*/
export function readPlayerDecalIndexFiles(source: string): readonly AddedFile[] | undefined {
const folder = resolvePlayerDecalCacheFolder(source);
const snapshot = readSnapshotIndexFiles(folder);
if (snapshot) return snapshot;
if (decalIndexes(folder).length > 0) return undefined;
const regional = findRegionalPack(folder);
if (!regional) return undefined;
return extractRegionalIndexFiles(regional);
export function ddsxPathForHash(hash: string): string | undefined {
const normalized = hash.trim().toLowerCase();
if (normalized.length < 3 || normalized.includes('/') || normalized.includes('\\')) return undefined;
return `${normalized.slice(0, 2)}/${normalized.slice(2)}${DDSX_EXTENSION}`;
}
/**
* Persist extracted vromfs decal/skin indexes into an imported cache snapshot so subsequent
* Scan a player decal cache folder (cache/content, its parent cache folder, the game root, or an
* imported snapshot) and collect the normalized relative paths ("<first2>/<rest>.ddsx", lowercased)
* of all cached .ddsx files, skipping .wto-index.
*/
export function scanCachedDdsxFiles(source: string): ReadonlySet<string> {
const folder = resolvePlayerDecalCacheFolder(source);
const cached = new Set<string>();
if (!existsSync(folder) || !statSync(folder).isDirectory()) return cached;
for (const entry of readdirSync(folder, { withFileTypes: true })) {
if (!entry.isDirectory() || entry.name === SNAPSHOT_INDEX_DIR) continue;
const bucket = entry.name.toLowerCase();
if (bucket.length !== 2) continue;
const sub = join(folder, entry.name);
for (const child of readdirSync(sub, { withFileTypes: true })) {
if (!child.isFile()) continue;
const name = child.name.toLowerCase();
if (name.endsWith(DDSX_EXTENSION)) cached.add(`${bucket}/${name}`);
}
}
return cached;
}
/**
* Filter a downloadable_decals.blk root block to only decals with at least one cached LOD
* texture in cachedDdsx, backfilling any missing lodN/hdrN from the best cached LOD.
*/
export function filterDownloadableDecalsBlock(
decalsBlk: BlkBlock,
cachedDdsx: ReadonlySet<string>,
): BlkBlock {
const blocks: BlkBlock[] = [];
for (const decal of decalsBlk.blocks) {
const normalized = normalizeTextureBlockLods(decal, cachedDdsx);
if (normalized !== undefined) blocks.push(normalized);
}
return { name: decalsBlk.name, params: decalsBlk.params, blocks };
}
/**
* Filter a downloadable_skins.blk root block to only skins whose texture entries all have at
* least one cached LOD texture in cachedDdsx, backfilling missing lodN (and hdrN if present)
* from the best cached LOD.
*/
export function filterDownloadableSkinsBlock(
skinsBlk: BlkBlock,
cachedDdsx: ReadonlySet<string>,
): BlkBlock {
const blocks: BlkBlock[] = [];
for (const skin of skinsBlk.blocks) {
if (skin.blocks.length > 0) {
const nextChildren: BlkBlock[] = [];
let allCached = true;
let hasTextureChild = false;
for (const child of skin.blocks) {
if (hasLodParams(child)) {
hasTextureChild = true;
const normalized = normalizeTextureBlockLods(child, cachedDdsx);
if (normalized === undefined) {
allCached = false;
break;
}
nextChildren.push(normalized);
} else {
nextChildren.push(child);
}
}
if (allCached && hasTextureChild) {
blocks.push({ name: skin.name, params: skin.params, blocks: nextChildren });
}
} else {
const normalized = normalizeTextureBlockLods(skin, cachedDdsx);
if (normalized !== undefined) blocks.push(normalized);
}
}
return { name: skinsBlk.name, params: skinsBlk.params, blocks };
}
/**
* Filter encoded dldata/downloadable_decals.blk and dldata/downloadable_skins.blk entries
* against the set of locally cached .ddsx relative paths.
*/
export function filterPlayerDecalIndexFiles(
files: readonly AddedFile[],
cachedDdsx: ReadonlySet<string>,
): readonly AddedFile[] {
return files.map((file) => {
if (file.path === DECALS_INDEX_PATH) {
return { path: file.path, content: encodeBlk(filterDownloadableDecalsBlock(decodeBlk(file.content), cachedDdsx)) };
}
if (file.path === SKINS_INDEX_PATH) {
return { path: file.path, content: encodeBlk(filterDownloadableSkinsBlock(decodeBlk(file.content), cachedDdsx)) };
}
return file;
});
}
/**
* Read dldata/downloadable_decals.blk and dldata/downloadable_skins.blk for embedding into
* char.vromfs.bin when the cache uses either an imported snapshot index or a sibling
* binary.<ver>/regional.vromfs.bin, filtered to entries whose .ddsx textures actually exist in
* the cache folder (with single-LOD fallback). Returns undefined for legacy
* downloadable_decals.<hash>.blk caches, which supply their index directly inside cache/content/.
*/
export function readPlayerDecalIndexFiles(source: string): readonly AddedFile[] | undefined {
const folder = resolvePlayerDecalCacheFolder(source);
const raw = readRawPlayerDecalIndexFiles(folder);
if (!raw) return undefined;
return filterPlayerDecalIndexFiles(raw, scanCachedDdsxFiles(folder));
}
/**
* Persist raw extracted vromfs decal/skin indexes into an imported cache snapshot so subsequent
* launches are completely self-contained and never touch the online client directory.
*/
export function writeDecalCacheIndexSnapshot(source: string, target: string): void {
const files = readPlayerDecalIndexFiles(source);
const folder = resolvePlayerDecalCacheFolder(source);
const files = readRawPlayerDecalIndexFiles(folder);
if (!files) return;
const indexDir = join(target, SNAPSHOT_INDEX_DIR);
mkdirSync(indexDir, { recursive: true });
@@ -140,6 +253,78 @@ function directDecalCacheProblem(folder: string): string | undefined {
return `${folder} has no downloadable_decals.<hash>.blk and no sibling binary.*/${REGIONAL_PACK_NAME}`;
}
function readRawPlayerDecalIndexFiles(folder: string): readonly AddedFile[] | undefined {
const snapshot = readSnapshotIndexFiles(folder);
if (snapshot) return snapshot;
if (decalIndexes(folder).length > 0) return undefined;
const regional = findRegionalPack(folder);
if (!regional) return undefined;
return extractRegionalIndexFiles(regional);
}
function hasLodParams(block: BlkBlock): boolean {
return block.params.some((param) => param.value.type === 'string' && LOD_PARAM.test(param.name));
}
function normalizeTextureBlockLods(
block: BlkBlock,
cachedDdsx: ReadonlySet<string>,
): BlkBlock | undefined {
const lods: Array<{ readonly index: number; readonly value: string; readonly cached: boolean }> = [];
const hdrs = new Map<number, string>();
for (const param of block.params) {
if (param.value.type !== 'string') continue;
const lodMatch = LOD_PARAM.exec(param.name);
if (lodMatch) {
const rel = ddsxPathForHash(param.value.value);
lods.push({
index: Number(lodMatch[1]),
value: param.value.value,
cached: rel !== undefined && cachedDdsx.has(rel),
});
continue;
}
const hdrMatch = HDR_PARAM.exec(param.name);
if (hdrMatch) {
hdrs.set(Number(hdrMatch[1]), param.value.value);
}
}
if (lods.length === 0) return undefined;
lods.sort((a, b) => a.index - b.index);
const best = lods.find((entry) => entry.cached);
if (!best) return undefined;
if (lods.every((entry) => entry.cached)) return block;
const missingIndices = new Set(lods.filter((entry) => !entry.cached).map((entry) => entry.index));
const bestHdr = hdrs.get(best.index);
const nextParams: BlkParam[] = [];
for (const param of block.params) {
if (param.value.type === 'string') {
const hdrMatch = HDR_PARAM.exec(param.name);
if (hdrMatch) {
const idx = Number(hdrMatch[1]);
if (missingIndices.has(idx) && bestHdr !== undefined) {
nextParams.push({ name: param.name, value: { type: 'string', value: bestHdr } });
continue;
}
}
const lodMatch = LOD_PARAM.exec(param.name);
if (lodMatch) {
const idx = Number(lodMatch[1]);
if (missingIndices.has(idx)) {
if (bestHdr !== undefined && !hdrs.has(idx)) {
nextParams.push({ name: `hdr${idx}`, value: { type: 'string', value: bestHdr } });
}
nextParams.push({ name: param.name, value: { type: 'string', value: best.value } });
continue;
}
}
}
nextParams.push(param);
}
return { name: block.name, params: nextParams, blocks: block.blocks };
}
function readSnapshotIndexFiles(folder: string): readonly AddedFile[] | undefined {
const decalsPath = join(folder, SNAPSHOT_INDEX_DIR, SNAPSHOT_DECALS_FILE);
if (!statSync(decalsPath, { throwIfNoEntry: false })?.isFile()) return undefined;
@@ -154,11 +339,23 @@ function readSnapshotIndexFiles(folder: string): readonly AddedFile[] | undefine
}
function hasCachedDdsxTextures(folder: string): boolean {
for (const entry of readdirSync(folder, { withFileTypes: true })) {
let entries;
try {
entries = readdirSync(folder, { withFileTypes: true });
} catch {
return false;
}
for (const entry of entries) {
if (!entry.isDirectory() || entry.name === SNAPSHOT_INDEX_DIR) continue;
const sub = join(folder, entry.name);
for (const child of readdirSync(sub, { withFileTypes: true })) {
if (child.isFile() && child.name.endsWith('.ddsx')) return true;
let children;
try {
children = readdirSync(sub, { withFileTypes: true });
} catch {
continue;
}
for (const child of children) {
if (child.isFile() && child.name.toLowerCase().endsWith(DDSX_EXTENSION)) return true;
}
}
return false;
@@ -167,8 +364,14 @@ function hasCachedDdsxTextures(folder: string): boolean {
function findRegionalPack(contentFolder: string): string | undefined {
const parent = dirname(contentFolder);
if (parent === contentFolder || !existsSync(parent)) return undefined;
let entries;
try {
entries = readdirSync(parent, { withFileTypes: true });
} catch {
return undefined;
}
const candidates: Array<{ readonly path: string; readonly version: string; readonly mtimeMs: number }> = [];
for (const entry of readdirSync(parent, { withFileTypes: true })) {
for (const entry of entries) {
if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
const match = BINARY_CACHE_DIR.exec(entry.name);
if (!match) continue;
@@ -211,7 +414,11 @@ function contains(parent: string, child: string): boolean {
}
function decalIndexes(folder: string): string[] {
return readdirSync(folder, { withFileTypes: true })
.filter((entry) => entry.isFile() && DECALS_INDEX_FILE.test(entry.name))
.map((entry) => entry.name);
try {
return readdirSync(folder, { withFileTypes: true })
.filter((entry) => entry.isFile() && DECALS_INDEX_FILE.test(entry.name))
.map((entry) => entry.name);
} catch {
return [];
}
}
@@ -226,6 +226,9 @@ export function computeModsBuildFingerprint(
hash.update(`port=${port};salt=${extraSalt}\n`);
for (const mod of mods) {
hash.update(`mod=${mod.manifest.id}@${mod.manifest.version}\n`);
if (mod.manifest.techTreeInsertions?.length) {
hash.update(`tech_tree_insertions=${JSON.stringify(mod.manifest.techTreeInsertions)}\n`);
}
const filesToStamp = [
...mod.content.packOperations.map((op) => op.sourceRelativePath),
...mod.content.guiPatchDirs,
+21 -6
View File
@@ -4,7 +4,7 @@
*/
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { decodeBlk, encodeBlk, isBinaryBlk, parseBlkText, parseSharedNameMap } from '@wto/blk';
import { decodeBlk, encodeBlk, isBinaryBlk, parseBlkText, parseSharedNameMap, type SharedNameContext } from '@wto/blk';
import {
applyBlkPatch,
applyBlkTextPatch,
@@ -18,6 +18,8 @@ import {
type ModdableClientPack,
} from '@wto/mods';
import { getFile, NAME_MAP_PATH, putFile, readArchive, writeArchive, type Archive } from '@wto/vromfs';
import { composeTechTreeInsertions, VEHICLE_ECONOMY_PATH } from '../tech-tree/compose-insertions.ts';
import { SHOP_PATH } from '../tech-tree/reveal-hidden-vehicles.ts';
export interface PackOverlayReport {
readonly pack: ModdableClientPack;
@@ -35,7 +37,10 @@ export function applyModPackOverlays(
ops: mod.content.packOperations.filter((op) => op.pack === packName),
}))
.filter((entry) => entry.ops.length > 0);
const totalOps = relevantMods.reduce((sum, entry) => sum + entry.ops.length, 0);
const insertions = packName === 'char.vromfs.bin'
? mods.flatMap(({ manifest }) => (manifest.techTreeInsertions ?? []).map((entry) => ({ ...entry, modId: manifest.id })))
: [];
const totalOps = relevantMods.reduce((sum, entry) => sum + entry.ops.length, insertions.length);
if (totalOps === 0) {
return { pack: basePack, report: { pack: packName, operationsApplied: 0 } };
}
@@ -74,10 +79,7 @@ export function applyModPackOverlays(
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 root = readOverlayBlk(archive, resolvedPath, { names, dictionary });
const patchText = readFileSync(sourcePath, 'utf8');
if (op.sourceRelativePath.toLowerCase().endsWith('.patch.blk')) {
applyBlkTextPatch(root, patchText, {
@@ -123,12 +125,25 @@ export function applyModPackOverlays(
}
}
if (insertions.length > 0) {
const shop = readOverlayBlk(archive, SHOP_PATH, { names, dictionary });
const economy = readOverlayBlk(archive, VEHICLE_ECONOMY_PATH, { names, dictionary });
composeTechTreeInsertions(shop, economy, insertions);
putFile(archive, SHOP_PATH, encodeBlk(shop));
putFile(archive, VEHICLE_ECONOMY_PATH, encodeBlk(economy));
}
return {
pack: writeArchive(archive),
report: { pack: packName, operationsApplied: totalOps },
};
}
function readOverlayBlk(archive: Archive, path: string, shared: SharedNameContext) {
const raw = getFile(archive, path);
return isBinaryBlk(raw) ? decodeBlk(raw, shared) : parseBlkText(Buffer.from(raw).toString('utf8'));
}
function createArchiveIncludeResolver(params: {
readonly archive: Archive;
readonly names: readonly string[];
@@ -0,0 +1,221 @@
/** Compose opt-in research links after the normal BLK overlays have supplied the vehicles. */
import { emptyBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
import type { ModTechTreeInsertion } from '@wto/mods';
export const VEHICLE_ECONOMY_PATH = 'config/wpcost.blk';
export interface RequestedTechTreeInsertion extends ModTechTreeInsertion {
readonly modId: string;
}
interface ShopPosition {
readonly entry: BlkBlock;
readonly page: BlkBlock;
readonly country: string;
readonly column: BlkBlock;
readonly group?: BlkBlock;
}
interface InsertionPlan {
readonly destination: BlkBlock;
readonly anchor: BlkBlock;
readonly successor: ShopPosition;
readonly updateGroupLink: boolean;
readonly entries: readonly { entry: BlkBlock; from: ShopPosition | undefined; rank: number; previous: string }[];
readonly lastVehicle: string;
}
export function composeTechTreeInsertions(
shop: BlkBlock,
economy: BlkBlock,
requests: readonly RequestedTechTreeInsertion[],
): void {
const catalog = indexByName(economy.blocks);
const positions = indexShop(shop);
const owners = new Map<string, string>();
const bySuccessor = new Map<string, RequestedTechTreeInsertion[]>();
for (const request of requests) {
const owner = owners.get(request.vehicle);
if (owner !== undefined) throw invalid(request, `"${request.vehicle}" is already inserted by mod "${owner}"`);
owners.set(request.vehicle, request.modId);
addToIndex(bySuccessor, request.before, request);
}
const links = new Map<string, { previous: string; request: RequestedTechTreeInsertion }>();
const plans: InsertionPlan[] = [];
for (const group of bySuccessor.values()) {
const first = group[0]!;
for (const request of group) {
if (owners.has(request.after) || owners.has(request.before)) {
throw invalid(request, 'insertion anchors must belong to the existing line');
}
if (request.after !== first.after) throw invalid(request, `mod "${first.modId}" names a different predecessor of "${request.before}"`);
}
const plan = planInsertion(catalog, positions, group);
for (const [index, entry] of plan.entries.entries()) {
links.set(entry.entry.name, { previous: entry.previous, request: group[index]! });
}
links.set(first.before, { previous: plan.lastVehicle, request: first });
plans.push(plan);
}
validateAcyclicLinks(catalog, links);
for (const [name, { previous, request }] of links) {
setParam(requireOne(catalog, name, VEHICLE_ECONOMY_PATH, request), 'reqAir', { type: 'string', value: previous });
}
for (const plan of plans) applyPlacement(plan);
}
function planInsertion(
catalog: ReadonlyMap<string, BlkBlock[]>,
positions: ReadonlyMap<string, ShopPosition[]>,
requests: readonly RequestedTechTreeInsertion[],
): InsertionPlan {
const first = requests[0]!;
const predecessor = requireOne(positions, first.after, 'config/shop.blk', first);
const successor = requireOne(positions, first.before, 'config/shop.blk', first);
if (predecessor.page !== successor.page) throw invalid(first, 'the two anchors must belong to the same country and branch');
const after = requireOne(catalog, first.after, VEHICLE_ECONOMY_PATH, first);
const before = requireOne(catalog, first.before, VEHICLE_ECONOMY_PATH, first);
const declaredPredecessor = textParam(before, 'reqAir');
if (declaredPredecessor !== first.after) {
throw invalid(first, `"${first.before}" requires ${declaredPredecessor ? `"${declaredPredecessor}"` : 'no vehicle'} in ${VEHICLE_ECONOMY_PATH}`);
}
const withinGroup = successor.group !== undefined && predecessor.group === successor.group;
const anchor = withinGroup ? successor.entry : successor.group ?? successor.entry;
if (successor.group && !withinGroup && successor.group.blocks[0] !== successor.entry) {
throw invalid(first, 'the link enters a non-leading variant of another folder');
}
validateShopPredecessor(anchor, first);
const maxRank = researchRank(before, successor, successor.country, first);
let lastRank = researchRank(after, predecessor, successor.country, first);
let lastVehicle = first.after;
const entries = requests.map((request) => {
const source = requireOne(catalog, request.vehicle, VEHICLE_ECONOMY_PATH, request);
const from = optionalOne(positions, request.vehicle, 'config/shop.blk', request);
if (from && from.page !== successor.page) throw invalid(request, `"${request.vehicle}" is placed in a different country or branch`);
if (from?.group && (!withinGroup || from.group !== successor.group)) {
throw invalid(request, `"${request.vehicle}" is already inside a different folder`);
}
const rank = researchRank(source, from, successor.country, request);
if (rank < lastRank || rank > maxRank) {
throw invalid(request, `rank ${rank} must be between ${lastRank} and ${maxRank} in mod load order`);
}
const entry = { entry: from?.entry ?? emptyBlock(request.vehicle), from, rank, previous: lastVehicle };
lastRank = rank;
lastVehicle = request.vehicle;
return entry;
});
return { destination: withinGroup ? successor.group! : successor.column, anchor, successor, updateGroupLink: anchor !== successor.entry, entries, lastVehicle };
}
function validateShopPredecessor(anchor: BlkBlock, request: RequestedTechTreeInsertion): void {
for (const key of ['reqAir', 'futureReqAir']) {
const value = findParam(anchor, key)?.value;
if (value !== undefined && (value.type !== 'string' || value.value !== request.after)) {
throw invalid(request, `"${anchor.name}" has a different ${key} in config/shop.blk`);
}
}
}
function applyPlacement(plan: InsertionPlan): void {
for (const item of plan.entries) {
if (item.from) {
const parent = item.from.group ?? item.from.column;
parent.blocks.splice(parent.blocks.indexOf(item.entry), 1);
}
setParam(item.entry, 'rank', { type: 'int', value: item.rank });
setPrerequisite(item.entry, item.previous);
}
plan.destination.blocks.splice(plan.destination.blocks.indexOf(plan.anchor), 0, ...plan.entries.map(({ entry }) => entry));
setPrerequisite(plan.successor.entry, plan.lastVehicle);
if (plan.updateGroupLink) setPrerequisite(plan.anchor, plan.lastVehicle);
}
function setPrerequisite(block: BlkBlock, previous: string): void {
setParam(block, 'reqAir', { type: 'string', value: previous });
if (findParam(block, 'futureReqAir')) setParam(block, 'futureReqAir', { type: 'string', value: previous });
}
function researchRank(entry: BlkBlock, position: ShopPosition | undefined, country: string, request: RequestedTechTreeInsertion): number {
const rank = findParam(entry, 'rank')?.value;
const gold = findParam(entry, 'costGold')?.value;
if (textParam(entry, 'country') !== country || rank?.type !== 'int' || rank.value < 1) {
throw invalid(request, `"${entry.name}" must have a valid rank in ${country} in ${VEHICLE_ECONOMY_PATH}`);
}
if (textParam(entry, 'gift') !== undefined || textParam(entry, 'event') !== undefined || textParam(entry, 'researchType') === 'clanVehicle'
|| findParam(entry, 'premPackAir')?.value.value === true || (gold?.type === 'int' && gold.value > 0)
|| (position && findParam(position.entry, 'showOnlyWhenBought')?.value.value === true)) {
throw invalid(request, `"${entry.name}" must be a regular vehicle in the research line`);
}
return rank.value;
}
function validateAcyclicLinks(
catalog: ReadonlyMap<string, BlkBlock[]>,
links: ReadonlyMap<string, { previous: string; request: RequestedTechTreeInsertion }>,
): void {
const checked = new Set<string>();
for (const [vehicle, { request }] of links) {
const path = new Set<string>();
let name: string | undefined = vehicle;
while (name !== undefined && !checked.has(name)) {
if (path.has(name)) throw invalid(request, `research prerequisites form a cycle at "${name}"`);
path.add(name);
const existing: BlkBlock | undefined = catalog.get(name)?.[0];
name = links.get(name)?.previous ?? (existing ? textParam(existing, 'reqAir') : undefined);
}
for (const visited of path) checked.add(visited);
}
}
function indexShop(shop: BlkBlock): Map<string, ShopPosition[]> {
const positions = new Map<string, ShopPosition[]>();
for (const country of shop.blocks) {
for (const page of country.blocks) {
for (const column of page.blocks) {
for (const entry of column.blocks) {
addToIndex(positions, entry.name, { entry, page, country: country.name, column });
for (const variant of entry.blocks) {
addToIndex(positions, variant.name, { entry: variant, page, country: country.name, column, group: entry });
}
}
}
}
}
return positions;
}
function indexByName(blocks: readonly BlkBlock[]): Map<string, BlkBlock[]> {
const entries = new Map<string, BlkBlock[]>();
for (const block of blocks) addToIndex(entries, block.name, block);
return entries;
}
function addToIndex<T>(index: Map<string, T[]>, key: string, entry: T): void {
const list = index.get(key);
if (list) list.push(entry);
else index.set(key, [entry]);
}
function requireOne<T>(index: ReadonlyMap<string, T[]>, name: string, where: string, request: RequestedTechTreeInsertion): T {
const entry = optionalOne(index, name, where, request);
if (entry === undefined) throw invalid(request, `"${name}" is missing from ${where}`);
return entry;
}
function optionalOne<T>(index: ReadonlyMap<string, T[]>, name: string, where: string, request: RequestedTechTreeInsertion): T | undefined {
const entries = index.get(name);
if (entries && entries.length > 1) throw invalid(request, `"${name}" is ambiguous in ${where}`);
return entries?.[0];
}
function textParam(block: BlkBlock, name: string): string | undefined {
const value = findParam(block, name)?.value;
return value?.type === 'string' ? value.value : undefined;
}
function invalid(request: RequestedTechTreeInsertion, reason: string): Error {
return new Error(`mod "${request.modId}" tech_tree_insertions (${request.after} -> ${request.vehicle} -> ${request.before}): ${reason}`);
}
@@ -15,21 +15,45 @@
* not been given them: event and promotion prizes, mission copies of tree vehicles (nt_f_4e,
* f_4e_event ...), the drones of the premium columns, the floatplanes that come with ships,
* and the launchers of the split air-defence systems (lab round 20, user feedback).
*
* Cross-promotion gift vehicles (e.g. us_m4_sherman_promo, bf-109c_1_promo,
* jp_destroyer_hatsuzuki) also carry `isCrossPromo:b` and `crossPromoBanner:t`. When
* `isCrossPromo` is true, stock client scripts (availabilitybuyonline.nut, unitcontextmenu.nut,
* slotactions.nut) hide the "Order" action and show a cross-promo locked banner instead of
* routing to the local store pack and bundle GUID generated for gift vehicles. Both parameters
* are stripped here so those vehicles can be ordered directly from the tech tree.
*/
import type { BlkBlock } from '@wto/blk';
export const SHOP_PATH = 'config/shop.blk';
const HIDING_FLAGS = new Set(['showOnlyWhenResearch', 'showOnlyWhenAvailableForPurchase']);
const CROSS_PROMO_PARAMS = new Set(['isCrossPromo', 'crossPromoBanner']);
/** Remove the hiding flags in place; returns how many vehicles were hidden before. */
/**
* Remove tech-tree hiding flags and cross-promo lock parameters in place.
* Returns how many vehicles had a hiding flag removed (cross-promo unlocks are not counted).
*/
export function revealHiddenVehicles(shop: BlkBlock): number {
let revealed = 0;
for (const entry of shopEntries(shop)) {
const kept = entry.params.filter((param) => !HIDING_FLAGS.has(param.name));
if (kept.length === entry.params.length) continue;
let wasHidden = false;
let stripped = false;
const kept = entry.params.filter((param) => {
if (HIDING_FLAGS.has(param.name)) {
wasHidden = true;
stripped = true;
return false;
}
if (CROSS_PROMO_PARAMS.has(param.name)) {
stripped = true;
return false;
}
return true;
});
if (!stripped) continue;
entry.params = kept;
revealed++;
if (wasHidden) revealed++;
}
return revealed;
}