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

+2 -2
View File
@@ -139,8 +139,8 @@ export function registerIpcHandlers(): void {
handle('saves:discoverOnlineData', () => discoverOnlineData());
handle('saves:copyOnlineData', ({ copyId, userId, accountId }) => copyOnlineData(copyId, userId, accountId));
handle('saves:pickOfficialBackups', (_input, sender) => pickOfficialBackups(BrowserWindow.fromWebContents(sender)));
handle('saves:previewOfficial', ({ copyId, userId, paths, includeUsedVehicles }) =>
previewSelectedBackups(copyId, userId, paths, includeUsedVehicles));
handle('saves:previewOfficial', ({ copyId, userId, paths }) =>
previewSelectedBackups(copyId, userId, paths));
handle('saves:importOfficial', ({ copyId, userId, paths, options }) =>
importSelectedBackups(copyId, userId, paths, options));
@@ -190,11 +190,16 @@ function onlineSavesRoot(): string {
return join(app.getPath('documents'), 'My Games', 'WarThunder', 'Saves');
}
async function offlineClientCacheFolder(userId: string): Promise<string | undefined> {
if (!/^\d+$/.test(userId)) return undefined;
async function offlineClientCacheFolders(userId: string): Promise<string[]> {
if (!/^\d+$/.test(userId)) return [];
const root = await canonicalCopyPath(join(app.getPath('documents'), 'My Games', 'WTOffline', 'Saves'));
const target = await canonicalCopyPath(join(root, userId, 'production'));
return copyPathContains(root, target) ? target : undefined;
const candidates = [join(root, userId, 'production'), join(root, 'last', 'production')];
const folders: string[] = [];
for (const candidate of candidates) {
const resolved = await canonicalCopyPath(candidate);
if (copyPathContains(root, resolved)) folders.push(resolved);
}
return folders;
}
/** Read-only discovery of local online client settings under Documents/My Games/WarThunder/Saves. */
@@ -276,12 +281,12 @@ export async function pickOfficialBackups(window: BrowserWindow | null): Promise
}
export async function previewSelectedBackups(
copyId: string, userId: string, paths: readonly string[], includeUsedVehicles: boolean,
copyId: string, userId: string, paths: readonly string[],
): Promise<OfficialPreview> {
const copy = await requireCopy(copyId);
await getSaveDetails(copyId, userId);
const selected = await verifyBackupLocations(copy, paths);
return await run({ operation: 'previewOfficial', ...location(copy), paths: selected, includeUsedVehicles }) as OfficialPreview;
return await run({ operation: 'previewOfficial', ...location(copy), paths: selected }) as OfficialPreview;
}
export async function importSelectedBackups(
@@ -291,7 +296,7 @@ export async function importSelectedBackups(
const copy = await requireCopy(copyId);
await getSaveDetails(copyId, userId);
const selected = await verifyBackupLocations(copy, paths);
const cacheFolder = await offlineClientCacheFolder(userId);
const cacheFolders = await offlineClientCacheFolders(userId);
const before = await captureSave(copy, userId);
await saveBackup(copy, userId, 'import');
try {
@@ -301,7 +306,7 @@ export async function importSelectedBackups(
userId,
paths: selected,
options,
...(cacheFolder ? { offlineClientCacheFolder: cacheFolder } : {}),
...(cacheFolders.length > 0 ? { offlineClientCacheFolders: cacheFolders } : {}),
}) as OfficialPreview;
} catch (error) {
await restoreDirectory(copy, userId, before);
@@ -13,13 +13,13 @@ export type SaveTask = Location & (
| { readonly operation: 'avatarPreview'; readonly avatar: string }
| { readonly operation: 'editAccount'; readonly userId: string; readonly edits: AccountEdits }
| { readonly operation: 'edit'; readonly userId: string; readonly values: CurrencyEdits }
| { readonly operation: 'previewOfficial'; readonly paths: readonly string[]; readonly includeUsedVehicles: boolean }
| { readonly operation: 'previewOfficial'; readonly paths: readonly string[] }
| {
readonly operation: 'importOfficial';
readonly paths: readonly string[];
readonly userId: string;
readonly options: OfficialImportOptions;
readonly offlineClientCacheFolder?: string;
readonly offlineClientCacheFolders?: readonly string[];
}
| { readonly operation: 'readResearch'; readonly userId: string; readonly branch?: ResearchBranch }
| { readonly operation: 'editResearch'; readonly userId: string; readonly branch: ResearchBranch; readonly action: ResearchOperation }
@@ -26,9 +26,9 @@ function execute(task: SaveTask): SaveReply {
return editSaveCurrencies(task, task.userId, task.values)
? { ok: true, result: null } : { ok: false, error: 'save_not_found' };
case 'previewOfficial':
return { ok: true, result: previewOfficialBackup(task, task.paths, task.includeUsedVehicles) };
return { ok: true, result: previewOfficialBackup(task, task.paths) };
case 'importOfficial':
return { ok: true, result: importOfficialBackup(task, task.userId, task.paths, task.options, task.offlineClientCacheFolder) };
return { ok: true, result: importOfficialBackup(task, task.userId, task.paths, task.options, task.offlineClientCacheFolders) };
case 'readResearch': {
const result = readSaveResearch(task, task.userId, task.branch);
return result ? { ok: true, result } : { ok: false, error: 'save_not_found' };
@@ -356,7 +356,6 @@
"full": "All equipment",
"basic": "Essential equipment",
"stock": "Stock configuration",
"includeUsed": "Include additional vehicles from per-unit settings (without prerequisite lines)",
"preview": "Preview",
"import": "Import",
"summary": "{{files}} file(s) · {{presets}} preset(s) · {{vehicles}} available vehicle(s)",
@@ -356,7 +356,6 @@
"full": "完全体",
"basic": "基础生存配件",
"stock": "白板状态",
"includeUsed": "额外包含其他单车配置中的载具(不连带解锁前置科技树)",
"preview": "预览",
"import": "导入",
"summary": "{{files}} 个文件 · {{presets}} 套预设 · {{vehicles}} 辆可用载具",
@@ -5,7 +5,7 @@ import { Row } from '../../components/Row.tsx';
import { ipcInvoke } from '../../ipc.ts';
const DEFAULTS: OfficialImportOptions = {
importSettings: true, unlockVehicles: true, includeUsedVehicles: false, equipment: 'full',
importSettings: true, unlockVehicles: true, equipment: 'full',
};
interface Props {
@@ -26,12 +26,12 @@ export function OfficialSaveImport({ copyId, userId, readOnly, onError, onImport
const [busy, setBusy] = useState(false);
const [imported, setImported] = useState(false);
const stageAndPreview = async (accountId: string, includeUsed: boolean): Promise<string[]> => {
const stageAndPreview = async (accountId: string): Promise<string[]> => {
const copied = await ipcInvoke('saves:copyOnlineData', { copyId, userId, accountId });
setSelectedAccount(accountId);
setPaths(copied);
setImported(false);
const nextPreview = await ipcInvoke('saves:previewOfficial', { copyId, userId, paths: copied, includeUsedVehicles: includeUsed });
const nextPreview = await ipcInvoke('saves:previewOfficial', { copyId, userId, paths: copied });
setPreview(nextPreview);
return copied;
};
@@ -49,7 +49,7 @@ export function OfficialSaveImport({ copyId, userId, readOnly, onError, onImport
return;
}
const first = found[0]!;
const copied = await stageAndPreview(first.accountId, options.includeUsedVehicles);
const copied = await stageAndPreview(first.accountId);
if (importImmediately && found.length === 1 && !readOnly && (options.importSettings || options.unlockVehicles)) {
const result = await ipcInvoke('saves:importOfficial', { copyId, userId, paths: copied, options });
setPreview(result);
@@ -65,7 +65,7 @@ export function OfficialSaveImport({ copyId, userId, readOnly, onError, onImport
if (!accountId) return;
setBusy(true);
setImported(false);
stageAndPreview(accountId, options.includeUsedVehicles)
stageAndPreview(accountId)
.catch(onError)
.finally(() => setBusy(false));
};
@@ -80,11 +80,11 @@ export function OfficialSaveImport({ copyId, userId, readOnly, onError, onImport
}).catch(onError);
};
const load = (targetPaths = paths, includeUsed = options.includeUsedVehicles): void => {
const load = (targetPaths = paths): void => {
if (targetPaths.length === 0) return;
setBusy(true);
setImported(false);
ipcInvoke('saves:previewOfficial', { copyId, userId, paths: targetPaths, includeUsedVehicles: includeUsed })
ipcInvoke('saves:previewOfficial', { copyId, userId, paths: targetPaths })
.then(setPreview)
.catch(onError)
.finally(() => setBusy(false));
@@ -178,19 +178,6 @@ export function OfficialSaveImport({ copyId, userId, readOnly, onError, onImport
<option value="basic">{t('saves.official.basic')}</option>
<option value="stock">{t('saves.official.stock')}</option>
</select>
<label className="check check-inline">
<input type="checkbox" checked={options.includeUsedVehicles} disabled={busy || !options.unlockVehicles} onChange={(event) => {
const nextInclude = event.target.checked;
setOptions({ ...options, includeUsedVehicles: nextInclude });
setImported(false);
if (paths.length > 0 && preview) {
load(paths, nextInclude);
} else {
setPreview(null);
}
}} />
{t('saves.official.includeUsed')}
</label>
</Row>
<div className="copy-list-actions">
<button type="button" className="button" disabled={busy || paths.length === 0} onClick={() => load()}>{t('saves.official.preview')}</button>
+1 -1
View File
@@ -213,7 +213,7 @@ export const ipcContract = {
output: z.array(z.string()),
},
'saves:previewOfficial': {
input: SaveOfficialRequestSchema.extend({ includeUsedVehicles: z.boolean() }),
input: SaveOfficialRequestSchema,
output: OfficialPreviewSchema,
},
'saves:importOfficial': {
+1 -1
View File
@@ -80,7 +80,7 @@ export const SaveOfficialRequestSchema = SaveKeysSchema.extend({
paths: z.array(z.string().min(1)).min(1).max(3),
});
export const OfficialImportOptionsSchema = z.object({
importSettings: z.boolean(), unlockVehicles: z.boolean(), includeUsedVehicles: z.boolean(),
importSettings: z.boolean(), unlockVehicles: z.boolean(),
equipment: z.enum(['full', 'basic', 'stock']),
});
export const OfficialPreviewSchema = z.object({
+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);