feat(saves): import official game backups
This commit is contained in:
1 parent
2e3cc0aaec
commit
597df6b4f5
15 files changed
+661
-16
No files matched your search
@@ -7,5 +7,6 @@ export { AccountStore, type RegistrationResult } from './accounts/account-store.
|
||||
export { REGISTRATION_PATH } from './accounts/registration-service.ts';
|
||||
export { HEALTH_PATH } from './transport/http-listener.ts';
|
||||
export { editSaveCurrencies, listSaveSummaries, readSaveDetails } from './saves/save-editor.ts';
|
||||
export { importOfficialBackup, previewOfficialBackup } from './saves/import/official-backup.ts';
|
||||
export { prepareTransferredProfile } from './saves/transferred-profile.ts';
|
||||
export { multiVehiclePackIds } from './store/store-pack-ids.ts';
|
||||
@@ -0,0 +1,194 @@
|
||||
import { decodeBlk, emptyBlock, type BlkBlock, type BlkValue } from '@wto/blk';
|
||||
|
||||
/**
|
||||
* Parse the self-contained BLK documents exported by the game. The official Dagor text format
|
||||
* and the existing binary encoder use the same typed values and repeated names.
|
||||
*/
|
||||
export function readBackupBlk(bytes: Uint8Array): BlkBlock {
|
||||
try {
|
||||
return decodeBlk(bytes);
|
||||
} catch {
|
||||
const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
||||
return new TextBlock(text).read();
|
||||
}
|
||||
}
|
||||
|
||||
class TextBlock {
|
||||
readonly #text: string;
|
||||
#at = 0;
|
||||
|
||||
constructor(text: string) {
|
||||
this.#text = text;
|
||||
}
|
||||
|
||||
read(): BlkBlock {
|
||||
return this.#block('', 0);
|
||||
}
|
||||
|
||||
#block(name: string, depth: number): BlkBlock {
|
||||
if (depth > 128) this.#fail('Block nesting is too deep');
|
||||
const result = emptyBlock(name);
|
||||
for (;;) {
|
||||
this.#space();
|
||||
if (depth > 0 && this.#take('}')) return result;
|
||||
if (this.#at === this.#text.length) {
|
||||
if (depth > 0) this.#fail('Unclosed block');
|
||||
return result;
|
||||
}
|
||||
const key = this.#word();
|
||||
if (this.#take('{')) {
|
||||
result.blocks.push(this.#block(key, depth + 1));
|
||||
} else {
|
||||
this.#expect(':');
|
||||
const type = this.#word();
|
||||
const array = this.#take('[');
|
||||
if (array) this.#expect(']');
|
||||
this.#expect('=');
|
||||
if (array) {
|
||||
this.#expect('[');
|
||||
if (this.#take(']')) continue;
|
||||
do {
|
||||
result.params.push({ name: key, value: this.#value(type) });
|
||||
} while (this.#take(','));
|
||||
this.#expect(']');
|
||||
} else {
|
||||
result.params.push({ name: key, value: this.#value(type) });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#value(type: string): BlkValue {
|
||||
switch (type) {
|
||||
case 't': return { type: 'string', value: this.#word() };
|
||||
case 'i': return { type: 'int', value: this.#int() };
|
||||
case 'i64': return { type: 'int64', value: this.#integer(64) };
|
||||
case 'r': return { type: 'real', value: this.#real() };
|
||||
case 'b': {
|
||||
const literal = this.#word().toLowerCase();
|
||||
if (['true', 'yes', 'on', '1'].includes(literal)) return { type: 'bool', value: true };
|
||||
if (['false', 'no', 'off', '0'].includes(literal)) return { type: 'bool', value: false };
|
||||
return this.#fail('Invalid Boolean');
|
||||
}
|
||||
case 'p2': return { type: 'point2', value: [this.#real(), this.#realAfterComma()] };
|
||||
case 'p3': return { type: 'point3', value: this.#row() };
|
||||
case 'p4': return { type: 'point4', value: [...this.#row(), this.#realAfterComma()] };
|
||||
case 'ip2': return { type: 'ipoint2', value: [this.#int(), this.#intAfterComma()] };
|
||||
case 'ip3': return { type: 'ipoint3', value: [this.#int(), this.#intAfterComma(), this.#intAfterComma()] };
|
||||
case 'ip4': return { type: 'ipoint4', value: [this.#int(), this.#intAfterComma(), this.#intAfterComma(), this.#intAfterComma()] };
|
||||
case 'c': {
|
||||
const [r, g, b] = [this.#int(), this.#intAfterComma(), this.#intAfterComma()];
|
||||
const a = this.#take(',') ? this.#int() : 255;
|
||||
if ([r, g, b, a].some((value) => value < 0 || value > 255)) this.#fail('Invalid color channel');
|
||||
return { type: 'color', value: ((a << 24) | (r << 16) | (g << 8) | b) >>> 0 };
|
||||
}
|
||||
case 'm': {
|
||||
const value: number[] = [];
|
||||
this.#expect('[');
|
||||
for (let row = 0; row < 4; row += 1) {
|
||||
this.#expect('[');
|
||||
value.push(...this.#row());
|
||||
this.#expect(']');
|
||||
if (row < 3) this.#take(',');
|
||||
}
|
||||
this.#expect(']');
|
||||
return { type: 'matrix', value };
|
||||
}
|
||||
default: return this.#fail('Unknown BLK type');
|
||||
}
|
||||
}
|
||||
|
||||
#row(): [number, number, number] {
|
||||
return [this.#real(), this.#realAfterComma(), this.#realAfterComma()];
|
||||
}
|
||||
|
||||
#realAfterComma(): number {
|
||||
this.#expect(',');
|
||||
return this.#real();
|
||||
}
|
||||
|
||||
#intAfterComma(): number {
|
||||
this.#expect(',');
|
||||
return this.#int();
|
||||
}
|
||||
|
||||
#int(): number {
|
||||
return Number(this.#integer(32));
|
||||
}
|
||||
|
||||
#integer(bits: number): bigint {
|
||||
const token = this.#word();
|
||||
if (!/^[+-]?(?:\d+|0x[\da-f]+)$/i.test(token)) this.#fail('Invalid integer');
|
||||
const negative = token.startsWith('-');
|
||||
const magnitude = BigInt(token.replace(/^[+-]/, ''));
|
||||
const value = negative ? -magnitude : magnitude;
|
||||
const limit = 1n << BigInt(bits - 1);
|
||||
if (value < -limit || value >= limit) this.#fail('Integer outside its BLK type');
|
||||
return value;
|
||||
}
|
||||
|
||||
#real(): number {
|
||||
const token = this.#word();
|
||||
if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(token)) this.#fail('Invalid real number');
|
||||
const value = Number(token);
|
||||
if (!Number.isFinite(Math.fround(value))) this.#fail('Real number out of range');
|
||||
return value;
|
||||
}
|
||||
|
||||
#word(): string {
|
||||
this.#space();
|
||||
const quote = this.#text[this.#at];
|
||||
if (quote === '"' || quote === "'") {
|
||||
this.#at += 1;
|
||||
let output = '';
|
||||
while (this.#at < this.#text.length) {
|
||||
const char = this.#text[this.#at++]!;
|
||||
if (char === quote) return output;
|
||||
if (char !== '~') {
|
||||
output += char;
|
||||
continue;
|
||||
}
|
||||
const next = this.#text[this.#at++];
|
||||
if (next === undefined) this.#fail('Incomplete string escape');
|
||||
output += next === 'n' ? '\n' : next === 'r' ? '\r' : next === 't' ? '\t' : next;
|
||||
}
|
||||
return this.#fail('Unclosed string');
|
||||
}
|
||||
const start = this.#at;
|
||||
while (this.#at < this.#text.length && !/[\s:={};,\[\]]/.test(this.#text[this.#at]!) &&
|
||||
!this.#text.startsWith('//', this.#at) && !this.#text.startsWith('/*', this.#at)) this.#at += 1;
|
||||
if (this.#at === start) this.#fail('Expected a name or value');
|
||||
return this.#text.slice(start, this.#at);
|
||||
}
|
||||
|
||||
#take(char: string): boolean {
|
||||
this.#space();
|
||||
if (this.#text[this.#at] !== char) return false;
|
||||
this.#at += 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
#expect(char: string): void {
|
||||
if (!this.#take(char)) this.#fail('Expected ' + char);
|
||||
}
|
||||
|
||||
#space(): void {
|
||||
for (;;) {
|
||||
const char = this.#text[this.#at] ?? '';
|
||||
if (/[\s;]/.test(char)) this.#at += 1;
|
||||
else if (this.#text.startsWith('//', this.#at)) {
|
||||
const end = this.#text.indexOf('\n', this.#at + 2);
|
||||
this.#at = end === -1 ? this.#text.length : end + 1;
|
||||
} else if (this.#text.startsWith('/*', this.#at)) {
|
||||
const end = this.#text.indexOf('*/', this.#at + 2);
|
||||
if (end === -1) this.#fail('Unclosed comment');
|
||||
this.#at = end + 2;
|
||||
} else return;
|
||||
}
|
||||
}
|
||||
|
||||
#fail(message: string): never {
|
||||
const line = this.#text.slice(0, this.#at).split('\n').length;
|
||||
throw new Error(`${message} (line ${line})`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { lstatSync, readFileSync } from 'node:fs';
|
||||
import { basename } from 'node:path';
|
||||
import { encodeBlk, findBlock, type BlkBlock } from '@wto/blk';
|
||||
import { AccountStore } from '../../accounts/account-store.ts';
|
||||
import { ClanStore } from '../../clans/clan-store.ts';
|
||||
import { CloudSettingsStore } from '../../cloud-settings/cloud-settings-store.ts';
|
||||
import { DatasetCache } from '../../game-data/datasets/dataset-cache.ts';
|
||||
import { crewSlotPrices } from '../../game-data/datasets/rank-settings.ts';
|
||||
import { vehicleCatalogue } from '../../game-data/datasets/vehicle-catalogue.ts';
|
||||
import { GameFiles } from '../../game-data/game-files.ts';
|
||||
import { intField } from '../../profile/blk-fields.ts';
|
||||
import { addCrew, allCrews, crewOf, putVehicleInCrew, trainCrewFor } from '../../profile/profile-crews.ts';
|
||||
import { addOwnedVehicle } from '../../profile/profile-hangar.ts';
|
||||
import { ownsModification, writeModificationRecord } from '../../profile/profile-modifications.ts';
|
||||
import { weaponRecord, writeWeaponRecord } from '../../profile/profile-weapons.ts';
|
||||
import { setUpProfiles, type ProfileServices } from '../../profiles-setup.ts';
|
||||
import { loadTuning } from '../../tuning/tuning.ts';
|
||||
import type { SaveLocation } from '../save-editor.ts';
|
||||
import { readBackupBlk } from './backup-blk.ts';
|
||||
|
||||
const TYPES = {
|
||||
'global.blk': 'GBT_GENERAL_SETTINGS',
|
||||
'machine.blk': 'GBT_GENERAL_MACHINE_SETTINGS',
|
||||
'storage.blk': 'GBT_GENERAL_STORAGE',
|
||||
} as const;
|
||||
type BackupName = keyof typeof TYPES;
|
||||
|
||||
const SURVIVAL = /^(tank_tool_kit|tank_extinguisher|tank_crew_replacement|tank_laser_rangefinder|tank_night_vision|tank_thermal_vision)$/;
|
||||
|
||||
export interface OfficialImportOptions {
|
||||
readonly importSettings: boolean;
|
||||
readonly unlockVehicles: boolean;
|
||||
readonly includeUsedVehicles: boolean;
|
||||
readonly equipment: 'full' | 'basic' | 'stock';
|
||||
}
|
||||
|
||||
interface OfficialFile {
|
||||
readonly name: BackupName;
|
||||
readonly version: number;
|
||||
readonly container: BlkBlock;
|
||||
readonly content: BlkBlock;
|
||||
}
|
||||
|
||||
interface Preset {
|
||||
readonly country: string;
|
||||
readonly title: string;
|
||||
readonly selected: boolean;
|
||||
readonly units: ReadonlyArray<{ readonly slot: number; readonly vehicle: string }>;
|
||||
}
|
||||
|
||||
export function previewOfficialBackup(location: SaveLocation, paths: readonly string[], includeUsed: boolean) {
|
||||
return prepare(location, paths, includeUsed).preview;
|
||||
}
|
||||
|
||||
export function importOfficialBackup(location: SaveLocation, userId: string, paths: readonly string[], options: OfficialImportOptions) {
|
||||
const dataFolder = location.dataFolder;
|
||||
const accounts = new AccountStore(dataFolder);
|
||||
if (!accounts.byUserId(userId)) throw new Error('Unknown account for official backup.');
|
||||
const { files, presets, vehicles, gameFiles, datasets, preview } = prepare(location, paths, options.includeUsedVehicles);
|
||||
if (options.unlockVehicles && vehicles.length > 0) {
|
||||
const tuning = loadTuning(dataFolder, () => {});
|
||||
const clans = new ClanStore(dataFolder, tuning.clans);
|
||||
const services = setUpProfiles(dataFolder, gameFiles, datasets, tuning, { accounts, clans });
|
||||
const availableSlots = datasets.load(crewSlotPrices).length;
|
||||
services.profiles.update(userId, (profile) => applyVehicles(profile, services, vehicles, presets, availableSlots, options.equipment));
|
||||
}
|
||||
|
||||
if (options.importSettings) {
|
||||
const store = new CloudSettingsStore(dataFolder);
|
||||
const existing = store.buildMetaBlk(userId);
|
||||
for (const file of files) {
|
||||
const blkType = TYPES[file.name];
|
||||
const version = Math.max(file.version, intField(findBlock(existing, blkType), 'version')) + 1;
|
||||
if (version > 0x7fffffff) throw new Error('Imported settings version exceeds the supported range.');
|
||||
const contentHash = createHash('md5').update(encodeBlk({ ...file.content, name: '' })).digest('hex');
|
||||
if (!store.saveUpload(userId, { blkType, version, contentHash, container: file.container })) {
|
||||
throw new Error('Could not store the imported settings.');
|
||||
}
|
||||
}
|
||||
}
|
||||
return preview;
|
||||
}
|
||||
|
||||
function prepare(location: SaveLocation, paths: readonly string[], includeUsed: boolean) {
|
||||
const files = paths.map(readFile);
|
||||
if (files.length === 0 || new Set(files.map(({ name }) => name)).size !== files.length) {
|
||||
throw new Error('Select at most one backup for each settings category.');
|
||||
}
|
||||
const gameFiles = new GameFiles(location.gameFolder);
|
||||
const datasets = new DatasetCache(location.dataFolder, gameFiles, () => {});
|
||||
const catalogue = datasets.load(vehicleCatalogue);
|
||||
const known = new Set(catalogue.map(({ name }) => name));
|
||||
const global = files.find(({ name }) => name === 'global.blk');
|
||||
const presets: Preset[] = global ? readPresets(global.content) : [];
|
||||
const referenced = new Set(presets.flatMap((entry) => entry.units.map(({ vehicle }) => vehicle)));
|
||||
if (includeUsed && global) considerUsed(global.content, known, referenced);
|
||||
const vehicles = [...referenced].filter((name) => known.has(name)).sort();
|
||||
const omitted = [...referenced].filter((name) => !known.has(name)).sort();
|
||||
return {
|
||||
files, presets, vehicles, gameFiles, datasets,
|
||||
preview: {
|
||||
files: files.map(({ name, version }) => ({ name, version })),
|
||||
presets: presets.map(({ country, title, units }) => ({ country, title, vehicles: units.map(({ vehicle }) => vehicle) })),
|
||||
vehicles, omitted,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function readFile(path: string): OfficialFile {
|
||||
const name = basename(path).toLowerCase();
|
||||
if (!Object.hasOwn(TYPES, name)) throw new Error('Unexpected official backup file: ' + name);
|
||||
const file = lstatSync(path);
|
||||
if (!file.isFile() || file.size > 32 * 1024 * 1024) throw new Error('Invalid backup file: ' + name);
|
||||
const container = readBackupBlk(readFileSync(path));
|
||||
const content = findBlock(container, 'content');
|
||||
const version = intField(container, 'version', -1);
|
||||
if (!content || !Number.isInteger(version) || version < 0) throw new Error('Expected a versioned settings container: ' + name);
|
||||
return { name: name as BackupName, version, container, content };
|
||||
}
|
||||
|
||||
function readPresets(content: BlkBlock): Preset[] {
|
||||
const root = namedBlock(content, 'slotbar_presets');
|
||||
return (root?.blocks ?? []).flatMap((country) => {
|
||||
const selected = intField(country, 'selected', 0);
|
||||
return country.params.filter(({ name }) => name === 'preset').flatMap((entry, index) => {
|
||||
if (entry.value.type !== 'string') return [];
|
||||
const parts = entry.value.value.split('|');
|
||||
if (parts.length !== 6) return [];
|
||||
const [, crewIds, vehicles, title, , slots] = parts as [string, string, string, string, string, string];
|
||||
const ids = (slots || crewIds).split(',');
|
||||
const units = vehicles.split(',').flatMap((vehicle, position) => {
|
||||
const token = ids[position];
|
||||
const slot = token && /^\d+$/.test(token) ? Number(token) : position;
|
||||
return vehicle && Number.isSafeInteger(slot) && slot >= 0 ? [{ slot, vehicle }] : [];
|
||||
});
|
||||
return [{ country: country.name, title, selected: index === selected, units }];
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function namedBlock(block: BlkBlock, name: string): BlkBlock | undefined {
|
||||
if (block.name === name) return block;
|
||||
for (const child of block.blocks) {
|
||||
const found = namedBlock(child, name);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
|
||||
function considerUsed(block: BlkBlock, known: ReadonlySet<string>, vehicles: Set<string>): void {
|
||||
if (known.has(block.name)) vehicles.add(block.name);
|
||||
for (const child of block.blocks) considerUsed(child, known, vehicles);
|
||||
}
|
||||
|
||||
function applyVehicles(
|
||||
profile: BlkBlock,
|
||||
{ research, equipment }: ProfileServices,
|
||||
vehicles: readonly string[],
|
||||
presets: readonly Preset[],
|
||||
slotLimit: number,
|
||||
tier: OfficialImportOptions['equipment'],
|
||||
): void {
|
||||
const granted = new Set<string>();
|
||||
const next = [...vehicles];
|
||||
while (next.length) {
|
||||
const name = next.pop()!;
|
||||
if (granted.has(name)) continue;
|
||||
const vehicle = research.techTree.vehicle(name);
|
||||
if (!vehicle) continue;
|
||||
granted.add(name);
|
||||
addOwnedVehicle(profile, name);
|
||||
if ((vehicle.kind === 'research' || vehicle.kind === 'purchase') && vehicle.requires) next.push(vehicle.requires);
|
||||
next.push(...vehicle.parts);
|
||||
}
|
||||
|
||||
if (tier !== 'stock') {
|
||||
for (const name of granted) {
|
||||
const facts = equipment.vehicle(name);
|
||||
if (!facts) continue;
|
||||
for (const mod of facts.modifications) {
|
||||
if (ownsModification(profile, name, mod.name) || (tier === 'basic' && !SURVIVAL.test(mod.name))) continue;
|
||||
writeModificationRecord(profile, name, mod.name, {
|
||||
silverLionsSpent: 0, goldenEaglesSpent: 0, enabled: true, count: Math.max(1, mod.maxCount),
|
||||
});
|
||||
}
|
||||
if (tier === 'full') {
|
||||
for (const weapon of facts.weapons) {
|
||||
if (weaponRecord(profile, name, weapon.name)) continue;
|
||||
writeWeaponRecord(profile, name, weapon.name, {
|
||||
silverLionsSpent: 0, goldenEaglesSpent: 0, count: Math.max(1, weapon.maxCount),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const preset of presets) {
|
||||
if (!research.techTree.hasCountry(preset.country)) continue;
|
||||
const crews = allCrews(profile).filter((crew) => crew.params.some((param) =>
|
||||
param.name === 'country' && param.value.type === 'string' && param.value.value === preset.country));
|
||||
for (const { slot, vehicle } of preset.units) {
|
||||
if (!granted.has(vehicle) || research.techTree.vehicle(vehicle)?.country !== preset.country ||
|
||||
slot >= Math.max(slotLimit, crews.length)) continue;
|
||||
while (crews.length <= slot) crews.push(crewOf(profile, addCrew(profile, preset.country))!);
|
||||
const crew = crews[slot]!;
|
||||
if (preset.selected) putVehicleInCrew(crew, vehicle);
|
||||
else trainCrewFor(crew, vehicle);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user