From de469b0d6bf63f91fb94d50d387c2c0771b1ae45 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sat, 28 Nov 2026 08:20:40 +0800 Subject: [PATCH] feat(battle): apply research efficiency rules to battle RP Vehicle research points now follow rank.blk: the predecessor bonus (expBonusPercentForChildForMode), the rank difference penalty (expPenaltyPercentForHigherRank / LowerRank) and the Vehicle Research Bonus (ExpNewNationBonus, five battles per nation and type per UTC day). Modifications keep the research points before these terms. The settlement records each vehicle's breakdown in the session log's container.researchPoints, which the stock debriefing explains in its research rows. The debriefing patch now selects the battle's logs by room id, since a LocalMP host is in no matching room and the stock current-room check cannot match them. --- .../replace.nut | 5 +- .../find-gather.nut | 2 + .../find-research-points.nut | 1 + .../find-room-logs.nut | 5 + .../use-settled-debriefing-stats/patch.jsonc | 22 +- .../replace-gather.nut | 6 + .../replace-research-points.nut | 3 + .../replace-room-logs.nut | 9 + .../use-settled-debriefing-stats/replace.nut | 8 +- .../src/battle/battle-debriefing.ts | 42 +-- .../src/battle/battle-result-log.ts | 36 ++ .../src/battle/battle-rp-investment.ts | 344 ++++++++++++------ .../src/battle/battle-settlement.ts | 53 +-- .../src/char/actions/battle-actions.ts | 3 + .../game-data/datasets/research-efficiency.ts | 82 +++++ packages/local-service/src/local-service.ts | 5 +- .../src/profile/profile-research-bonus.ts | 41 +++ .../src/research/research-efficiency.ts | 101 +++++ 18 files changed, 598 insertions(+), 170 deletions(-) create mode 100644 gui-patches/battle/use-settled-debriefing-stats/find-gather.nut create mode 100644 gui-patches/battle/use-settled-debriefing-stats/find-research-points.nut create mode 100644 gui-patches/battle/use-settled-debriefing-stats/find-room-logs.nut create mode 100644 gui-patches/battle/use-settled-debriefing-stats/replace-gather.nut create mode 100644 gui-patches/battle/use-settled-debriefing-stats/replace-research-points.nut create mode 100644 gui-patches/battle/use-settled-debriefing-stats/replace-room-logs.nut create mode 100644 packages/local-service/src/game-data/datasets/research-efficiency.ts create mode 100644 packages/local-service/src/profile/profile-research-bonus.ts create mode 100644 packages/local-service/src/research/research-efficiency.ts diff --git a/gui-patches/battle/report-local-battle-settlement/replace.nut b/gui-patches/battle/report-local-battle-settlement/replace.nut index 42607fe..98495c9 100644 --- a/gui-patches/battle/report-local-battle-settlement/replace.nut +++ b/gui-patches/battle/report-local-battle-settlement/replace.nut @@ -52,12 +52,11 @@ function applyWtoSettledDebriefing(wtoBattle) { .findvalue(@(l) l?.wtoSessionId == wtoBattle.sessionId) if (sessionLog?.wtoDebriefing == null) return - ndbWrite(["wto", "settledExp"], sessionLog.wtoDebriefing) + ndbWrite(["wto", "settled"], { exp = sessionLog.wtoDebriefing, roomId = sessionLog.roomId }) gatherDebriefingResult() - ndbDelete(["wto", "settledExp"]) + ndbDelete(["wto", "settled"]) let cur = getDebriefingResult() cur.isSucceed = sessionLog?.win ?? false - cur.roomUserlogs = [sessionLog].extend((cur?.roomUserlogs ?? []).filter(@(l) l?.type != EULT_SESSION_RESULT)) let evObj = events.getEvent(wtoBattle?.modeName ?? "") if (evObj != null && cur.roomEvent == null) cur.roomEvent = { diff --git a/gui-patches/battle/use-settled-debriefing-stats/find-gather.nut b/gui-patches/battle/use-settled-debriefing-stats/find-gather.nut new file mode 100644 index 0000000..d2947b9 --- /dev/null +++ b/gui-patches/battle/use-settled-debriefing-stats/find-gather.nut @@ -0,0 +1,2 @@ +function gatherDebriefingResult() { + let gm = get_game_mode() diff --git a/gui-patches/battle/use-settled-debriefing-stats/find-research-points.nut b/gui-patches/battle/use-settled-debriefing-stats/find-research-points.nut new file mode 100644 index 0000000..f48b87a --- /dev/null +++ b/gui-patches/battle/use-settled-debriefing-stats/find-research-points.nut @@ -0,0 +1 @@ + let resPointsLogs = getUserLogsList({ show = [EULT_SESSION_RESULT], currentRoomOnly = true })?[0].container.researchPoints.unit ?? [] diff --git a/gui-patches/battle/use-settled-debriefing-stats/find-room-logs.nut b/gui-patches/battle/use-settled-debriefing-stats/find-room-logs.nut new file mode 100644 index 0000000..23ce349 --- /dev/null +++ b/gui-patches/battle/use-settled-debriefing-stats/find-room-logs.nut @@ -0,0 +1,5 @@ + roomUserlogs = getUserLogsList({ + currentRoomOnly = true + needStackItems = false + disableVisible = true + }) diff --git a/gui-patches/battle/use-settled-debriefing-stats/patch.jsonc b/gui-patches/battle/use-settled-debriefing-stats/patch.jsonc index 136ab70..68e9666 100644 --- a/gui-patches/battle/use-settled-debriefing-stats/patch.jsonc +++ b/gui-patches/battle/use-settled-debriefing-stats/patch.jsonc @@ -1,10 +1,12 @@ -// Build the debriefing of a settled LocalMP battle from the statistics the local service computed. +// Build the debriefing of a settled LocalMP battle from what the local service settled: its +// statistics table, its room's logs and their Research Points breakdown. // Why the client: the debriefing reads stat_get_exp() (aces.exe 0x1053b70, the battle's -// SessionStatsNet), which online the battle server fills; a LocalMP host has none, so it is empty. -// Without it: the debriefing shows no rewards, activity or research. +// SessionStatsNet), which online the battle server fills, and picks the battle's logs with +// is_user_log_for_current_room (0x1799d30), which needs a matching room; a LocalMP host has neither. +// Without it: the debriefing shows no rewards, awards, activity or research. { "id": "battle/use-settled-debriefing-stats", - "title": "Use the local service's battle statistics in the LocalMP debriefing", + "title": "Use the local service's settled battle in the LocalMP debriefing", "file": "scripts/debriefing/debriefingfull.nut", "features": [ "L-结算页" @@ -13,9 +15,21 @@ "2.61.0.37" ], "edits": [ + { + "find": "find-gather.nut", + "replace": "replace-gather.nut" + }, + { + "find": "find-room-logs.nut", + "replace": "replace-room-logs.nut" + }, { "find": "find.nut", "replace": "replace.nut" + }, + { + "find": "find-research-points.nut", + "replace": "replace-research-points.nut" } ] } diff --git a/gui-patches/battle/use-settled-debriefing-stats/replace-gather.nut b/gui-patches/battle/use-settled-debriefing-stats/replace-gather.nut new file mode 100644 index 0000000..876111e --- /dev/null +++ b/gui-patches/battle/use-settled-debriefing-stats/replace-gather.nut @@ -0,0 +1,6 @@ +function gatherDebriefingResult() { + // WTOffline: while a LocalMP battle is being settled, nestdb wto.settled holds what the local + // service settled: { exp = the debriefing table, roomId = the battle's room id } + // (written by report-local-battle-settlement). + let wtoSettled = require("nestdb").ndbTryRead(["wto", "settled"]) + let gm = get_game_mode() diff --git a/gui-patches/battle/use-settled-debriefing-stats/replace-research-points.nut b/gui-patches/battle/use-settled-debriefing-stats/replace-research-points.nut new file mode 100644 index 0000000..2db5226 --- /dev/null +++ b/gui-patches/battle/use-settled-debriefing-stats/replace-research-points.nut @@ -0,0 +1,3 @@ + let resPointsLogs = (wtoSettled != null + ? debriefingResult.roomUserlogs.findvalue(@(l) l?.type == EULT_SESSION_RESULT)?.container?.researchPoints?.unit + : getUserLogsList({ show = [EULT_SESSION_RESULT], currentRoomOnly = true })?[0].container.researchPoints.unit) ?? [] diff --git a/gui-patches/battle/use-settled-debriefing-stats/replace-room-logs.nut b/gui-patches/battle/use-settled-debriefing-stats/replace-room-logs.nut new file mode 100644 index 0000000..f4fa039 --- /dev/null +++ b/gui-patches/battle/use-settled-debriefing-stats/replace-room-logs.nut @@ -0,0 +1,9 @@ + // WTOffline: a settled LocalMP battle's logs carry its room id, but the client is not in a + // matching room, so is_user_log_for_current_room cannot match them; select them by room id. + roomUserlogs = wtoSettled != null + ? getUserLogsList({ needStackItems = false, disableVisible = true }).filter(@(l) l?.roomId == wtoSettled.roomId) + : getUserLogsList({ + currentRoomOnly = true + needStackItems = false + disableVisible = true + }) diff --git a/gui-patches/battle/use-settled-debriefing-stats/replace.nut b/gui-patches/battle/use-settled-debriefing-stats/replace.nut index 5657b2e..ad4cc9d 100644 --- a/gui-patches/battle/use-settled-debriefing-stats/replace.nut +++ b/gui-patches/battle/use-settled-debriefing-stats/replace.nut @@ -1,5 +1,3 @@ - // WTOffline: while a LocalMP battle is being settled, take the debriefing statistics the local - // service computed (nestdb wto.settledExp, written by report-local-battle-settlement) instead of - // the local SessionStatsNet, which no battle server fills on a LocalMP host. - let wtoSettledExp = require("nestdb").ndbTryRead(["wto", "settledExp"]) - let exp = wtoSettledExp != null ? u.copy(wtoSettledExp) : (stat_get_exp() ?? {}) + // WTOffline: the settled statistics replace the local SessionStatsNet, which no battle server + // fills on a LocalMP host. + let exp = wtoSettled != null ? u.copy(wtoSettled.exp) : (stat_get_exp() ?? {}) diff --git a/packages/local-service/src/battle/battle-debriefing.ts b/packages/local-service/src/battle/battle-debriefing.ts index 1b91e7a..3bb9237 100644 --- a/packages/local-service/src/battle/battle-debriefing.ts +++ b/packages/local-service/src/battle/battle-debriefing.ts @@ -10,34 +10,19 @@ * investUnitName:t expInvestUnit:i expInvestUnitTotal:i * Vehicle only: expSkillBonus:i investModuleName:t expInvestModule:i expInvestModuleTotal:i * expInvestUnit:i expInvestUnitTotal:i + * Invest<...> is what reached the researched modification / vehicle, Invest<...>Total all RP for + * modification / vehicle research (battle-rp-investment.ts). * (key names from the strings of 0x1053b70, 0xf86c10 and 0xf89f90). */ import { emptyBlock, setParam, type BlkBlock } from '@wto/blk'; import type { BattleRewards, RewardRow, RowRewards } from './battle-rewards.ts'; +import type { BattleRpResult } from './battle-rp-investment.ts'; /** STATS_RESULT_* script constants, registered by aces.exe 0x17db810 (SUCCESS 1, FAIL 2). */ const STATS_RESULT_SUCCESS = 1; const STATS_RESULT_FAIL = 2; -export interface ModuleInvestment { - readonly vehicle: string; - readonly module: string; - readonly rp: number; -} - -export interface BranchInvestment { - /** Unit type suffix of the research branch: Aircraft, Tank, Ship, Boat or Helicopter. */ - readonly type: string; - readonly unit: string; - readonly rp: number; -} - -export interface DebriefingInvestments { - readonly modules: readonly ModuleInvestment[]; - readonly branches: readonly BranchInvestment[]; -} - -export function debriefingTable(name: string, rewards: BattleRewards, investments: DebriefingInvestments): BlkBlock { +export function debriefingTable(name: string, rewards: BattleRewards, research: BattleRpResult): BlkBlock { const root = emptyBlock(name); const rootRows = new Map(); for (const vehicle of rewards.vehicles) { @@ -55,10 +40,10 @@ export function debriefingTable(name: string, rewards: BattleRewards, investment setParam(root, 'expFree', { type: 'int', value: rewards.expFree }); setParam(root, 'expSkillBonusTotal', { type: 'int', value: rewards.vehicles.reduce((sum, v) => sum + v.skillBonusExp, 0) }); setParam(root, 'expSkillBonusLevel', { type: 'int', value: rewards.skillBonusLevel }); - for (const branch of investments.branches) { + for (const branch of research.branches) { setParam(root, `investUnitName${branch.type}`, { type: 'string', value: branch.unit }); - setParam(root, `expInvestUnit${branch.type}`, { type: 'int', value: branch.rp }); - setParam(root, `expInvestUnitTotal${branch.type}`, { type: 'int', value: branch.rp }); + setParam(root, `expInvestUnit${branch.type}`, { type: 'int', value: branch.invested }); + setParam(root, `expInvestUnitTotal${branch.type}`, { type: 'int', value: branch.total }); } const aircrafts = emptyBlock('aircrafts'); @@ -69,12 +54,13 @@ export function debriefingTable(name: string, rewards: BattleRewards, investment writeRows(block, vehicle.rows, vehicle.wpTotal, vehicle.expTotal); setParam(block, 'expSkillBonus', { type: 'int', value: vehicle.skillBonusExp }); setParam(block, 'expSkillBonusTotal', { type: 'int', value: vehicle.skillBonusExp }); - const module = investments.modules.find((m) => m.vehicle === vehicle.vehicle); - if (module) setParam(block, 'investModuleName', { type: 'string', value: module.module }); - setParam(block, 'expInvestModule', { type: 'int', value: module?.rp ?? 0 }); - setParam(block, 'expInvestModuleTotal', { type: 'int', value: module?.rp ?? 0 }); - setParam(block, 'expInvestUnit', { type: 'int', value: vehicle.expTotal }); - setParam(block, 'expInvestUnitTotal', { type: 'int', value: vehicle.expTotal }); + // expInvestModule < expInvestModuleTotal marks the modification as finished (debriefingFull.nut expModuleCapped). + const unit = research.units.find((entry) => entry.unit === vehicle.vehicle); + setParam(block, 'investModuleName', { type: 'string', value: unit?.invModuleName ?? '' }); + setParam(block, 'expInvestModule', { type: 'int', value: unit?.invModuleExp ?? 0 }); + setParam(block, 'expInvestModuleTotal', { type: 'int', value: unit?.moduleTotal ?? 0 }); + setParam(block, 'expInvestUnit', { type: 'int', value: unit?.invUnitExp ?? 0 }); + setParam(block, 'expInvestUnitTotal', { type: 'int', value: unit?.unitTotal ?? 0 }); aircrafts.blocks.push(block); } root.blocks.push(aircrafts); diff --git a/packages/local-service/src/battle/battle-result-log.ts b/packages/local-service/src/battle/battle-result-log.ts index 1de30ce..46e49fe 100644 --- a/packages/local-service/src/battle/battle-result-log.ts +++ b/packages/local-service/src/battle/battle-result-log.ts @@ -8,6 +8,7 @@ import { appendUserLog, EULT_SESSION_RESULT } from '../profile/profile-trophies- import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts'; import type { DebriefingRow } from './battle-economy.ts'; import type { BattleRewards, Bonuses } from './battle-rewards.ts'; +import type { ResearchPointsUnit } from './battle-rp-investment.ts'; import type { BattleSession } from './battle-session-store.ts'; export interface EarnedRpItem { @@ -23,6 +24,7 @@ export interface BattleResultSummary { readonly weaponRefillSl: number; readonly usedSpares: Readonly>; readonly rpItems: readonly EarnedRpItem[]; + readonly researchUnits: readonly ResearchPointsUnit[]; readonly debriefing: BlkBlock; } @@ -162,9 +164,43 @@ function buildContainerBlock(summary: BattleResultSummary): BlkBlock { return unit; }); if (skillUnits.length > 0) container.blocks.push({ name: 'expSkillBonus', params: [], blocks: skillUnits }); + if (summary.researchUnits.length > 0) { + container.blocks.push({ name: 'researchPoints', params: [], blocks: summary.researchUnits.map(researchPointsUnitBlock) }); + } return container; } +/** + * One `container.researchPoints.unit` entry, the RP breakdown the stock debriefing tooltips show + * (debriefingFull.nut ModsTotal / NewNationBonus / UnitTotal; the client sums the parts itself). + */ +function researchPointsUnitBlock(unit: ResearchPointsUnit): BlkBlock { + const block = emptyBlock('unit'); + const int = (name: string, value: number): void => setParam(block, name, { type: 'int', value }); + setParam(block, 'unit', { type: 'string', value: unit.unit }); + int('noBonusExpTotal', unit.noBonusExpTotal); + int('premAccExpTotal', unit.premAccExpTotal); + int('premModExpTotal', unit.premModExpTotal); + int('expSkillBonus', unit.expSkillBonus); + if (unit.invModuleName) setParam(block, 'invModuleName', { type: 'string', value: unit.invModuleName }); + int('invModuleExp', unit.invModuleExp); + if (unit.newNationBonusExp > 0) { + int('newNationBonusPercent', unit.newNationBonusPercent); + int('newNationBonusExp', unit.newNationBonusExp); + } + if (unit.childBonusExp > 0) { + int('childBonusPercent', unit.childBonusPercent); + int('childBonusExp', unit.childBonusExp); + } + if (unit.rankDiffPenaltyExp > 0) { + int('rankDiffPenaltyPercent', unit.rankDiffPenaltyPercent); + int('rankDiffPenaltyExp', unit.rankDiffPenaltyExp); + } + if (unit.invUnitName) setParam(block, 'invUnitName', { type: 'string', value: unit.invUnitName }); + int('invUnitExp', unit.invUnitExp); + return block; +} + function writeAmounts(block: BlkBlock, wp: number, exp: number, bonuses: Bonuses): void { setParam(block, 'wpNoBonus', { type: 'int', value: wp }); setParam(block, 'expNoBonus', { type: 'int', value: exp }); diff --git a/packages/local-service/src/battle/battle-rp-investment.ts b/packages/local-service/src/battle/battle-rp-investment.ts index 14d1e13..d9ebbe9 100644 --- a/packages/local-service/src/battle/battle-rp-investment.ts +++ b/packages/local-service/src/battle/battle-rp-investment.ts @@ -1,14 +1,26 @@ /** - * Post-battle Modification RP and Vehicle RP investment with overflow banking: - * - Modification RP completes at most the vehicle's active `investMode` modification, sets - * `investModePrev = `, clears `investMode = ""`, and banks remaining RP into - * `hangar//excessExp:i64` (unless all modifications on the vehicle are researched). - * - Vehicle RP aggregates per `(country, branchType)` before investing, completes at most the - * active `currUnit` once, sets `prevUnit = `, clears `currUnit = ""`, and - * banks remaining RP into `researchUnits..exp:i64`. + * Invests a battle's Research Points (rules: research/research-efficiency.ts): + * + * - Modifications: each owned vehicle's RP, before research efficiency, goes to its own active + * `investMode` modification (official wiki: "the total will be equal to the amount of vehicle + * research points awarded (before research efficiency multipliers)"). A finished modification + * becomes `investModePrev`, `investMode` is cleared and the rest is banked in + * `hangar//excessExp:i64` while the vehicle has modifications left to research. + * - Vehicles: each vehicle's RP plus the Vehicle Research Bonus, with the predecessor bonus or the + * rank penalty against the branch's research target, goes to that branch (all vehicles of a + * branch feed one pool, official wiki). The pool completes at most the current `currUnit`, which + * then becomes `prevUnit` with `currUnit` cleared; the rest is banked in + * `researchUnits..exp:i64`, and the stock client asks the player for the next + * research (scripts/researches/researchActions.nut) and spends the banked RP on it + * (cln_move_exp_to_unit). A branch without a research target banks the RP unchanged. + * + * Each vehicle's breakdown is returned in the shape of the `EULT_SESSION_RESULT` + * `container.researchPoints.unit` entries the stock debriefing explains RP with + * (gui.vromfs.bin scripts/debriefing/debriefingFull.nut rows ModsTotal, NewNationBonus, UnitTotal). */ import type { BlkBlock } from '@wto/blk'; import type { CrewSkillCatalogue } from '../crew/crew-skill-rules.ts'; +import type { EconomyDifficulty } from '../game-data/datasets/battle-economy.ts'; import type { UnitClass } from '../game-modes/catalogue/game-mode-declaration.ts'; import { isResearchable, type EquipmentCatalogue } from '../modifications/equipment-catalogue.ts'; import { pickDefaultResearchableModule } from '../modifications/module-state.ts'; @@ -18,6 +30,7 @@ import { crewForVehicleInCountry } from '../profile/profile-crews.ts'; import { readRedirectedResearchDomain, type VehicleDomain } from '../profile/profile-dest-rp.ts'; import { ownedVehicles } from '../profile/profile-hangar.ts'; import { moduleResearchPoints, setModuleResearchPoints } from '../profile/profile-module-research.ts'; +import { researchBonusBattlesUsed, useResearchBonusBattle } from '../profile/profile-research-bonus.ts'; import { branchExcessRp, finishedResearch, @@ -35,86 +48,201 @@ import { setVehicleExcessRp, vehicleExcessRp, } from '../profile/profile-vehicle-state.ts'; +import type { ResearchEfficiency } from '../research/research-efficiency.ts'; import { addResearchPoints } from '../research/research-progress.ts'; import type { ResearchRules } from '../research/research-rules.ts'; import { currentStatus, refreshResearchState } from '../research/research-state.ts'; +import type { TreeVehicle } from '../research/tech-tree.ts'; import { VehicleStatus } from '../research/vehicle-status.ts'; import type { EarnedRpItem } from './battle-result-log.ts'; -import type { BattleSession } from './battle-session-store.ts'; export interface BattleRpDeps { readonly research: ResearchRules; + readonly efficiency: ResearchEfficiency; readonly equipment: EquipmentCatalogue; readonly crew: CrewSkillCatalogue; } +/** A vehicle's Research Points of the battle, split as the debriefing shows them. */ export interface VehicleRp { readonly vehicle: string; - readonly rp: number; + readonly noBonusExp: number; + readonly premAccExp: number; + readonly premModExp: number; + readonly skillBonusExp: number; + /** The sum of the four. */ + readonly total: number; } -/** Each vehicle's Research Points go both to its own modification research and to its branch's vehicle research. */ -export function collectEarnedBattleRp( - profile: BlkBlock, - earned: readonly VehicleRp[], - session: BattleSession, - deps: BattleRpDeps, -): EarnedRpItem[] { - const rpItems: EarnedRpItem[] = []; - const owned = ownedVehicles(profile); - const branchTotals = new Map(); +export interface RpContext { + readonly country: string; + readonly requiredClass: UnitClass; + readonly difficulty: EconomyDifficulty; + readonly nowUnixSec: number; +} +/** One `container.researchPoints.unit` entry. */ +export interface ResearchPointsUnit { + readonly unit: string; + readonly noBonusExpTotal: number; + readonly premAccExpTotal: number; + readonly premModExpTotal: number; + readonly expSkillBonus: number; + readonly invModuleName?: string; + /** RP that reached the modification. */ + invModuleExp: number; + /** RP for modifications (the vehicle's total when it is owned, else 0). */ + readonly moduleTotal: number; + readonly newNationBonusPercent: number; + readonly newNationBonusExp: number; + readonly childBonusPercent: number; + readonly childBonusExp: number; + readonly rankDiffPenaltyPercent: number; + readonly rankDiffPenaltyExp: number; + invUnitName?: string; + /** RP that reached the researched vehicle. */ + invUnitExp: number; + /** RP for vehicle research after bonuses and penalty. */ + readonly unitTotal: number; +} + +export interface BranchInvestment { + /** Unit type suffix of the research branch: Aircraft, Tank, Ship, Boat or Helicopter. */ + readonly type: string; + /** The researched vehicle, or the vehicle finished last when the branch had no target. */ + readonly unit: string; + readonly invested: number; + readonly total: number; +} + +export interface BattleRpResult { + readonly units: readonly ResearchPointsUnit[]; + readonly branches: readonly BranchInvestment[]; + /** Entries of the session log's `rpEarned` list. */ + readonly rpItems: readonly EarnedRpItem[]; +} + +interface BranchPool { + readonly country: string; + readonly type: string; + readonly target: TreeVehicle | undefined; + readonly members: ResearchPointsUnit[]; + bonusBattle: boolean; +} + +export function investBattleRp(profile: BlkBlock, earned: readonly VehicleRp[], ctx: RpContext, deps: BattleRpDeps): BattleRpResult { refreshResearchState(profile, deps.research); - for (const { vehicle, rp } of earned) { - if (rp <= 0) continue; - if (owned.has(vehicle)) { - const modItem = investModificationRp(profile, deps.equipment, vehicle, rp); - if (modItem) rpItems.push(modItem); - investAceCrewRp(profile, deps.crew, session.country, vehicle, rp); + const owned = ownedVehicles(profile); + const units: ResearchPointsUnit[] = []; + const rpItems: EarnedRpItem[] = []; + const pools = new Map(); + + for (const rp of earned) { + if (rp.total <= 0) continue; + const isOwned = owned.has(rp.vehicle); + const module = isOwned ? investModificationRp(profile, deps.equipment, rp.vehicle, rp.total) : undefined; + if (module) rpItems.push(module); + if (isOwned) investAceCrewRp(profile, deps.crew, ctx.country, rp.vehicle, rp.total); + + const branch = branchOf(profile, deps.research, rp.vehicle, ctx); + if (!branch) continue; + const key = `${branch.country}\0${branch.type}`; + let pool = pools.get(key); + if (!pool) { + pool = { ...branch, target: researchTargetOf(profile, deps.research, branch.country, branch.type), members: [], bonusBattle: false }; + pools.set(key, pool); } - accumulateBranchRp(branchTotals, profile, deps.research, vehicle, session, rp); + const unit = vehicleResearchShare(rp, pool, profile, owned, ctx, deps); + units.push({ + ...unit, + ...(module?.modification ? { invModuleName: module.modification } : {}), + invModuleExp: module?.rp ?? 0, + moduleTotal: isOwned ? rp.total : 0, + }); + pool.members.push(units.at(-1)!); } - for (const entry of branchTotals.values()) { - const item = investIntoBranch(profile, deps.research, entry.country, entry.branchType, entry.amount); - if (item) rpItems.push(item); + + const branches: BranchInvestment[] = []; + for (const pool of pools.values()) { + if (pool.bonusBattle) useResearchBonusBattle(profile, pool.country, pool.type, ctx.nowUnixSec); + const invested = investBranchPool(profile, deps.research, pool); + if (invested) { + rpItems.push(invested.item); + branches.push(invested.branch); + } } - return rpItems; + return { units, branches, rpItems }; } -function accumulateBranchRp( - branchTotals: Map, +/** One vehicle's share of its branch pool: bonus, predecessor bonus or penalty against the target. */ +function vehicleResearchShare( + rp: VehicleRp, + pool: BranchPool, + profile: BlkBlock, + owned: ReadonlySet, + ctx: RpContext, + deps: BattleRpDeps, +): Omit { + const base = { + unit: rp.vehicle, + noBonusExpTotal: rp.noBonusExp, + premAccExpTotal: rp.premAccExp, + premModExpTotal: rp.premModExp, + expSkillBonus: rp.skillBonusExp, + invUnitExp: 0, + }; + const played = deps.research.techTree.vehicle(rp.vehicle); + const target = pool.target; + if (!target || !played) { + return { + ...base, + newNationBonusPercent: 0, + newNationBonusExp: 0, + childBonusPercent: 0, + childBonusExp: 0, + rankDiffPenaltyPercent: 0, + rankDiffPenaltyExp: 0, + unitTotal: rp.total, + }; + } + let nationPercent = deps.efficiency.nationBonusPercent(target, owned); + if (nationPercent > 0 && !pool.bonusBattle + && researchBonusBattlesUsed(profile, pool.country, pool.type, ctx.nowUnixSec) >= deps.efficiency.dailyBonusBattles) { + nationPercent = 0; + } + // A battle without base RP does not use a bonus battle (news "Following the Roadmap: Vehicle Research Bonuses"). + if (nationPercent > 0 && rp.noBonusExp > 0) pool.bonusBattle = true; + const nationExp = Math.round(rp.noBonusExp * nationPercent / 100); + const { childBonusPercent, rankDiffPenaltyPercent } = deps.efficiency.termsFor(played, target, ctx.difficulty); + const boosted = rp.total + nationExp; + const childBonusExp = Math.round(boosted * childBonusPercent / 100); + const rankDiffPenaltyExp = Math.round(boosted * rankDiffPenaltyPercent / 100); + return { + ...base, + newNationBonusPercent: nationExp > 0 ? nationPercent : 0, + newNationBonusExp: nationExp, + childBonusPercent, + childBonusExp, + rankDiffPenaltyPercent, + rankDiffPenaltyExp, + invUnitName: target.name, + unitTotal: Math.max(0, boosted + childBonusExp - rankDiffPenaltyExp), + }; +} + +function branchOf( profile: BlkBlock, research: ResearchRules, - playedVehicleName: string, - session: BattleSession, - amount: number, -): void { - const played = research.techTree.vehicle(playedVehicleName); - if (played) { - const targetBranch = readRedirectedResearchDomain(profile, played.country, played.type); - addToBranchMap(branchTotals, played.country, targetBranch, amount); - return; - } - const fallbackBranch = resolveFallbackBranch(profile, session.country, session.requiredClass); - if (fallbackBranch) { - const targetBranch = readRedirectedResearchDomain(profile, session.country, fallbackBranch); - addToBranchMap(branchTotals, session.country, targetBranch, amount); - } + vehicle: string, + ctx: RpContext, +): { country: string; type: string } | undefined { + const played = research.techTree.vehicle(vehicle); + if (played) return { country: played.country, type: readRedirectedResearchDomain(profile, played.country, played.type) }; + const fallback = fallbackBranch(profile, ctx.country, ctx.requiredClass); + return { country: ctx.country, type: readRedirectedResearchDomain(profile, ctx.country, fallback) }; } -function addToBranchMap( - map: Map, - country: string, - branchType: string, - amount: number, -): void { - const key = `${country}\0${branchType}`; - const existing = map.get(key); - if (existing) existing.amount += amount; - else map.set(key, { country, branchType, amount }); -} - -function resolveFallbackBranch(profile: BlkBlock, country: string, requiredClass: UnitClass): VehicleDomain | undefined { +function fallbackBranch(profile: BlkBlock, country: string, requiredClass: UnitClass): VehicleDomain { const preferred: Readonly> = { tank: ['Tank', 'Aircraft', 'Helicopter', 'Boat', 'Ship'], aircraft: ['Aircraft', 'Helicopter', 'Tank', 'Boat', 'Ship'], @@ -122,7 +250,59 @@ function resolveFallbackBranch(profile: BlkBlock, country: string, requiredClass ship: ['Ship', 'Boat', 'Aircraft', 'Tank', 'Helicopter'], }; return preferred[requiredClass].find((branch) => Boolean(researchTarget(profile, country, branch))) - ?? preferred[requiredClass][0]; + ?? preferred[requiredClass][0]!; +} + +function researchTargetOf(profile: BlkBlock, research: ResearchRules, country: string, type: string): TreeVehicle | undefined { + const name = researchTarget(profile, country, type); + const target = name ? research.techTree.vehicle(name) : undefined; + if (!target || target.researchPoints <= 0) return undefined; + return currentStatus(profile, research, target.name) === VehicleStatus.CAN_RESEARCH ? target : undefined; +} + +function investBranchPool( + profile: BlkBlock, + research: ResearchRules, + pool: BranchPool, +): { item: EarnedRpItem; branch: BranchInvestment } | undefined { + const amount = pool.members.reduce((sum, member) => sum + member.unitTotal, 0); + if (amount <= 0) return undefined; + const { country, type, target } = pool; + if (!target) { + if (!hasUnresearchedBranchVehicle(profile, research, country, type)) return undefined; + setBranchExcessRp(profile, country, type, branchExcessRp(profile, country, type) + amount); + const labelUnit = finishedResearch(profile, country, type); + if (!labelUnit) return undefined; + return { item: { unit: labelUnit, rp: 0, excessRp: amount }, branch: { type, unit: labelUnit, invested: 0, total: amount } }; + } + + const before = researchPointsOf(profile, target.name); + const invested = Math.min(amount, Math.max(0, target.researchPoints - before)); + const remaining = amount - invested; + if (invested > 0) addResearchPoints(profile, target, invested); + let left = invested; + for (const member of pool.members) { + member.invUnitExp = Math.min(left, member.unitTotal); + left -= member.invUnitExp; + } + + let bankedExcess = 0; + if (before + invested >= target.researchPoints) { + setResearchTarget(profile, country, type, ''); + setFinishedResearch(profile, country, type, target.name); + if (hasUnresearchedBranchVehicle(profile, research, country, type)) { + if (remaining > 0) { + setBranchExcessRp(profile, country, type, branchExcessRp(profile, country, type) + remaining); + bankedExcess = remaining; + } + } else { + setBranchExcessRp(profile, country, type, 0); + } + } + return { + item: { unit: target.name, rp: invested, ...(bankedExcess > 0 ? { excessRp: bankedExcess } : {}) }, + branch: { type, unit: target.name, invested, total: amount }, + }; } function investModificationRp( @@ -177,48 +357,6 @@ function investModificationRp( }; } -function investIntoBranch( - profile: BlkBlock, - research: ResearchRules, - country: string, - branchType: string, - amount: number, -): EarnedRpItem | undefined { - if (amount <= 0) return undefined; - const targetName = researchTarget(profile, country, branchType); - const target = targetName ? research.techTree.vehicle(targetName) : undefined; - if (!target || target.researchPoints <= 0 || currentStatus(profile, research, target.name) !== VehicleStatus.CAN_RESEARCH) { - if (!hasUnresearchedBranchVehicle(profile, research, country, branchType)) return undefined; - setBranchExcessRp(profile, country, branchType, branchExcessRp(profile, country, branchType) + amount); - const labelUnit = finishedResearch(profile, country, branchType); - return labelUnit ? { unit: labelUnit, rp: 0, excessRp: amount } : undefined; - } - - const before = researchPointsOf(profile, target.name); - const invested = Math.min(amount, Math.max(0, target.researchPoints - before)); - const remaining = amount - invested; - if (invested > 0) addResearchPoints(profile, target, invested); - - let bankedExcess = 0; - if (before + invested >= target.researchPoints) { - setResearchTarget(profile, country, branchType, ''); - setFinishedResearch(profile, country, branchType, target.name); - if (hasUnresearchedBranchVehicle(profile, research, country, branchType)) { - if (remaining > 0) { - setBranchExcessRp(profile, country, branchType, branchExcessRp(profile, country, branchType) + remaining); - bankedExcess = remaining; - } - } else { - setBranchExcessRp(profile, country, branchType, 0); - } - } - return { - unit: target.name, - rp: invested, - ...(bankedExcess > 0 ? { excessRp: bankedExcess } : {}), - }; -} - function hasUnresearchedModification( profile: BlkBlock, vehicle: string, diff --git a/packages/local-service/src/battle/battle-settlement.ts b/packages/local-service/src/battle/battle-settlement.ts index 152d686..3ca5bc0 100644 --- a/packages/local-service/src/battle/battle-settlement.ts +++ b/packages/local-service/src/battle/battle-settlement.ts @@ -16,14 +16,15 @@ import { remainingPremiumDays } from '../profile/profile-entitlements.ts'; import { ownedVehicles } from '../profile/profile-hangar.ts'; import { ownsModification } from '../profile/profile-modifications.ts'; import { addFreeResearchPoints } from '../profile/profile-research-points.ts'; -import { serverTimeNow } from '../profile/server-time.ts'; +import { serverTimeNow, serverTimeToUnixSeconds } from '../profile/server-time.ts'; +import type { ResearchEfficiency } from '../research/research-efficiency.ts'; import type { ResearchRules } from '../research/research-rules.ts'; -import { debriefingTable, type BranchInvestment, type ModuleInvestment } from './battle-debriefing.ts'; +import { debriefingTable } from './battle-debriefing.ts'; import { economyDifficulty, type BattleEconomy } from './battle-economy.ts'; import type { BattleReport } from './battle-report.ts'; -import { appendBattleResultLog, mergeEarnedRpItems, type EarnedRpItem } from './battle-result-log.ts'; -import { computeBattleRewards } from './battle-rewards.ts'; -import { collectEarnedBattleRp } from './battle-rp-investment.ts'; +import { appendBattleResultLog, mergeEarnedRpItems } from './battle-result-log.ts'; +import { computeBattleRewards, type VehicleRewards } from './battle-rewards.ts'; +import { investBattleRp, type VehicleRp } from './battle-rp-investment.ts'; import type { BattleSession } from './battle-session-store.ts'; /** Talisman modification name (scripts/airinfo.nut shopIsModificationEnabled(unit, "premExpMul")). */ @@ -31,6 +32,7 @@ const TALISMAN = 'premExpMul'; export interface BattleSettlementDeps { readonly research: ResearchRules; + readonly efficiency: ResearchEfficiency; readonly equipment: EquipmentCatalogue; readonly crew: CrewSkillCatalogue; readonly economy: BattleEconomy; @@ -38,10 +40,11 @@ export interface BattleSettlementDeps { export function settleBattle(profile: BlkBlock, report: BattleReport, session: BattleSession, deps: BattleSettlementDeps): void { const difficulty = economyDifficulty(session.difficulty); + const now = serverTimeNow(); const rewards = computeBattleRewards(report, deps.economy, { difficulty, economicName: session.economicName, - premiumAccount: remainingPremiumDays(profile, serverTimeNow()) > 0, + premiumAccount: remainingPremiumDays(profile, now) > 0, hasTalisman: (vehicle) => deps.economy.isPremiumVehicle(vehicle) || ownsModification(profile, vehicle, TALISMAN), }); @@ -53,36 +56,34 @@ export function settleBattle(profile: BlkBlock, report: BattleReport, session: B if (crew && vehicle.expTotal > 0) addEarnedSkillPoints(crew, vehicle.expTotal * crewExpMul); } const weaponRefillSl = refillOwnedEquipment(profile, deps.equipment); - const rpItems = collectEarnedBattleRp( - profile, - rewards.vehicles.map((vehicle) => ({ vehicle: vehicle.vehicle, rp: vehicle.expTotal })), - session, - deps, - ); - const debriefing = debriefingTable('wtoDebriefing', rewards, investmentsOf(rpItems, deps.research)); + const research = investBattleRp(profile, rewards.vehicles.map(vehicleRpOf), { + country: session.country, + requiredClass: session.requiredClass, + difficulty, + nowUnixSec: serverTimeToUnixSeconds(now), + }, deps); + const debriefing = debriefingTable('wtoDebriefing', rewards, research); appendBattleResultLog(profile, session, { country: session.country.startsWith('country_') ? session.country : `country_${session.country}`, rewards, weaponRefillSl, usedSpares: report.usedSpares, - rpItems: mergeEarnedRpItems(rpItems), + rpItems: mergeEarnedRpItems(research.rpItems), + researchUnits: research.units, debriefing, }); } -function investmentsOf(items: readonly EarnedRpItem[], research: ResearchRules): { modules: ModuleInvestment[]; branches: BranchInvestment[] } { - const modules: ModuleInvestment[] = []; - const branches: BranchInvestment[] = []; - for (const item of items) { - if (item.rp <= 0) continue; - if (item.modification) { - modules.push({ vehicle: item.unit, module: item.modification, rp: item.rp }); - continue; - } - const type = research.techTree.vehicle(item.unit)?.type; - if (type) branches.push({ type, unit: item.unit, rp: item.rp }); +function vehicleRpOf(vehicle: VehicleRewards): VehicleRp { + let noBonusExp = 0; + let premAccExp = 0; + let premModExp = 0; + for (const amounts of vehicle.rows.values()) { + noBonusExp += amounts.noBonusExp; + premAccExp += amounts.premAccExp; + premModExp += amounts.premModExp; } - return { modules, branches }; + return { vehicle: vehicle.vehicle, noBonusExp, premAccExp, premModExp, skillBonusExp: vehicle.skillBonusExp, total: vehicle.expTotal }; } function applyNetSilverLions(profile: BlkBlock, netDelta: number): void { diff --git a/packages/local-service/src/char/actions/battle-actions.ts b/packages/local-service/src/char/actions/battle-actions.ts index 3b90a67..dd14196 100644 --- a/packages/local-service/src/char/actions/battle-actions.ts +++ b/packages/local-service/src/char/actions/battle-actions.ts @@ -12,6 +12,7 @@ import type { CrewSkillCatalogue } from '../../crew/crew-skill-rules.ts'; import type { EquipmentCatalogue } from '../../modifications/equipment-catalogue.ts'; import { clientProfile } from '../../profile/client-profile.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts'; +import type { ResearchEfficiency } from '../../research/research-efficiency.ts'; import type { ResearchRules } from '../../research/research-rules.ts'; import type { CharActionHandler } from '../char-action.ts'; import { withAccount } from './account-context.ts'; @@ -19,6 +20,7 @@ import { withAccount } from './account-context.ts'; export interface BattleActionDependencies { readonly sessions: BattleSessionStore; readonly economy: BattleEconomy; + readonly efficiency: ResearchEfficiency; } export interface FinishBattleContext { @@ -32,6 +34,7 @@ export interface FinishBattleContext { export function finishBattleAction(ctx: FinishBattleContext, battle: BattleActionDependencies): CharActionHandler { const settlementDeps: BattleSettlementDeps = { research: ctx.research, + efficiency: battle.efficiency, equipment: ctx.equipment, crew: ctx.crew, economy: battle.economy, diff --git a/packages/local-service/src/game-data/datasets/research-efficiency.ts b/packages/local-service/src/game-data/datasets/research-efficiency.ts new file mode 100644 index 0000000..90db1a7 --- /dev/null +++ b/packages/local-service/src/game-data/datasets/research-efficiency.ts @@ -0,0 +1,82 @@ +/** + * Dataset: how a battle's Research Points reach the researched vehicle (implementation notes "3e"). + * + * char.vromfs.bin config/rank.blk: + * expBonusPercentForChildForMode bonus when the vehicle played precedes the researched one; + * the client reads N = the difficulty's diffCode + * (gui.vromfs.bin scripts/airinfo.nut) + * expPenaltyPercentForHigherRank penalty when the researched vehicle is N ranks above the one played + * expPenaltyPercentForLowerRank penalty when it is N ranks below + * ExpNewNationBonus{{rank}} "Vehicle Research Bonus" percent by the researched vehicle's rank + * expNewNationBonusDailyBattleCount battles per nation and branch per day that get it + * char.vromfs.bin config/shop.blk: + * country{ branch{ range{ vehicle | group{ vehicle... } } } }: the last entry of each range ends a + * research line; when it is a group, its first vehicle counts (official wiki "Research Points", + * "top" vehicle definition). + */ +import type { BlkBlock } from '@wto/blk'; +import { numberField } from './blk-fields.ts'; +import type { Dataset } from './dataset.ts'; +import { SHOP } from './shop-tree.ts'; + +export interface ResearchEfficiencyData { + /** Indexed by mode number N of expBonusPercentForChildForMode. */ + readonly childBonusPercent: readonly number[]; + /** Indexed by the rank difference. */ + readonly higherRankPenaltyPercent: readonly number[]; + readonly lowerRankPenaltyPercent: readonly number[]; + /** Vehicle type (rank.blk spelling: Tank, Aircraft, Helicopter, Ship, Boat) -> rank -> percent. */ + readonly nationBonusPercent: Readonly>>>; + readonly nationBonusDailyBattles: number; + /** The vehicle that ends each research line of shop.blk. */ + readonly lineEnds: readonly string[]; +} + +const RANK = 'config/rank.blk'; + +export const researchEfficiency: Dataset = { + id: 'research-efficiency', + version: 1, + extract: (source) => { + const rank = source.readBlk('char.vromfs.bin', RANK); + const nationBonus = rank.blocks.find((block) => block.name === 'ExpNewNationBonus'); + const dailyBattles = numberField(rank, 'expNewNationBonusDailyBattleCount'); + if (dailyBattles === undefined) throw new Error('rank.blk: expNewNationBonusDailyBattleCount is missing'); + return { + childBonusPercent: indexedSeries(rank, 'expBonusPercentForChildForMode'), + higherRankPenaltyPercent: indexedSeries(rank, 'expPenaltyPercentForHigherRank'), + lowerRankPenaltyPercent: indexedSeries(rank, 'expPenaltyPercentForLowerRank'), + nationBonusPercent: Object.fromEntries((nationBonus?.blocks ?? []).map((type) => [ + type.name, + Object.fromEntries(type.params.flatMap((param) => { + const rankNumber = /^rank(\d+)$/.exec(param.name)?.[1]; + return rankNumber !== undefined && param.value.type === 'int' ? [[Number(rankNumber), param.value.value]] : []; + })), + ])), + nationBonusDailyBattles: dailyBattles, + lineEnds: source.readBlk('char.vromfs.bin', SHOP).blocks.flatMap((country) => + country.blocks.flatMap((branch) => branch.blocks.filter((range) => range.name === 'range').flatMap(lineEnd))), + }; + }, +}; + +/** 0, 1, ... up to the first missing index. */ +function indexedSeries(block: BlkBlock, prefix: string): number[] { + const values: number[] = []; + for (let index = 0; ; index++) { + const value = numberField(block, `${prefix}${index}`); + if (value === undefined) break; + values.push(value); + } + if (values.length === 0) throw new Error(`rank.blk: ${prefix}0 is missing`); + return values; +} + +/** A vehicle entry has no child blocks; a group holds its vehicles as child blocks. */ +function lineEnd(range: BlkBlock): string[] { + const last = range.blocks.at(-1); + if (!last) return []; + if (last.blocks.length === 0) return [last.name]; + const first = last.blocks[0]; + return first ? [first.name] : []; +} diff --git a/packages/local-service/src/local-service.ts b/packages/local-service/src/local-service.ts index c446b39..c9a76ec 100644 --- a/packages/local-service/src/local-service.ts +++ b/packages/local-service/src/local-service.ts @@ -16,6 +16,8 @@ import { DecorShop } from './decor/decor-purchase.ts'; import { DownloadableContentService } from './downloadable-content/downloadable-content-service.ts'; import { battleEconomy } from './game-data/datasets/battle-economy.ts'; import { battleSpawnRules } from './game-data/datasets/battle-spawn-rules.ts'; +import { researchEfficiency } from './game-data/datasets/research-efficiency.ts'; +import { ResearchEfficiency } from './research/research-efficiency.ts'; import { clanEconomy } from './game-data/datasets/clan-economy.ts'; import { crewSkillData } from './game-data/datasets/crew-skills.ts'; import { DatasetCache } from './game-data/datasets/dataset-cache.ts'; @@ -83,6 +85,7 @@ export async function startLocalService(options: LocalServiceOptions): Promise country_usa{ Tank:i=2 } } + * + * The count resets when the UTC day changes (the bonus battles reset at 00:00 GMT). + */ +import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk'; + +const BLOCK = 'wtoResearchBonus'; +const DAY = 'day'; +const SECONDS_PER_DAY = 86_400; + +export function researchBonusBattlesUsed(profile: BlkBlock, country: string, vehicleType: string, nowUnixSec: number): number { + const block = findBlock(profile, BLOCK); + if (!block || intParam(block, DAY) !== dayOf(nowUnixSec)) return 0; + const countryBlock = findBlock(block, country); + return countryBlock ? intParam(countryBlock, vehicleType) : 0; +} + +export function useResearchBonusBattle(profile: BlkBlock, country: string, vehicleType: string, nowUnixSec: number): void { + const used = researchBonusBattlesUsed(profile, country, vehicleType, nowUnixSec); + const block = ensureBlock(profile, BLOCK); + const day = dayOf(nowUnixSec); + if (intParam(block, DAY) !== day) { + block.blocks.length = 0; + setParam(block, DAY, { type: 'int', value: day }); + } + setParam(ensureBlock(block, country), vehicleType, { type: 'int', value: used + 1 }); +} + +function dayOf(unixSec: number): number { + return Math.floor(unixSec / SECONDS_PER_DAY); +} + +function intParam(block: BlkBlock, name: string): number { + const value = findParam(block, name)?.value; + return value?.type === 'int' ? value.value : 0; +} diff --git a/packages/local-service/src/research/research-efficiency.ts b/packages/local-service/src/research/research-efficiency.ts new file mode 100644 index 0000000..c3fcc27 --- /dev/null +++ b/packages/local-service/src/research/research-efficiency.ts @@ -0,0 +1,101 @@ +/** + * How much of a battle's vehicle Research Points reaches the researched vehicle (game data: + * game-data/datasets/research-efficiency.ts; rules from the official wiki "Research Points" + * https://wiki.warthunder.com/Research_Points and the news "Following the Roadmap: Vehicle + * Research Bonuses", 2024-09-24, whose numbers match rank.blk): + * + * - Rank difference: researching a vehicle N ranks above or below the one played costs + * expPenaltyPercentForHigherRank / expPenaltyPercentForLowerRank percent. A premium + * vehicle researching lower-ranked vehicles has no penalty (the older wiki "Research Points" + * page says so; the current page does not mention it, so this is kept but unconfirmed). + * - Predecessor: playing the vehicle directly before the researched one (its reqAir) adds + * expBonusPercentForChildForMode percent and overrides the rank penalty. + * - Vehicle Research Bonus: once the player owns a "top" vehicle of a vehicle type in any nation, + * every nation's research of that type gets ExpNewNationBonus[type][rank of the researched + * vehicle] percent of the base Research Points, for expNewNationBonusDailyBattleCount battles per + * nation and type per day (00:00 GMT). A top vehicle is researchable (not premium, pack, event, + * squadron or hidden), ends a research line (the first vehicle when the line ends in a group), + * sits at the tree's highest rank and is at most two battle rating steps below the tree's + * highest battle rating. Not modelled: the exclusion of vehicles "considered new" (the game files + * carry no release dates). + */ +import type { ResearchEfficiencyData } from '../game-data/datasets/research-efficiency.ts'; +import type { EconomyDifficulty } from '../game-data/datasets/battle-economy.ts'; +import { isPremiumKind, type TechTree, type TreeVehicle } from './tech-tree.ts'; + +/** The client's diffCode of each difficulty (scripts/airinfo.nut reads the child bonus with it). */ +const DIFF_CODE: Readonly> = { arcade: 0, historical: 1, simulation: 2 }; + +/** Battle rating steps a top vehicle may sit below its tree's highest battle rating. */ +const TOP_VEHICLE_MRANK_STEPS = 2; + +export interface ResearchEfficiencyTerms { + readonly childBonusPercent: number; + readonly rankDiffPenaltyPercent: number; +} + +export class ResearchEfficiency { + readonly #data: ResearchEfficiencyData; + readonly #tree: TechTree; + readonly #topVehicles: ReadonlySet; + + constructor(data: ResearchEfficiencyData, tree: TechTree) { + this.#data = data; + this.#tree = tree; + this.#topVehicles = topVehiclesOf(data.lineEnds, tree); + } + + get dailyBonusBattles(): number { + return this.#data.nationBonusDailyBattles; + } + + /** Predecessor bonus or rank penalty of RP earned in `played` and invested into `researched`. */ + termsFor(played: TreeVehicle, researched: TreeVehicle, difficulty: EconomyDifficulty): ResearchEfficiencyTerms { + if (researched.requires === played.name) { + return { childBonusPercent: this.#data.childBonusPercent[DIFF_CODE[difficulty]] ?? 0, rankDiffPenaltyPercent: 0 }; + } + const diff = researched.rank - played.rank; + if (diff < 0 && isPremiumKind(played.kind)) return { childBonusPercent: 0, rankDiffPenaltyPercent: 0 }; + const series = diff >= 0 ? this.#data.higherRankPenaltyPercent : this.#data.lowerRankPenaltyPercent; + const percent = series[Math.min(Math.abs(diff), series.length - 1)] ?? 0; + return { childBonusPercent: 0, rankDiffPenaltyPercent: percent }; + } + + /** The Vehicle Research Bonus percent for researching `researched`, given the vehicles the player owns. */ + nationBonusPercent(researched: TreeVehicle, owned: ReadonlySet): number { + const hasTop = [...this.#topVehicles].some((name) => owned.has(name) && this.#tree.vehicle(name)?.type === researched.type); + if (!hasTop) return 0; + return this.#data.nationBonusPercent[researched.type]?.[researched.rank] ?? 0; + } +} + +function topVehiclesOf(lineEnds: readonly string[], tree: TechTree): Set { + const highestRank = new Map(tree.branches().map((branch) => [`${branch.country}/${branch.type}`, branch.highestRank])); + const highestMrank = new Map(); + for (const vehicle of tree.all()) { + if (!vehicle.inTechTree || vehicle.kind === 'hidden' || vehicle.kind === 'part') continue; + const key = `${vehicle.country}/${vehicle.type}`; + highestMrank.set(key, Math.max(highestMrank.get(key) ?? 0, maxMrank(vehicle))); + } + const top = new Set(); + for (const name of lineEnds) { + const vehicle = tree.vehicle(name); + if (!vehicle || vehicle.kind !== 'research') continue; + const key = `${vehicle.country}/${vehicle.type}`; + if (vehicle.rank !== highestRank.get(key)) continue; + if (maxMrank(vehicle) < (highestMrank.get(key) ?? 0) - TOP_VEHICLE_MRANK_STEPS) continue; + top.add(name); + } + return top; +} + +/** The highest economic rank of a vehicle over the game modes ("maximum BR among all game modes"). */ +function maxMrank(vehicle: TreeVehicle): number { + return Math.max( + vehicle.economicRankArcade, + vehicle.economicRankHistorical, + vehicle.economicRankSimulation, + vehicle.economicRankTankHistorical ?? 0, + vehicle.economicRankTankSimulation ?? 0, + ); +}