From 62da2e3038791e11fdfd79fea50ca8ed278c5df1 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:54:36 +0800 Subject: [PATCH] perf(server): index profile equipment and research refreshes Replace O(N^2) linear lookups and repeated array filtering across modifications, weapons, modsResearch and unitResearch with single-pass Map indexes, pre-sort catalogue equipment once on load, avoid redundant pre-change disk writes in PlayerProfiles.updateWhen, and shallow-copy only top-level lists in clientProfile. --- apps/server/src/modifications/ammo-refill.ts | 81 +++---- .../src/modifications/equipment-catalogue.ts | 9 +- apps/server/src/modifications/module-state.ts | 56 +++-- .../server/src/modifications/module-status.ts | 71 +++--- .../modifications/profile-equipment-index.ts | 203 ++++++++++++++++++ .../support-plane-modifications.ts | 14 +- apps/server/src/profile/client-profile.ts | 7 +- apps/server/src/profile/player-profiles.ts | 17 +- apps/server/src/research/research-state.ts | 47 ++-- apps/server/src/research/vehicle-status.ts | 51 +++-- 10 files changed, 401 insertions(+), 155 deletions(-) create mode 100644 apps/server/src/modifications/profile-equipment-index.ts diff --git a/apps/server/src/modifications/ammo-refill.ts b/apps/server/src/modifications/ammo-refill.ts index 2658423..34ae3b5 100644 --- a/apps/server/src/modifications/ammo-refill.ts +++ b/apps/server/src/modifications/ammo-refill.ts @@ -2,35 +2,12 @@ * Initial full stocking and `autoRefillWeapons` Silver-Lion top-up for an owned vehicle's * modifications, ammunition belts/shells, expendables (`tank_medical_kit_expendable`), and * secondary weapon presets. - * - * Rules: - * 1. Zero-cost modifications (`isFree`) whose `requires` are all owned cannot be bought by the - * client (`weaponsPurchase.nut` `canBuyItem` rejects zero cost) and receive `count = 1` in - * name + topological order, honoring `defaultEnabled` and non-bullet `exclusiveGroup` mutual - * exclusion. - * 2. Free secondary weapon presets (`isFreeWeapon`, excluding `isWeaponForCustomSlot` containers) - * whose `requires` (direct + `sum_weapons` container inheritance) are all owned receive - * `count = 1` so `shop_is_weapon_purchased` allows selecting them. - * 3. Silver-Lion counted modifications (`isCounted` with `goldenEagles === 0`, covering all - * 12,800 shells, gun belts, and `tank_medical_kit_expendable`) and paid weapon presets - * (`isPaidWeapon` with `goldenEagles === 0`) whose `requires` are all owned: - * - When no profile record exists yet (`record === undefined`, i.e. newly acquired vehicle or - * newly unlocked prerequisite modification), receive their initial full load (`maxCount`) - * at no extra Silver-Lion charge (`itemInfo.nut` `getAllModsCost` skips `maxAmount > 1`). - * - When a record already exists with `count < maxCount` (consumed in battle) and hangar - * `autoRefillWeapons` is enabled, buy as many missing pieces with Silver Lions in - * deterministic name order as the player's balance affords. - * - * Returns the Silver Lions spent on refilling (0 for the initial free stock and when - * autoRefill is off); battle settlement lists it as the automatic refill cost. */ import type { BlkBlock } from '@wto/blk'; import type { ModificationFacts, VehicleEquipment, WeaponFacts } from '../game-data/datasets/vehicle-equipment.ts'; import { balanceOf, pay } from '../profile/profile-currency.ts'; -import { modificationRecord, ownsModification, writeModificationRecord } from '../profile/profile-modifications.ts'; -import { weaponRecord, writeWeaponRecord } from '../profile/profile-weapons.ts'; import { isCounted, isFree, isFreeWeapon, isPaidWeapon } from './equipment-catalogue.ts'; -import { arePrerequisitesOwned } from './module-status.ts'; +import { ProfileEquipmentIndex } from './profile-equipment-index.ts'; export interface EquipmentRefillResult { readonly silverLionsSpent: number; @@ -40,30 +17,34 @@ export function stockAndRefillEquipment( profile: BlkBlock, equipment: VehicleEquipment, autoRefill: boolean, + index: ProfileEquipmentIndex = new ProfileEquipmentIndex(profile), ): EquipmentRefillResult { - const modifications = [...equipment.modifications].sort((a, b) => a.name.localeCompare(b.name)); - const weapons = [...equipment.weapons].sort((a, b) => a.name.localeCompare(b.name)); - grantUnlockedFreeModifications(profile, equipment.vehicle, modifications); - grantUnlockedFreeWeapons(profile, equipment.vehicle, weapons); + const { modifications, weapons } = equipment; + grantUnlockedFreeModifications(index, equipment.vehicle, modifications); + grantUnlockedFreeWeapons(index, equipment.vehicle, weapons); let silverLionsSpent = 0; for (const modification of modifications) { - silverLionsSpent += stockOrRefillCountedModification(profile, equipment.vehicle, modification, autoRefill); + silverLionsSpent += stockOrRefillCountedModification(profile, index, equipment.vehicle, modification, autoRefill); } for (const weapon of weapons) { - silverLionsSpent += stockOrRefillPaidWeapon(profile, equipment.vehicle, weapon, autoRefill); + silverLionsSpent += stockOrRefillPaidWeapon(profile, index, equipment.vehicle, weapon, autoRefill); } return { silverLionsSpent }; } -function grantUnlockedFreeModifications(profile: BlkBlock, vehicle: string, modifications: readonly ModificationFacts[]): void { +function prerequisitesOwned(index: ProfileEquipmentIndex, vehicle: string, requires: readonly string[]): boolean { + return requires.every((required) => index.ownsModification(vehicle, required)); +} + +function grantUnlockedFreeModifications(index: ProfileEquipmentIndex, vehicle: string, modifications: readonly ModificationFacts[]): void { let progressed = false; do { progressed = false; for (const modification of modifications) { - if (!isFree(modification) || ownsModification(profile, vehicle, modification.name)) continue; - if (!arePrerequisitesOwned(profile, vehicle, modification.requires)) continue; - const enabled = modification.defaultEnabled && !hasEnabledExclusivePeer(profile, vehicle, modifications, modification.exclusiveGroup); - writeModificationRecord(profile, vehicle, modification.name, { + if (!isFree(modification) || index.ownsModification(vehicle, modification.name)) continue; + if (!prerequisitesOwned(index, vehicle, modification.requires)) continue; + const enabled = modification.defaultEnabled && !hasEnabledExclusivePeer(index, vehicle, modifications, modification.exclusiveGroup); + index.writeModificationRecord(vehicle, modification.name, { silverLionsSpent: 0, goldenEaglesSpent: 0, enabled, @@ -75,34 +56,35 @@ function grantUnlockedFreeModifications(profile: BlkBlock, vehicle: string, modi } function hasEnabledExclusivePeer( - profile: BlkBlock, + index: ProfileEquipmentIndex, vehicle: string, modifications: readonly ModificationFacts[], exclusiveGroup: string | undefined, ): boolean { if (!exclusiveGroup) return false; - return modifications.some((peer) => peer.exclusiveGroup === exclusiveGroup && modificationRecord(profile, vehicle, peer.name)?.enabled === true); + return modifications.some((peer) => peer.exclusiveGroup === exclusiveGroup && index.modificationRecord(vehicle, peer.name)?.enabled === true); } -function grantUnlockedFreeWeapons(profile: BlkBlock, vehicle: string, weapons: readonly WeaponFacts[]): void { +function grantUnlockedFreeWeapons(index: ProfileEquipmentIndex, vehicle: string, weapons: readonly WeaponFacts[]): void { for (const weapon of weapons) { - if (!isFreeWeapon(weapon) || weaponRecord(profile, vehicle, weapon.name)) continue; - if (!arePrerequisitesOwned(profile, vehicle, weapon.requires)) continue; - writeWeaponRecord(profile, vehicle, weapon.name, { silverLionsSpent: 0, goldenEaglesSpent: 0, count: 1 }); + if (!isFreeWeapon(weapon) || index.weaponRecord(vehicle, weapon.name)) continue; + if (!prerequisitesOwned(index, vehicle, weapon.requires)) continue; + index.writeWeaponRecord(vehicle, weapon.name, { silverLionsSpent: 0, goldenEaglesSpent: 0, count: 1 }); } } function stockOrRefillCountedModification( profile: BlkBlock, + index: ProfileEquipmentIndex, vehicle: string, modification: ModificationFacts, autoRefill: boolean, ): number { if (!isCounted(modification) || modification.goldenEagles > 0) return 0; - if (!arePrerequisitesOwned(profile, vehicle, modification.requires)) return 0; - const record = modificationRecord(profile, vehicle, modification.name); + if (!prerequisitesOwned(index, vehicle, modification.requires)) return 0; + const record = index.modificationRecord(vehicle, modification.name); if (record === undefined) { - writeModificationRecord(profile, vehicle, modification.name, { + index.writeModificationRecord(vehicle, modification.name, { silverLionsSpent: 0, goldenEaglesSpent: 0, enabled: modification.defaultEnabled, @@ -115,7 +97,7 @@ function stockOrRefillCountedModification( if (toBuy <= 0) return 0; const cost = toBuy * modification.silverLions; if (cost > 0) pay(profile, { silverLions: cost, goldenEagles: 0 }); - writeModificationRecord(profile, vehicle, modification.name, { + index.writeModificationRecord(vehicle, modification.name, { ...record, silverLionsSpent: record.silverLionsSpent + cost, count: record.count + toBuy, @@ -125,15 +107,16 @@ function stockOrRefillCountedModification( function stockOrRefillPaidWeapon( profile: BlkBlock, + index: ProfileEquipmentIndex, vehicle: string, weapon: WeaponFacts, autoRefill: boolean, ): number { if (!isPaidWeapon(weapon) || weapon.goldenEagles > 0) return 0; - if (!arePrerequisitesOwned(profile, vehicle, weapon.requires)) return 0; - const record = weaponRecord(profile, vehicle, weapon.name); + if (!prerequisitesOwned(index, vehicle, weapon.requires)) return 0; + const record = index.weaponRecord(vehicle, weapon.name); if (record === undefined) { - writeWeaponRecord(profile, vehicle, weapon.name, { silverLionsSpent: 0, goldenEaglesSpent: 0, count: weapon.maxCount }); + index.writeWeaponRecord(vehicle, weapon.name, { silverLionsSpent: 0, goldenEaglesSpent: 0, count: weapon.maxCount }); return 0; } if (!autoRefill || record.count >= weapon.maxCount) return 0; @@ -141,7 +124,7 @@ function stockOrRefillPaidWeapon( if (toBuy <= 0) return 0; const cost = toBuy * weapon.silverLions; if (cost > 0) pay(profile, { silverLions: cost, goldenEagles: 0 }); - writeWeaponRecord(profile, vehicle, weapon.name, { + index.writeWeaponRecord(vehicle, weapon.name, { silverLionsSpent: record.silverLionsSpent + cost, goldenEaglesSpent: record.goldenEaglesSpent, count: record.count + toBuy, diff --git a/apps/server/src/modifications/equipment-catalogue.ts b/apps/server/src/modifications/equipment-catalogue.ts index 0452f01..a8712ba 100644 --- a/apps/server/src/modifications/equipment-catalogue.ts +++ b/apps/server/src/modifications/equipment-catalogue.ts @@ -8,7 +8,14 @@ export class EquipmentCatalogue { readonly #byVehicle: ReadonlyMap; constructor(equipment: readonly VehicleEquipment[]) { - this.#byVehicle = new Map(equipment.map((entry) => [entry.vehicle, entry])); + this.#byVehicle = new Map(equipment.map((entry) => [ + entry.vehicle, + { + ...entry, + modifications: [...entry.modifications].sort((a, b) => a.name.localeCompare(b.name)), + weapons: [...entry.weapons].sort((a, b) => a.name.localeCompare(b.name)), + }, + ])); } vehicle(name: string): VehicleEquipment | undefined { diff --git a/apps/server/src/modifications/module-state.ts b/apps/server/src/modifications/module-state.ts index c2bbc5b..6e293b4 100644 --- a/apps/server/src/modifications/module-state.ts +++ b/apps/server/src/modifications/module-state.ts @@ -8,72 +8,66 @@ * 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. After a modification finished - * (investModePrev set) a new one is picked while some remain, so - * the stock prompt opens WeaponsModalHandler in researchMode - * (or reports isResearchLast with investMode "" when the vehicle - * has nothing left); with banked hangar//excessExp and - * nothing just finished it stays empty for the player to choose. + * hangar//investMode cleared when that modification is no longer researchable. */ import type { BlkBlock } from '@wto/blk'; import type { VehicleEquipment } from '../game-data/datasets/vehicle-equipment.ts'; import { isAutoRefillWeaponsEnabled } from '../profile/profile-client-settings.ts'; import { ownedVehicles } from '../profile/profile-hangar.ts'; -import { moduleResearchPoints, removeModuleResearch, setModuleStatus } from '../profile/profile-module-research.ts'; -import { - finishedModuleResearch, - moduleResearchTarget, - setModuleResearchTarget, - setOpenTier, - setVehicleExcessRp, - vehicleExcessRp, -} from '../profile/profile-vehicle-state.ts'; import { stockAndRefillEquipment } from './ammo-refill.ts'; import { isResearchable, type EquipmentCatalogue } from './equipment-catalogue.ts'; import { isModuleResearched, ModuleStatus, vehicleModuleState, type VehicleModuleState } from './module-status.ts'; +import { ProfileEquipmentIndex } from './profile-equipment-index.ts'; export function refreshModuleState(profile: BlkBlock, catalogue: EquipmentCatalogue): void { const autoRefill = isAutoRefillWeaponsEnabled(profile); const owned = [...ownedVehicles(profile)].sort((a, b) => a.localeCompare(b)); + const index = new ProfileEquipmentIndex(profile); for (const vehicle of owned) { const equipment = catalogue.vehicle(vehicle); if (!equipment) continue; - stockAndRefillEquipment(profile, equipment, autoRefill); - const state = vehicleModuleState(profile, equipment); - setOpenTier(profile, vehicle, state.openTier); + stockAndRefillEquipment(profile, equipment, autoRefill, index); + const state = vehicleModuleState(profile, equipment, index); + index.setOpenTier(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); + if (status === undefined || (status === ModuleStatus.LOCKED && index.moduleResearchPoints(vehicle, modification.name) === 0)) { + index.removeModuleResearch(vehicle, modification.name); } else { - setModuleStatus(profile, vehicle, modification.name, status); + index.setModuleStatus(vehicle, modification.name, status); } } - syncVehicleInvestMode(profile, equipment, state); + syncVehicleInvestMode(profile, equipment, state, index); } + index.flush(); } -function syncVehicleInvestMode(profile: BlkBlock, equipment: VehicleEquipment, state: VehicleModuleState): void { +function syncVehicleInvestMode( + profile: BlkBlock, + equipment: VehicleEquipment, + state: VehicleModuleState, + index: ProfileEquipmentIndex, +): void { const vehicle = equipment.vehicle; - const target = moduleResearchTarget(profile, vehicle); + const target = index.moduleResearchTarget(vehicle); if (target && state.statuses.get(target) === ModuleStatus.CAN_RESEARCH) return; const hasAnyUnresearched = equipment.modifications.some( - (mod) => isResearchable(mod) && !isModuleResearched(profile, vehicle, mod), + (mod) => isResearchable(mod) && !isModuleResearched(profile, vehicle, mod, index), ); if (!hasAnyUnresearched) { - setModuleResearchTarget(profile, vehicle, ''); - setVehicleExcessRp(profile, vehicle, 0); + index.setModuleResearchTarget(vehicle, ''); + index.setVehicleExcessRp(vehicle, 0); return; } const nextMod = pickDefaultResearchableModule(equipment, state); - const prevMod = finishedModuleResearch(profile, vehicle); - const excess = vehicleExcessRp(profile, vehicle); + const prevMod = index.finishedModuleResearch(vehicle); + const excess = index.vehicleExcessRp(vehicle); if (prevMod !== '' || excess === 0) { - setModuleResearchTarget(profile, vehicle, nextMod); + index.setModuleResearchTarget(vehicle, nextMod); } else { - setModuleResearchTarget(profile, vehicle, ''); + index.setModuleResearchTarget(vehicle, ''); } } diff --git a/apps/server/src/modifications/module-status.ts b/apps/server/src/modifications/module-status.ts index e3682b7..0ba129e 100644 --- a/apps/server/src/modifications/module-status.ts +++ b/apps/server/src/modifications/module-status.ts @@ -1,25 +1,14 @@ /** * 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). + * `investMode` itself; the server supplies the rest through `modsResearch`. */ 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'; +import type { ProfileEquipmentIndex } from './profile-equipment-index.ts'; /** shopItemConsts ES_ITEM_STATUS_*; the same values as the vehicle statuses. */ export const ModuleStatus = { @@ -37,42 +26,70 @@ export interface VehicleModuleState { readonly statuses: ReadonlyMap; } -export function vehicleModuleState(profile: BlkBlock, equipment: VehicleEquipment): VehicleModuleState { - const openTier = openTierOf(profile, equipment); +export function vehicleModuleState( + profile: BlkBlock, + equipment: VehicleEquipment, + index?: ProfileEquipmentIndex, +): VehicleModuleState { + const openTier = openTierOf(profile, equipment, index); 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)); + if (isOwned(profile, equipment.vehicle, modification.name, index)) continue; + statuses.set(modification.name, statusOf(profile, equipment.vehicle, modification, openTier, index)); } 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; +export function isModuleResearched( + profile: BlkBlock, + vehicle: string, + modification: ModificationFacts, + index?: ProfileEquipmentIndex, +): boolean { + return isOwned(profile, vehicle, modification.name, index) + || researchPointsOf(profile, vehicle, modification.name, index) >= modification.researchPoints; } -export function arePrerequisitesOwned(profile: BlkBlock, vehicle: string, requires: readonly string[]): boolean { - return requires.every((required) => ownsModification(profile, vehicle, required)); +export function arePrerequisitesOwned( + profile: BlkBlock, + vehicle: string, + requires: readonly string[], + index?: ProfileEquipmentIndex, +): boolean { + return requires.every((required) => isOwned(profile, vehicle, required, index)); } -function openTierOf(profile: BlkBlock, equipment: VehicleEquipment): number { +function isOwned(profile: BlkBlock, vehicle: string, modification: string, index?: ProfileEquipmentIndex): boolean { + return index ? index.ownsModification(vehicle, modification) : ownsModification(profile, vehicle, modification); +} + +function researchPointsOf(profile: BlkBlock, vehicle: string, modification: string, index?: ProfileEquipmentIndex): number { + return index ? index.moduleResearchPoints(vehicle, modification) : moduleResearchPoints(profile, vehicle, modification); +} + +function openTierOf(profile: BlkBlock, equipment: VehicleEquipment, index?: ProfileEquipmentIndex): 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; + const researched = tierModifications.filter((modification) => isModuleResearched(profile, equipment.vehicle, modification, index)).length; if (researched < needed) break; tier++; } return tier; } -function statusOf(profile: BlkBlock, vehicle: string, modification: ModificationFacts, openTier: number): ModuleStatus { +function statusOf( + profile: BlkBlock, + vehicle: string, + modification: ModificationFacts, + openTier: number, + index?: ProfileEquipmentIndex, +): ModuleStatus { if (isResearchable(modification)) { if (modification.tier > openTier) return ModuleStatus.LOCKED; - return isModuleResearched(profile, vehicle, modification) ? ModuleStatus.CAN_BUY : ModuleStatus.CAN_RESEARCH; + return isModuleResearched(profile, vehicle, modification, index) ? ModuleStatus.CAN_BUY : ModuleStatus.CAN_RESEARCH; } - return arePrerequisitesOwned(profile, vehicle, modification.requires) ? ModuleStatus.CAN_BUY : ModuleStatus.LOCKED; + return arePrerequisitesOwned(profile, vehicle, modification.requires, index) ? ModuleStatus.CAN_BUY : ModuleStatus.LOCKED; } diff --git a/apps/server/src/modifications/profile-equipment-index.ts b/apps/server/src/modifications/profile-equipment-index.ts new file mode 100644 index 0000000..7273359 --- /dev/null +++ b/apps/server/src/modifications/profile-equipment-index.ts @@ -0,0 +1,203 @@ +/** + * Hash-indexed view over a profile's flat `hangar`, `modifications`, `weapons` and `modsResearch` + * blocks for the duration of a single refresh pass. Large profiles with 1,000+ spaded vehicles + * carry 30,000+ flat sub-blocks; indexing once drops refresh cost from O(N^2) to O(N). + */ +import { ensureBlock, findBlock, findParam, setParam, type BlkBlock, type BlkParam } from '@wto/blk'; +import { recordName, type ModificationRecord } from '../profile/profile-modifications.ts'; +import type { WeaponRecord } from '../profile/profile-weapons.ts'; + +const HANGAR = 'hangar'; +const MODIFICATIONS = 'modifications'; +const WEAPONS = 'weapons'; +const MODS_RESEARCH = 'modsResearch'; +const STATUS = 'modStatus'; +const RESEARCH_POINTS = 'exp'; + +export class ProfileEquipmentIndex { + readonly #profile: BlkBlock; + readonly #hangar = new Map(); + readonly #modifications = new Map(); + readonly #weapons = new Map(); + readonly #modsResearch = new Map(); + readonly #removedResearch = new Set(); + #modificationsBlock: BlkBlock | undefined; + #weaponsBlock: BlkBlock | undefined; + #modsResearchBlock: BlkBlock | undefined; + + constructor(profile: BlkBlock) { + this.#profile = profile; + const hangar = findBlock(profile, HANGAR); + if (hangar) for (const entry of hangar.blocks) this.#hangar.set(entry.name, entry); + + this.#modificationsBlock = findBlock(profile, MODIFICATIONS); + if (this.#modificationsBlock) { + for (const entry of this.#modificationsBlock.blocks) this.#modifications.set(entry.name, entry); + } + + this.#weaponsBlock = findBlock(profile, WEAPONS); + if (this.#weaponsBlock) { + for (const entry of this.#weaponsBlock.blocks) this.#weapons.set(entry.name, entry); + } + + this.#modsResearchBlock = findBlock(profile, MODS_RESEARCH); + if (this.#modsResearchBlock) { + for (const entry of this.#modsResearchBlock.blocks) this.#modsResearch.set(entry.name, entry); + } + } + + hangarEntry(vehicle: string): BlkBlock | undefined { + return this.#hangar.get(vehicle); + } + + setOpenTier(vehicle: string, tier: number): void { + const entry = this.#hangar.get(vehicle); + if (entry) setParam(entry, 'tierNumber', { type: 'int', value: tier }); + } + + moduleResearchTarget(vehicle: string): string { + const entry = this.#hangar.get(vehicle); + const value = entry && findParam(entry, 'investMode')?.value; + return value?.type === 'string' ? value.value : ''; + } + + setModuleResearchTarget(vehicle: string, modification: string): void { + const entry = this.#hangar.get(vehicle); + if (entry) setParam(entry, 'investMode', { type: 'string', value: modification }); + } + + finishedModuleResearch(vehicle: string): string { + const entry = this.#hangar.get(vehicle); + const value = entry && findParam(entry, 'investModePrev')?.value; + return value?.type === 'string' ? value.value : ''; + } + + vehicleExcessRp(vehicle: string): number { + const entry = this.#hangar.get(vehicle); + const value = entry && findParam(entry, 'excessExp')?.value; + if (value?.type === 'int64') return Math.max(0, Number(value.value)); + return value?.type === 'int' ? Math.max(0, value.value) : 0; + } + + setVehicleExcessRp(vehicle: string, amount: number): void { + const entry = this.#hangar.get(vehicle); + if (entry) setParam(entry, 'excessExp', { type: 'int64', value: BigInt(Math.max(0, Math.trunc(amount))) }); + } + + ownsModification(vehicle: string, modification: string): boolean { + return this.#modifications.has(recordName(vehicle, modification)); + } + + modificationRecord(vehicle: string, modification: string): ModificationRecord | undefined { + const block = this.#modifications.get(recordName(vehicle, modification)); + if (!block) return undefined; + return { + silverLionsSpent: intOf(block, 'wpSpent'), + goldenEaglesSpent: intOf(block, 'goldSpent'), + enabled: boolOf(block, 'enabled') ?? true, + count: intOf(block, 'count'), + }; + } + + writeModificationRecord(vehicle: string, modification: string, record: ModificationRecord): void { + const key = recordName(vehicle, modification); + let block = this.#modifications.get(key); + if (!block) { + this.#modificationsBlock ??= ensureBlock(this.#profile, MODIFICATIONS); + block = { name: key, params: [], blocks: [] }; + this.#modificationsBlock.blocks.push(block); + this.#modifications.set(key, block); + } + block.params = orderedModParams(record); + } + + weaponRecord(vehicle: string, weapon: string): WeaponRecord | undefined { + const block = this.#weapons.get(`${vehicle}_${weapon}`); + if (!block) return undefined; + return { + silverLionsSpent: intOf(block, 'wpSpent'), + goldenEaglesSpent: intOf(block, 'goldSpent'), + count: intOf(block, 'count'), + }; + } + + writeWeaponRecord(vehicle: string, weapon: string, record: WeaponRecord): void { + const key = `${vehicle}_${weapon}`; + let block = this.#weapons.get(key); + if (!block) { + this.#weaponsBlock ??= ensureBlock(this.#profile, WEAPONS); + block = { name: key, params: [], blocks: [] }; + this.#weaponsBlock.blocks.push(block); + this.#weapons.set(key, block); + } + block.params = orderedWeaponParams(record); + } + + moduleResearchPoints(vehicle: string, modification: string): number { + const key = recordName(vehicle, modification); + if (this.#removedResearch.has(key)) return 0; + const entry = this.#modsResearch.get(key); + const value = entry && findParam(entry, RESEARCH_POINTS)?.value; + if (value?.type === 'int64') return Number(value.value); + return value?.type === 'int' ? value.value : 0; + } + + setModuleStatus(vehicle: string, modification: string, status: number): void { + const key = recordName(vehicle, modification); + const points = this.moduleResearchPoints(vehicle, modification); + this.#removedResearch.delete(key); + let entry = this.#modsResearch.get(key); + if (!entry) { + this.#modsResearchBlock ??= ensureBlock(this.#profile, MODS_RESEARCH); + entry = { name: key, params: [], blocks: [] }; + this.#modsResearchBlock.blocks.push(entry); + this.#modsResearch.set(key, entry); + } + const params: BlkParam[] = []; + if (points) params.push({ name: RESEARCH_POINTS, value: { type: 'int64', value: BigInt(points) } }); + params.push({ name: STATUS, value: { type: 'int', value: status } }); + entry.params = params; + } + + removeModuleResearch(vehicle: string, modification: string): void { + const key = recordName(vehicle, modification); + if (!this.#modsResearch.has(key)) return; + this.#removedResearch.add(key); + this.#modsResearch.delete(key); + } + + flush(): void { + if (this.#removedResearch.size > 0 && this.#modsResearchBlock) { + this.#modsResearchBlock.blocks = this.#modsResearchBlock.blocks.filter((entry) => !this.#removedResearch.has(entry.name)); + this.#removedResearch.clear(); + } + } +} + +function orderedModParams(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 orderedWeaponParams(record: WeaponRecord): 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.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/apps/server/src/modifications/support-plane-modifications.ts b/apps/server/src/modifications/support-plane-modifications.ts index e660ab6..2a118c7 100644 --- a/apps/server/src/modifications/support-plane-modifications.ts +++ b/apps/server/src/modifications/support-plane-modifications.ts @@ -11,9 +11,9 @@ * plane's loadout box is empty. The player never owns these units, so online the server has to * provide the records (inferred; not observed). */ -import type { BlkBlock } from '@wto/blk'; +import { ensureBlock, findBlock, type BlkBlock } from '@wto/blk'; import type { BattleSpawnRulesData } from '../game-data/datasets/battle-spawn-rules.ts'; -import { ownsModification, writeModificationRecord } from '../profile/profile-modifications.ts'; +import { recordName } from '../profile/profile-modifications.ts'; import type { EquipmentCatalogue } from './equipment-catalogue.ts'; export interface SupportPlaneModification { @@ -43,8 +43,14 @@ export function supportPlaneModifications( } export function grantSupportPlaneModifications(profile: BlkBlock, grants: readonly SupportPlaneModification[]): void { + if (grants.length === 0) return; + let modsBlock = findBlock(profile, 'modifications'); + const existing = new Set((modsBlock?.blocks ?? []).map((entry) => entry.name)); for (const { vehicle, modification } of grants) { - if (ownsModification(profile, vehicle, modification)) continue; - writeModificationRecord(profile, vehicle, modification, { silverLionsSpent: 0, goldenEaglesSpent: 0, enabled: true, count: 1 }); + const key = recordName(vehicle, modification); + if (existing.has(key)) continue; + modsBlock ??= ensureBlock(profile, 'modifications'); + modsBlock.blocks.push({ name: key, params: [{ name: 'count', value: { type: 'int64', value: 1n } }], blocks: [] }); + existing.add(key); } } diff --git a/apps/server/src/profile/client-profile.ts b/apps/server/src/profile/client-profile.ts index 0bfc00e..fd05d8c 100644 --- a/apps/server/src/profile/client-profile.ts +++ b/apps/server/src/profile/client-profile.ts @@ -15,7 +15,12 @@ import { clearStoreCart } from './profile-store-cart.ts'; import { serverTimeNow } from './server-time.ts'; export function clientProfile(saved: BlkBlock, account: Account): BlkBlock { - const profile = structuredClone(saved); + // Shallow-copy only the top-level lists; child blocks are never mutated here. + const profile: BlkBlock = { + name: saved.name, + params: [...saved.params], + blocks: [...saved.blocks], + }; clearStoreCart(profile); const pilotIcon = appearance(profile).pilotIcon || DEFAULT_PILOT_ICON; setParam(profile, 'pilotIcon', { type: 'string', value: pilotIcon }); diff --git a/apps/server/src/profile/player-profiles.ts b/apps/server/src/profile/player-profiles.ts index f804343..dec7bb0 100644 --- a/apps/server/src/profile/player-profiles.ts +++ b/apps/server/src/profile/player-profiles.ts @@ -29,7 +29,8 @@ export class PlayerProfiles { } profileOf(userId: string): BlkBlock { - const profile = this.#saves.loadProfile(userId) ?? newProfile(this.#gameFiles.newAccountTemplate(), this.#startingContent); + const loaded = this.#saves.loadProfile(userId); + const profile = loaded ?? newProfile(this.#gameFiles.newAccountTemplate(), this.#startingContent); this.#refresh(profile, userId); this.#saves.saveProfile(userId, profile); return profile; @@ -46,10 +47,20 @@ export class PlayerProfiles { /** * 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. + * + * Runs one pre-change refresh in memory (without an extra disk write) so handlers see current + * derived state, then refreshes and persists once when the change succeeds. */ updateWhen(userId: string, change: (profile: BlkBlock) => boolean): BlkBlock | undefined { - const profile = this.profileOf(userId); - if (!change(profile)) return undefined; + const loaded = this.#saves.loadProfile(userId); + const profile = loaded ?? newProfile(this.#gameFiles.newAccountTemplate(), this.#startingContent); + if (!loaded) { + this.#refresh(profile, userId); + } + if (!change(profile)) { + if (!loaded) this.#saves.saveProfile(userId, profile); + return undefined; + } this.#refresh(profile, userId); this.#saves.saveProfile(userId, profile); return profile; diff --git a/apps/server/src/research/research-state.ts b/apps/server/src/research/research-state.ts index 31b0fa3..dd2ee72 100644 --- a/apps/server/src/research/research-state.ts +++ b/apps/server/src/research/research-state.ts @@ -3,21 +3,8 @@ * server keeps it current online; the local server 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, banked excess research points. - * - * 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. Keep every branch researching while it can: a target that is no - * longer researchable (bought, researched, ...) is cleared, and a new one is picked by - * auto-research-target.ts when the branch has just finished a vehicle (prevUnit set: the - * stock scripts then open the "choose the next research" window, ShopCheckResearch, from - * scripts/researches/researchActions.nut checkNonApprovedResearches) or has no banked - * exp. With banked RP and nothing just finished it stays empty, so the player chooses - * where the RP goes (cln_move_exp_to_unit). A branch with nothing left to research has its - * banked RP cleared. */ -import type { BlkBlock } from '@wto/blk'; +import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk'; import { ownedVehicles } from '../profile/profile-hangar.ts'; import { branchExcessRp, @@ -27,7 +14,6 @@ import { 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 { pickResearchTarget } from './auto-research-target.ts'; import { openEarnedRanks } from './era-progress.ts'; import type { ResearchRules } from './research-rules.ts'; @@ -47,15 +33,40 @@ export function refreshResearchState(profile: BlkBlock, rules: ResearchRules): v } const statuses = vehicleStatuses({ profile, owned, earnedUnlocks: earned, techTree: rules.techTree }); + let researchBlock = findBlock(profile, 'unitResearch'); + const researchEntries = new Map(); + if (researchBlock) { + for (const entry of researchBlock.blocks) researchEntries.set(entry.name, entry); + } + const removed = new Set(); + 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); + const entry = researchEntries.get(vehicle.name); + const expParam = entry && findParam(entry, 'exp')?.value; + const rp = expParam?.type === 'int64' ? Number(expParam.value) : (expParam?.type === 'int' ? expParam.value : 0); + + if (status === undefined || (status === VehicleStatus.LOCKED && rp === 0)) { + if (entry) { + removed.add(vehicle.name); + researchEntries.delete(vehicle.name); + } } else { - setVehicleStatus(profile, vehicle.name, status); + let target = entry; + if (!target) { + researchBlock ??= ensureBlock(profile, 'unitResearch'); + target = { name: vehicle.name, params: [], blocks: [] }; + researchBlock.blocks.push(target); + researchEntries.set(vehicle.name, target); + } + setParam(target, 'unitStatus', { type: 'int', value: status }); } } + if (removed.size > 0 && researchBlock) { + researchBlock.blocks = researchBlock.blocks.filter((entry) => !removed.has(entry.name)); + } + const candidates = researchCandidates(rules, statuses); const unresearchedBranches = branchesWithUnresearchedTreeVehicles(rules, statuses); for (const { country, type } of rules.techTree.branches()) { diff --git a/apps/server/src/research/vehicle-status.ts b/apps/server/src/research/vehicle-status.ts index 71cf1d8..f633d64 100644 --- a/apps/server/src/research/vehicle-status.ts +++ b/apps/server/src/research/vehicle-status.ts @@ -1,24 +1,9 @@ /** * 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). + * (gui.vromfs.bin scripts/unit/unitInfoTexts.nut getCantBuyUnitReason). */ -import type { BlkBlock } from '@wto/blk'; -import { openRank } from '../profile/profile-eras.ts'; +import { findBlock, findParam, type BlkBlock } from '@wto/blk'; import { researchPointsOf } from '../profile/profile-vehicle-research.ts'; import type { TechTree, TreeVehicle } from './tech-tree.ts'; @@ -42,13 +27,31 @@ export interface StatusInputs { /** Status of every vehicle the player does not own. */ export function vehicleStatuses(inputs: StatusInputs): Map { + const eras = new Map(); + const erasBlock = findBlock(inputs.profile, 'eras'); + if (erasBlock) { + for (const param of erasBlock.params) { + if (param.value.type === 'int') eras.set(param.name, param.value.value); + } + } + + const rpByVehicle = new Map(); + const researchBlock = findBlock(inputs.profile, 'unitResearch'); + if (researchBlock) { + for (const entry of researchBlock.blocks) { + const value = findParam(entry, 'exp')?.value; + if (value?.type === 'int64') rpByVehicle.set(entry.name, Number(value.value)); + else if (value?.type === 'int') rpByVehicle.set(entry.name, value.value); + } + } + 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); + status = computeStatus(vehicle, inputs, eras, rpByVehicle, statusOfName); statuses.set(vehicle.name, status); } return status; @@ -62,14 +65,20 @@ export function vehicleStatuses(inputs: StatusInputs): Map VehicleStatus | 'owned' | undefined): VehicleStatus { +function computeStatus( + vehicle: TreeVehicle, + inputs: StatusInputs, + eras: ReadonlyMap, + rpByVehicle: ReadonlyMap, + 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; + if (vehicle.kind !== 'squadron' && (eras.get(`${vehicle.type}_${vehicle.country}`) ?? 0) < 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; + if ((rpByVehicle.get(vehicle.name) ?? 0) >= vehicle.researchPoints) 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; }