Implement vehicle research and purchases

Recompute unlocked ranks, prerequisites, and unit states before serving
profiles. Add research target selection, research conversion, vehicle
and slot purchases, and the price table. Support editing convertible RP
and restrict hidden vehicle visibility to eligible entries.

The client still displays zero purchase prices pending price table
integration.
This commit is contained in:
N0VAN0M4LY committed 2026-11-24 21:04:19 +08:00
1 parent 8b31277c58
commit 7a08fff85e
37 files changed
+1336 -75

No files matched your search

@@ -1,6 +1,10 @@
/**
* The one way services get a player's profile: the saved one, or a new one that is written
* to the save before it is handed out.
*
* State that follows from the rest of the profile (statuses, open ranks, earned unlocks:
* research/research-state.ts) is brought up to date every time a profile is handed out or
* changed, and saved with it, so it also follows a game update that changed the data.
*/
import type { BlkBlock } from '@wto/blk';
import type { GameFiles } from '../game-data/game-files.ts';
@@ -8,29 +12,45 @@ import type { SaveStore } from '../saves/save-store.ts';
import { newProfile } from './new-profile.ts';
import type { StartingContent } from './starting-content.ts';
/** Brings the derived state of a profile up to date, in place. */
export type ProfileRefresh = (profile: BlkBlock) => void;
export class PlayerProfiles {
readonly #saves: SaveStore;
readonly #gameFiles: GameFiles;
readonly #startingContent: StartingContent;
readonly #refresh: ProfileRefresh;
constructor(saves: SaveStore, gameFiles: GameFiles, startingContent: StartingContent) {
constructor(saves: SaveStore, gameFiles: GameFiles, startingContent: StartingContent, refresh: ProfileRefresh) {
this.#saves = saves;
this.#gameFiles = gameFiles;
this.#startingContent = startingContent;
this.#refresh = refresh;
}
profileOf(userId: string): BlkBlock {
const saved = this.#saves.loadProfile(userId);
if (saved) return saved;
const created = newProfile(this.#gameFiles.newAccountTemplate(), this.#startingContent);
this.#saves.saveProfile(userId, created);
return created;
const profile = this.#saves.loadProfile(userId) ?? newProfile(this.#gameFiles.newAccountTemplate(), this.#startingContent);
this.#refresh(profile);
this.#saves.saveProfile(userId, profile);
return profile;
}
/** Change the player's profile and write it to the save before returning it. */
update(userId: string, change: (profile: BlkBlock) => void): BlkBlock {
return this.updateWhen(userId, (profile) => {
change(profile);
return true;
})!;
}
/**
* Change the player's profile if `change` accepts (returns true); the change must not touch
* the profile when it refuses. Returns the saved profile, or undefined when refused.
*/
updateWhen(userId: string, change: (profile: BlkBlock) => boolean): BlkBlock | undefined {
const profile = this.profileOf(userId);
change(profile);
if (!change(profile)) return undefined;
this.#refresh(profile);
this.#saves.saveProfile(userId, profile);
return profile;
}
@@ -18,10 +18,29 @@ const VEHICLES = 'aircrafts';
const TRAINED = 'trained';
const CURRENT = 'current';
const CREW_NAME = /^c(\d+)$/;
export function crewOf(profile: BlkBlock, crewId: number): BlkBlock | undefined {
return profile.blocks.find((block) => block.name === CREWS)?.blocks.find((crew) => crew.name === `c${crewId}`);
}
export function crewCountOf(profile: BlkBlock, country: string): number {
return (profile.blocks.find((block) => block.name === CREWS)?.blocks ?? []).filter((crew) => crewCountry(crew) === country).length;
}
/** Add an empty crew for the country, numbered after every existing crew; returns its id. */
export function addCrew(profile: BlkBlock, country: string): number {
const crews = ensureBlock(profile, CREWS);
const id = crews.blocks.reduce((highest, crew) => Math.max(highest, Number(CREW_NAME.exec(crew.name)?.[1] ?? -1)), -1) + 1;
crews.blocks.push({ name: `c${id}`, params: [{ name: 'country', value: { type: 'string', value: country } }], blocks: [{ name: VEHICLES, params: [], blocks: [] }] });
return id;
}
function crewCountry(crew: BlkBlock): string | undefined {
const value = crew.params.find((param) => param.name === 'country')?.value;
return value?.type === 'string' ? value.value : undefined;
}
/** Leave the crew's slot empty; the vehicles it is trained for stay trained. */
export function emptyCrewSlot(crew: BlkBlock): void {
const vehicles = crew.blocks.find((block) => block.name === VEHICLES);
@@ -35,6 +35,23 @@ export function setGoldenEagles(profile: BlkBlock, amount: number): void {
setParam(profile, GOLD, { type: 'int', value: amount });
}
/** A price in both currencies. */
export type Price = Balance;
export function canAfford(profile: BlkBlock, price: Price): boolean {
const balance = balanceOf(profile);
return balance.silverLions >= price.silverLions && balance.goldenEagles >= price.goldenEagles;
}
/** Pay a price the player can afford (callers check canAfford first): silver lions count as spent, golden eagles leave the balance. */
export function pay(profile: BlkBlock, price: Price): void {
requireAmount(price.silverLions, Number.MAX_SAFE_INTEGER);
requireAmount(price.goldenEagles, MAX_GOLD);
if (!canAfford(profile, price)) throw new RangeError('the player cannot afford this price');
if (price.silverLions > 0) setParam(profile, SPENT, { type: 'int64', value: BigInt(numberParam(profile, SPENT) + price.silverLions) });
if (price.goldenEagles > 0) setGoldenEagles(profile, numberParam(profile, GOLD) - price.goldenEagles);
}
function numberParam(profile: BlkBlock, name: string): number {
const value = findParam(profile, name)?.value;
if (value?.type === 'int64') return Number(value.value);
@@ -11,37 +11,21 @@
* table at 0x72b6d58 (Aircraft, Tank, Ship, Helicopter, Boat, Human, Transport) and keeps an
* integer, the highest rank open. The stock tech tree greys out and locks every rank above it
* (gui.vromfs.bin scripts/shop/shop.nut, is_era_available).
*
* The tech-tree branch names of config/shop.blk map to these types as the stock scripts pair
* them (scripts/unit/unitTypesList.nut armyId).
*/
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
const ERAS = 'eras';
const ERA_TYPE_OF_BRANCH: Readonly<Record<string, string>> = {
aviation: 'Aircraft',
army: 'Tank',
ships: 'Ship',
helicopters: 'Helicopter',
boats: 'Boat',
};
/** The rank open for research in a country's branch; 0 when none is. */
export function openRank(profile: BlkBlock, country: string, branch: string): number {
/** The highest rank open for research in a country for a vehicle type ("Tank", ...); 0 when none is. */
export function openRank(profile: BlkBlock, country: string, vehicleType: string): number {
const eras = findBlock(profile, ERAS);
const value = eras && findParam(eras, eraName(country, branch))?.value;
const value = eras && findParam(eras, `${vehicleType}_${country}`)?.value;
return value?.type === 'int' ? value.value : 0;
}
/** Open the branch up to the rank; a higher rank already open stays open. */
export function openRanksUpTo(profile: BlkBlock, country: string, branch: string, rank: number): void {
if (openRank(profile, country, branch) >= rank) return;
setParam(ensureBlock(profile, ERAS), eraName(country, branch), { type: 'int', value: rank });
}
function eraName(country: string, branch: string): string {
const type = ERA_TYPE_OF_BRANCH[branch];
if (!type) throw new Error(`unknown tech-tree branch: ${branch}`);
return `${type}_${country}`;
/** Open ranks up to this one; a higher rank already open stays open. Returns whether anything changed. */
export function openRanksUpTo(profile: BlkBlock, country: string, vehicleType: string, rank: number): boolean {
if (openRank(profile, country, vehicleType) >= rank) return false;
setParam(ensureBlock(profile, ERAS), `${vehicleType}_${country}`, { type: 'int', value: rank });
return true;
}
@@ -16,6 +16,10 @@ export function ownsVehicle(profile: BlkBlock, vehicle: string): boolean {
return hangar !== undefined && findBlock(hangar, vehicle) !== undefined;
}
export function ownedVehicles(profile: BlkBlock): Set<string> {
return new Set((findBlock(profile, HANGAR)?.blocks ?? []).map((owned) => owned.name));
}
/** Add the vehicle to the owned vehicles; nothing changes when the player owns it already. */
export function addOwnedVehicle(profile: BlkBlock, vehicle: string): void {
const hangar = ensureBlock(profile, HANGAR);
@@ -0,0 +1,51 @@
/**
* 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".
*/
import { findParam, setParam, type BlkBlock } from '@wto/blk';
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);
}
/** 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);
}
/** Make the free research points this amount (the save editor). */
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);
}
}
function earnedTotal(profile: BlkBlock): number {
return [EARNED, ...OTHER_EARNED].reduce((sum, name) => sum + counter(profile, name), 0);
}
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;
}
function setCounter(profile: BlkBlock, name: string, amount: number): void {
setParam(profile, name, { type: 'int64', value: BigInt(amount) });
}
@@ -0,0 +1,53 @@
/**
* The current research target and the just-finished research of each country and vehicle
* type.
*
* researchUnits{
* country_usa{
* currUnitTank:t="us_m2_medium"
* prevUnitTank:t=""
* }
* }
*
* Read by aces.exe 2.61.0.37 0x930150 for each country block: the parameter names are the
* field name followed by the vehicle type from the table at 0x72b6d98 (Aircraft, Tank, Ship,
* Helicopter, Boat, Human, Transport).
* - currUnit: the vehicle being researched (shop_get_researchable_unit_name, 0x17a3f80); the
* status function shows a researchable vehicle as "in research" when it is this one.
* - prevUnit: a vehicle whose research just finished; while it is set the stock scripts open
* the "choose the next research" window (shop_get_countries_list_with_autoset_units,
* 0x17a45e0; scripts/researches/researchActions.nut checkNonApprovedResearches).
* "" means none.
*/
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
const RESEARCH_UNITS = 'researchUnits';
const CURRENT = 'currUnit';
const FINISHED = 'prevUnit';
export function researchTarget(profile: BlkBlock, country: string, vehicleType: string): string {
return field(profile, country, `${CURRENT}${vehicleType}`);
}
export function setResearchTarget(profile: BlkBlock, country: string, vehicleType: string, vehicle: string): void {
setField(profile, country, `${CURRENT}${vehicleType}`, vehicle);
}
export function finishedResearch(profile: BlkBlock, country: string, vehicleType: string): string {
return field(profile, country, `${FINISHED}${vehicleType}`);
}
export function setFinishedResearch(profile: BlkBlock, country: string, vehicleType: string, vehicle: string): void {
setField(profile, country, `${FINISHED}${vehicleType}`, vehicle);
}
function field(profile: BlkBlock, country: string, name: string): string {
const units = findBlock(profile, RESEARCH_UNITS);
const block = units && findBlock(units, country);
const value = block && findParam(block, name)?.value;
return value?.type === 'string' ? value.value : '';
}
function setField(profile: BlkBlock, country: string, name: string, vehicle: string): void {
setParam(ensureBlock(ensureBlock(profile, RESEARCH_UNITS), country), name, { type: 'string', value: vehicle });
}
@@ -27,6 +27,18 @@ const UNLOCKS = 'unlocks';
const UNLOCK = 'unlock';
const ITEM = 'item';
/** The unlocks recorded as earned. */
export function earnedUnlocks(profile: BlkBlock): Set<string> {
const unlocks = profile.blocks.find((block) => block.name === UNLOCKS);
const earned = new Set<string>();
for (const unlock of unlocks?.blocks ?? []) {
const name = unlockName(unlock);
const flag = findParam(unlock, 'earned')?.value;
if (name !== undefined && flag?.type === 'bool' && flag.value) earned.add(name);
}
return earned;
}
/** Record the unlock as earned, rewriting an existing entry for it. */
export function addUnlock(profile: BlkBlock, name: string): void {
const unlocks = ensureBlock(profile, UNLOCKS);
@@ -0,0 +1,52 @@
/**
* The research state of the vehicles the player does not own.
*
* unitResearch{
* us_m2_medium{
* unitStatus:i=2
* exp:i64=1200
* }
* }
*
* Read by aces.exe 2.61.0.37 0x937a50 (block) and 0x943990 (each entry): unitStatus (default
* 1, locked) is what the status function shop_unit_research_status returns for a vehicle the
* player does not own (0xebf7a0); exp is the vehicle's research points (shop_get_unit_exp,
* 0x17a3980). A vehicle without an entry is locked and has no research points. Other
* parameters of an entry (attempts, wpSpent, goldSpent, hasScheme) are left as they are.
*/
import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
const UNIT_RESEARCH = 'unitResearch';
const STATUS = 'unitStatus';
const RESEARCH_POINTS = 'exp';
export function researchPointsOf(profile: BlkBlock, vehicle: string): number {
const entry = entryOf(profile, vehicle);
const value = entry && findParam(entry, RESEARCH_POINTS)?.value;
if (value?.type === 'int64') return Number(value.value);
return value?.type === 'int' ? value.value : 0;
}
export function setResearchPoints(profile: BlkBlock, vehicle: string, amount: number): void {
setParam(ensureEntry(profile, vehicle), RESEARCH_POINTS, { type: 'int64', value: BigInt(amount) });
}
/** Record the vehicle's status; the entry keeps its research points. */
export function setVehicleStatus(profile: BlkBlock, vehicle: string, status: number): void {
setParam(ensureEntry(profile, vehicle), STATUS, { type: 'int', value: status });
}
/** Drop the vehicle's entry: it is owned, or locked with no research points. */
export function removeVehicleResearch(profile: BlkBlock, vehicle: string): void {
const block = findBlock(profile, UNIT_RESEARCH);
if (block) block.blocks = block.blocks.filter((entry) => entry.name !== vehicle);
}
function entryOf(profile: BlkBlock, vehicle: string): BlkBlock | undefined {
const block = findBlock(profile, UNIT_RESEARCH);
return block && findBlock(block, vehicle);
}
function ensureEntry(profile: BlkBlock, vehicle: string): BlkBlock {
return ensureBlock(ensureBlock(profile, UNIT_RESEARCH), vehicle);
}
@@ -24,6 +24,7 @@
import type { BlkBlock } from '@wto/blk';
import type { ReserveVehicle } from '../game-data/datasets/reserve-vehicles.ts';
import type { ShopBranches } from '../game-data/datasets/shop-branches.ts';
import { vehicleTypeOfBranch } from '../research/vehicle-types.ts';
import { openRanksUpTo } from './profile-eras.ts';
import { addOwnedVehicle } from './profile-hangar.ts';
import { recordMissionCompleted } from './profile-mission-progress.ts';
@@ -40,7 +41,7 @@ export interface StartingContent {
export function applyStartingContent(profile: BlkBlock, content: StartingContent): void {
for (const vehicle of content.reserveVehicles) addOwnedVehicle(profile, vehicle.name);
for (const [country, branches] of Object.entries(content.branches)) {
for (const branch of branches) openRanksUpTo(profile, country, branch, FIRST_RANK);
for (const branch of branches) openRanksUpTo(profile, country, vehicleTypeOfBranch(branch), FIRST_RANK);
}
for (const tutorial of DIFFICULTY_GATING_TUTORIALS) recordMissionCompleted(profile, tutorial, HIGHEST_DIFFICULTY);
}