diff --git a/packages/local-service/src/char/actions/action-table.ts b/packages/local-service/src/char/actions/action-table.ts index 9b3710c..5f88bba 100644 --- a/packages/local-service/src/char/actions/action-table.ts +++ b/packages/local-service/src/char/actions/action-table.ts @@ -5,6 +5,7 @@ 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 { buyAllModificationsAction, buyModificationAction, buySparesAction, enableModificationsAction } from './modification-actions.ts'; import { entitlementsFull, initialMeta, legacyUserData } from './online-init-actions.ts'; import { priceEx } from './price-actions.ts'; import { buyAircraft, buySlot } from './purchase-actions.ts'; @@ -32,5 +33,9 @@ export function actionTable(deps: ActionDependencies): ReadonlyMap 0x29a890; lab round 18): + * { :b=yes ... } ... + */ +import type { BlkBlock } from '@wto/blk'; +import type { AccountStore } from '../../accounts/account-store.ts'; +import { buyAllModifications, buyModification, enableModifications } from '../../modifications/modification-purchase.ts'; +import { buySpares } from '../../modifications/spare-purchase.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 { boolParam, intParam, stringParam } from './payload-params.ts'; +import { ruleAction } from './rule-answer.ts'; + +export function buyModificationAction(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler { + return ruleAction(profiles, accounts, (payload) => { + const vehicle = stringParam(payload, 'aircraft'); + const modification = stringParam(payload, 'modification'); + if (vehicle === undefined || modification === undefined) return undefined; + const order = { + vehicle, + modification, + outright: boolParam(payload, 'open') ?? false, + amount: intParam(payload, 'count') ?? 1, + offered: offeredPrice(payload), + }; + return (profile) => buyModification(profile, rules.equipment, order); + }); +} + +export function buyAllModificationsAction(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler { + return ruleAction(profiles, accounts, (payload) => { + const vehicle = stringParam(payload, 'unit'); + if (vehicle === undefined) return undefined; + const outright = boolParam(payload, 'forceOpen') ?? false; + const offered = offeredPrice(payload); + return (profile) => buyAllModifications(profile, rules.equipment, vehicle, outright, offered); + }); +} + +export function buySparesAction(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler { + return ruleAction(profiles, accounts, (payload) => { + const vehicle = stringParam(payload, 'aircraft'); + if (vehicle === undefined) return undefined; + const amount = intParam(payload, 'count') ?? 1; + const offered = offeredPrice(payload); + return (profile) => buySpares(profile, rules.equipment, vehicle, amount, offered); + }); +} + +export function enableModificationsAction(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler { + return ruleAction(profiles, accounts, (payload) => { + const switches = payload.blocks.flatMap((vehicle) => vehicle.params.flatMap((param) => + param.value.type === 'bool' ? [{ vehicle: vehicle.name, modification: param.name, enabled: param.value.value }] : [])); + return (profile) => enableModifications(profile, switches); + }); +} + +function offeredPrice(payload: BlkBlock) { + return { silverLions: intParam(payload, 'cost') ?? 0, goldenEagles: intParam(payload, 'costGold') ?? 0 }; +} diff --git a/packages/local-service/src/char/actions/payload-params.ts b/packages/local-service/src/char/actions/payload-params.ts index 6206a71..24b7f6a 100644 --- a/packages/local-service/src/char/actions/payload-params.ts +++ b/packages/local-service/src/char/actions/payload-params.ts @@ -10,3 +10,8 @@ export function intParam(payload: BlkBlock, name: string): number | undefined { const value = findParam(payload, name)?.value; return value?.type === 'int' ? value.value : undefined; } + +export function boolParam(payload: BlkBlock, name: string): boolean | undefined { + const value = findParam(payload, name)?.value; + return value?.type === 'bool' ? value.value : undefined; +} diff --git a/packages/local-service/src/char/actions/price-actions.ts b/packages/local-service/src/char/actions/price-actions.ts index a2b5fd3..35484f3 100644 --- a/packages/local-service/src/char/actions/price-actions.ts +++ b/packages/local-service/src/char/actions/price-actions.ts @@ -9,6 +9,6 @@ import { priceTable } from '../../research/price-table.ts'; import type { ResearchRules } from '../../research/research-rules.ts'; export function priceEx(rules: ResearchRules): CharActionHandler { - const table = priceTable(rules.techTree); + const table = priceTable(rules.techTree, rules.equipment); return () => ({ kind: 'data', blk: table }); } diff --git a/packages/local-service/src/char/actions/research-actions.ts b/packages/local-service/src/char/actions/research-actions.ts index d4e6ca8..1c1ef54 100644 --- a/packages/local-service/src/char/actions/research-actions.ts +++ b/packages/local-service/src/char/actions/research-actions.ts @@ -5,6 +5,9 @@ * 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 + * or, for a modification (shop_set_researchable_unit_module, 0x17a3e00; implementation notes): + * unit:t the owned vehicle + * mod:t the modification to research * cln_reset_researchable (shop_reset_researchable_unit, 0x17a3f00): the player closed the * "research finished" prompt without choosing. * country:t, type:i @@ -14,6 +17,7 @@ */ import type { AccountStore } from '../../accounts/account-store.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts'; +import { chooseModuleResearch } from '../../modifications/module-research-target.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'; @@ -23,6 +27,8 @@ 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 modification = stringParam(payload, 'mod'); + if (vehicle !== undefined && modification !== undefined) return (profile) => chooseModuleResearch(profile, rules.equipment, vehicle, modification); const type = intParam(payload, 'type'); if (vehicle === undefined || type === undefined) return undefined; return (profile) => chooseResearchTarget(profile, rules, vehicle, type); diff --git a/packages/local-service/src/game-data/datasets/vehicle-equipment.ts b/packages/local-service/src/game-data/datasets/vehicle-equipment.ts new file mode 100644 index 0000000..a706796 --- /dev/null +++ b/packages/local-service/src/game-data/datasets/vehicle-equipment.ts @@ -0,0 +1,92 @@ +/** + * Dataset: every vehicle's modifications, ammunition, weapon presets and spare, with their + * research and purchase facts. + * + * char.vromfs.bin config/wpcost.blk, per vehicle: + * needBuyToOpenNextInTier:i researched modifications of tier N needed to open tier N+1 + * modifications{ { tier:i reqExp:i value:i costGold:i openCostGold:i + * reqModification:t (repeated) maxCount:i ammoCount:i ... } } + * Ammunition and expendables are modifications too (tier 0, maxCount, ammoCount). + * weapons{ { value:i costGold:i maxCount:i reqModification:t ... } } + * spare{ value:i costGold:i } + * + * Only what the file says is recorded; what it means is the rules layer's (modifications/). + */ +import type { BlkBlock } from '@wto/blk'; +import { findBlock } from '@wto/blk'; +import { numberField, stringList } from './blk-fields.ts'; +import type { Dataset } from './dataset.ts'; + +const VEHICLE_ECONOMY = 'config/wpcost.blk'; +/** wpcost.blk has needBuyToOpenNextInTier1..4; the modification tree has tiers 1..5 at most. */ +const TIER_REQUIREMENT_COUNT = 4; + +export interface ModificationFacts { + readonly name: string; + readonly tier: number; + /** reqExp; 0 when the modification is not researched (ammunition, expendables, premium). */ + readonly researchPoints: number; + readonly silverLions: number; + readonly goldenEagles: number; + /** openCostGold: golden eagles to get it without the research (scaled by progress, implementation notes). */ + readonly openGoldenEagles: number; + /** reqModification, repeated: modifications that must be bought first. */ + readonly requires: readonly string[]; + /** maxCount; 0 when the modification is not counted (bought once). */ + readonly maxCount: number; + /** ammoCount present: an ammunition belt or shell type. */ + readonly ammunition: boolean; +} + +export interface PriceFacts { + readonly name: string; + readonly silverLions: number; + readonly goldenEagles: number; +} + +export interface VehicleEquipment { + readonly vehicle: string; + /** needBuyToOpenNextInTier1..4 (index 0 = tier 1). */ + readonly tierRequirements: readonly number[]; + readonly modifications: readonly ModificationFacts[]; + readonly weapons: readonly PriceFacts[]; + /** spare; absent when the vehicle has no spare price. */ + readonly spare?: { readonly silverLions: number; readonly goldenEagles: number }; +} + +export const vehicleEquipment: Dataset = { + id: 'vehicle-equipment', + version: 1, + extract: (source) => source.readBlk('char.vromfs.bin', VEHICLE_ECONOMY).blocks.map(equipmentOf), +}; + +function equipmentOf(vehicle: BlkBlock): VehicleEquipment { + const tierRequirements: number[] = []; + for (let tier = 1; tier <= TIER_REQUIREMENT_COUNT; tier++) tierRequirements.push(numberField(vehicle, `needBuyToOpenNextInTier${tier}`) ?? 0); + const spare = findBlock(vehicle, 'spare'); + return { + vehicle: vehicle.name, + tierRequirements, + modifications: (findBlock(vehicle, 'modifications')?.blocks ?? []).map(modificationOf), + weapons: (findBlock(vehicle, 'weapons')?.blocks ?? []).map(priceOf), + ...(spare ? { spare: { silverLions: numberField(spare, 'value') ?? 0, goldenEagles: numberField(spare, 'costGold') ?? 0 } } : {}), + }; +} + +function modificationOf(modification: BlkBlock): ModificationFacts { + return { + name: modification.name, + tier: numberField(modification, 'tier') ?? 0, + researchPoints: numberField(modification, 'reqExp') ?? 0, + silverLions: numberField(modification, 'value') ?? 0, + goldenEagles: numberField(modification, 'costGold') ?? 0, + openGoldenEagles: numberField(modification, 'openCostGold') ?? 0, + requires: stringList(modification, 'reqModification'), + maxCount: numberField(modification, 'maxCount') ?? 0, + ammunition: numberField(modification, 'ammoCount') !== undefined, + }; +} + +function priceOf(entry: BlkBlock): PriceFacts { + return { name: entry.name, silverLions: numberField(entry, 'value') ?? 0, goldenEagles: numberField(entry, 'costGold') ?? 0 }; +} diff --git a/packages/local-service/src/modifications/equipment-catalogue.ts b/packages/local-service/src/modifications/equipment-catalogue.ts new file mode 100644 index 0000000..875c012 --- /dev/null +++ b/packages/local-service/src/modifications/equipment-catalogue.ts @@ -0,0 +1,39 @@ +/** + * Lookup over the vehicle-equipment dataset (game-data/datasets/vehicle-equipment.ts), plus the + * classifications the rules need. + */ +import type { ModificationFacts, VehicleEquipment } from '../game-data/datasets/vehicle-equipment.ts'; + +export class EquipmentCatalogue { + readonly #byVehicle: ReadonlyMap; + + constructor(equipment: readonly VehicleEquipment[]) { + this.#byVehicle = new Map(equipment.map((entry) => [entry.vehicle, entry])); + } + + vehicle(name: string): VehicleEquipment | undefined { + return this.#byVehicle.get(name); + } + + modification(vehicle: string, name: string): ModificationFacts | undefined { + return this.#byVehicle.get(vehicle)?.modifications.find((modification) => modification.name === name); + } +} + +/** Has to be researched before it can be bought (tier 1 and up, with research points). */ +export function isResearchable(modification: ModificationFacts): boolean { + return modification.tier >= 1 && modification.researchPoints > 0; +} + +/** + * Counts towards opening the next tier: the client's isModificationInTree (scripts + * weaponry/modsTree.nut) leaves out hidden, golden-eagle and ammunition modifications. + */ +export function countsForTier(modification: ModificationFacts): boolean { + return isResearchable(modification) && modification.goldenEagles === 0 && !modification.ammunition; +} + +/** Bought in amounts (ammunition, expendables): maxCount above 1. */ +export function isCounted(modification: ModificationFacts): boolean { + return modification.maxCount > 1; +} diff --git a/packages/local-service/src/modifications/modification-purchase.ts b/packages/local-service/src/modifications/modification-purchase.ts new file mode 100644 index 0000000..0c65eb9 --- /dev/null +++ b/packages/local-service/src/modifications/modification-purchase.ts @@ -0,0 +1,138 @@ +/** + * Buying and switching modifications: + * + * cln_buy_modification one modification, ammunition or expendable; with open:b=yes a + * researchable one is bought outright for golden eagles + * cln_buy_all_modification everything the vehicle can buy now (forceOpen: also outright) + * cln_enable_modifications switch bought modifications on or off + * + * Prices: silver lions and golden eagles from wpcost.blk times the amount; the outright price is + * max(1, openCostGold * (reqExp - points so far) / reqExp), points capped at reqExp, rounded + * down (aces.exe 0xec0910). A plain modification is bought once and comes mounted; counted ones + * (maxCount above 1) add to the amount up to maxCount. + */ +import type { BlkBlock } from '@wto/blk'; +import type { ModificationFacts } from '../game-data/datasets/vehicle-equipment.ts'; +import { canAfford, pay, type Price } from '../profile/profile-currency.ts'; +import { ownsVehicle } from '../profile/profile-hangar.ts'; +import { modificationRecord, writeModificationRecord } from '../profile/profile-modifications.ts'; +import { moduleResearchPoints, removeModuleResearch } from '../profile/profile-module-research.ts'; +import { moduleResearchTarget, setModuleResearchTarget } from '../profile/profile-vehicle-state.ts'; +import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; +import { isCounted, isResearchable, type EquipmentCatalogue } from './equipment-catalogue.ts'; +import { currentModuleStatus } from './module-state.ts'; +import { ModuleStatus } from './module-status.ts'; + +export interface ModificationOrder { + readonly vehicle: string; + readonly modification: string; + /** Bought outright for golden eagles instead of after research. */ + readonly outright: boolean; + readonly amount: number; + readonly offered: Price; +} + +export function buyModification(profile: BlkBlock, catalogue: EquipmentCatalogue, order: ModificationOrder): RuleOutcome { + const modification = catalogue.modification(order.vehicle, order.modification); + if (!modification || !ownsVehicle(profile, order.vehicle) || order.amount < 1) return refused('BAD_PARAMS'); + const purchase = order.outright ? outrightPurchase(profile, order.vehicle, modification, catalogue) + : regularPurchase(profile, order.vehicle, modification, catalogue, order.amount); + if (!purchase) return refused('NOT_AVAILABLE'); + if (purchase.price.silverLions !== order.offered.silverLions || purchase.price.goldenEagles !== order.offered.goldenEagles) return refused('PRICE_CHANGED'); + if (!canAfford(profile, purchase.price)) return refused('NOT_ENOUGH_MONEY'); + pay(profile, purchase.price); + addToRecord(profile, order.vehicle, modification, purchase); + return ACCEPTED; +} + +export function buyAllModifications(profile: BlkBlock, catalogue: EquipmentCatalogue, vehicle: string, outright: boolean, offered: Price): RuleOutcome { + const equipment = catalogue.vehicle(vehicle); + if (!equipment || !ownsVehicle(profile, vehicle)) return refused('BAD_PARAMS'); + const purchases = equipment.modifications.flatMap((modification) => { + const purchase = buyAllEntry(profile, vehicle, modification, catalogue, outright); + return purchase ? [{ modification, purchase }] : []; + }); + const price = purchases.reduce((sum, { purchase }) => ({ + silverLions: sum.silverLions + purchase.price.silverLions, + goldenEagles: sum.goldenEagles + purchase.price.goldenEagles, + }), { silverLions: 0, goldenEagles: 0 }); + if (purchases.length === 0) return refused('NOT_AVAILABLE'); + if (price.silverLions !== offered.silverLions || price.goldenEagles !== offered.goldenEagles) return refused('PRICE_CHANGED'); + if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY'); + pay(profile, price); + for (const { modification, purchase } of purchases) addToRecord(profile, vehicle, modification, purchase); + return ACCEPTED; +} + +/** Switches are applied to bought modifications only; the rest of the request is ignored. */ +export function enableModifications(profile: BlkBlock, switches: readonly { vehicle: string; modification: string; enabled: boolean }[]): RuleOutcome { + for (const { vehicle, modification, enabled } of switches) { + const record = modificationRecord(profile, vehicle, modification); + if (record && record.enabled !== enabled) writeModificationRecord(profile, vehicle, modification, { ...record, enabled }); + } + return ACCEPTED; +} + +/** The outright price (aces.exe 0xec0910). */ +export function outrightPrice(profile: BlkBlock, vehicle: string, modification: ModificationFacts): number { + const required = modification.researchPoints; + if (required <= 0 || modification.openGoldenEagles <= 0) return modification.openGoldenEagles; + const earned = Math.min(moduleResearchPoints(profile, vehicle, modification.name), required); + return Math.max(1, Math.floor(modification.openGoldenEagles * (required - earned) / required)); +} + +interface Purchase { + readonly price: Price; + readonly amount: number; +} + +function regularPurchase(profile: BlkBlock, vehicle: string, modification: ModificationFacts, catalogue: EquipmentCatalogue, amount: number): Purchase | undefined { + const record = modificationRecord(profile, vehicle, modification.name); + if (record) { + if (!isCounted(modification) || record.count + amount > modification.maxCount) return undefined; + } + else if (currentModuleStatus(profile, catalogue, vehicle, modification.name) !== ModuleStatus.CAN_BUY) return undefined; + if (!isCounted(modification) && amount !== 1) return undefined; + if (isCounted(modification) && amount > modification.maxCount) return undefined; + return { price: { silverLions: modification.silverLions * amount, goldenEagles: modification.goldenEagles * amount }, amount }; +} + +function outrightPurchase(profile: BlkBlock, vehicle: string, modification: ModificationFacts, catalogue: EquipmentCatalogue): Purchase | undefined { + if (!isResearchable(modification)) return undefined; + const status = currentModuleStatus(profile, catalogue, vehicle, modification.name); + if (status !== ModuleStatus.CAN_RESEARCH && status !== ModuleStatus.CAN_BUY) return undefined; + return { price: { silverLions: 0, goldenEagles: outrightPrice(profile, vehicle, modification) }, amount: 1 }; +} + +/** + * One entry of "buy all", as the client sums it (scripts weaponry/itemInfo.nut getAllModsCost): + * skip what is at its maximum; with forceOpen every modification starts at its outright price + * (whatever its status); a buyable one (canBuyMod) with a non-zero price takes its own price + * instead, and is skipped altogether when counted or priced in golden eagles. + */ +function buyAllEntry(profile: BlkBlock, vehicle: string, modification: ModificationFacts, catalogue: EquipmentCatalogue, outright: boolean): Purchase | undefined { + const record = modificationRecord(profile, vehicle, modification.name); + const maxAmount = Math.max(1, modification.maxCount); + if ((record?.count ?? 0) >= maxAmount) return undefined; + let purchase: Purchase | undefined; + const openPrice = outright && isResearchable(modification) ? outrightPrice(profile, vehicle, modification) : 0; + if (openPrice > 0) purchase = { price: { silverLions: 0, goldenEagles: openPrice }, amount: 1 }; + const buyable = record !== undefined || currentModuleStatus(profile, catalogue, vehicle, modification.name) === ModuleStatus.CAN_BUY; + if (buyable && (modification.silverLions > 0 || modification.goldenEagles > 0)) { + if (isCounted(modification) || modification.goldenEagles > 0) return undefined; + purchase = { price: { silverLions: modification.silverLions, goldenEagles: 0 }, amount: 1 }; + } + return purchase; +} + +function addToRecord(profile: BlkBlock, vehicle: string, modification: ModificationFacts, purchase: Purchase): void { + const record = modificationRecord(profile, vehicle, modification.name); + writeModificationRecord(profile, vehicle, modification.name, { + silverLionsSpent: (record?.silverLionsSpent ?? 0) + purchase.price.silverLions, + goldenEaglesSpent: (record?.goldenEaglesSpent ?? 0) + purchase.price.goldenEagles, + enabled: record?.enabled ?? true, + count: (record?.count ?? 0) + purchase.amount, + }); + removeModuleResearch(profile, vehicle, modification.name); + if (moduleResearchTarget(profile, vehicle) === modification.name) setModuleResearchTarget(profile, vehicle, ''); +} diff --git a/packages/local-service/src/modifications/module-research-target.ts b/packages/local-service/src/modifications/module-research-target.ts new file mode 100644 index 0000000..f65681b --- /dev/null +++ b/packages/local-service/src/modifications/module-research-target.ts @@ -0,0 +1,19 @@ +/** + * Choosing the modification a vehicle researches: cln_set_researchable + * with unit:t and mod:t (script shop_set_researchable_unit_module). The modification has to be + * researchable now; it goes into hangar//investMode, and the client shows it as "in + * research" from there. + */ +import type { BlkBlock } from '@wto/blk'; +import { setModuleResearchTarget } from '../profile/profile-vehicle-state.ts'; +import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; +import type { EquipmentCatalogue } from './equipment-catalogue.ts'; +import { currentModuleStatus } from './module-state.ts'; +import { ModuleStatus } from './module-status.ts'; + +export function chooseModuleResearch(profile: BlkBlock, catalogue: EquipmentCatalogue, vehicle: string, modification: string): RuleOutcome { + if (!catalogue.modification(vehicle, modification)) return refused('BAD_PARAMS'); + if (currentModuleStatus(profile, catalogue, vehicle, modification) !== ModuleStatus.CAN_RESEARCH) return refused('NOT_AVAILABLE'); + setModuleResearchTarget(profile, vehicle, modification); + return ACCEPTED; +} diff --git a/packages/local-service/src/modifications/module-state.ts b/packages/local-service/src/modifications/module-state.ts new file mode 100644 index 0000000..4e35187 --- /dev/null +++ b/packages/local-service/src/modifications/module-state.ts @@ -0,0 +1,40 @@ +/** + * Bringing the modification state of a profile up to date, like research/research-state.ts does + * for vehicles: whenever a profile is handed out or changed (profiles-setup.ts), for every owned + * vehicle + * hangar//tierNumber the highest open tier + * modsResearch the status of every modification not owned yet; locked ones + * only keep an entry while they hold research points + * hangar//investMode cleared when that modification is no longer researchable + */ +import type { BlkBlock } from '@wto/blk'; +import { ownedVehicles } from '../profile/profile-hangar.ts'; +import { moduleResearchPoints, removeModuleResearch, setModuleStatus } from '../profile/profile-module-research.ts'; +import { moduleResearchTarget, setModuleResearchTarget, setOpenTier } from '../profile/profile-vehicle-state.ts'; +import type { EquipmentCatalogue } from './equipment-catalogue.ts'; +import { ModuleStatus, vehicleModuleState } from './module-status.ts'; + +export function refreshModuleState(profile: BlkBlock, catalogue: EquipmentCatalogue): void { + for (const vehicle of ownedVehicles(profile)) { + const equipment = catalogue.vehicle(vehicle); + if (!equipment) continue; + const state = vehicleModuleState(profile, equipment); + setOpenTier(profile, vehicle, state.openTier); + for (const modification of equipment.modifications) { + const status = state.statuses.get(modification.name); + if (status === undefined || (status === ModuleStatus.LOCKED && moduleResearchPoints(profile, vehicle, modification.name) === 0)) { + removeModuleResearch(profile, vehicle, modification.name); + } + else setModuleStatus(profile, vehicle, modification.name, status); + } + const target = moduleResearchTarget(profile, vehicle); + if (target && state.statuses.get(target) !== ModuleStatus.CAN_RESEARCH) setModuleResearchTarget(profile, vehicle, ''); + } +} + +/** The status of one modification the player does not own; undefined when owned, unknown or the vehicle is not owned. */ +export function currentModuleStatus(profile: BlkBlock, catalogue: EquipmentCatalogue, vehicle: string, modification: string): ModuleStatus | undefined { + const equipment = catalogue.vehicle(vehicle); + if (!equipment || !ownedVehicles(profile).has(vehicle)) return undefined; + return vehicleModuleState(profile, equipment).statuses.get(modification); +} diff --git a/packages/local-service/src/modifications/module-status.ts b/packages/local-service/src/modifications/module-status.ts new file mode 100644 index 0000000..29518e1 --- /dev/null +++ b/packages/local-service/src/modifications/module-status.ts @@ -0,0 +1,74 @@ +/** + * The status of each modification of an owned vehicle. The client + * works out "owned" and "mounted" from the modifications records and "in research" from + * investMode itself; the server supplies the rest through modsResearch: + * + * researchable modification (tier 1+, research points) + * tier not open LOCKED + * research points reached CAN_BUY + * otherwise CAN_RESEARCH + * other modification (ammunition, expendables, premium) + * every required modification bought CAN_BUY + * otherwise LOCKED + * + * Tiers: tier 1 is open; tier N+1 opens once tier N is open and at least + * needBuyToOpenNextInTier of its counted modifications are researched (scripts + * weaponry/bulletsInfo.nut isWeaponTierAvailable, weaponry/modsTree.nut getNextTierModsCount). + */ +import type { BlkBlock } from '@wto/blk'; +import type { ModificationFacts, VehicleEquipment } from '../game-data/datasets/vehicle-equipment.ts'; +import { ownsModification } from '../profile/profile-modifications.ts'; +import { moduleResearchPoints } from '../profile/profile-module-research.ts'; +import { countsForTier, isResearchable } from './equipment-catalogue.ts'; + +/** shopItemConsts ES_ITEM_STATUS_*; the same values as the vehicle statuses. */ +export const ModuleStatus = { + LOCKED: 1, + CAN_RESEARCH: 2, + CAN_BUY: 8, +} as const; + +export type ModuleStatus = (typeof ModuleStatus)[keyof typeof ModuleStatus]; + +export interface VehicleModuleState { + /** The highest open tier (hangar tierNumber). */ + readonly openTier: number; + /** Status of every modification the player does not own. */ + readonly statuses: ReadonlyMap; +} + +export function vehicleModuleState(profile: BlkBlock, equipment: VehicleEquipment): VehicleModuleState { + const openTier = openTierOf(profile, equipment); + const statuses = new Map(); + for (const modification of equipment.modifications) { + if (ownsModification(profile, equipment.vehicle, modification.name)) continue; + statuses.set(modification.name, statusOf(profile, equipment.vehicle, modification, openTier)); + } + return { openTier, statuses }; +} + +export function isModuleResearched(profile: BlkBlock, vehicle: string, modification: ModificationFacts): boolean { + return ownsModification(profile, vehicle, modification.name) + || moduleResearchPoints(profile, vehicle, modification.name) >= modification.researchPoints; +} + +function openTierOf(profile: BlkBlock, equipment: VehicleEquipment): number { + let tier = 1; + while (tier <= equipment.tierRequirements.length) { + const needed = equipment.tierRequirements[tier - 1] ?? 0; + const tierModifications = equipment.modifications.filter((modification) => modification.tier === tier && countsForTier(modification)); + if (tierModifications.length === 0) break; + const researched = tierModifications.filter((modification) => isModuleResearched(profile, equipment.vehicle, modification)).length; + if (researched < needed) break; + tier++; + } + return tier; +} + +function statusOf(profile: BlkBlock, vehicle: string, modification: ModificationFacts, openTier: number): ModuleStatus { + if (isResearchable(modification)) { + if (modification.tier > openTier) return ModuleStatus.LOCKED; + return isModuleResearched(profile, vehicle, modification) ? ModuleStatus.CAN_BUY : ModuleStatus.CAN_RESEARCH; + } + return modification.requires.every((required) => ownsModification(profile, vehicle, required)) ? ModuleStatus.CAN_BUY : ModuleStatus.LOCKED; +} diff --git a/packages/local-service/src/modifications/spare-purchase.ts b/packages/local-service/src/modifications/spare-purchase.ts new file mode 100644 index 0000000..d7c5f1b --- /dev/null +++ b/packages/local-service/src/modifications/spare-purchase.ts @@ -0,0 +1,27 @@ +/** + * Buying spares (cln_buy_spare_aircrafts: aircraft:t count:i cost:i costGold:i, scripts + * weaponry/weaponsPurchase.nut): the wpcost.blk spare price times the amount, added to + * hangar//spareAircraftsCount, at most MAX_SPARE_AMOUNT (scripts + * weaponry/weaponryConsts.nut). + */ +import type { BlkBlock } from '@wto/blk'; +import { canAfford, pay, type Price } from '../profile/profile-currency.ts'; +import { ownsVehicle } from '../profile/profile-hangar.ts'; +import { setSpareCount, spareCount } from '../profile/profile-vehicle-state.ts'; +import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; +import type { EquipmentCatalogue } from './equipment-catalogue.ts'; + +const MAX_SPARE_AMOUNT = 100; + +export function buySpares(profile: BlkBlock, catalogue: EquipmentCatalogue, vehicle: string, amount: number, offered: Price): RuleOutcome { + const spare = catalogue.vehicle(vehicle)?.spare; + if (!spare || !ownsVehicle(profile, vehicle) || amount < 1) return refused('BAD_PARAMS'); + const owned = spareCount(profile, vehicle); + if (owned + amount > MAX_SPARE_AMOUNT) return refused('NOT_AVAILABLE'); + const price: Price = { silverLions: spare.silverLions * amount, goldenEagles: spare.goldenEagles * amount }; + if (price.silverLions !== offered.silverLions || price.goldenEagles !== offered.goldenEagles) return refused('PRICE_CHANGED'); + if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY'); + pay(profile, price); + setSpareCount(profile, vehicle, owned + amount); + return ACCEPTED; +} diff --git a/packages/local-service/src/profile/profile-modifications.ts b/packages/local-service/src/profile/profile-modifications.ts new file mode 100644 index 0000000..5ebdb0d --- /dev/null +++ b/packages/local-service/src/profile/profile-modifications.ts @@ -0,0 +1,71 @@ +/** + * Bought modifications in the profile: + * + * modifications{ + * us_m22_locust_tank_tool_kit{ count:i64=1 } + * us_m22_locust_37mm_usa_m3_APC{ wpSpent:i=450 count:i64=150 } + * us_m22_locust_new_tank_tracks{ enabled:b=no count:i64=1 } + * } + * + * One block per bought modification, named _; having a block means the + * modification is owned. The client reads a block's params strictly in this order and stops at + * the first one that does not match (aces.exe 0x942740), so a record is always rewritten whole: + * wpSpent:i goldSpent:i lastWpCost:i lastGoldCost:i persist:b rpEarned:i enabled:b count:i64 modLevel:i + * Absent values are left out; enabled is only written when false (the default is enabled). + */ +import { ensureBlock, findBlock, type BlkBlock, type BlkParam } from '@wto/blk'; + +const MODIFICATIONS = 'modifications'; + +export interface ModificationRecord { + readonly silverLionsSpent: number; + readonly goldenEaglesSpent: number; + readonly enabled: boolean; + /** How many the player has: 1 for a plain modification, the number of rounds or uses for counted ones. */ + readonly count: number; +} + +export function recordName(vehicle: string, modification: string): string { + return `${vehicle}_${modification}`; +} + +export function modificationRecord(profile: BlkBlock, vehicle: string, modification: string): ModificationRecord | undefined { + const block = findBlock(profile, MODIFICATIONS); + const record = block && findBlock(block, recordName(vehicle, modification)); + if (!record) return undefined; + return { + silverLionsSpent: intOf(record, 'wpSpent'), + goldenEaglesSpent: intOf(record, 'goldSpent'), + enabled: boolOf(record, 'enabled') ?? true, + count: intOf(record, 'count'), + }; +} + +export function ownsModification(profile: BlkBlock, vehicle: string, modification: string): boolean { + return modificationRecord(profile, vehicle, modification) !== undefined; +} + +export function writeModificationRecord(profile: BlkBlock, vehicle: string, modification: string, record: ModificationRecord): void { + const block = ensureBlock(ensureBlock(profile, MODIFICATIONS), recordName(vehicle, modification)); + block.params = orderedParams(record); +} + +function orderedParams(record: ModificationRecord): BlkParam[] { + const params: BlkParam[] = []; + if (record.silverLionsSpent) params.push({ name: 'wpSpent', value: { type: 'int', value: record.silverLionsSpent } }); + if (record.goldenEaglesSpent) params.push({ name: 'goldSpent', value: { type: 'int', value: record.goldenEaglesSpent } }); + if (!record.enabled) params.push({ name: 'enabled', value: { type: 'bool', value: false } }); + if (record.count) params.push({ name: 'count', value: { type: 'int64', value: BigInt(record.count) } }); + return params; +} + +function intOf(block: BlkBlock, name: string): number { + const value = block.params.find((param) => param.name === name)?.value; + if (value?.type === 'int64') return Number(value.value); + return value?.type === 'int' ? value.value : 0; +} + +function boolOf(block: BlkBlock, name: string): boolean | undefined { + const value = block.params.find((param) => param.name === name)?.value; + return value?.type === 'bool' ? value.value : undefined; +} diff --git a/packages/local-service/src/profile/profile-module-research.ts b/packages/local-service/src/profile/profile-module-research.ts new file mode 100644 index 0000000..4da3b94 --- /dev/null +++ b/packages/local-service/src/profile/profile-module-research.ts @@ -0,0 +1,46 @@ +/** + * Modification research in the profile: + * + * modsResearch{ us_m22_locust_new_tank_tracks{ unitStatus:i=2 exp:i64=120 } } + * + * One block per modification of an owned vehicle that is not bought yet, named + * _; each block has the layout of a unitResearch entry (the client reads + * both with aces.exe 0x943990): unitStatus is the status the server works out, + * exp the research points already put into it. + */ +import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk'; +import { recordName } from './profile-modifications.ts'; + +const MODS_RESEARCH = 'modsResearch'; +const STATUS = 'unitStatus'; +const RESEARCH_POINTS = 'exp'; + +export function moduleResearchPoints(profile: BlkBlock, vehicle: string, modification: string): number { + const entry = entryOf(profile, vehicle, modification); + 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 setModuleResearchPoints(profile: BlkBlock, vehicle: string, modification: string, amount: number): void { + setParam(ensureEntry(profile, vehicle, modification), RESEARCH_POINTS, { type: 'int64', value: BigInt(amount) }); +} + +export function setModuleStatus(profile: BlkBlock, vehicle: string, modification: string, status: number): void { + setParam(ensureEntry(profile, vehicle, modification), STATUS, { type: 'int', value: status }); +} + +export function removeModuleResearch(profile: BlkBlock, vehicle: string, modification: string): void { + const block = findBlock(profile, MODS_RESEARCH); + const name = recordName(vehicle, modification); + if (block) block.blocks = block.blocks.filter((entry) => entry.name !== name); +} + +function entryOf(profile: BlkBlock, vehicle: string, modification: string): BlkBlock | undefined { + const block = findBlock(profile, MODS_RESEARCH); + return block && findBlock(block, recordName(vehicle, modification)); +} + +function ensureEntry(profile: BlkBlock, vehicle: string, modification: string): BlkBlock { + return ensureBlock(ensureBlock(profile, MODS_RESEARCH), recordName(vehicle, modification)); +} diff --git a/packages/local-service/src/profile/profile-vehicle-state.ts b/packages/local-service/src/profile/profile-vehicle-state.ts new file mode 100644 index 0000000..aa76d14 --- /dev/null +++ b/packages/local-service/src/profile/profile-vehicle-state.ts @@ -0,0 +1,49 @@ +/** + * Per-vehicle fields of owned vehicles: hangar{ { ... } }, + * read by name by AircraftInfo::serialize (aces.exe 0x940510). Only the fields the local + * service maintains are handled here: + * investMode:t the modification being researched (empty = none) + * tierNumber:i the highest open modification tier (script is_tier_available) + * spareAircraftsCount:i spares the player has for this vehicle + */ +import { findBlock, findParam, setParam, type BlkBlock } from '@wto/blk'; + +const HANGAR = 'hangar'; +const RESEARCH_TARGET = 'investMode'; +const OPEN_TIER = 'tierNumber'; +const SPARES = 'spareAircraftsCount'; + +export function moduleResearchTarget(profile: BlkBlock, vehicle: string): string { + const value = fieldOf(profile, vehicle, RESEARCH_TARGET); + return value?.type === 'string' ? value.value : ''; +} + +export function setModuleResearchTarget(profile: BlkBlock, vehicle: string, modification: string): void { + const entry = vehicleEntry(profile, vehicle); + if (entry) setParam(entry, RESEARCH_TARGET, { type: 'string', value: modification }); +} + +export function setOpenTier(profile: BlkBlock, vehicle: string, tier: number): void { + const entry = vehicleEntry(profile, vehicle); + if (entry) setParam(entry, OPEN_TIER, { type: 'int', value: tier }); +} + +export function spareCount(profile: BlkBlock, vehicle: string): number { + const value = fieldOf(profile, vehicle, SPARES); + return value?.type === 'int' ? value.value : 0; +} + +export function setSpareCount(profile: BlkBlock, vehicle: string, count: number): void { + const entry = vehicleEntry(profile, vehicle); + if (entry) setParam(entry, SPARES, { type: 'int', value: count }); +} + +function fieldOf(profile: BlkBlock, vehicle: string, name: string) { + const entry = vehicleEntry(profile, vehicle); + return entry && findParam(entry, name)?.value; +} + +function vehicleEntry(profile: BlkBlock, vehicle: string): BlkBlock | undefined { + const hangar = findBlock(profile, HANGAR); + return hangar && findBlock(hangar, vehicle); +} diff --git a/packages/local-service/src/profiles-setup.ts b/packages/local-service/src/profiles-setup.ts index 62b001c..a3fa270 100644 --- a/packages/local-service/src/profiles-setup.ts +++ b/packages/local-service/src/profiles-setup.ts @@ -1,7 +1,7 @@ /** * 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. + * save store with its format upgrades, and the research and modification state kept up to date. */ import type { DatasetCache } from './game-data/datasets/dataset-cache.ts'; import { reserveVehicles } from './game-data/datasets/reserve-vehicles.ts'; @@ -10,6 +10,7 @@ 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 { refreshModuleState } from './modifications/module-state.ts'; import { refreshResearchState } from './research/research-state.ts'; import { loadResearchRules, type ResearchRules } from './research/research-rules.ts'; import { SaveStore } from './saves/save-store.ts'; @@ -23,6 +24,9 @@ export function setUpProfiles(dataFolder: string, gameFiles: GameFiles, datasets 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)); + const profiles = new PlayerProfiles(saves, gameFiles, startingContent, (profile) => { + refreshResearchState(profile, research); + refreshModuleState(profile, research.equipment); + }); return { profiles, research }; } diff --git a/packages/local-service/src/research/price-table.ts b/packages/local-service/src/research/price-table.ts index d69b923..3e1e9be 100644 --- a/packages/local-service/src/research/price-table.ts +++ b/packages/local-service/src/research/price-table.ts @@ -1,39 +1,69 @@ /** - * The price table the char server sends for cln_get_price_ex. + * The price table the char server sends for cln_get_price_ex (implementation notes, + * implementation notes). * * 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). Every price reader goes through one lookup (0x908a20 -> * 0x908d10): it first takes a top-level block named after a client-side string (default * "English"), else the top-level block "Common", else finds nothing; the path is looked up - * inside that block. So the whole table sits in Common. wp_get_cost / wp_get_cost_gold - * (0x10514f0 / 0x1051900) use the path aircrafts/ and read - * cost:i silver lions - * costGold:i golden eagles - * discount:i percent off (not sent: no discounts) - * A vehicle the lookup does not find 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). + * inside that block. So the whole table sits in Common: + * + * Common{ + * aircrafts{ + * { + * cost:i costGold:i the vehicle + * mods{ { cost:i costGold:i openCostGold:i } } + * weapons{ { cost:i costGold:i } } + * spare{ cost:i costGold:i } + * } + * } + * } + * + * Every entry is read as cost:i (silver lions), costGold:i (golden eagles), discount:i (percent + * off, not sent: no discounts), each 0 when missing (so zero prices are left out); openCostGold + * is the outright price of a modification before research progress (0xec0910). Anything the lookup does not find 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 rules charge. */ -import type { BlkBlock } from '@wto/blk'; +import type { BlkBlock, BlkParam } from '@wto/blk'; +import type { EquipmentCatalogue } from '../modifications/equipment-catalogue.ts'; import type { TechTree } from './tech-tree.ts'; /** The top-level block every client lookup falls back to (0x908e28). */ const COMMON_SECTION = 'Common'; -export function priceTable(techTree: TechTree): BlkBlock { +export function priceTable(techTree: TechTree, equipment: EquipmentCatalogue): 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: [], - }); + const entry: BlkBlock = { name: vehicle.name, params: priceParams(vehicle.silverLions, vehicle.goldenEagles), blocks: [] }; + const fitted = equipment.vehicle(vehicle.name); + if (fitted) { + const mods = fitted.modifications.filter((mod) => mod.silverLions > 0 || mod.goldenEagles > 0 || mod.openGoldenEagles > 0).map((mod) => ({ + name: mod.name, + params: [...priceParams(mod.silverLions, mod.goldenEagles), ...(mod.openGoldenEagles > 0 ? [intParam('openCostGold', mod.openGoldenEagles)] : [])], + blocks: [], + })); + const weapons = fitted.weapons.filter((weapon) => weapon.silverLions > 0 || weapon.goldenEagles > 0) + .map((weapon) => ({ name: weapon.name, params: priceParams(weapon.silverLions, weapon.goldenEagles), blocks: [] })); + if (mods.length) entry.blocks.push({ name: 'mods', params: [], blocks: mods }); + if (weapons.length) entry.blocks.push({ name: 'weapons', params: [], blocks: weapons }); + if (fitted.spare) entry.blocks.push({ name: 'spare', params: priceParams(fitted.spare.silverLions, fitted.spare.goldenEagles), blocks: [] }); + } + if (entry.blocks.length || vehicle.silverLions > 0 || vehicle.goldenEagles > 0) vehicles.push(entry); } const common: BlkBlock = { name: COMMON_SECTION, params: [], blocks: [{ name: 'aircrafts', params: [], blocks: vehicles }] }; return { name: '', params: [], blocks: [common] }; } + +/** Zero prices are left out: the client reads a missing value as 0, and the table stays small. */ +function priceParams(silverLions: number, goldenEagles: number): BlkParam[] { + return [ + ...(silverLions ? [intParam('cost', silverLions)] : []), + ...(goldenEagles ? [intParam('costGold', goldenEagles)] : []), + ]; +} + +function intParam(name: string, value: number): BlkParam { + return { name, value: { type: 'int', value } }; +} diff --git a/packages/local-service/src/research/research-rules.ts b/packages/local-service/src/research/research-rules.ts index afc051d..a6db559 100644 --- a/packages/local-service/src/research/research-rules.ts +++ b/packages/local-service/src/research/research-rules.ts @@ -6,7 +6,9 @@ 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 { vehicleEquipment } from '../game-data/datasets/vehicle-equipment.ts'; import { vehicleUnlocks, type UnlockDefinition } from '../game-data/datasets/vehicle-unlocks.ts'; +import { EquipmentCatalogue } from '../modifications/equipment-catalogue.ts'; import { TechTree } from './tech-tree.ts'; export interface ResearchRules { @@ -15,6 +17,8 @@ export interface ResearchRules { readonly vehicleUnlocks: readonly UnlockDefinition[]; readonly crewSlotPrices: CrewSlotPrices; readonly researchPointsPerGoldenEagle: number; + /** Modifications, ammunition, weapon presets and spares of every vehicle. */ + readonly equipment: EquipmentCatalogue; } export function loadResearchRules(datasets: DatasetCache): ResearchRules { @@ -24,5 +28,6 @@ export function loadResearchRules(datasets: DatasetCache): ResearchRules { vehicleUnlocks: datasets.load(vehicleUnlocks), crewSlotPrices: datasets.load(crewSlotPrices), researchPointsPerGoldenEagle: datasets.load(researchPointsPerGoldenEagle), + equipment: new EquipmentCatalogue(datasets.load(vehicleEquipment)), }; }