Files
WT-Offline/packages/local-service/src/battle/battle-settlement.ts
T
N0VAN0M4LY 8e4d4b6ea3 feat(battle): settle vehicle damage, repairs, and compensation
The local service now settles vehicle repair after a battle and charges
hangar repairs at the price the client shows.

- New dataset vehicle-repair (wpcost.blk repairCost<Mode>,
  repairCostPerMin<Mode>, modifications' repairCostCoef<Mode>) and
  RepairRules, which follow the client's own formulas: full cost =
  repairCost<Mode> x (1 + coefficients of the owned modifications)
  (aces.exe 2.61.0.37 0x10517b0, 0x964900); current cost =
  max(1, (1 - hp) x full cost) in the vehicle's lastGameMode
  (getAircraftRepairCost 0x90e0b0).
- The price table now carries aircrafts/<vehicle>/repair/<mode>/cost,
  where the client looks the full repair cost up; it read 0 before.
- After a battle each life costs the official lifetime share: destroyed
  = repairCostPerMin x minutes started, at most the full cost; leaving
  the vehicle (or the battle) early = full cost; surviving = nothing;
  destroyed by an ally = nothing. The cost is written as hp,
  lastGameMode and time on the hangar entry, so the client's own repair
  cost matches it.
- Automatic repair (autoRepairAircrafts, on by default) pays for the
  damaged vehicles the player can afford; premium accounts with
  automatic repair and ammunition purchase get the expenses beyond the
  battle's earnings back. The battle log gets aircrafts hp,
  autoRepairWasOn, container.aircraftsRepaired and
  wpExpensesCompensation; the debriefing gets the ExpensesCompensation
  row.
- cln_prepare_aircraft, cln_repair_all and cln_repair_all_in_slots
  carry no price; they now charge the current repair cost instead of
  repairing for free.

Not yet verified in game.
2026-11-28 12:08:20 +08:00

181 lines
8.7 KiB
TypeScript

/**
* Post-battle settlement (`cln_wto_finish_battle`): prices the reported battle with the player's
* active boosters (battle-rewards.ts, battle-boosters.ts), pays Silver Lions and free Research
* Points, invests the vehicles' Research Points, credits crew skill points, refills equipment when
* the player has it enabled, uses up boosters, moves the wager (battle-wager.ts, battle-items.ts),
* damages and repairs the battle's vehicles and pays the premium expense compensation
* (battle-repair.ts), and appends the `EULT_SESSION_RESULT` log that carries the debriefing table
* back to the client.
*/
import type { BlkBlock } from '@wto/blk';
import type { CrewSkillCatalogue } from '../crew/crew-skill-rules.ts';
import type { ItemCatalogue } from '../items/item-catalogue.ts';
import { stockAndRefillEquipment } from '../modifications/ammo-refill.ts';
import type { EquipmentCatalogue } from '../modifications/equipment-catalogue.ts';
import { isAutoRefillWeaponsEnabled, isAutoRepairEnabled } from '../profile/profile-client-settings.ts';
import { addEarnedSkillPoints } from '../profile/profile-crew-skills.ts';
import { crewForVehicleInCountry, crewVehiclesOfCountry } from '../profile/profile-crews.ts';
import { addSilverLions, balanceOf, pay } from '../profile/profile-currency.ts';
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, serverTimeToUnixSeconds } from '../profile/server-time.ts';
import type { ResearchEfficiency } from '../research/research-efficiency.ts';
import type { ResearchRules } from '../research/research-rules.ts';
import type { RepairMode } from '../game-data/datasets/vehicle-repair.ts';
import type { ModeDifficulty } from '../game-modes/catalogue/game-mode-declaration.ts';
import type { RepairRules } from '../repair/repair-rules.ts';
import { BattleBoosters } from './battle-boosters.ts';
import { debriefingTable } from './battle-debriefing.ts';
import { economyDifficulty, type BattleEconomy } from './battle-economy.ts';
import type { BattleReport } from './battle-report.ts';
import { activeBattleBoosters, activeWager, recordBoosterUses, recordWagerBattle } from './battle-items.ts';
import { autoRepairVehicles, damageBattleVehicles, expensesCompensation } from './battle-repair.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 { appendStreakLogs } from './battle-streak-log.ts';
import type { BattleStreaks } from './battle-streaks.ts';
import type { BattleSession } from './battle-session-store.ts';
import { wagerBattle } from './battle-wager.ts';
/** Talisman modification name (scripts/airinfo.nut shopIsModificationEnabled(unit, "premExpMul")). */
const TALISMAN = 'premExpMul';
export interface BattleSettlementDeps {
readonly research: ResearchRules;
readonly efficiency: ResearchEfficiency;
readonly equipment: EquipmentCatalogue;
readonly crew: CrewSkillCatalogue;
readonly economy: BattleEconomy;
readonly streaks: BattleStreaks;
readonly items: ItemCatalogue;
readonly repair: RepairRules;
}
const REPAIR_MODE: Readonly<Record<ModeDifficulty, RepairMode>> = { arcade: 'Arcade', realistic: 'Historical', simulator: 'Simulation' };
export function settleBattle(profile: BlkBlock, report: BattleReport, session: BattleSession, deps: BattleSettlementDeps): void {
const difficulty = economyDifficulty(session.difficulty);
const now = serverTimeNow();
const log = { timeSec: serverTimeToUnixSeconds(now), roomId: session.roomId };
const boosters = new BattleBoosters(activeBattleBoosters(profile, deps.items), report);
const premiumAccount = remainingPremiumDays(profile, now) > 0;
const rewards = computeBattleRewards(report, deps.economy, {
difficulty,
economicName: session.economicName,
premiumAccount,
hasTalisman: (vehicle) => deps.economy.isPremiumVehicle(vehicle) || ownsModification(profile, vehicle, TALISMAN),
boosters,
});
const allStreaks = deps.streaks.evaluate(report, session);
const streaks = allStreaks.filter((streak) => !streak.hidden);
const unlocks = {
count: streaks.length,
wp: streaks.reduce((sum, streak) => sum + streak.wp, 0),
exp: streaks.reduce((sum, streak) => sum + streak.exp, 0),
};
applyNetSilverLions(profile, rewards.wpTotal + unlocks.wp);
if (rewards.expFree > 0) addFreeResearchPoints(profile, rewards.expFree);
const crewExpMul = deps.economy.data.crewExpMul[difficulty];
for (const vehicle of rewards.vehicles) {
const crew = crewForVehicleInCountry(profile, session.country, vehicle.vehicle);
if (crew && vehicle.expTotal > 0) addEarnedSkillPoints(crew, vehicle.expTotal * crewExpMul);
}
const weaponRefillSl = refillOwnedEquipment(profile, deps.equipment);
const research = investBattleRp(profile, rewards.vehicles.map(vehicleRpOf), {
country: session.country,
requiredClass: session.requiredClass,
difficulty,
nowUnixSec: log.timeSec,
}, deps);
recordBoosterUses(profile, boosters.uses, log);
const wager = activeWager(profile, deps.items);
const wagerOutcome = wager && wagerBattle(wager.wager, wager.state, {
won: rewards.win,
events: report.events,
awards: countById(allStreaks),
difficulty,
missionName: session.missionName,
randomBattle: session.randomBattle,
lineupRanks: crewVehiclesOfCountry(profile, session.country).flatMap((vehicle) => {
const rank = deps.research.techTree.vehicle(vehicle)?.rank;
return rank === undefined ? [] : [rank];
}),
});
if (wager && wagerOutcome) recordWagerBattle(profile, wager, wagerOutcome, log);
const damages = damageBattleVehicles(profile, report, REPAIR_MODE[session.difficulty], deps.repair, now);
const autoRepair = isAutoRepairEnabled(profile);
const repairs = autoRepair ? autoRepairVehicles(profile, damages, deps.repair) : [];
const friendlyFirePenalty = rewards.events.reduce((sum, settled) => sum + (settled.priced.row === 'FriendlyKills' ? -settled.priced.wp : 0), 0);
const compensation = premiumAccount && autoRepair && isAutoRefillWeaponsEnabled(profile)
? expensesCompensation(
rewards.wpTotal + unlocks.wp + friendlyFirePenalty,
repairs.reduce((sum, repair) => sum + Math.max(0, repair.cost), 0) + weaponRefillSl,
)
: 0;
if (compensation > 0) addSilverLions(profile, compensation);
const debriefing = debriefingTable('wtoDebriefing', rewards, research, unlocks, compensation);
appendStreakLogs(profile, session, streaks);
appendBattleResultLog(profile, session, {
country: session.country.startsWith('country_') ? session.country : `country_${session.country}`,
rewards,
unlocksWp: unlocks.wp,
weaponRefillSl,
usedSpares: report.usedSpares,
rpItems: mergeEarnedRpItems(research.rpItems),
researchUnits: research.units,
affectedBoosters: boosters.applied.map((booster) => booster.id),
affectedWagers: wager && wagerOutcome ? [wager.id] : [],
damages,
autoRepair,
repairs,
compensation,
debriefing,
});
}
function countById(streaks: readonly { readonly id: string }[]): Map<string, number> {
const counts = new Map<string, number>();
for (const streak of streaks) counts.set(streak.id, (counts.get(streak.id) ?? 0) + 1);
return counts;
}
function vehicleRpOf(vehicle: VehicleRewards): VehicleRp {
let noBonusExp = 0;
let premAccExp = 0;
let premModExp = 0;
let boosterExp = 0;
for (const amounts of vehicle.rows.values()) {
noBonusExp += amounts.noBonusExp;
premAccExp += amounts.premAccExp;
premModExp += amounts.premModExp;
boosterExp += amounts.boosterExp;
}
return { vehicle: vehicle.vehicle, noBonusExp, premAccExp, premModExp, boosterExp, skillBonusExp: vehicle.skillBonusExp, total: vehicle.expTotal };
}
function applyNetSilverLions(profile: BlkBlock, netDelta: number): void {
if (netDelta > 0) {
addSilverLions(profile, netDelta);
} else if (netDelta < 0) {
const deduction = Math.min(balanceOf(profile).silverLions, -netDelta);
if (deduction > 0) pay(profile, { silverLions: deduction, goldenEagles: 0 });
}
}
function refillOwnedEquipment(profile: BlkBlock, catalogue: EquipmentCatalogue): number {
if (!isAutoRefillWeaponsEnabled(profile)) return 0;
const owned = [...ownedVehicles(profile)].sort((a, b) => a.localeCompare(b));
let totalSpent = 0;
for (const vehicle of owned) {
const eq = catalogue.vehicle(vehicle);
if (eq) totalSpent += stockAndRefillEquipment(profile, eq, true).silverLionsSpent;
}
return totalSpent;
}