feat(saves): edit account levels and avatars

Read rank thresholds and available avatar artwork from the selected copy. Persist avatar selections in the player profile and preserve free research points when a level changes.
This commit is contained in:
N0VAN0M4LY committed 2026-11-29 18:19:05 +08:00
1 parent d043a8f0f8
commit 5d1d7001b8
22 files changed
+337 -63

No files matched your search

@@ -111,19 +111,23 @@ class TrackedSource implements DatasetSource {
}
readBlk(pack: GamePackName, path: string): BlkBlock {
const gamePack = this.#gameFiles.pack(pack);
const sha1 = gamePack.fileDigest(path);
if (sha1 === undefined) throw new Error(`${pack} has no file ${path}`);
this.#files.set(`${pack}/${path}`, { pack, path, sha1 });
return gamePack.readBlk(path);
return this.#trackFile(pack, path).readBlk(path);
}
readText(pack: GamePackName, path: string): string {
return this.#trackFile(pack, path).readText(path);
}
readBytes(pack: GamePackName, path: string): Uint8Array {
return this.#trackFile(pack, path).readBytes(path);
}
#trackFile(pack: GamePackName, path: string) {
const gamePack = this.#gameFiles.pack(pack);
const sha1 = gamePack.fileDigest(path);
if (sha1 === undefined) throw new Error(`${pack} has no file ${path}`);
this.#files.set(`${pack}/${path}`, { pack, path, sha1 });
return gamePack.readText(path);
return gamePack;
}
listFiles(pack: GamePackName): readonly string[] {
@@ -11,6 +11,7 @@ import type { GamePackName } from '../game-files.ts';
export interface DatasetSource {
readBlk(pack: GamePackName, path: string): BlkBlock;
readText(pack: GamePackName, path: string): string;
readBytes(pack: GamePackName, path: string): Uint8Array;
/** Every file path in a pack, sorted. */
listFiles(pack: GamePackName): readonly string[];
}
@@ -16,6 +16,22 @@ import type { Dataset } from './dataset.ts';
const RANK = 'config/rank.blk';
const SLOT = /^slot(\d+)$/;
/** Cumulative XP thresholds read in the same order as scripts/ranks.nut. */
export const playerRankThresholds: Dataset<readonly number[]> = {
id: 'player-rank-thresholds',
version: 1,
extract: (source) => {
const block = source.readBlk('char.vromfs.bin', RANK).blocks.find((child) => child.name === 'exp_for_playerRank');
const thresholds: number[] = [];
for (const { value } of block?.params ?? []) {
const threshold = value.type === 'int' || value.type === 'int64' ? Number(value.value) : NaN;
if (!Number.isSafeInteger(threshold) || threshold <= (thresholds.at(-1) ?? 0)) return [];
thresholds.push(threshold);
}
return thresholds;
},
};
/** country -> parameter name -> vehicles needed, as written. */
export type EraRequirements = Readonly<Record<string, Readonly<Record<string, number>>>>;
+2 -1
View File
@@ -13,7 +13,8 @@ export type GamePackName =
| 'aces.vromfs.bin'
| 'gui.vromfs.bin'
| 'lang.vromfs.bin'
| 'ui/atlases.vromfs.bin';
| 'ui/atlases.vromfs.bin'
| 'ui/images.vromfs.bin';
/** Size and modification time provide a quick preliminary check of a pack file. */
export interface PackStamp {
+5 -1
View File
@@ -27,7 +27,11 @@ export class GamePack {
}
readText(pathInPack: string): string {
return Buffer.from(getFile(this.#archive, pathInPack)).toString('utf8');
return Buffer.from(this.readBytes(pathInPack)).toString('utf8');
}
readBytes(pathInPack: string): Uint8Array {
return getFile(this.#archive, pathInPack);
}
/** Every file path in the pack, sorted. */
+1
View File
@@ -8,6 +8,7 @@ export { REGISTRATION_PATH } from './accounts/registration-service.ts';
export { HEALTH_PATH } from './transport/http-listener.ts';
export { editSaveResearch, readSaveResearch } from './saves/save-research.ts';
export { editSaveAccount, editSaveCurrencies, listSaveSummaries, readSaveDetails } from './saves/save-editor.ts';
export { listSaveAvatars, readSaveAvatar } from './saves/save-avatars.ts';
export { importOfficialBackup, previewOfficialBackup } from './saves/import/official-backup.ts';
export { prepareTransferredProfile } from './saves/transferred-profile.ts';
export { readLauncherTuning, writeLauncherTuning, type LauncherTuningPatch } from './tuning/launcher-tuning.ts';
@@ -10,12 +10,15 @@
*/
import { setParam, type BlkBlock } from '@wto/blk';
import type { Account } from '../accounts/account-store.ts';
import { appearance } from './profile-appearance.ts';
import { clearStoreCart } from './profile-store-cart.ts';
import { serverTimeNow } from './server-time.ts';
export function clientProfile(saved: BlkBlock, account: Account): BlkBlock {
const profile = structuredClone(saved);
clearStoreCart(profile);
const pilotIcon = appearance(profile).pilotIcon;
if (pilotIcon !== undefined) setParam(profile, 'pilotIcon', { type: 'string', value: pilotIcon });
setParam(profile, 'charDrivenNick', { type: 'string', value: account.nick });
setParam(profile, 'serverTime', { type: 'int64', value: serverTimeNow() });
return profile;
@@ -30,6 +30,10 @@ export function appearance(profile: BlkBlock): Partial<Record<AppearanceField, s
const value = block && findParam(block, field)?.value;
if (value?.type === 'string') result[field] = value.value;
}
if (result.pilotIcon === undefined) {
const legacy = findParam(profile, 'pilotIcon')?.value;
if (legacy?.type === 'string') result.pilotIcon = legacy.value;
}
return result;
}
@@ -1,57 +1,50 @@
/**
* Free research points in the profile.
*
* The client shows shop_get_free_exp (aces.exe 2.61.0.37 0x17a4f40): the total of the
* experience counters (0x933190) minus "converted". The counters are top-level i64
* parameters read and written by 0x9331b0: experience, experienceOffline, valUnlocks,
* presented and valTrophy count into the total; Gaijin's new-account template has
* experience:i64=0. Free research points are earned into "experience" and spending them
* raises "converted".
* The client uses the total of the saved experience counters for its account rank.
* Free research points are that total minus the signed `converted` counter. Both
* values were observed in the 2.61.0.43 client's rank and free RP getters.
* Battle rewards increase `experience`, and spending free RP increases `converted`.
*/
import { findParam, setParam, type BlkBlock } from '@wto/blk';
import { setParam, type BlkBlock } from '@wto/blk';
import { int64Field } from './blk-fields.ts';
const EARNED = 'experience';
const OTHER_EARNED = ['experienceOffline', 'valUnlocks', 'presented', 'valTrophy'] as const;
const SPENT = 'converted';
export function freeResearchPoints(profile: BlkBlock): number {
return earnedTotal(profile) - counter(profile, SPENT);
return Number(playerExperience(profile) - int64Field(profile, SPENT));
}
/** Spend free research points the player has (callers check freeResearchPoints first). */
export function spendFreeResearchPoints(profile: BlkBlock, amount: number): void {
setCounter(profile, SPENT, counter(profile, SPENT) + amount);
setCounter(profile, SPENT, int64Field(profile, SPENT) + BigInt(amount));
}
/** Credit convertible (free) research points earned in battle (`experience:i64`). */
export function addFreeResearchPoints(profile: BlkBlock, amount: number): void {
if (!Number.isSafeInteger(amount) || amount < 0) throw new RangeError(`amount out of range: ${amount}`);
if (amount > 0) setCounter(profile, EARNED, counter(profile, EARNED) + amount);
if (amount > 0) setCounter(profile, EARNED, int64Field(profile, EARNED) + BigInt(amount));
}
/** Make the free research points this amount (the save editor). */
/** Set the free research balance while keeping the experience used for rank. */
export function setFreeResearchPoints(profile: BlkBlock, amount: number): void {
if (!Number.isSafeInteger(amount) || amount < 0) throw new RangeError(`amount out of range: ${amount}`);
const others = earnedTotal(profile) - counter(profile, EARNED);
const earned = amount + counter(profile, SPENT) - others;
if (earned >= 0) {
setCounter(profile, EARNED, earned);
} else {
setCounter(profile, EARNED, 0);
setCounter(profile, SPENT, counter(profile, SPENT) - earned);
}
setCounter(profile, SPENT, playerExperience(profile) - BigInt(amount));
}
function earnedTotal(profile: BlkBlock): number {
return [EARNED, ...OTHER_EARNED].reduce((sum, name) => sum + counter(profile, name), 0);
export function playerExperience(profile: BlkBlock): bigint {
return [EARNED, ...OTHER_EARNED].reduce((sum, name) => sum + int64Field(profile, name), 0n);
}
function counter(profile: BlkBlock, name: string): number {
const value = findParam(profile, name)?.value;
if (value?.type === 'int64') return Number(value.value);
return value?.type === 'int' ? value.value : 0;
/** Set rank experience by applying the same adjustment to earned and converted RP. */
export function setPlayerExperience(profile: BlkBlock, amount: bigint): void {
const difference = amount - playerExperience(profile);
setCounter(profile, EARNED, int64Field(profile, EARNED) + difference);
setCounter(profile, SPENT, int64Field(profile, SPENT) + difference);
}
function setCounter(profile: BlkBlock, name: string, amount: number): void {
setParam(profile, name, { type: 'int64', value: BigInt(amount) });
function setCounter(profile: BlkBlock, name: string, amount: bigint): void {
setParam(profile, name, { type: 'int64', value: amount });
}
+72
View File
@@ -0,0 +1,72 @@
import { DatasetCache } from '../game-data/datasets/dataset-cache.ts';
import type { Dataset } from '../game-data/datasets/dataset.ts';
import { parseLocalizedCsvMap, type LocalizedCsvText } from '../game-data/datasets/lang-csv.ts';
import { GameFiles } from '../game-data/game-files.ts';
import { stringField } from '../profile/blk-fields.ts';
import type { SaveLocation } from './save-editor.ts';
export const DEFAULT_SAVE_AVATAR = 'cardicon_default';
const IMAGE_PACK = 'ui/images.vromfs.bin';
const LANGUAGE_PACK = 'lang.vromfs.bin';
const AVATAR_IMAGE = /^images\/avatars\/(cardicon_[a-z0-9_]+)\.avif$/;
const LABEL_FILES = ['lang/menu_options.csv', 'lang/unlocks_achievements.csv'];
interface AvatarImage {
readonly name: LocalizedCsvText;
readonly image: string;
}
type AvatarImages = Readonly<Record<string, AvatarImage>>;
const saveAvatarImages: Dataset<AvatarImages> = {
id: 'save-avatar-images',
version: 1,
extract: (source) => {
const paths = source.listFiles(IMAGE_PACK);
const unlocks = source.readBlk('char.vromfs.bin', 'config/unlocks.blk');
const ids = new Set(unlocks.blocks
.filter((entry) => stringField(entry, 'type') === 'pilot')
.map((entry) => stringField(entry, 'id')));
ids.add(DEFAULT_SAVE_AVATAR);
const labels = new Map<string, LocalizedCsvText>();
const languagePaths = source.listFiles(LANGUAGE_PACK);
for (const file of LABEL_FILES) {
if (!languagePaths.includes(file)) continue;
for (const [key, text] of parseLocalizedCsvMap(source.readText(LANGUAGE_PACK, file))) {
labels.set(key, text);
}
}
const result: Record<string, AvatarImage> = {};
for (const path of paths) {
const id = AVATAR_IMAGE.exec(path)?.[1];
if (!id || !ids.has(id)) continue;
const fallback = id.slice('cardicon_'.length).replaceAll('_', ' ');
const name = labels.get(`pilotIcons/${id}`) ?? labels.get(`${id}/name`) ??
labels.get(`${id}/desc`) ?? { en: fallback, zh: fallback };
const image = Buffer.from(source.readBytes(IMAGE_PACK, path)).toString('base64');
result[id] = { name, image };
}
return result;
},
};
export function listSaveAvatars(location: SaveLocation) {
return Object.entries(loadImages(location)).map(([id, { name }]) => ({ id, name }));
}
export function readSaveAvatar(location: SaveLocation, id: string): string | null {
return loadImages(location)[id]?.image ?? null;
}
function loadImages(location: SaveLocation): AvatarImages {
const files = new GameFiles(location.gameFolder);
try {
return new DatasetCache(location.dataFolder, files, () => {}).load(saveAvatarImages);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {};
throw error;
}
}
+49 -10
View File
@@ -4,17 +4,20 @@ import { decodeBlk, findBlock, findParam, type BlkBlock } from '@wto/blk';
import { AccountStore, normalizedNickname, type Account } from '../accounts/account-store.ts';
import { ClanStore } from '../clans/clan-store.ts';
import { DatasetCache } from '../game-data/datasets/dataset-cache.ts';
import { playerRankThresholds } from '../game-data/datasets/rank-settings.ts';
import { GameFiles } from '../game-data/game-files.ts';
import { intField, stringField } from '../profile/blk-fields.ts';
import { appearance, setAppearance } from '../profile/profile-appearance.ts';
import { balanceOf, setGjnCents, setGoldenEagles, setSilverLions } from '../profile/profile-currency.ts';
import { remainingPremiumDays, setPremiumDays } from '../profile/profile-entitlements.ts';
import { ownedVehicles } from '../profile/profile-hangar.ts';
import { freeResearchPoints, setFreeResearchPoints } from '../profile/profile-research-points.ts';
import { freeResearchPoints, playerExperience, setFreeResearchPoints, setPlayerExperience } from '../profile/profile-research-points.ts';
import { EULT_SESSION_RESULT } from '../profile/profile-trophies-log.ts';
import { researchPointsOf } from '../profile/profile-vehicle-research.ts';
import { serverTimeNow } from '../profile/server-time.ts';
import { setUpProfiles } from '../profiles-setup.ts';
import { loadTuning } from '../tuning/tuning.ts';
import { DEFAULT_SAVE_AVATAR, readSaveAvatar } from './save-avatars.ts';
export interface SaveLocation {
readonly gameFolder: string;
@@ -28,11 +31,14 @@ export interface CurrencyEdits {
readonly freeRp?: number | undefined;
}
function summary(account: Account, profile: BlkBlock | undefined) {
function summary(account: Account, profile: BlkBlock | undefined, thresholds: readonly number[]) {
const battles = profile ? battleEntries(profile) : [];
const { userId, login, nick, created } = account;
const xp = profile ? playerExperience(profile) : 0n;
return {
userId, login, nick, created,
avatar: (profile && appearance(profile).pilotIcon) || DEFAULT_SAVE_AVATAR,
level: thresholds.length ? thresholds.filter((threshold) => xp >= BigInt(threshold)).length : null,
currencies: profile ? { ...balanceOf(profile), freeRp: freeResearchPoints(profile) } : null,
vehicleCount: profile ? ownedVehicles(profile).size : 0,
battleCount: battles.length,
@@ -71,11 +77,24 @@ function battleEntries(profile: BlkBlock) {
.sort((a, b) => b.time - a.time || b.id.localeCompare(a.id));
}
export function listSaveSummaries(dataFolder: string) {
return new AccountStore(dataFolder).all().map((account) => summary(account, readSaveSnapshot(dataFolder, account.userId)));
function rankThresholds(dataFolder: string, gameFolder: string | undefined): readonly number[] {
if (!gameFolder) return [];
try {
return new DatasetCache(dataFolder, new GameFiles(gameFolder), () => {}).load(playerRankThresholds);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
throw error;
}
}
export function readSaveDetails(dataFolder: string, userId: string) {
export function listSaveSummaries(dataFolder: string, gameFolder?: string) {
const accounts = new AccountStore(dataFolder).all();
if (!accounts.length) return [];
const thresholds = rankThresholds(dataFolder, gameFolder);
return accounts.map((account) => summary(account, readSaveSnapshot(dataFolder, account.userId), thresholds));
}
export function readSaveDetails(dataFolder: string, userId: string, gameFolder?: string) {
const account = new AccountStore(dataFolder).byUserId(userId);
if (!account) return null;
const profile = readSaveSnapshot(dataFolder, userId);
@@ -84,22 +103,42 @@ export function readSaveDetails(dataFolder: string, userId: string) {
? (findBlock(profile, 'unitResearch')?.blocks ?? []).map(({ name }) => ({ name, points: researchPointsOf(profile, name) }))
.filter(({ points }) => points > 0)
: [];
return { save: summary(account, profile), battles: profile ? battleEntries(profile) : [], owned, research };
const thresholds = rankThresholds(dataFolder, gameFolder);
return {
save: summary(account, profile, thresholds),
battles: profile ? battleEntries(profile) : [],
owned,
research,
maxLevel: thresholds.length || null,
};
}
export interface AccountEdits {
readonly nick?: string | undefined;
readonly premiumDays?: number | undefined;
readonly avatar?: string | undefined;
readonly level?: number | undefined;
}
export function editSaveAccount(location: SaveLocation, userId: string, edits: AccountEdits): 'updated' | 'invalid-nick' | 'not-found' {
export function editSaveAccount(location: SaveLocation, userId: string, edits: AccountEdits): 'updated' | 'invalid-nick' | 'invalid-avatar' | 'invalid-level' | 'not-found' {
const accounts = new AccountStore(location.dataFolder);
if (!accounts.byUserId(userId)) return 'not-found';
const nick = edits.nick === undefined ? undefined : normalizedNickname(edits.nick);
if (edits.nick !== undefined && nick === undefined) return 'invalid-nick';
const days = edits.premiumDays;
if (days !== undefined) {
updateProfile(location, accounts, userId, (profile) => setPremiumDays(profile, days, serverTimeNow()));
const { avatar, level, premiumDays } = edits;
if (avatar !== undefined && readSaveAvatar(location, avatar) === null) return 'invalid-avatar';
let xp: number | undefined;
if (level !== undefined) {
const thresholds = rankThresholds(location.dataFolder, location.gameFolder);
if (!thresholds.length || !Number.isSafeInteger(level) || level < 0 || level > thresholds.length) return 'invalid-level';
xp = level === 0 ? 0 : thresholds[level - 1];
}
if (avatar !== undefined || xp !== undefined || premiumDays !== undefined) {
updateProfile(location, accounts, userId, (profile) => {
if (avatar !== undefined) setAppearance(profile, 'pilotIcon', avatar);
if (xp !== undefined) setPlayerExperience(profile, BigInt(xp));
if (premiumDays !== undefined) setPremiumDays(profile, premiumDays, serverTimeNow());
});
}
return nick === undefined ? 'updated' : accounts.rename(userId, nick);
}