diff --git a/apps/launcher/src/main/ipc/handlers.ts b/apps/launcher/src/main/ipc/handlers.ts index c2bb9c8..57a1173 100644 --- a/apps/launcher/src/main/ipc/handlers.ts +++ b/apps/launcher/src/main/ipc/handlers.ts @@ -15,7 +15,7 @@ import { readInstalledLab } from '../services/launch/lab-handoff.ts'; import { getLaunchState, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts'; import { activePatchSet, applyPackUpdate, checkPackUpdate, revertToBundledPatchSet } from '../services/patch-pack/pack-update.ts'; import { resourcePaths } from '../services/resources/resource-paths.ts'; -import { changeSaveAccount, changeSaveResearch, createSave, exportSave, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts'; +import { changeSaveAccount, changeSaveResearch, createSave, exportSave, getSaveAvatarChoices, getSaveAvatarPreview, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts'; import { broadcast, handle } from './register.ts'; /** Registers the handler of every contract channel. One line per channel; the work is in services/. */ @@ -110,6 +110,8 @@ export function registerIpcHandlers(): void { handle('saves:details', ({ copyId, userId }) => getSaveDetails(copyId, userId)); handle('saves:setCurrent', ({ copyId, userId }) => selectSave(copyId, userId)); handle('saves:create', (request) => createSave(request)); + handle('saves:avatars', ({ copyId }) => getSaveAvatarChoices(copyId)); + handle('saves:avatarPreview', ({ copyId, avatar }) => getSaveAvatarPreview(copyId, avatar)); handle('saves:editAccount', ({ copyId, userId, edits }) => changeSaveAccount(copyId, userId, edits)); handle('saves:editCurrencies', ({ copyId, userId, values }) => setSaveCurrencies(copyId, userId, values)); diff --git a/apps/launcher/src/main/services/saves/manage-saves.ts b/apps/launcher/src/main/services/saves/manage-saves.ts index 876e344..01bba30 100644 --- a/apps/launcher/src/main/services/saves/manage-saves.ts +++ b/apps/launcher/src/main/services/saves/manage-saves.ts @@ -3,7 +3,7 @@ import { app, dialog, utilityProcess, type BrowserWindow } from 'electron'; import { compareVersions, isInSteamLibrary } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; import type { InstallRecord } from '@shared/schemas/install.ts'; -import type { AccountEdits, CurrencyEdits, OfficialImportOptions, OfficialPreview, SaveBackup, SaveDetails, SaveList, SaveRegistration, SaveTransfer, ResearchBranch, ResearchOperation, SaveResearch } from '@shared/schemas/saves.ts'; +import type { AccountEdits, CurrencyEdits, OfficialImportOptions, OfficialPreview, SaveBackup, SaveDetails, SaveList, SaveRegistration, SaveTransfer, ResearchBranch, ResearchOperation, SaveAvatarChoices, SaveResearch } from '@shared/schemas/saves.ts'; import type { SaveReply, SaveResult, SaveTask } from '../../workers/save-protocol.ts'; import { maintenanceInProgress } from '../copies/copy-maintenance.ts'; import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts'; @@ -55,15 +55,27 @@ export async function createSave({ copyId, login, password, nick }: SaveRegistra }); } +export async function getSaveAvatarChoices(copyId: string): Promise { + const copy = await requireCopy(copyId); + return await run({ operation: 'avatars', ...location(copy) }) as SaveAvatarChoices; +} + +export async function getSaveAvatarPreview(copyId: string, avatar: string): Promise { + const copy = await requireCopy(copyId); + return await run({ operation: 'avatarPreview', ...location(copy), avatar }) as string | null; +} + export async function changeSaveAccount(copyId: string, userId: string, edits: AccountEdits): Promise { return write(async () => { const copy = await requireCopy(copyId); - const before = edits.premiumDays === undefined ? null : await captureSave(copy, userId); + const changesProfile = edits.premiumDays !== undefined || edits.avatar !== undefined || edits.level !== undefined; + const before = changesProfile ? await captureSave(copy, userId) : null; try { await run({ operation: 'editAccount', ...location(copy), userId, edits }); } catch (error) { - if (before && - (!(error instanceof AppError) || (error.code !== 'save_nick_invalid' && error.code !== 'save_not_found'))) { + const rejectedEdit = error instanceof AppError && + ['save_nick_invalid', 'save_avatar_invalid', 'save_level_invalid', 'save_not_found'].includes(error.code); + if (before && !rejectedEdit) { await restoreDirectory(copy, userId, before); } throw error; diff --git a/apps/launcher/src/main/workers/save-protocol.ts b/apps/launcher/src/main/workers/save-protocol.ts index 3fce798..e5f190c 100644 --- a/apps/launcher/src/main/workers/save-protocol.ts +++ b/apps/launcher/src/main/workers/save-protocol.ts @@ -1,5 +1,5 @@ import type { AppErrorCode } from '@shared/errors.ts'; -import type { AccountEdits, CurrencyEdits, OfficialImportOptions, OfficialPreview, ResearchBranch, ResearchOperation, SaveDetails, SaveList, SaveResearch } from '@shared/schemas/saves.ts'; +import type { AccountEdits, SaveAvatarChoices, CurrencyEdits, OfficialImportOptions, OfficialPreview, ResearchBranch, ResearchOperation, SaveDetails, SaveList, SaveResearch } from '@shared/schemas/saves.ts'; interface Location { readonly gameFolder: string; @@ -9,6 +9,8 @@ interface Location { export type SaveTask = Location & ( | { readonly operation: 'list' } | { readonly operation: 'details'; readonly userId: string } + | { readonly operation: 'avatars' } + | { 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 } @@ -19,5 +21,5 @@ export type SaveTask = Location & ( | { readonly operation: 'filter'; readonly profile: Uint8Array; readonly filter: boolean } | { readonly operation: 'create'; readonly login: string; readonly password: string; readonly nick: string } ); -export type SaveResult = SaveList['saves'] | SaveDetails | OfficialPreview | SaveResearch | { userId: string } | Uint8Array | null; +export type SaveResult = SaveList['saves'] | SaveDetails | OfficialPreview | SaveResearch | { userId: string } | Uint8Array | SaveAvatarChoices | string | null; export type SaveReply = { ok: true; result: SaveResult } | { ok: false; error: AppErrorCode }; diff --git a/apps/launcher/src/main/workers/save-worker.ts b/apps/launcher/src/main/workers/save-worker.ts index c05fa28..c41eae5 100644 --- a/apps/launcher/src/main/workers/save-worker.ts +++ b/apps/launcher/src/main/workers/save-worker.ts @@ -1,20 +1,27 @@ import type { MessageEvent } from 'electron'; -import { AccountStore, editSaveAccount, editSaveCurrencies, editSaveResearch, importOfficialBackup, listSaveSummaries, prepareTransferredProfile, previewOfficialBackup, readSaveDetails, readSaveResearch } from '@wto/server'; +import { AccountStore, editSaveAccount, editSaveCurrencies, editSaveResearch, importOfficialBackup, listSaveAvatars, listSaveSummaries, prepareTransferredProfile, previewOfficialBackup, readSaveAvatar, readSaveDetails, readSaveResearch } from '@wto/server'; import type { SaveTask, SaveReply } from './save-protocol.ts'; function execute(task: SaveTask): SaveReply { switch (task.operation) { case 'list': - return { ok: true, result: listSaveSummaries(task.dataFolder) }; + return { ok: true, result: listSaveSummaries(task.dataFolder, task.gameFolder) }; case 'details': { - const result = readSaveDetails(task.dataFolder, task.userId); + const result = readSaveDetails(task.dataFolder, task.userId, task.gameFolder); return result ? { ok: true, result } : { ok: false, error: 'save_not_found' }; } - case 'editAccount': { - const status = editSaveAccount(task, task.userId, task.edits); - if (status === 'updated') return { ok: true, result: null }; - return { ok: false, error: status === 'invalid-nick' ? 'save_nick_invalid' : 'save_not_found' }; - } + case 'avatars': + return { ok: true, result: listSaveAvatars(task) }; + case 'avatarPreview': + return { ok: true, result: readSaveAvatar(task, task.avatar) }; + case 'editAccount': + switch (editSaveAccount(task, task.userId, task.edits)) { + case 'updated': return { ok: true, result: null }; + case 'invalid-nick': return { ok: false, error: 'save_nick_invalid' }; + case 'invalid-avatar': return { ok: false, error: 'save_avatar_invalid' }; + case 'invalid-level': return { ok: false, error: 'save_level_invalid' }; + case 'not-found': return { ok: false, error: 'save_not_found' }; + } case 'edit': return editSaveCurrencies(task, task.userId, task.values) ? { ok: true, result: null } : { ok: false, error: 'save_not_found' }; diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 097f71e..ec3ac26 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -354,6 +354,9 @@ "battles": "Recorded battles", "lastBattle": "Last battle", "premiumDays": "Premium account days", + "avatar": "Avatar", + "avatarUnavailable": "Avatar unavailable", + "level": "Account level", "saveAccount": "Save account details", "apply": "Save changes", "saved": "Changes saved.", @@ -565,6 +568,8 @@ "save_login_exists": "An account with this login already exists.", "save_password_invalid": "Enter a password.", "save_nick_invalid": "Enter a nickname with up to 16 characters.", + "save_avatar_invalid": "Select an avatar available in this game copy.", + "save_level_invalid": "Enter a level supported by this game copy.", "tuning_invalid": "The tuning values could not be read or saved. Check the session limits and the launcher log.", "copy_not_found": "The selected copy is no longer available.", "copies_write_failed": "The copy registry could not be saved.", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index c4a5792..a74a382 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -354,6 +354,9 @@ "battles": "已记录对局", "lastBattle": "上次对局", "premiumDays": "高级账户剩余天数", + "avatar": "头像", + "avatarUnavailable": "头像不可用", + "level": "账号等级", "saveAccount": "保存账号信息", "apply": "保存更改", "saved": "更改已保存。", @@ -565,6 +568,8 @@ "save_login_exists": "该登录账号已注册。", "save_password_invalid": "请输入密码。", "save_nick_invalid": "请输入最多 16 个字符的昵称。", + "save_avatar_invalid": "请选择此副本中可用的头像。", + "save_level_invalid": "请输入此副本支持的账号等级。", "tuning_invalid": "无法读取或保存数值。请核对对局人数限制和启动器日志。", "copy_not_found": "所选副本已不可用。", "copies_write_failed": "无法保存副本记录。", diff --git a/apps/launcher/src/renderer/src/pages/saves/SaveAvatarField.tsx b/apps/launcher/src/renderer/src/pages/saves/SaveAvatarField.tsx new file mode 100644 index 0000000..e7387dc --- /dev/null +++ b/apps/launcher/src/renderer/src/pages/saves/SaveAvatarField.tsx @@ -0,0 +1,65 @@ +import { useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import type { SaveAvatarChoices } from '@shared/schemas/saves.ts'; +import { Row } from '../../components/Row.tsx'; +import { ipcInvoke } from '../../ipc.ts'; + +interface SaveAvatarFieldProps { + readonly copyId: string; + readonly avatar: string; + readonly disabled: boolean; + readonly onError: (error: unknown) => void; +} + +export function SaveAvatarField({ copyId, avatar, disabled, onError }: SaveAvatarFieldProps) { + const { t, i18n } = useTranslation(); + const [choices, setChoices] = useState(null); + const [selected, setSelected] = useState(avatar); + const [preview, setPreview] = useState<{ id: string; data: string } | null>(null); + const canPreview = choices?.some(({ id }) => id === selected) ?? false; + + useEffect(() => { + let mounted = true; + ipcInvoke('saves:avatars', { copyId }) + .then((value) => { if (mounted) setChoices(value); }) + .catch((error: unknown) => { + if (mounted) { + setChoices([]); + onError(error); + } + }); + return () => { mounted = false; }; + }, [copyId, onError]); + + useEffect(() => { + if (!canPreview) return; + let mounted = true; + ipcInvoke('saves:avatarPreview', { copyId, avatar: selected }) + .then((data) => { if (mounted) setPreview(data ? { id: selected, data } : null); }) + .catch((error: unknown) => { if (mounted) onError(error); }); + return () => { mounted = false; }; + }, [canPreview, copyId, selected, onError]); + + const label = t('saves.avatar'); + const language = i18n.language.toLowerCase().startsWith('zh') ? 'zh' : 'en'; + return ( + + {choices === null + ? {t('saves.loading')} + : choices.length === 0 + ? {t('saves.avatarUnavailable')} + : ( +
+ {canPreview && preview?.id === selected && ( + + )} + +
+ )} +
+ ); +} diff --git a/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx b/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx index 1880619..304d477 100644 --- a/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx +++ b/apps/launcher/src/renderer/src/pages/saves/SavesPage.tsx @@ -7,6 +7,7 @@ import { Sheet } from '../../components/Sheet.tsx'; import { ipcInvoke } from '../../ipc.ts'; import type { SaveSection } from '../../shell/navigation.ts'; import { OfficialSaveImport } from './OfficialSaveImport.tsx'; +import { SaveAvatarField } from './SaveAvatarField.tsx'; import { SaveResearch } from './SaveResearch.tsx'; import { SaveBackups } from './SaveBackups.tsx'; @@ -109,8 +110,12 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag const data = new FormData(event.currentTarget); const nick = String(data.get('nick') ?? '').trim(); const days = String(data.get('premiumDays') ?? '').trim(); + const avatar = String(data.get('avatar') ?? ''); + const level = String(data.get('level') ?? '').trim(); const edits: AccountEdits = {}; if (nick !== details.save.nick) edits.nick = nick; + if (avatar && avatar !== details.save.avatar) edits.avatar = avatar; + if (level !== '' && Number(level) !== details.save.level) edits.level = Number(level); if (days !== '' && Number(days) !== details.save.premiumDays) edits.premiumDays = Number(days); if (Object.keys(edits).length === 0) return; setSaving(true); @@ -180,6 +185,7 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag
{t('saves.login')}
{save.login}
+
{t('saves.level')}
{save.level === null ? '—' : format.format(save.level)}
{t('saves.silverLions')}
{save.currencies ? format.format(save.currencies.silverLions) : '—'}
{t('saves.vehicles')}
{format.format(save.vehicleCount)}
{t('saves.battles')}
{format.format(save.battleCount)}
@@ -231,10 +237,17 @@ export function SavesPage({ copy, copies, section, readOnly, onError }: SavesPag <> {readOnly &&

{t('saves.readOnly')}

} {save.login} -
+ + + + {details.maxLevel === null ? '—' : ( + + )} + diff --git a/apps/launcher/src/shared/errors.ts b/apps/launcher/src/shared/errors.ts index 6c8063c..9d70a93 100644 --- a/apps/launcher/src/shared/errors.ts +++ b/apps/launcher/src/shared/errors.ts @@ -28,6 +28,8 @@ export const APP_ERROR_CODES = [ 'save_login_exists', 'save_password_invalid', 'save_nick_invalid', + 'save_avatar_invalid', + 'save_level_invalid', 'copies_write_failed', 'maintenance_busy', 'maintenance_location', diff --git a/apps/launcher/src/shared/ipc/contract.ts b/apps/launcher/src/shared/ipc/contract.ts index 68196bb..cd25f8a 100644 --- a/apps/launcher/src/shared/ipc/contract.ts +++ b/apps/launcher/src/shared/ipc/contract.ts @@ -16,7 +16,7 @@ import { import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts'; import { MaintenanceInfoSchema, MaintenanceProgressSchema, MaintenanceRequestSchema } from '../schemas/maintenance.ts'; import { ActivePatchSetSchema, PackApplyResultSchema, PackCheckSchema } from '../schemas/patch-pack.ts'; -import { AccountEditsSchema, ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts'; +import { AccountEditsSchema, SaveAvatarChoicesSchema, SaveAvatarIdSchema, ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts'; import { TuningPatchSchema, TuningViewSchema } from '../schemas/tuning.ts'; import { SettingsPatchSchema, SettingsSchema } from '../schemas/settings.ts'; @@ -146,6 +146,14 @@ export const ipcContract = { input: SaveRegistrationSchema, output: SaveListSchema, }, + 'saves:avatars': { + input: z.object({ copyId: CopyIdSchema }), + output: SaveAvatarChoicesSchema, + }, + 'saves:avatarPreview': { + input: z.object({ copyId: CopyIdSchema, avatar: SaveAvatarIdSchema }), + output: z.base64().nullable(), + }, 'saves:editAccount': { input: SaveKeysSchema.extend({ edits: AccountEditsSchema }), output: SaveDetailsSchema, diff --git a/apps/launcher/src/shared/schemas/saves.ts b/apps/launcher/src/shared/schemas/saves.ts index 46246b2..3e11fd1 100644 --- a/apps/launcher/src/shared/schemas/saves.ts +++ b/apps/launcher/src/shared/schemas/saves.ts @@ -4,7 +4,19 @@ import { CopyIdSchema } from './install.ts'; export const LocalUserIdSchema = z.string().regex(/^\d+$/); export const SaveKeysSchema = z.object({ copyId: CopyIdSchema, userId: LocalUserIdSchema }); -export const AccountEditsSchema = z.object({ nick: z.string().optional(), premiumDays: z.number().int().nonnegative().optional() }); +export const SaveAvatarIdSchema = z.string().regex(/^cardicon_[a-z0-9_]+$/); +export const SaveAvatarChoicesSchema = z.array(z.object({ + id: SaveAvatarIdSchema, + name: z.object({ en: z.string(), zh: z.string() }), +})); +export type SaveAvatarChoices = z.output; + +export const AccountEditsSchema = z.object({ + nick: z.string().optional(), + premiumDays: z.number().int().nonnegative().optional(), + avatar: SaveAvatarIdSchema.optional(), + level: z.number().int().nonnegative().optional(), +}); export type AccountEdits = z.output; export const CurrencyEditsSchema = z.object({ @@ -18,6 +30,8 @@ const SaveSummarySchema = z.object({ login: z.string(), nick: z.string(), created: z.string(), + avatar: z.string(), + level: z.number().int().nonnegative().nullable(), currencies: z.object({ silverLions: z.number(), goldenEagles: z.number(), @@ -32,6 +46,7 @@ const SaveSummarySchema = z.object({ export const SaveListSchema = z.object({ saves: z.array(SaveSummarySchema), current: LocalUserIdSchema.nullable() }); export const SaveDetailsSchema = z.object({ save: SaveSummarySchema, + maxLevel: z.number().int().positive().nullable(), battles: z.array(z.object({ id: z.string(), time: z.number(), won: z.boolean().nullable(), mission: z.string(), mode: z.string(), vehicles: z.array(z.string()), silverLions: z.number(), researchPoints: z.number(), diff --git a/apps/server/src/game-data/datasets/dataset-cache.ts b/apps/server/src/game-data/datasets/dataset-cache.ts index 9203540..9abafa8 100644 --- a/apps/server/src/game-data/datasets/dataset-cache.ts +++ b/apps/server/src/game-data/datasets/dataset-cache.ts @@ -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[] { diff --git a/apps/server/src/game-data/datasets/dataset.ts b/apps/server/src/game-data/datasets/dataset.ts index a5e5e08..49c972c 100644 --- a/apps/server/src/game-data/datasets/dataset.ts +++ b/apps/server/src/game-data/datasets/dataset.ts @@ -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[]; } diff --git a/apps/server/src/game-data/datasets/rank-settings.ts b/apps/server/src/game-data/datasets/rank-settings.ts index c0b591a..e360306 100644 --- a/apps/server/src/game-data/datasets/rank-settings.ts +++ b/apps/server/src/game-data/datasets/rank-settings.ts @@ -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 = { + 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>>>; diff --git a/apps/server/src/game-data/game-files.ts b/apps/server/src/game-data/game-files.ts index 4aba77e..bc38134 100644 --- a/apps/server/src/game-data/game-files.ts +++ b/apps/server/src/game-data/game-files.ts @@ -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 { diff --git a/apps/server/src/game-data/game-pack.ts b/apps/server/src/game-data/game-pack.ts index f265567..0d3523c 100644 --- a/apps/server/src/game-data/game-pack.ts +++ b/apps/server/src/game-data/game-pack.ts @@ -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. */ diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts index faa32ae..ad35f7a 100644 --- a/apps/server/src/index.ts +++ b/apps/server/src/index.ts @@ -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'; diff --git a/apps/server/src/profile/client-profile.ts b/apps/server/src/profile/client-profile.ts index 4453d1f..aeb21e4 100644 --- a/apps/server/src/profile/client-profile.ts +++ b/apps/server/src/profile/client-profile.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; diff --git a/apps/server/src/profile/profile-appearance.ts b/apps/server/src/profile/profile-appearance.ts index f680813..65b62a4 100644 --- a/apps/server/src/profile/profile-appearance.ts +++ b/apps/server/src/profile/profile-appearance.ts @@ -30,6 +30,10 @@ export function appearance(profile: BlkBlock): Partial 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 }); } diff --git a/apps/server/src/saves/save-avatars.ts b/apps/server/src/saves/save-avatars.ts new file mode 100644 index 0000000..15719ce --- /dev/null +++ b/apps/server/src/saves/save-avatars.ts @@ -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>; + +const saveAvatarImages: Dataset = { + 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(); + 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 = {}; + 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; + } +} diff --git a/apps/server/src/saves/save-editor.ts b/apps/server/src/saves/save-editor.ts index 5dd26cd..5f189ef 100644 --- a/apps/server/src/saves/save-editor.ts +++ b/apps/server/src/saves/save-editor.ts @@ -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); }