Serve game modes from extracted mission data
Publish stable mode IDs and matching responses in the stock format. Build the mission pools from the multiplayer mission data and provide required fields and localized names. Load datasets before listening and reuse cached results when the source file digests match. Preserve invalid UTF-8 bytes when round-tripping BLK strings and names. The game mode list appeared in the offline client.
This commit is contained in:
1 parent
6ed498e4d0
commit
40af06edad
26 files changed
+943
-28
No files matched your search
@@ -0,0 +1,31 @@
|
||||
/** Typed reads of BLK parameters for dataset extraction; a missing or differently typed parameter reads as undefined. */
|
||||
import { findBlock, findParam, type BlkBlock } from '@wto/blk';
|
||||
|
||||
export function stringField(block: BlkBlock | undefined, name: string): string | undefined {
|
||||
const value = block && findParam(block, name)?.value;
|
||||
return value?.type === 'string' ? value.value : undefined;
|
||||
}
|
||||
|
||||
export function numberField(block: BlkBlock | undefined, name: string): number | undefined {
|
||||
const value = block && findParam(block, name)?.value;
|
||||
return value?.type === 'int' || value?.type === 'real' ? value.value : undefined;
|
||||
}
|
||||
|
||||
/** Every string value of a repeated parameter, in order. */
|
||||
export function stringList(block: BlkBlock | undefined, name: string): string[] {
|
||||
if (!block) return [];
|
||||
return block.params.flatMap((param) => param.name === name && param.value.type === 'string' ? [param.value.value] : []);
|
||||
}
|
||||
|
||||
/** Every bool parameter of a block, by name. */
|
||||
export function boolFields(block: BlkBlock | undefined): Record<string, boolean> {
|
||||
if (!block) return {};
|
||||
return Object.fromEntries(block.params.flatMap((param) => param.value.type === 'bool' ? [[param.name, param.value.value]] : []));
|
||||
}
|
||||
|
||||
/** Follow a path of first-found sub-blocks. */
|
||||
export function blockAt(block: BlkBlock | undefined, ...names: string[]): BlkBlock | undefined {
|
||||
let current = block;
|
||||
for (const name of names) current = current && findBlock(current, name);
|
||||
return current;
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* Extract datasets once and reuse the result while the game files stay the same
|
||||
*:
|
||||
*
|
||||
* 1. every pack the dataset read has the same size and modification time as when it was
|
||||
* extracted: use the cached result;
|
||||
* 2. otherwise compare the SHA-1 of the files the dataset actually read (and of the file
|
||||
* listings it used): all equal, the result still holds, so only the pack stamps are
|
||||
* updated (the build rewrites char.vromfs.bin on every launch without touching what
|
||||
* the datasets read);
|
||||
* 3. otherwise extract again.
|
||||
*
|
||||
* Cache entries live in <data folder>/cache/datasets/<dataset id>.json.
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import type { BlkBlock } from '@wto/blk';
|
||||
import { writeFileAtomic } from '../../storage/atomic-file.ts';
|
||||
import type { GameFiles, GamePackName, PackStamp } from '../game-files.ts';
|
||||
import type { Dataset, DatasetSource } from './dataset.ts';
|
||||
|
||||
interface FileInput {
|
||||
readonly pack: GamePackName;
|
||||
readonly path: string;
|
||||
readonly sha1: string;
|
||||
}
|
||||
|
||||
interface ListingInput {
|
||||
readonly pack: GamePackName;
|
||||
readonly sha1: string;
|
||||
}
|
||||
|
||||
interface CacheEntry {
|
||||
readonly id: string;
|
||||
readonly version: number;
|
||||
readonly packs: Partial<Record<GamePackName, PackStamp>>;
|
||||
readonly files: readonly FileInput[];
|
||||
readonly listings: readonly ListingInput[];
|
||||
readonly data: unknown;
|
||||
}
|
||||
|
||||
export type DatasetOrigin = 'cache' | 'cache, verified by content' | 'extracted';
|
||||
|
||||
export class DatasetCache {
|
||||
readonly #folder: string;
|
||||
readonly #gameFiles: GameFiles;
|
||||
readonly #report: (line: string) => void;
|
||||
|
||||
constructor(dataFolder: string, gameFiles: GameFiles, report: (line: string) => void) {
|
||||
this.#folder = join(dataFolder, 'cache', 'datasets');
|
||||
this.#gameFiles = gameFiles;
|
||||
this.#report = report;
|
||||
}
|
||||
|
||||
load<T>(dataset: Dataset<T>): T {
|
||||
const entryPath = join(this.#folder, `${dataset.id}.json`);
|
||||
const cached = readEntry(entryPath);
|
||||
if (cached && cached.id === dataset.id && cached.version === dataset.version) {
|
||||
if (this.#stampsMatch(cached)) return this.#use(dataset, cached, 'cache');
|
||||
if (this.#contentMatches(cached)) {
|
||||
writeEntry(entryPath, { ...cached, packs: this.#stamps(Object.keys(cached.packs) as GamePackName[]) });
|
||||
return this.#use(dataset, cached, 'cache, verified by content');
|
||||
}
|
||||
}
|
||||
const started = Date.now();
|
||||
const tracked = new TrackedSource(this.#gameFiles);
|
||||
const data = dataset.extract(tracked);
|
||||
const entry: CacheEntry = {
|
||||
id: dataset.id,
|
||||
version: dataset.version,
|
||||
packs: this.#stamps(tracked.packs()),
|
||||
files: tracked.files(),
|
||||
listings: tracked.listings(),
|
||||
data,
|
||||
};
|
||||
writeEntry(entryPath, entry);
|
||||
this.#report(`dataset ${dataset.id}: extracted in ${Date.now() - started} ms (${entry.files.length} files)`);
|
||||
return data;
|
||||
}
|
||||
|
||||
#use<T>(dataset: Dataset<T>, entry: CacheEntry, origin: DatasetOrigin): T {
|
||||
this.#report(`dataset ${dataset.id}: ${origin}`);
|
||||
return entry.data as T;
|
||||
}
|
||||
|
||||
#stamps(packs: readonly GamePackName[]): Partial<Record<GamePackName, PackStamp>> {
|
||||
return Object.fromEntries(packs.map((pack) => [pack, this.#gameFiles.packStamp(pack)]));
|
||||
}
|
||||
|
||||
#stampsMatch(entry: CacheEntry): boolean {
|
||||
return Object.entries(entry.packs).every(([pack, stamp]) => {
|
||||
const current = this.#gameFiles.packStamp(pack as GamePackName);
|
||||
return stamp !== undefined && current.size === stamp.size && current.mtimeMs === stamp.mtimeMs;
|
||||
});
|
||||
}
|
||||
|
||||
#contentMatches(entry: CacheEntry): boolean {
|
||||
return entry.files.every(({ pack, path, sha1 }) => this.#gameFiles.pack(pack).fileDigest(path) === sha1)
|
||||
&& entry.listings.every(({ pack, sha1 }) => listingDigest(this.#gameFiles.pack(pack).paths()) === sha1);
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads through to the game files and remembers every input. */
|
||||
class TrackedSource implements DatasetSource {
|
||||
readonly #gameFiles: GameFiles;
|
||||
readonly #files = new Map<string, FileInput>();
|
||||
readonly #listings = new Map<GamePackName, ListingInput>();
|
||||
|
||||
constructor(gameFiles: GameFiles) {
|
||||
this.#gameFiles = gameFiles;
|
||||
}
|
||||
|
||||
readBlk(pack: GamePackName, path: string): BlkBlock {
|
||||
const gamePack = this.#gameFiles.pack(pack);
|
||||
const sha1 = gamePack.fileDigest(path);
|
||||
if (sha1 === undefined) throw new Error(`${pack} has no file ${path}`);
|
||||
this.#files.set(`${pack}/${path}`, { pack, path, sha1 });
|
||||
return gamePack.readBlk(path);
|
||||
}
|
||||
|
||||
listFiles(pack: GamePackName): readonly string[] {
|
||||
const paths = this.#gameFiles.pack(pack).paths();
|
||||
this.#listings.set(pack, { pack, sha1: listingDigest(paths) });
|
||||
return paths;
|
||||
}
|
||||
|
||||
packs(): GamePackName[] {
|
||||
return [...new Set([...this.#files.values(), ...this.#listings.values()].map((input) => input.pack))];
|
||||
}
|
||||
|
||||
files(): FileInput[] {
|
||||
return [...this.#files.values()];
|
||||
}
|
||||
|
||||
listings(): ListingInput[] {
|
||||
return [...this.#listings.values()];
|
||||
}
|
||||
}
|
||||
|
||||
function listingDigest(paths: readonly string[]): string {
|
||||
return createHash('sha1').update(paths.join('\n')).digest('hex');
|
||||
}
|
||||
|
||||
function readEntry(path: string): CacheEntry | undefined {
|
||||
try {
|
||||
return JSON.parse(readFileSync(path, 'utf8')) as CacheEntry;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function writeEntry(path: string, entry: CacheEntry): void {
|
||||
writeFileAtomic(path, JSON.stringify(entry));
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* A dataset: a set of static facts extracted from the player's game files (implementation notes
|
||||
* 3.4). Each dataset declares what it produces and reads its inputs only through the source
|
||||
* it is given, so the cache knows exactly which files the result depends on.
|
||||
*
|
||||
* A dataset only records what the game files say; deciding what the facts mean for a game
|
||||
* rule belongs to the rules layer.
|
||||
*/
|
||||
import type { BlkBlock } from '@wto/blk';
|
||||
import type { GamePackName } from '../game-files.ts';
|
||||
|
||||
export interface DatasetSource {
|
||||
readBlk(pack: GamePackName, path: string): BlkBlock;
|
||||
/** Every file path in a pack, sorted. */
|
||||
listFiles(pack: GamePackName): readonly string[];
|
||||
}
|
||||
|
||||
export interface Dataset<T> {
|
||||
/** File name of the cache entry; unique among datasets. */
|
||||
readonly id: string;
|
||||
/** Raise when the extraction code or the shape of the result changes: old cache entries are then ignored. */
|
||||
readonly version: number;
|
||||
/** The result must survive JSON.stringify / JSON.parse unchanged. */
|
||||
extract(source: DatasetSource): T;
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* Dataset: the game's multiplayer missions, as the game lists and describes them.
|
||||
*
|
||||
* - The list: char.vromfs.bin config/mislist.blk, block "skirmish". One sub-block per
|
||||
* category (e.g. air_ground_Dom, air_dom, air_naval_Dom, pve), holding the category's
|
||||
* flags (isDebug, isForceHidden, …) and its mission names (repeated "m").
|
||||
* - Each mission: mis.vromfs.bin gamedata/missions/…/<name lower-cased>.blk. Its
|
||||
* mission_settings block names the map, the kind of game, the two sides' countries, the
|
||||
* vehicle types allowed, per-difficulty overrides, and the players' spawn slots
|
||||
* ("wing" entries of player / player_teamB).
|
||||
*
|
||||
* 2.61.0.37: 1315 missions, each name matching exactly one mission file (docs/implementation notes).
|
||||
*/
|
||||
import type { BlkBlock } from '@wto/blk';
|
||||
import type { Dataset, DatasetSource } from './dataset.ts';
|
||||
import { blockAt, boolFields, numberField, stringField, stringList } from './blk-fields.ts';
|
||||
|
||||
const MISSION_LIST = 'config/mislist.blk';
|
||||
const MULTIPLAYER_SECTION = 'skirmish';
|
||||
const MISSION_FOLDER = 'gamedata/missions/';
|
||||
|
||||
export interface MissionCategory {
|
||||
readonly name: string;
|
||||
readonly flags: Readonly<Record<string, boolean>>;
|
||||
readonly missions: readonly string[];
|
||||
}
|
||||
|
||||
export interface MissionHeader {
|
||||
readonly name: string;
|
||||
readonly path: string;
|
||||
readonly level?: string;
|
||||
readonly type?: string;
|
||||
readonly environment?: string;
|
||||
readonly weather?: string;
|
||||
readonly countryAxis?: string;
|
||||
readonly countryAllies?: string;
|
||||
readonly timeLimit?: number;
|
||||
/** As written in the mission (isAirplanesAllowed, isTanksAllowed, …); empty when the mission does not say. */
|
||||
readonly allowedUnitTypes: Readonly<Record<string, boolean>>;
|
||||
/** Difficulties the mission has its own settings for. */
|
||||
readonly difficultyOverrides: readonly string[];
|
||||
/** Spawn slots per side. */
|
||||
readonly playerSlots: { readonly teamA: number; readonly teamB: number };
|
||||
}
|
||||
|
||||
export interface MultiplayerMissions {
|
||||
readonly categories: readonly MissionCategory[];
|
||||
readonly missions: Readonly<Record<string, MissionHeader>>;
|
||||
}
|
||||
|
||||
export const multiplayerMissions: Dataset<MultiplayerMissions> = {
|
||||
id: 'multiplayer-missions',
|
||||
version: 1,
|
||||
extract(source: DatasetSource): MultiplayerMissions {
|
||||
const section = blockAt(source.readBlk('char.vromfs.bin', MISSION_LIST), MULTIPLAYER_SECTION);
|
||||
if (!section) throw new Error(`${MISSION_LIST} has no "${MULTIPLAYER_SECTION}" block`);
|
||||
const categories = section.blocks.map((block): MissionCategory => ({
|
||||
name: block.name,
|
||||
flags: boolFields(block),
|
||||
missions: stringList(block, 'm'),
|
||||
}));
|
||||
|
||||
const pathByName = missionPathsByLowerName(source.listFiles('mis.vromfs.bin'));
|
||||
const missions: Record<string, MissionHeader> = {};
|
||||
for (const name of categories.flatMap((category) => category.missions)) {
|
||||
if (name in missions) continue;
|
||||
const path = pathByName.get(name.toLowerCase());
|
||||
if (!path) throw new Error(`mission ${name} (${MISSION_LIST}) has no file in mis.vromfs.bin`);
|
||||
missions[name] = readHeader(name, path, source.readBlk('mis.vromfs.bin', path));
|
||||
}
|
||||
return { categories, missions };
|
||||
},
|
||||
};
|
||||
|
||||
function missionPathsByLowerName(paths: readonly string[]): Map<string, string> {
|
||||
const byName = new Map<string, string>();
|
||||
const repeated = new Set<string>();
|
||||
for (const path of paths) {
|
||||
if (!path.startsWith(MISSION_FOLDER) || !path.endsWith('.blk')) continue;
|
||||
const name = path.slice(path.lastIndexOf('/') + 1, -'.blk'.length);
|
||||
if (byName.has(name)) repeated.add(name);
|
||||
byName.set(name, path);
|
||||
}
|
||||
for (const name of repeated) byName.delete(name);
|
||||
return byName;
|
||||
}
|
||||
|
||||
function readHeader(name: string, path: string, document: BlkBlock): MissionHeader {
|
||||
const settings = blockAt(document, 'mission_settings');
|
||||
const mission = blockAt(settings, 'mission');
|
||||
const optional = {
|
||||
level: stringField(mission, 'level'),
|
||||
type: stringField(mission, 'type'),
|
||||
environment: stringField(mission, 'environment'),
|
||||
weather: stringField(mission, 'weather'),
|
||||
countryAxis: stringField(mission, 'country_axis'),
|
||||
countryAllies: stringField(mission, 'country_allies'),
|
||||
timeLimit: numberField(mission, 'timeLimit'),
|
||||
};
|
||||
return {
|
||||
name,
|
||||
path,
|
||||
...Object.fromEntries(Object.entries(optional).filter(([, value]) => value !== undefined)),
|
||||
allowedUnitTypes: boolFields(blockAt(mission, 'allowedUnitTypes')),
|
||||
difficultyOverrides: (mission?.blocks ?? [])
|
||||
.filter((block) => block.name === 'mission')
|
||||
.flatMap((block) => stringField(block, 'difficulty') ?? []),
|
||||
playerSlots: {
|
||||
teamA: stringList(blockAt(settings, 'player'), 'wing').length,
|
||||
teamB: stringList(blockAt(settings, 'player_teamB'), 'wing').length,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Dataset: the countries of the game, in tech-tree order.
|
||||
*
|
||||
* char.vromfs.bin config/shop.blk has one top-level block per country (country_usa, …).
|
||||
* The stock UI builds its own country list the same way (gui.vromfs.bin
|
||||
* scripts/shop/shopCountriesList.nut, updateShopCountriesList).
|
||||
*/
|
||||
import type { Dataset } from './dataset.ts';
|
||||
|
||||
const SHOP = 'config/shop.blk';
|
||||
|
||||
export const shopCountries: Dataset<readonly string[]> = {
|
||||
id: 'shop-countries',
|
||||
version: 1,
|
||||
extract: (source) => source.readBlk('char.vromfs.bin', SHOP).blocks.map((block) => block.name),
|
||||
};
|
||||
Reference in new issue
Block a user