refactor(repo)!: move apps, shared packages, and patch definitions
Everything sat in packages/: two programs next to the small libraries
they use, and the patch data loose at the root. The programs now live in
apps/ and the shared libraries in packages/:
apps/server the local server (was packages/local-service),
package @wto/server
packages/patcher builds the game copy (was packages/build),
package @wto/patcher
patches/exe exe patch definitions (was exe-patches)
patches/gui GUI script patches (was gui-patches)
Inside the server, the network layer folder becomes transport/ so it is
not server/server/, the entry module is server.ts, and startLocalService
and its types become startServer, ServerOptions and RunningServer. The
health answer names the app wto-server, and the TLS files in the data
folder are server.key and server.crt (made again on the next start).
Comments, logs and tool texts say "local server".
The patcher no longer reaches into the server's folder. It read the
default tuning/store.jsonc by a relative path to register bundle GUIDs
for the multi-vehicle packs, which also ignored the player's overrides
in <data>/tuning/. It now takes the pack ids from its caller; the
server exports multiVehiclePackIds(dataFolder), which reads them the way
the running server does. rebuildGuiPack takes the patch folder from its
caller as well.
The development build moves out of the patcher to
scripts/build-game-copy.ts, since it uses both the server and the
patcher. It needs --data (the folder the server will run with) and
defaults the patch folders and the hook library to this repository.
Checked with the root typecheck, check-patches, check-gui,
check-offsets, the native build, a run of build-game-copy.ts into a
scratch folder (12 exe patches, 35 GUI patches, 496 bundle GUIDs as
before) and a server start from apps/server answering wto-server.
BREAKING CHANGE: Use @wto/server and @wto/patcher from the new workspace paths. Run the development build with scripts/build-game-copy.ts and pass --data.
This commit is contained in:
1 parent
9c813ccf7d
commit
930ea07630
476 files changed
+275
-251
No files matched your search
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Rebuild char.vromfs.bin: config/network.blk pointed at the local server, the offline
|
||||
* version's features turned on in config/game_settings.blk, every vehicle shown in the
|
||||
* 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 { 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';
|
||||
import { editPackBlks, readPackBlk } from './pack-edit.ts';
|
||||
import { revealHiddenVehicles, SHOP_PATH } from './tech-tree/reveal-hidden-vehicles.ts';
|
||||
|
||||
export const NETWORK_CONFIG_PATH = 'config/network.blk';
|
||||
|
||||
export interface CharPackResult {
|
||||
readonly pack: Uint8Array;
|
||||
readonly network: NetworkRedirectReport;
|
||||
/** Features that are now on for every player. */
|
||||
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 index was left out. */
|
||||
readonly placeholderDecals: number | undefined;
|
||||
}
|
||||
|
||||
export interface CharPackOptions {
|
||||
/** Store the placeholder decal index (false when the player's own web cache is copied). */
|
||||
readonly placeholderDecals: boolean;
|
||||
}
|
||||
|
||||
export function rebuildCharPack(stockPack: Uint8Array, endpoint: LocalEndpoint, options: CharPackOptions): CharPackResult {
|
||||
let network: NetworkRedirectReport | undefined;
|
||||
let features: string[] = [];
|
||||
let revealedVehicles = 0;
|
||||
const decals = options.placeholderDecals ? offlineDecalIndex(readPackBlk(stockPack, DECALS_CONFIG_PATH)) : undefined;
|
||||
const pack = editPackBlks(stockPack, [
|
||||
{ path: NETWORK_CONFIG_PATH, edit: (root) => { network = redirectNetworkConfig(root, endpoint); } },
|
||||
{ path: GAME_SETTINGS_PATH, edit: (root) => { features = enableFeaturesForEveryone(root, OFFLINE_FEATURES); } },
|
||||
{ path: SHOP_PATH, edit: (root) => { revealedVehicles = revealHiddenVehicles(root); } },
|
||||
], decals?.files ?? []);
|
||||
return { pack, network: network!, features, revealedVehicles, placeholderDecals: decals?.decals };
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* Decal and skin indexes stored in char.vromfs.bin, for a game copy that has no decal source
|
||||
* from the player (player-decal-cache.ts): every decal of the stock list shows one of the
|
||||
* client's built-in decal textures as a placeholder.
|
||||
*
|
||||
* How the client gets its decal list (aces.exe 2.61.0.37):
|
||||
* - webdlcontent init (0xd3bc40) first calls the vromfs index loader (0xd3cc60, also run when
|
||||
* regional.vromfs.bin is mounted, 0x15fe55b). If the setting debug{ dldataAllowVromIndex:b }
|
||||
* (default true) allows it and the mounted packs hold both dldata/downloadable_skins.blk and
|
||||
* dldata/downloadable_decals.blk, it loads them ("vromfs:dldata/downloadable_decals.blk"),
|
||||
* registers the decals (0xd3da50) and returns true; init then skips the download path
|
||||
* (jne 0xd3cc0d). No content hash and no signature is checked on this path.
|
||||
* - Otherwise the client reads dldata_s.info and looks for downloadable_decals.<hash>.blk in
|
||||
* its web cache folder (cache/content/, 0xd3e710 -> 0xd3f610). It does not download the
|
||||
* index there: a missing file leaves the list empty ("dldata: selected existing ...",
|
||||
* "registering 0 decals"), and a file that fails the signature check over its last 0x100
|
||||
* bytes (0xd383e0, "dlData: <%s> signature check failed") is deleted. An index the offline
|
||||
* version makes can only reach the client through the vromfs path.
|
||||
* - Each decal is registered as the managed texture "<lod0>*?<texProps_lod0>" (0xd44fc0). The
|
||||
* texture manager drops everything from the last '?' before the name lookup (DagorEngine
|
||||
* prog/engine/baseUtil/texMetaData.cpp TextureMetaData::decode), so lod0 "star" resolves to
|
||||
* "star*" from content/base/res/decals.dxp.bin. Only if no such texture is registered does
|
||||
* the client create a downloadable one from the hdr0 header (0xd49e00).
|
||||
* - config/decals.blk (char.vromfs.bin) is laid over the index afterwards (0xd48380, not
|
||||
* re-verified) and gives each decal its category, aspect ratio, price, unlock and
|
||||
* marketplace id; the index only adds textures.
|
||||
*/
|
||||
import { emptyBlock, encodeBlk, type BlkBlock } from '@wto/blk';
|
||||
import type { AddedFile } from '../pack-edit.ts';
|
||||
|
||||
export const DECALS_CONFIG_PATH = 'config/decals.blk';
|
||||
export const SKINS_INDEX_PATH = 'dldata/downloadable_skins.blk';
|
||||
export const DECALS_INDEX_PATH = 'dldata/downloadable_decals.blk';
|
||||
|
||||
interface PlaceholderTexture {
|
||||
/** Texture name in content/base/res/decals.dxp.bin (without the trailing '*'). */
|
||||
readonly name: string;
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
}
|
||||
|
||||
/** Built-in decal textures of the stock client (decals.dxp.bin: lang, panther, star). */
|
||||
const SQUARE_PLACEHOLDER: PlaceholderTexture = { name: 'star', width: 512, height: 512 };
|
||||
const WIDE_PLACEHOLDER: PlaceholderTexture = { name: 'panther', width: 512, height: 256 };
|
||||
/** Offline design: decals at least this much wider than tall use the wide placeholder. */
|
||||
const WIDE_ASPECT_RATIO = 1.5;
|
||||
|
||||
/** Dagor ddsx::Header (32 bytes) of an unpacked DXT5 texture, the layout hdr0/hdr1 carry. */
|
||||
const DDSX_HEADER_BYTES = 32;
|
||||
const DDSX_MAGIC = 0x78534444; // "DDSx"
|
||||
const DDSX_DXT5_FOURCC = 0x35545844; // "DXT5"
|
||||
const DDSX_UNPACKED_FLAGS = 0x00000044;
|
||||
const DDSX_QUALITY_WORD = 0x7401;
|
||||
const DXT5_BLOCK_BYTES = 16;
|
||||
|
||||
export interface OfflineDecalIndex {
|
||||
readonly files: readonly AddedFile[];
|
||||
readonly decals: number;
|
||||
}
|
||||
|
||||
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: [],
|
||||
})),
|
||||
};
|
||||
return {
|
||||
files: [
|
||||
{ path: SKINS_INDEX_PATH, content: encodeBlk(emptyBlock()) },
|
||||
{ path: DECALS_INDEX_PATH, content: encodeBlk(index) },
|
||||
],
|
||||
decals: index.blocks.length,
|
||||
};
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
function textureParams(texture: PlaceholderTexture): BlkBlock['params'] {
|
||||
const header = ddsxDxt5Header(texture.width, texture.height);
|
||||
return [
|
||||
{ name: 'hdr0', value: { type: 'string', value: header } },
|
||||
{ name: 'lod0', value: { type: 'string', value: texture.name } },
|
||||
{ name: 'hdr1', value: { type: 'string', value: header } },
|
||||
{ name: 'lod1', value: { type: 'string', value: texture.name } },
|
||||
];
|
||||
}
|
||||
|
||||
/** Base64 of the 32-byte header; read by 0xd49e00 only when the texture is not registered. */
|
||||
function ddsxDxt5Header(width: number, height: number): string {
|
||||
const header = Buffer.alloc(DDSX_HEADER_BYTES);
|
||||
header.writeUInt32LE(DDSX_MAGIC, 0);
|
||||
header.writeUInt32LE(DDSX_DXT5_FOURCC, 4);
|
||||
header.writeUInt32LE(DDSX_UNPACKED_FLAGS, 8);
|
||||
header.writeUInt16LE(width, 12);
|
||||
header.writeUInt16LE(height, 14);
|
||||
let w = width;
|
||||
let h = height;
|
||||
let levels = 0;
|
||||
let memSize = 0;
|
||||
for (;;) {
|
||||
levels += 1;
|
||||
memSize += Math.ceil(w / 4) * Math.ceil(h / 4) * DXT5_BLOCK_BYTES;
|
||||
if (w === 1 && h === 1) break;
|
||||
w = Math.max(1, w >> 1);
|
||||
h = Math.max(1, h >> 1);
|
||||
}
|
||||
header[16] = levels;
|
||||
header.writeUInt16LE(DDSX_QUALITY_WORD, 22);
|
||||
header.writeUInt32LE(memSize, 24);
|
||||
return header.toString('base64');
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* Decals 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), and the build copies it
|
||||
* into the game copy's cache/content. The offline version never looks for that folder itself.
|
||||
*
|
||||
* What the copy gives the client (aces.exe 2.61.0.37):
|
||||
* - cache/content/ is the web cache root ("ContentProvider::init mount=<game>/cache/content/").
|
||||
* - dldata_s.info names the current indexes; when the request for it fails, the client reads
|
||||
* the cached copy ("failed to get dlContent index hashes from %s, will fallback local copy",
|
||||
* 0xd3eb40), and the local server answers that request with 404.
|
||||
* - downloadable_decals.<hash>.blk is the decal index as the CDN served it, with its signature
|
||||
* (0xd383e0 checks it and deletes a file that fails). If the file named by dldata_s.info is
|
||||
* missing, the newest valid downloadable_decals.*.blk in the folder is used (0xd3f610).
|
||||
* - Each decal's texture is fetched through the web cache by its lod0 name (0xd44fc0); the
|
||||
* textures the player's client has cached are in the copied folder (assumed, not verified
|
||||
* against an online cache: the folder layout below httpCache/ was not examined). Textures it
|
||||
* never cached cannot be fetched offline and stay blank.
|
||||
*
|
||||
* With a player source the build leaves the vromfs index (offline-decal-index.ts) out of
|
||||
* char.vromfs.bin, because the client takes the vromfs index first and then skips the web cache.
|
||||
*/
|
||||
import { cpSync, existsSync, readdirSync, statSync } from 'node:fs';
|
||||
import { join, relative, resolve } from 'node:path';
|
||||
|
||||
export const WEB_CACHE_FOLDER = join('cache', 'content');
|
||||
const INDEX_LIST_FILE = 'dldata_s.info';
|
||||
const DECALS_INDEX_FILE = /^downloadable_decals\.[a-z2-7]{32}-[a-z2-7]{1,8}\.blk$/;
|
||||
|
||||
export interface PlayerDecalCache {
|
||||
readonly copiedTo: string;
|
||||
readonly decalIndexes: readonly string[];
|
||||
}
|
||||
|
||||
/** Check that the folder looks like an online client's web cache; returns the problem or undefined. */
|
||||
export function playerDecalCacheProblem(source: string): string | undefined {
|
||||
if (!existsSync(source) || !statSync(source).isDirectory()) return `${source} is not a folder`;
|
||||
if (!existsSync(join(source, INDEX_LIST_FILE))) return `${source} has no ${INDEX_LIST_FILE} (expected the cache/content folder of an online installation)`;
|
||||
if (decalIndexes(source).length === 0) return `${source} has no downloadable_decals.<hash>.blk`;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Copy the player's web cache folder into <copy>/cache/content; the source is only read. */
|
||||
export function copyPlayerDecalCache(source: string, copyFolder: string): PlayerDecalCache {
|
||||
const target = join(copyFolder, WEB_CACHE_FOLDER);
|
||||
const from = resolve(source);
|
||||
const to = resolve(target);
|
||||
if (from === to || !relative(from, to).startsWith('..')) throw new Error(`the decal source ${source} contains the game copy's web cache`);
|
||||
cpSync(from, to, { recursive: true, force: true });
|
||||
return { copiedTo: target, decalIndexes: decalIndexes(source) };
|
||||
}
|
||||
|
||||
function decalIndexes(folder: string): string[] {
|
||||
return readdirSync(folder).filter((name) => DECALS_INDEX_FILE.test(name));
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Patch a copy of aces.exe with every definition under patches/exe/. When any patch cannot be
|
||||
* applied, no executable is produced; the result lists the unavailable patches and the
|
||||
* features they cover.
|
||||
*/
|
||||
import { applyWrites, describePlan, loadPatches, PeImage, planPatches, type PatchPlan } from '@wto/exepatch';
|
||||
|
||||
export interface ExecutableResult {
|
||||
/** The patched executable, or null when some patch was unavailable. */
|
||||
readonly executable: Uint8Array | null;
|
||||
readonly plan: PatchPlan;
|
||||
readonly description: string;
|
||||
}
|
||||
|
||||
export function patchExecutable(stockExecutable: Uint8Array, patchesRoot: string): ExecutableResult {
|
||||
const plan = planPatches(new PeImage(stockExecutable), loadPatches(patchesRoot));
|
||||
const executable = plan.failures.length ? null : applyWrites(stockExecutable, plan.writes);
|
||||
return { executable, plan, description: describePlan(plan) };
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* Game features (feature flags) the offline version turns on for every player.
|
||||
*
|
||||
* char.vromfs.bin config/game_settings.blk lists features as features{ <name>{ condition:t } };
|
||||
* condition:t="" means every player has it (the UI scripts ask with hasFeature, which falls
|
||||
* back to the native local_player_has_feature, scripts/user/features.nut).
|
||||
*
|
||||
* AllowedToSkipBaseTutorials / AllowedToSkipBaseTankTutorials: let the player skip or close
|
||||
* every branch's base tutorial offer. `scripts/tutorials/tutorialsData.nut` gates air and naval
|
||||
* base tutorials on `AllowedToSkipBaseTutorials` and ground base tutorials (`lightTank`,
|
||||
* `lightTank_action`) on `AllowedToSkipBaseTankTutorials`; without both, `NextTutorialHandler`
|
||||
* hides its "do not ask me again" checkbox and close button until the tutorial is started once.
|
||||
*
|
||||
* PaymentMethods: lets scripts/onlineShop/onlinePurchase.nut offer GJN payment directly
|
||||
* inside the Golden Eagles and Premium Account windows (stock game_settings.blk restricts it
|
||||
* with PS4Access; implementation notes).
|
||||
*/
|
||||
import { ensureBlock, setParam, type BlkBlock } from '@wto/blk';
|
||||
|
||||
export const GAME_SETTINGS_PATH = 'config/game_settings.blk';
|
||||
|
||||
export const OFFLINE_FEATURES: readonly string[] = [
|
||||
'AllowedToSkipBaseTutorials',
|
||||
'AllowedToSkipBaseTankTutorials',
|
||||
'PaymentMethods',
|
||||
];
|
||||
|
||||
/** Give every player the features; returns the ones that were not on for everyone before. */
|
||||
export function enableFeaturesForEveryone(gameSettings: BlkBlock, names: readonly string[]): string[] {
|
||||
const features = ensureBlock(gameSettings, 'features');
|
||||
const changed: string[] = [];
|
||||
for (const name of names) {
|
||||
const feature = ensureBlock(features, name);
|
||||
const condition = feature.params.find((param) => param.name === 'condition')?.value;
|
||||
if (condition?.type === 'string' && condition.value === '') continue;
|
||||
setParam(feature, 'condition', { type: 'string', value: '' });
|
||||
changed.push(name);
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Files the build reads from a stock game folder and writes into the game copy, and the
|
||||
* checks that keep it from writing where it must not (working-rules 9: never the Steam
|
||||
* installation, never the folder it reads from).
|
||||
*/
|
||||
import { realpathSync } from 'node:fs';
|
||||
import { join, resolve, sep } from 'node:path';
|
||||
|
||||
export const GAME_FILES = {
|
||||
charPack: 'char.vromfs.bin',
|
||||
mainPack: 'aces.vromfs.bin',
|
||||
guiPack: 'gui.vromfs.bin',
|
||||
executable: join('win64', 'aces.exe'),
|
||||
} as const;
|
||||
|
||||
export function assertWritableCopy(stockFolder: string, copyFolder: string): void {
|
||||
const stock = canonical(stockFolder);
|
||||
const copy = canonical(copyFolder);
|
||||
if (copy === stock) throw new Error('the output folder is the folder the stock files are read from');
|
||||
if (copy.toLowerCase().split(sep).includes('steamapps')) {
|
||||
throw new Error(`refusing to write into a Steam library: ${copy}`);
|
||||
}
|
||||
}
|
||||
|
||||
function canonical(folder: string): string {
|
||||
try {
|
||||
return realpathSync(folder);
|
||||
} catch {
|
||||
return resolve(folder);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* Rebuild gui.vromfs.bin by applying the script patch definitions in `patches/gui/`
|
||||
* (implementation notes, format in gui-patch-definition.ts).
|
||||
*
|
||||
* Every edit must find its stock text exactly once in the current script; anything else
|
||||
* refuses the whole build rather than writing a half-patched archive.
|
||||
*/
|
||||
import { getFile, putFile, readArchive, writeArchive } from '@wto/vromfs';
|
||||
import { loadGuiPatches, type GuiScriptPatch } from './gui-patch-definition.ts';
|
||||
import type { LocalEndpoint } from './network/local-endpoint.ts';
|
||||
|
||||
const ENDPOINT_PLACEHOLDER = '{{LOCAL_ENDPOINT}}';
|
||||
|
||||
export interface GuiPackResult {
|
||||
readonly pack: Uint8Array;
|
||||
readonly applied: readonly GuiScriptPatch[];
|
||||
}
|
||||
|
||||
export function rebuildGuiPack(
|
||||
stockPack: Uint8Array,
|
||||
endpoint: LocalEndpoint,
|
||||
patchesFolder: string,
|
||||
): GuiPackResult {
|
||||
const patches = loadGuiPatches(patchesFolder);
|
||||
const archive = readArchive(stockPack);
|
||||
const hostPortText = `${endpoint.host}:${endpoint.port}`;
|
||||
|
||||
for (const patch of patches) {
|
||||
let current = Buffer.from(getFile(archive, patch.file)).toString('utf8');
|
||||
const newline = current.includes('\r\n') ? '\r\n' : '\n';
|
||||
for (const [index, edit] of patch.edits.entries()) {
|
||||
const replace = edit.replace.replaceAll('\n', newline).replaceAll(ENDPOINT_PLACEHOLDER, hostPortText);
|
||||
current = replaceUnique(current, edit.find, replace, `GUI patch ${patch.id} edit ${index + 1} in ${patch.file}`);
|
||||
}
|
||||
putFile(archive, patch.file, Buffer.from(current, 'utf8'));
|
||||
}
|
||||
|
||||
return {
|
||||
pack: writeArchive(archive),
|
||||
applied: patches,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the single occurrence of `find` (written with `\n` line endings) in `text`, treating
|
||||
* `\r\n` and `\n` in the script as the same line break; stock scripts mix both. Only the matched
|
||||
* span changes, every other byte of the script is kept.
|
||||
*/
|
||||
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 Error(`${label}: stock text not found; refusing to write`);
|
||||
if (normalized.indexOf(find, first + find.length) !== -1) throw new Error(`${label}: stock text appears more than once; refusing to write`);
|
||||
return text.slice(0, original[first]!) + replace + text.slice(original[first + find.length]!);
|
||||
}
|
||||
|
||||
/**
|
||||
* `text` with `\r\n` turned into `\n`, and for every normalized index the index in `text` where
|
||||
* that character's original sequence starts (a `\r\n` maps to its `\r`).
|
||||
*/
|
||||
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 };
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* GUI script patch definitions as stored on disk, one folder per change under
|
||||
* `patches/gui/<domain>/<name>/`:
|
||||
*
|
||||
* patch.jsonc id, title, target script, features, the game versions it was verified on,
|
||||
* and the list of edits; comments explain what the change does and why the
|
||||
* local server cannot provide it
|
||||
* <name>.nut the edit fragments named by `edits` (stock text to find, text to put there)
|
||||
*
|
||||
* Fragment files hold the exact script text followed by one terminating newline, which is not
|
||||
* part of the fragment. Line endings are normalised to `\n` here; applying matches regardless of
|
||||
* the script's line endings (stock scripts mix `\r\n` and `\n`), so fragments survive editors
|
||||
* and git newline conversion.
|
||||
*/
|
||||
import { readdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { parseJsonc } from '@wto/jsonc';
|
||||
|
||||
const PATCH_FILE = 'patch.jsonc';
|
||||
const ALLOWED_KEYS = new Set(['id', 'title', 'file', 'features', 'verified_on', 'edits']);
|
||||
|
||||
export interface GuiScriptEdit {
|
||||
/** Stock text that must occur exactly once in the target script, with `\n` line endings. */
|
||||
readonly find: string;
|
||||
/** Text written in its place, with `\n` line endings. */
|
||||
readonly replace: string;
|
||||
}
|
||||
|
||||
export interface GuiScriptPatch {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
/** Script path inside gui.vromfs.bin. */
|
||||
readonly file: string;
|
||||
readonly features: readonly string[];
|
||||
readonly verifiedOn: readonly string[];
|
||||
readonly edits: readonly GuiScriptEdit[];
|
||||
readonly directory: string;
|
||||
}
|
||||
|
||||
/** Every definition under `root`, sorted by id. */
|
||||
export function loadGuiPatches(root: string): readonly GuiScriptPatch[] {
|
||||
const patches = findDefinitionDirectories(root).map(readDefinition);
|
||||
rejectDuplicateIds(patches);
|
||||
return patches.sort((left, right) => left.id.localeCompare(right.id));
|
||||
}
|
||||
|
||||
function findDefinitionDirectories(root: string): string[] {
|
||||
const found: string[] = [];
|
||||
for (const entry of readdirSync(root, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
const directory = join(root, entry.name);
|
||||
if (isFile(join(directory, PATCH_FILE))) found.push(directory);
|
||||
else found.push(...findDefinitionDirectories(directory));
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
function readDefinition(directory: string): GuiScriptPatch {
|
||||
const where = join(directory, PATCH_FILE);
|
||||
const raw = readObject(where);
|
||||
const unknown = Object.keys(raw).filter((key) => !ALLOWED_KEYS.has(key));
|
||||
if (unknown.length) {
|
||||
throw new Error(`${where}: unknown key(s) ${unknown.join(', ')}; explanations belong in comments or the patch notes`);
|
||||
}
|
||||
return {
|
||||
id: requiredString(raw.id, where, 'id'),
|
||||
title: requiredString(raw.title, where, 'title'),
|
||||
file: requiredString(raw.file, where, 'file'),
|
||||
features: stringList(raw.features, where, 'features'),
|
||||
verifiedOn: nonEmptyStringList(raw.verified_on, where, 'verified_on'),
|
||||
edits: readEdits(raw.edits, directory, where),
|
||||
directory,
|
||||
};
|
||||
}
|
||||
|
||||
function readEdits(value: unknown, directory: string, where: string): GuiScriptEdit[] {
|
||||
if (!Array.isArray(value) || value.length === 0) throw new Error(`${where}: "edits" must be a non-empty list`);
|
||||
return value.map((item, index) => {
|
||||
if (!item || typeof item !== 'object') throw new Error(`${where}: edits[${index}] must be an object`);
|
||||
const edit = item as Record<string, unknown>;
|
||||
const find = readFragment(directory, requiredString(edit.find, where, `edits[${index}].find`));
|
||||
if (find === '') throw new Error(`${where}: edits[${index}].find is empty`);
|
||||
const replace = readFragment(directory, requiredString(edit.replace, where, `edits[${index}].replace`));
|
||||
return { find, replace };
|
||||
});
|
||||
}
|
||||
|
||||
/** Fragment text with `\n` line endings and the file's terminating newline removed. */
|
||||
export function readFragment(directory: string, name: string): string {
|
||||
if (name.includes('/') || name.includes('\\')) throw new Error(`${directory}: fragment "${name}" must be a file in the patch folder`);
|
||||
const text = readFileSync(join(directory, name), 'utf8').replace(/^/, '').replace(/\r\n/g, '\n');
|
||||
return text.endsWith('\n') ? text.slice(0, -1) : text;
|
||||
}
|
||||
|
||||
function readObject(path: string): Record<string, unknown> {
|
||||
let data: unknown;
|
||||
try {
|
||||
data = parseJsonc(readFileSync(path, 'utf8'));
|
||||
} catch (error) {
|
||||
throw new Error(`${path}: ${(error as Error).message}`);
|
||||
}
|
||||
if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error(`${path}: expected an object`);
|
||||
return data as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function requiredString(value: unknown, where: string, key: string): string {
|
||||
if (typeof value !== 'string' || value === '') throw new Error(`${where}: "${key}" must be a non-empty string`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function stringList(value: unknown, where: string, key: string): string[] {
|
||||
if (value === undefined) return [];
|
||||
if (!Array.isArray(value) || !value.every((item) => typeof item === 'string')) {
|
||||
throw new Error(`${where}: "${key}" must be a list of strings`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function nonEmptyStringList(value: unknown, where: string, key: string): string[] {
|
||||
const list = stringList(value, where, key);
|
||||
if (list.length === 0) throw new Error(`${where}: "${key}" must name at least one game version`);
|
||||
return list;
|
||||
}
|
||||
|
||||
function rejectDuplicateIds(patches: readonly GuiScriptPatch[]): void {
|
||||
const seen = new Map<string, string>();
|
||||
for (const patch of patches) {
|
||||
const previous = seen.get(patch.id);
|
||||
if (previous) throw new Error(`two GUI patches use id "${patch.id}": ${previous} and ${patch.directory}`);
|
||||
seen.set(patch.id, patch.directory);
|
||||
}
|
||||
}
|
||||
|
||||
function isFile(path: string): boolean {
|
||||
try {
|
||||
return statSync(path).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* The patcher: builds the game copy by pointing the client at the local server
|
||||
* and patching the executable. Used by the development script scripts/build-game-copy.ts and by
|
||||
* the launcher. The patch definitions and the network hook library are given by the caller.
|
||||
*/
|
||||
export { NETWORK_CONFIG_PATH, rebuildCharPack, type CharPackResult } from './char-pack.ts';
|
||||
export { copyPlayerDecalCache, playerDecalCacheProblem } from './decals/player-decal-cache.ts';
|
||||
export { patchExecutable, type ExecutableResult } from './executable.ts';
|
||||
export { assertWritableCopy, GAME_FILES } from './game-copy.ts';
|
||||
export { rebuildGuiPack, type GuiPackResult } from './gui-pack.ts';
|
||||
export { loadGuiPatches, type GuiScriptEdit, type GuiScriptPatch } from './gui-patch-definition.ts';
|
||||
export { ENGINE_SETTINGS_PATH, EXTRA_STORE_BUNDLE_GUID_MAP, EXTRA_STORE_BUNDLE_GUIDS, rebuildMainPack, type MainPackResult } from './main-pack.ts';
|
||||
export { redirectAddresses, type AddressChange } from './network/address-rewrite.ts';
|
||||
export { hostPort, localEndpoint, localUrl, type LocalEndpoint } from './network/local-endpoint.ts';
|
||||
export { NETWORK_HOOK_LIBRARY, networkHookSettings } from './network/network-hook.ts';
|
||||
export { redirectNetworkConfig, type NetworkRedirectReport } from './network/redirect-network-config.ts';
|
||||
export { offlinePackBundleGuids } from './store/offline-bundles.ts';
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Rebuild aces.vromfs.bin with the engine settings' server addresses pointed at the local
|
||||
* service.
|
||||
*
|
||||
* config/settings.blk, block `network`: publicConfigsUrl and publicConfigsUrls are where the
|
||||
* engine's public-configs module downloads files at startup, including a signed network.blk
|
||||
* that would replace the one in char.vromfs.bin (DagorEngine prog/gameLibs/publicConfigs/
|
||||
* publicConfigs.cpp, init). On a machine with internet access the download would succeed and
|
||||
* point the game back at Gaijin's servers. Redirected, the request reaches the local server;
|
||||
* it has no such file, so the game keeps the network.blk of char.vromfs.bin.
|
||||
*
|
||||
* Only the `network` block is touched: the rest of settings.blk is engine configuration, not
|
||||
* server addresses.
|
||||
*/
|
||||
import { ensureBlock, findBlock, setParam, type BlkBlock } from '@wto/blk';
|
||||
import { redirectAddresses, type AddressChange } from './network/address-rewrite.ts';
|
||||
import type { LocalEndpoint } from './network/local-endpoint.ts';
|
||||
import { editPackBlks } from './pack-edit.ts';
|
||||
|
||||
export const ENGINE_SETTINGS_PATH = 'config/settings.blk';
|
||||
export const GUI_CONFIG_PATH = 'config/gui.blk';
|
||||
const NETWORK_BLOCK = 'network';
|
||||
|
||||
/**
|
||||
* GUIDs added to config/gui.blk bundles/guid so scripts/onlineShop/entitlementsInfo.nut
|
||||
* requests GJN prices for GJN-priced Premium Account tiers alongside the stock eagles* packs
|
||||
*.
|
||||
*/
|
||||
export const EXTRA_STORE_BUNDLE_GUIDS: ReadonlyArray<readonly [entitlement: string, guid: string]> = [
|
||||
['wto_prem_20d', 'A1E00020-5754-4F46-8F00-000000000020'],
|
||||
['wto_prem_60d', 'A1E00060-5754-4F46-8F00-000000000060'],
|
||||
['wto_prem_180d', 'A1E00180-5754-4F46-8F00-000000000180'],
|
||||
];
|
||||
|
||||
export const EXTRA_STORE_BUNDLE_GUID_MAP: Readonly<Record<string, string>> = Object.fromEntries(EXTRA_STORE_BUNDLE_GUIDS);
|
||||
|
||||
export interface MainPackResult {
|
||||
readonly pack: Uint8Array;
|
||||
readonly addresses: readonly AddressChange[];
|
||||
}
|
||||
|
||||
export function rebuildMainPack(
|
||||
stockPack: Uint8Array,
|
||||
endpoint: LocalEndpoint,
|
||||
extraBundles: ReadonlyArray<readonly [string, string]> = [],
|
||||
): MainPackResult {
|
||||
let addresses: AddressChange[] = [];
|
||||
const pack = editPackBlks(stockPack, [
|
||||
{
|
||||
path: ENGINE_SETTINGS_PATH,
|
||||
edit: (root) => {
|
||||
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]);
|
||||
},
|
||||
},
|
||||
{
|
||||
path: GUI_CONFIG_PATH,
|
||||
edit: (root) => registerStoreBundleGuids(root, [...EXTRA_STORE_BUNDLE_GUIDS, ...extraBundles]),
|
||||
},
|
||||
]);
|
||||
return { pack, addresses };
|
||||
}
|
||||
|
||||
function registerStoreBundleGuids(guiRoot: BlkBlock, bundles: ReadonlyArray<readonly [string, string]>): void {
|
||||
const guidBlock = ensureBlock(ensureBlock(guiRoot, 'bundles'), 'guid');
|
||||
for (const [entitlement, guid] of bundles) {
|
||||
setParam(guidBlock, entitlement, { type: 'string', value: guid });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* Rewrite one configuration string that names a Gaijin server so that it names the local
|
||||
* service instead. Only values that clearly are server addresses are touched:
|
||||
*
|
||||
* http(s)://host[:port]/path -> http://127.0.0.1:<port>/host/path (host is a Gaijin domain or an external IP)
|
||||
* ws(s)://host[:port]/path -> ws://127.0.0.1:<port>/host/path
|
||||
* host:port -> 127.0.0.1:<port> (raw TCP endpoints: matching, chat)
|
||||
*
|
||||
* Bare Gaijin host names without a port (e.g. the event log host) are left as they are so the
|
||||
* client keeps their Host header and SNI; wto_ws.dll resolves them locally and sends their
|
||||
* connections to the local server port. Everything else (file patterns,
|
||||
* placeholders such as "https://not.used", DNS server IPs) is also left as it is.
|
||||
*/
|
||||
import { visitParams, type BlkBlock } from '@wto/blk';
|
||||
import { hostPort, localUrl, type LocalEndpoint } from './local-endpoint.ts';
|
||||
|
||||
export interface AddressChange {
|
||||
readonly path: string;
|
||||
readonly before: string;
|
||||
readonly after: string;
|
||||
}
|
||||
|
||||
/** Rewrite every server address among the string parameters of `root`, in place. */
|
||||
export function redirectAddresses(root: BlkBlock, endpoint: LocalEndpoint, pathPrefix: readonly string[] = []): AddressChange[] {
|
||||
const changes: AddressChange[] = [];
|
||||
visitParams(root, (param, path) => {
|
||||
if (param.value.type !== 'string') return;
|
||||
const rewritten = rewriteAddress(param.value.value, endpoint);
|
||||
if (rewritten === null || rewritten === param.value.value) return;
|
||||
changes.push({ path: [...pathPrefix, ...path, param.name].join('/'), before: param.value.value, after: rewritten });
|
||||
param.value = { type: 'string', value: rewritten };
|
||||
});
|
||||
return changes;
|
||||
}
|
||||
|
||||
/** gaijin.ops is Gaijin's internal domain, used by the internal test environments. */
|
||||
const GAIJIN_DOMAINS = ['gaijin.net', 'gaijinent.com', 'warthunder.com', 'gaijin.ops'];
|
||||
const URL_PATTERN = /^(https?|wss?):\/\/([^/:?#]+)(?::\d+)?([/?#].*)?$/i;
|
||||
const HOST_PORT_PATTERN = /^([a-z0-9.-]+):(\d{1,5})$/i;
|
||||
const IPV4_PATTERN = /^\d{1,3}(?:\.\d{1,3}){3}$/;
|
||||
|
||||
export function rewriteAddress(value: string, endpoint: LocalEndpoint): string | null {
|
||||
const url = URL_PATTERN.exec(value);
|
||||
if (url) {
|
||||
const host = url[2]!.toLowerCase();
|
||||
const scheme = url[1]!.toLowerCase().startsWith('ws') ? 'ws' : 'http';
|
||||
return isServerHost(host) ? localUrl(endpoint, host, url[3] ?? '/', scheme) : null;
|
||||
}
|
||||
const hostAndPort = HOST_PORT_PATTERN.exec(value);
|
||||
if (hostAndPort) return isServerHost(hostAndPort[1]!.toLowerCase()) ? hostPort(endpoint) : null;
|
||||
return null;
|
||||
}
|
||||
|
||||
function isServerHost(host: string): boolean {
|
||||
return isGaijinDomain(host) || (IPV4_PATTERN.test(host) && !host.startsWith('127.'));
|
||||
}
|
||||
|
||||
function isGaijinDomain(host: string): boolean {
|
||||
return GAIJIN_DOMAINS.some((domain) => host === domain || host.endsWith(`.${domain}`));
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/** Where the local server listens. The port is chosen at every launch. */
|
||||
export interface LocalEndpoint {
|
||||
readonly host: string;
|
||||
readonly port: number;
|
||||
}
|
||||
|
||||
export const LOOPBACK = '127.0.0.1';
|
||||
|
||||
export function localEndpoint(port: number): LocalEndpoint {
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new RangeError(`port must be an integer from 1 to 65535, got ${port}`);
|
||||
return { host: LOOPBACK, port };
|
||||
}
|
||||
|
||||
/** `host:port` of the local server. */
|
||||
export function hostPort(endpoint: LocalEndpoint): string {
|
||||
return `${endpoint.host}:${endpoint.port}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Local URL standing in for a Gaijin URL. The original host becomes the first path segment,
|
||||
* so the local server can tell which Gaijin service a request was meant for even when two
|
||||
* services use the same path (char and inventory both use "/char").
|
||||
*/
|
||||
export function localUrl(endpoint: LocalEndpoint, originalHost: string, originalPath: string, scheme: 'http' | 'ws' = 'http'): string {
|
||||
const path = originalPath.startsWith('/') ? originalPath : `/${originalPath}`;
|
||||
return `${scheme}://${hostPort(endpoint)}/${originalHost}${path}`;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Settings of an environment block's `yuplay` sub-block, which the game hands to its login
|
||||
* component.
|
||||
*
|
||||
* The URL keys get a local URL built from the login component's default address for that
|
||||
* key, so the local server sees which login request was meant. Only `loginURL`'s default is
|
||||
* certain (https://auth.gaijinent.com/login.php); the others are matched by name to the
|
||||
* addresses in the executable's string table.
|
||||
*
|
||||
* The host-only keys (authHost, ssoHost, storeApiHost, authFallbackHost) and `fallbackIP` are
|
||||
* intentionally not set: the host keys replace only the host name while keeping port 443, and
|
||||
* `fallbackIP` (yu_init.cpp) substitutes a bare IP literal on port 443 when DNS fails — both
|
||||
* strip the original Host/SNI domain and bypass wto_ws.dll's DNS-based routing. Leaving the
|
||||
* Gaijin host names in place lets wto_ws.dll resolve them to 127.0.0.2 and route their TLS
|
||||
* connections to the local server port with the original Host and SNI intact.
|
||||
*/
|
||||
import { localUrl, type LocalEndpoint } from './local-endpoint.ts';
|
||||
|
||||
const URL_DEFAULTS: ReadonlyArray<readonly [key: string, host: string, path: string]> = [
|
||||
['loginURL', 'auth.gaijinent.com', '/login.php'],
|
||||
['tagUserURL', 'auth.gaijinent.com', '/tag.php'],
|
||||
['userStokenURL', 'api.gaijinent.com', '/user_stoken.php'],
|
||||
['stokenLoginURL', 'api.gaijinent.com', '/login_stoken.php'],
|
||||
['versionURL', 'yupmaster.gaijinent.com', '/yuitem/get_version.php'],
|
||||
['yupURL', 'yupmaster.gaijinent.com', '/yuitem/get_yup.php'],
|
||||
];
|
||||
|
||||
export function loginOverrides(endpoint: LocalEndpoint): ReadonlyArray<readonly [key: string, value: string]> {
|
||||
return URL_DEFAULTS.map(([key, host, path]) => [key, localUrl(endpoint, host, path)] as const);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* The network hook library in the game copy: the exe patch
|
||||
* online/network-hook-library makes aces.exe load win64/wto_ws.dll, which reads the local
|
||||
* service port from win64/wto_ws.cfg. Both files are written next to the executable; the DLL is
|
||||
* built from native/wto-net (build.ps1).
|
||||
*/
|
||||
import type { LocalEndpoint } from './local-endpoint.ts';
|
||||
|
||||
export const NETWORK_HOOK_LIBRARY = 'wto_ws.dll';
|
||||
const SETTINGS = 'wto_ws.cfg';
|
||||
|
||||
export function networkHookSettings(endpoint: LocalEndpoint): { name: string; content: Uint8Array } {
|
||||
return { name: SETTINGS, content: new TextEncoder().encode(`port=${endpoint.port}\n`) };
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Point config/network.blk at the local server.
|
||||
*
|
||||
* The environment names stay as they are: the stock scripts branch on the environment name
|
||||
* (for example on whether it contains "production"), so renaming it would change client
|
||||
* behaviour. Instead:
|
||||
* - every server address in the file is rewritten to the local server (address-rewrite.ts);
|
||||
* - every environment block (a block with `charServer` entries) gets certificate checking
|
||||
* turned off and its login component settings pointed at the local server.
|
||||
*/
|
||||
import { ensureBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
|
||||
import { redirectAddresses, type AddressChange } from './address-rewrite.ts';
|
||||
import type { LocalEndpoint } from './local-endpoint.ts';
|
||||
import { loginOverrides } from './login-overrides.ts';
|
||||
|
||||
export interface NetworkRedirectReport {
|
||||
readonly environments: readonly string[];
|
||||
readonly addresses: readonly AddressChange[];
|
||||
}
|
||||
|
||||
export function redirectNetworkConfig(root: BlkBlock, endpoint: LocalEndpoint): NetworkRedirectReport {
|
||||
const addresses = redirectAddresses(root, endpoint);
|
||||
const environments = root.blocks.filter((block) => findParam(block, 'charServer'));
|
||||
for (const environment of environments) configureEnvironment(environment, endpoint);
|
||||
return { environments: environments.map((block) => block.name), addresses };
|
||||
}
|
||||
|
||||
function configureEnvironment(environment: BlkBlock, endpoint: LocalEndpoint): void {
|
||||
setParam(environment, 'enableSslCertCheck', { type: 'bool', value: false });
|
||||
// The local store page. The stock value carries URL tags; here only
|
||||
// auto_local, so scripts/onlineShop/url.nut adds ?skin_lang=<game language> and opens it in
|
||||
// the built-in browser. No auto_login: that goes through Gaijin's login.gaijin.net.
|
||||
setParam(environment, 'webstoreURL', { type: 'string', value: `auto_local http://${endpoint.host}:${endpoint.port}/store` });
|
||||
const login = ensureBlock(environment, 'yuplay');
|
||||
for (const [key, value] of loginOverrides(endpoint)) setParam(login, key, { type: 'string', value });
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Rebuild a data pack with some of its BLK documents edited and, optionally, new files added.
|
||||
* Every other file of the pack is kept byte for byte. Edited documents are stored self-contained (they no longer depend on
|
||||
* the pack's shared name map), which the game accepts in every loading mode
|
||||
*.
|
||||
*/
|
||||
import { decodeBlk, encodeBlk, parseSharedNameMap, type BlkBlock } from '@wto/blk';
|
||||
import { getFile, NAME_MAP_PATH, putFile, readArchive, writeArchive, type Archive } from '@wto/vromfs';
|
||||
|
||||
export interface PackEditResult<T> {
|
||||
readonly pack: Uint8Array;
|
||||
readonly report: T;
|
||||
}
|
||||
|
||||
/** One BLK document of the pack and the change to make to it. */
|
||||
export interface BlkEdit {
|
||||
readonly path: string;
|
||||
readonly edit: (root: BlkBlock) => void;
|
||||
}
|
||||
|
||||
export function editPackBlk<T>(stockPack: Uint8Array, blkPath: string, edit: (root: BlkBlock) => T): PackEditResult<T> {
|
||||
let report: T | undefined;
|
||||
const pack = editPackBlks(stockPack, [{ path: blkPath, edit: (root) => { report = edit(root); } }]);
|
||||
return { pack, report: report as T };
|
||||
}
|
||||
|
||||
/** A file the stock pack does not have, stored as is. */
|
||||
export interface AddedFile {
|
||||
readonly path: string;
|
||||
readonly content: Uint8Array;
|
||||
}
|
||||
|
||||
export function editPackBlks(stockPack: Uint8Array, edits: readonly BlkEdit[], added: readonly AddedFile[] = []): Uint8Array {
|
||||
const archive = readArchive(stockPack);
|
||||
const dictionary = findDictionary(archive);
|
||||
const names = archive.files.has(NAME_MAP_PATH) ? parseSharedNameMap(getFile(archive, NAME_MAP_PATH), dictionary).names : [];
|
||||
for (const { path, edit } of edits) {
|
||||
const root = decodeBlk(getFile(archive, path), { names, dictionary });
|
||||
edit(root);
|
||||
putFile(archive, path, encodeBlk(root));
|
||||
}
|
||||
for (const file of added) {
|
||||
if (archive.files.has(file.path)) throw new Error(`the data pack already has ${file.path}`);
|
||||
putFile(archive, file.path, file.content);
|
||||
}
|
||||
return writeArchive(archive);
|
||||
}
|
||||
|
||||
/** Read one BLK document of a pack without changing anything. */
|
||||
export function readPackBlk(stockPack: Uint8Array, path: string): BlkBlock {
|
||||
const archive = readArchive(stockPack);
|
||||
const dictionary = findDictionary(archive);
|
||||
const names = archive.files.has(NAME_MAP_PATH) ? parseSharedNameMap(getFile(archive, NAME_MAP_PATH), dictionary).names : [];
|
||||
return decodeBlk(getFile(archive, path), { names, dictionary });
|
||||
}
|
||||
|
||||
/** The pack's zstd dictionary, if it has one. */
|
||||
function findDictionary(archive: Archive): Uint8Array | undefined {
|
||||
const dictionaries = [...archive.files.keys()].filter((path) => path.endsWith('.dict'));
|
||||
if (dictionaries.length > 1) throw new Error(`the data pack has several zstd dictionaries: ${dictionaries.join(', ')}`);
|
||||
return dictionaries.length ? archive.files.get(dictionaries[0]!) : undefined;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Offline store bundle GUIDs for config/gui.blk `bundles/guid`.
|
||||
*
|
||||
* The game opens a gift vehicle's own store page only when `getBundleId(<entitlement>)` finds a
|
||||
* GUID for it (scripts/onlineShop/onlineShopModel.nut showUnitGoods → doBrowserPurchaseByGuid);
|
||||
* the URL then comes from the local server's item_info.php `url` field. Every vehicle carrying
|
||||
* `gift` in char.vromfs.bin config/wpcost.blk gets `stableGuid(wto_pack_<vehicle>)`, and every
|
||||
* multi-vehicle pack the local server sells gets `stableGuid(<pack id>)`; the caller gives those
|
||||
* ids, as the server reads them for the same data folder. Entries the store does not sell are
|
||||
* never looked up, so registering extra ones is harmless.
|
||||
*/
|
||||
import { singleVehiclePackId, stableGuid, type BlkBlock } from '@wto/blk';
|
||||
import { readPackBlk } from '../pack-edit.ts';
|
||||
|
||||
export const WPCOST_PATH = 'config/wpcost.blk';
|
||||
|
||||
export function offlinePackBundleGuids(charPack: Uint8Array, multiVehiclePackIds: readonly string[]): Array<readonly [string, string]> {
|
||||
const ids = new Set<string>(multiVehiclePackIds);
|
||||
for (const vehicle of giftVehicles(readPackBlk(charPack, WPCOST_PATH))) ids.add(singleVehiclePackId(vehicle));
|
||||
return [...ids].sort().map((id) => [id, stableGuid(id)] as const);
|
||||
}
|
||||
|
||||
function giftVehicles(wpcost: BlkBlock): string[] {
|
||||
return wpcost.blocks.filter((unit) => unit.params.some((param) => param.name === 'gift')).map((unit) => unit.name);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Show the tech-tree vehicles the live game hides until they are researched or on sale (user
|
||||
* quote 98: e.g. the German Maus and Panther II).
|
||||
*
|
||||
* char.vromfs.bin config/shop.blk: country -> branch -> column -> vehicle (grouped vehicles one
|
||||
* level deeper). The stock UI hides a vehicle (gui.vromfs.bin scripts/unit/unit.nut
|
||||
* isVisibleInShop) when its entry has
|
||||
* showOnlyWhenResearch:b until the player researches it (2.61.0.37: 22
|
||||
* vehicles, among them the Maus and the Panther II)
|
||||
* showOnlyWhenAvailableForPurchase:b except while a promotion sells it (74 premium vehicles)
|
||||
* showOnlyWhenBought:b unless the player owns it (208)
|
||||
* The first two are removed, so the stock rule shows those vehicles.
|
||||
*
|
||||
* showOnlyWhenBought stays: it marks vehicles that are not part of the tree for anyone who has
|
||||
* 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).
|
||||
*/
|
||||
import type { BlkBlock } from '@wto/blk';
|
||||
|
||||
export const SHOP_PATH = 'config/shop.blk';
|
||||
|
||||
const HIDING_FLAGS = new Set(['showOnlyWhenResearch', 'showOnlyWhenAvailableForPurchase']);
|
||||
|
||||
/** Remove the hiding flags in place; returns how many vehicles were hidden before. */
|
||||
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;
|
||||
entry.params = kept;
|
||||
revealed++;
|
||||
}
|
||||
return revealed;
|
||||
}
|
||||
|
||||
/** Every block below the countries: branches, columns, groups and vehicles. */
|
||||
function shopEntries(shop: BlkBlock): BlkBlock[] {
|
||||
const entries: BlkBlock[] = [];
|
||||
const walk = (block: BlkBlock): void => {
|
||||
for (const entry of block.blocks) {
|
||||
entries.push(entry);
|
||||
walk(entry);
|
||||
}
|
||||
};
|
||||
for (const country of shop.blocks) walk(country);
|
||||
return entries;
|
||||
}
|
||||
Reference in new issue
Block a user