fix(saves): keep imported presets intact, cap crews to preset units and drop used-unit scan

This commit is contained in:
N0VAN0M4LY committed 2026-11-30 19:21:47 +08:00
1 parent 388dc9d9d7
commit e6e75d92c6
10 files changed
+109 -114

No files matched your search

+81 -76
View File
@@ -13,6 +13,7 @@ import { intField } from '../../profile/blk-fields.ts';
import { addCrew, allCrews, crewOf, emptyCrewSlot, putVehicleInCrew, trainCrewFor } from '../../profile/profile-crews.ts';
import { addOwnedVehicle } from '../../profile/profile-hangar.ts';
import { ownsModification, writeModificationRecord } from '../../profile/profile-modifications.ts';
import { addUnlock, earnedUnlocks } from '../../profile/profile-unlocks.ts';
import { weaponRecord, writeWeaponRecord } from '../../profile/profile-weapons.ts';
import { setUpProfiles, type ProfileServices } from '../../profiles-setup.ts';
import { loadTuning } from '../../tuning/tuning.ts';
@@ -29,11 +30,17 @@ type BackupName = keyof typeof TYPES;
const SURVIVAL = /^(tank_tool_kit|tank_extinguisher|tank_crew_replacement|tank_laser_rangefinder|tank_night_vision|tank_thermal_vision)$/;
const TALISMAN = 'premExpMul';
const CREW_BLOCK_NAME = /^c(\d+)$/;
const FIRST_CHOSEN_UNIT_TYPES = [
'chosen_unit_type_tank',
'chosen_unit_type_air',
'chosen_unit_type_ship',
'chosen_unit_type_ship_without_boat',
'chosen_unit_type_helicopter',
] as const;
export interface OfficialImportOptions {
readonly importSettings: boolean;
readonly unlockVehicles: boolean;
readonly includeUsedVehicles: boolean;
readonly equipment: 'full' | 'basic' | 'stock';
}
@@ -55,7 +62,7 @@ interface ParsedPreset {
readonly gameModeId: string;
readonly selected: boolean;
readonly selectedOnlineCrewId: number;
readonly onlineCrewOrder: readonly number[];
readonly slotCrewOrder: readonly number[];
readonly units: readonly PresetUnit[];
}
@@ -64,8 +71,8 @@ interface CountryCrewMapping {
readonly offlineCrewIds: readonly number[];
}
export function previewOfficialBackup(location: SaveLocation, paths: readonly string[], includeUsed: boolean) {
return prepare(location, paths, includeUsed).preview;
export function previewOfficialBackup(location: SaveLocation, paths: readonly string[]) {
return prepare(location, paths).preview;
}
export function importOfficialBackup(
@@ -73,17 +80,15 @@ export function importOfficialBackup(
userId: string,
paths: readonly string[],
options: OfficialImportOptions,
offlineClientCacheFolder?: string,
offlineClientCacheFolders: readonly string[] = [],
) {
const dataFolder = location.dataFolder;
const accounts = new AccountStore(dataFolder);
if (!accounts.byUserId(userId)) throw new Error('Unknown account for online data import.');
const { files, presets, presetVehicles, extraUsedVehicles, known, gameFiles, datasets, preview } = prepare(
location, paths, options.includeUsedVehicles,
);
const { files, presets, presetVehicles, known, gameFiles, datasets, preview } = prepare(location, paths);
const crewMappings = new Map<string, CountryCrewMapping>();
const needsProfile = (options.unlockVehicles && (presetVehicles.length > 0 || extraUsedVehicles.length > 0))
const needsProfile = (options.unlockVehicles && presetVehicles.length > 0)
|| (options.importSettings && presets.length > 0);
if (needsProfile) {
@@ -91,14 +96,17 @@ export function importOfficialBackup(
const clans = new ClanStore(dataFolder, tuning.clans);
const services = setUpProfiles(dataFolder, gameFiles, datasets, tuning, { accounts, clans });
const availableSlots = datasets.load(crewSlotPrices).length;
if (options.unlockVehicles && (presetVehicles.length > 0 || extraUsedVehicles.length > 0)) {
services.profiles.update(userId, (profile) => {
applyVehicles(profile, services, presetVehicles, extraUsedVehicles, presets, availableSlots, options.equipment, crewMappings);
});
} else {
const profile = services.profiles.profileOf(userId);
buildExistingCrewMappings(profile, services, presets, crewMappings);
}
services.profiles.update(userId, (profile) => {
if (options.unlockVehicles && presetVehicles.length > 0) {
applyVehicles(profile, services, presetVehicles, presets, availableSlots, options.equipment, crewMappings);
} else {
buildExistingCrewMappings(profile, services, presets, crewMappings);
}
if (options.importSettings && presets.length > 0) {
// Mark first-choice onboarding complete so `newbieInitSlotbarPresets` never wipes imported presets.
markFirstChoiceComplete(profile, services, presets);
}
});
}
if (options.importSettings) {
@@ -111,22 +119,25 @@ export function importOfficialBackup(
const existing = store.buildMetaBlk(userId);
for (const file of files) {
const blkType = TYPES[file.name];
const localCachedVersion = offlineClientCacheFolder ? readCachedLocalVersion(offlineClientCacheFolder, file.name) : 0;
const localCachedVersion = offlineClientCacheFolders.reduce(
(highest, folder) => Math.max(highest, readCachedLocalVersion(folder, file.name)),
0,
);
const version = Math.max(file.version, intField(findBlock(existing, blkType), 'version'), localCachedVersion) + 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.');
}
if (offlineClientCacheFolder) {
clearCachedLocalFile(offlineClientCacheFolder, file.name);
for (const folder of offlineClientCacheFolders) {
clearCachedLocalFile(folder, file.name);
}
}
}
return preview;
}
function prepare(location: SaveLocation, paths: readonly string[], includeUsed: boolean) {
function prepare(location: SaveLocation, paths: readonly string[]) {
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 file for each settings category.');
@@ -138,19 +149,16 @@ function prepare(location: SaveLocation, paths: readonly string[], includeUsed:
const global = files.find(({ name }) => name === 'global.blk');
const presets: ParsedPreset[] = global ? readPresets(global.content) : [];
const presetReferenced = new Set(presets.flatMap((entry) => entry.units.map(({ vehicle }) => vehicle)));
const extraReferenced = new Set<string>();
if (includeUsed && global) considerUsedUnits(global.content, known, presetReferenced, extraReferenced);
const presetVehicles = [...presetReferenced].filter((name) => known.has(name)).sort();
const extraUsedVehicles = [...extraReferenced].filter((name) => known.has(name)).sort();
const vehicles = [...new Set([...presetVehicles, ...extraUsedVehicles])].sort();
const omitted = [...presetReferenced].filter((name) => !known.has(name)).sort();
return {
files, presets, presetVehicles, extraUsedVehicles, known, gameFiles, datasets,
files, presets, presetVehicles, known, 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,
vehicles: presetVehicles,
omitted,
},
};
}
@@ -222,16 +230,16 @@ function parsePresetString(country: string, raw: string, selected: boolean): Par
units.push({ onlineCrewId: Number(token), vehicle });
}
const onlineCrewOrder: number[] = [];
const slotCrewOrder: number[] = [];
const seen = new Set<number>();
for (const id of [...slotCrewIds, ...units.map(({ onlineCrewId }) => onlineCrewId)]) {
for (const id of slotCrewIds) {
if (!seen.has(id)) {
seen.add(id);
onlineCrewOrder.push(id);
slotCrewOrder.push(id);
}
}
return { country, title, gameModeId, selected, selectedOnlineCrewId, onlineCrewOrder, units };
return { country, title, gameModeId, selected, selectedOnlineCrewId, slotCrewOrder, units };
}
function namedBlock(block: BlkBlock, name: string): BlkBlock | undefined {
@@ -242,30 +250,6 @@ function namedBlock(block: BlkBlock, name: string): BlkBlock | undefined {
}
}
/**
* Only read per-unit battle settings from `content/settings/unitsSettings` rather than scanning
* the whole file, so protection analysis, skin lists and crosshair tables are never mistaken
* for owned vehicles.
*/
function considerUsedUnits(
content: BlkBlock,
known: ReadonlySet<string>,
presetVehicles: ReadonlySet<string>,
extraVehicles: Set<string>,
): void {
const settings = findBlock(content, 'settings');
const unitsSettings = settings ? findBlock(settings, 'unitsSettings') : undefined;
if (!unitsSettings) return;
for (const unitBlock of unitsSettings.blocks) {
if (!known.has(unitBlock.name) || presetVehicles.has(unitBlock.name)) continue;
const hasConfiguredLoadout = unitBlock.params.some((param) =>
(param.name === 'USEROPT_BULLET_COUNT0' && param.value.type === 'int' && param.value.value > 0)
|| (param.name === 'USEROPT_WEAPONS' && param.value.type === 'string' && param.value.value.length > 0),
);
if (hasConfiguredLoadout) extraVehicles.add(unitBlock.name);
}
}
function crewIdOfBlock(crew: BlkBlock): number {
return Number(CREW_BLOCK_NAME.exec(crew.name)?.[1] ?? -1);
}
@@ -276,21 +260,58 @@ function countryCrewsOf(profile: BlkBlock, country: string): BlkBlock[] {
);
}
/**
* Only allocate local crew slots for online crew IDs that actually hold at least one vehicle in
* the country's presets, preserving their slotbar order from `crewInSlots` without importing
* unused/historical empty slot IDs.
*/
function orderedOnlineCrewIdsForCountry(presets: readonly ParsedPreset[], country: string): number[] {
const countryPresets = presets.filter((preset) => preset.country === country);
const used = new Set<number>();
for (const preset of countryPresets) {
for (const { onlineCrewId } of preset.units) used.add(onlineCrewId);
}
const ordered: number[] = [];
const seen = new Set<number>();
for (const preset of presets) {
if (preset.country !== country) continue;
for (const id of preset.onlineCrewOrder) {
if (!seen.has(id)) {
for (const preset of countryPresets) {
for (const id of preset.slotCrewOrder) {
if (used.has(id) && !seen.has(id)) {
seen.add(id);
ordered.push(id);
}
}
}
for (const preset of countryPresets) {
for (const { onlineCrewId } of preset.units) {
if (!seen.has(onlineCrewId)) {
seen.add(onlineCrewId);
ordered.push(onlineCrewId);
}
}
}
return ordered;
}
function markFirstChoiceComplete(
profile: BlkBlock,
{ research }: ProfileServices,
presets: readonly ParsedPreset[],
): void {
const earned = earnedUnlocks(profile);
if (!FIRST_CHOSEN_UNIT_TYPES.some((id) => earned.has(id))) {
addUnlock(profile, 'chosen_unit_type_tank');
}
const countries = [...new Set(presets.map(({ country }) => country))]
.filter((country) => research.techTree.hasCountry(country));
for (const country of countries) {
if (!earned.has(country)) addUnlock(profile, country);
}
const hasChosenCountry = [...earned].some((id) => id.startsWith('chosen_country_'));
if (!hasChosenCountry) {
addUnlock(profile, `chosen_${countries[0] ?? 'country_usa'}`);
}
}
function buildExistingCrewMappings(
profile: BlkBlock,
{ research }: ProfileServices,
@@ -315,14 +336,13 @@ function applyVehicles(
profile: BlkBlock,
{ research, equipment }: ProfileServices,
presetVehicles: readonly string[],
extraUsedVehicles: readonly string[],
presets: readonly ParsedPreset[],
slotLimit: number,
tier: OfficialImportOptions['equipment'],
mappings: Map<string, CountryCrewMapping>,
): void {
const granted = new Set<string>();
// Trace tech-tree prerequisites only for vehicles that actually appear in slotbar presets.
// Trace tech-tree prerequisites for vehicles present in slotbar presets.
const next = [...presetVehicles];
while (next.length) {
const name = next.pop()!;
@@ -335,21 +355,6 @@ function applyVehicles(
next.push(...vehicle.parts);
}
// Optional extra vehicles from unitsSettings are granted individually without unlocking whole lines.
for (const name of extraUsedVehicles) {
if (granted.has(name)) continue;
const vehicle = research.techTree.vehicle(name);
if (!vehicle) continue;
granted.add(name);
addOwnedVehicle(profile, name);
for (const part of vehicle.parts) {
if (!granted.has(part)) {
granted.add(part);
addOwnedVehicle(profile, part);
}
}
}
if (tier !== 'stock') {
for (const name of granted) {
const facts = equipment.vehicle(name);