diff --git a/packages/build/src/tech-tree/reveal-hidden-vehicles.ts b/packages/build/src/tech-tree/reveal-hidden-vehicles.ts index b0b3a78..8237776 100644 --- a/packages/build/src/tech-tree/reveal-hidden-vehicles.ts +++ b/packages/build/src/tech-tree/reveal-hidden-vehicles.ts @@ -1,36 +1,31 @@ /** - * Show every vehicle in the tech tree, including the ones the live game hides from players - * who have not researched or bought them (local verification: e.g. the German Maus and Panther II). + * Show the tech-tree vehicles the live game hides until they are researched or on sale (user + * quote 98: e.g. the German Maus and Panther II). * * char.vromfs.bin config/shop.blk: country -> branch -> column -> vehicle (grouped vehicles one * level deeper). The stock UI hides a vehicle (gui.vromfs.bin scripts/unit/unit.nut * isVisibleInShop) when its entry has - * showOnlyWhenResearch:b until the player researches it (2.61.0.37: 22 vehicles) - * showOnlyWhenBought:b until the player owns it (208) - * showOnlyWhenAvailableForPurchase:b except while a promotion sells it (74) - * Removing these flags lets the stock rule show them. + * showOnlyWhenResearch:b until the player researches it (2.61.0.37: 22 + * vehicles, among them the Maus and the Panther II) + * showOnlyWhenAvailableForPurchase:b except while a promotion sells it (74 premium vehicles) + * showOnlyWhenBought:b unless the player owns it (208) + * The first two are removed, so the stock rule shows those vehicles. * - * Kept hidden: - * - the parts of split vehicles: a vehicle another entry names as its slaveUnit (2.61.0.37: the - * launchers of the 10 split air-defence systems) comes with its master vehicle and is not a - * vehicle of its own in the tech tree (local verification); - * - platform and language variants (showByPlatform, hideByPlatform, hideForLangs, - * hideFeature): they pick one of several versions of the same vehicle. + * showOnlyWhenBought stays: it marks vehicles that are not part of the tree for anyone who has + * not been given them: event and promotion prizes, mission copies of tree vehicles (nt_f_4e, + * f_4e_event ...), the drones of the premium columns, the floatplanes that come with ships, + * and the launchers of the split air-defence systems (lab round 20, user feedback). */ import type { BlkBlock } from '@wto/blk'; export const SHOP_PATH = 'config/shop.blk'; -const HIDING_FLAGS = new Set(['showOnlyWhenResearch', 'showOnlyWhenBought', 'showOnlyWhenAvailableForPurchase']); -const SLAVE_UNIT = 'slaveUnit'; +const HIDING_FLAGS = new Set(['showOnlyWhenResearch', 'showOnlyWhenAvailableForPurchase']); /** Remove the hiding flags in place; returns how many vehicles were hidden before. */ export function revealHiddenVehicles(shop: BlkBlock): number { - const entries = shopEntries(shop); - const parts = new Set(entries.flatMap((entry) => entry.params.flatMap((param) => (param.name === SLAVE_UNIT && param.value.type === 'string' ? [param.value.value] : [])))); let revealed = 0; - for (const entry of entries) { - if (parts.has(entry.name)) continue; + for (const entry of shopEntries(shop)) { const kept = entry.params.filter((param) => !HIDING_FLAGS.has(param.name)); if (kept.length === entry.params.length) continue; entry.params = kept; diff --git a/packages/local-service/src/char/actions/action-table.ts b/packages/local-service/src/char/actions/action-table.ts index 455368b..9b3710c 100644 --- a/packages/local-service/src/char/actions/action-table.ts +++ b/packages/local-service/src/char/actions/action-table.ts @@ -1,15 +1,20 @@ /** Char action names mapped to their handlers (full list of names: research-data/char_actions_37.json). */ import type { AccountStore } from '../../accounts/account-store.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts'; +import type { ResearchRules } from '../../research/research-rules.ts'; import type { CharActionHandler } from '../char-action.ts'; import { acceptEula } from './agreement-actions.ts'; import { bulkTrainCrews, trainCrew } from './crew-actions.ts'; import { entitlementsFull, initialMeta, legacyUserData } from './online-init-actions.ts'; +import { priceEx } from './price-actions.ts'; +import { buyAircraft, buySlot } from './purchase-actions.ts'; +import { convertExp, resetResearchable, setResearchable } from './research-actions.ts'; import { setStartingInfo } from './starting-info-actions.ts'; export interface ActionDependencies { readonly profiles: PlayerProfiles; readonly accounts: AccountStore; + readonly research: ResearchRules; } export function actionTable(deps: ActionDependencies): ReadonlyMap { @@ -21,5 +26,11 @@ export function actionTable(deps: ActionDependencies): ReadonlyMap ({ kind: 'data', blk: table }); +} diff --git a/packages/local-service/src/char/actions/purchase-actions.ts b/packages/local-service/src/char/actions/purchase-actions.ts new file mode 100644 index 0000000..658421e --- /dev/null +++ b/packages/local-service/src/char/actions/purchase-actions.ts @@ -0,0 +1,38 @@ +/** + * Purchase actions; the client applies each answer as a profile + * update, so each answers the whole profile. + * + * cln_buy_aircraft (char_send_blk, job type 13; gui.vromfs.bin scripts/unit/unitActions.nut + * impl_buyUnit): + * name:t the vehicle + * cost:i the silver lion price the client showed + * costGold:i the golden eagle price the client showed + * cln_buy_slot (purchase_crew_slot, aces.exe 2.61.0.37 0x1555a90 -> 0x2998f0, job type 10): + * country:t the country that gets one more crew slot + */ +import type { AccountStore } from '../../accounts/account-store.ts'; +import type { PlayerProfiles } from '../../profile/player-profiles.ts'; +import { buyCrewSlot } from '../../research/crew-slot-purchase.ts'; +import type { ResearchRules } from '../../research/research-rules.ts'; +import { buyVehicle } from '../../research/vehicle-purchase.ts'; +import type { CharActionHandler } from '../char-action.ts'; +import { intParam, stringParam } from './payload-params.ts'; +import { ruleAction } from './rule-answer.ts'; + +export function buyAircraft(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler { + return ruleAction(profiles, accounts, (payload) => { + const vehicle = stringParam(payload, 'name'); + const silverLions = intParam(payload, 'cost') ?? 0; + const goldenEagles = intParam(payload, 'costGold') ?? 0; + if (vehicle === undefined) return undefined; + return (profile) => buyVehicle(profile, rules, vehicle, { silverLions, goldenEagles }); + }); +} + +export function buySlot(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler { + return ruleAction(profiles, accounts, (payload) => { + const country = stringParam(payload, 'country'); + if (country === undefined) return undefined; + return (profile) => buyCrewSlot(profile, rules, country); + }); +} diff --git a/packages/local-service/src/char/actions/research-actions.ts b/packages/local-service/src/char/actions/research-actions.ts new file mode 100644 index 0000000..d4e6ca8 --- /dev/null +++ b/packages/local-service/src/char/actions/research-actions.ts @@ -0,0 +1,48 @@ +/** + * Research actions. All are sent with char_send_blk (job type 13), + * so the client applies each answer as a profile update and each answers the whole profile. + * + * cln_set_researchable (shop_set_researchable_unit, aces.exe 2.61.0.37 0x17a3e80): + * unit:t the vehicle to research + * type:i its vehicle type number + * cln_reset_researchable (shop_reset_researchable_unit, 0x17a3f00): the player closed the + * "research finished" prompt without choosing. + * country:t, type:i + * cln_convert_exp (shop_convert_free_exp_for_unit, 0x17a4ec0): free research points into a + * vehicle, paid with golden eagles. + * unit:t, amount:i research points + */ +import type { AccountStore } from '../../accounts/account-store.ts'; +import type { PlayerProfiles } from '../../profile/player-profiles.ts'; +import { chooseResearchTarget, convertFreeResearchPoints, dismissFinishedResearch } from '../../research/research-progress.ts'; +import type { ResearchRules } from '../../research/research-rules.ts'; +import type { CharActionHandler } from '../char-action.ts'; +import { intParam, stringParam } from './payload-params.ts'; +import { ruleAction } from './rule-answer.ts'; + +export function setResearchable(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler { + return ruleAction(profiles, accounts, (payload) => { + const vehicle = stringParam(payload, 'unit'); + const type = intParam(payload, 'type'); + if (vehicle === undefined || type === undefined) return undefined; + return (profile) => chooseResearchTarget(profile, rules, vehicle, type); + }); +} + +export function resetResearchable(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler { + return ruleAction(profiles, accounts, (payload) => { + const country = stringParam(payload, 'country'); + const type = intParam(payload, 'type'); + if (country === undefined || type === undefined) return undefined; + return (profile) => dismissFinishedResearch(profile, rules, country, type); + }); +} + +export function convertExp(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler { + return ruleAction(profiles, accounts, (payload) => { + const vehicle = stringParam(payload, 'unit'); + const amount = intParam(payload, 'amount'); + if (vehicle === undefined || amount === undefined) return undefined; + return (profile) => convertFreeResearchPoints(profile, rules, vehicle, amount); + }); +} diff --git a/packages/local-service/src/char/actions/rule-answer.ts b/packages/local-service/src/char/actions/rule-answer.ts new file mode 100644 index 0000000..720b9c3 --- /dev/null +++ b/packages/local-service/src/char/actions/rule-answer.ts @@ -0,0 +1,28 @@ +/** + * Actions that run one rule on the player's profile and answer the whole updated profile + * (job types the client applies as profile updates, implementation notes). A refused + * rule changes nothing and answers "!ERROR:". + */ +import type { BlkBlock } from '@wto/blk'; +import type { AccountStore } from '../../accounts/account-store.ts'; +import { clientProfile } from '../../profile/client-profile.ts'; +import type { PlayerProfiles } from '../../profile/player-profiles.ts'; +import type { RuleOutcome } from '../../research/rule-outcome.ts'; +import type { CharActionHandler } from '../char-action.ts'; +import { withAccount } from './account-context.ts'; + +/** Read the request into a rule (undefined: malformed request), run it, answer the outcome. */ +export function ruleAction(profiles: PlayerProfiles, accounts: AccountStore, + readRequest: (payload: BlkBlock) => ((profile: BlkBlock) => RuleOutcome) | undefined): CharActionHandler { + return (context) => withAccount(context, accounts, (account) => { + const rule = context.payload && readRequest(context.payload); + if (!rule) return { kind: 'error', code: 'BAD_PARAMS' }; + let outcome: RuleOutcome = { ok: false, refusal: 'BAD_PARAMS' }; + const profile = profiles.updateWhen(account.userId, (saved) => { + outcome = rule(saved); + return outcome.ok; + }); + if (profile) return { kind: 'data', blk: clientProfile(profile, account) }; + return { kind: 'error', code: outcome.ok ? 'BAD_PARAMS' : outcome.refusal }; + }); +} diff --git a/packages/local-service/src/game-data/datasets/blk-fields.ts b/packages/local-service/src/game-data/datasets/blk-fields.ts index 95118d4..63e2b5a 100644 --- a/packages/local-service/src/game-data/datasets/blk-fields.ts +++ b/packages/local-service/src/game-data/datasets/blk-fields.ts @@ -11,6 +11,11 @@ export function numberField(block: BlkBlock | undefined, name: string): number | return value?.type === 'int' || value?.type === 'real' ? value.value : undefined; } +export function boolField(block: BlkBlock | undefined, name: string): boolean | undefined { + const value = block && findParam(block, name)?.value; + return value?.type === 'bool' ? value.value : undefined; +} + /** Every string value of a repeated parameter, in order. */ export function stringList(block: BlkBlock | undefined, name: string): string[] { if (!block) return []; diff --git a/packages/local-service/src/game-data/datasets/rank-settings.ts b/packages/local-service/src/game-data/datasets/rank-settings.ts new file mode 100644 index 0000000..c0b591a --- /dev/null +++ b/packages/local-service/src/game-data/datasets/rank-settings.ts @@ -0,0 +1,55 @@ +/** + * Datasets from char.vromfs.bin config/rank.blk. + * + * needBuyToOpenNextInEra{ { needBuyToOpenNextInEra:i=N } } + * how many vehicles of a rank a country's branch must own before the next rank opens; the + * stock scripts also look up the name without the type (gui.vromfs.bin + * scripts/unit/unitInfo.nut getUnitsNeedBuyToOpenNextInEra). + * + * crew_slots{ slot{ cost:i costGold:i } } + * the price of a country's next crew slot when it has N crews (aces.exe 2.61.0.37 + * get_crew_slot_cost, 0x90eaa0). + */ +import { numberField } from './blk-fields.ts'; +import type { Dataset } from './dataset.ts'; + +const RANK = 'config/rank.blk'; +const SLOT = /^slot(\d+)$/; + +/** country -> parameter name -> vehicles needed, as written. */ +export type EraRequirements = Readonly>>>; + +export const eraRequirements: Dataset = { + id: 'era-requirements', + version: 1, + extract: (source) => { + const block = source.readBlk('char.vromfs.bin', RANK).blocks.find((child) => child.name === 'needBuyToOpenNextInEra'); + return Object.fromEntries((block?.blocks ?? []).map((country) => [ + country.name, + Object.fromEntries(country.params.flatMap((param) => (param.value.type === 'int' ? [[param.name, param.value.value]] : []))), + ])); + }, +}; + +export interface CrewSlotPrice { + readonly silverLions: number; + readonly goldenEagles: number; +} + +/** Indexed by the number of crews the country has; a missing index has no price (cannot be bought). */ +export type CrewSlotPrices = readonly (CrewSlotPrice | null)[]; + +export const crewSlotPrices: Dataset = { + id: 'crew-slot-prices', + version: 1, + extract: (source) => { + const block = source.readBlk('char.vromfs.bin', RANK).blocks.find((child) => child.name === 'crew_slots'); + const prices: (CrewSlotPrice | null)[] = []; + for (const slot of block?.blocks ?? []) { + const index = SLOT.exec(slot.name)?.[1]; + if (index === undefined) continue; + prices[Number(index)] = { silverLions: numberField(slot, 'cost') ?? 0, goldenEagles: numberField(slot, 'costGold') ?? 0 }; + } + return Array.from(prices, (price) => price ?? null); + }, +}; diff --git a/packages/local-service/src/game-data/datasets/research-point-rate.ts b/packages/local-service/src/game-data/datasets/research-point-rate.ts new file mode 100644 index 0000000..4fca0f1 --- /dev/null +++ b/packages/local-service/src/game-data/datasets/research-point-rate.ts @@ -0,0 +1,17 @@ +/** + * Dataset: how many free research points one golden eagle converts into a vehicle's research + * points (implementation notes, cln_convert_exp). + * + * char.vromfs.bin config/warpoints.blk playerExpToCountryFor1Gold:i (2.61.0.37: 45). The + * client reads it in wp_get_exp_convert_exp_for_gold_rate (aces.exe 0x1052af0 -> 0x916eb0), + * defaulting to 1; the price table can override it per country (exp_to_gold_rate), which the + * local service does not send. + */ +import { numberField } from './blk-fields.ts'; +import type { Dataset } from './dataset.ts'; + +export const researchPointsPerGoldenEagle: Dataset = { + id: 'research-point-rate', + version: 1, + extract: (source) => numberField(source.readBlk('char.vromfs.bin', 'config/warpoints.blk'), 'playerExpToCountryFor1Gold') ?? 1, +}; diff --git a/packages/local-service/src/game-data/datasets/vehicle-catalogue.ts b/packages/local-service/src/game-data/datasets/vehicle-catalogue.ts new file mode 100644 index 0000000..9a6bcf8 --- /dev/null +++ b/packages/local-service/src/game-data/datasets/vehicle-catalogue.ts @@ -0,0 +1,96 @@ +/** + * Dataset: every vehicle's research and purchase facts. + * + * The client takes a vehicle's economy from char.vromfs.bin config/wpcost.blk (gui.vromfs.bin + * scripts/unit/unit.nut initOnce; the native status function reads the same file, + * implementation notes): one block per vehicle with + * country:t the country whose tech tree and ranks it belongs to + * unitClass:t exp_fighter, exp_tank, ... (the vehicle type, implementation notes) + * rank:i + * reqAir:t the vehicle that has to be researched before it + * reqExp:i research points needed + * value:i price in silver lions + * costGold:i price in golden eagles + * premPackAir:b, gift:t, event:t, researchType:t premium, gift, event and squadron vehicles + * config/shop.blk places vehicles in the tech tree (country -> branch -> column -> vehicle, + * grouped vehicles one level deeper) and adds per-vehicle entries that matter here: + * reqUnlock:t an unlock from config/unlocks.blk the player must have earned first + * slaveUnit:t the separate part of a split vehicle (a launcher), which comes with it + * showOnlyWhenBought:b the stock UI only shows it to players who own it (kept by the build, + * packages/build reveal-hidden-vehicles.ts) + * + * Only what the files say is recorded; what it means for research is the rules layer's + * (research/tech-tree.ts). + */ +import type { BlkBlock } from '@wto/blk'; +import { boolField, numberField, stringField } from './blk-fields.ts'; +import type { Dataset } from './dataset.ts'; + +const VEHICLE_ECONOMY = 'config/wpcost.blk'; +const SHOP = 'config/shop.blk'; + +export interface CatalogueVehicle { + readonly name: string; + readonly country: string; + readonly unitClass: string; + readonly rank: number; + /** wpcost.blk reqAir; absent when empty or missing. */ + readonly requires?: string; + /** wpcost.blk reqExp; 0 when missing. */ + readonly researchPoints: number; + readonly silverLions: number; + readonly goldenEagles: number; + readonly premiumPack: boolean; + readonly gift: boolean; + readonly event: boolean; + readonly researchType?: string; + /** Listed in config/shop.blk. */ + readonly inTechTree: boolean; + /** shop.blk reqUnlock. */ + readonly requiredUnlock?: string; + /** shop.blk slaveUnit, repeated. */ + readonly parts: readonly string[]; + /** shop.blk showOnlyWhenBought. */ + readonly onlyShownWhenOwned: boolean; +} + +export const vehicleCatalogue: Dataset = { + id: 'vehicle-catalogue', + version: 2, + extract: (source) => { + const shopEntries = new Map(); + for (const country of source.readBlk('char.vromfs.bin', SHOP).blocks) { + for (const entry of entriesBelow(country)) if (!shopEntries.has(entry.name)) shopEntries.set(entry.name, entry); + } + return source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks.map((vehicle) => catalogueVehicle(vehicle, shopEntries.get(vehicle.name))); + }, +}; + +function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined): CatalogueVehicle { + const requires = stringField(vehicle, 'reqAir'); + const researchType = stringField(vehicle, 'researchType'); + const requiredUnlock = stringField(shopEntry, 'reqUnlock'); + return { + name: vehicle.name, + country: stringField(vehicle, 'country') ?? '', + unitClass: stringField(vehicle, 'unitClass') ?? '', + rank: numberField(vehicle, 'rank') ?? 0, + ...(requires ? { requires } : {}), + researchPoints: numberField(vehicle, 'reqExp') ?? 0, + silverLions: numberField(vehicle, 'value') ?? 0, + goldenEagles: numberField(vehicle, 'costGold') ?? 0, + premiumPack: boolField(vehicle, 'premPackAir') ?? false, + gift: stringField(vehicle, 'gift') !== undefined, + event: stringField(vehicle, 'event') !== undefined, + ...(researchType ? { researchType } : {}), + inTechTree: shopEntry !== undefined, + ...(requiredUnlock ? { requiredUnlock } : {}), + parts: shopEntry ? shopEntry.params.flatMap((param) => (param.name === 'slaveUnit' && param.value.type === 'string' && param.value.value ? [param.value.value] : [])) : [], + onlyShownWhenOwned: boolField(shopEntry, 'showOnlyWhenBought') ?? false, + }; +} + +/** Every block below a country: branches, columns, groups and vehicles (non-vehicles have no wpcost entry and are never looked up). */ +function entriesBelow(block: BlkBlock): BlkBlock[] { + return block.blocks.flatMap((child) => [child, ...entriesBelow(child)]); +} diff --git a/packages/local-service/src/game-data/datasets/vehicle-unlocks.ts b/packages/local-service/src/game-data/datasets/vehicle-unlocks.ts new file mode 100644 index 0000000..d681dc9 --- /dev/null +++ b/packages/local-service/src/game-data/datasets/vehicle-unlocks.ts @@ -0,0 +1,103 @@ +/** + * Dataset: the unlocks that vehicles depend on, with their conditions. + * + * char.vromfs.bin config/unlocks.blk: unlockable{ id:t type:t mode{ type:t ... } }. The + * conditions of type char_* are checked by the char server, which then records the unlock in + * the profile. Taken here: the unlocks config/shop.blk names as a vehicle's reqUnlock, every + * unlock of type "aircraft" (earning one gives the vehicle of the same name), and every + * unlock those name in their conditions, transitively (2.61.0.37: 73 roots, 131 in all). + * + * Mode parameters kept, as written: + * char_unlocks num:i, unlock:t (repeated) + * char_aircrafts_in_era country:t, era:i, num:i, unitClass:t (repeated), rankExactly:b, + * premium:b, clanUnits:b + * char_player_era country:t, era:i, unitClass:t + * A mode with condition{} sub-blocks is marked: those conditions (first battle, login time + * ...) belong to other features. + */ +import type { BlkBlock } from '@wto/blk'; +import { boolField, numberField, stringField, stringList } from './blk-fields.ts'; +import type { Dataset } from './dataset.ts'; + +const UNLOCKS = 'config/unlocks.blk'; +const SHOP = 'config/shop.blk'; +/** Unlocks of this type give the vehicle named by the unlock's id. */ +export const VEHICLE_UNLOCK_TYPE = 'aircraft'; + +export interface UnlockMode { + readonly type: string; + readonly num?: number; + readonly unlocks: readonly string[]; + readonly country?: string; + readonly era?: number; + readonly unitClasses: readonly string[]; + readonly rankExactly?: boolean; + readonly premium?: boolean; + readonly clanUnits?: boolean; + readonly hasOtherConditions: boolean; +} + +export interface UnlockDefinition { + readonly id: string; + readonly type: string; + readonly modes: readonly UnlockMode[]; +} + +export const vehicleUnlocks: Dataset = { + id: 'vehicle-unlocks', + version: 1, + extract: (source) => { + const definitions = new Map(); + for (const block of source.readBlk('char.vromfs.bin', UNLOCKS).blocks) { + if (block.name !== 'unlockable') continue; + const id = stringField(block, 'id'); + if (id && !definitions.has(id)) definitions.set(id, unlockDefinition(id, block)); + } + const roots = [ + ...requiredUnlocks(source.readBlk('char.vromfs.bin', SHOP)), + ...[...definitions.values()].filter((definition) => definition.type === VEHICLE_UNLOCK_TYPE).map((definition) => definition.id), + ]; + const kept = new Map(); + const pending = [...roots]; + while (pending.length) { + const definition = definitions.get(pending.pop()!); + if (!definition || kept.has(definition.id)) continue; + kept.set(definition.id, definition); + for (const mode of definition.modes) pending.push(...mode.unlocks); + } + return [...kept.values()]; + }, +}; + +function unlockDefinition(id: string, block: BlkBlock): UnlockDefinition { + return { id, type: stringField(block, 'type') ?? '', modes: block.blocks.filter((child) => child.name === 'mode').map(unlockMode) }; +} + +function unlockMode(mode: BlkBlock): UnlockMode { + const optional = { + num: numberField(mode, 'num'), + country: stringField(mode, 'country'), + era: numberField(mode, 'era'), + rankExactly: boolField(mode, 'rankExactly'), + premium: boolField(mode, 'premium'), + clanUnits: boolField(mode, 'clanUnits'), + }; + return { + type: stringField(mode, 'type') ?? '', + unlocks: stringList(mode, 'unlock'), + unitClasses: stringList(mode, 'unitClass'), + hasOtherConditions: mode.blocks.some((child) => child.name === 'condition'), + ...Object.fromEntries(Object.entries(optional).filter(([, value]) => value !== undefined)), + }; +} + +function requiredUnlocks(shop: BlkBlock): string[] { + const found: string[] = []; + const walk = (block: BlkBlock): void => { + const unlock = stringField(block, 'reqUnlock'); + if (unlock) found.push(unlock); + block.blocks.forEach(walk); + }; + shop.blocks.forEach(walk); + return found; +} diff --git a/packages/local-service/src/local-service.ts b/packages/local-service/src/local-service.ts index 2d6e6cb..9591ff3 100644 --- a/packages/local-service/src/local-service.ts +++ b/packages/local-service/src/local-service.ts @@ -9,17 +9,12 @@ import { CharService } from './char/char-service.ts'; import { DownloadableContentService } from './downloadable-content/downloadable-content-service.ts'; import { DatasetCache } from './game-data/datasets/dataset-cache.ts'; import { multiplayerMissions } from './game-data/datasets/multiplayer-missions.ts'; -import { reserveVehicles } from './game-data/datasets/reserve-vehicles.ts'; -import { shopBranches } from './game-data/datasets/shop-branches.ts'; import { shopCountries } from './game-data/datasets/shop-countries.ts'; import { GameFiles } from './game-data/game-files.ts'; import { GameModes } from './game-modes/game-modes.ts'; import { LoginService } from './login/login-service.ts'; import { matchingRequests } from './matching/matching-requests.ts'; -import { PlayerProfiles } from './profile/player-profiles.ts'; -import { profileUpgrades } from './profile/profile-upgrades.ts'; -import type { StartingContent } from './profile/starting-content.ts'; -import { SaveStore } from './saves/save-store.ts'; +import { setUpProfiles } from './profiles-setup.ts'; import { createPortListener } from './server/port-listener.ts'; import { Router } from './server/router.ts'; import { TrafficLog } from './traffic-log/traffic-log.ts'; @@ -47,16 +42,14 @@ export async function startLocalService(options: LocalServiceOptions): Promise 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; } diff --git a/packages/local-service/src/profile/profile-crews.ts b/packages/local-service/src/profile/profile-crews.ts index 4cd0668..581fd2d 100644 --- a/packages/local-service/src/profile/profile-crews.ts +++ b/packages/local-service/src/profile/profile-crews.ts @@ -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); diff --git a/packages/local-service/src/profile/profile-currency.ts b/packages/local-service/src/profile/profile-currency.ts index 37adf50..ea84bf6 100644 --- a/packages/local-service/src/profile/profile-currency.ts +++ b/packages/local-service/src/profile/profile-currency.ts @@ -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); diff --git a/packages/local-service/src/profile/profile-eras.ts b/packages/local-service/src/profile/profile-eras.ts index e3bd897..c7b3e08 100644 --- a/packages/local-service/src/profile/profile-eras.ts +++ b/packages/local-service/src/profile/profile-eras.ts @@ -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> = { - 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; } diff --git a/packages/local-service/src/profile/profile-hangar.ts b/packages/local-service/src/profile/profile-hangar.ts index 083bbf3..0546b59 100644 --- a/packages/local-service/src/profile/profile-hangar.ts +++ b/packages/local-service/src/profile/profile-hangar.ts @@ -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 { + 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); diff --git a/packages/local-service/src/profile/profile-research-points.ts b/packages/local-service/src/profile/profile-research-points.ts new file mode 100644 index 0000000..1f007d6 --- /dev/null +++ b/packages/local-service/src/profile/profile-research-points.ts @@ -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) }); +} diff --git a/packages/local-service/src/profile/profile-research-targets.ts b/packages/local-service/src/profile/profile-research-targets.ts new file mode 100644 index 0000000..2956a8d --- /dev/null +++ b/packages/local-service/src/profile/profile-research-targets.ts @@ -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 }); +} diff --git a/packages/local-service/src/profile/profile-unlocks.ts b/packages/local-service/src/profile/profile-unlocks.ts index 991787e..55851cd 100644 --- a/packages/local-service/src/profile/profile-unlocks.ts +++ b/packages/local-service/src/profile/profile-unlocks.ts @@ -27,6 +27,18 @@ const UNLOCKS = 'unlocks'; const UNLOCK = 'unlock'; const ITEM = 'item'; +/** The unlocks recorded as earned. */ +export function earnedUnlocks(profile: BlkBlock): Set { + const unlocks = profile.blocks.find((block) => block.name === UNLOCKS); + const earned = new Set(); + 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); diff --git a/packages/local-service/src/profile/profile-vehicle-research.ts b/packages/local-service/src/profile/profile-vehicle-research.ts new file mode 100644 index 0000000..4985118 --- /dev/null +++ b/packages/local-service/src/profile/profile-vehicle-research.ts @@ -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); +} diff --git a/packages/local-service/src/profile/starting-content.ts b/packages/local-service/src/profile/starting-content.ts index 713f8dc..cd5048f 100644 --- a/packages/local-service/src/profile/starting-content.ts +++ b/packages/local-service/src/profile/starting-content.ts @@ -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); } diff --git a/packages/local-service/src/profiles-setup.ts b/packages/local-service/src/profiles-setup.ts new file mode 100644 index 0000000..62b001c --- /dev/null +++ b/packages/local-service/src/profiles-setup.ts @@ -0,0 +1,28 @@ +/** + * Assemble the players' profiles with the rules they depend on, the same way for the local + * service and for the save editor (save-cli.ts): static data from the dataset cache, the + * save store with its format upgrades, and the research state kept up to date. + */ +import type { DatasetCache } from './game-data/datasets/dataset-cache.ts'; +import { reserveVehicles } from './game-data/datasets/reserve-vehicles.ts'; +import { shopBranches } from './game-data/datasets/shop-branches.ts'; +import type { GameFiles } from './game-data/game-files.ts'; +import { PlayerProfiles } from './profile/player-profiles.ts'; +import { profileUpgrades } from './profile/profile-upgrades.ts'; +import type { StartingContent } from './profile/starting-content.ts'; +import { refreshResearchState } from './research/research-state.ts'; +import { loadResearchRules, type ResearchRules } from './research/research-rules.ts'; +import { SaveStore } from './saves/save-store.ts'; + +export interface ProfileServices { + readonly profiles: PlayerProfiles; + readonly research: ResearchRules; +} + +export function setUpProfiles(dataFolder: string, gameFiles: GameFiles, datasets: DatasetCache): ProfileServices { + const startingContent: StartingContent = { reserveVehicles: datasets.load(reserveVehicles), branches: datasets.load(shopBranches) }; + const research = loadResearchRules(datasets); + const saves = new SaveStore(dataFolder, profileUpgrades(startingContent)); + const profiles = new PlayerProfiles(saves, gameFiles, startingContent, (profile) => refreshResearchState(profile, research)); + return { profiles, research }; +} diff --git a/packages/local-service/src/research/crew-slot-purchase.ts b/packages/local-service/src/research/crew-slot-purchase.ts new file mode 100644 index 0000000..f69cc5a --- /dev/null +++ b/packages/local-service/src/research/crew-slot-purchase.ts @@ -0,0 +1,23 @@ +/** + * Buying a crew slot (cln_buy_slot, implementation notes). + * + * The price of a country's next slot is config/rank.blk crew_slots slot, N being the + * number of crews the country has, as the client shows it (get_crew_slot_cost, aces.exe + * 2.61.0.37 0x90eaa0). Without a slot there is nothing more to buy. The new crew is empty + * and numbered after every existing crew. + */ +import type { BlkBlock } from '@wto/blk'; +import { addCrew, crewCountOf } from '../profile/profile-crews.ts'; +import { canAfford, pay } from '../profile/profile-currency.ts'; +import type { ResearchRules } from './research-rules.ts'; +import { ACCEPTED, refused, type RuleOutcome } from './rule-outcome.ts'; + +export function buyCrewSlot(profile: BlkBlock, rules: ResearchRules, country: string): RuleOutcome { + if (!rules.techTree.hasCountry(country)) return refused('BAD_PARAMS'); + const price = rules.crewSlotPrices[crewCountOf(profile, country)]; + if (!price) return refused('NOT_AVAILABLE'); + if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY'); + pay(profile, price); + addCrew(profile, country); + return ACCEPTED; +} diff --git a/packages/local-service/src/research/era-progress.ts b/packages/local-service/src/research/era-progress.ts new file mode 100644 index 0000000..983aa52 --- /dev/null +++ b/packages/local-service/src/research/era-progress.ts @@ -0,0 +1,42 @@ +/** + * Opening ranks. + * + * rank.blk needBuyToOpenNextInEra gives, per country, how many vehicles of rank k a vehicle + * type must own before rank k+1 opens: the name with the type first + * ("needBuyToOpenNextInEraTank3"), then without it ("needBuyToOpenNextInEra3"); neither means + * no requirement (scripts/unit/unitInfo.nut getUnitsNeedBuyToOpenNextInEra returns -1, which + * leaves nothing to buy). Owned vehicles count whatever their kind, at exactly that rank, as + * the stock tech tree counts them (scripts/shop/shop.nut updateBoughtVehiclesCount). Rank k+1 + * is open when every rank up to k has enough; rank I is always open. + */ +import type { BlkBlock } from '@wto/blk'; +import type { EraRequirements } from '../game-data/datasets/rank-settings.ts'; +import { openRanksUpTo } from '../profile/profile-eras.ts'; +import type { TechTree } from './tech-tree.ts'; +import type { VehicleType } from './vehicle-types.ts'; + +/** Open every rank the owned vehicles allow; ranks never close. Returns whether anything changed. */ +export function openEarnedRanks(profile: BlkBlock, owned: ReadonlySet, techTree: TechTree, requirements: EraRequirements): boolean { + const ownedByRank = new Map(); + for (const vehicle of techTree.all()) { + if (!owned.has(vehicle.name)) continue; + const key = rankKey(vehicle.country, vehicle.type, vehicle.rank); + ownedByRank.set(key, (ownedByRank.get(key) ?? 0) + 1); + } + let changed = false; + for (const { country, type, highestRank } of techTree.branches()) { + let open = 1; + while (open < highestRank && (ownedByRank.get(rankKey(country, type, open)) ?? 0) >= vehiclesNeeded(requirements, country, type, open)) open++; + if (openRanksUpTo(profile, country, type, open)) changed = true; + } + return changed; +} + +function vehiclesNeeded(requirements: EraRequirements, country: string, type: VehicleType, rank: number): number { + const forCountry = requirements[country]; + return forCountry?.[`needBuyToOpenNextInEra${type}${rank}`] ?? forCountry?.[`needBuyToOpenNextInEra${rank}`] ?? 0; +} + +function rankKey(country: string, type: VehicleType, rank: number): string { + return `${country}/${type}/${rank}`; +} diff --git a/packages/local-service/src/research/price-table.ts b/packages/local-service/src/research/price-table.ts new file mode 100644 index 0000000..7c6ffdb --- /dev/null +++ b/packages/local-service/src/research/price-table.ts @@ -0,0 +1,32 @@ +/** + * The price table the char server sends for cln_get_price_ex. + * + * The client keeps the answer whole as its price table (aces.exe 2.61.0.37 0xeb7a88, job type + * 0x21; stored in the save-data object at +0x3f5c0, which warpoints::init makes the price + * source, 0x105bb4d..0x105bb67). wp_get_cost / wp_get_cost_gold (0x10514f0 / 0x1051900) look + * a vehicle up under aircrafts/ (0x908a20) and read + * cost:i silver lions + * costGold:i golden eagles + * discount:i percent off (not sent: no discounts) + * A vehicle missing from the table costs 0 for the client, which then offers it at 0 (lab + * round 20). The prices are config/wpcost.blk value and costGold, the same the purchase rule + * charges (vehicle-purchase.ts). + */ +import type { BlkBlock } from '@wto/blk'; +import type { TechTree } from './tech-tree.ts'; + +export function priceTable(techTree: TechTree): BlkBlock { + const vehicles: BlkBlock[] = []; + for (const vehicle of techTree.all()) { + if (vehicle.silverLions <= 0 && vehicle.goldenEagles <= 0) continue; + vehicles.push({ + name: vehicle.name, + params: [ + { name: 'cost', value: { type: 'int', value: vehicle.silverLions } }, + { name: 'costGold', value: { type: 'int', value: vehicle.goldenEagles } }, + ], + blocks: [], + }); + } + return { name: '', params: [], blocks: [{ name: 'aircrafts', params: [], blocks: vehicles }] }; +} diff --git a/packages/local-service/src/research/research-progress.ts b/packages/local-service/src/research/research-progress.ts new file mode 100644 index 0000000..ea039db --- /dev/null +++ b/packages/local-service/src/research/research-progress.ts @@ -0,0 +1,67 @@ +/** + * Choosing what to research and putting research points into a vehicle (implementation notes + * sections 1.2, 4.3 and 5). + * + * - Choosing a research target (cln_set_researchable) makes a researchable vehicle the + * target of its country and type and closes the "research finished" prompt. + * - Dismissing that prompt (cln_reset_researchable) only closes it. + * - Converting free research points (cln_convert_exp) costs the points and golden eagles: + * one golden eagle per researchPointsPerGoldenEagle points, rounded up. The stock window + * (scripts/convertExp/convertExpHandler.nut) never asks for more than the vehicle still + * needs; more is cut down to that. + * - When a vehicle's research points reach what it needs and it is the target, the target is + * cleared and the vehicle recorded as just finished, which makes the client offer the next + * research. + */ +import type { BlkBlock } from '@wto/blk'; +import { balanceOf, pay } from '../profile/profile-currency.ts'; +import { freeResearchPoints, spendFreeResearchPoints } from '../profile/profile-research-points.ts'; +import { researchTarget, setFinishedResearch, setResearchTarget } from '../profile/profile-research-targets.ts'; +import { researchPointsOf, setResearchPoints } from '../profile/profile-vehicle-research.ts'; +import { currentStatus } from './research-state.ts'; +import type { ResearchRules } from './research-rules.ts'; +import { ACCEPTED, refused, type RuleOutcome } from './rule-outcome.ts'; +import type { TreeVehicle } from './tech-tree.ts'; +import { VehicleStatus } from './vehicle-status.ts'; +import { vehicleTypeById } from './vehicle-types.ts'; + +export function chooseResearchTarget(profile: BlkBlock, rules: ResearchRules, vehicleName: string, typeId: number): RuleOutcome { + const vehicle = rules.techTree.vehicle(vehicleName); + if (!vehicle || vehicleTypeById(typeId) !== vehicle.type) return refused('BAD_PARAMS'); + if (currentStatus(profile, rules, vehicleName) !== VehicleStatus.CAN_RESEARCH) return refused('NOT_AVAILABLE'); + setResearchTarget(profile, vehicle.country, vehicle.type, vehicle.name); + setFinishedResearch(profile, vehicle.country, vehicle.type, ''); + return ACCEPTED; +} + +export function dismissFinishedResearch(profile: BlkBlock, rules: ResearchRules, country: string, typeId: number): RuleOutcome { + const type = vehicleTypeById(typeId); + if (!type || !rules.techTree.hasCountry(country)) return refused('BAD_PARAMS'); + setFinishedResearch(profile, country, type, ''); + return ACCEPTED; +} + +export function convertFreeResearchPoints(profile: BlkBlock, rules: ResearchRules, vehicleName: string, requested: number): RuleOutcome { + const vehicle = rules.techTree.vehicle(vehicleName); + if (!vehicle || !Number.isSafeInteger(requested) || requested <= 0) return refused('BAD_PARAMS'); + if (currentStatus(profile, rules, vehicleName) !== VehicleStatus.CAN_RESEARCH) return refused('NOT_AVAILABLE'); + const amount = Math.min(requested, vehicle.researchPoints - researchPointsOf(profile, vehicle.name)); + const goldenEagles = Math.ceil(amount / rules.researchPointsPerGoldenEagle); + if (freeResearchPoints(profile) < amount) return refused('NOT_ENOUGH_RESEARCH_POINTS'); + if (balanceOf(profile).goldenEagles < goldenEagles) return refused('NOT_ENOUGH_MONEY'); + pay(profile, { silverLions: 0, goldenEagles }); + spendFreeResearchPoints(profile, amount); + addResearchPoints(profile, vehicle, amount); + return ACCEPTED; +} + +/** Add research points to a vehicle; finishing the research target opens the next-research prompt. */ +export function addResearchPoints(profile: BlkBlock, vehicle: TreeVehicle, amount: number): void { + const before = researchPointsOf(profile, vehicle.name); + setResearchPoints(profile, vehicle.name, before + amount); + const finished = before < vehicle.researchPoints && before + amount >= vehicle.researchPoints; + if (finished && researchTarget(profile, vehicle.country, vehicle.type) === vehicle.name) { + setResearchTarget(profile, vehicle.country, vehicle.type, ''); + setFinishedResearch(profile, vehicle.country, vehicle.type, vehicle.name); + } +} diff --git a/packages/local-service/src/research/research-rules.ts b/packages/local-service/src/research/research-rules.ts new file mode 100644 index 0000000..afc051d --- /dev/null +++ b/packages/local-service/src/research/research-rules.ts @@ -0,0 +1,28 @@ +/** + * The static facts research and purchase rules use, loaded once at start-up from the + * player's game files. + */ +import type { DatasetCache } from '../game-data/datasets/dataset-cache.ts'; +import { crewSlotPrices, eraRequirements, type CrewSlotPrices, type EraRequirements } from '../game-data/datasets/rank-settings.ts'; +import { researchPointsPerGoldenEagle } from '../game-data/datasets/research-point-rate.ts'; +import { vehicleCatalogue } from '../game-data/datasets/vehicle-catalogue.ts'; +import { vehicleUnlocks, type UnlockDefinition } from '../game-data/datasets/vehicle-unlocks.ts'; +import { TechTree } from './tech-tree.ts'; + +export interface ResearchRules { + readonly techTree: TechTree; + readonly eraRequirements: EraRequirements; + readonly vehicleUnlocks: readonly UnlockDefinition[]; + readonly crewSlotPrices: CrewSlotPrices; + readonly researchPointsPerGoldenEagle: number; +} + +export function loadResearchRules(datasets: DatasetCache): ResearchRules { + return { + techTree: new TechTree(datasets.load(vehicleCatalogue)), + eraRequirements: datasets.load(eraRequirements), + vehicleUnlocks: datasets.load(vehicleUnlocks), + crewSlotPrices: datasets.load(crewSlotPrices), + researchPointsPerGoldenEagle: datasets.load(researchPointsPerGoldenEagle), + }; +} diff --git a/packages/local-service/src/research/research-state.ts b/packages/local-service/src/research/research-state.ts new file mode 100644 index 0000000..6a0a126 --- /dev/null +++ b/packages/local-service/src/research/research-state.ts @@ -0,0 +1,51 @@ +/** + * Bringing the research state of a profile up to date. The char + * server keeps it current online; the local service does it whenever a profile is handed out + * or changed (profile/player-profiles.ts), so the state always follows from the facts: + * owned vehicles, research points, earned unlocks. + * + * 1. Open ranks and earn unlocks until neither changes anything (an unlock can give a vehicle, + * a vehicle can open a rank, a rank can earn an unlock). + * 2. Write every vehicle's status into unitResearch: owned vehicles have no entry, locked + * vehicles only keep one while they hold research points. + * 3. Drop research targets that are no longer researchable (bought, researched, ...). + */ +import type { BlkBlock } from '@wto/blk'; +import { ownedVehicles } from '../profile/profile-hangar.ts'; +import { researchTarget, setResearchTarget } from '../profile/profile-research-targets.ts'; +import { earnedUnlocks } from '../profile/profile-unlocks.ts'; +import { removeVehicleResearch, researchPointsOf, setVehicleStatus } from '../profile/profile-vehicle-research.ts'; +import { openEarnedRanks } from './era-progress.ts'; +import type { ResearchRules } from './research-rules.ts'; +import { earnVehicleUnlocks } from './vehicle-unlock-rules.ts'; +import { VehicleStatus, vehicleStatuses } from './vehicle-status.ts'; + +/** More rounds than any chain in the game data needs; stops a faulty data loop. */ +const MAX_ROUNDS = 16; + +export function refreshResearchState(profile: BlkBlock, rules: ResearchRules): void { + const owned = ownedVehicles(profile); + const earned = earnedUnlocks(profile); + for (let round = 0; round < MAX_ROUNDS; round++) { + const ranksChanged = openEarnedRanks(profile, owned, rules.techTree, rules.eraRequirements); + const unlocksChanged = earnVehicleUnlocks(profile, { earned, owned }, rules.vehicleUnlocks, rules.techTree); + if (!ranksChanged && !unlocksChanged) break; + } + + const statuses = vehicleStatuses({ profile, owned, earnedUnlocks: earned, techTree: rules.techTree }); + for (const vehicle of rules.techTree.all()) { + const status = statuses.get(vehicle.name); + if (status === undefined || (status === VehicleStatus.LOCKED && researchPointsOf(profile, vehicle.name) === 0)) removeVehicleResearch(profile, vehicle.name); + else setVehicleStatus(profile, vehicle.name, status); + } + + for (const { country, type } of rules.techTree.branches()) { + const target = researchTarget(profile, country, type); + if (target && statuses.get(target) !== VehicleStatus.CAN_RESEARCH) setResearchTarget(profile, country, type, ''); + } +} + +/** The current status of one vehicle the player does not own; undefined when it is owned or unknown. */ +export function currentStatus(profile: BlkBlock, rules: ResearchRules, vehicle: string): VehicleStatus | undefined { + return vehicleStatuses({ profile, owned: ownedVehicles(profile), earnedUnlocks: earnedUnlocks(profile), techTree: rules.techTree }).get(vehicle); +} diff --git a/packages/local-service/src/research/rule-outcome.ts b/packages/local-service/src/research/rule-outcome.ts new file mode 100644 index 0000000..497046d --- /dev/null +++ b/packages/local-service/src/research/rule-outcome.ts @@ -0,0 +1,19 @@ +/** What a research or purchase rule says about a player's request. */ + +export type Refusal = + /** The request names something that does not exist or does not fit (unknown vehicle, wrong type ...). */ + | 'BAD_PARAMS' + /** The vehicle's status does not allow it (locked, not researchable, already owned ...). */ + | 'NOT_AVAILABLE' + /** The price the client offered is not the current price. */ + | 'PRICE_CHANGED' + | 'NOT_ENOUGH_MONEY' + | 'NOT_ENOUGH_RESEARCH_POINTS'; + +export type RuleOutcome = { readonly ok: true } | { readonly ok: false; readonly refusal: Refusal }; + +export const ACCEPTED: RuleOutcome = { ok: true }; + +export function refused(refusal: Refusal): RuleOutcome { + return { ok: false, refusal }; +} diff --git a/packages/local-service/src/research/tech-tree.ts b/packages/local-service/src/research/tech-tree.ts new file mode 100644 index 0000000..db0a273 --- /dev/null +++ b/packages/local-service/src/research/tech-tree.ts @@ -0,0 +1,89 @@ +/** + * The vehicles as research and purchase see them: the catalogue (game-data vehicle-catalogue) + * with each vehicle's type and how it is obtained. + * + * Kinds, checked in this order: + * part the separate part of a split vehicle; comes with its main vehicle + * hidden shop.blk showOnlyWhenBought: event and promotion prizes, mission copies, + * drones, ship floatplanes; the stock UI only shows them to players who own + * them, so they are not offered + * squadron researchType clanVehicle: researched with squadron research points or bought + * early for golden eagles (feature-inventory I, later); no rank requirement + * gift gift:t: packs and marketplace vehicles; the stock scripts never offer them + * for silver lions or golden eagles (scripts/unit/unitShopInfo.nut + * canBuyUnitEvenNotInShop); the local shop gives them (feature-inventory G, later) + * event event:t (feature-inventory G, later) + * premium costGold > 0 or premPackAir (the scripts' isUnitSpecial): bought for golden + * eagles without research, rank or previous vehicle + * research reqExp > 0: researched, then bought + * purchase no reqExp: bought without research (helicopters that start a branch, free + * vehicles unlocked by an achievement, reserve vehicles) + */ +import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts'; +import { vehicleTypeOfClass, type VehicleType } from './vehicle-types.ts'; + +export type VehicleKind = 'part' | 'hidden' | 'squadron' | 'gift' | 'event' | 'premium' | 'research' | 'purchase'; + +export interface TreeVehicle extends CatalogueVehicle { + readonly type: VehicleType; + readonly kind: VehicleKind; +} + +const SQUADRON_RESEARCH = 'clanVehicle'; + +export class TechTree { + readonly #vehicles: ReadonlyMap; + + constructor(catalogue: readonly CatalogueVehicle[]) { + const parts = new Set(catalogue.filter((vehicle) => vehicle.inTechTree).flatMap((vehicle) => vehicle.parts)); + const vehicles = new Map(); + for (const vehicle of catalogue) { + const type = vehicleTypeOfClass(vehicle.unitClass); + // Without a type or country the client's status function locks the vehicle (0x911750, 0x961dd0). + if (type && vehicle.country) vehicles.set(vehicle.name, { ...vehicle, type, kind: kindOf(vehicle, parts) }); + } + this.#vehicles = vehicles; + } + + vehicle(name: string): TreeVehicle | undefined { + return this.#vehicles.get(name); + } + + /** Every vehicle with a type and country, in the tech tree or not. */ + all(): Iterable { + return this.#vehicles.values(); + } + + /** The countries and vehicle types that have vehicles in the tech tree, with their highest rank. */ + branches(): { country: string; type: VehicleType; highestRank: number }[] { + const highest = new Map(); + for (const vehicle of this.#vehicles.values()) { + if (!vehicle.inTechTree) continue; + const key = `${vehicle.country}/${vehicle.type}`; + const known = highest.get(key); + if (!known) highest.set(key, { country: vehicle.country, type: vehicle.type, highestRank: vehicle.rank }); + else known.highestRank = Math.max(known.highestRank, vehicle.rank); + } + return [...highest.values()]; + } + + hasCountry(country: string): boolean { + for (const vehicle of this.#vehicles.values()) if (vehicle.inTechTree && vehicle.country === country) return true; + return false; + } +} + +function kindOf(vehicle: CatalogueVehicle, parts: ReadonlySet): VehicleKind { + if (parts.has(vehicle.name)) return 'part'; + if (vehicle.onlyShownWhenOwned) return 'hidden'; + if (vehicle.researchType === SQUADRON_RESEARCH) return 'squadron'; + if (vehicle.gift) return 'gift'; + if (vehicle.event) return 'event'; + if (vehicle.goldenEagles > 0 || vehicle.premiumPack) return 'premium'; + return vehicle.researchPoints > 0 ? 'research' : 'purchase'; +} + +/** Premium-like vehicles for unlock conditions that count "premium" vehicles separately (unlocks.blk premium:b). */ +export function isPremiumKind(kind: VehicleKind): boolean { + return kind === 'premium' || kind === 'gift' || kind === 'event'; +} diff --git a/packages/local-service/src/research/vehicle-purchase.ts b/packages/local-service/src/research/vehicle-purchase.ts new file mode 100644 index 0000000..9ae6d60 --- /dev/null +++ b/packages/local-service/src/research/vehicle-purchase.ts @@ -0,0 +1,30 @@ +/** + * Buying a vehicle (cln_buy_aircraft, implementation notes). + * + * The vehicle must be buyable (status "can buy"). Its price is config/wpcost.blk value + * (silver lions) and costGold (golden eagles): the client prices it the same way + * (wp_get_cost / wp_get_cost_gold, aces.exe 2.61.0.37 0x9158a0) and only applies discounts + * from the price table, which the local service sends empty. The client sends the price it + * showed; a different one is refused, as when a discount ended online. The parts of a split + * vehicle come with it. + */ +import type { BlkBlock } from '@wto/blk'; +import { canAfford, pay, type Price } from '../profile/profile-currency.ts'; +import { addOwnedVehicle } from '../profile/profile-hangar.ts'; +import { currentStatus } from './research-state.ts'; +import type { ResearchRules } from './research-rules.ts'; +import { ACCEPTED, refused, type RuleOutcome } from './rule-outcome.ts'; +import { VehicleStatus } from './vehicle-status.ts'; + +export function buyVehicle(profile: BlkBlock, rules: ResearchRules, vehicleName: string, offered: Price): RuleOutcome { + const vehicle = rules.techTree.vehicle(vehicleName); + if (!vehicle) return refused('BAD_PARAMS'); + if (currentStatus(profile, rules, vehicleName) !== VehicleStatus.CAN_BUY) return refused('NOT_AVAILABLE'); + const price: Price = { silverLions: vehicle.silverLions, goldenEagles: vehicle.goldenEagles }; + if (offered.silverLions !== price.silverLions || offered.goldenEagles !== price.goldenEagles) return refused('PRICE_CHANGED'); + if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY'); + pay(profile, price); + addOwnedVehicle(profile, vehicle.name); + for (const part of vehicle.parts) addOwnedVehicle(profile, part); + return ACCEPTED; +} diff --git a/packages/local-service/src/research/vehicle-status.ts b/packages/local-service/src/research/vehicle-status.ts new file mode 100644 index 0000000..71cf1d8 --- /dev/null +++ b/packages/local-service/src/research/vehicle-status.ts @@ -0,0 +1,79 @@ +/** + * The status of each vehicle the player does not own, in + * the order of the stock explanation of why a vehicle cannot be bought or researched + * (gui.vromfs.bin scripts/unit/unitInfoTexts.nut getCantBuyUnitReason): + * + * not in the tech tree, part, hidden, gift, event locked + * reqUnlock not earned locked + * premium can buy + * rank not open (squadron vehicles have no rank gate) locked + * research points reached (or none needed): + * previous vehicle owned, or none can buy + * otherwise researched ("buy the previous first") + * not reached: + * previous vehicle researched or owned, or none can research + * otherwise locked + * + * "In research" is not a status the server gives: the client shows a researchable vehicle + * that way when it is the research target (aces.exe 2.61.0.37 0xebf7a0). + */ +import type { BlkBlock } from '@wto/blk'; +import { openRank } from '../profile/profile-eras.ts'; +import { researchPointsOf } from '../profile/profile-vehicle-research.ts'; +import type { TechTree, TreeVehicle } from './tech-tree.ts'; + +/** Values of shop_unit_research_status (registered from aces.exe 0x17dbc20). */ +export const VehicleStatus = { + LOCKED: 1, + CAN_RESEARCH: 2, + CAN_BUY: 8, + RESEARCHED: 0x40, +} as const; +export type VehicleStatus = (typeof VehicleStatus)[keyof typeof VehicleStatus]; + +const UNAVAILABLE_KINDS = new Set(['part', 'hidden', 'gift', 'event']); + +export interface StatusInputs { + readonly profile: BlkBlock; + readonly owned: ReadonlySet; + readonly earnedUnlocks: ReadonlySet; + readonly techTree: TechTree; +} + +/** Status of every vehicle the player does not own. */ +export function vehicleStatuses(inputs: StatusInputs): Map { + const statuses = new Map(); + const statusOf = (vehicle: TreeVehicle): VehicleStatus => { + let status = statuses.get(vehicle.name); + if (status === undefined) { + // Locked while being worked out, so a loop in the previous-vehicle data cannot recurse forever. + statuses.set(vehicle.name, VehicleStatus.LOCKED); + status = computeStatus(vehicle, inputs, statusOfName); + statuses.set(vehicle.name, status); + } + return status; + }; + const statusOfName = (name: string): VehicleStatus | 'owned' | undefined => { + if (inputs.owned.has(name)) return 'owned'; + const vehicle = inputs.techTree.vehicle(name); + return vehicle && statusOf(vehicle); + }; + for (const vehicle of inputs.techTree.all()) if (!inputs.owned.has(vehicle.name)) statusOf(vehicle); + return statuses; +} + +function computeStatus(vehicle: TreeVehicle, inputs: StatusInputs, statusOfName: (name: string) => VehicleStatus | 'owned' | undefined): VehicleStatus { + if (!vehicle.inTechTree || UNAVAILABLE_KINDS.has(vehicle.kind)) return VehicleStatus.LOCKED; + if (vehicle.requiredUnlock && !inputs.earnedUnlocks.has(vehicle.requiredUnlock)) return VehicleStatus.LOCKED; + if (vehicle.kind === 'premium') return VehicleStatus.CAN_BUY; + // getCantBuyUnitReason skips the rank check for squadron vehicles. + if (vehicle.kind !== 'squadron' && openRank(inputs.profile, vehicle.country, vehicle.type) < vehicle.rank) return VehicleStatus.LOCKED; + const previous = vehicle.requires === undefined ? 'owned' : statusOfName(vehicle.requires); + if (isResearched(vehicle, inputs.profile)) return previous === 'owned' ? VehicleStatus.CAN_BUY : VehicleStatus.RESEARCHED; + const previousResearched = previous === 'owned' || previous === VehicleStatus.CAN_BUY || previous === VehicleStatus.RESEARCHED; + return previousResearched ? VehicleStatus.CAN_RESEARCH : VehicleStatus.LOCKED; +} + +export function isResearched(vehicle: TreeVehicle, profile: BlkBlock): boolean { + return researchPointsOf(profile, vehicle.name) >= vehicle.researchPoints; +} diff --git a/packages/local-service/src/research/vehicle-types.ts b/packages/local-service/src/research/vehicle-types.ts new file mode 100644 index 0000000..3beec58 --- /dev/null +++ b/packages/local-service/src/research/vehicle-types.ts @@ -0,0 +1,56 @@ +/** + * Vehicle types as the client numbers and names them. + * + * Numbers: the ES unit type the scripts send (getEsUnitType; cln_set_researchable "type"). + * Names: the table at aces.exe 2.61.0.37 0x72b6d98 / 0x72b6d58, used in the profile's + * parameter names (eras "_", researchUnits "currUnit"). The type of a + * vehicle comes from its wpcost.blk unitClass, mapped as EconomicState::getUnitType does + * (0x911750, class table 0x72b6338). + */ + +export const VEHICLE_TYPES = ['Aircraft', 'Tank', 'Ship', 'Helicopter', 'Boat', 'Human', 'Transport'] as const; +export type VehicleType = (typeof VEHICLE_TYPES)[number]; + +const TYPE_OF_CLASS: Readonly> = { + exp_fighter: 'Aircraft', + exp_bomber: 'Aircraft', + exp_assault: 'Aircraft', + exp_tank: 'Tank', + exp_heavy_tank: 'Tank', + exp_tank_destroyer: 'Tank', + exp_SPAA: 'Tank', + exp_ship: 'Ship', + exp_destroyer: 'Ship', + exp_cruiser: 'Ship', + exp_torpedo_boat: 'Boat', + exp_gun_boat: 'Boat', + exp_torpedo_gun_boat: 'Boat', + exp_submarine_chaser: 'Boat', + exp_naval_ferry_barge: 'Boat', + exp_helicopter: 'Helicopter', + exp_human: 'Human', + exp_transport: 'Transport', +}; + +/** The tech-tree branches of config/shop.blk, as the stock scripts pair them (scripts/unit/unitTypesList.nut armyId). */ +const TYPE_OF_BRANCH: Readonly> = { + aviation: 'Aircraft', + army: 'Tank', + ships: 'Ship', + helicopters: 'Helicopter', + boats: 'Boat', +}; + +export function vehicleTypeOfClass(unitClass: string): VehicleType | undefined { + return TYPE_OF_CLASS[unitClass]; +} + +export function vehicleTypeOfBranch(branch: string): VehicleType { + const type = TYPE_OF_BRANCH[branch]; + if (!type) throw new Error(`unknown tech-tree branch: ${branch}`); + return type; +} + +export function vehicleTypeById(id: number): VehicleType | undefined { + return VEHICLE_TYPES[id]; +} diff --git a/packages/local-service/src/research/vehicle-unlock-rules.ts b/packages/local-service/src/research/vehicle-unlock-rules.ts new file mode 100644 index 0000000..50ef8ac --- /dev/null +++ b/packages/local-service/src/research/vehicle-unlock-rules.ts @@ -0,0 +1,90 @@ +/** + * Earning the unlocks vehicles depend on. The char server checks + * these conditions and records the unlock; an unlock of type "aircraft" also gives the + * vehicle of the same name. + * + * char_unlocks at least num of the listed unlocks are earned + * char_aircrafts_in_era the player owns at least num vehicles of the country (if given) + * whose class is listed, at rank era or above (exactly era with + * rankExactly); premium and squadron vehicles only count with + * premium:b=yes / clanUnits:b=yes + * char_player_era the country has rank era open for the class + * Other condition types, and modes with extra condition{} blocks (first battle, logins ...), + * are left to the features they belong to and count as not met. + * + * Unlock classes: "tank", "ship", "boat", "helicopter", and "aircraft" for aircraft and + * helicopters ("aircraft_only" is the aircraft alone). That "aircraft" includes helicopters + * is inferred from the separate "aircraft_only" class. + */ +import type { BlkBlock } from '@wto/blk'; +import { VEHICLE_UNLOCK_TYPE, type UnlockDefinition, type UnlockMode } from '../game-data/datasets/vehicle-unlocks.ts'; +import { openRank } from '../profile/profile-eras.ts'; +import { addOwnedVehicle } from '../profile/profile-hangar.ts'; +import { addUnlock } from '../profile/profile-unlocks.ts'; +import { isPremiumKind, type TechTree } from './tech-tree.ts'; +import type { VehicleType } from './vehicle-types.ts'; + +const TYPES_OF_UNLOCK_CLASS: Readonly> = { + aircraft: ['Aircraft', 'Helicopter'], + aircraft_only: ['Aircraft'], + helicopter: ['Helicopter'], + tank: ['Tank'], + ship: ['Ship'], + boat: ['Boat'], +}; + +export interface UnlockState { + readonly earned: Set; + readonly owned: Set; +} + +/** Earn every unlock whose condition holds; returns whether anything changed. */ +export function earnVehicleUnlocks(profile: BlkBlock, state: UnlockState, definitions: readonly UnlockDefinition[], techTree: TechTree): boolean { + let changed = false; + for (const definition of definitions) { + if (state.earned.has(definition.id) || !definition.modes.some((mode) => modeHolds(mode, profile, state, techTree))) continue; + addUnlock(profile, definition.id); + state.earned.add(definition.id); + if (definition.type === VEHICLE_UNLOCK_TYPE && techTree.vehicle(definition.id) && !state.owned.has(definition.id)) { + addOwnedVehicle(profile, definition.id); + state.owned.add(definition.id); + } + changed = true; + } + return changed; +} + +function modeHolds(mode: UnlockMode, profile: BlkBlock, state: UnlockState, techTree: TechTree): boolean { + if (mode.hasOtherConditions) return false; + switch (mode.type) { + case 'char_unlocks': + return mode.unlocks.filter((unlock) => state.earned.has(unlock)).length >= (mode.num ?? mode.unlocks.length); + case 'char_aircrafts_in_era': + return ownedInEra(mode, state.owned, techTree) >= (mode.num ?? 1); + case 'char_player_era': + return mode.country !== undefined && mode.era !== undefined + && typesOf(mode).some((type) => openRank(profile, mode.country!, type) >= mode.era!); + default: + return false; + } +} + +function ownedInEra(mode: UnlockMode, owned: ReadonlySet, techTree: TechTree): number { + const types = new Set(typesOf(mode)); + const era = mode.era ?? 1; + let count = 0; + for (const name of owned) { + const vehicle = techTree.vehicle(name); + if (!vehicle || !types.has(vehicle.type)) continue; + if (mode.country !== undefined && vehicle.country !== mode.country) continue; + if (mode.rankExactly ? vehicle.rank !== era : vehicle.rank < era) continue; + if (!mode.premium && isPremiumKind(vehicle.kind)) continue; + if (!mode.clanUnits && vehicle.kind === 'squadron') continue; + count++; + } + return count; +} + +function typesOf(mode: UnlockMode): VehicleType[] { + return mode.unitClasses.flatMap((unitClass) => TYPES_OF_UNLOCK_CLASS[unitClass] ?? []); +} diff --git a/packages/local-service/src/save-cli.ts b/packages/local-service/src/save-cli.ts index c283c16..5bdf52a 100644 --- a/packages/local-service/src/save-cli.ts +++ b/packages/local-service/src/save-cli.ts @@ -3,22 +3,19 @@ * section A; the launcher will call the same profile functions). * * node packages/local-service/src/save-cli.ts --game --data - * --player [--silver ] [--gold ] + * --player [--silver ] [--gold ] [--free-rp ] * - * Without --silver / --gold it only prints the balance. The edit is written to the save; the + * --free-rp sets the free research points. Without any amount it + * only prints the balance. The edit is written to the save; the * game shows it after its next profile update (any action, or signing in again). */ import { parseArgs } from 'node:util'; import { AccountStore } from './accounts/account-store.ts'; import { DatasetCache } from './game-data/datasets/dataset-cache.ts'; -import { reserveVehicles } from './game-data/datasets/reserve-vehicles.ts'; -import { shopBranches } from './game-data/datasets/shop-branches.ts'; import { GameFiles } from './game-data/game-files.ts'; -import { PlayerProfiles } from './profile/player-profiles.ts'; import { balanceOf, setGoldenEagles, setSilverLions } from './profile/profile-currency.ts'; -import { profileUpgrades } from './profile/profile-upgrades.ts'; -import type { StartingContent } from './profile/starting-content.ts'; -import { SaveStore } from './saves/save-store.ts'; +import { freeResearchPoints, setFreeResearchPoints } from './profile/profile-research-points.ts'; +import { setUpProfiles } from './profiles-setup.ts'; function main(): number { const { values } = parseArgs({ @@ -28,16 +25,18 @@ function main(): number { player: { type: 'string' }, silver: { type: 'string' }, gold: { type: 'string' }, + 'free-rp': { type: 'string' }, }, }); if (!values.game || !values.data || !values.player) { - console.error('usage: save-cli.ts --game --data --player [--silver ] [--gold ]'); + console.error('usage: save-cli.ts --game --data --player [--silver ] [--gold ] [--free-rp ]'); return 2; } const silver = optionalAmount(values.silver); const gold = optionalAmount(values.gold); - if (silver === null || gold === null) { - console.error('--silver and --gold take a whole number of 0 or more'); + const freeRp = optionalAmount(values['free-rp']); + if (silver === null || gold === null || freeRp === null) { + console.error('--silver, --gold and --free-rp take a whole number of 0 or more'); return 2; } @@ -49,17 +48,17 @@ function main(): number { } const gameFiles = new GameFiles(values.game); const datasets = new DatasetCache(values.data, gameFiles, () => {}); - const startingContent: StartingContent = { reserveVehicles: datasets.load(reserveVehicles), branches: datasets.load(shopBranches) }; - const profiles = new PlayerProfiles(new SaveStore(values.data, profileUpgrades(startingContent)), gameFiles, startingContent); + const { profiles } = setUpProfiles(values.data, gameFiles, datasets); - const profile = silver === undefined && gold === undefined + const profile = silver === undefined && gold === undefined && freeRp === undefined ? profiles.profileOf(account.userId) : profiles.update(account.userId, (saved) => { if (silver !== undefined) setSilverLions(saved, silver); if (gold !== undefined) setGoldenEagles(saved, gold); + if (freeRp !== undefined) setFreeResearchPoints(saved, freeRp); }); const balance = balanceOf(profile); - console.log(`${account.login} (${account.userId}): ${balance.silverLions} silver lions, ${balance.goldenEagles} golden eagles`); + console.log(`${account.login} (${account.userId}): ${balance.silverLions} silver lions, ${balance.goldenEagles} golden eagles, ${freeResearchPoints(profile)} free research points`); return 0; }